/php-voms-admin-0.6/modules/sql_functions.php
PHP | 2302 lines | 1735 code | 183 blank | 384 comment | 526 complexity | 39be226d97c265e53cfe0b34a5e69179 MD5 | raw file
Possible License(s): Apache-2.0
- <?php
- // Copyright 2010 Andrii Salnikov
- //
- // Licensed under the Apache License, Version 2.0 (the "License");
- // you may not use this file except in compliance with the License.
- // You may obtain a copy of the License at
- //
- // http://www.apache.org/licenses/LICENSE-2.0
- //
- // Unless required by applicable law or agreed to in writing, software
- // distributed under the License is distributed on an "AS IS" BASIS,
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- // See the License for the specific language governing permissions and
- // limitations under the License.
- //
- /////////////////////////////////////////////////////////////////////
- // Transaction handling wrappers
- /////////////////////////////////////////////////////////////////////
- /* Invoke specified function and log transaction to database ( admin_id, function_name, arguments )
- return invoked function return code */
- function _invoke_transactional_sql ( ) {
- global $db_connection, $USER_DN;
- global $enable_transactions_log;
- if ( ! isset($enable_transactions_log) ) $enable_transactions_log = false;
- // check author and function name specified
- if ( func_num_args() < 3 ) return 0;
- if ( $USER_DN === 0 ) return 0;
- // get function parameters
- $argv = func_get_args();
- $updator = array_shift($argv);
- $f_name = array_shift($argv);
- // begin transaction in SQL
- mysql_query("START TRANSACTION",$db_connection);
- // invoke function
- unset($GLOBALS['pva_id2uuid_arr']);
- if ( $argv ) $f_result = call_user_func_array($f_name, $argv);
- else $f_result = call_user_func($f_name);
- if ( $enable_transactions_log ) {
- if ( $f_result === 1 ) {
- // add uuids array to the end of the function args before saving to transaction table
- if ( isset($GLOBALS['pva_id2uuid_arr']) ) $argv[] = $GLOBALS['pva_id2uuid_arr'];
- // write to transactions table
- $sql = sprintf("INSERT INTO pva_transactions(adminid, uuid, fname, args, source_id)
- VALUES ('%s',UUID(),'%s','%s',%d)",
- $USER_DN, $f_name,
- base64_encode(serialize($argv)),
- $updator);
- if ( ! mysql_query($sql, $db_connection) ) {
- $f_result = 0;
- printf("<p class=\"error\">ERROR: Failed to write transaction log. Performing transaction rollback. </p>");
- }
- }
- }
- if ( $f_result === 1 ) mysql_query("COMMIT",$db_connection);
- else mysql_query("ROLLBACK",$db_connection);
- return $f_result;
- }
- // invoke function inside transaction (operation source is authorized updator)
- function _invoke_transactional_sql_update ( $updator, $admid, $uuid, $f_name, $base64args, $status, $nt_stamp ) {
- global $db_connection;
- // begin transaction in SQL
- mysql_query("START TRANSACTION",$db_connection);
- $f_result = 1;
- $invoke_error = false;
- // write to transactions table (and check if transaction already exists)
- $sql = sprintf("INSERT INTO pva_transactions(adminid, uuid, fname, args, source_id)
- VALUES ('%s','%s','%s','%s',%d)",
- $admid,
- $uuid,
- $f_name,
- $base64args,
- $updator);
- if ( ! mysql_query($sql, $db_connection) ) {
- $op_errno = mysql_errno($db_connection);
- if ( $op_errno !== 1062 ) {
- //log_pva_error
- $invoke_error = array ( 1, 4, array($op_errno));
- $f_result = 0;
- } else $f_result = 2; // do not ROLLBACK transaction time update on duplicate
- }
-
- // invoke function on success
- if ( $f_result === 1 ) {
- $fargv = unserialize(base64_decode($base64args));
- if ( $fargv ) $f_result = call_user_func_array($f_name, $fargv);
- else $f_result = call_user_func($f_name);
- }
- // update last transaction time in updator
- if ( $f_result ) {
- $sql = sprintf("UPDATE pva_authorized_updators
- SET status=2, t_stamp=FROM_UNIXTIME('%s'), sync_time = CURRENT_TIMESTAMP
- WHERE pva_authorized_updators.au_id = %d",
- $nt_stamp, $updator );
- if ( ! mysql_query($sql, $db_connection) ) {
- $f_result = 0;
- }
- } else {
- // log_pva_error
- $invoke_error = array (1, 3, array ($f_name, var_export($fargv,true)));
- }
- if ( $f_result ) mysql_query("COMMIT",$db_connection);
- else mysql_query("ROLLBACK",$db_connection);
- if ( $invoke_error ) call_user_func_array('storeLogRecord',$invoke_error);
- return $f_result;
- }
- // get transactions filtered by limits
- function get_transaction_log ( $limit = 0 ) {
- global $db_connection;
- global $items_per_page;
- $sql = "SELECT pva_transactions.t_stamp, pva_transactions.adminid, pva_transactions.fname,
- pva_transactions.args, pva_authorized_updators.dn
- FROM pva_transactions INNER JOIN pva_authorized_updators
- ON pva_transactions.source_id = pva_authorized_updators.au_id
- ORDER BY pva_transactions.t_stamp DESC";
- $sql .= " LIMIT ". $limit .", ". $items_per_page;
- $result = array();
- $query = mysql_query($sql, $db_connection);
- if ( $query ) if ( mysql_num_rows($query) ) while ( $row = mysql_fetch_assoc($query)) {
- $result[] = array (
- 'time' => $row['t_stamp'],
- 'admdn' => $row['adminid'],
- 'fname' => $row['fname'],
- 'fargs' => unserialize(base64_decode($row['args'])),
- 'upddn' => $row['dn']
- );
- }
- return $result;
- }
- // update last sync time with updator
- function update_transactions_sync_time ($updator) {
- global $db_connection;
- $sql = sprintf("UPDATE pva_authorized_updators SET sync_time = CURRENT_TIMESTAMP, status=2
- WHERE pva_authorized_updators.au_id = %d", $updator );
- return mysql_query($sql, $db_connection);
- }
- // create autorized updators and transactions table
- function createTransactionsTables () {
- global $db_connection;
- $sql = "CREATE TABLE IF NOT EXISTS `pva_authorized_updators` (
- `au_id` smallint(6) NOT NULL AUTO_INCREMENT,
- `status` tinyint(4) NOT NULL,
- `dn` varchar(255) NOT NULL,
- `cahash` varchar(10) NOT NULL,
- `ip` varchar(16) NOT NULL,
- `endpoint` varchar(128) NOT NULL,
- `auth_key` varchar(64) NOT NULL,
- `foreign_key` varchar(64) NOT NULL,
- `t_stamp` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
- `sync_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
- PRIMARY KEY (`au_id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2;";
- if ( ! mysql_query($sql, $db_connection) ) return 0;
- $sql = "INSERT INTO `pva_authorized_updators` (`au_id`, `status`, `dn`, `cahash`, `ip`, `endpoint`, `auth_key`, `foreign_key`, `t_stamp`, `sync_time`) VALUES (1, 9, '/O=VOMS/O=System/CN=Local PHP VOMS-Admin', '', '', '', '', '', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP);";
- if ( ! mysql_query($sql, $db_connection) ) {
- // if already exists - does not report error
- if ( mysql_errno($db_connection) !== 1062 ) return 0;
- }
- $sql = "CREATE TABLE IF NOT EXISTS `pva_transactions` (
- `t_stamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
- `uuid` char(36) NOT NULL,
- `adminid` varchar(255) NOT NULL,
- `fname` varchar(32) NOT NULL,
- `args` text NOT NULL,
- `source_id` int(11) NOT NULL,
- KEY `t_stamp` (`t_stamp`),
- UNIQUE KEY `uuid` (`uuid`)
- ) ENGINE=InnoDB DEFAULT CHARSET=latin1;";
- if ( ! mysql_query($sql, $db_connection) ) return 0;
- return saveSettingsToDB('transactions_tables_created',1);
- }
- // create table to map autoincremented id to uuid and vice versa
- function create_id2uuid_table () {
- global $db_connection;
- $sql = "CREATE TABLE IF NOT EXISTS `pva_id2uuid_map` (
- `id` int(11) NOT NULL,
- `table` varchar(36) NOT NULL,
- `uuid` varchar(36) NOT NULL,
- PRIMARY KEY (`uuid`),
- KEY `id` (`id`),
- KEY `table` (`table`)
- ) ENGINE=InnoDB DEFAULT CHARSET=latin1;";
- if ( ! mysql_query($sql, $db_connection) ) return 0;
- return 1;
- }
- // assing uuid map for already existent database ids
- function create_id2uuid_data () {
- global $db_connection;
- $autoincrement_keys = array (
- "acl2" => "acl_id",
- "admins" => "adminid",
- "attributes" => "a_id",
- "ca" => "cid",
- "capabilities" => "cid",
- "groups" => "gid",
- "m" => "mapping_id",
- "memb_req" => "id",
- "roles" => "rid",
- "usr" => "userid"
- );
- foreach ( $autoincrement_keys as $table_name => $key_name ) {
- $sql = sprintf("SELECT `%s` FROM `%s`", $key_name, $table_name);
- $query = mysql_query($sql, $db_connection);
- if ( ! $query ) return 0;
- if ( ! mysql_num_rows($query) ) continue;
- while ( $row = mysql_fetch_row($query)) UUID4id($row[0],$table_name);
- }
- return 1;
- }
- // return UUID value for specified $id in $table
- // if map does not exists - function will create it
- // if optional $uuid parameter specified - it value will be used on new map creation
- function UUID4id($id, $table, $uuid = 0) {
- global $db_connection, $id2uuid_map_created;
- // if id2uuid mapping is not activated - do not execute function and return 0;
- if ( ! isset($id2uuid_map_created) ) return 0;
- // check if already exists
- $sql = sprintf("SELECT `uuid` FROM pva_id2uuid_map WHERE `id` = %d AND `table` = '%s'", $id, $table);
- $query = mysql_query($sql, $db_connection);
- if ( ! $query ) return 0;
- if ( mysql_num_rows($query) ) {
- $row = mysql_fetch_row($query);
- return $row[0];
- } else { // record does not exists
- // set uuid
- if ( $uuid ) $sql = sprintf("SET @UD='%s'",$uuid);
- else $sql = "SET @UD=UUID()";
- $query = mysql_query($sql, $db_connection);
- if ( ! $query ) return 0;
- // insert uuid to id map
- $sql = sprintf("INSERT INTO pva_id2uuid_map(`id`,`table`,`uuid`)
- VALUES (%d, '%s', @UD)", $id, $table);
- $query = mysql_query($sql, $db_connection);
- if ( ! $query ) return 0;
- // return uuid value
- $sql = "SELECT @UD";
- $query = mysql_query($sql, $db_connection);
- if ( ! $query ) return 0;
- if ( ! mysql_num_rows($query) ) return 0;
- $row = mysql_fetch_row($query);
- return $row[0];
- }
- }
- // return id for specified uuid
- function id4UUID($uuid) {
- global $db_connection;
- if ( ! $uuid ) return 0;
- $sql = sprintf("SELECT id FROM pva_id2uuid_map WHERE `uuid` = '%s'", $uuid );
- $query = mysql_query($sql, $db_connection);
- if ( ! $query ) return 0;
- if ( ! mysql_num_rows($query) ) return 0;
- $row = mysql_fetch_row($query);
- return $row[0];
- }
- // set id by uuid (if specified) or set uuid for id
- function id2uuid_convert ($table, &$id, &$uuids) {
- global $id2uuid_map_created;
- // if id2uuid mapping is not activated - do not execute function and return 1;
- if ( ! isset($id2uuid_map_created) ) return 1;
- if ( isset($uuids[$table]) ) $id = id4UUID($uuids[$table]);
- else $uuids[$table] = UUID4id($id, $table);
- if ( ! $id ) return 0;
- if ( ! $uuids[$table] ) return 0;
- return 1;
- }
- /////////////////////////////////////////////////////////////////////
- // VO settings in database
- /////////////////////////////////////////////////////////////////////
- function getSettingFromDB () {
- global $db_connection;
- $sql = "SELECT * FROM pva_variables";
- $query = mysql_query($sql, $db_connection);
- if ( ! $query ) return 0;
- while ( $row = mysql_fetch_row($query)) {
- $var = $row[0];
- $GLOBALS[$var] = $row[1];
- }
- }
- function getVariableFromDB ($var) {
- global $db_connection;
- $sql = sprintf("SELECT pva_variables.value FROM pva_variables WHERE pva_variables.var = '%s'", $var);
- $query = mysql_query($sql, $db_connection);
- if ( ! $query ) return NULL;
- $row = mysql_fetch_row($query);
- return $row[0];
- }
- function saveSettingsToDB ($var, $value) {
- global $db_connection;
- if ( getVariableFromDB($var) === NULL ) {
- $sql = sprintf("INSERT INTO pva_variables(var,value) VALUES ('%s', '%s')", $var, $value);
- } else {
- $sql = sprintf("UPDATE pva_variables SET pva_variables.value = '%s' WHERE pva_variables.var = '%s'", $value, $var);
- }
- if ( ! mysql_query($sql, $db_connection) ) return 0;
- return 1;
- }
- function createSettingTable () {
- global $db_connection;
- $sql = "CREATE TABLE pva_variables (var VARCHAR(128) NOT NULL, value VARCHAR(255) NOT NULL, UNIQUE KEY var (var)) ENGINE = InnoDB";
- return mysql_query($sql,$db_connection);
- }
- /////////////////////////////////////////////////////////////////////
- // SQL for SOAP requests -- VOMSCompatibility.php
- /////////////////////////////////////////////////////////////////////
- /* Convert request container to array (group, capability, role)
- return NULL instead text value of group, capability or role if not present */
- function getGroupCapabilityRole ( $container ) {
- global $regex_name_set, $regex_name_sset;
- $matches = array ();
- if ( preg_match("/^((\/".$regex_name_set.")+)(\/Role=".$regex_name_set.")?(\/Capability=".$regex_name_sset.")?$/", $container, $matches ) ) {
- // Parse container
- $group = $matches[1];
- unset($matches[0]);
- unset($matches[1]);
- unset($matches[2]);
- $matchrole = array (); $matchcap = array ();
- foreach( $matches as $mv ) {
- if ( preg_match("/^\/Role=(".$regex_name_set.")$/", $mv, $matchrole ) ) {
- $role = $matchrole[1];
- };
- if ( preg_match("/^\/Capability=(".$regex_name_sset.")$/", $mv, $matchcap) ) {
- $capability = $matchcap[1];
- };
- }
- }
- $group = isset($group) ? $group : NULL;
- $capability = isset($capability) ? $capability : NULL;
- $role = isset($role) ? $role : NULL;
-
- return array($group, $capability, $role);
- }
- /* get VO members DN list
- return (array) array of DN */
- function getVOMembers () {
- global $db_connection;
- $sql = "SELECT usr.dn FROM usr";
- $query = mysql_query($sql, $db_connection);
- $result = array();
- while ( $row = mysql_fetch_row($query)) {
- $result[] = $row[0];
- }
- return $result;
- }
- /* get number of VO member corresponting specified criterias:
- name patern, group ID, role ID
- return (int) members count */
- function getVOMembersCount ( $like = null, $gid = 0, $rid = 0) {
- global $db_connection;
- if ( ( $gid !== 0 ) && ( is_numeric($gid)) ) {
- if ( ( $rid !== 0 ) && ( is_numeric($rid)) )
- $sql_count = "SELECT COUNT(usr.cn) AS cncount FROM usr, m
- WHERE m.userid = usr.userid AND m.rid = ".$rid." AND m.cid IS NULL AND m.gid = " . $gid;
- else
- $sql_count = "SELECT COUNT(usr.cn) AS cncount FROM usr, m
- WHERE m.userid = usr.userid AND m.rid IS NULL AND m.cid IS NULL AND m.gid = " . $gid;
- } else $sql_count = "SELECT COUNT(usr.cn) AS cncount FROM usr";
- if ( $like != null ) $sql_count .= " WHERE usr.cn LIKE '%".mysql_real_escape_string($like)."%'";
- $result = mysql_query($sql_count,$db_connection);
- if ( ! $result ) return 0;
- $count_arr = mysql_fetch_array($result);
- return $count_arr["cncount"];
- }
- /* get VO members DN list coresponding specified criterias:
- group name, role name, capability name
- return (array) array of DN */
- function getVOContainerMembers( $group, $role, $capability ) {
- global $db_connection;
- $sql = "SELECT usr.dn FROM m, usr, groups";
- if ( $role !== NULL ) $sql .= ", roles";
- if ( $capability !== NULL ) $sql .= ", capabilities";
- $sql .= " WHERE m.userid = usr.userid AND m.gid = groups.gid AND groups.dn = '" . mysql_real_escape_string($group) ."' ";
- if ( $role !== NULL ) $sql .= "AND m.rid = roles.rid AND roles.role = '" . mysql_real_escape_string($role) . "' ";
- if ( $capability !== NULL ) $sql .= "AND m.cid = capabilities.cid AND capabilities.capability = '" . mysql_real_escape_string($capability) . "' ";
-
- $query = mysql_query($sql, $db_connection);
- $result = array();
- while ( $row = mysql_fetch_row($query)) {
- $result[] = $row[0];
- }
- return $result;
- }
- /* return (int) VOMS version from database */
- function getVersion() {
- global $db_connection;
- $sql = "SELECT version.version FROM version";
- $query = mysql_query($sql, $db_connection);
- $res = mysql_fetch_row($query);
- $result = isset($res[0]) ? $res[0] : 0;
- return $result;
- }
- ////////////////////////////////////////////////////////////////
- // Non-SQL operations with access rights
- // (required before functions inport for SQL operation with ACL
- ////////////////////////////////////////////////////////////////
- /* Decode permissions intenger to hash
- return (hash) of permissions flags */
- function decodeACLPermissions ( $permissions ) {
- $pstring = sprintf("%021b", $permissions);
- $parr["container"]["r"] = $pstring[20];
- $parr["container"]["w"] = $pstring[19];
- $parr["membership"]["r"] = $pstring[18];
- $parr["membership"]["w"] = $pstring[17];
- $parr["acl"]["r"] = $pstring[16];
- $parr["acl"]["w"] = $pstring[15];
- $parr["acl"]["d"] = $pstring[14];
- $parr["requests"]["r"] = $pstring[13];
- $parr["requests"]["w"] = $pstring[12];
- $parr["attributes"]["r"] = $pstring[11];
- $parr["attributes"]["w"] = $pstring[10];
- $parr["preferences"]["r"] = $pstring[9];
- $parr["preferences"]["w"] = $pstring[8];
- return $parr;
- }
- /* Encode permissions hash to database integer
- return (int) permissions db value */
- function constructACLPermissions( $perm_arr ) {
- $perm = 0;
- if ( isset( $perm_arr["containerr"] ) ) $perm += 1;
- if ( isset( $perm_arr["containerw"] ) ) $perm += 2;
- if ( isset( $perm_arr["membershipr"] ) ) $perm += 4;
- if ( isset( $perm_arr["membershipw"] ) ) $perm += 8;
- if ( isset( $perm_arr["aclr"] ) ) $perm += 16;
- if ( isset( $perm_arr["aclw"] ) ) $perm += 32;
- if ( isset( $perm_arr["acld"] ) ) $perm += 64;
- if ( isset( $perm_arr["requestsr"] ) ) $perm += 128;
- if ( isset( $perm_arr["requestsw"] ) ) $perm += 256;
- if ( isset( $perm_arr["attributesr"] ) ) $perm += 512;
- if ( isset( $perm_arr["attributesw"] ) ) $perm += 1024;
- if ( isset( $perm_arr["preferencesr"] ) ) $perm += 2048;
- if ( isset( $perm_arr["preferencesw"] ) ) $perm += 4096;
- return $perm;
- }
- //////////////////////////////////////////////////////////////////////////
- // SQL operations for PVA web frontend
- //////////////////////////////////////////////////////////////////////////
- /* get $items_per_page number of VO members coresponding specified parameters:
- number of first shown user, user name patern, group ID, role ID
- return (array of hash) array of userinfo (cn, ca, database id, dn) */
- function getVOMembersCA ($limit = 0, $like = null, $gid = 0, $rid = 0 ) {
- global $db_connection;
- global $items_per_page;
- if ( ( $gid !== 0 ) && ( is_numeric($gid)) ) {
- if ( ( $rid !== 0 ) && ( is_numeric($rid)) )
- $sql = "SELECT usr.cn, ca.ca, usr.userid, usr.dn FROM usr, ca, m WHERE usr.ca = ca.cid
- AND m.userid = usr.userid AND m.rid = ". $rid ." AND m.cid IS NULL AND m.gid = " . $gid;
- else
- $sql = "SELECT usr.cn, ca.ca, usr.userid, usr.dn FROM usr, ca, m WHERE usr.ca = ca.cid
- AND m.userid = usr.userid AND m.rid IS NULL AND m.cid IS NULL AND m.gid = " . $gid;
- } else $sql = "SELECT usr.cn, ca.ca, usr.userid, usr.dn FROM usr, ca WHERE usr.ca = ca.cid";
- if ( $like != null ) $sql .= " AND usr.cn LIKE '%". mysql_real_escape_string($like) . "%'";
- $sql .= " LIMIT ". $limit .", ". $items_per_page;
- $query = mysql_query($sql, $db_connection);
- $result = array();
- if ( ! $query ) return 0;
- while ( $row = mysql_fetch_row($query)) {
- $cacn = CNfromDN ( $row[1] );
- $result[] = array ( "cn" => $row[0], "ca" => $cacn, "id" => $row[2], "dn" => $row[3] );
- }
- return $result;
- }
- /* Check if the user have specified attributes in VO:
- database user id, group ID, role ID, capability ID
- return (bool) check result */
- function checkMembership ( $userid, $gid, $role = NULL, $cid = NULL ) {
- global $db_connection;
- $sql = sprintf("SELECT m.userid FROM m WHERE m.userid = %d AND m.gid = %d AND m.rid %s AND m.cid %s", $userid, $gid, (( $role ) ? "= ".$role : "IS NULL"), (( $cid ) ? "= ".$cid : "IS NULL") );
- $query = mysql_query($sql, $db_connection);
- if ( $query == null ) return 0;
- return mysql_num_rows($query);
- }
- /* get access permissions for specified user:
- user DN, user CA, membership flag, group ID
- return (int) access permissions */
- function getProperUserACL ( $dn, $ca, $member = 0, $gid = 1 ) {
- global $db_connection, $lastresort_permissions;
- $groupn = getGroupById ( $gid );
- $caid = getCAId ( $ca );
-
- // First directly check dn
- $sql = sprintf("SELECT admins.adminid FROM admins WHERE admins.dn = '%s' AND admins.ca = %d ", mysql_real_escape_string($dn), $caid );
- $query = mysql_query($sql, $db_connection);
- if ( ! $query ) return 0;
-
- if ( mysql_num_rows($query) ) {
- $row = mysql_fetch_row($query);
- $perm = getAdminPermissions($gid, $row[0]);
- if ( $perm ) return $perm;
- }
- if ( $member ) {
- // Check Role
- $roleca = getCAId ( "/O=VOMS/O=System/CN=VOMS Role" );
- $sql = sprintf("SELECT admins.dn, admins.adminid
- FROM admins
- WHERE admins.ca = %d
- ORDER BY admins.dn ASC", $roleca );
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) )
- while ( $row = mysql_fetch_row($query) ) {
- list($group, $capability, $role) = getGroupCapabilityRole( $row[0] );
- //print_r(getGroupCapabilityRole($row[0]));
- if ( $group != $groupn ) continue;
- if ( checkMembership($member, $gid, getRoleId($role), $capability)) {
- $perm = getAdminPermissions($gid, $row[1]);
- if ( $perm ) return $perm;
- }
- }
- // Check group
- $groupca = getCAId ( "/O=VOMS/O=System/CN=VOMS Group" );
- $sql = sprintf("SELECT admins.dn, admins.adminid
- FROM admins
- WHERE admins.ca = %d
- ORDER BY admins.dn ASC", $groupca );
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) )
- while ( $row = mysql_fetch_row($query) ) {
- list($group, $capability, $role) = getGroupCapabilityRole( $row[0] );
- if ( $group != $groupn ) continue;
- if ( checkMembership($member, $gid ) ) {
- $perm = getAdminPermissions($gid, $row[1]);
- if ( $perm ) return $perm;
- }
- }
- }
- // Check any authenticated
- if ( ( $dn ) && ( $caid ) ) {
- $sql = "SELECT admins.adminid FROM admins WHERE admins.dn = '/O=VOMS/O=System/CN=Any Authenticated User'";
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) ) {
- $row = mysql_fetch_row($query);
- $perm = getAdminPermissions($gid, $row[0]);
- if ( $perm ) return $perm;
- }
- }
- // If nothing of above -- any user
- $sql = "SELECT admins.adminid FROM admins WHERE admins.dn = '/O=VOMS/O=System/CN=Absolutely Anyone'";
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) ) {
- $row = mysql_fetch_row($query);
- $perm = getAdminPermissions($gid, $row[0]);
- if ( $perm ) return $perm;
- }
- // Hope this never happened but no permissions if nothing
- if ( $gid == 1 ) return $lastresort_permissions;
- else return 0;
- }
- /* check if specified user is a member of VO:
- user DN, user CA
- return (bool) check result */
- function checkMember ( $dn, $ca = 0 ) {
- global $db_connection;
- $caid = getCAId ( $ca );
- // Check membership
- if ( $ca === 0 ) $sql = sprintf("SELECT usr.userid FROM usr WHERE usr.dn = '%s'", mysql_real_escape_string($dn));
- else $sql = sprintf("SELECT usr.userid FROM usr WHERE usr.dn = '%s' AND usr.ca = %d", mysql_real_escape_string($dn), $caid );
- $query = mysql_query($sql, $db_connection);
- if ( ! $query ) return 0;
- if ( mysql_num_rows($query) ) {
- $row = mysql_fetch_row($query);
- return $row[0];
- } else return 0;
- }
- /* get list of supported CA
- return (array) list of [ca database id] = [ca name] */
- function getCAList () {
- global $db_connection;
- $sql = "SELECT ca.ca, ca.cid FROM ca ";
- $query = mysql_query($sql, $db_connection);
- $result = array();
- while ( $row = mysql_fetch_row($query)) {
- $result[$row[1]] = $row[0];
- }
- return $result;
- }
- /* function checks for CA .0 files on disk and insert CA record to database on success
- return (int) CA database ID */
- function addCA ( $cadn, $uuids = array() ) {
- global $db_connection, $ca_certificates_path;
- if ( ! isset($uuids['ca']) ) {
- $checkcert_exec = sprintf("for i in `ls -1 %s/*.0`; do openssl x509 -in \$i -noout -subject | sed 's/subject= //' ; done | grep %s", $ca_certificates_path, escapeshellarg($cadn) );
- // if not exists in trusted return 0
- if ( shell_exec($checkcert_exec) == "" ) return -1;
- }
- // add to database
- $sql = "INSERT INTO ca(ca) VALUES ('". mysql_real_escape_string($cadn) ."')";
- if ( ! mysql_query($sql, $db_connection) ) return 0;
- $ca_ins_id = mysql_insert_id();
- $uuids['ca'] = UUID4id($ca_ins_id, 'ca', isset($uuids['ca'])?$uuids['ca']:0);
- $GLOBALS['pva_id2uuid_arr'] = $uuids;
- return $ca_ins_id;
- }
- /* get CA database ID for CA DN:
- CA DN
- return (int) CA database ID */
- function getCAId ( $cadn ) {
- global $db_connection;
- if ( ! $cadn ) return 0;
- // Get CA ID by DN
- $sql = "SELECT ca.cid FROM ca WHERE ca.ca = '".mysql_real_escape_string($cadn)."'";
- $query = mysql_query($sql, $db_connection);
- if ( ! $query ) return 0;
- if ( mysql_num_rows($query) !== 0 ) {
- $ca_arr = mysql_fetch_row($query);
- return $ca_arr[0];
- } else return 0;
- }
- /* get CA name for database ID:
- CA database ID
- return (string) CA DN */
- function getCAName ( $caid ) {
- global $db_connection;
- if ( ! is_numeric($caid) ) return 0;
- $sql = sprintf("SELECT ca.ca FROM ca WHERE ca.cid = %d", $caid);
- $query = mysql_query($sql, $db_connection);
- if ( ! $query ) return 0;
- if ( mysql_num_rows($query) !== 0 ) {
- $ca_arr = mysql_fetch_row($query);
- return $ca_arr[0];
- } else return 0;
- }
- /* create new VO member with:
- user DN, CA DN, user CN, user e-mail, VO name
- and add membership to root group /voname
- return (bool) operation status */
- function createUser ( $dn, $cadn, $cn, $email, $vo, $uuids = array() ) {
- global $db_connection;
- // id2uuid
- if ( ! isset($uuids['usr']) ) $uuids['usr'] = 0;
- if ( ! isset($uuids['m']) ) $uuids['m'] = 0;
- $ca = getCAId( $cadn );
- if ( ! $ca ) {
- $ca = addCA($cadn, $uuids);
- $uuids = $GLOBALS['pva_id2uuid_arr'];
- }
- if ( $ca <= 0 ) return $ca;
- if ( ! checkMember( $dn ) ) {
- $sql = sprintf("INSERT INTO usr(dn,ca,cn,mail) VALUES ('%s',%d,'%s','%s')",
- mysql_real_escape_string($dn), $ca, mysql_real_escape_string($cn), mysql_real_escape_string($email));
- if ( ! mysql_query($sql, $db_connection) ) return 0;
- $usrid = mysql_insert_id();
- $uuids['usr'] = UUID4id($usrid,'usr',$uuids['usr']);
- $sql = sprintf("INSERT INTO m(userid, gid) SELECT %d, groups.gid FROM groups WHERE groups.dn = '/%s'",
- $usrid, mysql_real_escape_string($vo));
- if ( ! mysql_query($sql, $db_connection) ) return 0;
- $mid = mysql_insert_id();
- if ( $mid ) $uuids['m'] = UUID4id($mid, 'm', $uuids['m']);
- $GLOBALS['pva_id2uuid_arr'] = $uuids;
- return 1;
- } else return 0;
- }
- /* create new role and handle its ACL permissions
- role name, VO name
- return (bool) operation status */
- function createRole ( $crrole, $vo, $uuids = array() ) {
- global $db_connection;
- // id2uuid
- if ( empty($uuids) ) {
- $uuids['roles'] = 0;
- $empty_uuids = 1;
- } else $uuids_empty = 0;
- // Check if not exists
- $sql = sprintf("SELECT roles.rid FROM roles WHERE roles.role = '%s'", mysql_real_escape_string($crrole) );
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) !== 0 ) return -1;
- // Get all ACLs to clone
- $sql = "SELECT acl2.acl_id, acl2.group_id FROM acl2 WHERE acl2.defaultACL = 0 AND acl2.role_id IS NULL";
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) == 0 ) return 0;
- while ( $row = mysql_fetch_row($query) ) {
- $gacls[$row[1]] = $row[0];
- if ( isset($empty_uuids) ) $uuids["acltc".$row[0]] = 0;
- }
- // Add record to roles table
- $sql = sprintf("INSERT INTO roles(role) VALUES ('%s');", mysql_real_escape_string($crrole));
- if ( ! mysql_query($sql, $db_connection) ) return 0;
- $roleid = mysql_insert_id();
- $uuids['roles'] = UUID4id($roleid, 'roles', $uuids['roles']);
- foreach ( $gacls as $groupid => $acltoclone ) {
- $sql = sprintf("INSERT INTO acl2(group_id, defaultACL, role_id) VALUES ( %d, 0, %d);", $groupid, $roleid);
- if ( ! mysql_query($sql, $db_connection) ) return 0;
- $aclid = mysql_insert_id();
- $uuids["acltc".$acltoclone] = UUID4id($aclid, 'acl2', $uuids["acltc".$acltoclone]);
- $sql2 = sprintf("SELECT acl2_permissions.permissions, acl2_permissions.admin_id
- FROM acl2_permissions WHERE acl2_permissions.acl_id = %d", $acltoclone);
- $query2 = mysql_query($sql2, $db_connection);
- if ( ! $query2 ) return 0;
- if ( mysql_num_rows($query2) == 0 ) return 0;
- while ( $row2 = mysql_fetch_row($query2) ) {
- $sql = sprintf("INSERT INTO acl2_permissions(acl_id, permissions, admin_id)
- VALUES (%d, %d, %d);", $aclid, $row2[0], $row2[1]);
- if ( ! mysql_query($sql, $db_connection) ) return 0;
- }
- }
- $GLOBALS['pva_id2uuid_arr'] = $uuids;
- return 1;
- }
- /* create new group and handle it ACL permissions (including "default" permissions)
- group name, parent group name, vo name
- return (bool) operation status */
- function createGroup ( $crgrp, $crpgrp, $vo, $uuids = array()) {
- global $db_connection;
- // id2uuid
- if ( empty($uuids) ) {
- $uuids['groups'] = 0;
- $uuids['acl2'] = 0;
- $empty_uuids = 1;
- }
- // Get parent group name
- $sql = "SELECT groups.dn FROM groups WHERE groups.gid = " . $crpgrp;
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) !== 0 ) {
- $row = mysql_fetch_row($query);
- $parent_name = $row[0];
- } else return 0;
- // New group full name
- $group_name = $parent_name . "/" . $crgrp;
- $uuids['group_name'] = $group_name;
- // Check if not allready exists
- $sql = "SELECT groups.gid FROM groups WHERE groups.dn = '".mysql_real_escape_string($group_name)."' AND groups.parent = " . $crpgrp . " AND groups.must = 1";
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) !== 0 ) return 0;
- // Get VO roles ID array ( I really dont understand why Roles in permission table is important and what functionality is represented with this row - so I use this Roles only to recopy instances of NULL-role ACL to it. Maybe this is bug. Looking forward to hearing from you, please write any propositions to manf@grid.org.ua )
- $roles_array = array ( );
- $sql = "SELECT roles.rid, roles.role FROM roles";
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) !== 0 ) {
- while ( $row = mysql_fetch_row($query) ) {
- $roles_array[$row[1]] = $row[0];
- if ( isset($empty_uuids) ) $uuids[$row[1]] = 0;
- }
- }
- // Get ACL for creation
- $group_permissions = array ();
- // --if exists default ACL for parrent - use it
- $sql = "SELECT acl2.acl_id FROM acl2 WHERE acl2.group_id = " . $crpgrp . " AND acl2.defaultACL = 1";
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) !== 0 ) {
- $row = mysql_fetch_row($query);
- $aclid = $row[0];
- } else { // -- default not exists - copy from parent NULL (this is a part of "Roles" question: default ACL is without Role recopiing to all roles, I suppose that normal acl has the same behaviour )
- $sql = "SELECT acl2.acl_id FROM acl2 WHERE acl2.group_id = " . $crpgrp . " AND acl2.defaultACL = 0 AND acl2.role_id IS NULL";
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) == 0 ) return 0;
- $row = mysql_fetch_row($query);
- $aclid = $row[0];
- }
- // get stored ACL permissions to apply
- $sql = "SELECT acl2_permissions.permissions, acl2_permissions.admin_id FROM acl2_permissions WHERE acl2_permissions.acl_id = " . $aclid;
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) == 0 ) return 0;
- while ( $row = mysql_fetch_row($query) )
- $group_permissions[$row[1]] = $row[0];
- // Ok, now we have all information required to crete group and all it's acl statemnts -- inserting
- // -- insert into group table
- $sql = sprintf("INSERT INTO groups(dn, parent, must) VALUES ('%s', %d, 1 );",
- mysql_real_escape_string($group_name), $crpgrp);
- if ( ! mysql_query($sql, $db_connection) ) return 0;
- $groupid = mysql_insert_id();
- $uuids['groups'] = UUID4id($groupid, 'groups', $uuids['groups']);
- // -- create acl without group
- $sql = sprintf("INSERT INTO acl2(group_id, defaultACL, role_id) VALUES( %d, 0, NULL );", $groupid);
- if ( ! mysql_query($sql, $db_connection) ) return 0;
- $aclid = mysql_insert_id();
- $uuids['acl2'] = UUID4id($aclid, 'acl2', $uuids['acl2']);
- foreach ( $group_permissions as $gpadmid => $gpp ) {
- $asql = sprintf("INSERT INTO acl2_permissions(acl_id, permissions, admin_id)
- VALUES ( %d, %d, %d );",$aclid,$gpp,$gpadmid);
- if ( ! mysql_query($asql, $db_connection) ) return 0;
- }
-
- // -- create acl for each role
- foreach ( $roles_array as $rolename => $role ) {
- $sql = sprintf("INSERT INTO acl2(group_id, defaultACL, role_id) VALUES( %d, 0, %s );", $groupid, $role );
- if ( ! mysql_query($sql, $db_connection) ) return 0;
- $aclid = mysql_insert_id();
- $uuids[$rolename] = UUID4id($aclid, 'acl2', $uuids[$rolename]);
- foreach ( $group_permissions as $gpadmid => $gpp ) {
- $asql = sprintf("INSERT INTO acl2_permissions(acl_id, permissions, admin_id)
- VALUES ( %d, %d, %d );",$aclid,$gpp,$gpadmid);
- if ( ! mysql_query($asql, $db_connection) ) return 0;
- }
- }
- $GLOBALS['pva_id2uuid_arr'] = $uuids;
- return 1;
- }
- /* delete user by user ID
- return (bool) operation status */
- function deleteUser ($userid, $uuids = array() ) {
- global $db_connection;
- // id2uuid
- if (! id2uuid_convert ('usr', $userid, $uuids) ) return 0;
- // function description handling
- if (! isset($uuids['userdn']) ) $uuids['userdn'] = getUserDN($userid);
- // perform delete user
- $sql = array (
- "DELETE FROM usr WHERE usr.userid = " . $userid . ";",
- "DELETE FROM m WHERE m.userid = " . $userid . ";",
- "DELETE FROM usr_attrs WHERE usr_attrs.u_id = " . $userid . ";"
- );
- foreach ( $sql as $ssql ) {
- $result = mysql_query($ssql, $db_connection);
- if ( ! $result ) return 0;
- }
- $GLOBALS['pva_id2uuid_arr'] = $uuids;
- return 1;
- }
- /* delete group by group ID
- group ID, VO name
- return (int) operation status:
- 0 on failure
- -1 on child exist
- 1 on success */
- function deleteGroup ($gid, $vo, $uuids = array() ) {
- global $db_connection;
- // id2uuid
- if (! id2uuid_convert ('groups', $gid, $uuids) ) return 0;
- // function description handling
- if (! isset($uuids['group_name']) ) $uuids['group_name'] = getGroupById($gid);
- // Check for top group
- $sql = "SELECT groups.gid FROM groups WHERE groups.gid = ". $gid." AND groups.dn = '/".mysql_real_escape_string($vo)."'";
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) !== 0 ) return 0;
- // Check for child
- $sql = "SELECT groups.gid FROM groups WHERE groups.parent = " . $gid;
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) !== 0 ) return -1;
- // Get ACL Ids for group
- $sql = "SELECT acl2.acl_id FROM acl2 WHERE acl2.group_id = " . $gid;
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) == 0 ) return 0;
- $sql = array ( "DELETE FROM role_attrs WHERE role_attrs.g_id = " . $gid . ";" );
- while ( $row = mysql_fetch_row($query) )
- $sql[] = "DELETE FROM acl2_permissions WHERE acl_id = " . $row[0];
- $sql[] = "DELETE FROM acl2 WHERE acl2.group_id = " . $gid . ";";
- $sql[] = "DELETE FROM groups WHERE groups.gid = " . $gid . ";";
- $sql[] = "DELETE FROM group_attrs WHERE group_attrs.g_id = " . $gid . ";";
- $sql[] = "DELETE FROM m WHERE m.gid = " . $gid . ";";
- foreach ( $sql as $ssql ) {
- $result = mysql_query($ssql, $db_connection);
- if ( ! $result ) return 0;
- }
- $GLOBALS['pva_id2uuid_arr'] = $uuids;
- return 1;
- }
- /* delete role by role ID
- role ID, VO name
- return (bool) operation status */
- function deleteRole ($rid, $vo, $uuids = array() ) {
- global $db_connection;
- // id2uuid
- if (! id2uuid_convert ('roles', $rid, $uuids) ) return 0;
- // function description handling
- if (! isset($uuids['role_name']) ) $uuids['role_name'] = getRoleName($rid);
- // Get ACL Ids for role
- $sql = "SELECT acl2.acl_id FROM acl2 WHERE acl2.role_id = " . $rid;
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) == 0 ) return 0;
- $sql = array ( "DELETE FROM role_attrs WHERE role_attrs.r_id = " . $rid . ";" );
- while ( $row = mysql_fetch_row($query) )
- $sql[] = "DELETE FROM acl2_permissions WHERE acl_id = " . $row[0];
- $sql[] = "DELETE FROM acl2 WHERE acl2.role_id = " . $rid . ";";
- $sql[] = "DELETE FROM m WHERE m.rid = " . $rid . ";";
- $sql[] = "DELETE FROM roles WHERE roles.rid = " . $rid . ";";
- foreach ( $sql as $ssql ) {
- $result = mysql_query($ssql, $db_connection);
- if ( ! $result ) return 0;
- }
- $GLOBALS['pva_id2uuid_arr'] = $uuids;
- return 1;
- }
- /* get user DN by user ID
- return (string) user DN */
- function getUserDN ( $id ) {
- global $db_connection;
- $sql = "SELECT usr.dn FROM usr WHERE usr.userid = " . $id;
- $query = mysql_query($sql, $db_connection);
- if ( ! $query ) return 0;
- if ( ! mysql_num_rows($query) ) return 0;
- $row = mysql_fetch_row($query);
- return $row[0];
- }
- /* get user information by user ID
- return (array) array of (user DN, user CN, CA DN, user e-mail, CA database ID) */
- function getUserInfo( $id ) {
- global $db_connection;
- $sql = "SELECT usr.dn, usr.cn, ca.ca, usr.mail, ca.cid FROM usr, ca WHERE ca.cid = usr.ca AND usr.userid = " . $id;
- $query = mysql_query($sql, $db_connection);
- $row = mysql_fetch_row($query);
- return array( $row[0], $row[1], $row[2], $row[3], $row[4] );
- }
- /* get information about all users
- return (array of hash) */
- function getAllUsersInfo( ) {
- global $db_connection;
- $sql = "SELECT usr.dn, usr.cn, ca.ca, usr.mail, usr.cauri FROM usr, ca WHERE ca.cid = usr.ca";
- $query = mysql_query($sql, $db_connection);
- if ( ! $query ) return 0;
- $result = array();
- while ( $row = mysql_fetch_row($query) ){
- $result[] = array( "CA" => $row[2], "CN" => $row[1], "DN" => $row[0], "certUri" => $row[4], "mail" => $row[3] );
- }
- return $result;
- }
- /* update user CN and e-mail
- user ID, new user CN, new user e-mail
- return (bool) operation status */
- function updateUserInfo( $id , $cn, $mail, $uuids = array() ) {
- global $db_connection;
- // id2uuid
- if (! id2uuid_convert ('usr', $id, $uuids) ) return 0;
- // function description handling
- if (! isset($uuids['user_dn'])) $uuids['user_dn'] = getUserDN($id);
- // perform update
- $sql = sprintf("UPDATE usr SET usr.cn = '%s', usr.mail = '%s'
- WHERE usr.userid = %s", mysql_real_escape_string($cn), mysql_real_escape_string($mail), $id);
- if ( ! mysql_query($sql, $db_connection) ) return 0;
- $GLOBALS['pva_id2uuid_arr'] = $uuids;
- return 1;
- }
- /* get $items_per_page number of groups
- start from group, name patern
- return (array) [group name] = group ID */
- function getGroups ( $limit = 0, $like = null ) {
- global $db_connection;
- global $items_per_page;
- $groups = array();
- $sql = "SELECT groups.gid, groups.dn FROM groups";
- if ( $like !== null ) $sql .= " WHERE groups.dn LIKE '%".mysql_real_escape_string($like)."%'";
- $sql .= " LIMIT ". $limit .", ". $items_per_page;
- $query = mysql_query($sql, $db_connection);
- while ( $row = mysql_fetch_row($query) ){
- $groups[$row[1]] = $row[0];
- };
- return $groups;
- }
- /* get group name by ID
- return (string) group name */
- function getGroupById ( $id ) {
- global $db_connection;
- $sql = sprintf("SELECT groups.dn FROM groups WHERE groups.gid = %d", $id );
- $query = mysql_query($sql, $db_connection);
- if ( ! $query ) return 0;
- if ( mysql_num_rows($query) == 0 ) return 0;
- $row = mysql_fetch_row($query);
- return $row[0];
- }
- /* get $items_per_page number of roles
- start from role, role name patern
- return (array) [role name] = role ID */
- function getRoles ( $limit = 0, $like = null ) {
- global $db_connection;
- global $items_per_page;
- $roles = array();
- $sql = "SELECT roles.rid, roles.role FROM roles";
- if ( $like !== null ) $sql .= " WHERE roles.role LIKE '%".mysql_real_escape_string($like)."%'";
- $sql .= " LIMIT ". $limit .", ". $items_per_page;
- $query = mysql_query($sql, $db_connection);
- while ( $row = mysql_fetch_row($query) ){
- $roles[$row[1]] = $row[0];
- };
- return $roles;
- }
- /* get number of groups corresponding:
- group name pattern
- return (int) number of groups */
- function getGroupsCount ( $like = null ) {
- global $db_connection;
- $sql_count = "SELECT COUNT(groups.gid) AS gcount FROM groups";
- if ( $like !== null ) $sql_count .= " WHERE groups.dn LIKE '%".mysql_real_escape_string($like)."%'";
- $count_arr = mysql_fetch_array(mysql_query($sql_count,$db_connection));
- return $count_arr["gcount"];
- }
- /* get number of roles corresponding:
- role name pattern
- return (int) number of roles */
- function getRolesCount ( $like = null ) {
- global $db_connection;
- $sql_count = "SELECT COUNT(roles.rid) AS rcount FROM roles";
- if ( $like !== null ) $sql_count .= " WHERE roles.role LIKE '%".mysql_real_escape_string($like)."%'";
- $count_arr = mysql_fetch_array(mysql_query($sql_count,$db_connection));
- return $count_arr["rcount"];
- }
- /* get role name by ID
- return (string) role name */
- function getRoleName ( $id ) {
- global $db_connection;
- if ( ! is_numeric($id) ) return 0;
- $sql = "SELECT roles.role FROM roles WHERE roles.rid = " . $id;
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) == 0 ) return 0;
- $row = mysql_fetch_row($query);
- return $row[0];
- }
- /* get role ID by Name
- return (int) role ID */
- function getRoleId ( $name ) {
- global $db_connection;
- $sql = "SELECT roles.rid FROM roles WHERE roles.role = '" . mysql_real_escape_string($name) . "'";
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) == 0 ) return 0;
- $row = mysql_fetch_row($query);
- return $row[0];
- }
- /* get ACL id for specified:
- group ID, role ID, default flag
- return (int) ACL id, 0 if false */
- function getACLid ( $gid, $rid, $default ) {
- global $db_connection;
- if ( ! is_numeric($gid) ) return 0;
- if ( $rid !== NULL ) if ( ! is_numeric($rid) ) return 0;
- if ( ! is_numeric($default) ) return 0;
- $sql = sprintf("SELECT acl2.acl_id FROM acl2 WHERE acl2.group_id = %d AND acl2.defaultACL = %d AND acl2.role_id %s", $gid, $default, ( $rid === NULL ) ? "IS NULL" : "= ".$rid );
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) == 0 ) return 0;
- $row = mysql_fetch_row($query);
- return $row[0];
- }
- /* get all ACL values for specified ACL id (group and role actually)
- returning set of permissions for each user or role/group having special permissions for this ACL ID
- return (hash of array) [admin CN] = array of (ca, admid, [array of permission categoty] = permissions in human readable format) */
- function getACLvalues ( $id ) {
- global $db_connection;
- if ( ! is_numeric($id) ) return 0;
- $sql = sprintf("SELECT acl2_permissions.permissions, admins.dn, ca.ca, admins.adminid FROM acl2_permissions, admins, ca
- WHERE acl2_permissions.acl_id = %d
- AND acl2_permissions.admin_id = admins.adminid
- AND admins.ca = ca.cid ", $id );
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) == 0 ) return 0;
- $result = array ();
- while ( $row = mysql_fetch_row($query) ) {
- // If Groups and Roles permissions - just print it, otherwise get CN
- $adm_ca = CNfromDN($row[2]);
- if (( $adm_ca === "VOMS Role" ) || ( $adm_ca === "VOMS Group" ) ) $adm_cn = $row[1];
- else $adm_cn = CNfromDN($row[1]);
- // Not listed in interface of original Java-based VOMS-Admin, but present in database
- if ( $adm_cn === "Internal VOMS Process" ) continue;
- if ( $adm_cn === "Local Database Administrator" ) continue;
- if ( $adm_cn === "Absolutely Anyone" ) continue;
- $result[$adm_cn]["ca"] = $adm_ca;
- $result[$adm_cn]["admid"] = $row[3];
- // Decode permissions
- $parr = decodeACLPermissions($row[0]);
- foreach ( $parr as $pcat => $ppa ) {
- $result[$adm_cn][$pcat] = "";
- if ( $ppa["r"] == 1 ) $result[$adm_cn][$pcat] .= "r";
- if ( $ppa["w"] == 1 ) $result[$adm_cn][$pcat] .= "w";
- if (isset($ppa["d"])) if ( $ppa["d"] == 1 ) $result[$adm_cn][$pcat] .= "d";
- }
- }
- return $result;
- }
- /* find all child groups with permission ids for this groups;
- recursive function, that handle information via reference parameters
- processed_parents -- array of allready processed parents (must be empty at first call)
- to_process -- array of [gid] = 1 to processed. To emulate set of elements and quckly check if in set
- acl_ids -- array of ACL ids of all child groups
- */
- function getAllChildren ( &$processed_parents, &$to_process, &$acl_ids ) {
- global $db_connection;
- $pgid = key($to_process);
- $sql = sprintf("SELECT acl2.acl_id, acl2.group_id FROM groups, acl2 WHERE acl2.group_id = groups.gid AND groups.parent = %d", $pgid);
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) == 0 ) return 0;
- while ( $row = mysql_fetch_row($query) ) {
- $acl_ids[] = $row[0];
- if ( ! isset($processed_parents[$row[1]]) ) $to_process[$row[1]] = 1;
- }
- unset($to_process[$pgid]);
- $processed_parents[$pgid] = 1;
- if ( empty($to_process) ) return 0;
- getAllChildren ( $processed_parents, $to_process, $acl_ids );
- }
- /* update ACL permissions for specified
- ACL ID, admin ID, permissions value, propagate to all child flags, group ID, default ACL flag
- return (bool) operation status */
- function updateACLPermissions($aclid, $admid, $perm, $propagate = 0, $gid = 0, $default_acl = 0, $uuids = array() ) {
- global $db_connection;
- // id2uuid
- if (! id2uuid_convert ('acl2', $aclid, $uuids) ) return 0;
- if (! id2uuid_convert ('admins', $admid, $uuids) ) return 0;
- // group id and defaultACL flag
- if ($aclid) {
- // for existed ACL
- $sql = sprintf("SELECT acl2.group_id, acl2.defaultACL FROM acl2 WHERE acl2.acl_id = %d", $aclid);
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) == 0 ) return 0;
- $row = mysql_fetch_row($query);
- $group_id = $row[0];
- $defaultACL = $row[1];
- } else {
- // for new ACL
- $group_id = $gid;
- $defaultACL = $default_acl;
- }
- // function description handling
- if (! isset($uuids['group_name'])) $uuids['group_name'] = getGroupById($group_id);
- if (! isset($uuids['admin_cn'])){
- $adm_info = getAdminInfo($admid);
- $uuids['admin_cn'] = $adm_info['cn'];
- }
-
- // find ACL (normal/default) for this group
- $acl_ids = array ();
- $sql = sprintf("SELECT acl2.acl_id FROM acl2 WHERE acl2.group_id = %s",$group_id);
- if ( $default_acl ) $sql .= " AND acl2.defaultACL = 1 AND acl2.role_id IS NULL";
- $query = mysql_query($sql, $db_connection);
- // if ACL not found, then create new one
- // store ACL id(s) to array
- if ( mysql_num_rows($query) == 0 ) {
- if ( $default_acl ) {
- $sql = sprintf("INSERT INTO acl2(group_id, defaultACL, role_id) VALUES (%d, 1, NULL)", $group_id);
- if ( ! mysql_query($sql, $db_connection) ) return 0;
- // id2uuid for new ACL
- $acl_ins_id = mysql_insert_id();
- $uuids['acl2_def'] = UUID4id($acl_ins_id, 'acl2', isset($uuids['acl2_def']) ? $uuids['acl2_def'] : 0);
- $acl_ids[] = $acl_ins_id;
- } else return 0;
- } else while ( $row = mysql_fetch_row($query) ) $acl_ids[] = $row[0];
- // get all child group ACLs for this parent when propagate requested
- if ( ( $propagate ) && ( ! $defaultACL ) ) {
- $processed_parents = array ();
- if ($aclid) $to_process[$propagate] = 1; else $to_process[$gid] = 1;
- // add child ACLs to ids array
- getAllChildren ( $processed_parents, $to_process, $acl_ids );
- }
- // create(update) ACL_permissions for every ACL in array for requested admin
- foreach ( array_unique($acl_ids) as $acl_id ) {
- // using UPDATE, MySQL will not update columns where the new value is the same as the old value
- // so SELECT first
- $sql = sprintf("SELECT acl2_permissions.acl_id FROM acl2_permissions
- WHERE acl2_permissions.permissions = %d
- AND acl2_permissions.acl_id = %d
- AND acl2_permissions.admin_id = %d", $perm, $acl_id, $admid);
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) != 0 ) continue;
- // same permissions record not found, trying to update
- $sql = sprintf("UPDATE acl2_permissions
- SET acl2_permissions.permissions = %d
- WHERE acl2_permissions.acl_id = %d
- AND acl2_permissions.admin_id = %d", $perm, $acl_id, $admid);
- mysql_query($sql, $db_connection);
- // if update does not succeed then insert new value
- if ( ! mysql_affected_rows() ) {
- $sql = sprintf("INSERT INTO acl2_permissions(acl_id, permissions, admin_id)
- VALUES (%d, %d, %d)",$acl_id, $perm, $admid);
- if ( ! mysql_query($sql, $db_connection) ) return 0;
- }
- }
- $GLOBALS['pva_id2uuid_arr'] = $uuids;
- return 1;
- }
- /* delete an ACL with specified
- ACL ID, admin ID, remove from all child flag, default ACL flag
- return (bool) operation status */
- function deleteACLentry($aclid, $admid, $propagate = 0, $default = 0, $uuids = array() ) {
- global $db_connection;
- // id2uuid
- if (! id2uuid_convert ('acl2', $aclid, $uuids) ) return 0;
- if (! id2uuid_convert ('admins', $admid, $uuids) ) return 0;
- // function description handling
- if (! isset($uuids['admin_cn'])){
- $adm_info = getAdminInfo($admid);
- $uuids['admin_cn'] = $adm_info['cn'];
- }
- $GLOBALS['pva_id2uuid_arr'] = $uuids;
- // when remove from child requested ( $propagate contain parent group identifier )
- if ( $propagate ) {
- if (! isset($uuids['group_name'])) $uuids['group_name'] = getGroupById($propagate);
- $sql = sprintf("DELETE FROM acl2_permissions
- USING acl2_permissions INNER JOIN acl2 INNER JOIN groups
- WHERE acl2_permissions.acl_id = acl2.acl_id
- AND acl2.group_id = groups.gid
- AND ( groups.parent = %d OR groups.gid = %d )
- AND acl2_permissions.admin_id = %d", $propagate, $propagate, $admid);
- if ( ! mysql_query($sql, $db_connection)) {
- $GLOBALS['pva_id2uuid_arr'] = $uuids;
- return 0;
- } else return 1;
- }
- // delete ACL for admin
- $sql = sprintf("DELETE FROM acl2_permissions
- WHERE acl2_permissions.acl_id = %d
- AND acl2_permissions.admin_id = %d", $aclid, $admid);
- if ( ! mysql_query($sql, $db_connection)) return 0;
- // get group and defaultACL flag from aclid
- $sql = sprintf("SELECT acl2.group_id, acl2.defaultACL
- FROM acl2
- WHERE acl2.acl_id = %d", $aclid);
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) == 0 ) return 0;
- $row = mysql_fetch_row($query);
- $group_id = $row[0];
- $default = $row[1];
- // function description handling
- if (! isset($uuids['group_name'])) $uuids['group_name'] = getGroupById($group_id);
- $GLOBALS['pva_id2uuid_arr'] = $uuids;
- // if ACLs permissions records for other admins not exist -- delete record in ACL table
- if ( mysql_affected_rows() ) {
- if ( $default ) {
- $sql = sprintf("SELECT acl2_permissions.acl_id FROM acl2_permissions
- WHERE acl2_permissions.acl_id = %d ", $aclid);
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) ) { return 1; } else {
- $sql = sprintf("DELETE FROM acl2 WHERE acl2.acl_id = %d AND acl2.defaultACL = 1", $aclid);
- if ( ! mysql_query($sql, $db_connection)) return 0;
- if ( mysql_affected_rows() ) return 1;
- return 0;
- }
- } else return 1;
- } else return 0;
- }
- /* get permissions numerical value for
- ACL ID, admin ID
- return (int) permissions database value */
- function getPermissions ( $aclid, $admid ) {
- global $db_connection;
- $sql = sprintf("SELECT acl2_permissions.permissions FROM acl2_permissions
- WHERE acl2_permissions.acl_id = %d
- AND acl2_permissions.admin_id = %d",$aclid,$admid);
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) == 0 ) return 0;
- $row = mysql_fetch_row($query);
- return $row[0];
- }
- /* get permissions numerical value for specified
- group ID, admin ID
- return (int) permissions database value */
- function getAdminPermissions( $gid, $admid) {
- global $db_connection;
- $sql = sprintf("SELECT acl2_permissions.permissions FROM acl2_permissions
- INNER JOIN acl2 ON acl2_permissions.acl_id = acl2.acl_id
- WHERE acl2.group_id = %d
- AND acl2.role_id IS NULL
- AND acl2_permissions.admin_id = %d
- AND acl2.defaultACL = 0",
- $gid, $admid);
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) == 0 ) return 0;
- $row = mysql_fetch_row($query);
- return $row[0];
- }
- /* get group characteristics for specified ACL ID
- return (hash) group parameters ([gid] => group ID, [gdn] => group name, [default] => default ACL) */
- function getACLGroup ( $aclid ) {
- global $db_connection;
- $sql = sprintf("SELECT acl2.group_id, groups.dn, acl2.defaultACL
- FROM acl2, groups
- WHERE acl2.group_id = groups.gid AND acl2.acl_id = %d", $aclid );
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) == 0 ) return 0;
- $row = mysql_fetch_row($query);
- return array( "gid" => $row[0], "gdn" => $row[1], "default" => $row[2] );
- }
- /* get user roles in groups by user ID
- return (hash) [group][role] = role */
- function getUserMembership ( $id ) {
- global $db_connection;
- $sql = "SELECT groups.dn, roles.role FROM m LEFT JOIN groups ON m.gid = groups.gid LEFT JOIN roles ON m.rid = roles.rid WHERE m.userid = ".$id ." ORDER BY groups.dn";
- $query = mysql_query($sql, $db_connection);
- if ( ! $query ) return 0;
- $result = array();
- while ($row = mysql_fetch_row($query)){
- $result[$row[0]][$row[1]] = $row[1];
- }
- return $result;
- }
- /* add user membership in group with role:
- group ID, user ID, role ID (optional)
- return (bool) operation status */
- function addMembership ( $gid, $uid, $rid = 0, $uuids = array() ) {
- global $db_connection;
- // id2uuid
- if (! id2uuid_convert ('groups', $gid, $uuids) ) return 0;
- if (! id2uuid_convert ('usr', $uid, $uuids) ) return 0;
- if ( $rid !== 0 ) if (! id2uuid_convert ('roles', $rid, $uuids) ) return 0;
- // function description handling
- if (! isset($uuids['user_name']) ) $uuids['user_name'] = getUserDN($uid);
- if (! isset($uuids['group_name']) ) $uuids['group_name'] = getGroupById($gid);
- if ( $rid !== 0 ) if (! isset($uuids['role_name']) ) $uuids['role_name'] = getRoleName($rid);
- // Check for allready exists
- $sql = "SELECT m.mapping_id FROM m WHERE m.userid = ".$uid." AND m.gid = ".$gid;
- if ( $rid !== 0 ) $sql .= " AND m.rid = ".$rid;
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) !== 0 ) return -1;
- if ( $rid !== 0 ) $sql = "INSERT INTO m ( userid, gid, rid ) VALUES ( ".$uid.", ". $gid .", ". $rid ." )";
- else $sql = "INSERT INTO m ( userid, gid ) VALUES ( ".$uid.", ". $gid ." )";
- if ( ! mysql_query($sql, $db_connection) ) return 0;
- $GLOBALS['pva_id2uuid_arr'] = $uuids;
- return 1;
- }
- /* remove user membersip in group with role
- group ID, user ID, role ID (optional)
- return (bool) operation status */
- function delMembership ( $gid, $uid, $rid = 0, $uuids = array() ) {
- global $db_connection;
- // id2uuid
- if (! id2uuid_convert ('groups', $gid, $uuids) ) return 0;
- if (! id2uuid_convert ('usr', $uid, $uuids) ) return 0;
- if ( $rid !== 0 ) if (! id2uuid_convert ('roles', $rid, $uuids) ) return 0;
- // function description handling
- if (! isset($uuids['user_name']) ) $uuids['user_name'] = getUserDN($uid);
- if (! isset($uuids['group_name']) ) $uuids['group_name'] = getGroupById($gid);
- if ( $rid !== 0 ) if (! isset($uuids['role_name']) ) $uuids['role_name'] = getRoleName($rid);
-
- $sql = "SELECT m.mapping_id FROM m WHERE m.userid = ".$uid." AND m.gid = ".$gid;
- if ( $rid !== 0 ) $sql .= " AND m.rid = ".$rid;
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) == 0 ) return -1;
- $sql = "DELETE FROM m WHERE m.userid = ".$uid." AND m.gid = ".$gid;
- if ( $rid !== 0 ) $sql .= " AND m.rid = ".$rid;
- if ( ! mysql_query($sql, $db_connection) ) return 0;
- $GLOBALS['pva_id2uuid_arr'] = $uuids;
- return 1;
- }
- /* check user/group attribute exists (by reference return unique flag)
- attribute ID, user/group ID, &unique flag, user/group switch
- return (bool) check result */
- function checkAttrExists ( $aid, $uid, &$uniq, $wt = "u" ) {
- global $db_connection;
- if ( $wt === "u" ) { $dbn = "usr_attrs"; $dbuid = "u_id"; } else
- if ( $wt === "g" ) { $dbn = "group_attrs"; $dbuid = "g_id"; } else
- return 0;
- $sql = "SELECT attributes.a_uniq FROM attributes WHERE attributes.a_id = ". $aid;
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) != NULL ) {
- $row = mysql_fetch_row($query);
- $uniq = $row[0];
- $sql = sprintf("SELECT %s.a_id FROM %s WHERE %s.a_id = %d AND %s.%s = %d", $dbn, $dbn, $dbn, $aid, $dbn, $dbuid, $uid);
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) != NULL ) return 1;
- }
- return 0;
- }
- /* check role attribute exists (by reference return unique flag)
- attribute ID, role ID, group ID, &unique flag
- return (bool) check result */
- function checkRoleAttrExists( $aid, $rid, $gid, &$uniq) {
- global $db_connection;
- $sql = "SELECT attributes.a_uniq FROM attributes WHERE attributes.a_id = ". $aid;
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) != NULL ) {
- $row = mysql_fetch_row($query);
- $uniq = $row[0];
- $sql = sprintf("SELECT role_attrs.a_id FROM role_attrs WHERE role_attrs.a_id = %d AND role_attrs.r_id = %d AND role_attrs.g_id = %d", $aid, $rid, $gid);
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) != NULL ) return 1;
- }
- return 0;
- }
- /* check if attribute is unique for user/group
- attribute ID, attribute value, user/group switch
- return (bool) check result */
- function checkUniqAttr ( $aid, $value, $wt = "u" ) {
- global $db_connection;
- if ( $wt === "u" ) $dbn = "usr_attrs"; else
- if ( $wt === "g" ) $dbn = "group_attrs"; else
- return 0;
- $sql = sprintf("SELECT %s.a_id FROM %s WHERE %s.a_id = %d AND %s.a_value = '%s'", $dbn, $dbn, $dbn, $aid, $dbn, mysql_real_escape_string($value)) ;
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) != NULL ) return 0;
- return 1;
- }
- /* check if attribute is unique for role
- attribute ID, group ID, attrubute value
- return (bool) check result */
- function checkRoleUniqAttr ( $aid, $gid, $value ) {
- global $db_connection;
- $sql = sprintf("SELECT role_atrs.a_id FROM role_atrs WHERE role_atrs.a_id = %d AND role_atrs.g_id = %d AND role_atrs.a_value = '%s'", $aid, $gid, mysql_real_escape_string($value));
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) != NULL ) return 0;
- return 1;
- }
- /* get attribute name by attribute id
- attribute ID
- return (string) attribute name */
- function getAttributeName ( $aid ) {
- global $db_connection;
- $sql = "SELECT attributes.a_name FROM attributes WHERE attributes.a_id = " . $aid;
- $query = mysql_query($sql, $db_connection);
- if ( ! $query ) return 0;
- if ( ! mysql_num_rows($query) ) return 0;
- $row = mysql_fetch_row($query);
- return $row[0];
- }
- /* add attribute for user/group
- attribute ID, user/group ID, attribute value, user/group switch
- return (bool) operation status */
- function addAttribute ( $aid, $uid, $value, $wt = "u", $uuids = array() ) {
- global $db_connection;
- // id2uuid
- if (! id2uuid_convert ('attributes', $aid, $uuids) ) return 0;
- if ( $wt === "u" ) {
- $dbn = "usr_attrs"; $dbuid = "u_id";
- if (! id2uuid_convert ('usr', $uid, $uuids) ) return 0;
- } else if ( $wt === "g" ) {
- $dbn = "group_attrs"; $dbuid = "g_id";
- if (! id2uuid_convert ('groups', $uid, $uuids) ) return 0;
- } else return 0;
- // function description handling
- if (! isset($uuids['attr_name'])) $uuids['attr_name'] = getAttributeName($aid);
- if ( $wt === "u" ) if (! isset($uuids['user_name'])) $uuids['user_name'] = getUserDN($uid); else
- if ( $wt === "g" ) if (! isset($uuids['group_name'])) $uuids['group_name'] = getGroupById($uid);
- $uniq = 0;
- $exists = checkAttrExists( $aid, $uid, $uniq, $wt );
- if ( $uniq == 1 ) if ( ! checkUniqAttr( $aid, $value, $wt ) ) return -1;
- if ( $exists ) {
- $sql = sprintf("UPDATE %s SET %s.a_value = '%s' WHERE %s.a_id = %d AND %s.%s = %d",
- $dbn, $dbn, mysql_real_escape_string($value), $dbn, $aid, $dbn, $dbuid, $uid);
- } else {
- $sql = sprintf("INSERT INTO %s(a_id, %s, a_value) VALUES ( %d, %d, '%s' )",
- $dbn, $dbuid, $aid, $uid, mysql_real_escape_string($value) );
- }
- if ( ! mysql_query($sql, $db_connection) ) return 0;
- $GLOBALS['pva_id2uuid_arr'] = $uuids;
- return 1;
- }
- /* delete attribute for user/group
- attribute ID, user/group ID, user/group switch
- return (bool) operation status */
- function delAttribute ( $aid, $uid, $wt = "u", $uuids = array() ) {
- global $db_connection;
- // id2uuid
- if (! id2uuid_convert ('attributes', $aid, $uuids) ) return 0;
- if ( $wt === "u" ) {
- $dbn = "usr_attrs"; $dbuid = "u_id";
- if (! id2uuid_convert ('usr', $uid, $uuids) ) return 0;
- } else if ( $wt === "g" ) {
- $dbn = "group_attrs"; $dbuid = "g_id";
- if (! id2uuid_convert ('groups', $uid, $uuids) ) return 0;
- } else return 0;
- // function description handling
- if (! isset($uuids['attr_name'])) $uuids['attr_name'] = getAttributeName($aid);
- if ( $wt === "u" ) if (! isset($uuids['user_name'])) $uuids['user_name'] = getUserDN($uid); else
- if ( $wt === "g" ) if (! isset($uuids['group_name'])) $uuids['group_name'] = getGroupById($uid);
- $sql = sprintf("DELETE FROM %s WHERE %s.a_id = %d AND %s.%s = %d", $dbn, $dbn, $aid, $dbn, $dbuid, $uid);
- if ( ! mysql_query($sql, $db_connection) ) return 0;
- $GLOBALS['pva_id2uuid_arr'] = $uuids;
- return 1;
- }
- /* add attribute for role
- attribute ID, role ID, group ID, attribure value
- return (bool) operation status */
- function addRoleAttribute ($aid, $rid, $gid, $value, $uuids = array()) {
- global $db_connection;
- // id2uuid
- if (! id2uuid_convert ('attributes', $aid, $uuids) ) return 0;
- if (! id2uuid_convert ('roles', $rid, $uuids) ) return 0;
- if (! id2uuid_convert ('groups', $gid, $uuids) ) return 0;
- // function description handling
- if (! isset($uuids['attr_name'])) $uuids['attr_name'] = getAttributeName($aid);
- if (! isset($uuids['role_name'])) $uuids['role_name'] = getRoleName($rid);
- if (! isset($uuids['group_name'])) $uuids['group_name'] = getGroupById($gid);
- $uniq = 0;
- $exists = checkRoleAttrExists( $aid, $rid, $gid, $uniq);
- if ( $uniq == 1 ) if ( ! checkRoleUniqAttr( $aid, $gid, $value ) ) return -1;
- if ( $exists )
- $sql = sprintf("UPDATE role_attrs SET role_attrs.a_value = '%s' WHERE role_attrs.a_id = %d AND role_attrs.r_id = %d AND role_attrs.g_id = %d", mysql_real_escape_string($value), $aid, $rid, $gid);
- else
- $sql = sprintf("INSERT INTO role_attrs(a_id, g_id, r_id, a_value) VALUES ( %d, %d, %d, '%s')", $aid, $gid, $rid, mysql_real_escape_string($value) );
- if ( ! mysql_query($sql, $db_connection) ) return 0;
- $GLOBALS['pva_id2uuid_arr'] = $uuids;
- return 1;
- }
- /* delete attribute for role
- attribute ID, role ID, group ID
- return (bool) operation status */
- function delRoleAttribute ($aid, $rid, $gid, $uuids = array()) {
- global $db_connection;
- // id2uuid
- if (! id2uuid_convert ('attributes', $aid, $uuids) ) return 0;
- if (! id2uuid_convert ('roles', $rid, $uuids) ) return 0;
- if (! id2uuid_convert ('groups', $gid, $uuids) ) return 0;
- // function description handling
- if (! isset($uuids['attr_name'])) $uuids['attr_name'] = getAttributeName($aid);
- if (! isset($uuids['role_name'])) $uuids['role_name'] = getRoleName($rid);
- if (! isset($uuids['group_name'])) $uuids['group_name'] = getGroupById($gid);
- $sql = sprintf("DELETE FROM role_attrs WHERE role_attrs.a_id = %d AND role_attrs.r_id = %d AND role_attrs.g_id = %d",
- $aid, $rid, $gid);
- if ( ! mysql_query($sql, $db_connection) ) return 0;
- $GLOBALS['pva_id2uuid_arr'] = $uuids;
- return 1;
- }
- /* delete attribute from VO database by attribute ID
- return (bool) operation status */
- function delVOAttribute ($aid, $uuids = array()) {
- global $db_connection;
- // id2uuid
- if (! id2uuid_convert ('attributes', $aid, $uuids) ) return 0;
- // function description handling
- if (! isset($uuids['attr_name'])) $uuids['attr_name'] = getAttributeName($aid);
- $sql = array ( "DELETE FROM role_attrs WHERE role_attrs.a_id = " . $aid . ";",
- "DELETE FROM group_attrs WHERE group_attrs.a_id = " . $aid . ";",
- "DELETE FROM usr_attrs WHERE usr_attrs.a_id = " . $aid . ";",
- "DELETE FROM attributes WHERE attributes.a_id = " . $aid . ";"
- );
- foreach ( $sql as $ssql ) {
- $result = mysql_query($ssql, $db_connection);
- if ( ! $result ) return 0;
- }
- $GLOBALS['pva_id2uuid_arr'] = $uuids;
- return 1;
- }
- /* add attribute to VO database
- attribute name, attribute descriptiom, unique flag
- return (bool) operation status */
- function addVOAttribute($attrname, $attrdescr, $attruniq, $uuids = array()) {
- global $db_connection;
- $sql = sprintf("SELECT attributes.a_id FROM attributes WHERE attributes.a_name = '%s' AND attributes.a_uniq = %d ",
- mysql_real_escape_string($attrname), $attruniq);
- $query = mysql_query($sql, $db_connection);
- if ( ! mysql_num_rows($query) ) {
- // Attribute doesnot exists - chech the same name but different uniq
- $sql = sprintf("SELECT attributes.a_id FROM attributes WHERE attributes.a_name = '%s'",
- mysql_real_escape_string($attrname) );
- $query = mysql_query($sql, $db_connection);
- if ( ! mysql_num_rows($query) ) {
- // All clear - create new
- $sql = sprintf("INSERT INTO attributes(a_name, a_desc, a_uniq) VALUES ('%s', '%s', %d)",
- mysql_real_escape_string($attrname), mysql_real_escape_string($attrdescr), $attruniq);
- if ( ! mysql_query($sql, $db_connection) ) return 0;
- $attr_ins_id = mysql_insert_id();
- $uuids['attrs'] = UUID4id($attr_ins_id, 'attributes', isset($uuids['attrs'])?$uuids['attrs']:0);
- $GLOBALS['pva_id2uuid_arr'] = $uuids;
- } else return -1;
- } else {
- $row = mysql_fetch_row($query);
- $sql = sprintf("UPDATE attributes SET attributes.a_desc = '%s' WHERE attributes.a_id = %d",
- mysql_real_escape_string($attrdescr), $row[0] );
- if ( ! mysql_query($sql, $db_connection) ) return 0;
- }
- return 1;
- }
- /* get all attributes for user by user ID
- return (hash) of attributes ( [name] => name, [value] => value ) */
- function getUserAttributes ( $uid ) {
- global $db_connection;
- $sql = "SELECT attributes.a_id, attributes.a_name, usr_attrs.a_value FROM attributes, usr_attrs WHERE attributes.a_id = usr_attrs.a_id AND usr_attrs.u_id = ".$uid;
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) == NULL ) return 0;
- $result = array ();
- while ( $row = mysql_fetch_row($query)) {
- $result[$row[0]] = array ( "name" => $row[1], "value" => $row[2] );
- }
- return $result;
- }
- /* get all attributes for group by group ID
- return (hash) of attributes ( [name] => name, [value] => value ) */
- function getGroupAttributes ( $gid ) {
- global $db_connection;
- $sql = "SELECT attributes.a_id, attributes.a_name, group_attrs.a_value FROM attributes, group_attrs WHERE attributes.a_id = group_attrs.a_id AND group_attrs.g_id = ".$gid;
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) == NULL ) return 0;
- $result = array ();
- while ( $row = mysql_fetch_row($query)) {
- $result[$row[0]] = array ( "name" => $row[1], "value" => $row[2] );
- }
- return $result;
- }
- /* get all attributes for role by role ID
- return (hash) of attributes ( [name] => name, [value] => value, [group], [groupid], [aid] ) */
- function getRoleAttributes ( $rid ) {
- global $db_connection;
- $sql = "SELECT attributes.a_id, attributes.a_name, role_attrs.a_value, groups.dn, groups.gid FROM attributes, role_attrs, groups
- WHERE attributes.a_id = role_attrs.a_id AND role_attrs.g_id = groups.gid
- AND role_attrs.r_id = ".$rid;
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) == NULL ) return 0;
- $result = array ();
- $i = 0;
- while ( $row = mysql_fetch_row($query)) {
- $result[$i++] = array ( "name" => $row[1], "value" => $row[2], "group" => $row[3], "groupid" => $row[4], "aid" => $row[0] );
- }
- return $result;
- }
- /* get all attributes in VO database
- return (hash) of all attributes parameters ( [name] => name, [descr] => description, [uniq] => unique flag ) */
- function getAttributes ( ){
- global $db_connection;
- $sql = "SELECT attributes.a_id, attributes.a_name, attributes.a_desc, attributes.a_uniq FROM attributes";
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) == NULL ) return 0;
- $result = array ();
- while ( $row = mysql_fetch_row($query)) {
- $result[$row[0]] = array ( "name" => $row[1], "descr" => $row[2], "uniq" => $row[3] );
- }
- return $result;
- }
- /* get $items_per_page users that have assigned attributes
- start record to show, name patern
- return (hash) of ( [attr] => attribute name, [attrv] => attribute value, [cn] => user CN, [ca] => user CA, [usrid] => user ID )*/
- function getAllUserAttributes( $limit = 0, $like = null ) {
- global $db_connection;
- global $items_per_page;
- $attributes = array();
- $sql = "SELECT attributes.a_name, usr_attrs.a_value, usr.dn, ca.ca, usr.userid FROM attributes, usr_attrs, usr, ca
- WHERE usr_attrs.a_id = attributes.a_id AND usr_attrs.u_id = usr.userid
- AND usr.ca = ca.cid";
- if ( $like != null ) $sql .= " AND attributes.a_name LIKE '%".mysql_real_escape_string($like)."%'";
- $sql .= " LIMIT ". $limit .", ". $items_per_page;
- $query = mysql_query($sql, $db_connection);
- $i = 0;
- while ( $row = mysql_fetch_row($query) ){
- $usrcn = CNfromDN($row[2]);
- $cacn = CNfromDN($row[3]);
- $attributes[$i++] = array ( "attr" => $row[0], "attrv" => $row[1], "cn" => $usrcn, "ca" => $cacn, "usrid" => $row[4] );
- };
- return $attributes;
- }
- /* get number of all attributes records
- attribute name pattern
- return (int) attribute records count */
- function getAllUserAttributesCount( $like = null ){
- global $db_connection;
- $attributes = array();
- $sql = "SELECT attributes.a_name, usr_attrs.a_value, usr.dn, ca.ca, usr.userid FROM attributes, usr_attrs, usr, ca
- WHERE usr_attrs.a_id = attributes.a_id AND usr_attrs.u_id = usr.userid
- AND usr.ca = ca.cid";
- if ( $like != null ) $sql .= " AND attributes.a_name LIKE '%".mysql_real_escape_string($like)."%'";
- $query = mysql_query($sql, $db_connection);
- if ( ! $query ) return 0;
- if ( mysql_num_rows($query) == NULL ) return 0;
- return mysql_num_rows($query);
- }
- /* check if user allready sent membership request within 24 hours
- user DN, user CA
- return (int) check results:
- 0 - there is no such request
- -1 - request unconfirmed by user
- 1 - request exists */
- function requestExists ( $dn, $ca ) {
- global $db_connection;
- $sql = sprintf("SELECT memb_req.status FROM memb_req WHERE memb_req.dn = '%s' AND memb_req.ca = '%s' AND memb_req.status IN (0,1) AND memb_req.evaluation_date IS NULL AND memb_req.creation_date > NOW() - INTERVAL 1 DAY;", mysql_real_escape_string($dn), mysql_real_escape_string($ca));
- $query = mysql_query($sql, $db_connection);
- if ( ! $query ) return 0;
- if ( mysql_num_rows($query) == NULL ) return 0;
- $row = mysql_fetch_row($query);
- if ( $row[0] == 0 ) return -1;
- return 1;
- }
- /* clear all unconfirmed by user reqests that older then 24 hours */
- function clearPendingRequests () {
- global $db_connection;
- $sql = "DELETE FROM memb_req WHERE memb_req.status = 0 AND memb_req.creation_date < NOW() - INTERVAL 1 DAY";
- return mysql_query($sql, $db_connection);
- }
- /* create new membership request in database
- user DN, user CA, user CN, user e-mail, user institute, user phone, user confirmation ID
- return (int) request id */
- function createNewRequest ( $dn, $ca, $cn, $mail, $inst, $phone, $comments, $confirm_id, $uuids = array() ) {
- global $db_connection;
- $sql = sprintf("INSERT INTO memb_req(creation_date, status, confirm_id, dn, ca, cn, mail, institute, phone, comment) VALUES ( NOW(), 0, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ", mysql_real_escape_string($confirm_id), mysql_real_escape_string($dn), mysql_real_escape_string($ca), mysql_real_escape_string($cn), mysql_real_escape_string($mail), mysql_real_escape_string($inst), mysql_real_escape_string($phone), mysql_real_escape_string($comments) );
- $res = mysql_query($sql, $db_connection);
- if ( $res == 0 ) return 0;
- $req_ins_id = mysql_insert_id();
- $uuids['memb_req'] = UUID4id($req_ins_id, 'memb_req', isset($uuids['memb_req'])?$uuids['memb_req']:0);
- $GLOBALS['ins_id'] = $req_ins_id;
- $GLOBALS['pva_id2uuid_arr'] = $uuids;
- return 1;
- }
- /* get all confirmed by user requests that awaiting for administrator configmation
- return (hash of hash) of requests info [id] => ( [cn] => user CN, [ca] => user CA ) */
- function getVOPendingRequests () {
- global $db_connection;
- clearPendingRequests();
- $sql = "SELECT memb_req.id, memb_req.cn, memb_req.ca FROM memb_req WHERE memb_req.status = 1";
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) == NULL ) return 0;
- while ( $row = mysql_fetch_row($query) ){
- $cacn = CNfromDN($row[2]);
- $result[$row[0]] = array( "cn" => $row[1], "ca" => $cacn );
- }
- return $result;
- }
-
- /* get all requests procesed by administrator
- return (hash of hash) of requests info [id] => ( [cn] => user CN, [ca] => CA DN, [approved] => approvel status ) */
- function getVOProcessedRequests() {
- global $db_connection;
- $sql = "SELECT memb_req.id, memb_req.cn, memb_req.ca, memb_req.status FROM memb_req WHERE memb_req.status IN (2,3)";
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) == NULL ) return 0;
- while ( $row = mysql_fetch_row($query) ){
- $cacn = CNfromDN($row[2]);
- $approved = ( $row[3] == 2 ) ? 1 : 0;
- $result[$row[0]] = array( "cn" => $row[1], "ca" => $cacn, "approved" => $approved );
- }
- return $result;
- }
- /* get detailed request information by ID
- request ID, pending switch
- return (hash) information set ( [dn] => user DN, [cn] => user CN, [ca] => user CA DN,
- [mail] => user e-mail, [inst] => institute, [status] => approval status,
- [cmnt] => comment, [crdate] => request creation date, [evdate] => evaluation date */
- function getReqInfo ( $id, $pending = 0 ) {
- global $db_connection;
- $status = ( $pending == 1 ) ? "IN (2,3)" : "= 1";
- $sql = "SELECT memb_req.dn AS dn, memb_req.cn AS cn, memb_req.ca AS ca, memb_req.mail AS mail, memb_req.institute AS inst, memb_req.status AS status,
- memb_req.phone AS phone, memb_req.comment AS cmnt, memb_req.creation_date AS crdate, memb_req.evaluation_date AS evdate
- FROM memb_req
- WHERE memb_req.id = ".$id." AND memb_req.status " . $status;
- $query = mysql_query($sql, $db_connection);
- if ( ! $query ) return 0;
- if ( mysql_num_rows($query) == NULL ) return 0;
- return mysql_fetch_assoc($query);
- }
-
- /* change request state (approve or decline by administrator)
- if request approved -- create user
- VO name, request ID, new status
- return (bool) operation status */
- function changeRequestState( $vo, $id, $status, $uuids = array()) {
- global $db_connection;
- clearPendingRequests();
- // id2uuid
- if (! id2uuid_convert ('memb_req', $id, $uuids) ) return 0;
- // function description handling
- $req_info = getReqInfo( $id );
- if (! isset($uuids['user_dn'])) $uuids['user_dn'] = $req_info["dn"];
- if (! isset($uuids['user_ca'])) $uuids['user_ca'] = $req_info["ca"];
- $GLOBALS['pva_id2uuid_arr'] = $uuids; // return uuids, but if createUser has called - values will be overwritten
- if ( $status == 2 ) {
- $crures = createUser( $req_info["dn"], $req_info["ca"], $req_info["cn"], $req_info["mail"], $vo, $uuids );
- if ( $crures <= 0 ) return $crures;
- }
- $sql = sprintf("UPDATE memb_req SET memb_req.status = %d, memb_req.evaluation_date = NOW() WHERE memb_req.id = %d AND memb_req.status = 1;", $status, $id);
- if ( ! mysql_query($sql, $db_connection)) return 0;
- return 1;
- }
- /* request confirmation by user
- request ID, user DN, user CA, confirmation code
- return (bool) operation status */
- function confirmRegRequest($reqid, $dn, $ca, $ccode, $uuids = array()) {
- global $db_connection;
- clearPendingRequests();
- // id2uuid
- if (! id2uuid_convert ('memb_req', $reqid, $uuids) ) return 0;
- $sql = sprintf("UPDATE memb_req SET memb_req.status = 1 WHERE memb_req.id = %d AND memb_req.status = 0 AND memb_req.dn = '%s' AND memb_req.ca = '%s' AND memb_req.confirm_id = '%s'", $reqid, mysql_real_escape_string($dn), mysql_real_escape_string($ca), $ccode );
- if ( ! mysql_query($sql, $db_connection) ) return 0;
- if ( ! mysql_affected_rows() ) return 0;
- $GLOBALS['pva_id2uuid_arr'] = $uuids;
- return 1;
- }
- /* delete registration request
- request ID, user DN, user CA, confirmation code
- return (bool) operation status */
- function deleteRegRequest($reqid, $dn, $ca, $ccode, $uuids = array()) {
- global $db_connection;
- // id2uuid
- if (! id2uuid_convert ('memb_req', $id, $uuids) ) return 0;
- $sql = sprintf("DELETE FROM memb_req WHERE memb_req.id = %d AND memb_req.status = 0 AND memb_req.dn = '%s' AND memb_req.ca = '%s' AND memb_req.confirm_id = '%s'", $reqid, $dn, $ca, $ccode );
- if ( ! mysql_query($sql, $db_connection) ) return 0;
- if ( ! mysql_affected_rows() ) return 0;
- $GLOBALS['pva_id2uuid_arr'] = $uuids;
- return 1;
- }
- /* get VO admins e-mails ( select admin only with corresponding ACL )
- return (array of hash) admins of ( [cn] => admin CN, [mail] => admin mail ) */
- function getAdminContacts ($acl = "", $rw = "") {
- global $db_connection;
- $sql = "SELECT admins.dn, admins.email_address, acl2_permissions.permissions FROM admins, acl2_permissions, acl2
- WHERE acl2.group_id = 1 AND acl2.defaultACL = 0 AND acl2.role_id IS NULL
- AND acl2.acl_id = acl2_permissions.acl_id AND acl2_permissions.admin_id = admins.adminid AND admins.email_address IS NOT NULL";
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) == NULL ) return 0;
- while ( $row = mysql_fetch_row($query) ){
- $perms = decodeACLPermissions($row[2]);
- if ( $perms[$acl][$rw] == 0 ) continue;
- $cn = CNfromDN($row[0]);
- $result[] = array( "cn" => $cn, "mail" => $row[1] );
- }
- return $result;
- }
- /* return admin ID by information about it:
- array ( [dn] => admin DN, [caid] => CA ID, [mail] => admin e-mail
- return 0 if admin is not in database
- return (int) admin ID */
- function checkAdminId ( $adminfo ) {
- global $db_connection;
- $sql = sprintf("SELECT admins.adminid FROM admins WHERE admins.dn = '%s'", mysql_real_escape_string($adminfo["dn"]));
- $query = mysql_query($sql, $db_connection);
- if ( ! $query ) return 0;
- if ( ! mysql_num_rows($query) ) return 0;
- $row = mysql_fetch_row($query);
- return $row[0];
- }
- /* create admin by information about it:
- array ( [dn] => admin DN, [caid] => CA ID, [mail] => admin e-mail
- return (int) admin ID */
- function createAdmin ( $adminfo, $uuids = array() ) {
- global $db_connection;
- if ( ! isset($adminfo["mail"]) ) {
- $sql = sprintf("INSERT INTO admins(dn,ca) VALUES ( '%s', %d )",
- mysql_real_escape_string($adminfo["dn"]), mysql_real_escape_string($adminfo["caid"]));
- } else {
- $sql = sprintf("INSERT INTO admins(dn,email_address,ca) VALUES ( '%s', '%s', %d )",
- mysql_real_escape_string($adminfo["dn"]), mysql_real_escape_string($adminfo["mail"]),
- mysql_real_escape_string($adminfo["caid"]));
- }
- if ( ! mysql_query($sql, $db_connection) ) return 0;
- $admin_ins_id = mysql_insert_id();
- $uuids['admins'] = UUID4id($admin_ins_id, 'admins', isset($uuids['admins'])?$uuids['admins']:0);
- $GLOBALS['pva_id2uuid_arr'] = $uuids;
- $GLOBALS['pva_createadmin_insid'] = $admin_ins_id;
- return 1;
- }
- /* get information about admin by admin ID
- return (hash) information ( [cn] => admin CN, [ca] => admin CA */
- function getAdminInfo ( $admid ) {
- global $db_connection;
- $sql = sprintf("SELECT admins.dn, ca.ca FROM admins, ca WHERE admins.adminid = %d AND admins.ca = ca.cid", $admid );
- $query = mysql_query($sql, $db_connection);
- if ( mysql_num_rows($query) == NULL ) return 0;
- $row = mysql_fetch_row($query);
- $cn = CNfromDN($row[0]);
- $cacn = CNfromDN($row[1]);
- return array( "cn" => $cn, "ca" => $cacn );
- }
- /////////////////////////////////////////////////////////////////////
- // RPC handling function
- /////////////////////////////////////////////////////////////////////
- function get_authorized_updator_id($au_ip, $code) {
- global $db_connection;
- $sql = sprintf("SELECT pva_authorized_updators.au_id FROM pva_authorized_updators
- WHERE pva_authorized_updators.ip = '%s' AND pva_authorized_updators.auth_key = '%s'",
- mysql_real_escape_string($au_ip), mysql_real_escape_string($code));
- $query = mysql_query($sql, $db_connection);
- if ( ! $query ) return 0;
- if ( ! mysql_num_rows($query) ) return 0;
- $row = mysql_fetch_row($query);
- return $row[0];
- }
- function get_authorized_updator_status($id) {
- global $db_connection;
- global $regex_digits;
- if ( ! preg_match($regex_digits, $id)) return -1;
- $sql = sprintf("SELECT pva_authorized_updators.status FROM pva_authorized_updators
- WHERE pva_authorized_updators.au_id = %d", $id);
- $query = mysql_query($sql, $db_connection);
- if ( ! $query ) return -1;
- if ( ! mysql_num_rows($query) ) return -1;
- $row = mysql_fetch_row($query);
- return $row[0];
- }
- function get_authorized_updator_by_id ($id) {
- global $db_connection;
- global $regex_digits;
- if ( ! preg_match($regex_digits, $id)) return 0;
- $sql = sprintf("SELECT *, TIMESTAMPDIFF(SECOND,sync_time,CURRENT_TIMESTAMP) AS sync_diff
- FROM pva_authorized_updators
- WHERE pva_authorized_updators.au_id = %d AND pva_authorized_updators.status IN (0,1,2)",$id);
- $query = mysql_query($sql, $db_connection);
- if ( ! $query ) return 0;
- if ( ! mysql_num_rows($query) ) return 0;
- $arr = mysql_fetch_assoc($query);
- return $arr;
- }
- function get_authorized_updators ($account_status=0) {
- global $db_connection;
- $sql = "SELECT *, UNIX_TIMESTAMP(t_stamp) AS ut_stamp, TIMESTAMPDIFF(SECOND,sync_time,CURRENT_TIMESTAMP) AS sync_diff
- FROM pva_authorized_updators WHERE pva_authorized_updators.status";
- if ( $account_status == 1 ) $sql .= " IN (1,2)";
- else if ( $account_status == 2 ) $sql .= " = 2";
- else $sql .= " IN (0,1,2)";
- $query = mysql_query($sql, $db_connection);
- if ( ! $query ) return 0;
- if ( ! mysql_num_rows($query) ) return 0;
- $res = array();
- while ( $arr = mysql_fetch_assoc($query) ){
- $res[] = $arr;
- }
- return $res;
- }
- function add_authorized_updator ($dn, $endpoint, $ip, $adj_code, $repl_code, $cahash) {
- global $db_connection;
- $sql = sprintf("INSERT INTO pva_authorized_updators (status,dn,cahash,ip,endpoint,auth_key,foreign_key,t_stamp)
- VALUES(0,'%s','%s','%s','%s','%s','%s',CURRENT_TIMESTAMP)",
- mysql_real_escape_string($dn),
- mysql_real_escape_string($cahash),
- mysql_real_escape_string($ip),
- mysql_real_escape_string($endpoint),
- mysql_real_escape_string($adj_code),
- mysql_real_escape_string($repl_code));
- if ( ! mysql_query($sql, $db_connection) ) return 0;
- return 1;
- }
- function del_authorized_updator ($id) {
- global $db_connection;
- // instead of removing updator from database completele, changing of the status to smth meaningless performed
- // this method provide database consistency, thus transactions table contain information about transaction source
- global $regex_digits;
- if ( ! preg_match($regex_digits, $id)) return 0;
- if ( $id == 0 ) return 0;
- $sql = sprintf("UPDATE pva_authorized_updators
- SET pva_authorized_updators.status = -1, pva_authorized_updators.auth_key = 'DELETED'
- WHERE pva_authorized_updators.au_id = %d", $id);
- if ( ! mysql_query($sql, $db_connection) ) return 0;
- return 1;
- }
- function update_replication_code($id, $repl_code) {
- global $db_connection;
- if ( $id === 0 ) return 0;
- $sql = sprintf("UPDATE pva_authorized_updators SET status=0, foreign_key='%s' WHERE pva_authorized_updators.au_id = %d",
- mysql_real_escape_string($repl_code), $id);
- if ( ! mysql_query($sql, $db_connection) ) return 0;
- return 1;
- }
- function get_replication_status ($account_status=0) {
- global $db_connection;
- $sql = sprintf("SELECT pva_authorized_updators.au_id FROM pva_authorized_updators");
- if ( $account_status ) $sql .= " WHERE pva_authorized_updators.status IN (1,2)";
- else $sql .= " WHERE pva_authorized_updators.status IN (0,1,2)";
- $query = mysql_query($sql, $db_connection);
- if ( ! $query ) return 0;
- if ( mysql_num_rows($query) ) return 1;
- return 0;
- }
- function set_replication_status ($id, $status) {
- global $db_connection;
- $sql = sprintf("UPDATE pva_authorized_updators SET status=%d WHERE pva_authorized_updators.au_id = %d", $status, $id );
- if ( mysql_query($sql, $db_connection) ) return 1;
- return 0;
- }
- function get_last_transaction_time () {
- global $db_connection;
- $sql = "SELECT UNIX_TIMESTAMP(pva_transactions.t_stamp) FROM pva_transactions ORDER BY t_stamp DESC LIMIT 1";
- $query = mysql_query($sql, $db_connection);
- if ( ! $query ) return 0;
- if ( ! mysql_num_rows($query) ) return 0;
- $row = mysql_fetch_row($query);
- return $row[0];
- }
- function get_transactions_diff ($unixtime) {
- global $db_connection;
- $sql = sprintf("SELECT * FROM pva_transactions WHERE t_stamp > FROM_UNIXTIME('%s') ORDER BY t_stamp ASC", $unixtime);
- $query = mysql_query($sql, $db_connection);
- if ( ! $query ) return 0;
- $trans_arr = array();
- while ($trans = mysql_fetch_array($query)) {
- $trans_arr[] = array ( 'uuid'=>$trans['uuid'],
- 'adminid'=>$trans['adminid'],
- 'fname'=>$trans['fname'],
- 'args'=>$trans['args'] );
- }
- return $trans_arr;
- }
- $vo_replicate_tables_array = array (
- "attributes",
- "ca",
- "capabilities",
- "groups",
- "roles",
- "usr",
- "group_attrs",
- "role_attrs",
- "usr_attrs",
- "admins",
- "m",
- "memb_req",
- "acl2",
- "acl2_permissions",
- "pva_variables",
- "pva_id2uuid_map"
- );
- function get_all_vo_tables () {
- global $db_connection, $vo_replicate_tables_array;
- $all_data = array();
- foreach ( $vo_replicate_tables_array as $tbl ) {
- $tbl_data = array();
- // select all data for each table
- $sql = sprintf("SELECT * FROM `%s`", $tbl);
- $query = mysql_query($sql, $db_connection);
- if ( ! $query ) return 0;
- while ( $qarr = mysql_fetch_assoc($query) ) {
- $tbl_data[] = $qarr;
- }
- // save in resulting array
- $all_data[$tbl] = $tbl_data;
- }
- return $all_data;
- }
- function set_all_vo_tables ($all_data, $id=0) {
- global $db_connection, $vo_replicate_tables_array;
- // start transaction
- mysql_query("START TRANSACTION",$db_connection);
- mysql_query("SET FOREIGN_KEY_CHECKS=0",$db_connection);
- $exit_status = true;
- // drop all tables in the reverse safe-fill order
- foreach ( array_reverse($vo_replicate_tables_array) as $tbl ) {
- // $sql = sprintf( "TRUNCATE TABLE `%s`", $tbl ); // Fasater, but invoke DROP and does not transaction-safe
- $sql = sprintf( "DELETE FROM `%s`", $tbl );
- if ( ! mysql_query($sql, $db_connection) ) {
- $exit_status = false;
- break;
- }
- }
- // fill tables with array data
- if ( $exit_status ) foreach ( $vo_replicate_tables_array as $tbl ) {
- if ( ! array_key_exists($tbl,$all_data) ) {
- $exit_status = false;
- break;
- }
- foreach ( $all_data[$tbl] as $tbl_data ) {
- $sql_keys = sprintf("INSERT INTO `%s`(", $tbl);
- $sql_values = "VALUES(";
- $separator = "";
- foreach ($tbl_data as $k => $v ) {
- $sql_keys .= $separator . "`" . $k . "`";
- if ( $v === NULL ) {
- $sql_values .= $separator . "NULL";
- } else {
- $sql_values .= $separator . "'" . mysql_real_escape_string($v) . "'";
- }
- $separator = ",";
- }
- $sql = $sql_keys . ") " . $sql_values . ")";
- if ( ! mysql_query($sql, $db_connection) ) {
- $exit_status = false;
- break;
- }
- }
- }
- // update adjacency status if id specified
- if ( $exit_status ) if ( $id ) {
- $sql = sprintf("UPDATE pva_authorized_updators SET status=1 WHERE pva_authorized_updators.au_id = %d", $id );
- if ( ! mysql_query($sql, $db_connection) ) $exit_status = false;
- }
- // commit on success
- if ( $exit_status ) {
- mysql_query("COMMIT",$db_connection);
- mysql_query("SET FOREIGN_KEY_CHECKS=1",$db_connection);
- } else mysql_query("ROLLBACK",$db_connection);
- return $exit_status;
- }
- //
- // LOG SUBSYSTEM FUNCTIONS
- //
- function createLogTable () {
- global $db_connection, $pva_log_table_created;
- if ( isset($pva_log_table_created) ) return 1;
- $sql = "CREATE TABLE IF NOT EXISTS `pva_logs` (
- `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
- `level` char(1) NOT NULL,
- `subsys` smallint(5) unsigned NOT NULL,
- `msg_code` int(10) unsigned NOT NULL,
- `msg_parms` text NOT NULL,
- `count` int(10) unsigned NOT NULL DEFAULT '1',
- `first_occured` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
- `last_occured` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
- PRIMARY KEY (`id`),
- KEY `msg_code` (`msg_code`)
- ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1";
- if ( ! mysql_query($sql, $db_connection) ) return 0;
- saveSettingsToDB('pva_log_table_created',1);
- return 1;
- }
- function storeLogRecord ($subsys, $msg_code, $msg_params = array (), $level = 'E') {
- global $db_connection;
- if ( ! createLogTable() ) return 0;
- $s_msg_params = serialize($msg_params);
- $exists = true;
- // check record already exists
- $sql = sprintf("SELECT pva_logs.id, pva_logs.count FROM pva_logs WHERE pva_logs.subsys = %d
- AND pva_logs.msg_code = %d
- AND pva_logs.level = '%s'
- AND pva_logs.msg_parms = '%s'",
- $subsys, $msg_code, $level, mysql_real_escape_string($s_msg_params));
- $query = mysql_query($sql, $db_connection);
- if ( ! $query ) $exists = false;
- if ( $exists ) if ( ! mysql_num_rows($query) ) $exists = false;
- if ( $exists ) {
- $record = mysql_fetch_assoc($query);
- $count = $record['count'] + 1;
- $id = $record['id'];
- $upd_sql = sprintf("UPDATE pva_logs SET pva_logs.count = %d, pva_logs.last_occured = CURRENT_TIMESTAMP
- WHERE pva_logs.id = %d", $count, $id);
- return mysql_query($upd_sql, $db_connection);
- } else {
- $ins_sql = sprintf("INSERT INTO pva_logs(level,subsys,msg_code,msg_parms,last_occured)
- VALUES('%s',%d,%d,'%s',CURRENT_TIMESTAMP)",
- $level, $subsys, $msg_code, mysql_real_escape_string($s_msg_params));
- return mysql_query($ins_sql, $db_connection);
- }
- }
- function getLogRecords () {
- global $db_connection;
- if ( ! createLogTable() ) return 0;
- $sql = "SELECT * FROM pva_logs ORDER BY last_occured DESC";
- $query = mysql_query($sql, $db_connection);
- if ( ! $query ) return 0;
- if ( ! mysql_num_rows($query) ) return 0;
- $result = array ();
- while ( $row = mysql_fetch_assoc($query)) {
- $result[] = array (
- 'id' => $row['id'],
- 'level' => $row['level'],
- 'subsys' => $row['subsys'],
- 'msg_code' => $row['msg_code'],
- 'msg_parms' => unserialize($row['msg_parms']),
- 'count' => $row['count'],
- 'first_occured' => $row['first_occured'],
- 'last_occured' => $row['last_occured']
- );
- }
- return $result;
- }
- function getLogRecordsCount () {
- global $db_connection;
- if ( ! createLogTable() ) return 0;
- $sql = "SELECT SUM(pva_logs.count) FROM pva_logs";
- $query = mysql_query($sql, $db_connection);
- if ( ! $query ) return 0;
- if ( ! mysql_num_rows($query) ) return 0;
- $row = mysql_fetch_row($query);
- return $row[0];
- }
- function removeLogRecords ($ids = array () ){
- global $db_connection;
- if ( empty($ids) ) return 0;
- if ( ! createLogTable() ) return 0;
- $sql = "DELETE FROM pva_logs WHERE pva_logs.id IN (";
- $separator = "";
- foreach ( $ids as $id ) {
- $sql .= $separator . $id;
- $separator = ",";
- }
- $sql .= ")";
- return mysql_query($sql, $db_connection);
- }
- ?>