user_defs.php 47.7 KB
Newer Older
1 2
<?php
#
Leigh Stoller's avatar
Leigh 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
	    
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
	}
	# Insert into cache.
98 99
	$user_cache["$uid_idx"]  =& $foo;
	$user_cache[$foo->uid()] =& $foo;
100
	return $foo;
101 102 103
    }

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

109 110 111 112
        # Look in cache first
	if (array_key_exists("$uid", $user_cache))
	    return $user_cache["$uid"];

113
	$query_result =
114 115
	    DBQueryWarn("select uid_idx from users ".
			"where uid='$safe_uid' and ".
116
			"      status!='$status_archived'");
117 118 119 120 121 122 123

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

124 125
	return User::Lookup($idx);
    }
126

127 128
    # Used in the change password code and to make sure that emails are
    # locally unique.
129
    function LookupByEmail($email) {
130
	$safe_email = addslashes($email);
131
	$status_archived = TBDB_USERSTATUS_ARCHIVED;
132 133 134

	$query_result =
	    DBQueryWarn("select uid_idx from users ".
135
			"where LCASE(usr_email)=LCASE('$safe_email') and ".
136
			"      status!='$status_archived'");
137 138 139 140 141 142 143 144 145 146 147 148

	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.
149
    function LookupByWikiName($wikiname) {
150
	$safe_wikiname = addslashes($wikiname);
151
	$status_archived = TBDB_USERSTATUS_ARCHIVED;
152 153 154

	$query_result =
	    DBQueryWarn("select uid_idx from users ".
155
			"where wikiname='$safe_wikiname' and ".
156
			"      status!='$status_archived'");
157 158 159 160 161 162 163 164

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

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

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

	return User::Lookup($idx);
    }
    
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
    #
    # 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
219
	$this->user = mysql_fetch_array($query_result);
220 221 222
	return 0;
    }

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

	# Add these. Maybe caller should do this?
245
	$args["uid"]  = $target_user->uid_idx();
246 247 248 249 250 251 252 253 254 255 256

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

257 258 259 260
	
	# 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",
261 262 263 264
			 SUEXEC_ACTION_IGNORE);

	if ($retval) {
	    if ($retval < 0) {
265
		$errors[] = "Transient error(3, $retval); please try again later.";
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
		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
Leigh Stoller's avatar
Leigh Stoller committed
281
		    SUEXECERROR(SUEXEC_ACTION_CONTINUE);
282
		    $errors[] = "Transient error(4, $retval); please try again later.";
283
	    }
284
	    unlink($xmlname);
285 286 287 288 289 290 291 292 293 294 295
	    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;
    }

296 297 298 299
    #
    # Equality test.
    #
    function SameUser($user) {
Leigh Stoller's avatar
Leigh Stoller committed
300
	return $user->idx() == $this->idx();
301 302 303 304 305 306 307 308 309 310
    }

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

311 312 313 314
    # accessors
    function field($name) {
	return (is_null($this->user) ? -1 : $this->user[$name]);
    }
315 316 317
    function stats($name) {
	return (is_null($this->stats) ? -1 : $this->stats[$name]);
    }
318
    function uid_idx()		{ return $this->field("uid_idx"); }
Leigh Stoller's avatar
Leigh Stoller committed
319
    function idx()		{ return $this->field("uid_idx"); }
320
    function uid()		{ return $this->field("uid"); }
321
    function webid()		{ return $this->field("uid_idx"); }
322
    function dbid()		{ return $this->field("uid_idx"); }
323
    function uuid()		{ return $this->field("uid_uuid"); }
324 325 326 327 328 329
    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"); }
330
    function affil_abbrev()	{ return $this->field("usr_affil_abbrev"); }
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
    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"); }
369
    function nonlocal_id()	{ return $this->field("nonlocal_id"); }
370
    function weblogin_last()	{ return $this->stats("weblogin_last"); }
371
    function portal()	     { return $this->field("portal"); }
372
    function ga_userid()     { return $this->field("ga_userid"); }
373 374
    function portal_interface_warned() {
        return $this->field("portal_interface_warned"); }
375 376 377 378 379
    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() &&
380 381 382
                                       $this->portal() == "phantomnet" ? 1 :0);}
    function isPowder()	     { return ($this->portal() &&
                                       $this->portal() == "powder" ? 1 : 0);}
383 384 385 386
    function isEmulab()	     { return ($this->portal() &&
                                       $this->portal() == "emulab" ? 1 : 0); }
    # Not via the Portal interface.
    function isClassic()     { return ($this->portal() ? 0 : 1); }
387

