All new accounts created on Gitlab now require administrator approval. If you invite any collaborators, please let Flux staff know so they can approve the accounts.

user_defs.php 45.6 KB
Newer Older
1 2
<?php
#
Leigh B Stoller's avatar
Leigh B Stoller committed
3
# Copyright (c) 2006-2018 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 $stats;
34
    var $tempdata;		# For temporary data values ...
35

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

46 47 48
    #
    # Constructor by lookup on unique index.
    #
49
    function User($uid_idx) {
50 51 52 53 54 55 56 57 58
	$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;
	}
59
	$this->user = mysql_fetch_array($query_result);
60 61 62 63 64 65 66 67 68 69

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

	if (!$query_result || !mysql_num_rows($query_result)) {
	    $this->user = NULL;
	    return;
	}
	$this->stats = mysql_fetch_array($query_result);
70 71 72 73 74 75 76 77
    }

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

    # Lookup by uid_idx.
78
    function Lookup($uid_idx) {
79 80 81 82 83
	global $user_cache;

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

85
	$foo = new User($uid_idx);
86 87 88

	if (! $foo->IsValid()) {
	    # Try lookup by plain uid.
89
	    $foo = User::LookupByUid($uid_idx);
90
	    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
91
	    if (!$foo || !$foo->IsValid())
92 93 94
		return null;
	    
	    # Already in the cache from LookupByUid() so just return it.
95
	    return $foo;
96 97 98 99
	}
	# Insert into cache.
	$user_cache["$uid_idx"] =& $foo;
	return $foo;
100 101 102
    }

    # Backwards compatable lookup by uid. Will eventually flush this.
103
    function LookupByUid($uid) {
104
	$safe_uid = addslashes($uid);
105
	$status_archived = TBDB_USERSTATUS_ARCHIVED;
106 107

	$query_result =
108 109
	    DBQueryWarn("select uid_idx from users ".
			"where uid='$safe_uid' and ".
110
			"      status!='$status_archived'");
111 112 113 114 115 116 117

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

118 119
	return User::Lookup($idx);
    }
120

121 122
    # Used in the change password code and to make sure that emails are
    # locally unique.
123
    function LookupByEmail($email) {
124
	$safe_email = addslashes($email);
125
	$status_archived = TBDB_USERSTATUS_ARCHIVED;
126 127 128

	$query_result =
	    DBQueryWarn("select uid_idx from users ".
129
			"where LCASE(usr_email)=LCASE('$safe_email') and ".
130
			"      status!='$status_archived'");
131 132 133 134 135 136 137 138 139 140 141 142

	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.
143
    function LookupByWikiName($wikiname) {
144
	$safe_wikiname = addslashes($wikiname);
145
	$status_archived = TBDB_USERSTATUS_ARCHIVED;
146 147 148

	$query_result =
	    DBQueryWarn("select uid_idx from users ".
149
			"where wikiname='$safe_wikiname' and ".
150
			"      status!='$status_archived'");
151 152 153 154 155 156 157 158

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

	return User::Lookup($idx);
159 160
    }
    
161 162 163 164 165 166 167
    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 ".
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
			"      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'");
187 188 189 190 191 192 193 194 195 196

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

	return User::Lookup($idx);
    }
    
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
    #
    # 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
213
	$this->user = mysql_fetch_array($query_result);
214 215 216
	return 0;
    }

217 218 219
    #
    # Class function to change the user profile.
    #
220
    function ModUserInfo($target_user, $uid, $args, &$errors) {
221 222 223 224 225 226 227 228
	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);
229
	    $errors[] = "Transient error(1); please try again later.";
230 231 232 233
	    return null;
	}
	if (! ($fp = fopen($xmlname, "w"))) {
	    TBERROR("Could not open temp file $xmlname", 0);
234
	    $errors[] = "Transient error(2); please try again later.";
235 236 237 238
	    return null;
	}

	# Add these. Maybe caller should do this?
239
	$args["uid"]  = $target_user->uid_idx();
240 241 242 243 244 245 246 247 248 249 250

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

