user_defs.php 36.2 KB
Newer Older
1 2 3
<?php
#
# EMULAB-COPYRIGHT
4
# Copyright (c) 2006, 2007, 2008 University of Utah and the Flux Group.
5 6
# All rights reserved.
#
7 8 9 10 11 12

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

13 14
class User
{
15
    var	$user;
16
    var $tempdata;		# For temporary data values ...
17

18 19 20 21 22 23 24 25 26 27
    #
    # For pedantic checks early in pages.
    #
    function ValidWebID($token) {
	if (! preg_match("/^[-\w]+$/", $token)) {
	    return 0;
	}
	return 1;
    }

28 29 30
    #
    # Constructor by lookup on unique index.
    #
31
    function User($uid_idx) {
32 33 34 35 36 37 38 39 40
	$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;
	}
41
	$this->user = mysql_fetch_array($query_result);
42 43 44 45 46 47 48 49
    }

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

    # Lookup by uid_idx.
50
    function Lookup($uid_idx) {
51 52 53 54 55
	global $user_cache;

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

57
	$foo = new User($uid_idx);
58 59 60

	if (! $foo->IsValid()) {
	    # Try lookup by plain uid.
61
	    $foo = User::LookupByUid($uid_idx);
62
	    
63
	    if (!$foo || !$foo->IsValid())
64 65 66
		return null;
	    
	    # Already in the cache from LookupByUid() so just return it.
67
	    return $foo;
68 69 70 71
	}
	# Insert into cache.
	$user_cache["$uid_idx"] =& $foo;
	return $foo;
72 73 74
    }

    # Backwards compatable lookup by uid. Will eventually flush this.
75
    function LookupByUid($uid) {
76
	$safe_uid = addslashes($uid);
77
	$status_archived = TBDB_USERSTATUS_ARCHIVED;
78 79

	$query_result =
80 81 82
	    DBQueryWarn("select uid_idx from users ".
			"where uid='$safe_uid' and ".
			"      status!='$status_archived'");
83 84 85 86 87 88 89

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

90 91
	return User::Lookup($idx);
    }
92

93 94
    # Used in the change password code and to make sure that emails are
    # locally unique.
95
    function LookupByEmail($email) {
96
	$safe_email = addslashes($email);
97
	$status_archived = TBDB_USERSTATUS_ARCHIVED;
98 99 100

	$query_result =
	    DBQueryWarn("select uid_idx from users ".
101 102
			"where LCASE(usr_email)=LCASE('$safe_email') and ".
			"      status!='$status_archived'");
103 104 105 106 107 108 109 110 111 112 113 114

	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.
115
    function LookupByWikiName($wikiname) {
116
	$safe_wikiname = addslashes($wikiname);
117
	$status_archived = TBDB_USERSTATUS_ARCHIVED;
118 119 120

	$query_result =
	    DBQueryWarn("select uid_idx from users ".
121 122
			"where wikiname='$safe_wikiname' and ".
			"      status!='$status_archived'");
123 124 125 126 127 128 129 130

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

	return User::Lookup($idx);
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
    }
    
    #
    # 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 Stoller's avatar
Leigh Stoller committed
149
	$this->user = mysql_fetch_array($query_result);
150 151 152
	return 0;
    }

153 154 155
    #
    # Class function to change the user profile.
    #
156
    function ModUserInfo($target_user, $uid, $args, &$errors) {
157 158 159 160 161 162 163 164
	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);
165
	    $errors[] = "Transient error(1); please try again later.";
166 167 168 169
	    return null;
	}
	if (! ($fp = fopen($xmlname, "w"))) {
	    TBERROR("Could not open temp file $xmlname", 0);
170
	    $errors[] = "Transient error(2); please try again later.";
171 172 173 174
	    return null;
	}

	# Add these. Maybe caller should do this?
175
	$args["uid"]  = $target_user->uid_idx();
176 177 178 179 180 181 182 183 184 185 186

	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);

187 188 189 190
	
	# 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",
191 192 193 194
			 SUEXEC_ACTION_IGNORE);

	if ($retval) {
	    if ($retval < 0) {
195
		$errors[] = "Transient error(3, $retval); please try again later.";
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
		SUEXECERROR(SUEXEC_ACTION_CONTINUE);
	    }
	    else {
		# unlink($xmlname);
		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
212
		    $errors[] = "Transient error(4, $retval); please try again later.";
213 214 215 216 217 218 219 220 221 222 223 224
	    }
	    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;
    }

