Example #1
0
   /**
    * Return the generated form output.
    * @return Form HTML.
    */
   public static function get_form($args, $node)
   {
       define("MODE_GRID", 0);
       define("MODE_NEW_SAMPLE", 1);
       define("MODE_EXISTING", 2);
       self::parse_defaults($args);
       self::getArgDefaults($args);
       global $user;
       $logged_in = $user->uid > 0;
       $r = '';
       // Get authorisation tokens to update and read from the Warehouse.
       $auth = data_entry_helper::get_read_write_auth($args['website_id'], $args['password']);
       $svcUrl = data_entry_helper::$base_url . '/index.php/services';
       self::$auth = $auth;
       $mode = isset($args['no_grid']) && $args['no_grid'] ? MODE_NEW_SAMPLE : MODE_GRID;
       // default mode when no grid set to false - display grid of existing data
       // mode MODE_EXISTING: display existing sample
       $loadedSampleId = null;
       $loadedOccurrenceId = null;
       if ($_POST) {
           if (!array_key_exists('website_id', $_POST)) {
               // non Indicia POST, in this case must be the location allocations. add check to ensure we don't corrept the data by accident
               if (iform_loctools_checkaccess($node, 'admin') && array_key_exists('mnhnld1', $_POST)) {
                   iform_loctools_deletelocations($node);
                   foreach ($_POST as $key => $value) {
                       $parts = explode(':', $key);
                       iform_loctools_insertlocation($node, $parts[2], $parts[1]);
                   }
               }
           } else {
               if (!is_null(data_entry_helper::$entity_to_load)) {
                   $mode = MODE_EXISTING;
                   // errors with new sample, entity populated with post, so display this data.
               }
           }
           // else valid save, so go back to gridview: default mode 0
       }
       if (array_key_exists('sample_id', $_GET)) {
           $mode = MODE_EXISTING;
           $loadedSampleId = $_GET['sample_id'];
       }
       if (array_key_exists('occurrence_id', $_GET)) {
           $mode = MODE_EXISTING;
           $loadedOccurrenceId = $_GET['occurrence_id'];
       }
       if ($mode != MODE_EXISTING && array_key_exists('newSample', $_GET)) {
           $mode = MODE_NEW_SAMPLE;
           data_entry_helper::$entity_to_load = array();
       }
       // else default to mode MODE_GRID or MODE_NEW_SAMPLE depending on no_grid parameter
       self::$mode = $mode;
       // default mode  MODE_GRID : display grid of the samples to add a new one
       // or edit an existing one.
       if ($mode == MODE_GRID) {
           $attributes = data_entry_helper::getAttributes(array('valuetable' => 'sample_attribute_value', 'attrtable' => 'sample_attribute', 'key' => 'sample_id', 'fieldprefix' => 'smpAttr', 'extraParams' => $auth['read'], 'survey_id' => $args['survey_id']));
           $tabs = array('#sampleList' => lang::get('LANG_Main_Samples_Tab'));
           if ($args['includeLocTools'] && iform_loctools_checkaccess($node, 'admin')) {
               $tabs['#setLocations'] = lang::get('LANG_Allocate_Locations');
           }
           if (count($tabs) > 1) {
               $r .= "<div id=\"controls\">" . data_entry_helper::enable_tabs(array('divId' => 'controls', 'active' => '#sampleList')) . "<div id=\"temp\"></div>";
               $r .= data_entry_helper::tab_header(array('tabs' => $tabs));
           }
           $r .= "<div id=\"sampleList\">" . self::getSampleListGrid($args, $node, $auth, $attributes) . "</div>";
           if ($args['includeLocTools'] && iform_loctools_checkaccess($node, 'admin')) {
               $r .= '
 <div id="setLocations">
   <form method="post">
     <input type="hidden" id="mnhnld1" name="mnhnld1" value="mnhnld1" /><table border="1"><tr><td></td>';
               $url = $svcUrl . '/data/location?mode=json&view=detail&auth_token=' . $auth['read']['auth_token'] . "&nonce=" . $auth['read']["nonce"] . "&parent_id=NULL&orderby=name";
               $session = curl_init($url);
               curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
               $entities = json_decode(curl_exec($session), true);
               $userlist = iform_loctools_listusers($node);
               foreach ($userlist as $uid => $a_user) {
                   $r .= '<td>' . $a_user->name . '</td>';
               }
               $r .= "</tr>";
               if (!empty($entities)) {
                   foreach ($entities as $entity) {
                       if (!$entity["parent_id"]) {
                           // only assign parent locations.
                           $r .= "<tr><td>" . $entity["name"] . "</td>";
                           $defaultuserids = iform_loctools_getusers($node, $entity["id"]);
                           foreach ($userlist as $uid => $a_user) {
                               $r .= '<td><input type="checkbox" name="location:' . $entity["id"] . ':' . $uid . (in_array($uid, $defaultuserids) ? '" checked="checked"' : '"') . '></td>';
                           }
                           $r .= "</tr>";
                       }
                   }
               }
               $r .= "</table>\n      <input type=\"submit\" class=\"ui-state-default ui-corner-all\" value=\"" . lang::get('LANG_Save_Location_Allocations') . "\" />\n    </form>\n  </div>";
           }
           if (count($tabs) > 1) {
               // close tabs div if present
               $r .= "</div>";
           }
           return $r;
       }
       if ($mode == MODE_EXISTING) {
           data_entry_helper::$entity_to_load = array();
           // Displaying an existing sample. If we know the occurrence ID, and don't know the sample ID or are displaying just one occurrence
           // rather than a grid of occurrences then we must load the occurrence data.
           if ($loadedOccurrenceId && (!$loadedSampleId || !self::getGridMode($args))) {
               // The URL has provided us with an occurrence ID, but we need to know the sample ID as well.
               $url = $svcUrl . "/data/occurrence/{$loadedOccurrenceId}";
               $url .= "?mode=json&view=detail&auth_token=" . $auth['read']['auth_token'] . "&nonce=" . $auth['read']["nonce"];
               $session = curl_init($url);
               curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
               $entity = json_decode(curl_exec($session), true);
               // Get the sample ID for the occurrence. This overwrites it if supply in GET but did not match the occurrence's sample
               $loadedSampleId = $entity[0]['sample_id'];
               if (!self::getGridMode($args)) {
                   // populate the entity to load with the single occurrence's data
                   foreach ($entity[0] as $key => $value) {
                       data_entry_helper::$entity_to_load['occurrence:' . $key] = $value;
                   }
               }
           }
           if ($loadedSampleId) {
               $url = $svcUrl . '/data/sample/' . $loadedSampleId;
               $url .= "?mode=json&view=detail&auth_token=" . $auth['read']['auth_token'] . "&nonce=" . $auth['read']["nonce"];
               $session = curl_init($url);
               curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
               $entity = json_decode(curl_exec($session), true);
               // Build a list of the sample data.
               foreach ($entity[0] as $key => $value) {
                   data_entry_helper::$entity_to_load['sample:' . $key] = $value;
               }
               data_entry_helper::$entity_to_load['sample:geom'] = '';
               // value received from db is not WKT, which is assumed by all the code.
               data_entry_helper::$entity_to_load['sample:date'] = data_entry_helper::$entity_to_load['sample:date_start'];
               // bit of a bodge to get around vague dates.
           }
       }
       // atributes must be fetched after the entity to load is filled in - this is because the id gets filled in then!
       $attributes = data_entry_helper::getAttributes(array('id' => data_entry_helper::$entity_to_load['sample:id'], 'valuetable' => 'sample_attribute_value', 'attrtable' => 'sample_attribute', 'key' => 'sample_id', 'fieldprefix' => 'smpAttr', 'extraParams' => $auth['read'], 'survey_id' => $args['survey_id']));
       // Make sure the form action points back to this page
       $reload = data_entry_helper::get_reload_link_parts();
       $reloadPath = $reload['path'];
       $r = "<form method=\"post\" id=\"entry_form\" action=\"{$reloadPath}\">\n";
       // Get authorisation tokens to update the Warehouse, plus any other hidden data.
       $hiddens = $auth['write'] . "<input type=\"hidden\" id=\"website_id\" name=\"website_id\" value=\"" . $args['website_id'] . "\" />\n" . "<input type=\"hidden\" id=\"survey_id\" name=\"survey_id\" value=\"" . $args['survey_id'] . "\" />\n";
       if (isset(data_entry_helper::$entity_to_load['sample:id'])) {
           $hiddens .= "<input type=\"hidden\" id=\"sample:id\" name=\"sample:id\" value=\"" . data_entry_helper::$entity_to_load['sample:id'] . "\" />\n";
       }
       if (isset(data_entry_helper::$entity_to_load['occurrence:id'])) {
           $hiddens .= "<input type=\"hidden\" id=\"occurrence:id\" name=\"occurrence:id\" value=\"" . data_entry_helper::$entity_to_load['occurrence:id'] . "\" />\n";
       }
       // Check if Record Status is included as a control. If not, then add it as a hidden.
       $arr = explode("\r\n", $args['structure']);
       if (!in_array('[record status]', $arr)) {
           $value = isset($args['defaults']['occurrence:record_status']) ? $args['defaults']['occurrence:record_status'] : 'C';
           $hiddens .= "<input type=\"hidden\" id=\"occurrence:record_status\" name=\"occurrence:record_status\" value=\"{$value}\" />\n";
       }
       // request automatic JS validation
       if (!isset($args['clientSideValidation']) || $args['clientSideValidation']) {
           data_entry_helper::enable_validation('entry_form');
       }
       // If logged in, output some hidden data about the user
       foreach ($attributes as &$attribute) {
           if (strcasecmp($attribute['caption'], 'cms user id') == 0) {
               if ($logged_in) {
                   $attribute['value'] = $user->uid;
               }
               $attribute['handled'] = true;
               // user id attribute is never displayed
           } elseif (strcasecmp($attribute['caption'], 'cms username') == 0) {
               if ($logged_in) {
                   $attribute['value'] = $user->name;
               }
               $attribute['handled'] = true;
               // username attribute is never displayed
           } elseif (strcasecmp($attribute['caption'], 'email') == 0) {
               if ($logged_in) {
                   if ($args['emailShow'] != true) {
                       // email attribute is not displayed
                       $attribute['value'] = $user->mail;
                       $attribute['handled'] = true;
                   } else {
                       $attribute['default'] = $user->mail;
                   }
               }
           } elseif ((strcasecmp($attribute['caption'], 'first name') == 0 || strcasecmp($attribute['caption'], 'last name') == 0 || strcasecmp($attribute['caption'], 'surname') == 0) && $logged_in) {
               if ($args['nameShow'] != true) {
                   // name attributes are not displayed
                   $attribute['handled'] = true;
               }
           }
           if (isset($attribute['value'])) {
               $hiddens .= '<input type="hidden" name="' . $attribute['fieldname'] . '" value="' . $attribute['value'] . '" />' . "\n";
           }
       }
       $customAttributeTabs = self::get_attribute_tabs($attributes);
       $tabs = self::get_all_tabs($args['structure'], $customAttributeTabs);
       $r .= "<div id=\"controls\">\n";
       // Build a list of the tabs that actually have content
       $tabHtml = self::get_tab_html($tabs, $auth, $args, $attributes, $hiddens);
       // Output the dynamic tab headers
       if ($args['interface'] != 'one_page') {
           $headerOptions = array('tabs' => array());
           foreach ($tabHtml as $tab => $tabContent) {
               $alias = preg_replace('/[^a-zA-Z0-9]/', '', strtolower($tab));
               $tabtitle = lang::get("LANG_Tab_{$alias}");
               if ($tabtitle == "LANG_Tab_{$alias}") {
                   // if no translation provided, we'll just use the standard heading
                   $tabtitle = $tab;
               }
               $headerOptions['tabs']['#' . $alias] = $tabtitle;
           }
           $r .= data_entry_helper::tab_header($headerOptions);
           data_entry_helper::enable_tabs(array('divId' => 'controls', 'style' => $args['interface'], 'progressBar' => isset($args['tabProgress']) && $args['tabProgress'] == true));
       }
       // Output the dynamic tab content
       $pageIdx = 0;
       foreach ($tabHtml as $tab => $tabContent) {
           // get a machine readable alias for the heading
           $tabalias = preg_replace('/[^a-zA-Z0-9]/', '', strtolower($tab));
           $r .= '<div id="' . $tabalias . '">' . "\n";
           // For wizard include the tab title as a header.
           if ($args['interface'] == 'wizard') {
               $r .= '<h1>' . $headerOptions['tabs']['#' . $tabalias] . '</h1>';
           }
           $r .= $tabContent;
           // Add any buttons required at the bottom of the tab
           if ($args['interface'] == 'wizard') {
               $r .= data_entry_helper::wizard_buttons(array('divId' => 'controls', 'page' => $pageIdx === 0 ? 'first' : ($pageIdx == count($tabs) - 1 ? 'last' : 'middle')));
           } elseif ($pageIdx == count($tabs) - 1 && !($args['interface'] == 'tabs' && $args['save_button_below_all_pages'])) {
               // last part of a non wizard interface must insert a save button, unless it is tabbed interface with save button beneath all pages
               $r .= "<input type=\"submit\" class=\"ui-state-default ui-corner-all\" value=\"" . lang::get('LANG_Save') . "\" />\n";
           }
           $pageIdx++;
           $r .= "</div>\n";
       }
       $r .= "</div>\n";
       if ($args['interface'] == 'tabs' && $args['save_button_below_all_pages']) {
           $r .= "<input type=\"submit\" class=\"ui-state-default ui-corner-all\" value=\"" . lang::get('LANG_Save') . "\" />\n";
       }
       if (!empty(data_entry_helper::$validation_errors)) {
           $r .= data_entry_helper::dump_remaining_errors();
       }
       $r .= "</form>";
       // may need to keep following code for location change functionality
       // @todo Why is this not in the data entry helper, and is it really needed?
       if (self::$want_location_layer) {
           data_entry_helper::$onload_javascript .= "\n    \nlocationChange = function(obj){\n  locationLayer.destroyFeatures();\n  if(obj.value != ''){\n    jQuery.getJSON(\"" . $svcUrl . "\" + \"/data/location/\"+obj.value +\n      \"?mode=json&view=detail&auth_token=" . $auth['read']['auth_token'] . "&nonce=" . $auth['read']["nonce"] . "\" +\n      \"&callback=?\", function(data) {\n        if (data.length>0) {\n          var parser = new OpenLayers.Format.WKT();\n          for (var i=0;i<data.length;i++) {\n            if(data[i].centroid_geom){\n              feature = parser.read(data[i].centroid_geom);\n              centre = feature.geometry.getCentroid();\n              centrefeature = new OpenLayers.Feature.Vector(centre, {}, {label: data[i].name});\n              locationLayer.addFeatures([feature, centrefeature]); \n            }\n            if (data[i].boundary_geom){\n              feature = parser.read(data[i].boundary_geom);\n              feature.style = {strokeColor: \"Blue\",\n                  strokeWidth: 2,\n                  label: (data[i].centroid_geom ? \"\" : data[i].name)};\n                  locationLayer.addFeatures([feature]);\n            }\n          }\n          var extent=locationLayer.getDataExtent();\n          if (extent!==null) {\n            locationLayer.map.zoomToExtent(extent);\n          }\n        }\n\t\t  }\n    );\n  }\n};\njQuery('#imp-location').unbind('change');\njQuery('#imp-location').change(function(){\n\tlocationChange(this);\n});\n\nvar updatePlaceTabHandler = function(event, ui) { \n  if (ui.panel.id=='place') {\n    // upload location & sref initial values into map.\n    jQuery('#imp-location').change();\n    jQuery('#imp-sref').change();\n    jQuery('#controls').unbind('tabsshow', updatePlaceTabHandler);\n  }\n}\njQuery('#controls').bind('tabsshow', updatePlaceTabHandler);\n\n";
       }
       $r .= self::link_species_popups($args);
       return $r;
   }
   /**
    * Construct a grid of existing records.
    * @param array $args iform parameters.
    * @param object $node node being shown.
    * @param array $auth authentication tokens for accessing the warehouse.
    * @return string HTML for grid.
    */
   protected static function getGrid($args, $node, $auth)
   {
       $r = '';
       $attributeOpts = array('valuetable' => 'sample_attribute_value', 'attrtable' => 'sample_attribute', 'key' => 'sample_id', 'fieldprefix' => 'smpAttr', 'extraParams' => $auth['read'], 'survey_id' => $args['survey_id']);
       if (isset($args['sample_method_id'])) {
           $attributeOpts['sample_method_id'] = $args['sample_method_id'];
       }
       $attributes = data_entry_helper::getAttributes($attributeOpts, false);
       $tabs = array('#sampleList' => lang::get('LANG_Main_Samples_Tab'));
       // Add in a tab for the allocation of locations if this option was selected
       if ($args['includeLocTools'] && function_exists('iform_loctools_checkaccess') && iform_loctools_checkaccess($node, 'admin')) {
           $tabs['#setLocations'] = lang::get('LANG_Allocate_Locations');
       }
       // An option for derived classes to add in extra tabs
       if (method_exists(self::$called_class, 'getExtraGridModeTabs')) {
           $extraTabs = call_user_func(array(self::$called_class, 'getExtraGridModeTabs'), false, $auth['read'], $args, $attributes);
           if (is_array($extraTabs)) {
               $tabs = $tabs + $extraTabs;
           }
       }
       // Only actually need to show tabs if there is more than one
       if (count($tabs) > 1) {
           $active = isset($_GET['page']) ? '#setLocations' : '#sampleList';
           $r .= "<div id=\"controls\">" . data_entry_helper::enable_tabs(array('divId' => 'controls', 'active' => $active)) . "<div id=\"temp\"></div>";
           $r .= data_entry_helper::tab_header(array('tabs' => $tabs));
       }
       // Here is where we get the table of samples
       $r .= "<div id=\"sampleList\">" . call_user_func(array(self::$called_class, 'getSampleListGrid'), $args, $node, $auth, $attributes) . "</div>";
       // Add content to the Allocate Locations tab if this option was selected
       if ($args['includeLocTools'] && function_exists('iform_loctools_checkaccess') && iform_loctools_checkaccess($node, 'admin')) {
           $r .= '<div id="setLocations">';
           $url = data_entry_helper::$base_url . '/index.php/services/data/location?mode=json&view=detail' . '&auth_token=' . $auth['read']['auth_token'] . '&nonce=' . $auth['read']["nonce"] . "&parent_id=NULL&orderby=name" . "&columns=id,name" . (isset($args['loctoolsLocTypeID']) && $args['loctoolsLocTypeID'] != '' ? '&location_type_id=' . $args['loctoolsLocTypeID'] : '');
           if (!isset($options['loctoolsPageSize'])) {
               $options['loctoolsPageSize'] = 20;
           }
           $page = empty($_REQUEST['page']) ? 1 : $_REQUEST['page'];
           // starts at 1.
           $session = curl_init($url);
           curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
           $entities = json_decode(curl_exec($session), true);
           $pages = ceil(count($entities) / $options['loctoolsPageSize']);
           // starts at 1
           $count = $page < $pages ? $options['loctoolsPageSize'] : (count($entities) - 1) % $options['loctoolsPageSize'] + 1;
           // number displayed on this page
           // build a jumper control:
           if ($pages > 1) {
               $reload = data_entry_helper::get_reload_link_parts();
               $r .= '<form method="GET" action="' . $reload['path'] . '">';
               if (count($reload['params'])) {
                   foreach ($reload['params'] as $param => $value) {
                       if ($param != "page") {
                           $r .= '<input type="hidden" name="' . $param . '" value="' . $value . '">';
                       }
                   }
               }
               $r .= '<label style="width:auto;" for="pageField">' . lang::get('Jump to page for location') . ':</label><select id="pageField" name="page"><option value="1">' . lang::get('Pick') . '</option>';
               foreach ($entities as $idx => $entity) {
                   $r .= '<option value="' . ceil(($idx + 1) / $options['loctoolsPageSize']) . '">' . $entity["name"] . '</option>';
               }
               $r .= "<input type=\"submit\" class=\"default-button\" value=\"" . lang::get('Go') . "\" /></form>\n";
               $r .= '<p>' . lang::get('You must save any changes made to data on this page before viewing any other page, otherwise those changes will be lost.') . "</p>\n";
           }
           $r .= '<form method="post"><input type="hidden" id="mnhnld1" name="mnhnld1" value="mnhnld1" /><input type="hidden" name="page" value="' . $page . '" />
 <div class="location-allocation-wrapper-outer" ><div class="location-allocation-wrapper-inner"><table border="1"></thead><tr><th class="freeze-first-col">' . lang::get('Location') . '</th>';
           // Main table body
           $userlist = iform_loctools_listusers($node);
           foreach ($userlist as $uid => $a_user) {
               $r .= '<th>' . $a_user->name . '</th>';
           }
           $r .= "</tr></thead><tbody>";
           if (!empty($entities)) {
               for ($i = 0; $i < $count; $i++) {
                   $entity = $entities[$i + ($page - 1) * $options['loctoolsPageSize']];
                   // only assign parent locations.
                   $r .= '<tr><td class="freeze-first-col">' . $entity["name"] . '</td>';
                   $defaultuserids = iform_loctools_getusers($node, $entity["id"]);
                   foreach ($userlist as $uid => $a_user) {
                       $r .= '<td><input type="hidden" name="location:' . $entity["id"] . ':' . $uid . '" value="0"><input type="checkbox" name="location:' . $entity["id"] . ':' . $uid . (in_array($uid, $defaultuserids) ? '" checked="checked"' : '"') . ' value="1"></td>';
                   }
                   $r .= "</tr>";
               }
           }
           $r .= "<tbody></table></div></div>\n";
           // build pager outside scrollable table.
           $numEachSide = 5;
           if ($pages > 1) {
               $path = iform_mnhnl_getReloadPath();
               $path .= (strpos($path, '?') === false ? '?' : '&') . 'page=';
               $r .= "<div class=\"pager ui-helper-clearfix\">";
               if ($page == 1) {
                   $r .= '<span class="ui-state-disabled pager-button">1</span>';
               } else {
                   $r .= '<a class="pager-button" href="' . $path . '1" rel="nofollow">1</a>';
               }
               if ($page - $numEachSide > 2) {
                   $r .= '...';
               }
               for ($i = max(2, $page - $numEachSide); $i <= min($pages - 1, $page + $numEachSide); $i++) {
                   if ($page == $i) {
                       $r .= ' <span class="ui-state-disabled pager-button">' . $i . '</span> ';
                   } else {
                       $r .= '<a class="pager-button" href="' . $path . $i . '" rel="nofollow">' . $i . '</a>';
                   }
               }
               if ($page + $numEachSide < $pages - 1) {
                   $r .= '...';
               }
               if ($page == $pages) {
                   $r .= '<span class="ui-state-disabled pager-button">' . $pages . '</span>';
               } else {
                   $r .= '<a class="pager-button" href="' . $path . $pages . '" rel="nofollow">' . $pages . '</a>';
               }
               $r .= "</div>";
           }
           $r .= '</table><input type="submit" class="default-button" value="' . lang::get('Save Location Allocations') . '" /></form></div>';
       }
       // Add content to extra tabs that derived classes may have added
       if (method_exists(self::$called_class, 'getExtraGridModeTabs')) {
           $r .= call_user_func(array(self::$called_class, 'getExtraGridModeTabs'), true, $auth['read'], $args, $attributes);
       }
       // Close tabs div if present
       if (count($tabs) > 1) {
           $r .= "</div>";
       }
       return $r;
   }
   /**
    * Return the generated form output.
    * @return Form HTML.
    */
   public static function get_form($args, $node)
   {
       define("MODE_GRID", 0);
       define("MODE_NEW_SAMPLE", 1);
       define("MODE_EXISTING", 2);
       self::parse_defaults($args);
       self::getArgDefaults($args);
       self::$node = $node;
       // if we use locks, we want them to be distinct for each drupal user
       if (function_exists('profile_load_profile')) {
           // check we are in drupal
           global $user;
           data_entry_helper::$javascript .= "if (indicia && indicia.locks && indicia.locks.setUser) {\n        indicia.locks.setUser ('" . $user->uid . "');\n      }\n";
       }
       // hard-wire some 'dynamic' options to simplify the form. Todo: take out the dynamic code for these
       $args['subjectAccordion'] = false;
       $args['emailShow'] = false;
       $args['nameShow'] = false;
       $args['copyFromProfile'] = false;
       $args['multiple_subject_observation_mode'] = 'single';
       $args['extra_list_id'] = '';
       $args['occurrence_comment'] = false;
       $args['col_widths'] = '';
       $args['includeLocTools'] = false;
       $args['loctoolsLocTypeID'] = 0;
       $args['subject_observation_confidential'] = false;
       $args['observation_images'] = false;
       // Get authorisation tokens to update and read from the Warehouse.
       $auth = data_entry_helper::get_read_write_auth($args['website_id'], $args['password']);
       $svcUrl = self::warehouseUrl() . 'index.php/services';
       self::$auth = $auth;
       drupal_add_js(iform_media_folder_path() . 'js/jquery.form.js', 'module');
       $mode = isset($args['no_grid']) && $args['no_grid'] ? MODE_NEW_SAMPLE : MODE_GRID;
       // default mode when no grid set to false - display grid of existing data
       // mode MODE_EXISTING: display existing sample
       $loadedSampleId = null;
       $loadedSubjectObservationId = null;
       if ($_POST) {
           if (!array_key_exists('website_id', $_POST)) {
               // non Indicia POST, in this case must be the location allocations. add check to ensure we don't corrept the data by accident
               if (function_exists('iform_loctools_checkaccess') && iform_loctools_checkaccess($node, 'admin') && array_key_exists('mnhnld1', $_POST)) {
                   iform_loctools_deletelocations($node);
                   foreach ($_POST as $key => $value) {
                       $parts = explode(':', $key);
                       iform_loctools_insertlocation($node, $parts[2], $parts[1]);
                   }
               }
           } else {
               if (!is_null(data_entry_helper::$entity_to_load)) {
                   $mode = MODE_EXISTING;
                   // errors with new sample, entity populated with post, so display this data.
               }
           }
           // else valid save, so go back to gridview: default mode 0
       }
       if (array_key_exists('sample_id', $_GET) && $_GET['sample_id'] != '{sample_id}') {
           $mode = MODE_EXISTING;
           $loadedSampleId = $_GET['sample_id'];
       }
       if (array_key_exists('subject_observation_id', $_GET) && $_GET['subject_observation_id'] != '{subject_observation_id}') {
           $mode = MODE_EXISTING;
           // single subject_observation case
           $loadedSubjectObservationId = $_GET['subject_observation_id'];
           self::$subjectObservationIds = array($loadedSubjectObservationId);
       }
       if ($mode != MODE_EXISTING && array_key_exists('newSample', $_GET)) {
           $mode = MODE_NEW_SAMPLE;
           data_entry_helper::$entity_to_load = array();
       }
       // else default to mode MODE_GRID or MODE_NEW_SAMPLE depending on no_grid parameter
       self::$mode = $mode;
       // default mode  MODE_GRID : display grid of the samples to add a new one
       // or edit an existing one.
       if ($mode == MODE_GRID) {
           $r = '';
           // debug section
           if (!empty($args['debug_info']) && $args['debug_info']) {
               $r .= '<input type="button" value="Debug info" onclick="$(\'#debug-info-div\').slideToggle();" /><br />' . '<div id="debug-info-div" style="display: none;">';
               $r .= '<p>$_GET is:<br /><pre>' . print_r($_GET, true) . '</pre></p>';
               $r .= '<p>$_POST is:<br /><pre>' . print_r($_POST, true) . '</pre></p>';
               $r .= '<p>Entity to load is:<br /><pre>' . print_r(data_entry_helper::$entity_to_load, true) . '</pre></p>';
               $r .= '<p>Submission was:<br /><pre>' . print_r(self::$submission, true) . '</pre></p>';
               $r .= '<input type="button" value="Hide debug info" onclick="$(\'#debug-info-div\').slideToggle();" />';
               $r .= '</div>';
           }
           if (method_exists(get_called_class(), 'getHeaderHTML')) {
               $r .= call_user_func(array(get_called_class(), 'getHeaderHTML'), true, $args);
           }
           $attributes = data_entry_helper::getAttributes(array('valuetable' => 'sample_attribute_value', 'attrtable' => 'sample_attribute', 'key' => 'sample_id', 'fieldprefix' => 'smpAttr', 'extraParams' => $auth['read'], 'survey_id' => $args['survey_id']), false);
           $tabs = array('#sampleList' => lang::get('LANG_Main_Samples_Tab'));
           if ($args['includeLocTools'] && function_exists('iform_loctools_checkaccess') && iform_loctools_checkaccess($node, 'admin')) {
               $tabs['#setLocations'] = lang::get('LANG_Allocate_Locations');
           }
           if (method_exists(get_called_class(), 'getExtraGridModeTabs')) {
               $extraTabs = call_user_func(array(get_called_class(), 'getExtraGridModeTabs'), false, $auth['read'], $args, $attributes);
               if (is_array($extraTabs)) {
                   $tabs = $tabs + $extraTabs;
               }
           }
           if (count($tabs) > 1) {
               $r .= "<div id=\"controls\">" . data_entry_helper::enable_tabs(array('divId' => 'controls', 'active' => '#sampleList')) . "<div id=\"temp\"></div>";
               $r .= data_entry_helper::tab_header(array('tabs' => $tabs));
           }
           $r .= "<div id=\"sampleList\">" . call_user_func(array(get_called_class(), 'getSampleListGrid'), $args, $node, $auth, $attributes) . "</div>";
           if ($args['includeLocTools'] && function_exists('iform_loctools_checkaccess') && iform_loctools_checkaccess($node, 'admin')) {
               $r .= '
 <div id="setLocations">
   <form method="post">
     <input type="hidden" id="mnhnld1" name="mnhnld1" value="mnhnld1" /><table border="1"><tr><td></td>';
               $url = $svcUrl . '/data/location?mode=json&view=detail&auth_token=' . $auth['read']['auth_token'] . "&nonce=" . $auth['read']["nonce"] . "&parent_id=NULL&orderby=name" . (isset($args['loctoolsLocTypeID']) && $args['loctoolsLocTypeID'] != '' ? '&location_type_id=' . $args['loctoolsLocTypeID'] : '');
               $session = curl_init($url);
               curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
               $entities = json_decode(curl_exec($session), true);
               $userlist = iform_loctools_listusers($node);
               foreach ($userlist as $uid => $a_user) {
                   $r .= '<td>' . $a_user->name . '</td>';
               }
               $r .= "</tr>";
               if (!empty($entities)) {
                   foreach ($entities as $entity) {
                       if (!$entity["parent_id"]) {
                           // only assign parent locations.
                           $r .= "<tr><td>" . $entity["name"] . "</td>";
                           $defaultuserids = iform_loctools_getusers($node, $entity["id"]);
                           foreach ($userlist as $uid => $a_user) {
                               $r .= '<td><input type="checkbox" name="location:' . $entity["id"] . ':' . $uid . (in_array($uid, $defaultuserids) ? '" checked="checked"' : '"') . '></td>';
                           }
                           $r .= "</tr>";
                       }
                   }
               }
               $r .= "</table>\n      <input type=\"submit\" class=\"ui-state-default ui-corner-all\" value=\"" . lang::get('LANG_Save_Location_Allocations') . "\" />\n    </form>\n  </div>";
           }
           if (method_exists(get_called_class(), 'getExtraGridModeTabs')) {
               $r .= call_user_func(array(get_called_class(), 'getExtraGridModeTabs'), true, $auth['read'], $args, $attributes);
           }
           if (count($tabs) > 1) {
               // close tabs div if present
               $r .= "</div>";
           }
           if (method_exists(get_called_class(), 'getTrailerHTML')) {
               $r .= call_user_func(array(get_called_class(), 'getTrailerHTML'), true, $args);
           }
           return $r;
       }
       // from this point on, we are MODE_EXISTING or MODE_NEW_SAMPLE
       if ($mode == MODE_EXISTING && is_null(data_entry_helper::$entity_to_load)) {
           // only load if not in error situation
           // Displaying an existing sample. If we know the subject_observation ID, and don't know the sample ID
           // then we must get the sample id from the subject_observation data.
           if ($loadedSubjectObservationId && !$loadedSampleId) {
               data_entry_helper::load_existing_record($auth['read'], 'subject_observation', $loadedSubjectObservationId);
               $loadedSampleId = data_entry_helper::$entity_to_load['subject_observation:sample_id'];
           }
           data_entry_helper::$entity_to_load = self::reload_form_data($loadedSampleId, $args, $auth);
       }
       // get the sample attributes
       $attrOpts = array('id' => data_entry_helper::$entity_to_load['sample:id'], 'valuetable' => 'sample_attribute_value', 'attrtable' => 'sample_attribute', 'key' => 'sample_id', 'fieldprefix' => 'smpAttr', 'extraParams' => $auth['read'], 'survey_id' => $args['survey_id']);
       // select only the custom attributes that are for this sample method or all sample methods, if this
       // form is for a specific sample method.
       if (!empty($args['sample_method_id'])) {
           $attrOpts['sample_method_id'] = $args['sample_method_id'];
       }
       $attributes = data_entry_helper::getAttributes($attrOpts, false);
       // Check if Recorder details is included as a control.
       // If so, remove the recorder attributes from the $attributes array so not output anywhere else.
       $arr = helper_base::explode_lines($args['structure']);
       if (in_array('[recorder details]', $arr)) {
           $attrCount = count($attributes);
           for ($i = 0; $i < $attrCount; $i++) {
               if (strcasecmp($attributes[$i]['caption'], 'first name') === 0 || strcasecmp($attributes[$i]['caption'], 'last name') === 0 || strcasecmp($attributes[$i]['caption'], 'email') === 0) {
                   unset($attributes[$i]);
               }
           }
       }
       //// Make sure the form action points back to this page
       $reload = data_entry_helper::get_reload_link_parts();
       unset($reload['params']['sample_id']);
       unset($reload['params']['subject_observation_id']);
       unset($reload['params']['newSample']);
       $reloadPath = $reload['path'];
       // don't url-encode the drupal path id using dirty url
       $pathParam = function_exists('variable_get') && variable_get('clean_url', 0) == '0' ? 'q' : '';
       if (count($reload['params'])) {
           if ($pathParam === 'q' && array_key_exists('q', $reload['params'])) {
               $reloadPath .= '?q=' . $reload['params']['q'];
               unset($reload['params']['q']);
               if (count($reload['params'])) {
                   $reloadPath .= '&' . http_build_query($reload['params']);
               }
           } else {
               $reloadPath .= '?' . http_build_query($reload['params']);
           }
       }
       $r = "<form method=\"post\" id=\"entry_form\" action=\"{$reloadPath}\">\n";
       // debug section
       if (!empty($args['debug_info']) && $args['debug_info']) {
           $r .= '<input type="button" value="Debug info" onclick="$(\'#debug-info-div\').slideToggle();" /><br />' . '<div id="debug-info-div" style="display: none;">';
           $r .= '<p>$_GET is:<br /><pre>' . print_r($_GET, true) . '</pre></p>';
           $r .= '<p>$_POST is:<br /><pre>' . print_r($_POST, true) . '</pre></p>';
           $r .= '<p>Entity to load is:<br /><pre>' . print_r(data_entry_helper::$entity_to_load, true) . '</pre></p>';
           $r .= '<p>Submission was:<br /><pre>' . print_r(self::$submission, true) . '</pre></p>';
           $r .= '<input type="button" value="Hide debug info" onclick="$(\'#debug-info-div\').slideToggle();" />';
           $r .= '</div>';
       }
       // reset button
       $r .= '<input type="button" class="ui-state-default ui-corner-all" value="' . lang::get('Abandon Form and Reload') . '" ' . 'onclick="window.location.href=\'' . url('node/' . $node->nid, array('query' => 'newSample')) . '\'">';
       // clear all padlocks button
       $r .= ' <input type="button" class="ui-state-default ui-corner-all" value="' . lang::get('Clear All Padlocks') . '" ' . 'onclick="if (indicia && indicia.locks) indicia.locks.unlockRegion(\'body\');">';
       // Get authorisation tokens to update the Warehouse, plus any other hidden data.
       $hiddens = $auth['write'] . "<input type=\"hidden\" id=\"read_auth_token\" name=\"read_auth_token\" value=\"" . $auth['read']['auth_token'] . "\" />\n" . "<input type=\"hidden\" id=\"read_nonce\" name=\"read_nonce\" value=\"" . $auth['read']['nonce'] . "\" />\n" . "<input type=\"hidden\" id=\"website_id\" name=\"website_id\" value=\"" . $args['website_id'] . "\" />\n" . "<input type=\"hidden\" id=\"survey_id\" name=\"survey_id\" value=\"" . $args['survey_id'] . "\" />\n";
       if (!empty($args['sample_method_id'])) {
           $hiddens .= '<input type="hidden" name="sample:sample_method_id" value="' . $args['sample_method_id'] . '"/>';
       }
       if (isset(data_entry_helper::$entity_to_load['sample:id'])) {
           $hiddens .= "<input type=\"hidden\" id=\"sample:id\" name=\"sample:id\" value=\"" . data_entry_helper::$entity_to_load['sample:id'] . "\" />\n";
       }
       // request automatic JS validation
       if (!isset($args['clientSideValidation']) || $args['clientSideValidation']) {
           data_entry_helper::enable_validation('entry_form');
           // override the default invalidHandler to activate the first accordion panels which has an error
           global $indicia_templates;
           $indicia_templates['invalid_handler_javascript'] = "function(form, validator) {\n          var tabselected=false;\n          var accordion\$=jQuery('.ui-accordion');\n          jQuery.each(validator.errorMap, function(ctrlId, error) {\n            // select the tab containing the first error control\n            var ctrl = jQuery('[name=' + ctrlId.replace(/:/g, '\\\\:').replace(/\\[/g, '\\\\[').replace(/]/g, '\\\\]') + ']');\n            if (!tabselected && typeof(tabs)!=='undefined') {\n              tabs.tabs('select',ctrl.filter('input,select').parents('.ui-tabs-panel')[0].id);\n              tabselected = true;\n            }\n            ctrl.parents('fieldset').removeClass('collapsed');\n            ctrl.parents('.fieldset-wrapper').show();\n            // for each accordion, activate the first panel which has an error\n            ctrl.parents('.ui-accordion-content').each(function (n) {\n              var acc\$ = \$(this).closest('.ui-accordion');\n              var accId = acc\$[0].id.replace(/:/g, '\\\\:').replace(/\\[/g, '\\\\[').replace(/]/g, '\\\\]');\n              if (accordion\$.is('#'+accId)) {\n                var header\$ = \$(this).prev('h3');\n                var accHeaderId = header\$.attr('id').replace(/:/g, '\\\\:').replace(/\\[/g, '\\\\[').replace(/]/g, '\\\\]');\n                acc\$.accordion('activate', '#'+accHeaderId);\n                accordion\$ = accordion\$.not('#'+accId);\n              }\n            });\n          });\n        }";
           // By default, validate doesn't validate any ':hidden' fields,
           // but we need to validate hidden with display: none; fields in accordions
           data_entry_helper::$javascript .= "jQuery.validator.setDefaults({ \n        ignore: \"input[type='hidden']\"\n      });\n";
       }
       if (method_exists(get_called_class(), 'getHeaderHTML')) {
           $r .= call_user_func(array(get_called_class(), 'getHeaderHTML'), true, $args);
       }
       if ($mode == MODE_EXISTING && ($loadedSampleId || $loadedSubjectObservationId)) {
           $existing = true;
       } else {
           $existing = false;
       }
       $hiddens .= get_user_profile_hidden_inputs($attributes, $args, $existing, $auth['read']);
       $customAttributeTabs = get_attribute_tabs($attributes);
       // remove added comment controls unless editing an existing sample
       if ($mode !== MODE_EXISTING || helper_base::$form_mode === 'ERRORS') {
           $controls = helper_base::explode_lines($args['structure']);
           $new_controls = array();
           foreach ($controls as $control) {
               if ($control !== '[show added sample comments]' && $control !== '[add sample comment]') {
                   $new_controls[] = $control;
               }
           }
           $args['structure'] = implode("\r\n", $new_controls);
       }
       $tabs = self::get_all_tabs($args['structure'], $customAttributeTabs);
       $r .= "<div id=\"controls\">\n";
       // Build a list of the tabs that actually have content
       $tabHtml = self::get_tab_html($tabs, $auth, $args, $attributes, $hiddens);
       // Output the dynamic tab headers
       if ($args['interface'] != 'one_page') {
           $headerOptions = array('tabs' => array());
           foreach ($tabHtml as $tab => $tabContent) {
               $alias = preg_replace('/[^a-zA-Z0-9]/', '', strtolower($tab));
               $tabtitle = lang::get("LANG_Tab_{$alias}");
               if ($tabtitle == "LANG_Tab_{$alias}") {
                   // if no translation provided, we'll just use the standard heading
                   $tabtitle = $tab;
               }
               $headerOptions['tabs']['#' . $alias] = $tabtitle;
           }
           $r .= data_entry_helper::tab_header($headerOptions);
           data_entry_helper::enable_tabs(array('divId' => 'controls', 'style' => $args['interface'], 'progressBar' => isset($args['tabProgress']) && $args['tabProgress'] == true));
       }
       // Output the dynamic tab content
       $pageIdx = 0;
       foreach ($tabHtml as $tab => $tabContent) {
           // get a machine readable alias for the heading
           $tabalias = preg_replace('/[^a-zA-Z0-9]/', '', strtolower($tab));
           $r .= '<div id="' . $tabalias . '">' . "\n";
           // For wizard include the tab title as a header.
           if ($args['interface'] == 'wizard') {
               $r .= '<h1>' . $headerOptions['tabs']['#' . $tabalias] . '</h1>';
           }
           $r .= $tabContent;
           // Add any buttons required at the bottom of the tab
           if ($args['interface'] == 'wizard') {
               $r .= data_entry_helper::wizard_buttons(array('divId' => 'controls', 'page' => $pageIdx === 0 ? 'first' : ($pageIdx == count($tabHtml) - 1 ? 'last' : 'middle')));
           } elseif ($pageIdx == count($tabHtml) - 1 && !($args['interface'] == 'tabs' && $args['save_button_below_all_pages'])) {
               // last part of a non wizard interface must insert a save button, unless it is tabbed interface with save button beneath all pages
               $r .= "<input type=\"submit\" class=\"ui-state-default ui-corner-all\" id=\"save-button\" value=\"" . lang::get('LANG_Save') . "\" />\n";
           }
           $pageIdx++;
           $r .= "</div>\n";
       }
       $r .= "</div>\n";
       if ($args['interface'] == 'tabs' && $args['save_button_below_all_pages']) {
           $r .= "<input type=\"submit\" class=\"ui-state-default ui-corner-all\" id=\"save-button\" value=\"" . lang::get('LANG_Save') . "\" />\n";
       }
       if (!empty(data_entry_helper::$validation_errors)) {
           $r .= data_entry_helper::dump_remaining_errors();
       }
       $r .= "</form>";
       if (method_exists(get_called_class(), 'getTrailerHTML')) {
           $r .= call_user_func(array(get_called_class(), 'getTrailerHTML'), true, $args);
       }
       return $r;
   }