251 252 253 254
	
	# 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",
255 256 257 258
			 SUEXEC_ACTION_IGNORE);

	if ($retval) {
	    if ($retval < 0) {
259
		$errors[] = "Transient error(3, $retval); please try again later.";
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
		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
275
		    $errors[] = "Transient error(4, $retval); please try again later.";
276
	    }
277
	    unlink($xmlname);
278 279 280 281 282 283 284 285 286 287 288
	    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;
    }

289 290 291 292
    #
    # Equality test.
    #
    function SameUser($user) {
Leigh B Stoller's avatar
Leigh B Stoller committed
293
	return $user->idx() == $this->idx();
294 295 296 297 298 299 300 301 302 303
    }

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

304 305 306 307
    # accessors
    function field($name) {
	return (is_null($this->user) ? -1 : $this->user[$name]);
    }
308 309 310
    function stats($name) {
	return (is_null($this->stats) ? -1 : $this->stats[$name]);
    }
311
    function uid_idx()		{ return $this->field("uid_idx"); }
Leigh B Stoller's avatar
Leigh B Stoller committed
312
    function idx()		{ return $this->field("uid_idx"); }
313
    function uid()		{ return $this->field("uid"); }
314
    function webid()		{ return $this->field("uid_idx"); }
315
    function dbid()		{ return $this->field("uid_idx"); }
316
    function uuid()		{ return $this->field("uid_uuid"); }
317 318 319 320 321 322
    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"); }
323
    function affil_abbrev()	{ return $this->field("usr_affil_abbrev"); }
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
    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"); }
362
    function nonlocal_id()	{ return $this->field("nonlocal_id"); }
363
    function weblogin_last()	{ return $this->stats("weblogin_last"); }
364
    function portal()	     { return $this->field("portal"); }
365
    function ga_userid()     { return $this->field("ga_userid"); }
366 367 368 369 370
    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() &&
371 372 373
                                       $this->portal() == "phantomnet" ? 1 :0);}
    function isPowder()	     { return ($this->portal() &&
                                       $this->portal() == "powder" ? 1 : 0);}
374 375 376 377
    function isEmulab()	     { return ($this->portal() &&
                                       $this->portal() == "emulab" ? 1 : 0); }
    # Not via the Portal interface.
    function isClassic()     { return ($this->portal() ? 0 : 1); }
378

379 380 381 382 383 384 385 386 387 388
    function urn() {
      global $OURDOMAIN;
      if ($this->IsNonLocal()) {
          return $this->nonlocal_id();
      } else {
          return 'urn:publicid:IDN+' .
	      $OURDOMAIN . '+user+' . $this->uid();
      }
    }

Leigh B Stoller's avatar
Leigh B Stoller committed
389 390 391
    function IsNonLocal() {
	return ($this->field("nonlocal_id") ? 1 : 0);
    }
392 393 394
    function IsActive() {
        return ($this->status() == TBDB_USERSTATUS_ACTIVE ? 1 : 0);
    }
395
    # Temporary data storage ... useful.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
396 397
    function SetTempData($value) {
	$this->tempdata = $value;
398
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
399
    function GetTempData() {
400 401 402
	return $this->tempdata;
    }

403 404 405 406 407 408 409
    function adminEmail() {
        global $TBMAIL_APPROVAL;
        
        return 
            ($this->isAPT() ? "aptlab-approval@aptlab.net" :
             ($this->isCloud() ? "cloudlab-approval@cloudlab.us" :
              ($this->isPNet() ? "phantomnet-approval@phantomnet.org" :
410 411
               ($this->isPNet() ? "powder-approval@powderwireless.net" :
                $TBMAIL_APPROVAL))));
412 413
    }

414 415 416
    #
    # Class function to create new user and return object.
    #
417
    function NewUser($uid, $flags, $args) {
418 419
	global $TBBASE, $TBMAIL_APPROVAL, $TBMAIL_AUDIT, $TBMAIL_WWW;
	global $MIN_UNIX_UID;
420

421 422 423 424
	$isleader = ($flags & TBDB_NEWACCOUNT_PROJLEADER ? 1 : 0);
	$wikionly = ($flags & TBDB_NEWACCOUNT_WIKIONLY   ? 1 : 0);
	$webonly  = ($flags & TBDB_NEWACCOUNT_WEBONLY    ? 1 : 0);

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 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
	#
	# 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);
	    }
	}
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
	
	#
	# 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 ".
