/**
  * Action: Register a new dataset.
  *
  * This action performs a geonetwork insert request to register a new 
  * metadata entry. It uses the GeoNetwork restful service API to pass
  * on the metadata details to the registered Metadata catalogue.
  *
  * @param array $data request data
  * @param form $form Form instance (registration form)
  * 
  * @return void
  *
  * @todo add error message when geonetwork is down
  */
 function doRegisterMetadata($data, $form)
 {
     // process form submission and send request to GeoNetwork.
     // for Session-Messages
     $prefix = $this->prefixx();
     foreach ($data as $key => $value) {
         if ($key == "MDTopicCategory") {
             continue;
         }
         // Topic Category is an array of predefined values
         $invalidText = '//]]>';
         if (!(strpos($value, $invalidText) === false)) {
             $mess = "Please ensure that the information you have entered does not contain the following<br /> text: '" . $invalidText . "'.<br />";
             $mess .= "Unfortunately, this text segment can not be stored in the catalogue. ";
             Session::set($prefix . ".errors.message", $mess);
             Session::set($prefix . ".errors.messageType", 'Error');
             // optional: send email to admin?
             $emailValues = array("SendEmailFrom" => $this->data()->get_email_sender(), "SendEmailTo" => Email::getAdminEmail(), "SendEmailSubject" => 'We encountered an exception', "DetailsText" => $mess, "ExceptionText" => '');
             $this->doSendEmailToAdministrator($emailValues, 'ErrorEMail');
             return Director::redirectBack();
         }
     }
     $metadata = new MDMetadata();
     $form->saveInto($metadata);
     $metadata->MDLanguage = 'English';
     $metadata->write();
     $scopeCodes = explode('||', $data['MDHierarchyLevelData']);
     $scopeTypes = explode('||', $data['MDHierarchyLevelNameData']);
     foreach ($scopeCodes as $code) {
         $item = new MDHierarchyLevel();
         $item->Value = $code;
         $item->write();
         $metadata->MDHierarchyLevel()->add($item);
     }
     foreach ($scopeTypes as $type) {
         $item = new MDHierarchyLevelName();
         $item->Value = $type;
         $item->write();
         $metadata->MDHierarchyLevelName()->add($item);
     }
     for ($i = 1; $i < 4; $i++) {
         if (!empty($data['MDDateTime' . $i])) {
             $item = new MDCitationDate();
             $item->MDDateTime = $data['MDDateTime' . $i];
             $item->MDDateType = $data['MDDateType' . $i];
             $item->write();
             $metadata->MDCitationDates()->add($item);
         }
     }
     for ($i = 1; $i < 6; $i++) {
         if (!empty($data['MDResourceFormatName' . $i])) {
             $item = new MDResourceFormat();
             $item->Name = $data['MDResourceFormatName' . $i];
             $item->Version = $data['MDResourceFormatVersion' . $i];
             $item->write();
             $metadata->MDResourceFormats()->add($item);
         }
     }
     $urls = explode('||', $data['CIOnlineLinkageData']);
     foreach ($urls as $url) {
         $item = new CIOnlineResource();
         $item->CIOnlineLinkage = $url;
         $item->CIOnlineName = $item->CIOnlineLinkage;
         $item->CIOnlineProtocol = 'WWW:LINK-1.0-http--link';
         $item->write();
         $metadata->CIOnlineResources()->add($item);
     }
     foreach ($data['MDTopicCategory'] as $category) {
         $item = new MDTopicCategory();
         $item->Value = $category;
         $metadata->MDTopicCategory()->add($item);
     }
     $contact = new MDContact();
     $contact->write();
     $form->saveInto($contact);
     $emails = explode('||', $data['MDElectronicMailAddressData']);
     $phonenumbers = explode('||', $data['MDVoiceData']);
     foreach ($emails as $email) {
         $item = new MDEmail();
         $item->Value = $email;
         $item->write();
         $contact->MDElectronicMailAddress()->add($item);
     }
     foreach ($phonenumbers as $phone) {
         $item = new MDPhoneNumber();
         $item->Value = $phone;
         $item->write();
         $contact->MDVoice()->add($item);
     }
     // foreach($contact->MDElectronicMailAddress() as $item) {
     // 	Debug::show($item);
     // }
     //
     $contact->write();
     $metadata->MDContacts()->add($contact);
     $item = new MDResourceConstraint();
     $form->saveInto($item);
     $item->write();
     $metadata->MDResourceConstraints()->add($item);
     //Debug::show($metadata); exit();
     $data = array('MDMetadata' => $metadata);
     // generate GeoNetwork HTTP request (query metadata).
     $cmd = $this->getCommand("GnCreateInsert", $data);
     $request_params = $cmd->execute();
     $data = array('RequestParameter' => $request_params);
     $page = $this->data();
     $cmd = $this->getCommand("GnInsert", $data);
     $cmd->setUsername($page->Username);
     $cmd->setPassword($page->Password);
     $gnID = null;
     try {
         $gnID = $cmd->execute();
     } catch (GeoNetworkRestfulService_Exception $exception) {
         // add error message
         $mess = 'Unfortunately the registration process failed due to a technical problem. Please retry later. ';
         $mess .= $exception->getMessage();
         Session::set($prefix . ".errors.message", $mess);
         Session::set($prefix . ".errors.messageType", 'Error');
         // optional: send email to admin?
         $emailValues = array("SendEmailFrom" => $this->data()->get_email_sender(), "SendEmailTo" => Email::getAdminEmail(), "SendEmailSubject" => 'We encountered an exception', "DetailsText" => 'While doing a "GnInsert" we caught the following "GeoNetworkRestfulService_Exception" exception:', "ExceptionText" => $exception->getMessage());
         $this->doSendEmailToAdministrator($emailValues, 'ErrorEMail');
         return Director::redirectBack();
     } catch (GeonetworkInsertCommand_Exception $exception) {
         // add error message
         $mess = 'Unfortunately the registration process failed due to a technical problem. Please retry later. ';
         $mess .= $exception->getMessage();
         //Session::setFormMessage($prefix, $mess, 'Error');	// Info , Notice, Warning, Error or something like that
         Session::set($prefix . ".errors.message", $mess);
         Session::set($prefix . ".errors.messageType", 'Error');
         // optional: send email to admin?
         $emailValues = array("SendEmailFrom" => $this->data()->get_email_sender(), "SendEmailTo" => Email::getAdminEmail(), "SendEmailSubject" => 'We encountered an exception', "DetailsText" => 'While doing a "GnInsert" we caught the following "GeonetworkInsertCommand_Exception" exception:', "ExceptionText" => $exception->getMessage());
         $this->doSendEmailToAdministrator($emailValues, 'ErrorEMail');
         return Director::redirectBack();
     }
     $uuid = $cmd->get_uuid();
     $metadata->gnID = $gnID;
     $metadata->fileIdentifier = $uuid;
     $metadata->write();
     $page = $this->data();
     if (!isset($page)) {
         throw new CataloguePage_Exception('Metadata Catalogue Page is not defined correctly.');
     }
     // get GeoNetwork URL of that page.
     $url = $page->RedirectOnSuccess;
     $baseURLParts = explode('/', $this->AbsoluteLink());
     if (array_pop($baseURLParts) == '') {
         //if it's empty, we had a slash at the end and have to remove the controllername
         //again ;0)
         array_pop($baseURLParts);
     }
     $absoluteURLToDetails = implode('/', $baseURLParts) . "/" . $url . "/dogetrecordbyid/" . $uuid;
     $nameWhoGetsTheEmail = $page->EmailName;
     if ($nameWhoGetsTheEmail == '') {
         $nameWhoGetsTheEmail = 'Administrator';
     }
     // prepare email sending
     $emailValues = array("emailName" => $nameWhoGetsTheEmail, "SendEmailFrom" => $page->get_email_sender(), "SendEmailTo" => $page->SendConfitmationsTo, "SendEmailSubject" => 'Metadata Catalogue: New submission from ' . $contact->MDElectronicMailAddress, "detailsURL" => $absoluteURLToDetails, "submittedEmail" => $contact->MDElectronicMailAddress, "submittedTitle" => $metadata->MDTitle, "submittedAbstract" => substr($metadata->MDAbstract, 0, 500));
     $successfulySentEmail = $this->doSendEmailToAdministrator($emailValues, 'ConfirmationEMail');
     $refe = $page->URLSegment;
     if ($refe == '') {
         $refe = 'javascript:history.back(2)';
     }
     $messageObj = new ViewableData();
     $customFields = array('TakeMeBackTo' => $refe);
     $messageObj->customise($customFields);
     $mess = $messageObj->renderWith('ConfirmationMessage');
     $prefix = "FormInfo." . $page->RedirectOnSuccess;
     Session::set($prefix . ".info.message", $mess);
     Session::set($prefix . ".info.messageType", 'ThankYou');
     Director::redirect($url . "/dogetrecordbyid/" . $uuid);
 }
 /**
  * This method loads a provided array into the data structure.
  * It also creates dependencies, such as contact data objects
  * and populate the values into those objects.
  *
  * @param $data array of db-values.
  */
 public function loadData($data)
 {
     if ($data == null) {
         return;
     }
     if (!is_array($data)) {
         return;
     }
     foreach ($data as $k => $v) {
         // store data into this object (no ':" in the string)
         if (strpos($k, ':') === false) {
             $this->{$k} = Convert::xml2raw($v);
         } else {
             // A ':' is used as a namespace marker. It is used to
             // create the related data objects, such as MDContacts.
             $relations = explode(':', $k);
             $fieldName = array_pop($relations);
             $relObj = $this;
             // iterate through the relationships. At the moment, this
             // loading process just works for 1 level hierarchies.
             foreach ($relations as $relation) {
                 if ($relation == 'PointOfContacts') {
                     // load the sub-array into the MDContact object
                     $item = new MDContact();
                     $item->loadData($v);
                     // add the new MDContect to the collection class of this
                     // object.
                     $relObj->PointOfContacts()->add($item);
                 }
                 if ($relation == 'MDContacts') {
                     // load the sub-array into the MDContact object
                     $item = new MDContact();
                     $item->loadData($v);
                     // add the new MDContect to the collection class of this
                     // object.
                     $relObj->MDContacts()->add($item);
                 }
                 if ($relation == 'MDResourceConstraints') {
                     // load the sub-array into the MDResourceConstraints object
                     if (is_array($v)) {
                         foreach ($v as $vitem) {
                             $item = new MDResourceConstraint();
                             $item->loadData($vitem);
                             // add the new MDContect to the collection class of this
                             // object.
                             $relObj->MDResourceConstraints()->add($item);
                         }
                     }
                 }
                 if ($relation == 'MDResourceFormats') {
                     if (is_array($v)) {
                         foreach ($v as $vitem) {
                             // load the sub-array into the MDResourceFormats object
                             $item = new MDResourceFormat();
                             $item->loadData($vitem);
                             // add the new MDContect to the collection class of this
                             // object.
                             $relObj->MDResourceFormats()->add($item);
                         }
                     }
                 }
                 if ($relation == 'MDTopicCategory') {
                     if (is_array($v)) {
                         foreach ($v as $vitem) {
                             // load the sub-array into the MDResourceFormats object
                             $item = new MDTopicCategory();
                             $item->loadData($vitem);
                             // add the new MDTopicCategory to the collection class of this
                             // object.
                             $relObj->MDTopicCategory()->add($item);
                         }
                     }
                 }
                 if ($relation == 'MDCitationDates') {
                     if (is_array($v)) {
                         foreach ($v as $vitem) {
                             // load the sub-array into the MDResourceFormats object
                             $item = new MDCitationDate();
                             $item->loadData($vitem);
                             // add the new MDContect to the collection class of this
                             // object.
                             $relObj->MDCitationDates()->add($item);
                         }
                     }
                 }
                 if ($relation == 'MCPMDCreativeCommons') {
                     if (is_array($v)) {
                         foreach ($v as $vitem) {
                             // load the sub-array into the MDContact object
                             $item = new MCPMDCreativeCommons();
                             $item->loadData($vitem);
                             // add the new MCPMDCreativeCommons to the collection class of this
                             // object.
                             $relObj->MCPMDCreativeCommons()->add($item);
                         }
                     }
                 }
                 if ($relation == 'CIOnlineResources') {
                     if (is_array($v)) {
                         foreach ($v as $vitem) {
                             // load the sub-array into the MDContact object
                             $item = new CIOnlineResource();
                             $item->loadData($vitem);
                             // add the new MDContect to the collection class of this
                             // object.
                             $relObj->CIOnlineResources()->add($item);
                         }
                     }
                 }
                 if ($relation == 'MDHierarchyLevel') {
                     if (is_array($v)) {
                         foreach ($v as $vitem) {
                             $codes = MDCodeTypes::get_scope_codes();
                             if (isset($codes[$vitem['Value']])) {
                                 $item = new MDHierarchyLevel();
                                 $item->loadData($vitem);
                                 $relObj->MDHierarchyLevel()->add($item);
                             }
                         }
                     }
                 }
                 if ($relation == 'MDHierarchyLevelName') {
                     if (is_array($v)) {
                         foreach ($v as $vitem) {
                             $item = new MDHierarchyLevelName();
                             $item->loadData($vitem);
                             $relObj->MDHierarchyLevelName()->add($item);
                         }
                     }
                 }
             }
         }
     }
 }