225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
    #
    # Equality test.
    #
    function SameUser($user) {
	return $user->uid_idx() == $this->uid_idx();
    }

    #
    # 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();
    }

240 241 242 243 244 245
    # accessors
    function field($name) {
	return (is_null($this->user) ? -1 : $this->user[$name]);
    }
    function uid_idx()		{ return $this->field("uid_idx"); }
    function uid()		{ return $this->field("uid"); }
246
    function webid()		{ return $this->field("uid_idx"); }
247
    function dbid()		{ return $this->field("uid_idx"); }
248
    function uuid()		{ return $this->field("uid_uuid"); }
249 250 251 252 253 254
    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"); }
255
    function affil_abbrev()	{ return $this->field("usr_affil_abbrev"); }
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
    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"); }

295
    # Temporary data storage ... useful.
Leigh Stoller's avatar
Leigh Stoller committed
296 297
    function SetTempData($value) {
	$this->tempdata = $value;
298
    }
Leigh Stoller's avatar
Leigh Stoller committed
299
    function GetTempData() {
300 301 302
	return $this->tempdata;
    }

303 304 305
    #
    # Class function to create new user and return object.
    #
306
    function NewUser($uid, $flags, $args) {
307 308
	global $TBBASE, $TBMAIL_APPROVAL, $TBMAIL_AUDIT, $TBMAIL_WWW;
	global $MIN_UNIX_UID;
309

310 311 312 313
	$isleader = ($flags & TBDB_NEWACCOUNT_PROJLEADER ? 1 : 0);
	$wikionly = ($flags & TBDB_NEWACCOUNT_WIKIONLY   ? 1 : 0);
	$webonly  = ($flags & TBDB_NEWACCOUNT_WEBONLY    ? 1 : 0);

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 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
	#
	# 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);
	    }
	}
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
	
	#
	# 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 ".
405
			 "where u.unix_uid>=$MIN_UNIX_UID and ".
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
			 "      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.
422 423 424 425 426
	if ($wikionly)
	    $insert_data[] = "wikionly='1'";
	if ($webonly)
	    $insert_data[] = "webonly='1'";
	
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 466 467 468 469 470 471 472 473 474 475 476 477
	$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!"
	:
478 479 480 481
	($webonly ?
	 "Once you have verified your account, Testbed Operations will be\n".
	 "able to approve you. You MUST verify your account first!"
	 :
482 483 484 485 486 487 488 489 490 491 492
	($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".
493
	 "will be granted full access to your user account."))) .
494 495 496 497 498 499 500 501 502 503
       "\n\n".
       "Thanks,\n".
       "Testbed Operations\n",
       "From: $TBMAIL_APPROVAL\n".
       "Bcc: $TBMAIL_AUDIT\n".
       "Errors-To: $TBMAIL_WWW");
	
	return $newuser;
    }

504
    function NewNewUserXML($args, &$error) {
505 506 507 508 509 510
        #
        # Generate a temporary file and write in the XML goo.
        #
	$xmlname = tempnam("/tmp", "newuser");
	if (! $xmlname) {
	    TBERROR("Could not create temporary filename", 0);
511
	    $error = "Transient error(1); please try again later.";
512 513 514 515
	    return null;
	}
	if (! ($fp = fopen($xmlname, "w"))) {
	    TBERROR("Could not open temp file $xmlname", 0);
516
	    $error = "Transient error(2); please try again later.";
517 518 519 520 521 522 523 524 525 526 527 528 529
	    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);

530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
	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";

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

548 549 550 551 552
	$retval = SUEXEC("nobody", "nobody", "webnewuser $typearg $xmlname",
			 SUEXEC_ACTION_IGNORE);

	if ($retval) {
	    if ($retval < 0) {
553
		$error = "Transient error(3, $retval); please try again later.";
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
		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)) {
570
	    $error = "Transient error(4, $retval); please try again later.";
571 572 573 574 575 576
	    SUEXECERROR(SUEXEC_ACTION_CONTINUE);
	    return null;
	}
	$uid_idx = $matches[2];
	$newuser = User::Lookup($uid_idx);
	if (! $newuser) {
577
	    $error = "Transient error(5); please try again later.";
578 579 580 581 582 583 584 585 586
	    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;	    
    }    

587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
    #
    # 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;
    }

603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
    #
    # 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;
    }
629