388 389 390 391 392 393 394 395 396 397
    function urn() {
      global $OURDOMAIN;
      if ($this->IsNonLocal()) {
          return $this->nonlocal_id();
      } else {
          return 'urn:publicid:IDN+' .
	      $OURDOMAIN . '+user+' . $this->uid();
      }
    }

398 399 400
    function IsNonLocal() {
	return ($this->field("nonlocal_id") ? 1 : 0);
    }
401 402 403
    function IsActive() {
        return ($this->status() == TBDB_USERSTATUS_ACTIVE ? 1 : 0);
    }
404
    # Temporary data storage ... useful.
Leigh Stoller's avatar
Leigh Stoller committed
405 406
    function SetTempData($value) {
	$this->tempdata = $value;
407
    }
Leigh Stoller's avatar
Leigh Stoller committed
408
    function GetTempData() {
409 410 411
	return $this->tempdata;
    }

412 413 414 415 416 417 418
    function adminEmail() {
        global $TBMAIL_APPROVAL;
        
        return 
            ($this->isAPT() ? "aptlab-approval@aptlab.net" :
             ($this->isCloud() ? "cloudlab-approval@cloudlab.us" :
              ($this->isPNet() ? "phantomnet-approval@phantomnet.org" :
419 420
               ($this->isPNet() ? "powder-approval@powderwireless.net" :
                $TBMAIL_APPROVAL))));
421 422
    }

423 424 425
    #
    # Class function to create new user and return object.
    #
426
    function NewUser($uid, $flags, $args) {
427 428
	global $TBBASE, $TBMAIL_APPROVAL, $TBMAIL_AUDIT, $TBMAIL_WWW;
	global $MIN_UNIX_UID;
429

430 431 432 433
	$isleader = ($flags & TBDB_NEWACCOUNT_PROJLEADER ? 1 : 0);
	$wikionly = ($flags & TBDB_NEWACCOUNT_WIKIONLY   ? 1 : 0);
	$webonly  = ($flags & TBDB_NEWACCOUNT_WEBONLY    ? 1 : 0);

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 495 496 497 498 499 500 501 502 503
	#
	# 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);
	    }
	}
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
	
	#
	# 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 ".
525
			 "where u.unix_uid>=$MIN_UNIX_UID and ".
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
			 "      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.
542 543 544 545 546
	if ($wikionly)
	    $insert_data[] = "wikionly='1'";
	if ($webonly)
	    $insert_data[] = "webonly='1'";
	
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 589 590 591 592 593 594 595 596 597
	$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!"
	:
598 599 600 601
	($webonly ?
	 "Once you have verified your account, Testbed Operations will be\n".
	 "able to approve you. You MUST verify your account first!"
	 :
602 603 604 605 606 607 608 609 610 611 612
	($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".
613
	 "will be granted full access to your user account."))) .
614 615 616 617 618 619 620 621 622 623
       "\n\n".
       "Thanks,\n".
       "Testbed Operations\n",
       "From: $TBMAIL_APPROVAL\n".
       "Bcc: $TBMAIL_AUDIT\n".
       "Errors-To: $TBMAIL_WWW");
	
	return $newuser;
    }

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

650 651 652 653 654 655 656 657 658 659 660 661 662
	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";
663 664
	elseif ($flags & TBDB_NEWACCOUNT_NONLOCAL)
	    $typearg = "-t nonlocal";
665 666 667 668 669

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

670 671 672 673 674
	$retval = SUEXEC("nobody", "nobody", "webnewuser $typearg $xmlname",
			 SUEXEC_ACTION_IGNORE);

	if ($retval) {
	    if ($retval < 0) {
675
		$error = "Transient error(3, $retval); please try again later.";
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
		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)) {
692
	    $error = "Transient error(4, $retval); please try again later.";
693 694 695 696 697 698
	    SUEXECERROR(SUEXEC_ACTION_CONTINUE);
	    return null;
	}
	$uid_idx = $matches[2];
	$newuser = User::Lookup($uid_idx);
	if (! $newuser) {
699
	    $error = "Transient error(5); please try again later.";
700 701 702 703 704 705 706 707 708
	    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;	    
    }    

709 710 711 712 713 714 715 716 717 718 719 720 721
    #
    # 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"]);
	
722 723 724
	if (array_key_exists($this->uid(), $user_cache))
	    unset($user_cache[$this->uid()]);
	
725 726 727
	return 0;
    }

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

Leigh Stoller's avatar
Leigh Stoller committed
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
    #
    # 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'");
    }