516
			 "where u.unix_uid>=$MIN_UNIX_UID and ".
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
			 "      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.
533 534 535 536 537
	if ($wikionly)
	    $insert_data[] = "wikionly='1'";
	if ($webonly)
	    $insert_data[] = "webonly='1'";
	
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
	$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!"
	:
589 590 591 592
	($webonly ?
	 "Once you have verified your account, Testbed Operations will be\n".
	 "able to approve you. You MUST verify your account first!"
	 :
593 594 595 596 597 598 599 600 601 602 603
	($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".
604
	 "will be granted full access to your user account."))) .
605 606 607 608 609 610 611 612 613 614
       "\n\n".
       "Thanks,\n".
       "Testbed Operations\n",
       "From: $TBMAIL_APPROVAL\n".
       "Bcc: $TBMAIL_AUDIT\n".
       "Errors-To: $TBMAIL_WWW");
	
	return $newuser;
    }

615
    function NewNewUserXML($args, &$error) {
616 617 618 619 620 621
        #
        # Generate a temporary file and write in the XML goo.
        #
	$xmlname = tempnam("/tmp", "newuser");
	if (! $xmlname) {
	    TBERROR("Could not create temporary filename", 0);
622
	    $error = "Transient error(1); please try again later.";
623 624 625 626
	    return null;
	}
	if (! ($fp = fopen($xmlname, "w"))) {
	    TBERROR("Could not open temp file $xmlname", 0);
627
	    $error = "Transient error(2); please try again later.";
628 629 630 631 632 633 634 635 636 637 638 639 640
	    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);

641 642 643 644 645 646 647 648 649 650 651 652 653
	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";
654 655
	elseif ($flags & TBDB_NEWACCOUNT_NONLOCAL)
	    $typearg = "-t nonlocal";
656 657 658 659 660

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

661 662 663 664 665
	$retval = SUEXEC("nobody", "nobody", "webnewuser $typearg $xmlname",
			 SUEXEC_ACTION_IGNORE);

	if ($retval) {
	    if ($retval < 0) {
666
		$error = "Transient error(3, $retval); please try again later.";
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
		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)) {
683
	    $error = "Transient error(4, $retval); please try again later.";
684 685 686 687 688 689
	    SUEXECERROR(SUEXEC_ACTION_CONTINUE);
	    return null;
	}
	$uid_idx = $matches[2];
	$newuser = User::Lookup($uid_idx);
	if (! $newuser) {
690
	    $error = "Transient error(5); please try again later.";
691 692 693 694 695 696 697 698 699
	    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;	    
    }    

700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
    #
    # 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;
    }

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

Leigh B Stoller's avatar
Leigh B Stoller committed
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
    #
    # Does the user need to accept the AUP. Always goto the DB for this
    # since the user might have multiple windows/tabs.
    #
    function RequireAUP() {
        global $PORTAL_GENESIS;
	$uid_idx = $this->uid_idx();
	
	$query_result =
	    DBQueryFatal("select require_aup from users ".
			 "where uid_idx='$uid_idx' and ".
                         "      FIND_IN_SET(require_aup, '$PORTAL_GENESIS')");

        return mysql_num_rows($query_result);
    }
    function AcceptAUP($portal) {
	$uid_idx = $this->uid_idx();

        DBQueryFatal("update users set ".
                     "  require_aup=TRIM(BOTH ',' FROM ".
                     "      REPLACE(CONCAT(',', require_aup, ','), ".
                     "              CONCAT(',', '$portal', ','), ',')) ".
                     "where uid_idx='$uid_idx'");
    }

