diff --git a/.codeclimate.yml b/.codeclimate.yml index c50476375..c2a5e1312 100644 --- a/.codeclimate.yml +++ b/.codeclimate.yml @@ -2,6 +2,9 @@ version: "2" plugins: phpcodesniffer: enabled: true + # Need the beta channel to enforce PSR12, + # see https://docs.codeclimate.com/docs/phpcodesniffer#standard. + channel: "beta" config: standard: "phpcs.xml" phpmd: diff --git a/.github/workflows/continuous-integration.yml b/.github/workflows/continuous-integration.yml index 146097a77..4f7a6186a 100644 --- a/.github/workflows/continuous-integration.yml +++ b/.github/workflows/continuous-integration.yml @@ -18,7 +18,7 @@ jobs: steps: - name: "Checkout" - uses: "actions/checkout@v3" + uses: "actions/checkout@v4" with: fetch-depth: 2 @@ -106,7 +106,7 @@ jobs: steps: - name: "Checkout" - uses: "actions/checkout@v3" + uses: "actions/checkout@v4" with: fetch-depth: 2 diff --git a/config/gocdb_schema.xml b/config/gocdb_schema.xml index 414320453..8320bd4c1 100644 --- a/config/gocdb_schema.xml +++ b/config/gocdb_schema.xml @@ -415,18 +415,22 @@ - service_type - - NAME - 255 - /^([[:alpha:]]|[[:digit:]]|[\._-])*$/ - - - DESCRIPTION - 255 - - /^[^`'\";<>]+$/ - + service_type + + NAME + 255 + /^([[:alpha:]]|[[:digit:]]|[\._-])*$/ + + + DESCRIPTION + 255 + + /^[^`'\";<>]+$/ + + + ALLOWMONITORINGEXCEPTION + boolean + diff --git a/config/local_info.xml b/config/local_info.xml index 6115d7ed8..ee3cdb787 100755 --- a/config/local_info.xml +++ b/config/local_info.xml @@ -1,9 +1,11 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/web_portal/README.md b/config/web_portal/README.md new file mode 100644 index 000000000..a72169350 --- /dev/null +++ b/config/web_portal/README.md @@ -0,0 +1,57 @@ +# Auto-generation of menu.xsd and its use in GOCDB configuration + +## What *config/web_portal/menu.xsd* is for + +This file is the schema file for the definiton of GOCDB's left-hand column menu, used to check that only valid menu names are included in the GOCDB main configuration file config/local_info.xml. The menu.xsd file is built automatically, **do not edit it** - see the next question. + +GOCDB uses an XML definition (config/web_portal/menu.xml) to programatically draw the left-hand menu items on the user +interface. Which menu items are drawn is selected via the \ element in the GOCDB configuration file (config/local_info.xml). To check that only valid menu item names are given within the \ element it is necessary to generate an XML schema containing all valid menu names (config/web_portal/menu.xsd). + +## What *config/web_portal/menu.xslt* is for + +This file is the transformation file which builds the menu.xsd schema definition file - see the previous question - from the menu definition file config/web_portal/menu.xml. + +To avoid having to specify menu names manually twice: once in the XML and once in the schema definition (config/local_info.xsd), an XSL Transformation file (config/web_portal/menu.xslt) is used to generate the menu schema (config/web_portal/menu.xsd) directly from the XML menu file. This menu schema is then included into the overall GOCDB schema when the configuration is validated. + +## How to make changes made to the left-hand menu + +Left-hand menu items can be added or deleted by editing the menu XML file (config/web_portal/menu.xml). You should then run the XSL Transformation processor command *xsltproc* to generate a new menu schema - + +```bash +xsltproc -o menu.xsd menu.xslt menu.xml +``` + +The resulting .xsd file will automatically be included in the configuration validation. + +## Why these files are used + +To prevent mistypes and other difficult-to-spot configuration errors, GOCDB uses an XML schema file (config/local_info.xsd) to validate the XML elements given in the main configuration file (config/local_info.xml). + +## How these files are used + +Checking that the schema is correct is done as part of the operations monitoring tests (htdocs/web_portal/GOCDB_monitor/*). + +An XSLT translation file is not used to build the main configuration schema file (config/local_info.xsd) because the menu XML is part of the codebase, whereas the main configuration XML is variable content to be validated against the main schema definition which is also part of the codebase. + +```mermaid +--- +title: Updating menu items and configuration validation +--- +flowchart TB + menu.xml[config/web_portal/menu.xml] + menu.xsd[config/web_portal/menu.xsd] + menu.xslt[config/web_portal/menu.xslt] + local_info.xsd[config/local_info.xsd] + local_info.xml[config/local_info.xml] + + edits([add or delete menu items]) -->menu.xml + + menu.xml & menu.xslt --> xsltproc[[xsltproc translation]] -->menu.xsd + + menu.xsd-->|include in|local_info.xsd + + config([configuration value edits]) -->local_info.xml + + local_info.xsd & local_info.xml --> validation[[XML validation]] --> result[\"#nbsp;Result: valid or invalid configuration#nbsp;"\] + +``` diff --git a/config/web_portal/menu.xsd b/config/web_portal/menu.xsd new file mode 100644 index 000000000..7a62fad05 --- /dev/null +++ b/config/web_portal/menu.xsd @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/web_portal/menu.xslt b/config/web_portal/menu.xslt new file mode 100644 index 000000000..6aaf67cc3 --- /dev/null +++ b/config/web_portal/menu.xslt @@ -0,0 +1,48 @@ + + + + + + + + + + + ** DO NOT EDIT THIS FILE DIRECTLY. ** + ** THIS FILE IS AUTO GENERATED. ** + ** SEE menu.xslt FOR DETAILS. ** + + <xs:schema version="1.0" + xmlns:xs="http://www.w3.org/2001/XMLSchema" + > + + <xs:complexType name="validMenus"> + <xs:all> + + + </xs:all> + </xs:complexType> +</xs:schema> + + + + + + <xs:element name=" + + " type="showType" minOccurs="0"/> + + + + + + diff --git a/htdocs/PI/index.php b/htdocs/PI/index.php index 8029fc636..49ba91642 100644 --- a/htdocs/PI/index.php +++ b/htdocs/PI/index.php @@ -1,4 +1,4 @@ -method = $_GET['method']; unset($_GET['method']); @@ -367,11 +366,11 @@ private function getXml() break; case "get_site_count_per_country": require_once($directory . 'GetSiteCountPerCountry.php'); - $getSiteCountPerCountry = new GetSiteCountPerCountry($em); - $getSiteCountPerCountry->validateParameters($this->params); - $getSiteCountPerCountry->createQuery(); - $getSiteCountPerCountry->executeQuery(); - $xml = $getSiteCountPerCountry->getRenderingOutput(); + $getCountrySiteCount = new GetSiteCountPerCountry($em); + $getCountrySiteCount->validateParameters($this->params); + $getCountrySiteCount->createQuery(); + $getCountrySiteCount->executeQuery(); + $xml = $getCountrySiteCount->getRenderingOutput(); break; //case "get_role_action_mappings": default: @@ -404,19 +403,20 @@ private function authByIdentifier($forceStrictForHosts = false) $admin = false; $authenticated = false; + // Check if incoming identifier is a registered API Authentication credential. + + $authEntServ = \Factory::getAPIAuthenticationService(); + $authEnt = $authEntServ->getAPIAuthentication($this->identifier); + + if (!is_null($authEnt)) { + $authEntServ->updateLastUseTime($authEnt); + $authenticated = true; + } + $user = \Factory::getUserService()->getUserByPrinciple($this->identifier); if ($user == null) { // Incoming credential is not that of a registered user. - // Check if it is registered API Authentication credential. - - $authEntServ = \Factory::getAPIAuthenticationService(); - $authEnts = $authEntServ->getAPIAuthentication($this->identifier); - - if (count($authEnts) > 0) { - $authEntServ->updateLastUseTime($authEnts); - $authenticated = true; - } if (!\Factory::getConfigService()->isRestrictPDByRole($forceStrictForHosts)) { // Only a 'valid' identifier is needed. diff --git a/htdocs/PI/private/index.php b/htdocs/PI/private/index.php index 131d68312..dbd87c5c7 100644 --- a/htdocs/PI/private/index.php +++ b/htdocs/PI/private/index.php @@ -22,4 +22,4 @@ include '../index.php'; -?> \ No newline at end of file +?> diff --git a/htdocs/PI/public/index.php b/htdocs/PI/public/index.php index 3de6f28a9..fedc043bb 100644 --- a/htdocs/PI/public/index.php +++ b/htdocs/PI/public/index.php @@ -21,4 +21,4 @@ /*====================================================== */ include '../index.php'; -?> \ No newline at end of file +?> diff --git a/htdocs/PI/write/PIWriteRequest.php b/htdocs/PI/write/PIWriteRequest.php index 0c2c140cd..d3149635b 100644 --- a/htdocs/PI/write/PIWriteRequest.php +++ b/htdocs/PI/write/PIWriteRequest.php @@ -975,7 +975,7 @@ private function updateServicePropPut (\Service $service, $servicePropName, $ser //Validate production/monitored flag combination try { - $this->serviceService->validateProductionMonitoredCombination($service->getServiceType()->getName(), $production, $monitored); + $this->serviceService->validateProductionMonitoredCombination($service->getServiceType(), $production, $monitored); } catch(\Exception $e){ $this->exceptionWithResponseCode(403, $e->getMessage()); } @@ -1351,7 +1351,7 @@ private function updateEndpointPropPost (\EndpointLocation $endpoint, $endpointP #POST not valid for Endpoint booleans as they are set when the entity created and so are already defined $this->exceptionWithResponseCode(405,$this->genericExceptionMessages["cantPostABool"]); - } elseif ($this->serviceService->EndpointPropSet($endpoint, $endpointPropName)) { + } elseif ($this->serviceService->endpointPropSet($endpoint, $endpointPropName)) { #POST method must fail if the value is already set $this->exceptionWithResponseCode(409,$this->genericExceptionMessages["propAlreadySet"]); diff --git a/htdocs/web_portal/GOCDB_monitor/check.php b/htdocs/web_portal/GOCDB_monitor/check.php index 45dcd8465..638b4af1f 100644 --- a/htdocs/web_portal/GOCDB_monitor/check.php +++ b/htdocs/web_portal/GOCDB_monitor/check.php @@ -1,42 +1,20 @@ setLocalInfoOverride($_SERVER['SERVER_NAME']); - -$res[1] = test_db_connection(); -$res[2] = test_url( - \Factory::getConfigService()->GetPiUrl(). - get_testPiMethod() - ); -$res[3] = test_url( - \Factory::getConfigService()->GetPortalURL() - ); +/** + * RUn GOCDB status checks and report as single-line text output. + */ -$counts=array( "ok" => 0, - "warn" => 0, - "error" => 0 - ); - -foreach ($res as $r){ - $counts[$r["status"]]++; -} +require_once "tests.php"; -if ($counts["error"] != 0) { - $url = \Factory::getConfigService()->GetPortalURL() . "/GOCDB_monitor/"; +$errorCount = run_tests($message); - echo("An error has been detected while checking GOCDB services. ". - "Please check $url to find out more\n"); +if ($errorCount != 0) { + echo("One or more errors have been detected while checking GOCDB services - " . + $message . + ". See https://goc.egi.eu/portal/GOCDB_monitor/ to find out more\n"); exit(2); // return Nagios error code for CRITICAL } -else if ($counts["warn"] != 0) { - echo("At least one of GOCDB tests shows a warning. It is safe to ignore it anyway\n"); - exit(0); // we don't want notifications if there is just a warning -} -else { - echo("All GOCDB tests are looking good\n"); - exit(0); -} -?> +echo("All GOCDB tests are looking good\n"); + +exit(0); diff --git a/htdocs/web_portal/GOCDB_monitor/check_with_error.php b/htdocs/web_portal/GOCDB_monitor/check_with_error.php index b96a32287..731cf40e6 100644 --- a/htdocs/web_portal/GOCDB_monitor/check_with_error.php +++ b/htdocs/web_portal/GOCDB_monitor/check_with_error.php @@ -4,4 +4,4 @@ echo("An error has been detected while checking GOCDB services. One or more services might not be working\n"); exit(2); // return Nagios error code for CRITICAL -?> \ No newline at end of file +?> diff --git a/htdocs/web_portal/GOCDB_monitor/index.php b/htdocs/web_portal/GOCDB_monitor/index.php index 1d1637582..e54fbe879 100644 --- a/htdocs/web_portal/GOCDB_monitor/index.php +++ b/htdocs/web_portal/GOCDB_monitor/index.php @@ -5,36 +5,43 @@ URLs as defined by local_info.xml

"; - -$piUrl = Factory::getConfigService()->GetPiUrl().get_testPiMethod(); -echo "

PI URL is: ".$piUrl."

"; - -$portalUrl = Factory::getConfigService()->GetPortalURL(); -echo "

Portal URl is: ".$portalUrl."

"; - -$baseUrl = Factory::getConfigService()->getServerBaseUrl(); -echo "

Server Base URL is: ".$baseUrl."

"; +$config = Factory::getConfigService(); // GOCDB5 DB connection $res = test_db_connection(); -$test_statuses["GOCDB5 DB connection"] = $res["status"]; -$test_messages["GOCDB5 DB connection"] = $res["message"]; +$test_statuses[TEST_1] = $res["status"]; +$test_messages[TEST_1] = $res["message"]; -// GOCDBPI v5 -$res = test_url($piUrl); -$test_statuses["GOCDBPI_v5 availability"] = $res["status"]; -$test_messages["GOCDBPI_v5 availability"] = $res["message"]; +// GOCDB5 configuration +$res = test_config($config); +$test_statuses[TEST_4] = $res["status"]; +$test_messages[TEST_4] = $res["message"]; -// GOCDB5 web portal -$res = test_url($portalUrl); -$test_statuses["GOCDB5 central portal availability"] = $res["status"]; -$test_messages["GOCDB5 central portal availability"] = $res["message"]; +// Following tests depend on the config file being valid. +if (strcasecmp($res["status"], OK) == 0) { + define_test_urls($config); + // GOCDBPI v5 + $res = test_url(PI_URL); + $test_statuses[TEST_2] = $res["status"]; + $test_messages[TEST_2] = $res["message"]; + // GOCDB5 web portal + $res = test_url(SERVER_BASE_URL); + $test_statuses[TEST_3] = $res["status"]; + $test_messages[TEST_3] = $res["message"]; -// DISPLAY RESULTS + // DISPLAY RESULTS + echo "

URLs as defined by local_info.xml

"; + echo "

PI URL is: " . PI_URL . "

"; + echo "

Portal URl is: " . PORTAL_URL . "

"; + echo "

Server Base URL is: " . SERVER_BASE_URL . "

"; +} else { + echo "

Unable to extract URL information due to configuration test failure.

"; +} ?>

Service status overview

+

Other tests may have dependencies on the server configuration so may +show ERROR or UNKNOWN if the configuration is invalid.

@@ -48,10 +55,10 @@ $status) { echo(""); - echo(""); + echo(""); echo($disp[$status]); - echo(""); - echo(""); + echo(""); + echo(""); echo(""); } ?> @@ -62,12 +69,24 @@

Other tests and check pages

    -
  • GOCDB server ganglia page - Useful to see if there are memory or CPU problems
  • -
  • Status check - non vebose check of GOCDB service status. Just returns 'OK' if all the tests in \"service status overview\" are fine, 'WARNING' or 'ERROR' otherwise. Used for automatic tests
  • +
  • GOCDB server + ganglia page - Useful to see if there are memory or CPU + problems
  • +
  • Status check - a less verbose check of + GOCDB service status. Returns the single line 'All GOCDB tests + are looking good' if all tests run without error and 'GOCDB + Web Portal is unable to connect to the GOCDB back end database' + otherwise. Used for automated tests.

Further documentation

diff --git a/htdocs/web_portal/GOCDB_monitor/ops_monitor_check.php b/htdocs/web_portal/GOCDB_monitor/ops_monitor_check.php index c9353bd6e..3c7c38b86 100644 --- a/htdocs/web_portal/GOCDB_monitor/ops_monitor_check.php +++ b/htdocs/web_portal/GOCDB_monitor/ops_monitor_check.php @@ -1,49 +1,27 @@ GetPiUrl().get_testPiMethod()); -$res[3] = test_url(Factory::getConfigService()->GetPortalURL()); - -$counts=array( - "ok" => 0, - "warn" => 0, - "error" => 0 -); - -foreach ($res as $r){ - $counts[$r["status"]]++; -} -/* -If there is an error, counts["error"] is incremented, e.g. -Array -( - [ok] => 0 - [warn] => 0 - [error] => 1 -) +/** + * Run GOCDB status checks reporting any failure with HTTP 500 return. + * The URL parameter 'fake_failure' can be used to force failure for testing - + * https://hostname.com/portal/GOCDB_monitor/ops_monitor_check.php?fake_failure */ +require_once "tests.php"; /* If someone wants to test the failure, they can fake one using * the fake_failure parameter */ -if(isset($_REQUEST['fake_failure'])) { - header("HTTP/1.0 500"); - echo("GOCDB Web Portal is unable to connect to the GOCDB back end database\n"); - die(); +if (isset($_REQUEST['fake_failure'])) { + $message = 'Fake failure'; + $errorCount = 1; +} else { + $errorCount = run_tests($message); } -if ($counts["error"] != 0) { +if ($errorCount != 0) { header("HTTP/1.0 500"); - echo("GOCDB Web Portal is unable to connect to the GOCDB back end database\n"); - die(); -} -else { - echo("All GOCDB tests are looking good\n"); + echo($message . "\n"); die(); } -?> +echo("All GOCDB tests are looking good\n"); +die(); diff --git a/htdocs/web_portal/GOCDB_monitor/tests.php b/htdocs/web_portal/GOCDB_monitor/tests.php index 033e90b5f..a78d395c9 100644 --- a/htdocs/web_portal/GOCDB_monitor/tests.php +++ b/htdocs/web_portal/GOCDB_monitor/tests.php @@ -1,34 +1,83 @@ setLocalInfoFileLocation(...) + \Factory::getConfigService()->setLocalInfoOverride($_SERVER['SERVER_NAME']); $test_statuses = array( - "GOCDB5 DB connection" => "unknown", - "GOCDBPI_v5 availability" => "unknown", - "GOCDB5 central portal availability" => "unknown" + TEST_1 => UKN, + TEST_2 => UKN, + TEST_3 => UKN, + TEST_4 => UKN ); $test_desc = array( - "GOCDB5 DB connection" => "Connect to GOCDB5 (RAL/master instance) from this machine using EntityManager->getConnection()->connect()", - "GOCDBPI_v5 availability" => "Retrieve https://goc.egi.eu/gocdbpi/?method=get_site_list&sitename=RAL-LCG2 using PHP CURL", - "GOCDB5 central portal availability" => "N/A", + TEST_1 => + "Connect to GOCDB5 (RAL/master instance) from this " . + "machine using EntityManager->getConnection()->connect()", + TEST_2 => + "Retrieve https://goc.egi.eu/gocdbpi/?" . + "method=get_site_list&sitename=RAL-LCG2 using PHP CURL", + TEST_3 => + "N/A", + TEST_4 => + "Server XML configuration validation." ); $test_doc = array( - "GOCDB5 DB connection" => "documentation/recipe", - "GOCDBPI_v5 availability" => "documentation/recipe", - "GOCDB5 central portal availability" => "documentation/recipe" + TEST_1 => + "" . + "documentation/recipe", + TEST_2 => + "" . + "documentation/recipe", + TEST_3 => + "" . + "documentation/recipe", + TEST_4 => + "

Contact GOCDB service managers." . + "
Other tests have dependencies on the server configuration " . + "
so may show errors if the configuration is invalid.

" ); - $test_messages = array( - "GOCDB5 DB connection" => "no information", - "GOCDBPI_v5 availability" => "no information", - "GOCDB5 central portal availability" => "no information" + TEST_1 => UKNMSG, + TEST_2 => UKNMSG, + TEST_3 => UKNMSG, + TEST_4 => UKNMSG ); $disp = array( @@ -38,37 +87,82 @@ "ok" => "", ); +// Run the tests but return nothing but a count of passes and failures +function get_test_counts($config) +{ + $res[1] = test_db_connection(); + $res[4] = test_config($config); + + if ($res[4]["status"] != "error") { + // Only define test URLs if the config is valid + define_test_urls($config); + + $res[2] = test_url(PI_URL); + $res[3] = test_url(SERVER_BASE_URL); + } + + $counts = array("ok" => 0, + "warn" => 0, + "error" => 0 + ); + + foreach ($res as $r) { + $counts[$r["status"]]++; + } + + return $counts; +} + +// Define url constants for testing. +// Note: Should only be called if test_config is successful +function define_test_urls(\org\gocdb\services\config $config) +{ + + list($serverBaseURL, $webPortalURL, $piURL) = $config->getURLs(); + + define("PI_URL", $piURL . get_testPiMethod()); + define("PORTAL_URL", $webPortalURL); + define("SERVER_BASE_URL", $serverBaseURL); + + //define("SERVER_SSLCERT", "/etc/grid-security/hostcert.pem"); + //define("SERVER_SSLKEY", "/etc/pki/tls/private/hostkey.pem"); +} + // Test the connection to the database using Doctrine -function test_db_connection(){ +function test_db_connection() +{ + $retval = []; try { $entityManager = Factory::getNewEntityManager(); $entityManager->getConnection()->connect(); - $retval["status"] = "ok"; - $retval["message"] = "everything is well"; + $retval["status"] = OK; + $retval["message"] = OKMSG; } catch (\Exception $e) { $message = $e->getMessage(); - $retval["status"] = "error"; + $retval["status"] = NOK; $retval["message"] = "$message"; } return $retval; } -function test_url($url) { - try{ +function test_url($url) +{ + $retval = []; + try { get_https2($url); - $retval["status"] = "ok"; - $retval["message"] = "everything is well"; - } catch (Exception $exception){ + $retval["status"] = OK; + $retval["message"] = OKMSG; + } catch (Exception $exception) { $message = $exception->getMessage(); - $retval["status"] = "error"; + $retval["status"] = NOK; $retval["message"] = "$message"; } return $retval; } -function get_https2($url){ - +function get_https2($url) +{ $curloptions = array ( // In addition to transfer failures, check inside the HTTP response for an error // response code (HTTP > 400) @@ -95,9 +189,9 @@ function get_https2($url){ CURLOPT_RETURNTRANSFER => true, CURLOPT_CAPATH => '/etc/grid-security/certificates/' ); - if( defined('SERVER_SSLCERT') && defined('SERVER_SSLKEY') ){ - $curloptions[CURLOPT_SSLCERT] = SERVER_SSLCERT; - $curloptions[CURLOPT_SSLKEY] = SERVER_SSLKEY; + if (defined('SERVER_SSLCERT') && defined('SERVER_SSLKEY')) { + $curloptions[CURLOPT_SSLCERT] = constant("SERVER_SSLCERT"); + $curloptions[CURLOPT_SSLKEY] = constant("SERVER_SSLKEY"); } $handle = curl_init(); @@ -112,19 +206,68 @@ function get_https2($url){ // See man page for curl --fail option throw new Exception("http response code: $httpResponse"); } - throw new Exception("curl error:".curl_error($handle)); + throw new Exception("curl error:" . curl_error($handle)); } curl_close($handle); if ($return == false) { - throw new Exception("no result returned. curl says: ".curl_getinfo($handle)); + throw new Exception("no result returned. curl says: " . curl_getinfo($handle)); } return $return; } -function get_testPiMethod () { +function get_testPiMethod() +{ return "/public/?method=get_site_list"; } +/** + * Run the standard 3 GOCDB monitoring tests + * + * @param string &$message Returned error messages or '' + * @return int Count of failed tests + */ +function run_tests(&$message) +{ + $errorCount = 0; + $messages = []; + + $res = test_db_connection(); + + if ($res["status"] != "ok") { + $errorCount++; + $messages[] = "Database connection test failed: " . $res["message"]; + } + + $res = test_url(Factory::getConfigService()->GetPiUrl() . + get_testPiMethod()); + + if ($res["status"] != "ok") { + $errorCount++; + $messages[] = "PI interface test failed: " . $res["message"]; + } -?> + $res = test_url(Factory::getConfigService()->GetPortalURL()); + + if ($res["status"] != "ok") { + $errorCount++; + $messages[] = "Server base URL test failed: " . $res["message"]; + } + + $message = join(" | ", $messages); + + return $errorCount; +} +function test_config($config) +{ + $retval = []; + try { + validate_local_info_xml($config->getLocalInfoFileLocation()); + $retval["status"] = OK; + $retval["message"] = OKMSG; + } catch (Exception $exception) { + $retval["status"] = NOK; + $retval["message"] = $exception->getMessage(); + } + return $retval; +} diff --git a/htdocs/web_portal/GOCDB_monitor/tests/URL.php b/htdocs/web_portal/GOCDB_monitor/tests/URL.php index 7b1116d52..402635e9c 100644 --- a/htdocs/web_portal/GOCDB_monitor/tests/URL.php +++ b/htdocs/web_portal/GOCDB_monitor/tests/URL.php @@ -94,4 +94,4 @@ private function get_https($url){ return; } -} \ No newline at end of file +} diff --git a/htdocs/web_portal/GOCDB_monitor/validate_local_info_xml.php b/htdocs/web_portal/GOCDB_monitor/validate_local_info_xml.php new file mode 100644 index 000000000..a1e20bcd3 --- /dev/null +++ b/htdocs/web_portal/GOCDB_monitor/validate_local_info_xml.php @@ -0,0 +1,67 @@ +\n"; + + switch ($error->level) { + case LIBXML_ERR_WARNING: + $return .= "Warning $error->code: "; + break; + case LIBXML_ERR_ERROR: + $return .= "Error $error->code: "; + break; + case LIBXML_ERR_FATAL: + $return .= "Fatal Error $error->code: "; + break; + } + $return .= trim($error->message); + + if ($error->file) { + $return .= " in $error->file"; + } + $return .= " on line $error->line\n"; + return $return; +} + +/** + * Loop over all errors printing a message for each + */ +function libxml_display_errors() +{ + $message = ""; + + $errors = libxml_get_errors(); + foreach ($errors as $error) { + $message .= libxml_display_error($error); + } + libxml_clear_errors(); + + return $message; +} + +/** + * Check that the given xml matches its schema. + * The schema .xsd file must have the same name prefix and + * be in the same dir as the input .xml file + */ +function validate_local_info_xml($path) +{ + // Enable user error handling + libxml_use_internal_errors(true); + + $xml = new DOMDocument(); + + $xml->load($path); + + $xsd = preg_replace('/\.xml$/', '.xsd', $path); + + if (!$xml->schemaValidate($xsd)) { + throw new Exception(libxml_display_errors()); + } + + return; +} diff --git a/htdocs/web_portal/components/Draw_Components/draw_user_status.php b/htdocs/web_portal/components/Draw_Components/draw_user_status.php index 51fd27515..5ff244271 100644 --- a/htdocs/web_portal/components/Draw_Components/draw_user_status.php +++ b/htdocs/web_portal/components/Draw_Components/draw_user_status.php @@ -58,4 +58,4 @@ function Get_User_Info_HTML($user) return $Roles_HTML; } -?> \ No newline at end of file +?> diff --git a/htdocs/web_portal/controllers/admin/add_ngi.php b/htdocs/web_portal/controllers/admin/add_ngi.php index 6062d928d..fe68f3036 100644 --- a/htdocs/web_portal/controllers/admin/add_ngi.php +++ b/htdocs/web_portal/controllers/admin/add_ngi.php @@ -86,4 +86,4 @@ function submit() { show_view('error.php', $e->getMessage()); die(); } -} \ No newline at end of file +} diff --git a/htdocs/web_portal/controllers/admin/add_scope.php b/htdocs/web_portal/controllers/admin/add_scope.php index dbe3987e0..ccf2b3ffe 100644 --- a/htdocs/web_portal/controllers/admin/add_scope.php +++ b/htdocs/web_portal/controllers/admin/add_scope.php @@ -80,4 +80,4 @@ function submit() { } } -?> \ No newline at end of file +?> diff --git a/htdocs/web_portal/controllers/admin/add_service_type.php b/htdocs/web_portal/controllers/admin/add_service_type.php index 66dcd51df..748336393 100644 --- a/htdocs/web_portal/controllers/admin/add_service_type.php +++ b/htdocs/web_portal/controllers/admin/add_service_type.php @@ -1,4 +1,5 @@ getUserByPrinciple($dn); try { - //function will through error if user does not have the correct permissions + //function will throw error if user does not have the correct permissions + /** + * @var \ServiceType $serviceType + */ $serviceType = \Factory::getServiceTypeService()->addServiceType($newValues, $user); $params = array('Name' => $serviceType->getName(), - 'Description'=> $serviceType->getDescription(), - 'ID'=> $serviceType->getId()); + 'Description' => $serviceType->getDescription(), + 'AllowMonitoringException' => $serviceType->getAllowMonitoringException(), + 'ID' => $serviceType->getId()); show_view("admin/added_service_type.php", $params, "Successfuly added new service type"); } catch (Exception $e) { show_view('error.php', $e->getMessage()); die(); } } - -?> \ No newline at end of file diff --git a/htdocs/web_portal/controllers/admin/delete_ngi.php b/htdocs/web_portal/controllers/admin/delete_ngi.php index 8765fe9f7..1bb0c517a 100644 --- a/htdocs/web_portal/controllers/admin/delete_ngi.php +++ b/htdocs/web_portal/controllers/admin/delete_ngi.php @@ -90,4 +90,4 @@ function submit() { show_view('/site/deleted_site.php', $params); -} \ No newline at end of file +} diff --git a/htdocs/web_portal/controllers/admin/delete_scope.php b/htdocs/web_portal/controllers/admin/delete_scope.php index 83426c321..a0d53f00f 100644 --- a/htdocs/web_portal/controllers/admin/delete_scope.php +++ b/htdocs/web_portal/controllers/admin/delete_scope.php @@ -93,4 +93,3 @@ function remove_scope(){ } } - diff --git a/htdocs/web_portal/controllers/admin/delete_service_type.php b/htdocs/web_portal/controllers/admin/delete_service_type.php index 07b0c06d2..8b0020139 100644 --- a/htdocs/web_portal/controllers/admin/delete_service_type.php +++ b/htdocs/web_portal/controllers/admin/delete_service_type.php @@ -48,4 +48,4 @@ function delete_service_type(){ show_view("admin/deleted_service_type.php", $params, $params['Name'].'deleted'); -} \ No newline at end of file +} diff --git a/htdocs/web_portal/controllers/admin/delete_service_type_denied.php b/htdocs/web_portal/controllers/admin/delete_service_type_denied.php index c9d97c64a..3c0d8035e 100644 --- a/htdocs/web_portal/controllers/admin/delete_service_type_denied.php +++ b/htdocs/web_portal/controllers/admin/delete_service_type_denied.php @@ -38,4 +38,4 @@ function deny_delete_type(){ //display the deletion denied view show_view("admin/delete_service_type_denied.php", $params, 'Deletion Failed'); -} \ No newline at end of file +} diff --git a/htdocs/web_portal/controllers/admin/edit_scope.php b/htdocs/web_portal/controllers/admin/edit_scope.php index df92c20ba..9779f7e6c 100644 --- a/htdocs/web_portal/controllers/admin/edit_scope.php +++ b/htdocs/web_portal/controllers/admin/edit_scope.php @@ -97,4 +97,4 @@ function submit() { } } -?> \ No newline at end of file +?> diff --git a/htdocs/web_portal/controllers/admin/edit_service_type.php b/htdocs/web_portal/controllers/admin/edit_service_type.php index 6c65a15c6..46c8e6806 100644 --- a/htdocs/web_portal/controllers/admin/edit_service_type.php +++ b/htdocs/web_portal/controllers/admin/edit_service_type.php @@ -1,4 +1,5 @@ getServiceType($_REQUEST['id']); $params = array('Name' => $serviceType->getName(),'ID' => $serviceType->getId(), - 'Description' => $serviceType->getDescription()); + 'Description' => $serviceType->getDescription(), + 'AllowMonitoringException' => $serviceType->getAllowMonitoringException()); show_view("admin/edit_service_type.php", $params, "Edit " . $serviceType->getName()); } @@ -66,7 +73,8 @@ function draw() { * services layer's service type functions. * @return null */ -function submit() { +function submit() +{ require_once __DIR__ . '/../../../../htdocs/web_portal/components/Get_User_Principle.php'; //Get the posted service type data @@ -78,19 +86,24 @@ function submit() { //get the service type service and the service type being edited $serv = \Factory::getServiceTypeService(); + /** + * @var \ServiceType $unalteredServiceType + */ $unalteredServiceType = $serv->getServiceType($newValues['ID']); try { //function will throw error if user does not have the correct permissions - $alteredServiceType =$serv->editServiceType($unalteredServiceType, $newValues, $user); + /** + * @var \User $user + */ + $alteredServiceType = $serv->editServiceType($unalteredServiceType, $newValues, $user); $params = array('Name' => $alteredServiceType->getName(), - 'Description'=> $alteredServiceType->getDescription(), - 'ID'=> $alteredServiceType->getId()); + 'Description' => $alteredServiceType->getDescription(), + 'AllowMonitoringException' => $alteredServiceType->getAllowMonitoringException(), + 'ID' => $alteredServiceType->getId()); show_view("admin/edited_service_type.php", $params); } catch (Exception $e) { show_view('error.php', $e->getMessage()); die(); } } - -?> \ No newline at end of file diff --git a/htdocs/web_portal/controllers/admin/edit_user_identifier.php b/htdocs/web_portal/controllers/admin/edit_user_identifier.php index bfb6fedf7..d41cf8b42 100644 --- a/htdocs/web_portal/controllers/admin/edit_user_identifier.php +++ b/htdocs/web_portal/controllers/admin/edit_user_identifier.php @@ -163,4 +163,4 @@ function submit() { } } -?> \ No newline at end of file +?> diff --git a/htdocs/web_portal/controllers/admin/edit_user_isadmin.php b/htdocs/web_portal/controllers/admin/edit_user_isadmin.php index 2273cdeeb..ef867cae1 100644 --- a/htdocs/web_portal/controllers/admin/edit_user_isadmin.php +++ b/htdocs/web_portal/controllers/admin/edit_user_isadmin.php @@ -121,4 +121,4 @@ function submit() { }*/ } -?> \ No newline at end of file +?> diff --git a/htdocs/web_portal/controllers/admin/move_service_end_point.php b/htdocs/web_portal/controllers/admin/move_service_end_point.php index dbf822617..d55201895 100644 --- a/htdocs/web_portal/controllers/admin/move_service_end_point.php +++ b/htdocs/web_portal/controllers/admin/move_service_end_point.php @@ -182,4 +182,4 @@ function submitMoveSEP($movementDetails) { $params['NewSite'] = $newSite; $params['Services'] = $services; show_view("admin/moved_service_end_point.php", $params); -} \ No newline at end of file +} diff --git a/htdocs/web_portal/controllers/admin/move_site.php b/htdocs/web_portal/controllers/admin/move_site.php index 21ce1e873..f101894b2 100644 --- a/htdocs/web_portal/controllers/admin/move_site.php +++ b/htdocs/web_portal/controllers/admin/move_site.php @@ -180,4 +180,4 @@ function submitMoveSite($movementDetails) { $params['sites'] = $sites; show_view("admin/moved_site.php", $params); -} \ No newline at end of file +} diff --git a/htdocs/web_portal/controllers/admin/users.php b/htdocs/web_portal/controllers/admin/users.php index c309db037..8b44892bd 100644 --- a/htdocs/web_portal/controllers/admin/users.php +++ b/htdocs/web_portal/controllers/admin/users.php @@ -68,4 +68,4 @@ function show_users() { $params["Users"] = \Factory::getUserService()->getUsers($surname, $forename, $idString, $isAdmin); show_view("admin/users.php", $params, "Users"); -} \ No newline at end of file +} diff --git a/htdocs/web_portal/controllers/admin/view_service_type.php b/htdocs/web_portal/controllers/admin/view_service_type.php index 0acca32f7..f94895324 100644 --- a/htdocs/web_portal/controllers/admin/view_service_type.php +++ b/htdocs/web_portal/controllers/admin/view_service_type.php @@ -1,4 +1,5 @@ getUserByPrinciple($dn); - $serv= \Factory::getServiceTypeService(); - $serviceType =$serv ->getServiceType($_REQUEST['id']); + $serv = \Factory::getServiceTypeService(); + /** + * @var \ServiceType $serviceType + */ + $serviceType = $serv ->getServiceType($_REQUEST['id']); - $params['Name'] = $serviceType -> getName(); - $params['Description'] = $serviceType -> getDescription(); - $params['ID']= $serviceType ->getId(); - $params['Services'] = $serv ->getServices($params['ID']); + $params = []; + $params['Name'] = $serviceType->getName(); + $params['Description'] = $serviceType->getDescription(); + $params['ID'] = $serviceType->getId(); + $params['AllowMonitoringException'] = $serviceType->getAllowMonitoringException(); + $params['Services'] = $serv->getServices($params['ID']); + /** + * @var \User $user + */ $params['portalIsReadOnly'] = portalIsReadOnlyAndUserIsNotAdmin($user); show_view("admin/view_service_type.php", $params, $params['Name']); - } - diff --git a/htdocs/web_portal/controllers/search.php b/htdocs/web_portal/controllers/search.php index 95ad0e18a..d057ae830 100644 --- a/htdocs/web_portal/controllers/search.php +++ b/htdocs/web_portal/controllers/search.php @@ -23,7 +23,7 @@ function search() { require_once __DIR__.'/../../../lib/Gocdb_Services/Factory.php'; - + $params = []; $dn = Get_User_Principle(); $user = \Factory::getUserService()->getUserByPrinciple($dn); @@ -58,11 +58,16 @@ function search() { $serviceResults = $searchServ->getServices($params['searchTerm']); $userResults = $searchServ->getUsers($params['searchTerm']); $ngiResults = $searchServ->getNgis($params['searchTerm']); + $siteIdentifiers = $searchServ->getSiteIdentifiers( + $user, + $params['searchTerm'] + ); $params['siteResults'] = $siteResults; $params['serviceResults'] = $serviceResults; $params['userResults'] = $userResults; $params['ngiResults'] = $ngiResults; + $params['siteIdentifiers'] = $siteIdentifiers; show_view('search_results.php', $params, "Searching for \"{$params['searchTerm']}\""); } diff --git a/htdocs/web_portal/controllers/service_group/add_service_group.php b/htdocs/web_portal/controllers/service_group/add_service_group.php index 9f5d46455..d7277c92c 100644 --- a/htdocs/web_portal/controllers/service_group/add_service_group.php +++ b/htdocs/web_portal/controllers/service_group/add_service_group.php @@ -22,6 +22,8 @@ * See the License for the specific language governing permissions and * limitations under the License. /*====================================================== */ +use Exception; + require_once __DIR__ . '/../../../../lib/Gocdb_Services/Factory.php'; require_once __DIR__ . '/../../components/Get_User_Principle.php'; require_once __DIR__ . '/../utils.php'; @@ -74,6 +76,20 @@ function draw($user) { throw new \Exception("Unregistered users can't create service groups."); } + $hasAdminCredentials = $user->isAdmin(); + $roleService = \Factory::getRoleService(); + $userRoles = $roleService->getUserRoles($user); + + $isUserValid = $hasAdminCredentials ? true : !empty($userRoles); + + if (!$isUserValid) { + throw new Exception( + "You do not have permission to add a new " + . "Service Group. To add a new Service Group, you require " + . "at least one role assigned over an entity in GOCDB." + ); + } + // can user assign reserved scopes ? $disableReservedScopes = true; if ($user->isAdmin()) { diff --git a/htdocs/web_portal/controllers/user/view_user.php b/htdocs/web_portal/controllers/user/view_user.php index 17d479045..772d41acb 100644 --- a/htdocs/web_portal/controllers/user/view_user.php +++ b/htdocs/web_portal/controllers/user/view_user.php @@ -156,6 +156,7 @@ function view_user() $params['ShowEdit'] = false; } + $params['callingUser'] = $callingUser; $params['idString'] = $userService->getDefaultIdString($user); $params['projectNamesIds'] = $projectNamesIds; $params['role_ProjIds'] = $roleProjectIds; diff --git a/htdocs/web_portal/controllers/utils.php b/htdocs/web_portal/controllers/utils.php index 3a6d87ed1..aa98bb42e 100644 --- a/htdocs/web_portal/controllers/utils.php +++ b/htdocs/web_portal/controllers/utils.php @@ -1,4 +1,5 @@ $line) { - $trimedLine = trim($line); - if(empty($trimedLine) || (!$isWaitingOtherLine && strpos($line,"#") === 0)) continue; + foreach ($lines as $i => $line) { + $trimedLine = trim($line); + if (empty($trimedLine) || (!$isWaitingOtherLine && strpos($line, "#") === 0)) { + continue; + } - if(!$isWaitingOtherLine) { - $key = substr($line,0,strpos($line,'=')); - $value = substr($line,strpos($line,'=') + 1, strlen($line)); - } - else { - $value .= $line; - } + if (!$isWaitingOtherLine) { + $key = substr($line, 0, strpos($line, '=')); + $value = substr($line, strpos($line, '=') + 1, strlen($line)); + } else { + $value .= $line; + } - /* Check if ends with single '\' */ - if(strpos($value,"\\") === strlen($value)-strlen("\\")) { - $value = substr($value, 0, strlen($value)-1)."\n"; - $isWaitingOtherLine = true; - } - else { - $isWaitingOtherLine = false; - } + /* Check if ends with single '\' */ + if (strpos($value, "\\") === strlen($value) - strlen("\\")) { + $value = substr($value, 0, strlen($value) - 1) . "\n"; + $isWaitingOtherLine = true; + } else { + $isWaitingOtherLine = false; + } - if ($key == NULL) { - $line = $i + 1; - throw new \Exception("Property name on line {$line} is null"); - } - if ($value == NULL) { - $line = $i + 1; - throw new \Exception("Property value on line {$line} is null"); - } + if ($key == null) { + $line = $i + 1; + throw new \Exception("Property name on line {$line} is null"); + } + if ($value == null) { + $line = $i + 1; + throw new \Exception("Property value on line {$line} is null"); + } - //we can't use the prop key as the key due to key duplicates [PREVIOUSLY] being allowed - //we are using an indexed array of indexed arrays TODO: use prop key as array key - $result[] = array($key, $value); + //we can't use the prop key as the key due to key duplicates [PREVIOUSLY] being allowed + //we are using an indexed array of indexed arrays TODO: use prop key as array key + $result[] = array($key, $value); - unset($lines[$i]); - } + unset($lines[$i]); + } return $result; } @@ -68,7 +70,8 @@ function parse_properties($txtProperties) { *
  • 'reserved_optional_inheritable' - Lists reserved tags that CAN be inherited * from the $parentScopedEntity (the tag may/may-not be already assigned to the target).
  • *
  • 'reserved' - The remaining Reserved tags.
  • - *
  • 'disableReserved' - Defines a boolean rather than a tag list - true to disable the 'reserved' tags or false to enable.
  • + *
  • 'disableReserved' - Defines a boolean rather than a tag list - + * true to disable the 'reserved' tags or false to enable.
  • * *

    * For each scope value, the attributes are ["PK/ID", "tagValue", "boolCheckedOrNot"]. @@ -88,26 +91,30 @@ function parse_properties($txtProperties) { * * @param \IScopedEntity $targetScopedEntity Optional, use Null if creating a new IScopedEntity * @param \IScopedEntity $parentScopedEntity Optional, the parent to inherit tags from - * @param bool $disableReservedScopes True to disable 'reserved' tags - * @param bool $inheritParentScopeChecked True to set the checked status of each scope value + * @param bool $noReservedScopes True to disable 'reserved' tags + * @param bool $inheritScopeChecked True to set the checked status of each scope value * according to whether the parent has the same scope checked (every scope will always be * false if the $parentScopedEntity is null) * @return string * @throws \LogicException */ -function getEntityScopesAsJSON2($targetScopedEntity = null, $parentScopedEntity = null, - $disableReservedScopes = true, $inheritParentScopeChecked = false){ +function getEntityScopesAsJSON2( + $targetScopedEntity = null, + $parentScopedEntity = null, + $noReservedScopes = true, + $inheritScopeChecked = false +) { $targetScopes = array(); - if($targetScopedEntity != null){ - if(!($targetScopedEntity instanceof \IScopedEntity)){ + if ($targetScopedEntity != null) { + if (!($targetScopedEntity instanceof \IScopedEntity)) { throw new \LogicException('Invalid $scopedEntityChild, does not implement IScopedEntity'); } - $targetScopes = $targetScopedEntity->getScopes()->toArray(); + $targetScopes = $targetScopedEntity->getScopes()->toArray(); } $parentScopes = array(); - if($parentScopedEntity != null) { - if(!($parentScopedEntity instanceof \IScopedEntity)){ + if ($parentScopedEntity != null) { + if (!($parentScopedEntity instanceof \IScopedEntity)) { throw new \LogicException('Invalid scopedEntityParent, does not implement IScopedEntity'); } $parentScopes = $parentScopedEntity->getScopes()->toArray(); @@ -116,38 +123,41 @@ function getEntityScopesAsJSON2($targetScopedEntity = null, $parentScopedEntity // $reservedScopeNames = \Factory::getConfigService()->getReservedScopeList(); $allScopes = \Factory::getScopeService()->getScopes(); $optionalScopeIds = array(); - $reservedOptionalScopeIds = array(); - $reservedOptionalInheritableScopeIds = array(); + // Reserved optional scope ids + $resOptScopeIds = array(); + // Reserved optional inherited scope ids + $resOptHeritScopeIds = array(); $reservedScopeIds = array(); /* @var $scope \Scope */ - foreach($allScopes as $scope){ + foreach ($allScopes as $scope) { $targetChecked = false; $parentChecked = false; // is scope already joined to target - if(in_array($scope, $targetScopes)){ + if (in_array($scope, $targetScopes)) { $targetChecked = true; } // is scope already joined to parent - if(in_array($scope, $parentScopes)){ + if (in_array($scope, $parentScopes)) { $parentChecked = true; } // Determine if this tag should be checked = t/f $isChecked = $targetChecked; - if($inheritParentScopeChecked){ + if ($inheritScopeChecked) { $isChecked = $parentChecked; } // Is scope tag in the reserved list ? - if($scope->getReserved()){ + if ($scope->getReserved()) { // A reserved scope tag: - if($parentChecked || $targetChecked){ - if($parentChecked){ + if ($parentChecked || $targetChecked) { + if ($parentChecked) { // tag CAN be inherited from parent, so put in relevant array - $reservedOptionalInheritableScopeIds[] = array($scope->getId(), $scope->getName(), $isChecked); + $resOptHeritScopeIds[] = array($scope->getId(), $scope->getName(), $isChecked); } else { - // tag CAN'T be inherited from parent, but it has already been directly assigned, so put in relevant array - $reservedOptionalScopeIds[] = array($scope->getId(), $scope->getName(), $isChecked); + // tag CAN'T be inherited from parent, but it has already been directly assigned, + // so put in relevant array + $resOptScopeIds[] = array($scope->getId(), $scope->getName(), $isChecked); } } else { // tag is not inheritable and has not been directly assigned, so its reserved/protected @@ -161,10 +171,10 @@ function getEntityScopesAsJSON2($targetScopedEntity = null, $parentScopedEntity // build the response $scopeCategories = array(); $scopeCategories['optional'] = $optionalScopeIds; - $scopeCategories['reserved_optional'] = $reservedOptionalScopeIds; - $scopeCategories['reserved_optional_inheritable'] = $reservedOptionalInheritableScopeIds; + $scopeCategories['reserved_optional'] = $resOptScopeIds; + $scopeCategories['reserved_optional_inheritable'] = $resOptHeritScopeIds; $scopeCategories['reserved'] = $reservedScopeIds; - $scopeCategories['disableReserved'] = $disableReservedScopes ? true : false; + $scopeCategories['disableReserved'] = $noReservedScopes ? true : false; return json_encode($scopeCategories); } @@ -175,8 +185,9 @@ function getEntityScopesAsJSON2($targetScopedEntity = null, $parentScopedEntity * * @throws \Exception */ -function checkPortalIsNotReadOnlyOrUserIsAdmin(\User $user = null) { - if (portalIsReadOnlyAndUserIsNotAdmin($user)){ +function checkPortalIsNotReadOnlyOrUserIsAdmin(\User $user = null) +{ + if (portalIsReadOnlyAndUserIsNotAdmin($user)) { throw new \Exception("The portal is currently in read only mode, changes can not be made."); } } @@ -190,20 +201,21 @@ function checkPortalIsNotReadOnlyOrUserIsAdmin(\User $user = null) { * current user * @return boolean */ -function portalIsReadOnlyAndUserIsNotAdmin(\user $user = null) { +function portalIsReadOnlyAndUserIsNotAdmin(\user $user = null) +{ require_once __DIR__ . '/../../../lib/Gocdb_Services/Factory.php'; // this block is required to deal with unregistered users (where $user is null) $userIsAdmin = false; - if (! is_null($user)){ - if ($user->isAdmin()){ // sub query required becauser ->isAdmin can't be called on null + if (! is_null($user)) { + if ($user->isAdmin()) { // sub query required becauser ->isAdmin can't be called on null $userIsAdmin = true; } } - if (\Factory::getConfigService()->IsPortalReadOnly() and ! $userIsAdmin){ + if (\Factory::getConfigService()->IsPortalReadOnly() and ! $userIsAdmin) { return true; - }else{ + } else { return false; } } @@ -214,25 +226,36 @@ function portalIsReadOnlyAndUserIsNotAdmin(\user $user = null) { * @return null * */ -function checkUserIsAdmin() { +function checkUserIsAdmin() +{ require_once __DIR__ . '/../../web_portal/components/Get_User_Principle.php'; $dn = Get_User_Principle(); + /** + * @var \User $user + */ $user = \Factory::getUserService()->getUserByPrinciple($dn); - if ($user == null){ + if ($user == null) { throw new Exception("Unregistered users may not carry out this operation"); } - if (! $user->isAdmin()){ + if (! $user->isAdmin()) { throw new Exception("Only GOCDB administrators can perform this action."); } } -function CheckCurrentUserCanEditProject(\Project $project) { +function CheckCurrentUserCanEditProject(\Project $project) +{ require_once __DIR__ . '/../../web_portal/components/Get_User_Principle.php'; $dn = Get_User_Principle(); $user = \Factory::getUserService()->getUserByPrinciple($dn); //$enablingRoles = \Factory::getProjectService()->authorize Action('ACTION_EDIT_OBJECT', $project, $user); //if (count($enablingRoles) == 0){ - if(\Factory::getRoleActionAuthorisationService()->authoriseAction(\Action::EDIT_OBJECT, $project, $user)->getGrantAction() == FALSE){ + if ( + \Factory::getRoleActionAuthorisationService()->authoriseAction( + \Action::EDIT_OBJECT, + $project, + $user + )->getGrantAction() == false + ) { throw new Exception("You do not have a role that enables you to edit this project"); } } @@ -245,52 +268,55 @@ function CheckCurrentUserCanEditProject(\Project $project) { * @global array $_REQUEST site data submitted by the end user * @return array an array representation of a site */ -function getSiteDataFromWeb() { +function getSiteDataFromWeb() +{ // Fields that are used to link other objects to the site $fields = array ( 'Country', 'ProductionStatus' ); - foreach($fields as $field){ - $site_data [$field] = $_REQUEST [$field]; + $siteData = []; + foreach ($fields as $field) { + $siteData[$field] = $_REQUEST [$field]; } - if(isset($_REQUEST['childServiceScopeAction'])){ - $site_data['childServiceScopeAction'] = $_REQUEST['childServiceScopeAction']; + if (isset($_REQUEST['childServiceScopeAction'])) { + $siteData['childServiceScopeAction'] = $_REQUEST['childServiceScopeAction']; } else { - $site_data['childServiceScopeAction'] = 'noModify'; + $siteData['childServiceScopeAction'] = 'noModify'; } // get non-reserved scopes if any are selected, if not set as empty array - if (isset($_REQUEST ['Scope_ids'])){ - $site_data ['Scope_ids'] = $_REQUEST ['Scope_ids']; - }else{ - $site_data ['Scope_ids'] = array (); + if (isset($_REQUEST ['Scope_ids'])) { + $siteData ['Scope_ids'] = $_REQUEST ['Scope_ids']; + } else { + $siteData ['Scope_ids'] = array (); } // get reserved scopes if any are selected, if not set as empty array - if (isset($_REQUEST ['ReservedScope_ids'])){ - $site_data ['ReservedScope_ids'] = $_REQUEST ['ReservedScope_ids']; - }else{ - $site_data ['ReservedScope_ids'] = array (); + if (isset($_REQUEST ['ReservedScope_ids'])) { + $siteData ['ReservedScope_ids'] = $_REQUEST ['ReservedScope_ids']; + } else { + $siteData ['ReservedScope_ids'] = array (); } /* - * Certification status is only set during the add_site procedure. Editing an existing site's cert status uses a separate form + * Certification status is only set during the add_site procedure. + * Editing an existing site's cert status uses a separate form */ - if (isset($_REQUEST ['Certification_Status'])){ - $site_data ['Certification_Status'] = $_REQUEST ['Certification_Status']; + if (isset($_REQUEST ['Certification_Status'])) { + $siteData ['Certification_Status'] = $_REQUEST ['Certification_Status']; } /* * ROC is only set during the add_site procedure. A site's ROC can't be edited in the web portal */ - if (isset($_REQUEST ['NGI'])){ - $site_data ['NGI'] = $_REQUEST ['NGI']; + if (isset($_REQUEST ['NGI'])) { + $siteData ['NGI'] = $_REQUEST ['NGI']; } // Fields specific to the site object and not linked to other entities - $site_object_fields = array ( + $siteObjectFields = array ( 'SHORT_NAME', 'OFFICIAL_NAME', 'HOME_URL', @@ -312,23 +338,24 @@ function getSiteDataFromWeb() { 'TIMEZONE' ); - foreach($site_object_fields as $field){ - $site_data ['Site'] [$field] = trim($_REQUEST [$field]); + foreach ($siteObjectFields as $field) { + $siteData ['Site'] [$field] = trim($_REQUEST [$field]); } //Notifcations - $site_data ['NOTIFY'] = $_REQUEST ['NOTIFY']; + $siteData ['NOTIFY'] = $_REQUEST ['NOTIFY']; /* - * If the user is updating a site the optional cobjectid parameter will be set. If it is set we return it as part of the array + * If the user is updating a site the optional cobjectid parameter will be set. + * If it is set we return it as part of the array */ - if (! empty($_REQUEST ['ID'])){ - $site_data ['ID'] = $_REQUEST ['ID']; + if (! empty($_REQUEST ['ID'])) { + $siteData ['ID'] = $_REQUEST ['ID']; } // - return $site_data; + return $siteData; } /** @@ -338,39 +365,41 @@ function getSiteDataFromWeb() { * @global array $_REQUEST site data submitted by the end user * @return array An array of service group data */ -function getSGroupDataFromWeb() { +function getSGroupDataFromWeb() +{ /* * $_REQUEST['monitored'] is set by the "Should this Virtual Site be monitored?" tick box */ - if (isset($_REQUEST ['monitored'])){ + if (isset($_REQUEST ['monitored'])) { $monitored = 'Y'; - }else{ + } else { $monitored = 'N'; } - $sg ['MONITORED'] = $monitored; + $sGroup = []; + $sGroup['MONITORED'] = $monitored; - if (isset($_REQUEST ['objectId'])){ - $sg ['ID'] = $_REQUEST ['objectId']; + if (isset($_REQUEST ['objectId'])) { + $sGroup['ID'] = $_REQUEST ['objectId']; } - $sg ['SERVICEGROUP'] ['NAME'] = trim($_REQUEST ['name']); - $sg ['SERVICEGROUP'] ['DESCRIPTION'] = trim($_REQUEST ['description']); - $sg ['SERVICEGROUP'] ['EMAIL'] = trim($_REQUEST ['email']); + $sGroup['SERVICEGROUP'] ['NAME'] = trim($_REQUEST ['name']); + $sGroup['SERVICEGROUP'] ['DESCRIPTION'] = trim($_REQUEST ['description']); + $sGroup['SERVICEGROUP'] ['EMAIL'] = trim($_REQUEST ['email']); // get scopes if any are selected, if not set as null - if (isset($_REQUEST ['Scope_ids'])){ - $sg ['Scope_ids'] = $_REQUEST ['Scope_ids']; - }else{ - $sg ['Scope_ids'] = array (); + if (isset($_REQUEST ['Scope_ids'])) { + $sGroup['Scope_ids'] = $_REQUEST ['Scope_ids']; + } else { + $sGroup['Scope_ids'] = array (); } - if (isset($_REQUEST ['ReservedScope_ids'])){ - $sg['ReservedScope_ids'] = $_REQUEST ['ReservedScope_ids']; - }else{ - $sg['ReservedScope_ids'] = array (); + if (isset($_REQUEST ['ReservedScope_ids'])) { + $sGroup['ReservedScope_ids'] = $_REQUEST ['ReservedScope_ids']; + } else { + $sGroup['ReservedScope_ids'] = array (); } - return $sg; + return $sGroup; } /** @@ -381,7 +410,8 @@ function getSGroupDataFromWeb() { * @global array $_REQUEST SE data submitted by the end user * @return array an array representation of a service */ -function getSeDataFromWeb() { +function getSeDataFromWeb() +{ $fields = array ( 'serviceType', @@ -389,61 +419,64 @@ function getSeDataFromWeb() { 'NOTIFY', 'PRODUCTION_LEVEL' ); - - foreach($fields as $field){ - $se_data [$field] = $_REQUEST [$field]; + $seData = []; + foreach ($fields as $field) { + $seData [$field] = $_REQUEST [$field]; } /* * If the user is adding a new service the optional HOSTING_SITE parameter will be set. * If it is set we return it as part of the array */ - if (! empty($_REQUEST ['hostingSite'])){ - $se_data ['hostingSite'] = $_REQUEST ['hostingSite']; - } - - // $se_data['SE']['ENDPOINT'] = $_REQUEST['HOSTNAME'] . $_REQUEST['serviceType']; - $se_data ['SE'] ['HOSTNAME'] = trim($_REQUEST ['HOSTNAME']); - $se_data ['SE'] ['HOST_IP'] = trim($_REQUEST ['HOST_IP']); - $se_data ['SE'] ['HOST_IP_V6'] = trim($_REQUEST['HOST_IP_V6']); - $se_data ['SE'] ['HOST_DN'] = trim($_REQUEST ['HOST_DN']); - $se_data ['SE'] ['DESCRIPTION'] = trim($_REQUEST ['DESCRIPTION']); - $se_data ['SE'] ['HOST_OS'] = trim($_REQUEST ['HOST_OS']); - $se_data ['SE'] ['HOST_ARCH'] = trim($_REQUEST ['HOST_ARCH']); - $se_data ['SE'] ['EMAIL'] = trim($_REQUEST ['EMAIL']); - $se_data ['SE'] ['URL'] = trim($_REQUEST ['endpointUrl']); - $se_data ['BETA'] = $_REQUEST ['HOST_BETA']; + if (! empty($_REQUEST ['hostingSite'])) { + $seData ['hostingSite'] = $_REQUEST ['hostingSite']; + } + + // $seData['SE']['ENDPOINT'] = $_REQUEST['HOSTNAME'] . $_REQUEST['serviceType']; + $seData ['SE'] ['HOSTNAME'] = trim($_REQUEST ['HOSTNAME']); + $seData ['SE'] ['HOST_IP'] = trim($_REQUEST ['HOST_IP']); + $seData ['SE'] ['HOST_IP_V6'] = trim($_REQUEST['HOST_IP_V6']); + $seData ['SE'] ['HOST_DN'] = trim($_REQUEST ['HOST_DN']); + $seData ['SE'] ['DESCRIPTION'] = trim($_REQUEST ['DESCRIPTION']); + $seData ['SE'] ['HOST_OS'] = trim($_REQUEST ['HOST_OS']); + $seData ['SE'] ['HOST_ARCH'] = trim($_REQUEST ['HOST_ARCH']); + $seData ['SE'] ['EMAIL'] = trim($_REQUEST ['EMAIL']); + $seData ['SE'] ['URL'] = trim($_REQUEST ['endpointUrl']); + $seData ['BETA'] = $_REQUEST ['HOST_BETA']; /* - * If the user is updating a service the optional cobjectid parameter will be set. If it is set we return it as part of the array + * If the user is updating a service the optional cobjectid parameter will be set. + * If it is set we return it as part of the array */ - if (! empty($_REQUEST ['ID'])){ - $se_data ['ID'] = $_REQUEST ['ID']; + if (! empty($_REQUEST ['ID'])) { + $seData ['ID'] = $_REQUEST ['ID']; } // get scopes if any are selected, if not set as null - if (isset($_REQUEST ['Scope_ids'])){ - $se_data ['Scope_ids'] = $_REQUEST ['Scope_ids']; - }else{ - $se_data ['Scope_ids'] = array (); + if (isset($_REQUEST ['Scope_ids'])) { + $seData ['Scope_ids'] = $_REQUEST ['Scope_ids']; + } else { + $seData ['Scope_ids'] = array (); } - if (isset($_REQUEST ['ReservedScope_ids'])){ - $se_data ['ReservedScope_ids'] = $_REQUEST ['ReservedScope_ids']; - }else{ - $se_data ['ReservedScope_ids'] = array (); + if (isset($_REQUEST ['ReservedScope_ids'])) { + $seData ['ReservedScope_ids'] = $_REQUEST ['ReservedScope_ids']; + } else { + $seData ['ReservedScope_ids'] = array (); } - return $se_data; + return $seData; } /** * * @return array */ -function getProjectDataFromWeb() { +function getProjectDataFromWeb() +{ + $projectValues = []; // new projects won't have an id - if (isset($_REQUEST ['ID'])){ + if (isset($_REQUEST ['ID'])) { $projectValues ['ID'] = $_REQUEST ['ID']; } @@ -453,12 +486,13 @@ function getProjectDataFromWeb() { 'Description' ); - foreach($fields as $field){ + foreach ($fields as $field) { $projectValues [$field] = trim($_REQUEST [$field]); } return $projectValues; } -function getNGIDataFromWeb() { +function getNGIDataFromWeb() +{ // Get the NGI post data into an array $fields = array ( 'EMAIL', @@ -467,13 +501,13 @@ function getNGIDataFromWeb() { 'SECURITY_EMAIL', 'GGUS_SU' ); - - foreach($fields as $field){ - $NGIValues [$field] = trim($_REQUEST [$field]); + $ngiValues = []; + foreach ($fields as $field) { + $ngiValues [$field] = trim($_REQUEST [$field]); } - if (isset($_REQUEST ['NAME'])){ - $NGIValues ['NAME'] = $_REQUEST ['NAME']; + if (isset($_REQUEST ['NAME'])) { + $ngiValues ['NAME'] = $_REQUEST ['NAME']; } // $scopes = array (); @@ -483,25 +517,25 @@ function getNGIDataFromWeb() { // get scopes if any are selected, if not set as null $optionalScopes = array(); - if (isset($_REQUEST ['Scope_ids'])){ + if (isset($_REQUEST ['Scope_ids'])) { $optionalScopes['Scope_ids'] = $_REQUEST ['Scope_ids']; - }else{ + } else { $optionalScopes['Scope_ids'] = array (); } $reservedScopes = array(); - if (isset($_REQUEST ['ReservedScope_ids'])){ + if (isset($_REQUEST ['ReservedScope_ids'])) { $reservedScopes['ReservedScope_ids'] = $_REQUEST ['ReservedScope_ids']; - }else{ + } else { $reservedScopes['ReservedScope_ids'] = array (); } $id = null; - if (isset($_REQUEST ['ID'])){ + if (isset($_REQUEST ['ID'])) { $id = $_REQUEST ['ID']; } $values = array ( - 'NGI' => $NGIValues, + 'NGI' => $ngiValues, //'SCOPES' => $scopes, 'Scope_ids' => $optionalScopes['Scope_ids'], 'ReservedScope_ids' => $reservedScopes['ReservedScope_ids'], @@ -518,123 +552,134 @@ function getNGIDataFromWeb() { * @global array $_REQUEST Downtime data submitted by the end user * @return array an array representation of a downtime */ -function getDtDataFromWeb() { - $dt ['DOWNTIME'] ['SEVERITY'] = $_REQUEST ['SEVERITY']; - $dt ['DOWNTIME'] ['DESCRIPTION'] = trim($_REQUEST ['DESCRIPTION']); - $dt ['DOWNTIME'] ['START_TIMESTAMP'] = $_REQUEST ['START_TIMESTAMP']; - $dt ['DOWNTIME'] ['END_TIMESTAMP'] = $_REQUEST ['END_TIMESTAMP']; +function getDtDataFromWeb() +{ + $downTime = []; + $downTime['DOWNTIME'] ['SEVERITY'] = $_REQUEST ['SEVERITY']; + $downTime['DOWNTIME'] ['DESCRIPTION'] = trim($_REQUEST ['DESCRIPTION']); + $downTime['DOWNTIME'] ['START_TIMESTAMP'] = $_REQUEST ['START_TIMESTAMP']; + $downTime['DOWNTIME'] ['END_TIMESTAMP'] = $_REQUEST ['END_TIMESTAMP']; - $dt ['DOWNTIME'] ['DEFINE_TZ_BY_UTC_OR_SITE'] = 'utc'; //default - if(isset($_REQUEST ['DEFINE_TZ_BY_UTC_OR_SITE'])){ - $dt ['DOWNTIME'] ['DEFINE_TZ_BY_UTC_OR_SITE'] = $_REQUEST ['DEFINE_TZ_BY_UTC_OR_SITE']; // 'utc' or 'site' + $downTime['DOWNTIME'] ['DEFINE_TZ_BY_UTC_OR_SITE'] = 'utc'; //default + if (isset($_REQUEST ['DEFINE_TZ_BY_UTC_OR_SITE'])) { + $downTime['DOWNTIME'] ['DEFINE_TZ_BY_UTC_OR_SITE'] = $_REQUEST ['DEFINE_TZ_BY_UTC_OR_SITE']; // 'utc' or 'site' } - if (! isset($_REQUEST ['IMPACTED_IDS'])){ + if (! isset($_REQUEST ['IMPACTED_IDS'])) { throw new Exception('Error - No endpoints or services selected, downtime must affect at least one endpoint'); } - $dt ['IMPACTED_IDS'] = $_REQUEST ['IMPACTED_IDS']; + $downTime['IMPACTED_IDS'] = $_REQUEST ['IMPACTED_IDS']; //Get the previous downtimes ID if we are doing an edit - if(isset($_REQUEST['DOWNTIME_ID'])){ - $dt['DOWNTIME']['EXISTINGID'] = $_REQUEST['DOWNTIME_ID']; + if (isset($_REQUEST['DOWNTIME_ID'])) { + $downTime['DOWNTIME']['EXISTINGID'] = $_REQUEST['DOWNTIME_ID']; } - return $dt; + return $downTime; } /** * Gets the site properties data passed by user * */ -function getSpDataFromWeb() { - $sp ['SITEPROPERTIES'] ['SITE'] = $_REQUEST ['SITE']; - $sp ['SITEPROPERTIES'] ['NAME'] = $_REQUEST ['KEYPAIRNAME']; - $sp ['SITEPROPERTIES'] ['VALUE'] = $_REQUEST ['KEYPAIRVALUE']; - if (isset($_REQUEST ['PROP'])){ - $sp ['SITEPROPERTIES'] ['PROP'] = $_REQUEST ['PROP']; +function getSpDataFromWeb() +{ + $siteProp = []; + $siteProp['SITEPROPERTIES'] ['SITE'] = $_REQUEST ['SITE']; + $siteProp['SITEPROPERTIES'] ['NAME'] = $_REQUEST ['KEYPAIRNAME']; + $siteProp['SITEPROPERTIES'] ['VALUE'] = $_REQUEST ['KEYPAIRVALUE']; + if (isset($_REQUEST ['PROP'])) { + $siteProp['SITEPROPERTIES'] ['PROP'] = $_REQUEST ['PROP']; } - if(isset($sp['SITEPROPERTIES']['NAME'])){ - $sp['SITEPROPERTIES']['NAME'] = $sp['SITEPROPERTIES']['NAME']; + if (isset($siteProp['SITEPROPERTIES']['NAME'])) { + $siteProp['SITEPROPERTIES']['NAME'] = $siteProp['SITEPROPERTIES']['NAME']; } - if(isset($sp['SITEPROPERTIES']['VALUE'])){ - $sp['SITEPROPERTIES']['VALUE'] = $sp['SITEPROPERTIES']['VALUE']; + if (isset($siteProp['SITEPROPERTIES']['VALUE'])) { + $siteProp['SITEPROPERTIES']['VALUE'] = $siteProp['SITEPROPERTIES']['VALUE']; } - return $sp; + return $siteProp; } /** * Gets the service properties data passed by user * */ -function getSerPropDataFromWeb() { - $sp ['SERVICEPROPERTIES'] ['SERVICE'] = $_REQUEST ['SERVICE']; - $sp ['SERVICEPROPERTIES'] ['NAME'] = $_REQUEST ['KEYPAIRNAME']; - $sp ['SERVICEPROPERTIES'] ['VALUE'] = $_REQUEST ['KEYPAIRVALUE']; - if (isset($_REQUEST ['PROP'])){ - $sp ['SERVICEPROPERTIES'] ['PROP'] = trim($_REQUEST ['PROP']); - } - if(isset($sp['SERVICEPROPERTIES']['NAME'])){ - $sp['SERVICEPROPERTIES']['NAME'] = $sp['SERVICEPROPERTIES']['NAME']; - } - if(isset($sp['SERVICEPROPERTIES']['VALUE'])){ - $sp['SERVICEPROPERTIES']['VALUE'] = $sp['SERVICEPROPERTIES']['VALUE']; - } - return $sp; +function getSerPropDataFromWeb() +{ + $serviceProp = []; + $serviceProp['SERVICEPROPERTIES'] ['SERVICE'] = $_REQUEST ['SERVICE']; + $serviceProp['SERVICEPROPERTIES'] ['NAME'] = $_REQUEST ['KEYPAIRNAME']; + $serviceProp['SERVICEPROPERTIES'] ['VALUE'] = $_REQUEST ['KEYPAIRVALUE']; + if (isset($_REQUEST ['PROP'])) { + $serviceProp['SERVICEPROPERTIES'] ['PROP'] = trim($_REQUEST ['PROP']); + } + if (isset($serviceProp['SERVICEPROPERTIES']['NAME'])) { + $serviceProp['SERVICEPROPERTIES']['NAME'] = $serviceProp['SERVICEPROPERTIES']['NAME']; + } + if (isset($serviceProp['SERVICEPROPERTIES']['VALUE'])) { + $serviceProp['SERVICEPROPERTIES']['VALUE'] = $serviceProp['SERVICEPROPERTIES']['VALUE']; + } + return $serviceProp; } /** * Gets the endpoint properties data passed by user */ -function getEndpointPropDataFromWeb() { - $sp = array(); - if (isset($_REQUEST ['PROP'])){ - $sp ['ENDPOINTPROPERTIES'] ['PROP'] = trim($_REQUEST ['PROP']); +function getEndpointPropDataFromWeb() +{ + $endpointProp = array(); + if (isset($_REQUEST ['PROP'])) { + $endpointProp['ENDPOINTPROPERTIES'] ['PROP'] = trim($_REQUEST ['PROP']); } - if(isset($_REQUEST ['ENDPOINTID'])){ - $sp['ENDPOINTPROPERTIES']['ENDPOINTID'] = trim($_REQUEST ['ENDPOINTID']); + if (isset($_REQUEST ['ENDPOINTID'])) { + $endpointProp['ENDPOINTPROPERTIES']['ENDPOINTID'] = trim($_REQUEST ['ENDPOINTID']); } - if(isset($_REQUEST ['KEYPAIRNAME'])){ - $sp['ENDPOINTPROPERTIES']['NAME'] = $_REQUEST ['KEYPAIRNAME']; + if (isset($_REQUEST ['KEYPAIRNAME'])) { + $endpointProp['ENDPOINTPROPERTIES']['NAME'] = $_REQUEST ['KEYPAIRNAME']; } - if(isset($_REQUEST ['KEYPAIRVALUE'])){ - $sp['ENDPOINTPROPERTIES']['VALUE'] = $_REQUEST ['KEYPAIRVALUE']; + if (isset($_REQUEST ['KEYPAIRVALUE'])) { + $endpointProp['ENDPOINTPROPERTIES']['VALUE'] = $_REQUEST ['KEYPAIRVALUE']; } - return $sp; + return $endpointProp; } /** * Gets the service group properties data passed by user * */ -function getSerGroupPropDataFromWeb() { - $sp ['SERVICEGROUPPROPERTIES'] ['SERVICEGROUP'] = $_REQUEST ['SERVICEGROUP']; - $sp ['SERVICEGROUPPROPERTIES'] ['NAME'] = $_REQUEST ['KEYPAIRNAME']; - $sp ['SERVICEGROUPPROPERTIES'] ['VALUE'] = $_REQUEST ['KEYPAIRVALUE']; - if (isset($_REQUEST ['PROP'])){ - $sp ['SERVICEGROUPPROPERTIES'] ['PROP'] = $_REQUEST ['PROP']; - } - return $sp; +function getSerGroupPropDataFromWeb() +{ + $serGroupProp = []; + $serGroupProp['SERVICEGROUPPROPERTIES'] ['SERVICEGROUP'] = $_REQUEST ['SERVICEGROUP']; + $serGroupProp['SERVICEGROUPPROPERTIES'] ['NAME'] = $_REQUEST ['KEYPAIRNAME']; + $serGroupProp['SERVICEGROUPPROPERTIES'] ['VALUE'] = $_REQUEST ['KEYPAIRVALUE']; + if (isset($_REQUEST ['PROP'])) { + $serGroupProp['SERVICEGROUPPROPERTIES'] ['PROP'] = $_REQUEST ['PROP']; + } + return $serGroupProp; } /** * Gets the service endpoint data passed by user * */ -function getEndpointDataFromWeb() { - $endpoint ['SERVICEENDPOINT'] ['SERVICE'] = $_REQUEST ['SERVICE']; - $endpoint ['SERVICEENDPOINT'] ['NAME'] = trim($_REQUEST ['ENDPOINTNAME']); - $endpoint ['SERVICEENDPOINT'] ['URL'] = trim($_REQUEST ['ENDPOINTURL']); - $endpoint ['SERVICEENDPOINT'] ['INTERFACENAME'] = trim($_REQUEST ['ENDPOINTINTERFACENAME']); - if(isset($_REQUEST ['DESCRIPTION'])){ - $endpoint ['SERVICEENDPOINT'] ['DESCRIPTION'] = trim($_REQUEST ['DESCRIPTION']); - } - if (isset($_REQUEST ['ENDPOINTID'])){ - $endpoint ['SERVICEENDPOINT'] ['ENDPOINTID'] = trim($_REQUEST ['ENDPOINTID']); +function getEndpointDataFromWeb() +{ + $endpoint = []; + $endpoint['SERVICEENDPOINT'] ['SERVICE'] = $_REQUEST ['SERVICE']; + $endpoint['SERVICEENDPOINT'] ['NAME'] = trim($_REQUEST ['ENDPOINTNAME']); + $endpoint['SERVICEENDPOINT'] ['URL'] = trim($_REQUEST ['ENDPOINTURL']); + $endpoint['SERVICEENDPOINT'] ['INTERFACENAME'] = trim($_REQUEST ['ENDPOINTINTERFACENAME']); + if (isset($_REQUEST ['DESCRIPTION'])) { + $endpoint['SERVICEENDPOINT'] ['DESCRIPTION'] = trim($_REQUEST ['DESCRIPTION']); + } + if (isset($_REQUEST ['ENDPOINTID'])) { + $endpoint['SERVICEENDPOINT'] ['ENDPOINTID'] = trim($_REQUEST ['ENDPOINTID']); } $endpoint['SERVICEENDPOINT']['EMAIL'] = trim($_REQUEST ['EMAIL']); //The value comes from a checkbox, which wiill not return a value when unchecked - if(isset($_REQUEST['IS_MONITORED'])) { + if (isset($_REQUEST['IS_MONITORED'])) { $endpoint['IS_MONITORED'] = $_REQUEST ['IS_MONITORED']; } else { - $endpoint['IS_MONITORED'] =false; + $endpoint['IS_MONITORED'] = false; } return $endpoint; @@ -643,7 +688,8 @@ function getEndpointDataFromWeb() { /** * Date format used by the calendar Javascript in downtime controllers * */ -function getDateFormat() { +function getDateFormat() +{ return "d/m/Y H:i"; } @@ -653,15 +699,17 @@ function getDateFormat() { * @global array $_REQUEST array containg the post data * @return array */ -function getScopeDataFromWeb() { - $scopeData ['Name'] = trim($_REQUEST ['Name']); - $scopeData ['Description'] = trim($_REQUEST ['Description']); +function getScopeDataFromWeb() +{ + $scopeData = []; + $scopeData['Name'] = trim($_REQUEST ['Name']); + $scopeData['Description'] = trim($_REQUEST ['Description']); // 'Reserved' value is a checkbox ==>> absent if not checked - if (array_key_exists('Reserved', $_REQUEST)){ - $scopeData ['Reserved'] = ($_REQUEST ['Reserved'] == '1'); + if (array_key_exists('Reserved', $_REQUEST)) { + $scopeData['Reserved'] = ($_REQUEST ['Reserved'] == '1'); } - if (array_key_exists('Id', $_REQUEST)){ - $scopeData ['Id'] = $_REQUEST ['Id']; + if (array_key_exists('Id', $_REQUEST)) { + $scopeData['Id'] = $_REQUEST ['Id']; } return $scopeData; @@ -673,11 +721,18 @@ function getScopeDataFromWeb() { * @global array $_REQUEST array containg the post data * @return array $serviceTypeData an array containg the new site data */ -function getSTDataFromWeb() { - $serviceTypeData ['Name'] = trim($_REQUEST ['Name']); - $serviceTypeData ['Description'] = trim($_REQUEST ['Description']); - if (array_key_exists('ID', $_REQUEST)){ - $serviceTypeData ['ID'] = $_REQUEST ['ID']; +function getSTDataFromWeb() +{ + $serviceTypeData = []; + $serviceTypeData['Name'] = trim($_REQUEST ['Name']); + $serviceTypeData['Description'] = trim($_REQUEST ['Description']); + if (isset($_REQUEST['AllowMonitoringException'])) { + $serviceTypeData['AllowMonitoringException'] = ($_REQUEST ['AllowMonitoringException'] == "checked"); + } else { + $serviceTypeData['AllowMonitoringException'] = false; + } + if (array_key_exists('ID', $_REQUEST)) { + $serviceTypeData['ID'] = $_REQUEST ['ID']; } return $serviceTypeData; @@ -689,15 +744,16 @@ function getSTDataFromWeb() { * @global array $_REQUEST array containg the post data * @return array */ -function getAPIAuthenticationFromWeb() { +function getAPIAuthenticationFromWeb() +{ + $authEntityData = []; $authEntityData['TYPE'] = $_REQUEST['TYPE']; $authEntityData['IDENTIFIER'] = trim($_REQUEST['IDENTIFIER']); - $authEntityData['ALLOW_WRITE'] = key_exists('ALLOW_WRITE', $_REQUEST)? - trim($_REQUEST['ALLOW_WRITE']) == 'checked': + $authEntityData['ALLOW_WRITE'] = key_exists('ALLOW_WRITE', $_REQUEST) ? + trim($_REQUEST['ALLOW_WRITE']) == 'checked' : false; return $authEntityData; - } /** * Return information message text @@ -705,7 +761,8 @@ function getAPIAuthenticationFromWeb() { * @return string short message, a dash, supplementary text * e.g. "PROTECTED - Registration required" */ -function getInfoMessage($code = null) { +function getInfoMessage($code = null) +{ if ($code == null) { $code = 'privacy-1'; @@ -723,37 +780,38 @@ function getInfoMessage($code = null) { } if (!array_key_exists($code, $messages)) { - throw new LogicException("Information message code $code has not been defined. Please contact GOCDB administrators."); + throw new LogicException("Information message code $code has not been defined. " . + "Please contact GOCDB administrators."); } return $messages[$code]; - } /** * Helper function to set view parameters for deciding to show personal data * * @return array parameter array */ -function getReadPDParams($user) { - require_once __DIR__.'/../../../lib/Doctrine/entities/User.php'; +function getReadPDParams($user) +{ + require_once __DIR__ . '/../../../lib/Doctrine/entities/User.php'; $userIsAdmin = false; $authenticated = false; /* */ - if(!is_null($user)) { + if (!is_null($user)) { // User will only see personal data if they have a role somewhere // ToDo: should this be restricted to role at a site? if (!$user instanceof \User) { - throw new LogicException("Personal data read authorisation expected User object as input. Received ". get_class($user) . "'."); + throw new LogicException("Personal data read authorisation expected User object as input. Received " . + get_class($user) . "'."); } - if($user->isAdmin()) { + if ($user->isAdmin()) { $userIsAdmin = true; $authenticated = true; - } - elseif (\Factory::getUserService()->isAllowReadPD($user)) { + } elseif (\Factory::getUserService()->isAllowReadPD($user)) { $authenticated = true; } } diff --git a/htdocs/web_portal/css/web_portal.php b/htdocs/web_portal/css/web_portal.php index 9102a074b..0eab2a969 100644 --- a/htdocs/web_portal/css/web_portal.php +++ b/htdocs/web_portal/css/web_portal.php @@ -774,3 +774,12 @@ vertical-align: middle; padding-right: 1em; } + +img.pencil, img.trash { + height: 25px; + float: right; +} + +img.trash { + margin-right: 0.4em; +} diff --git a/htdocs/web_portal/img/ngi/Collaboration_Tools.jpg b/htdocs/web_portal/img/ngi/Collaboration_Tools.jpg new file mode 100644 index 000000000..b9891f1e7 Binary files /dev/null and b/htdocs/web_portal/img/ngi/Collaboration_Tools.jpg differ diff --git a/htdocs/web_portal/img/ngi/EOSC_AAI.jpg b/htdocs/web_portal/img/ngi/EOSC_AAI.jpg new file mode 100644 index 000000000..b9891f1e7 Binary files /dev/null and b/htdocs/web_portal/img/ngi/EOSC_AAI.jpg differ diff --git a/htdocs/web_portal/img/ngi/EOSC_Accounting.jpg b/htdocs/web_portal/img/ngi/EOSC_Accounting.jpg new file mode 100644 index 000000000..b9891f1e7 Binary files /dev/null and b/htdocs/web_portal/img/ngi/EOSC_Accounting.jpg differ diff --git a/htdocs/web_portal/img/ngi/EOSC_Data_Transfer.jpg b/htdocs/web_portal/img/ngi/EOSC_Data_Transfer.jpg new file mode 100644 index 000000000..b9891f1e7 Binary files /dev/null and b/htdocs/web_portal/img/ngi/EOSC_Data_Transfer.jpg differ diff --git a/htdocs/web_portal/img/ngi/EOSC_Front-Office.jpg b/htdocs/web_portal/img/ngi/EOSC_Front-Office.jpg new file mode 100644 index 000000000..b9891f1e7 Binary files /dev/null and b/htdocs/web_portal/img/ngi/EOSC_Front-Office.jpg differ diff --git a/htdocs/web_portal/img/ngi/EOSC_Helpdesk.jpg b/htdocs/web_portal/img/ngi/EOSC_Helpdesk.jpg new file mode 100644 index 000000000..b9891f1e7 Binary files /dev/null and b/htdocs/web_portal/img/ngi/EOSC_Helpdesk.jpg differ diff --git a/htdocs/web_portal/img/ngi/EOSC_Messaging.jpg b/htdocs/web_portal/img/ngi/EOSC_Messaging.jpg new file mode 100644 index 000000000..b9891f1e7 Binary files /dev/null and b/htdocs/web_portal/img/ngi/EOSC_Messaging.jpg differ diff --git a/htdocs/web_portal/img/ngi/EOSC_Monitoring.jpg b/htdocs/web_portal/img/ngi/EOSC_Monitoring.jpg new file mode 100644 index 000000000..b9891f1e7 Binary files /dev/null and b/htdocs/web_portal/img/ngi/EOSC_Monitoring.jpg differ diff --git a/htdocs/web_portal/img/ngi/EOSC_Observatory.jpg b/htdocs/web_portal/img/ngi/EOSC_Observatory.jpg new file mode 100644 index 000000000..b9891f1e7 Binary files /dev/null and b/htdocs/web_portal/img/ngi/EOSC_Observatory.jpg differ diff --git a/htdocs/web_portal/img/ngi/EOSC_Order_Management.jpg b/htdocs/web_portal/img/ngi/EOSC_Order_Management.jpg new file mode 100644 index 000000000..b9891f1e7 Binary files /dev/null and b/htdocs/web_portal/img/ngi/EOSC_Order_Management.jpg differ diff --git a/htdocs/web_portal/img/ngi/EOSC_Resource_Catalogue.jpg b/htdocs/web_portal/img/ngi/EOSC_Resource_Catalogue.jpg new file mode 100644 index 000000000..b9891f1e7 Binary files /dev/null and b/htdocs/web_portal/img/ngi/EOSC_Resource_Catalogue.jpg differ diff --git a/htdocs/web_portal/img/ngi/EOSC_Topology.jpg b/htdocs/web_portal/img/ngi/EOSC_Topology.jpg new file mode 100644 index 000000000..b9891f1e7 Binary files /dev/null and b/htdocs/web_portal/img/ngi/EOSC_Topology.jpg differ diff --git a/htdocs/web_portal/img/ngi/NGI_LT.jpg b/htdocs/web_portal/img/ngi/NGI_LT.jpg new file mode 100644 index 000000000..05052ed78 Binary files /dev/null and b/htdocs/web_portal/img/ngi/NGI_LT.jpg differ diff --git a/htdocs/web_portal/img/ngi/fullSize/Collaboration_Tools.jpg b/htdocs/web_portal/img/ngi/fullSize/Collaboration_Tools.jpg new file mode 100644 index 000000000..1289f0c8d Binary files /dev/null and b/htdocs/web_portal/img/ngi/fullSize/Collaboration_Tools.jpg differ diff --git a/htdocs/web_portal/img/ngi/fullSize/EOSC_AAI.jpg b/htdocs/web_portal/img/ngi/fullSize/EOSC_AAI.jpg new file mode 100644 index 000000000..1289f0c8d Binary files /dev/null and b/htdocs/web_portal/img/ngi/fullSize/EOSC_AAI.jpg differ diff --git a/htdocs/web_portal/img/ngi/fullSize/EOSC_Accounting.jpg b/htdocs/web_portal/img/ngi/fullSize/EOSC_Accounting.jpg new file mode 100644 index 000000000..1289f0c8d Binary files /dev/null and b/htdocs/web_portal/img/ngi/fullSize/EOSC_Accounting.jpg differ diff --git a/htdocs/web_portal/img/ngi/fullSize/EOSC_Data_Transfer.jpg b/htdocs/web_portal/img/ngi/fullSize/EOSC_Data_Transfer.jpg new file mode 100644 index 000000000..1289f0c8d Binary files /dev/null and b/htdocs/web_portal/img/ngi/fullSize/EOSC_Data_Transfer.jpg differ diff --git a/htdocs/web_portal/img/ngi/fullSize/EOSC_Front-Office.jpg b/htdocs/web_portal/img/ngi/fullSize/EOSC_Front-Office.jpg new file mode 100644 index 000000000..1289f0c8d Binary files /dev/null and b/htdocs/web_portal/img/ngi/fullSize/EOSC_Front-Office.jpg differ diff --git a/htdocs/web_portal/img/ngi/fullSize/EOSC_Helpdesk.jpg b/htdocs/web_portal/img/ngi/fullSize/EOSC_Helpdesk.jpg new file mode 100644 index 000000000..1289f0c8d Binary files /dev/null and b/htdocs/web_portal/img/ngi/fullSize/EOSC_Helpdesk.jpg differ diff --git a/htdocs/web_portal/img/ngi/fullSize/EOSC_Messaging.jpg b/htdocs/web_portal/img/ngi/fullSize/EOSC_Messaging.jpg new file mode 100644 index 000000000..1289f0c8d Binary files /dev/null and b/htdocs/web_portal/img/ngi/fullSize/EOSC_Messaging.jpg differ diff --git a/htdocs/web_portal/img/ngi/fullSize/EOSC_Monitoring.jpg b/htdocs/web_portal/img/ngi/fullSize/EOSC_Monitoring.jpg new file mode 100644 index 000000000..1289f0c8d Binary files /dev/null and b/htdocs/web_portal/img/ngi/fullSize/EOSC_Monitoring.jpg differ diff --git a/htdocs/web_portal/img/ngi/fullSize/EOSC_Observatory.jpg b/htdocs/web_portal/img/ngi/fullSize/EOSC_Observatory.jpg new file mode 100644 index 000000000..1289f0c8d Binary files /dev/null and b/htdocs/web_portal/img/ngi/fullSize/EOSC_Observatory.jpg differ diff --git a/htdocs/web_portal/img/ngi/fullSize/EOSC_Order_Management.jpg b/htdocs/web_portal/img/ngi/fullSize/EOSC_Order_Management.jpg new file mode 100644 index 000000000..1289f0c8d Binary files /dev/null and b/htdocs/web_portal/img/ngi/fullSize/EOSC_Order_Management.jpg differ diff --git a/htdocs/web_portal/img/ngi/fullSize/EOSC_Resource_Catalogue.jpg b/htdocs/web_portal/img/ngi/fullSize/EOSC_Resource_Catalogue.jpg new file mode 100644 index 000000000..1289f0c8d Binary files /dev/null and b/htdocs/web_portal/img/ngi/fullSize/EOSC_Resource_Catalogue.jpg differ diff --git a/htdocs/web_portal/img/ngi/fullSize/EOSC_Topology.jpg b/htdocs/web_portal/img/ngi/fullSize/EOSC_Topology.jpg new file mode 100644 index 000000000..1289f0c8d Binary files /dev/null and b/htdocs/web_portal/img/ngi/fullSize/EOSC_Topology.jpg differ diff --git a/htdocs/web_portal/img/ngi/fullSize/NGI_LT.jpg b/htdocs/web_portal/img/ngi/fullSize/NGI_LT.jpg new file mode 100644 index 000000000..1c6a94ed1 Binary files /dev/null and b/htdocs/web_portal/img/ngi/fullSize/NGI_LT.jpg differ diff --git a/htdocs/web_portal/index.php b/htdocs/web_portal/index.php index 2e21d49f6..6947b333c 100644 --- a/htdocs/web_portal/index.php +++ b/htdocs/web_portal/index.php @@ -76,7 +76,7 @@ function rejectIfNotAuthenticated($message = null){ //rejectIfNotAuthenticated(); // Initialise the configuration service with the host url of the incoming request. -// Allows the overriding of configuration values. Do not use 'new' to create a new +// Allows the overriding of configuration values. Do not use 'new' to create a new // instance after this. \Factory::getConfigService()->setLocalInfoOverride($_SERVER['SERVER_NAME']); diff --git a/htdocs/web_portal/views/admin/add_ngi.php b/htdocs/web_portal/views/admin/add_ngi.php index f8485014e..534d1e92f 100644 --- a/htdocs/web_portal/views/admin/add_ngi.php +++ b/htdocs/web_portal/views/admin/add_ngi.php @@ -67,4 +67,4 @@ '#optionalScopeCheckBoxDIV', true); }); - \ No newline at end of file + diff --git a/htdocs/web_portal/views/admin/add_project.php b/htdocs/web_portal/views/admin/add_project.php index cb3e6fa97..039288498 100644 --- a/htdocs/web_portal/views/admin/add_project.php +++ b/htdocs/web_portal/views/admin/add_project.php @@ -10,4 +10,4 @@
    - \ No newline at end of file + diff --git a/htdocs/web_portal/views/admin/add_scope.php b/htdocs/web_portal/views/admin/add_scope.php index 88fade79c..b460ddf7d 100644 --- a/htdocs/web_portal/views/admin/add_scope.php +++ b/htdocs/web_portal/views/admin/add_scope.php @@ -11,4 +11,4 @@
    - \ No newline at end of file + diff --git a/htdocs/web_portal/views/admin/add_service_type.php b/htdocs/web_portal/views/admin/add_service_type.php index 173259ca0..a9cc34a1a 100644 --- a/htdocs/web_portal/views/admin/add_service_type.php +++ b/htdocs/web_portal/views/admin/add_service_type.php @@ -6,8 +6,14 @@ Description - + + + +
    - \ No newline at end of file + + - diff --git a/htdocs/web_portal/views/admin/added_project.php b/htdocs/web_portal/views/admin/added_project.php index 8e8743e81..c7e3c87b3 100644 --- a/htdocs/web_portal/views/admin/added_project.php +++ b/htdocs/web_portal/views/admin/added_project.php @@ -10,4 +10,3 @@ - diff --git a/htdocs/web_portal/views/admin/added_scope.php b/htdocs/web_portal/views/admin/added_scope.php index abaa46cb1..83e541679 100644 --- a/htdocs/web_portal/views/admin/added_scope.php +++ b/htdocs/web_portal/views/admin/added_scope.php @@ -9,4 +9,3 @@ - diff --git a/htdocs/web_portal/views/admin/added_service_type.php b/htdocs/web_portal/views/admin/added_service_type.php index e38caf4b3..8654752d9 100644 --- a/htdocs/web_portal/views/admin/added_service_type.php +++ b/htdocs/web_portal/views/admin/added_service_type.php @@ -1,14 +1,11 @@

    Success


    +

    New service type created -

    + + - has been successfully added as a new service - type with the following description: "". -
    -
    Click here to view the service type.
    - - diff --git a/htdocs/web_portal/views/admin/delete_ngi.php b/htdocs/web_portal/views/admin/delete_ngi.php index 491979ad2..4d145d9a5 100644 --- a/htdocs/web_portal/views/admin/delete_ngi.php +++ b/htdocs/web_portal/views/admin/delete_ngi.php @@ -50,4 +50,4 @@ - \ No newline at end of file + diff --git a/htdocs/web_portal/views/admin/delete_scope_denied.php b/htdocs/web_portal/views/admin/delete_scope_denied.php index 254eae0f0..5acfb70fa 100644 --- a/htdocs/web_portal/views/admin/delete_scope_denied.php +++ b/htdocs/web_portal/views/admin/delete_scope_denied.php @@ -64,4 +64,4 @@ - \ No newline at end of file + diff --git a/htdocs/web_portal/views/admin/delete_service_type_denied.php b/htdocs/web_portal/views/admin/delete_service_type_denied.php index cde534411..170852f70 100644 --- a/htdocs/web_portal/views/admin/delete_service_type_denied.php +++ b/htdocs/web_portal/views/admin/delete_service_type_denied.php @@ -19,4 +19,4 @@
    These services will need their service type changing before the service type can be deleted. - \ No newline at end of file + diff --git a/htdocs/web_portal/views/admin/deleted_ngi.php b/htdocs/web_portal/views/admin/deleted_ngi.php index 4feecbdf2..26940f665 100644 --- a/htdocs/web_portal/views/admin/deleted_ngi.php +++ b/htdocs/web_portal/views/admin/deleted_ngi.php @@ -1,4 +1,4 @@

    Deletion Successful


    The NGI '' and any associated sites and services have been successfully removed from GOCDB -
    \ No newline at end of file + diff --git a/htdocs/web_portal/views/admin/deleted_scope.php b/htdocs/web_portal/views/admin/deleted_scope.php index 7d2a73d2a..67e485c50 100644 --- a/htdocs/web_portal/views/admin/deleted_scope.php +++ b/htdocs/web_portal/views/admin/deleted_scope.php @@ -1,4 +1,4 @@

    Deletion Successful


    The scope '' has been successfully removed from GOCDB -
    \ No newline at end of file + diff --git a/htdocs/web_portal/views/admin/deleted_service_type.php b/htdocs/web_portal/views/admin/deleted_service_type.php index 59d610f58..242a0143c 100644 --- a/htdocs/web_portal/views/admin/deleted_service_type.php +++ b/htdocs/web_portal/views/admin/deleted_service_type.php @@ -1,4 +1,4 @@

    Deletion Successful


    The service type '' has been successfully removed from GOCDB -
    \ No newline at end of file + diff --git a/htdocs/web_portal/views/admin/edit_scope.php b/htdocs/web_portal/views/admin/edit_scope.php index 821d2684b..2881c2ee9 100644 --- a/htdocs/web_portal/views/admin/edit_scope.php +++ b/htdocs/web_portal/views/admin/edit_scope.php @@ -13,4 +13,4 @@
    - \ No newline at end of file + diff --git a/htdocs/web_portal/views/admin/edit_service_type.php b/htdocs/web_portal/views/admin/edit_service_type.php index 709c4c29f..a2ca48f9e 100644 --- a/htdocs/web_portal/views/admin/edit_service_type.php +++ b/htdocs/web_portal/views/admin/edit_service_type.php @@ -7,9 +7,21 @@ Description -
    + + + /> + + +
    - \ No newline at end of file + diff --git a/htdocs/web_portal/views/admin/edit_user_identifier.php b/htdocs/web_portal/views/admin/edit_user_identifier.php index 5bf878b65..95169c873 100644 --- a/htdocs/web_portal/views/admin/edit_user_identifier.php +++ b/htdocs/web_portal/views/admin/edit_user_identifier.php @@ -41,4 +41,4 @@ - \ No newline at end of file + diff --git a/htdocs/web_portal/views/admin/edited_scope.php b/htdocs/web_portal/views/admin/edited_scope.php index 294bddc1e..141091791 100644 --- a/htdocs/web_portal/views/admin/edited_scope.php +++ b/htdocs/web_portal/views/admin/edited_scope.php @@ -19,4 +19,3 @@

    - diff --git a/htdocs/web_portal/views/admin/edited_service_type.php b/htdocs/web_portal/views/admin/edited_service_type.php index 30733251c..76b3924eb 100644 --- a/htdocs/web_portal/views/admin/edited_service_type.php +++ b/htdocs/web_portal/views/admin/edited_service_type.php @@ -1,18 +1,14 @@

    Success


    -

    - has been successfully edited as follows: -

    -

    - Name: -
    - Description: +

    + Service Type properties have been successfully edited to -

    + + +

    Click here to edit the service type again.

    - - diff --git a/htdocs/web_portal/views/admin/edited_user_identifier.php b/htdocs/web_portal/views/admin/edited_user_identifier.php index 87b259864..e5bc53a98 100644 --- a/htdocs/web_portal/views/admin/edited_user_identifier.php +++ b/htdocs/web_portal/views/admin/edited_user_identifier.php @@ -6,5 +6,3 @@ has been successfully updated. - - diff --git a/htdocs/web_portal/views/admin/edited_user_isadmin.php b/htdocs/web_portal/views/admin/edited_user_isadmin.php index 7d31bb805..298ef3ba3 100644 --- a/htdocs/web_portal/views/admin/edited_user_isadmin.php +++ b/htdocs/web_portal/views/admin/edited_user_isadmin.php @@ -13,5 +13,3 @@ Return to the users page. - - diff --git a/htdocs/web_portal/views/admin/move_service_end_point.php b/htdocs/web_portal/views/admin/move_service_end_point.php index 10f0183e8..32ca79c46 100644 --- a/htdocs/web_portal/views/admin/move_service_end_point.php +++ b/htdocs/web_portal/views/admin/move_service_end_point.php @@ -26,4 +26,4 @@
    - \ No newline at end of file + diff --git a/htdocs/web_portal/views/admin/move_service_end_point_select_old_site.php b/htdocs/web_portal/views/admin/move_service_end_point_select_old_site.php index b258b32a4..23634b512 100644 --- a/htdocs/web_portal/views/admin/move_service_end_point_select_old_site.php +++ b/htdocs/web_portal/views/admin/move_service_end_point_select_old_site.php @@ -14,4 +14,4 @@ - \ No newline at end of file + diff --git a/htdocs/web_portal/views/admin/move_site.php b/htdocs/web_portal/views/admin/move_site.php index 73241db5c..0f30ae81e 100644 --- a/htdocs/web_portal/views/admin/move_site.php +++ b/htdocs/web_portal/views/admin/move_site.php @@ -26,4 +26,4 @@
    - \ No newline at end of file + diff --git a/htdocs/web_portal/views/admin/move_site_select_old_ngi.php b/htdocs/web_portal/views/admin/move_site_select_old_ngi.php index 6e2a279bc..432c3c734 100644 --- a/htdocs/web_portal/views/admin/move_site_select_old_ngi.php +++ b/htdocs/web_portal/views/admin/move_site_select_old_ngi.php @@ -14,4 +14,4 @@ - \ No newline at end of file + diff --git a/htdocs/web_portal/views/admin/moved_service_end_point.php b/htdocs/web_portal/views/admin/moved_service_end_point.php index d1a799006..4e4ded933 100644 --- a/htdocs/web_portal/views/admin/moved_service_end_point.php +++ b/htdocs/web_portal/views/admin/moved_service_end_point.php @@ -13,4 +13,4 @@ . " "; } ?> - \ No newline at end of file + diff --git a/htdocs/web_portal/views/admin/moved_site.php b/htdocs/web_portal/views/admin/moved_site.php index 1374f4be5..f70d36f27 100644 --- a/htdocs/web_portal/views/admin/moved_site.php +++ b/htdocs/web_portal/views/admin/moved_site.php @@ -13,4 +13,4 @@ . " "; } ?> - \ No newline at end of file + diff --git a/htdocs/web_portal/views/admin/view_service_type.php b/htdocs/web_portal/views/admin/view_service_type.php index 15dce787c..0c407dccf 100644 --- a/htdocs/web_portal/views/admin/view_service_type.php +++ b/htdocs/web_portal/views/admin/view_service_type.php @@ -1,9 +1,10 @@ @@ -13,26 +14,32 @@

    Service Type:

    - + +
    +
    - +
    $test$test{$test_messages[$test]}{$test_doc[$test]}{$test_messages[$test]}{$test_doc[$test]}
    OK
    @@ -63,8 +78,8 @@ + foreach ($services as $se) { + ?> - diff --git a/htdocs/web_portal/views/admin/view_service_types.php b/htdocs/web_portal/views/admin/view_service_types.php index c7100d962..7586f3739 100644 --- a/htdocs/web_portal/views/admin/view_service_types.php +++ b/htdocs/web_portal/views/admin/view_service_types.php @@ -10,7 +10,7 @@ - +
    Hostname
    @@ -72,7 +87,8 @@ - getHostname());?> (getServiceType()->getName());?>) + getHostname());?> + (getServiceType()->getName());?>) @@ -80,15 +96,17 @@ getProduction()) { + switch ($se->getProduction()) { case true: ?> - + - + getMonitored()) { + switch ($se->getMonitored()) { case true: ?> - + - + getScopeNamesAsString()); ?>
    + 0)) { - foreach($params['ServiceTypes'] as $serviceType) { - ?> + if ($numberOfServiceTypes > 0) { + foreach ($params['ServiceTypes'] as $serviceType) { + ?> + + -
    NameServices Description
    @@ -48,15 +51,23 @@
    + getServices())); ?> + getDescription()); ?>
    - \ No newline at end of file + diff --git a/htdocs/web_portal/views/downtime/add_downtime.php b/htdocs/web_portal/views/downtime/add_downtime.php index 35508c0d2..50b255cb0 100644 --- a/htdocs/web_portal/views/downtime/add_downtime.php +++ b/htdocs/web_portal/views/downtime/add_downtime.php @@ -631,21 +631,3 @@ function getURLParameter(name) { }*/ - - - - - - - - - - - - - - - - - - diff --git a/htdocs/web_portal/views/downtime/added_downtime.php b/htdocs/web_portal/views/downtime/added_downtime.php index 563515a0c..68ed49348 100644 --- a/htdocs/web_portal/views/downtime/added_downtime.php +++ b/htdocs/web_portal/views/downtime/added_downtime.php @@ -2,4 +2,4 @@

    Success


    New Downtime successfully created.
    View new downtime - \ No newline at end of file + diff --git a/htdocs/web_portal/views/downtime/confirm_add_downtime.php b/htdocs/web_portal/views/downtime/confirm_add_downtime.php index 6ecebd831..84583afb1 100644 --- a/htdocs/web_portal/views/downtime/confirm_add_downtime.php +++ b/htdocs/web_portal/views/downtime/confirm_add_downtime.php @@ -99,4 +99,3 @@ - diff --git a/htdocs/web_portal/views/downtime/custom_json_encode.php b/htdocs/web_portal/views/downtime/custom_json_encode.php index ed9ec8b2f..57dbac537 100644 --- a/htdocs/web_portal/views/downtime/custom_json_encode.php +++ b/htdocs/web_portal/views/downtime/custom_json_encode.php @@ -59,4 +59,4 @@ function __json_encode( $data ) { $json = strtolower(var_export( $data, true )); } return $json; -} \ No newline at end of file +} diff --git a/htdocs/web_portal/views/downtime/deleted_downtime.php b/htdocs/web_portal/views/downtime/deleted_downtime.php index 7366bca59..d60c2efc9 100644 --- a/htdocs/web_portal/views/downtime/deleted_downtime.php +++ b/htdocs/web_portal/views/downtime/deleted_downtime.php @@ -3,4 +3,4 @@ Downtime deleted.
    Go Home - \ No newline at end of file + diff --git a/htdocs/web_portal/views/downtime/downtimes_calendar.php b/htdocs/web_portal/views/downtime/downtimes_calendar.php index b3ad0e7c1..e46196e55 100644 --- a/htdocs/web_portal/views/downtime/downtimes_calendar.php +++ b/htdocs/web_portal/views/downtime/downtimes_calendar.php @@ -676,4 +676,4 @@ function updateDate(time) { changeViewMode(); }) - \ No newline at end of file + diff --git a/htdocs/web_portal/views/downtime/edit_downtime.php b/htdocs/web_portal/views/downtime/edit_downtime.php index e2f54ba4e..02149685f 100644 --- a/htdocs/web_portal/views/downtime/edit_downtime.php +++ b/htdocs/web_portal/views/downtime/edit_downtime.php @@ -225,7 +225,10 @@ class="form-control" id="Select_Sites" name="select_sites" size="10" $('#startDate').data("DateTimePicker").date(""); $('#endDate').data("DateTimePicker").date(""); - //Set the start and finish times (don't echo in the full date, just the time values, time widget didn’t like timestamp with date) + /** + * Set the start and finish times (don't echo in the full date, + * just the time values, time widget didn't like timestamp with date) + */ $('#startTime').data("DateTimePicker").date(""); $('#endTime').data("DateTimePicker").date(""); @@ -654,21 +657,3 @@ function getDate(){ return datesValid; }*/ - - - - - - - - - - - - - - - - - - diff --git a/htdocs/web_portal/views/downtime/edited_downtime.php b/htdocs/web_portal/views/downtime/edited_downtime.php index befc0212d..c9d94370f 100644 --- a/htdocs/web_portal/views/downtime/edited_downtime.php +++ b/htdocs/web_portal/views/downtime/edited_downtime.php @@ -3,4 +3,4 @@ Downtime updated.
    View downtime - \ No newline at end of file + diff --git a/htdocs/web_portal/views/downtime/ended_downtime.php b/htdocs/web_portal/views/downtime/ended_downtime.php index 32932746b..049cab3dd 100644 --- a/htdocs/web_portal/views/downtime/ended_downtime.php +++ b/htdocs/web_portal/views/downtime/ended_downtime.php @@ -3,4 +3,4 @@ Downtime will end within the next 60 seconds.
    View downtime - \ No newline at end of file + diff --git a/htdocs/web_portal/views/downtime/view_downtime.php b/htdocs/web_portal/views/downtime/view_downtime.php index 8e4f284e1..06f22589a 100644 --- a/htdocs/web_portal/views/downtime/view_downtime.php +++ b/htdocs/web_portal/views/downtime/view_downtime.php @@ -23,7 +23,7 @@ \ No newline at end of file + diff --git a/htdocs/web_portal/views/exportProperties.php b/htdocs/web_portal/views/exportProperties.php index e3ddb11d5..6bb7bcde1 100644 --- a/htdocs/web_portal/views/exportProperties.php +++ b/htdocs/web_portal/views/exportProperties.php @@ -6,4 +6,3 @@ echo(PHP_EOL); } ?> - diff --git a/htdocs/web_portal/views/fragments/serviceTypeInfo.php b/htdocs/web_portal/views/fragments/serviceTypeInfo.php new file mode 100644 index 000000000..dad7e47f4 --- /dev/null +++ b/htdocs/web_portal/views/fragments/serviceTypeInfo.php @@ -0,0 +1,23 @@ + + + + + + + + + + + + + +
    Name:
    Description:
    Monitoring: + +
    +
    diff --git a/htdocs/web_portal/views/my_sites.php b/htdocs/web_portal/views/my_sites.php index 36428d88f..938ccfd8e 100644 --- a/htdocs/web_portal/views/my_sites.php +++ b/htdocs/web_portal/views/my_sites.php @@ -93,4 +93,3 @@ - diff --git a/htdocs/web_portal/views/ngi/edit_ngi.php b/htdocs/web_portal/views/ngi/edit_ngi.php index ceefa63d3..49f86dbbb 100644 --- a/htdocs/web_portal/views/ngi/edit_ngi.php +++ b/htdocs/web_portal/views/ngi/edit_ngi.php @@ -85,4 +85,4 @@ '#optionalScopeCheckBoxDIV', true); }); - \ No newline at end of file + diff --git a/htdocs/web_portal/views/ngi/ngi_updated.php b/htdocs/web_portal/views/ngi/ngi_updated.php index 5a4062123..24212102f 100644 --- a/htdocs/web_portal/views/ngi/ngi_updated.php +++ b/htdocs/web_portal/views/ngi/ngi_updated.php @@ -3,4 +3,4 @@ NGI updated.
    View NGI - \ No newline at end of file + diff --git a/htdocs/web_portal/views/ngi/view_ngi.php b/htdocs/web_portal/views/ngi/view_ngi.php index 50ae20b58..14a176c76 100644 --- a/htdocs/web_portal/views/ngi/view_ngi.php +++ b/htdocs/web_portal/views/ngi/view_ngi.php @@ -26,7 +26,7 @@ - +
    Admin
    Delete
    @@ -35,7 +35,7 @@ \ No newline at end of file + diff --git a/htdocs/web_portal/views/political_role/request_accepted.php b/htdocs/web_portal/views/political_role/request_accepted.php index 791bacc4c..2c5f8868a 100644 --- a/htdocs/web_portal/views/political_role/request_accepted.php +++ b/htdocs/web_portal/views/political_role/request_accepted.php @@ -1,4 +1,4 @@

    Success

    Role request accepted -
    \ No newline at end of file + diff --git a/htdocs/web_portal/views/political_role/request_denied.php b/htdocs/web_portal/views/political_role/request_denied.php index b819527c9..dbbaf4c80 100644 --- a/htdocs/web_portal/views/political_role/request_denied.php +++ b/htdocs/web_portal/views/political_role/request_denied.php @@ -1,4 +1,4 @@

    Success

    Role request denied -
    \ No newline at end of file + diff --git a/htdocs/web_portal/views/political_role/request_role.php b/htdocs/web_portal/views/political_role/request_role.php index ed2042dd3..f34fe4f22 100644 --- a/htdocs/web_portal/views/political_role/request_role.php +++ b/htdocs/web_portal/views/political_role/request_role.php @@ -22,4 +22,4 @@ - \ No newline at end of file + diff --git a/htdocs/web_portal/views/political_role/role_revoked.php b/htdocs/web_portal/views/political_role/role_revoked.php index 5faf0864b..7174ce985 100644 --- a/htdocs/web_portal/views/political_role/role_revoked.php +++ b/htdocs/web_portal/views/political_role/role_revoked.php @@ -4,4 +4,3 @@
    Back to Manage Role Requests - diff --git a/htdocs/web_portal/views/political_role/role_self_revoked.php b/htdocs/web_portal/views/political_role/role_self_revoked.php index 2a2d894a8..7a2149456 100644 --- a/htdocs/web_portal/views/political_role/role_self_revoked.php +++ b/htdocs/web_portal/views/political_role/role_self_revoked.php @@ -4,4 +4,3 @@
    Back to Manage Role Requests - diff --git a/htdocs/web_portal/views/project/add_ngis.php b/htdocs/web_portal/views/project/add_ngis.php index e787e3bde..89d6bb021 100644 --- a/htdocs/web_portal/views/project/add_ngis.php +++ b/htdocs/web_portal/views/project/add_ngis.php @@ -40,4 +40,3 @@ - diff --git a/htdocs/web_portal/views/project/added_ngis.php b/htdocs/web_portal/views/project/added_ngis.php index 25c7eb159..f61f5747d 100644 --- a/htdocs/web_portal/views/project/added_ngis.php +++ b/htdocs/web_portal/views/project/added_ngis.php @@ -12,4 +12,4 @@ . " "; } ?> - \ No newline at end of file + diff --git a/htdocs/web_portal/views/project/deleted_project.php b/htdocs/web_portal/views/project/deleted_project.php index bc0604de3..589f33aa3 100644 --- a/htdocs/web_portal/views/project/deleted_project.php +++ b/htdocs/web_portal/views/project/deleted_project.php @@ -1,4 +1,4 @@

    Deletion Successful


    The project '' has been successfully removed from GOCDB -
    \ No newline at end of file + diff --git a/htdocs/web_portal/views/project/edit_project.php b/htdocs/web_portal/views/project/edit_project.php index de5f05fd6..9b38a9725 100644 --- a/htdocs/web_portal/views/project/edit_project.php +++ b/htdocs/web_portal/views/project/edit_project.php @@ -13,4 +13,4 @@
    - \ No newline at end of file + diff --git a/htdocs/web_portal/views/project/edited_project.php b/htdocs/web_portal/views/project/edited_project.php index 9057a631d..855043a98 100644 --- a/htdocs/web_portal/views/project/edited_project.php +++ b/htdocs/web_portal/views/project/edited_project.php @@ -15,5 +15,3 @@

    - - diff --git a/htdocs/web_portal/views/project/remove_ngis.php b/htdocs/web_portal/views/project/remove_ngis.php index 4d165ca87..2f7c63670 100644 --- a/htdocs/web_portal/views/project/remove_ngis.php +++ b/htdocs/web_portal/views/project/remove_ngis.php @@ -35,4 +35,3 @@ - diff --git a/htdocs/web_portal/views/project/removed_ngis.php b/htdocs/web_portal/views/project/removed_ngis.php index fa5518ef9..ee6f05456 100644 --- a/htdocs/web_portal/views/project/removed_ngis.php +++ b/htdocs/web_portal/views/project/removed_ngis.php @@ -4,4 +4,4 @@ project - \ No newline at end of file + diff --git a/htdocs/web_portal/views/project/view_project.php b/htdocs/web_portal/views/project/view_project.php index 93fb6244b..03f107861 100644 --- a/htdocs/web_portal/views/project/view_project.php +++ b/htdocs/web_portal/views/project/view_project.php @@ -23,7 +23,7 @@
    - +

    Edit @@ -35,7 +35,7 @@
    - +

    Delete diff --git a/htdocs/web_portal/views/scope.php b/htdocs/web_portal/views/scope.php index 5b4dfe9dc..b197a114f 100644 --- a/htdocs/web_portal/views/scope.php +++ b/htdocs/web_portal/views/scope.php @@ -43,7 +43,7 @@
    0"?> - + + 0) { ?> +
    +
    + +

    + API credentials +

    +
    + + + + + + + + + + + + + + + + + + +
    Site NameIdentifier
    + + getParentSite()->getShortName()) ?> + + + getIdentifier()); ?> +
    + +
    + 0"?> + +
    No results found
    diff --git a/htdocs/web_portal/views/service/add_endpoint_properties.php b/htdocs/web_portal/views/service/add_endpoint_properties.php index 17e4612ac..a981edfbd 100644 --- a/htdocs/web_portal/views/service/add_endpoint_properties.php +++ b/htdocs/web_portal/views/service/add_endpoint_properties.php @@ -7,4 +7,4 @@ -
    \ No newline at end of file +
    diff --git a/htdocs/web_portal/views/service/add_endpoint_properties_confirmation.php b/htdocs/web_portal/views/service/add_endpoint_properties_confirmation.php index b318672bb..9c7b933c8 100644 --- a/htdocs/web_portal/views/service/add_endpoint_properties_confirmation.php +++ b/htdocs/web_portal/views/service/add_endpoint_properties_confirmation.php @@ -7,4 +7,4 @@

    Add Endpoint Properties


    -
    \ No newline at end of file + diff --git a/htdocs/web_portal/views/service/add_service_properties.php b/htdocs/web_portal/views/service/add_service_properties.php index 50da4216a..3fe624d24 100644 --- a/htdocs/web_portal/views/service/add_service_properties.php +++ b/htdocs/web_portal/views/service/add_service_properties.php @@ -7,4 +7,4 @@ - \ No newline at end of file + diff --git a/htdocs/web_portal/views/service/add_service_properties_confirmation.php b/htdocs/web_portal/views/service/add_service_properties_confirmation.php index cf2f7e9e4..0e4115b1f 100644 --- a/htdocs/web_portal/views/service/add_service_properties_confirmation.php +++ b/htdocs/web_portal/views/service/add_service_properties_confirmation.php @@ -7,4 +7,4 @@

    Add Service Properties


    -
    \ No newline at end of file + diff --git a/htdocs/web_portal/views/service/added_endpoint_properties.php b/htdocs/web_portal/views/service/added_endpoint_properties.php index 74b93f9b5..a008464f6 100644 --- a/htdocs/web_portal/views/service/added_endpoint_properties.php +++ b/htdocs/web_portal/views/service/added_endpoint_properties.php @@ -10,4 +10,4 @@
    View endpoint - \ No newline at end of file + diff --git a/htdocs/web_portal/views/service/added_service_properties.php b/htdocs/web_portal/views/service/added_service_properties.php index a62361886..d35e773c9 100644 --- a/htdocs/web_portal/views/service/added_service_properties.php +++ b/htdocs/web_portal/views/service/added_service_properties.php @@ -10,4 +10,4 @@ View service - \ No newline at end of file + diff --git a/htdocs/web_portal/views/service/delete_service_endpoint.php b/htdocs/web_portal/views/service/delete_service_endpoint.php index ef8cbdf7c..46694dbd5 100644 --- a/htdocs/web_portal/views/service/delete_service_endpoint.php +++ b/htdocs/web_portal/views/service/delete_service_endpoint.php @@ -20,4 +20,4 @@ - \ No newline at end of file + diff --git a/htdocs/web_portal/views/service/deleted_endpoint_properties.php b/htdocs/web_portal/views/service/deleted_endpoint_properties.php index 11517b36e..91401ad01 100644 --- a/htdocs/web_portal/views/service/deleted_endpoint_properties.php +++ b/htdocs/web_portal/views/service/deleted_endpoint_properties.php @@ -17,4 +17,4 @@ View endpoint

    - \ No newline at end of file + diff --git a/htdocs/web_portal/views/service/deleted_service_endpoint.php b/htdocs/web_portal/views/service/deleted_service_endpoint.php index ff5ba8d37..2290a4b5d 100644 --- a/htdocs/web_portal/views/service/deleted_service_endpoint.php +++ b/htdocs/web_portal/views/service/deleted_service_endpoint.php @@ -15,4 +15,4 @@ View service

    - \ No newline at end of file + diff --git a/htdocs/web_portal/views/service/deleted_service_properties.php b/htdocs/web_portal/views/service/deleted_service_properties.php index 93a6623e7..cd9783e19 100644 --- a/htdocs/web_portal/views/service/deleted_service_properties.php +++ b/htdocs/web_portal/views/service/deleted_service_properties.php @@ -17,4 +17,4 @@ View service

    - \ No newline at end of file + diff --git a/htdocs/web_portal/views/service/edit_endpoint_property.php b/htdocs/web_portal/views/service/edit_endpoint_property.php index 4386ff6f2..1416599ad 100644 --- a/htdocs/web_portal/views/service/edit_endpoint_property.php +++ b/htdocs/web_portal/views/service/edit_endpoint_property.php @@ -22,4 +22,4 @@ - \ No newline at end of file + diff --git a/htdocs/web_portal/views/service/edit_service_property.php b/htdocs/web_portal/views/service/edit_service_property.php index f4f193a53..a32f7c619 100644 --- a/htdocs/web_portal/views/service/edit_service_property.php +++ b/htdocs/web_portal/views/service/edit_service_property.php @@ -21,4 +21,4 @@ - \ No newline at end of file + diff --git a/htdocs/web_portal/views/service/endpoint_property_updated.php b/htdocs/web_portal/views/service/endpoint_property_updated.php index af8920e57..2800419b1 100644 --- a/htdocs/web_portal/views/service/endpoint_property_updated.php +++ b/htdocs/web_portal/views/service/endpoint_property_updated.php @@ -3,4 +3,4 @@ Endpoint Property updated.
    View endpoint - \ No newline at end of file + diff --git a/htdocs/web_portal/views/service/service_deleted.php b/htdocs/web_portal/views/service/service_deleted.php index d0d32aadb..7aab00e81 100644 --- a/htdocs/web_portal/views/service/service_deleted.php +++ b/htdocs/web_portal/views/service/service_deleted.php @@ -3,4 +3,4 @@ Service deleted.
    Go Home - \ No newline at end of file + diff --git a/htdocs/web_portal/views/service/service_endpoint_updated.php b/htdocs/web_portal/views/service/service_endpoint_updated.php index 38e14d4b6..741318c8c 100644 --- a/htdocs/web_portal/views/service/service_endpoint_updated.php +++ b/htdocs/web_portal/views/service/service_endpoint_updated.php @@ -6,4 +6,4 @@
    View Service - \ No newline at end of file + diff --git a/htdocs/web_portal/views/service/service_property_updated.php b/htdocs/web_portal/views/service/service_property_updated.php index e960f5c4f..e810d2eb4 100644 --- a/htdocs/web_portal/views/service/service_property_updated.php +++ b/htdocs/web_portal/views/service/service_property_updated.php @@ -3,4 +3,4 @@ Service Property updated.
    View service - \ No newline at end of file + diff --git a/htdocs/web_portal/views/service/service_updated.php b/htdocs/web_portal/views/service/service_updated.php index 2dbf7753e..c663f09dd 100644 --- a/htdocs/web_portal/views/service/service_updated.php +++ b/htdocs/web_portal/views/service/service_updated.php @@ -3,4 +3,4 @@ Service updated.
    View service - \ No newline at end of file + diff --git a/htdocs/web_portal/views/service/submit_add_service.php b/htdocs/web_portal/views/service/submit_add_service.php index 674eb6cb8..d07c9eefe 100644 --- a/htdocs/web_portal/views/service/submit_add_service.php +++ b/htdocs/web_portal/views/service/submit_add_service.php @@ -3,4 +3,4 @@ New Service successfully created.
    View new service - \ No newline at end of file + diff --git a/htdocs/web_portal/views/service/view_service.php b/htdocs/web_portal/views/service/view_service.php index 1d4efe983..ee3c6ad93 100644 --- a/htdocs/web_portal/views/service/view_service.php +++ b/htdocs/web_portal/views/service/view_service.php @@ -23,7 +23,7 @@
    - +

    Edit @@ -33,7 +33,7 @@
    - +

    Delete diff --git a/htdocs/web_portal/views/service/view_service_endpoint.php b/htdocs/web_portal/views/service/view_service_endpoint.php index 0944b428e..a0390fae3 100644 --- a/htdocs/web_portal/views/service/view_service_endpoint.php +++ b/htdocs/web_portal/views/service/view_service_endpoint.php @@ -26,7 +26,7 @@
    diff --git a/htdocs/web_portal/views/service_group/add_service_group.php b/htdocs/web_portal/views/service_group/add_service_group.php index 0cbfbc74c..26d9efc7e 100644 --- a/htdocs/web_portal/views/service_group/add_service_group.php +++ b/htdocs/web_portal/views/service_group/add_service_group.php @@ -53,4 +53,4 @@ '#optionalScopeCheckBoxDIV', true); }); - \ No newline at end of file + diff --git a/htdocs/web_portal/views/service_group/add_service_group_properties.php b/htdocs/web_portal/views/service_group/add_service_group_properties.php index aa7a76004..2a30bf862 100644 --- a/htdocs/web_portal/views/service_group/add_service_group_properties.php +++ b/htdocs/web_portal/views/service_group/add_service_group_properties.php @@ -7,4 +7,4 @@ -
    \ No newline at end of file +
    diff --git a/htdocs/web_portal/views/service_group/add_service_group_properties_confirmation.php b/htdocs/web_portal/views/service_group/add_service_group_properties_confirmation.php index 520b921c2..700498b21 100644 --- a/htdocs/web_portal/views/service_group/add_service_group_properties_confirmation.php +++ b/htdocs/web_portal/views/service_group/add_service_group_properties_confirmation.php @@ -7,4 +7,4 @@

    Add Service Group Properties


    -
    \ No newline at end of file + diff --git a/htdocs/web_portal/views/service_group/added_service_group_properties.php b/htdocs/web_portal/views/service_group/added_service_group_properties.php index ee0d1cd24..4b16eda0e 100644 --- a/htdocs/web_portal/views/service_group/added_service_group_properties.php +++ b/htdocs/web_portal/views/service_group/added_service_group_properties.php @@ -10,4 +10,4 @@
    View service group - \ No newline at end of file + diff --git a/htdocs/web_portal/views/service_group/deleted_service_group.php b/htdocs/web_portal/views/service_group/deleted_service_group.php index 195abc534..a024a47f8 100644 --- a/htdocs/web_portal/views/service_group/deleted_service_group.php +++ b/htdocs/web_portal/views/service_group/deleted_service_group.php @@ -3,4 +3,4 @@ Service Group deleted.
    Go Home - \ No newline at end of file + diff --git a/htdocs/web_portal/views/service_group/deleted_service_group_properties.php b/htdocs/web_portal/views/service_group/deleted_service_group_properties.php index 287dfff32..e25f66d25 100644 --- a/htdocs/web_portal/views/service_group/deleted_service_group_properties.php +++ b/htdocs/web_portal/views/service_group/deleted_service_group_properties.php @@ -17,4 +17,4 @@ View service group

    - \ No newline at end of file + diff --git a/htdocs/web_portal/views/service_group/edit_service_group_property.php b/htdocs/web_portal/views/service_group/edit_service_group_property.php index af8702b34..5f6106bd1 100644 --- a/htdocs/web_portal/views/service_group/edit_service_group_property.php +++ b/htdocs/web_portal/views/service_group/edit_service_group_property.php @@ -21,4 +21,4 @@ - \ No newline at end of file + diff --git a/htdocs/web_portal/views/service_group/return_removed_se.php b/htdocs/web_portal/views/service_group/return_removed_se.php index d60de058b..6aade1f51 100644 --- a/htdocs/web_portal/views/service_group/return_removed_se.php +++ b/htdocs/web_portal/views/service_group/return_removed_se.php @@ -1,2 +1,2 @@ getId(); \ No newline at end of file +echo $params['se']->getId(); diff --git a/htdocs/web_portal/views/service_group/se_search.php b/htdocs/web_portal/views/service_group/se_search.php index f3ccad330..d3e613003 100644 --- a/htdocs/web_portal/views/service_group/se_search.php +++ b/htdocs/web_portal/views/service_group/se_search.php @@ -1,4 +1,4 @@ \ No newline at end of file +?> diff --git a/htdocs/web_portal/views/service_group/service_group_property_updated.php b/htdocs/web_portal/views/service_group/service_group_property_updated.php index ec462f00e..197cc1ab5 100644 --- a/htdocs/web_portal/views/service_group/service_group_property_updated.php +++ b/htdocs/web_portal/views/service_group/service_group_property_updated.php @@ -3,4 +3,4 @@ Service Group Property updated.
    View service group - \ No newline at end of file + diff --git a/htdocs/web_portal/views/service_group/submit_add_new_se_to_service_group.php b/htdocs/web_portal/views/service_group/submit_add_new_se_to_service_group.php index 9bf9d0d7a..871ecb057 100644 --- a/htdocs/web_portal/views/service_group/submit_add_new_se_to_service_group.php +++ b/htdocs/web_portal/views/service_group/submit_add_new_se_to_service_group.php @@ -3,4 +3,4 @@ New Service successfully created and added to service group .
    View service group - \ No newline at end of file + diff --git a/htdocs/web_portal/views/service_group/submit_add_service_group.php b/htdocs/web_portal/views/service_group/submit_add_service_group.php index 0607b00f8..2ae41ff91 100644 --- a/htdocs/web_portal/views/service_group/submit_add_service_group.php +++ b/htdocs/web_portal/views/service_group/submit_add_service_group.php @@ -3,4 +3,4 @@ New Service group getName()) ?> successfully created.
    View getName()) ?> - \ No newline at end of file + diff --git a/htdocs/web_portal/views/service_group/submit_edited_service_group.php b/htdocs/web_portal/views/service_group/submit_edited_service_group.php index 2276b3f11..2ef747926 100644 --- a/htdocs/web_portal/views/service_group/submit_edited_service_group.php +++ b/htdocs/web_portal/views/service_group/submit_edited_service_group.php @@ -3,4 +3,4 @@ Service group getName()) ?> successfully edited.
    View getName()) ?> - \ No newline at end of file + diff --git a/htdocs/web_portal/views/service_group/submit_service_group_ses.php b/htdocs/web_portal/views/service_group/submit_service_group_ses.php index c5bce2704..ff5f9409d 100644 --- a/htdocs/web_portal/views/service_group/submit_service_group_ses.php +++ b/htdocs/web_portal/views/service_group/submit_service_group_ses.php @@ -3,4 +3,4 @@ Services successfully added to service group.
    View service group - \ No newline at end of file + diff --git a/htdocs/web_portal/views/service_group/view_sgroup.php b/htdocs/web_portal/views/service_group/view_sgroup.php index 9a4961486..5112278c5 100644 --- a/htdocs/web_portal/views/service_group/view_sgroup.php +++ b/htdocs/web_portal/views/service_group/view_sgroup.php @@ -24,7 +24,7 @@ diff --git a/htdocs/web_portal/views/site/add_site_properties_confirmation.php b/htdocs/web_portal/views/site/add_site_properties_confirmation.php index b6e82d260..f0a42b79d 100644 --- a/htdocs/web_portal/views/site/add_site_properties_confirmation.php +++ b/htdocs/web_portal/views/site/add_site_properties_confirmation.php @@ -7,4 +7,4 @@

    Add Site Properties


    -
    \ No newline at end of file + diff --git a/htdocs/web_portal/views/site/add_site_property.php b/htdocs/web_portal/views/site/add_site_property.php index 1cfae18fc..055b9609e 100644 --- a/htdocs/web_portal/views/site/add_site_property.php +++ b/htdocs/web_portal/views/site/add_site_property.php @@ -19,4 +19,4 @@ - \ No newline at end of file + diff --git a/htdocs/web_portal/views/site/added_site_properties.php b/htdocs/web_portal/views/site/added_site_properties.php index bdf7af744..c3feb8c02 100644 --- a/htdocs/web_portal/views/site/added_site_properties.php +++ b/htdocs/web_portal/views/site/added_site_properties.php @@ -10,4 +10,4 @@
    View site - \ No newline at end of file + diff --git a/htdocs/web_portal/views/site/added_site_property.php b/htdocs/web_portal/views/site/added_site_property.php index ef1bda414..a3677f099 100644 --- a/htdocs/web_portal/views/site/added_site_property.php +++ b/htdocs/web_portal/views/site/added_site_property.php @@ -3,4 +3,4 @@ New site property successfully created.
    View site - \ No newline at end of file + diff --git a/htdocs/web_portal/views/site/cert_status_edited.php b/htdocs/web_portal/views/site/cert_status_edited.php index 545826e7f..006d29379 100644 --- a/htdocs/web_portal/views/site/cert_status_edited.php +++ b/htdocs/web_portal/views/site/cert_status_edited.php @@ -3,4 +3,4 @@ Certification status updated.
    View site - \ No newline at end of file + diff --git a/htdocs/web_portal/views/site/delete_site.php b/htdocs/web_portal/views/site/delete_site.php index 0c4f2d75f..ed078722a 100644 --- a/htdocs/web_portal/views/site/delete_site.php +++ b/htdocs/web_portal/views/site/delete_site.php @@ -37,4 +37,4 @@ - \ No newline at end of file + diff --git a/htdocs/web_portal/views/site/deleted_site.php b/htdocs/web_portal/views/site/deleted_site.php index 2fd602337..7398c7b3d 100644 --- a/htdocs/web_portal/views/site/deleted_site.php +++ b/htdocs/web_portal/views/site/deleted_site.php @@ -1,4 +1,4 @@

    Deletion Successful


    The site '' and any associated services have been successfully removed from GOCDB -
    \ No newline at end of file + diff --git a/htdocs/web_portal/views/site/deleted_site_properties.php b/htdocs/web_portal/views/site/deleted_site_properties.php index 8f68172f6..d9d6ebde4 100644 --- a/htdocs/web_portal/views/site/deleted_site_properties.php +++ b/htdocs/web_portal/views/site/deleted_site_properties.php @@ -17,4 +17,4 @@ View Site

    - \ No newline at end of file + diff --git a/htdocs/web_portal/views/site/edit_cert_status.php b/htdocs/web_portal/views/site/edit_cert_status.php index 2b9ebd162..09ef38a21 100644 --- a/htdocs/web_portal/views/site/edit_cert_status.php +++ b/htdocs/web_portal/views/site/edit_cert_status.php @@ -28,4 +28,4 @@ - \ No newline at end of file + diff --git a/htdocs/web_portal/views/site/edit_site_property.php b/htdocs/web_portal/views/site/edit_site_property.php index a5feb1e96..75f43f40c 100644 --- a/htdocs/web_portal/views/site/edit_site_property.php +++ b/htdocs/web_portal/views/site/edit_site_property.php @@ -21,4 +21,4 @@ - \ No newline at end of file + diff --git a/htdocs/web_portal/views/site/site_property_updated.php b/htdocs/web_portal/views/site/site_property_updated.php index 1d2511eee..7601d8e30 100644 --- a/htdocs/web_portal/views/site/site_property_updated.php +++ b/htdocs/web_portal/views/site/site_property_updated.php @@ -3,4 +3,4 @@ Site Property updated.
    View site - \ No newline at end of file + diff --git a/htdocs/web_portal/views/site/site_updated.php b/htdocs/web_portal/views/site/site_updated.php index c597f8166..d778b12a7 100644 --- a/htdocs/web_portal/views/site/site_updated.php +++ b/htdocs/web_portal/views/site/site_updated.php @@ -3,4 +3,4 @@ Site updated.
    View site - \ No newline at end of file + diff --git a/htdocs/web_portal/views/site/submit_new_site.php b/htdocs/web_portal/views/site/submit_new_site.php index 9cdf4062f..45cb5e38c 100644 --- a/htdocs/web_portal/views/site/submit_new_site.php +++ b/htdocs/web_portal/views/site/submit_new_site.php @@ -3,4 +3,4 @@ New Site successfully created.
    View new site - \ No newline at end of file + diff --git a/htdocs/web_portal/views/site/view_site.php b/htdocs/web_portal/views/site/view_site.php index 49ad64c31..6c0a5b24c 100644 --- a/htdocs/web_portal/views/site/view_site.php +++ b/htdocs/web_portal/views/site/view_site.php @@ -1,5 +1,6 @@ getId(); @@ -22,23 +23,23 @@ - +
    - + - +
    - +

    Edit @@ -53,7 +54,9 @@
    - Contact Info + + Contact Info + @@ -62,32 +65,37 @@ getEmail()) ?> - + + } else { + echo(getInfoMessage()); + } + ?> @@ -96,7 +104,9 @@ getCsirtEmail()) ?> - + @@ -106,7 +116,9 @@ getEmergencyEmail()) ?> - + @@ -116,14 +128,16 @@ getHelpdeskEmail()) ?> - + + + + + + +
    TelephonegetTelephone()); - } else + } else { echo(getInfoMessage()); + } ?>
    Emergency TelgetEmergencyTel()); - } else + } else { echo(getInfoMessage()); + } ?>
    CSIRT TelgetCsirtTel()); - } else - echo(getInfoMessage()) - ?>
    CSIRT E-Mail
    Notifications - Project Data + + Project Data + @@ -146,7 +162,10 @@ - + + @@ -155,29 +174,31 @@ getCertificationStatus()->getName()) ?>   - + Change - + $sharedWithParent) { - if ($sharedWithParent) { - $scopeString .= $scopeName; - } else { - $scopeString .= $scopeName . '(x)'; - } - if (++$count != $numScopes) { - $scopeString .= ", "; - } - } - ?> + $count = 0; + $numScopes = sizeof($params['Scopes']); + $scopeString = ''; + foreach ($params['Scopes'] as $scopeName => $sharedWithParent) { + if ($sharedWithParent) { + $scopeString .= $scopeName; + } else { + $scopeString .= $scopeName . '(x)'; + } + if (++$count != $numScopes) { + $scopeString .= ", "; + } + } + ?> + ?> -
    InfrastructuregetInfrastructure()->getName()) ?>Infrastructure + getInfrastructure()->getName()) ?> +
    Certification Status
    @@ -197,7 +218,9 @@
    - Networking + + Networking + @@ -207,7 +230,9 @@ getHomeUrl()) ?> - + @@ -216,8 +241,9 @@ getGiisUrl()); - } else + } else { echo(getInfoMessage()); + } ?> @@ -227,8 +253,9 @@ getIpRange()); - } else + } else { echo(getInfoMessage()); + } ?> @@ -238,8 +265,9 @@ getIpV6Range()); - } else + } else { echo(getInfoMessage()); + } ?> @@ -247,10 +275,11 @@ @@ -259,7 +288,9 @@
    - Location + + Location +
    Domain getDomain()); - } else - echo(getInfoMessage()); + if ($showPD) { + xecho($site->getDomain()); + } else { + echo(getInfoMessage()); + } ?>
    @@ -353,9 +384,9 @@ + $se = $serviceAndScopes['Service']; + $scopes = $serviceAndScopes['Scopes']; + ?> @@ -403,22 +432,22 @@ $numScopes = sizeof($scopes); $scopeString = ''; foreach ($scopes as $scopeName => $sharedWithParent) { - if ($sharedWithParent) { - $scopeString .= $scopeName; - } else { - $scopeString .= $scopeName . '(x)'; - } - if (++$count != $numScopes) { - $scopeString .= ", "; - } + if ($sharedWithParent) { + $scopeString .= $scopeName; + } else { + $scopeString .= $scopeName . '(x)'; + } + if (++$count != $numScopes) { + $scopeString .= ", "; + } } ?> + } // End of the foreach loop iterating over ServicesAndScopes + ?>
    @@ -363,37 +394,35 @@ - + getProduction()) { - case true: - ?> - - - - '; + break; + case false: + echo ''; + break; } ?> getMonitored()) { - case true: - ?> - - - - '; + break; + case false: + echo ''; + break; } ?>
    @@ -427,21 +456,30 @@ - - - Add Service + + + Add Service
    -
    - Users (Click on name to manage roles) + if ($showPD) { + ?> + + Users (Click on name to manage roles) + @@ -453,12 +491,16 @@ + ?> -
    @@ -469,20 +511,20 @@ ?>
    -
    @@ -507,28 +549,37 @@
    - + getDescription()) ?> getStartDate()->format('Y-m-d H:i'/*$dt::DATE_FORMAT*/)) ?> getEndDate()->format('Y-m-d H:i'/*$dt::DATE_FORMAT*/)) ?>
    - + - - + + Add Downtime @@ -543,10 +594,11 @@ ?> - +
    - Credentials authorised to use the GOCDB read and write APIs (Only shown if you have the relevant permissions) + Credentials authorised to use the GOCDB read and write APIs + (Only shown if you have the relevant permissions) @@ -555,8 +607,9 @@ - - + + + @@ -573,7 +626,7 @@ // delete the credential $disableDelete = false; } - ?> + ?> +
    Type Identifier UserAPI WriteEditLast UsedWriteEdit Delete
    getType())?> @@ -587,34 +640,56 @@ $disableDelete = false; if ($APIAuthEnt->getUser() != null) { // Credentials added prior to 5.8 have no owning user - echo "getUser()->getId(), "\" "; + echo "getUser()->getId(), + "\" "; echo "title=\"", $APIAuthEnt->getUser()->getFullname(), "\">"; - echo substr($APIAuthEnt->getUser()->getSurname(),0,10); + echo substr($APIAuthEnt->getUser()->getSurname(), 0, 10); echo ""; } ?> + getLastUseTime(); + if ($useTime == null) { + $titleStr = 'Created/Renewed ' . $APIAuthEnt->getLastRenewTime()->format('d-m-Y H:iTP'); + echo '
    Unused
    '; + } else { + $titleStr = 'Last used ' . $useTime->format('d-m-Y H:iTP'); + echo '
    ' . $useTime->format('d-m-y') . '
    '; + } + ?> +
    getAllowAPIWrite())) { - echo '"'.\GocContextPath::getPath().'img/tick.png"'; + echo '"' . \GocContextPath::getPath() . 'img/tick.png"'; + echo 'title="API write enabled"'; } else { - echo '"'.\GocContextPath::getPath().'img/cross.png"'; + echo '"' . \GocContextPath::getPath() . 'img/cross.png"'; + echo 'title="API write disabled"'; } ?> /> - -
    -
    - +
    - -
    -
    @@ -624,11 +699,17 @@
    - + - - + + Add API credential diff --git a/htdocs/web_portal/views/user/deleted_user.php b/htdocs/web_portal/views/user/deleted_user.php index e55bcc510..cfcfbdb30 100644 --- a/htdocs/web_portal/views/user/deleted_user.php +++ b/htdocs/web_portal/views/user/deleted_user.php @@ -3,4 +3,4 @@ User deleted.
    Go Home -
    \ No newline at end of file + diff --git a/htdocs/web_portal/views/user/deleted_user_identifier.php b/htdocs/web_portal/views/user/deleted_user_identifier.php index 34f79f761..a6a5141f3 100644 --- a/htdocs/web_portal/views/user/deleted_user_identifier.php +++ b/htdocs/web_portal/views/user/deleted_user_identifier.php @@ -4,4 +4,4 @@ View user - \ No newline at end of file + diff --git a/htdocs/web_portal/views/user/link_identity.php b/htdocs/web_portal/views/user/link_identity.php index 1ffb3c5e8..ff5513281 100644 --- a/htdocs/web_portal/views/user/link_identity.php +++ b/htdocs/web_portal/views/user/link_identity.php @@ -1,59 +1,24 @@
    -

    Link Identity or Recover an Account

    - -
    - +

    Link Identifier or Recover an Account

    -

    What is identity linking?

    -
      -
    • - You can use this process to add your current authentication method as a way to log in to an existing account. -
    • -
    • - This allows access to a single account through two or more identifiers. -
    • -
    • - You must have access to the email address associated with the account being linked. -
    • -
    • - Your current authentication type must be different to any authentication types already associated - with the account being linked. -
    • -
    - -

    What is account recovery?

    -
      -
    • - If your identifier has changed, you can use this process to update it and regain control of your old account. -
    • -
    • - You must have access to the email address associated with your old account. -
    • -
    • - Your current authentication type must be the same as the authentication type you enter for your old account. -
    • + This page allows you to either add a new identifier to an exisiting GOCDB + account, or recover a GOCDB account if your identifier has changed. You + must have access to the email address associated with that GOCDB account. + You must be authenticated with the new identifier.
    -
    -
    - +
    Your current ID string (e.g. certificate DN) is: - -
    - +
    +
    Your current authentication type is: - - -
    -
    - -

    Details of account to be linked or recovered

    +
    -
    +

    Details of account to be linked to or recovered

    @@ -104,8 +69,6 @@ class="form-control"
    -
    -
    \ No newline at end of file +
    diff --git a/htdocs/web_portal/views/user/link_identity_rejected.php b/htdocs/web_portal/views/user/link_identity_rejected.php index 471632323..58d7995fb 100644 --- a/htdocs/web_portal/views/user/link_identity_rejected.php +++ b/htdocs/web_portal/views/user/link_identity_rejected.php @@ -17,4 +17,4 @@ please unlink all other identifiers first.

    If you wish to add new identifiers to this account, please access GOCDB while authenticated with the new identifier.

    -
    \ No newline at end of file +
    diff --git a/htdocs/web_portal/views/user/linked_identity.php b/htdocs/web_portal/views/user/linked_identity.php index 34a0ce3e7..598ef24e0 100644 --- a/htdocs/web_portal/views/user/linked_identity.php +++ b/htdocs/web_portal/views/user/linked_identity.php @@ -2,4 +2,4 @@

    Success

    Your identifier has been successfully
    - \ No newline at end of file + diff --git a/htdocs/web_portal/views/user/registered.php b/htdocs/web_portal/views/user/registered.php index a23ab75e4..8cd1cfd9b 100644 --- a/htdocs/web_portal/views/user/registered.php +++ b/htdocs/web_portal/views/user/registered.php @@ -6,4 +6,4 @@ New user registered.
    View user - \ No newline at end of file + diff --git a/htdocs/web_portal/views/user/user_updated.php b/htdocs/web_portal/views/user/user_updated.php index 5da2449be..56dc7e87e 100644 --- a/htdocs/web_portal/views/user/user_updated.php +++ b/htdocs/web_portal/views/user/user_updated.php @@ -3,4 +3,4 @@ User updated.
    View user - \ No newline at end of file + diff --git a/htdocs/web_portal/views/user/view_user.php b/htdocs/web_portal/views/user/view_user.php index cd5a6d64e..866ab9637 100644 --- a/htdocs/web_portal/views/user/view_user.php +++ b/htdocs/web_portal/views/user/view_user.php @@ -20,8 +20,7 @@ if ($params['ShowEdit']) {?> '; @@ -74,7 +72,9 @@ - + isAdmin(); + ?>
    @@ -129,6 +129,21 @@
    Last Logged In + getLastLoginDate()) { + xecho( + $params['user']->getLastLoginDate() + ->format('Y-m-d H:i:s') + ); + } + ?> +
    diff --git a/lib/Authentication/_autoload.php b/lib/Authentication/_autoload.php index bed78a5a8..1e1ca4e7a 100644 --- a/lib/Authentication/_autoload.php +++ b/lib/Authentication/_autoload.php @@ -73,4 +73,3 @@ function securityLoader($className){ spl_autoload_register(__NAMESPACE__ .'\securityLoader', false); - diff --git a/lib/DAOs/AbstractDAO.php b/lib/DAOs/AbstractDAO.php index b80927402..894585518 100644 --- a/lib/DAOs/AbstractDAO.php +++ b/lib/DAOs/AbstractDAO.php @@ -25,4 +25,4 @@ public function setEntityManager(\Doctrine\ORM\EntityManager $em){ public function getEntityManager(){ return $this->em; } -} \ No newline at end of file +} diff --git a/lib/DAOs/NGIDAO.php b/lib/DAOs/NGIDAO.php index 168784e26..ee87cb3e6 100644 --- a/lib/DAOs/NGIDAO.php +++ b/lib/DAOs/NGIDAO.php @@ -51,4 +51,4 @@ public function addNGIToArchive(\NGI $ngi, \User $user){ $this->em->persist($archievedNgi); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/entities/APIAuthentication.php b/lib/Doctrine/entities/APIAuthentication.php index e4288f67c..61a4129bc 100644 --- a/lib/Doctrine/entities/APIAuthentication.php +++ b/lib/Doctrine/entities/APIAuthentication.php @@ -1,4 +1,5 @@ setLastRenewTime(); } /** * Get PK of Authentication entity * @return int */ - public function getId() { + public function getId() + { return $this->id; } @@ -93,7 +106,8 @@ public function getId() { * Get the authentication enties parent site * @return \Site */ - public function getParentSite() { + public function getParentSite() + { return $this->parentSite; } @@ -101,7 +115,8 @@ public function getParentSite() { * Get they autentication type of this entity * @return string */ - public function getType() { + public function getType() + { return $this->type; } @@ -109,35 +124,40 @@ public function getType() { * Get the unique identifier for this autnentication entity. * @return string */ - public function getIdentifier() { + public function getIdentifier() + { return $this->identifier; } /** * @return \User */ - public function getUser() { + public function getUser() + { return $this->user; } /** * @return bool $allowAPIWrite */ - public function getAllowAPIWrite () { + public function getAllowAPIWrite() + { return $this->allowAPIWrite; } /** * @return \DateTime */ - public function getLastUseTime () { + public function getLastUseTime() + { return $this->lastUseTime; } /** * @return \DateTime $time */ - protected function getLastRenewTime() { + public function getLastRenewTime() + { return $this->lastRenewTime; } @@ -145,7 +165,8 @@ protected function getLastRenewTime() { * Set the type of this authentication entity * @param string $name */ - public function setType($type) { + public function setType($type) + { $this->type = $type; } @@ -153,14 +174,16 @@ public function setType($type) { * Set the unique identifier of this authentication entity. * @param string $identifier */ - public function setIdentifier($identifier) { + public function setIdentifier($identifier) + { $this->identifier = $identifier; } /** * @param \DateTime $time if null, current UTC time is set */ - public function setLastUseTime (\DateTime $time = null) { + public function setLastUseTime(\DateTime $time = null) + { $useTime = $time; @@ -174,7 +197,8 @@ public function setLastUseTime (\DateTime $time = null) { /** * @param \DateTime $time if null, current UTC time is set */ - public function setLastRenewTime(\DateTime $time = null) { + public function setLastRenewTime(\DateTime $time = null) + { $renewTime = $time; @@ -189,9 +213,10 @@ public function setLastRenewTime(\DateTime $time = null) { * * @param bool $allowAPIWrite */ - public function setAllowAPIWrite ($allowWrite) { + public function setAllowAPIWrite($allowWrite) + { if (!is_bool($allowWrite)) { - throw new LogicException("Expected bool, received".gettype($allowWrite)); + throw new LogicException("Expected bool, received" . gettype($allowWrite)); } $this->allowAPIWrite = $allowWrite; } @@ -207,13 +232,15 @@ public function setAllowAPIWrite ($allowWrite) { * * @param \Site $site */ - public function _setParentSite(\Site $site){ + public function _setParentSite(\Site $site) + { $this->parentSite = $site; } /** * @param \User $user */ - public function _setUser(\User $user) { + public function _setUser(\User $user) + { $this->user = $user; } - } +} diff --git a/lib/Doctrine/entities/ServiceType.php b/lib/Doctrine/entities/ServiceType.php index 2e3d231c1..a3ac63567 100644 --- a/lib/Doctrine/entities/ServiceType.php +++ b/lib/Doctrine/entities/ServiceType.php @@ -24,8 +24,8 @@ * * @Entity @Table(name="ServiceTypes", options={"collate"="utf8mb4_bin", "charset"="utf8mb4"}) */ -class ServiceType { - +class ServiceType +{ /** @Id @Column(type="integer") @GeneratedValue */ protected $id; @@ -38,14 +38,24 @@ class ServiceType { /** @OneToMany(targetEntity="Service", mappedBy="serviceType") */ protected $services = null; - public function __construct() { + /** + * An instance of a Service of this ServiceType may + * unmonitored while in production. + * @Column(type="boolean", options={"default":FALSE}) + */ + protected $monitoringException; + + public function __construct() + { $this->services = new ArrayCollection(); + $this->monitoringException = false; } /** * @return int The PK of this entity or null if not persisted */ - public function getId() { + public function getId() + { return $this->id; } @@ -53,7 +63,8 @@ public function getId() { * Get the unique name of this service type. * @return string */ - public function getName() { + public function getName() + { return $this->name; } @@ -61,7 +72,8 @@ public function getName() { * Get the human readable description of this service type. * @return string or null */ - public function getDescription() { + public function getDescription() + { return $this->description; } @@ -69,7 +81,8 @@ public function getDescription() { * Set the unique name of this service type. Required. * @param string $name */ - public function setName($name) { + public function setName($name) + { $this->name = $name; } @@ -77,7 +90,8 @@ public function setName($name) { * Set the human readable description of this service type. * @param string $description */ - public function setDescription($description) { + public function setDescription($description) + { $this->description = $description; } @@ -85,7 +99,8 @@ public function setDescription($description) { * Get all the {@see Service}s that are linked to this service type. * @return ArrayCollection */ - public function getServices() { + public function getServices() + { return $this->services; } @@ -95,17 +110,37 @@ public function getServices() { * to establish the join on both sides of the relationship. * @param \Service $service */ - public function addService($service) { + public function addService($service) + { $this->services[] = $service; $service->setServiceType($this); } + /** + * Add an exception where an instance of this ServiceType is allowed + * to be unmonitored when in production with a specific Scope. + * Return value is the existing boolean state + */ + public function setAllowMonitoringException($state) + { + $oldState = $this->getAllowMonitoringException(); + $this->monitoringException = $state; + return $oldState; + } + /** + * Check if a monitoring exception is allowed within the given scope. + */ + public function getAllowMonitoringException() + { + return $this->monitoringException; + } + /** * Gets the name of this service type. * @return string */ - public function __toString() { + public function __toString() + { return $this->getName(); } - } diff --git a/lib/Gocdb_Services/CertificationStatus.php b/lib/Gocdb_Services/CertificationStatus.php index 25252a6a9..0ad274572 100644 --- a/lib/Gocdb_Services/CertificationStatus.php +++ b/lib/Gocdb_Services/CertificationStatus.php @@ -160,4 +160,4 @@ public function isChangeValid(\Site $site, \CertificationStatus $newCertStatus) } } } -?> \ No newline at end of file +?> diff --git a/lib/Gocdb_Services/Config.php b/lib/Gocdb_Services/Config.php index b7bd22328..59576f417 100644 --- a/lib/Gocdb_Services/Config.php +++ b/lib/Gocdb_Services/Config.php @@ -157,7 +157,6 @@ private function readLocalInfoXML($path, $url = null) if (!$base) { $this->throwXmlErrors('Failed to load configuration file ' . $path); } - // Search the input XML for a 'local_info' section that does NOT have a url attribute // specified. This is the default spec. $unqualified = $base->xpath("//local_info[not(@url)]"); @@ -401,8 +400,9 @@ public function GetPortalURL() */ public function isRestrictPDByRole($forceStrict = false) { - if ($forceStrict === true) + if ($forceStrict === true) { return true; + } $localInfo = $this->GetLocalInfoXML(); $value = $localInfo->restrict_personal_data; @@ -432,7 +432,18 @@ public function getServerBaseUrl() $url = $localInfo->server_base_url; return strval($url); } + /** + * Convenience function to return the 3 configuration URLs + */ + public function getURLs() + { + $localInfo = $this->GetLocalInfoXML(); + $serverBaseUrl = $localInfo->server_base_url; + $webPortalUrl = $localInfo->web_portal_url; + $piUrl = $localInfo->pi_url; + return array($serverBaseUrl, $webPortalUrl, $piUrl); + } /** * The write API documentation URL as recorded in local_info.xml. * This URL is given to users of the write API in error messages @@ -552,7 +563,7 @@ public function getEmailFrom() public function getEmailTo() { - $emailTo = $this->GetlocalInfoXML()->email_to; + $emailTo = $this->GetLocalInfoXML()->email_to; return $emailTo; } diff --git a/lib/Gocdb_Services/ExtensionsService.php b/lib/Gocdb_Services/ExtensionsService.php index 7930a8d0d..c1f05643a 100644 --- a/lib/Gocdb_Services/ExtensionsService.php +++ b/lib/Gocdb_Services/ExtensionsService.php @@ -58,4 +58,4 @@ public function getServiceGroupExtensionsKeyNames() { return $qb->getQuery()->execute(); } -} \ No newline at end of file +} diff --git a/lib/Gocdb_Services/PI/GetCertStatusChanges.php b/lib/Gocdb_Services/PI/GetCertStatusChanges.php index 70a25c889..4835c0644 100644 --- a/lib/Gocdb_Services/PI/GetCertStatusChanges.php +++ b/lib/Gocdb_Services/PI/GetCertStatusChanges.php @@ -354,4 +354,4 @@ public function getPostExecutionPageInfo(){ $pageInfo['count'] = $this->resultSetSize; return $pageInfo; } -} \ No newline at end of file +} diff --git a/lib/Gocdb_Services/PI/GetCertStatusDate.php b/lib/Gocdb_Services/PI/GetCertStatusDate.php index ae3ad157b..e91f7c6cb 100644 --- a/lib/Gocdb_Services/PI/GetCertStatusDate.php +++ b/lib/Gocdb_Services/PI/GetCertStatusDate.php @@ -345,4 +345,4 @@ public function getPostExecutionPageInfo(){ $pageInfo['count'] = $this->resultSetSize; return $pageInfo; } -} \ No newline at end of file +} diff --git a/lib/Gocdb_Services/PI/GetNGIContacts.php b/lib/Gocdb_Services/PI/GetNGIContacts.php index 254ac19d1..514eec313 100644 --- a/lib/Gocdb_Services/PI/GetNGIContacts.php +++ b/lib/Gocdb_Services/PI/GetNGIContacts.php @@ -362,4 +362,4 @@ public function getPostExecutionPageInfo(){ $pageInfo['count'] = $this->resultSetSize; return $pageInfo; } -} \ No newline at end of file +} diff --git a/lib/Gocdb_Services/PI/GetNGIList.php b/lib/Gocdb_Services/PI/GetNGIList.php index 48cc2a768..92271e6e0 100644 --- a/lib/Gocdb_Services/PI/GetNGIList.php +++ b/lib/Gocdb_Services/PI/GetNGIList.php @@ -233,4 +233,4 @@ private function getXML(){ }*/ -} \ No newline at end of file +} diff --git a/lib/Gocdb_Services/PI/GetProjectContacts.php b/lib/Gocdb_Services/PI/GetProjectContacts.php index 56c5b017c..181eaf2b5 100644 --- a/lib/Gocdb_Services/PI/GetProjectContacts.php +++ b/lib/Gocdb_Services/PI/GetProjectContacts.php @@ -342,4 +342,4 @@ public function getPostExecutionPageInfo(){ $pageInfo['count'] = $this->resultSetSize; return $pageInfo; } -} \ No newline at end of file +} diff --git a/lib/Gocdb_Services/PI/GetServiceGroupRole.php b/lib/Gocdb_Services/PI/GetServiceGroupRole.php index f8b05f1be..03d4a5bff 100644 --- a/lib/Gocdb_Services/PI/GetServiceGroupRole.php +++ b/lib/Gocdb_Services/PI/GetServiceGroupRole.php @@ -377,4 +377,4 @@ public function getPostExecutionPageInfo(){ $pageInfo['count'] = $this->resultSetSize; return $pageInfo; } -} \ No newline at end of file +} diff --git a/lib/Gocdb_Services/PI/GetServiceTypes.php b/lib/Gocdb_Services/PI/GetServiceTypes.php index 5ff72e1ad..3588ea738 100644 --- a/lib/Gocdb_Services/PI/GetServiceTypes.php +++ b/lib/Gocdb_Services/PI/GetServiceTypes.php @@ -180,4 +180,4 @@ private function getXML(){ return $xmlString; } -} \ No newline at end of file +} diff --git a/lib/Gocdb_Services/PI/GetSiteContacts.php b/lib/Gocdb_Services/PI/GetSiteContacts.php index f91e290d1..c6af53fc5 100644 --- a/lib/Gocdb_Services/PI/GetSiteContacts.php +++ b/lib/Gocdb_Services/PI/GetSiteContacts.php @@ -390,4 +390,4 @@ public function getPostExecutionPageInfo(){ $pageInfo['count'] = $this->resultSetSize; return $pageInfo; } -} \ No newline at end of file +} diff --git a/lib/Gocdb_Services/PI/GetSiteSecurityInfo.php b/lib/Gocdb_Services/PI/GetSiteSecurityInfo.php index ac835bca2..73bc69d6b 100644 --- a/lib/Gocdb_Services/PI/GetSiteSecurityInfo.php +++ b/lib/Gocdb_Services/PI/GetSiteSecurityInfo.php @@ -353,4 +353,4 @@ public function getPostExecutionPageInfo(){ $pageInfo['count'] = $this->resultSetSize; return $pageInfo; } -} \ No newline at end of file +} diff --git a/lib/Gocdb_Services/PI/GetSubGridList.php b/lib/Gocdb_Services/PI/GetSubGridList.php index 083cedf55..ef2bac31d 100644 --- a/lib/Gocdb_Services/PI/GetSubGridList.php +++ b/lib/Gocdb_Services/PI/GetSubGridList.php @@ -175,4 +175,4 @@ private function getXML(){ $xmlString = $dom->saveXML (); return $xmlString; } -} \ No newline at end of file +} diff --git a/lib/Gocdb_Services/PI/IPIQueryPageable.php b/lib/Gocdb_Services/PI/IPIQueryPageable.php index 7d2d0471f..89d56d6b3 100644 --- a/lib/Gocdb_Services/PI/IPIQueryPageable.php +++ b/lib/Gocdb_Services/PI/IPIQueryPageable.php @@ -56,4 +56,4 @@ public function setPageSize($pageSize); */ public function getPostExecutionPageInfo(); -} \ No newline at end of file +} diff --git a/lib/Gocdb_Services/PI/QueryBuilders/ExtensionsParser.php b/lib/Gocdb_Services/PI/QueryBuilders/ExtensionsParser.php index 7b4e10c2b..1637694b7 100644 --- a/lib/Gocdb_Services/PI/QueryBuilders/ExtensionsParser.php +++ b/lib/Gocdb_Services/PI/QueryBuilders/ExtensionsParser.php @@ -161,4 +161,4 @@ private function checkLimit($parsedQueries){ } } -} \ No newline at end of file +} diff --git a/lib/Gocdb_Services/Project.php b/lib/Gocdb_Services/Project.php index 4dea41209..61e55ea29 100644 --- a/lib/Gocdb_Services/Project.php +++ b/lib/Gocdb_Services/Project.php @@ -468,5 +468,3 @@ private function validate($projectData) { } } } - - diff --git a/lib/Gocdb_Services/Scope.php b/lib/Gocdb_Services/Scope.php index 84eafd766..40ddca0ed 100644 --- a/lib/Gocdb_Services/Scope.php +++ b/lib/Gocdb_Services/Scope.php @@ -545,4 +545,4 @@ private function validate($scopeData, $scopeIsNew, $oldScopeName = '') { } } -} \ No newline at end of file +} diff --git a/lib/Gocdb_Services/Search.php b/lib/Gocdb_Services/Search.php index 5103a99b3..6b5b42106 100644 --- a/lib/Gocdb_Services/Search.php +++ b/lib/Gocdb_Services/Search.php @@ -101,4 +101,21 @@ public function getNgis($searchTerm) { return $ngis; } -} \ No newline at end of file + /** + * When the user is admin, it retrieves the matching identifiers. + */ + public function getSiteIdentifiers($user, $searchTerm) + { + if ($user->isAdmin()) { + $dql = "SELECT ui FROM APIAuthentication ui " + . " WHERE UPPER(ui.identifier) " + . " LIKE UPPER(concat(concat('%', :searchTerm), '%'))"; + $siteIdentifiers = $this->em + ->createQuery($dql) + ->setParameter(":searchTerm", $searchTerm) + ->getResult(); + + return $siteIdentifiers; + } + } +} diff --git a/lib/Gocdb_Services/SecurityContextSource.php b/lib/Gocdb_Services/SecurityContextSource.php index c2dc0a284..618fa8404 100644 --- a/lib/Gocdb_Services/SecurityContextSource.php +++ b/lib/Gocdb_Services/SecurityContextSource.php @@ -20,4 +20,3 @@ public static function getContext(){ return self::$context; } } - diff --git a/lib/Gocdb_Services/ServiceService.php b/lib/Gocdb_Services/ServiceService.php index 52f1029cf..451938274 100644 --- a/lib/Gocdb_Services/ServiceService.php +++ b/lib/Gocdb_Services/ServiceService.php @@ -19,6 +19,9 @@ require_once __DIR__ . '/RoleActionAuthorisationService.php'; require_once __DIR__ . '/Config.php'; +use org\gocdb\services\Config; +use org\gocdb\services\Validate; + /** * GOCDB Stateless service facade (business routines) for Service objects. * The public API methods are atomic and transactional. @@ -30,13 +33,17 @@ * @author George Ryall * @author James McCarthy */ -class ServiceService extends AbstractEntityService { - private $roleActionAuthorisationService; +class ServiceService extends AbstractEntityService +{ + // roleActionAuthorisationService + private $roleAAS; private $configService; private $scopeService; - function __construct(/* $roleActionAuthorisationService */) { - parent::__construct (); - // $this->roleActionAuthorisationService = $roleActionAuthorisationService; + + public function __construct(/* $roleAAS */) + { + parent::__construct(); + // $this->roleAAS = $roleActionAuthorisationService; $this->configService = \Factory::getConfigService(); } @@ -44,10 +51,11 @@ function __construct(/* $roleActionAuthorisationService */) { * Set class dependency (REQUIRED). * * @todo Mandatory objects should be injected via constructor. - * @param \org\gocdb\services\RoleActionAuthorisationService $roleActionAuthService + * @param \org\gocdb\services\RoleActionAuthorisationService $newService */ - public function setRoleActionAuthorisationService(RoleActionAuthorisationService $roleActionAuthService) { - $this->roleActionAuthorisationService = $roleActionAuthService; + public function setRoleActionAuthorisationService(RoleActionAuthorisationService $newService) + { + $this->roleAAS = $newService; } /** @@ -56,7 +64,8 @@ public function setRoleActionAuthorisationService(RoleActionAuthorisationService * @todo Mandatory objects should be injected via constructor. * @param \org\gocdb\services\Scope $scopeService */ - public function setScopeService(Scope $scopeService) { + public function setScopeService(Scope $scopeService) + { $this->scopeService = $scopeService; } @@ -66,19 +75,21 @@ public function setScopeService(Scope $scopeService) { * @param int $id the service ID * @return \Service a service object */ - public function getService($id) { + public function getService($id) + { $dql = "SELECT s FROM Service s WHERE s.id = :id"; - $service = $this->em->createQuery ( $dql )->setParameter ( 'id', $id )->getSingleResult (); + $service = $this->em->createQuery($dql)->setParameter('id', $id)->getSingleResult(); return $service; } - public function getEndpoint($id) { + public function getEndpoint($id) + { $dql = "SELECT el FROM EndpointLocation el WHERE el.id = :id"; - $endpoint = $this->em->createQuery ( $dql )->setParameter ( 'id', $id )->getSingleResult (); + $endpoint = $this->em->createQuery($dql)->setParameter('id', $id)->getSingleResult(); return $endpoint; } @@ -103,11 +114,41 @@ public function getEndpoint($id) { * false to return a hydrated Doctine object graph * @return type array graph or object graph of {@link \Service} entities */ - public function getSes($term = null, $serviceType = null, $production = null, $monitored = null, $scope = null, $ngi = null, $certStatus = null, $showClosed = null, $servKeyNames = null, $servKeyValues = null, $startRecord = null, $endRecord = null, $returnArray = false) { + public function getSes( + $term = null, + $serviceType = null, + $production = null, + $monitored = null, + $scope = null, + $ngi = null, + $certStatus = null, + $showClosed = null, + $servKeyNames = null, + $servKeyValues = null, + $startRecord = null, + $endRecord = null, + $returnArray = false + ) { // this method needs to be dropped in favor of getServicesFilterByParams, // but it is still needed when adding services to serviceGroups. - return $this->getServicesHelper ( $term, $serviceType, $production, $monitored, $scope, $ngi, $certStatus, $showClosed, $servKeyNames, $servKeyValues, $startRecord, $endRecord, $returnArray, false ); + + return $this->getServicesHelper( + $term, + $serviceType, + $production, + $monitored, + $scope, + $ngi, + $certStatus, + $showClosed, + $servKeyNames, + $servKeyValues, + $startRecord, + $endRecord, + $returnArray, + false + ); } /** @@ -115,65 +156,131 @@ public function getSes($term = null, $serviceType = null, $production = null, $m * search parameters. * {@link getSes} */ - public function getSesCount($term = null, $serviceType = null, $production = null, $monitored = null, $scope = null, $ngi = null, $certStatus = null, $showClosed = null, $servKeyNames = null, $servKeyValues = null, $startRecord = null, $endRecord = null, $returnArray = false) { - return $this->getServicesHelper ( $term, $serviceType, $production, $monitored, $scope, $ngi, $certStatus, $showClosed, $servKeyNames, $servKeyValues, $startRecord, $endRecord, $returnArray, true ); + + + public function getSesCount( + $term = null, + $serviceType = null, + $production = null, + $monitored = null, + $scope = null, + $ngi = null, + $certStatus = null, + $showClosed = null, + $servKeyNames = null, + $servKeyValues = null, + $startRecord = null, + $endRecord = null, + $returnArray = false + ) { + + return $this->getServicesHelper( + $term, + $serviceType, + $production, + $monitored, + $scope, + $ngi, + $certStatus, + $showClosed, + $servKeyNames, + $servKeyValues, + $startRecord, + $endRecord, + $returnArray, + true + ); } - private function getServicesHelper($term = null, $serviceType = null, $production = null, $monitored = null, $scope = null, $ngi = null, $certStatus = null, $showClosed = null, $servKeyNames = null, $servKeyValues = null, $startRecord = null, $endRecord = null, $returnArray = false, $count = false) { + private function getServicesHelper( + $term = null, + $serviceType = null, + $production = null, + $monitored = null, + $scope = null, + $ngi = null, + $certStatus = null, + $showClosed = null, + $servKeyNames = null, + $servKeyValues = null, + $startRecord = null, + $endRecord = null, + $returnArray = false, + $count = false + ) { // this method can be dropped when getSes and getSesCount have been dropped. if ($production == "TRUE") { $production = "1"; - } else if ($production == "FALSE") { + } elseif ($production == "FALSE") { $production = "0"; } if ($monitored == "TRUE") { $monitored = "1"; - } else if ($monitored == "FALSE") { + } elseif ($monitored == "FALSE") { $monitored = "0"; } - $qb = $this->em->createQueryBuilder (); + $qbr = $this->em->createQueryBuilder(); if ($count) { - $qb->select ( 'count(DISTINCT se)' ); + $qbr->select('count(DISTINCT se)'); } else { - $qb->select ( 'DISTINCT se', 'si', 'st', 'cs', 'n' ); + $qbr->select('DISTINCT se', 'si', 'st', 'cs', 'n'); } - $qb->from ( 'Service', 'se' )->leftjoin ( 'se.serviceType', 'st' )->leftjoin ( 'se.scopes', 's' )->leftjoin ( 'se.parentSite', 'si' )->leftjoin ( 'si.certificationStatus', 'cs' )->leftjoin ( 'si.ngi', 'n' )->orderBy ( 'se.hostName' ); + $qbr->from('Service', 'se') + ->leftjoin('se.serviceType', 'st') + ->leftjoin('se.scopes', 's') + ->leftjoin('se.parentSite', 'si') + ->leftjoin('si.certificationStatus', 'cs') + ->leftjoin('si.ngi', 'n') + ->orderBy('se.hostName'); // For use with search function, convert all terms to upper and do a like query + if ($term != null && $term != '%%') { - $qb->andWhere ( $qb->expr ()->orX ( $qb->expr ()->like ( $qb->expr ()->upper ( 'se.hostName' ), ':term' ), $qb->expr ()->like ( $qb->expr ()->upper ( 'se.description' ), ':term' ) ) )->setParameter ( ':term', strtoupper ( $term ) ); + $qbr->andWhere($qbr->expr()->orX( + $qbr->expr()->like($qbr->expr()->upper('se.hostName'), ':term'), + $qbr->expr()->like($qbr->expr()->upper('se.description'), ':term') + ))->setParameter(':term', strtoupper($term)); } if ($serviceType != null && $serviceType != '%%') { - $qb->andWhere ( $qb->expr ()->like ( $qb->expr ()->upper ( 'st.name' ), ':serviceType' ) )->setParameter ( ':serviceType', strtoupper ( $serviceType ) ); + $qbr->andWhere($qbr->expr()->like( + $qbr->expr()->upper('st.name'), + ':serviceType' + ))->setParameter(':serviceType', strtoupper($serviceType)); } if ($production != null && $production != '%%') { - $qb->andWhere ( $qb->expr ()->like ( $qb->expr ()->upper ( 'se.production' ), ':production' ) )->setParameter ( ':production', $production ); + $qbr->andWhere($qbr->expr()->like($qbr->expr()->upper('se.production'), ':production')) + ->setParameter(':production', $production); } if ($monitored != null && $monitored != '%%') { - $qb->andWhere ( $qb->expr ()->like ( $qb->expr ()->upper ( 'se.monitored' ), ':monitored' ) )->setParameter ( ':monitored', $monitored ); + $qbr->andWhere($qbr->expr()->like($qbr->expr()->upper('se.monitored'), ':monitored')) + ->setParameter(':monitored', $monitored); } if ($scope != null && $scope != '%%') { - $qb->andWhere ( $qb->expr ()->like ( 's.name', ':scope' ) )->setParameter ( ':scope', $scope ); + $qbr->andWhere($qbr->expr()->like('s.name', ':scope')) + ->setParameter(':scope', $scope); } if ($certStatus != null && $certStatus != '%%') { - $qb->andWhere ( $qb->expr ()->like ( 'cs.name', ':certStatus' ) )->setParameter ( ':certStatus', $certStatus ); + $qbr->andWhere($qbr->expr()->like('cs.name', ':certStatus')) + ->setParameter(':certStatus', $certStatus); } if ($showClosed != 1) { - $qb->andWhere ( $qb->expr ()->not ( $qb->expr ()->like ( 'cs.name', ':closed' ) ) )->setParameter ( ':closed', 'Closed' ); + $qbr->andWhere($qbr->expr()->not($qbr->expr()->like('cs.name', ':closed'))) + ->setParameter(':closed', 'Closed'); } if ($ngi != null && $ngi != '%%') { - $qb->andWhere ( $qb->expr ()->like ( 'n.name', ':ngi' ) )->setParameter ( ':ngi', $ngi ); + $qbr->andWhere($qbr->expr()->like('n.name', ':ngi')) + ->setParameter(':ngi', $ngi); } if ($servKeyNames != null && $servKeyNames != '%%') { @@ -181,46 +288,53 @@ private function getServicesHelper($term = null, $serviceType = null, $productio $servKeyValues = '%%'; } - $sQ = $this->em->createQueryBuilder (); - $sQ->select ( 'se1' . '.id' )->from ( 'Service', 'se1' )->join ( 'se1.serviceProperties', 'sp' )->andWhere ( $sQ->expr ()->andX ( $sQ->expr ()->eq ( 'sp.keyName', ':keyname' ), $sQ->expr ()->like ( 'sp.keyValue', ':keyvalue' ) ) ); + $sqbr = $this->em->createQueryBuilder(); + $sqbr->select('se1' . '.id') + ->from('Service', 'se1') + ->join('se1.serviceProperties', 'sp') + ->andWhere($sqbr->expr() + ->andX( + $sqbr->expr()->eq('sp.keyName', ':keyname'), + $sqbr->expr()->like('sp.keyValue', ':keyvalue') + )); - $qb->andWhere ( $qb->expr ()->in ( 'se', $sQ->getDQL () ) ); - $qb->setParameter ( ':keyname', $servKeyNames )->setParameter ( ':keyvalue', $servKeyValues ); + $qbr->andWhere($qbr->expr()->in('se', $sqbr->getDQL())); + $qbr->setParameter(':keyname', $servKeyNames)->setParameter(':keyvalue', $servKeyValues); } - $query = $qb->getQuery (); + $query = $qbr->getQuery(); if ($count) { - $count = $query->getSingleScalarResult (); + $count = $query->getSingleScalarResult(); return $count; } else { - - if (! empty ( $startRecord )) { - $query->setFirstResult ( $startRecord ); + if (! empty($startRecord)) { + $query->setFirstResult($startRecord); } - if (! empty ( $endRecord )) { - $query->setMaxResults ( $endRecord ); + if (! empty($endRecord)) { + $query->setMaxResults($endRecord); } if ($returnArray) { - $results = $query->getResult ( \Doctrine\ORM\Query::HYDRATE_ARRAY ); + $results = $query->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY); return $results; } else { - $results = $query->getResult (); + $results = $query->getResult(); return $results; } // print_r($results); } } - public function getAllSesJoinParentSites() { + public function getAllSesJoinParentSites() + { $dql = "SELECT se, st, si FROM Service se JOIN se.serviceType st JOIN se.parentSite si"; - $query = $this->em->createQuery ( $dql ); - return $query->getResult (); + $query = $this->em->createQuery($dql); + return $query->getResult(); } /** @@ -253,7 +367,8 @@ public function getAllSesJoinParentSites() { * @return mixed Array of {@link \Service} entities or int representing * the service count */ - public function getServicesFilterByParams($filterParams) { + public function getServicesFilterByParams($filterParams) + { $searchTerm = null; $serviceType = null; $production = null; @@ -269,151 +384,177 @@ public function getServicesFilterByParams($filterParams) { $returnArray = false; $count = false; - if (isset ( $filterParams ['searchTerm'] )) { + if (isset($filterParams ['searchTerm'])) { $searchTerm = $filterParams ['searchTerm']; } - if (isset ( $filterParams ['serviceType'] )) { + if (isset($filterParams ['serviceType'])) { $serviceType = $filterParams ['serviceType']; } - if (isset ( $filterParams ['production'] )) { - if (strtoupper ( $filterParams ['production'] ) == "TRUE") { + if (isset($filterParams ['production'])) { + if (strtoupper($filterParams ['production']) == "TRUE") { $production = "1"; - } else if (strtoupper ( $filterParams ['production'] ) == "FALSE") { + } elseif (strtoupper($filterParams ['production']) == "FALSE") { $production = "0"; } } - if (isset ( $filterParams ['monitored'] )) { - if (strtoupper ( $filterParams ['monitored'] ) == "TRUE") { + if (isset($filterParams ['monitored'])) { + if (strtoupper($filterParams ['monitored']) == "TRUE") { $monitored = "1"; - } else if (strtoupper ( $filterParams ['monitored'] ) == "FALSE") { + } elseif (strtoupper($filterParams ['monitored']) == "FALSE") { $monitored = "0"; } } - if (isset ( $filterParams ['scope'] )) { + if (isset($filterParams ['scope'])) { $scope = $filterParams ['scope']; $scopeMatch = 'all'; } - if (isset ( $filterParams ['scopeMatch'] )) { + if (isset($filterParams ['scopeMatch'])) { $scopeMatch = $filterParams ['scopeMatch']; } - if (isset ( $filterParams ['ngi'] )) { + if (isset($filterParams ['ngi'])) { $ngi = $filterParams ['ngi']; } - if (isset ( $filterParams ['certStatus'] )) { + if (isset($filterParams ['certStatus'])) { $certStatus = $filterParams ['certStatus']; } - if (isset ( $filterParams ['showClosed'] ) && $filterParams ['showClosed'] == TRUE) { + if (isset($filterParams ['showClosed']) && $filterParams ['showClosed'] == true) { $showClosed = $filterParams ['showClosed']; } - if (isset ( $filterParams ['servKeyNames'] )) { + if (isset($filterParams ['servKeyNames'])) { $servKeyNames = $filterParams ['servKeyNames']; } - if (isset ( $filterParams ['servKeyValue'] )) { + if (isset($filterParams ['servKeyValue'])) { $servKeyValue = $filterParams ['servKeyValue']; } - if (isset ( $filterParams ['startRecord'] )) { + if (isset($filterParams ['startRecord'])) { $startRecord = $filterParams ['startRecord']; } - if (isset ( $filterParams ['maxResults'] )) { + if (isset($filterParams ['maxResults'])) { $maxResults = $filterParams ['maxResults']; } - if (isset ( $filterParams ['returnArray'] )) { + if (isset($filterParams ['returnArray'])) { $returnArray = $filterParams ['returnArray']; } - if (isset ( $filterParams ['count'] ) && $filterParams ['count'] != null) { + if (isset($filterParams ['count']) && $filterParams ['count'] != null) { $count = $filterParams ['count']; } // bind count - used to create positional bind params. - $bc = - 1; - $qb = $this->em->createQueryBuilder (); + $bCount = - 1; + $qbr = $this->em->createQueryBuilder(); if ($count) { - $qb->select ( 'count(DISTINCT se)' ); + $qbr->select('count(DISTINCT se)'); } else { - $qb->select ( 'DISTINCT se', 'si', 'st', 'cs', 'n' ); + $qbr->select('DISTINCT se', 'si', 'st', 'cs', 'n'); } - $qb->from ( 'Service', 'se' )->leftjoin ( 'se.serviceType', 'st' )->leftjoin ( 'se.scopes', 's' )->leftjoin ( 'se.parentSite', 'si' )->leftjoin ( 'si.certificationStatus', 'cs' )->leftjoin ( 'si.ngi', 'n' )->orderBy ( 'se.hostName' ); + $qbr->from('Service', 'se') + ->leftjoin('se.serviceType', 'st') + ->leftjoin('se.scopes', 's') + ->leftjoin('se.parentSite', 'si') + ->leftjoin('si.certificationStatus', 'cs') + ->leftjoin('si.ngi', 'n') + ->orderBy('se.hostName'); // For use with search function, convert all terms to upper and do a like query + if ($searchTerm != null) { - $qb->andWhere ( $qb->expr ()->orX ( $qb->expr ()->like ( $qb->expr ()->upper ( 'se.hostName' ), '?' . ++ $bc ), $qb->expr ()->like ( $qb->expr ()->upper ( 'se.description' ), '?' . $bc ) ) )->setParameter ( $bc, strtoupper ( $searchTerm ) ); + $qbr->andWhere($qbr->expr() + ->orX( + $qbr->expr()->like( + $qbr->expr()->upper('se.hostName'), + '?' . ++$bCount + ), + $qbr->expr()->like($qbr->expr()->upper('se.description'), '?' . $bCount) + ))->setParameter($bCount, strtoupper($searchTerm)); } if ($serviceType != null) { - $qb->andWhere ( $qb->expr ()->like ( $qb->expr ()->upper ( 'st.name' ), '?' . ++ $bc ) )->setParameter ( $bc, strtoupper ( $serviceType ) ); + $qbr->andWhere($qbr->expr()->like($qbr->expr()->upper('st.name'), '?' . ++$bCount)) + ->setParameter($bCount, strtoupper($serviceType)); } if ($production != null) { - $qb->andWhere ( $qb->expr ()->like ( $qb->expr ()->upper ( 'se.production' ), '?' . ++ $bc ) )->setParameter ( $bc, $production ); + $qbr->andWhere($qbr->expr()->like($qbr->expr()->upper('se.production'), '?' . ++$bCount)) + ->setParameter($bCount, $production); } if ($monitored != null) { - $qb->andWhere ( $qb->expr ()->like ( $qb->expr ()->upper ( 'se.monitored' ), '?' . ++ $bc ) )->setParameter ( $bc, $monitored ); + $qbr->andWhere($qbr->expr()->like($qbr->expr()->upper('se.monitored'), '?' . ++$bCount)) + ->setParameter($bCount, $monitored); } // Create WHERE clauses for multiple scopes using positional bind params if ($scope != null) { require_once __DIR__ . '/PI/QueryBuilders/ScopeQueryBuilder.php'; - $scopeQueryBuilder = new ScopeQueryBuilder ( $scope, $scopeMatch, $qb, $this->em, $bc, 'Service', 'se' ); + $scopeQueryBuilder = new ScopeQueryBuilder($scope, $scopeMatch, $qbr, $this->em, $bCount, 'Service', 'se'); // Get the result of the scope builder - /* @var $qb \Doctrine\ORM\QueryBuilder */ - $qb = $scopeQueryBuilder->getQB (); - $bc = $scopeQueryBuilder->getBindCount (); + /* @var $qbr \Doctrine\ORM\QueryBuilder */ + $qbr = $scopeQueryBuilder->getQB(); + $bCount = $scopeQueryBuilder->getBindCount(); // Get the binds and store them in the local bind array only if any binds are fetched from scopeQueryBuilder - $binds = ( array ) $scopeQueryBuilder->getBinds (); - foreach ( $binds as $bind ) { + $binds = (array) $scopeQueryBuilder->getBinds(); + foreach ($binds as $bind) { $binds [] = $bind; } - foreach ( $binds as $bindIdValue ) { - $qb->setParameter ( $bindIdValue [0], $bindIdValue [1] ); // , \Doctrine\DBAL\Types\Type::STRING ); + foreach ($binds as $bindIdValue) { + $qbr->setParameter($bindIdValue [0], $bindIdValue [1]); // , \Doctrine\DBAL\Types\Type::STRING ); } } if ($certStatus != null) { - $qb->andWhere ( $qb->expr ()->like ( 'cs.name', '?' . ++ $bc ) )->setParameter ( $bc, $certStatus ); + $qbr->andWhere($qbr->expr()->like('cs.name', '?' . ++$bCount))->setParameter($bCount, $certStatus); } if ($showClosed) { // don't add the extra where clause } else { // add a where clause to drop Closed certStatus, i.e. 'WHERE cs.name IS NOT LIKE Closed' - $qb->andWhere ( $qb->expr ()->not ( $qb->expr ()->like ( 'cs.name', '?' . ++ $bc ) ) )->setParameter ( $bc, 'Closed' ); + $qbr->andWhere($qbr->expr()->not($qbr->expr()->like('cs.name', '?' . ++$bCount))) + ->setParameter($bCount, 'Closed'); } if ($ngi != null) { - $qb->andWhere ( $qb->expr ()->like ( 'n.name', '?' . ++ $bc ) )->setParameter ( $bc, $ngi ); + $qbr->andWhere($qbr->expr()->like('n.name', '?' . ++$bCount)) + ->setParameter($bCount, $ngi); } if ($servKeyNames != null) { if ($servKeyValue == null || $servKeyValue == '') { $servKeyValue = '%%'; } - $sQ = $this->em->createQueryBuilder (); - $sQ->select ( 'se_p1' . '.id' )->from ( 'Service', 'se_p1' )->join ( 'se_p1.serviceProperties', 'sp' )->andWhere ( $sQ->expr ()->andX ( $sQ->expr ()->eq ( 'sp.keyName', '?' . ++ $bc ), $sQ->expr ()->like ( 'sp.keyValue', '?' . ++ $bc ) ) ); - $qb->andWhere ( $qb->expr ()->in ( 'se', $sQ->getDQL () ) ); - $qb->setParameter ( $bc - 1, $servKeyNames )->setParameter ( $bc, $servKeyValue ); + $sqbr = $this->em->createQueryBuilder(); + $sqbr->select('se_p1' . '.id') + ->from('Service', 'se_p1') + ->join('se_p1.serviceProperties', 'sp') + ->andWhere($sqbr->expr()->andX( + $sqbr->expr()->eq('sp.keyName', '?' . ++$bCount), + $sqbr->expr()->like('sp.keyValue', '?' . ++$bCount) + )); + + $qbr->andWhere($qbr->expr()->in('se', $sqbr->getDQL())); + $qbr->setParameter($bCount - 1, $servKeyNames)->setParameter($bCount, $servKeyValue); } - $query = $qb->getQuery (); + $query = $qbr->getQuery(); if ($count) { - $count = $query->getSingleScalarResult (); + $count = $query->getSingleScalarResult(); return $count; } else { - if (! empty ( $startRecord )) { - $query->setFirstResult ( $startRecord ); + if (! empty($startRecord)) { + $query->setFirstResult($startRecord); } - if (! empty ( $maxResults )) { - $query->setMaxResults ( $maxResults ); + if (! empty($maxResults)) { + $query->setMaxResults($maxResults); } if ($returnArray) { - $results = $query->getResult ( \Doctrine\ORM\Query::HYDRATE_ARRAY ); + $results = $query->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY); return $results; } else { - $results = $query->getResult (); + $results = $query->getResult(); return $results; } // print_r($results); @@ -426,13 +567,13 @@ public function getServicesFilterByParams($filterParams) { * @param integer $id Service ID * @param integer $dayLimit */ - public function getDowntimes($id, $dayLimit) { + public function getDowntimes($id, $dayLimit) + { if ($dayLimit != null) { - $di = \DateInterval::createFromDateString ( $dayLimit . 'days' ); - $dayLimit = new \DateTime (); - $dayLimit->sub ( $di ); + $dateInterval = \DateInterval::createFromDateString($dayLimit . 'days'); + $dayLimit = new \DateTime(); + $dayLimit->sub($dateInterval); } - // Simplified and updated query for MEPs model by JM&DM - 18/06/2014 $dql = "SELECT d FROM Downtime d @@ -441,7 +582,10 @@ public function getDowntimes($id, $dayLimit) { AND ( :dayLimit IS NULL OR d.startDate > :dayLimit) ORDER BY d.startDate DESC"; - $downtimes = $this->em->createQuery ( $dql )->setParameter ( 'id', $id )->setParameter ( 'dayLimit', $dayLimit )->getResult (); + $downtimes = $this->em->createQuery($dql) + ->setParameter('id', $id) + ->setParameter('dayLimit', $dayLimit) + ->getResult(); // $downtimes = $this->getService($id)->getDowntimes(); return $downtimes; @@ -452,10 +596,11 @@ public function getDowntimes($id, $dayLimit) { * * @return array $types An array of all ServiceType entities */ - public function getServiceTypes() { + public function getServiceTypes() + { $dql = "SELECT st FROM ServiceType st ORDER BY st.name"; - $types = $this->em->createQuery ( $dql )->getResult (); + $types = $this->em->createQuery($dql)->getResult(); return $types; } @@ -470,19 +615,27 @@ public function getServiceTypes() { * is invalid. The \Exception's message will contain a human readable error * message. */ - public function validateProductionMonitoredCombination($serviceTypeName, $production, $monitored) { + public function validateProductionMonitoredCombination($serviceType, $production, $monitored) + { // Service types that are exceptions to the // 'production => monitored' rule. $ruleExceptions = array('VOMS', 'emi.ARGUS', 'org.squid-cache.Squid'); + $serviceTypeName = $serviceType->getName(); // Check that the service type is not an exception to the // 'production => monitored'. - if (!in_array ($serviceTypeName, $ruleExceptions)) { - if ($production && !$monitored) { + if ($production && !$monitored) { + // Legacy hard-coded rules (as of Jan-20) should be removed + if ( + !in_array($serviceTypeName, $ruleExceptions) and + !$serviceType->getAllowMonitoringException() + ) { throw new \Exception( - "For the '".$serviceTypeName."' service type, if the ". - "Production flag is set to True, the Monitored flag must ". - "also be True."); + "For the '" . $serviceTypeName . "' service type, if a " . + "service is in Production it must be Monitored. " . + "Contact GOCDB administrators if required to discuss " . + "changing this requirement." + ); } } } @@ -491,7 +644,7 @@ public function validateProductionMonitoredCombination($serviceTypeName, $produc * Updates a Service. * Returns the updated SE * - * Accepts an array $se_data as a parameter. $se_data's format is as follows: + * Accepts an array $newValues as a parameter. $newValues's format is as follows: *
          * Array
          * (
    @@ -517,72 +670,88 @@ public function validateProductionMonitoredCombination($serviceTypeName, $produc
          * )
          * 
    * - * @param array $se_data Array of updated service data, specified above. - * return Service The updated service entity + * @param array $newValues Array of updated service data, specified above. + * @return \Service The updated service entity */ - public function editService(\Service $se, $newValues, \User $user = null) { + public function editService(\Service $service, $newValues, \User $user = null) + { require_once __DIR__ . '/../../htdocs/web_portal/components/Get_User_Principle.php'; // Check the portal is not in read only mode, throws exception if it is - $this->checkPortalIsNotReadOnlyOrUserIsAdmin ( $user ); + $this->checkPortalIsNotReadOnlyOrUserIsAdmin($user); + // Authorise the change - if ($this->roleActionAuthorisationService->authoriseAction ( \Action::EDIT_OBJECT, $se->getParentSite (), $user )->getGrantAction () == FALSE) { - throw new \Exception ( "You do not have permission over this service." ); + if ( + $this->roleAAS->authoriseAction( + \Action::EDIT_OBJECT, + $service->getParentSite(), + $user + )->getGrantAction() == false + ) { + throw new \Exception("You do not have permission over this service."); } - $st = $this->getServiceType ( $newValues ['serviceType'] ); - $this->validate ( $newValues ['SE'], 'service' ); - $this->uniqueCheck ( $newValues ['SE'] ['HOSTNAME'], $st, $se->getParentSite () ); - // validate production/monitored combination - $this->validateProductionMonitoredCombination( - $this->getServiceType($newValues['serviceType']), - $this->ptlTexToBool($newValues['PRODUCTION_LEVEL']), - $this->ptlTexToBool($newValues['IS_MONITORED']) - ); + $servType = $this->getServiceType($newValues ['serviceType']); + + $this->validate($newValues ['SE'], 'service'); + $this->uniqueCheck($newValues ['SE'] ['HOSTNAME'], $servType, $service->getParentSite()); // EDIT SCOPE TAGS: // collate selected scopeIds (reserved and non-reserved) $scopeIdsToApply = array (); - foreach ( $newValues ['Scope_ids'] as $sid ) { + foreach ($newValues ['Scope_ids'] as $sid) { $scopeIdsToApply [] = $sid; } - foreach ( $newValues ['ReservedScope_ids'] as $sid ) { + foreach ($newValues ['ReservedScope_ids'] as $sid) { $scopeIdsToApply [] = $sid; } - $selectedScopesToApply = $this->scopeService->getScopes ( $scopeIdsToApply ); + $scopesToApply = $this->scopeService->getScopes($scopeIdsToApply); // If not admin, Check user edits to the service's Reserved scopes: // Required to prevent users manually crafting a POST request in an attempt // to select reserved scopes, this is unlikely but it is a possible hack. - if (! $user->isAdmin ()) { - $selectedReservedScopes = $this->scopeService->getScopesFilterByParams ( array ( + if (! $user->isAdmin()) { + $resScopesToApply = $this->scopeService->getScopesFilterByParams(array ( 'excludeNonReserved' => true - ), $selectedScopesToApply ); - - $existingReservedScopes = $this->scopeService->getScopesFilterByParams ( array ( + ), $scopesToApply); + // Existing reserved scopes + $resScopes = $this->scopeService->getScopesFilterByParams(array ( 'excludeNonReserved' => true - ), $se->getScopes ()->toArray () ); + ), $service->getScopes()->toArray()); - $existingReservedScopesParent = $this->scopeService->getScopesFilterByParams ( array ( + $resScopesParent = $this->scopeService->getScopesFilterByParams(array ( 'excludeNonReserved' => true - ), $se->getParentSite ()->getScopes ()->toArray () ); + ), $service->getParentSite()->getScopes()->toArray()); - foreach ( $selectedReservedScopes as $sc ) { + foreach ($resScopesToApply as $sc) { // Reserved scopes must already be assigned to se or parent - if (! in_array ( $sc, $existingReservedScopes ) && ! in_array ( $sc, $existingReservedScopesParent )) { - throw new \Exception ( "A reserved Scope Tag was selected that " . "is not assigned to the Service or to the Parent Site" ); + + if (! in_array($sc, $resScopes) && ! in_array($sc, $resScopesParent)) { + throw new \Exception("A reserved Scope Tag was selected that " . + "is not assigned to the Service or to the Parent Site"); } } } // check there are the required number of optional scopes specified - $this->checkNumberOfScopes ( $this->scopeService->getScopesFilterByParams ( array ( - 'excludeReserved' => true - ), $selectedScopesToApply ) ); - $updatedServiceValues =array(); + $this->checkNumberOfScopes( + $this->scopeService->getScopesFilterByParams( + array('excludeReserved' => true), + $scopesToApply + ) + ); + + // validate production/monitored combination + $this->validateProductionMonitoredCombination( + $servType, + $this->ptlTexToBool($newValues['PRODUCTION_LEVEL']), + $this->ptlTexToBool($newValues['IS_MONITORED']) + ); + + $updatedServiceValues = array(); $updatedServiceValues['hostname'] = $newValues ['SE'] ['HOSTNAME']; $updatedServiceValues['description'] = $newValues ['SE'] ['DESCRIPTION']; $updatedServiceValues['url'] = $newValues['SE']['URL']; @@ -595,31 +764,29 @@ public function editService(\Service $se, $newValues, \User $user = null) { $updatedServiceValues['monitored'] = $this->ptlTexToBool($newValues['IS_MONITORED']); $updatedServiceValues['beta'] = $this->ptlTexToBool($newValues['BETA']); $updatedServiceValues['production'] = $this->ptlTexToBool($newValues['PRODUCTION_LEVEL']); - $updatedServiceValues['notify']; - if (!isset($newValues['NOTIFY'])){ + if (!isset($newValues['NOTIFY'])) { $updatedServiceValues['notify'] = false; - } - else { + } else { $updatedServiceValues['notify'] = $this->ptlTexToBool($newValues['NOTIFY']); } - $this->editServiceLogic($se, $selectedScopesToApply, $st, $updatedServiceValues); + $this->editServiceLogic($service, $scopesToApply, $servType, $updatedServiceValues); - return $se; + return $service; } /** * Function called by write API to edit a service. Provides API specific * authorisation on top of shared logic with web portal - * @param Service $service service being updated + * @param \Service $service service being updated * @param string $hostname service hostname * @param string $description service description * @param string $url service url * @param string $dn service dn - * @param string $ip service IP + * @param string $ip4 service IP (ipV4) * @param string $ip6 serviec IP (ipV6) - * @param string $os service OS + * @param string $opSys service OS * @param string $email service email * @param string $arch service archetecture * @param string $monitored @@ -629,42 +796,59 @@ public function editService(\Service $se, $newValues, \User $user = null) { * @param string $authIdentifierType * @param string $authIdentifier */ - public function editServiceApi(\Service $service, $hostname, $description, $url, $dn, $ip, $ip6, $os, $email, $arch, $monitored, $beta, $production, $notify, $authIdentifierType, $authIdentifier) { + + public function editServiceApi( + \Service $service, + $hostname, + $description, + $url, + $dn, + $ip4, + $ip6, + $opSys, + $email, + $arch, + $monitored, + $beta, + $production, + $notify, + $authIdentifierType, + $authIdentifier + ) { //Check the portal is not in read only mode, throws exception if it is - $this->checkGOCDBIsNotReadOnly(); - - $this->checkAuthorisedAPIIdentifier($service->getParentSite(), $authIdentifier, $authIdentifierType); - - $scopes = clone $service->getScopes(); - $sType = $service->getServiceType(); - $updatedServiceValues = array ( - 'hostname'=>$hostname, - 'description'=>$description, - 'url'=>$url, - 'dn'=>$dn, - 'ip'=>$ip, - 'ip6'=>$ip6, - 'os'=>$os, - 'email'=>$email, - 'arch'=>$arch, - 'monitored'=>$monitored, - 'beta'=>$beta, - 'production'=>$production, - 'notify'=>$notify, - ); - - $this->validateProductionMonitoredCombination($service->getServiceType()->getName(), $production, $monitored); - - $this->editServiceLogic($service, $scopes, $sType, $updatedServiceValues); - } + $this->checkGOCDBIsNotReadOnly(); + + $this->checkAuthorisedAPIIdentifier($service->getParentSite(), $authIdentifier, $authIdentifierType); + + $scopes = clone $service->getScopes(); + $sType = $service->getServiceType(); + $updatedServiceValues = array ( + 'hostname' => $hostname, + 'description' => $description, + 'url' => $url, + 'dn' => $dn, + 'ip' => $ip4, + 'ip6' => $ip6, + 'os' => $opSys, + 'email' => $email, + 'arch' => $arch, + 'monitored' => $monitored, + 'beta' => $beta, + 'production' => $production, + 'notify' => $notify, + ); + $this->validateProductionMonitoredCombination($service->getServiceType(), $production, $monitored); + + $this->editServiceLogic($service, $scopes, $sType, $updatedServiceValues); + } /** * The logic of editing a service, without the authorisation or validation. * Private function as there should always be authorisation anad validation * steps within the service before calling this function. * - * @param Service $service service to be updated + * @param \Service $service service to be updated * @param array $scopes scopes of service being updated * @param $sType service type of service * @param array $updatedServiceValues values being updated for $service. Should contain: @@ -674,7 +858,7 @@ public function editServiceApi(\Service $service, $hostname, $description, $url, * ['dn'] dn of service being updated * ['$ip6'] ip V6 of service being updated * ['ip'] ip of service being updated - * ['$os'] os of service being updated + * ['os'] os of service being updated * ['email'] email of service being updated * ['$arch'] architecture of service being updated * ['$monitored'] boolean monitored of service being updated @@ -683,78 +867,80 @@ public function editServiceApi(\Service $service, $hostname, $description, $url, * ['$notify'] boolean notify value of service being updated * @throws Exception */ - private function editServiceLogic(\Service $service, $scopes, $sType, $updatedServiceValues){ + private function editServiceLogic(\Service $service, $scopes, $sType, $updatedServiceValues) + { // Explicitly demarcate our tx boundary - $this->em->getConnection ()->beginTransaction (); - try { - // Set the service's member variables - $service->setHostName($updatedServiceValues['hostname']); - $service->setDescription($updatedServiceValues['description']); - $service->setUrl($updatedServiceValues['url']); - $service->setDn($updatedServiceValues['dn']); - $service->setIpAddress($updatedServiceValues['ip']); - $service->setIpV6Address($updatedServiceValues['ip6']); - $service->setOperatingSystem($updatedServiceValues['os']); - $service->setEmail($updatedServiceValues['email']); - $service->setArchitecture($updatedServiceValues['arch']); - $service->setMonitored($updatedServiceValues['monitored']); - $service->setBeta($updatedServiceValues['beta']); - $service->setProduction($updatedServiceValues['production']); - $service->setNotify($updatedServiceValues['notify']); - - $service->setServiceType($sType); - - // Update the scope of the service - // firstly remove all existing scope links - $oldScopes = $service->getScopes (); - foreach($oldScopes as $s ) { - $service->removeScope($s); - } - - // find each specified scope and then link it to the specified site - foreach($scopes as $scope) { - $service->addScope($scope); - } - - $this->em->merge($service); - $this->em->flush (); - $this->em->getConnection ()->commit (); - } catch ( \Exception $e ) { - $this->em->getConnection ()->rollback (); - $this->em->close (); - throw $e; - } + $this->em->getConnection()->beginTransaction(); + try { + // Set the service's member variables + $service->setHostName($updatedServiceValues['hostname']); + $service->setDescription($updatedServiceValues['description']); + $service->setUrl($updatedServiceValues['url']); + $service->setDn($updatedServiceValues['dn']); + $service->setIpAddress($updatedServiceValues['ip']); + $service->setIpV6Address($updatedServiceValues['ip6']); + $service->setOperatingSystem($updatedServiceValues['os']); + $service->setEmail($updatedServiceValues['email']); + $service->setArchitecture($updatedServiceValues['arch']); + $service->setMonitored($updatedServiceValues['monitored']); + $service->setBeta($updatedServiceValues['beta']); + $service->setProduction($updatedServiceValues['production']); + $service->setNotify($updatedServiceValues['notify']); + + $service->setServiceType($sType); + + // Update the scope of the service + // firstly remove all existing scope links + $oldScopes = $service->getScopes(); + foreach ($oldScopes as $scope) { + $service->removeScope($scope); + } + + // find each specified scope and then link it to the specified site + foreach ($scopes as $scope) { + $service->addScope($scope); + } + + $this->em->merge($service); + $this->em->flush(); + $this->em->getConnection()->commit(); + } catch (\Exception $e) { + $this->em->getConnection()->rollback(); + $this->em->close(); + throw $e; + } } /** * Validates user inputted service data against the * checks in the gocdb_schema.xml. * - * @param array $se_data containing all the fields for a Service + * @param array $seData containing all the fields for a Service * @throws \Exception If the SE data can't be * validated. The \Exception message will contain a human * readable description of which field failed validation. * @return null */ - private function validate($se_data, $type) { + private function validate($seData, $type) + { require_once __DIR__ . '/Validate.php'; - $serv = new \org\gocdb\services\Validate (); - foreach ( $se_data as $field => $value ) { - $valid = $serv->validate ( $type, $field, $value ); + $serv = new Validate(); + foreach ($seData as $field => $value) { + $valid = $serv->validate($type, $field, $value); if (! $valid) { $error = "$field contains an invalid value: $value"; - throw new \Exception ( $error ); + throw new \Exception($error); } } // Apply additional logic for validation that can't be captured solely using gocdb_schema.xml - if (! empty ( $se_data ['HOST_IP_V6'] )) { + if (! empty($seData ['HOST_IP_V6'])) { require_once __DIR__ . '/validation/IPv6Validator.php'; - $validator = new \IPv6Validator (); + $validator = new \IPv6Validator(); $errors = array (); - $errors = $validator->validate ( $se_data ['HOST_IP_V6'], $errors ); - if (count ( $errors ) > 0) { - throw new \Exception ( $errors [0] ); // show the first message. + $errors = $validator->validate($seData ['HOST_IP_V6'], $errors); + if (count($errors) > 0) { + throw new \Exception($errors [0]); // show the first message. } } } @@ -788,86 +974,86 @@ private function validate($se_data, $type) { * @param Array $values Balues for the new SE (defined above) * @param org\gocdb\services\User $user The user adding the SE */ - public function addService($values, \User $user = null) { + public function addService($values, \User $user = null) + { // get the parent site $dql = "SELECT s from Site s WHERE s.id = :id"; /* @var $site \Site */ - $site = $this->em->createQuery ( $dql )->setParameter ( 'id', $values ['hostingSite'] )->getSingleResult (); + $site = $this->em->createQuery($dql)->setParameter('id', $values ['hostingSite'])->getSingleResult(); // get the service type - $st = $this->getServiceType ( $values ['serviceType'] ); + $servType = $this->getServiceType($values ['serviceType']); - if ($this->roleActionAuthorisationService->authoriseAction ( \Action::SITE_ADD_SERVICE, $site, $user )->getGrantAction () == FALSE) { - throw new \Exception ( "You don't have permission to add a service to this site." ); + if ($this->roleAAS->authoriseAction(\Action::SITE_ADD_SERVICE, $site, $user)->getGrantAction() == false) { + throw new \Exception("You don't have permission to add a service to this site."); } - $this->validate ( $values ['SE'], 'service' ); - $this->uniqueCheck ( $values ['SE'] ['HOSTNAME'], $st, $site ); - - // validate production/monitored combination - $this->validateProductionMonitoredCombination( - $this->getServiceType($values['serviceType']), - $this->ptlTexToBool($values['PRODUCTION_LEVEL']), - $this->ptlTexToBool($values['IS_MONITORED']) - ); + $this->validate($values ['SE'], 'service'); + $this->uniqueCheck($values ['SE'] ['HOSTNAME'], $servType, $site); // ADD SCOPE TAGS: // collate selected reserved and non-reserved scopeIds. // Note, Reserved scopes can be inherited from the parent Site. $allSelectedScopeIds = array (); - foreach ( $values ['Scope_ids'] as $sid ) { + foreach ($values ['Scope_ids'] as $sid) { $allSelectedScopeIds [] = $sid; } - foreach ( $values ['ReservedScope_ids'] as $sid ) { + foreach ($values ['ReservedScope_ids'] as $sid) { $allSelectedScopeIds [] = $sid; } - $selectedScopesToApply = $this->scopeService->getScopes ( $allSelectedScopeIds ); + $scopesToApply = $this->scopeService->getScopes($allSelectedScopeIds); // If not admin, check that requested reserved scopes are already implemented by the parent Site. // Required to prevent users manually crafting a POST request in an attempt // to select reserved scopes, this is unlikely but it is a possible hack. - if (! $user->isAdmin ()) { - $selectedReservedScopes = $this->scopeService->getScopesFilterByParams ( array ( + if (! $user->isAdmin()) { + $resScopesToApply = $this->scopeService->getScopesFilterByParams(array ( 'excludeNonReserved' => true - ), $selectedScopesToApply ); + ), $scopesToApply); - $existingReservedScopesParent = $this->scopeService->getScopesFilterByParams ( array ( + $resScopesParent = $this->scopeService->getScopesFilterByParams(array ( 'excludeNonReserved' => true - ), $site->getScopes ()->toArray () ); + ), $site->getScopes()->toArray()); - foreach ( $selectedReservedScopes as $sc ) { + foreach ($resScopesToApply as $sc) { // Reserved scopes must already be assigned to parent - if (! in_array ( $sc, $existingReservedScopesParent )) { - throw new \Exception ( "A reserved Scope Tag was selected that is not assigned to the Parent Site" ); + if (! in_array($sc, $resScopesParent)) { + throw new \Exception("A reserved Scope Tag was selected that is not assigned to the Parent Site"); } } } // check there are the required number of OPTIONAL scopes specified - $this->checkNumberOfScopes ( $values ['Scope_ids'] ); + $this->checkNumberOfScopes($values ['Scope_ids']); + + // validate production/monitored combination + $this->validateProductionMonitoredCombination( + $servType, + $this->ptlTexToBool($values['PRODUCTION_LEVEL']), + $this->ptlTexToBool($values['IS_MONITORED']) + ); - $this->em->getConnection ()->beginTransaction (); + $this->em->getConnection()->beginTransaction(); try { - $se = new \Service (); - $se->setParentSiteDoJoin ( $site ); - $se->setServiceType ( $st ); + $serv = new \Service(); + $serv->setParentSiteDoJoin($site); + $serv->setServiceType($servType); // Set production - $se->setProduction($this->ptlTexToBool($values['PRODUCTION_LEVEL'])); + $serv->setProduction($this->ptlTexToBool($values['PRODUCTION_LEVEL'])); // Set Beta - $se->setBeta($this->ptlTexToBool($values['BETA'])); + $serv->setBeta($this->ptlTexToBool($values['BETA'])); // Set monitored - $se->setMonitored($this->ptlTexToBool($values['IS_MONITORED'])); + $serv->setMonitored($this->ptlTexToBool($values['IS_MONITORED'])); //Set notify flag for site - if (!isset($values['NOTIFY'])){ - $se->setNotify(false); - } - else{ - $se->setNotify($this->ptlTexToBool($values['NOTIFY'])); + if (!isset($values['NOTIFY'])) { + $serv->setNotify(false); + } else { + $serv->setNotify($this->ptlTexToBool($values['NOTIFY'])); } // Set the scopes @@ -876,30 +1062,30 @@ public function addService($values, \User $user = null) { // $scope = $this->em->createQuery($dql) // ->setParameter('id', $scopeId) // ->getSingleResult(); - // $se->addScope($scope); + // $serv->addScope($scope); // } - foreach ( $selectedScopesToApply as $scope ) { - $se->addScope ( $scope ); + foreach ($scopesToApply as $scope) { + $serv->addScope($scope); } - $se->setDn ( $values ['SE'] ['HOST_DN'] ); - $se->setIpAddress ( $values ['SE'] ['HOST_IP'] ); - $se->setOperatingSystem ( $values ['SE'] ['HOST_OS'] ); - $se->setArchitecture ( $values ['SE'] ['HOST_ARCH'] ); - $se->setHostName ( $values ['SE'] ['HOSTNAME'] ); - $se->setDescription ( $values ['SE'] ['DESCRIPTION'] ); - $se->setEmail ( $values ['SE'] ['EMAIL'] ); - $se->setUrl ( $values ['SE'] ['URL'] ); - - $this->em->persist ( $se ); - $this->em->flush (); - $this->em->getConnection ()->commit (); - } catch ( \Exception $e ) { - $this->em->getConnection ()->rollback (); - $this->em->close (); + $serv->setDn($values ['SE'] ['HOST_DN']); + $serv->setIpAddress($values ['SE'] ['HOST_IP']); + $serv->setOperatingSystem($values ['SE'] ['HOST_OS']); + $serv->setArchitecture($values ['SE'] ['HOST_ARCH']); + $serv->setHostName($values ['SE'] ['HOSTNAME']); + $serv->setDescription($values ['SE'] ['DESCRIPTION']); + $serv->setEmail($values ['SE'] ['EMAIL']); + $serv->setUrl($values ['SE'] ['URL']); + + $this->em->persist($serv); + $this->em->flush(); + $this->em->getConnection()->commit(); + } catch (\Exception $e) { + $this->em->getConnection()->rollback(); + $this->em->close(); throw $e; } - return $se; + return $serv; } /** @@ -913,11 +1099,12 @@ public function addService($values, \User $user = null) { * (as explained by Rajesh Kalmady) * * @param string $hostName New hostname - * @param ServiceType $serviceType New service type - * @param Site $site The site to add the SE to + * @param \ServiceType $serviceType New service type + * @param \Site $site The site to add the SE to * @return null */ - private function uniqueCheck($hostName, \ServiceType $serviceType, \Site $site) { + private function uniqueCheck($hostName, \ServiceType $serviceType, \Site $site) + { // Get all existing services with this hostname and service type, not under this site $dql = "SELECT se from Service se JOIN se.serviceType st @@ -925,29 +1112,15 @@ private function uniqueCheck($hostName, \ServiceType $serviceType, \Site $site) WHERE se.hostName = :hostName AND st.id = :stId AND s.id != :siteId"; - $ses = $this->em->createQuery ( $dql )->setParameter ( 'hostName', $hostName )->setParameter ( 'stId', $serviceType->getId () )->setParameter ( 'siteId', $site->getId () )->getResult (); - - if (sizeof ( $ses ) != 0) { - throw new \Exception ( "A $serviceType service named $hostName already exists." ); - } - } - /** - * Check that if if the selected scope for this SE is EGI, the parent site - * is also EGI - * - * @param Site $site The SE's parent site - * @param Scope $scope The SE's new scope - * @return null - */ - private function scopeCheck(\Site $site, \Scope $scope) { - // If the scope isn't EGI then don't raise an error - if ($scope->getName () != 'EGI') { - return; - } + $ses = $this->em->createQuery($dql) + ->setParameter('hostName', $hostName) + ->setParameter('stId', $serviceType->getId()) + ->setParameter('siteId', $site->getId()) + ->getResult(); - if ($site->getScopes ()->first ()->getName () != "EGI") { - throw new \Exception ( "For this service to be EGI scoped, $site must also be EGI scoped." ); + if (sizeof($ses) != 0) { + throw new \Exception("A $serviceType service named $hostName already exists."); } } @@ -957,19 +1130,21 @@ private function scopeCheck(\Site $site, \Scope $scope) { * @param integer $id The service type ID * @return \ServiceType */ - private function getServiceType($id) { + private function getServiceType($id) + { $dql = "SELECT st FROM ServiceType st WHERE st.id = :id"; - $st = $this->em->createQuery ( $dql )->setParameter ( 'id', $id )->getSingleResult (); - return $st; + $servType = $this->em->createQuery($dql)->setParameter('id', $id)->getSingleResult(); + return $servType; } /** * * @return array of all properties for a service */ - public function getProperties($id) { + public function getProperties($id) + { $dql = "SELECT p FROM ServiceProperty p WHERE p.parentSite = :ID"; - $properties = $this->em->createQuery ( $dql )->setParameter ( 'ID', $id )->getOneOrNullResult (); + $properties = $this->em->createQuery($dql)->setParameter('ID', $id)->getOneOrNullResult(); return $properties; } @@ -977,9 +1152,10 @@ public function getProperties($id) { * * @return a single service property or null if not found */ - public function getProperty($id) { + public function getProperty($id) + { $dql = "SELECT p FROM ServiceProperty p WHERE p.id = :ID"; - $property = $this->em->createQuery ( $dql )->setParameter ( 'ID', $id )->getOneOrNullResult (); + $property = $this->em->createQuery($dql)->setParameter('ID', $id)->getOneOrNullResult(); return $property; } @@ -987,57 +1163,69 @@ public function getProperty($id) { * * @return a single service endpoint property or null if not foud */ - public function getEndpointProperty($id) { + public function getEndpointProperty($id) + { $dql = "SELECT p FROM EndpointProperty p WHERE p.id = :ID"; - $property = $this->em->createQuery ( $dql )->setParameter ( 'ID', $id )->getOneOrNullResult (); + $property = $this->em->createQuery($dql)->setParameter('ID', $id)->getOneOrNullResult(); return $property; } /** * @return \ServiceProperty a single service property */ - public function getServicePropertyByKeyAndParent($key, $parentService) { + public function getServicePropertyByKeyAndParent($key, $parentService) + { $parentServiceID = $parentService->getId(); $dql = "SELECT p FROM ServiceProperty p WHERE p.keyName = :KEY AND p.parentService = :PARENTSERVICEID"; $property = $this->em - ->createQuery ($dql) - ->setParameter ('KEY', $key) - ->setParameter ('PARENTSERVICEID', $parentServiceID) - ->getOneOrNullResult (); + ->createQuery($dql) + ->setParameter('KEY', $key) + ->setParameter('PARENTSERVICEID', $parentServiceID) + ->getOneOrNullResult(); return $property; } /** * @return \SiteProperty a single site property */ - public function getEndpointPropertyByKeyAndParent($key, $parentEndpoint) { + public function getEndpointPropertyByKeyAndParent($key, $parentEndpoint) + { $parentEndpointID = $parentEndpoint->getId(); $dql = "SELECT p FROM EndpointProperty p WHERE p.keyName = :KEY AND p.parentEndpoint = :PARENTENDPOINTID"; $property = $this->em - ->createQuery ($dql) - ->setParameter ('KEY', $key) - ->setParameter ('PARENTENDPOINTID', $parentEndpointID) - ->getOneOrNullResult (); + ->createQuery($dql) + ->setParameter('KEY', $key) + ->setParameter('PARENTENDPOINTID', $parentEndpointID) + ->getOneOrNullResult(); return $property; } /** - * This method will check that a user has edit permissions over a service before allowing a user to add, edit or delete + * This method will check that a user has edit permissions over a service before + * allowing a user to add, edit or delete * any service information. * * @param \User $user * @param \Service $service * @throws \Exception */ - public function validateAddEditDeleteActions(\User $user, \Service $service) { + public function validateAddEditDeleteActions(\User $user, \Service $service) + { // Check to see whether the user has a role that covers this service // if(count($this->authorize Action(\Action::EDIT_OBJECT, $service, $user))==0){ // throw new \Exception("You don't have permission over ". $service->getHostName()); // } - if ($this->roleActionAuthorisationService->authoriseAction ( \Action::EDIT_OBJECT, $service->getParentSite (), $user )->getGrantAction () == FALSE) { - throw new \Exception ( "You don't have permission over service." ); + + if ( + $this->roleAAS->authoriseAction( + \Action::EDIT_OBJECT, + $service->getParentSite(), + $user + )->getGrantAction() == false + ) { + throw new \Exception("You don't have permission over service."); } } @@ -1050,22 +1238,23 @@ public function validateAddEditDeleteActions(\User $user, \Service $service) { * @param bool $preventOverwrite * @throws \Exception */ - public function addProperties(\Service $service, \User $user, array $propArr, $preventOverwrite = false) { + public function addProperties(\Service $service, \User $user, array $propArr, $preventOverwrite = false) + { // Check the portal is not in read only mode, throws exception if it is $this->checkPortalIsNotReadOnlyOrUserIsAdmin($user); //Check that the user has the requisite permissions - $this->validateAddEditDeleteActions ($user,$service); + $this->validateAddEditDeleteActions($user, $service); //Make the change - $this->em->getConnection ()->beginTransaction (); + $this->em->getConnection()->beginTransaction(); try { - $this->addPropertiesLogic($service,$propArr,$preventOverwrite); - $this->em->flush (); - $this->em->getConnection ()->commit (); - } catch ( \Exception $e ) { - $this->em->getConnection ()->rollback (); - $this->em->close (); + $this->addPropertiesLogic($service, $propArr, $preventOverwrite); + $this->em->flush(); + $this->em->getConnection()->commit(); + } catch (\Exception $e) { + $this->em->getConnection()->rollback(); + $this->em->close(); throw $e; } } @@ -1075,22 +1264,30 @@ public function addProperties(\Service $service, \User $user, array $propArr, $p * @param \Service $service * @param array $propArr * @param bool $preventOverwrite - * @param string $authenticationType - * @param string $authenticationIdentifier + * @param string $authType + * @param string $authIdentifier * @throws \Exception */ - public function addServicePropertiesAPI(\Service $service, array $propKVArr, $preventOverwrite, $authenticationType, $authenticationIdentifier) { + + public function addServicePropertiesAPI( + \Service $service, + array $propKVArr, + $preventOverwrite, + $authType, + $authIdentifier + ) { //Check the portal is not in read only mode, throws exception if it is $this->checkGOCDBIsNotReadOnly(); // Validate the user has permission to add properties - $this->checkAuthorisedAPIIdentifier($service->getParentSite(), $authenticationIdentifier, $authenticationType); + $this->checkAuthorisedAPIIdentifier($service->getParentSite(), $authIdentifier, $authType); //Convert the property array into the format used by the webportal logic - #TODO: make the web portal use a more sensible format (e.g. array(key=> value), rather than array([1]=>key,array[2]=>value)) - $propArr=array(); + #TODO: make the web portal use a more sensible format + #(e.g. array(key=> value), rather than array([1]=>key,array[2]=>value)) + $propArr = array(); foreach ($propKVArr as $key => $value) { - $propArr[]= array(0=>$key,1=>$value); + $propArr[] = array(0 => $key,1 => $value); } //Add the properties @@ -1114,16 +1311,18 @@ public function addServicePropertiesAPI(\Service $service, array $propKVArr, $pr * @param bool $preventOverwrite * @throws \Exception */ - protected function addPropertiesLogic(\Service $service, array $propArr, $preventOverwrite = false) { - $existingProperties = $service->getServiceProperties (); + protected function addPropertiesLogic(\Service $service, array $propArr, $preventOverwrite = false) + { + $existingProperties = $service->getServiceProperties(); //We will use this variable to track the keys as we go along, this will be used check they are all unique later - $keys=array(); + $keys = array(); - //We will use this variable to track teh final number of properties and ensure we do not exceede the specified limit + // We will use this variable to track teh final number of properties and + // ensure we do not exceede the specified limit $propertyCount = sizeof($existingProperties); - foreach ( $propArr as $i => $prop ) { + foreach ($propArr as $prop) { /*Trim off trailing and leading whitspace - as we currently don't want this. *The input array is awkwardly formatted as keys didn't use to have to be unique. */ @@ -1136,9 +1335,9 @@ protected function addPropertiesLogic(\Service $service, array $propArr, $preven *we will want to edit the existing property later, rather than create it. */ $property = null; - foreach ( $existingProperties as $existProp ) { - if ($existProp->getKeyName () == $key) { - $property=$existProp; + foreach ($existingProperties as $existProp) { + if ($existProp->getKeyName() == $key) { + $property = $existProp; } } @@ -1148,39 +1347,48 @@ protected function addPropertiesLogic(\Service $service, array $propArr, $preven */ if (is_null($property)) { // validate key value + $validateArray = []; $validateArray ['NAME'] = $key; $validateArray ['VALUE'] = $value; - $this->validate ( $validateArray, 'serviceproperty' ); + $this->validate($validateArray, 'serviceproperty'); - $serviceProperty = new \ServiceProperty (); - $serviceProperty->setKeyName ( $key ); - $serviceProperty->setKeyValue ( $value ); - $service->addServicePropertyDoJoin ( $serviceProperty ); - $this->em->persist ( $serviceProperty ); + $serviceProperty = new \ServiceProperty(); + $serviceProperty->setKeyName($key); + $serviceProperty->setKeyValue($value); + $service->addServicePropertyDoJoin($serviceProperty); + $this->em->persist($serviceProperty); //increment the property counter to enable check against property limit $propertyCount++; } elseif (!$preventOverwrite) { - $this->editServicePropertyLogic($service, $property, array('SERVICEPROPERTIES'=>array('NAME'=>$key,'VALUE'=>$value))); + $this->editServicePropertyLogic( + $service, + $property, + array('SERVICEPROPERTIES' => array('NAME' => $key,'VALUE' => $value)) + ); } else { - throw new \Exception("A property with name \"$key\" already exists for this object, no properties were added."); + throw new \Exception( + "A property with name \"$key\" already exists for this object, no properties were added." + ); } - //Add the key to the keys array, to enable unique check - $keys[]=$key; + // Add the key to the keys array, to enable unique check + $keys[] = $key; } - //Keys should be unique, create an exception if they are not - if(count(array_unique($keys))!=count($keys)) { + // Keys should be unique, create an exception if they are not + if (count(array_unique($keys)) != count($keys)) { throw new \Exception( - "Property names should be unique. The requested new properties include multiple properties with the same name." + "Property names should be unique. The requested new properties " . + "include multiple properties with the same name." ); } - //Check to see if adding the new properties will exceed the max limit defined in local_info.xml, and throw an exception if so + // Check to see if adding the new properties will exceed the max limit + // defined in local_info.xml, and throw an exception if so $extensionLimit = \Factory::getConfigService()->getExtensionsLimit(); - if ($propertyCount > $extensionLimit){ + if ($propertyCount > $extensionLimit) { throw new \Exception("Property(s) could not be added due to the property limit of $extensionLimit"); } } @@ -1194,22 +1402,29 @@ protected function addPropertiesLogic(\Service $service, array $propArr, $preven * @param bool $preventOverwrite * @throws \Exception */ - public function addEndpointProperties(\EndpointLocation $endpoint, \User $user, array $propArr, $preventOverwrite = false) { + + public function addEndpointProperties( + \EndpointLocation $endpoint, + \User $user, + array $propArr, + $preventOverwrite = false + ) { + // Check the portal is not in read only mode, throws exception if it is - $this->checkPortalIsNotReadOnlyOrUserIsAdmin ($user); + $this->checkPortalIsNotReadOnlyOrUserIsAdmin($user); //Check the user has the requisite permissions - $this->validateAddEditDeleteActions ($user, $endpoint->getService()); + $this->validateAddEditDeleteActions($user, $endpoint->getService()); //Make the change - $this->em->getConnection ()->beginTransaction (); + $this->em->getConnection()->beginTransaction(); try { - $this->addEndpointPropertiesLogic($endpoint,$propArr,$preventOverwrite); - $this->em->flush (); - $this->em->getConnection ()->commit (); - } catch ( \Exception $e ) { - $this->em->getConnection ()->rollback (); - $this->em->close (); + $this->addEndpointPropertiesLogic($endpoint, $propArr, $preventOverwrite); + $this->em->flush(); + $this->em->getConnection()->commit(); + } catch (\Exception $e) { + $this->em->getConnection()->rollback(); + $this->em->close(); throw $e; } } @@ -1219,22 +1434,37 @@ public function addEndpointProperties(\EndpointLocation $endpoint, \User $user, * @param \EndpointLocation $service * @param array $propArr * @param bool $preventOverwrite - * @param string $authenticationType - * @param string $authenticationIdentifier + * @param string $authType + * @param string $authIdentifier * @throws \Exception */ - public function addEndpointPropertiesAPI(\EndpointLocation $endpoint, array $propKVArr, $preventOverwrite, $authenticationType, $authenticationIdentifier) { + + public function addEndpointPropertiesAPI( + \EndpointLocation $endpoint, + array $propKVArr, + $preventOverwrite, + $authType, + $authIdentifier + ) { + //Check the portal is not in read only mode, throws exception if it is $this->checkGOCDBIsNotReadOnly(); // Validate the user has permission to add properties - $this->checkAuthorisedAPIIdentifier($endpoint->getService()->getParentSite(), $authenticationIdentifier, $authenticationType); + + $this->checkAuthorisedAPIIdentifier( + $endpoint->getService()->getParentSite(), + $authIdentifier, + $authType + ); + //Convert the property array into the format used by the webportal logic - #TODO: make the web portal use a more sensible format (e.g. array(key=> value), rather than array([1]=>key,array[2]=>value)) - $propArr=array(); + # TODO: make the web portal use a more sensible format + # (e.g. array(key=> value), rather than array([1]=>key,array[2]=>value)) + $propArr = array(); foreach ($propKVArr as $key => $value) { - $propArr[]= array(0=>$key,1=>$value); + $propArr[] = array(0 => $key,1 => $value); } //Add the properties @@ -1258,16 +1488,24 @@ public function addEndpointPropertiesAPI(\EndpointLocation $endpoint, array $pro * @param bool $preventOverwrite * @throws \Exception */ - protected function addEndpointPropertiesLogic(\EndpointLocation $endpoint, array $propArr, $preventOverwrite = false) { - $existingProperties = $endpoint->getEndpointProperties (); - //We will use this variable to track the keys as we go along, this will be used check they are all unique later - $keys=array(); + protected function addEndpointPropertiesLogic( + \EndpointLocation $endpoint, + array $propArr, + $preventOverwrite = false + ) { + + $existingProperties = $endpoint->getEndpointProperties(); - //We will use this variable to track teh final number of properties and ensure we do not exceede the specified limit + // We will use this variable to track the keys as we go along, + // this will be used check they are all unique later + $keys = array(); + + // We will use this variable to track the final number of properties + // and ensure we do not exceede the specified limit $propertyCount = sizeof($existingProperties); - foreach ( $propArr as $i => $prop ) { + foreach ($propArr as $prop) { /*Trim off trailing and leading whitspace - as we currently don't want this. *The input array is awkwardly formatted as keys didn't use to have to be unique. */ @@ -1280,8 +1518,8 @@ protected function addEndpointPropertiesLogic(\EndpointLocation $endpoint, array *we will want to edit the existing property later, rather than create it. */ $property = null; - foreach ( $existingProperties as $existProp ) { - if ($existProp->getKeyName () == $key) { + foreach ($existingProperties as $existProp) { + if ($existProp->getKeyName() == $key) { $property = $existProp; } } @@ -1292,40 +1530,48 @@ protected function addEndpointPropertiesLogic(\EndpointLocation $endpoint, array */ if (is_null($property)) { // validate key value + $validateArray = []; $validateArray ['NAME'] = $key; $validateArray ['VALUE'] = $value; - $validateArray ['ENDPOINTID'] = $endpoint->getId (); - $this->validate ( $validateArray, 'endpointproperty' ); + $validateArray ['ENDPOINTID'] = $endpoint->getId(); + $this->validate($validateArray, 'endpointproperty'); - $property = new \EndpointProperty (); - $property->setKeyName ( $key ); - $property->setKeyValue ( $value ); - $endpoint->addEndpointPropertyDoJoin ( $property ); - $this->em->persist ( $property ); + $property = new \EndpointProperty(); + $property->setKeyName($key); + $property->setKeyValue($value); + $endpoint->addEndpointPropertyDoJoin($property); + $this->em->persist($property); //increment the property counter to enable check against property limit $propertyCount++; } elseif (!$preventOverwrite) { - $this->editEndpointPropertyLogic($endpoint->getService(), $property, array('ENDPOINTPROPERTIES'=>array('NAME'=>$key,'VALUE'=>$value))); + $this->editEndpointPropertyLogic( + $endpoint->getService(), + $property, + array('ENDPOINTPROPERTIES' => array('NAME' => $key,'VALUE' => $value)) + ); } else { - throw new \Exception("A property with name \"$key\" already exists for this object, no properties were added."); + throw new \Exception("A property with name \"$key\" already exists for " . + "this object, no properties were added."); } //Add the key to the keys array, to enable unique check - $keys[]=$key; + $keys[] = $key; } - //Keys should be unique, create an exception if they are not - if(count(array_unique($keys))!=count($keys)) { + // Keys should be unique, create an exception if they are not + if (count(array_unique($keys)) != count($keys)) { throw new \Exception( - "Property names should be unique. The requested new properties include multiple properties with the same name." + "Property names should be unique. " . + "The requested new properties include multiple properties with the same name." ); } - //Check to see if adding the new properties will exceed the max limit defined in local_info.xml, and throw an exception if so + // Check to see if adding the new properties will exceed the max limit + // defined in local_info.xml, and throw an exception if so $extensionLimit = \Factory::getConfigService()->getExtensionsLimit(); - if ($propertyCount > $extensionLimit){ + if ($propertyCount > $extensionLimit) { throw new \Exception("Property(s) could not be added due to the property limit of $extensionLimit"); } } @@ -1339,22 +1585,23 @@ protected function addEndpointPropertiesLogic(\EndpointLocation $endpoint, array * @param \User $user * @param array $propArr */ - public function deleteServiceProperties(\Service $service, \User $user, array $propArr) { + public function deleteServiceProperties(\Service $service, \User $user, array $propArr) + { // Check the portal is not in read only mode, throws exception if it is - $this->checkPortalIsNotReadOnlyOrUserIsAdmin ( $user ); + $this->checkPortalIsNotReadOnlyOrUserIsAdmin($user); //Ensure the user has the requisite permissions - $this->validateAddEditDeleteActions ( $user, $service ); + $this->validateAddEditDeleteActions($user, $service); //Make the change - $this->em->getConnection ()->beginTransaction (); + $this->em->getConnection()->beginTransaction(); try { $this->deleteServicePropertiesLogic($service, $propArr); - $this->em->flush (); - $this->em->getConnection ()->commit (); - } catch ( \Exception $e ) { - $this->em->getConnection ()->rollback (); - $this->em->close (); + $this->em->flush(); + $this->em->getConnection()->commit(); + } catch (\Exception $e) { + $this->em->getConnection()->rollback(); + $this->em->close(); throw $e; } } @@ -1366,7 +1613,8 @@ public function deleteServiceProperties(\Service $service, \User $user, array $p * @param \User $user * @param array $propArr */ - public function deleteServicePropertiesAPI(\Service $service, array $propArr, $authIdentifierType, $authIdentifier) { + public function deleteServicePropertiesAPI(\Service $service, array $propArr, $authIdentifierType, $authIdentifier) + { //Check the portal is not in read only mode, throws exception if it is $this->checkGOCDBIsNotReadOnly(); @@ -1397,19 +1645,20 @@ public function deleteServicePropertiesAPI(\Service $service, array $propArr, $a * @param \Service $service * @param array $propArr */ - protected function deleteServicePropertiesLogic(\Service $service, array $propArr) { - foreach ( $propArr as $prop ) { + protected function deleteServicePropertiesLogic(\Service $service, array $propArr) + { + foreach ($propArr as $prop) { // throw new \Exception(var_dump($prop)); // check property is in service - if ($prop->getParentService () != $service) { - $id = $prop->getId (); - throw new \Exception ( "Property {$id} does not belong to the specified service" ); + if ($prop->getParentService() != $service) { + $id = $prop->getId(); + throw new \Exception("Property {$id} does not belong to the specified service"); } // Service is the owning side so remove elements from service. - $service->getServiceProperties ()->removeElement ( $prop ); + $service->getServiceProperties()->removeElement($prop); // Once relationship is removed delete the actual element - $this->em->remove ( $prop ); + $this->em->remove($prop); } } @@ -1421,22 +1670,23 @@ protected function deleteServicePropertiesLogic(\Service $service, array $propAr * @param \User $user * @param array $propArr */ - public function deleteEndpointProperties(\Service $service, \User $user, array $propArr) { + public function deleteEndpointProperties(\Service $service, \User $user, array $propArr) + { // Check the portal is not in read only mode, throws exception if it is - $this->checkPortalIsNotReadOnlyOrUserIsAdmin ( $user ); + $this->checkPortalIsNotReadOnlyOrUserIsAdmin($user); //Check the user has the rquisite permissions - $this->validateAddEditDeleteActions ($user, $service); + $this->validateAddEditDeleteActions($user, $service); // Carry out the change - $this->em->getConnection ()->beginTransaction (); + $this->em->getConnection()->beginTransaction(); try { $this->deleteEndpointPropertiesLogic($service, $propArr); - $this->em->flush (); - $this->em->getConnection ()->commit (); - } catch ( \Exception $e ) { - $this->em->getConnection ()->rollback (); - $this->em->close (); + $this->em->flush(); + $this->em->getConnection()->commit(); + } catch (\Exception $e) { + $this->em->getConnection()->rollback(); + $this->em->close(); throw $e; } } @@ -1448,8 +1698,14 @@ public function deleteEndpointProperties(\Service $service, \User $user, array $ * @param \User $user * @param array $propArr */ - public function deleteEndpointPropertiesAPI(\EndpointLocation $endpoint, array $propArr, $authIdentifierType, $authIdentifier) { - //Check the portal is not in read only mode, throws exception if it is + + public function deleteEndpointPropertiesAPI( + \EndpointLocation $endpoint, + array $propArr, + $authIdentifierType, + $authIdentifier + ) { + // Check the portal is not in read only mode, throws exception if it is $this->checkGOCDBIsNotReadOnly(); $parentService = $endpoint->getService(); @@ -1484,27 +1740,27 @@ public function deleteEndpointPropertiesAPI(\EndpointLocation $endpoint, array $ * @param \Service $service * @param array $propArr */ - protected function deleteEndpointPropertiesLogic(\Service $service, array $propArr) { - foreach ( $propArr as $prop ) { - + protected function deleteEndpointPropertiesLogic(\Service $service, array $propArr) + { + foreach ($propArr as $prop) { // check endpoint property has a parent endpoint - $endpoint = $prop->getParentEndpoint (); + $endpoint = $prop->getParentEndpoint(); if ($endpoint == null) { - $id = $prop->getId (); - throw new \Exception ( "Property {$id} does not have a parent endpoint" ); + $id = $prop->getId(); + throw new \Exception("Property {$id} does not have a parent endpoint"); } if ($endpoint->getService() != $service) { - $id = $prop->getId (); - throw new \Exception ( + $id = $prop->getId(); + throw new \Exception( "Property {$id} does not belong to an endpoint of the specified service" ); } // Endoint is the owning side so remove elements from endpoint. - $endpoint->getEndpointProperties ()->removeElement ( $prop ); + $endpoint->getEndpointProperties()->removeElement($prop); // Once relationship is removed delete the actual element - $this->em->remove ( $prop ); + $this->em->remove($prop); } } @@ -1519,22 +1775,23 @@ protected function deleteEndpointPropertiesLogic(\Service $service, array $propA * @param \ServiceProperty $prop * @param array $newValues */ - public function editServiceProperty(\Service $service, \User $user, \ServiceProperty $prop, $newValues) { + public function editServiceProperty(\Service $service, \User $user, \ServiceProperty $prop, $newValues) + { // Check the portal is not in read only mode, throws exception if it is - $this->checkPortalIsNotReadOnlyOrUserIsAdmin ( $user ); + $this->checkPortalIsNotReadOnlyOrUserIsAdmin($user); // Validate the user has permission to edit properties - $this->validateAddEditDeleteActions ( $user, $service ); + $this->validateAddEditDeleteActions($user, $service); //Make the change - $this->em->getConnection ()->beginTransaction (); + $this->em->getConnection()->beginTransaction(); try { $this->editServicePropertyLogic($service, $prop, $newValues); - $this->em->flush (); - $this->em->getConnection ()->commit (); - } catch ( \Exception $ex ) { - $this->em->getConnection ()->rollback (); - $this->em->close (); + $this->em->flush(); + $this->em->getConnection()->commit(); + } catch (\Exception $ex) { + $this->em->getConnection()->rollback(); + $this->em->close(); throw $ex; } } @@ -1549,22 +1806,23 @@ public function editServiceProperty(\Service $service, \User $user, \ServiceProp * @param \ServiceProperty $prop * @param array $newValues */ - protected function editServicePropertyLogic(\Service $service, \ServiceProperty $prop, $newValues) { + protected function editServicePropertyLogic(\Service $service, \ServiceProperty $prop, $newValues) + { - $this->validate ( $newValues ['SERVICEPROPERTIES'], 'serviceproperty' ); + $this->validate($newValues ['SERVICEPROPERTIES'], 'serviceproperty'); //We don't currently want trailing or leading whitespace, so we trim it $keyname = trim($newValues['SERVICEPROPERTIES']['NAME']); $keyvalue = trim($newValues['SERVICEPROPERTIES']['VALUE']); // Check that the prop is from the service - if ($prop->getParentService () != $service) { - $id = $prop->getId (); - throw new \Exception ( "Property {$id} does not belong to the specified service" ); + if ($prop->getParentService() != $service) { + $id = $prop->getId(); + throw new \Exception("Property {$id} does not belong to the specified service"); } //If the properties key has changed, check there isn't an existing property with that key - if ($keyname != $prop->getKeyName()){ + if ($keyname != $prop->getKeyName()) { $existingProperties = $service->getServiceProperties(); foreach ($existingProperties as $existingProp) { if ($existingProp->getKeyName() == $keyname) { @@ -1574,10 +1832,10 @@ protected function editServicePropertyLogic(\Service $service, \ServiceProperty } // Set the service propertys new member variables - $prop->setKeyName ( $keyname ); - $prop->setKeyValue ( $keyvalue ); + $prop->setKeyName($keyname); + $prop->setKeyValue($keyvalue); - $this->em->merge ( $prop ); + $this->em->merge($prop); } /** @@ -1592,22 +1850,23 @@ protected function editServicePropertyLogic(\Service $service, \ServiceProperty * @param array $newValues * @throws \Exception */ - public function editEndpointProperty(\Service $service, \User $user, \EndpointProperty $prop, $newValues) { + public function editEndpointProperty(\Service $service, \User $user, \EndpointProperty $prop, $newValues) + { // Check the portal is not in read only mode, throws exception if it is - $this->checkPortalIsNotReadOnlyOrUserIsAdmin ($user); + $this->checkPortalIsNotReadOnlyOrUserIsAdmin($user); // Validate the user has permission to edit properties - $this->validateAddEditDeleteActions ($user, $service); + $this->validateAddEditDeleteActions($user, $service); //Make the change - $this->em->getConnection ()->beginTransaction (); + $this->em->getConnection()->beginTransaction(); try { $this->editEndpointPropertyLogic($service, $prop, $newValues); - $this->em->flush (); - $this->em->getConnection ()->commit (); - } catch ( \Exception $ex ) { - $this->em->getConnection ()->rollback (); - $this->em->close (); + $this->em->flush(); + $this->em->getConnection()->commit(); + } catch (\Exception $ex) { + $this->em->getConnection()->rollback(); + $this->em->close(); throw $ex; } } @@ -1623,22 +1882,23 @@ public function editEndpointProperty(\Service $service, \User $user, \EndpointPr * @param array $newValues * @throws \Exception */ - protected function editEndpointPropertyLogic(\Service $service, \EndpointProperty $prop, $newValues) { + protected function editEndpointPropertyLogic(\Service $service, \EndpointProperty $prop, $newValues) + { - $this->validate ( $newValues ['ENDPOINTPROPERTIES'], 'endpointproperty' ); + $this->validate($newValues ['ENDPOINTPROPERTIES'], 'endpointproperty'); //We don't currently want trailing or leading whitespace, so we trim it $keyname = trim($newValues['ENDPOINTPROPERTIES']['NAME']); $keyvalue = trim($newValues['ENDPOINTPROPERTIES']['VALUE']); // Check that the prop is from the endpoint - if ($prop->getParentEndpoint ()->getService () != $service) { - $id = $prop->getId (); - throw new \Exception ( "Property {$id} does not belong to the specified service endpoint" ); + if ($prop->getParentEndpoint()->getService() != $service) { + $id = $prop->getId(); + throw new \Exception("Property {$id} does not belong to the specified service endpoint"); } //If the properties key has changed, check there isn't an existing property with that key - if ($keyname != $prop->getKeyName()){ + if ($keyname != $prop->getKeyName()) { $existingProperties = $prop->getParentEndpoint()->getEndpointProperties(); foreach ($existingProperties as $existingProp) { if ($existingProp->getKeyName() == $keyname) { @@ -1648,51 +1908,60 @@ protected function editEndpointPropertyLogic(\Service $service, \EndpointPropert } // Set the endpoints propertys new member variables - $prop->setKeyName ( $keyname ); - $prop->setKeyValue ( $keyvalue ); + $prop->setKeyName($keyname); + $prop->setKeyValue($keyvalue); - $this->em->merge ( $prop ); + $this->em->merge($prop); } /** * Deletes a service * - * @param \Service $s To be deleted + * @param \Service $service To be deleted * @param \User $user Making the request * @param $isTest when unit testing this allows for true to be supplied and this method * will not attempt to archive the service which can easily cause errors for service objects without * a full set of information * @throws \Exception If user can't be authorized */ - public function deleteService(\Service $s, \User $user = null, $isTest = false) { + public function deleteService(\Service $service, \User $user = null, $isTest = false) + { require_once __DIR__ . '/../DAOs/ServiceDAO.php'; // Check the portal is not in read only mode, throws exception if it is - $this->checkPortalIsNotReadOnlyOrUserIsAdmin ( $user ); + $this->checkPortalIsNotReadOnlyOrUserIsAdmin($user); - if ($this->roleActionAuthorisationService->authoriseAction ( \Action::EDIT_OBJECT, $s->getParentSite (), $user )->getGrantAction () == FALSE) { - throw new \Exception ( "You don't have permission to delete service." ); + + if ( + $this->roleAAS->authoriseAction( + \Action::EDIT_OBJECT, + $service->getParentSite(), + $user + )->getGrantAction() == false + ) { + throw new \Exception("You don't have permission to delete service."); } - $this->em->getConnection ()->beginTransaction (); + + $this->em->getConnection()->beginTransaction(); try { - $serviceDAO = new \ServiceDAO (); - $serviceDAO->setEntityManager ( $this->em ); + $serviceDAO = new \ServiceDAO(); + $serviceDAO->setEntityManager($this->em); // Archive site - if this is a test then don't archive if ($isTest == false) { // Create entry in audit table - $serviceDAO->addServiceToArchive ( $s, $user ); + $serviceDAO->addServiceToArchive($service, $user); } // Break links with downtimes and remove downtimes only associated // with this service, then remove service - $serviceDAO->removeService ( $s ); + $serviceDAO->removeService($service); - $this->em->flush (); - $this->em->getConnection ()->commit (); - } catch ( \Exception $e ) { - $this->em->getConnection ()->rollback (); - $this->em->close (); + $this->em->flush(); + $this->em->getConnection()->commit(); + } catch (\Exception $e) { + $this->em->getConnection()->rollback(); + $this->em->close(); throw $e; } } @@ -1702,53 +1971,52 @@ public function deleteService(\Service $s, \User $user = null, $isTest = false) * * If the service is already a child of the site, no move is attempted. * - * @param \Service $Service Service to move. - * @param \Site $Site Target site to move the service to. + * @param \Service $service Service to move. + * @param \Site $site Target site to move the service to. * @param \User $user * @throws \Exception * @throws \LogicException */ - public function moveService(\Service $Service, \Site $Site, \User $user = null) { + public function moveService(\Service $service, \Site $site, \User $user = null) + { // Throws exception if user is not an administrator - $this->checkUserIsAdmin ( $user ); + $this->checkUserIsAdmin($user); - $this->em->getConnection ()->beginTransaction (); // suspend auto-commit + $this->em->getConnection()->beginTransaction(); // suspend auto-commit try { // If the site or service have no ID - throw logic exception - $site_id = $Site->getId (); - if (empty ( $site_id )) { - throw new \LogicException ( 'Site has no ID' ); + $siteId = $site->getId(); + if (empty($siteId)) { + throw new \LogicException('Site has no ID'); } - $Service_id = $Service->getId (); - if (empty ( $Service_id )) { - throw new \LogicException ( 'Service has no ID' ); + $serviceId = $service->getId(); + if (empty($serviceId)) { + throw new \LogicException('Service has no ID'); } // find old site - $old_Site = $Service->getParentSite (); + $oldSite = $service->getParentSite(); // If the Site has changed, then we move the service. - if ($old_Site != $Site) { - + if ($oldSite != $site) { // Remove the service from the old site if it has an old site - if (! empty ( $old_Site )) { - - $old_Site->getServices ()->removeElement ( $Service ); + if (! empty($oldSite)) { + $oldSite->getServices()->removeElement($service); } // Add Service to new Site - $Site->addServiceDoJoin ( $Service ); + $site->addServiceDoJoin($service); // persist - $this->em->merge ( $Site ); - $this->em->merge ( $old_Site ); + $this->em->merge($site); + $this->em->merge($oldSite); } // close if - $this->em->flush (); - $this->em->getConnection ()->commit (); - } catch ( \Exception $e ) { - $this->em->getConnection ()->rollback (); - $this->em->close (); + $this->em->flush(); + $this->em->getConnection()->commit(); + } catch (\Exception $e) { + $this->em->getConnection()->rollback(); + $this->em->close(); throw $e; } } @@ -1758,59 +2026,48 @@ public function moveService(\Service $Service, \Site $Site, \User $user = null) * * @returns boolean */ - public function servicePropSet (\Service $service, $servicePropName) { - switch (strtolower($servicePropName)) { - case 'hostname':{ - $propValue = $service->getHostName(); - break; - } - case 'description':{ - $propValue = $service->getDescription(); - break; - } - case 'url':{ - $propValue = $service->getUrl(); - break; - } - case 'host_dn':{ - $propValue = $service->getDn(); - break; - } - case 'host_ip':{ - $propValue = $service->getIpAddress(); - break; - } - case 'host_ip_v6':{ - $propValue = $service->getIpV6Address(); - break; - } - case 'host_os':{ - $propValue = $service->getOperatingSystem(); - break; - } - case 'email':{ - $propValue = $service->getEmail(); - break; - } - case 'host_arch':{ - $propValue = $service->getArchitecture(); - break; - } - case 'monitored': - case 'beta': - case 'production': - case 'notify': - { - #booleans are always set - return true; - } - default:{ - throw new \Exception("Internal error: service property name ($servicePropName) not ". - "recognised. Please contact a GOCDB administrator and report this error."); - } - } - - return !empty($propValue); + public function servicePropSet(\Service $service, $servicePropName) + { + switch (strtolower($servicePropName)) { + case 'hostname': + $propValue = $service->getHostName(); + break; + case 'description': + $propValue = $service->getDescription(); + break; + case 'url': + $propValue = $service->getUrl(); + break; + case 'host_dn': + $propValue = $service->getDn(); + break; + case 'host_ip': + $propValue = $service->getIpAddress(); + break; + case 'host_ip_v6': + $propValue = $service->getIpV6Address(); + break; + case 'host_os': + $propValue = $service->getOperatingSystem(); + break; + case 'email': + $propValue = $service->getEmail(); + break; + case 'host_arch': + $propValue = $service->getArchitecture(); + break; + case 'monitored': + case 'beta': + case 'production': + case 'notify': + #booleans are always set + return true; + default: + throw new \Exception("Internal error: service property name ($servicePropName) not " . + "recognised. Please contact a GOCDB administrator and report this error."); + } + + return !empty($propValue); } /** @@ -1821,16 +2078,17 @@ public function servicePropSet (\Service $service, $servicePropName) { * @throws Exception * @return \Endpoint */ - public function addEndpoint($values, \User $user = null) { + public function addEndpoint($values, \User $user = null) + { // Check the portal is not in read only mode, throws exception if it is - $this->checkPortalIsNotReadOnlyOrUserIsAdmin ( $user ); - $this->validate ( $values ['SERVICEENDPOINT'], 'endpoint' ); + $this->checkPortalIsNotReadOnlyOrUserIsAdmin($user); + $this->validate($values ['SERVICEENDPOINT'], 'endpoint'); $serviceID = $values ['SERVICEENDPOINT'] ['SERVICE']; - $service = $this->getService ( $serviceID ); + $service = $this->getService($serviceID); // check user has permission to edit endpoint's service - $this->validateAddEditDeleteActions ( $user, $service ); + $this->validateAddEditDeleteActions($user, $service); $name = $values ['SERVICEENDPOINT'] ['NAME']; $url = $values ['SERVICEENDPOINT'] ['URL']; @@ -1841,10 +2099,10 @@ public function addEndpoint($values, \User $user = null) { if ($values ['SERVICEENDPOINT'] ['INTERFACENAME'] != '') { $interfaceName = $values ['SERVICEENDPOINT'] ['INTERFACENAME']; } else { - $interfaceName = ( string ) $service->getServiceType (); + $interfaceName = (string) $service->getServiceType(); } - if($values['IS_MONITORED']) { + if ($values['IS_MONITORED']) { $monitored = true; } else { $monitored = false; @@ -1867,13 +2125,24 @@ public function addEndpoint($values, \User $user = null) { * @param string $authIdentifier Authentication string from API * @param string $authIdentifierType Type of Authentication string */ - public function addEndpointApi(\Service $service, $name, $url, $interfaceName, $description, $email, $monitored, $authIdentifier, $authIdentifierType) { - //Check the portal is not in read only mode, throws exception if it is - $this->checkGOCDBIsNotReadOnly(); - $this->checkAuthorisedAPIIdentifier($service->getParentSite(), $authIdentifier, $authIdentifierType); + public function addEndpointApi( + \Service $service, + $name, + $url, + $interfaceName, + $description, + $email, + $monitored, + $authIdentifier, + $authIdentifierType + ) { + // Check the portal is not in read only mode, throws exception if it is + $this->checkGOCDBIsNotReadOnly(); + + $this->checkAuthorisedAPIIdentifier($service->getParentSite(), $authIdentifier, $authIdentifierType); - $this->addEndpointLogic($service, $name, $url, $interfaceName, $description, $email, $monitored); + $this->addEndpointLogic($service, $name, $url, $interfaceName, $description, $email, $monitored); } /** @@ -1889,36 +2158,37 @@ public function addEndpointApi(\Service $service, $name, $url, $interfaceName, $ * @param boolean $monitored whether endpoint is monitored * @throws \Exception */ - private function addEndpointLogic (\Service $service, $name, $url, $interfaceName, $description, $email, $monitored){ + private function addEndpointLogic(\Service $service, $name, $url, $interfaceName, $description, $email, $monitored) + { - if (empty ( $name )) { - throw new \Exception ( "An endpoint must have a name." ); - } + if (empty($name)) { + throw new \Exception("An endpoint must have a name."); + } // check endpoint's name is unique under the service - if($this->endpointWithNameExists($service, $name)){ - throw new \Exception ( "Please provide a unique name for this Service Endpoint." ); - } - - $this->em->getConnection ()->beginTransaction (); - try { - $endpoint = new \EndpointLocation (); - $endpoint->setName($name); - $endpoint->setUrl($url); - $endpoint->setInterfaceName($interfaceName); - $endpoint->setDescription($description); - $endpoint->setEmail($email); - $endpoint->setMonitored($monitored); - $service->addEndpointLocationDoJoin($endpoint); - $this->em->persist($endpoint); - - $this->em->flush(); - $this->em->getConnection()->commit(); - } catch(\Exception $e) { - $this->em->getConnection()->rollback(); - $this->em->close(); - throw $e; - } - return $endpoint; + if ($this->endpointWithNameExists($service, $name)) { + throw new \Exception("Please provide a unique name for this Service Endpoint."); + } + + $this->em->getConnection()->beginTransaction(); + try { + $endpoint = new \EndpointLocation(); + $endpoint->setName($name); + $endpoint->setUrl($url); + $endpoint->setInterfaceName($interfaceName); + $endpoint->setDescription($description); + $endpoint->setEmail($email); + $endpoint->setMonitored($monitored); + $service->addEndpointLocationDoJoin($endpoint); + $this->em->persist($endpoint); + + $this->em->flush(); + $this->em->getConnection()->commit(); + } catch (\Exception $e) { + $this->em->getConnection()->rollback(); + $this->em->close(); + throw $e; + } + return $endpoint; } /** @@ -1931,17 +2201,19 @@ private function addEndpointLogic (\Service $service, $name, $url, $interfaceNam * @throws \Exception * @throws Exception */ - public function editEndpoint(\User $user, \EndpointLocation $endpoint, $newValues) { + public function editEndpoint(\User $user, \EndpointLocation $endpoint, $newValues) + { // Check the portal is not in read only mode, throws exception if it is - $this->checkPortalIsNotReadOnlyOrUserIsAdmin ( $user ); - $this->validate ( $newValues ['SERVICEENDPOINT'], 'endpoint' ); + $this->checkPortalIsNotReadOnlyOrUserIsAdmin($user); + $this->validate($newValues ['SERVICEENDPOINT'], 'endpoint'); - //We shouldn't rely on the service being given to the function - this allows bugs to be introduced that feed the wrong service - //TODO: remove the $service from the endpoint parameters - $service = $endpoint->getService (); + // We shouldn't rely on the service being given to the function - this + // allows bugs to be introduced that feed the wrong service + // TODO: remove the $service from the endpoint parameters + $service = $endpoint->getService(); // check user has permission to edit endpoint's service - $this->validateAddEditDeleteActions ( $user, $service ); + $this->validateAddEditDeleteActions($user, $service); $name = $newValues ['SERVICEENDPOINT'] ['NAME']; $url = $newValues ['SERVICEENDPOINT'] ['URL']; @@ -1949,7 +2221,7 @@ public function editEndpoint(\User $user, \EndpointLocation $endpoint, $newValue $email = $newValues['SERVICEENDPOINT']['EMAIL']; $interfaceName = $newValues ['SERVICEENDPOINT'] ['INTERFACENAME']; - if($newValues['IS_MONITORED']) { + if ($newValues['IS_MONITORED']) { $monitored = true; } else { $monitored = false; @@ -1971,14 +2243,30 @@ public function editEndpoint(\User $user, \EndpointLocation $endpoint, $newValue * @param string $authIdentifier Authentication string from API * @param string $authIdentifierType Type of Authentication string */ - public function editEndpointApi (\EndpointLocation $endpoint, $name, $url, $interfaceName, $description, $email, $monitored, $authIdentifier, $authIdentifierType) { - //Check the portal is not in read only mode, throws exception if it is - $this->checkGOCDBIsNotReadOnly(); - $this->checkAuthorisedAPIIdentifier($endpoint->getService()->getParentSite(), $authIdentifier, $authIdentifierType); + public function editEndpointApi( + \EndpointLocation $endpoint, + $name, + $url, + $interfaceName, + $description, + $email, + $monitored, + $authIdentifier, + $authIdentifierType + ) { + // Check the portal is not in read only mode, throws exception if it is + $this->checkGOCDBIsNotReadOnly(); + + + $this->checkAuthorisedAPIIdentifier( + $endpoint->getService()->getParentSite(), + $authIdentifier, + $authIdentifierType + ); - $this->editEndpointLogic($endpoint, $name, $url, $interfaceName, $description, $email, $monitored); + $this->editEndpointLogic($endpoint, $name, $url, $interfaceName, $description, $email, $monitored); } /** @@ -1993,44 +2281,54 @@ public function editEndpointApi (\EndpointLocation $endpoint, $name, $url, $inte * @param boolean $monitored whether endpoint is monitored * @throws \Exception */ - private function editEndpointLogic (\EndpointLocation $endpoint, $name, $url, $interfaceName, $description, $email, $monitored){ - $service = $endpoint->getService (); - if (empty ( $name )) { - throw new \Exception ( "An endpoint must have a name." ); - } + private function editEndpointLogic( + \EndpointLocation $endpoint, + $name, + $url, + $interfaceName, + $description, + $email, + $monitored + ) { + + $service = $endpoint->getService(); + + if (empty($name)) { + throw new \Exception("An endpoint must have a name."); + } //if no interface name is provided, default to service type - if ($interfaceName == '') { - $interfaceName = ( string ) $service->getServiceType (); - } + if ($interfaceName == '') { + $interfaceName = (string) $service->getServiceType(); + } // check endpoint's name is unique under the service - foreach ( $service->getEndpointLocations () as $endpointL ) { - // exclude itself - if ($endpoint != $endpointL && $endpointL->getName () == $name) { - throw new \Exception ( "Please provide a unique name for this endpoint." ); - } - } - - $this->em->getConnection ()->beginTransaction (); - - try { - // Set the endpoints new member variables - $endpoint->setName ( $name ); - $endpoint->setUrl ( $url ); - $endpoint->setInterfaceName ( $interfaceName ); - $endpoint->setDescription ( $description ); - $endpoint->setEmail($email); - $endpoint->setMonitored($monitored); - $this->em->merge ( $endpoint ); - $this->em->flush (); - $this->em->getConnection ()->commit (); - } catch ( \Exception $ex ) { - $this->em->getConnection ()->rollback (); - $this->em->close (); - throw $ex; - } + foreach ($service->getEndpointLocations() as $endpointL) { + // exclude itself + if ($endpoint != $endpointL && $endpointL->getName() == $name) { + throw new \Exception("Please provide a unique name for this endpoint."); + } + } + + $this->em->getConnection()->beginTransaction(); + + try { + // Set the endpoints new member variables + $endpoint->setName($name); + $endpoint->setUrl($url); + $endpoint->setInterfaceName($interfaceName); + $endpoint->setDescription($description); + $endpoint->setEmail($email); + $endpoint->setMonitored($monitored); + $this->em->merge($endpoint); + $this->em->flush(); + $this->em->getConnection()->commit(); + } catch (\Exception $ex) { + $this->em->getConnection()->rollback(); + $this->em->close(); + throw $ex; + } } /** @@ -2040,15 +2338,16 @@ private function editEndpointLogic (\EndpointLocation $endpoint, $name, $url, $i * @param \User $user * @throws Exception */ - public function deleteEndpoint(\EndpointLocation $endpoint, \User $user) { + public function deleteEndpoint(\EndpointLocation $endpoint, \User $user) + { // Check the portal is not in read only mode, throws exception if it is - $this->checkPortalIsNotReadOnlyOrUserIsAdmin ( $user ); + $this->checkPortalIsNotReadOnlyOrUserIsAdmin($user); - $service = $endpoint->getService (); + $service = $endpoint->getService(); // check user has permission to edit endpoint's service - $this->validateAddEditDeleteActions ( $user, $service ); + $this->validateAddEditDeleteActions($user, $service); $this->deleteEndpointLogic($endpoint); } @@ -2056,43 +2355,51 @@ public function deleteEndpoint(\EndpointLocation $endpoint, \User $user) { /** * Function called from API to delete an endpoint * - * @param EndpointLocation $endpoint endpoint to be deleted - * @param Service $service service of endpoint being deleted + * @param \EndpointLocation $endpoint endpoint to be deleted + * @param \Service $service service of endpoint being deleted * @thows Exception */ - public function deleteEndpointAPI (\EndpointLocation $endpoint, $authIdentifier, $authIdentifierType) { - //Check the portal is not in read only mode, throws exception if it is - $this->checkGOCDBIsNotReadOnly(); + public function deleteEndpointAPI(\EndpointLocation $endpoint, $authIdentifier, $authIdentifierType) + { + // Check the portal is not in read only mode, throws exception if it is + $this->checkGOCDBIsNotReadOnly(); + + // Check authorisation + + $this->checkAuthorisedAPIIdentifier( + $endpoint->getService()->getParentSite(), + $authIdentifier, + $authIdentifierType + ); - //Check authorisation - $this->checkAuthorisedAPIIdentifier($endpoint->getService()->getParentSite(), $authIdentifier, $authIdentifierType); - //Make the change - $this->deleteEndpointLogic($endpoint); + // Make the change + $this->deleteEndpointLogic($endpoint); } /** * Logic to delete an endpoint, abstracted array from authorisation and validation * - * @param EndpointLocation $endpoint endpoint to delete - * @throws Exception + * @param \EndpointLocation $endpoint endpoint to delete + * @throws \Exception */ - private function deleteEndpointLogic (\EndpointLocation $endpoint) { - require_once __DIR__ . '/../DAOs/ServiceDAO.php'; - - $this->em->getConnection ()->beginTransaction (); - try { - $serviceDAO = new \ServiceDAO (); - $serviceDAO->setEntityManager ( $this->em ); - $serviceDAO->removeEndpoint ( $endpoint ); - - $this->em->flush (); - $this->em->getConnection ()->commit (); - } catch ( \Exception $e ) { - $this->em->getConnection ()->rollback (); - $this->em->close (); - throw $e; - } + private function deleteEndpointLogic(\EndpointLocation $endpoint) + { + require_once __DIR__ . '/../DAOs/ServiceDAO.php'; + + $this->em->getConnection()->beginTransaction(); + try { + $serviceDAO = new \ServiceDAO(); + $serviceDAO->setEntityManager($this->em); + $serviceDAO->removeEndpoint($endpoint); + + $this->em->flush(); + $this->em->getConnection()->commit(); + } catch (\Exception $e) { + $this->em->getConnection()->rollback(); + $this->em->close(); + throw $e; + } } /** @@ -2100,39 +2407,33 @@ private function deleteEndpointLogic (\EndpointLocation $endpoint) { * * @returns boolean */ - public function EndpointPropSet (\EndpointLocation $endpoint, $endpointPropName) { - switch (strtolower($endpointPropName)) { - case 'name':{ - $propValue = $endpoint->getName(); - break; - } - case 'url':{ - $propValue = $endpoint->getUrl(); - break; - } - case 'interfacename':{ - $propValue = $endpoint->getInterfaceName(); - break; - } - case 'description':{ - $propValue = $endpoint->getDescription(); - break; - } - case 'email':{ - $propValue = $endpoint->getEmail(); - break; - } - case 'monitored': { - #booleans are always set - return true; - } - default:{ - throw new \Exception("Internal error: endpoint property name ($endpointPropName) not ". - "recognised. Please contact a GOCDB administrator and report this error."); - } - } - - return !empty($propValue); + public function endpointPropSet(\EndpointLocation $endpoint, $endpointPropName) + { + switch (strtolower($endpointPropName)) { + case 'name': + $propValue = $endpoint->getName(); + break; + case 'url': + $propValue = $endpoint->getUrl(); + break; + case 'interfacename': + $propValue = $endpoint->getInterfaceName(); + break; + case 'description': + $propValue = $endpoint->getDescription(); + break; + case 'email': + $propValue = $endpoint->getEmail(); + break; + case 'monitored': + #booleans are always set + return true; + default: + throw new \Exception("Internal error: endpoint property name ($endpointPropName) not " . + "recognised. Please contact a GOCDB administrator and report this error."); + } + + return !empty($propValue); } /** @@ -2143,13 +2444,14 @@ public function EndpointPropSet (\EndpointLocation $endpoint, $endpointPropName) * @param string $name endpoint name being checked * @return boolean */ - public function endpointWithNameExists (\Service $service, $name) { - foreach ($service->getEndpointLocations() as $endpoint) { - if ($name == $endpoint->getName()){ - return true; + public function endpointWithNameExists(\Service $service, $name) + { + foreach ($service->getEndpointLocations() as $endpoint) { + if ($name == $endpoint->getName()) { + return true; + } } - } - return false; + return false; } /** @@ -2161,24 +2463,25 @@ public function endpointWithNameExists (\Service $service, $name) { * @return \Endpoint endpoint * @throws \Exception */ - public function getEndpointByName (\Service $service, $name) { - foreach ($service->getEndpointLocations() as $endpoint) { - if ($name == $endpoint->getName()){ - return $endpoint; + public function getEndpointByName(\Service $service, $name) + { + foreach ($service->getEndpointLocations() as $endpoint) { + if ($name == $endpoint->getName()) { + return $endpoint; + } } - } - - //If the endpoint wasn't found, throw exceptions - throw new \Exception("Endpoint not found"); + // If the endpoint wasn't found, throw exceptions + throw new \Exception("Endpoint not found"); } - private function checkNumberOfScopes($scopeIds) { - require_once __DIR__ . '/Config.php'; - $configService = new \org\gocdb\services\Config (); - $minumNumberOfScopes = $configService->getMinimumScopesRequired ( 'service' ); - if (sizeof ( $scopeIds ) < $minumNumberOfScopes) { - throw new \Exception ( "A service must have at least " . $minumNumberOfScopes . " optional scope(s) assigned to it." ); + private function checkNumberOfScopes($scopeIds) + { + $configService = new Config(); + $minumNumberOfScopes = $configService->getMinimumScopesRequired('service'); + if (sizeof($scopeIds) < $minumNumberOfScopes) { + throw new \Exception("A service must have at least " . $minumNumberOfScopes . + " optional scope(s) assigned to it."); } } @@ -2191,37 +2494,38 @@ private function checkNumberOfScopes($scopeIds) { * @param \Service $service * @return associative array */ - public function getScopesWithParentScopeInfo(\Service $service) { - $parentSite = $service->getParentSite (); - $parentScopes = $parentSite->getScopes (); - $childScopes = $service->getScopes (); + public function getScopesWithParentScopeInfo(\Service $service) + { + $parentSite = $service->getParentSite(); + $parentScopes = $parentSite->getScopes(); + $childScopes = $service->getScopes(); $parentScopesNames = array (); - foreach ( $parentScopes as $parentScope ) { - $parentScopesNames [] = $parentScope->getName (); + foreach ($parentScopes as $parentScope) { + $parentScopesNames[] = $parentScope->getName(); } $childScopesNames = array (); - foreach ( $childScopes as $childScope ) { - $childScopesNames [] = $childScope->getName (); + foreach ($childScopes as $childScope) { + $childScopesNames[] = $childScope->getName(); } - $sharedScopesNames = array_intersect ( $childScopesNames, $parentScopesNames ); + $sharedScopesNames = array_intersect($childScopesNames, $parentScopesNames); - $scopeNamesNotShared = array_diff ( $childScopesNames, $parentScopesNames ); - - $ScopeNamesAndParentShareInfo = array (); - foreach ( $sharedScopesNames as $sharedScopesName ) { - $ScopeNamesAndParentShareInfo [$sharedScopesName] = true; + $scopeNamesNotShared = array_diff($childScopesNames, $parentScopesNames); + // scopeNamesAndParentShareInfo + $shareInfo = array(); + foreach ($sharedScopesNames as $sharedScopesName) { + $shareInfo[$sharedScopesName] = true; } - foreach ( $scopeNamesNotShared as $scopeNameNotShared ) { - $ScopeNamesAndParentShareInfo [$scopeNameNotShared] = false; + foreach ($scopeNamesNotShared as $scopeNameNotShared) { + $shareInfo[$scopeNameNotShared] = false; } - // can be replaced with ksort($ScopeNamesAndParentShareInfo, SORT_NATURAL); in php>=5.5 - uksort ( $ScopeNamesAndParentShareInfo, 'strcasecmp' ); + // can be replaced with ksort($shareInfo, SORT_NATURAL); in php>=5.5 + uksort($shareInfo, 'strcasecmp'); - return $ScopeNamesAndParentShareInfo; + return $shareInfo; } /** @@ -2230,11 +2534,12 @@ public function getScopesWithParentScopeInfo(\Service $service) { * @param string $text string, usually "Y" or "N" * @return boolean */ - private function ptlTexToBool($text) { - if ($text == "Y") { - return true; - } else { - return false; - } + private function ptlTexToBool($text) + { + if ($text == "Y") { + return true; + } else { + return false; + } } } diff --git a/lib/Gocdb_Services/ServiceType.php b/lib/Gocdb_Services/ServiceType.php index 48d56a48e..5eabacef6 100644 --- a/lib/Gocdb_Services/ServiceType.php +++ b/lib/Gocdb_Services/ServiceType.php @@ -116,7 +116,7 @@ public function deleteServiceType(\ServiceType $serviceType, \User $user = null) * @param array $newValues array containing the name and description for the * new service type * @param \user $user User adding the service type, used for permissions check - * @return \org\gocdb\services\ServiceType returns created service type + * @return \ServiceType returns created service type */ public function addServiceType($values, \user $user = null){ //Check the portal is not in read only mode, throws exception if it is @@ -143,6 +143,8 @@ public function addServiceType($values, \user $user = null){ $serviceType->setName($values['Name']); //set description $serviceType->setDescription($values['Description']); + //set flag for monitoring exception allowed + $serviceType->setAllowMonitoringException($values['AllowMonitoringException']); $this->em->persist($serviceType); $this->em->flush(); @@ -186,6 +188,8 @@ public function editServiceType(\ServiceType $serviceType, $newValues, \User $us $serviceType->setName($newValues['Name']); //set description $serviceType->setDescription($newValues['Description']); + //flag for monitoring exception allowed + $serviceType->setAllowMonitoringException($newValues['AllowMonitoringException']); $this->em->merge($serviceType); $this->em->flush(); @@ -270,5 +274,3 @@ private function validate($serviceTypeData) { } } } - - diff --git a/lib/Gocdb_Services/Validate.php b/lib/Gocdb_Services/Validate.php index dc1d38464..03eaf332d 100644 --- a/lib/Gocdb_Services/Validate.php +++ b/lib/Gocdb_Services/Validate.php @@ -1,5 +1,7 @@ schemaXml = simplexml_load_file(__DIR__ . $this::SCHEMA_XML); + } + + /* Validates $fieldValue using validation settings from the GOCDB * - * Checks the particular object (specified by $Object_Name) for a field - * ($Field_Name) and gets the validation requirements for this field type. - * Returns a boolean value as to whether $Field_Value is valid for the field - * type specified in $Field_Name. + * Checks the particular object (specified by $objectName) for a field + * ($fieldName) and gets the validation requirements for this field type. + * Returns a boolean value as to whether $fieldValue is valid for the field + * type specified in $fieldName. */ - public function validate($Object_Name, $Field_Name, $Field_Value) + public function validate($objectName, $fieldName, $fieldValue) { //Check the length of the field value, if too long, throws exception - $this->checkFieldLength($Object_Name, $Field_Name, $Field_Value); + $this->checkFieldLength($objectName, $fieldName, $fieldValue); //Check the Type of the field value, where this is defined - $type = $this->Get_Field_value($Object_Name, $Field_Name, 'ftype'); + $type = $this->getFieldValue($objectName, $fieldName, 'ftype'); if (count($type) != 0) { - if (strtolower($type) == "string") { - if (!is_string($Field_Value)) { - throw new \Exception($Field_Name . " must be a string."); - } - } elseif (strtolower($type) == "boolean") { - if (!is_bool($Field_Value)) { - throw new \Exception($Field_Name . " must be a boolean."); + if (strtolower($type) == "string") { + if (!is_string($fieldValue)) { + throw new \Exception($fieldName . " must be a string."); + } + } elseif (strtolower($type) == "boolean") { + if (!is_bool($fieldValue)) { + throw new \Exception($fieldName . " must be a boolean."); + } + } else { + throw new \Exception("Internal error: validation of data of type $type " . + "is not supported by the validation service"); } - } else { - throw new \Exception("Internal error: validation of data of type $type is not supported by the validation service"); - } } - - $RegEx = $this->Get_Field_value($Object_Name, $Field_Name, 'regex'); - // If there are no checks to perform then $Field_Value must be valid - if(count($RegEx) == 0) + + $regEx = $this->getFieldValue($objectName, $fieldName, 'regex'); + // If there are no checks to perform then $fieldValue must be valid + if (count($regEx) == 0) { return true; + } - if(!preg_match($RegEx, $Field_Value)) { + if (!preg_match($regEx, $fieldValue)) { return false; } @@ -68,11 +83,12 @@ public function validate($Object_Name, $Field_Name, $Field_Value) * Checks the length of inputs against the length specified in the schema. * @throws \Exception */ - private function checkFieldLength($objectName, $fieldName, $fieldValue){ - $length = $this->Get_Field_value($objectName, $fieldName, 'length'); + private function checkFieldLength($objectName, $fieldName, $fieldValue) + { + $length = $this->getFieldValue($objectName, $fieldName, 'length'); - if(!count($length) == 0){ //only check length if the schema has a length specified in it - if(strlen($fieldValue)>$length or $length == 0){ + if (!count($length) == 0) { //only check length if the schema has a length specified in it + if (strlen($fieldValue) > $length or $length == 0) { throw new \Exception($fieldName . " may not be more than " . $length . " chracters in length"); } } @@ -83,37 +99,34 @@ private function checkFieldLength($objectName, $fieldName, $fieldValue){ * Format: $Checks[Check_Name] = $Check_Parameter * i.e. $Checks[Regular_Expression] = "[Y|N]" */ - private function Get_Field_value($Object_Name, $Field_Name, $valueType) + private function getFieldValue($objectName, $fieldName, $valueType) { - $Schema_XML = simplexml_load_file(__DIR__ . $this::SCHEMA_XML); - $Entity = $this->Find_Entity($Object_Name, $Schema_XML); - $Field = $this->Find_Field($Field_Name, $Entity); - return $Field->$valueType; + $entity = $this->findEntity($objectName, $this->schemaXml); + $field = $this->findField($fieldName, $entity); + return $field->$valueType; } - /* Search for the XML for $Object_Name within Schema XML + /* Search for the XML for $objectName within Schema XML * Throw an exeption if this isn't found. */ - private function Find_Entity($Object_Name, $Schema_XML) + private function findEntity($objectName, $schemaXml) { - foreach($Schema_XML->entity as $entity) - { - if ((string) $entity->name == $Object_Name) { + foreach ($schemaXml->entity as $entity) { + if ((string) $entity->name == $objectName) { return $entity; } } - throw new \Exception("Object type: $Object_Name not found in schema XML"); + throw new \Exception("Object type: $objectName not found in schema XML"); } - private function Find_Field($Field_Name, $Entity) + private function findField($fieldName, $entity) { - foreach($Entity->field as $Field) - { - if(strtoupper((string) $Field->fname) == strtoupper($Field_Name)) { - return $Field; + foreach ($entity->field as $field) { + if (strtoupper((string) $field->fname) == strtoupper($fieldName)) { + return $field; } } - throw new \Exception("Field Name: $Field_Name not found in schema XML"); + throw new \Exception("Field Name: $fieldName not found in schema XML"); } } diff --git a/lib/MonologConf.php b/lib/MonologConf.php index 40915dcc4..4a69d2439 100644 --- a/lib/MonologConf.php +++ b/lib/MonologConf.php @@ -25,4 +25,3 @@ // You can now use your logger $log1->addDebug('log1 is now ready'); - diff --git a/phpcs.xml b/phpcs.xml index f7625d787..2d1349ca3 100644 --- a/phpcs.xml +++ b/phpcs.xml @@ -13,4 +13,10 @@ --> + + + + + + diff --git a/resources/ApplyScopeTagsToSitesAndServicesRunner.php b/resources/ApplyScopeTagsToSitesAndServicesRunner.php index 9f916206d..2971a4850 100644 --- a/resources/ApplyScopeTagsToSitesAndServicesRunner.php +++ b/resources/ApplyScopeTagsToSitesAndServicesRunner.php @@ -259,5 +259,3 @@ $em->close(); echo $e->getMessage(); } - - diff --git a/resources/ManageAPICredentials/ManageAPICredentialsActions.php b/resources/ManageAPICredentials/ManageAPICredentialsActions.php new file mode 100644 index 000000000..51e2b895b --- /dev/null +++ b/resources/ManageAPICredentials/ManageAPICredentialsActions.php @@ -0,0 +1,263 @@ +dryRun = $dryRun; + $this->entityManager = $entityManager; + $this->baseTime = $baseTime; + } + /** + * Find API credentials unused for a number of months. + * + * Find API credentials which have not been used for a number of months prior to a given base time based + * on the credential property lastUseTime. + * + * @param int $threshold The number of months of no-use prior to $baseTime to use for selection + */ + public function getCreds($threshold, $propertyName) + { + $qbl = $this->entityManager->createQueryBuilder(); + + $qbl->select('cred') + ->from('APIAuthentication', 'cred') + ->where($qbl->expr()->isNotNull("cred.user")) // cope with legacy entities + ->andWhere('cred.' . $propertyName . '< :threshold'); + + $timeThresh = clone $this->baseTime; + + if ($threshold > 0) { + $timeThresh->sub(new DateInterval("P" . $threshold . "M")); + }; + + $qbl->setParameter('threshold', $timeThresh->format('Y-m-d 00:00:00')); + + $creds = $qbl->getQuery()->getResult(); + + return $creds; + } + /** + * Select API credentials for deletion. + * + * Find API credentials which have not been used for a given number of months + * and delete them or, if dry-run option is true, generate a summary report + * of the credentils found. + * + * @param array $creds Array of credentials to process. + * @param \Doctrine\Orm\EntityManager $entitymanager A valid Doctrine Entity Manager + * @param \DateTime $baseTime Time from which interval of no-use is measured + * @param int $deleteThreshold The number of months of no-use which will trigger deletion + * @return array Credentials which were not deleted. + */ + public function deleteCreds($creds, $deleteThreshold) + { + $deletedCreds = []; + + $serv = new APIAuthenticationService(); + $serv->setEntityManager($this->entityManager); + + /* @var $apiCred APIAuthentication */ + foreach ($creds as $apiCred) { + if ($this->isOverThreshold($apiCred, $this->baseTime, $deleteThreshold)) { + $deletedCreds[] = $apiCred; + if (!$this->dryRun) { + $serv->deleteAPIAuthentication($apiCred); + } + } + } + if ($this->dryRun) { + $this->reportDryRun($deletedCreds, "deleting"); + } + + return array_udiff($creds, $deletedCreds, array($this, 'compareCredIds')); + } + /** + * Send of warning emails where credentials have not been used for a given number of months + * + * Find API credentials from the input array which have not been used for a given number of months + * and send emails to the owners and site address, taken from the credential object, + * warning of impending deletion if the period of no-use reaches a given threshold. + * If dry-run option is true, generate a summary report of the credentials found + * instead of sending emails. + * + * @param array $creds Array of credentials to process. + * @param int $warningThreshold The number of months of no-use which triggers warning emails + * @param int $deleteThreshold The number of months of no-use which will trigger deletion + * @param string $fromEmail Email address to use as sender's (From:) address + * @param string $replyToEmail Email address for replies (Reply-To:) + * @return array Array of credentials identifed for sending warning emails + */ + public function warnUsers( + $creds, + $warningThreshold, + $deletionThreshold, + $fromEmail, + $replyToEmail + ) { + $warnedCreds = []; + + /* @var $api APIAuthentication */ + foreach ($creds as $apiCred) { + // The credentials list is pre-selected based on the given threshold in the query + // so this check is probably redundant. + if ($this->isOverThreshold($apiCred, $this->baseTime, $warningThreshold)) { + $lastUsed = $apiCred->getLastUseTime(); + $lastUseMonths = $this->baseTime->diff($lastUsed)->format('%m'); + + if (!$this->dryRun) { + $this->sendWarningEmail( + $fromEmail, + $replyToEmail, + $apiCred, + intval($lastUseMonths), + $deletionThreshold + ); + } + + $warnedCreds[] = $apiCred; + } + } + + if ($this->dryRun) { + $this->reportDryRun($warnedCreds, "sending warning emails"); + } + + return array_udiff($creds, $warnedCreds, array($this, 'compareCredIds')); + } +/** + * @return boolean true if the credential has not been used within $threshold months, else false + */ + private function isOverThreshold(APIAuthentication $cred, DateTime $baseTime, $threshold) + { + $lastUsed = $cred->getLastUseTime(); + + $diffTime = $baseTime->diff($lastUsed); + $lastUseMonths = ($diffTime->y * 12) + $diffTime->m; + + return $lastUseMonths >= $threshold; + } +/** + * Helper function to check if two API credentials have the same id. + * + * @return integer zero if equal, -1 if id1 < id2, 1 if id1 > id2 + * +*/ + private function compareCredIds(APIAuthentication $cred1, APIAuthentication $cred2) + { + $id1 = $cred1->getId(); + $id2 = $cred2->getId(); + + if ($id1 == $id2) { + return 0; + }; + + return $id1 > $id2 ? 1 : -1; + } + +/** + * Format and send warning emails. + * + * Send emails to API credential owner and the registered site address warning of impending credential deletion + * if the credential remains unused until a given threshold of months. + * + * @param string $fromEmail Email address to use as sender's (From:) address + * @param string $replyToEmail Email address for replies (Reply-To:) + * @param \APIAuthentication $api Credential to warn about + * @param int $elapsedMonths The number of months of non-use so far. + * @param int $deleteionThreshold The number of months of no-use which will trigger deletion if reached. + * @return void + */ + private function sendWarningEmail( + $fromEmail, + $replyToEmail, + \APIAuthentication $api, + $elapsedMonths, + $deletionThreshold + ) { + $user = $api->getUser(); + $userEmail = $user->getEmail(); + $siteName = $api->getParentSite()->getShortName(); + $siteEmail = $siteName . ' <' . $api->getParentSite()->getEmail() . '>'; + + $headersArray = array ("From: $fromEmail", + "Cc: $siteEmail"); + if (strlen($replyToEmail) > 0 && $fromEmail !== $replyToEmail) { + $headersArray[] = "Reply-To: $replyToEmail"; + } + $headers = join("\r\n", $headersArray); + + $subject = "GOCDB: Site API credential deletion notice"; + + $body = "Dear " . $user->getForename() . ",\n\n" . + "The API credential associated with the following identifier registered\n" . + "at site $siteName has not been used during\n" . + "the last $elapsedMonths months and will be deleted if this period of inactivity\n" . + "reaches $deletionThreshold months.\n\n"; + + $body .= "Identifier: " . $api->getIdentifier() . "\n"; + $body .= "Owner email: " . $userEmail . "\n"; + + $body .= "\n"; + $body .= "Use of the credential will prevent its deletion.\n"; + $body .= "\nRegards,\nGOCDB Administrators\n"; + + // Send the email (or not, according to local configuration) + Factory::getEmailService()->send($userEmail, $subject, $body, $headers); + } +/** + * Generate a summary report. + * + * Generate a report to stdout summarising information about each credential in an array when + * a dry-run operation is in progress. + * + * @param array $creds Array of API credential objects to be summarised. + * @param string $text Brief description of the operation which would have been + * performed without dry-run to be included in the report. + * @return void + */ + private function reportDryRun(array $creds, $text) + { + if (count($creds) == 0) { + print("Dry run: No matching credentials found for $text.\n"); + return; + } + + print("Dry run: Found " . count($creds) . " credentials for $text.\n"); + + foreach ($creds as $api) { + print("Dry run: Processing credential id " . $api->getId() . "\n" . + " Identifier: " . $api->getIdentifier() . "\n" . + " User email: " . $api->getUser()->getEmail() . "\n" . + " Site: " . $api->getParentSite()->getShortName() . "\n" . + " Last used: " . $api->getLastUseTime() // DateTimeInterface::ISO8601 + ->format("Y-m-d\\TH:i:sO") . "\n" + ); + } + } +} diff --git a/resources/ManageAPICredentials/ManageUnusedAPICredentials.php b/resources/ManageAPICredentials/ManageUnusedAPICredentials.php new file mode 100644 index 000000000..88009d04f --- /dev/null +++ b/resources/ManageAPICredentials/ManageUnusedAPICredentials.php @@ -0,0 +1,74 @@ +setLocalInfoOverride($_SERVER['SERVER_NAME']); + +$configService = \Factory::getConfigService(); +$fromEmail = (string) $configService->getEmailFrom(); +$replyToEmail = (string) $configService->getEmailTo(); + +try { + $options = new ManageUnusedAPICredentialsOptions(); + + if ($options->isShowHelp()) { + return; + } + + $baseTime = new DateTime("now", new DateTimeZone('UTC')); + + $actions = new ManageAPICredentialsActions($options->isDryRun(), $entityManager, $baseTime); + + $creds = $actions->getCreds($options->getThreshold(), 'lastUseTime'); + + if ($options->isDeleteEnabled()) { + $creds = $actions->deleteCreds( + $creds, + $options->getDelete() + ); + } + + if ($options->isWarnEnabled()) { + $actions->warnUsers( + $creds, + $options->getWarn(), + $options->getDelete(), + $fromEmail, + $replyToEmail + ); + } +} catch (InvalidArgumentException $except) { + ManageUnusedAPICredentialsOptions::usage($except->getMessage()); +} diff --git a/resources/ManageAPICredentials/ManageUnusedAPICredentialsOptions.php b/resources/ManageAPICredentials/ManageUnusedAPICredentialsOptions.php new file mode 100644 index 000000000..8463c6e8b --- /dev/null +++ b/resources/ManageAPICredentials/ManageUnusedAPICredentialsOptions.php @@ -0,0 +1,140 @@ +getOptions(); + } + /** + * @throws \InvInvalidArgumentException If errors found in argument processing + */ + public function getOptions() + { + $shortOptions = 'hw:d:'; + + $longOptions = [ + 'help', + 'dry-run', + 'warning_threshold:', + 'deletion_threshold:' + ]; + + // Beware that getopt is not clever at spotting invalid/misspelled arguments + $given = getopt($shortOptions, $longOptions); + + if ($given === false) { + throw new InvalidArgumentException('failed to parse command line arguments'); + } + + if ($this->getBoolOption($given, 'help', 'h')) { + $this->usage(); + $this->showHelp = true; + return; + } + + $this->dryRun = isset($given['dry-run']); + + $this->delete = $this->getValOption($given, 'deletion_threshold', 'd'); + $this->warn = $this->getValOption($given, 'warning_threshold', 'w'); + + if (!(is_null($this->delete) || is_null($this->warn))) { + if ($this->delete < $this->warn) { + throw new InvalidArgumentException( + "deletion_threshold must be greater than warning_threshold" + ); + } + } + return; + } + private function getValOption($given, $long, $short) + { + if (isset($given[$long]) || isset($given[$short])) { + $tValGiven = isset($given[$short]) ? $given[$short] : $given[$long]; + return $this->positiveInteger($tValGiven, $long); + } + return; + } + private function getBoolOption($given, $long, $short) + { + return isset($given[$long]) || isset($given[$short]); + } + private function positiveInteger($val, $txt) + { + if ((string)abs((int)$val) != $val) { + throw new InvalidArgumentException( + "$txt must be integer and greater than zero . Received: $val" + ); + } + return (int)$val; + } + public static function usage($message = '') + { + if ($message != '') { + print + ( + "Error: $message\n" + ); + } + print + ( + "Usage: php ManageAPICredentials.php [--help | -h] [--dry-run] \\\ \n" . + " [[--warning_threshold | -w] MONTHS ] \\\ \n" . + " [[--deletion_threshold | -d ] MONTHS ] \n" . + "Options: \n" . + " -h, --help Print this message.\n" . + " --dry-run Report but do nothing.\n" . + " -w, --warning_threshold MONTHS Email the owning user about credentials \n" . + " which have not been used for MONTHS months.\n" . + " -d, --deletion_threshold MONTHS Delete credentials which have not been used\n" . + " for MONTHS months.\n" + ); + } + public function isShowHelp() + { + return $this->showHelp; + } + public function isDryRun() + { + return $this->dryRun; + } + public function isDeleteEnabled() + { + return !is_null($this->getDelete()); + } + public function isWarnEnabled() + { + return !is_null($this->getWarn()); + } + public function getWarn() + { + return $this->warn; + } + public function getDelete() + { + return $this->delete; + } + /** + * The delete threshold may not be given in which case the warning threshold should be used. + * Note that it is an error is delete is greater than warning. + */ + public function getThreshold() + { + return $this->isWarnEnabled() ? $this->getWarn() : $this->getDelete(); + } +} diff --git a/resources/QueryPopulateSSO_UsernameRunner.php b/resources/QueryPopulateSSO_UsernameRunner.php index c420e1dfe..e3fae5a18 100644 --- a/resources/QueryPopulateSSO_UsernameRunner.php +++ b/resources/QueryPopulateSSO_UsernameRunner.php @@ -74,5 +74,3 @@ function cleanDN($dn) { return trim(str_replace(' ', '%20', $dn)); } - - diff --git a/tests/DoctrineTestSuite1.php b/tests/DoctrineTestSuite1.php index 0f6eab43c..a7d11af27 100644 --- a/tests/DoctrineTestSuite1.php +++ b/tests/DoctrineTestSuite1.php @@ -19,9 +19,12 @@ require_once __DIR__ . '/doctrine/ExtensionsTest.php'; require_once __DIR__ . '/doctrine/Scoped_IPIQuery_Test1.php'; require_once __DIR__ . '/doctrine/DowntimeServiceEndpointTest1.php'; +require_once __DIR__ . '/doctrine/ServiceTypeTest.php'; require_once __DIR__ . '/unit/lib/Gocdb_Services/RoleActionAuthorisationServiceTest.php'; require_once __DIR__ . '/unit/lib/Gocdb_Services/RoleActionMappingServiceTest.php'; require_once __DIR__ . '/unit/lib/Gocdb_Services/ScopeServiceTest.php'; +require_once __DIR__ . '/unit/lib/Gocdb_Services/ServiceServiceTest.php'; +require_once __DIR__ . '/unit/lib/Gocdb_Services/ServiceTypeServiceTest.php'; require_once __DIR__ . '/unit/lib/Gocdb_Services/UserServiceTest.php'; require_once __DIR__ . '/unit/lib/Gocdb_Services/SiteServiceTest.php'; require_once __DIR__ . '/unit/lib/Gocdb_Services/RoleServiceTest2.php'; @@ -29,8 +32,8 @@ require_once __DIR__ . '/writeAPI/siteMethods.php'; require_once __DIR__ . '/writeAPI/serviceMethods.php'; require_once __DIR__ . '/writeAPI/endpointMethods.php'; - -require_once __DIR__ . '/unit/lib/Gocdb_Services/ServiceServiceTest.php'; +require_once __DIR__ . '/resourcesTests/ManageUnusedAPICredentialsTest.php'; +require_once __DIR__ . '/resourcesTests/ManageUnrenewedAPICredentialsTest.php'; use PHPUnit_Framework_TestSuite; @@ -62,15 +65,19 @@ public static function suite() $suite->addTestSuite('RoleActionAuthorisationServiceTest'); $suite->addTestSuite('RoleActionMappingServiceTest'); $suite->addTestSuite('ScopeServiceTest'); + $suite->addTestSuite('org\gocdb\tests\ServiceServiceTest'); + $suite->addTestSuite('org\gocdb\tests\ServiceTypeTest'); + $suite->addTestSuite('org\gocdb\tests\ServiceTypeServiceTest'); $suite->addTestSuite('UserServiceTest'); - $suite->addTestSuite('SiteServiceTest'); + $suite->addTestSuite('org\gocdb\tests\SiteServiceTest'); $suite->addTestSuite('RoleServiceTest2'); $suite->addTestSuite('org\gocdb\tests\APIAuthenticationServiceTest'); $suite->addTestSuite('WriteAPIsiteMethodsTests'); $suite->addTestSuite('WriteAPIserviceMethodsTests'); $suite->addTestSuite('WriteAPIendpointMethodsTests'); + $suite->addTestSuite('org\gocdb\tests\ManageUnusedAPICredentialsTest'); + $suite->addTestSuite('org\gocdb\tests\ManageUnrenewedAPICredentialsTest'); - $suite->addTestSuite('ServiceServiceTest'); return $suite; } diff --git a/tests/doctrine/ServiceTypeTest.php b/tests/doctrine/ServiceTypeTest.php new file mode 100644 index 000000000..801dcaa9a --- /dev/null +++ b/tests/doctrine/ServiceTypeTest.php @@ -0,0 +1,148 @@ +createFlatXMLDataSet(dirname(__FILE__) . '/truncateDataTables.xml'); + } + + /** + * Overridden. + */ + protected function getSetUpOperation() + { + // CLEAN_INSERT is default + //return PHPUnit_Extensions_Database_Operation_Factory::CLEAN_INSERT(); + //return PHPUnit_Extensions_Database_Operation_Factory::UPDATE(); + //return PHPUnit_Extensions_Database_Operation_Factory::NONE(); + // + // Issue a DELETE from which is more portable than a + // TRUNCATE table
    (some DBs require high privileges for truncate statements + // and also do not allow truncates across tables with FK contstraints e.g. Oracle) + return PHPUnit_Extensions_Database_Operation_Factory::DELETE_ALL(); + } + + /** + * Overridden. + */ + protected function getTearDownOperation() + { + // NONE is default + return PHPUnit_Extensions_Database_Operation_Factory::NONE(); + } + + /** + * Sets up the fixture, e.g create a new entityManager for each test run + * This method is called before each test method is executed. + */ + protected function setUp() + { + parent::setUp(); + $this->em = $this->createEntityManager(); + } + + /** + * @todo Still need to setup connection to different databases. + * @return EntityManager + */ + private function createEntityManager() + { + $entityManager = null; + require dirname(__FILE__) . '/bootstrap_doctrine.php'; + return $entityManager; + } + + /** + * Called after setUp() and before each test. Used for common assertions + * across all tests. + */ + protected function assertPreConditions() + { + $con = $this->getConnection(); + $fixture = dirname(__FILE__) . '/truncateDataTables.xml'; + $tables = simplexml_load_file($fixture); + + foreach ($tables as $tableName) { + //print $tableName->getName() . "\n"; + $sql = "SELECT * FROM " . $tableName->getName(); + $result = $con->createQueryTable('results_table', $sql); + //echo 'row count: '.$result->getRowCount() ; + if ($result->getRowCount() != 0) { + throw new RuntimeException("Invalid fixture. Table has rows: " . $tableName->getName()); + } + } + } + + /** + * Any function with test at the start of the name will execute with PHPUnit + */ + public function testServiceType() + { + print __METHOD__ . "\n"; + + /** + * Check some logic related to monitoring exceptions in ServiceType entity + */ + + $type1 = TestUtil::createSampleServiceType( + 'this is a test serviceType', + 'type1' + ); + + // Default assumed to disallow monitoring exception + $this->assertEquals($type1->getAllowMonitoringException(), 0); + // Set to true and check return is the current state + $this->assertEquals($type1->setAllowMonitoringException(1), 0); + // Check that it's changed + $this->assertEquals($type1->getAllowMonitoringException(), 1); + } +} diff --git a/tests/doctrine/TestUtil.php b/tests/doctrine/TestUtil.php index eedafeeba..7effe2afd 100644 --- a/tests/doctrine/TestUtil.php +++ b/tests/doctrine/TestUtil.php @@ -56,10 +56,10 @@ public static function createSampleService($label){ return $serv; } - public static function createSampleServiceType($name){ + public static function createSampleServiceType($description, $name){ $stype = new ServiceType(); $stype->setName($name); - $stype->setDescription('sample service type'); + $stype->setDescription($description); return $stype; } diff --git a/tests/miscTests/PI_Extensions_Param_ParsingTest.php b/tests/miscTests/PI_Extensions_Param_ParsingTest.php index d3f57e511..4266529f7 100644 --- a/tests/miscTests/PI_Extensions_Param_ParsingTest.php +++ b/tests/miscTests/PI_Extensions_Param_ParsingTest.php @@ -793,5 +793,3 @@ public function test_ExensionsParser2() { } - - diff --git a/tests/miscTests/ValidateLocalInfoXML.php b/tests/miscTests/ValidateLocalInfoXML.php new file mode 100644 index 000000000..86e81d96d --- /dev/null +++ b/tests/miscTests/ValidateLocalInfoXML.php @@ -0,0 +1,22 @@ +load('../../config/local_info.xml'); + +if (!$xml->schemaValidate('../../config/local_info.xsd')) { + print '

    Errors found.

    '; + print libxml_display_errors(); +} else { + print '

    Validated. No errors found.

    '; +} diff --git a/tests/resources/QueryPI_GetXmlOutput.php b/tests/resources/QueryPI_GetXmlOutput.php index dec30ad40..518f2ef2b 100644 --- a/tests/resources/QueryPI_GetXmlOutput.php +++ b/tests/resources/QueryPI_GetXmlOutput.php @@ -177,8 +177,3 @@ else { echo "Error no valid arg given\n"; } - - - - - diff --git a/tests/resourcesTests/ManageAPICredentialsTestUtils.php b/tests/resourcesTests/ManageAPICredentialsTestUtils.php new file mode 100644 index 000000000..32a7f53b4 --- /dev/null +++ b/tests/resourcesTests/ManageAPICredentialsTestUtils.php @@ -0,0 +1,66 @@ +entityManager = $entityManager; + $this->serviceTestUtil = new ServiceTestUtil(); + } + /** + * Create a number of unique API authentication credentials, evenly spaced each + * with last used time and last renewed time a given number of months before the + * previous, starting the given number of months before the current time. + * + * @param integer $number The number of credentials to create + * @param integer $intervalMonths The interval in months between credentials used to + * set lastUseTime and lastRenewTime + * @return \DateTime Time used as base: the first credential will have time values + * $intervalMonths older than this + */ + public function createTestAuthEnts($number, $intervalMonths) + { + list($user, $site, $siteService) = + $this->serviceTestUtil->createGocdbEntities($this->entityManager); + + $baseTime = new DateTime('now', new DateTimeZone('UTC')); + + $type = 'X.509'; + + $time = clone $baseTime; + + for ($count = 1; $count <= $number; $count++) { + // $useTime will be decremented by 6M for each loop + $time->sub(new DateInterval('P' . $intervalMonths . 'M')); + $ident = '/CN=A Dummy Subject ' . $count; + $authEnt = $siteService->addAPIAuthEntity( + $site, + $user, + array( + 'IDENTIFIER' => $ident, + 'TYPE' => $type, + 'ALLOW_WRITE' => false + ) + ); + $authEnt->setLastUseTime($time); + $authEnt->setLastRenewTime($time); + } + return $baseTime; + } +} diff --git a/tests/resourcesTests/ManageUnrenewedAPICredentialsTest.php b/tests/resourcesTests/ManageUnrenewedAPICredentialsTest.php new file mode 100644 index 000000000..6065dea04 --- /dev/null +++ b/tests/resourcesTests/ManageUnrenewedAPICredentialsTest.php @@ -0,0 +1,167 @@ +dbOpsFactory = new PHPUnit_Extensions_Database_Operation_Factory(); + } + /** + * Overridden. + */ + public static function setUpBeforeClass() + { + parent::setUpBeforeClass(); + echo "\n\n-------------------------------------------------\n"; + echo "Executing ManageUnrenewedAPICredentialsTest. . .\n"; + } + /** + * Overridden. Returns the test database connection. + * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection + */ + protected function getConnection() + { + require_once __DIR__ . '/../doctrine/bootstrap_pdo.php'; + return getConnectionToTestDB(); + } + /** + * Overridden. Returns the test dataset. + * Defines how the initial state of the database should look before each test is executed. + * @return PHPUnit_Extensions_Database_DataSet_IDataSet + */ + protected function getDataSet() + { + $dataset = $this->createFlatXMLDataSet(__DIR__ . '/../doctrine/truncateDataTables.xml'); + return $dataset; + // Use below to return an empty data set if we don't want to truncate and seed + //return new PHPUnit_Extensions_Database_DataSet_DefaultDataSet(); + } + /** + * Overridden. + */ + protected function getSetUpOperation() + { + // CLEAN_INSERT is default + //return PHPUnit_Extensions_Database_Operation_Factory::CLEAN_INSERT(); + //return PHPUnit_Extensions_Database_Operation_Factory::UPDATE(); + //return PHPUnit_Extensions_Database_Operation_Factory::NONE(); + // + // Issue a DELETE from

    which is more portable than a + // TRUNCATE table
    (some DBs require high privileges for truncate statements + // and also do not allow truncates across tables with FK contstraints e.g. Oracle) + return $this->dbOpsFactory->DELETE_ALL(); + } + /** + * Overridden. + */ + protected function getTearDownOperation() + { + // NONE is default + return $this->dbOpsFactory->NONE(); + } + /** + * Sets up the fixture, e.g create a new entityManager for each test run + * This method is called before each test method is executed. + */ + protected function setUp() + { + parent::setUp(); + $this->entityManager = $this->createEntityManager(); + // Pass the Entity Manager into the Factory to allow Gocdb_Services + // to use other Gocdb_Services. + \Factory::setEntityManager($this->entityManager); + + date_default_timezone_set("UTC"); + } + /** + * Run after each test function to prevent pile-up of database connections. + */ + protected function tearDown() + { + parent::tearDown(); + if (!is_null($this->entityManager)) { + $this->entityManager->getConnection()->close(); + } + } + /** + * @return EntityManager + */ + private function createEntityManager() + { + $entityManager = null; // Initialise in local scope to avoid unused variable warnings + require __DIR__ . '/../doctrine/bootstrap_doctrine.php'; + return $entityManager; + } + public function testLastRenewTime() + { + print __METHOD__ . "\n"; + + // Create 8 credentials, each 2 month apart. + // 2 months chosen so the exact definition of a month doesn't matter. + $utils = new ManageAPICredentialsTestUtils($this->entityManager); + $baseTime = $utils->createTestAuthEnts(8, 2); + + $entityManager = $this->createEntityManager(); + + $actions = new ManageAPICredentialsActions(false, $entityManager, $baseTime); + + // Fetch credentials not renewed in the last 5 months - should be 6. + $creds = $actions->getCreds(5, 'lastRenewTime'); + + $this->assertCount( + 6, + $creds, + 'Failed to filter credentials based on last renew time.' + ); + + // remove credentials last renewed more than 9 months ago + // there should be 2 left after this operation (as 2 of + // the 6 fetched above have been renewed with 9 months). + $creds = $actions->deleteCreds($creds, 9); + + $this->assertCount( + 2, + $creds, + 'Failed to delete credential by renew time.' + ); + + // If we now repeat the original query there should be just 4 + // credential following the delete. + $creds = $actions->getCreds(5, 'lastRenewTime'); + + $this->assertCount( + 2, + $creds, + 'Unexpected credential count following deletion.' + ); + } +} diff --git a/tests/resourcesTests/ManageUnusedAPICredentialsTest.php b/tests/resourcesTests/ManageUnusedAPICredentialsTest.php new file mode 100644 index 000000000..ca5dd4a33 --- /dev/null +++ b/tests/resourcesTests/ManageUnusedAPICredentialsTest.php @@ -0,0 +1,164 @@ +dbOpsFactory = new PHPUnit_Extensions_Database_Operation_Factory(); + } + /** + * Overridden. + */ + public static function setUpBeforeClass() + { + parent::setUpBeforeClass(); + echo "\n\n-------------------------------------------------\n"; + echo "Executing ManageUnusedAPICredentialsTest. . .\n"; + } + /** + * Overridden. Returns the test database connection. + * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection + */ + protected function getConnection() + { + require_once __DIR__ . '/../doctrine/bootstrap_pdo.php'; + return getConnectionToTestDB(); + } + /** + * Overridden. Returns the test dataset. + * Defines how the initial state of the database should look before each test is executed. + * @return PHPUnit_Extensions_Database_DataSet_IDataSet + */ + protected function getDataSet() + { + $dataset = $this->createFlatXMLDataSet(__DIR__ . '/../doctrine/truncateDataTables.xml'); + return $dataset; + // Use below to return an empty data set if we don't want to truncate and seed + //return new PHPUnit_Extensions_Database_DataSet_DefaultDataSet(); + } + /** + * Overridden. + */ + protected function getSetUpOperation() + { + // CLEAN_INSERT is default + //return PHPUnit_Extensions_Database_Operation_Factory::CLEAN_INSERT(); + //return PHPUnit_Extensions_Database_Operation_Factory::UPDATE(); + //return PHPUnit_Extensions_Database_Operation_Factory::NONE(); + // + // Issue a DELETE from
    which is more portable than a + // TRUNCATE table
    (some DBs require high privileges for truncate statements + // and also do not allow truncates across tables with FK contstraints e.g. Oracle) + return $this->dbOpsFactory->DELETE_ALL(); + } + /** + * Overridden. + */ + protected function getTearDownOperation() + { + // NONE is default + return $this->dbOpsFactory->NONE(); + } + /** + * Sets up the fixture, e.g create a new entityManager for each test run + * This method is called before each test method is executed. + */ + protected function setUp() + { + parent::setUp(); + $this->entityManager = $this->createEntityManager(); + // Pass the Entity Manager into the Factory to allow Gocdb_Services + // to use other Gocdb_Services. + \Factory::setEntityManager($this->entityManager); + + date_default_timezone_set("UTC"); + } + /** + * Run after each test function to prevent pile-up of database connections. + */ + protected function tearDown() + { + parent::tearDown(); + if (!is_null($this->entityManager)) { + $this->entityManager->getConnection()->close(); + } + } + /** + * @return EntityManager + */ + private function createEntityManager() + { + $entityManager = null; // Initialise in local scope to avoid unused variable warnings + require __DIR__ . '/../doctrine/bootstrap_doctrine.php'; + return $entityManager; + } + public function testLastUseTime() + { + print __METHOD__ . "\n"; + + $utils = new ManageAPICredentialsTestUtils($this->entityManager); + $baseTime = $utils->createTestAuthEnts(3, 6); + + $entityManager = $this->createEntityManager(); + + $actions = new ManageAPICredentialsActions(false, $entityManager, $baseTime); + + // Fetch credentials not used in the last 7 months - should be 2 + $creds = $actions->getCreds(7, 'lastUseTime'); + + $this->assertCount( + 2, + $creds, + 'Failed to filter credentials based on last use time.' + ); + + // remove credentials last used more than 13 months ago + // there should be one left after this operation + $creds = $actions->deleteCreds($creds, 13); + + $this->assertCount( + 1, + $creds, + 'Failed to delete credential based on last use time.' + ); + + // If we now repeat the original query there should be just one + // credential following the delete. + $creds = $actions->getCreds(7, 'lastUseTime'); + + $this->assertCount( + 1, + $creds, + 'Unexpected credential count following deletion based on last use time.' + ); + } +} diff --git a/tests/unit/lib/Gocdb_Services/APIAuthenticationServiceTest.php b/tests/unit/lib/Gocdb_Services/APIAuthenticationServiceTest.php index 9f9de89bb..3be93251c 100644 --- a/tests/unit/lib/Gocdb_Services/APIAuthenticationServiceTest.php +++ b/tests/unit/lib/Gocdb_Services/APIAuthenticationServiceTest.php @@ -22,7 +22,7 @@ use PHPUnit_Extensions_Database_Operation_Factory; use PHPUnit_Extensions_Database_TestCase; use RuntimeException; -use ServiceTestUtil; +use org\gocdb\tests\ServiceTestUtil; use TestUtil; /** @@ -34,6 +34,7 @@ class APIAuthEnticationServiceTest extends PHPUnit_Extensions_Database_TestCase { private $entityManager; private $dbOpsFactory; + private $serviceTestUtil; public function __construct() { @@ -41,6 +42,7 @@ public function __construct() // Use a local instance to avoid Mess Detector's whinging about avoiding // static access. $this->dbOpsFactory = new PHPUnit_Extensions_Database_Operation_Factory(); + $this->serviceTestUtil = new ServiceTestUtil(); } /** * Overridden. @@ -154,22 +156,8 @@ public function testGetAPIAuthentication() { print __METHOD__ . "\n"; - $siteData = ServiceTestUtil::getSiteData($this->entityManager); - $siteService = ServiceTestUtil::getSiteService($this->entityManager); - $site = ServiceTestUtil::createAndAddSite($this->entityManager, $siteData); - - $user = TestUtil::createSampleUser('Beta', 'User'); - $user->setAdmin(true); - - $identifier = TestUtil::createSampleUserIdentifier('X.509', '/Beta.User'); - ServiceTestUtil::persistAndFlush($this->entityManager, $identifier); - - $user->addUserIdentifierDoJoin($identifier); - - ServiceTestUtil::persistAndFlush($this->entityManager, $user); - - $authEntServ = new APIAuthenticationService(); - $authEntServ->setEntityManager($this->entityManager); + list($user, $site, $siteService, $authEntServ) = + $this->serviceTestUtil->createGocdbEntities($this->entityManager); $this->assertTrue( $authEntServ instanceof APIAuthenticationService, diff --git a/tests/unit/lib/Gocdb_Services/ServiceServiceTest.php b/tests/unit/lib/Gocdb_Services/ServiceServiceTest.php index 788a769d1..4be36998b 100644 --- a/tests/unit/lib/Gocdb_Services/ServiceServiceTest.php +++ b/tests/unit/lib/Gocdb_Services/ServiceServiceTest.php @@ -1,217 +1,467 @@ createFlatXMLDataSet(__DIR__ . '/../../../doctrine/truncateDataTables.xml'); - // Use below to return an empty data set if we don't want to truncate and seed - //return new PHPUnit_Extensions_Database_DataSet_DefaultDataSet(); - } + /** + * Overridden. Returns the test dataset. + * Defines how the initial state of the database should look before each test is executed. + * @return PHPUnit_Extensions_Database_DataSet_IDataSet + */ + protected function getDataSet() + { + return $this->createFlatXMLDataSet(__DIR__ . '/../../../doctrine/truncateDataTables.xml'); + } - /** - * Overridden. - */ - protected function getSetUpOperation() { - // CLEAN_INSERT is default - //return PHPUnit_Extensions_Database_Operation_Factory::CLEAN_INSERT(); - //return PHPUnit_Extensions_Database_Operation_Factory::UPDATE(); - //return PHPUnit_Extensions_Database_Operation_Factory::NONE(); - // - // Issue a DELETE from
    which is more portable than a - // TRUNCATE table
    (some DBs require high privileges for truncate statements - // and also do not allow truncates across tables with FK contstraints e.g. Oracle) - return PHPUnit_Extensions_Database_Operation_Factory::DELETE_ALL(); - } + /** + * Overridden. + */ + protected function getSetUpOperation() + { + // CLEAN_INSERT is default + //return PHPUnit_Extensions_Database_Operation_Factory::CLEAN_INSERT(); + //return PHPUnit_Extensions_Database_Operation_Factory::UPDATE(); + //return PHPUnit_Extensions_Database_Operation_Factory::NONE(); + // + // Issue a DELETE from
    which is more portable than a + // TRUNCATE table
    (some DBs require high privileges for truncate statements + // and also do not allow truncates across tables with FK contstraints e.g. Oracle) + return PHPUnit_Extensions_Database_Operation_Factory::DELETE_ALL(); + } - /** - * Overridden. - */ - protected function getTearDownOperation() { - // NONE is default - return PHPUnit_Extensions_Database_Operation_Factory::NONE(); - } + /** + * Overridden. + */ + protected function getTearDownOperation() + { + // NONE is default + return PHPUnit_Extensions_Database_Operation_Factory::NONE(); + } - /** - * Sets up the fixture, e.g create a new entityManager for each test run - * This method is called before each test method is executed. - */ - protected function setUp() { - parent::setUp(); - $this->eMan = $this->createEntityManager(); - } - /** - * Run after each test function to prevent pile-up of database connections. - */ - protected function tearDown() - { - parent::tearDown(); - if (!is_null($this->eMan)) { - $this->eMan->getConnection()->close(); - } - } - /** - * @todo Still need to setup connection to different databases. - * @return EntityManager - */ - private function createEntityManager(){ - // Initialise to avoid unused variable warnings - $entityManager = NULL; - require __DIR__ . '/../../../doctrine/bootstrap_doctrine.php'; - return $entityManager; - } + /** + * Sets up the fixture, e.g create a new entityManager for each test run + * This method is called before each test method is executed. + */ + protected function setUp() + { + parent::setUp(); + $this->em = $this->createEntityManager(); + /** + * It would be nce to put the database setup here but it creates a rats nest of + * problems with cleaning the database between tests. + * ref: https://github.com/sebastianbergmann/dbunit/issues/37 + */ + } + /** + * Run after each test function to prevent pile-up of database connections. + */ + protected function tearDown() + { + parent::tearDown(); + if (!is_null($this->em)) { + $this->em->getConnection()->close(); + } + } + /** + * @todo Still need to setup connection to different databases. + * @return EntityManager + */ + private function createEntityManager() + { + // Initialise to avoid unused variable warnings + $entityManager = null; + require __DIR__ . '/../../../doctrine/bootstrap_doctrine.php'; + return $entityManager; + } - /** - * Called after setUp() and before each test. Used for common assertions - * across all tests. - */ - protected function assertPreConditions() { - $con = $this->getConnection(); - $fixture = __DIR__ . '/../../../doctrine/truncateDataTables.xml'; - $tables = simplexml_load_file($fixture); + /** + * Called after setUp() and before each test. Used for common assertions + * across all tests. + */ + protected function assertPreConditions() + { + /** + * Checks that all tables are empty before we start a test. + */ + $con = $this->getConnection(); + $fixture = __DIR__ . '/../../../doctrine/truncateDataTables.xml'; + $tables = simplexml_load_file($fixture); + + foreach ($tables as $tableName) { + $sql = "SELECT * FROM " . $tableName->getName(); + $result = $con->createQueryTable('results_table', $sql); + if ($result->getRowCount() != 0) { + throw new RuntimeException("Invalid fixture. Table has rows: " . $tableName->getName()); + } + } + } + private function createTestData() + { + + //$project1 = new \Project("project1"); + //$this->em->persist($project1); + //$ngi1 = TestUtil::createSampleNGI("ngi1"); + //$this->em->persist($ngi1); + + $pKey = new \PrimaryKey(); + $this->em->persist($pKey); + + $this->em->flush(); + + $site1 = TestUtil::createSampleSite("site1"); + $this->em->persist($site1); + $site1->setPrimaryKey($pKey->getId()); + + $service1 = TestUtil::createSampleService("service1"); + $this->em->persist($service1); + + $type1 = TestUtil::createSampleServiceType("sample service type", "servicetype1"); + $this->em->persist($type1); + + $user1 = TestUtil::createSampleUser("forename1", "surname1", "/cn=dummy1"); + $this->em->persist($user1); + $user1->setAdmin(true); + + $scope1 = TestUtil::createSampleScope("sample scope1", "scope1"); + $this->em->persist($scope1); + + //$service1->setParentSiteDoJoin($site1); + //$ngi1->addSiteDoJoin($site1); + //$project1->addNgi($ngi1); + + $this->em->flush(); + + // This seems to be the minimal newvalues array to allow the + // editService to execute + $serviceValues = array( + "hostingSite" => $site1->getId(), + "serviceType" => $type1->getId(), + "PRODUCTION_LEVEL" => "Y", + "IS_MONITORED" => "Y", + "BETA" => false, + "Scope_ids" => array($scope1), + "ReservedScope_ids" => array(), + "SE" => array( + "HOSTNAME" => "gocdb.somedomain.biz", + "URL" => "https://gocdb.somedomain.biz", + "DESCRIPTION" => "some text to describe something", + "HOST_DN" => "/C=UK/O=HR/CN=me.me.me", + "HOST_IP" => "0.0.0.0", + "HOST_IP_V6" => "0000:0000:0000:0000:0000:0000:0000:0000", + "HOST_OS" => "BSD", + "HOST_ARCH" => "x86_64", + "EMAIL" => "pooh.bear@gocdb.org" + ) + ); + + $servService = new ServiceService(); + $servService->setEntityManager($this->em); + + $roleAMS = new RoleActionMappingService(); + + $roleAAS = new RoleActionAuthorisationService($roleAMS); + $roleAAS->setEntityManager($this->em); + + $servService->setRoleActionAuthorisationService($roleAAS); + + $scopeService = new ScopeService(); + $scopeService->setEntityManager($this->em); + + $servService->setScopeService($scopeService); + + return array ($servService, $serviceValues, $user1, $type1); + } + + /** + * Check that basic add service works + */ + public function testAddService() + { + + print __METHOD__ . "\n"; + + list ($servService, $serviceValues, $user, ) = $this->createTestData(); + + // Check we get a service back. + $this->assertInstanceOf( + '\Service', + $service = $servService->addService($serviceValues, $user) + ); + + $this->assertTrue($service->getProduction()); + $this->assertTrue($service->getMonitored()); + } + /** + * Check the default rule that production services must be monitored. + * @depends testAddService + */ + public function testMonitoringFlag1() + { + + print __METHOD__ . "\n"; + + list ($servService, $serviceValues, $user, ) = $this->createTestData(); + + // Force Monitoring and Production in conflict: should fail. + $serviceValues["PRODUCTION_LEVEL"] = "Y"; + $serviceValues["IS_MONITORED"] = "N"; + + $this->setExpectedException('Exception'); + $this->assertInstanceOf( + '\Service', + $servService->addService($serviceValues, $user) + ); + } + /** + * Check that exceptions to the default rule that production services + * must be monitored are handled correctly + * @depends testMonitoringFlag1 + */ + public function testMonitoringFlag2() + { + + print __METHOD__ . "\n"; + + list ($servService, $serviceValues, $user, $type) = $this->createTestData(); + + // Force Monitoring and Production in conflict: should fail but ... + $serviceValues["PRODUCTION_LEVEL"] = "Y"; + $serviceValues["IS_MONITORED"] = "N"; + + // ... set the exception so it doesn't. + $type->setAllowMonitoringException(1); + + $this->assertInstanceOf( + '\Service', + $service = $servService->addService($serviceValues, $user) + ); - foreach($tables as $tableName) { - $sql = "SELECT * FROM ".$tableName->getName(); - $result = $con->createQueryTable('results_table', $sql); - if($result->getRowCount() != 0){ - throw new RuntimeException("Invalid fixture. Table has rows: ".$tableName->getName()); - } + $this->assertTrue($service->getProduction()); + $this->assertFalse($service->getMonitored()); } - } + /** + * Check that exceptions to the default rule that production services + * must be monitored are handled correctly + * @depends testAddService + */ + public function testEditService() + { - public function createValidationEntities(){ + print __METHOD__ . "\n"; - $util = new TestUtil(); + list ($servService, $serviceValues, $user, ) = $this->createTestData(); - $site = $util->createSampleSite("TestSite"); - $this->eMan->persist($site); + // Get a service + $service = $servService->addService($serviceValues, $user); - $service = $util->createSampleService("TestService1"); - $this->eMan->persist($service); - $service->setParentSiteDoJoin($site); + // Make some rather arbitrary changes not in conflict + $serviceValues["PRODUCTION_LEVEL"] = "N"; + $serviceValues["IS_MONITORED"] = "N"; - $user = $util->createSampleUser("Test", "Testing"); - $identifier= TestUtil::createSampleUserIdentifier("X.509", "/c=test"); - $user->addUserIdentifierDoJoin($identifier); - $this->eMan->persist($identifier); - $this->eMan->persist($user); - $user->setAdmin(TRUE); + $this->assertInstanceOf( + '\Service', + $newS = $servService->editService($service, $serviceValues, $user) + ); - $roleAMS = new org\gocdb\services\RoleActionMappingService(); - $roleAAS = new org\gocdb\services\RoleActionAuthorisationService($roleAMS); - $roleAAS->setEntityManager($this->eMan); + $this->assertFalse($newS->getProduction()); + $this->assertFalse($newS->getMonitored()); + } + /** + * Check that exceptions to the default rule that production services + * must be monitored are handled correctly + * @depends testEditService + */ + public function testMonitoringFlag3() + { + + print __METHOD__ . "\n"; + + list ($servService, $serviceValues, $user, ) = $this->createTestData(); - $this->eMan->flush(); + // Get a service + $service = $servService->addService($serviceValues, $user); - $serviceService = new org\gocdb\services\ServiceService(); - $serviceService->setEntityManager($this->eMan); - $serviceService->setRoleActionAuthorisationService($roleAAS); + // Force Monitoring and Production in conflict: should fail. + $serviceValues["PRODUCTION_LEVEL"] = "Y"; + $serviceValues["IS_MONITORED"] = "N"; + + $this->setExpectedException('Exception'); + $this->assertInstanceOf( + '\Service', + $servService->editService($service, $serviceValues, $user) + ); + } + /** + * Check that exceptions to the default rule that production services + * must be monitored are handled correctly + * @depends testMonitoringFlag3 + */ + public function testMonitoringFlag4() + { - return array($service, $user, $serviceService); - } + print __METHOD__ . "\n"; + + list ($servService, $serviceValues, $user, $type) = $this->createTestData(); + + // Get a service + $service = $servService->addService($serviceValues, $user); + + // Force Monitoring and Production in conflict: should fail but ... + $serviceValues["PRODUCTION_LEVEL"] = "Y"; + $serviceValues["IS_MONITORED"] = "N"; + + // ... set the exception so it doesn't. + $type->setAllowMonitoringException(1); + + $this->assertInstanceOf( + '\Service', + $newS = $servService->editService($service, $serviceValues, $user) + ); + + $this->assertTrue($newS->getProduction()); + $this->assertFalse($newS->getMonitored()); + } + public function createValidationEntities() + { + + $util = new TestUtil(); + + $site = $util->createSampleSite("TestSite"); + $this->em->persist($site); + + $service = $util->createSampleService("TestService1"); + $this->em->persist($service); + $service->setParentSiteDoJoin($site); + + $user = $util->createSampleUser("Test", "Testing"); + $identifier = TestUtil::createSampleUserIdentifier("X.509", "/c=test"); + $user->addUserIdentifierDoJoin($identifier); + $this->em->persist($identifier); + $this->em->persist($user); + $user->setAdmin(true); + + $roleAMS = new RoleActionMappingService(); + $roleAAS = new RoleActionAuthorisationService($roleAMS); + $roleAAS->setEntityManager($this->em); + + $this->em->flush(); + + $serviceService = new ServiceService(); + $serviceService->setEntityManager($this->em); + $serviceService->setRoleActionAuthorisationService($roleAAS); + + return array($service, $user, $serviceService); + } /** * Check the basics - * Duplicates some simple testing from ExtensionsTest */ - public function testValidateProperty(){ - print __METHOD__ . "\n"; + public function testValidateProperty() + { + print __METHOD__ . "\n"; - list ($service, $user, $serviceService) = $this->createValidationEntities(); - // Properties are specified as array of arrays of form - // [[Name,Value],[Name,Value], ... ] - $values[0] = array("ValidName1","ValidValue"); - $values[1] = array("ValidName2",""); + list ($service, $user, $serviceService) = $this->createValidationEntities(); + // Properties are specified as array of arrays of form + // [[Name,Value],[Name,Value], ... ] + $values = []; + $values[0] = array("ValidName1","ValidValue"); + $values[1] = array("ValidName2",""); - $this->assertTrue($serviceService->addProperties($service, $user, $values) == NULL); + $this->assertTrue($serviceService->addProperties($service, $user, $values) == null); - $this->assertTrue(count($properties = $service->getServiceProperties()) == 2); + $this->assertTrue(count($properties = $service->getServiceProperties()) == 2); - $this->assertTrue( - $serviceService->deleteServiceProperties($service, $user, $properties->toArray()) - == NULL); + $this->assertTrue( + $serviceService->deleteServiceProperties($service, $user, $properties->toArray()) + == null + ); - $this->assertTrue(count($properties = $service->getServiceProperties()) == 0); - } + $this->assertTrue(count($properties = $service->getServiceProperties()) == 0); + } /** * Check that validation of property name is operating as expected * Added to test code changes to pass through "<>" chars * @depends testValidateProperty */ - public function testValidatePropertyNameFails(){ - print __METHOD__ . "\n"; - - list ($service, $user, $serviceService) = $this->createValidationEntities(); - // Properties are specified as array of arrays of form - // [[Name,Value],[Name,Value], ... ] - // < & > are invalid characters in the property name but are valid - // for the property value. - $values[0] = array("",""); + public function testValidatePropertyNameFails() + { + print __METHOD__ . "\n"; - $this->setExpectedException('Exception'); + list ($service, $user, $serviceService) = $this->createValidationEntities(); + // Properties are specified as array of arrays of form + // [[Name,Value],[Name,Value], ... ] + // < & > are invalid characters in the property name but are valid + // for the property value. + $values = []; + $values[0] = array("",""); - $serviceService->addProperties($service, $user, $values); + $this->setExpectedException('Exception'); - } + $serviceService->addProperties($service, $user, $values); + } /** * Check that validation of property value is operating as expected * @depends testValidateProperty */ - public function testValidatePropertyValueFails(){ - print __METHOD__ . "\n"; + public function testValidatePropertyValueFails() + { + print __METHOD__ . "\n"; - list ($service, $user, $serviceService) = $this->createValidationEntities(); - // Properties are specified as array of arrays of form - // [[Name,Value],[Name,Value], ... ] - // Quote characters are invalid in property value - $values[0] = array("Valid","'Not Valid'"); + list ($service, $user, $serviceService) = $this->createValidationEntities(); + // Properties are specified as array of arrays of form + // [[Name,Value],[Name,Value], ... ] + // Quote characters are invalid in property value + $values = []; + $values[0] = array("Valid","'Not Valid'"); - $this->setExpectedException('Exception'); + $this->setExpectedException('Exception'); - $serviceService->addProperties($service, $user, $values); - - } + $serviceService->addProperties($service, $user, $values); + } } diff --git a/tests/unit/lib/Gocdb_Services/ServiceTestUtil.php b/tests/unit/lib/Gocdb_Services/ServiceTestUtil.php index f0bdcfab5..9765e62b7 100644 --- a/tests/unit/lib/Gocdb_Services/ServiceTestUtil.php +++ b/tests/unit/lib/Gocdb_Services/ServiceTestUtil.php @@ -1,48 +1,59 @@ persist($instance); - $em->flush(); - } - /** - * Create some test site data - * @param EntityManager $em Entity Manager handle - */ - public static function getSiteData ($em) { +class ServiceTestUtil +{ + /** + * Persist and flush an entity + * @param \Doctrine\ORM\EntityManager $em Entity manager + * @param Object $instance + */ + public static function persistAndFlush($em, $instance) + { + $em->persist($instance); + $em->flush(); + } + /** + * Create some test site data + * @param EntityManager $em Entity Manager handle + */ + public static function getSiteData($em) + { - $infra = TestUtil::createSampleInfrastructure('Production'); - $em->persist($infra); + $infra = TestUtil::createSampleInfrastructure('Production'); + $em->persist($infra); - $ngi = TestUtil::createSampleNGI('ngi1_'); - $em->persist($ngi); + $ngi = TestUtil::createSampleNGI('ngi1_'); + $em->persist($ngi); - $scope = TestUtil::createSampleScope('scope 1', 'Scope1'); - $em->persist($scope); + $scope = TestUtil::createSampleScope('scope 1', 'Scope1'); + $em->persist($scope); - $certStatus = TestUtil::createSampleCertStatus('Certified'); - $em->persist($certStatus); + $certStatus = TestUtil::createSampleCertStatus('Certified'); + $em->persist($certStatus); - $country = TestUtil::createSampleCountry('Utopia'); - $em->persist($country); + $country = TestUtil::createSampleCountry('Utopia'); + $em->persist($country); - $em->flush(); + $em->flush(); - $siteData = array ( - 'NGI' => $ngi->getId(), - 'Site' => array( + $siteData = array ( + 'NGI' => $ngi->getId(), + 'Site' => array( 'SHORT_NAME' => 's1', 'DESCRIPTION' => 'A test site', 'OFFICIAL_NAME' => 'An-official-site', @@ -62,67 +73,98 @@ public static function getSiteData ($em) { 'EMERGENCYEMAIL' => 'anon@localhost.net', 'HELPDESKEMAIL' => 'anon@localhost.net', 'TIMEZONE' => 'GMT'), - 'Scope_ids' => array($scope->getId()), - 'ReservedScope_ids' => array(), - 'ProductionStatus' => $infra->getId(), - 'Certification_Status' => $certStatus->getId(), - 'Country' => $country->getId() - ); - - return $siteData; - } + 'Scope_ids' => array($scope->getId()), + 'ReservedScope_ids' => array(), + 'ProductionStatus' => $infra->getId(), + 'Certification_Status' => $certStatus->getId(), + 'Country' => $country->getId() + ); + + return $siteData; + } /** * Create and return a minimal Site Service instance * @param \Doctrine\ORM\EntityManager EntityManager $em * @param array $siteData Minimal initial site data array * @return \Site $site */ - public static function createAndAddSite ($em, $siteData) { + public function createAndAddSite($em, $siteData) + { - $user = TestUtil::createSampleUser('Alpha','User'); + $user = TestUtil::createSampleUser('Alpha', 'User'); // We don't want to test all the roleAction logic here so simply make us an admin - $user->setAdmin(true); + $user->setAdmin(true); - $identifier = TestUtil::createSampleUserIdentifier('X.509', '/Alpha.User'); - ServiceTestUtil::persistAndFlush($em, $identifier); + $identifier = TestUtil::createSampleUserIdentifier('X.509', '/Alpha.User'); + $this->persistAndFlush($em, $identifier); - $user->addUserIdentifierDoJoin($identifier); + $user->addUserIdentifierDoJoin($identifier); - ServiceTestUtil::persistAndFlush($em, $user); + $this->persistAndFlush($em, $user); - $siteService = ServiceTestUtil::getSiteService($em); + $siteService = $this->getSiteService($em); - $site = $siteService->addSite($siteData, $user); + $site = $siteService->addSite($siteData, $user); - return $site; - } + return $site; + } /** * Generate minimal Site Service - * @param \Doctrine\ORM\EntityManager EntityManager $em - * @return org\gocdb\services\Site $siteService + * @param EntityManager EntityManager $em + * @return Site $siteService */ - public static function getSiteService ($em) { - $siteService = new org\gocdb\services\Site(); - $siteService->setEntityManager($em); + public function getSiteService($em) + { + $siteService = new Site(); + $siteService->setEntityManager($em); // Need stubs for both role and scope services - $roleAAS = TestUtil::createSampleRoleAAS(__DIR__ . + $roleAAS = TestUtil::createSampleRoleAAS(__DIR__ . "/../../resources/roleActionMappingSamples/TestRoleActionMappings5.xml"); - $roleAAS->setEntityManager($em); - $siteService->setRoleActionAuthorisationService($roleAAS); - $siteService->setScopeService(ServiceTestUtil::getScopeService($em)); + $roleAAS->setEntityManager($em); + $siteService->setRoleActionAuthorisationService($roleAAS); + $siteService->setScopeService($this->getScopeService($em)); - return $siteService; - } + return $siteService; + } /** * Generate a useless minimal Scope Service * NB. Should be done in the siteService constructor (?) */ - private static function getScopeService($em) { - $scopeService = new \org\gocdb\services\Scope(); - $scopeService->setEntityManager($em); + private static function getScopeService($em) + { + $scopeService = new Scope(); + $scopeService->setEntityManager($em); + + return $scopeService; + } + public function createGocdbEntities($entityManager) + { + /** + * Set up the site, user and service objects shared by + * some tests. + * + * @return array Created User, Site and SiteService instances + */ + + $siteData = $this->getSiteData($entityManager); + $siteService = $this->getSiteService($entityManager); + $site = $this->createAndAddSite($entityManager, $siteData); + + $user = TestUtil::createSampleUser('Beta', 'User'); + $user->setAdmin(true); + + $identifier = TestUtil::createSampleUserIdentifier('X.509', '/Beta.User'); + $this->persistAndFlush($entityManager, $identifier); + + $user->addUserIdentifierDoJoin($identifier); + + $this->persistAndFlush($entityManager, $user); + + $authEntServ = new APIAuthenticationService(); + $authEntServ->setEntityManager($entityManager); - return $scopeService; - } + return [$user, $site, $siteService, $authEntServ]; + } } diff --git a/tests/unit/lib/Gocdb_Services/ServiceTypeServiceTest.php b/tests/unit/lib/Gocdb_Services/ServiceTypeServiceTest.php new file mode 100644 index 000000000..8f7c9fa4f --- /dev/null +++ b/tests/unit/lib/Gocdb_Services/ServiceTypeServiceTest.php @@ -0,0 +1,252 @@ +createFlatXMLDataSet(__DIR__ . '/../../../doctrine/truncateDataTables.xml'); + } + + /** + * Overridden. + */ + protected function getSetUpOperation() + { + // CLEAN_INSERT is default + //return PHPUnit_Extensions_Database_Operation_Factory::CLEAN_INSERT(); + //return PHPUnit_Extensions_Database_Operation_Factory::UPDATE(); + //return PHPUnit_Extensions_Database_Operation_Factory::NONE(); + // + // Issue a DELETE from
    which is more portable than a + // TRUNCATE table
    (some DBs require high privileges for truncate statements + // and also do not allow truncates across tables with FK contstraints e.g. Oracle) + return PHPUnit_Extensions_Database_Operation_Factory::DELETE_ALL(); + } + + /** + * Overridden. + */ + protected function getTearDownOperation() + { + // NONE is default + return PHPUnit_Extensions_Database_Operation_Factory::NONE(); + } + + /** + * Sets up the fixture, e.g create a new entityManager for each test run + * This method is called before each test method is executed. + */ + protected function setUp() + { + parent::setUp(); + $this->em = $this->createEntityManager(); + /** + * It would be nce to put the database setup here but it creates a rats nest of + * problems with cleaning the database between tests. + * ref: https://github.com/sebastianbergmann/dbunit/issues/37 + */ + } + + /** + * @todo Still need to setup connection to different databases. + * @return EntityManager + */ + private function createEntityManager() + { + $entityManager = null; + require __DIR__ . '/../../../doctrine/bootstrap_doctrine.php'; + return $entityManager; + } + + /** + * Called after setUp() and before each test. Used for common assertions + * across all tests. + */ + protected function assertPreConditions() + { + /** + * Checks that all tables are empty before we start a test. + */ + $con = $this->getConnection(); + $fixture = __DIR__ . '/../../../doctrine/truncateDataTables.xml'; + $tables = simplexml_load_file($fixture); + + foreach ($tables as $tableName) { + //print $tableName->getName() . "\n"; + $sql = "SELECT * FROM " . $tableName->getName(); + $result = $con->createQueryTable('results_table', $sql); + //echo 'row count: '.$result->getRowCount() ; + if ($result->getRowCount() != 0) { + throw new RuntimeException("Invalid fixture. Table has rows: " . $tableName->getName()); + } + } + } + private function createTestData() + { + + //$project1 = new \Project("project1"); + //$this->em->persist($project1); + //$ngi1 = TestUtil::createSampleNGI("ngi1"); + //$this->em->persist($ngi1); + + $pKey = new \PrimaryKey(); + $this->em->persist($pKey); + + $this->em->flush(); + + $user1 = TestUtil::createSampleUser("forename1", "surname1", "/cn=dummy1"); + $this->em->persist($user1); + $user1->setAdmin(true); + + $this->em->flush(); + + $values = array ( + "Name" => "serviceType1", + "Description" => "description of service type 1", + "AllowMonitoringException" => false ); + + return array ($values, $user1); + } + + /** + * Check that basic add service works and monitoring is not allowed + * for production services. + */ + public function testAddServiceType1() + { + + print __METHOD__ . "\n"; + + list ($values, $user) = $this->createTestData(); + + $this->assertInstanceOf( + 'org\gocdb\services\ServiceType', + $sTypeServ = new ServiceTypeService() + ); + + $sTypeServ->setEntityManager($this->em); + + // Check we get a service type back. + $this->assertInstanceOf( + '\ServiceType', + $sType = $sTypeServ->addServiceType($values, $user) + ); + + $this->assertFalse($sType->getAllowMonitoringException()); + } + /** + * Check that duplicates fail + * @depends testAddServiceType1 + */ + public function testAddServiceType2() + { + + print __METHOD__ . "\n"; + + list ($values, $user) = $this->createTestData(); + + $sTypeServ = new ServiceTypeService(); + + $sTypeServ->setEntityManager($this->em); + $sTypeServ->addServiceType($values, $user); + + // Finally - trying to add the same again should fail + $this->setExpectedException('Exception'); + $sTypeServ->addServiceType($values, $user); + } + /** + * Check that admin privileges are needed + * @depends testAddServiceType1 + */ + public function testAddServiceType3() + { + + print __METHOD__ . "\n"; + + list ($values, $user) = $this->createTestData(); + + $user->setAdmin(false); + + $sTypeServ = new ServiceTypeService(); + + $sTypeServ->setEntityManager($this->em); + + $this->setExpectedException('Exception'); + $sTypeServ->addServiceType($values, $user); + } + /** + * Check that admin privileges are needed + * @depends testAddServiceType1 + */ + public function testEditServiceType1() + { + print __METHOD__ . "\n"; + + list ($values, $user) = $this->createTestData(); + + $sTypeServ = new ServiceTypeService(); + + $sTypeServ->setEntityManager($this->em); + + $sType = $sTypeServ->addServiceType($values, $user); + + // Change the name and check the edit succeeds + $newName = $values['Name'] . '0'; + $values['Name'] = $newName; + + $sTypeServ->editServiceType($sType, $values, $user); + + $this->assertEquals($newName, $sType->getName()); + } +} diff --git a/tests/unit/lib/Gocdb_Services/SiteServiceTest.php b/tests/unit/lib/Gocdb_Services/SiteServiceTest.php index 85bf39ed5..f71b445b7 100644 --- a/tests/unit/lib/Gocdb_Services/SiteServiceTest.php +++ b/tests/unit/lib/Gocdb_Services/SiteServiceTest.php @@ -12,6 +12,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + +namespace org\gocdb\tests; + require_once __DIR__ . '/../../../doctrine/TestUtil.php'; require_once __DIR__ . '/ServiceTestUtil.php'; require_once __DIR__ . '/../../../../lib/Doctrine/entities/User.php'; @@ -21,25 +24,32 @@ require_once __DIR__ . '/../../../../lib/Gocdb_Services/Scope.php'; use Doctrine\ORM\EntityManager; +use org\gocdb\tests\ServiceTestUtil; +use PHPUnit_Extensions_Database_Operation_Factory; +use PHPUnit_Extensions_Database_TestCase; +use RuntimeException; +use TestUtil; /** * DBUnit test class for the {@see \org\gocdb\services\Site} service. * * @author Ian Neilson (after David Meredith) */ -class siteServiceTest extends PHPUnit_Extensions_Database_TestCase +class SiteServiceTest extends PHPUnit_Extensions_Database_TestCase { private $entityManager; private $dbOpsFactory; /** @var TestUtil $testUtil */ private $testUtil; + private $serviceTestUtil; - function __construct() + public function __construct() { parent::__construct(); // Use a local instance to avoid Mess Detector's whinging about avoiding // static access. $this->dbOpsFactory = new PHPUnit_Extensions_Database_Operation_Factory(); + $this->serviceTestUtil = new ServiceTestUtil(); } /** * Overridden. @@ -167,16 +177,16 @@ public function testAddSite() { print __METHOD__ . "\n"; - $siteData = ServiceTestUtil::getSiteData($this->entityManager); - $siteService = ServiceTestUtil::getSiteService($this->entityManager); + $siteData = $this->serviceTestUtil->getSiteData($this->entityManager); + $siteService = $this->serviceTestUtil->getSiteService($this->entityManager); // The most basic check $this->assertTrue( - $siteService instanceof org\gocdb\services\Site, + $siteService instanceof \org\gocdb\services\Site, 'Site Service failed to create and return a Site service' ); - ServiceTestUtil::createAndAddSite($this->entityManager, $siteData); + $this->serviceTestUtil->createAndAddSite($this->entityManager, $siteData); // Check // N.B. Although getSitesFilterByParams says all the filters are optional, @@ -198,9 +208,9 @@ public function testAddAPIAuthentication() $user->setAdmin(true); $this->persistAndFlush($user); - $siteData = ServiceTestUtil::getSiteData($this->entityManager); - $siteService = ServiceTestUtil::getSiteService($this->entityManager); - ServiceTestUtil::createAndAddSite($this->entityManager, $siteData); + $siteData = $this->serviceTestUtil->getSiteData($this->entityManager); + $siteService = $this->serviceTestUtil->getSiteService($this->entityManager); + $this->serviceTestUtil->createAndAddSite($this->entityManager, $siteData); $sites = $siteService->getSitesFilterByParams(array('scope' => 'Scope1')); $site = $sites[0]; diff --git a/tests/writeAPI/abstractClass.php b/tests/writeAPI/abstractClass.php index 93a66480f..d8aef7003 100644 --- a/tests/writeAPI/abstractClass.php +++ b/tests/writeAPI/abstractClass.php @@ -266,7 +266,7 @@ protected function createSampleService($append = "") { #create a sample site and create a new sample service and join it to that site $sampleService = TestUtil::createSampleService("Sample service" . $append); - $sampleST = TestUtil::createSampleServiceType("sample.service.type" . $append); + $sampleST = TestUtil::createSampleServiceType("Service type Description", "sample.service.type" . $append); $sampleService->setServiceType($sampleST); $sampleSite = $this->createSampleSite($append); $sampleSite->addServiceDoJoin($sampleService); diff --git a/unused_resources/ParseAtlasDataRunner.php b/unused_resources/ParseAtlasDataRunner.php index 7161da8f1..b848607a0 100644 --- a/unused_resources/ParseAtlasDataRunner.php +++ b/unused_resources/ParseAtlasDataRunner.php @@ -51,4 +51,3 @@ foreach($siteArray as $siteName){ echo $siteName."\n"; } -