780 781 782 783 784 785 786 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
    #
    # Find all the project licenses this user needs to accept (as leader
    # of a project that is required to accept a license).
    #
    function ProjectLicenses() {
	$uid_idx   = $this->uid_idx();
        $trust     = TBDB_TRUSTSTRING_PROJROOT;

        $query_result = 
	    DBQueryFatal("select pl.*,l.* from group_membership as g ".
                         "left join projects as p on p.pid_idx=g.pid_idx ".
                         "inner join project_licenses as pl on ".
                         "      pl.pid_idx=g.pid_idx ".
                         "left join licenses as l on ".
                         "     l.license_idx=pl.license_idx ".
			 "where g.pid_idx=g.gid_idx and ".
			 "      g.uid_idx='$uid_idx' and ".
                         "      g.trust='$trust' and ".
                         "      pl.accepted is null and ".
                         "      p.approved!=0");
        
	if (mysql_num_rows($query_result) == 0) {
	    return null;
	}
        $result = array();

        while ($row = mysql_fetch_array($query_result)) {
            $result[] = $row;
        }
        return $result;
    }

812
    function Show($html = FALSE) {
813
	global $WIKISUPPORT;
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832

	$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();
833
	$usr_affil_abbrev = $user->affil_abbrev();
834 835 836 837 838 839 840 841
	$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();
842
	$widearearoot= $user->widearearoot();
843
	$wikionly    = $user->wikionly();
844
	$stud        = $user->stud();
845
	$uuid        = $user->uuid();
846
	$portal      = $user->portal();
847
        $nonlocal_id = $user->nonlocal_id();
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864

	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.
        #
865
	if (($lastweblogin = LASTWEBLOGIN($uid_idx)) == 0)
866
	    $lastweblogin = "&nbsp;";
867
	if (($lastuserslogininfo = TBUsersLastLogin($uid_idx)) == 0)
868 869 870 871 872 873
	    $lastuserslogin = "N/A";
	else {
	    $lastuserslogin = $lastuserslogininfo["date"] . " " .
		$lastuserslogininfo["time"];
	}
    
874
	if (($lastnodelogininfo = TBUidNodeLastLogin($uid_idx)) == 0)
875 876 877 878 879 880 881
	    $lastnodelogin = "N/A";
	else {
	    $lastnodelogin = $lastnodelogininfo["date"] . " " .
		$lastnodelogininfo["time"] . " " .
		"(" . $lastnodelogininfo["node_id"] . ")";
	}
    
882 883
	if ($html)
	    ob_start();
884 885 886 887 888 889
	echo "<table align=center border=1>\n";
    
	echo "<tr>
                  <td>Username:</td>
                  <td>$uid ($uid_idx)</td>
              </tr>\n";
890 891 892 893 894 895 896

        if ($nonlocal_id) {
            echo "<tr>
                      <td>Nonlocal ID:</td>
                      <td>$nonlocal_id</td>
                      </tr>\n";
        }
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 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
    
        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";
    
973 974 975 976 977
	echo "<tr>
                  <td>Institutional Abbreviation:</td>
                  <td>$usr_affil_abbrev</td>
              </tr>\n";
    
978 979 980 981 982 983 984 985 986 987 988 989
        echo "<tr>
                  <td>Status:</td>
                  <td>$status</td>
              </tr>\n";

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

990 991 992
	if ($admin || ISADMIN()) {
	    $admintag = ($admin ? "Yes" : "No");

993 994
	    echo "<tr>
                      <td>Administrator:</td>
995 996
                      <td>$admintag";
	    
997 998 999
	    $adminflip = ($admin ? 0 : 1);
	    $toggle_url = CreateURL("toggle", $user, "type", "adminflag",
				    "value", $adminflip);
1000

1001 1002
	    echo " (<em>Be very careful with this</em> ".
		"<a href='$toggle_url'>Toggle</a>)";
1003 1004

	    echo "</td>
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
                  </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()) {
1024 1025 1026 1027
	    echo "<tr>
                    <td>UUID: </td>
                    <td class=left>$uuid</td>
                  </tr>\n";
1028

1029
	    if (isset($portal)) {
1030
		echo "<tr>
1031 1032
                      <td>Portal: </td>
                      <td class=left>$portal</td>
1033 1034
                   </tr>\n";
	    }
1035 1036
	}
	if (ISADMIN() && $status != TBDB_USERSTATUS_ARCHIVED) {
1037 1038 1039 1040 1041 1042 1043 1044 1045
	    $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";
1046 1047 1048 1049 1050 1051 1052 1053 1054

	    $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";
1055 1056 1057 1058 1059
	
	    $freezeflip = ($frozen ? 0 : 1);
	    $toggle_url = CreateURL("toggle", $user,
				    "type", "webfreeze", "value", $freezeflip);

1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
	    $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);
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
	    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";
1092 1093 1094 1095 1096
	if ($html) {
	    $table_html = ob_get_contents();
	    ob_end_clean();
	    return $table_html;
	}
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
    }

    #
    # 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 ".
