cs-webapplibs-commits Mailing List for CS Web Application Libraries (Page 2)
Status: Beta
Brought to you by:
crazedsanity
You can subscribe to this list here.
2009 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
(47) |
Sep
(8) |
Oct
(1) |
Nov
(3) |
Dec
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
2010 |
Jan
|
Feb
|
Mar
(1) |
Apr
|
May
(3) |
Jun
(14) |
Jul
(5) |
Aug
|
Sep
(5) |
Oct
(2) |
Nov
|
Dec
|
2011 |
Jan
(15) |
Feb
(7) |
Mar
(1) |
Apr
(1) |
May
(1) |
Jun
|
Jul
(1) |
Aug
|
Sep
|
Oct
(2) |
Nov
(3) |
Dec
(1) |
2012 |
Jan
(1) |
Feb
|
Mar
(1) |
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
From: <cra...@us...> - 2011-01-26 23:07:11
|
Revision: 197 http://cs-webapplibs.svn.sourceforge.net/cs-webapplibs/?rev=197&view=rev Author: crazedsanity Date: 2011-01-26 18:09:30 +0000 (Wed, 26 Jan 2011) Log Message: ----------- Add some stuff for permissions so it will use an "id path", so it will be much easier to determine what should inherit from what... EXPERIMENTAL!!! Modified Paths: -------------- trunk/0.4/setup/genericPermissions.pgsql.sql Added Paths: ----------- trunk/0.4/cs_idPath.class.php trunk/0.4/cs_urlBasedPermission.class.php Copied: trunk/0.4/cs_idPath.class.php (from rev 195, trunk/0.4/cs_genericPermission.class.php) =================================================================== --- trunk/0.4/cs_idPath.class.php (rev 0) +++ trunk/0.4/cs_idPath.class.php 2011-01-26 18:09:30 UTC (rev 197) @@ -0,0 +1,26 @@ +<?php +/* + * Created on January 26, 2011 + * + * FILE INFORMATION: + * + * $HeadURL$ + * $Id$ + * $LastChangedDate$ + * $LastChangedBy$ + * $LastChangedRevision$ + */ + +class cs_idPath extends cs_webapplibsAbstract { + + /** cs_globalFunctions object, for cleaning strings & such. */ + public $gfObj; + + //============================================================================ + /** + */ + public function __construct() { + }//end __construct() + //============================================================================ + +} Property changes on: trunk/0.4/cs_idPath.class.php ___________________________________________________________________ Added: svn:keywords + Id Author Revision HeadURL Date Added: svn:mergeinfo + Copied: trunk/0.4/cs_urlBasedPermission.class.php (from rev 195, trunk/0.4/cs_genericPermission.class.php) =================================================================== --- trunk/0.4/cs_urlBasedPermission.class.php (rev 0) +++ trunk/0.4/cs_urlBasedPermission.class.php 2011-01-26 18:09:30 UTC (rev 197) @@ -0,0 +1,54 @@ +<?php +/* + * Created on January 26, 2011 + * + * FILE INFORMATION: + * + * $HeadURL$ + * $Id$ + * $LastChangedDate$ + * $LastChangedBy$ + * $LastChangedRevision$ + */ + +class cs_urlBasedPermission extends cs_genericPermission { + + + //============================================================================ + /** + * Permission system for Web URLs; so "http://web.site.com/index" can have + * special permissions. The most important part is that a permission set for + * the URL "/" might have a setting, and "/x/y/z" might as well, without + * anything for the interim URLs ("/x", "/x/y", "/x/y/z"); those missing URLs + * are given the permissions for the closest URL (in this case "/"). + */ + public function __construct(cs_phpDB $db) { + $this->db = $db; + $this->gfObj = new cs_globalFunctions; + parent::__construct($db); + }//end __construct() + //============================================================================ + + + + //============================================================================ + /** + * Break the URL into bits (delimited by "/"), and return an array. + */ + private function _get_url_bits($url) { + $url = $this->gfObj->clean_url($url); + if(!is_array($url)) { + $bits = array("/"); + } + else { + $bits = explode("/", $url); + } + return($bits); + }//end _get_url_bits() + //============================================================================ + + + + //============================================================================ + //============================================================================ +} Property changes on: trunk/0.4/cs_urlBasedPermission.class.php ___________________________________________________________________ Added: svn:keywords + Id Author Revision HeadURL Date Added: svn:mergeinfo + Modified: trunk/0.4/setup/genericPermissions.pgsql.sql =================================================================== --- trunk/0.4/setup/genericPermissions.pgsql.sql 2011-01-26 18:08:16 UTC (rev 196) +++ trunk/0.4/setup/genericPermissions.pgsql.sql 2011-01-26 18:09:30 UTC (rev 197) @@ -6,7 +6,8 @@ CREATE TABLE cswal_group_table ( group_id serial NOT NULL PRIMARY KEY, group_name text NOT NULL UNIQUE, - group_admin integer REFERENCES cs_authentication_table(uid) + group_admin integer REFERENCES cs_authentication_table(uid), + created TIMESTAMPTZ NOT NULL DEFAULT NOW() ); -- @@ -17,21 +18,54 @@ CREATE TABLE cswal_user_group_table ( user_group_id serial NOT NULL PRIMARY KEY, user_id integer NOT NULL REFERENCES cs_authentication_table(uid), - group_id integer NOT NULL REFERENCES cswal_group_table(group_id) + group_id integer NOT NULL REFERENCES cswal_group_table(group_id), + created TIMESTAMPTZ NOT NULL DEFAULT NOW() ); +-- +-- System Table +-- Allows types of permissions to be separated (i.e. URL-based permissions from action-based permissions) +-- NOTE::: setting "use_default_deny" to TRUE means requests to objects within the given system are automatically denied, a setting +-- of FALSE means those requests are automatically granted (USE WITH CAUTION). +-- +CREATE TABLE cswal_system_table ( + system_id serial NOT NULL PRIMARY KEY, + system_name text NOT NULL UNIQUE, + use_default_deny boolean NOT NULL DEFAULT TRUE, + created TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + + +-- +-- Object table +-- Unique set of names which should be chained together to create an object path; for a URL of "/member/blog/edit", the pieces would be created +-- with ID's, such as "member"=1, "blog"=2, "edit"=3; the object path would then be ":1::2::3:"; an extra prefix element might be created to +-- define a default, inheritable set of permissions, such as "{root}"=10; the path might then be ":10::1::2::3:". -- --- Object table --- Contains unique list of objects along with the owner, default group, & user/group/other permissions (like *nix filesystem permissions) +CREATE TABLE cswal_object_table ( + object_id integer NOT NULL PRIMARY KEY, + object_name text NOT NULL UNIQUE, + is_hidden boolean NOT NULL DEFAULT FALSE, + created TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + + +-- +-- Permission table +-- Contains unique list of object paths along with the owner, default group, & user/group/other permissions (like *nix filesystem permissions) -- The permissions for user/group/other could be converted to octal (i.e. "rwxrwxrwx" == "777"), but it isn't as straightforward to read. -- NOTE::: the "user_id" table should be updated to match your database schema. +-- NOTE2:: the "inherit" column isn't used by the base permissions system. +-- NOTE3:: the "object_path" is a chain of object_id's. -- -CREATE TABLE cswal_object_table ( - object_id serial NOT NULL PRIMARY KEY, - object_name text NOT NULL UNIQUE, +CREATE TABLE cswal_permission_table ( + permission_id serial NOT NULL PRIMARY KEY, + system_name integer NOT NULL DEFAULT 0 REFERENCES cswal_system_table(system_id), + object_path text NOT NULL UNIQUE, user_id integer NOT NULL REFERENCES cs_authentication_table(uid), group_id integer NOT NULL REFERENCES cswal_group_table(group_id), + inherit boolean NOT NULL DEFAULT FALSE, u_r boolean NOT NULL DEFAULT TRUE, u_w boolean NOT NULL DEFAULT TRUE, u_x boolean NOT NULL DEFAULT FALSE, @@ -40,20 +74,26 @@ g_x boolean NOT NULL DEFAULT FALSE, o_r boolean NOT NULL DEFAULT TRUE, o_w boolean NOT NULL DEFAULT FALSE, - o_x boolean NOT NULL DEFAULT FALSE + o_x boolean NOT NULL DEFAULT FALSE, + created TIMESTAMPTZ NOT NULL DEFAULT NOW() ); +INSERT INTO cswal_system_table (system_id, system_name) VALUES (0, 'DEFAULT'); INSERT INTO cswal_group_table (group_name) VALUES ('www'); INSERT INTO cswal_group_table (group_name) VALUES ('blogs'); INSERT INTO cswal_group_table (group_name) VALUES ('admin'); -INSERT INTO cswal_object_table - (object_name,user_id, group_id) +INSERT INTO cswal_object_table (object_id, object_name,is_hidden) VALUES (0, '/', true); +INSERT INTO cswal_object_table (object_id, object_name,is_hidden) VALUES (1, 'member', false); + +INSERT INTO cswal_permission_table + (object_path,user_id, group_id) VALUES - ('/', 101, 1); + (':0:', 101, 1); -INSERT INTO cswal_object_table - (object_name, user_id, group_id, g_r, g_w) +INSERT INTO cswal_permission_table + (object_path, user_id, group_id, g_r, g_w) VALUES - ('/member', 101, 2, true, true); + (':0::1:', 101, 2, true, true); + This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2011-01-26 23:06:52
|
Revision: 195 http://cs-webapplibs.svn.sourceforge.net/cs-webapplibs/?rev=195&view=rev Author: crazedsanity Date: 2011-01-26 17:26:38 +0000 (Wed, 26 Jan 2011) Log Message: ----------- All tests work + minor fixes and tweaks. /tests/testOfCSGenericPermissions.php: * __construct() [NEW]: -- explicitely define so parent::__construct() is not called. * setUp(): -- call get_valid_users() only AFTER the permission object is used to create the schema for cs-webapplibs. * tearDown(): -- allow a way to NOT destroy the database after a test. * test_userGroups(): -- commented-out code for keeping a database around -- fixed code for testing creation of user groups (remove a hard-coded value of group ID, instead using a dynamic one). /abstract/cs_genericUserGroup.abstract.class.php: * get_user_groups(): -- also retrieve the "group_admin" field in the query (for later use) Modified Paths: -------------- trunk/0.4/abstract/cs_genericUserGroup.abstract.class.php trunk/0.4/tests/testOfCSGenericPermissions.php Modified: trunk/0.4/abstract/cs_genericUserGroup.abstract.class.php =================================================================== --- trunk/0.4/abstract/cs_genericUserGroup.abstract.class.php 2011-01-26 04:33:58 UTC (rev 194) +++ trunk/0.4/abstract/cs_genericUserGroup.abstract.class.php 2011-01-26 17:26:38 UTC (rev 195) @@ -52,7 +52,7 @@ public function get_user_groups($userId) { if(is_numeric($userId) && $userId >= 0) { try { - $sql = "SELECT ug.*, g.group_name FROM ". self::ugTable ." AS ug INNER " + $sql = "SELECT ug.*, g.group_name, g.group_admin FROM ". self::ugTable ." AS ug INNER " ."JOIN ". parent::groupTable ." as g USING (group_id) WHERE user_id=". $userId; $retval = $this->db->run_query($sql, 'group_id'); } Modified: trunk/0.4/tests/testOfCSGenericPermissions.php =================================================================== --- trunk/0.4/tests/testOfCSGenericPermissions.php 2011-01-26 04:33:58 UTC (rev 194) +++ trunk/0.4/tests/testOfCSGenericPermissions.php 2011-01-26 17:26:38 UTC (rev 195) @@ -13,14 +13,22 @@ class testOfCSGenericPermissions extends testDbAbstract { + //-------------------------------------------------------------------------- + public function __construct() { + }//end __construct() + //-------------------------------------------------------------------------- + + + + //-------------------------------------------------------------------------- function setUp() { $this->gfObj = new cs_globalFunctions; $this->gfObj->debugPrintOpt=1; parent::__construct('postgres','', 'localhost', '5432'); - $this->get_valid_users(); $this->permObj = new _gpTester($this->db); $this->permObj->do_schema(); + $this->get_valid_users(); }//end setUp() //-------------------------------------------------------------------------- @@ -28,7 +36,12 @@ //-------------------------------------------------------------------------- public function tearDown() { - $this->destroy_db(); + if(isset($GLOBALS['keepDb'])) { + unset($GLOBALS['keepDb']); + } + else { + $this->destroy_db(); + } } //-------------------------------------------------------------------------- @@ -54,6 +67,7 @@ //-------------------------------------------------------------------------- public function test_userGroups() { + #$GLOBALS['keepDb'] = true; //make sure there are groups available. { $groupList = $this->permObj->get_all_groups(); @@ -83,9 +97,11 @@ //create & test user_group relationships. { - $newId = $this->permObj->create_user_group($this->validUsers[$myKey]['uid'],1); + $newId = $this->permObj->create_user_group($this->validUsers[$myKey]['uid'],$newGroupId); $this->assertTrue(is_numeric($newId)); - $this->assertTrue($this->permObj->is_group_member($this->validUsers[$myKey]['uid'],1)); + $this->assertTrue($this->permObj->is_group_member($this->validUsers[$myKey]['uid'],$newGroupId), "user (". + $this->validUsers[$myKey]['uid'] .") isn't member of group (". $newGroupId .") after ". + "being added to it... "); $ugList = $this->permObj->get_user_groups($this->validUsers[$myKey]['uid']); $this->assertTrue(is_array($ugList)); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2011-01-26 23:06:46
|
Revision: 196 http://cs-webapplibs.svn.sourceforge.net/cs-webapplibs/?rev=196&view=rev Author: crazedsanity Date: 2011-01-26 18:08:16 +0000 (Wed, 26 Jan 2011) Log Message: ----------- This is an ALPHA version of the library, not guaranteed to work at all. NOTE::: many changes revolve around classes that were not available in v0.3.x, so it may not actually be a problem at all. Modified Paths: -------------- trunk/0.4/VERSION Modified: trunk/0.4/VERSION =================================================================== --- trunk/0.4/VERSION 2011-01-26 17:26:38 UTC (rev 195) +++ trunk/0.4/VERSION 2011-01-26 18:08:16 UTC (rev 196) @@ -1,6 +1,6 @@ ## Stores the current version of the cs-versionparse system, and it's source. ## Please do NOT modify this file. -VERSION: 0.3.0 +VERSION: 0.4-ALPHA1 PROJECT: cs-webapplibs -$HeadURL$ \ No newline at end of file +$HeadURL$ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2011-01-26 04:34:04
|
Revision: 194 http://cs-webapplibs.svn.sourceforge.net/cs-webapplibs/?rev=194&view=rev Author: crazedsanity Date: 2011-01-26 04:33:58 +0000 (Wed, 26 Jan 2011) Log Message: ----------- Add method to load database schema, remove unnecessary calls from constructor. Modified Paths: -------------- trunk/0.4/abstract/cs_webapplibs.abstract.class.php Modified: trunk/0.4/abstract/cs_webapplibs.abstract.class.php =================================================================== --- trunk/0.4/abstract/cs_webapplibs.abstract.class.php 2011-01-26 04:25:41 UTC (rev 193) +++ trunk/0.4/abstract/cs_webapplibs.abstract.class.php 2011-01-26 04:33:58 UTC (rev 194) @@ -15,10 +15,8 @@ protected $gfObj; //------------------------------------------------------------------------- - function __construct($makeGfObj=true) { + public function __construct($makeGfObj=true) { $this->set_version_file_location(dirname(__FILE__) . '/../VERSION'); - $this->get_version(); - $this->get_project(); if($makeGfObj === true) { //make a cs_globalFunctions{} object. @@ -27,6 +25,21 @@ } }//end __construct() //------------------------------------------------------------------------- + + + + //------------------------------------------------------------------------- + public function load_schema($dbType, cs_phpDb $db) { + $file = dirname(__FILE__) .'/../setup/schema.'. $dbType .'.sql'; + try { + $result = $db->run_sql_file($file); + } + catch(Exception $e) { + throw new exception(__METHOD__ .": failed to load schema file (". $file ."), DETAILS::: ". $e->getMessage()); + } + return($result); + }//end load_schema() + //------------------------------------------------------------------------- } ?> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2011-01-26 04:25:48
|
Revision: 193 http://cs-webapplibs.svn.sourceforge.net/cs-webapplibs/?rev=193&view=rev Author: crazedsanity Date: 2011-01-26 04:25:41 +0000 (Wed, 26 Jan 2011) Log Message: ----------- Drop Generic Data Linker code, since it was flawed and really isn't used. Modified Paths: -------------- trunk/0.4/setup/schema.mysql.sql trunk/0.4/setup/schema.pgsql.sql trunk/0.4/tests/testOfCSWebAppLibs.php Removed Paths: ------------- trunk/0.4/abstract/cs_gdlAttrib.abstract.class.php trunk/0.4/abstract/cs_gdlObject.abstract.class.php trunk/0.4/abstract/cs_gdlPath.abstract.class.php Deleted: trunk/0.4/abstract/cs_gdlAttrib.abstract.class.php =================================================================== --- trunk/0.4/abstract/cs_gdlAttrib.abstract.class.php 2011-01-20 01:27:08 UTC (rev 192) +++ trunk/0.4/abstract/cs_gdlAttrib.abstract.class.php 2011-01-26 04:25:41 UTC (rev 193) @@ -1,89 +0,0 @@ -<?php -/* - * Created on Jan 29, 2009 - * - * FILE INFORMATION: - * - * $HeadURL$ - * $Id$ - * $LastChangedDate$ - * $LastChangedBy$ - * $LastChangedRevision$ - */ - -abstract class cs_gdlAttribAbstract extends cs_gdlPathAbstract { - - - const table='cswal_gdl_attribute_table'; - const tableSeq = 'cswal_gdl_attribute_table_attribute_id_seq'; - - - - //------------------------------------------------------------------------- - public function create_attrib($path, $data, $type=null) { - - $objectId = $this->get_object_id_from_path($path); - - $insertString = ""; - $attribs = array(); - if(is_array($data) && count($data)) { - foreach($data as $n=>$v) { - $n = $this->translate_attrib_name($n); - $attribs[$n] = $v; - } - } - elseif(!is_null($type)) { - $key = $this->translate_attrib_name($type); - $attribs = array($key => $data); - } - else { - throw new exception(__METHOD__ .": data was not array and no type set"); - } - - if(!is_array($attribs) || !count($attribs)) { - throw new exception(__METHOD__ .": failed to create an array of attributes... ". $this->gfObj->debug_print(func_get_args(),0)); - } - - $attribs['object_id'] = $objectId; - $insertString = $this->gfObj->string_from_array($attribs, 'insert'); - - - if(!strlen($insertString)) { - throw new exception(__METHOD__ .": invalid insert string (". $insertString .")"); - } - $sql = "INSERT INTO ". self::attrTable ." ". $insertString; - - try { - $retval = $this->db->run_insert($sql, self::attrTableSeq); - } - catch(exception $e) { - throw new exception(__METHOD__ .": failed to perform insert::: ". $e->getMessage() .' ---- '. $sql); - } - - return($retval); - }//end create_attrib() - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - public function translate_attrib_name($name) { - $retval = null; - foreach($this->validTypes as $type) { - if(preg_match('/^'. $type .'/', $name)) { - $retval = 'a_'. $type; - break; - } - } - - if(is_null($retval) || !strlen($retval)) { - $this->gfObj->debug_print(__METHOD__ .": name was (". $name ."), retval=(". $retval .")",1); - throw new exception(__METHOD__ .": invalid attribute name (". $name .")"); - } - - return($retval); - }//end translate_attrib_name() - //------------------------------------------------------------------------- - -} -?> \ No newline at end of file Deleted: trunk/0.4/abstract/cs_gdlObject.abstract.class.php =================================================================== --- trunk/0.4/abstract/cs_gdlObject.abstract.class.php 2011-01-20 01:27:08 UTC (rev 192) +++ trunk/0.4/abstract/cs_gdlObject.abstract.class.php 2011-01-26 04:25:41 UTC (rev 193) @@ -1,136 +0,0 @@ -<?php -/* - * Created on Jan 29, 2009 - * - * FILE INFORMATION: - * - * $HeadURL$ - * $Id$ - * $LastChangedDate$ - * $LastChangedBy$ - * $LastChangedRevision$ - */ - -abstract class cs_gdlObjectAbstract extends cs_webapplibsAbstract { - - - const table='cswal_gdl_object_table'; - const tableSeq = 'cswal_gdl_object_table_object_id_seq'; - - //------------------------------------------------------------------------- - public function get_object_id_from_path($path) { - $sql = "SELECT object_id FROM ". self::table ." WHERE object_path='". - $this->clean_path($path) ."'"; - - try { - $data = $this->db->run_query($sql); - - if(is_array($data) && count($data) == 1) { - $retval = $data['object_id']; - } - else { - throw new exception(__METHOD__ .": invalid data for path (". $this->clean_path($path) .")::: ". $this->gfObj->debug_var_dump($data,0)); - } - } - catch(exception $e) { - throw new exception(__METHOD__ .": error retrieving path::: ". $e->getMessage()); - } - - return($retval); - }//end get_object_id_from_path() - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - public function create_object($name, $data=null, $type=null) { - $sql = "INSERT INTO ". self::table ." (object_name) VALUES ('". - $this->gfObj->cleanString($this->clean_path($name), 'sql_insert') ."')"; - try { - $retval = $this->db->run_insert($sql, self::tableSeq); - } - catch(exception $e) { - throw new exception(__METHOD__ .": failed to perform insert::: ". $e->getMessage()); - } - - if(!is_null($data)) { - throw new exception(__METHOD__ .": can't create data for objects yet"); - } - return($retval); - }//end create_object() - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - public function build_object_id_list(array $objects) { - $this->gfObj->switch_force_sql_quotes(1); - $sql = "SELECT * FROM ". self::table ." WHERE object_name IN (". - $this->gfObj->string_from_array($objects, null, ',', 'sql') .")"; - $this->gfObj->switch_force_sql_quotes(0); - - $retval = array(); - try { - $retval = $this->db->run_query($sql, 'object_name', 'object_id'); - if(!is_array($retval)) { - $retval = array(); - } - } - catch(exception $e) { - //throw new exception(__METHOD__ .": failed to retrieve list"); - } - - return($retval); - }//end build_object_id_list() - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - public function build_object_name_list(array $objectIds) { - $this->gfObj->switch_force_sql_quotes(1); -//string_from_array($array,$style=NULL,$separator=NULL, $cleanString=NULL, $removeEmptyVals=FALSE) - foreach($objectIds as $i=>$myId) { - if(!strlen($myId)) { - unset($objectIds[$i]); - } - } - $sql = "SELECT * FROM ". self::table ." WHERE object_id IN (". - $this->gfObj->string_from_array($objectIds, null, ',', 'sql',true) .")"; - $this->gfObj->switch_force_sql_quotes(0); - - try { - $retval = $this->db->run_query($sql, 'object_id', 'object_name'); - if(!is_array($retval)) { - $retval = array(); - } - } - catch(exception $e) { - throw new exception(__METHOD__ .": failed to retrieve list::: ". $e->getMessage()); - } - - return($retval); - }//end build_object_id_list() - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - public function create_objects_enmasse(array $objectList) { - $retval = 0; - foreach($objectList as $name) { - try { - $this->create_object($name); - $retval++; - } - catch(exception $e) { - //nothing to see here, move along. - } - } - return($retval); - }//end create_objects_enmasse() - //------------------------------------------------------------------------- - - -} -?> Deleted: trunk/0.4/abstract/cs_gdlPath.abstract.class.php =================================================================== --- trunk/0.4/abstract/cs_gdlPath.abstract.class.php 2011-01-20 01:27:08 UTC (rev 192) +++ trunk/0.4/abstract/cs_gdlPath.abstract.class.php 2011-01-26 04:25:41 UTC (rev 193) @@ -1,126 +0,0 @@ -<?php -/* - * Created on Jan 29, 2009 - * - * FILE INFORMATION: - * - * $HeadURL$ - * $Id$ - * $LastChangedDate$ - * $LastChangedBy$ - * $LastChangedRevision$ - */ - -abstract class cs_gdlPathAbstract extends cs_gdlObjectAbstract { - - - const table='cswal_gdl_path_table'; - const tableSeq = 'cswal_gdl_path_table_path_id_seq'; - - - - - - //------------------------------------------------------------------------- - public function create_path($path) { - $idList = $this->create_path_objects($path); - $pathIdList = $this->create_id_path($idList); - - if($this->get_path_from_idlist($pathIdList)) { - $retval = $pathIdList; - } - else { - - $sql = "INSERT INTO ". self::table ." (path_id_list) VALUES ('". $pathIdList ."')"; - - try { - $insertedId = $this->db->run_insert($sql, self::tableSeq); - $retval = $pathIdList; - } - catch(exception $e) { - throw new exception(__METHOD__ .": unable to create path::: ". $e->getMessage()); - } - } - - return($retval); - }//end create_path() - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - public function clean_path($path, $appendBase=true) { - if(strlen($path)) { - if($appendBase === true && !is_null($this->basePath)) { - $path = $this->basePath .'/'. $path; - } - $newPath = preg_replace('/\/{2,}/', '/', $path); - - if(!strlen($newPath)) { - throw new exception(__METHOD__ .": new path is zero-length (". $newPath ."), old path=(". func_get_arg(0) .")"); - } - } - else { - throw new exception(__METHOD__ .": no valid path given (". $path .")"); - } - - return($newPath); - }//end clean_path() - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - public function set_base_path($path) { - if(is_null($path) || !strlen($path)) { - $this->basePath = null; - } - else { - $this->basePath = $this->clean_path($path,false); - } - }//end set_base_path() - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - public function explode_path($path, $appendBase=true) { - $path = $this->clean_path($path, $appendBase); - $path = preg_replace('/^\//', '', $path); - $path = preg_replace('/\/$/', '', $path); - - return(explode('/', $path)); - }//end explode_path() - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - public function create_id_path(array $idList) { - $retval = ':'. $this->gfObj->string_from_array($idList, null, '::') .':'; - return($retval); - }//end create_id_path() - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - public function get_path_from_idlist($idPath) { - - $idList = explode('::', preg_replace('/^:/', '', preg_replace('/:$/', '', $idPath))); - - $nameList = $this->build_object_name_list($idList); - - $retval = "/"; - foreach($nameList as $id=>$name) { - $retval = $this->gfObj->create_list($retval, $name, '/'); - } - - $retval = $this->clean_path($retval,false); - - return($retval); - }//end get_text_path_from_id_path() - //------------------------------------------------------------------------- - -} -?> \ No newline at end of file Modified: trunk/0.4/setup/schema.mysql.sql =================================================================== --- trunk/0.4/setup/schema.mysql.sql 2011-01-20 01:27:08 UTC (rev 192) +++ trunk/0.4/setup/schema.mysql.sql 2011-01-26 04:25:41 UTC (rev 193) @@ -168,33 +168,6 @@ -- --- Table for cs_genericDataLinker{}. --- -CREATE TABLE `cswal_gdl_object_table` ( - `object_id` int(11) NOT NULL PRIMARY KEY auto_increment, - `object_name` text NOT NULL UNIQUE -) ENGINE=InnoDB; - - -CREATE TABLE `cswal_gdl_path_table` ( - `path_id` int(11) NOT NULL PRIMARY KEY auto_increment, - `path_id_list` text NOT NULL UNIQUE -) ENGINE=InnoDB; - --- --- Store attributes here. --- NOTE: fields prefixed with "a_" to avoid clashes with reserved words. --- -CREATE TABLE `cswal_gdl_attribute_table` ( - `attribute_id` serial NOT NULL PRIMARY KEY auto_increment, - `object_path` text NOT NULL, - `a_text` text DEFAULT NULL, - `a_int` integer DEFAULT NULL, - `a_dec` decimal(10,2) DEFAULT NULL, - `a_bool` boolean DEFAULT NULL -) ENGINE=InnoDB; - --- -- Constraints for dumped tables -- Modified: trunk/0.4/setup/schema.pgsql.sql =================================================================== --- trunk/0.4/setup/schema.pgsql.sql 2011-01-20 01:27:08 UTC (rev 192) +++ trunk/0.4/setup/schema.pgsql.sql 2011-01-26 04:25:41 UTC (rev 193) @@ -119,30 +119,3 @@ session_data text ); - --- --- Table for cs_genericDataLinker{}. --- -CREATE TABLE cswal_gdl_object_table ( - object_id serial NOT NULL PRIMARY KEY, - object_name text NOT NULL UNIQUE -); - - -CREATE TABLE cswal_gdl_path_table ( - path_id serial NOT NULL PRIMARY KEY, - path_id_list text NOT NULL UNIQUE -); - --- --- Store attributes here. --- NOTE: fields prefixed with "a_" to avoid clashes with reserved words. --- -CREATE TABLE cswal_gdl_attribute_table ( - attribute_id serial NOT NULL PRIMARY KEY, - object_path text NOT NULL, - a_text text DEFAULT NULL, - a_int integer DEFAULT NULL, - a_dec decimal(10,2) DEFAULT NULL, - a_bool boolean DEFAULT NULL -); Modified: trunk/0.4/tests/testOfCSWebAppLibs.php =================================================================== --- trunk/0.4/tests/testOfCSWebAppLibs.php 2011-01-20 01:27:08 UTC (rev 192) +++ trunk/0.4/tests/testOfCSWebAppLibs.php 2011-01-26 04:25:41 UTC (rev 193) @@ -11,66 +11,40 @@ * $LastChangedRevision$ */ -class testOfCSWebAppLibs extends UnitTestCase { +class testOfCSWebAppLibs extends testDbAbstract { //-------------------------------------------------------------------------- function __construct() { $this->gfObj = new cs_globalFunctions; $this->gfObj->debugPrintOpt=1; - if(!defined('CS_UNITTEST')) { - throw new exception(__METHOD__ .": FATAL: constant 'CS_UNITTEST' not set, can't do testing safely"); - } }//end __construct() //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- - private function create_dbconn() { - $dbParams = array( - 'host' => constant('cs_webapplibs-DB_CONNECT_HOST'), - 'dbname' => constant('cs_webapplibs-DB_CONNECT_DBNAME'), - 'user' => constant('cs_webapplibs-DB_CONNECT_USER'), - 'password' => constant('cs_webapplibs-DB_CONNECT_PASSWORD'), - 'port' => constant('cs_webapplibs-DB_CONNECT_PORT') - ); - $db = new cs_phpDB(constant('DBTYPE')); - $db->connect($dbParams); - return($db); - }//end create_dbconn() + function setUp() { + $this->gfObj = new cs_globalFunctions; + $this->gfObj->debugPrintOpt=1; + parent::__construct('postgres','', 'localhost', '5432'); + $tok = new authTokenTester($this->db); + $tok->load_schema('pgsql', $this->db); + }//end setUp() //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- - private function remove_tables() { - $tableList = array( - 'cswal_auth_token_table', 'cswal_version_table', 'cswal_attribute_table', - 'cswal_category_table', 'cswal_class_table', 'cswal_event_table', - 'cswal_log_attribute_table', 'cswal_log_table', 'cswal_session_store_table', - 'cswal_gdl_object_table', 'cswal_gdl_path_table', 'cswal_gdl_attribute_table' - ); - - $db = $this->create_dbconn(); - foreach($tableList as $name) { - try { - $db->run_update("DROP TABLE ". $name ." CASCADE", true); - } - catch(exception $e) { - //force an error. - //$this->assertTrue(false, "Error while dropping (". $name .")::: ". $e->getMessage()); - } - } - }//end remove_tables() + public function tearDown() { + $this->destroy_db(); + } //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- function test_token_basics() { - $db = $this->create_dbconn(); - $this->remove_tables(); - $tok = new authTokenTester($db); + $tok = new authTokenTester($this->db); //Generic test to ensure we get the appropriate data back. { @@ -202,262 +176,6 @@ //-------------------------------------------------------------------------- - function test_genericDataLinker() { - - $x = new gdlTester($this->create_dbconn()); - - //test objects & paths first. - { - $myPath = '/character/sheet///Tetra Tealeaf'; - - $this->assertEqual(array('character', 'sheet', 'Tetra Tealeaf'), $x->explode_path($myPath)); - $x->set_base_path('/testing'); - $this->assertEqual('/testing/character/sheet/Tetra Tealeaf', $x->clean_path($myPath)); - $this->assertEqual(array('testing', 'character', 'sheet', 'Tetra Tealeaf'), $x->explode_path($myPath)); - $x->set_base_path(null); - $this->assertNotEqual(array('testing', 'character', 'sheet', 'Tetra Tealeaf'), $x->explode_path($myPath)); - $this->assertEqual(array('character', 'sheet', 'Tetra Tealeaf'), $x->explode_path($myPath)); - $this->assertEqual('/character/sheet/Tetra Tealeaf', $x->clean_path($myPath)); - - //now create some objects. - $pathBits = array(); - foreach($x->explode_path($myPath) as $name) { - $pathBits[$x->create_object($name)] = $name; - } - $newPathIdList = $x->create_path($myPath); - $myPathIdList = ':'. $this->gfObj->string_from_array(array_keys($pathBits), null, '::') .':'; - $this->assertEqual($newPathIdList, $myPathIdList); - - $newId = $x->create_object('testing'); - $t = array_keys($pathBits); - $t = array_pop($t); - $lastPathId = $t; - $this->assertEqual($newId, ($lastPathId +1)); - - $oldBits = $pathBits; - $pathBits = array(); - $pathBits[$newId] = 'testing'; - foreach($oldBits as $id=>$name) { - $pathBits[$id] = $name; - } - - $newPathIdList = $x->create_path('/testing/'. $myPath); - $myPathIdList = ':'. $this->gfObj->string_from_array(array_flip($pathBits), null, '::') .':'; - $this->assertEqual($newPathIdList, $myPathIdList); - - $this->assertEqual($newPathIdList, $x->create_path('/testing/'. $myPath)); - - $myRearrangedPath = array_reverse($pathBits, true); - $rPathIdList = ':'. $this->gfObj->string_from_array(array_flip($myRearrangedPath), null, '::') .':'; - $rPath = '/'. $this->gfObj->string_from_array($myRearrangedPath, null, '/'); - $this->assertEqual($x->create_path($rPath), $rPathIdList); - - $this->assertEqual($x->get_path_from_idlist($x->create_path($rPath)), $x->get_path_from_idlist($rPathIdList)); - $this->assertEqual($x->get_path_from_idlist($x->create_path($rPath)), $x->get_path_from_idlist($rPathIdList)); - $this->assertEqual($x->get_path_from_idlist($x->create_path($rPath)), $x->get_path_from_idlist($rPathIdList)); - $this->assertEqual($x->get_path_from_idlist($x->create_path($rPath)), $x->get_path_from_idlist($rPathIdList)); - } - - - //basic tests for building text-based paths vs. id-based paths. - { - $myPath = '/character/sheet/Tetra Tealeaf'; - - - $idList = $x->createPathObjects($myPath); - - $testObjectIdList = explode('/', preg_replace('/^\//', '', $myPath)); - $this->assertEqual($idList, $x->build_object_id_list($testObjectIdList)); - - $idList2 = $x->create_path($myPath); - $this->assertEqual($x->create_id_path(array_values($idList)), $idList2); - - $this->assertEqual($myPath, $x->get_path_from_idlist($x->create_id_path($idList))); - $this->gfObj->debug_var_dump($x->get_path_from_idlist($x->create_id_path($idList))); - - $this->gfObj->debug_var_dump($idList); - $this->gfObj->debug_var_dump($idList2); - - $this->assertEqual(':1::2::3:', $idList2); - $this->assertEqual($idList2, ':'. $this->gfObj->string_from_array($idList, null, '::') .':'); - - $this->assertEqual(':1::2::3:', $x->create_id_path($idList)); - - $this->assertEqual(':1:', $x->create_id_path(array(1))); - $this->assertEqual(':000010:', $x->create_id_path(array('000010'))); - - } - - - // now REALLY test paths. - { - $gdl = new gdlTester($this->create_dbconn()); - - $myBasePath = '/character/sheet/Xander Cage'; - $x->set_base_path($myBasePath); - - //now add something that should be BENEATH that path. - $idList = $x->create_path('attributes/str'); - - $this->gfObj->debug_var_dump($idList); - } - #*/ - - - - - /*/test some basics first. - $translations = array( - 'good' => array( - 'a_int' => array('int', 'integer', 'integraIsACarNotAnArgument'), - 'a_dec' => array('dec', 'decimal', 'decemberIsAMonth'), - 'a_bool' => array('bool', 'boolean', 'boolJustLooksLikeSomethingJiggly'), - 'a_text' => array('text', 'textual', 'textPaperJustLooksPink') - ), - 'bad' => array( - 'a_int' => array('num', 'a_int', 'nittedStuff'), - 'a_dec' => array('dce', 'a_dec', 'dceStuff'), - 'a_bool' => array('bolo', 'a_bool', 'boloMeansBeOnLookOut'), - 'a_text' => array('txt', 'a_text', 'txtIsABadAbbreviation') - ) - ); - - foreach($translations as $goodBad=>$matchesArray) { - foreach($matchesArray as $matchThis => $tryThese) { - foreach($tryThese as $k) { - try { - $this->assertEqual($matchThis, $x->translate_attrib_name($k)); - } - catch(exception $e) { - if($goodBad == 'good') { - $this->assertFalse(true, "test (". $k .") should have been good, but was bad::: ". $e->getMessage()); - } - } - } - } - } - $testData = array( - 'skills/Appraise/cc' => array('bool' => true), - 'skills/Appraise/mod' => array('int' => 3), - 'skills/Appraise/ab_mod' => array('int' => 3), - 'skills/Appraise/rank' => array('int' => 3), - 'skills/Appraise/misc_mod' => array('int' => 3), - 'skills/Appraise/notes' => array('text' => "Lorem ipsum dolor sit amet, consectetur adipiscing elit."), - 'skills/Appraise/test' => array( - 'text' => "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", - 'bool' => true, - 'dec' => 0.03 - ), - ); - - - $myBasePath = '/characters/Tetra Tealeaf/'; - $x->set_base_path($myBasePath); - foreach($testData as $path=>$subData) { - $this->assertEqual($myBasePath . $path, $x->clean_path($path)); - $this->assertTrue(is_numeric($x->create_object($path, $subData))); - } - - //get each individual item about the skill 'Appraise' individually. - $x->get_object_attribs('skills/Appraise/cc', 'bool'); - $x->get_object_attribs('skills/Appraise/mod', 'int'); - $x->get_object_attribs('skills/Appraise/ab_mod', 'int'); - $x->get_object_attribs('skills/Appraise/rank', 'int'); - $x->get_object_attribs('skills/Appraise/misc_mod', 'int'); - $x->get_object_attribs('skills/Appraise/notes', 'text'); - $x->get_object_attribs('skills/Appraise/test', array('text', 'bool', 'dec')); - $returnVal = array( - 'text' => "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", - 'bool' => true, - 'dec' => 0.03 - ); - - - //another way to retrieve it, without caring about what types are returned::: - $returnVal = $x->get_all_object_attribs('skills/Appraise', false); - $returnVal = array( - 'cc' => array( - 'test' => null, - 'bool' => true, - 'int' => null, - 'dec' => null - ), - 'mod' => array( - 'test' => null, - 'bool' => null, - 'int' => 10, - 'dec' => null - ), - 'ab_mod' => array( - 'test' => null, - 'bool' => null, - 'int' => 3, - 'dec' => null - ), - 'rank' => array( - 'test' => null, - 'bool' => null, - 'int' => 6, - 'dec' => null - ), - 'misc_mod' => array( - 'test' => null, - 'bool' => null, - 'int' => 1, - 'dec' => null - ), - 'notes' => array( - 'test' => "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", - 'bool' => null, - 'int' => null, - 'dec' => null - ), - 'test' => array( - 'text' => "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", - 'bool' => true, - 'int' => null, - 'dec' => 0.03 - ) - ); - - //a better way to retrieve that data: - $returnVal = $x->get_all_object_attribs('skills/Appraise', false); - $returnVal = array( - 'cc' => true, - 'mod' => 10, - 'ab_mod' => 3, - 'rank' => 6, - 'misc_mod' => 1, - 'notes' => "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", - 'test' => array( - 'text' => "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", - 'bool' => true, - 'dec' => 0.03 - ) - ); - - //if we don't want all that junk in test, we can specify what to get for EACH one: - $types = array( - 'cc' => "bool", - 'test' => "dec" - ); - $returnVal = $x->get_all_object_attribs('skills/Appraise', false, $types); - $returnVal = array( - 'cc' => true, - 'mod' => 10, - 'ab_mod' => 3, - 'rank' => 6, - 'misc_mod' => 1, - 'notes' => "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", - 'test' => 0.03 - ); - #*/ - }//end test_genericDataLinker() - //-------------------------------------------------------------------------- - - - - //-------------------------------------------------------------------------- public function test_genericPermissions() { }//end test_genericPermissions() //-------------------------------------------------------------------------- @@ -494,16 +212,4 @@ } } -class gdlTester extends cs_genericDataLinker { - public $isTest = true; - - public function __construct($db) { - parent::__construct($db); - } - - public function createPathObjects($path) { - return($this->create_path_objects($path)); - } -} - ?> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2011-01-20 01:27:15
|
Revision: 192 http://cs-webapplibs.svn.sourceforge.net/cs-webapplibs/?rev=192&view=rev Author: crazedsanity Date: 2011-01-20 01:27:08 +0000 (Thu, 20 Jan 2011) Log Message: ----------- Better testing using created+dropped database to avoid breaking existing db. /abstract/testDb.abstract.class.php [NEW]: * class for creating, accessing, and destroying a test database. * NOTE::: this class lacks proper exception/error handling. /setup/genericPermissions.pgsql.sql: * remove the BEGIN statement from the top of the file. /tests/testOfCSGenericPermissions.php: * MAIN: -- extends testDbAbstract instead of UnitTestCase. * setUp(): -- call parent to create database -- create new _gpTester, use connection from extended (parent) class * tearDown(): -- destroy the database instead of removing tables * create_dbconn() [DELETED]: -- removed, using connection from parent class. * remove_tables() [DELETED]: -- no longer needed; using a temporary database instead. * get_valid_users(): -- remove call to deleted method -- reference internal db var * test_userGroups(): -- use internal permObj var. -- use internal db var. * test_permissions(): -- don't create new _gpTester (unnecessary) /tests/files/test_db.sql: * fixed uid's so they would not collide. Modified Paths: -------------- trunk/0.4/setup/genericPermissions.pgsql.sql trunk/0.4/tests/files/test_db.sql trunk/0.4/tests/testOfCSGenericPermissions.php Added Paths: ----------- trunk/0.4/abstract/testDb.abstract.class.php Added: trunk/0.4/abstract/testDb.abstract.class.php =================================================================== --- trunk/0.4/abstract/testDb.abstract.class.php (rev 0) +++ trunk/0.4/abstract/testDb.abstract.class.php 2011-01-20 01:27:08 UTC (rev 192) @@ -0,0 +1,83 @@ +<?php + + +abstract class testDbAbstract extends UnitTestCase { + + protected $config = array(); + protected $db; + private $templateDb; + private $templateConfig; + + //----------------------------------------------------------------------------- + public function __construct($superUserName, $password, $hostname, $port) { + /* + 'host' => $this->host, + 'port' => $this->port, + 'dbname' => $this->dbname, + 'user' => $this->user, + 'password' => $this->password + */ + $this->config = array( + 'user' => $superUserName, + 'password' => $password, + 'host' => $hostname, + 'port' => $port, + + //make sure the database name is unique and has (almost) no chance of clashing. + 'dbname' => $this->set_dbname(__CLASS__) + ); + $this->templateConfig = $this->config; + $this->templateConfig['dbname'] = 'template1'; + $this->templateDb = new cs_phpdb('pgsql'); + $this->templateDb->connect($this->templateConfig); + + $this->gfObj = new cs_globalFunctions; + + $this->db = new cs_phpdb('pgsql'); + $this->create_db(); + }//end __construct() + //----------------------------------------------------------------------------- + + + + //----------------------------------------------------------------------------- + private function set_dbname($prefix) { + return(strtolower(__CLASS__ .'_'. preg_replace('/\./', '', microtime(true)))); + }//end set_dbname() + //----------------------------------------------------------------------------- + + + + //----------------------------------------------------------------------------- + protected function create_db() { + $sql = "CREATE DATABASE ". $this->config['dbname']; + $this->templateDb->exec($sql); + + //now run the SQL file. + $this->db->connect($this->config); + $this->db->run_sql_file(dirname(__FILE__) .'/../tests/files/test_db.sql'); + }//end create_db() + //----------------------------------------------------------------------------- + + + + //----------------------------------------------------------------------------- + protected function destroy_db() { + $this->db->close(); + $this->templateDb->exec("DROP DATABASE ". $this->config['dbname']); + }//end destroy_db() + //----------------------------------------------------------------------------- + + + + //----------------------------------------------------------------------------- + public function __destruct() { + #$this->destroy_db(); + }//end __destruct() + //----------------------------------------------------------------------------- + + + +}//end testDbAbstract{} + +?> Modified: trunk/0.4/setup/genericPermissions.pgsql.sql =================================================================== --- trunk/0.4/setup/genericPermissions.pgsql.sql 2011-01-15 05:27:39 UTC (rev 191) +++ trunk/0.4/setup/genericPermissions.pgsql.sql 2011-01-20 01:27:08 UTC (rev 192) @@ -1,4 +1,3 @@ -BEGIN; -- -- Group table Modified: trunk/0.4/tests/files/test_db.sql =================================================================== --- trunk/0.4/tests/files/test_db.sql 2011-01-15 05:27:39 UTC (rev 191) +++ trunk/0.4/tests/files/test_db.sql 2011-01-20 01:27:08 UTC (rev 192) @@ -67,11 +67,11 @@ -- INSERT INTO cs_authentication_table VALUES (101, 'slaughter', 'x', true, '2008-06-01', '2011-01-10 21:07:07.029629-06', 'sla...@de...ll', 1); -INSERT INTO cs_authentication_table VALUES (101, 'mary', 'x', true, '2008-06-01', '2011-01-10 21:07:07.029629-06', 'ma...@de...ll', 1); -INSERT INTO cs_authentication_table VALUES (101, 'einstein', 'x', true, '2008-06-01', '2011-01-10 21:07:07.029629-06', 'ein...@de...ll', 1); -INSERT INTO cs_authentication_table VALUES (101, 'alexander.graham.bell', 'x', true, '2008-06-01', '2011-01-10 21:07:07.029629-06', 'ale...@de...ll', 1); -INSERT INTO cs_authentication_table VALUES (101, 'john', 'x', true, '2008-06-01', '2011-01-10 21:07:07.029629-06', 'jo...@de...ll', 1); -INSERT INTO cs_authentication_table VALUES (101, 'xavier', 'x', true, '2008-06-01', '2011-01-10 21:07:07.029629-06', 'xa...@de...ll', 1); +INSERT INTO cs_authentication_table VALUES (102, 'mary', 'x', true, '2008-06-01', '2011-01-10 21:07:07.029629-06', 'ma...@de...ll', 1); +INSERT INTO cs_authentication_table VALUES (103, 'einstein', 'x', true, '2008-06-01', '2011-01-10 21:07:07.029629-06', 'ein...@de...ll', 1); +INSERT INTO cs_authentication_table VALUES (104, 'alexander.graham.bell', 'x', true, '2008-06-01', '2011-01-10 21:07:07.029629-06', 'ale...@de...ll', 1); +INSERT INTO cs_authentication_table VALUES (105, 'john', 'x', true, '2008-06-01', '2011-01-10 21:07:07.029629-06', 'jo...@de...ll', 1); +INSERT INTO cs_authentication_table VALUES (106, 'xavier', 'x', true, '2008-06-01', '2011-01-10 21:07:07.029629-06', 'xa...@de...ll', 1); -- Modified: trunk/0.4/tests/testOfCSGenericPermissions.php =================================================================== --- trunk/0.4/tests/testOfCSGenericPermissions.php 2011-01-15 05:27:39 UTC (rev 191) +++ trunk/0.4/tests/testOfCSGenericPermissions.php 2011-01-20 01:27:08 UTC (rev 192) @@ -11,18 +11,16 @@ * $LastChangedRevision$ */ -class testOfCSGenericPermissions extends UnitTestCase { +class testOfCSGenericPermissions extends testDbAbstract { //-------------------------------------------------------------------------- function setUp() { $this->gfObj = new cs_globalFunctions; $this->gfObj->debugPrintOpt=1; - if(!defined('CS_UNITTEST')) { - throw new exception(__METHOD__ .": FATAL: constant 'CS_UNITTEST' not set, can't do testing safely"); - } + parent::__construct('postgres','', 'localhost', '5432'); $this->get_valid_users(); - $perm = new _gpTester($this->create_dbconn()); - $perm->do_schema(); + $this->permObj = new _gpTester($this->db); + $this->permObj->do_schema(); }//end setUp() //-------------------------------------------------------------------------- @@ -30,60 +28,20 @@ //-------------------------------------------------------------------------- public function tearDown() { - $this->remove_tables(); + $this->destroy_db(); } //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- - private function create_dbconn() { - $dbParams = array( - 'host' => constant('cs_webapplibs-DB_CONNECT_HOST'), - 'dbname' => constant('cs_webapplibs-DB_CONNECT_DBNAME'), - 'user' => constant('cs_webapplibs-DB_CONNECT_USER'), - 'password' => constant('cs_webapplibs-DB_CONNECT_PASSWORD'), - 'port' => constant('cs_webapplibs-DB_CONNECT_PORT') - ); - $db = new cs_phpDB(constant('DBTYPE')); - $db->connect($dbParams); - return($db); - }//end create_dbconn() - //-------------------------------------------------------------------------- - - - - //-------------------------------------------------------------------------- - private function remove_tables() { - $tableList = array( - 'cswal_gdl_object_table', 'cswal_gdl_attribute_table', 'cswal_gdl_path_table', - 'cswal_object_table', 'cswal_user_group_table', 'cswal_group_table' - ); - - $db = $this->create_dbconn(); - foreach($tableList as $name) { - try { - $db->run_update("DROP TABLE ". $name ." CASCADE", true); - } - catch(exception $e) { - //force an error. - //$this->assertTrue(false, "Error while dropping (". $name .")::: ". $e->getMessage()); - } - } - }//end remove_tables() - //-------------------------------------------------------------------------- - - - - //-------------------------------------------------------------------------- /** * Just like the schema, this SQL will need to change to match your database in order to work. */ private function get_valid_users() { $sql = "SELECT uid,username FROM cs_authentication_table ORDER BY uid"; try { - $db = $this->create_dbconn(); - $this->validUsers = $db->run_query($sql); + $this->validUsers = $this->db->run_query($sql); } catch(Exception $e) { cs_debug_backtrace(1); @@ -96,11 +54,9 @@ //-------------------------------------------------------------------------- public function test_userGroups() { - $perm = new _gpTester($this->create_dbconn()); - //make sure there are groups available. { - $groupList = $perm->get_all_groups(); + $groupList = $this->permObj->get_all_groups(); $keys = array_keys($groupList); $myKey = $keys[0]; @@ -114,24 +70,24 @@ //create some groups. { - $newGroupId = $perm->create_group(__METHOD__); + $newGroupId = $this->permObj->create_group(__METHOD__); $this->assertTrue(is_numeric($newGroupId)); - $groupList = $perm->get_all_groups(); + $groupList = $this->permObj->get_all_groups(); foreach($groupList as $groupData) { - $this->assertEqual($perm->get_group_by_id($groupData['group_id']), $groupData); - $this->assertEqual($perm->get_group($groupData['group_name']), $groupData); + $this->assertEqual($this->permObj->get_group_by_id($groupData['group_id']), $groupData); + $this->assertEqual($this->permObj->get_group($groupData['group_name']), $groupData); } } //create & test user_group relationships. { - $newId = $perm->create_user_group($this->validUsers[$myKey]['uid'],1); + $newId = $this->permObj->create_user_group($this->validUsers[$myKey]['uid'],1); $this->assertTrue(is_numeric($newId)); - $this->assertTrue($perm->is_group_member($this->validUsers[$myKey]['uid'],1)); + $this->assertTrue($this->permObj->is_group_member($this->validUsers[$myKey]['uid'],1)); - $ugList = $perm->get_user_groups($this->validUsers[$myKey]['uid']); + $ugList = $this->permObj->get_user_groups($this->validUsers[$myKey]['uid']); $this->assertTrue(is_array($ugList)); $this->assertTrue(count($ugList) > 0); $this->assertFalse(isset($ugList['group_name'])); @@ -144,8 +100,6 @@ //-------------------------------------------------------------------------- public function test_permissions() { - $perm = new _gpTester($this->create_dbconn()); - //Test permission string parsing. { $myPermArr = array( @@ -178,16 +132,16 @@ ); $permString = 'rwx-----x'; - $this->assertEqual(strlen($perm->make_perm_string($myPermArr)),9); - $this->assertEqual(count($perm->parse_perm_string($permString)), 9); - $this->assertEqual($perm->make_perm_string($myPermArr), $permString); - $this->assertEqual(array_keys($perm->parse_perm_string($permString)), array_keys($myPermArr)); - $this->assertEqual($perm->make_perm_string($perm->parse_perm_string($permString)), $permString); - $this->assertEqual(array_keys($perm->parse_perm_string($perm->make_perm_string($myPermArr))), array_keys($myPermArr)); + $this->assertEqual(strlen($this->permObj->make_perm_string($myPermArr)),9); + $this->assertEqual(count($this->permObj->parse_perm_string($permString)), 9); + $this->assertEqual($this->permObj->make_perm_string($myPermArr), $permString); + $this->assertEqual(array_keys($this->permObj->parse_perm_string($permString)), array_keys($myPermArr)); + $this->assertEqual($this->permObj->make_perm_string($this->permObj->parse_perm_string($permString)), $permString); + $this->assertEqual(array_keys($this->permObj->parse_perm_string($this->permObj->make_perm_string($myPermArr))), array_keys($myPermArr)); - $this->assertEqual($perm->get_perm_list($myPermArr,'u'), $permByType['u']); - $this->assertEqual($perm->get_perm_list($myPermArr,'g'), $permByType['g']); - $this->assertEqual($perm->get_perm_list($myPermArr,'o'), $permByType['o']); + $this->assertEqual($this->permObj->get_perm_list($myPermArr,'u'), $permByType['u']); + $this->assertEqual($this->permObj->get_perm_list($myPermArr,'g'), $permByType['g']); + $this->assertEqual($this->permObj->get_perm_list($myPermArr,'o'), $permByType['o']); } //create some permissions. @@ -198,39 +152,39 @@ $usePermString = 'rwxrw-r--'; $usePermName = __METHOD__ .'/test1'; - $this->assertFalse($perm->permission_exists($usePermName)); - $permId = $perm->create_permission($usePermName, $myUid, 1, $usePermString); - $this->assertTrue($perm->permission_exists($usePermName)); + $this->assertFalse($this->permObj->permission_exists($usePermName)); + $permId = $this->permObj->create_permission($usePermName, $myUid, 1, $usePermString); + $this->assertTrue($this->permObj->permission_exists($usePermName)); $this->assertTrue(is_numeric($permId)); //the method 'build_permissions_string()' should disregard extra indices in the array & build the string. - $this->assertEqual($perm->make_perm_string($perm->get_permission_by_id($permId)), $usePermString); - $this->assertEqual($perm->make_perm_string($perm->get_object_by_id($permId)), $usePermString); - $this->assertEqual($perm->make_perm_string($perm->get_permission($usePermName)), $usePermString); - $this->assertEqual($perm->make_perm_string($perm->get_object($usePermName)), $usePermString); + $this->assertEqual($this->permObj->make_perm_string($this->permObj->get_permission_by_id($permId)), $usePermString); + $this->assertEqual($this->permObj->make_perm_string($this->permObj->get_object_by_id($permId)), $usePermString); + $this->assertEqual($this->permObj->make_perm_string($this->permObj->get_permission($usePermName)), $usePermString); + $this->assertEqual($this->permObj->make_perm_string($this->permObj->get_object($usePermName)), $usePermString); //check to make sure individual permission requests work as expected. - $this->assertTrue($perm->has_read_permission($myUid, $usePermName)); - $this->assertTrue($perm->has_write_permission($myUid, $usePermName)); - $this->assertTrue($perm->has_execute_permission($myUid, $usePermName)); + $this->assertTrue($this->permObj->has_read_permission($myUid, $usePermName)); + $this->assertTrue($this->permObj->has_write_permission($myUid, $usePermName)); + $this->assertTrue($this->permObj->has_execute_permission($myUid, $usePermName)); //make sure "anonymous" permissions are correct. - $this->assertTrue($perm->has_read_permission(0,$usePermName)); - $this->assertFalse($perm->has_write_permission(0,$usePermName)); - $this->assertFalse($perm->has_execute_permission(0,$usePermName)); + $this->assertTrue($this->permObj->has_read_permission(0,$usePermName)); + $this->assertFalse($this->permObj->has_write_permission(0,$usePermName)); + $this->assertFalse($this->permObj->has_execute_permission(0,$usePermName)); //put a second user into the proper user_group, then test group permissions. $secondUser = $this->validUsers[$userKeys[1]]['uid']; - $this->assertTrue(is_numeric($perm->create_user_group($secondUser, 1))); - $this->assertTrue($perm->has_read_permission($secondUser, $usePermName)); - $this->assertTrue($perm->has_write_permission($secondUser, $usePermName)); - $this->assertFalse($perm->has_execute_permission($secondUser, $usePermName)); + $this->assertTrue(is_numeric($this->permObj->create_user_group($secondUser, 1))); + $this->assertTrue($this->permObj->has_read_permission($secondUser, $usePermName)); + $this->assertTrue($this->permObj->has_write_permission($secondUser, $usePermName)); + $this->assertFalse($this->permObj->has_execute_permission($secondUser, $usePermName)); //test a THIRD user (non-zero uid), make sure they are subject to the same permissions as anonymous (uid=0) $thirdUser = $this->validUsers[$userKeys[2]]['uid']; - $this->assertEqual($perm->has_read_permission(0,$usePermName), $perm->has_read_permission($thirdUser,$usePermName)); - $this->assertEqual($perm->has_write_permission(0,$usePermName), $perm->has_write_permission($thirdUser,$usePermName)); - $this->assertEqual($perm->has_execute_permission(0,$usePermName), $perm->has_execute_permission($thirdUser,$usePermName)); + $this->assertEqual($this->permObj->has_read_permission(0,$usePermName), $this->permObj->has_read_permission($thirdUser,$usePermName)); + $this->assertEqual($this->permObj->has_write_permission(0,$usePermName), $this->permObj->has_write_permission($thirdUser,$usePermName)); + $this->assertEqual($this->permObj->has_execute_permission(0,$usePermName), $this->permObj->has_execute_permission($thirdUser,$usePermName)); } }//end test_permissions //-------------------------------------------------------------------------- This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2011-01-15 05:27:45
|
Revision: 191 http://cs-webapplibs.svn.sourceforge.net/cs-webapplibs/?rev=191&view=rev Author: crazedsanity Date: 2011-01-15 05:27:39 +0000 (Sat, 15 Jan 2011) Log Message: ----------- File with the minimum requirements for testing. Added Paths: ----------- trunk/0.4/tests/files/test_db.sql Added: trunk/0.4/tests/files/test_db.sql =================================================================== --- trunk/0.4/tests/files/test_db.sql (rev 0) +++ trunk/0.4/tests/files/test_db.sql 2011-01-15 05:27:39 UTC (rev 191) @@ -0,0 +1,96 @@ +-- +-- PostgreSQL database dump +-- + +SET client_encoding = 'UTF8'; +SET standard_conforming_strings = off; +SET check_function_bodies = false; +SET client_min_messages = warning; +SET escape_string_warning = off; + +SET search_path = public, pg_catalog; + +SET default_tablespace = ''; + +SET default_with_oids = false; + +-- +-- Name: cs_authentication_table; Type: TABLE; Schema: public; Owner: -; Tablespace: +-- + +CREATE TABLE cs_authentication_table ( + uid integer NOT NULL, + username text NOT NULL, + passwd character varying(32), + is_active boolean DEFAULT true NOT NULL, + date_created date DEFAULT now() NOT NULL, + last_login timestamp with time zone, + email text, + user_status_id integer +); + + +-- +-- Name: cs_authentication_table_uid_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE cs_authentication_table_uid_seq + INCREMENT BY 1 + NO MAXVALUE + NO MINVALUE + CACHE 1; + + +-- +-- Name: cs_authentication_table_uid_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE cs_authentication_table_uid_seq OWNED BY cs_authentication_table.uid; + + +-- +-- Name: cs_authentication_table_uid_seq; Type: SEQUENCE SET; Schema: public; Owner: - +-- + +SELECT pg_catalog.setval('cs_authentication_table_uid_seq', 121, true); + + +-- +-- Name: uid; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE cs_authentication_table ALTER COLUMN uid SET DEFAULT nextval('cs_authentication_table_uid_seq'::regclass); + + +-- +-- Data for Name: cs_authentication_table; Type: TABLE DATA; Schema: public; Owner: - +-- + +INSERT INTO cs_authentication_table VALUES (101, 'slaughter', 'x', true, '2008-06-01', '2011-01-10 21:07:07.029629-06', 'sla...@de...ll', 1); +INSERT INTO cs_authentication_table VALUES (101, 'mary', 'x', true, '2008-06-01', '2011-01-10 21:07:07.029629-06', 'ma...@de...ll', 1); +INSERT INTO cs_authentication_table VALUES (101, 'einstein', 'x', true, '2008-06-01', '2011-01-10 21:07:07.029629-06', 'ein...@de...ll', 1); +INSERT INTO cs_authentication_table VALUES (101, 'alexander.graham.bell', 'x', true, '2008-06-01', '2011-01-10 21:07:07.029629-06', 'ale...@de...ll', 1); +INSERT INTO cs_authentication_table VALUES (101, 'john', 'x', true, '2008-06-01', '2011-01-10 21:07:07.029629-06', 'jo...@de...ll', 1); +INSERT INTO cs_authentication_table VALUES (101, 'xavier', 'x', true, '2008-06-01', '2011-01-10 21:07:07.029629-06', 'xa...@de...ll', 1); + + +-- +-- Name: cs_authentication_table_pkey; Type: CONSTRAINT; Schema: public; Owner: -; Tablespace: +-- + +ALTER TABLE ONLY cs_authentication_table + ADD CONSTRAINT cs_authentication_table_pkey PRIMARY KEY (uid); + + +-- +-- Name: cs_authentication_table_username_key; Type: CONSTRAINT; Schema: public; Owner: -; Tablespace: +-- + +ALTER TABLE ONLY cs_authentication_table + ADD CONSTRAINT cs_authentication_table_username_key UNIQUE (username); + + +-- +-- PostgreSQL database dump complete +-- + This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2011-01-06 01:38:47
|
Revision: 190 http://cs-webapplibs.svn.sourceforge.net/cs-webapplibs/?rev=190&view=rev Author: crazedsanity Date: 2011-01-06 01:38:41 +0000 (Thu, 06 Jan 2011) Log Message: ----------- Default ordering. /abstract/cs_singleTableHandler.abstract.class.php: * get_records(): -- set default "ORDER BY" clause to be the primary key's column. Modified Paths: -------------- trunk/0.4/abstract/cs_singleTableHandler.abstract.class.php Modified: trunk/0.4/abstract/cs_singleTableHandler.abstract.class.php =================================================================== --- trunk/0.4/abstract/cs_singleTableHandler.abstract.class.php 2011-01-06 00:59:29 UTC (rev 189) +++ trunk/0.4/abstract/cs_singleTableHandler.abstract.class.php 2011-01-06 01:38:41 UTC (rev 190) @@ -182,7 +182,7 @@ } } - $orderByStr = ''; + $orderByStr = ' ORDER BY '. $this->pkeyField; if(is_string($orderBy) && strlen($orderBy)) { $orderByStr = ' ORDER BY '. $orderBy; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2011-01-06 00:59:35
|
Revision: 189 http://cs-webapplibs.svn.sourceforge.net/cs-webapplibs/?rev=189&view=rev Author: crazedsanity Date: 2011-01-06 00:59:29 +0000 (Thu, 06 Jan 2011) Log Message: ----------- Add default log details. /cs_webdblogger.class.php: * log_by_class(): -- set default details to avoid running into unnecessary exceptions. Modified Paths: -------------- trunk/0.4/cs_webdblogger.class.php Modified: trunk/0.4/cs_webdblogger.class.php =================================================================== --- trunk/0.4/cs_webdblogger.class.php 2010-10-07 19:08:10 UTC (rev 188) +++ trunk/0.4/cs_webdblogger.class.php 2011-01-06 00:59:29 UTC (rev 189) @@ -287,6 +287,9 @@ */ public function log_by_class($details, $className="error", $uid=NULL, array $logAttribs=NULL) { + if(is_null($details) || !strlen($details)) { + $details = "(". __METHOD__ .": no details given)"; + } if($this->suspendLogging === true) { $this->pendingLogs[] = func_get_args(); $retval = count($this->pendingLogs) -1; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2010-10-07 19:08:16
|
Revision: 188 http://cs-webapplibs.svn.sourceforge.net/cs-webapplibs/?rev=188&view=rev Author: crazedsanity Date: 2010-10-07 19:08:10 +0000 (Thu, 07 Oct 2010) Log Message: ----------- Changes to work with cs-phpxml v1.1 (trunk) /cs_siteConfig.class.php: * __construct(): -- use cs_phpxmlCreator::attributeIndex to remove any root attributes. * parse_config(): -- use cs_phpxmlCreator::attributeIndex to remove any root attributes. -- TODO about taking out the UPPERCASE requirement... -- modifications to handle cs-phpxml v1.1 (trunk) * get_section(): -- minor changes to retrieve data based on cs-phpxml v1.1 (trunk) * get_value(): -- use dataIndex constant from cs_phpxmlCreator to get value. /cs_webdbupgrade.class.php: * read_upgrade_config_file(): -- build the "matching" array here. -- pull the "INITIALVERSION" value here, if it exists. * do_single_upgrade(): -- updated paths to configuration data. * get_upgrade_list(): -- updated path to config data * load_initial_version(): -- use new location of INITIALVERSION in config. Modified Paths: -------------- trunk/0.4/cs_siteConfig.class.php trunk/0.4/cs_webdbupgrade.class.php Modified: trunk/0.4/cs_siteConfig.class.php =================================================================== --- trunk/0.4/cs_siteConfig.class.php 2010-10-01 19:24:30 UTC (rev 187) +++ trunk/0.4/cs_siteConfig.class.php 2010-10-07 19:08:10 UTC (rev 188) @@ -103,7 +103,7 @@ if(is_null($section) || !strlen($section)) { $myData = $this->xmlReader->get_path($this->xmlReader->get_root_element()); - unset($myData['type'], $myData['attributes']); + unset($myData['type'], $myData[cs_phpxmlCreator::attributeIndex]); $myData = array_keys($myData); $section = $myData[0]; } @@ -168,22 +168,23 @@ private function parse_config() { if(is_object($this->xmlReader)) { $data = $this->xmlReader->get_path($this->xmlReader->get_root_element()); + unset($data[cs_phpxmlCreator::attributeIndex]); $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" + //only handle UPPERCASE index names.... + //TODO: take this (above) requirement out, as cs-phpxml doesn't require everything to be upper-case. if($section == strtoupper($section)) { $this->configSections[] = $section; - unset($secData['type']); - - if(isset($secData['attributes']) && is_array($secData['attributes'])) { - $sectionAttribs = $secData['attributes']; - unset($secData['attributes']); + //TODO: use method (i.e. $this->xmlReader->get_attribute($path)) to retrieve attributes. + if(isset($secData[cs_phpxmlCreator::attributeIndex]) && is_array($secData[cs_phpxmlCreator::attributeIndex])) { + //TODO: use method (i.e. $this->xmlReader->get_attribute($path)) to retrieve attributes. + $sectionAttribs = $secData[cs_phpxmlCreator::attributeIndex]; + unset($secData[cs_phpxmlCreator::attributeIndex]); //put stuff into the globals scope... if(isset($sectionAttribs['SETGLOBAL'])) { @@ -197,13 +198,23 @@ } } + $secData = $secData[0]; + $tSectionAttribs = null; + if(isset($secData[cs_phpxmlCreator::attributeIndex])) { + $tSectionAttribs = $secData[cs_phpxmlCreator::attributeIndex]; + unset($secData[cs_phpxmlCreator::attributeIndex]); + } foreach($secData as $itemName=>$itemValue) { $attribs = array(); - if(isset($itemValue['attributes']) && is_array($itemValue['attributes'])) { - $attribs = $itemValue['attributes']; + //TODO: use method (i.e. $this->xmlReader->get_attribute($path)) to retrieve attributes. + if(isset($itemValue[0][cs_phpxmlCreator::attributeIndex]) && is_array($itemValue[0][cs_phpxmlCreator::attributeIndex])) { + //TODO: use method (i.e. $this->xmlReader->get_attribute($path)) to retrieve attributes. + $attribs = $itemValue[0][cs_phpxmlCreator::attributeIndex]; } - if(isset($itemValue['value'])) { - $itemValue = $itemValue['value']; + //TODO: use method (i.e. $this->xmlReader->get_value($path)) to retrieve tag value. + if(isset($itemValue[0][cs_phpxmlCreator::dataIndex])) { + //TODO: use method (i.e. $this->xmlReader->get_value($path)) to retrieve tag value. + $itemValue = $itemValue[0][cs_phpxmlCreator::dataIndex]; } else { $itemValue = null; @@ -230,7 +241,7 @@ $parseThis[$itemName] = $itemValue; $parseThis[$section ."/". $itemName] = $itemValue; - $data[$section][$itemName]['value'] = $itemValue; + $data[$section][$itemName][cs_phpxmlCreator::dataIndex] = $itemValue; $setVarIndex = $this->setVarPrefix . $itemName; if(isset($attribs['SETGLOBAL'])) { @@ -264,7 +275,7 @@ if($this->a2p->get_data($configPath)) { $setMe = array(); foreach($this->a2p->get_data($configPath) as $i=>$v) { - $setMe[$i] = $v['value']; + $setMe[$i] = $v[cs_phpxmlCreator::dataIndex]; } $globA2p->set_data($globalsPath, $setMe); } @@ -294,14 +305,13 @@ public function get_section($section) { if($this->isInitialized === true) { $section = strtoupper($section); - $data = $this->a2p->get_data($section); + $data = $this->a2p->get_data($section .'/0'); - if(is_array($data) && count($data) && $data['type'] == 'open') { - unset($data['type']); + if(is_array($data) && count($data)) { $retval = $data; } else { - throw new exception(__METHOD__ .": invalid section (". $section .") or no data (". $data['type'] .")"); + throw new exception(__METHOD__ .": invalid section (". $section .") or no data::: ". $this->gfObj->debug_print($data,0)); } } else { @@ -332,7 +342,7 @@ //section NOT given, assume they're looking for something in the active section. $index = $this->activeSection ."/". $index; } - $retval = $this->a2p->get_data($index .'/value'); + $retval = $this->a2p->get_data($index .'/'. cs_phpxmlCreator::dataIndex); } else { throw new exception(__METHOD__ .": not initialized"); Modified: trunk/0.4/cs_webdbupgrade.class.php =================================================================== --- trunk/0.4/cs_webdbupgrade.class.php 2010-10-01 19:24:30 UTC (rev 187) +++ trunk/0.4/cs_webdbupgrade.class.php 2010-10-07 19:08:10 UTC (rev 188) @@ -304,10 +304,32 @@ //parse the file. $xmlParser = new cs_phpxmlParser($xmlString); - $config = $xmlParser->get_tree(TRUE); - - if(is_array($config['UPGRADE']) && count($config['UPGRADE'])) { - $this->config['UPGRADELIST'] = $config['UPGRADE']; + if($xmlParser->get_root_element() == 'UPGRADE') { + + //see if there's an "initial version" setting. + try { + $this->config['INITIALVERSION'] = $xmlParser->get_tag_value('/UPGRADE/INITIALVERSION'); + } + catch(Exception $e) { + //no worries, this only happens when the tag doesn't exist or it doesn't have data (that is okay). + } + + $tConfig = array(); + if(is_array($xmlParser->get_data('/UPGRADE/MATCHING'))) { + $matchingData = $xmlParser->get_data('/UPGRADE/MATCHING'); + foreach($matchingData as $index=>$array) { + $array = $array[0]; + foreach($array as $matchingName=>$subInfo) { + if(isset($subInfo[0][cs_phpxmlCreator::dataIndex])) { + $tConfig[$index][$matchingName] = $subInfo[0][cs_phpxmlCreator::dataIndex]; + } + else { + throw new exception(__METHOD__ .": invalid data beneath matching (". $index .")::: ". $this->gfObj->debug_print($subInfo,0)); + } + } + } + } + $this->config['matchingData'] = $tConfig; } else { $this->error_handler(__METHOD__ .": failed to retrieve 'UPGRADE' section; " . @@ -581,7 +603,7 @@ private function do_single_upgrade($fromVersion, $toVersion=null) { //Use the "matching_syntax" data in the upgrade.xml file to determine the filename. $versionIndex = "V". $this->get_full_version_string($fromVersion); - if(!isset($this->config['UPGRADELIST']['MATCHING'][$versionIndex])) { + if(!isset($this->config['matchingData'][$versionIndex])) { //version-only upgrade. $this->newVersion = $toVersion; $this->update_database_version($toVersion); @@ -590,7 +612,7 @@ //scripted upgrade... $scriptIndex = $versionIndex; - $upgradeData = $this->config['UPGRADELIST']['MATCHING'][$versionIndex]; + $upgradeData = $this->config['matchingData'][$versionIndex]; if(isset($upgradeData['TARGET_VERSION']) && count($upgradeData) > 1) { $this->newVersion = $upgradeData['TARGET_VERSION']; @@ -764,9 +786,9 @@ if(!$this->is_higher_version($dbVersion, $newVersion)) { $this->error_handler(__METHOD__ .": version (". $newVersion .") isn't higher than (". $dbVersion .")... something is broken"); } - elseif(is_array($this->config['UPGRADELIST']['MATCHING'])) { + elseif(is_array($this->config['matchingData'])) { $lastVersion = $dbVersion; - foreach($this->config['UPGRADELIST']['MATCHING'] as $matchVersion=>$data) { + foreach($this->config['matchingData'] as $matchVersion=>$data) { $matchVersion = preg_replace('/^V/', '', $matchVersion); if($matchVersion == $data['TARGET_VERSION']) { @@ -1044,8 +1066,8 @@ //if there's an INITIAL_VERSION in the upgrade config file, use that. $this->read_upgrade_config_file(); $insertData = array(); - if(isset($this->config['UPGRADELIST']['INITIALVERSION'])) { - $parseThis = $this->config['UPGRADELIST']['INITIALVERSION']; + if(isset($this->config['INITIALVERSION'])) { + $parseThis = $this->config['INITIALVERSION']; } else { $parseThis = $this->versionFileVersion; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2010-10-01 19:24:36
|
Revision: 187 http://cs-webapplibs.svn.sourceforge.net/cs-webapplibs/?rev=187&view=rev Author: crazedsanity Date: 2010-10-01 19:24:30 +0000 (Fri, 01 Oct 2010) Log Message: ----------- Building new version, based on impending changes to cs-phpxml that are potentially non-backwards-compatible. Added Paths: ----------- trunk/0.4/ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2010-09-09 02:42:00
|
Revision: 186 http://cs-webapplibs.svn.sourceforge.net/cs-webapplibs/?rev=186&view=rev Author: crazedsanity Date: 2010-09-09 02:41:54 +0000 (Thu, 09 Sep 2010) Log Message: ----------- Allow deleting of records. NOTE::: there is no logic for only allowing a single record to get deleted, and no transaction support (see TODO). /abstract/cs_singleTableHandler.abstract.class.php: * delete_record() [NEW]: -- allow deleting of record(s). -- see important TODO; this will hopefully be added in the near future. Modified Paths: -------------- trunk/0.3/abstract/cs_singleTableHandler.abstract.class.php Modified: trunk/0.3/abstract/cs_singleTableHandler.abstract.class.php =================================================================== --- trunk/0.3/abstract/cs_singleTableHandler.abstract.class.php 2010-09-02 14:35:30 UTC (rev 185) +++ trunk/0.3/abstract/cs_singleTableHandler.abstract.class.php 2010-09-09 02:41:54 UTC (rev 186) @@ -246,6 +246,29 @@ return($retval); }//end update_record() //------------------------------------------------------------------------- + + + + //------------------------------------------------------------------------- + /** + * TODO: only allow 1 record to be deleted, or a specific number of records (add transaction logic)? + */ + public function delete_record($recId) { + if(is_numeric($recId)) { + $sql = "DELETE FROM ". $this->tableName ." WHERE ". $this->pkeyField ."=". $recId; + try { + $result = $this->dbObj->run_update($sql); + } + catch(Exception $e) { + throw new exception(__METHOD__ .": failed to delete record, DETAILS::: ". $e->getMessage()); + } + } + else { + throw new exception(__METHOD__ .":: failed to delete record, invalid data (". $recId .")"); + } + return($result); + }//end delete_record() + //------------------------------------------------------------------------- } ?> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2010-09-02 14:35:36
|
Revision: 185 http://cs-webapplibs.svn.sourceforge.net/cs-webapplibs/?rev=185&view=rev Author: crazedsanity Date: 2010-09-02 14:35:30 +0000 (Thu, 02 Sep 2010) Log Message: ----------- Change protected functions into public ones for simplicity's sake. Modified Paths: -------------- trunk/0.3/abstract/cs_singleTableHandler.abstract.class.php Modified: trunk/0.3/abstract/cs_singleTableHandler.abstract.class.php =================================================================== --- trunk/0.3/abstract/cs_singleTableHandler.abstract.class.php 2010-09-01 14:12:57 UTC (rev 184) +++ trunk/0.3/abstract/cs_singleTableHandler.abstract.class.php 2010-09-02 14:35:30 UTC (rev 185) @@ -81,7 +81,7 @@ * @RETURN (int) SUCCESS: the (int) is the last inserted ID. * @EXCEPTION FAIL: exception indicates the error. */ - protected function create_record(array $data) { + public function create_record(array $data) { if(is_array($data) && count($data)) { $sql = 'INSERT INTO '. $this->tableName .' ' . $this->gfObj->string_from_array($data, 'insert', null, $this->cleanStringArr, true); @@ -110,7 +110,7 @@ * @RETURN (array) SUCCESS: list of field=>value of data from database. * @EXCEPTION FAIL: exception indicates the error. */ - protected function get_record_by_id($recId) { + public function get_record_by_id($recId) { if(is_numeric($recId)) { try { $data = $this->get_records(array($this->pkeyField => $recId)); @@ -137,7 +137,7 @@ * @RETURN (array) SUCCESS: returns single record with all fields. * @EXCEPTION FAIL: exception indicates error */ - protected function get_single_record(array $filter) { + public function get_single_record(array $filter) { if(is_array($filter) && count($filter)) { try { $data = $this->get_records($filter, null, 1); @@ -171,7 +171,7 @@ * @RETURN (array) SUCCESS: Primary index is the record ID, sub-array is same as returned by get_record_by_id(). * @EXCEPTION FAIL: exception indicates error. */ - protected function get_records(array $filter=null, $orderBy=null, $limit=null, $offset=null) { + public function get_records(array $filter=null, $orderBy=null, $limit=null, $offset=null) { $limitOffsetStr = ''; if(is_numeric($limit) && $limit > 0) { $limitOffsetStr = ' LIMIT '. $limit; @@ -221,7 +221,7 @@ * @RETURN (int) SUCCESS: (int) is the number of records updated (should always be 1) * @EXCEPTION FAIL: exception indicates the error. */ - protected function update_record($recId, array $updates, $removeEmptyVals=true) { + public function update_record($recId, array $updates, $removeEmptyVals=true) { if(is_numeric($recId) && $recId >= 0 && is_array($updates) && count($updates) > 0) { $updateString = $this->gfObj->string_from_array($updates, 'update', null, $this->cleanStringArr, $removeEmptyVals); if(is_null($updateString) || !strlen($updateString) || strlen($updateString) < 3) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2010-09-01 14:13:03
|
Revision: 184 http://cs-webapplibs.svn.sourceforge.net/cs-webapplibs/?rev=184&view=rev Author: crazedsanity Date: 2010-09-01 14:12:57 +0000 (Wed, 01 Sep 2010) Log Message: ----------- Throw exceptions when invalid data is encountered. /abstract/cs_singleTableHandler.abstract.class.php: * create_record(): -- throw an exception if there is no data. * get_single_record(): -- throw an exception if there's no data in the filter. * get_records(): -- throw an exception if there's a filter but no actual SQL appears to have been created (if the text is less than 3 characters). Modified Paths: -------------- trunk/0.3/abstract/cs_singleTableHandler.abstract.class.php Modified: trunk/0.3/abstract/cs_singleTableHandler.abstract.class.php =================================================================== --- trunk/0.3/abstract/cs_singleTableHandler.abstract.class.php 2010-09-01 14:09:53 UTC (rev 183) +++ trunk/0.3/abstract/cs_singleTableHandler.abstract.class.php 2010-09-01 14:12:57 UTC (rev 184) @@ -82,13 +82,18 @@ * @EXCEPTION FAIL: exception indicates the error. */ protected function create_record(array $data) { - $sql = 'INSERT INTO '. $this->tableName .' ' - . $this->gfObj->string_from_array($data, 'insert', null, $this->cleanStringArr, true); - try { - $newId = $this->dbObj->run_insert($sql, $this->seqName); + if(is_array($data) && count($data)) { + $sql = 'INSERT INTO '. $this->tableName .' ' + . $this->gfObj->string_from_array($data, 'insert', null, $this->cleanStringArr, true); + try { + $newId = $this->dbObj->run_insert($sql, $this->seqName); + } + catch(Exception $e) { + throw new exception(__METHOD__ .":: failed to create record, DETAILS::: ". $e->getMessage()); + } } - catch(Exception $e) { - throw new exception(__METHOD__ .":: failed to create record, DETAILS::: ". $e->getMessage()); + else { + throw new exception(__METHOD__ .":: no data passed"); } return($newId); }//end create_record() @@ -133,14 +138,19 @@ * @EXCEPTION FAIL: exception indicates error */ protected function get_single_record(array $filter) { - try { - $data = $this->get_records($filter, null, 1); - - $keys = array_keys($data); - $retval = $data[$keys[0]]; + if(is_array($filter) && count($filter)) { + try { + $data = $this->get_records($filter, null, 1); + + $keys = array_keys($data); + $retval = $data[$keys[0]]; + } + catch(Exception $e) { + throw new exception(__METHOD__ .":: failed to retrieve record, DETAILS::: ". $e->getMessage()); + } } - catch(Exception $e) { - throw new exception(__METHOD__ .":: failed to retrieve record, DETAILS::: ". $e->getMessage()); + else { + throw new exception(__METHOD__ .":: no filter passed"); } return($retval); @@ -179,7 +189,13 @@ $filterStr = ''; if(is_array($filter) && count($filter) > 0) { - $filterStr = ' WHERE '. $this->gfObj->string_from_array($filter, 'select', null, $this->cleanStringArr, true); + $filterSql = $this->gfObj->string_from_array($filter, 'select', null, $this->cleanStringArr, true); + if(strlen($filterSql) > 2) { + $filterStr = ' WHERE '. $filterSql; + } + else { + throw new exception(__METHOD__ .":: no filter created (". $this->gfObj->debug_print($filter,0) .")"); + } } $sql = 'SELECT * FROM '. $this->tableName . $filterStr . $orderByStr . $limitOffsetStr; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2010-09-01 14:09:59
|
Revision: 183 http://cs-webapplibs.svn.sourceforge.net/cs-webapplibs/?rev=183&view=rev Author: crazedsanity Date: 2010-09-01 14:09:53 +0000 (Wed, 01 Sep 2010) Log Message: ----------- More error handling for invalid SID's. /cs_sessionDB.class.php: * is_valid_sid(): -- call exception_handler() if something goes wrong. * sessdb_write(): -- check if the SID is the proper length, call exception handler if it is not. Modified Paths: -------------- trunk/0.3/cs_sessionDB.class.php Modified: trunk/0.3/cs_sessionDB.class.php =================================================================== --- trunk/0.3/cs_sessionDB.class.php 2010-09-01 14:07:52 UTC (rev 182) +++ trunk/0.3/cs_sessionDB.class.php 2010-09-01 14:09:53 UTC (rev 183) @@ -128,7 +128,7 @@ } } catch(exception $e) { - //well... do nothing I guess. + $this->exception_handler(__METHOD__ .": invalid sid (". $sid .")"); } } @@ -188,52 +188,57 @@ //------------------------------------------------------------------------- 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($sid) && strlen($sid) >= 20) { + $data = array( + 'session_data' => $data, + 'user_id' => null + ); + $cleanString = array( + 'session_data' => 'sql', + 'user_id' => 'numeric' + ); - if(is_string($uidVal) || is_numeric($uidVal)) { - $data['user_id'] = $uidVal; + + + //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 ."), sid=(". $sid ."), sid length=(". strlen($sid) ."), validSid=(". $this->is_valid_sid($sid) .")::: ". $e->getMessage()); + } } - - $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; + $this->exception_handler(__METHOD__ .": invalid sid (". $sid ."), DATA::: ". $this->gfObj->debug_print($data,0)); } - $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 ."), sid=(". $sid ."), sid length=(". strlen($sid) ."), validSid=(". $this->is_valid_sid($sid) .")::: ". $e->getMessage()); - } - return(true); }//end sessdb_write() //------------------------------------------------------------------------- This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2010-09-01 14:07:59
|
Revision: 182 http://cs-webapplibs.svn.sourceforge.net/cs-webapplibs/?rev=182&view=rev Author: crazedsanity Date: 2010-09-01 14:07:52 +0000 (Wed, 01 Sep 2010) Log Message: ----------- Ability to write all SQL queries to a file. /cs_phpDB.class.php: * MAIN::: -- NEW (protected) ARG: $fsObj -- NEW (protected) ARG: $logFile -- NEW (protected) ARG: $writeCommandsToFile * __construct(): -- ARG CHANGE: NEW ARG: #2 ($writeCommandsToFile=null) -- updated header -- added option to write all queries to a log file, whose name can be specified (i.e. $writeCommandsToFile=myfile.txt) -- logic to create a file if one not present * __call(): -- write data to a file if method was 'exec' and internal var, writeCommandsToFile, has been set. Modified Paths: -------------- trunk/0.3/cs_phpDB.class.php Modified: trunk/0.3/cs_phpDB.class.php =================================================================== --- trunk/0.3/cs_phpDB.class.php 2010-07-31 17:50:13 UTC (rev 181) +++ trunk/0.3/cs_phpDB.class.php 2010-09-01 14:07:52 UTC (rev 182) @@ -31,9 +31,21 @@ private $dbType; public $connectParams = array(); protected $gfObj; + protected $fsObj; + protected $logFile; + protected $writeCommandsToFile; //========================================================================= - public function __construct($type='pgsql') { + /** + * + * @param string $type + * @param bool $writeCommandsToFile (change this to a string for a filename, + * or use boolean true and it write to + * a default filename (__CLASS__.log). + * @return unknown_type + */ + public function __construct($type='pgsql', $writeCommandsToFile=null) { + if(is_null($type) || !strlen($type)) { $type = 'pgsql'; } @@ -46,6 +58,21 @@ parent::__construct(true); $this->isInitialized = TRUE; + + $this->writeCommandsToFile = $writeCommandsToFile; + + if($this->writeCommandsToFile) { + $this->logFile = __CLASS__ .".log"; + if(is_string($this->writeCommandsToFile)) { + $this->logFile = $this->writeCommandsToFile; + } + $this->fsObj = new cs_fileSystem(constant('RWDIR')); + $lsData = $this->fsObj->ls(); + if(!isset($lsData[$this->logFile])) { + $this->fsObj->create_file($this->logFile); + } + $this->fsObj->openFile($this->logFile, 'a'); + } }//end __construct() //========================================================================= @@ -67,6 +94,11 @@ array_pop($this->queryList); } array_unshift($this->queryList, $args[0]); + + //log it to a file. + if($this->writeCommandsToFile) { + $this->fsObj->append_to_file(date('D, d M Y H:i:s') . ' ('. microtime(true) . ')::: '. $args[0]); + } } $retval = call_user_func_array(array($this->dbLayerObj, $methodName), $args); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2010-07-31 17:50:19
|
Revision: 181 http://cs-webapplibs.svn.sourceforge.net/cs-webapplibs/?rev=181&view=rev Author: crazedsanity Date: 2010-07-31 17:50:13 +0000 (Sat, 31 Jul 2010) Log Message: ----------- Fix issue where session ID's aren't necessarily 32 characters long. /cs_sessionDB.class.php: * is_valid_sid(): -- length must be at least 20 (not 32) characters. * sessdb_write(): -- more info in the exception details. Modified Paths: -------------- trunk/0.3/cs_sessionDB.class.php Modified: trunk/0.3/cs_sessionDB.class.php =================================================================== --- trunk/0.3/cs_sessionDB.class.php 2010-07-23 14:17:25 UTC (rev 180) +++ trunk/0.3/cs_sessionDB.class.php 2010-07-31 17:50:13 UTC (rev 181) @@ -114,7 +114,7 @@ //------------------------------------------------------------------------- protected function is_valid_sid($sid) { $isValid = false; - if(strlen($sid) == 32) { + if(strlen($sid) >= 20) { try { $sql = "SELECT * FROM ". $this->tableName ." WHERE session_id='". $sid ."'"; @@ -231,7 +231,7 @@ } catch(exception $e) { //umm... yeah. - $this->exception_handler(__METHOD__ .": failed to perform action (". $type .")::: ". $e->getMessage()); + $this->exception_handler(__METHOD__ .": failed to perform action (". $type ."), sid=(". $sid ."), sid length=(". strlen($sid) ."), validSid=(". $this->is_valid_sid($sid) .")::: ". $e->getMessage()); } return(true); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2010-07-23 14:17:31
|
Revision: 180 http://cs-webapplibs.svn.sourceforge.net/cs-webapplibs/?rev=180&view=rev Author: crazedsanity Date: 2010-07-23 14:17:25 +0000 (Fri, 23 Jul 2010) Log Message: ----------- Updates to single-table handling & minor bug fixes. /cs_phpDB.class.php: * run_insert(): -- fix call to numRows() (was mistyped to instead appear to access a property instead of a method. /abstract/cs_singleTableHandler.abstract.class.php: * get_single_record(): -- header updated with new functionality -- accepts an array which is passed on to get_records() to allow for complex queries. -- forcibly limit result to 1 -- NOTE::: it may be desirable to allow an ordering too, and possibly a limit + offset, and NOT force limit to 1: if more than a single record is returned, it can throw an exception (the current way will always return a single record, but might actually be lulling them into a false sense of security due to the forced limit). * get_records(): -- minor update for header * update_record(): -- extra check to ensure cs_globalFunctions::string_from_array() actually created a string (handles the situation where all items in the array have empty values and are thereby removed) Modified Paths: -------------- trunk/0.3/abstract/cs_singleTableHandler.abstract.class.php trunk/0.3/cs_phpDB.class.php Modified: trunk/0.3/abstract/cs_singleTableHandler.abstract.class.php =================================================================== --- trunk/0.3/abstract/cs_singleTableHandler.abstract.class.php 2010-07-09 16:43:30 UTC (rev 179) +++ trunk/0.3/abstract/cs_singleTableHandler.abstract.class.php 2010-07-23 14:17:25 UTC (rev 180) @@ -125,23 +125,24 @@ //------------------------------------------------------------------------- /** - * Just a simple wrapper to get_records(), no initial (id-based) record used. + * Just a simple wrapper to get_records(), guaranteed to return a single record. * - * @param $fieldname (str) field to search (for $value) - * @param $value (str) value to find (in $field) - * @param $orderBy (str) field to order by; can contain "DESC" or "ASC" - * @param $limit (int) how many records to display - * @param $offset (int) offset by this many records + * @param $filter (array) fieldname=>value list of filters. * * @RETURN (array) SUCCESS: returns single record with all fields. * @EXCEPTION FAIL: exception indicates error */ - protected function get_single_record($fieldname, $value, $orderBy=null, $limit=null, $offset=null) { - $data = $this->get_records(array($fieldname=>$value), $orderBy, $limit, $offset); + protected function get_single_record(array $filter) { + try { + $data = $this->get_records($filter, null, 1); + + $keys = array_keys($data); + $retval = $data[$keys[0]]; + } + catch(Exception $e) { + throw new exception(__METHOD__ .":: failed to retrieve record, DETAILS::: ". $e->getMessage()); + } - $keys = array_keys($data); - $retval = $data[$keys[0]]; - return($retval); }//end get_single_record() //------------------------------------------------------------------------- @@ -153,7 +154,7 @@ * Retrieves a number of records based on arguments. * * @$filter (array) Field=>value list of filters (i.e. 'my_id'=>1) - * @$orderBy (str) Field to order by; can contain "DESC" or "ASC". + * @$orderBy (str) Field to order by; can contain "DESC" or "ASC". * @$limit (int) How many max records to display. * @$offset (int) Offset by this number of records. * @@ -204,20 +205,27 @@ * @RETURN (int) SUCCESS: (int) is the number of records updated (should always be 1) * @EXCEPTION FAIL: exception indicates the error. */ - protected function update_record($recId, array $updates) { + protected function update_record($recId, array $updates, $removeEmptyVals=true) { if(is_numeric($recId) && $recId >= 0 && is_array($updates) && count($updates) > 0) { - $sql = 'UPDATE '. $this->tableName .' SET ' - . $this->gfObj->string_from_array($updates, 'update', null, $this->cleanStringArr, true) - .' WHERE '. $this->pkeyField .'='. $recId; - try { - $retval = $this->dbObj->run_update($sql, true); + $updateString = $this->gfObj->string_from_array($updates, 'update', null, $this->cleanStringArr, $removeEmptyVals); + if(is_null($updateString) || !strlen($updateString) || strlen($updateString) < 3) { + throw new exception(__METHOD__ .":: no update string created (". $updateSTring ."), contents::: ". $this->gfObj->debug_var_dump($updates,0)); } - catch(Exception $e) { - throw new exception(__METHOD__ .":: failed to update record (". $recId ."), DETAILS::: ". $e->getMessage()); + else { + $sql = 'UPDATE '. $this->tableName .' SET ' + . $updateString + .' WHERE '. $this->pkeyField .'='. $recId; + try { + $retval = $this->dbObj->run_update($sql, true); +#$this->gfObj->debug_print(__METHOD__ .":: retval=(". $retval ."), SQL::: ". $sql ,1); + } + catch(Exception $e) { + throw new exception(__METHOD__ .":: failed to update record (". $recId ."), DETAILS::: ". $e->getMessage()); + } } } else { - throw new exception(__METHOD__ .":: failed to update record (". $recId ."), DETAILS::: ". $e->getMessage()); + throw new exception(__METHOD__ .":: failed to update record (". $recId ."), invalid recordId (". $recId ."), or no data in array::: ". $this->gfObj->debug_var_dump($updates,0)); } return($retval); }//end update_record() Modified: trunk/0.3/cs_phpDB.class.php =================================================================== --- trunk/0.3/cs_phpDB.class.php 2010-07-09 16:43:30 UTC (rev 179) +++ trunk/0.3/cs_phpDB.class.php 2010-07-23 14:17:25 UTC (rev 180) @@ -151,7 +151,7 @@ } else { //something broke... - throw new exception(__METHOD__ .": failed to insert, rows=(". $this->numRows .")... " + throw new exception(__METHOD__ .": failed to insert, rows=(". $this->numRows() .")... " ."ERROR::: ". $this->errorMsg() ."\n -- SQL:::: ". $sql); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2010-07-09 16:43:36
|
Revision: 179 http://cs-webapplibs.svn.sourceforge.net/cs-webapplibs/?rev=179&view=rev Author: crazedsanity Date: 2010-07-09 16:43:30 +0000 (Fri, 09 Jul 2010) Log Message: ----------- Declare __construct() as public, change get_single_record() to protected. Modified Paths: -------------- trunk/0.3/abstract/cs_singleTableHandler.abstract.class.php Modified: trunk/0.3/abstract/cs_singleTableHandler.abstract.class.php =================================================================== --- trunk/0.3/abstract/cs_singleTableHandler.abstract.class.php 2010-07-08 16:08:46 UTC (rev 178) +++ trunk/0.3/abstract/cs_singleTableHandler.abstract.class.php 2010-07-09 16:43:30 UTC (rev 179) @@ -29,7 +29,7 @@ * @param $pkeyField (str) Name of the primary key field, for performing updates & retrieving specific records. * @param $cleanStringArr (array) Array of {fieldName}=>{dataType} for allowing updates & creating records. */ - function __construct(cs_phpDB $dbObj, $tableName, $seqName, $pkeyField, array $cleanStringArr) { + public function __construct(cs_phpDB $dbObj, $tableName, $seqName, $pkeyField, array $cleanStringArr) { $this->set_version_file_location(dirname(__FILE__) . '/../VERSION'); parent::__construct(true); @@ -136,7 +136,7 @@ * @RETURN (array) SUCCESS: returns single record with all fields. * @EXCEPTION FAIL: exception indicates error */ - public function get_single_record($fieldname, $value, $orderBy=null, $limit=null, $offset=null) { + protected function get_single_record($fieldname, $value, $orderBy=null, $limit=null, $offset=null) { $data = $this->get_records(array($fieldname=>$value), $orderBy, $limit, $offset); $keys = array_keys($data); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2010-07-08 16:08:52
|
Revision: 178 http://cs-webapplibs.svn.sourceforge.net/cs-webapplibs/?rev=178&view=rev Author: crazedsanity Date: 2010-07-08 16:08:46 +0000 (Thu, 08 Jul 2010) Log Message: ----------- Method for retrieving a single record, updating header comments. Modified Paths: -------------- trunk/0.3/abstract/cs_singleTableHandler.abstract.class.php Modified: trunk/0.3/abstract/cs_singleTableHandler.abstract.class.php =================================================================== --- trunk/0.3/abstract/cs_singleTableHandler.abstract.class.php 2010-07-07 14:14:46 UTC (rev 177) +++ trunk/0.3/abstract/cs_singleTableHandler.abstract.class.php 2010-07-08 16:08:46 UTC (rev 178) @@ -23,11 +23,11 @@ /** * Generic way of using a class to define how to update a single database table. * - * @dbObj (object) Connected instance of cs_phpDB{}. - * @tableName (str) Name of table inserting/updating. - * @seqName (str) Name of sequence, used with PostgreSQL for retrieving the last inserted ID. - * @pkeyField (str) Name of the primary key field, for performing updates & retrieving specific records. - * @cleanStringArr (array) Array of {fieldName}=>{dataType} for allowing updates & creating records. + * @param $dbObj (object) Connected instance of cs_phpDB{}. + * @param $tableName (str) Name of table inserting/updating. + * @param $seqName (str) Name of sequence, used with PostgreSQL for retrieving the last inserted ID. + * @param $pkeyField (str) Name of the primary key field, for performing updates & retrieving specific records. + * @param $cleanStringArr (array) Array of {fieldName}=>{dataType} for allowing updates & creating records. */ function __construct(cs_phpDB $dbObj, $tableName, $seqName, $pkeyField, array $cleanStringArr) { $this->set_version_file_location(dirname(__FILE__) . '/../VERSION'); @@ -76,7 +76,7 @@ /** * Insert a new record into the table. * - * @$data (array) field=>value pairs of data to be inserted. + * @param $data (array) field=>value pairs of data to be inserted. * * @RETURN (int) SUCCESS: the (int) is the last inserted ID. * @EXCEPTION FAIL: exception indicates the error. @@ -100,10 +100,10 @@ /** * Retrieve a record based on a given ID, such as was returned from create_record(). * - * @$recId (int) ID to retrieve. + * @param $recId (int) ID to retrieve. * - * @RETURN (array) SUCCESS: list of field=>value of data from database. - * @EXCEPTION FAIL: exception indicates the error. + * @RETURN (array) SUCCESS: list of field=>value of data from database. + * @EXCEPTION FAIL: exception indicates the error. */ protected function get_record_by_id($recId) { if(is_numeric($recId)) { @@ -125,12 +125,37 @@ //------------------------------------------------------------------------- /** + * Just a simple wrapper to get_records(), no initial (id-based) record used. + * + * @param $fieldname (str) field to search (for $value) + * @param $value (str) value to find (in $field) + * @param $orderBy (str) field to order by; can contain "DESC" or "ASC" + * @param $limit (int) how many records to display + * @param $offset (int) offset by this many records + * + * @RETURN (array) SUCCESS: returns single record with all fields. + * @EXCEPTION FAIL: exception indicates error + */ + public function get_single_record($fieldname, $value, $orderBy=null, $limit=null, $offset=null) { + $data = $this->get_records(array($fieldname=>$value), $orderBy, $limit, $offset); + + $keys = array_keys($data); + $retval = $data[$keys[0]]; + + return($retval); + }//end get_single_record() + //------------------------------------------------------------------------- + + + + //------------------------------------------------------------------------- + /** * Retrieves a number of records based on arguments. * * @$filter (array) Field=>value list of filters (i.e. 'my_id'=>1) - * @orderBy (str) Field to order by; can contain "DESC" or "ASC". - * @limit (int) How many max records to display. - * @offset (int) Offset by this number of records. + * @$orderBy (str) Field to order by; can contain "DESC" or "ASC". + * @$limit (int) How many max records to display. + * @$offset (int) Offset by this number of records. * * @RETURN (array) SUCCESS: Primary index is the record ID, sub-array is same as returned by get_record_by_id(). * @EXCEPTION FAIL: exception indicates error. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2010-07-07 14:14:55
|
Revision: 177 http://cs-webapplibs.svn.sourceforge.net/cs-webapplibs/?rev=177&view=rev Author: crazedsanity Date: 2010-07-07 14:14:46 +0000 (Wed, 07 Jul 2010) Log Message: ----------- Better checking, exceptions on invalid data, add queryList to cs_phpDB. /cs_phpDB.class.php: * MAIN::: -- NEW (public) VAR: $queryList=array() * __call(): -- if method is 'exec', add query to the queryList (holds last 20) * is_connected(): -- returns the value of dbLayerObj->is_connected(). /cs_webdblogger.class.php: * __construct(): -- throws an exception if the passed $db object isn't an object. /cs_webdbupgrade.class.php: * load_initial_version(): -- put calls to cs_phpDB methods into try/catch /abstract/cs_singleTableHandler.abstract.class.php: * MAIN::: -- changed members/vars to non-abstract (not valid) * __construct(): -- better checking of the database object. /db_types/cs_phpDB__pgsql.class.php: * exec(): -- simplify checking: if numRows() gives a good answer, use that; otherwise, use the output of numAffected(). /db_types/cs_phpDB__mysql.class.php: * exec(): -- simplify check as in pgsql layer. /db_types/cs_phpDB__sqlite.class.php: * exec(): -- simplify check as in pgsql layer. /tests/testOfCSGenericPermissions.php: * get_valid_users(): -- put stuff into try/catch. -- NOTE::: there's a call to cs_debug_backtrace(), which is a function that only exists locally. Modified Paths: -------------- trunk/0.3/abstract/cs_singleTableHandler.abstract.class.php trunk/0.3/cs_phpDB.class.php trunk/0.3/cs_webdblogger.class.php trunk/0.3/cs_webdbupgrade.class.php trunk/0.3/db_types/cs_phpDB__mysql.class.php trunk/0.3/db_types/cs_phpDB__pgsql.class.php trunk/0.3/db_types/cs_phpDB__sqlite.class.php trunk/0.3/tests/testOfCSGenericPermissions.php Modified: trunk/0.3/abstract/cs_singleTableHandler.abstract.class.php =================================================================== --- trunk/0.3/abstract/cs_singleTableHandler.abstract.class.php 2010-06-24 21:15:25 UTC (rev 176) +++ trunk/0.3/abstract/cs_singleTableHandler.abstract.class.php 2010-07-07 14:14:46 UTC (rev 177) @@ -13,11 +13,11 @@ abstract class cs_singleTableHandlerAbstract extends cs_webapplibsAbstract { protected $gfObj; - abstract protected $tableName; - abstract protected $seqName; - abstract protected $pkeyField; - abstract protected $cleanStringArr; - abstract protected $dbParams; + protected $tableName; + protected $seqName; + protected $pkeyField; + protected $cleanStringArr; + protected $dbParams; //------------------------------------------------------------------------- /** @@ -33,11 +33,11 @@ $this->set_version_file_location(dirname(__FILE__) . '/../VERSION'); parent::__construct(true); - if($dbObj->is_connnected()) { + if(isset($dbObj) && is_object($dbObj) && $dbObj->is_connected()) { $this->dbObj = $dbObj; } else { - throw new exception(__METHOD__ .":: database object not connected"); + throw new exception(__METHOD__ .":: database object not connected or not passed"); } if(is_string($tableName) && strlen($tableName)) { Modified: trunk/0.3/cs_phpDB.class.php =================================================================== --- trunk/0.3/cs_phpDB.class.php 2010-06-24 21:15:25 UTC (rev 176) +++ trunk/0.3/cs_phpDB.class.php 2010-07-07 14:14:46 UTC (rev 177) @@ -26,6 +26,7 @@ class cs_phpDB extends cs_webapplibsAbstract { + public $queryList=array(); private $dbLayerObj; private $dbType; public $connectParams = array(); @@ -60,6 +61,13 @@ //capture the connection parameters. $this->connectParams = $args[0]; } + elseif($methodName == 'exec') { + //update lastQuery list... should hold the last few SQL commands. + if(count($this->queryList) > 20) { + array_pop($this->queryList); + } + array_unshift($this->queryList, $args[0]); + } $retval = call_user_func_array(array($this->dbLayerObj, $methodName), $args); } else { @@ -204,6 +212,14 @@ return($retval); }//end run_sql_file() //========================================================================= + + + + //========================================================================= + public function is_connected() { + return($this->dbLayerObj->is_connected()); + }//end is_connected() + //========================================================================= } // end class phpDB ?> Modified: trunk/0.3/cs_webdblogger.class.php =================================================================== --- trunk/0.3/cs_webdblogger.class.php 2010-06-24 21:15:25 UTC (rev 176) +++ trunk/0.3/cs_webdblogger.class.php 2010-07-07 14:14:46 UTC (rev 177) @@ -86,7 +86,12 @@ */ public function __construct(cs_phpDB &$db, $logCategory=null, $checkForUpgrades=true) { //assign the database object. - $this->db = $db; + if(is_object($db) && get_class($db) == 'cs_phpDB') { + $this->db = $db; + } + else { + throw new exception(__METHOD__ .":: invalid database object"); + } $this->set_version_file_location(dirname(__FILE__) . '/VERSION'); Modified: trunk/0.3/cs_webdbupgrade.class.php =================================================================== --- trunk/0.3/cs_webdbupgrade.class.php 2010-06-24 21:15:25 UTC (rev 176) +++ trunk/0.3/cs_webdbupgrade.class.php 2010-07-07 14:14:46 UTC (rev 177) @@ -1058,12 +1058,17 @@ $sql = 'INSERT INTO '. $this->config['DB_TABLE'] . $this->gfObj->string_from_array($insertData, 'insert'); - if($this->db->run_insert($sql, $this->sequenceName)) { - $loadRes = true; - $this->do_log("Created data for '". $this->projectName ."' with version '". $insertData['version_string'] ."'", 'initialize'); + try { + if($this->db->run_insert($sql, $this->sequenceName)) { + $loadRes = true; + $this->do_log("Created data for '". $this->projectName ."' with version '". $insertData['version_string'] ."'", 'initialize'); + } + else { + $this->error_handler(__METHOD__ .": failed to load initial version::: ". $e->getMessage()); + } } - else { - $this->error_handler(__METHOD__ .": failed to load initial version::: ". $e->getMessage()); + catch(Exception $e) { + $this->error_handler(__METHOD__ .":: failed to load initial version due to exception, DETAILS::: ". $e->getMessage()); } return($loadRes); Modified: trunk/0.3/db_types/cs_phpDB__mysql.class.php =================================================================== --- trunk/0.3/db_types/cs_phpDB__mysql.class.php 2010-06-24 21:15:25 UTC (rev 176) +++ trunk/0.3/db_types/cs_phpDB__mysql.class.php 2010-07-07 14:14:46 UTC (rev 177) @@ -213,19 +213,18 @@ $this->result = mysql_query($query, $this->connectionID); if($this->result !== false) { - if (eregi("^[[:space:]]*select", $query)) { - //If we didn't have an error and we are a select statement, move the pointer to first result + if($this->result !== false) { $numRows = $this->numRows(); - if($numRows > 0) { - $this->move_first(); + if($numRows != 0) { + $returnVal = $numRows; + if($numRows > 0) { + $this->move_first(); + } } - $returnVal = $numRows; - + else { + $returnVal = $this->numAffected(); + } } - else { - //We got something other than an update. Use numAffected - $returnVal = $this->numAffected(); - } } return($returnVal); }//end exec() Modified: trunk/0.3/db_types/cs_phpDB__pgsql.class.php =================================================================== --- trunk/0.3/db_types/cs_phpDB__pgsql.class.php 2010-06-24 21:15:25 UTC (rev 176) +++ trunk/0.3/db_types/cs_phpDB__pgsql.class.php 2010-07-07 14:14:46 UTC (rev 177) @@ -230,27 +230,25 @@ if($this->useQueryList) { $this->queryList[] = $query; } - $returnVal = false; + $returnVal = false; if(($this->get_transaction_status() != -1) && ($this->connectionID != -1)) { $this->result = @pg_query($this->connectionID, $query); if($this->result !== false) { - if (eregi("^[[:space:]]*select", $query)) { - //If we didn't have an error and we are a select statement, move the pointer to first result - $numRows = $this->numRows(); + $numRows = $this->numRows(); + if($numRows != 0) { + $returnVal = $numRows; if($numRows > 0) { $this->move_first(); } - $returnVal = $numRows; - } else { - //We got something other than an update. Use numAffected $returnVal = $this->numAffected(); } } } + return($returnVal); }//end exec() //========================================================================= Modified: trunk/0.3/db_types/cs_phpDB__sqlite.class.php =================================================================== --- trunk/0.3/db_types/cs_phpDB__sqlite.class.php 2010-06-24 21:15:25 UTC (rev 176) +++ trunk/0.3/db_types/cs_phpDB__sqlite.class.php 2010-07-07 14:14:46 UTC (rev 177) @@ -178,13 +178,14 @@ $this->result = @sqlite_query($this->connectionID, $query); if($this->result !== false) { - if (eregi("^[[:space:]]*select", $query)) { - //If we didn't have an error and we are a select statement, move the pointer to first result - $numRows = $this->numRows(); + $numRows = $this->numRows(); + if($numRows != 0) { $returnVal = $numRows; + if($numRows > 0) { + $this->move_first(); + } } else { - //We got something other than an update. Use numAffected $returnVal = $this->numAffected(); } } Modified: trunk/0.3/tests/testOfCSGenericPermissions.php =================================================================== --- trunk/0.3/tests/testOfCSGenericPermissions.php 2010-06-24 21:15:25 UTC (rev 176) +++ trunk/0.3/tests/testOfCSGenericPermissions.php 2010-07-07 14:14:46 UTC (rev 177) @@ -81,8 +81,14 @@ */ private function get_valid_users() { $sql = "SELECT uid,username FROM cs_authentication_table ORDER BY uid"; - $db = $this->create_dbconn(); - $this->validUsers = $db->run_query($sql); + try { + $db = $this->create_dbconn(); + $this->validUsers = $db->run_query($sql); + } + catch(Exception $e) { + cs_debug_backtrace(1); + throw new exception(__METHOD__ .":: failed to retrieve any records (". $db->numRows() ."), DB OBJECT::: ". $this->gfObj->debug_print($db,0)); + } }//end get_valid_users() //-------------------------------------------------------------------------- This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2010-06-24 21:15:31
|
Revision: 176 http://cs-webapplibs.svn.sourceforge.net/cs-webapplibs/?rev=176&view=rev Author: crazedsanity Date: 2010-06-24 21:15:25 +0000 (Thu, 24 Jun 2010) Log Message: ----------- Class that simplifies other classes which simply do database modifications on a single table. Added Paths: ----------- trunk/0.3/abstract/cs_singleTableHandler.abstract.class.php Copied: trunk/0.3/abstract/cs_singleTableHandler.abstract.class.php (from rev 175, trunk/0.3/abstract/cs_webapplibs.abstract.class.php) =================================================================== --- trunk/0.3/abstract/cs_singleTableHandler.abstract.class.php (rev 0) +++ trunk/0.3/abstract/cs_singleTableHandler.abstract.class.php 2010-06-24 21:15:25 UTC (rev 176) @@ -0,0 +1,202 @@ +<?php +/* + * Created on June 24, 2010 + * + * SVN INFORMATION::: + * ------------------- + * Last Author::::::::: $Author$ + * Current Revision:::: $Revision$ + * Repository Location: $HeadURL$ + * Last Updated:::::::: $Date$ + */ + +abstract class cs_singleTableHandlerAbstract extends cs_webapplibsAbstract { + + protected $gfObj; + abstract protected $tableName; + abstract protected $seqName; + abstract protected $pkeyField; + abstract protected $cleanStringArr; + abstract protected $dbParams; + + //------------------------------------------------------------------------- + /** + * Generic way of using a class to define how to update a single database table. + * + * @dbObj (object) Connected instance of cs_phpDB{}. + * @tableName (str) Name of table inserting/updating. + * @seqName (str) Name of sequence, used with PostgreSQL for retrieving the last inserted ID. + * @pkeyField (str) Name of the primary key field, for performing updates & retrieving specific records. + * @cleanStringArr (array) Array of {fieldName}=>{dataType} for allowing updates & creating records. + */ + function __construct(cs_phpDB $dbObj, $tableName, $seqName, $pkeyField, array $cleanStringArr) { + $this->set_version_file_location(dirname(__FILE__) . '/../VERSION'); + parent::__construct(true); + + if($dbObj->is_connnected()) { + $this->dbObj = $dbObj; + } + else { + throw new exception(__METHOD__ .":: database object not connected"); + } + + if(is_string($tableName) && strlen($tableName)) { + $this->tableName = $tableName; + } + else { + throw new exception(__METHOD__ .":: invalid table name (". $tableName .")"); + } + + if(is_string($seqName) && strlen($seqName)) { + $this->seqName = $seqName; + } + else { + throw new exception(__METHOD__ .":: invalid sequence name (". $seqName .")"); + } + + if(is_string($pkeyField) && strlen($pkeyField)) { + $this->pkeyField = $pkeyField; + } + else { + throw new exception(__METHOD__ .":: invalid primary key field name (". $pkeyField .")"); + } + + if(is_array($cleanStringArr) && count($cleanStringArr)) { + $this->cleanStringArr = $cleanStringArr; + } + else { + throw new exception(__METHOD__ .":: invalid clean string array"); + } + }//end __construct() + //------------------------------------------------------------------------- + + + + //------------------------------------------------------------------------- + /** + * Insert a new record into the table. + * + * @$data (array) field=>value pairs of data to be inserted. + * + * @RETURN (int) SUCCESS: the (int) is the last inserted ID. + * @EXCEPTION FAIL: exception indicates the error. + */ + protected function create_record(array $data) { + $sql = 'INSERT INTO '. $this->tableName .' ' + . $this->gfObj->string_from_array($data, 'insert', null, $this->cleanStringArr, true); + try { + $newId = $this->dbObj->run_insert($sql, $this->seqName); + } + catch(Exception $e) { + throw new exception(__METHOD__ .":: failed to create record, DETAILS::: ". $e->getMessage()); + } + return($newId); + }//end create_record() + //------------------------------------------------------------------------- + + + + //------------------------------------------------------------------------- + /** + * Retrieve a record based on a given ID, such as was returned from create_record(). + * + * @$recId (int) ID to retrieve. + * + * @RETURN (array) SUCCESS: list of field=>value of data from database. + * @EXCEPTION FAIL: exception indicates the error. + */ + protected function get_record_by_id($recId) { + if(is_numeric($recId)) { + try { + $data = $this->get_records(array($this->pkeyField => $recId)); + } + catch(Exception $e) { + throw new exception(__METHOD__ .":: error while retrieving record (". $recId ."), DETAILS::: ". $e->getMessage()); + } + } + else { + throw new exception(__METHOD__ .":: failed to retrieve record (". $recId ."), DETAILS::: ". $e->getMessage()); + } + return($data); + }//end get_record_by_id() + //------------------------------------------------------------------------- + + + + //------------------------------------------------------------------------- + /** + * Retrieves a number of records based on arguments. + * + * @$filter (array) Field=>value list of filters (i.e. 'my_id'=>1) + * @orderBy (str) Field to order by; can contain "DESC" or "ASC". + * @limit (int) How many max records to display. + * @offset (int) Offset by this number of records. + * + * @RETURN (array) SUCCESS: Primary index is the record ID, sub-array is same as returned by get_record_by_id(). + * @EXCEPTION FAIL: exception indicates error. + */ + protected function get_records(array $filter=null, $orderBy=null, $limit=null, $offset=null) { + $limitOffsetStr = ''; + if(is_numeric($limit) && $limit > 0) { + $limitOffsetStr = ' LIMIT '. $limit; + + //While it appears to be acceptable to provide an offset without a limit, it seems ridiculous to me. + if(is_numeric($offset) && $offset > 0) { + $limitOffsetStr .= ' OFFSET '. $offset; + } + } + + $orderByStr = ''; + if(is_string($orderBy) && strlen($orderBy)) { + $orderByStr = ' ORDER BY '. $orderBy; + } + + $filterStr = ''; + if(is_array($filter) && count($filter) > 0) { + $filterStr = ' WHERE '. $this->gfObj->string_from_array($filter, 'select', null, $this->cleanStringArr, true); + } + + $sql = 'SELECT * FROM '. $this->tableName . $filterStr . $orderByStr . $limitOffsetStr; + try { + $data = $this->dbObj->run_query($sql, $this->pkeyField); + } + catch(Exception $e) { + throw new exception(__METHOD__ .":: failed to retrieve records, DETAILS::: ". $e->getMessage()); + } + return($data); + }//end get_records() + //------------------------------------------------------------------------- + + + + //------------------------------------------------------------------------- + /** + * Update a single record with the given changes. + * + * @recId (int) ID to update. + * @updates (array) field=>value list of changes. + * + * @RETURN (int) SUCCESS: (int) is the number of records updated (should always be 1) + * @EXCEPTION FAIL: exception indicates the error. + */ + protected function update_record($recId, array $updates) { + if(is_numeric($recId) && $recId >= 0 && is_array($updates) && count($updates) > 0) { + $sql = 'UPDATE '. $this->tableName .' SET ' + . $this->gfObj->string_from_array($updates, 'update', null, $this->cleanStringArr, true) + .' WHERE '. $this->pkeyField .'='. $recId; + try { + $retval = $this->dbObj->run_update($sql, true); + } + catch(Exception $e) { + throw new exception(__METHOD__ .":: failed to update record (". $recId ."), DETAILS::: ". $e->getMessage()); + } + } + else { + throw new exception(__METHOD__ .":: failed to update record (". $recId ."), DETAILS::: ". $e->getMessage()); + } + return($retval); + }//end update_record() + //------------------------------------------------------------------------- +} + +?> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2010-06-23 13:46:04
|
Revision: 175 http://cs-webapplibs.svn.sourceforge.net/cs-webapplibs/?rev=175&view=rev Author: crazedsanity Date: 2010-06-23 13:45:57 +0000 (Wed, 23 Jun 2010) Log Message: ----------- Better enumeration of permission bits + testing & removal of misleading example. /docs/example_genericPermission.php [DELETED]: * removed unnecessary (misleading) example. /tests/testOfCSGenericPermissions.php: * new tests: -- check if user is member of a group after user_group record created -- create permission by type array, enumerating user/group/other perms for sanity checking. -- test to ensure permission doesn't already exist before creating. -- check has_*_permission() for several users to mostly ensure that everything is working as intended. /abstract/cs_genericUserGroup.abstract.class.php: * get_user_groups(): -- minor comment change -- wording change on exception * is_group_member() [NEW]: -- determines if a user is member of a given groupId, instead of having to manually check user's entire group list. /cs_genericPermission.class.php: * ADDED HEADERS: -- __construct() -- parse_permission_string() -- build_permission_string() -- create_object() -- create_permission() -- get_object() -- get_permission() -- get_object_by_id() -- get_permission_by_id() * build_permission_string(): -- use evaluate_perm_value() instead of arbitrary check when deciding between "-" and the given permission bit (r/w/x) * check_permission() [NEW]: -- retrieves a permission list for the given user for the given object. * get_permission_list() [NEW]: -- returns an array of permission bits based on type (u/g/o) * evaluate_perm_value() [NEW]: -- determine if a particular bit's value is true/false (defaults to true, keeping in line with PHP's true/false evaluation). * permission_exists() [NEW]: -- true/false determination of whether or not a permission exists. -- NOTE::: this is just like using a try/catch around get_permission() where an exception means false; it is just a simpler approach. * has_read_permission() [NEW]: -- true/false whether user has read permission for the given named object. * has_write_permission() [NEW]: -- true/false if user has write permission for given named object. * has_execute_permission() [NEW]: -- true/false if user has execute permission for given named object. Modified Paths: -------------- trunk/0.3/abstract/cs_genericUserGroup.abstract.class.php trunk/0.3/cs_genericPermission.class.php trunk/0.3/tests/testOfCSGenericPermissions.php Removed Paths: ------------- trunk/0.3/docs/example_genericPermission.php Modified: trunk/0.3/abstract/cs_genericUserGroup.abstract.class.php =================================================================== --- trunk/0.3/abstract/cs_genericUserGroup.abstract.class.php 2010-06-21 17:56:47 UTC (rev 174) +++ trunk/0.3/abstract/cs_genericUserGroup.abstract.class.php 2010-06-23 13:45:57 UTC (rev 175) @@ -57,15 +57,28 @@ $retval = $this->db->run_query($sql, 'group_id'); } catch(Exception $e) { - throw new exception(__METHOD__ .":: failed to locate group (". $groupName ."), DETAILS::: ". $e->getMessage()); + throw new exception(__METHOD__ .":: failed to locate groups for user_id=(". $userId ."), DETAILS::: ". $e->getMessage()); } } else { throw new exception(__METHOD__ .":: invalid or non-numeric user_id (". $userId .")"); } return($retval); - }//end get_group() + }//end get_user_groups() //============================================================================ + + + //============================================================================ + public function is_group_member($userId, $groupId) { + $groupList = $this->get_user_groups($userId); + $retval = false; + if(isset($groupList[$groupId])) { + $retval = true; + } + return($retval); + }//end is_group_member() + //============================================================================ + } ?> Modified: trunk/0.3/cs_genericPermission.class.php =================================================================== --- trunk/0.3/cs_genericPermission.class.php 2010-06-21 17:56:47 UTC (rev 174) +++ trunk/0.3/cs_genericPermission.class.php 2010-06-23 13:45:57 UTC (rev 175) @@ -29,6 +29,9 @@ protected $keys = array(); //============================================================================ + /** + * Generic permission system based on *nix filesystem permissions. + */ public function __construct(cs_phpDB $db) { $this->db = $db; parent::__construct($db); @@ -63,6 +66,9 @@ //============================================================================ + /** + * Parses a string like 'rwxr-xr--' into keys for the database. + */ protected function parse_permission_string($string) { $this->_sanityCheck(); if(is_string($string) && strlen($string) == 9) { @@ -87,6 +93,9 @@ //============================================================================ + /** + * Create permission string based on an array (the opposite of parse_permission_string()) + */ protected function build_permission_string(array $perms) { $this->_sanityCheck(); if(is_array($perms) && count($perms) >= count($this->keys)) { @@ -94,9 +103,11 @@ foreach($this->keys as $dbColName) { if(isset($perms[$dbColName])) { //get the last character of the column name. - $permChar = substr($dbColName, -1); - if($perms[$dbColName] === false || !strlen($perms[$dbColName]) || $perms[$dbColName] === '-' || $perms[$dbColName] === 'f') { - + $thisPermChar = substr($dbColName, -1); + if($this->evaluate_perm_value($perms[$dbColName], $thisPermChar)) { + $permChar = substr($dbColName, -1); + } + else { $permChar = '-'; } $retval .= $permChar; @@ -116,6 +127,9 @@ //============================================================================ + /** + * Same as create_permission(). + */ public function create_object($name, $userId, $groupId, $permString) { return($this->create_permission($name, $userId, $groupId, $permString)); }//end create_object() @@ -124,6 +138,9 @@ //============================================================================ + /** + * Creates a permission object record. + */ public function create_permission($name, $userId, $groupId, $permString) { if(is_string($name) && strlen($name) && is_numeric($userId) && $userId >= 0 && is_numeric($groupId) && $groupId >= 0) { $cleanStringArr = array( @@ -165,6 +182,9 @@ //============================================================================ + /** + * Same as get_permission(). + */ public function get_object($name) { return($this->get_permission($name)); }//end get_object() @@ -173,6 +193,9 @@ //============================================================================ + /** + * Retrieves a permission object by name from the database, exception on failure. + */ public function get_permission($name) { try { $name = $this->gfObj->cleanString($name, 'sql', 0); @@ -190,6 +213,9 @@ //============================================================================ + /** + * Same as get_permission_by_id(). + */ public function get_object_by_id($objectId) { return($this->get_permission_by_id($objectId)); }//end get_object_by_id() @@ -198,6 +224,9 @@ //============================================================================ + /** + * Retrieves a permission object from the database based on an ID. + */ public function get_permission_by_id($permId) { try { if(!is_null($permId) && is_numeric($permId)) { @@ -215,5 +244,159 @@ return($retval); }//end get_permission_by_id() //============================================================================ + + + + //============================================================================ + /** + * Check available permissions... + */ + public function check_permission($objectName, $userId) { + $availablePerms = array( + 'r' => false, + 'w' => false, + 'x' => false + ); + + try { + //get the object. + $permission = $this->get_permission($objectName); + + //now figure out what permissions they have. + if($permission['user_id'] == $userId) { + //it is the owner, determine based on the permissions with the 'u_' prefix. + $availablePerms = $this->get_permission_list($permission, 'u'); + } + elseif($this->is_group_member($userId, $permission['group_id'])) { + //group member, use the 'g_' permissions. + $availablePerms = $this->get_permission_list($permission, 'g'); + } + else { + //not owner OR group member, use the 'o_' permissions + $availablePerms = $this->get_permission_list($permission, 'o'); + } + } + catch(Exception $e) { + //consider logging this... maybe based on some internal variable. + } + + return($availablePerms); + }//end check_permission() + //============================================================================ + + + + //============================================================================ + /** + * Creates an array of permission bits based on user/group/other from the given + * permission data (i.e. the return from get_permission()). + */ + protected function get_permission_list(array $permData, $type) { + $retval = array(); + if(in_array($type, array('u', 'g', 'o'))) { + foreach($this->keys as $myKey) { + if(preg_match('/'. $type .'_[rwx]$/',$myKey)) { + //chop the last character off (i.e. 'r' from 'u_r') + $myPermChar = substr($myKey, -1); + #$retval[$myPermChar] = $this->gfObj->interpret_bool($permData[$myKey], array('f', 't')); + $retval[$myPermChar] = $this->evaluate_perm_value($permData[$myKey], $type); + } + } + } + else { + throw new exception(__METHOD__ .":: invalid type (". $type ."), must be u/g/o"); + } + + return($retval); + }//end get_permission_list() + //============================================================================ + + + + //============================================================================ + /** + * Evaluate the value in a permission bit as true (allowed) or false (disallowed). + */ + protected function evaluate_perm_value($val=null) { + + if($val === '-' || $val === false || $val === 'f' || $val === 0 || $val === '0' || !strlen($val)) { + $retval = false; + } + else { + $retval = true; + } + return($retval); + }//end evaluate_perm_value + //============================================================================ + + + + //============================================================================ + /** + * Determines if a permission record exists (based on name). + */ + public function permission_exists($permName) { + try { + $info = $this->get_permission($permName); + $retval = false; + if(is_array($info)) { + $retval = true; + } + } + catch(Exception $e) { + $retval = false; + } + + return($retval); + }//end permission_exists() + //============================================================================ + + + + //============================================================================ + /** + * If user has read permission for the given named permission/object. + */ + public function has_read_permission($userId, $permName) { + $myPerms = $this->check_permission($permName, $userId); + $retval = false; + if($myPerms['r'] === true) { + $retval = true; + } + return($retval); + }//end has_read_permission() + //============================================================================ + + + + //============================================================================ + /** + * If user has write permission for the given named permission/object. + */ + public function has_write_permission($userId, $permName) { + $myPerms = $this->check_permission($permName, $userId); + $retval = false; + if($myPerms['w'] === true) { + $retval = true; + } + return($retval); + }//end has_write_permission() + //============================================================================ + + + + //============================================================================ + /** + * If user has execute permission for the given named permission/object. + */ + public function has_execute_permission($userId, $permName) { + $myPerms = $this->check_permission($permName, $userId); + $retval = false; + if($myPerms['x'] === true) { + $retval = true; + } + return($retval); + }//end has_execute_permission() + //============================================================================ } ?> Deleted: trunk/0.3/docs/example_genericPermission.php =================================================================== --- trunk/0.3/docs/example_genericPermission.php 2010-06-21 17:56:47 UTC (rev 174) +++ trunk/0.3/docs/example_genericPermission.php 2010-06-23 13:45:57 UTC (rev 175) @@ -1,53 +0,0 @@ -<?php - -//instantiate the permission object with a database & the proper UID. -$permObj = new cs_genericUserPermission($page->db, $_SESSION['uid']); - - -//Creating Permissions/Groups -{ - //create a group. - $permObj->create_group("blogs"); - - //define default permissions for the group. - //NOTE::: the "false" entries can be technically excluded, as the default is false. - $perms = array( - 'view' => true, - 'create' => true, - 'edit' => true, - 'set_timestamp' => true, - 'update_timestamp' => false, - 'delete_entry' => false, - 'set_draft' => true, - 'update_to_draft' => false - ); - $permObj->set_group_perms("blogs", $perms); - - //set specific permissions for a user. - //NOTE::: if the group or permission doesn't exist, this will throw an exception. - $permObj->set_user_perm("blogs", "update_timestamp"); -} - - -//Checking Permissions/Groups -{ - //get a list of permissions... - $perms = $permObj->get_user_permissions(); - - //check if the user is part of a group... in this case, the "blogs" group. - $isGroupMember = $permObj->check_group_membership("blogs"); - - //Pull all available permissions for a group... again, the "blogs" group. - $allBlogsPerms = $permObj->get_group_perms("blogs"); - - //check permissions for a specific "group" (or "object")... in this case, "can the user create a blog?" - $hasPermission = $permObj->check_permission("blogs", "create"); - - - //a more advanced check, involving membership in multiple cascading groups (unimplemented)... "can the user administratively view blogs?" - //NOTE::: the code in this method would have to allow an unlimited number of arguments (minimum 2), where the last one is the permission name. - #$permObj->check_cascading_permission("admin", "blogs", "view"); -} - - -?> Modified: trunk/0.3/tests/testOfCSGenericPermissions.php =================================================================== --- trunk/0.3/tests/testOfCSGenericPermissions.php 2010-06-21 17:56:47 UTC (rev 174) +++ trunk/0.3/tests/testOfCSGenericPermissions.php 2010-06-23 13:45:57 UTC (rev 175) @@ -123,6 +123,7 @@ { $newId = $perm->create_user_group($this->validUsers[$myKey]['uid'],1); $this->assertTrue(is_numeric($newId)); + $this->assertTrue($perm->is_group_member($this->validUsers[$myKey]['uid'],1)); $ugList = $perm->get_user_groups($this->validUsers[$myKey]['uid']); $this->assertTrue(is_array($ugList)); @@ -152,6 +153,23 @@ 'o_w' => '-', 'o_x' => 'x' ); + $permByType = array( + 'u' => array( + 'r' => true, + 'w' => true, + 'x' => true + ), + 'g' => array( + 'r' => false, + 'w' => false, + 'x' => false + ), + 'o' => array( + 'r' => false, + 'w' => false, + 'x' => true + ) + ); $permString = 'rwx-----x'; $this->assertEqual(strlen($perm->make_perm_string($myPermArr)),9); @@ -160,16 +178,23 @@ $this->assertEqual(array_keys($perm->parse_perm_string($permString)), array_keys($myPermArr)); $this->assertEqual($perm->make_perm_string($perm->parse_perm_string($permString)), $permString); $this->assertEqual(array_keys($perm->parse_perm_string($perm->make_perm_string($myPermArr))), array_keys($myPermArr)); + + $this->assertEqual($perm->get_perm_list($myPermArr,'u'), $permByType['u']); + $this->assertEqual($perm->get_perm_list($myPermArr,'g'), $permByType['g']); + $this->assertEqual($perm->get_perm_list($myPermArr,'o'), $permByType['o']); } //create some permissions. { $userKeys = array_keys($this->validUsers); $myUser = $this->validUsers[$userKeys[0]]; + $myUid = $myUser['uid']; - $usePermString = 'rwxrw-rw-'; + $usePermString = 'rwxrw-r--'; $usePermName = __METHOD__ .'/test1'; - $permId = $perm->create_permission($usePermName, $myUser['uid'], 1, $usePermString); + $this->assertFalse($perm->permission_exists($usePermName)); + $permId = $perm->create_permission($usePermName, $myUid, 1, $usePermString); + $this->assertTrue($perm->permission_exists($usePermName)); $this->assertTrue(is_numeric($permId)); //the method 'build_permissions_string()' should disregard extra indices in the array & build the string. @@ -177,6 +202,29 @@ $this->assertEqual($perm->make_perm_string($perm->get_object_by_id($permId)), $usePermString); $this->assertEqual($perm->make_perm_string($perm->get_permission($usePermName)), $usePermString); $this->assertEqual($perm->make_perm_string($perm->get_object($usePermName)), $usePermString); + + //check to make sure individual permission requests work as expected. + $this->assertTrue($perm->has_read_permission($myUid, $usePermName)); + $this->assertTrue($perm->has_write_permission($myUid, $usePermName)); + $this->assertTrue($perm->has_execute_permission($myUid, $usePermName)); + + //make sure "anonymous" permissions are correct. + $this->assertTrue($perm->has_read_permission(0,$usePermName)); + $this->assertFalse($perm->has_write_permission(0,$usePermName)); + $this->assertFalse($perm->has_execute_permission(0,$usePermName)); + + //put a second user into the proper user_group, then test group permissions. + $secondUser = $this->validUsers[$userKeys[1]]['uid']; + $this->assertTrue(is_numeric($perm->create_user_group($secondUser, 1))); + $this->assertTrue($perm->has_read_permission($secondUser, $usePermName)); + $this->assertTrue($perm->has_write_permission($secondUser, $usePermName)); + $this->assertFalse($perm->has_execute_permission($secondUser, $usePermName)); + + //test a THIRD user (non-zero uid), make sure they are subject to the same permissions as anonymous (uid=0) + $thirdUser = $this->validUsers[$userKeys[2]]['uid']; + $this->assertEqual($perm->has_read_permission(0,$usePermName), $perm->has_read_permission($thirdUser,$usePermName)); + $this->assertEqual($perm->has_write_permission(0,$usePermName), $perm->has_write_permission($thirdUser,$usePermName)); + $this->assertEqual($perm->has_execute_permission(0,$usePermName), $perm->has_execute_permission($thirdUser,$usePermName)); } }//end test_permissions //-------------------------------------------------------------------------- @@ -199,5 +247,9 @@ public function parse_perm_string($string) { return($this->parse_permission_string($string)); } + + public function get_perm_list(array $permData, $type) { + return($this->get_permission_list($permData, $type)); + } } ?> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2010-06-21 17:56:54
|
Revision: 174 http://cs-webapplibs.svn.sourceforge.net/cs-webapplibs/?rev=174&view=rev Author: crazedsanity Date: 2010-06-21 17:56:47 +0000 (Mon, 21 Jun 2010) Log Message: ----------- Lots of tests, and minor changes so all the tests work. Modified Paths: -------------- trunk/0.3/abstract/cs_genericGroup.abstract.class.php trunk/0.3/abstract/cs_genericUserGroup.abstract.class.php trunk/0.3/cs_genericPermission.class.php trunk/0.3/tests/testOfCSGenericPermissions.php trunk/0.3/tests/testOfCSWebAppLibs.php Modified: trunk/0.3/abstract/cs_genericGroup.abstract.class.php =================================================================== --- trunk/0.3/abstract/cs_genericGroup.abstract.class.php 2010-06-21 15:59:57 UTC (rev 173) +++ trunk/0.3/abstract/cs_genericGroup.abstract.class.php 2010-06-21 17:56:47 UTC (rev 174) @@ -23,7 +23,7 @@ const groupTable = "cswal_group_table"; /** Sequence for groups table. */ - const groupSeq = "cswal_group_table_group_id"; + const groupSeq = "cswal_group_table_group_id_seq"; //============================================================================ public function __construct(cs_phpDB $db) { @@ -42,6 +42,7 @@ else { throw new exception(__METHOD__ .":: invalid string (". $name .")"); } + return($name); }//end clean_group_name() //============================================================================ @@ -52,7 +53,7 @@ try{ $name = $this->clean_group_name($name); $sql = "INSERT INTO ". self::groupTable ." (group_name) VALUES ('". $name ."')"; - $newId = $this->db->run_insert($sql, self::gropuSeq); + $newId = $this->db->run_insert($sql, self::groupSeq); } catch(Exception $e) { throw new exception(__METHOD__ .":: failed to create new record, DETAILS::: ". $e->getMessage()); @@ -82,6 +83,22 @@ //============================================================================ + public function get_all_groups() { + try { + $sql = "SELECT * FROM ". self::groupTable ." ORDER BY group_name"; + $retval = $this->db->run_query($sql); + } + catch(Exception $e) { + throw new exception(__METHOD__ .":: failed to retrieve groups, DETAILS::: ". $e->getMessage()); + } + + return($retval); + }//end get_all_groups() + //============================================================================ + + + + //============================================================================ public function get_group_by_id($groupId) { try { if(!is_null($groupId) && is_numeric($groupId)) { Modified: trunk/0.3/abstract/cs_genericUserGroup.abstract.class.php =================================================================== --- trunk/0.3/abstract/cs_genericUserGroup.abstract.class.php 2010-06-21 15:59:57 UTC (rev 173) +++ trunk/0.3/abstract/cs_genericUserGroup.abstract.class.php 2010-06-21 17:56:47 UTC (rev 174) @@ -53,8 +53,8 @@ if(is_numeric($userId) && $userId >= 0) { try { $sql = "SELECT ug.*, g.group_name FROM ". self::ugTable ." AS ug INNER " - ."JOIN ". parent::groupTable ." as g WHERE user_id=". $userId; - $retval = $this->db->run_query($sql); + ."JOIN ". parent::groupTable ." as g USING (group_id) WHERE user_id=". $userId; + $retval = $this->db->run_query($sql, 'group_id'); } catch(Exception $e) { throw new exception(__METHOD__ .":: failed to locate group (". $groupName ."), DETAILS::: ". $e->getMessage()); Modified: trunk/0.3/cs_genericPermission.class.php =================================================================== --- trunk/0.3/cs_genericPermission.class.php 2010-06-21 15:59:57 UTC (rev 173) +++ trunk/0.3/cs_genericPermission.class.php 2010-06-21 17:56:47 UTC (rev 174) @@ -23,7 +23,7 @@ const objTable = "cswal_object_table"; /** Sequence for permissions table. */ - const objSeq = "cswal_object_table_object_id"; + const objSeq = "cswal_object_table_object_id_seq"; /** List of valid keys... */ protected $keys = array(); @@ -89,13 +89,14 @@ //============================================================================ protected function build_permission_string(array $perms) { $this->_sanityCheck(); - if(is_array($perms) && count($perms) == count($this->keys)) { + if(is_array($perms) && count($perms) >= count($this->keys)) { $retval = ""; foreach($this->keys as $dbColName) { if(isset($perms[$dbColName])) { //get the last character of the column name. - $permChar = substring($dbColName, -1); - if($perms[$dbColName] === false) { + $permChar = substr($dbColName, -1); + if($perms[$dbColName] === false || !strlen($perms[$dbColName]) || $perms[$dbColName] === '-' || $perms[$dbColName] === 'f') { + $permChar = '-'; } $retval .= $permChar; @@ -125,13 +126,27 @@ //============================================================================ public function create_permission($name, $userId, $groupId, $permString) { if(is_string($name) && strlen($name) && is_numeric($userId) && $userId >= 0 && is_numeric($groupId) && $groupId >= 0) { + $cleanStringArr = array( + 'object_name' => 'sql', + 'user_id' => 'numeric', + 'group_id' => 'numeric', + 'u_r' => 'bool', + 'u_w' => 'bool', + 'u_x' => 'bool', + 'g_r' => 'bool', + 'g_w' => 'bool', + 'g_x' => 'bool', + 'o_r' => 'bool', + 'o_w' => 'bool', + 'o_x' => 'bool' + ); try{ $insertArr = $this->parse_permission_string($permString); $insertArr['object_name'] = $this->gfObj->cleanString($name, 'sql', 0); $insertArr['user_id'] = $userId; $insertArr['group_id'] = $groupId; - $insertSql = $this->gfObj->string_from_array($insertArr, 'insert'); + $insertSql = $this->gfObj->string_from_array($insertArr, 'insert', null, $cleanStringArr); $sql = "INSERT INTO ". self::objTable ." ". $insertSql; $newId = $this->db->run_insert($sql, self::objSeq); } @@ -160,8 +175,8 @@ //============================================================================ public function get_permission($name) { try { - $name = $this->clean_permission_name($name); - $sql = "SELECT * FROM ". self::objTable ." WHERE permission_name='". $name ."'"; + $name = $this->gfObj->cleanString($name, 'sql', 0); + $sql = "SELECT * FROM ". self::objTable ." WHERE object_name='". $name ."'"; $retval = $this->db->run_query($sql); } catch(Exception $e) { Modified: trunk/0.3/tests/testOfCSGenericPermissions.php =================================================================== --- trunk/0.3/tests/testOfCSGenericPermissions.php 2010-06-21 15:59:57 UTC (rev 173) +++ trunk/0.3/tests/testOfCSGenericPermissions.php 2010-06-21 17:56:47 UTC (rev 174) @@ -14,19 +14,29 @@ class testOfCSGenericPermissions extends UnitTestCase { //-------------------------------------------------------------------------- - function __construct() { + function setUp() { $this->gfObj = new cs_globalFunctions; $this->gfObj->debugPrintOpt=1; if(!defined('CS_UNITTEST')) { throw new exception(__METHOD__ .": FATAL: constant 'CS_UNITTEST' not set, can't do testing safely"); } $this->get_valid_users(); - }//end __construct() + $perm = new _gpTester($this->create_dbconn()); + $perm->do_schema(); + }//end setUp() //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- + public function tearDown() { + $this->remove_tables(); + } + //-------------------------------------------------------------------------- + + + + //-------------------------------------------------------------------------- private function create_dbconn() { $dbParams = array( 'host' => constant('cs_webapplibs-DB_CONNECT_HOST'), @@ -81,15 +91,96 @@ //-------------------------------------------------------------------------- public function test_userGroups() { $perm = new _gpTester($this->create_dbconn()); - $perm->do_schema(); - //create a group with an invalid group_id. - $perm->create_user_group($this->validUsers[0]['uid'],1); + //make sure there are groups available. + { + $groupList = $perm->get_all_groups(); + $keys = array_keys($groupList); + $myKey = $keys[0]; + + $this->assertTrue(is_array($groupList)); + $this->assertTrue(count($groupList) > 0); + + $this->assertTrue(isset($groupList[$myKey])); + $this->assertTrue(isset($groupList[$myKey]['group_name'])); + $this->assertTrue(isset($groupList[$myKey]['group_id'])); + } + + //create some groups. + { + $newGroupId = $perm->create_group(__METHOD__); + $this->assertTrue(is_numeric($newGroupId)); + + $groupList = $perm->get_all_groups(); + + foreach($groupList as $groupData) { + $this->assertEqual($perm->get_group_by_id($groupData['group_id']), $groupData); + $this->assertEqual($perm->get_group($groupData['group_name']), $groupData); + } + } + + //create & test user_group relationships. + { + $newId = $perm->create_user_group($this->validUsers[$myKey]['uid'],1); + $this->assertTrue(is_numeric($newId)); + + $ugList = $perm->get_user_groups($this->validUsers[$myKey]['uid']); + $this->assertTrue(is_array($ugList)); + $this->assertTrue(count($ugList) > 0); + $this->assertFalse(isset($ugList['group_name'])); + } }//end test_userGroups //-------------------------------------------------------------------------- + //-------------------------------------------------------------------------- + public function test_permissions() { + + $perm = new _gpTester($this->create_dbconn()); + + //Test permission string parsing. + { + $myPermArr = array( + 'u_r' => 'x', + 'u_w' => 'x', + 'u_x' => 'r', + 'g_r' => '-', + 'g_w' => '-', + 'g_x' => '', + 'o_r' => '', + 'o_w' => '-', + 'o_x' => 'x' + ); + $permString = 'rwx-----x'; + + $this->assertEqual(strlen($perm->make_perm_string($myPermArr)),9); + $this->assertEqual(count($perm->parse_perm_string($permString)), 9); + $this->assertEqual($perm->make_perm_string($myPermArr), $permString); + $this->assertEqual(array_keys($perm->parse_perm_string($permString)), array_keys($myPermArr)); + $this->assertEqual($perm->make_perm_string($perm->parse_perm_string($permString)), $permString); + $this->assertEqual(array_keys($perm->parse_perm_string($perm->make_perm_string($myPermArr))), array_keys($myPermArr)); + } + + //create some permissions. + { + $userKeys = array_keys($this->validUsers); + $myUser = $this->validUsers[$userKeys[0]]; + + $usePermString = 'rwxrw-rw-'; + $usePermName = __METHOD__ .'/test1'; + $permId = $perm->create_permission($usePermName, $myUser['uid'], 1, $usePermString); + $this->assertTrue(is_numeric($permId)); + + //the method 'build_permissions_string()' should disregard extra indices in the array & build the string. + $this->assertEqual($perm->make_perm_string($perm->get_permission_by_id($permId)), $usePermString); + $this->assertEqual($perm->make_perm_string($perm->get_object_by_id($permId)), $usePermString); + $this->assertEqual($perm->make_perm_string($perm->get_permission($usePermName)), $usePermString); + $this->assertEqual($perm->make_perm_string($perm->get_object($usePermName)), $usePermString); + } + }//end test_permissions + //-------------------------------------------------------------------------- + } class _gpTester extends cs_genericPermission { @@ -100,5 +191,13 @@ public function do_schema() { $this->build_schema(); } + + public function make_perm_string(array $perms) { + return($this->build_permission_string($perms)); + } + + public function parse_perm_string($string) { + return($this->parse_permission_string($string)); + } } ?> Modified: trunk/0.3/tests/testOfCSWebAppLibs.php =================================================================== --- trunk/0.3/tests/testOfCSWebAppLibs.php 2010-06-21 15:59:57 UTC (rev 173) +++ trunk/0.3/tests/testOfCSWebAppLibs.php 2010-06-21 17:56:47 UTC (rev 174) @@ -291,7 +291,7 @@ // now REALLY test paths. { - #$gdl = new gdlTester($this->create_dbconn()); + $gdl = new gdlTester($this->create_dbconn()); $myBasePath = '/character/sheet/Xander Cage'; $x->set_base_path($myBasePath); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2010-06-21 16:00:04
|
Revision: 173 http://cs-webapplibs.svn.sourceforge.net/cs-webapplibs/?rev=173&view=rev Author: crazedsanity Date: 2010-06-21 15:59:57 +0000 (Mon, 21 Jun 2010) Log Message: ----------- Fix cs_phpDB::run_sql_file() so it works, remove debug_print() from tests... Modified Paths: -------------- trunk/0.3/cs_phpDB.class.php trunk/0.3/tests/testOfCSGenericPermissions.php Modified: trunk/0.3/cs_phpDB.class.php =================================================================== --- trunk/0.3/cs_phpDB.class.php 2010-06-21 15:54:15 UTC (rev 172) +++ trunk/0.3/cs_phpDB.class.php 2010-06-21 15:59:57 UTC (rev 173) @@ -193,14 +193,7 @@ * Execute the entire contents of the given file (with absolute path) as SQL. */ public function run_sql_file($filename) { - if(!is_object($this->fsObj)) { - if(class_exists('cs_fileSystem')) { - $fsObj = new cs_fileSystem(dirname($filename)); - } - else { - throw new exception(__METHOD__ .": required library (cs_fileSystem) not found"); - } - } + $fsObj = new cs_fileSystem(dirname($filename)); $this->lastSQLFile = $filename; Modified: trunk/0.3/tests/testOfCSGenericPermissions.php =================================================================== --- trunk/0.3/tests/testOfCSGenericPermissions.php 2010-06-21 15:54:15 UTC (rev 172) +++ trunk/0.3/tests/testOfCSGenericPermissions.php 2010-06-21 15:59:57 UTC (rev 173) @@ -73,7 +73,6 @@ $sql = "SELECT uid,username FROM cs_authentication_table ORDER BY uid"; $db = $this->create_dbconn(); $this->validUsers = $db->run_query($sql); - $this->gfObj->debug_print($this->validUsers); }//end get_valid_users() //-------------------------------------------------------------------------- This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |