PageRenderTime 67ms CodeModel.GetById 30ms RepoModel.GetById 1ms app.codeStats 0ms

/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

Large files files are truncated, but you can click here to view the full file

  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;

Large files files are truncated, but you can click here to view the full file