1139
			 "     g.uid_idx='$this_idx' ".
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
			 "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;
    }

    #
1151
    # How many PCs is user using. 
1152 1153
    #
    function PCsInUse() {
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
	$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);
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 1234 1235 1236 1237
    }

    #
    # 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;
    }
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
    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;
    }
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
    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;
    }
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
    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;
    }
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
    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;
    }
1282 1283 1284 1285 1286 1287 1288 1289 1290
    function SetPortalWarned() {
	$idx   = $this->uid_idx();

	DBQueryFatal("update users set ".
		     "   portal_interface_warned='1' ".
		     "where uid_idx='$idx'");
	$this->user["portal_interface_warned"] = 1;
	return 0;
    }
1291 1292 1293 1294 1295
    function UpdateWebLoginFail() {
	$idx   = $this->uid_idx();

	DBQueryFatal("update users set ".
		     "       weblogin_failcount=weblogin_failcount+1, ".
1296
		     "       weblogin_failstamp=UNIX_TIMESTAMP(now()) ".
1297 1298 1299 1300
		     "where uid_idx='$idx'");

	return $this->Refresh();
    }
1301 1302 1303 1304 1305 1306
    function HasEncryptedCert($expired_notokay) {
	$query_result =
	    $this->TableLookUp("user_sslcerts", "cert,privkey",
			       "encrypted=1 and revoked is null ".
			       ($expired_notokay ? "and expires > now()" : ""));
					   
1307 1308
	return mysql_num_rows($query_result);
    }
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
    #
    # 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);
    }
    
1323 1324 1325 1326 1327 1328 1329 1330
    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;
    }
1331 1332 1333 1334 1335 1336

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

	$uid_idx     = $this->uid_idx();
	$result      = array();
1345
	$user_clause = "where uid_idx='$uid_idx' and p.nonlocal_id is null and";
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
	$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 Stoller's avatar
Leigh Stoller committed
1359
	    $trust_clause = "trust='$trust_group'";
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
	}
	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 =
1383 1384 1385 1386
	    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");
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397

	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;
	}
1398 1399 1400 1401 1402 1403

        # 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 ".
1404
                         " group by s.pid,s.pid_idx order by last desc) ".
1405 1406 1407 1408
                         "union ".
                         "(select pid,max(UNIX_TIMESTAMP(created)) as last ".
                         " from apt_instances ".
                         " where creator_idx='$uid_idx' and pid is not null ".
1409
                         " group by pid,pid_idx order by last desc)");
1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
        
	$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);
1432 1433 1434 1435 1436 1437
	return $result;
    }

    #
    # Return project membership list for a user.
    #
1438 1439 1440 1441 1442 1443 1444 1445
    function ProjectMembershipList($desired_trust = null) {
	$uid_idx   = $this->uid_idx();
	$result    = array();
	$condition = "";

	if ($desired_trust && $desired_trust != "") {
	    $condition = "and trust='$desired_trust'";
	}
1446 1447 1448 1449

	$query_result =
	    DBQueryFatal("select pid_idx from group_membership ".
			 "where pid_idx=gid_idx and ".
1450
			 "      uid_idx='$uid_idx' $condition");
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463

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

1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478
    #
    # Return a list of disabled projects for user, if any.
    #
    function DisabledProjects() {
	$result   = array();
        $projlist = $this->ProjectMembershipList();

        foreach ($projlist as $project) {
            if ($project->disabled()) {
                $result[] = $project;
            }
        }
        return $result;
    }

1479 1480 1481 1482 1483 1484 1485 1486 1487
    #
    # 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);
    }

1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564
    #
    # 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();
	    }
1565
	    $result["$uid_idx"][] = $group;
1566 1567 1568 1569
	}
	return $result;
    }

1570 1571 1572
    #
    # Return list of experiments for a user, or just a count.
    #
1573
    function ExperimentList($listify = 1, $target = null) {
1574 1575 1576 1577
	$uid_idx = $this->uid_idx();
	$gclause = "";

	# within optional group only.
1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
        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'";
            }
        }
1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612

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

1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629
    #
    # 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);
    }
1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668

    #
    # 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;
    }
1669 1670 1671 1672 1673 1674 1675

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

	$query_result =
1676 1677
	    DBQueryFatal("select pubkey from user_pubkeys ".
			 "where uid_idx='$uid_idx' and internal=0");
1678 1679 1680 1681 1682 1683

	while ($row = mysql_fetch_array($query_result)) {
	    $result[] = $row["pubkey"];
	}
	return $result;
    }
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695
    function GetAPTSSHKey() {
    	$uid_idx = $this->uid_idx();

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