768
    function Show($html = FALSE) {
769
	global $WIKISUPPORT;
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788

	$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();
789
	$usr_affil_abbrev = $user->affil_abbrev();
790 791 792 793 794 795 796 797
	$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();
798
	$widearearoot= $user->widearearoot();
799
	$wikionly    = $user->wikionly();
800
	$stud        = $user->stud();
801
	$uuid        = $user->uuid();
802
	$portal      = $user->portal();
803
        $nonlocal_id = $user->nonlocal_id();
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820

	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.
        #
821
	if (($lastweblogin = LASTWEBLOGIN($uid_idx)) == 0)
822
	    $lastweblogin = "&nbsp;";
823
	if (($lastuserslogininfo = TBUsersLastLogin($uid_idx)) == 0)
824 825 826 827 828 829
	    $lastuserslogin = "N/A";
	else {
	    $lastuserslogin = $lastuserslogininfo["date"] . " " .
		$lastuserslogininfo["time"];
	}
    
830
	if (($lastnodelogininfo = TBUidNodeLastLogin($uid_idx)) == 0)
831 832 833 834 835 836 837
	    $lastnodelogin = "N/A";
	else {
	    $lastnodelogin = $lastnodelogininfo["date"] . " " .
		$lastnodelogininfo["time"] . " " .
		"(" . $lastnodelogininfo["node_id"] . ")";
	}
    
838 839
	if ($html)
	    ob_start();
840 841 842 843 844 845
	echo "<table align=center border=1>\n";
    
	echo "<tr>
                  <td>Username:</td>
                  <td>$uid ($uid_idx)</td>
              </tr>\n";
846 847 848 849 850 851 852

        if ($nonlocal_id) {
            echo "<tr>
                      <td>Nonlocal ID:</td>
                      <td>$nonlocal_id</td>
                      </tr>\n";
        }
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 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
    
        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";
    
929 930 931 932 933
	echo "<tr>
                  <td>Institutional Abbreviation:</td>
                  <td>$usr_affil_abbrev</td>
              </tr>\n";
    
934 935 936 937 938 939 940 941 942 943 944 945
        echo "<tr>
                  <td>Status:</td>
                  <td>$status</td>
              </tr>\n";

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

946 947 948
	if ($admin || ISADMIN()) {
	    $admintag = ($admin ? "Yes" : "No");

949 950
	    echo "<tr>
                      <td>Administrator:</td>
951 952
                      <td>$admintag";
	    
953 954 955
	    $adminflip = ($admin ? 0 : 1);
	    $toggle_url = CreateURL("toggle", $user, "type", "adminflag",
				    "value", $adminflip);
956

957 958
	    echo " (<em>Be very careful with this</em> ".
		"<a href='$toggle_url'>Toggle</a>)";
959 960

	    echo "</td>
961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979
                  </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()) {
980 981 982 983
	    echo "<tr>
                    <td>UUID: </td>
                    <td class=left>$uuid</td>
                  </tr>\n";
984

985
	    if (isset($portal)) {
986
		echo "<tr>
987 988
                      <td>Portal: </td>
                      <td class=left>$portal</td>
989 990
                   </tr>\n";
	    }
991 992
	}
	if (ISADMIN() && $status != TBDB_USERSTATUS_ARCHIVED) {
993 994 995 996 997 998 999 1000 1001
	    $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";
1002 1003 1004 1005 1006 1007 1008 1009 1010

	    $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";
1011 1012 1013 1014 1015
	
	    $freezeflip = ($frozen ? 0 : 1);
	    $toggle_url = CreateURL("toggle", $user,
				    "type", "webfreeze", "value", $freezeflip);

1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
	    $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);
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
	    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";
1048 1049 1050 1051 1052
	if ($html) {
	    $table_html = ob_get_contents();
	    ob_end_clean();
	    return $table_html;
	}
1053 1054 1055 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
    }

    #
    # 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 ".
1095
			 "     g.uid_idx='$this_idx' ".
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
			 "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;
    }

    #
1107
    # How many PCs is user using. 
1108 1109
    #
    function PCsInUse() {
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
	$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);
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 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
    }

    #
    # 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;
    }
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
    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;
    }
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
    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;
    }
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
    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;
    }
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
    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;
    }