Example #4
0
   /**
    * Return the generated form output.
    * @return Form HTML.
    */
   public static function get_form($args, $node)
   {
       define("MODE_GRID", 0);
       define("MODE_NEW_SAMPLE", 1);
       define("MODE_EXISTING", 2);
       self::parse_defaults($args);
       self::getArgDefaults($args);
       global $user;
       $logged_in = $user->uid > 0;
       self::$node = $node;
       // Get authorisation tokens to update and read from the Warehouse.
       $auth = data_entry_helper::get_read_write_auth($args['website_id'], $args['password']);
       $svcUrl = data_entry_helper::$base_url . '/index.php/services';
       self::$auth = $auth;
       $mode = isset($args['no_grid']) && $args['no_grid'] ? MODE_NEW_SAMPLE : MODE_GRID;
       // default mode when no grid set to false - display grid of existing data
       // mode MODE_EXISTING: display existing sample
       $loadedSampleId = null;
       $loadedOccurrenceId = null;
       if ($_POST) {
           if (!array_key_exists('website_id', $_POST)) {
               // non Indicia POST, in this case must be the location allocations. add check to ensure we don't corrept the data by accident
               if (function_exists('iform_loctools_checkaccess') && iform_loctools_checkaccess($node, 'admin') && array_key_exists('mnhnld1', $_POST)) {
                   iform_loctools_deletelocations($node);
                   foreach ($_POST as $key => $value) {
                       $parts = explode(':', $key);
                       iform_loctools_insertlocation($node, $parts[2], $parts[1]);
                   }
               }
           } else {
               if (!is_null(data_entry_helper::$entity_to_load)) {
                   $mode = MODE_EXISTING;
                   // errors with new sample, entity populated with post, so display this data.
               }
           }
           // else valid save, so go back to gridview: default mode 0
       }
       if (array_key_exists('sample_id', $_GET) && $_GET['sample_id'] != '{sample_id}') {
           $mode = MODE_EXISTING;
           $loadedSampleId = $_GET['sample_id'];
       }
       if (array_key_exists('occurrence_id', $_GET) && $_GET['occurrence_id'] != '{occurrence_id}') {
           $mode = MODE_EXISTING;
           $loadedOccurrenceId = $_GET['occurrence_id'];
           self::$occurrenceIds = array($loadedOccurrenceId);
       }
       if ($mode != MODE_EXISTING && array_key_exists('newSample', $_GET)) {
           $mode = MODE_NEW_SAMPLE;
           data_entry_helper::$entity_to_load = array();
       }
       // else default to mode MODE_GRID or MODE_NEW_SAMPLE depending on no_grid parameter
       self::$mode = $mode;
       // default mode  MODE_GRID : display grid of the samples to add a new one
       // or edit an existing one.
       if ($mode == MODE_GRID) {
           $r = '';
           $attributes = data_entry_helper::getAttributes(array('valuetable' => 'sample_attribute_value', 'attrtable' => 'sample_attribute', 'key' => 'sample_id', 'fieldprefix' => 'smpAttr', 'extraParams' => $auth['read'], 'survey_id' => $args['survey_id']), false);
           $tabs = array('#sampleList' => lang::get('LANG_Main_Samples_Tab'));
           if ($args['includeLocTools'] && function_exists('iform_loctools_checkaccess') && iform_loctools_checkaccess($node, 'admin')) {
               $tabs['#setLocations'] = lang::get('LANG_Allocate_Locations');
           }
           if (method_exists(get_called_class(), 'getExtraGridModeTabs')) {
               $extraTabs = call_user_func(array(get_called_class(), 'getExtraGridModeTabs'), false, $auth['read'], $args, $attributes);
               if (is_array($extraTabs)) {
                   $tabs = $tabs + $extraTabs;
               }
           }
           if (count($tabs) > 1) {
               $r .= "<div id=\"controls\">" . data_entry_helper::enable_tabs(array('divId' => 'controls', 'active' => '#sampleList')) . "<div id=\"temp\"></div>";
               $r .= data_entry_helper::tab_header(array('tabs' => $tabs));
           }
           $r .= "<div id=\"sampleList\">" . call_user_func(array(get_called_class(), 'getSampleListGrid'), $args, $node, $auth, $attributes) . "</div>";
           if ($args['includeLocTools'] && function_exists('iform_loctools_checkaccess') && iform_loctools_checkaccess($node, 'admin')) {
               $r .= '
 <div id="setLocations">
   <form method="post">
     <input type="hidden" id="mnhnld1" name="mnhnld1" value="mnhnld1" /><table border="1"><tr><td></td>';
               $url = $svcUrl . '/data/location?mode=json&view=detail&auth_token=' . $auth['read']['auth_token'] . "&nonce=" . $auth['read']["nonce"] . "&parent_id=NULL&orderby=name";
               $session = curl_init($url);
               curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
               $entities = json_decode(curl_exec($session), true);
               $userlist = iform_loctools_listusers($node);
               foreach ($userlist as $uid => $a_user) {
                   $r .= '<td>' . $a_user->name . '</td>';
               }
               $r .= "</tr>";
               if (!empty($entities)) {
                   foreach ($entities as $entity) {
                       if (!$entity["parent_id"]) {
                           // only assign parent locations.
                           $r .= "<tr><td>" . $entity["name"] . "</td>";
                           $defaultuserids = iform_loctools_getusers($node, $entity["id"]);
                           foreach ($userlist as $uid => $a_user) {
                               $r .= '<td><input type="checkbox" name="location:' . $entity["id"] . ':' . $uid . (in_array($uid, $defaultuserids) ? '" checked="checked"' : '"') . '></td>';
                           }
                           $r .= "</tr>";
                       }
                   }
               }
               $r .= "</table>\n      <input type=\"submit\" class=\"ui-state-default ui-corner-all\" value=\"" . lang::get('LANG_Save_Location_Allocations') . "\" />\n    </form>\n  </div>";
           }
           if (method_exists(get_called_class(), 'getExtraGridModeTabs')) {
               $r .= call_user_func(array(get_called_class(), 'getExtraGridModeTabs'), true, $auth['read'], $args, $attributes);
           }
           if (count($tabs) > 1) {
               // close tabs div if present
               $r .= "</div>";
           }
           return $r;
       }
       if ($mode == MODE_EXISTING && is_null(data_entry_helper::$entity_to_load)) {
           // only load if not in error situation
           data_entry_helper::$entity_to_load = array();
           // Displaying an existing sample. If we know the occurrence ID, and don't know the sample ID or are displaying just one occurrence
           // rather than a grid of occurrences then we must load the occurrence data to get the sample id.
           if ($loadedOccurrenceId && (!$loadedSampleId || !self::getGridMode($args))) {
               data_entry_helper::load_existing_record($auth['read'], 'occurrence', $loadedOccurrenceId);
               // Get the sample ID for the occurrence. This overwrites it if supply in GET but did not match the occurrence's sample
               $loadedSampleId = data_entry_helper::$entity_to_load['occurrence:sample_id'];
               if (self::getGridMode($args)) {
                   // in grid mode, we only needed to load the occurrence to find out the sample id.
                   data_entry_helper::$entity_to_load = array();
               }
           }
           if ($loadedSampleId) {
               data_entry_helper::load_existing_record($auth['read'], 'sample', $loadedSampleId);
           }
       }
       // attributes must be fetched after the entity to load is filled in - this is because the id gets filled in then!
       $attrOpts = array('id' => data_entry_helper::$entity_to_load['sample:id'], 'valuetable' => 'sample_attribute_value', 'attrtable' => 'sample_attribute', 'key' => 'sample_id', 'fieldprefix' => 'smpAttr', 'extraParams' => $auth['read'], 'survey_id' => $args['survey_id']);
       // select only the custom attributes that are for this sample method or all sample methods, if this
       // form is for a specific sample method.
       if (!empty($args['sample_method_id'])) {
           $attrOpts['sample_method_id'] = $args['sample_method_id'];
       }
       $attributes = data_entry_helper::getAttributes($attrOpts, false);
       //// Make sure the form action points back to this page
       $reload = data_entry_helper::get_reload_link_parts();
       unset($reload['params']['sample_id']);
       unset($reload['params']['occurrence_id']);
       unset($reload['params']['newSample']);
       $reloadPath = $reload['path'];
       if (count($reload['params'])) {
           $reloadPath .= '?' . http_build_query($reload['params']);
       }
       $r = "<form method=\"post\" id=\"entry_form\" action=\"{$reloadPath}\">\n";
       // Get authorisation tokens to update the Warehouse, plus any other hidden data.
       $hiddens = $auth['write'] . "<input type=\"hidden\" id=\"website_id\" name=\"website_id\" value=\"" . $args['website_id'] . "\" />\n" . "<input type=\"hidden\" id=\"survey_id\" name=\"survey_id\" value=\"" . $args['survey_id'] . "\" />\n";
       if (!empty($args['sample_method_id'])) {
           $hiddens .= '<input type="hidden" name="sample:sample_method_id" value="' . $args['sample_method_id'] . '"/>';
       }
       if (isset(data_entry_helper::$entity_to_load['sample:id'])) {
           $hiddens .= "<input type=\"hidden\" id=\"sample:id\" name=\"sample:id\" value=\"" . data_entry_helper::$entity_to_load['sample:id'] . "\" />\n";
       }
       if (isset(data_entry_helper::$entity_to_load['occurrence:id'])) {
           $hiddens .= "<input type=\"hidden\" id=\"occurrence:id\" name=\"occurrence:id\" value=\"" . data_entry_helper::$entity_to_load['occurrence:id'] . "\" />\n";
       }
       // Check if Record Status is included as a control. If not, then add it as a hidden.
       $arr = explode("\r\n", $args['structure']);
       if (!in_array('[record status]', $arr)) {
           $value = isset($args['defaults']['occurrence:record_status']) ? $args['defaults']['occurrence:record_status'] : 'C';
           $hiddens .= "<input type=\"hidden\" id=\"occurrence:record_status\" name=\"occurrence:record_status\" value=\"{$value}\" />\n";
       }
       // request automatic JS validation
       if (!isset($args['clientSideValidation']) || $args['clientSideValidation']) {
           data_entry_helper::enable_validation('entry_form');
       }
       // If logged in, output some hidden data about the user
       if (isset($args['copyFromProfile']) && $args['copyFromProfile'] == true) {
           self::profile_load_all_profile($user);
       }
       foreach ($attributes as &$attribute) {
           $attrPropName = 'profile_' . strtolower(str_replace(' ', '_', $attribute['caption']));
           if (isset($args['copyFromProfile']) && $args['copyFromProfile'] == true && isset($user->{$attrPropName})) {
               if ($args['nameShow'] == true) {
                   $attribute['default'] = $user->{$attrPropName};
               } else {
                   // profile attributes are not displayed as the user is logged in
                   $attribute['handled'] = true;
                   $attribute['value'] = $user->{$attrPropName};
               }
           } elseif (strcasecmp($attribute['caption'], 'cms user id') == 0) {
               if ($logged_in) {
                   $attribute['value'] = $user->uid;
               }
               $attribute['handled'] = true;
               // user id attribute is never displayed
           } elseif (strcasecmp($attribute['caption'], 'cms username') == 0) {
               if ($logged_in) {
                   $attribute['value'] = $user->name;
               }
               $attribute['handled'] = true;
               // username attribute is never displayed
           } elseif (strcasecmp($attribute['caption'], 'email') == 0) {
               if ($logged_in) {
                   if ($args['emailShow'] != true) {
                       // email attribute is not displayed
                       $attribute['value'] = $user->mail;
                       $attribute['handled'] = true;
                   } else {
                       $attribute['default'] = $user->mail;
                   }
               }
           } elseif ((strcasecmp($attribute['caption'], 'first name') == 0 || strcasecmp($attribute['caption'], 'last name') == 0 || strcasecmp($attribute['caption'], 'surname') == 0) && $logged_in) {
               if ($args['nameShow'] != true) {
                   // name attributes are not displayed because we have the users login
                   $attribute['handled'] = true;
               }
           }
           // If we have a value for one of the user login attributes then we need to output this value. BUT, for existing data
           // we must not overwrite the user who created the record.
           if (isset($attribute['value']) && $mode != MODE_EXISTING) {
               $hiddens .= '<input type="hidden" name="' . $attribute['fieldname'] . '" value="' . $attribute['value'] . '" />' . "\n";
           }
       }
       $customAttributeTabs = get_attribute_tabs($attributes);
       $tabs = self::get_all_tabs($args['structure'], $customAttributeTabs);
       $r .= "<div id=\"controls\">\n";
       // Build a list of the tabs that actually have content
       $tabHtml = self::get_tab_html($tabs, $auth, $args, $attributes, $hiddens);
       // Output the dynamic tab headers
       if ($args['interface'] != 'one_page') {
           $headerOptions = array('tabs' => array());
           foreach ($tabHtml as $tab => $tabContent) {
               $alias = preg_replace('/[^a-zA-Z0-9]/', '', strtolower($tab));
               $tabtitle = lang::get("LANG_Tab_{$alias}");
               if ($tabtitle == "LANG_Tab_{$alias}") {
                   // if no translation provided, we'll just use the standard heading
                   $tabtitle = $tab;
               }
               $headerOptions['tabs']['#' . $alias] = $tabtitle;
           }
           $r .= data_entry_helper::tab_header($headerOptions);
           data_entry_helper::enable_tabs(array('divId' => 'controls', 'style' => $args['interface'], 'progressBar' => isset($args['tabProgress']) && $args['tabProgress'] == true));
       }
       // Output the dynamic tab content
       $pageIdx = 0;
       foreach ($tabHtml as $tab => $tabContent) {
           // get a machine readable alias for the heading
           $tabalias = preg_replace('/[^a-zA-Z0-9]/', '', strtolower($tab));
           $r .= '<div id="' . $tabalias . '">' . "\n";
           // For wizard include the tab title as a header.
           if ($args['interface'] == 'wizard') {
               $r .= '<h1>' . $headerOptions['tabs']['#' . $tabalias] . '</h1>';
           }
           $r .= $tabContent;
           // Add any buttons required at the bottom of the tab
           if ($args['interface'] == 'wizard') {
               $r .= data_entry_helper::wizard_buttons(array('divId' => 'controls', 'page' => $pageIdx === 0 ? 'first' : ($pageIdx == count($tabHtml) - 1 ? 'last' : 'middle')));
           } elseif ($pageIdx == count($tabHtml) - 1 && !($args['interface'] == 'tabs' && $args['save_button_below_all_pages'])) {
               // last part of a non wizard interface must insert a save button, unless it is tabbed interface with save button beneath all pages
               $r .= "<input type=\"submit\" class=\"ui-state-default ui-corner-all\" id=\"save-button\" value=\"" . lang::get('LANG_Save') . "\" />\n";
           }
           $pageIdx++;
           $r .= "</div>\n";
       }
       $r .= "</div>\n";
       if ($args['interface'] == 'tabs' && $args['save_button_below_all_pages']) {
           $r .= "<input type=\"submit\" class=\"ui-state-default ui-corner-all\" id=\"save-button\" value=\"" . lang::get('LANG_Save') . "\" />\n";
       }
       if (!empty(data_entry_helper::$validation_errors)) {
           $r .= data_entry_helper::dump_remaining_errors();
       }
       $r .= "</form>";
       $r .= self::link_species_popups($args);
       return $r;
   }