template_search.php 19.4 KB
Newer Older
1 2 3
<?php
#
# Copyright (c) 2006, 2007 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 30 31 32
#
include("defs.php3");
include_once("template_defs.php");
include_once("form_defs.php");

#
# Only known and logged in users can look at experiments.
#
$this_user = CheckLoginOrDie();
$uid       = $this_user->uid();
33
$uid_idx   = $this_user->uid_idx();
34 35 36 37 38
$isadmin   = ISADMIN();

#
# Verify page arguments.
#
39 40 41 42 43
$reqargs = RequiredPageArguments("template",     PAGEARG_TEMPLATE);
$optargs = OptionalPageArguments("search",       PAGEARG_STRING,
				 "prevsearch",   PAGEARG_STRING,
				 "addclause",    PAGEARG_STRING,
				 "formfields",   PAGEARG_ARRAY); 
44 45 46 47 48 49

#
# Standard Testbed Header after argument checking.
#
PAGEHEADER("Template Search");

50 51 52 53
# Need these below.
$guid = $template->guid();
$vers = $template->vers();

54 55 56 57 58
#
# Check permission.
#
if (! $template->AccessCheck($this_user, $TB_EXPT_READINFO)) {
    USERERROR("You do not have permission to view experiment template ".
59
	      "$guid/$vers!", 1);
60 61 62 63 64 65 66
}

#
# We display the info for all versions of the template. 
#
$root = $template->LookupRoot($template->guid());

67
echo $template->PageHeader();
68 69 70 71 72 73 74 75 76 77 78 79 80 81
echo "<br><br>\n";

# A list of match conditions we know about.
$clauseselection = array('equal'     => "==",
			 'like'      => "like",
			 'less'      => "<",
			 'lesseq'    => "<= ",
			 'greater'   => ">",
			 'greatereq' => ">=");

#
# Define the form.
#
$form = array('#id'	  => 'myform',
82
	      '#action'   => CreateURL("template_search", $template),
83
	      '#caption'  => "Search your template (records) ".
84
	                        "by parameter values");
85 86 87 88 89 90

$fields = array();

#
# Search either templates, instances, or runs.
#
91 92 93 94 95 96 97 98 99 100 101 102
$fields['searchwhat'] =
    array('#type'       => 'radio',
	  '#label'      => 'Search which template versions',
	  '#required'   => TRUE,
	  '#radios'     => array('Template' =>
				 array('#label'        => 'This Version',
				       '#return_value' => "this"),
				 'Instance' =>
				 array('#label'        => 'All Versions',
				       '#return_value' => "all")),
	  '#checkslot'  => "/^(this|all)$/");

103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
$fields['searchwhich'] =
    array('#type'       => 'radio',
	  '#label'      => 'What do you want to search',
	  '#required'   => TRUE,
	  '#radios'     => array('Template' =>
				 array('#label'        => 'Templates',
				       '#return_value' => "template"),
				 'Instance' =>
				 array('#label'        => 'Instances',
				       '#return_value' => "instance"),
				 'Run' =>
				 array('#label'        => 'Runs',
				       '#return_value' => "run")),
	  '#checkslot'  => "/^(template|instance|run)$/");

$fields['matchif'] =
    array('#type'       => 'radio',
	  '#label'      => 'Match on',
	  '#description'=> 'all clauses match or any clause matches',
	  '#required'   => TRUE,
	  '#radios'     => array('Any' =>
				 array('#label'        => 'Any',
				       '#return_value' => "any"),
				 'All' =>
				 array('#label'        => 'All',
				       '#return_value' => "all")),
	  '#checkslot'  => "/^(any|all)$/");

131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
#
# User is given the option to save this search for later.
#
$fields['save'] = array('#type'    => 'list',
			'#label'   => 'Save this search',
			'#elements'=> array('savesearch' =>
					    array('#type'       => 'checkbox',
						  '#label'      => 'Yes',
						  '#return_value'=> 1),
					    'savename'   =>
					    array('#type'       => 'textfield',
						  '#label'      => 'Save Name',
						  '#size'       => 20,
						  '#maxlength'  => 64)));

146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
#
# Grab a list of all parameters across all the templates and create
# a list of input boxes.
#
$query_result =
    DBQueryFatal("select distinct name from experiment_template_parameters ".
		 "where parent_guid='$guid' ".
		 "order by name");
