user_defs.php 43 KB
Newer Older
1 2
<?php
#
3
# Copyright (c) 2006-2016 University of Utah and the Flux Group.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
23
#
24 25 26 27 28 29

#
# A cache of users to avoid lookups. Indexed by uid_idx.
#
$user_cache = array();

30 31
class User
{
32
    var	$user;
33
    var $tempdata;		# For temporary data values ...
34

35 36 37 38 39 40 41 42 43 44
    #
    # For pedantic checks early in pages.
    #
    function ValidWebID($token) {
	if (! preg_match("/^[-\w]+$/", $token)) {
	    return 0;
	}
	return 1;
    }

45 46 47
    #
    # Constructor by lookup on unique index.
    #
48
    function User($uid_idx) {
49 50 51 52 53 54 55 56 57
	$safe_uid_idx = addslashes($uid_idx);

	$query_result =
	    DBQueryWarn("select * from users where uid_idx='$safe_uid_idx'");

	if (!$query_result || !mysql_num_rows($query_result)) {
	    $this->user = NULL;
	    return;
	}
58
	$this->user = mysql_fetch_array($query_result);
59 60 61 62 63 64 65 66
    }

    # Hmm, how does one cause an error in a php constructor?
    function IsValid() {
	return !is_null($this->user);
    }

    # Lookup by uid_idx.
67
    function Lookup($uid_idx) {
68 69 70 71 72
	global $user_cache;

        # Look in cache first
	if (array_key_exists("$uid_idx", $user_cache))
	    return $user_cache["$uid_idx"];
73

74
	$foo = new User($uid_idx);
75 76 77

	if (! $foo->IsValid()) {
	    # Try lookup by plain uid.
78
	    $foo = User::LookupByUid($uid_idx);
79
	    
80
	    if (!$foo || !$foo->IsValid())
81 82 83
		return null;
	    
	    # Already in the cache from LookupByUid() so just return it.
84
	    return $foo;
85 86 87 88
	}
	# Insert into cache.
	$user_cache["$uid_idx"] =& $foo;
	return $foo;
89 90 91
    }

    # Backwards compatable lookup by uid. Will eventually flush this.
92
    function LookupByUid($uid) {
93
	$safe_uid = addslashes($uid);
94
	$status_archived = TBDB_USERSTATUS_ARCHIVED;
95 96

	$query_result =
97 98
	    DBQueryWarn("select uid_idx from users ".
			"where uid='$safe_uid' and ".
99
			"      status!='$status_archived'");
100 101 102 103 104 105 106

	if (!$query_result || !mysql_num_rows($query_result)) {
	    return null;
	}
	$row = mysql_fetch_array($query_result);
	$idx = $row['uid_idx'];

107 108
	return User::Lookup($idx);
    }
109

110 111
    # Used in the change password code and to make sure that emails are
    # locally unique.
112
    function LookupByEmail($email) {
113
	$safe_email = addslashes($email);
114
	$status_archived = TBDB_USERSTATUS_ARCHIVED;
115 116 117

	$query_result =
	    DBQueryWarn("select uid_idx from users ".
118
			"where LCASE(usr_email)=LCASE('$safe_email') and ".
119
			"      status!='$status_archived'");
120 121 122 123 124 125 126 127 128 129 130 131

	if (!$query_result || !mysql_num_rows($query_result)) {
	    return null;
	}
	$row = mysql_fetch_array($query_result);
	$idx = $row['uid_idx'];

	return User::Lookup($idx);
    }
    
    # Used in new/join project code to make sure that wikinames are
    # locally unique.
132
    function LookupByWikiName($wikiname) {
133
	$safe_wikiname = addslashes($wikiname);
134
	$status_archived = TBDB_USERSTATUS_ARCHIVED;
135 136 137

	$query_result =
	    DBQueryWarn("select uid_idx from users ".
138
			"where wikiname='$safe_wikiname' and ".
139
			"      status!='$status_archived'");
140 141 142 143 144 145 146 147

	if (!$query_result || !mysql_num_rows($query_result)) {
	    return null;
	}
	$row = mysql_fetch_array($query_result);
	$idx = $row['uid_idx'];

	return User::Lookup($idx);
148 149
    }
    
150 151 152 153 154 155 156
    function LookupByUUID($uuid) {
	$safe_uuid = addslashes($uuid);
	$status_archived = TBDB_USERSTATUS_ARCHIVED;

	$query_result =
	    DBQueryWarn("select uid_idx from users ".
			"where uid_uuid='$safe_uuid' and ".
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
			"      status!='$status_archived'");

	if (!$query_result || !mysql_num_rows($query_result)) {
	    return null;
	}
	$row = mysql_fetch_array($query_result);
	$idx = $row['uid_idx'];

	return User::Lookup($idx);
    }
    
