PageRenderTime 76ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/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
  1. <?php
  2. // Copyright 2010 Andrii Salnikov
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. //
  16. /////////////////////////////////////////////////////////////////////
  17. // Transaction handling wrappers
  18. /////////////////////////////////////////////////////////////////////
  19. /* Invoke specified function and log transaction to database ( admin_id, function_name, arguments )
  20. return invoked function return code */
  21. function _invoke_transactional_sql ( ) {
  22. global $db_connection, $USER_DN;
  23. global $enable_transactions_log;
  24. if ( ! isset($enable_transactions_log) ) $enable_transactions_log = false;
  25. // check author and function name specified
  26. if ( func_num_args() < 3 ) return 0;
  27. if ( $USER_DN === 0 ) return 0;
  28. // get function parameters
  29. $argv = func_get_args();
  30. $updator = array_shift($argv);
  31. $f_name = array_shift($argv);
  32. // begin transaction in SQL
  33. mysql_query("START TRANSACTION",$db_connection);
  34. // invoke function
  35. unset($GLOBALS['pva_id2uuid_arr']);
  36. if ( $argv ) $f_result = call_user_func_array($f_name, $argv);
  37. else $f_result = call_user_func($f_name);
  38. if ( $enable_transactions_log ) {
  39. if ( $f_result === 1 ) {
  40. // add uuids array to the end of the function args before saving to transaction table
  41. if ( isset($GLOBALS['pva_id2uuid_arr']) ) $argv[] = $GLOBALS['pva_id2uuid_arr'];
  42. // write to transactions table
  43. $sql = sprintf("INSERT INTO pva_transactions(adminid, uuid, fname, args, source_id)
  44. VALUES ('%s',UUID(),'%s','%s',%d)",
  45. $USER_DN, $f_name,
  46. base64_encode(serialize($argv)),
  47. $updator);
  48. if ( ! mysql_query($sql, $db_connection) ) {
  49. $f_result = 0;
  50. printf("<p class=\"error\">ERROR: Failed to write transaction log. Performing transaction rollback. </p>");
  51. }
  52. }
  53. }
  54. if ( $f_result === 1 ) mysql_query("COMMIT",$db_connection);
  55. else mysql_query("ROLLBACK",$db_connection);
  56. return $f_result;
  57. }
  58. // invoke function inside transaction (operation source is authorized updator)
  59. function _invoke_transactional_sql_update ( $updator, $admid, $uuid, $f_name, $base64args, $status, $nt_stamp ) {
  60. global $db_connection;
  61. // begin transaction in SQL
  62. mysql_query("START TRANSACTION",$db_connection);
  63. $f_result = 1;
  64. $invoke_error = false;
  65. // write to transactions table (and check if transaction already exists)
  66. $sql = sprintf("INSERT INTO pva_transactions(adminid, uuid, fname, args, source_id)
  67. VALUES ('%s','%s','%s','%s',%d)",
  68. $admid,
  69. $uuid,
  70. $f_name,
  71. $base64args,
  72. $updator);
  73. if ( ! mysql_query($sql, $db_connection) ) {
  74. $op_errno = mysql_errno($db_connection);
  75. if ( $op_errno !== 1062 ) {
  76. //log_pva_error
  77. $invoke_error = array ( 1, 4, array($op_errno));
  78. $f_result = 0;
  79. } else $f_result = 2; // do not ROLLBACK transaction time update on duplicate
  80. }
  81. // invoke function on success
  82. if ( $f_result === 1 ) {
  83. $fargv = unserialize(base64_decode($base64args));
  84. if ( $fargv ) $f_result = call_user_func_array($f_name, $fargv);
  85. else $f_result = call_user_func($f_name);
  86. }
  87. // update last transaction time in updator
  88. if ( $f_result ) {
  89. $sql = sprintf("UPDATE pva_authorized_updators
  90. SET status=2, t_stamp=FROM_UNIXTIME('%s'), sync_time = CURRENT_TIMESTAMP
  91. WHERE pva_authorized_updators.au_id = %d",
  92. $nt_stamp, $updator );
  93. if ( ! mysql_query($sql, $db_connection) ) {
  94. $f_result = 0;
  95. }
  96. } else {
  97. // log_pva_error
  98. $invoke_error = array (1, 3, array ($f_name, var_export($fargv,true)));
  99. }
  100. if ( $f_result ) mysql_query("COMMIT",$db_connection);
  101. else mysql_query("ROLLBACK",$db_connection);
  102. if ( $invoke_error ) call_user_func_array('storeLogRecord',$invoke_error);
  103. return $f_result;
  104. }
  105. // get transactions filtered by limits
  106. function get_transaction_log ( $limit = 0 ) {
  107. global $db_connection;
  108. global $items_per_page;
  109. $sql = "SELECT pva_transactions.t_stamp, pva_transactions.adminid, pva_transactions.fname,
  110. pva_transactions.args, pva_authorized_updators.dn
  111. FROM pva_transactions INNER JOIN pva_authorized_updators
  112. ON pva_transactions.source_id = pva_authorized_updators.au_id
  113. ORDER BY pva_transactions.t_stamp DESC";
  114. $sql .= " LIMIT ". $limit .", ". $items_per_page;
  115. $result = array();
  116. $query = mysql_query($sql, $db_connection);
  117. if ( $query ) if ( mysql_num_rows($query) ) while ( $row = mysql_fetch_assoc($query)) {
  118. $result[] = array (
  119. 'time' => $row['t_stamp'],
  120. 'admdn' => $row['adminid'],
  121. 'fname' => $row['fname'],
  122. 'fargs' => unserialize(base64_decode($row['args'])),
  123. 'upddn' => $row['dn']
  124. );
  125. }
  126. return $result;
  127. }
  128. // update last sync time with updator
  129. function update_transactions_sync_time ($updator) {
  130. global $db_connection;
  131. $sql = sprintf("UPDATE pva_authorized_updators SET sync_time = CURRENT_TIMESTAMP, status=2
  132. WHERE pva_authorized_updators.au_id = %d", $updator );
  133. return mysql_query($sql, $db_connection);
  134. }
  135. // create autorized updators and transactions table
  136. function createTransactionsTables () {
  137. global $db_connection;
  138. $sql = "CREATE TABLE IF NOT EXISTS `pva_authorized_updators` (
  139. `au_id` smallint(6) NOT NULL AUTO_INCREMENT,
  140. `status` tinyint(4) NOT NULL,
  141. `dn` varchar(255) NOT NULL,
  142. `cahash` varchar(10) NOT NULL,
  143. `ip` varchar(16) NOT NULL,
  144. `endpoint` varchar(128) NOT NULL,
  145. `auth_key` varchar(64) NOT NULL,
  146. `foreign_key` varchar(64) NOT NULL,
  147. `t_stamp` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  148. `sync_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  149. PRIMARY KEY (`au_id`)
  150. ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2;";
  151. if ( ! mysql_query($sql, $db_connection) ) return 0;
  152. $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);";
  153. if ( ! mysql_query($sql, $db_connection) ) {
  154. // if already exists - does not report error
  155. if ( mysql_errno($db_connection) !== 1062 ) return 0;
  156. }
  157. $sql = "CREATE TABLE IF NOT EXISTS `pva_transactions` (
  158. `t_stamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  159. `uuid` char(36) NOT NULL,
  160. `adminid` varchar(255) NOT NULL,
  161. `fname` varchar(32) NOT NULL,
  162. `args` text NOT NULL,
  163. `source_id` int(11) NOT NULL,
  164. KEY `t_stamp` (`t_stamp`),
  165. UNIQUE KEY `uuid` (`uuid`)
  166. ) ENGINE=InnoDB DEFAULT CHARSET=latin1;";
  167. if ( ! mysql_query($sql, $db_connection) ) return 0;
  168. return saveSettingsToDB('transactions_tables_created',1);
  169. }
  170. // create table to map autoincremented id to uuid and vice versa
  171. function create_id2uuid_table () {
  172. global $db_connection;
  173. $sql = "CREATE TABLE IF NOT EXISTS `pva_id2uuid_map` (
  174. `id` int(11) NOT NULL,
  175. `table` varchar(36) NOT NULL,
  176. `uuid` varchar(36) NOT NULL,
  177. PRIMARY KEY (`uuid`),
  178. KEY `id` (`id`),
  179. KEY `table` (`table`)
  180. ) ENGINE=InnoDB DEFAULT CHARSET=latin1;";
  181. if ( ! mysql_query($sql, $db_connection) ) return 0;
  182. return 1;
  183. }
  184. // assing uuid map for already existent database ids
  185. function create_id2uuid_data () {
  186. global $db_connection;
  187. $autoincrement_keys = array (
  188. "acl2" => "acl_id",
  189. "admins" => "adminid",
  190. "attributes" => "a_id",
  191. "ca" => "cid",
  192. "capabilities" => "cid",
  193. "groups" => "gid",
  194. "m" => "mapping_id",
  195. "memb_req" => "id",
  196. "roles" => "rid",
  197. "usr" => "userid"
  198. );
  199. foreach ( $autoincrement_keys as $table_name => $key_name ) {
  200. $sql = sprintf("SELECT `%s` FROM `%s`", $key_name, $table_name);
  201. $query = mysql_query($sql, $db_connection);
  202. if ( ! $query ) return 0;
  203. if ( ! mysql_num_rows($query) ) continue;
  204. while ( $row = mysql_fetch_row($query)) UUID4id($row[0],$table_name);
  205. }
  206. return 1;
  207. }
  208. // return UUID value for specified $id in $table
  209. // if map does not exists - function will create it
  210. // if optional $uuid parameter specified - it value will be used on new map creation
  211. function UUID4id($id, $table, $uuid = 0) {
  212. global $db_connection, $id2uuid_map_created;
  213. // if id2uuid mapping is not activated - do not execute function and return 0;
  214. if ( ! isset($id2uuid_map_created) ) return 0;
  215. // check if already exists
  216. $sql = sprintf("SELECT `uuid` FROM pva_id2uuid_map WHERE `id` = %d AND `table` = '%s'", $id, $table);
  217. $query = mysql_query($sql, $db_connection);
  218. if ( ! $query ) return 0;
  219. if ( mysql_num_rows($query) ) {
  220. $row = mysql_fetch_row($query);
  221. return $row[0];
  222. } else { // record does not exists
  223. // set uuid
  224. if ( $uuid ) $sql = sprintf("SET @UD='%s'",$uuid);
  225. else $sql = "SET @UD=UUID()";
  226. $query = mysql_query($sql, $db_connection);
  227. if ( ! $query ) return 0;
  228. // insert uuid to id map
  229. $sql = sprintf("INSERT INTO pva_id2uuid_map(`id`,`table`,`uuid`)
  230. VALUES (%d, '%s', @UD)", $id, $table);
  231. $query = mysql_query($sql, $db_connection);
  232. if ( ! $query ) return 0;
  233. // return uuid value
  234. $sql = "SELECT @UD";
  235. $query = mysql_query($sql, $db_connection);
  236. if ( ! $query ) return 0;
  237. if ( ! mysql_num_rows($query) ) return 0;
  238. $row = mysql_fetch_row($query);
  239. return $row[0];
  240. }
  241. }
  242. // return id for specified uuid
  243. function id4UUID($uuid) {
  244. global $db_connection;
  245. if ( ! $uuid ) return 0;
  246. $sql = sprintf("SELECT id FROM pva_id2uuid_map WHERE `uuid` = '%s'", $uuid );
  247. $query = mysql_query($sql, $db_connection);
  248. if ( ! $query ) return 0;
  249. if ( ! mysql_num_rows($query) ) return 0;
  250. $row = mysql_fetch_row($query);
  251. return $row[0];
  252. }
  253. // set id by uuid (if specified) or set uuid for id
  254. function id2uuid_convert ($table, &$id, &$uuids) {
  255. global $id2uuid_map_created;
  256. // if id2uuid mapping is not activated - do not execute function and return 1;
  257. if ( ! isset($id2uuid_map_created) ) return 1;
  258. if ( isset($uuids[$table]) ) $id = id4UUID($uuids[$table]);
  259. else $uuids[$table] = UUID4id($id, $table);
  260. if ( ! $id ) return 0;
  261. if ( ! $uuids[$table] ) return 0;
  262. return 1;
  263. }
  264. /////////////////////////////////////////////////////////////////////
  265. // VO settings in database
  266. /////////////////////////////////////////////////////////////////////
  267. function getSettingFromDB () {
  268. global $db_connection;
  269. $sql = "SELECT * FROM pva_variables";
  270. $query = mysql_query($sql, $db_connection);
  271. if ( ! $query ) return 0;
  272. while ( $row = mysql_fetch_row($query)) {
  273. $var = $row[0];
  274. $GLOBALS[$var] = $row[1];
  275. }
  276. }
  277. function getVariableFromDB ($var) {
  278. global $db_connection;
  279. $sql = sprintf("SELECT pva_variables.value FROM pva_variables WHERE pva_variables.var = '%s'", $var);
  280. $query = mysql_query($sql, $db_connection);
  281. if ( ! $query ) return NULL;
  282. $row = mysql_fetch_row($query);
  283. return $row[0];
  284. }
  285. function saveSettingsToDB ($var, $value) {
  286. global $db_connection;
  287. if ( getVariableFromDB($var) === NULL ) {
  288. $sql = sprintf("INSERT INTO pva_variables(var,value) VALUES ('%s', '%s')", $var, $value);
  289. } else {
  290. $sql = sprintf("UPDATE pva_variables SET pva_variables.value = '%s' WHERE pva_variables.var = '%s'", $value, $var);
  291. }
  292. if ( ! mysql_query($sql, $db_connection) ) return 0;
  293. return 1;
  294. }
  295. function createSettingTable () {
  296. global $db_connection;
  297. $sql = "CREATE TABLE pva_variables (var VARCHAR(128) NOT NULL, value VARCHAR(255) NOT NULL, UNIQUE KEY var (var)) ENGINE = InnoDB";
  298. return mysql_query($sql,$db_connection);
  299. }
  300. /////////////////////////////////////////////////////////////////////
  301. // SQL for SOAP requests -- VOMSCompatibility.php
  302. /////////////////////////////////////////////////////////////////////
  303. /* Convert request container to array (group, capability, role)
  304. return NULL instead text value of group, capability or role if not present */
  305. function getGroupCapabilityRole ( $container ) {
  306. global $regex_name_set, $regex_name_sset;
  307. $matches = array ();
  308. if ( preg_match("/^((\/".$regex_name_set.")+)(\/Role=".$regex_name_set.")?(\/Capability=".$regex_name_sset.")?$/", $container, $matches ) ) {
  309. // Parse container
  310. $group = $matches[1];
  311. unset($matches[0]);
  312. unset($matches[1]);
  313. unset($matches[2]);
  314. $matchrole = array (); $matchcap = array ();
  315. foreach( $matches as $mv ) {
  316. if ( preg_match("/^\/Role=(".$regex_name_set.")$/", $mv, $matchrole ) ) {
  317. $role = $matchrole[1];
  318. };
  319. if ( preg_match("/^\/Capability=(".$regex_name_sset.")$/", $mv, $matchcap) ) {
  320. $capability = $matchcap[1];
  321. };
  322. }
  323. }
  324. $group = isset($group) ? $group : NULL;
  325. $capability = isset($capability) ? $capability : NULL;
  326. $role = isset($role) ? $role : NULL;
  327. return array($group, $capability, $role);
  328. }
  329. /* get VO members DN list
  330. return (array) array of DN */
  331. function getVOMembers () {
  332. global $db_connection;
  333. $sql = "SELECT usr.dn FROM usr";
  334. $query = mysql_query($sql, $db_connection);
  335. $result = array();
  336. while ( $row = mysql_fetch_row($query)) {
  337. $result[] = $row[0];
  338. }
  339. return $result;
  340. }
  341. /* get number of VO member corresponting specified criterias:
  342. name patern, group ID, role ID
  343. return (int) members count */
  344. function getVOMembersCount ( $like = null, $gid = 0, $rid = 0) {
  345. global $db_connection;
  346. if ( ( $gid !== 0 ) && ( is_numeric($gid)) ) {
  347. if ( ( $rid !== 0 ) && ( is_numeric($rid)) )
  348. $sql_count = "SELECT COUNT(usr.cn) AS cncount FROM usr, m
  349. WHERE m.userid = usr.userid AND m.rid = ".$rid." AND m.cid IS NULL AND m.gid = " . $gid;
  350. else
  351. $sql_count = "SELECT COUNT(usr.cn) AS cncount FROM usr, m
  352. WHERE m.userid = usr.userid AND m.rid IS NULL AND m.cid IS NULL AND m.gid = " . $gid;
  353. } else $sql_count = "SELECT COUNT(usr.cn) AS cncount FROM usr";
  354. if ( $like != null ) $sql_count .= " WHERE usr.cn LIKE '%".mysql_real_escape_string($like)."%'";
  355. $result = mysql_query($sql_count,$db_connection);
  356. if ( ! $result ) return 0;
  357. $count_arr = mysql_fetch_array($result);
  358. return $count_arr["cncount"];
  359. }
  360. /* get VO members DN list coresponding specified criterias:
  361. group name, role name, capability name
  362. return (array) array of DN */
  363. function getVOContainerMembers( $group, $role, $capability ) {
  364. global $db_connection;
  365. $sql = "SELECT usr.dn FROM m, usr, groups";
  366. if ( $role !== NULL ) $sql .= ", roles";
  367. if ( $capability !== NULL ) $sql .= ", capabilities";
  368. $sql .= " WHERE m.userid = usr.userid AND m.gid = groups.gid AND groups.dn = '" . mysql_real_escape_string($group) ."' ";
  369. if ( $role !== NULL ) $sql .= "AND m.rid = roles.rid AND roles.role = '" . mysql_real_escape_string($role) . "' ";
  370. if ( $capability !== NULL ) $sql .= "AND m.cid = capabilities.cid AND capabilities.capability = '" . mysql_real_escape_string($capability) . "' ";
  371. $query = mysql_query($sql, $db_connection);
  372. $result = array();
  373. while ( $row = mysql_fetch_row($query)) {
  374. $result[] = $row[0];
  375. }
  376. return $result;
  377. }
  378. /* return (int) VOMS version from database */
  379. function getVersion() {
  380. global $db_connection;
  381. $sql = "SELECT version.version FROM version";
  382. $query = mysql_query($sql, $db_connection);
  383. $res = mysql_fetch_row($query);
  384. $result = isset($res[0]) ? $res[0] : 0;
  385. return $result;
  386. }
  387. ////////////////////////////////////////////////////////////////
  388. // Non-SQL operations with access rights
  389. // (required before functions inport for SQL operation with ACL
  390. ////////////////////////////////////////////////////////////////
  391. /* Decode permissions intenger to hash
  392. return (hash) of permissions flags */
  393. function decodeACLPermissions ( $permissions ) {
  394. $pstring = sprintf("%021b", $permissions);
  395. $parr["container"]["r"] = $pstring[20];
  396. $parr["container"]["w"] = $pstring[19];
  397. $parr["membership"]["r"] = $pstring[18];
  398. $parr["membership"]["w"] = $pstring[17];
  399. $parr["acl"]["r"] = $pstring[16];
  400. $parr["acl"]["w"] = $pstring[15];
  401. $parr["acl"]["d"] = $pstring[14];
  402. $parr["requests"]["r"] = $pstring[13];
  403. $parr["requests"]["w"] = $pstring[12];
  404. $parr["attributes"]["r"] = $pstring[11];
  405. $parr["attributes"]["w"] = $pstring[10];
  406. $parr["preferences"]["r"] = $pstring[9];
  407. $parr["preferences"]["w"] = $pstring[8];
  408. return $parr;
  409. }
  410. /* Encode permissions hash to database integer
  411. return (int) permissions db value */
  412. function constructACLPermissions( $perm_arr ) {
  413. $perm = 0;
  414. if ( isset( $perm_arr["containerr"] ) ) $perm += 1;
  415. if ( isset( $perm_arr["containerw"] ) ) $perm += 2;
  416. if ( isset( $perm_arr["membershipr"] ) ) $perm += 4;
  417. if ( isset( $perm_arr["membershipw"] ) ) $perm += 8;
  418. if ( isset( $perm_arr["aclr"] ) ) $perm += 16;
  419. if ( isset( $perm_arr["aclw"] ) ) $perm += 32;
  420. if ( isset( $perm_arr["acld"] ) ) $perm += 64;
  421. if ( isset( $perm_arr["requestsr"] ) ) $perm += 128;
  422. if ( isset( $perm_arr["requestsw"] ) ) $perm += 256;
  423. if ( isset( $perm_arr["attributesr"] ) ) $perm += 512;
  424. if ( isset( $perm_arr["attributesw"] ) ) $perm += 1024;
  425. if ( isset( $perm_arr["preferencesr"] ) ) $perm += 2048;
  426. if ( isset( $perm_arr["preferencesw"] ) ) $perm += 4096;
  427. return $perm;
  428. }
  429. //////////////////////////////////////////////////////////////////////////
  430. // SQL operations for PVA web frontend
  431. //////////////////////////////////////////////////////////////////////////
  432. /* get $items_per_page number of VO members coresponding specified parameters:
  433. number of first shown user, user name patern, group ID, role ID
  434. return (array of hash) array of userinfo (cn, ca, database id, dn) */
  435. function getVOMembersCA ($limit = 0, $like = null, $gid = 0, $rid = 0 ) {
  436. global $db_connection;
  437. global $items_per_page;
  438. if ( ( $gid !== 0 ) && ( is_numeric($gid)) ) {
  439. if ( ( $rid !== 0 ) && ( is_numeric($rid)) )
  440. $sql = "SELECT usr.cn, ca.ca, usr.userid, usr.dn FROM usr, ca, m WHERE usr.ca = ca.cid
  441. AND m.userid = usr.userid AND m.rid = ". $rid ." AND m.cid IS NULL AND m.gid = " . $gid;
  442. else
  443. $sql = "SELECT usr.cn, ca.ca, usr.userid, usr.dn FROM usr, ca, m WHERE usr.ca = ca.cid
  444. AND m.userid = usr.userid AND m.rid IS NULL AND m.cid IS NULL AND m.gid = " . $gid;
  445. } else $sql = "SELECT usr.cn, ca.ca, usr.userid, usr.dn FROM usr, ca WHERE usr.ca = ca.cid";
  446. if ( $like != null ) $sql .= " AND usr.cn LIKE '%". mysql_real_escape_string($like) . "%'";
  447. $sql .= " LIMIT ". $limit .", ". $items_per_page;
  448. $query = mysql_query($sql, $db_connection);
  449. $result = array();
  450. if ( ! $query ) return 0;
  451. while ( $row = mysql_fetch_row($query)) {
  452. $cacn = CNfromDN ( $row[1] );
  453. $result[] = array ( "cn" => $row[0], "ca" => $cacn, "id" => $row[2], "dn" => $row[3] );
  454. }
  455. return $result;
  456. }
  457. /* Check if the user have specified attributes in VO:
  458. database user id, group ID, role ID, capability ID
  459. return (bool) check result */
  460. function checkMembership ( $userid, $gid, $role = NULL, $cid = NULL ) {
  461. global $db_connection;
  462. $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") );
  463. $query = mysql_query($sql, $db_connection);
  464. if ( $query == null ) return 0;
  465. return mysql_num_rows($query);
  466. }
  467. /* get access permissions for specified user:
  468. user DN, user CA, membership flag, group ID
  469. return (int) access permissions */
  470. function getProperUserACL ( $dn, $ca, $member = 0, $gid = 1 ) {
  471. global $db_connection, $lastresort_permissions;
  472. $groupn = getGroupById ( $gid );
  473. $caid = getCAId ( $ca );
  474. // First directly check dn
  475. $sql = sprintf("SELECT admins.adminid FROM admins WHERE admins.dn = '%s' AND admins.ca = %d ", mysql_real_escape_string($dn), $caid );
  476. $query = mysql_query($sql, $db_connection);
  477. if ( ! $query ) return 0;
  478. if ( mysql_num_rows($query) ) {
  479. $row = mysql_fetch_row($query);
  480. $perm = getAdminPermissions($gid, $row[0]);
  481. if ( $perm ) return $perm;
  482. }
  483. if ( $member ) {
  484. // Check Role
  485. $roleca = getCAId ( "/O=VOMS/O=System/CN=VOMS Role" );
  486. $sql = sprintf("SELECT admins.dn, admins.adminid
  487. FROM admins
  488. WHERE admins.ca = %d
  489. ORDER BY admins.dn ASC", $roleca );
  490. $query = mysql_query($sql, $db_connection);
  491. if ( mysql_num_rows($query) )
  492. while ( $row = mysql_fetch_row($query) ) {
  493. list($group, $capability, $role) = getGroupCapabilityRole( $row[0] );
  494. //print_r(getGroupCapabilityRole($row[0]));
  495. if ( $group != $groupn ) continue;
  496. if ( checkMembership($member, $gid, getRoleId($role), $capability)) {
  497. $perm = getAdminPermissions($gid, $row[1]);
  498. if ( $perm ) return $perm;
  499. }
  500. }
  501. // Check group
  502. $groupca = getCAId ( "/O=VOMS/O=System/CN=VOMS Group" );
  503. $sql = sprintf("SELECT admins.dn, admins.adminid
  504. FROM admins
  505. WHERE admins.ca = %d
  506. ORDER BY admins.dn ASC", $groupca );
  507. $query = mysql_query($sql, $db_connection);
  508. if ( mysql_num_rows($query) )
  509. while ( $row = mysql_fetch_row($query) ) {
  510. list($group, $capability, $role) = getGroupCapabilityRole( $row[0] );
  511. if ( $group != $groupn ) continue;
  512. if ( checkMembership($member, $gid ) ) {
  513. $perm = getAdminPermissions($gid, $row[1]);
  514. if ( $perm ) return $perm;
  515. }
  516. }
  517. }
  518. // Check any authenticated
  519. if ( ( $dn ) && ( $caid ) ) {
  520. $sql = "SELECT admins.adminid FROM admins WHERE admins.dn = '/O=VOMS/O=System/CN=Any Authenticated User'";
  521. $query = mysql_query($sql, $db_connection);
  522. if ( mysql_num_rows($query) ) {
  523. $row = mysql_fetch_row($query);
  524. $perm = getAdminPermissions($gid, $row[0]);
  525. if ( $perm ) return $perm;
  526. }
  527. }
  528. // If nothing of above -- any user
  529. $sql = "SELECT admins.adminid FROM admins WHERE admins.dn = '/O=VOMS/O=System/CN=Absolutely Anyone'";
  530. $query = mysql_query($sql, $db_connection);
  531. if ( mysql_num_rows($query) ) {
  532. $row = mysql_fetch_row($query);
  533. $perm = getAdminPermissions($gid, $row[0]);
  534. if ( $perm ) return $perm;
  535. }
  536. // Hope this never happened but no permissions if nothing
  537. if ( $gid == 1 ) return $lastresort_permissions;
  538. else return 0;
  539. }
  540. /* check if specified user is a member of VO:
  541. user DN, user CA
  542. return (bool) check result */
  543. function checkMember ( $dn, $ca = 0 ) {
  544. global $db_connection;
  545. $caid = getCAId ( $ca );
  546. // Check membership
  547. if ( $ca === 0 ) $sql = sprintf("SELECT usr.userid FROM usr WHERE usr.dn = '%s'", mysql_real_escape_string($dn));
  548. else $sql = sprintf("SELECT usr.userid FROM usr WHERE usr.dn = '%s' AND usr.ca = %d", mysql_real_escape_string($dn), $caid );
  549. $query = mysql_query($sql, $db_connection);
  550. if ( ! $query ) return 0;
  551. if ( mysql_num_rows($query) ) {
  552. $row = mysql_fetch_row($query);
  553. return $row[0];
  554. } else return 0;
  555. }
  556. /* get list of supported CA
  557. return (array) list of [ca database id] = [ca name] */
  558. function getCAList () {
  559. global $db_connection;
  560. $sql = "SELECT ca.ca, ca.cid FROM ca ";
  561. $query = mysql_query($sql, $db_connection);
  562. $result = array();
  563. while ( $row = mysql_fetch_row($query)) {
  564. $result[$row[1]] = $row[0];
  565. }
  566. return $result;
  567. }
  568. /* function checks for CA .0 files on disk and insert CA record to database on success
  569. return (int) CA database ID */
  570. function addCA ( $cadn, $uuids = array() ) {
  571. global $db_connection, $ca_certificates_path;
  572. if ( ! isset($uuids['ca']) ) {
  573. $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) );
  574. // if not exists in trusted return 0
  575. if ( shell_exec($checkcert_exec) == "" ) return -1;
  576. }
  577. // add to database
  578. $sql = "INSERT INTO ca(ca) VALUES ('". mysql_real_escape_string($cadn) ."')";
  579. if ( ! mysql_query($sql, $db_connection) ) return 0;
  580. $ca_ins_id = mysql_insert_id();
  581. $uuids['ca'] = UUID4id($ca_ins_id, 'ca', isset($uuids['ca'])?$uuids['ca']:0);
  582. $GLOBALS['pva_id2uuid_arr'] = $uuids;
  583. return $ca_ins_id;
  584. }
  585. /* get CA database ID for CA DN:
  586. CA DN
  587. return (int) CA database ID */
  588. function getCAId ( $cadn ) {
  589. global $db_connection;
  590. if ( ! $cadn ) return 0;
  591. // Get CA ID by DN
  592. $sql = "SELECT ca.cid FROM ca WHERE ca.ca = '".mysql_real_escape_string($cadn)."'";
  593. $query = mysql_query($sql, $db_connection);
  594. if ( ! $query ) return 0;
  595. if ( mysql_num_rows($query) !== 0 ) {
  596. $ca_arr = mysql_fetch_row($query);
  597. return $ca_arr[0];
  598. } else return 0;
  599. }
  600. /* get CA name for database ID:
  601. CA database ID
  602. return (string) CA DN */
  603. function getCAName ( $caid ) {
  604. global $db_connection;
  605. if ( ! is_numeric($caid) ) return 0;
  606. $sql = sprintf("SELECT ca.ca FROM ca WHERE ca.cid = %d", $caid);
  607. $query = mysql_query($sql, $db_connection);
  608. if ( ! $query ) return 0;
  609. if ( mysql_num_rows($query) !== 0 ) {
  610. $ca_arr = mysql_fetch_row($query);
  611. return $ca_arr[0];
  612. } else return 0;
  613. }
  614. /* create new VO member with:
  615. user DN, CA DN, user CN, user e-mail, VO name
  616. and add membership to root group /voname
  617. return (bool) operation status */
  618. function createUser ( $dn, $cadn, $cn, $email, $vo, $uuids = array() ) {
  619. global $db_connection;
  620. // id2uuid
  621. if ( ! isset($uuids['usr']) ) $uuids['usr'] = 0;
  622. if ( ! isset($uuids['m']) ) $uuids['m'] = 0;
  623. $ca = getCAId( $cadn );
  624. if ( ! $ca ) {
  625. $ca = addCA($cadn, $uuids);
  626. $uuids = $GLOBALS['pva_id2uuid_arr'];
  627. }
  628. if ( $ca <= 0 ) return $ca;
  629. if ( ! checkMember( $dn ) ) {
  630. $sql = sprintf("INSERT INTO usr(dn,ca,cn,mail) VALUES ('%s',%d,'%s','%s')",
  631. mysql_real_escape_string($dn), $ca, mysql_real_escape_string($cn), mysql_real_escape_string($email));
  632. if ( ! mysql_query($sql, $db_connection) ) return 0;
  633. $usrid = mysql_insert_id();
  634. $uuids['usr'] = UUID4id($usrid,'usr',$uuids['usr']);
  635. $sql = sprintf("INSERT INTO m(userid, gid) SELECT %d, groups.gid FROM groups WHERE groups.dn = '/%s'",
  636. $usrid, mysql_real_escape_string($vo));
  637. if ( ! mysql_query($sql, $db_connection) ) return 0;
  638. $mid = mysql_insert_id();
  639. if ( $mid ) $uuids['m'] = UUID4id($mid, 'm', $uuids['m']);
  640. $GLOBALS['pva_id2uuid_arr'] = $uuids;
  641. return 1;
  642. } else return 0;
  643. }
  644. /* create new role and handle its ACL permissions
  645. role name, VO name
  646. return (bool) operation status */
  647. function createRole ( $crrole, $vo, $uuids = array() ) {
  648. global $db_connection;
  649. // id2uuid
  650. if ( empty($uuids) ) {
  651. $uuids['roles'] = 0;
  652. $empty_uuids = 1;
  653. } else $uuids_empty = 0;
  654. // Check if not exists
  655. $sql = sprintf("SELECT roles.rid FROM roles WHERE roles.role = '%s'", mysql_real_escape_string($crrole) );
  656. $query = mysql_query($sql, $db_connection);
  657. if ( mysql_num_rows($query) !== 0 ) return -1;
  658. // Get all ACLs to clone
  659. $sql = "SELECT acl2.acl_id, acl2.group_id FROM acl2 WHERE acl2.defaultACL = 0 AND acl2.role_id IS NULL";
  660. $query = mysql_query($sql, $db_connection);
  661. if ( mysql_num_rows($query) == 0 ) return 0;
  662. while ( $row = mysql_fetch_row($query) ) {
  663. $gacls[$row[1]] = $row[0];
  664. if ( isset($empty_uuids) ) $uuids["acltc".$row[0]] = 0;
  665. }
  666. // Add record to roles table
  667. $sql = sprintf("INSERT INTO roles(role) VALUES ('%s');", mysql_real_escape_string($crrole));
  668. if ( ! mysql_query($sql, $db_connection) ) return 0;
  669. $roleid = mysql_insert_id();
  670. $uuids['roles'] = UUID4id($roleid, 'roles', $uuids['roles']);
  671. foreach ( $gacls as $groupid => $acltoclone ) {
  672. $sql = sprintf("INSERT INTO acl2(group_id, defaultACL, role_id) VALUES ( %d, 0, %d);", $groupid, $roleid);
  673. if ( ! mysql_query($sql, $db_connection) ) return 0;
  674. $aclid = mysql_insert_id();
  675. $uuids["acltc".$acltoclone] = UUID4id($aclid, 'acl2', $uuids["acltc".$acltoclone]);
  676. $sql2 = sprintf("SELECT acl2_permissions.permissions, acl2_permissions.admin_id
  677. FROM acl2_permissions WHERE acl2_permissions.acl_id = %d", $acltoclone);
  678. $query2 = mysql_query($sql2, $db_connection);
  679. if ( ! $query2 ) return 0;
  680. if ( mysql_num_rows($query2) == 0 ) return 0;
  681. while ( $row2 = mysql_fetch_row($query2) ) {
  682. $sql = sprintf("INSERT INTO acl2_permissions(acl_id, permissions, admin_id)
  683. VALUES (%d, %d, %d);", $aclid, $row2[0], $row2[1]);
  684. if ( ! mysql_query($sql, $db_connection) ) return 0;
  685. }
  686. }
  687. $GLOBALS['pva_id2uuid_arr'] = $uuids;
  688. return 1;
  689. }
  690. /* create new group and handle it ACL permissions (including "default" permissions)
  691. group name, parent group name, vo name
  692. return (bool) operation status */
  693. function createGroup ( $crgrp, $crpgrp, $vo, $uuids = array()) {
  694. global $db_connection;
  695. // id2uuid
  696. if ( empty($uuids) ) {
  697. $uuids['groups'] = 0;
  698. $uuids['acl2'] = 0;
  699. $empty_uuids = 1;
  700. }
  701. // Get parent group name
  702. $sql = "SELECT groups.dn FROM groups WHERE groups.gid = " . $crpgrp;
  703. $query = mysql_query($sql, $db_connection);
  704. if ( mysql_num_rows($query) !== 0 ) {
  705. $row = mysql_fetch_row($query);
  706. $parent_name = $row[0];
  707. } else return 0;
  708. // New group full name
  709. $group_name = $parent_name . "/" . $crgrp;
  710. $uuids['group_name'] = $group_name;
  711. // Check if not allready exists
  712. $sql = "SELECT groups.gid FROM groups WHERE groups.dn = '".mysql_real_escape_string($group_name)."' AND groups.parent = " . $crpgrp . " AND groups.must = 1";
  713. $query = mysql_query($sql, $db_connection);
  714. if ( mysql_num_rows($query) !== 0 ) return 0;
  715. // 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 )
  716. $roles_array = array ( );
  717. $sql = "SELECT roles.rid, roles.role FROM roles";
  718. $query = mysql_query($sql, $db_connection);
  719. if ( mysql_num_rows($query) !== 0 ) {
  720. while ( $row = mysql_fetch_row($query) ) {
  721. $roles_array[$row[1]] = $row[0];
  722. if ( isset($empty_uuids) ) $uuids[$row[1]] = 0;
  723. }
  724. }
  725. // Get ACL for creation
  726. $group_permissions = array ();
  727. // --if exists default ACL for parrent - use it
  728. $sql = "SELECT acl2.acl_id FROM acl2 WHERE acl2.group_id = " . $crpgrp . " AND acl2.defaultACL = 1";
  729. $query = mysql_query($sql, $db_connection);
  730. if ( mysql_num_rows($query) !== 0 ) {
  731. $row = mysql_fetch_row($query);
  732. $aclid = $row[0];
  733. } 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 )
  734. $sql = "SELECT acl2.acl_id FROM acl2 WHERE acl2.group_id = " . $crpgrp . " AND acl2.defaultACL = 0 AND acl2.role_id IS NULL";
  735. $query = mysql_query($sql, $db_connection);
  736. if ( mysql_num_rows($query) == 0 ) return 0;
  737. $row = mysql_fetch_row($query);
  738. $aclid = $row[0];
  739. }
  740. // get stored ACL permissions to apply
  741. $sql = "SELECT acl2_permissions.permissions, acl2_permissions.admin_id FROM acl2_permissions WHERE acl2_permissions.acl_id = " . $aclid;
  742. $query = mysql_query($sql, $db_connection);
  743. if ( mysql_num_rows($query) == 0 ) return 0;
  744. while ( $row = mysql_fetch_row($query) )
  745. $group_permissions[$row[1]] = $row[0];
  746. // Ok, now we have all information required to crete group and all it's acl statemnts -- inserting
  747. // -- insert into group table
  748. $sql = sprintf("INSERT INTO groups(dn, parent, must) VALUES ('%s', %d, 1 );",
  749. mysql_real_escape_string($group_name), $crpgrp);
  750. if ( ! mysql_query($sql, $db_connection) ) return 0;
  751. $groupid = mysql_insert_id();
  752. $uuids['groups'] = UUID4id($groupid, 'groups', $uuids['groups']);
  753. // -- create acl without group
  754. $sql = sprintf("INSERT INTO acl2(group_id, defaultACL, role_id) VALUES( %d, 0, NULL );", $groupid);
  755. if ( ! mysql_query($sql, $db_connection) ) return 0;
  756. $aclid = mysql_insert_id();
  757. $uuids['acl2'] = UUID4id($aclid, 'acl2', $uuids['acl2']);
  758. foreach ( $group_permissions as $gpadmid => $gpp ) {
  759. $asql = sprintf("INSERT INTO acl2_permissions(acl_id, permissions, admin_id)
  760. VALUES ( %d, %d, %d );",$aclid,$gpp,$gpadmid);
  761. if ( ! mysql_query($asql, $db_connection) ) return 0;
  762. }
  763. // -- create acl for each role
  764. foreach ( $roles_array as $rolename => $role ) {
  765. $sql = sprintf("INSERT INTO acl2(group_id, defaultACL, role_id) VALUES( %d, 0, %s );", $groupid, $role );
  766. if ( ! mysql_query($sql, $db_connection) ) return 0;
  767. $aclid = mysql_insert_id();
  768. $uuids[$rolename] = UUID4id($aclid, 'acl2', $uuids[$rolename]);
  769. foreach ( $group_permissions as $gpadmid => $gpp ) {
  770. $asql = sprintf("INSERT INTO acl2_permissions(acl_id, permissions, admin_id)
  771. VALUES ( %d, %d, %d );",$aclid,$gpp,$gpadmid);
  772. if ( ! mysql_query($asql, $db_connection) ) return 0;
  773. }
  774. }
  775. $GLOBALS['pva_id2uuid_arr'] = $uuids;
  776. return 1;
  777. }
  778. /* delete user by user ID
  779. return (bool) operation status */
  780. function deleteUser ($userid, $uuids = array() ) {
  781. global $db_connection;
  782. // id2uuid
  783. if (! id2uuid_convert ('usr', $userid, $uuids) ) return 0;
  784. // function description handling
  785. if (! isset($uuids['userdn']) ) $uuids['userdn'] = getUserDN($userid);
  786. // perform delete user
  787. $sql = array (
  788. "DELETE FROM usr WHERE usr.userid = " . $userid . ";",
  789. "DELETE FROM m WHERE m.userid = " . $userid . ";",
  790. "DELETE FROM usr_attrs WHERE usr_attrs.u_id = " . $userid . ";"
  791. );
  792. foreach ( $sql as $ssql ) {
  793. $result = mysql_query($ssql, $db_connection);
  794. if ( ! $result ) return 0;
  795. }
  796. $GLOBALS['pva_id2uuid_arr'] = $uuids;
  797. return 1;
  798. }
  799. /* delete group by group ID
  800. group ID, VO name
  801. return (int) operation status:
  802. 0 on failure
  803. -1 on child exist
  804. 1 on success */
  805. function deleteGroup ($gid, $vo, $uuids = array() ) {
  806. global $db_connection;
  807. // id2uuid
  808. if (! id2uuid_convert ('groups', $gid, $uuids) ) return 0;
  809. // function description handling
  810. if (! isset($uuids['group_name']) ) $uuids['group_name'] = getGroupById($gid);
  811. // Check for top group
  812. $sql = "SELECT groups.gid FROM groups WHERE groups.gid = ". $gid." AND groups.dn = '/".mysql_real_escape_string($vo)."'";
  813. $query = mysql_query($sql, $db_connection);
  814. if ( mysql_num_rows($query) !== 0 ) return 0;
  815. // Check for child
  816. $sql = "SELECT groups.gid FROM groups WHERE groups.parent = " . $gid;
  817. $query = mysql_query($sql, $db_connection);
  818. if ( mysql_num_rows($query) !== 0 ) return -1;
  819. // Get ACL Ids for group
  820. $sql = "SELECT acl2.acl_id FROM acl2 WHERE acl2.group_id = " . $gid;
  821. $query = mysql_query($sql, $db_connection);
  822. if ( mysql_num_rows($query) == 0 ) return 0;
  823. $sql = array ( "DELETE FROM role_attrs WHERE role_attrs.g_id = " . $gid . ";" );
  824. while ( $row = mysql_fetch_row($query) )
  825. $sql[] = "DELETE FROM acl2_permissions WHERE acl_id = " . $row[0];
  826. $sql[] = "DELETE FROM acl2 WHERE acl2.group_id = " . $gid . ";";
  827. $sql[] = "DELETE FROM groups WHERE groups.gid = " . $gid . ";";
  828. $sql[] = "DELETE FROM group_attrs WHERE group_attrs.g_id = " . $gid . ";";
  829. $sql[] = "DELETE FROM m WHERE m.gid = " . $gid . ";";
  830. foreach ( $sql as $ssql ) {
  831. $result = mysql_query($ssql, $db_connection);
  832. if ( ! $result ) return 0;
  833. }
  834. $GLOBALS['pva_id2uuid_arr'] = $uuids;
  835. return 1;
  836. }
  837. /* delete role by role ID
  838. role ID, VO name
  839. return (bool) operation status */
  840. function deleteRole ($rid, $vo, $uuids = array() ) {
  841. global $db_connection;
  842. // id2uuid
  843. if (! id2uuid_convert ('roles', $rid, $uuids) ) return 0;
  844. // function description handling
  845. if (! isset($uuids['role_name']) ) $uuids['role_name'] = getRoleName($rid);
  846. // Get ACL Ids for role
  847. $sql = "SELECT acl2.acl_id FROM acl2 WHERE acl2.role_id = " . $rid;
  848. $query = mysql_query($sql, $db_connection);
  849. if ( mysql_num_rows($query) == 0 ) return 0;
  850. $sql = array ( "DELETE FROM role_attrs WHERE role_attrs.r_id = " . $rid . ";" );
  851. while ( $row = mysql_fetch_row($query) )
  852. $sql[] = "DELETE FROM acl2_permissions WHERE acl_id = " . $row[0];
  853. $sql[] = "DELETE FROM acl2 WHERE acl2.role_id = " . $rid . ";";
  854. $sql[] = "DELETE FROM m WHERE m.rid = " . $rid . ";";
  855. $sql[] = "DELETE FROM roles WHERE roles.rid = " . $rid . ";";
  856. foreach ( $sql as $ssql ) {
  857. $result = mysql_query($ssql, $db_connection);
  858. if ( ! $result ) return 0;
  859. }
  860. $GLOBALS['pva_id2uuid_arr'] = $uuids;
  861. return 1;
  862. }
  863. /* get user DN by user ID
  864. return (string) user DN */
  865. function getUserDN ( $id ) {
  866. global $db_connection;
  867. $sql = "SELECT usr.dn FROM usr WHERE usr.userid = " . $id;
  868. $query = mysql_query($sql, $db_connection);
  869. if ( ! $query ) return 0;
  870. if ( ! mysql_num_rows($query) ) return 0;
  871. $row = mysql_fetch_row($query);
  872. return $row[0];
  873. }
  874. /* get user information by user ID
  875. return (array) array of (user DN, user CN, CA DN, user e-mail, CA database ID) */
  876. function getUserInfo( $id ) {
  877. global $db_connection;
  878. $sql = "SELECT usr.dn, usr.cn, ca.ca, usr.mail, ca.cid FROM usr, ca WHERE ca.cid = usr.ca AND usr.userid = " . $id;
  879. $query = mysql_query($sql, $db_connection);
  880. $row = mysql_fetch_row($query);
  881. return array( $row[0], $row[1], $row[2], $row[3], $row[4] );
  882. }
  883. /* get information about all users
  884. return (array of hash) */
  885. function getAllUsersInfo( ) {
  886. global $db_connection;
  887. $sql = "SELECT usr.dn, usr.cn, ca.ca, usr.mail, usr.cauri FROM usr, ca WHERE ca.cid = usr.ca";
  888. $query = mysql_query($sql, $db_connection);
  889. if ( ! $query ) return 0;
  890. $result = array();
  891. while ( $row = mysql_fetch_row($query) ){
  892. $result[] = array( "CA" => $row[2], "CN" => $row[1], "DN" => $row[0], "certUri" => $row[4], "mail" => $row[3] );
  893. }
  894. return $result;
  895. }
  896. /* update user CN and e-mail
  897. user ID, new user CN, new user e-mail
  898. return (bool) operation status */
  899. function updateUserInfo( $id , $cn, $mail, $uuids = array() ) {
  900. global $db_connection;
  901. // id2uuid
  902. if (! id2uuid_convert ('usr', $id, $uuids) ) return 0;
  903. // function description handling
  904. if (! isset($uuids['user_dn'])) $uuids['user_dn'] = getUserDN($id);
  905. // perform update
  906. $sql = sprintf("UPDATE usr SET usr.cn = '%s', usr.mail = '%s'
  907. WHERE usr.userid = %s", mysql_real_escape_string($cn), mysql_real_escape_string($mail), $id);
  908. if ( ! mysql_query($sql, $db_connection) ) return 0;
  909. $GLOBALS['pva_id2uuid_arr'] = $uuids;
  910. return 1;
  911. }
  912. /* get $items_per_page number of groups
  913. start from group, name patern
  914. return (array) [group name] = group ID */
  915. function getGroups ( $limit = 0, $like = null ) {
  916. global $db_connection;
  917. global $items_per_page;
  918. $groups = array();
  919. $sql = "SELECT groups.gid, groups.dn FROM groups";
  920. if ( $like !== null ) $sql .= " WHERE groups.dn LIKE '%".mysql_real_escape_string($like)."%'";
  921. $sql .= " LIMIT ". $limit .", ". $items_per_page;
  922. $query = mysql_query($sql, $db_connection);
  923. while ( $row = mysql_fetch_row($query) ){
  924. $groups[$row[1]] = $row[0];
  925. };
  926. return $groups;
  927. }
  928. /* get group name by ID
  929. return (string) group name */
  930. function getGroupById ( $id ) {
  931. global $db_connection;
  932. $sql = sprintf("SELECT groups.dn FROM groups WHERE groups.gid = %d", $id );
  933. $query = mysql_query($sql, $db_connection);
  934. if ( ! $query ) return 0;
  935. if ( mysql_num_rows($query) == 0 ) return 0;
  936. $row = mysql_fetch_row($query);
  937. return $row[0];
  938. }
  939. /* get $items_per_page number of roles
  940. start from role, role name patern
  941. return (array) [role name] = role ID */
  942. function getRoles ( $limit = 0, $like = null ) {
  943. global $db_connection;
  944. global $items_per_page;
  945. $roles = array();
  946. $sql = "SELECT roles.rid, roles.role FROM roles";
  947. if ( $like !== null ) $sql .= " WHERE roles.role LIKE '%".mysql_real_escape_string($like)."%'";
  948. $sql .= " LIMIT ". $limit .", ". $items_per_page;
  949. $query = mysql_query($sql, $db_connection);
  950. while ( $row = mysql_fetch_row($query) ){
  951. $roles[$row[1]] = $row[0];
  952. };
  953. return $roles;
  954. }
  955. /* get number of groups corresponding:
  956. group name pattern
  957. return (int) number of groups */
  958. function getGroupsCount ( $like = null ) {
  959. global $db_connection;
  960. $sql_count = "SELECT COUNT(groups.gid) AS gcount FROM groups";
  961. if ( $like !== null ) $sql_count .= " WHERE groups.dn LIKE '%".mysql_real_escape_string($like)."%'";
  962. $count_arr = mysql_fetch_array(mysql_query($sql_count,$db_connection));
  963. return $count_arr["gcount"];
  964. }
  965. /* get number of roles corresponding:
  966. role name pattern
  967. return (int) number of roles */
  968. function getRolesCount ( $like = null ) {
  969. global $db_connection;
  970. $sql_count = "SELECT COUNT(roles.rid) AS rcount FROM roles";
  971. if ( $like !== null ) $sql_count .= " WHERE roles.role LIKE '%".mysql_real_escape_string($like)."%'";
  972. $count_arr = mysql_fetch_array(mysql_query($sql_count,$db_connection));
  973. return $count_arr["rcount"];
  974. }
  975. /* get role name by ID
  976. return (string) role name */
  977. function getRoleName ( $id ) {
  978. global $db_connection;
  979. if ( ! is_numeric($id) ) return 0;
  980. $sql = "SELECT roles.role FROM roles WHERE roles.rid = " . $id;
  981. $query = mysql_query($sql, $db_connection);
  982. if ( mysql_num_rows($query) == 0 ) return 0;
  983. $row = mysql_fetch_row($query);
  984. return $row[0];
  985. }
  986. /* get role ID by Name
  987. return (int) role ID */
  988. function getRoleId ( $name ) {
  989. global $db_connection;
  990. $sql = "SELECT roles.rid FROM roles WHERE roles.role = '" . mysql_real_escape_string($name) . "'";
  991. $query = mysql_query($sql, $db_connection);
  992. if ( mysql_num_rows($query) == 0 ) return 0;
  993. $row = mysql_fetch_row($query);
  994. return $row[0];
  995. }
  996. /* get ACL id for specified:
  997. group ID, role ID, default flag
  998. return (int) ACL id, 0 if false */
  999. function getACLid ( $gid, $rid, $default ) {
  1000. global $db_connection;
  1001. if ( ! is_numeric($gid) ) return 0;
  1002. if ( $rid !== NULL ) if ( ! is_numeric($rid) ) return 0;
  1003. if ( ! is_numeric($default) ) return 0;
  1004. $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 );
  1005. $query = mysql_query($sql, $db_connection);
  1006. if ( mysql_num_rows($query) == 0 ) return 0;
  1007. $row = mysql_fetch_row($query);
  1008. return $row[0];
  1009. }
  1010. /* get all ACL values for specified ACL id (group and role actually)
  1011. returning set of permissions for each user or role/group having special permissions for this ACL ID
  1012. return (hash of array) [admin CN] = array of (ca, admid, [array of permission categoty] = permissions in human readable format) */
  1013. function getACLvalues ( $id ) {
  1014. global $db_connection;
  1015. if ( ! is_numeric($id) ) return 0;
  1016. $sql = sprintf("SELECT acl2_permissions.permissions, admins.dn, ca.ca, admins.adminid FROM acl2_permissions, admins, ca
  1017. WHERE acl2_permissions.acl_id = %d
  1018. AND acl2_permissions.admin_id = admins.adminid
  1019. AND admins.ca = ca.cid ", $id );
  1020. $query = mysql_query($sql, $db_connection);
  1021. if ( mysql_num_rows($query) == 0 ) return 0;
  1022. $result = array ();
  1023. while ( $row = mysql_fetch_row($query) ) {
  1024. // If Groups and Roles permissions - just print it, otherwise get CN
  1025. $adm_ca = CNfromDN($row[2]);
  1026. if (( $adm_ca === "VOMS Role" ) || ( $adm_ca === "VOMS Group" ) ) $adm_cn = $row[1];
  1027. else $adm_cn = CNfromDN($row[1]);
  1028. // Not listed in interface of original Java-based VOMS-Admin, but present in database
  1029. if ( $adm_cn === "Internal VOMS Process" ) continue;
  1030. if ( $adm_cn === "Local Database Administrator" ) continue;
  1031. if ( $adm_cn === "Absolutely Anyone" ) continue;
  1032. $result[$adm_cn]["ca"] = $adm_ca;
  1033. $result[$adm_cn]["admid"] = $row[3];
  1034. // Decode permissions
  1035. $parr = decodeACLPermissions($row[0]);
  1036. foreach ( $parr as $pcat => $ppa ) {
  1037. $result[$adm_cn][$pcat] = "";
  1038. if ( $ppa["r"] == 1 ) $result[$adm_cn][$pcat] .= "r";
  1039. if ( $ppa["w"] == 1 ) $result[$adm_cn][$pcat] .= "w";
  1040. if (isset($ppa["d"])) if ( $ppa["d"] == 1 ) $result[$adm_cn][$pcat] .= "d";
  1041. }
  1042. }
  1043. return $result;
  1044. }
  1045. /* find all child groups with permission ids for this groups;
  1046. recursive function, that handle information via reference parameters
  1047. processed_parents -- array of allready processed parents (must be empty at first call)
  1048. to_process -- array of [gid] = 1 to processed. To emulate set of elements and quckly check if in set
  1049. acl_ids -- array of ACL ids of all child groups
  1050. */
  1051. function getAllChildren ( &$processed_parents, &$to_process, &$acl_ids ) {
  1052. global $db_connection;
  1053. $pgid = key($to_process);
  1054. $sql = sprintf("SELECT acl2.acl_id, acl2.group_id FROM groups, acl2 WHERE acl2.group_id = groups.gid AND groups.parent = %d", $pgid);
  1055. $query = mysql_query($sql, $db_connection);
  1056. if ( mysql_num_rows($query) == 0 ) return 0;
  1057. while ( $row = mysql_fetch_row($query) ) {
  1058. $acl_ids[] = $row[0];
  1059. if ( ! isset($processed_parents[$row[1]]) ) $to_process[$row[1]] = 1;
  1060. }
  1061. unset($to_process[$pgid]);
  1062. $processed_parents[$pgid] = 1;
  1063. if ( empty($to_process) ) return 0;
  1064. getAllChildren ( $processed_parents, $to_process, $acl_ids );
  1065. }
  1066. /* update ACL permissions for specified
  1067. ACL ID, admin ID, permissions value, propagate to all child flags, group ID, default ACL flag
  1068. return (bool) operation status */
  1069. function updateACLPermissions($aclid, $admid, $perm, $propagate = 0, $gid = 0, $default_acl = 0, $uuids = array() ) {
  1070. global $db_connection;
  1071. // id2uuid
  1072. if (! id2uuid_convert ('acl2', $aclid, $uuids) ) return 0;
  1073. if (! id2uuid_convert ('admins', $admid, $uuids) ) return 0;
  1074. // group id and defaultACL flag
  1075. if ($aclid) {
  1076. // for existed ACL
  1077. $sql = sprintf("SELECT acl2.group_id, acl2.defaultACL FROM acl2 WHERE acl2.acl_id = %d", $aclid);
  1078. $query = mysql_query($sql, $db_connection);
  1079. if ( mysql_num_rows($query) == 0 ) return 0;
  1080. $row = mysql_fetch_row($query);
  1081. $group_id = $row[0];
  1082. $defaultACL = $row[1];
  1083. } else {
  1084. // for new ACL
  1085. $group_id = $gid;
  1086. $defaultACL = $default_acl;
  1087. }
  1088. // function description handling
  1089. if (! isset($uuids['group_name'])) $uuids['group_name'] = getGroupById($group_id);
  1090. if (! isset($uuids['admin_cn'])){
  1091. $adm_info = getAdminInfo($admid);
  1092. $uuids['admin_cn'] = $adm_info['cn'];
  1093. }
  1094. // find ACL (normal/default) for this group
  1095. $acl_ids = array ();
  1096. $sql = sprintf("SELECT acl2.acl_id FROM acl2 WHERE acl2.group_id = %s",$group_id);
  1097. if ( $default_acl ) $sql .= " AND acl2.defaultACL = 1 AND acl2.role_id IS NULL";
  1098. $query = mysql_query($sql, $db_connection);
  1099. // if ACL not found, then create new one
  1100. // store ACL id(s) to array
  1101. if ( mysql_num_rows($query) == 0 ) {
  1102. if ( $default_acl ) {
  1103. $sql = sprintf("INSERT INTO acl2(group_id, defaultACL, role_id) VALUES (%d, 1, NULL)", $group_id);
  1104. if ( ! mysql_query($sql, $db_connection) ) return 0;
  1105. // id2uuid for new ACL
  1106. $acl_ins_id = mysql_insert_id();
  1107. $uuids['acl2_def'] = UUID4id($acl_ins_id, 'acl2', isset($uuids['acl2_def']) ? $uuids['acl2_def'] : 0);
  1108. $acl_ids[] = $acl_ins_id;
  1109. } else return 0;
  1110. } else while ( $row = mysql_fetch_row($query) ) $acl_ids[] = $row[0];
  1111. // get all child group ACLs for this parent when propagate requested
  1112. if ( ( $propagate ) && ( ! $defaultACL ) ) {
  1113. $processed_parents = array ();
  1114. if ($aclid) $to_process[$propagate] = 1; else $to_process[$gid] = 1;
  1115. // add child ACLs to ids array
  1116. getAllChildren ( $processed_parents, $to_process, $acl_ids );
  1117. }
  1118. // create(update) ACL_permissions for every ACL in array for requested admin
  1119. foreach ( array_unique($acl_ids) as $acl_id ) {
  1120. // using UPDATE, MySQL will not update columns where the new value is the same as the old value
  1121. // so SELECT first
  1122. $sql = sprintf("SELECT acl2_permissions.acl_id FROM acl2_permissions
  1123. WHERE acl2_permissions.permissions = %d
  1124. AND acl2_permissions.acl_id = %d
  1125. AND acl2_permissions.admin_id = %d", $perm, $acl_id, $admid);
  1126. $query = mysql_query($sql, $db_connection);
  1127. if ( mysql_num_rows($query) != 0 ) continue;
  1128. // same permissions record not found, trying to update
  1129. $sql = sprintf("UPDATE acl2_permissions
  1130. SET acl2_permissions.permissions = %d
  1131. WHERE acl2_permissions.acl_id = %d
  1132. AND acl2_permissions.admin_id = %d", $perm, $acl_id, $admid);
  1133. mysql_query($sql, $db_connection);
  1134. // if update does not succeed then insert new value
  1135. if ( ! mysql_affected_rows() ) {
  1136. $sql = sprintf("INSERT INTO acl2_permissions(acl_id, permissions, admin_id)
  1137. VALUES (%d, %d, %d)",$acl_id, $perm, $admid);
  1138. if ( ! mysql_query($sql, $db_connection) ) return 0;
  1139. }
  1140. }
  1141. $GLOBALS['pva_id2uuid_arr'] = $uuids;
  1142. return 1;
  1143. }
  1144. /* delete an ACL with specified
  1145. ACL ID, admin ID, remove from all child flag, default ACL flag
  1146. return (bool) operation status */
  1147. function deleteACLentry($aclid, $admid, $propagate = 0, $default = 0, $uuids = array() ) {
  1148. global $db_connection;
  1149. // id2uuid
  1150. if (! id2uuid_convert ('acl2', $aclid, $uuids) ) return 0;
  1151. if (! id2uuid_convert ('admins', $admid, $uuids) ) return 0;
  1152. // function description handling
  1153. if (! isset($uuids['admin_cn'])){
  1154. $adm_info = getAdminInfo($admid);
  1155. $uuids['admin_cn'] = $adm_info['cn'];
  1156. }
  1157. $GLOBALS['pva_id2uuid_arr'] = $uuids;
  1158. // when remove from child requested ( $propagate contain parent group identifier )
  1159. if ( $propagate ) {
  1160. if (! isset($uuids['group_name'])) $uuids['group_name'] = getGroupById($propagate);
  1161. $sql = sprintf("DELETE FROM acl2_permissions
  1162. USING acl2_permissions INNER JOIN acl2 INNER JOIN groups
  1163. WHERE acl2_permissions.acl_id = acl2.acl_id
  1164. AND acl2.group_id = groups.gid
  1165. AND ( groups.parent = %d OR groups.gid = %d )
  1166. AND acl2_permissions.admin_id = %d", $propagate, $propagate, $admid);
  1167. if ( ! mysql_query($sql, $db_connection)) {
  1168. $GLOBALS['pva_id2uuid_arr'] = $uuids;
  1169. return 0;
  1170. } else return 1;
  1171. }
  1172. // delete ACL for admin
  1173. $sql = sprintf("DELETE FROM acl2_permissions
  1174. WHERE acl2_permissions.acl_id = %d
  1175. AND acl2_permissions.admin_id = %d", $aclid, $admid);
  1176. if ( ! mysql_query($sql, $db_connection)) return 0;
  1177. // get group and defaultACL flag from aclid
  1178. $sql = sprintf("SELECT acl2.group_id, acl2.defaultACL
  1179. FROM acl2
  1180. WHERE acl2.acl_id = %d", $aclid);
  1181. $query = mysql_query($sql, $db_connection);
  1182. if ( mysql_num_rows($query) == 0 ) return 0;
  1183. $row = mysql_fetch_row($query);
  1184. $group_id = $row[0];
  1185. $default = $row[1];
  1186. // function description handling
  1187. if (! isset($uuids['group_name'])) $uuids['group_name'] = getGroupById($group_id);
  1188. $GLOBALS['pva_id2uuid_arr'] = $uuids;
  1189. // if ACLs permissions records for other admins not exist -- delete record in ACL table
  1190. if ( mysql_affected_rows() ) {
  1191. if ( $default ) {
  1192. $sql = sprintf("SELECT acl2_permissions.acl_id FROM acl2_permissions
  1193. WHERE acl2_permissions.acl_id = %d ", $aclid);
  1194. $query = mysql_query($sql, $db_connection);
  1195. if ( mysql_num_rows($query) ) { return 1; } else {
  1196. $sql = sprintf("DELETE FROM acl2 WHERE acl2.acl_id = %d AND acl2.defaultACL = 1", $aclid);
  1197. if ( ! mysql_query($sql, $db_connection)) return 0;
  1198. if ( mysql_affected_rows() ) return 1;
  1199. return 0;
  1200. }
  1201. } else return 1;
  1202. } else return 0;
  1203. }
  1204. /* get permissions numerical value for
  1205. ACL ID, admin ID
  1206. return (int) permissions database value */
  1207. function getPermissions ( $aclid, $admid ) {
  1208. global $db_connection;
  1209. $sql = sprintf("SELECT acl2_permissions.permissions FROM acl2_permissions
  1210. WHERE acl2_permissions.acl_id = %d
  1211. AND acl2_permissions.admin_id = %d",$aclid,$admid);
  1212. $query = mysql_query($sql, $db_connection);
  1213. if ( mysql_num_rows($query) == 0 ) return 0;
  1214. $row = mysql_fetch_row($query);
  1215. return $row[0];
  1216. }
  1217. /* get permissions numerical value for specified
  1218. group ID, admin ID
  1219. return (int) permissions database value */
  1220. function getAdminPermissions( $gid, $admid) {
  1221. global $db_connection;
  1222. $sql = sprintf("SELECT acl2_permissions.permissions FROM acl2_permissions
  1223. INNER JOIN acl2 ON acl2_permissions.acl_id = acl2.acl_id
  1224. WHERE acl2.group_id = %d
  1225. AND acl2.role_id IS NULL
  1226. AND acl2_permissions.admin_id = %d
  1227. AND acl2.defaultACL = 0",
  1228. $gid, $admid);
  1229. $query = mysql_query($sql, $db_connection);
  1230. if ( mysql_num_rows($query) == 0 ) return 0;
  1231. $row = mysql_fetch_row($query);
  1232. return $row[0];
  1233. }
  1234. /* get group characteristics for specified ACL ID
  1235. return (hash) group parameters ([gid] => group ID, [gdn] => group name, [default] => default ACL) */
  1236. function getACLGroup ( $aclid ) {
  1237. global $db_connection;
  1238. $sql = sprintf("SELECT acl2.group_id, groups.dn, acl2.defaultACL
  1239. FROM acl2, groups
  1240. WHERE acl2.group_id = groups.gid AND acl2.acl_id = %d", $aclid );
  1241. $query = mysql_query($sql, $db_connection);
  1242. if ( mysql_num_rows($query) == 0 ) return 0;
  1243. $row = mysql_fetch_row($query);
  1244. return array( "gid" => $row[0], "gdn" => $row[1], "default" => $row[2] );
  1245. }
  1246. /* get user roles in groups by user ID
  1247. return (hash) [group][role] = role */
  1248. function getUserMembership ( $id ) {
  1249. global $db_connection;
  1250. $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";
  1251. $query = mysql_query($sql, $db_connection);
  1252. if ( ! $query ) return 0;
  1253. $result = array();
  1254. while ($row = mysql_fetch_row($query)){
  1255. $result[$row[0]][$row[1]] = $row[1];
  1256. }
  1257. return $result;
  1258. }
  1259. /* add user membership in group with role:
  1260. group ID, user ID, role ID (optional)
  1261. return (bool) operation status */
  1262. function addMembership ( $gid, $uid, $rid = 0, $uuids = array() ) {
  1263. global $db_connection;
  1264. // id2uuid
  1265. if (! id2uuid_convert ('groups', $gid, $uuids) ) return 0;
  1266. if (! id2uuid_convert ('usr', $uid, $uuids) ) return 0;
  1267. if ( $rid !== 0 ) if (! id2uuid_convert ('roles', $rid, $uuids) ) return 0;
  1268. // function description handling
  1269. if (! isset($uuids['user_name']) ) $uuids['user_name'] = getUserDN($uid);
  1270. if (! isset($uuids['group_name']) ) $uuids['group_name'] = getGroupById($gid);
  1271. if ( $rid !== 0 ) if (! isset($uuids['role_name']) ) $uuids['role_name'] = getRoleName($rid);
  1272. // Check for allready exists
  1273. $sql = "SELECT m.mapping_id FROM m WHERE m.userid = ".$uid." AND m.gid = ".$gid;
  1274. if ( $rid !== 0 ) $sql .= " AND m.rid = ".$rid;
  1275. $query = mysql_query($sql, $db_connection);
  1276. if ( mysql_num_rows($query) !== 0 ) return -1;
  1277. if ( $rid !== 0 ) $sql = "INSERT INTO m ( userid, gid, rid ) VALUES ( ".$uid.", ". $gid .", ". $rid ." )";
  1278. else $sql = "INSERT INTO m ( userid, gid ) VALUES ( ".$uid.", ". $gid ." )";
  1279. if ( ! mysql_query($sql, $db_connection) ) return 0;
  1280. $GLOBALS['pva_id2uuid_arr'] = $uuids;
  1281. return 1;
  1282. }
  1283. /* remove user membersip in group with role
  1284. group ID, user ID, role ID (optional)
  1285. return (bool) operation status */
  1286. function delMembership ( $gid, $uid, $rid = 0, $uuids = array() ) {
  1287. global $db_connection;
  1288. // id2uuid
  1289. if (! id2uuid_convert ('groups', $gid, $uuids) ) return 0;
  1290. if (! id2uuid_convert ('usr', $uid, $uuids) ) return 0;
  1291. if ( $rid !== 0 ) if (! id2uuid_convert ('roles', $rid, $uuids) ) return 0;
  1292. // function description handling
  1293. if (! isset($uuids['user_name']) ) $uuids['user_name'] = getUserDN($uid);
  1294. if (! isset($uuids['group_name']) ) $uuids['group_name'] = getGroupById($gid);
  1295. if ( $rid !== 0 ) if (! isset($uuids['role_name']) ) $uuids['role_name'] = getRoleName($rid);
  1296. $sql = "SELECT m.mapping_id FROM m WHERE m.userid = ".$uid." AND m.gid = ".$gid;
  1297. if ( $rid !== 0 ) $sql .= " AND m.rid = ".$rid;
  1298. $query = mysql_query($sql, $db_connection);
  1299. if ( mysql_num_rows($query) == 0 ) return -1;
  1300. $sql = "DELETE FROM m WHERE m.userid = ".$uid." AND m.gid = ".$gid;
  1301. if ( $rid !== 0 ) $sql .= " AND m.rid = ".$rid;
  1302. if ( ! mysql_query($sql, $db_connection) ) return 0;
  1303. $GLOBALS['pva_id2uuid_arr'] = $uuids;
  1304. return 1;
  1305. }
  1306. /* check user/group attribute exists (by reference return unique flag)
  1307. attribute ID, user/group ID, &unique flag, user/group switch
  1308. return (bool) check result */
  1309. function checkAttrExists ( $aid, $uid, &$uniq, $wt = "u" ) {
  1310. global $db_connection;
  1311. if ( $wt === "u" ) { $dbn = "usr_attrs"; $dbuid = "u_id"; } else
  1312. if ( $wt === "g" ) { $dbn = "group_attrs"; $dbuid = "g_id"; } else
  1313. return 0;
  1314. $sql = "SELECT attributes.a_uniq FROM attributes WHERE attributes.a_id = ". $aid;
  1315. $query = mysql_query($sql, $db_connection);
  1316. if ( mysql_num_rows($query) != NULL ) {
  1317. $row = mysql_fetch_row($query);
  1318. $uniq = $row[0];
  1319. $sql = sprintf("SELECT %s.a_id FROM %s WHERE %s.a_id = %d AND %s.%s = %d", $dbn, $dbn, $dbn, $aid, $dbn, $dbuid, $uid);
  1320. $query = mysql_query($sql, $db_connection);
  1321. if ( mysql_num_rows($query) != NULL ) return 1;
  1322. }
  1323. return 0;
  1324. }
  1325. /* check role attribute exists (by reference return unique flag)
  1326. attribute ID, role ID, group ID, &unique flag
  1327. return (bool) check result */
  1328. function checkRoleAttrExists( $aid, $rid, $gid, &$uniq) {
  1329. global $db_connection;
  1330. $sql = "SELECT attributes.a_uniq FROM attributes WHERE attributes.a_id = ". $aid;
  1331. $query = mysql_query($sql, $db_connection);
  1332. if ( mysql_num_rows($query) != NULL ) {
  1333. $row = mysql_fetch_row($query);
  1334. $uniq = $row[0];
  1335. $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);
  1336. $query = mysql_query($sql, $db_connection);
  1337. if ( mysql_num_rows($query) != NULL ) return 1;
  1338. }
  1339. return 0;
  1340. }
  1341. /* check if attribute is unique for user/group
  1342. attribute ID, attribute value, user/group switch
  1343. return (bool) check result */
  1344. function checkUniqAttr ( $aid, $value, $wt = "u" ) {
  1345. global $db_connection;
  1346. if ( $wt === "u" ) $dbn = "usr_attrs"; else
  1347. if ( $wt === "g" ) $dbn = "group_attrs"; else
  1348. return 0;
  1349. $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)) ;
  1350. $query = mysql_query($sql, $db_connection);
  1351. if ( mysql_num_rows($query) != NULL ) return 0;
  1352. return 1;
  1353. }
  1354. /* check if attribute is unique for role
  1355. attribute ID, group ID, attrubute value
  1356. return (bool) check result */
  1357. function checkRoleUniqAttr ( $aid, $gid, $value ) {
  1358. global $db_connection;
  1359. $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));
  1360. $query = mysql_query($sql, $db_connection);
  1361. if ( mysql_num_rows($query) != NULL ) return 0;
  1362. return 1;
  1363. }
  1364. /* get attribute name by attribute id
  1365. attribute ID
  1366. return (string) attribute name */
  1367. function getAttributeName ( $aid ) {
  1368. global $db_connection;
  1369. $sql = "SELECT attributes.a_name FROM attributes WHERE attributes.a_id = " . $aid;
  1370. $query = mysql_query($sql, $db_connection);
  1371. if ( ! $query ) return 0;
  1372. if ( ! mysql_num_rows($query) ) return 0;
  1373. $row = mysql_fetch_row($query);
  1374. return $row[0];
  1375. }
  1376. /* add attribute for user/group
  1377. attribute ID, user/group ID, attribute value, user/group switch
  1378. return (bool) operation status */
  1379. function addAttribute ( $aid, $uid, $value, $wt = "u", $uuids = array() ) {
  1380. global $db_connection;
  1381. // id2uuid
  1382. if (! id2uuid_convert ('attributes', $aid, $uuids) ) return 0;
  1383. if ( $wt === "u" ) {
  1384. $dbn = "usr_attrs"; $dbuid = "u_id";
  1385. if (! id2uuid_convert ('usr', $uid, $uuids) ) return 0;
  1386. } else if ( $wt === "g" ) {
  1387. $dbn = "group_attrs"; $dbuid = "g_id";
  1388. if (! id2uuid_convert ('groups', $uid, $uuids) ) return 0;
  1389. } else return 0;
  1390. // function description handling
  1391. if (! isset($uuids['attr_name'])) $uuids['attr_name'] = getAttributeName($aid);
  1392. if ( $wt === "u" ) if (! isset($uuids['user_name'])) $uuids['user_name'] = getUserDN($uid); else
  1393. if ( $wt === "g" ) if (! isset($uuids['group_name'])) $uuids['group_name'] = getGroupById($uid);
  1394. $uniq = 0;
  1395. $exists = checkAttrExists( $aid, $uid, $uniq, $wt );
  1396. if ( $uniq == 1 ) if ( ! checkUniqAttr( $aid, $value, $wt ) ) return -1;
  1397. if ( $exists ) {
  1398. $sql = sprintf("UPDATE %s SET %s.a_value = '%s' WHERE %s.a_id = %d AND %s.%s = %d",
  1399. $dbn, $dbn, mysql_real_escape_string($value), $dbn, $aid, $dbn, $dbuid, $uid);
  1400. } else {
  1401. $sql = sprintf("INSERT INTO %s(a_id, %s, a_value) VALUES ( %d, %d, '%s' )",
  1402. $dbn, $dbuid, $aid, $uid, mysql_real_escape_string($value) );
  1403. }
  1404. if ( ! mysql_query($sql, $db_connection) ) return 0;
  1405. $GLOBALS['pva_id2uuid_arr'] = $uuids;
  1406. return 1;
  1407. }
  1408. /* delete attribute for user/group
  1409. attribute ID, user/group ID, user/group switch
  1410. return (bool) operation status */
  1411. function delAttribute ( $aid, $uid, $wt = "u", $uuids = array() ) {
  1412. global $db_connection;
  1413. // id2uuid
  1414. if (! id2uuid_convert ('attributes', $aid, $uuids) ) return 0;
  1415. if ( $wt === "u" ) {
  1416. $dbn = "usr_attrs"; $dbuid = "u_id";
  1417. if (! id2uuid_convert ('usr', $uid, $uuids) ) return 0;
  1418. } else if ( $wt === "g" ) {
  1419. $dbn = "group_attrs"; $dbuid = "g_id";
  1420. if (! id2uuid_convert ('groups', $uid, $uuids) ) return 0;
  1421. } else return 0;
  1422. // function description handling
  1423. if (! isset($uuids['attr_name'])) $uuids['attr_name'] = getAttributeName($aid);
  1424. if ( $wt === "u" ) if (! isset($uuids['user_name'])) $uuids['user_name'] = getUserDN($uid); else
  1425. if ( $wt === "g" ) if (! isset($uuids['group_name'])) $uuids['group_name'] = getGroupById($uid);
  1426. $sql = sprintf("DELETE FROM %s WHERE %s.a_id = %d AND %s.%s = %d", $dbn, $dbn, $aid, $dbn, $dbuid, $uid);
  1427. if ( ! mysql_query($sql, $db_connection) ) return 0;
  1428. $GLOBALS['pva_id2uuid_arr'] = $uuids;
  1429. return 1;
  1430. }
  1431. /* add attribute for role
  1432. attribute ID, role ID, group ID, attribure value
  1433. return (bool) operation status */
  1434. function addRoleAttribute ($aid, $rid, $gid, $value, $uuids = array()) {
  1435. global $db_connection;
  1436. // id2uuid
  1437. if (! id2uuid_convert ('attributes', $aid, $uuids) ) return 0;
  1438. if (! id2uuid_convert ('roles', $rid, $uuids) ) return 0;
  1439. if (! id2uuid_convert ('groups', $gid, $uuids) ) return 0;
  1440. // function description handling
  1441. if (! isset($uuids['attr_name'])) $uuids['attr_name'] = getAttributeName($aid);
  1442. if (! isset($uuids['role_name'])) $uuids['role_name'] = getRoleName($rid);
  1443. if (! isset($uuids['group_name'])) $uuids['group_name'] = getGroupById($gid);
  1444. $uniq = 0;
  1445. $exists = checkRoleAttrExists( $aid, $rid, $gid, $uniq);
  1446. if ( $uniq == 1 ) if ( ! checkRoleUniqAttr( $aid, $gid, $value ) ) return -1;
  1447. if ( $exists )
  1448. $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);
  1449. else
  1450. $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) );
  1451. if ( ! mysql_query($sql, $db_connection) ) return 0;
  1452. $GLOBALS['pva_id2uuid_arr'] = $uuids;
  1453. return 1;
  1454. }
  1455. /* delete attribute for role
  1456. attribute ID, role ID, group ID
  1457. return (bool) operation status */
  1458. function delRoleAttribute ($aid, $rid, $gid, $uuids = array()) {
  1459. global $db_connection;
  1460. // id2uuid
  1461. if (! id2uuid_convert ('attributes', $aid, $uuids) ) return 0;
  1462. if (! id2uuid_convert ('roles', $rid, $uuids) ) return 0;
  1463. if (! id2uuid_convert ('groups', $gid, $uuids) ) return 0;
  1464. // function description handling
  1465. if (! isset($uuids['attr_name'])) $uuids['attr_name'] = getAttributeName($aid);
  1466. if (! isset($uuids['role_name'])) $uuids['role_name'] = getRoleName($rid);
  1467. if (! isset($uuids['group_name'])) $uuids['group_name'] = getGroupById($gid);
  1468. $sql = sprintf("DELETE FROM role_attrs WHERE role_attrs.a_id = %d AND role_attrs.r_id = %d AND role_attrs.g_id = %d",
  1469. $aid, $rid, $gid);
  1470. if ( ! mysql_query($sql, $db_connection) ) return 0;
  1471. $GLOBALS['pva_id2uuid_arr'] = $uuids;
  1472. return 1;
  1473. }
  1474. /* delete attribute from VO database by attribute ID
  1475. return (bool) operation status */
  1476. function delVOAttribute ($aid, $uuids = array()) {
  1477. global $db_connection;
  1478. // id2uuid
  1479. if (! id2uuid_convert ('attributes', $aid, $uuids) ) return 0;
  1480. // function description handling
  1481. if (! isset($uuids['attr_name'])) $uuids['attr_name'] = getAttributeName($aid);
  1482. $sql = array ( "DELETE FROM role_attrs WHERE role_attrs.a_id = " . $aid . ";",
  1483. "DELETE FROM group_attrs WHERE group_attrs.a_id = " . $aid . ";",
  1484. "DELETE FROM usr_attrs WHERE usr_attrs.a_id = " . $aid . ";",
  1485. "DELETE FROM attributes WHERE attributes.a_id = " . $aid . ";"
  1486. );
  1487. foreach ( $sql as $ssql ) {
  1488. $result = mysql_query($ssql, $db_connection);
  1489. if ( ! $result ) return 0;
  1490. }
  1491. $GLOBALS['pva_id2uuid_arr'] = $uuids;
  1492. return 1;
  1493. }
  1494. /* add attribute to VO database
  1495. attribute name, attribute descriptiom, unique flag
  1496. return (bool) operation status */
  1497. function addVOAttribute($attrname, $attrdescr, $attruniq, $uuids = array()) {
  1498. global $db_connection;
  1499. $sql = sprintf("SELECT attributes.a_id FROM attributes WHERE attributes.a_name = '%s' AND attributes.a_uniq = %d ",
  1500. mysql_real_escape_string($attrname), $attruniq);
  1501. $query = mysql_query($sql, $db_connection);
  1502. if ( ! mysql_num_rows($query) ) {
  1503. // Attribute doesnot exists - chech the same name but different uniq
  1504. $sql = sprintf("SELECT attributes.a_id FROM attributes WHERE attributes.a_name = '%s'",
  1505. mysql_real_escape_string($attrname) );
  1506. $query = mysql_query($sql, $db_connection);
  1507. if ( ! mysql_num_rows($query) ) {
  1508. // All clear - create new
  1509. $sql = sprintf("INSERT INTO attributes(a_name, a_desc, a_uniq) VALUES ('%s', '%s', %d)",
  1510. mysql_real_escape_string($attrname), mysql_real_escape_string($attrdescr), $attruniq);
  1511. if ( ! mysql_query($sql, $db_connection) ) return 0;
  1512. $attr_ins_id = mysql_insert_id();
  1513. $uuids['attrs'] = UUID4id($attr_ins_id, 'attributes', isset($uuids['attrs'])?$uuids['attrs']:0);
  1514. $GLOBALS['pva_id2uuid_arr'] = $uuids;
  1515. } else return -1;
  1516. } else {
  1517. $row = mysql_fetch_row($query);
  1518. $sql = sprintf("UPDATE attributes SET attributes.a_desc = '%s' WHERE attributes.a_id = %d",
  1519. mysql_real_escape_string($attrdescr), $row[0] );
  1520. if ( ! mysql_query($sql, $db_connection) ) return 0;
  1521. }
  1522. return 1;
  1523. }
  1524. /* get all attributes for user by user ID
  1525. return (hash) of attributes ( [name] => name, [value] => value ) */
  1526. function getUserAttributes ( $uid ) {
  1527. global $db_connection;
  1528. $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;
  1529. $query = mysql_query($sql, $db_connection);
  1530. if ( mysql_num_rows($query) == NULL ) return 0;
  1531. $result = array ();
  1532. while ( $row = mysql_fetch_row($query)) {
  1533. $result[$row[0]] = array ( "name" => $row[1], "value" => $row[2] );
  1534. }
  1535. return $result;
  1536. }
  1537. /* get all attributes for group by group ID
  1538. return (hash) of attributes ( [name] => name, [value] => value ) */
  1539. function getGroupAttributes ( $gid ) {
  1540. global $db_connection;
  1541. $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;
  1542. $query = mysql_query($sql, $db_connection);
  1543. if ( mysql_num_rows($query) == NULL ) return 0;
  1544. $result = array ();
  1545. while ( $row = mysql_fetch_row($query)) {
  1546. $result[$row[0]] = array ( "name" => $row[1], "value" => $row[2] );
  1547. }
  1548. return $result;
  1549. }
  1550. /* get all attributes for role by role ID
  1551. return (hash) of attributes ( [name] => name, [value] => value, [group], [groupid], [aid] ) */
  1552. function getRoleAttributes ( $rid ) {
  1553. global $db_connection;
  1554. $sql = "SELECT attributes.a_id, attributes.a_name, role_attrs.a_value, groups.dn, groups.gid FROM attributes, role_attrs, groups
  1555. WHERE attributes.a_id = role_attrs.a_id AND role_attrs.g_id = groups.gid
  1556. AND role_attrs.r_id = ".$rid;
  1557. $query = mysql_query($sql, $db_connection);
  1558. if ( mysql_num_rows($query) == NULL ) return 0;
  1559. $result = array ();
  1560. $i = 0;
  1561. while ( $row = mysql_fetch_row($query)) {
  1562. $result[$i++] = array ( "name" => $row[1], "value" => $row[2], "group" => $row[3], "groupid" => $row[4], "aid" => $row[0] );
  1563. }
  1564. return $result;
  1565. }
  1566. /* get all attributes in VO database
  1567. return (hash) of all attributes parameters ( [name] => name, [descr] => description, [uniq] => unique flag ) */
  1568. function getAttributes ( ){
  1569. global $db_connection;
  1570. $sql = "SELECT attributes.a_id, attributes.a_name, attributes.a_desc, attributes.a_uniq FROM attributes";
  1571. $query = mysql_query($sql, $db_connection);
  1572. if ( mysql_num_rows($query) == NULL ) return 0;
  1573. $result = array ();
  1574. while ( $row = mysql_fetch_row($query)) {
  1575. $result[$row[0]] = array ( "name" => $row[1], "descr" => $row[2], "uniq" => $row[3] );
  1576. }
  1577. return $result;
  1578. }
  1579. /* get $items_per_page users that have assigned attributes
  1580. start record to show, name patern
  1581. return (hash) of ( [attr] => attribute name, [attrv] => attribute value, [cn] => user CN, [ca] => user CA, [usrid] => user ID )*/
  1582. function getAllUserAttributes( $limit = 0, $like = null ) {
  1583. global $db_connection;
  1584. global $items_per_page;
  1585. $attributes = array();
  1586. $sql = "SELECT attributes.a_name, usr_attrs.a_value, usr.dn, ca.ca, usr.userid FROM attributes, usr_attrs, usr, ca
  1587. WHERE usr_attrs.a_id = attributes.a_id AND usr_attrs.u_id = usr.userid
  1588. AND usr.ca = ca.cid";
  1589. if ( $like != null ) $sql .= " AND attributes.a_name LIKE '%".mysql_real_escape_string($like)."%'";
  1590. $sql .= " LIMIT ". $limit .", ". $items_per_page;
  1591. $query = mysql_query($sql, $db_connection);
  1592. $i = 0;
  1593. while ( $row = mysql_fetch_row($query) ){
  1594. $usrcn = CNfromDN($row[2]);
  1595. $cacn = CNfromDN($row[3]);
  1596. $attributes[$i++] = array ( "attr" => $row[0], "attrv" => $row[1], "cn" => $usrcn, "ca" => $cacn, "usrid" => $row[4] );
  1597. };
  1598. return $attributes;
  1599. }
  1600. /* get number of all attributes records
  1601. attribute name pattern
  1602. return (int) attribute records count */
  1603. function getAllUserAttributesCount( $like = null ){
  1604. global $db_connection;
  1605. $attributes = array();
  1606. $sql = "SELECT attributes.a_name, usr_attrs.a_value, usr.dn, ca.ca, usr.userid FROM attributes, usr_attrs, usr, ca
  1607. WHERE usr_attrs.a_id = attributes.a_id AND usr_attrs.u_id = usr.userid
  1608. AND usr.ca = ca.cid";
  1609. if ( $like != null ) $sql .= " AND attributes.a_name LIKE '%".mysql_real_escape_string($like)."%'";
  1610. $query = mysql_query($sql, $db_connection);
  1611. if ( ! $query ) return 0;
  1612. if ( mysql_num_rows($query) == NULL ) return 0;
  1613. return mysql_num_rows($query);
  1614. }
  1615. /* check if user allready sent membership request within 24 hours
  1616. user DN, user CA
  1617. return (int) check results:
  1618. 0 - there is no such request
  1619. -1 - request unconfirmed by user
  1620. 1 - request exists */
  1621. function requestExists ( $dn, $ca ) {
  1622. global $db_connection;
  1623. $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));
  1624. $query = mysql_query($sql, $db_connection);
  1625. if ( ! $query ) return 0;
  1626. if ( mysql_num_rows($query) == NULL ) return 0;
  1627. $row = mysql_fetch_row($query);
  1628. if ( $row[0] == 0 ) return -1;
  1629. return 1;
  1630. }
  1631. /* clear all unconfirmed by user reqests that older then 24 hours */
  1632. function clearPendingRequests () {
  1633. global $db_connection;
  1634. $sql = "DELETE FROM memb_req WHERE memb_req.status = 0 AND memb_req.creation_date < NOW() - INTERVAL 1 DAY";
  1635. return mysql_query($sql, $db_connection);
  1636. }
  1637. /* create new membership request in database
  1638. user DN, user CA, user CN, user e-mail, user institute, user phone, user confirmation ID
  1639. return (int) request id */
  1640. function createNewRequest ( $dn, $ca, $cn, $mail, $inst, $phone, $comments, $confirm_id, $uuids = array() ) {
  1641. global $db_connection;
  1642. $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) );
  1643. $res = mysql_query($sql, $db_connection);
  1644. if ( $res == 0 ) return 0;
  1645. $req_ins_id = mysql_insert_id();
  1646. $uuids['memb_req'] = UUID4id($req_ins_id, 'memb_req', isset($uuids['memb_req'])?$uuids['memb_req']:0);
  1647. $GLOBALS['ins_id'] = $req_ins_id;
  1648. $GLOBALS['pva_id2uuid_arr'] = $uuids;
  1649. return 1;
  1650. }
  1651. /* get all confirmed by user requests that awaiting for administrator configmation
  1652. return (hash of hash) of requests info [id] => ( [cn] => user CN, [ca] => user CA ) */
  1653. function getVOPendingRequests () {
  1654. global $db_connection;
  1655. clearPendingRequests();
  1656. $sql = "SELECT memb_req.id, memb_req.cn, memb_req.ca FROM memb_req WHERE memb_req.status = 1";
  1657. $query = mysql_query($sql, $db_connection);
  1658. if ( mysql_num_rows($query) == NULL ) return 0;
  1659. while ( $row = mysql_fetch_row($query) ){
  1660. $cacn = CNfromDN($row[2]);
  1661. $result[$row[0]] = array( "cn" => $row[1], "ca" => $cacn );
  1662. }
  1663. return $result;
  1664. }
  1665. /* get all requests procesed by administrator
  1666. return (hash of hash) of requests info [id] => ( [cn] => user CN, [ca] => CA DN, [approved] => approvel status ) */
  1667. function getVOProcessedRequests() {
  1668. global $db_connection;
  1669. $sql = "SELECT memb_req.id, memb_req.cn, memb_req.ca, memb_req.status FROM memb_req WHERE memb_req.status IN (2,3)";
  1670. $query = mysql_query($sql, $db_connection);
  1671. if ( mysql_num_rows($query) == NULL ) return 0;
  1672. while ( $row = mysql_fetch_row($query) ){
  1673. $cacn = CNfromDN($row[2]);
  1674. $approved = ( $row[3] == 2 ) ? 1 : 0;
  1675. $result[$row[0]] = array( "cn" => $row[1], "ca" => $cacn, "approved" => $approved );
  1676. }
  1677. return $result;
  1678. }
  1679. /* get detailed request information by ID
  1680. request ID, pending switch
  1681. return (hash) information set ( [dn] => user DN, [cn] => user CN, [ca] => user CA DN,
  1682. [mail] => user e-mail, [inst] => institute, [status] => approval status,
  1683. [cmnt] => comment, [crdate] => request creation date, [evdate] => evaluation date */
  1684. function getReqInfo ( $id, $pending = 0 ) {
  1685. global $db_connection;
  1686. $status = ( $pending == 1 ) ? "IN (2,3)" : "= 1";
  1687. $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,
  1688. memb_req.phone AS phone, memb_req.comment AS cmnt, memb_req.creation_date AS crdate, memb_req.evaluation_date AS evdate
  1689. FROM memb_req
  1690. WHERE memb_req.id = ".$id." AND memb_req.status " . $status;
  1691. $query = mysql_query($sql, $db_connection);
  1692. if ( ! $query ) return 0;
  1693. if ( mysql_num_rows($query) == NULL ) return 0;
  1694. return mysql_fetch_assoc($query);
  1695. }
  1696. /* change request state (approve or decline by administrator)
  1697. if request approved -- create user
  1698. VO name, request ID, new status
  1699. return (bool) operation status */
  1700. function changeRequestState( $vo, $id, $status, $uuids = array()) {
  1701. global $db_connection;
  1702. clearPendingRequests();
  1703. // id2uuid
  1704. if (! id2uuid_convert ('memb_req', $id, $uuids) ) return 0;
  1705. // function description handling
  1706. $req_info = getReqInfo( $id );
  1707. if (! isset($uuids['user_dn'])) $uuids['user_dn'] = $req_info["dn"];
  1708. if (! isset($uuids['user_ca'])) $uuids['user_ca'] = $req_info["ca"];
  1709. $GLOBALS['pva_id2uuid_arr'] = $uuids; // return uuids, but if createUser has called - values will be overwritten
  1710. if ( $status == 2 ) {
  1711. $crures = createUser( $req_info["dn"], $req_info["ca"], $req_info["cn"], $req_info["mail"], $vo, $uuids );
  1712. if ( $crures <= 0 ) return $crures;
  1713. }
  1714. $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);
  1715. if ( ! mysql_query($sql, $db_connection)) return 0;
  1716. return 1;
  1717. }
  1718. /* request confirmation by user
  1719. request ID, user DN, user CA, confirmation code
  1720. return (bool) operation status */
  1721. function confirmRegRequest($reqid, $dn, $ca, $ccode, $uuids = array()) {
  1722. global $db_connection;
  1723. clearPendingRequests();
  1724. // id2uuid
  1725. if (! id2uuid_convert ('memb_req', $reqid, $uuids) ) return 0;
  1726. $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 );
  1727. if ( ! mysql_query($sql, $db_connection) ) return 0;
  1728. if ( ! mysql_affected_rows() ) return 0;
  1729. $GLOBALS['pva_id2uuid_arr'] = $uuids;
  1730. return 1;
  1731. }
  1732. /* delete registration request
  1733. request ID, user DN, user CA, confirmation code
  1734. return (bool) operation status */
  1735. function deleteRegRequest($reqid, $dn, $ca, $ccode, $uuids = array()) {
  1736. global $db_connection;
  1737. // id2uuid
  1738. if (! id2uuid_convert ('memb_req', $id, $uuids) ) return 0;
  1739. $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 );
  1740. if ( ! mysql_query($sql, $db_connection) ) return 0;
  1741. if ( ! mysql_affected_rows() ) return 0;
  1742. $GLOBALS['pva_id2uuid_arr'] = $uuids;
  1743. return 1;
  1744. }
  1745. /* get VO admins e-mails ( select admin only with corresponding ACL )
  1746. return (array of hash) admins of ( [cn] => admin CN, [mail] => admin mail ) */
  1747. function getAdminContacts ($acl = "", $rw = "") {
  1748. global $db_connection;
  1749. $sql = "SELECT admins.dn, admins.email_address, acl2_permissions.permissions FROM admins, acl2_permissions, acl2
  1750. WHERE acl2.group_id = 1 AND acl2.defaultACL = 0 AND acl2.role_id IS NULL
  1751. AND acl2.acl_id = acl2_permissions.acl_id AND acl2_permissions.admin_id = admins.adminid AND admins.email_address IS NOT NULL";
  1752. $query = mysql_query($sql, $db_connection);
  1753. if ( mysql_num_rows($query) == NULL ) return 0;
  1754. while ( $row = mysql_fetch_row($query) ){
  1755. $perms = decodeACLPermissions($row[2]);
  1756. if ( $perms[$acl][$rw] == 0 ) continue;
  1757. $cn = CNfromDN($row[0]);
  1758. $result[] = array( "cn" => $cn, "mail" => $row[1] );
  1759. }
  1760. return $result;
  1761. }
  1762. /* return admin ID by information about it:
  1763. array ( [dn] => admin DN, [caid] => CA ID, [mail] => admin e-mail
  1764. return 0 if admin is not in database
  1765. return (int) admin ID */
  1766. function checkAdminId ( $adminfo ) {
  1767. global $db_connection;
  1768. $sql = sprintf("SELECT admins.adminid FROM admins WHERE admins.dn = '%s'", mysql_real_escape_string($adminfo["dn"]));
  1769. $query = mysql_query($sql, $db_connection);
  1770. if ( ! $query ) return 0;
  1771. if ( ! mysql_num_rows($query) ) return 0;
  1772. $row = mysql_fetch_row($query);
  1773. return $row[0];
  1774. }
  1775. /* create admin by information about it:
  1776. array ( [dn] => admin DN, [caid] => CA ID, [mail] => admin e-mail
  1777. return (int) admin ID */
  1778. function createAdmin ( $adminfo, $uuids = array() ) {
  1779. global $db_connection;
  1780. if ( ! isset($adminfo["mail"]) ) {
  1781. $sql = sprintf("INSERT INTO admins(dn,ca) VALUES ( '%s', %d )",
  1782. mysql_real_escape_string($adminfo["dn"]), mysql_real_escape_string($adminfo["caid"]));
  1783. } else {
  1784. $sql = sprintf("INSERT INTO admins(dn,email_address,ca) VALUES ( '%s', '%s', %d )",
  1785. mysql_real_escape_string($adminfo["dn"]), mysql_real_escape_string($adminfo["mail"]),
  1786. mysql_real_escape_string($adminfo["caid"]));
  1787. }
  1788. if ( ! mysql_query($sql, $db_connection) ) return 0;
  1789. $admin_ins_id = mysql_insert_id();
  1790. $uuids['admins'] = UUID4id($admin_ins_id, 'admins', isset($uuids['admins'])?$uuids['admins']:0);
  1791. $GLOBALS['pva_id2uuid_arr'] = $uuids;
  1792. $GLOBALS['pva_createadmin_insid'] = $admin_ins_id;
  1793. return 1;
  1794. }
  1795. /* get information about admin by admin ID
  1796. return (hash) information ( [cn] => admin CN, [ca] => admin CA */
  1797. function getAdminInfo ( $admid ) {
  1798. global $db_connection;
  1799. $sql = sprintf("SELECT admins.dn, ca.ca FROM admins, ca WHERE admins.adminid = %d AND admins.ca = ca.cid", $admid );
  1800. $query = mysql_query($sql, $db_connection);
  1801. if ( mysql_num_rows($query) == NULL ) return 0;
  1802. $row = mysql_fetch_row($query);
  1803. $cn = CNfromDN($row[0]);
  1804. $cacn = CNfromDN($row[1]);
  1805. return array( "cn" => $cn, "ca" => $cacn );
  1806. }
  1807. /////////////////////////////////////////////////////////////////////
  1808. // RPC handling function
  1809. /////////////////////////////////////////////////////////////////////
  1810. function get_authorized_updator_id($au_ip, $code) {
  1811. global $db_connection;
  1812. $sql = sprintf("SELECT pva_authorized_updators.au_id FROM pva_authorized_updators
  1813. WHERE pva_authorized_updators.ip = '%s' AND pva_authorized_updators.auth_key = '%s'",
  1814. mysql_real_escape_string($au_ip), mysql_real_escape_string($code));
  1815. $query = mysql_query($sql, $db_connection);
  1816. if ( ! $query ) return 0;
  1817. if ( ! mysql_num_rows($query) ) return 0;
  1818. $row = mysql_fetch_row($query);
  1819. return $row[0];
  1820. }
  1821. function get_authorized_updator_status($id) {
  1822. global $db_connection;
  1823. global $regex_digits;
  1824. if ( ! preg_match($regex_digits, $id)) return -1;
  1825. $sql = sprintf("SELECT pva_authorized_updators.status FROM pva_authorized_updators
  1826. WHERE pva_authorized_updators.au_id = %d", $id);
  1827. $query = mysql_query($sql, $db_connection);
  1828. if ( ! $query ) return -1;
  1829. if ( ! mysql_num_rows($query) ) return -1;
  1830. $row = mysql_fetch_row($query);
  1831. return $row[0];
  1832. }
  1833. function get_authorized_updator_by_id ($id) {
  1834. global $db_connection;
  1835. global $regex_digits;
  1836. if ( ! preg_match($regex_digits, $id)) return 0;
  1837. $sql = sprintf("SELECT *, TIMESTAMPDIFF(SECOND,sync_time,CURRENT_TIMESTAMP) AS sync_diff
  1838. FROM pva_authorized_updators
  1839. WHERE pva_authorized_updators.au_id = %d AND pva_authorized_updators.status IN (0,1,2)",$id);
  1840. $query = mysql_query($sql, $db_connection);
  1841. if ( ! $query ) return 0;
  1842. if ( ! mysql_num_rows($query) ) return 0;
  1843. $arr = mysql_fetch_assoc($query);
  1844. return $arr;
  1845. }
  1846. function get_authorized_updators ($account_status=0) {
  1847. global $db_connection;
  1848. $sql = "SELECT *, UNIX_TIMESTAMP(t_stamp) AS ut_stamp, TIMESTAMPDIFF(SECOND,sync_time,CURRENT_TIMESTAMP) AS sync_diff
  1849. FROM pva_authorized_updators WHERE pva_authorized_updators.status";
  1850. if ( $account_status == 1 ) $sql .= " IN (1,2)";
  1851. else if ( $account_status == 2 ) $sql .= " = 2";
  1852. else $sql .= " IN (0,1,2)";
  1853. $query = mysql_query($sql, $db_connection);
  1854. if ( ! $query ) return 0;
  1855. if ( ! mysql_num_rows($query) ) return 0;
  1856. $res = array();
  1857. while ( $arr = mysql_fetch_assoc($query) ){
  1858. $res[] = $arr;
  1859. }
  1860. return $res;
  1861. }
  1862. function add_authorized_updator ($dn, $endpoint, $ip, $adj_code, $repl_code, $cahash) {
  1863. global $db_connection;
  1864. $sql = sprintf("INSERT INTO pva_authorized_updators (status,dn,cahash,ip,endpoint,auth_key,foreign_key,t_stamp)
  1865. VALUES(0,'%s','%s','%s','%s','%s','%s',CURRENT_TIMESTAMP)",
  1866. mysql_real_escape_string($dn),
  1867. mysql_real_escape_string($cahash),
  1868. mysql_real_escape_string($ip),
  1869. mysql_real_escape_string($endpoint),
  1870. mysql_real_escape_string($adj_code),
  1871. mysql_real_escape_string($repl_code));
  1872. if ( ! mysql_query($sql, $db_connection) ) return 0;
  1873. return 1;
  1874. }
  1875. function del_authorized_updator ($id) {
  1876. global $db_connection;
  1877. // instead of removing updator from database completele, changing of the status to smth meaningless performed
  1878. // this method provide database consistency, thus transactions table contain information about transaction source
  1879. global $regex_digits;
  1880. if ( ! preg_match($regex_digits, $id)) return 0;
  1881. if ( $id == 0 ) return 0;
  1882. $sql = sprintf("UPDATE pva_authorized_updators
  1883. SET pva_authorized_updators.status = -1, pva_authorized_updators.auth_key = 'DELETED'
  1884. WHERE pva_authorized_updators.au_id = %d", $id);
  1885. if ( ! mysql_query($sql, $db_connection) ) return 0;
  1886. return 1;
  1887. }
  1888. function update_replication_code($id, $repl_code) {
  1889. global $db_connection;
  1890. if ( $id === 0 ) return 0;
  1891. $sql = sprintf("UPDATE pva_authorized_updators SET status=0, foreign_key='%s' WHERE pva_authorized_updators.au_id = %d",
  1892. mysql_real_escape_string($repl_code), $id);
  1893. if ( ! mysql_query($sql, $db_connection) ) return 0;
  1894. return 1;
  1895. }
  1896. function get_replication_status ($account_status=0) {
  1897. global $db_connection;
  1898. $sql = sprintf("SELECT pva_authorized_updators.au_id FROM pva_authorized_updators");
  1899. if ( $account_status ) $sql .= " WHERE pva_authorized_updators.status IN (1,2)";
  1900. else $sql .= " WHERE pva_authorized_updators.status IN (0,1,2)";
  1901. $query = mysql_query($sql, $db_connection);
  1902. if ( ! $query ) return 0;
  1903. if ( mysql_num_rows($query) ) return 1;
  1904. return 0;
  1905. }
  1906. function set_replication_status ($id, $status) {
  1907. global $db_connection;
  1908. $sql = sprintf("UPDATE pva_authorized_updators SET status=%d WHERE pva_authorized_updators.au_id = %d", $status, $id );
  1909. if ( mysql_query($sql, $db_connection) ) return 1;
  1910. return 0;
  1911. }
  1912. function get_last_transaction_time () {
  1913. global $db_connection;
  1914. $sql = "SELECT UNIX_TIMESTAMP(pva_transactions.t_stamp) FROM pva_transactions ORDER BY t_stamp DESC LIMIT 1";
  1915. $query = mysql_query($sql, $db_connection);
  1916. if ( ! $query ) return 0;
  1917. if ( ! mysql_num_rows($query) ) return 0;
  1918. $row = mysql_fetch_row($query);
  1919. return $row[0];
  1920. }
  1921. function get_transactions_diff ($unixtime) {
  1922. global $db_connection;
  1923. $sql = sprintf("SELECT * FROM pva_transactions WHERE t_stamp > FROM_UNIXTIME('%s') ORDER BY t_stamp ASC", $unixtime);
  1924. $query = mysql_query($sql, $db_connection);
  1925. if ( ! $query ) return 0;
  1926. $trans_arr = array();
  1927. while ($trans = mysql_fetch_array($query)) {
  1928. $trans_arr[] = array ( 'uuid'=>$trans['uuid'],
  1929. 'adminid'=>$trans['adminid'],
  1930. 'fname'=>$trans['fname'],
  1931. 'args'=>$trans['args'] );
  1932. }
  1933. return $trans_arr;
  1934. }
  1935. $vo_replicate_tables_array = array (
  1936. "attributes",
  1937. "ca",
  1938. "capabilities",
  1939. "groups",
  1940. "roles",
  1941. "usr",
  1942. "group_attrs",
  1943. "role_attrs",
  1944. "usr_attrs",
  1945. "admins",
  1946. "m",
  1947. "memb_req",
  1948. "acl2",
  1949. "acl2_permissions",
  1950. "pva_variables",
  1951. "pva_id2uuid_map"
  1952. );
  1953. function get_all_vo_tables () {
  1954. global $db_connection, $vo_replicate_tables_array;
  1955. $all_data = array();
  1956. foreach ( $vo_replicate_tables_array as $tbl ) {
  1957. $tbl_data = array();
  1958. // select all data for each table
  1959. $sql = sprintf("SELECT * FROM `%s`", $tbl);
  1960. $query = mysql_query($sql, $db_connection);
  1961. if ( ! $query ) return 0;
  1962. while ( $qarr = mysql_fetch_assoc($query) ) {
  1963. $tbl_data[] = $qarr;
  1964. }
  1965. // save in resulting array
  1966. $all_data[$tbl] = $tbl_data;
  1967. }
  1968. return $all_data;
  1969. }
  1970. function set_all_vo_tables ($all_data, $id=0) {
  1971. global $db_connection, $vo_replicate_tables_array;
  1972. // start transaction
  1973. mysql_query("START TRANSACTION",$db_connection);
  1974. mysql_query("SET FOREIGN_KEY_CHECKS=0",$db_connection);
  1975. $exit_status = true;
  1976. // drop all tables in the reverse safe-fill order
  1977. foreach ( array_reverse($vo_replicate_tables_array) as $tbl ) {
  1978. // $sql = sprintf( "TRUNCATE TABLE `%s`", $tbl ); // Fasater, but invoke DROP and does not transaction-safe
  1979. $sql = sprintf( "DELETE FROM `%s`", $tbl );
  1980. if ( ! mysql_query($sql, $db_connection) ) {
  1981. $exit_status = false;
  1982. break;
  1983. }
  1984. }
  1985. // fill tables with array data
  1986. if ( $exit_status ) foreach ( $vo_replicate_tables_array as $tbl ) {
  1987. if ( ! array_key_exists($tbl,$all_data) ) {
  1988. $exit_status = false;
  1989. break;
  1990. }
  1991. foreach ( $all_data[$tbl] as $tbl_data ) {
  1992. $sql_keys = sprintf("INSERT INTO `%s`(", $tbl);
  1993. $sql_values = "VALUES(";
  1994. $separator = "";
  1995. foreach ($tbl_data as $k => $v ) {
  1996. $sql_keys .= $separator . "`" . $k . "`";
  1997. if ( $v === NULL ) {
  1998. $sql_values .= $separator . "NULL";
  1999. } else {
  2000. $sql_values .= $separator . "'" . mysql_real_escape_string($v) . "'";
  2001. }
  2002. $separator = ",";
  2003. }
  2004. $sql = $sql_keys . ") " . $sql_values . ")";
  2005. if ( ! mysql_query($sql, $db_connection) ) {
  2006. $exit_status = false;
  2007. break;
  2008. }
  2009. }
  2010. }
  2011. // update adjacency status if id specified
  2012. if ( $exit_status ) if ( $id ) {
  2013. $sql = sprintf("UPDATE pva_authorized_updators SET status=1 WHERE pva_authorized_updators.au_id = %d", $id );
  2014. if ( ! mysql_query($sql, $db_connection) ) $exit_status = false;
  2015. }
  2016. // commit on success
  2017. if ( $exit_status ) {
  2018. mysql_query("COMMIT",$db_connection);
  2019. mysql_query("SET FOREIGN_KEY_CHECKS=1",$db_connection);
  2020. } else mysql_query("ROLLBACK",$db_connection);
  2021. return $exit_status;
  2022. }
  2023. //
  2024. // LOG SUBSYSTEM FUNCTIONS
  2025. //
  2026. function createLogTable () {
  2027. global $db_connection, $pva_log_table_created;
  2028. if ( isset($pva_log_table_created) ) return 1;
  2029. $sql = "CREATE TABLE IF NOT EXISTS `pva_logs` (
  2030. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  2031. `level` char(1) NOT NULL,
  2032. `subsys` smallint(5) unsigned NOT NULL,
  2033. `msg_code` int(10) unsigned NOT NULL,
  2034. `msg_parms` text NOT NULL,
  2035. `count` int(10) unsigned NOT NULL DEFAULT '1',
  2036. `first_occured` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  2037. `last_occured` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  2038. PRIMARY KEY (`id`),
  2039. KEY `msg_code` (`msg_code`)
  2040. ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1";
  2041. if ( ! mysql_query($sql, $db_connection) ) return 0;
  2042. saveSettingsToDB('pva_log_table_created',1);
  2043. return 1;
  2044. }
  2045. function storeLogRecord ($subsys, $msg_code, $msg_params = array (), $level = 'E') {
  2046. global $db_connection;
  2047. if ( ! createLogTable() ) return 0;
  2048. $s_msg_params = serialize($msg_params);
  2049. $exists = true;
  2050. // check record already exists
  2051. $sql = sprintf("SELECT pva_logs.id, pva_logs.count FROM pva_logs WHERE pva_logs.subsys = %d
  2052. AND pva_logs.msg_code = %d
  2053. AND pva_logs.level = '%s'
  2054. AND pva_logs.msg_parms = '%s'",
  2055. $subsys, $msg_code, $level, mysql_real_escape_string($s_msg_params));
  2056. $query = mysql_query($sql, $db_connection);
  2057. if ( ! $query ) $exists = false;
  2058. if ( $exists ) if ( ! mysql_num_rows($query) ) $exists = false;
  2059. if ( $exists ) {
  2060. $record = mysql_fetch_assoc($query);
  2061. $count = $record['count'] + 1;
  2062. $id = $record['id'];
  2063. $upd_sql = sprintf("UPDATE pva_logs SET pva_logs.count = %d, pva_logs.last_occured = CURRENT_TIMESTAMP
  2064. WHERE pva_logs.id = %d", $count, $id);
  2065. return mysql_query($upd_sql, $db_connection);
  2066. } else {
  2067. $ins_sql = sprintf("INSERT INTO pva_logs(level,subsys,msg_code,msg_parms,last_occured)
  2068. VALUES('%s',%d,%d,'%s',CURRENT_TIMESTAMP)",
  2069. $level, $subsys, $msg_code, mysql_real_escape_string($s_msg_params));
  2070. return mysql_query($ins_sql, $db_connection);
  2071. }
  2072. }
  2073. function getLogRecords () {
  2074. global $db_connection;
  2075. if ( ! createLogTable() ) return 0;
  2076. $sql = "SELECT * FROM pva_logs ORDER BY last_occured DESC";
  2077. $query = mysql_query($sql, $db_connection);
  2078. if ( ! $query ) return 0;
  2079. if ( ! mysql_num_rows($query) ) return 0;
  2080. $result = array ();
  2081. while ( $row = mysql_fetch_assoc($query)) {
  2082. $result[] = array (
  2083. 'id' => $row['id'],
  2084. 'level' => $row['level'],
  2085. 'subsys' => $row['subsys'],
  2086. 'msg_code' => $row['msg_code'],
  2087. 'msg_parms' => unserialize($row['msg_parms']),
  2088. 'count' => $row['count'],
  2089. 'first_occured' => $row['first_occured'],
  2090. 'last_occured' => $row['last_occured']
  2091. );
  2092. }
  2093. return $result;
  2094. }
  2095. function getLogRecordsCount () {
  2096. global $db_connection;
  2097. if ( ! createLogTable() ) return 0;
  2098. $sql = "SELECT SUM(pva_logs.count) FROM pva_logs";
  2099. $query = mysql_query($sql, $db_connection);
  2100. if ( ! $query ) return 0;
  2101. if ( ! mysql_num_rows($query) ) return 0;
  2102. $row = mysql_fetch_row($query);
  2103. return $row[0];
  2104. }
  2105. function removeLogRecords ($ids = array () ){
  2106. global $db_connection;
  2107. if ( empty($ids) ) return 0;
  2108. if ( ! createLogTable() ) return 0;
  2109. $sql = "DELETE FROM pva_logs WHERE pva_logs.id IN (";
  2110. $separator = "";
  2111. foreach ( $ids as $id ) {
  2112. $sql .= $separator . $id;
  2113. $separator = ",";
  2114. }
  2115. $sql .= ")";
  2116. return mysql_query($sql, $db_connection);
  2117. }
  2118. ?>