$index = 1;
$paramselection = array();
while ($row = mysql_fetch_array($query_result)) {
    $paramselection[$index++] = $row['name'];
}

#
# Start with a single clause. 
#
$fields['clause1'] =
    array('#type'     => 'list',
	  '#label'    => 'Clause 1',
	  '#elements' => array('parameter1' =>
			       array('#type'      => 'select',
				     '#default'   => 'Parameter',
				     '#which'     => 1,
				     '#checkslot' => 'CheckParameter',
				     '#options'   => $paramselection),
			       'condition1' =>
			       array('#type'      => 'select',
				     '#default'   => 'Cond',
				     '#which'     => 1,
				     '#checkslot' => 'CheckCondition',
				     '#options'   => $clauseselection),
			       'value1' =>
			       array('#type'      => 'textfield',
				     '#which'     => 1,
				     '#checkslot' => 'CheckValue',
				     '#size'      => 30)));
$fields['clausecount'] = array('#type'     => 'hidden',
			       '#required' => TRUE,
			       '#value'    => "1");

#
# Spit the form out using the array of data. 
# 
function SPITFORM($formfields, $errors)
{
192
    global $form, $fields, $root, $template, $prevsearch, $this_user;
193 194

    if (($savedsearches = $root->SavedSearches($this_user))) {
195
	$action = CreateURL("template_search", $template);
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
    
	echo "<script language=JavaScript>
              function PreviousSearch() {
                  var index = document.prevsearch.prevselect.selectedIndex;
                  document.prevsearch.target='_self';
                  document.prevsearch.action='$action' + '&prevsearch=' +
                     document.prevsearch.prevselect.options[index].value;
                  document.prevsearch.submit();
              }
              </script>\n";
	echo "<form name=prevsearch onsubmit=\"return false;\"
                    action=foo method=post>\n";
	echo FormRenderSelect("savedsearches",
			      array('#type'      => 'select',
				    '#default'   => 'Choose a Previous Search',
				    '#options'   => $savedsearches,
				    '#name'      => 'prevselect',
				    '#javascript'=>
				      "onchange=\"PreviousSearch();\""));
	echo "</form>\n";
    }
217

218 219 220 221 222 223 224 225 226 227 228
    if (isset($prevsearch)) {
	#
	# Lets add a primitive mechanism to allow saved search deletion.
	# Add a delete button to the saved search row.
	#
	$fields['save']['#elements']['deletesearch'] =
	    array('#type'  => 'image',
		  '#value' => "$prevsearch",
		  '#image' => "trash.jpg");
    }
    
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
    $fields['submits'] =
	array('#type'     => 'list',
	      '#colspan'  => TRUE,
	      '#elements' => array('addclause' =>
				  array('#type'  => 'submit',
					'#value' => "Add Clause"),
				  'search' =>
				  array('#type'  => 'submit',
					'#value' => "Search")));

    echo "<center>";
    FormRender($form, $errors, $fields, $formfields);
    echo "</center>";
}

#
# On first load, display a virgin form and exit.
#
if (!isset($formfields)) {
248 249 250 251 252
    if (isset($prevsearch)) {
	$defaults = $root->SavedSearch(addslashes($prevsearch), $this_user);
    }
    else {
	$defaults = array();
253
	$defaults["searchwhat"]  = "this";
254 255 256
	$defaults["searchwhich"] = "template";
	$defaults["matchif"]     = "any";
    }
257 258 259 260 261 262 263 264 265 266 267

    SPITFORM($defaults, null);
    PAGEFOOTER();
    return;
}
# Form submitted.
if (!isset($formfields['clausecount']) ||
    $formfields['clausecount'] <= 0 || $formfields['clausecount'] > 20) {
    PAGEARGERROR("Invalid form arguments.");
}