    function LookupNonLocal($urn) {
	$safe_urn = addslashes($urn);
	$status_archived = TBDB_USERSTATUS_ARCHIVED;

	$query_result =
	    DBQueryWarn("select uid_idx from users ".
			"where nonlocal_id='$safe_urn' and ".
			"      status!='$status_archived'");
176 177 178 179 180 181 182 183 184 185

	if (!$query_result || !mysql_num_rows($query_result)) {
	    return null;
	}
	$row = mysql_fetch_array($query_result);
	$idx = $row['uid_idx'];

	return User::Lookup($idx);
    }
    
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
    #
    # Refresh an instance by reloading from the DB.
    #
    function Refresh() {
	if (! $this->IsValid())
	    return -1;

	$uid_idx = $this->uid_idx();

	$query_result =
	    DBQueryWarn("select * from users where uid_idx='$uid_idx'");
    
	if (!$query_result || !mysql_num_rows($query_result)) {
	    $this->user = NULL;
	    return -1;
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
202
	$this->user = mysql_fetch_array($query_result);
203 204 205
	return 0;
    }

206 207 208
    #
    # Class function to change the user profile.
    #
209
    function ModUserInfo($target_user, $uid, $args, &$errors) {
210 211 212 213 214 215 216 217
	global $suexec_output, $suexec_output_array;

        #
        # Generate a temporary file and write in the XML goo.
        #
	$xmlname = tempnam("/tmp", "moduserinfo");
	if (! $xmlname) {
	    TBERROR("Could not create temporary filename", 0);
218
	    $errors[] = "Transient error(1); please try again later.";
219 220 221 222
	    return null;
	}
	if (! ($fp = fopen($xmlname, "w"))) {
	    TBERROR("Could not open temp file $xmlname", 0);
223
	    $errors[] = "Transient error(2); please try again later.";
224 225 226 227
	    return null;
	}

	# Add these. Maybe caller should do this?
228
	$args["uid"]  = $target_user->uid_idx();
229 230 231 232 233 234 235 236 237 238 239

	fwrite($fp, "<userinfo>\n");
	foreach ($args as $name => $value) {
	    fwrite($fp, "<attribute name=\"$name\">");
	    fwrite($fp, "  <value>" . htmlspecialchars($value) . "</value>");
	    fwrite($fp, "</attribute>\n");
	}
	fwrite($fp, "</userinfo>\n");
	fclose($fp);
	chmod($xmlname, 0666);

240 241 242 243
	
	# Invoke the back-end script as the user if an admin for permissions.
	$suexec_uid = ISADMIN() ? $uid : "nobody";
	$retval = SUEXEC($suexec_uid, "nobody", "webmoduserinfo $xmlname",
244 245 246 247
			 SUEXEC_ACTION_IGNORE);

	if ($retval) {
	    if ($retval < 0) {
248
		$errors[] = "Transient error(3, $retval); please try again later.";
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
		SUEXECERROR(SUEXEC_ACTION_CONTINUE);
	    }
	    else {
		if (count($suexec_output_array)) {
		    for ($i = 0; $i < count($suexec_output_array); $i++) {
			$line = $suexec_output_array[$i];
			if (preg_match("/^([-\w]+):\s*(.*)$/",
				       $line, $matches)) {
			    $errors[$matches[1]] = $matches[2];
			}
			else
			    $errors[] = $line;
		    }
		}
		else
264
		    $errors[] = "Transient error(4, $retval); please try again later.";
265
	    }
266
	    unlink($xmlname);
267 268 269 270 271 272 273 274 275 276 277
	    return null;
	}

	# There are no return value(s) to parse at the end of the output.

	# Unlink this here, so that the file is left behind in case of error.
	# We can then do the operation by hand from the xmlfile, if desired.
	unlink($xmlname);
	return true;
    }

278 279 280 281
    #
    # Equality test.
    #
    function SameUser($user) {
Leigh B Stoller's avatar
Leigh B Stoller committed
282
	return $user->idx() == $this->idx();
283 284 285 286 287 288 289 290 291 292
    }

    #
    # At some point we will stop passing uid and start using uid_idx.
    # Use this function to avoid having to change a bunch of code twice.
    #
    function URLParam() {
	return $this->uid();
    }

293 294 295 296 297
    # accessors
    function field($name) {
	return (is_null($this->user) ? -1 : $this->user[$name]);
    }
    function uid_idx()		{ return $this->field("uid_idx"); }
Leigh B Stoller's avatar
Leigh B Stoller committed
298
    function idx()		{ return $this->field("uid_idx"); }
299
    function uid()		{ return $this->field("uid"); }
300
    function webid()		{ return $this->field("uid_idx"); }
301
    function dbid()		{ return $this->field("uid_idx"); }
302
    function uuid()		{ return $this->field("uid_uuid"); }
303 304 305 306 307 308
    function created()		{ return $this->field("usr_created"); }
    function expires()		{ return $this->field("usr_expires"); }
    function modified()		{ return $this->field("usr_modified"); }
    function name()		{ return $this->field("usr_name"); }
    function title()		{ return $this->field("usr_title"); }
    function affil()		{ return $this->field("usr_affil"); }
309
    function affil_abbrev()	{ return $this->field("usr_affil_abbrev"); }
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
    function email()		{ return $this->field("usr_email"); }
    function URL()		{ return $this->field("usr_URL"); }
    function addr()		{ return $this->field("usr_addr"); }
    function addr2()		{ return $this->field("usr_addr2"); }
    function city()		{ return $this->field("usr_city"); }
    function state()		{ return $this->field("usr_state"); }
    function zip()		{ return $this->field("usr_zip"); }
    function country()		{ return $this->field("usr_country"); }
    function phone()		{ return $this->field("usr_phone"); }
    function shell()		{ return $this->field("usr_shell"); }
    function pswd()		{ return $this->field("usr_pswd"); }
    function w_pswd()		{ return $this->field("usr_w_pswd"); }
    function unix_uid()		{ return $this->field("unix_uid"); }
    function status()		{ return $this->field("status"); }
    function admin()		{ return $this->field("admin"); }
    function foreign_admin()	{ return $this->field("foreign_admin"); }
    function dbedit()		{ return $this->field("dbedit"); }
    function stud()		{ return $this->field("stud"); }
    function webonly()		{ return $this->field("webonly"); }
    function pswd_expires()	{ return $this->field("pswd_expires"); }
    function cvsweb()		{ return $this->field("cvsweb"); }
    function emulab_pubkey()	{ return $this->field("emulab_pubkey"); }
    function home_pubkey()	{ return $this->field("home_pubkey"); }
    function adminoff()		{ return $this->field("adminoff"); }
    function verify_key()	{ return $this->field("verify_key"); }
    function widearearoot()	{ return $this->field("widearearoot"); }
    function wideareajailroot() { return $this->field("wideareajailroot"); }
    function notes()		{ return $this->field("notes"); }
    function weblogin_frozen()  { return $this->field("weblogin_frozen"); }
    function weblogin_failcount(){return $this->field("weblogin_failcount");}
    function weblogin_failstamp(){return $this->field("weblogin_failstamp");}
    function plab_user()	{ return $this->field("plab_user"); }
    function user_interface()	{ return $this->field("user_interface"); }
    function chpasswd_key()	{ return $this->field("chpasswd_key"); }
    function chpasswd_expires() { return $this->field("chpasswd_expires"); }
    function wikiname()		{ return $this->field("wikiname"); }
    function wikionly()		{ return $this->field("wikionly"); }
    function mailman_password() { return $this->field("mailman_password"); }
348
    function nonlocal_id()	{ return $this->field("nonlocal_id"); }
349 350 351 352 353 354 355 356 357 358 359
    function portal()	     { return $this->field("portal"); }
    function isAPT()	     { return ($this->portal() &&
                                       $this->portal() == "aptlab" ? 1 : 0); }
    function isCloud()	     { return ($this->portal() &&
                                       $this->portal() == "cloudlab" ? 1 : 0); }
    function isPNet()	     { return ($this->portal() &&
                                       $this->portal() == "phantomnet" ? 1 : 0);}
    function isEmulab()	     { return ($this->portal() &&
                                       $this->portal() == "emulab" ? 1 : 0); }
    # Not via the Portal interface.
    function isClassic()     { return ($this->portal() ? 0 : 1); }
360

361 362 363
    function IsNonLocal() {
	return ($this->field("nonlocal_id") ? 1 : 0);
    }
364 365 366
    function IsActive() {
        return ($this->status() == TBDB_USERSTATUS_ACTIVE ? 1 : 0);
    }
367
    # Temporary data storage ... useful.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
368 369
    function SetTempData($value) {
	$this->tempdata = $value;
370
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
371
    function GetTempData() {
372 373 374
	return $this->tempdata;
    }

375 376 377 378 379 380 381 382 383 384
    function adminEmail() {
        global $TBMAIL_APPROVAL;
        
        return 
            ($this->isAPT() ? "aptlab-approval@aptlab.net" :
             ($this->isCloud() ? "cloudlab-approval@cloudlab.us" :
              ($this->isPNet() ? "phantomnet-approval@phantomnet.org" :
               $TBMAIL_APPROVAL)));
    }

385 386 387
    #
    # Class function to create new user and return object.
    #
388
    function NewUser($uid, $flags, $args) {
389 390
	global $TBBASE, $TBMAIL_APPROVAL, $TBMAIL_AUDIT, $TBMAIL_WWW;
	global $MIN_UNIX_UID;
391

392 393 394 395
	$isleader = ($flags & TBDB_NEWACCOUNT_PROJLEADER ? 1 : 0);
	$wikionly = ($flags & TBDB_NEWACCOUNT_WIKIONLY   ? 1 : 0);
	$webonly  = ($flags & TBDB_NEWACCOUNT_WEBONLY    ? 1 : 0);

396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
	#
	# If no uid, we need to generate a unique one for the user.
	#
	if (! $uid) {
	    #
	    # Take the first 5 letters of the email to form a root. That gives
	    # us 3 digits to make it unique, since unix uids are limited to 8
	    # chars, sheesh!
	    #
	    $email = $args["usr_email"];

	    if (! preg_match('/^([-\w\+\.]+)\@([-\w\.]+)$/', $email, $matches))
		return null;

	    $token = $matches[1];

            # Squeeze out any dots or dashes.
	    $token = preg_replace('/\./', '', $token);
	    $token = preg_replace('/\-/', '', $token);

            # Trim off any trailing numbers or +foo tokens.
	    if (! preg_match('/^([a-zA-Z]+)/', $token, $matches)) {
		return null;
	    }
	    
	    $token = $matches[1];

	    # First 5 chars, at most.
	    $token = substr($token, 0, 5);

	    # Grab all root matches from the DB.
	    $query_result =
		DBQueryFatal("select uid from users ".
			     "where uid like '${token}%'");

	    if (!$query_result)
		return null;

	    # Easy; no matches at all!
	    if (!mysql_num_rows($query_result)) {
		$uid = "$token" . "001";
	    }
	    else {
		$max = 0;
		
		#
		# Find unused slot. Must be a better way to do this!
		#
		while ($row = mysql_fetch_array($query_result)) {
		    $foo = $row[0];

                    # Split name from number
		    if (! preg_match('/^([a-zA-Z]+)(\d*)$/', $foo, $matches)) {
			return null;
		    }
		    $name   = $matches[1];
		    $number = $matches[2];

		    # Must be exact root
		    if ($name != $token)
			continue;

		    # Backwards compatability; might not have appended number.
		    if (isset($number) && intval($number) > $max)
			$max = intval($number);
		}
		$max++;
		$uid = $token . sprintf("%03d", $max);
	    }
	}
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
	
	#
	# The array of inserts is assumed to be safe already. Generate
	# a list of actual insert clauses to be joined below.
	#
	$insert_data = array();
	
	foreach ($args as $name => $value) {
	    $insert_data[] = "$name='$value'";
	}

	# Every user gets a new unique index.
	$uid_idx = TBGetUniqueIndex('next_uid');

	# Get me an unused unix id. Nice query, eh? Basically, find 
	# unused numbers by looking at existing numbers plus one, and check
	# to see if that number is taken. 
	$query_result =
	    DBQueryFatal("select u.unix_uid + 1 as start from users as u ".
			 "left outer join users as r on ".
			 "  u.unix_uid + 1 = r.unix_uid ".
487
			 "where u.unix_uid>=$MIN_UNIX_UID and ".
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
			 "      u.unix_uid<60000 and ".
			 "      r.unix_uid is null limit 1");

	if (!$query_result || !mysql_num_rows($query_result)) {
	    TBERROR("Could not find an unused unix_uid!", 1);
	}
	$row = mysql_fetch_row($query_result);
	$unix_uid = $row[0];

        # Initial mailman_password.
	$mailman_password = substr(GENHASH(), 0, 10);

	# And a verification key.
	$verify_key = md5(uniqid(rand(),1));

	# Now tack on other stuff we need.
504 505 506 507 508
	if ($wikionly)
	    $insert_data[] = "wikionly='1'";
	if ($webonly)
	    $insert_data[] = "webonly='1'";
	
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
	$insert_data[] = "usr_created=now()";
	$insert_data[] = "usr_modified=now()";
	$insert_data[] = "pswd_expires=date_add(now(), interval 1 year)";
	$insert_data[] = "unix_uid=$unix_uid";
	$insert_data[] = "status='newuser'";
	$insert_data[] = "mailman_password='$mailman_password'";
	$insert_data[] = "verify_key='$verify_key'";
	$insert_data[] = "uid_idx='$uid_idx'";
	$insert_data[] = "uid='$uid'";

	# Insert into DB. Should probably lock the table ...
	if (!DBQueryWarn("insert into users set ".
			 implode(",", $insert_data))) {
	    return null;
	}

	if (! DBQueryWarn("insert into user_stats (uid, uid_idx) ".
			  "VALUES ('$uid', $uid_idx)")) {
	    DBQueryFatal("delete from users where uid_idx='$uid_idx'");
	    return null;
	}
	$newuser = User::Lookup($uid_idx);
	if (! $newuser)
	    return null;

        #
        # See if we are in an initial Emulab setup.
        #
        $FirstInitState = (TBGetFirstInitState() == "createproject");
	if ($FirstInitState)
	    return $newuser;

        # stuff for email message.
	$key       = $newuser->verify_key();
	$usr_name  = $newuser->name();
	$usr_email = $newuser->email();
	    
	# Email to user.
	TBMAIL("$usr_name '$uid' <$usr_email>",
       "Your New User Key",
       "\n".
       "Dear $usr_name ($uid):\n\n".
       "This is your account verification key: $key\n\n".
       "Please use this link to verify your user account:\n".
       "\n".
       "    ${TBBASE}/login.php3?vuid=$uid&key=$key\n".
       "\n".
       ($wikionly ?
	"Once you have verified your account, you will be able to access\n".
	"the Wiki. You MUST verify your account first!"
	:
560 561 562 563
	($webonly ?
	 "Once you have verified your account, Testbed Operations will be\n".
	 "able to approve you. You MUST verify your account first!"
	 :
564 565 566 567 568 569 570 571 572 573 574
	($isleader ?
	 "You will then be verified as a user. When you have been both\n".
	 "verified and approved by Testbed Operations, you will be marked\n".
	 "as an active user and granted full access to your account.\n".
	 "You MUST verify your account before your project can be approved!\n"
	 :
	 "Once you have verified your account, the project leader will be\n".
	 "able to approve you.\n\n".
	 "You MUST verify your account before the project leader can ".
	 "approve you\n".
	 "After project approval, you will be marked as an active user, and\n".
575
	 "will be granted full access to your user account."))) .
576 577 578 579 580 581 582 583 584 585
       "\n\n".
       "Thanks,\n".
       "Testbed Operations\n",
       "From: $TBMAIL_APPROVAL\n".
       "Bcc: $TBMAIL_AUDIT\n".
       "Errors-To: $TBMAIL_WWW");
	
	return $newuser;
    }

586
    function NewNewUserXML($args, &$error) {
587 588 589 590 591 592
        #
        # Generate a temporary file and write in the XML goo.
        #
	$xmlname = tempnam("/tmp", "newuser");
	if (! $xmlname) {
	    TBERROR("Could not create temporary filename", 0);
593
	    $error = "Transient error(1); please try again later.";
594 595 596 597
	    return null;
	}
	if (! ($fp = fopen($xmlname, "w"))) {
	    TBERROR("Could not open temp file $xmlname", 0);
598
	    $error = "Transient error(2); please try again later.";
599 600 601 602 603 604 605 606 607 608 609 610 611
	    return null;
	}

	fwrite($fp, "<user>\n");
	foreach ($args as $name => $value) {
	    fwrite($fp, "<attribute name=\"$name\">");
	    fwrite($fp, "  <value>" . htmlspecialchars($value) . "</value>");
	    fwrite($fp, "</attribute>\n");
	}
	fwrite($fp, "</user>\n");
	fclose($fp);
	chmod($xmlname, 0666);

612 613 614 615 616 617 618 619 620 621 622 623 624
	return $xmlname;
    }

    function NewNewUser($flags, $args, &$error) {
	global $suexec_output, $suexec_output_array;
	$typearg = "";

	if ($flags & TBDB_NEWACCOUNT_PROJLEADER)
	    $typearg = "-t leader";
	elseif ($flags & TBDB_NEWACCOUNT_WIKIONLY)
	    $typearg = "-t wikionly";
	elseif ($flags & TBDB_NEWACCOUNT_WEBONLY)
	    $typearg = "-t webonly";
625 626
	elseif ($flags & TBDB_NEWACCOUNT_NONLOCAL)
	    $typearg = "-t nonlocal";
627 628 629 630 631

	if (! ($xmlname = User::NewNewUserXML($args, $error))) {
	    return null;
	}

632 633 634 635 636
	$retval = SUEXEC("nobody", "nobody", "webnewuser $typearg $xmlname",
			 SUEXEC_ACTION_IGNORE);

	if ($retval) {
	    if ($retval < 0) {
637
		$error = "Transient error(3, $retval); please try again later.";
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
		SUEXECERROR(SUEXEC_ACTION_CONTINUE);
	    }
	    else {
		$error = $suexec_output;
	    }
	    return null;
	}

        #
        # Parse the last line of output. Ick.
        #
	unset($matches);
	
	if (!preg_match("/^User\s+(\w+)\/(\d+)\s+/",
			$suexec_output_array[count($suexec_output_array)-1],
			$matches)) {
654
	    $error = "Transient error(4, $retval); please try again later.";
655 656 657 658 659 660
	    SUEXECERROR(SUEXEC_ACTION_CONTINUE);
	    return null;
	}
	$uid_idx = $matches[2];
	$newuser = User::Lookup($uid_idx);
	if (! $newuser) {
661
	    $error = "Transient error(5); please try again later.";
662 663 664 665 666 667 668 669 670
	    TBERROR("Could not lookup new user $uid_idx", 0);
	    return null;
	}
	# Unlink this here, so that the file is left behind in case of error.
	# We can then create the user by hand from the xmlfile, if desired.
	unlink($xmlname);
	return $newuser;	    
    }    

671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
    #
    # Delete a user, but JUST from the users table. 
    #
    function Delete() {
	global $user_cache;

	$uid_idx = $this->uid_idx();

	DBQueryFatal("delete from users where uid_idx='$uid_idx'");

	if (array_key_exists("$uid_idx", $user_cache))
	    unset($user_cache["$uid_idx"]);
	
	return 0;
    }

687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
    #
    # Stats
    #
    function ShowStats() {
	$uid_idx = $this->uid_idx();
	
	$query_result =
	    DBQueryFatal("select s.* from user_stats as s ".
			 "where s.uid_idx='$uid_idx'");

	if (! mysql_num_rows($query_result)) {
	    return "";
	}
	$row = mysql_fetch_assoc($query_result);

        #
        # Not pretty printed yet.
        #
	$html = "<table align=center border=1>\n";
    
	foreach($row as $key => $value) {
	    $html .= "<tr><td>$key:</td><td>$value</td></tr>\n";
	}
	$html .= "</table>\n";
	return $html;
    }
713

714
    function Show($html = FALSE) {
715
	global $WIKISUPPORT;
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734

	$user = $this;

	$uid         = $user->uid();
	$webid       = $user->webid();
	$uid_idx     = $user->uid_idx();
	$usr_email   = $user->email();
	$usr_URL     = $user->URL();
	$usr_addr    = $user->addr();
	$usr_addr2   = $user->addr2();
	$usr_city    = $user->city();
	$usr_state   = $user->state();
	$usr_zip     = $user->zip();
	$usr_country = $user->country();
	$usr_name    = $user->name();
	$usr_phone   = $user->phone();
	$usr_shell   = $user->shell();
	$usr_title   = $user->title();
	$usr_affil   = $user->affil();
735
	$usr_affil_abbrev = $user->affil_abbrev();
736 737 738 739 740 741 742 743
	$status      = $user->status();
	$admin       = $user->admin();
	$notes       = $user->notes();
	$frozen      = $user->weblogin_frozen();
	$failcount   = $user->weblogin_failcount();
	$failstamp   = $user->weblogin_failstamp();
	$wikiname    = $user->wikiname();
	$cvsweb      = $user->cvsweb();
744
	$widearearoot= $user->widearearoot();
745
	$wikionly    = $user->wikionly();
746
	$stud        = $user->stud();
747
	$uuid        = $user->uuid();
748
	$portal      = $user->portal();
749
        $nonlocal_id = $user->nonlocal_id();
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766

	if (!strcmp($usr_addr2, ""))
	    $usr_addr2 = "&nbsp;";
	if (!strcmp($usr_city, ""))
	    $usr_city = "&nbsp;";
	if (!strcmp($usr_state, ""))
	    $usr_state = "&nbsp;";
	if (!strcmp($usr_zip, ""))
	    $usr_zip = "&nbsp;";
	if (!strcmp($usr_country, ""))
	    $usr_country = "&nbsp;";
	if (!strcmp($notes, ""))
	    $notes = "&nbsp;";

        #
        # Last Login info.
        #
767
	if (($lastweblogin = LASTWEBLOGIN($uid_idx)) == 0)
768
	    $lastweblogin = "&nbsp;";
769
	if (($lastuserslogininfo = TBUsersLastLogin($uid_idx)) == 0)
770 771 772 773 774 775
	    $lastuserslogin = "N/A";
	else {
	    $lastuserslogin = $lastuserslogininfo["date"] . " " .
		$lastuserslogininfo["time"];
	}
    
776
	if (($lastnodelogininfo = TBUidNodeLastLogin($uid_idx)) == 0)
777 778 779 780 781 782 783
	    $lastnodelogin = "N/A";
	else {
	    $lastnodelogin = $lastnodelogininfo["date"] . " " .
		$lastnodelogininfo["time"] . " " .
		"(" . $lastnodelogininfo["node_id"] . ")";
	}
    
784 785
	if ($html)
	    ob_start();
786 787 788 789 790 791
	echo "<table align=center border=1>\n";
    
	echo "<tr>
                  <td>Username:</td>
                  <td>$uid ($uid_idx)</td>
              </tr>\n";
792 793 794 795 796 797 798

        if ($nonlocal_id) {
            echo "<tr>
                      <td>Nonlocal ID:</td>
                      <td>$nonlocal_id</td>
                      </tr>\n";
        }
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874
    
        echo "<tr>
                  <td>Full Name:</td>
                  <td>$usr_name</td>
              </tr>\n";
    
        echo "<tr>
                  <td>Email Address:</td>
                  <td>$usr_email</td>
              </tr>\n";

        echo "<tr>
                  <td>Home Page URL:</td>
                  <td><a href='$usr_URL'>$usr_URL</a></td>
              </tr>\n";

	if ($WIKISUPPORT && isset($wikiname)) {
	    $wikiurl = "gotowiki.php3?redurl=Main/$wikiname";
	
	    echo "<tr>
                      <td>Emulab Wiki Page:</td>
                      <td class=\"left\">
                          <a href='$wikiurl'>$wikiname</a></td>
                  </tr>\n";
	}
    
	echo "<tr>
                  <td>Address 1:</td>
                  <td>$usr_addr</td>
             </tr>\n";
    
        echo "<tr>
                  <td>Address 2:</td>
                  <td>$usr_addr2</td>
              </tr>\n";
    
        echo "<tr>
                  <td>City:</td>
                  <td>$usr_city</td>
              </tr>\n";
    
	echo "<tr>
                  <td>State:</td>
                  <td>$usr_state</td>
              </tr>\n";
    
        echo "<tr>
                  <td>ZIP:</td>
                  <td>$usr_zip</td>
              </tr>\n";

        echo "<tr>
                  <td>Country:</td>
                  <td>$usr_country</td>
              </tr>\n";
    
        echo "<tr>
                  <td>Phone #:</td>
                  <td>$usr_phone</td>
              </tr>\n";

	echo "<tr>
	          <td>Shell:</td>
	          <td>$usr_shell</td>
              </tr>\n";
    
        echo "<tr>
                  <td>Title/Position:</td>
                  <td>$usr_title</td>
             </tr>\n";
    
	echo "<tr>
                  <td>Institutional Affiliation:</td>
                  <td>$usr_affil</td>
              </tr>\n";
    
875 876 877 878 879
	echo "<tr>
                  <td>Institutional Abbreviation:</td>
                  <td>$usr_affil_abbrev</td>
              </tr>\n";
    
880 881 882 883 884 885 886 887 888 889 890 891
        echo "<tr>
                  <td>Status:</td>
                  <td>$status</td>
              </tr>\n";

	if ($wikionly) {
	    echo "<tr>
                      <td><b>Wikionly</b>:</td>
                      <td>Yes</td>
                  </tr>\n";
	}

892 893 894
	if ($admin || ISADMIN()) {
	    $admintag = ($admin ? "Yes" : "No");

895 896
	    echo "<tr>
                      <td>Administrator:</td>
897 898
                      <td>$admintag";
	    
899 900 901
	    $adminflip = ($admin ? 0 : 1);
	    $toggle_url = CreateURL("toggle", $user, "type", "adminflag",
				    "value", $adminflip);
902

903 904
	    echo " (<em>Be very careful with this</em> ".
		"<a href='$toggle_url'>Toggle</a>)";
905 906

	    echo "</td>
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925
                  </tr>\n";
	}
    
	echo "<tr>
                  <td>Last Web Login:</td>
                  <td>$lastweblogin</td>
              </tr>\n";
    
	echo "<tr>
                  <td>Last Users Login:</td>
                  <td>$lastuserslogin</td>
              </tr>\n";
    
        echo "<tr>
                  <td>Last Node Login:</td>
                  <td>$lastnodelogin</td>
              </tr>\n";

	if (ISADMIN()) {
926 927 928 929
	    echo "<tr>
                    <td>UUID: </td>
                    <td class=left>$uuid</td>
                  </tr>\n";
930

931
	    if (isset($portal)) {
932
		echo "<tr>
933 934
                      <td>Portal: </td>
                      <td class=left>$portal</td>
935 936
                   </tr>\n";
	    }
937 938
	}
	if (ISADMIN() && $status != TBDB_USERSTATUS_ARCHIVED) {
939 940 941 942 943 944 945 946 947
	    $cvswebflip = ($cvsweb ? 0 : 1);

	    $toggle_url = CreateURL("toggle", $user,
				    "type", "cvsweb", "value", $cvswebflip);

	    echo "<tr>
                      <td>CVSWeb Access:</td>
                      <td>$cvsweb (<a href='$toggle_url'>Toggle</a>)
                  </tr>\n";
948 949 950 951 952 953 954 955 956

	    $widearearootflip = ($widearearoot ? 0 : 1);
	    $toggle_url = CreateURL("toggle", $user,
				    "type", "widearearoot",
				    "value", $widearearootflip);
	    echo "<tr>
                      <td>Widearearoot:</td>
                      <td>$widearearoot (<a href='$toggle_url'>Toggle</a>)
                  </tr>\n";
957 958 959 960 961
	
	    $freezeflip = ($frozen ? 0 : 1);
	    $toggle_url = CreateURL("toggle", $user,
				    "type", "webfreeze", "value", $freezeflip);

962 963 964 965 966 967 968 969 970 971 972 973 974
	    $studflip = ($stud ? 0 : 1);

	    $toggle_url = CreateURL("toggle", $user,
				    "type", "stud", "value", $studflip);

	    echo "<tr>
                      <td>Studly:</td>
                      <td>$stud (<a href='$toggle_url'>Toggle</a>)
                  </tr>\n";
	
	    $freezeflip = ($frozen ? 0 : 1);
	    $toggle_url = CreateURL("toggle", $user,
				    "type", "webfreeze", "value", $freezeflip);
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993
	    echo "<tr>
                      <td>Web Freeze:</td>
                      <td>$frozen (<a href='$toggle_url'>Toggle</a>)
                  </tr>\n";
	
	    if ($frozen && $failstamp && $failcount) {
		$when = strftime("20%y-%m-%d %H:%M:%S", $failstamp);
	    
		echo "<tr>
                          <td>Login Failures:</td>
                          <td>$failcount ($when)</td>
                      </tr>\n";
	    }
	    echo "<tr>
                      <td>Notes:</td>
                      <td>$notes</td>
                  </tr>\n";
	}
	echo "</table>\n";
994 995 996 997 998
	if ($html) {
	    $table_html = ob_get_contents();
	    ob_end_clean();
	    return $table_html;
	}
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
    }

    #
    # Access Check, determines if $user can access $this record.
    #
    #	returns 0 if not allowed.
    #   returns 1 if allowed.
    # 
    function AccessCheck($user, $access_type) {
	global $TB_USERINFO_READINFO;
	global $TB_USERINFO_MODIFYINFO;
	global $TB_USERINFO_MIN;
	global $TB_USERINFO_MAX;

	$this_idx = $this->uid_idx();
	$auth_idx = $user->uid_idx();

	if ($access_type < $TB_USERINFO_MIN ||
	    $access_type > $TB_USERINFO_MAX) {
	    TBERROR("UserAccessCheck: Invalid access type $access_type!", 1);
	}

	if ($this->uid_idx() == $user->uid_idx()) {
	    return 1;
	}

        #
        # Admins do whatever they want.
        # 
        if (ISADMIN()) {
	    return 1;
	}

        #
        # This join will allow the operation if the current user is in the 
        # same group (any group) as the target user, but with root permissions.
        # 
	$query_result =
	    DBQueryFatal("select g.trust from group_membership as g ".
			 "left join group_membership as authed on ".
			 "     g.pid_idx=authed.pid_idx and ".
			 "     g.gid_idx=authed.gid_idx and ".
1041
			 "     g.uid_idx='$this_idx' ".
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
			 "where authed.uid_idx='$auth_idx' and ".
			 "      (authed.trust='group_root' or ".
			 "       authed.trust='project_root')");

	if (mysql_num_rows($query_result) == 0) {
	    return 0;
	}
	return 1;
    }

    #
1053
    # How many PCs is user using. 
1054 1055
    #
    function PCsInUse() {
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
	$uid_idx = $this->uid_idx();
	
	$query_result =
	    DBQueryFatal("select a.node_id from nodes as a ".
			 "left join reserved as b on a.node_id=b.node_id ".
			 "left join node_types as nt on a.type=nt.type ".
			 "left join experiments as e on b.pid=e.pid and ".
			 "     b.eid=e.eid ".
			 "where e.swapper_idx='$uid_idx' and ".
			 "      e.pid!='emulab-ops' and ".
			 "      a.role='testnode' and nt.class = 'pc'");

	return mysql_num_rows($query_result);
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
    }

    #
    # Functions to change various DB values.
    #
    function SetStatus($status) {
	$idx = $this->uid_idx();

	DBQueryFatal("update users set status='$status' ".
		     "where uid_idx='$idx'");
	$this->user["status"] = $status;
	return 0;
    }
    function SetChangePassword($key, $expires) {
	$idx = $this->uid_idx();

	DBQueryFatal("update users set ".
		     "  chpasswd_key='$key',chpasswd_expires=$expires ".
		     "where uid_idx='$idx'");
	return 0;
    }
    function SetWindowsPassword($password) {
	$idx = $this->uid_idx();

	DBQueryFatal("update users set ".
		     "  usr_w_pswd='$password' ".
		     "where uid_idx='$idx'");
	$this->user["usr_w_pswd"] = $password;
	return 0;
    }
    function SetNotes($notes) {
	$idx   = $this->uid_idx();
	$notes = addslashes($notes);
			    
	DBQueryFatal("update users set ".
		     "  notes='$notes' ".
		     "where uid_idx='$idx'");
	$this->user["notes"] = $notes;
	return 0;
    }
    function SetUserInterface($interface) {
	$idx   = $this->uid_idx();
			    
	DBQueryFatal("update users set ".
		     "  user_interface='$interface' ".
		     "where uid_idx='$idx'");
	$this->user["user_interface"] = $interface;
	return 0;
    }
    function SetWebFreeze($freeze) {
	$idx   = $this->uid_idx();

	$freeze = ($freeze ? 1 : 0);
			    
	DBQueryFatal("update users set ".
		     "   weblogin_frozen='$freeze' ".
		     "where uid_idx='$idx'");
	$this->user["weblogin_frozen"] = $freeze;
	return 0;
    }
    function SetCVSWeb($onoff) {
	$idx   = $this->uid_idx();

	$onoff = ($onoff ? 1 : 0);
			    
	DBQueryFatal("update users set ".
		     "   cvsweb='$onoff' ".
		     "where uid_idx='$idx'");
	$this->user["cvsweb"] = $onoff;
	return 0;
    }
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
    function SetStudly($onoff) {
	$idx   = $this->uid_idx();

	$onoff = ($onoff ? 1 : 0);
			    
	DBQueryFatal("update users set ".
		     "   stud='$onoff' ".
		     "where uid_idx='$idx'");
	$this->user["stud"] = $onoff;
	return 0;
    }
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
    function SetForeignAdmin($onoff) {
	$idx   = $this->uid_idx();

	$onoff = ($onoff ? 1 : 0);
			    
	DBQueryFatal("update users set ".
		     "   foreign_admin='$onoff' ".
		     "where uid_idx='$idx'");
	$this->user["foreign_admin"] = $onoff;
	return 0;
    }
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
    function SetAdminFlag($onoff) {
	$idx   = $this->uid_idx();

	$onoff = ($onoff ? 1 : 0);
			    
	DBQueryFatal("update users set ".
		     "   admin='$onoff' ".
		     "where uid_idx='$idx'");
	$this->user["admin"] = $onoff;
	return 0;
    }
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
    function SetWideAreaRoot($onoff) {
	$idx   = $this->uid_idx();

	$onoff = ($onoff ? 1 : 0);
			    
	DBQueryFatal("update users set ".
		     "   widearearoot='$onoff' ".
		     "where uid_idx='$idx'");
	$this->user["stud"] = $onoff;
	return 0;
    }
1184 1185 1186 1187 1188
    function UpdateWebLoginFail() {
	$idx   = $this->uid_idx();

	DBQueryFatal("update users set ".
		     "       weblogin_failcount=weblogin_failcount+1, ".
1189
		     "       weblogin_failstamp=UNIX_TIMESTAMP(now()) ".
1190 1191 1192 1193
		     "where uid_idx='$idx'");

	return $this->Refresh();
    }
1194 1195 1196 1197 1198 1199
    function HasEncryptedCert($expired_notokay) {
	$query_result =
	    $this->TableLookUp("user_sslcerts", "cert,privkey",
			       "encrypted=1 and revoked is null ".
			       ($expired_notokay ? "and expires > now()" : ""));
					   
1200 1201
	return mysql_num_rows($query_result);
    }
1202 1203 1204 1205 1206 1207

    #
    # Return project access list for a user. This returns just pid,eid for
    # now, later return actual objects. 
    #
    function ProjectAccessList($access_type) {
1208
    	global $TB_PROJECT_CREATEEXPT;
1209 1210 1211 1212 1213 1214 1215
	global $TB_PROJECT_MAKEOSID;
	global $TB_PROJECT_MAKEIMAGEID;
	global $TB_PROJECT_MAKEGROUP;
	global $TB_PROJECT_READINFO;

	$uid_idx     = $this->uid_idx();
	$result      = array();
1216
	$user_clause = "where uid_idx='$uid_idx' and p.nonlocal_id is null and";
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
	$trust_clause= "";

	# Constants.
	$trust_none   = TBDB_TRUSTSTRING_NONE;
	$trust_user   = TBDB_TRUSTSTRING_USER;
	$trust_local  = TBDB_TRUSTSTRING_LOCALROOT;
	$trust_group  = TBDB_TRUSTSTRING_GROUPROOT;
	$trust_project= TBDB_TRUSTSTRING_PROJROOT;
	
	if ($access_type == $TB_PROJECT_READINFO) {
	    $trust_clause = "trust!='$trust_none'";
	}
	elseif ($access_type == $TB_PROJECT_MAKEGROUP) {
Leigh B Stoller's avatar
Leigh B Stoller committed
1230
	    $trust_clause = "trust='$trust_group'";
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
	}
	elseif ($access_type == $TB_PROJECT_CREATEEXPT) {
	    $trust_clause =
		"(trust='$trust_project' or trust='$trust_group' or ".
		" trust='$trust_local')";
	}
	elseif ($access_type == $TB_PROJECT_MAKEOSID ||
		$access_type == $TB_PROJECT_MAKEIMAGEID) {
	    if (ISADMIN()) {
		$user_clause = "";
	    }
	    else {
		$trust_clause =
		    "(trust='$trust_project' or trust='$trust_group' or ".
		    " trust='$trust_local')";
	    
	    }
	}
	else {
	    TBERROR("Invalid access type $access_type!", 1);
	}
    
	$query_result =
1254 1255 1256 1257
	    DBQueryFatal("SELECT distinct g.pid,g.gid ".
                         "   FROM group_membership as g ".
                         "left join projects as p on p.pid=g.pid ".
			 "$user_clause $trust_clause order by g.pid");
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268

	if (mysql_num_rows($query_result) == 0) {
	    return $result;
	}

	while ($row = mysql_fetch_array($query_result)) {
	    $pid = $row['pid'];
	    $gid = $row['gid'];
	
	    $result[$pid][] = $gid;
	}
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302

        # We want to order by time of last usage.
        $query_result =
            DBQueryFatal("(select pid,max(UNIX_TIMESTAMP(s.last_activity)) ".
                         "   as last from experiment_stats as s ".
                         " where s.creator_idx='$uid_idx' and pid_idx!=0 ".
                         " group by s.pid_idx order by last desc) ".
                         "union ".
                         "(select pid,max(UNIX_TIMESTAMP(created)) as last ".
                         " from apt_instances ".
                         " where creator_idx='$uid_idx' and pid is not null ".
                         " group by pid_idx order by last desc)");
        
	$ordered = array();
	while ($row = mysql_fetch_array($query_result)) {
	    $pid   = $row['pid'];
	    $stamp = $row['last'];

	    if (array_key_exists($pid, $ordered)) {
                if ($ordered[$pid] > $stamp) {
                    continue;
                }
            }
	    $ordered[$pid] = $stamp;
	}
        $sorter = function ($a, $b) use ($ordered) {
            $s1 = $ordered[$a];
            $s2 = $ordered[$b];
            if ($s1 == $s2) {
                return 0;
            }
            return ($s1 > $s2) ? -1 : 1;
        };
        uksort($result, $sorter);
1303 1304 1305 1306 1307 1308
	return $result;
    }

    #
    # Return project membership list for a user.
    #
1309 1310 1311 1312 1313 1314 1315 1316
    function ProjectMembershipList($desired_trust = null) {
	$uid_idx   = $this->uid_idx();
	$result    = array();
	$condition = "";

	if ($desired_trust && $desired_trust != "") {
	    $condition = "and trust='$desired_trust'";
	}
1317 1318 1319 1320

	$query_result =
	    DBQueryFatal("select pid_idx from group_membership ".
			 "where pid_idx=gid_idx and ".
1321
			 "      uid_idx='$uid_idx' $condition");
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334

	while ($row = mysql_fetch_array($query_result)) {
	    $pid_idx = $row["pid_idx"];

	    if (! ($project = Project::Lookup($pid_idx))) {
		TBERROR("User::ProjectMembershipList: ".
			"Could not load project $pid_idx!", 1);
	    }
	    $result[] = $project;
	}
	return $result;
    }

1335 1336 1337 1338 1339 1340 1341 1342 1343
    #
    # Return list of unapproved membership in projects. This will not
    # include projects for which the user is the leader, that is a
    # different set.
    #
    function PendingMembership() {
        return $this->ProjectMembershipList(TBDB_TRUSTSTRING_NONE);
    }

1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
    #
    # First approved project.
    #
    function FirstApprovedProject() {
	$uid_idx = $this->uid_idx();

	$query_result =
	    DBQueryFatal("select pid_idx from group_membership ".
			 "where uid_idx='$uid_idx' and pid=gid and ".
			 "      trust!='". TBDB_TRUSTSTRING_NONE . "' ".
			 "order by date_approved asc limit 1");
	
	if (mysql_num_rows($query_result) == 0) {
	    return null;
	}
	$row = mysql_fetch_array($query_result);
	$pid_idx = $row["pid_idx"];

	if (! ($project = Project::Lookup($pid_idx))) {
	    TBERROR("User::FirstApprovedProject: ".
		    "Could not load project $pid_idx!", 1);
	}
	return $project;
    }

    #
    # Are there users waiting to be approved by this user?
    #
    function ApprovalList($listify = 1) {
	$uid_idx = $this->uid_idx();

	#
        # Find all of the groups that this person has project/group root in,
	# and then in all of those groups, all of the people who are awaiting
	# to be approved (status = none).
	#
        # Okay, so this operation sucks out the right people by joining the
        # group_membership table with itself.
	#
	$query_result =
	    DBQueryFatal("select g.uid_idx,g.gid_idx ".
			 "   from group_membership as authed ".
			 "left join group_membership as g on ".
			 "    g.pid_idx=authed.pid_idx and ".
			 "    g.gid_idx=authed.gid_idx ".
			 "left join users as u on u.uid_idx=g.uid_idx ".
			 "where u.status!='". TBDB_USERSTATUS_UNVERIFIED . "'".
			 "  and u.status!='". TBDB_USERSTATUS_NEWUSER . "'".
			 "  and g.uid_idx!='$uid_idx' and ".
			 "      g.trust='". TBDB_TRUSTSTRING_NONE . "' ".
			 "  and authed.uid_idx='$uid_idx' and ".
			 "     (authed.trust='group_root' or ".
			 "      authed.trust='project_root') ".
			 "ORDER BY g.uid,g.pid,g.gid");

	if (! $listify) {
	    return mysql_num_rows($query_result);
	}
	
	# Else, create a list of the groups.
	$result  = array();

	while ($row = mysql_fetch_array($query_result)) {
	    $uid_idx = $row["uid_idx"];
	    $gid_idx = $row["gid_idx"];

	    if (! ($group = Group::Lookup($gid_idx))) {
		TBERROR("User::ApprovalList: ".
			"Could not load group $gid_idx!", 1);
	    }
	    if (! ($user = User::Lookup($uid_idx))) {
		TBERROR("User::ApprovalList: ".
			"Could not load user $uid_idx!", 1);
	    }
	    if (! array_key_exists("$uid_idx", $result)) {
		$result["$uid_idx"] = array();
	    }
1421
	    $result["$uid_idx"][] = $group;
1422 1423 1424 1425
	}
	return $result;
    }

1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
    #
    # Return list of experiments for a user, or just a count.
    #
    function ExperimentList($listify = 1, $group = null) {
	$uid_idx = $this->uid_idx();
	$gclause = "";

	# within optional group only.
	if ($group) {
	    $pid     = $group->pid();
	    $gid     = $group->gid();
	    $gclause = "and pid='$pid' and gid='$gid'";
	}

	$query_result =
	    DBQueryFatal("select idx from experiments ".
			 "where creator_idx='$uid_idx' $gclause");

	if (! $listify) {
	    return mysql_num_rows($query_result);
	}

	# Else, create a list of the groups.
	$result  = array();

	while ($row = mysql_fetch_array($query_result)) {
	    $idx = $row["idx"];

	    if (! ($experiment = Experiment::Lookup($idx))) {
		TBERROR("Group::ExperimentList: ".
			"Could not load experiment $idx!", 1);
	    }
	    $result[] = $experiment;
	}
	return $result;
    }

1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
    #
    # See if user has enough permission to view the webcams. If not an admin
    # person, then must be a project with permission to use the robots.
    # Eventually this needs to be a much more restrictive test.
    #
    function WebCamAllowed() {
	$uid_idx = $this->uid_idx();
	
	$query_result =
	    DBQueryFatal("select distinct class from group_membership as g ".
			 "left join nodetypeXpid_permissions as p on ".
			 "     g.pid=p.pid ".
			 "left join node_types as nt on nt.type=p.type ".
			 "where g.uid_idx='$uid_idx' and class='robot'");
	
	return mysql_num_rows($query_result);
    }
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518

    #
    # Generic function to look up some table values given a set of desired
    # fields and some conditions. Pretty simple, not widely usful, but it
    # helps to avoid spreding more uid based queries around then we need to.
    #
    function &TableLookUp($table, $fields, $conditions = "") {
	$uid_idx = $this->uid_idx();

	if ($conditions && $conditions != "") {
	    $conditions = "and ($conditions)";
	}
	else {
	    $conditions = "";
	}

	$query_result =
	    DBQueryWarn("select distinct $fields from $table ".
			"where uid_idx='$uid_idx' $conditions");

	return $query_result;
    }
    # Ditto for delete
    function TableDelete($table, $conditions = "") {
	$uid_idx = $this->uid_idx();

	if ($conditions && $conditions != "") {
	    $conditions = "and ($conditions)";
	}
	else {
	    $conditions = "";
	}

	if (!DBQueryWarn("delete from $table ".
			 "where uid_idx='$uid_idx' $conditions"))
	    return -1;

	return 0;
    }
1519 1520 1521 1522 1523 1524 1525

    # Get user uploaded ssh keys.
    function GetSSHKeys() {
	$result  = array();
    	$uid_idx = $this->uid_idx();

	$query_result =
1526 1527
	    DBQueryFatal("select pubkey from user_pubkeys ".
			 "where uid_idx='$uid_idx' and internal=0");
1528 1529 1530 1531 1532 1533

	while ($row = mysql_fetch_array($query_result)) {
	    $result[] = $row["pubkey"];
	}
	return $result;
    }
1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
    function GetAPTSSHKey() {
    	$uid_idx = $this->uid_idx();

	$query_result =
	    DBQueryFatal("select pubkey from user_pubkeys ".
			 "where uid_idx='$uid_idx' and isaptkey=1");
	if (!mysql_num_rows($query_result))
	    return null;
	
	$row = mysql_fetch_array($query_result);
	return $row["pubkey"];
    }
1546
}
1547
?>