630
    function Show($html = FALSE) {
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
	global $WIKISUPPORT;

	$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();
651
	$usr_affil_abbrev = $user->affil_abbrev();
652 653 654 655 656 657 658 659
	$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();
660
	$widearearoot= $user->widearearoot();
661
	$wikionly    = $user->wikionly();
662
	$stud        = $user->stud();
663
	$uuid        = $user->uuid();
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697

	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.
        #
	if (($lastweblogin = LASTWEBLOGIN($uid)) == 0)
	    $lastweblogin = "&nbsp;";
	if (($lastuserslogininfo = TBUsersLastLogin($uid)) == 0)
	    $lastuserslogin = "N/A";
	else {
	    $lastuserslogin = $lastuserslogininfo["date"] . " " .
		$lastuserslogininfo["time"];
	}
    
	if (($lastnodelogininfo = TBUidNodeLastLogin($uid)) == 0)
	    $lastnodelogin = "N/A";
	else {
	    $lastnodelogin = $lastnodelogininfo["date"] . " " .
		$lastnodelogininfo["time"] . " " .
		"(" . $lastnodelogininfo["node_id"] . ")";
	}
    
698 699
	if ($html)
	    ob_start();
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
	echo "<table align=center border=1>\n";
    
	echo "<tr>
                  <td>Username:</td>
                  <td>$uid ($uid_idx)</td>
              </tr>\n";
    
        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";
    
782 783 784 785 786
	echo "<tr>
                  <td>Institutional Abbreviation:</td>
                  <td>$usr_affil_abbrev</td>
              </tr>\n";
    
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
        echo "<tr>
                  <td>Status:</td>
                  <td>$status</td>
              </tr>\n";

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

	if ($admin) {
	    echo "<tr>
                      <td>Administrator:</td>
                      <td>Yes</td>
                  </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()) {
822 823 824 825 826
	    echo "<tr>
                    <td>UUID: </td>
                    <td class=left>$uuid</td>
                  </tr>\n";
	    
827 828 829 830 831 832 833 834 835
	    $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";
836 837 838 839 840 841 842 843 844

	    $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";
845 846 847 848 849
	
	    $freezeflip = ($frozen ? 0 : 1);
	    $toggle_url = CreateURL("toggle", $user,
				    "type", "webfreeze", "value", $freezeflip);

850 851 852 853 854 855 856 857 858 859 860 861 862
	    $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);
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
	    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";
882 883 884 885 886
	if ($html) {
	    $table_html = ob_get_contents();
	    ob_end_clean();
	    return $table_html;
	}
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
    }

    #
    # 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 ".
929
			 "     g.uid_idx='$this_idx' ".
930 931 932 933 934 935 936 937 938 939 940
			 "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;
    }

    #
941
    # How many PCs is user using. 
942 943
    #
    function PCsInUse() {
944 945 946 947 948 949 950 951 952 953 954 955 956
	$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);
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 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
    }

    #
    # 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;
    }
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
    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;
    }
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
    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;
    }
1050 1051 1052 1053 1054
    function UpdateWebLoginFail() {
	$idx   = $this->uid_idx();

	DBQueryFatal("update users set ".
		     "       weblogin_failcount=weblogin_failcount+1, ".
Leigh Stoller's avatar
Leigh Stoller committed
1055
		     "       weblogin_failstamp='now()' ".
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 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
		     "where uid_idx='$idx'");

	return $this->Refresh();
    }

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

	$uid_idx     = $this->uid_idx();
	$result      = array();
	$user_clause = "where uid_idx='$uid_idx' and";
	$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) {
	    $trust_clause = "trust='$trust_project'";
	}
	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 =
	    DBQueryFatal("SELECT distinct pid,gid FROM group_membership ".
			 "$user_clause $trust_clause order by pid");

	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;
	}
	return $result;
    }

    #
    # Return project membership list for a user.
    #
1131 1132 1133 1134 1135 1136 1137 1138
    function ProjectMembershipList($desired_trust = null) {
	$uid_idx   = $this->uid_idx();
	$result    = array();
	$condition = "";

	if ($desired_trust && $desired_trust != "") {
	    $condition = "and trust='$desired_trust'";
	}
1139 1140 1141 1142

	$query_result =
	    DBQueryFatal("select pid_idx from group_membership ".
			 "where pid_idx=gid_idx and ".
1143
			 "      uid_idx='$uid_idx' $condition");
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233

	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;
    }

    #
    # 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();
	    }
1234
	    $result["$uid_idx"][] = $group;
1235 1236 1237 1238
	}
	return $result;
    }

1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
    #
    # 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;
    }

1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
    #
    # 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);
    }
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331

    #
    # 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;
    }
1332
}