268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
#
# Old searches. Process a deletion request before generating new list.
#
if (isset($formfields['deletesearch']) && $formfields['deletesearch'] != "" &&
    TBcheck_dbslot($formfields['deletesearch'],
		   "experiment_template_searches", "name",
		   TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
    $root->DeleteSearch(addslashes($formfields['deletesearch']), $this_user);
    #
    # Lets clear the saved search stuff.
    #
    unset($formfields['savesearch']);
    unset($formfields['savename']);
}

283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
#
# Need to generate new clauses for any added previously, plus a new one
# if the Add Clause button was pressed. But, have to watch for deleted
# clauses since the formfield names encode the clause number. In other
# words, we end up with holes in the array.
#
$clausecount = $formfields['clausecount'];
if (isset($addclause)) {
     $clausecount++;
     $formfields['clausecount'] = $clausecount;
}
for ($i = 2; $i <= $clausecount; $i++) {
    #
    # If the user used the Trash button, then delete (skip) that clause.
    # It does not matter that there are values in $formfields; they will
    # be ignored.
    #
    if (isset($formfields["delete${i}"]))
	continue;

    # Watch for holes or end of list.
    if (!isset($formfields["parameter${i}"])) {
	# Added clause goes at the end of course (not in a hole).
	if (isset($addclause) && $i == $clausecount) {
	    unset($addclause);
	}
	else
	    continue;
    }
	      
    $fields["clause${i}"] =
	array('#type'     => 'list',
	      '#label'    => "Clause $i",
	      '#elements' => array("parameter${i}" =>
				   array('#type'      => 'select',
					 '#default'   => 'Parameter',
					 '#which'     => $i,
					 '#checkslot' => 'CheckParameter',
					 '#options'   => $paramselection),
				   "condition${i}" =>
				   array('#type'      => 'select',
					 '#default'   => 'Cond',
					 '#which'     => $i,
					 '#checkslot' => 'CheckCondition',
					 '#options'   => $clauseselection),
				   "value${i}" =>
				   array('#type'      => 'textfield',
					 '#which'     => $i,
					 '#checkslot' => 'CheckValue',
					 '#size'      => 30),
				   "delete${i}" =>
				   array('#type'  => 'image',
					 '#value' => 'Delete',
					 '#image' => "trash.jpg")));
}
if (!isset($search)) {
    SPITFORM($formfields, null);
    PAGEFOOTER();
    return;
}

#
# Otherwise, must validate and redisplay if errors
#
$errors  = array();

#
# This is the callback referenced above in the checkslot fields.
#
function CheckParameter($name, &$errors, $attributes, $value)
{
    global $paramselection;
    $which = $attributes['#which'];

    if (!(isset($value) && $value != "")) {
	$errors["Parameter $which"] = "Missing required value";
	return;
    }
    
    #
    # The param value is the index of a param. It must be a real param
    # index.
    #
    if ($value < 0 || $value > count($paramselection)) {
	$errors["Parameter $which"] = "Out of range";
    }
}
function CheckCondition($name, &$errors, $attributes, $value)
{
    global $clauseselection;

    $which = $attributes['#which'];
    if (!(isset($value) && $value != "")) {
	$errors["Condition $which"] = "Missing required value";
	return;
    }
   
    if (!array_key_exists($value, $clauseselection)) {
	$errors["Condition $which"] = "Invalid condition";
    }
}
function CheckValue($name, &$errors, $attributes, $value)
{
    $which = $attributes['#which'];

    # Allow a null value. User wants to compare against ""
    if (!isset($value) || $value == "") {
	return;
    }
    
    #
    # The value has to be plain text, but thats about it. We will escape
    # it before passing off to mysql in a query.
    #
    if (!TBvalid_userdata($value)) {
	$errors["Value $which"] = TBFieldErrorString();
    }
}
FormValidate($form, $errors, $fields, $formfields);

403 404 405 406 407 408 409 410 411 412 413 414 415
# Check the save search stuff; easier then trying to automate it since 
# I need to figure out how to automate correlated checks.
if (isset($formfields['savesearch']) && $formfields['savesearch']) {
    if (!isset($formfields['savename']) || $formfields['savename'] == "") {
	$errors['Save Name'] = "Must provide a search save name";
    }
    elseif (!TBcheck_dbslot($formfields['savename'],
			    "experiment_template_searches", "name",
			    TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
	$errors['Save Name'] = TBFieldErrorString();
    }
}

416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
#
# If any errors, respit the form with the current values and the
# error messages displayed. Iterate until happy.
# 
if (count($errors)) {
    SPITFORM($formfields, $errors);
    PAGEFOOTER();
    return;
}

#
# Build up the match clauses first.
#
$clauses = array();

for ($i = 1; $i <= $clausecount; $i++) {
    $name  = $paramselection[$formfields["parameter${i}"]];
    $cond  = $formfields["condition${i}"];
    $value = addslashes($formfields["value${i}"]);

    switch ($cond) {
    case 'equal':
	$clauses[] = "(name='$name' and value='$value')";
	break;
    case 'like':
	$clauses[] = "(name='$name' and value like '$value')";
	break;
    case 'less':
	$clauses[] = "(name='$name' and value regexp '^[0-9\.]+$' and ".
	    "CAST(value as signed)<'$value')";
	break;
    case 'lesseq':
	$clauses[] = "(name='$name' and value regexp '^[0-9\.]+$' and ".
	    "CAST(value as signed)<='$value')";
	break;
    case 'greater':
	$clauses[] = "(name='$name' and value regexp '^[0-9\.]+$' and ".
	    "CAST(value as signed)>'$value')";
	break;
    case 'greatereq':
	$clauses[] = "(name='$name' and value regexp '^[0-9\.]+$' and ".
	    "CAST(value as signed)>='$value')";
	break;
    }
}
# We want all rows that match.
$clausestring = join(" or ", $clauses);

# Any/All will match the number of rows returned by above clause.
if ($formfields["matchif"] == "any") {
    $matchif = ">=1";
}
else {
    $matchif = "=" . count($clauses);
}
471 472 473 474
#
# This will be set to a specific version if not searching all template versions
#
$versionclause = "";
475 476

if ($formfields["searchwhich"] == "template") {
477 478 479
    if ($formfields["searchwhat"] == "this") {
	$versionclause = "and p.parent_vers='$vers'";
    }
480 481 482 483
    $query_string =
	"select t.* from experiment_template_parameters as p ".
	"left join experiment_templates as t on t.guid=p.parent_guid and ".
	"     t.vers=p.parent_vers ".
484
	"where (p.parent_guid='$guid' $versionclause) and ($clausestring) ".
485 486 487
	"group by t.vers having count(t.vers) $matchif";
}
elseif ($formfields["searchwhich"] == "instance") {
488 489 490
    if ($formfields["searchwhat"] == "this") {
	$versionclause = "and b.parent_vers='$vers'";
    }
491 492 493 494
    $query_string =
	"select i.* from experiment_template_instance_bindings as b ".
	"left join experiment_template_instances as i on ".
	"     i.parent_guid=b.parent_guid and ".
495 496
	"     i.parent_vers=b.parent_vers and ".
	"     i.idx=b.instance_idx ".
497
	"where (b.parent_guid='$guid' $versionclause) and ($clausestring) ".
498
	"group by i.idx having count(i.idx) $matchif";
499 500
}
else {
501
    #
502
    # This is complicated by the fact tha neither experiment_runs nor
503 504 505 506 507
    # experiment_run_bindings has a backlink to the template.
    #
    if ($formfields["searchwhat"] == "this") {
	$versionclause = "and i.parent_vers='$vers'";
    }    
508 509 510 511 512 513
    $query_string =
	"select r.*,b.runidx,i.parent_vers ".
	"     from experiment_template_instances as i ".
	"left join experiment_run_bindings as b on b.exptidx=i.exptidx ".
	"left join experiment_runs as r on ".
	"     r.exptidx=b.exptidx and r.idx=b.runidx ".
514
	"where (i.parent_guid='$guid' $versionclause) and ($clausestring) ".
515
	"group by i.idx,b.runidx having count(b.runidx) $matchif";
516 517 518 519 520 521 522 523 524 525 526
}

#TBERROR($query_string, 0);

$query_result = DBQueryWarn($query_string);
if (!$query_result || !mysql_num_rows($query_result)) {
    $errors["Match Failure"] = "There were no matches";
    SPITFORM($formfields, $errors);
    return;
}

527 528 529 530 531
# Save this search to the DB if requested.
if (isset($formfields['savesearch']) && $formfields['savesearch']) {
    DBQueryWarn("replace into experiment_template_searches set ".
		" uid_idx='$uid_idx', created=now(), ".
		" parent_guid='$guid', ".
532
		" parent_vers='" . $root->vers() . "'," .
533 534 535 536 537 538
		" name='" . addslashes($formfields['savename']) . "'," .
		" expr='" . addslashes(serialize($formfields)) . "'");
    # Indicate that we are using a saved search, so that we get delete button.
    $prevsearch = $formfields['savename'];
}

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 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
# Spit the form again so the user can change the search criteria.
SPITFORM($formfields, $errors);
echo "<br>\n";

if ($formfields["searchwhich"] == "template") {
    AddSortedTable("mytable");
    echo "<table align=center id='mytable'
		 border=1 cellpadding=5 cellspacing=2>\n";

    echo "<thead class='sort'>\n";
    echo "<tr>
            <th>Vers</th>
            <th>Parent</th>
            <th>TID</th>
            <th>Created</th>
            <th>Description</th>
          </tr>\n";
    echo "</thead>\n";

    while ($row = mysql_fetch_array($query_result)) {
	$vers    = $row['vers'];
	$tid     = $row['tid'];
	$pvers   = $row['parent_vers'];
	$tid     = $row['tid'];
	$desc    = $row['description'];
	$created = $row['created'];

	$onmouseover = MakeMouseOver($desc);
	if (strlen($desc) > 30) {
	    $desc = substr($desc, 0, 30) . " <b>... </b>";
	}
	$parent_link = MakeLink("template",
				"guid=$guid&version=$pvers", "$pvers");

	$current_link = MakeLink("template",
				 "guid=$guid&version=$vers", "$vers");

	echo "<tr>".
	    "<td>$current_link</td>".
	    "<td>$parent_link</td>".
	    "<td>$tid</td>".
	    "<td>$created</td>".
	    "<td $onmouseover>$desc</td>";
    }
    echo "</table>\n";
}
elseif ($formfields["searchwhich"] == "instance") {
    AddSortedTable("mytable");
    echo "<table align=center id='mytable'
		 border=1 cellpadding=5 cellspacing=2>\n";

    echo "<thead class='sort'>\n";
    echo "<tr>
            <th>Instance</th>
            <th>Template</th>
            <th>Started</th>
            <th>Stopped</th>
            <th>Description</th>
          </tr>\n";
    echo "</thead>\n";

    while ($row = mysql_fetch_array($query_result)) {
	$pvers    = $row['parent_vers'];
	$exptidx  = $row['exptidx'];
	$desc     = $row['description'];
	$started  = $row['start_time'];
	$stopped  = $row['stop_time'];

	$onmouseover = MakeMouseOver($desc);
	if (strlen($desc) > 30) {
	    $desc = substr($desc, 0, 30) . " <b>... </b>";
	}
	$template_link = MakeLink("template",
				  "guid=$guid&version=$pvers", "$pvers");

	$instance_link = MakeLink("instance",
				  "instance=$exptidx", "$exptidx");

	echo "<tr>".
	    "<td>$instance_link</td>".
	    "<td>$template_link</td>".
	    "<td>$started</td>".
	    "<td>$stopped</td>".
	    "<td $onmouseover>$desc</td>";
    }
    echo "</table>\n";
}
else {
    AddSortedTable("mytable");
    echo "<table align=center id='mytable'
		 border=1 cellpadding=5 cellspacing=2>\n";

    echo "<thead class='sort'>\n";
    echo "<tr>
            <th>Run</th>
            <th>Instance</th>
            <th>Template</th>
            <th>ID</th>
            <th>Started</th>
            <th>Stopped</th>
            <th>Description</th>
          </tr>\n";
    echo "</thead>\n";

    while ($row = mysql_fetch_array($query_result)) {
	$pvers    = $row['parent_vers'];
	$runidx   = $row['runidx'];
	$runid    = $row['runid'];
	$exptidx  = $row['exptidx'];
	$desc     = $row['description'];
	$started  = $row['start_time'];
	$stopped  = $row['stop_time'];

	$onmouseover = MakeMouseOver($desc);
	if (strlen($desc) > 30) {
	    $desc = substr($desc, 0, 30) . " <b>... </b>";
	}
	$template_link = MakeLink("template",
				  "guid=$guid&version=$pvers", "$pvers");

	$instance_link = MakeLink("instance",
				  "instance=$exptidx", "$exptidx");

	$run_link = MakeLink("run",
			     "instance=$exptidx&runidx=$runidx", "$runidx");

	echo "<tr>".
	    "<td>$run_link</td>".
	    "<td>$instance_link</td>".
	    "<td>$template_link</td>".
	    "<td>$runid</td>".
	    "<td>$started</td>".
	    "<td>$stopped</td>".
	    "<td $onmouseover>$desc</td>";
    }
    echo "</table>\n";
}

#
# Standard Testbed Footer
# 
PAGEFOOTER();
?>