1238 1239 1240 1241 1242
    function UpdateWebLoginFail() {
	$idx   = $this->uid_idx();

	DBQueryFatal("update users set ".
		     "       weblogin_failcount=weblogin_failcount+1, ".
1243
		     "       weblogin_failstamp=UNIX_TIMESTAMP(now()) ".
1244 1245 1246 1247
		     "where uid_idx='$idx'");

	return $this->Refresh();
    }
1248 1249 1250 1251 1252 1253
    function HasEncryptedCert($expired_notokay) {
	$query_result =
	    $this->TableLookUp("user_sslcerts", "cert,privkey",
			       "encrypted=1 and revoked is null ".
			       ($expired_notokay ? "and expires > now()" : ""));
					   
1254 1255
	return mysql_num_rows($query_result);
    }
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
    #
    # Generate an encrypted certificate using existing passphrase or
    # randomized one.
    #
    function GenEncryptedCert() {
        $project = $this->FirstApprovedProject();
        $pid = (isset($project) ? $project->pid() : "nobody");
        $uid = $this->uid();
        
        SUEXEC($uid, $pid,
               "webmkusercert -r -P -G $uid",
               SUEXEC_ACTION_CONTINUE);
    }
    
1270 1271 1272 1273 1274 1275 1276 1277
    function SetGaUserid($id) {
	$idx = $this->uid_idx();

	DBQueryFatal("update users set ga_userid='$id' ".
		     "where uid_idx='$idx'");
	$this->user["ga_userid"] = $id;
	return 0;
    }
1278 1279 1280 1281 1282 1283

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

	$uid_idx     = $this->uid_idx();
	$result      = array();
1292
	$user_clause = "where uid_idx='$uid_idx' and p.nonlocal_id is null and";
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
	$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
1306
	    $trust_clause = "trust='$trust_group'";
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
	}
	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 =
1330 1331 1332 1333
	    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");
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344

	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;
	}
1345 1346 1347 1348 1349 1350

        # 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 ".
1351
                         " group by s.pid,s.pid_idx order by last desc) ".
1352 1353 1354 1355
                         "union ".
                         "(select pid,max(UNIX_TIMESTAMP(created)) as last ".
                         " from apt_instances ".
                         " where creator_idx='$uid_idx' and pid is not null ".
1356
                         " group by pid,pid_idx order by last desc)");
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
        
	$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);
1379 1380 1381 1382 1383 1384
	return $result;
    }

    #
    # Return project membership list for a user.
    #
1385 1386 1387 1388 1389 1390 1391 1392
    function ProjectMembershipList($desired_trust = null) {
	$uid_idx   = $this->uid_idx();
	$result    = array();
	$condition = "";

	if ($desired_trust && $desired_trust != "") {
	    $condition = "and trust='$desired_trust'";
	}
1393 1394 1395 1396

	$query_result =
	    DBQueryFatal("select pid_idx from group_membership ".
			 "where pid_idx=gid_idx and ".
1397
			 "      uid_idx='$uid_idx' $condition");
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410

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

1411 1412 1413 1414 1415 1416 1417 1418 1419
    #
    # 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);
    }

1420 1421 1422 1423 1424 1425 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 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
    #
    # 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();
	    }
1497
	    $result["$uid_idx"][] = $group;
1498 1499 1500 1501
	}
	return $result;
    }

1502 1503 1504
    #
    # Return list of experiments for a user, or just a count.
    #
1505
    function ExperimentList($listify = 1, $target = null) {
1506 1507 1508 1509
	$uid_idx = $this->uid_idx();
	$gclause = "";

	# within optional group only.
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
        if ($target) {
            if (get_class($target) == "Group") {
                $pid     = $target->pid();
                $gid     = $target->gid();
                $gclause = "and pid='$pid' and gid='$gid'";
            }
            else {
                $pid     = $target->pid();
                $gclause = "and pid='$pid'";
            }
        }
1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544

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

1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561
    #
    # 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);
    }
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572