/** * Return the generated form output. * @return Form HTML. */ public static function get_form($args) { $r = "<form method=\"post\">\n"; // Get authorisation tokens to update and read from the Warehouse. $r .= data_entry_helper::get_auth(1, 'password'); $readAuth = data_entry_helper::get_read_auth($args['website_id'], $args['password']); $r .= '<input type="hidden" name="website_id" value="' . $args['website_id'] . '" />' . "\n"; $r .= '<input type="hidden" name="sample:survey_id" value="' . $args['survey_id'] . '" />' . "\n"; $r .= "<input type=\"hidden\" id=\"record_status\" value=\"C\" />\n"; $r .= data_entry_helper::autocomplete(array('label' => 'Species', 'fieldname' => 'occurrence:taxa_taxon_list_id', 'table' => 'taxa_taxon_list', 'captionField' => 'taxon', 'valueField' => 'id', 'extraParams' => $readAuth + array('taxon_list_id' => $args['taxon_list_id']))); $r .= data_entry_helper::date_picker(array('label' => 'Date', 'fieldname' => 'sample:date')); $r .= data_entry_helper::map(); $r .= "<input type=\"submit\" class=\"ui-state-default ui-corner-all\" value=\"Save\" />\n"; $r .= "</form>"; return $r; }
/** * Return the generated form output. * @param array $args List of parameter values passed through to the form depending on how the form has been configured. * This array always contains a value for language. * @param object $node The Drupal node object. * @param array $response When this form is reloading after saving a submission, contains the response from the service call. * Note this does not apply when redirecting (in this case the details of the saved object are in the $_GET data). * @return Form HTML. */ public static function get_form($args, $node, $response = null) { global $indicia_templates; iform_load_helpers(array('map_helper', 'report_helper')); // apply defaults $args = array_merge(array(), $args); $reloadPath = self::getReloadPath(); data_entry_helper::$website_id = $args['website_id']; $auth = data_entry_helper::get_read_write_auth($args['website_id'], $args['password']); if (!empty($_GET['user_trust_id'])) { self::loadExistingUserTrust($_GET['user_trust_id'], $auth, $args); } $r = "<form method=\"post\" id=\"entry_form\" action=\"{$reloadPath}\">\n"; $r .= $auth['write'] . "<input type=\"hidden\" id=\"website_id\" name=\"website_id\" value=\"" . $args['website_id'] . "\" />\n"; $r .= data_entry_helper::hidden_text(array('fieldname' => 'user_trust:id')); $r .= data_entry_helper::autocomplete(array('label' => lang::get('Recorder to trust'), 'fieldname' => 'user_trust:user_id', 'table' => 'user', 'valueField' => 'id', 'captionField' => 'person_name', 'extraParams' => $auth['read'] + array('view' => 'detail'), 'class' => 'control-width-4')); $col1 = '<p>Define the combination of survey, taxon group and/or location that this recorder is trusted for below.</p>'; $col1 .= '<fieldset><legend>' . lang::get('Trust settings') . '</legend>'; $col1 .= data_entry_helper::autocomplete(array('label' => lang::get('Trust records in this survey'), 'fieldname' => 'user_trust:survey_id', 'table' => 'survey', 'valueField' => 'id', 'captionField' => 'title', 'blankText' => '<' . lang::get('any') . '>', 'extraParams' => $auth['read'] + array('sharing' => 'verification'), 'class' => 'control-width-4')); $col1 .= data_entry_helper::autocomplete(array('label' => lang::get('Trust records in this taxon group'), 'fieldname' => 'user_trust:taxon_group_id', 'table' => 'taxon_group', 'valueField' => 'id', 'captionField' => 'title', 'blankText' => '<' . lang::get('any') . '>', 'extraParams' => $auth['read'], 'class' => 'control-width-4')); $col1 .= data_entry_helper::autocomplete(array('label' => lang::get('Trust records in this location'), 'fieldname' => 'user_trust:location_id', 'table' => 'location', 'valueField' => 'id', 'captionField' => 'name', 'blankText' => '<' . lang::get('any') . '>', 'extraParams' => $auth['read'] + array('location_type_id' => variable_get('indicia_profile_location_type_id', '')), 'class' => 'control-width-4')); $col2 = '<p>' . lang::get('Review this recorder\'s experience in the tabs below') . '</p>'; $col2 .= '<div id="summary-tabs">'; $col2 .= data_entry_helper::tab_header(array('tabs' => array('#tab-surveys' => lang::get('Surveys'), '#tab-taxon-groups' => lang::get('Taxon groups'), '#tab-locations' => lang::get('Locations')))); data_entry_helper::enable_tabs(array('divId' => 'summary-tabs')); $col2 .= '<div id="tab-surveys">'; $col2 .= report_helper::report_grid(array('id' => 'surveys-summary', 'readAuth' => $auth['read'], 'dataSource' => 'library/surveys/filterable_surveys_verification_breakdown', 'ajax' => TRUE, 'autoloadAjax' => FALSE, 'extraParams' => array('my_records' => 1))); $col2 .= '</div>'; $col2 .= '<div id="tab-taxon-groups">'; $col2 .= report_helper::report_grid(array('id' => 'taxon-groups-summary', 'readAuth' => $auth['read'], 'dataSource' => 'library/taxon_groups/filterable_taxon_groups_verification_breakdown', 'ajax' => TRUE, 'autoloadAjax' => FALSE, 'extraParams' => array('my_records' => 1))); $col2 .= '</div>'; $col2 .= '<div id="tab-locations">'; $col2 .= report_helper::report_grid(array('id' => 'locations-summary', 'readAuth' => $auth['read'], 'dataSource' => 'library/locations/filterable_locations_verification_breakdown', 'ajax' => TRUE, 'autoloadAjax' => FALSE, 'extraParams' => array('my_records' => 1, 'location_type_id' => variable_get('indicia_profile_location_type_id', '')))); $col2 .= '</div>'; $col2 .= '</div>'; $r .= str_replace(array('{col-1}', '{col-2}'), array($col1, $col2), $indicia_templates['two-col-50']); $r .= '</fieldset>'; $r .= '<input type="submit" class="indicia-button" id="save-button" value="' . (empty(data_entry_helper::$entity_to_load['user_trust_id:id']) ? lang::get('Grant trust') : lang::get('Update trust settings')) . "\" />\n"; if (!empty($_GET['user_trust_id'])) { $r .= '<input type="submit" class="indicia-button" id="delete-button" name="delete-button" value="' . lang::get('Revoke this trust') . "\" />\n"; data_entry_helper::$javascript .= "\$('#delete-button').click(function(e) {\n if (!confirm(\"Are you sure you want to revoke this trust?\")) {\n e.preventDefault();\n return false;\n }\n });\n"; } $r .= '</form>'; data_entry_helper::enable_validation('entry_form'); return $r; }
/** * Return the generated form output. * @return Form HTML. */ public static function get_form($args, $node, $response = null) { global $user; global $custom_terms; $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']); $readAuth = $auth['read']; $svcUrl = data_entry_helper::$base_url . '/index.php/services'; drupal_add_js(drupal_get_path('module', 'iform') . '/media/js/jquery.form.js', 'module'); data_entry_helper::link_default_stylesheet(); data_entry_helper::add_resource('jquery_ui'); $language = iform_lang_iso_639_2($args['language']); if ($args['language'] != 'en') { data_entry_helper::add_resource('jquery_ui_' . $args['language']); } // If not logged in: Display an information message. // This form should only be called in POST mode when setting the location allocation. // All other posting is now done via AJAX. // When invoked by GET there are the following modes: // No additional arguments: mode 0. // Additional argument - new : mode 1. // Additional argument - sample_id=<id> : mode 2. // Additional argument - occurrence_id=<id> : mode 3. // Additional arguments - merge_sample_id1=<id>&merge_sample_id2=<id> : mode 2.1 $mode = 0; // default mode : output survey selector // mode 1: output the main Data Entry page: occurrence list or add/edit occurrence tabs hidden. "Survey" tab active // mode 2: output the main Data Entry page, display existing sample. Active tab determined by iform params. No occurence details filled in. // mode 2.1: sample 2 has all its occurrences merged into sample 1. sample 2 is then flagged as deleted. sample 1 is then viewed as in normal mode 2. // mode 3: output the main Data Entry page, display existing occurrence. "Edit Occurrence" tab active. Occurence details filled in. $surveyReadOnly = false; // On top of this, things can be flagged as readonly. RO mode 2+4 means no Add Occurrence tab. if (!$logged_in) { return lang::get('LANG_not_logged_in'); } $parentSample = array(); $parentLoadID = null; $childSample = array(); $childLoadID = null; $thisOccID = -1; // IDs have to be >0, so this is outside the valid range // Load up attribute details $sample_walk_direction_id = self::getAttrID($auth, $args, 'sample', self::ATTR_WALK); $sample_reliability_id = self::getAttrID($auth, $args, 'sample', self::ATTR_RELIABILITY); $sample_visit_number_id = self::getAttrID($auth, $args, 'sample', self::ATTR_VISIT); $sample_wind_id = self::getAttrID($auth, $args, 'sample', self::ATTR_WIND); $sample_precipitation_id = self::getAttrID($auth, $args, 'sample', self::ATTR_RAIN); $sample_temperature_id = self::getAttrID($auth, $args, 'sample', self::ATTR_TEMP); $sample_cloud_id = self::getAttrID($auth, $args, 'sample', self::ATTR_CLOUD); $sample_start_time_id = self::getAttrID($auth, $args, 'sample', self::ATTR_START_TIME); $sample_end_time_id = self::getAttrID($auth, $args, 'sample', self::ATTR_END_TIME); $sample_closure_id = self::getAttrID($auth, $args, 'sample', self::ATTR_CLOSED); $uid_attr_id = self::getAttrID($auth, $args, 'sample', self::ATTR_UID); $email_attr_id = self::getAttrID($auth, $args, 'sample', self::ATTR_EMAIL); $username_attr_id = self::getAttrID($auth, $args, 'sample', self::ATTR_USERNAME); $occurrence_confidence_id = self::getAttrID($auth, $args, 'occurrence', self::ATTR_CONFIDENCE); $occurrence_count_id = self::getAttrID($auth, $args, 'occurrence', self::ATTR_COUNT); $occurrence_approximation_id = self::getAttrID($auth, $args, 'occurrence', self::ATTR_APPROXIMATION); $occurrence_territorial_id = self::getAttrID($auth, $args, 'occurrence', self::ATTR_TERRITORIAL); $occurrence_atlas_code_id = self::getAttrID($auth, $args, 'occurrence', self::ATTR_ATLAS_CODE); $occurrence_overflying_id = self::getAttrID($auth, $args, 'occurrence', self::ATTR_OVERFLYING); if (!$sample_closure_id) { return '<p>This form must be used with a survey which has the "' . self::ATTR_CLOSED . '" sample attribute allocated to it. Survey_id = ' . $args['survey_id']; } if (!$uid_attr_id) { return '<p>This form must be used with a survey which has the "' . self::ATTR_UID . '" sample attribute allocated to it. Survey_id = ' . $args['survey_id']; } if (!$email_attr_id) { return '<p>This form must be used with a survey which has the "' . self::ATTR_EMAIL . '" sample attribute allocated to it. Survey_id = ' . $args['survey_id']; } if (!$username_attr_id) { return '<p>This form must be used with a survey which has the "' . self::ATTR_USERNAME . '" sample attribute allocated to it. Survey_id = ' . $args['survey_id']; } if (!$sample_walk_direction_id) { return '<p>This form must be used with a survey which has the "' . self::ATTR_WALK . '" sample attribute allocated to it. Survey_id = ' . $args['survey_id']; } if (!$sample_visit_number_id) { return '<p>This form must be used with a survey which has the "' . self::ATTR_VISIT . '" sample attribute allocated to it. Survey_id = ' . $args['survey_id']; } if (!$occurrence_count_id) { return '<p>This form must be used with a survey which has the "' . self::ATTR_COUNT . '" occurrence attribute allocated to it. Survey_id = ' . $args['survey_id']; } if (!$occurrence_territorial_id) { return '<p>This form must be used with a survey which has the "' . self::ATTR_TERRITORIAL . '" occurrence attribute allocated to it. Survey_id = ' . $args['survey_id']; } if (!$occurrence_atlas_code_id) { return '<p>This form must be used with a survey which has the "' . self::ATTR_ATLAS_CODE . '" occurrence attribute allocated to it. Survey_id = ' . $args['survey_id']; } 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('mnhnlbtw', $_POST)) { iform_loctools_deletelocations($node); foreach ($_POST as $key => $value) { $parts = explode(':', $key); if ($parts[0] == 'location' && $value) { iform_loctools_insertlocation($node, $value, $parts[1]); } } } } } else { if (array_key_exists('merge_sample_id1', $_GET) && array_key_exists('merge_sample_id2', $_GET) && user_access($args['edit_permission'])) { $mode = 2; // first check can access the 2 samples given $parentLoadID = $_GET['merge_sample_id1']; $url = $svcUrl . '/data/sample/' . $parentLoadID . "?mode=json&view=detail&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"]; $session = curl_init($url); curl_setopt($session, CURLOPT_RETURNTRANSFER, true); $entity = json_decode(curl_exec($session), true); if (count($entity) == 0 || $entity[0]["parent_id"]) { return '<p>' . lang::get('LANG_No_Access_To_Sample') . ' ' . $parentLoadID . '</p>'; } // The check for id2 is slightly different: there is the possiblity that someone will F5/refresh their browser, after the transfer and delete have taken place. // In this case we carry on, but do not do the transfer and delete. $url = $svcUrl . '/data/sample/' . $_GET['merge_sample_id2'] . "?mode=json&view=detail&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"]; $session = curl_init($url); curl_setopt($session, CURLOPT_RETURNTRANSFER, true); $entity = json_decode(curl_exec($session), true); if (count($entity) > 0 && !$entity[0]["parent_id"]) { // now get child samples and point to new parent. $url = $svcUrl . '/data/sample?mode=json&view=detail&auth_token=' . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"] . '&parent_id=' . $_GET['merge_sample_id2']; $session = curl_init($url); curl_setopt($session, CURLOPT_RETURNTRANSFER, true); $entities = json_decode(curl_exec($session), true); if (count($entities) > 0) { foreach ($entities as $entity) { $Model = data_entry_helper::wrap(array('id' => $entity['id'], 'parent_id' => $_GET['merge_sample_id1']), 'sample'); $request = data_entry_helper::$base_url . "/index.php/services/data/save"; $postargs = 'submission=' . json_encode($Model) . '&auth_token=' . $auth['write_tokens']['auth_token'] . '&nonce=' . $auth['write_tokens']['nonce'] . '&persist_auth=true'; $postresponse = data_entry_helper::http_post($request, $postargs, false); // the response array will always feature an output, which is the actual response or error message. if it is not json format, assume error text, and json encode that. $response = $postresponse['output']; if (!json_decode($response, true)) { return "<p>" . lang::get('LANG_Error_When_Moving_Sample') . ": id " . $entity['id'] . " : " . $response; } } } // finally delete the no longer used sample $Model = data_entry_helper::wrap(array('id' => $_GET['merge_sample_id2'], 'deleted' => 'true'), 'sample'); $request = data_entry_helper::$base_url . "/index.php/services/data/save"; $postargs = 'submission=' . json_encode($Model) . '&auth_token=' . $auth['write_tokens']['auth_token'] . '&nonce=' . $auth['write_tokens']['nonce'] . '&persist_auth=true'; $postresponse = data_entry_helper::http_post($request, $postargs, false); // the response array will always feature an output, which is the actual response or error message. if it is not json format, assume error text, and json encode that. $response = $postresponse['output']; if (!json_decode($response, true)) { return "<p>" . lang::get('LANG_Error_When_Deleting_Sample') . ": id " . $entity['id'] . " : " . $response; } } } else { if (array_key_exists('sample_id', $_GET)) { $mode = 2; $parentLoadID = $_GET['sample_id']; } else { if (array_key_exists('occurrence_id', $_GET)) { $mode = 3; $childLoadID = $_GET['occurrence_id']; $thisOccID = $childLoadID; } else { if (array_key_exists('new', $_GET)) { $mode = 1; } } } } // else default to mode 0 } // define language strings so they can be used for validation translation. data_entry_helper::$javascript .= "var translations = [\n"; foreach ($custom_terms as $key => $value) { if (substr($key, 0, 4) != "LANG") { data_entry_helper::$javascript .= " {key: \"" . $key . "\", translated: \"" . $value . "\"},\n"; } } data_entry_helper::$javascript .= "];\n"; // define layers for all maps. // each argument is a comma separated list eg: // "Name:Lux Outline,URL:http://localhost/geoserver/wms,LAYERS:indicia:nation2,SRS:EPSG:2169,FORMAT:image/png,minScale:0,maxScale:1000000,units:m"; $optionsArray_Location = array(); $options = explode(',', $args['locationLayer']); foreach ($options as $option) { $parts = explode(':', $option); $optionName = $parts[0]; unset($parts[0]); $optionsArray_Location[$optionName] = implode(':', $parts); } // Work out list of locations this user can see. $locations = iform_loctools_listlocations($node); if ($locations != 'all') { data_entry_helper::$javascript .= "var locationList = [" . implode(',', $locations) . "];\n"; } drupal_add_js(drupal_get_path('module', 'iform') . '/media/js/hasharray.js', 'module'); drupal_add_js(drupal_get_path('module', 'iform') . '/media/js/jquery.datagrid.js', 'module'); if (method_exists(get_called_class(), 'getHeaderHTML')) { $r .= call_user_func(array(get_called_class(), 'getHeaderHTML'), $args); } // Work out list of locations this user can see. // $locations = iform_loctools_listlocations($node); /////////////////////////////////////////////////////////////////// // default mode 0 : display a page with tabs for survey selector, // locations allocator and reports (last two require permissions) /////////////////////////////////////////////////////////////////// if ($mode == 0) { // If the user has permissions, add tabs so can choose to see // locations allocator $tabs = array('#surveyList' => lang::get('LANG_Surveys')); if (iform_loctools_checkaccess($node, 'admin')) { $tabs['#setLocations'] = lang::get('LANG_Allocate_Locations'); } if (iform_loctools_checkaccess($node, 'superuser')) { $tabs['#downloads'] = lang::get('LANG_Download'); } if (count($tabs) > 1) { $r .= "<div id=\"controls\">" . data_entry_helper::enable_tabs(array('divId' => 'controls', 'active' => '#surveyList')) . "<div id=\"temp\"></div>"; $r .= data_entry_helper::tab_header(array('tabs' => $tabs)); } if ($locations == 'all') { $useloclist = 'NO'; $loclist = '-1'; } else { // an empty list will cause an sql error, lids must be > 0, so push a -1 to prevent the error. if (empty($locations)) { $locations[] = -1; } $useloclist = 'YES'; $loclist = implode(',', $locations); } // Create the Survey list datagrid for this user. drupal_add_js("jQuery(document).ready(function(){\n \$('div#smp_grid').indiciaDataGrid('rpt:reports_for_prebuilt_forms/MNHNL/mnhnl_btw_list_samples', {\n indiciaSvc: '" . $svcUrl . "',\n dataColumns: ['location_name', 'date', 'num_visit', 'num_occurrences', 'num_taxa'],\n reportColumnTitles: {location_name : '" . lang::get('LANG_Transect') . "', date : '" . lang::get('LANG_Date') . "', num_visit : '" . lang::get('LANG_Visit_No') . "', num_occurrences : '" . lang::get('LANG_Num_Occurrences') . "', num_taxa : '" . lang::get('LANG_Num_Species') . "'},\n actionColumns: {" . lang::get('LANG_Show') . " : \"" . url('node/' . $node->nid, array('query' => 'sample_id=£id£')) . "\"},\n auth : { nonce : '" . $readAuth['nonce'] . "', auth_token : '" . $readAuth['auth_token'] . "'},\n parameters : { survey_id : '" . $args['survey_id'] . "', visit_attr_id : '" . $sample_visit_number_id . "', closed_attr_id : '" . $sample_closure_id . "', use_location_list : '" . $useloclist . "', locations : '" . $loclist . "'},\n itemsPerPage : 12,\n condCss : {field : 'closed', value : '0', css: 'mnhnl-btw-highlight'},\n cssOdd : ''\n });\n});\n ", 'inline'); data_entry_helper::$javascript .= "\n// Create Layers.\nvar locationListLayer;\nmapInitialisationHooks.push(function (div) {\n \"use strict\";"; if ($locations == 'all' || $loclist != '-1') { data_entry_helper::$javascript .= "\n var WMSoptions = {SERVICE: 'WMS', VERSION: '1.1.0', STYLES: '',\n SRS: div.map.projection.proj.srsCode, /* Now takes it from map */\n FORMAT: '" . $optionsArray_Location['FORMAT'] . "',\n TRANSPARENT: 'true', "; if ($locations != 'all') { // when given a restricted feature list we have to use the feature id to filter in order to not go over 2000 char limit on the URL // Can only generate the feature id if we access a table directly, not through a view. Go direct to the locations table. // don't need to worry about parent_id in this case as we know exactly which features we want. // need to use btw_transects view for unrestricted so we can filter by parent_id=NULL. $locFeatures = array(); foreach ($locations as $location) { $locFeatures[] = "locations." . $location; } data_entry_helper::$javascript .= "\n LAYERS: 'indicia:locations',\n FEATUREID: '" . implode(',', $locFeatures) . "'"; } else { data_entry_helper::$javascript .= " LAYERS: '" . $optionsArray_Location['LAYERS'] . "', CQL_FILTER: 'website_id=" . $args['website_id'] . "'"; } data_entry_helper::$javascript .= "\n };\n locationListLayer = new OpenLayers.Layer.WMS('" . $optionsArray_Location['Name'] . "',\n '" . (function_exists(iform_proxy_url) ? iform_proxy_url($optionsArray_Location['URL']) : $optionsArray_Location['URL']) . "',\n WMSoptions, {\n minScale: " . $optionsArray_Location['minScale'] . ",\n maxScale: " . $optionsArray_Location['maxScale'] . ",\n units: '" . $optionsArray_Location['units'] . "',\n isBaseLayer: false,\n singleTile: true\n });\n div.map.addLayer(locationListLayer);\n});\n"; } $r .= ' <div id="surveyList" class="mnhnl-btw-datapanel"><div id="smp_grid"></div> <form><input type="button" value="' . lang::get('LANG_Add_Survey') . '" onclick="window.location.href=\'' . url('node/' . $node->nid, array('query' => 'new')) . '\'"></form></div>'; // Add the locations allocator if user has admin rights. if (iform_loctools_checkaccess($node, 'admin')) { $r .= ' <div id="setLocations" class="mnhnl-btw-datapanel"> <form method="post"> <input type="hidden" id="mnhnlbtw" name="mnhnlbtw" value="mnhnlbtw" />'; $url = $svcUrl . '/data/location?mode=json&view=detail&auth_token=' . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"] . "&parent_id=NULL&orderby=name&columns=id,name,parent_id"; $session = curl_init($url); curl_setopt($session, CURLOPT_RETURNTRANSFER, true); $entities = json_decode(curl_exec($session), true); $userlist = iform_loctools_listusers($node); if (!empty($entities)) { foreach ($entities as $entity) { if (!$entity["parent_id"]) { // only assign parent locations. $r .= "\n<label for=\"location:" . $entity["id"] . "\">" . $entity["name"] . ":</label><select id=\"location:" . $entity["id"] . "\" name=\"location:" . $entity["id"] . "\"><option value=\"\" ><" . lang::get('LANG_Not_Allocated') . "></option>"; $defaultuserid = iform_loctools_getuser($node, $entity["id"]); foreach ($userlist as $uid => $a_user) { $r .= "<option value=\"" . $uid . "\" " . ($uid == $defaultuserid ? 'selected="selected" ' : '') . ">" . $a_user->name . "</option>"; } $r .= "</select>"; } } } $r .= "\n <input type=\"submit\" class=\"ui-state-default ui-corner-all\" value=\"" . lang::get('Save Location Allocations') . "\" />\n </form>\n </div>"; } // Add the downloader if user has manager (superuser) rights. if (iform_loctools_checkaccess($node, 'superuser')) { $r .= ' <div id="downloads" class="mnhnl-btw-datapanel"> <form method="post" action="' . data_entry_helper::$base_url . '/index.php/services/report/requestReport?report=reports_for_prebuilt_forms/MNHNL/mnhnl_btw_transect_direction_report.xml&reportSource=local&auth_token=' . $readAuth['auth_token'] . '&nonce=' . $readAuth['nonce'] . '&mode=csv"> <p>' . lang::get('LANG_Direction_Report') . '</p> <input type="hidden" name="params" value=\'{"survey_id":' . $args['survey_id'] . ', "direction_attr_id":' . $sample_walk_direction_id . ', "closed_attr_id":' . $sample_closure_id . '}\' /> <input type="submit" class="ui-state-default ui-corner-all" value="' . lang::get('LANG_Direction_Report_Button') . '"> </form> <form method="post" action="' . data_entry_helper::$base_url . '/index.php/services/report/requestReport?report=reports_for_prebuilt_forms/MNHNL/mnhnl_btw_verified_data_report.xml&reportSource=local&auth_token=' . $readAuth['auth_token'] . '&nonce=' . $readAuth['nonce'] . '&mode=csv"> <p>' . lang::get('LANG_Verified_Data_Report') . '</p> <input type="hidden" name="params" value=\'{"survey_id":' . $args['survey_id'] . '}\' /> <input type="submit" class="ui-state-default ui-corner-all" value="' . lang::get('LANG_Verified_Data_Report_Button') . '"> </form> <form method="post" action="' . data_entry_helper::$base_url . '/index.php/services/report/requestReport?report=reports_for_prebuilt_forms/MNHNL/mnhnl_btw_download_report_2.xml&reportSource=local&auth_token=' . $readAuth['auth_token'] . '&nonce=' . $readAuth['nonce'] . '&mode=csv"> <p>' . lang::get('LANG_Initial_Download') . '</p> <input type="hidden" name="params" value=\'{"survey_id":' . $args['survey_id'] . ', "closed_attr_id":' . $sample_closure_id . ', "download": "INITIAL", "quality": "!R", "occattrs": "' . $occurrence_confidence_id . ',' . $occurrence_count_id . ',' . $occurrence_approximation_id . ',' . $occurrence_territorial_id . ',' . $occurrence_atlas_code_id . ',' . $occurrence_overflying_id . '", "smpattrs" : "' . $sample_walk_direction_id . ',' . $sample_reliability_id . ',' . $sample_visit_number_id . ',' . $sample_wind_id . ',' . $sample_precipitation_id . ',' . $sample_temperature_id . ',' . $sample_cloud_id . ',' . $sample_start_time_id . ',' . $sample_end_time_id . ',' . $sample_closure_id . ',' . $uid_attr_id . ',' . $email_attr_id . ',' . $username_attr_id . '"}\' /> <input type="submit" class="ui-state-default ui-corner-all" value="' . lang::get('LANG_Initial_Download_Button') . '"> </form> <form method="post" action="' . data_entry_helper::$base_url . '/index.php/services/report/requestReport?report=reports_for_prebuilt_forms/MNHNL/mnhnl_btw_download_report_2.xml&reportSource=local&auth_token=' . $readAuth['auth_token'] . '&nonce=' . $readAuth['nonce'] . '&mode=csv"> <p>' . lang::get('LANG_Confirm_Download') . '</p> <input type="hidden" name="params" value=\'{"survey_id":' . $args['survey_id'] . ', "closed_attr_id":' . $sample_closure_id . ', "download": "CONFIRM", "quality": "V", "occattrs": "' . $occurrence_confidence_id . ',' . $occurrence_count_id . ',' . $occurrence_approximation_id . ',' . $occurrence_territorial_id . ',' . $occurrence_atlas_code_id . ',' . $occurrence_overflying_id . '", "smpattrs" : "' . $sample_walk_direction_id . ',' . $sample_reliability_id . ',' . $sample_visit_number_id . ',' . $sample_wind_id . ',' . $sample_precipitation_id . ',' . $sample_temperature_id . ',' . $sample_cloud_id . ',' . $sample_start_time_id . ',' . $sample_end_time_id . ',' . $sample_closure_id . ',' . $uid_attr_id . ',' . $email_attr_id . ',' . $username_attr_id . '"}\' /> <input type="submit" class="ui-state-default ui-corner-all" value="' . lang::get('LANG_Confirm_Download_Button') . '"> </form> <form method="post" action="' . data_entry_helper::$base_url . '/index.php/services/report/requestReport?report=reports_for_prebuilt_forms/MNHNL/mnhnl_btw_download_report_2.xml&reportSource=local&auth_token=' . $readAuth['auth_token'] . '&nonce=' . $readAuth['nonce'] . '&mode=csv"> <p>' . lang::get('LANG_Final_Download') . '</p> <input type="hidden" name="params" value=\'{"survey_id":' . $args['survey_id'] . ', "closed_attr_id":' . $sample_closure_id . ', "download": "FINAL", "quality": "V", "occattrs": "' . $occurrence_confidence_id . ',' . $occurrence_count_id . ',' . $occurrence_approximation_id . ',' . $occurrence_territorial_id . ',' . $occurrence_atlas_code_id . ',' . $occurrence_overflying_id . '", "smpattrs" : "' . $sample_walk_direction_id . ',' . $sample_reliability_id . ',' . $sample_visit_number_id . ',' . $sample_wind_id . ',' . $sample_precipitation_id . ',' . $sample_temperature_id . ',' . $sample_cloud_id . ',' . $sample_start_time_id . ',' . $sample_end_time_id . ',' . $sample_closure_id . ',' . $uid_attr_id . ',' . $email_attr_id . ',' . $username_attr_id . '"}\' /> <input type="submit" class="ui-state-default ui-corner-all" value="' . lang::get('LANG_Final_Download_Button') . '"> </form> <form method="post" action="' . data_entry_helper::$base_url . '/index.php/services/report/requestReport?report=reports_for_prebuilt_forms/MNHNL/mnhnl_btw_download_report_2.xml&reportSource=local&auth_token=' . $readAuth['auth_token'] . '&nonce=' . $readAuth['nonce'] . '&mode=csv"> <p>' . lang::get('LANG_Complete_Final_Download') . '</p> <input type="hidden" name="params" value=\'{"survey_id":' . $args['survey_id'] . ', "closed_attr_id":' . $sample_closure_id . ', "download": "OFF", "quality": "NA", "occattrs": "' . $occurrence_confidence_id . ',' . $occurrence_count_id . ',' . $occurrence_approximation_id . ',' . $occurrence_territorial_id . ',' . $occurrence_atlas_code_id . ',' . $occurrence_overflying_id . '", "smpattrs" : "' . $sample_walk_direction_id . ',' . $sample_reliability_id . ',' . $sample_visit_number_id . ',' . $sample_wind_id . ',' . $sample_precipitation_id . ',' . $sample_temperature_id . ',' . $sample_cloud_id . ',' . $sample_start_time_id . ',' . $sample_end_time_id . ',' . $sample_closure_id . ',' . $uid_attr_id . ',' . $email_attr_id . ',' . $username_attr_id . '"}\' /> <input type="submit" class="ui-state-default ui-corner-all" value="' . lang::get('LANG_Complete_Final_Download_Button') . '"> </form> </div>'; } // Create Map $options = iform_map_get_map_options($args, $readAuth); $olOptions = iform_map_get_ol_options($args); // if($locations == 'all' || $loclist != '-1') // $options['layers'] = array('locationListLayer'); $options['searchLayer'] = 'false'; $options['editLayer'] = 'false'; $options['initialFeatureWkt'] = null; $options['proxy'] = ''; $options['scroll_wheel_zoom'] = false; $options['width'] = 'auto'; // TBD remove from arglist $r .= "<div class=\"mnhnl-btw-mappanel\">\n" . data_entry_helper::map_panel($options, $olOptions) . "</div>\n"; data_entry_helper::$javascript .= "\n\$('#controls').bind('tabsshow', function(event, ui) {\n var y = \$('.mnhnl-btw-datapanel:visible').outerHeight(true) + \$('.mnhnl-btw-datapanel:visible').position().top;\n if(y < \$('.mnhnl-btw-mappanel').outerHeight(true)+ \$('.mnhnl-btw-mappanel').position().top){\n y = \$('.mnhnl-btw-mappanel').outerHeight(true)+ \$('.mnhnl-btw-mappanel').position().top;\n }\n \$('#controls').height(y - \$('#controls').position().top);\n});\n"; 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'), $args); } return $r; } /////////////////////////////////////////////////////////////////// // At this point there are 3 modes: // Adding a new survey // editing/showing an existing survey // editing/showing an existing occurrence // First load the occurrence (and its position sample) if provided // Then load the parent sample if provided, or derived from occurrence. // $occReadOnly is set if the occurrence has been downloaded. Not even an admin user can modify it in this case. data_entry_helper::$javascript .= "\n// Create Layers.\nvar locationLayer, occListLayer, control;\nmapInitialisationHooks.push(function (div) {\n \"use strict\";\n // Create vector layers: one to display the location onto, and another for the occurrence list\n // the default edit layer is used for the occurrences themselves\n var locStyleMap = new OpenLayers.StyleMap({\n 'default': new OpenLayers.Style({\n fillColor: 'Green',\n strokeColor: 'Black',\n fillOpacity: 0.2,\n strokeWidth: 1\n })});\n locationLayer = new OpenLayers.Layer.Vector('" . lang::get("LANG_Location_Layer") . "', {styleMap: locStyleMap});\n var occStyleMap = new OpenLayers.StyleMap({\n 'default': new OpenLayers.Style({\n pointRadius: 3,\n fillColor: 'Red',\n fillOpacity: 0.3,\n strokeColor: 'Red',\n strokeWidth: 1\n })});\n occListLayer = new OpenLayers.Layer.Vector(\"" . lang::get("LANG_Occurrence_List_Layer") . "\", {styleMap: occStyleMap});\n div.map.addLayer(locationLayer);\n div.map.addLayer(occListLayer);\n var control = new OpenLayers.Control.SelectFeature(occListLayer);\n occListLayer.map.addControl(control);\n function onPopupClose(evt) {\n // 'this' is the popup.\n control.unselect(this.feature);\n }\n function onFeatureSelect(evt) {\n feature = evt.feature;\n popup = new OpenLayers.Popup.FramedCloud(\"featurePopup\",\n feature.geometry.getBounds().getCenterLonLat(),\n new OpenLayers.Size(100,100),\n feature.attributes.taxon + \" (\" + feature.attributes.count + \")\",\n null, true, onPopupClose);\n feature.popup = popup;\n popup.feature = feature;\n feature.layer.map.addPopup(popup);\n }\n function onFeatureUnselect(evt) {\n feature = evt.feature;\n if (feature.popup) {\n popup.feature = null;\n feature.layer.map.removePopup(feature.popup);\n feature.popup.destroy();\n feature.popup = null;\n }\n }\n occListLayer.events.on({\n 'featureselected': onFeatureSelect,\n 'featureunselected': onFeatureUnselect\n });\n control.activate();\n});\n"; $occReadOnly = false; $childSample = array(); if ($childLoadID) { // load the occurrence and its associated sample (which holds the position) $url = $svcUrl . '/data/occurrence/' . $childLoadID; $url .= "?mode=json&view=detail&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"]; $session = curl_init($url); curl_setopt($session, CURLOPT_RETURNTRANSFER, true); $entity = json_decode(curl_exec($session), true); if (count($entity) == 0) { return '<p>' . lang::get('LANG_No_Access_To_Occurrence') . '</p>'; } foreach ($entity[0] as $key => $value) { $childSample['occurrence:' . $key] = $value; } if ($entity[0]['downloaded_flag'] == 'F') { // Final download complete, now readonly $occReadOnly = true; } $url = $svcUrl . '/data/sample/' . $childSample['occurrence:sample_id']; $url .= "?mode=json&view=detail&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"]; $session = curl_init($url); curl_setopt($session, CURLOPT_RETURNTRANSFER, true); $entity = json_decode(curl_exec($session), true); if (count($entity) == 0) { return '<p>' . lang::get('LANG_No_Access_To_Occurrence') . '</p>'; } foreach ($entity[0] as $key => $value) { $childSample['sample:' . $key] = $value; } $childSample['sample:geom'] = ''; // value received from db is not WKT, which is assumed by all the code. $childSample['taxon'] = $childSample['occurrence:taxon']; $parentLoadID = $childSample['sample:parent_id']; } $parentSample = array(); if ($parentLoadID) { // load the container master sample $url = $svcUrl . '/data/sample/' . $parentLoadID; $url .= "?mode=json&view=detail&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"]; $session = curl_init($url); curl_setopt($session, CURLOPT_RETURNTRANSFER, true); $entity = json_decode(curl_exec($session), true); if (count($entity) == 0) { return '<p>' . lang::get('LANG_No_Access_To_Sample') . '</p>'; } foreach ($entity[0] as $key => $value) { $parentSample['sample:' . $key] = $value; } if (is_array($locations) && !in_array($entity[0]["location_id"], $locations)) { return '<p>' . lang::get('LANG_No_Access_To_Location') . '</p>'; } if ($entity[0]["parent_id"]) { return '<p>' . lang::get('LANG_No_Access_To_Sample') . '</p>'; } $parentSample['sample:date'] = $parentSample['sample:date_start']; // bit of a bodge $childSample['sample:date'] = $parentSample['sample:date']; // enforce a match between child and parent sample dates // default values for attributes from DB are picked up automatically. } data_entry_helper::$entity_to_load = $parentSample; $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' => $readAuth)); $closedFieldName = $attributes[$sample_closure_id]['fieldname']; $closedFieldValue = data_entry_helper::check_default_value($closedFieldName, array_key_exists('default', $attributes[$sample_closure_id]) ? $attributes[$sample_closure_id]['default'] : '0'); // default is not closed if ($closedFieldValue == '') { $closedFieldValue = '0'; } if ($closedFieldValue == '1' && !user_access($args['edit_permission'])) { // sample has been closed, no admin perms. Everything now set to read only. $surveyReadOnly = true; $disabledText = "disabled=\"disabled\""; $defAttrOptions = array('extraParams' => $readAuth, 'disabled' => $disabledText); } else { // sample editable. Admin users can modify closed samples. $disabledText = ""; $defAttrOptions = array('extraParams' => $readAuth); } // with the AJAX code, we deal with the validation semi manually: Form name is meant be invalid as we only want code included. data_entry_helper::enable_validation(null); $r .= "<div id=\"controls\">\n"; $activeTab = 'survey'; // mode 1 = new Sample, display sample. if ($mode == 2) { // have specified a sample ID if ($args["on_edit_survey_nav"] == "survey") { $activeTab = 'survey'; } else { if ($surveyReadOnly || $args["on_edit_survey_nav"] == "list") { $activeTab = 'occurrenceList'; } else { $activeTab = 'occurrence'; } } if ($surveyReadOnly) { data_entry_helper::$javascript .= "jQuery('#occ-form').hide();"; } } else { if ($mode == 3) { // have specified an occurrence ID $activeTab = 'occurrence'; } } // Set Up form tabs. $r .= data_entry_helper::enable_tabs(array('divId' => 'controls', 'active' => $activeTab)); $r .= "<div id=\"temp\"></div>"; $r .= data_entry_helper::tab_header(array('tabs' => array('#survey' => lang::get('LANG_Survey'), '#occurrence' => lang::get($surveyReadOnly || $occReadOnly ? 'LANG_Show_Occurrence' : (isset($childSample['sample:id']) ? 'LANG_Edit_Occurrence' : 'LANG_Add_Occurrence')), '#occurrenceList' => lang::get('LANG_Occurrence_List')))); // Set up main Survey Form. $r .= "<div id=\"survey\" class=\"mnhnl-btw-datapanel\">\n <p id=\"read-only-survey\"><strong>" . lang::get('LANG_Read_Only_Survey') . "</strong></p>"; if (user_access($args['edit_permission']) && array_key_exists('sample:id', data_entry_helper::$entity_to_load)) { // check for other surveys of same date/transect: only if admin user. $url = $svcUrl . '/data/sample?mode=json&view=detail&auth_token=' . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"] . "&date_start=" . $parentSample['sample:date_start'] . "&location_id=" . $parentSample['sample:location_id']; $session = curl_init($url); curl_setopt($session, CURLOPT_RETURNTRANSFER, true); $entity = json_decode(curl_exec($session), true); if (count($entity) > 1) { // ignore ourselves! $r .= "<div id=\"mergeSurveys\"><p><strong>" . lang::get('LANG_Found_Mergable_Surveys') . "</strong></p>"; foreach ($entity as $survey) { if ($survey['id'] != $parentSample['sample:id']) { $r .= "<form action=\"" . url('node/' . $node->nid, array()) . "\" method=\"get\"><input type=\"submit\" value=\"" . lang::get('LANG_Merge_With_ID') . " " . $survey['id'] . "\"><input type=\"hidden\" name=\"merge_sample_id1\" value=\"" . $parentSample['sample:id'] . "\" /><input type=\"hidden\" name=\"merge_sample_id2\" value=\"" . $survey['id'] . "\" /></form>"; } } $r .= "</div>"; } } $r .= "<form id=\"SurveyForm\" action=\"" . iform_ajaxproxy_url($node, 'sample') . "\" method=\"post\">\n <input type=\"hidden\" id=\"website_id\" name=\"website_id\" value=\"" . $args['website_id'] . "\" />\n <input type=\"hidden\" id=\"sample:survey_id\" name=\"sample:survey_id\" value=\"" . $args['survey_id'] . "\" />"; if (array_key_exists('sample:id', data_entry_helper::$entity_to_load)) { $r .= "<input type=\"hidden\" id=\"sample:id\" name=\"sample:id\" value=\"" . data_entry_helper::$entity_to_load['sample:id'] . "\" />\n"; } else { $r .= "<input type=\"hidden\" id=\"sample:id\" name=\"sample:id\" value=\"\" disabled=\"disabled\" />\n"; // GvB 19/Nov/2012 : change to user detail defaults // logic is now much simpler, and they are only included/created if the sample is new. $fieldName = $attributes[$uid_attr_id]['fieldname']; $fieldValue = data_entry_helper::check_default_value($fieldName, $user->uid); $r .= "<input type=\"hidden\" name=\"" . $fieldName . "\" value=\"" . $fieldValue . "\" />\n"; $fieldName = $attributes[$email_attr_id]['fieldname']; $fieldValue = data_entry_helper::check_default_value($fieldName, $user->mail); $r .= "<input type=\"hidden\" name=\"" . $fieldName . "\" value=\"" . $fieldValue . "\" />\n"; $fieldName = $attributes[$username_attr_id]['fieldname']; $fieldValue = data_entry_helper::check_default_value($fieldName, $user->name); $r .= "<input type=\"hidden\" name=\"" . $fieldName . "\" value=\"" . $fieldValue . "\" />\n"; } $defAttrOptions['validation'] = array('required'); if ($locations == 'all') { $locOptions = array_merge(array('label' => lang::get('LANG_Transect')), $defAttrOptions); $locOptions['extraParams'] = array_merge(array('parent_id' => 'NULL', 'view' => 'detail', 'orderby' => 'name'), $locOptions['extraParams']); $r .= data_entry_helper::location_select($locOptions); } else { // can't use location select due to location filtering. $r .= "<label for=\"imp-location\">" . lang::get('LANG_Transect') . ":</label>\n<select id=\"imp-location\" name=\"sample:location_id\" " . $disabled_text . " class=\" \" >"; $url = $svcUrl . '/data/location?mode=json&view=detail&parent_id=NULL&orderby=name&auth_token=' . $readAuth['auth_token'] . '&nonce=' . $readAuth["nonce"]; $session = curl_init($url); curl_setopt($session, CURLOPT_RETURNTRANSFER, true); $entities = json_decode(curl_exec($session), true); if (!empty($entities)) { foreach ($entities as $entity) { if (in_array($entity["id"], $locations)) { if ($entity["id"] == data_entry_helper::$entity_to_load['sample:location_id']) { $selected = 'selected="selected"'; } else { $selected = ''; } $r .= "<option value=\"" . $entity["id"] . "\" " . $selected . ">" . $entity["name"] . "</option>"; } } } $r .= "</select><span class=\"deh-required\">*</span><br />"; } $languageFilteredAttrOptions = $defAttrOptions + array('language' => iform_lang_iso_639_2($args['language'])); $r .= data_entry_helper::outputAttribute($attributes[$sample_walk_direction_id], $languageFilteredAttrOptions) . ($sample_reliability_id ? data_entry_helper::outputAttribute($attributes[$sample_reliability_id], $languageFilteredAttrOptions) : "<span style=\"display: none;\">Sample attribute '" . self::ATTR_RELIABILITY . "' not assigned to this survey</span>") . data_entry_helper::outputAttribute($attributes[$sample_visit_number_id], array_merge($languageFilteredAttrOptions, array('default' => 1, 'noBlankText' => true))); if (isset(data_entry_helper::$entity_to_load['sample:date']) && preg_match('/^(\\d{4})/', data_entry_helper::$entity_to_load['sample:date'])) { // Date has 4 digit year first (ISO style) - convert date to expected output format $d = new DateTime(data_entry_helper::$entity_to_load['sample:date']); data_entry_helper::$entity_to_load['sample:date'] = $d->format('d/m/Y'); } if ($args['language'] != 'en') { data_entry_helper::add_resource('jquery_ui_' . $args['language']); } // this will autoload the jquery_ui resource. The date_picker does not have access to the args. if ($surveyReadOnly) { $r .= data_entry_helper::text_input(array_merge($defAttrOptions, array('label' => lang::get('LANG_Date'), 'fieldname' => 'sample:date', 'disabled' => $disabledText))); } else { $r .= data_entry_helper::date_picker(array('label' => lang::get('LANG_Date'), 'fieldname' => 'sample:date', 'class' => 'vague-date-picker')); } $r .= ($sample_wind_id ? data_entry_helper::outputAttribute($attributes[$sample_wind_id], $languageFilteredAttrOptions) : "<span style=\"display: none;\">Sample attribute '" . self::ATTR_WIND . "' not assigned to this survey</span>") . ($sample_precipitation_id ? data_entry_helper::outputAttribute($attributes[$sample_precipitation_id], $languageFilteredAttrOptions) : "<span style=\"display: none;\">Sample attribute '" . self::ATTR_RAIN . "' not assigned to this survey</span>") . ($sample_temperature_id ? data_entry_helper::outputAttribute($attributes[$sample_temperature_id], array_merge($defAttrOptions, array('suffixTemplate' => 'nosuffix'))) . "<span class=\"attr-trailer\"> °C</span><br />" : "<span style=\"display: none;\">Sample attribute '" . self::ATTR_TEMP . "' not assigned to this survey</span>") . ($sample_cloud_id ? data_entry_helper::outputAttribute($attributes[$sample_cloud_id], $defAttrOptions) : "<span style=\"display: none;\">Sample attribute '" . self::ATTR_CLOUD . "' not assigned to this survey</span>") . ($sample_start_time_id ? data_entry_helper::outputAttribute($attributes[$sample_start_time_id], array_merge($defAttrOptions, array('suffixTemplate' => 'nosuffix'))) . "<span class=\"attr-trailer\"> hh:mm</span><br />" : "<span style=\"display: none;\">Sample attribute '" . self::ATTR_START_TIME . "' not assigned to this survey</span>") . ($sample_end_time_id ? data_entry_helper::outputAttribute($attributes[$sample_end_time_id], array_merge($defAttrOptions, array('suffixTemplate' => 'nosuffix'))) . "<span class=\"attr-trailer\"> hh:mm</span><br />" : "<span style=\"display: none;\">Sample attribute '" . self::ATTR_END_TIME . "' not assigned to this survey</span>"); data_entry_helper::$javascript .= "\njQuery('.attr-trailer').prev('br').remove();\n"; unset($defAttrOptions['suffixTemplate']); unset($defAttrOptions['validation']); if (user_access($args['edit_permission'])) { // users with admin permissions can override the closing of the // sample by unchecking the checkbox. // Because this is attached to the sample, we have to include the sample required fields in the // the post. This means they can't be disabled, so we enable all fields in this case. // Normal users can only set this to closed, and they do this using a button/hidden field. $r .= data_entry_helper::outputAttribute($attributes[$sample_closure_id], $defAttrOptions); // In addition admin users can delete a survey/sample. $r .= data_entry_helper::checkbox(array('label' => lang::get('Deleted'), 'fieldname' => 'sample:deleted', 'id' => 'main-sample-deleted')); } else { // hidden closed $r .= "<input type=\"hidden\" id=\"main-sample-closed\" name=\"" . $closedFieldName . "\" value=\"" . $closedFieldValue . "\" />\n"; } data_entry_helper::$javascript .= "\n\$.validator.messages.required = \"" . lang::get('validation_required') . "\";\n\$.validator.defaults.onsubmit = false; // override default - so that we handle all submission validation.\n"; if (!$surveyReadOnly) { // NB that we don't even include the buttons when readonly. data_entry_helper::$javascript .= "\njQuery('#read-only-survey').hide();\njQuery('#ro-sur-occ-warn').hide();\n"; $r .= "<input type=button id=\"close1\" class=\"ui-state-default ui-corner-all \" value=\"" . lang::get('LANG_Save_Survey_Details') . "\";\n onclick=\"var result = \$('#SurveyForm input').valid();\n var result2 = \$('#SurveyForm select').valid();\n if (!result || !result2) {\n return;\n }\n jQuery('#close1').addClass('loading-button');\n jQuery('#SurveyForm').submit();\">\n"; if (!user_access($args['edit_permission'])) { if ($mode == 1) { data_entry_helper::$javascript .= "jQuery('#close2').hide();\n"; } $r .= "<input type=button id=\"close2\" class=\"ui-state-default ui-corner-all \" value=\"" . lang::get('LANG_Save_Survey_And_Close') . "\"\n onclick=\"if(confirm('" . lang::get('LANG_Close_Survey_Confirm') . "')){\n var result = \$('#SurveyForm input').valid();\n var result2 = \$('#SurveyForm select').valid();\n if (!result || !result2) {\n return;\n }\n jQuery('#main-sample-closed').val('1');\n jQuery('#close2').addClass('loading-button');\n jQuery('#SurveyForm').submit();\n };\">\n"; } } $r .= "</form></div>\n"; data_entry_helper::$javascript .= "\nalertIndiciaError = function(data){\n\tvar errorString = \"" . lang::get('LANG_Indicia_Warehouse_Error') . "\";\n\tif(data.error){\terrorString = errorString + ' : ' + data.error;\t}\n\tif(data.errors){\n\t\tfor (var i in data.errors){\n\t\t\terrorString = errorString + ' : ' + data.errors[i];\n\t\t}\n\t}\n\talert(errorString);\n\t// the most likely cause is authentication failure - eg the read authentication has timed out.\n\t// prevent further use of the form:\n\t\$('.loading-panel').remove();\n\t\$('.loading-hide').removeClass('loading-hide');\n};\nerrorPos = null;\nclearErrors = function(formSel) {\n\tjQuery(formSel).find('.inline-error').remove();\n\terrorPos = null;\n};\nmyScrollTo = function(selector){\n\tjQuery(selector).filter(':visible').each(function(){\n\t\tif(errorPos == null || jQuery(this).offset().top < errorPos){\n\t\t\terrorPos = jQuery(this).offset().top;\n\t\t\twindow.scroll(0,errorPos);\n\t\t}\n\t});\n};\nmyScrollToError = function(){\n\tjQuery('.inline-error,.error').filter(':visible').prev().each(function(){\n\t\tif(errorPos == null || jQuery(this).offset().top < errorPos){\n\t\t\terrorPos = jQuery(this).offset().top;\n\t\t\twindow.scroll(0,errorPos);\n\t\t}\n\t});\n};\njQuery('#SurveyForm').ajaxForm({\n\tasync: false,\n\tdataType: 'json',\n beforeSubmit: function(data, obj, options){\n \tvar valid = true;\n \tclearErrors('form#SurveyForm');\n \tif (!jQuery('form#SurveyForm > input').valid()) {\n\t\t\tmyScrollToError();\n \t\t\tjQuery('.loading-button').removeClass('loading-button');\n\t\t\treturn false;\n \t\t};\n \t\tSurveyFormRetVal = true;\n \t\tif(jQuery('#main-sample-deleted:checked').length == 0){ // only do check if not deleting\n jQuery.ajax({ // now check if there are any other samples with this combination of date and location\n type: 'GET',\n url: \"" . $svcUrl . "/data/sample?mode=json&view=detail\" +\n \"&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n \"&orderby=id&callback=?&location_id=\"+jQuery('#imp-location').val()+\"&date_start=\"+jQuery('#SurveyForm [name=sample\\:date]').val(),\n data: {},\n success: function(detData) {\n for(i=0, j=0; i< detData.length; i++){\n if(detData[i].id != jQuery('#SurveyForm [name=sample\\:id]').val()) j++;\n }\n if(j) {\n \tSurveyFormRetVal = confirm(\"" . lang::get('LANG_Survey_Already_Exists') . "\");\n }\n },\n dataType: 'json',\n async: false\n });\n }\n\t\treturn SurveyFormRetVal;\n\t},\n success: function(data){\n // this will leave all the fields populated.\n \tif(data.success == 'multiple records' && data.outer_table == 'sample'){\n jQuery('#occ-form').show();\n jQuery('#na-occ-warn,#mergeSurveys').hide();"; if (!user_access($args['edit_permission'])) { // don't need to worry about record_status value for non admins as they can't modify when closed. data_entry_helper::$javascript .= "\n if(jQuery('#main-sample-closed').val() == '1'){\n jQuery('#read-only-survey,#ro-sur-occ-warn').show();\n jQuery('#close1,#close2,#occ-form').hide(); //can't enter any more occurrences\n jQuery('#SurveyForm').children().attr('disabled','disabled');\n };\n"; } else { data_entry_helper::$javascript .= "\n jQuery('#occurrence\\\\:record_status').val(jQuery('#smpAttr\\\\:" . $attributes[$sample_closure_id]['attributeId'] . ":checked').length > 0 ? 'C' : 'I');\n if(jQuery('#main-sample-deleted:checked').length > 0){\n jQuery('#return-to-main').click();\n return;\n };\n"; } data_entry_helper::$javascript .= "// If sample_id filled in -> we have a previously saved collection, so possibly have subsamples.\nif(jQuery('#SurveyForm > input[name=sample\\:id]').val() != ''){\n // Put up warning dialogue that we are checking the subsamples: include a progress bar: set to zero%.\n var dialog = \$('<span id=\"subsample-progress-span\"><p>'+\"" . lang::get('Please wait whilst some data integrity checks are carried out.') . "\"+'</p><div id=\"subsample-progress\"></div></span>').dialog({ title: \"" . lang::get('Checks') . "\", zIndex: 4000 });\n jQuery('#subsample-progress').progressbar({value: 0});\n jQuery.ajax({ // get all subsamples/occurrences to check if the dates match\n type: 'GET',\n url: \"" . $svcUrl . "/report/requestReport?report=library/occurrences/occurrences_list_for_parent_sample.xml&reportSource=local&mode=json&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n \"&callback=?&sample_id=\"+data.outer_id+\"&survey_id=&date_from=&date_to=&taxon_group_id=&smpattrs=&occattrs=\",\n data: {},\n success: function(subData) {\n jQuery('#subsample-progress').data('max',subData.length+1);\n var mainDate = \$.datepicker.formatDate('yy-mm-dd', jQuery('#SurveyForm > input[name=sample\\:date]').datepicker(\"getDate\"));\n for(i=0; i< subData.length; i++){ // loop through all subsamples\n jQuery('#subsample-progress').progressbar('option','value',(i+1)*100/jQuery('#subsample-progress').data('max'));\n var values = {};\n var url = '';\n // Check if date on subsamples matches supersample date: if not set up a post array for the sample, with correct date.\n if(subData[i].date_start != mainDate){\n values['sample:id']=subData[i].sample_id;\n values['sample:date']=mainDate;\n url=\"" . iform_ajaxproxy_url($node, 'sample') . "\";\n }\n"; // Send AJAX request to set occurrence to 'C' if closed : use sync if (!user_access($args['edit_permission'])) { data_entry_helper::$javascript .= " if(jQuery('#main-sample-closed').val() == '1'){\n"; } else { data_entry_helper::$javascript .= " if(jQuery('#smpAttr\\\\:" . $attributes[$sample_closure_id]['attributeId'] . ":checked').length > 0){\n"; } // If records are already verified, they are left verified, as if the records themselves are saved // they will flagged as no longer verified: But have to force a re verification if date is changed. data_entry_helper::$javascript .= "\n if(subData[i].record_status == 'I' || typeof values['sample:id'] != 'undefined'){\n values['occurrence:id']=subData[i].occurrence_id;\n values['occurrence:record_status']='C';\n url=(url == '' ? \"" . iform_ajaxproxy_url($node, 'occurrence') . "\" : \"" . iform_ajaxproxy_url($node, 'smp-occ') . "\");\n }\n } else { // any occurrences on unclosed collections must be flagged as 'I' - reopening unverifies.\n if(subData[i].record_status != 'I'){\n values['occurrence:id']=subData[i].occurrence_id;\n values['occurrence:record_status']='I';\n url=(url == '' ? \"" . iform_ajaxproxy_url($node, 'occurrence') . "\" : \"" . iform_ajaxproxy_url($node, 'smp-occ') . "\");\n }\n }\n if(url!=''){\n values['website_id']=" . $args['website_id'] . ";\n jQuery.ajax({ type: 'POST', url: url, data: values, dataType: 'json', async: false});\n }\n }\n },\n dataType: 'json',\n async: false\n });\n dialog.dialog('close');\n dialog.dialog('destroy');\n jQuery('#subsample-progress-span').remove();\n}\n\n\t\t\twindow.scroll(0,0);\n jQuery('#SurveyForm > input[name=sample\\:id]').removeAttr('disabled').val(data.outer_id);\n jQuery('#occ-form > input[name=sample\\:parent_id]').val(data.outer_id);\n jQuery('#occ-form > input[name=sample\\:date]').val(jQuery('#SurveyForm > input[name=sample\\:date]').val());\n loadAttributes('sample_attribute_value', 'sample_attribute_id', 'sample_id', data.outer_id, 'smpAttr');\n switch(\"" . $args["on_save_survey_nav"] . "\"){\n\t\t\t\tcase \"list\":\n\t\t\t\t\tvar a = \$('ul.ui-tabs-nav a')[2];\n\t\t\t\t\t\$(a).click();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"survey\":\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:"; if (!user_access($args['edit_permission'])) { data_entry_helper::$javascript .= "\n\t\t\t\t\tif(jQuery('#main-sample-closed').val() == 0){\n\t\t\t\t\t\tvar a = \$('ul.ui-tabs-nav a')[1];\n\t\t\t\t\t\t\$(a).click();\n\t\t\t\t\t};"; } else { data_entry_helper::$javascript .= "\n\t\t\t\t\tvar a = \$('ul.ui-tabs-nav a')[1];\n\t\t\t\t\t\$(a).click();"; } data_entry_helper::$javascript .= "\n\t\t\t\t\tbreak;\n\t\t\t}\n } else {\n\t\t\tif(data.error){\n\t\t\t\tvar lastIndex = data.error.lastIndexOf('Validation error');\n \t\t\tif (lastIndex != -1 && lastIndex == (data.error.length - 16)){\n\t\t\t\t\tif(data.errors){\n\t\t\t\t\t\t// TODO translation\n\t\t\t\t\t\tfor (i in data.errors){\n\t\t\t\t\t\t\tvar label = \$('<p/>').addClass('inline-error').html(data.errors[i]);\n\t\t\t\t\t\t\tlabel.insertAfter('[name='+i+']');\n\t\t\t\t\t\t}\n\t\t\t\t\t\tmyScrollToError();\n\t\t\t\t\t\treturn;\n \t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\talertIndiciaError(data);\n }\n\t},\n complete: function (){\n \t\tjQuery('.loading-button').removeClass('loading-button');\n \t}\n});\n// In this case, all the samples attributes are on the survey tab, and all the occurrence attributes are on the occurrence tab. No need to worry about getting the correct form.\nloadAttributes = function(attributeTable, attributeKey, key, keyValue, prefix){\n jQuery.ajax({\n type: \"GET\",\n url: \"" . $svcUrl . "/data/\" + attributeTable + \"?mode=json&view=list\" +\n \t\"&reset_timeout=true&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n \t\t\t\"&\" + key + \"=\" + keyValue + \"&callback=?\",\n data: {},\n success: (function(attrPrefix, attrKey) {\n var retVal = function(attrdata) {\n if(!(attrdata instanceof Array)){\n alertIndiciaError(attrdata);\n } else if (attrdata.length>0) {\n for (var i=0;i<attrdata.length;i++){\n // in all cases if the attribute already has the <prefix>:<X>:<Y> format name we leave. Other wise we update <prefix>:<X> to <prefix>:<X>:<Y>\n // We leave all values unchanged.\n // need to be careful about Cloud: this is a drop down, but it is not language specific: the termlist is\n // always in english, so the iso won't match.\n if (attrdata[i].id){\n if (attrdata[i].iso == null || attrdata[i].iso == '') // no iso - not a look up.\n jQuery('[name='+attrPrefix+'\\:'+attrdata[i][attrKey]+']').attr('name', attrPrefix+':'+attrdata[i][attrKey]+':'+attrdata[i].id);\n else {\n if (attrdata[i].iso == '" . $language . "') // this is our actual language so OK\n jQuery('[name='+attrPrefix+'\\:'+attrdata[i][attrKey]+']').attr('name', attrPrefix+':'+attrdata[i][attrKey]+':'+attrdata[i].id);\n else {// not our language: look up all the other attrs, and if we don't find one of this id for our language, use this one.\n var found = false;\n for (var j=0;j<attrdata.length;j++)\n found = found || (i!=j && attrdata[i][attrKey] == attrdata[j][attrKey] && attrdata[j].iso == '" . $language . "');\n if(!found)\n jQuery('[name='+attrPrefix+'\\:'+attrdata[i][attrKey]+']').attr('name', attrPrefix+':'+attrdata[i][attrKey]+':'+attrdata[i].id);\n }\n }\n }\n }\n }};\n return retVal;\n })(prefix, attributeKey),\n\t\tdataType: 'json',\n\t async: false\n\t});\n}"; // Set up Occurrence List tab: don't include when creating a new sample as it will have no occurrences // Grid populated at a later point $r .= "<div id=\"occurrenceList\" class=\"mnhnl-btw-datapanel\"><div id=\"occ_grid\"></div>\n <form method=\"post\" action=\"" . data_entry_helper::$base_url . "/index.php/services/report/requestReport?report=reports_for_prebuilt_forms/MNHNL/mnhnl_btw_occurrences_report.xml&reportSource=local&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth['nonce'] . "&mode=csv\">\n <input type=\"hidden\" id=\"params\" name=\"params\" value='{\"survey_id\":" . $args['survey_id'] . ", \"sample_id\":" . data_entry_helper::$entity_to_load['sample:id'] . "}' />\n <input type=\"submit\" class=\"ui-state-default ui-corner-all\" value=\"" . lang::get('LANG_Download_Occurrences') . "\">\n </form></div>"; if ($occReadOnly) { // NB that we don't even include the buttons when readonly. data_entry_helper::$javascript .= "\njQuery('#ro-occ-occ-warn').show();\njQuery('#ro-sur-occ-warn').hide();\n"; } else { data_entry_helper::$javascript .= "\njQuery('#ro-occ-occ-warn').hide();\n"; } if ($mode == 1) { data_entry_helper::$javascript .= "jQuery('#occ-form').hide();"; } else { data_entry_helper::$javascript .= "jQuery('#na-occ-warn').hide();"; } // Set up Occurrence tab: don't allow entry of a new occurrence until after top level sample is saved. data_entry_helper::$entity_to_load = $childSample; $attributes = data_entry_helper::getAttributes(array('id' => data_entry_helper::$entity_to_load['occurrence:id'], 'valuetable' => 'occurrence_attribute_value', 'attrtable' => 'occurrence_attribute', 'key' => 'occurrence_id', 'fieldprefix' => 'occAttr', 'extraParams' => $readAuth)); $extraParams = $readAuth + array('taxon_list_id' => $args['list_id'], 'view' => 'detail', 'query' => urlencode(json_encode(array('in' => array('language_iso', array('lat', iform_lang_iso_639_2($args['language']))))))); if ($occReadOnly) { // if the occurrence has been downloaded, no one can modify it. $disabledText = "disabled=\"disabled\""; $defAttrOptions['disabled'] = $disabledText; } $species_ctrl_args = array('label' => lang::get('LANG_Species'), 'fieldname' => 'occurrence:taxa_taxon_list_id', 'table' => 'taxa_taxon_list', 'captionField' => 'taxon', 'valueField' => 'id', 'columns' => 2, 'extraParams' => $extraParams, 'disabled' => $disabledText, 'defaultCaption' => data_entry_helper::$entity_to_load['occurrence:taxon']); $r .= " <div id=\"occurrence\" class=\"mnhnl-btw-datapanel\">\n <p id=\"ro-occ-occ-warn\"><strong>" . lang::get('LANG_Read_Only_Occurrence') . "</strong></p>\n <p id=\"ro-sur-occ-warn\"><strong>" . lang::get('LANG_Read_Only_Survey') . "</strong></p>\n <p id=\"na-occ-warn\"><strong>" . lang::get('LANG_Page_Not_Available') . "</strong></p>\n <form method=\"post\" id=\"occ-form\" action=\"" . iform_ajaxproxy_url($node, 'smp-occ') . "\" >\n <input type=\"hidden\" id=\"website_id\" name=\"website_id\" value=\"" . $args['website_id'] . "\" />\n <input type=\"hidden\" id=\"sample:survey_id\" name=\"sample:survey_id\" value=\"" . $args['survey_id'] . "\" />\n <input type=\"hidden\" id=\"sample:parent_id\" name=\"sample:parent_id\" value=\"" . $parentSample['sample:id'] . "\" />\n <input type=\"hidden\" id=\"sample:date\" name=\"sample:date\" value=\"" . data_entry_helper::$entity_to_load['sample:date'] . "\" />\n <input type=\"hidden\" id=\"sample:id\" name=\"sample:id\" value=\"" . data_entry_helper::$entity_to_load['sample:id'] . "\" />\n <input type=\"hidden\" id=\"occurrence:id\" name=\"occurrence:id\" value=\"" . data_entry_helper::$entity_to_load['occurrence:id'] . "\" />\n <input type=\"hidden\" id=\"occurrence:record_status\" name=\"occurrence:record_status\" value=\"" . ($closedFieldValue == '0' ? 'I' : 'C') . "\" />\n <input type=\"hidden\" id=\"occurrence:downloaded_flag\" name=\"occurrence:downloaded_flag\" value=\"N\" />\n " . data_entry_helper::autocomplete($species_ctrl_args) . "\n " . ($occurrence_confidence_id ? data_entry_helper::outputAttribute($attributes[$occurrence_confidence_id], array_merge($languageFilteredAttrOptions, array('noBlankText' => ''))) : "<span style=\"display: none;\">Occurrence attribute '" . self::ATTR_CONFIDENCE . "' not assigned to this survey</span>") . "\n " . data_entry_helper::sref_and_system(array('label' => lang::get('LANG_Spatial_ref'), 'systems' => array('2169' => 'Luref (Gauss Luxembourg)'))) . "\n <p>" . lang::get('LANG_Click_on_map') . "</p>\n " . data_entry_helper::outputAttribute($attributes[$occurrence_count_id], array_merge($defAttrOptions, array('default' => 1))) . "\n " . ($occurrence_approximation_id ? data_entry_helper::outputAttribute($attributes[$occurrence_approximation_id], $defAttrOptions) : "<span style=\"display: none;\">Occurrence attribute '" . self::ATTR_APPROXIMATION . "' not assigned to this survey</span>") . "\n " . data_entry_helper::outputAttribute($attributes[$occurrence_territorial_id], array_merge($defAttrOptions, array('default' => 1, 'id' => 'occ-territorial'))) . "\n " . data_entry_helper::outputAttribute($attributes[$occurrence_atlas_code_id], $languageFilteredAttrOptions) . "\n " . ($occurrence_overflying_id ? data_entry_helper::outputAttribute($attributes[$occurrence_overflying_id], $defAttrOptions) : "<span style=\"display: none;\">Occurrence attribute '" . self::ATTR_OVERFLYING . "' not assigned to this survey</span>") . "\n " . data_entry_helper::textarea(array('label' => lang::get('LANG_Comment'), 'fieldname' => 'occurrence:comment', 'disabled' => $disabledText)); if (!$surveyReadOnly && !$occReadOnly) { if ($mode == 3) { $r .= data_entry_helper::checkbox(array('label' => lang::get('Delete'), 'fieldname' => 'sample:deleted', 'id' => 'occ-sample-deleted')); } $r .= "<input type=\"submit\" id=\"occ-submit\" class=\"ui-state-default ui-corner-all\" value=\"" . lang::get('LANG_Save_Occurrence_Details') . "\" />"; } $r .= " </form>\n"; data_entry_helper::$javascript .= "\n// because of ID tracking it is easier to rebuild entire list etc.\nretriggerGrid = function(){\n \$('div#occ_grid').empty();\n occListLayer.destroyFeatures();\n activateAddList = 1;\n thisOccID = -1;\n \$('div#occ_grid').indiciaDataGrid('rpt:reports_for_prebuilt_forms/MNHNL/mnhnl_btw_list_occurrences', {\n indiciaSvc: '" . $svcUrl . "',\n dataColumns: ['taxon', 'territorial', 'count'],\n reportColumnTitles: {taxon : '" . lang::get('LANG_Species') . "', territorial : '" . lang::get('LANG_Territorial') . "', count : '" . lang::get('LANG_Count') . "'},\n actionColumns: {'" . lang::get('LANG_Show') . "' : \"" . url('node/' . $node->nid, array('query' => 'occurrence_id=£id£')) . "\",\n '" . lang::get('LANG_Highlight') . "' : \"script:highlight(£id£);\"},\n auth : { nonce : '" . $readAuth['nonce'] . "', auth_token : '" . $readAuth['auth_token'] . "'},\n parameters : { survey_id : '" . $args['survey_id'] . "',\n parent_id : jQuery('#SurveyForm [name=sample\\:id]').val(),\n territorial_attr_id : '" . $occurrence_territorial_id . "',\n count_attr_id : '" . $occurrence_count_id . "'},\n itemsPerPage : 12,\n callback : addListFeature ,\n cssOdd : ''\n });\n}\n\njQuery('#occ-form').ajaxForm({\n\tasync: false,\n\tdataType: 'json',\n beforeSubmit: function(data, obj, options){\n \tvar valid = true;\n \tclearErrors('form#occ-form');\n \tif (!jQuery('form#occ-form > input').valid()) { valid = false; }\n \tif (!jQuery('form#occ-form > select').valid()) { valid = false; }\n \tif(!valid) {\n\t\t\tmyScrollToError();\n\t\t\treturn false;\n\t\t};\n\t\tjQuery('#occ-submit').addClass('loading-button');\n\t\treturn true;\n\t},\n success: function(data){\n // this will leave all the fields populated.\n \tif(data.success == 'multiple records' && data.outer_table == 'sample'){\n\t\t\twindow.scroll(0,0);\n\t\t\t// cant use reset form, as returns it to original values: if this was called with occurrence_id =<x> then it would repopulate with original occurrence's values\n\t\t\t// website_id, survey_id, record_status, downloaded_flag, sample:entered_sref_system are constants and are left alone. parent_id, date are only set referring to parent sample.\n\t\t\tjQuery('form#occ-form').find('[name^=occAttr\\:]').each(function(){\n\t\t\t\tvar name = jQuery(this).attr('name').split(':');\n\t\t\t\tjQuery(this).attr('name', name[0]+':'+name[1]);\n\t\t\t});\n\t\t\tjQuery('form#occ-form').find('[name=occurrence\\:id],[name=sample\\:id]').val('').attr('disabled', 'disabled');\n\t\t\tjQuery('form#occ-form').find('[name=occurrence\\:taxa_taxon_list_id],[name=occurrence\\:taxa_taxon_list_id\\:taxon],[name=sample\\:entered_sref],[name=sample\\:geom],[name=occurrence\\:comment]').val('');\n\t\t\tjQuery('form#occ-form').find('[name=occAttr\\:" . $occurrence_confidence_id . "]').find('option').removeAttr('selected');\n\t\t\tjQuery('form#occ-form').find('[name=occAttr\\:" . $occurrence_count_id . "]').val('1');\n\t\t\tjQuery('form#occ-form').find('input[name=occAttr\\:" . $occurrence_approximation_id . "],input[name=occAttr\\:" . $occurrence_overflying_id . "]').removeAttr('checked','checked');\n\t\t\tjQuery('form#occ-form').find('#occ-territorial').attr('checked','checked');\n\t\t\tjQuery('label[for=occ-sample-deleted]').remove(); // sample deleted only applicable when editing an existing occurrence. After saving reverts to Add Occurreence: no delete. Remove label then actual checkbox\n\t\t\tjQuery('form#occ-form').find('[name=sample\\:deleted]').remove(); // This removes both parts of the checkbox.\n\t\t\tsetAtlasStatus();\n\t\t\tretriggerGrid();\n\t\t\tlocationLayer.map.editLayer.destroyFeatures();\n\t\t\tvar a = \$('ul.ui-tabs-nav a')[1];\n\t\t\t\$(a).empty().html('<span>" . lang::get('LANG_Add_Occurrence') . "</span>');\n\t\t\tswitch(\"" . $args["on_save_occurrence_nav"] . "\"){\n\t\t\t\tcase \"list\":\n\t\t\t\t\ta = \$('ul.ui-tabs-nav a')[2];\n\t\t\t\t\t\$(a).click();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"survey\":\n\t\t\t\t\ta = \$('ul.ui-tabs-nav a')[0];\n\t\t\t\t\t\$(a).click();\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\n } else {\n\t\t\tif(data.error){\n\t\t\t\tvar lastIndex = data.error.lastIndexOf('Validation error');\n \t\t\tif (lastIndex != -1 && lastIndex == (data.error.length - 16)){\n\t\t\t\t\tif(data.errors){\n\t\t\t\t\t\t// TODO translation\n\t\t\t\t\t\tfor (i in data.errors){\n\t\t\t\t\t\t\tvar label = \$('<p/>').addClass('inline-error').html(data.errors[i]);\n\t\t\t\t\t\t\tlabel.insertAfter('[name='+i+']');\n\t\t\t\t\t\t}\n\t\t\t\t\t\tmyScrollToError();\n\t\t\t\t\t\treturn;\n \t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\talertIndiciaError(data);\n }\n\t},\n complete: function (){\n \t\tjQuery('.loading-button').removeClass('loading-button');\n \t}\n});\nsetAtlasStatus = function() {\n if (jQuery(\"#occ-territorial:checked\").length == 0) {\n jQuery(\"select[name=occAttr\\:" . $occurrence_atlas_code_id . "],select[name^=occAttr\\:" . $occurrence_atlas_code_id . "\\:]\").val('');\n } else {\n if(jQuery(\"select[name=occAttr\\:" . $occurrence_atlas_code_id . "],select[name^=occAttr\\:" . $occurrence_atlas_code_id . "\\:]\").val() == '') {\n // Find the BB02 option (depends on the language what val it has)\n var bb02;\n jQuery.each(jQuery(\"select[name=occAttr\\:" . $occurrence_atlas_code_id . "],select[name^=occAttr\\:" . $occurrence_atlas_code_id . "\\:]\").find('option'), function(index, option) {\n if (option.text.substr(0,4)=='BB02') {\n bb02 = option.value;\n return; // just from the each loop\n }\n });\n jQuery(\"select[name=occAttr\\:" . $occurrence_atlas_code_id . "],select[name^=occAttr\\:" . $occurrence_atlas_code_id . "\\:]\").val(bb02);\n }\n }\n};\njQuery(\"#occ-territorial\").change(setAtlasStatus);\nif(\$.browser.msie) {\n jQuery(\"#occ-territorial\").click(function() {\n \$(this).change();\n });\n}\n\n"; if ($mode != 3) { data_entry_helper::$javascript .= "setAtlasStatus();\n"; } // reset the atlas when not looking at a old occurrence. $r .= '</div>'; // add map panel. $options = iform_map_get_map_options($args, $readAuth); $olOptions = iform_map_get_ol_options($args); // $options['layers'] = array('locationLayer', 'occListLayer'); $options['searchLayer'] = 'false'; $options['initialFeatureWkt'] = null; $options['proxy'] = ''; $options['scroll_wheel_zoom'] = false; $options['width'] = 'auto'; // TBD remove from arglist $r .= "<div class=\"mnhnl-btw-mappanel\">\n"; $r .= data_entry_helper::map_panel($options, $olOptions); // for timing reasons, all the following has to be done after the map is loaded. // 1) feature selector for occurrence list must have the map present to attach the control // 2) location placer must have the location layer populated and the map present in // order to zoom the map into the location. // 3) occurrence list feature adder must have map present in order to zoom into any // current selection. data_entry_helper::$onload_javascript .= "\n\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=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["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 {\n if(data[i].centroid_geom){\n " . self::readBoundaryJs('data[i].centroid_geom', $args['map_projection']) . "\n feature.style = {label: data[i].name,\n\t\t\t\t\t\t strokeColor: \"Green\",\n strokeWidth: 2,\n fillOpacity: 0};\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 " . self::readBoundaryJs('data[i].boundary_geom', $args['map_projection']) . "\n feature.style = {strokeColor: \"Blue\", strokeWidth: 2};\n locationLayer.addFeatures([feature]);\n }\n locationLayer.map.zoomToExtent(locationLayer.getDataExtent());\n }\n }\n });\n jQuery.getJSON(\"" . $svcUrl . "\" + \"/data/location\" +\n \"?mode=json&view=detail&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"] . "&callback=?&parent_id=\"+obj.value, function(data) {\n if (data.length>0) {\n var parser = new OpenLayers.Format.WKT();\n for (var i=0;i<data.length;i++)\n {\n if(data[i].centroid_geom){\n " . self::readBoundaryJs('data[i].centroid_geom', $args['map_projection']) . "\n locationLayer.addFeatures([feature]);\n }\n if(data[i].boundary_geom){\n " . self::readBoundaryJs('data[i].boundary_geom', $args['map_projection']) . "\n feature.style = {label: data[i].name,\n labelAlign: \"cb\",\n strokeColor: \"Blue\",\n strokeWidth: 2};\n locationLayer.addFeatures([feature]);\n }\n }\n }\n });\n }\n};\n// upload location initial value into map.\njQuery('#imp-location').each(function(){\n locationChange(this);\n});\njQuery('#imp-location').unbind('change');\njQuery('#imp-location').change(function(){\n locationChange(this);\n});\nvar selected = \$('#controls').tabs('option', 'selected');\n\n// Only leave the click control activated for edit/add occurrence tab.\nif(selected != 1){\n locationLayer.map.editLayer.clickControl.deactivate();\n}\n\$('#controls').bind('tabsshow', function(event, ui) {\n if(ui.index == 1)\n {\n locationLayer.map.editLayer.clickControl.activate();\n }\n else\n {\n locationLayer.map.editLayer.clickControl.deactivate();\n }\n }\n);\nactivateAddList = 1;\nthisOccID = " . $thisOccID . ";\naddListFeature = function(div, r, record, count) {\n if(activateAddList == 0)\n return;\n if(r == count)\n activateAddList = 0;\n var parser = new OpenLayers.Format.WKT();\n " . self::readBoundaryJs('record.geom', $args['map_projection']) . "\n if(record.id != thisOccID || 1==" . ($surveyReadOnly ? 1 : 0) . " || 1==" . ($occReadOnly ? 1 : 0) . "){\n feature.attributes.id = record.id;\n feature.attributes.taxon = record.taxon;\n feature.attributes.count = record.count;\n occListLayer.addFeatures([feature]);\n if(record.id == " . $thisOccID . "){\n var bounds=feature.geometry.getBounds();\n locationLayer.map.setCenter(bounds.getCenterLonLat());\n }\n } else {\n locationLayer.map.editLayer.destroyFeatures();\n locationLayer.map.editLayer.addFeatures([feature]);\n var bounds=feature.geometry.getBounds()\n var centre=bounds.getCenterLonLat();\n locationLayer.map.setCenter(centre);\n }\n};\nhighlight = function(id){\n if(id == " . $thisOccID . "){\n if(occListLayer.map.editLayer.features.length > 0){\n var bounds=occListLayer.map.editLayer.features[0].geometry.getBounds()\n var centre=bounds.getCenterLonLat();\n occListLayer.map.setCenter(centre);\n return;\n }\n }\n for(var i = 0; i < occListLayer.features.length; i++){\n if(occListLayer.features[i].attributes.id == id){\n control.unselectAll();\n var bounds=occListLayer.features[i].geometry.getBounds()\n var centre=bounds.getCenterLonLat();\n occListLayer.map.setCenter(centre);\n control.select(occListLayer.features[i]);\n return;\n }\n }\n}\n"; if ($mode != 1) { data_entry_helper::$onload_javascript .= "\n\$('div#occ_grid').indiciaDataGrid('rpt:reports_for_prebuilt_forms/MNHNL/mnhnl_btw_list_occurrences', {\n indiciaSvc: '" . $svcUrl . "',\n dataColumns: ['taxon', 'territorial', 'count'],\n reportColumnTitles: {taxon : '" . lang::get('LANG_Species') . "', territorial : '" . lang::get('LANG_Territorial') . "', count : '" . lang::get('LANG_Count') . "'},\n actionColumns: {'" . lang::get('LANG_Show') . "' : \"" . url('node/' . $node->nid, array('query' => 'occurrence_id=£id£')) . "\",\n '" . lang::get('LANG_Highlight') . "' : \"script:highlight(£id£);\"},\n auth : { nonce : '" . $readAuth['nonce'] . "', auth_token : '" . $readAuth['auth_token'] . "'},\n parameters : { survey_id : '" . $args['survey_id'] . "',\n parent_id : '" . $parentSample['sample:id'] . "',\n territorial_attr_id : '" . $occurrence_territorial_id . "',\n count_attr_id : '" . $occurrence_count_id . "'},\n itemsPerPage : 12,\n callback : addListFeature ,\n cssOdd : ''\n });\n\n// activateAddList = 0;\n\n"; } $r .= "</div><div><form><input id=\"return-to-main\" type=\"button\" value=\"" . lang::get('LANG_Return') . "\" onclick=\"window.location.href='" . url('node/' . $node->nid, array('query' => 'Main')) . "'\"></form></div></div>\n"; if (method_exists(get_called_class(), 'getTrailerHTML')) { $r .= call_user_func(array(get_called_class(), 'getTrailerHTML'), $args); } return $r; }
* * @package People tidier * @subpackage Views * @author Indicia Team * @license http://www.gnu.org/licenses/gpl.html GPL * @link http://code.google.com/p/indicia/ */ require_once DOCROOT . 'client_helpers/data_entry_helper.php'; $readAuth = data_entry_helper::get_read_auth(0 - $_SESSION['auth_user']->id, kohana::config('indicia.private_key')); ?> <p>Search for people records in the database that might be the same person as the currently selected person. Use * for wildcards to help when searching:</p> <div class="ui-helper-clearfix"> <div class="left" style="width: 45%"> <h2>User search</h2> <?php echo data_entry_helper::autocomplete(array('label' => 'Search', 'fieldname' => 'person_id', 'table' => 'person', 'captionField' => 'caption', 'valueField' => 'id', 'extraParams' => $readAuth + array('query' => urlencode(json_encode(array('notin' => array('id', $personId))))))); data_entry_helper::$javascript .= "\$('input#person_id\\:caption').change(function(event) {\n var personId=\$('input#person_id').val(), table;\n \$('#found-person-id').val(personId);\n jQuery.ajax({ \n type: 'GET', \n url: '" . url::site() . "people_tidier/person_panel/'+personId, \n data: {}, \n success: function(table) {\n \$('#selected-person').html(table);\n \$('#resolution input').attr('disabled','');\n },\n });\n});\n\n\$('#resolution').submit(function(e){\n if (!confirm('Are you absolutely sure that the 2 person records on this page refer to the same person and that you want to merge them into 1 record?'))\n e.preventDefault();\n});\n"; ?> <div id="selected-person" style="margin-left: 160px"></div> </div> <div class="right" style="width: 45%"> <h2>Selected user</h2> <?php echo $currentPersonPanel; ?> </div> </div> <form method="post" id="resolution" action="<?php echo url::site(); ?> people_tidier/merge_people" class="ui-helper-clearfix">
/** * Returns a control to insert onto a parameters form. * @param string $key The unique identifier of this control. * @param array $info Configuration options for the parameter as defined in the report, including the * description, display (label), default and datatype. * @param array $options Control options array * @param array $tools Any tools to be embedded in the map toolbar are returned in this * parameter rather than as the return result of the function. * @return string The HTML for the form parameter. */ private static function get_params_form_control($key, $info, $options, &$tools) { $r = ''; $fieldPrefix = isset($options['fieldNamePrefix']) ? $options['fieldNamePrefix'] . '-' : ''; $ctrlOptions = array('label' => lang::get($info['display']), 'helpText' => $options['helpText'] ? $info['description'] : '', 'fieldname' => $fieldPrefix . $key, 'nocache' => isset($options['nocache']) && $options['nocache']); // If this parameter is in the URL or post data, put it in the control instead of the original default if (isset($options['defaults'][$key])) { $ctrlOptions['default'] = $options['defaults'][$key]; } elseif (isset($info['default'])) { $ctrlOptions['default'] = $info['default']; } if ($info['datatype'] == 'idlist') { // idlists are not for human input so use a hidden. $r .= "<input type=\"hidden\" name=\"{$fieldPrefix}{$key}\" value=\"" . self::get_preset_param($options, $key) . "\" class=\"" . $fieldPrefix . "idlist-param\" />\n"; } elseif (isset($options['extraParams']) && array_key_exists($key, $options['extraParams'])) { $r .= "<input type=\"hidden\" name=\"{$fieldPrefix}{$key}\" value=\"" . self::get_preset_param($options, $key) . "\" />\n"; } elseif ($info['datatype'] == 'lookup' && isset($info['population_call'])) { // population call is colon separated, of the form direct|report:table|view|report:idField:captionField:params(key=value,key=value,...) $popOpts = explode(':', $info['population_call']); $extras = array(); // if there are any extra parameters on the report lookup call, apply them if (count($popOpts) >= 5) { // because any extra params might contain colons, any colons from item 5 onwards are considered part of the extra params. So we // have to take the remaining items and re-implode them, then split them by commas instead. E.g. population call could be set to // direct:term:id:term:term=a:b - in this case option 5 (term=a:b) is not to be split by colons. $extraItems = explode(',', implode(':', array_slice($popOpts, 4))); foreach ($extraItems as $extraItem) { $extraItem = explode('=', $extraItem); $extras[$extraItem[0]] = $extraItem[1]; } } // allow local page configuration to apply extra restrictions on the return values: e.g. only return some location_types from the termlist if (isset($options['param_lookup_extras']) && isset($options['param_lookup_extras'][$key])) { foreach ($options['param_lookup_extras'][$key] as $param => $value) { // direct table access can handle 'in' statements, reports can't. $extras[$param] = $popOpts[0] == 'direct' ? $value : (is_array($value) ? implode(',', $value) : $value); } // $extras[$param] = $value; } $ctrlOptions = array_merge($ctrlOptions, array('valueField' => $popOpts[2], 'captionField' => $popOpts[3], 'blankText' => '<please select>', 'extraParams' => $options['readAuth'] + $extras)); if ($popOpts[0] == 'direct') { $ctrlOptions['table'] = $popOpts[1]; } else { $ctrlOptions['report'] = $popOpts[1]; } if (isset($info['linked_to']) && isset($info['linked_filter_field'])) { $ctrlOptions['filterIncludesNulls'] = false; //exclude null entries from filter field by default if (isset($options['extraParams']) && array_key_exists($info['linked_to'], $options['extraParams'])) { // if the control this is linked to is hidden because it has a preset value, just use that value as a filter on the // population call for this control $ctrlOptions = array_merge($ctrlOptions, array('extraParams' => array_merge($ctrlOptions['extraParams'], array('query' => json_encode(array('in' => array($info['linked_filter_field'] => array($options['extraParams'][$info['linked_to']], null)))))))); } else { // otherwise link the 2 controls $ctrlOptions = array_merge($ctrlOptions, array('parentControlId' => $fieldPrefix . $info['linked_to'], 'filterField' => $info['linked_filter_field'], 'parentControlLabel' => $options['form'][$info['linked_to']]['display'])); } } //If user has set option, then make any lookup parameter an autocomplete, note that autocomplete controls also have a "selectMode" //which is why there is a further option provided if you want to use that mode. if (!empty($options['forceLookupParamAutocomplete']) && $options['forceLookupParamAutocomplete'] == true) { if (!empty($options['forceLookupParamAutocompleteSelectMode']) && $options['forceLookupParamAutocompleteSelectMode'] == true) { $ctrlOptions['selectMode'] = true; } $r .= data_entry_helper::autocomplete($ctrlOptions); } else { $r .= data_entry_helper::select($ctrlOptions); } } elseif ($info['datatype'] == 'lookup' && isset($info['lookup_values'])) { // Convert the lookup values into an associative array $lookups = explode(',', $info['lookup_values']); $lookupsAssoc = array(); foreach ($lookups as $lookup) { $lookup = explode(':', $lookup); $lookupsAssoc[$lookup[0]] = $lookup[1]; } $ctrlOptions = array_merge($ctrlOptions, array('blankText' => '<' . lang::get('please select') . '>', 'lookupValues' => $lookupsAssoc)); //If user has set option, then make any lookup parameter an autocomplete, note that autocomplete controls also have a "selectMode" //which is why there is a further option provided if you want to use that mode. if (!empty($options['forceLookupParamAutocomplete']) && $options['forceLookupParamAutocomplete'] == true) { if (!empty($options['forceLookupParamAutocompleteSelectMode']) && $options['forceLookupParamAutocompleteSelectMode'] == true) { $ctrlOptions['selectMode'] = true; } $r .= data_entry_helper::autocomplete($ctrlOptions); } else { $r .= data_entry_helper::select($ctrlOptions); } } elseif ($info['datatype'] == 'date') { $r .= data_entry_helper::date_picker($ctrlOptions); } elseif ($info['datatype'] == 'geometry') { $tools = array('Polygon', 'Line', 'Point'); } elseif ($info['datatype'] == 'polygon') { $tools = array('Polygon'); } elseif ($info['datatype'] == 'line') { $tools = array('Line'); } elseif ($info['datatype'] == 'point') { $tools = array('Point'); } else { if (method_exists('data_entry_helper', $info['datatype'])) { $ctrl = $info['datatype']; $r .= data_entry_helper::$ctrl($ctrlOptions); } else { $r .= data_entry_helper::text_input($ctrlOptions); } } return $r; }
<input type='hidden' id='record_status' name='record_status' value='C' /> <input type='hidden' id='id' name='id' value='<?php echo data_entry_helper::check_default_value('id'); ?> ' /> <?php echo data_entry_helper::autocomplete(array('label' => 'Taxon', 'fieldname' => 'occurrence:taxa_taxon_list_id', 'table' => 'taxa_taxon_list', 'captionField' => 'taxon', 'valueField' => 'id', 'extraParams' => $readAuth)); echo data_entry_helper::date_picker(array('label' => 'Date', 'fieldname' => 'sample:date')); echo data_entry_helper::map(); echo data_entry_helper::text_input(array('label' => 'Locality Description', 'fieldname' => 'sample:location_name', 'class' => 'wide')); echo data_entry_helper::select(array('label' => 'Survey', 'fieldname' => 'sample:survey_id', 'table' => 'survey', 'captionField' => 'title', 'valueField' => 'id', 'extraParams' => $readAuth)); ?> <br /> <label for='occurrence:determiner_id:caption'>Determiner:</label> <?php echo data_entry_helper::autocomplete('occurrence:determiner_id', 'person', 'caption', 'id', $readAuth); ?> <br /> <?php echo data_entry_helper::textarea(array('label' => 'Comment', 'fieldname' => 'sample:comment')); echo data_entry_helper::image_upload(array('label' => 'Image Upload', 'fieldname' => 'occurrence:image')); ?> <fieldset> <legend>Occurrence attributes</legend> <label for='<?php echo $config['dafor']; ?> '>Abundance DAFOR:</label> <?php echo data_entry_helper::select($config['dafor'], 'termlists_term', 'term', 'id', $readAuth + array('termlist_id' => $config['dafor_termlist'])); ?>
<?php data_entry_helper::enable_validation('entry-form'); echo $metadata; ?> <fieldset> <input type="hidden" name="identifiers_subject_observation:id" value="<?php echo $id; ?> " /> <input type="hidden" name="identifiers_subject_observation:subject_observation_id" value="<?php echo html::initial_value($values, 'identifiers_subject_observation:subject_observation_id'); ?> " /> <legend>Identifier Details</legend> <?php echo data_entry_helper::autocomplete(array('label' => 'Identifier', 'fieldname' => 'identifiers_subject_observation:identifier_id', 'table' => 'identifier', 'captionField' => 'coded_value', 'valueField' => 'id', 'extraParams' => $readAuth, 'default' => html::initial_value($values, 'identifiers_subject_observation:identifier_id'), 'defaultCaption' => html::initial_value($values, 'identifier:coded_value'), 'validation' => 'required')); echo data_entry_helper::checkbox(array('fieldname' => 'identifiers_subject_observation:matched', 'label' => 'Matched', 'helpText' => 'Does this observation match a known identifier?', 'default' => html::initial_value($values, 'identifiers_subject_observation:matched'))); echo data_entry_helper::select(array('fieldname' => 'identifiers_subject_observation:verified_status', 'label' => 'Verified status', 'helpText' => 'Status of this identifier observation.', 'lookupValues' => array('' => 'Please select>', 'U' => 'unknown', 'M' => 'misread', 'V' => 'verified'), 'default' => html::initial_value($values, 'identifiers_subject_observation:verified_status'), 'validation' => 'required')); ?> </fieldset> <?php if (array_key_exists('attributes', $values) && count($values['attributes']) > 0) { ?> <fieldset> <legend>Custom Attributes</legend> <ol> <?php foreach ($values['attributes'] as $attr) { $name = 'isoAttr:' . $attr['identifiers_subject_observation_attribute_id']; // if this is an existing attribute, tag it with the attribute value record id so we can re-save it
/** * Return the generated form output. * @return Form HTML. */ public static function get_form($args, $node, $response = null) { global $user; $logged_in = $user->uid > 0; $r = ''; // Get authorisation tokens to update and read from the Warehouse. $writeAuth = data_entry_helper::get_auth($args['website_id'], $args['password']); $readAuth = data_entry_helper::get_read_auth($args['website_id'], $args['password']); $svcUrl = data_entry_helper::$base_url . '/index.php/services'; $presetLayers = array(); // read out the activated preset layers if (isset($args['preset_layers'])) { foreach ($args['preset_layers'] as $layer => $active) { if ($active !== 0) { $presetLayers[] = $layer; } } } // When invoked by GET there are the following modes: // Not logged in: Display an information message. // No additional arguments: display the survey selector. // Additional argument - newSample: display the main page, no occurrence or occurrence list tabs. Survey tab active. // Additional argument - sample_id=<id>: display the main page, fill in the main sample details, "Add Occurrence" tab present, survey tab active. // Additional argument - occurrence_id=<id>: display the main page, fill in the main sample details, "Add Occurrence" tab active. $mode = 0; // default mode : display survey selector // mode 1: display new sample: no occurrence list or add occurrence tabs. Survey tab active // mode 2: display existing sample. Survey tab active. No occurence details filled in. // mode 3: display existing occurrence. Add Occurrence tab active. Occurence details filled in. // mode 4: NO LONGER USED. display Occurrence List. Occurrence List tab active. No occurence details filled in. $readOnly = false; // On top of this, things can be flagged as readonly. RO mode 2+4 means no Add Occurrence tab. if (!$logged_in) { return lang::get('LANG_not_logged_in'); } $parentSample = array(); $parentErrors = null; $parentLoadID = null; $childSample = array(); $childErrors = null; $childLoadID = null; $saveErrors = data_entry_helper::$validation_errors; $thisOccID = -1; // IDs have to be >0, so this is outside the valid range $displayThisOcc = true; // when populating from the DB rather than POST we have to be // careful with selection object, as geom in wrong format. if ($_POST) { if (array_key_exists('website_id', $_POST)) { // Indicia POST, already handled. if (array_key_exists('newSample', $_GET)) { if (!is_null(data_entry_helper::$entity_to_load)) { $mode = 1; // errors with new sample, entity populated with post, so display this data. $parentSample = data_entry_helper::$entity_to_load; $parentErrors = $saveErrors; } else { // else new sample just saved, so reload it ready to add occurrences // OR, child sample/occurrence saved against new parent sample, in which case parent sample is in the post. $mode = 2; $parentLoadID = array_key_exists('sample:parent_id', $_POST) ? $_POST['sample:parent_id'] : $response['outer_id']; } } else { // could have saved parent sample or child sample/occurrence pair. if (array_key_exists('sample:parent_id', $_POST)) { // have saved child sample/occurrence pair $parentLoadID = $_POST['sample:parent_id']; // load the parent sample. $mode = 3; if (isset(data_entry_helper::$entity_to_load)) { // errors so display Edit Occurrence page. $childSample = data_entry_helper::$entity_to_load; $childErrors = $saveErrors; $displayThisOcc = false; if ($childSample['occurrence:id']) { $thisOccID = $childSample['occurrence:id']; } } } else { // saved parent record. display updated parent, no child. $mode = 2; // display parent sample details, whether errors or not. if (isset(data_entry_helper::$entity_to_load)) { // errors so use posted data. $parentSample = data_entry_helper::$entity_to_load; $parentErrors = $saveErrors; } else { $parentLoadID = $_POST['sample:id']; // load the parent sample. } } } } else { // 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('mnhnlbtw', $_POST)) { iform_loctools_deletelocations($node); foreach ($_POST as $key => $value) { $parts = explode(':', $key); if ($parts[0] == 'location' && $value) { iform_loctools_insertlocation($node, $value, $parts[1]); } } } } } else { if (array_key_exists('sample_id', $_GET)) { $mode = 2; $parentLoadID = $_GET['sample_id']; } else { if (array_key_exists('occurrence_id', $_GET)) { $mode = 3; $childLoadID = $_GET['occurrence_id']; $thisOccID = $childLoadID; } else { if (array_key_exists('newSample', $_GET)) { $mode = 1; } } } // else default to mode 0 } // define layers for all maps. // each argument is a comma separated list eg: // "Name:Lux Outline,URL:http://localhost/geoserver/wms,LAYERS:indicia:nation2,SRS:EPSG:2169,FORMAT:image/png,minScale:0,maxScale:1000000,units:m"; $optionArray_1 = array(); $optionArray_2 = array(); $options = explode(',', $args['layer1']); foreach ($options as $option) { $parts = explode(':', $option); $optionName = $parts[0]; unset($parts[0]); $optionsArray_1[$optionName] = implode(':', $parts); } $options = explode(',', $args['layer2']); foreach ($options as $option) { $parts = explode(':', $option); $optionName = $parts[0]; unset($parts[0]); $optionsArray_2[$optionName] = implode(':', $parts); } data_entry_helper::$javascript .= "\n// Create Layers.\n// Base Layers first.\nvar WMSoptions = {\n LAYERS: '" . $optionsArray_1['LAYERS'] . "',\n SERVICE: 'WMS',\n VERSION: '1.1.0',\n STYLES: '',\n SRS: '" . $optionsArray_1['SRS'] . "',\n FORMAT: '" . $optionsArray_1['FORMAT'] . "'\n };\nbaseLayer_1 = new OpenLayers.Layer.WMS('" . $optionsArray_1['Name'] . "',\n '" . iform_proxy_url($optionsArray_1['URL']) . "',\n WMSoptions, {\n minScale: " . $optionsArray_1['minScale'] . ",\n maxScale: " . $optionsArray_1['maxScale'] . ",\n units: '" . $optionsArray_1['units'] . "',\n isBaseLayer: true,\n singleTile: true\n });\nWMSoptions = {\n LAYERS: '" . $optionsArray_2['LAYERS'] . "',\n SERVICE: 'WMS',\n VERSION: '1.1.0',\n STYLES: '',\n SRS: '" . $optionsArray_2['SRS'] . "',\n FORMAT: '" . $optionsArray_2['FORMAT'] . "'\n };\nbaseLayer_2 = new OpenLayers.Layer.WMS('" . $optionsArray_2['Name'] . "',\n '" . iform_proxy_url($optionsArray_2['URL']) . "',\n WMSoptions, {\n minScale: " . $optionsArray_2['minScale'] . ",\n maxScale: " . $optionsArray_2['maxScale'] . ",\n units: '" . $optionsArray_2['units'] . "',\n isBaseLayer: true,\n singleTile: true\n });\n// Create vector layers: one to display the location onto, and another for the occurrence list\n// the default edit layer is used for the occurrences themselves\nlocStyleMap = new OpenLayers.StyleMap({\n \"default\": new OpenLayers.Style({\n fillColor: \"Green\",\n strokeColor: \"Black\",\n fillOpacity: 0.2,\n strokeWidth: 1\n })\n });\nlocationLayer = new OpenLayers.Layer.Vector(\"" . lang::get("LANG_Location_Layer") . "\",\n {styleMap: locStyleMap});\noccStyleMap = new OpenLayers.StyleMap({\n \"default\": new OpenLayers.Style({\n pointRadius: 3,\n fillColor: \"Red\",\n fillOpacity: 0.3,\n strokeColor: \"Red\",\n strokeWidth: 1\n }) });\noccListLayer = new OpenLayers.Layer.Vector(\"" . lang::get("LANG_Occurrence_List_Layer") . "\",\n {styleMap: occStyleMap});\n"; // Work out list of locations this user can see. $locations = iform_loctools_listlocations($node); /////////////////////////////////////////////////////////////////// // default mode 0 : display survey selector and locations allocator /////////////////////////////////////////////////////////////////// if ($mode == 0) { // If the user has permissions, add tabs so can choose to see // locations allocator $tabs = array('#surveyList' => lang::get('LANG_Surveys')); if (iform_loctools_checkaccess($node, 'admin')) { $tabs['#setLocations'] = lang::get('LANG_Allocate_Locations'); } if (iform_loctools_checkaccess($node, 'superuser')) { $tabs['#downloads'] = lang::get('LANG_Download'); } if (count($tabs) > 1) { $r .= "<div id=\"controls\">\n"; $r .= data_entry_helper::enable_tabs(array('divId' => 'controls', 'active' => '#surveyList')); $r .= "<div id=\"temp\"></div>"; $r .= data_entry_helper::tab_header(array('tabs' => $tabs)); } if ($locations == 'all') { $useloclist = 'NO'; $loclist = '-1'; } else { // an empty list will cause an sql error, lids must be > 0, so push a -1 to prevent the error. if (empty($locations)) { $locations[] = -1; } $useloclist = 'YES'; $loclist = implode(',', $locations); } // Create the Survey list datagrid for this user. drupal_add_js(drupal_get_path('module', 'iform') . '/media/js/hasharray.js', 'module'); drupal_add_js(drupal_get_path('module', 'iform') . '/media/js/jquery.datagrid.js', 'module'); drupal_add_js("jQuery(document).ready(function(){\n \$('div#smp_grid').indiciaDataGrid('rpt:mnhnl_btw_list_samples', {\n indiciaSvc: '" . $svcUrl . "',\n dataColumns: ['location_name', 'date', 'num_visit', 'num_occurrences', 'num_taxa'],\n reportColumnTitles: {location_name : '" . lang::get('LANG_Transect') . "', date : '" . lang::get('LANG_Date') . "', num_visit : '" . lang::get('LANG_Visit_No') . "', num_occurrences : '" . lang::get('LANG_Num_Occurrences') . "', num_taxa : '" . lang::get('LANG_Num_Species') . "'},\n actionColumns: {" . lang::get('LANG_Show') . " : \"" . url('node/' . $node->nid, array('query' => 'sample_id=£id£')) . "\"},\n auth : { nonce : '" . $readAuth['nonce'] . "', auth_token : '" . $readAuth['auth_token'] . "'},\n parameters : { survey_id : '" . $args['survey_id'] . "', visit_attr_id : '" . $args['sample_visit_number_id'] . "', closed_attr_id : '" . $args['sample_closure_id'] . "', use_location_list : '" . $useloclist . "', locations : '" . $loclist . "'},\n itemsPerPage : 12,\n condCss : {field : 'closed', value : '0', css: 'mnhnl-btw-highlight'},\n cssOdd : ''\n });\n});\n\n", 'inline'); $r .= '<div id="surveyList" class="mnhnl-btw-datapanel"><div id="smp_grid"></div>'; $r .= '<form><input type="button" value="' . lang::get('LANG_Add_Survey') . '" onclick="window.location.href=\'' . url('node/' . $node->nid, array('query' => 'newSample')) . '\'"></form></div>'; // Add the locations allocator if user has admin rights. if (iform_loctools_checkaccess($node, 'admin')) { $r .= '<div id="setLocations" class="mnhnl-btw-datapanel"><form method="post">'; $r .= "<input type=\"hidden\" id=\"mnhnlbtw\" name=\"mnhnlbtw\" value=\"mnhnlbtw\" />\n"; $url = $svcUrl . '/data/location'; $url .= "?mode=json&view=detail&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["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); if (!empty($entities)) { foreach ($entities as $entity) { if (!$entity["parent_id"]) { // only assign parent locations. $r .= "\n<label for=\"location:" . $entity["id"] . "\">" . $entity["name"] . ":</label><select id=\"location:" . $entity["id"] . "\" name=\"location:" . $entity["id"] . "\">"; $r .= "<option value=\"\" ><" . lang::get('LANG_Not_Allocated') . "></option>"; $defaultuserid = iform_loctools_getuser($node, $entity["id"]); foreach ($userlist as $uid => $a_user) { if ($uid == $defaultuserid) { $selected = 'selected="selected"'; } else { $selected = ''; } $r .= "<option value=\"" . $uid . "\" " . $selected . ">" . $a_user->name . "</option>"; } $r .= "</select>"; } } } $r .= "<input type=\"submit\" class=\"ui-state-default ui-corner-all\" value=\"" . lang::get('LANG_Save_Location_Allocations') . "\" />\n"; $r .= "</form></div>"; } // Add the downloader if user has manager (superuser) rights. if (iform_loctools_checkaccess($node, 'superuser')) { $r .= '<div id="downloads" class="mnhnl-btw-datapanel">'; $r .= "<form method=\"post\" action=\"" . data_entry_helper::$base_url . "/index.php/services/report/requestReport?report=mnhnl_btw_transect_direction_report.xml&reportSource=local&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth['nonce'] . "&mode=csv\">"; $r .= '<p>' . lang::get('LANG_Direction_Report') . '</p>'; $r .= "<input type=\"hidden\" id=\"params\" name=\"params\" value='{\"survey_id\":" . $args['survey_id'] . ", \"direction_attr_id\":" . $args['sample_walk_direction_id'] . ", \"closed_attr_id\":" . $args['sample_closure_id'] . "}' />"; $r .= "<input type=\"submit\" class=\"ui-state-default ui-corner-all\" value=\"" . lang::get('LANG_Direction_Report_Button') . "\">"; $r .= "</form>"; $r .= "<form method=\"post\" action=\"" . data_entry_helper::$base_url . "/index.php/services/report/requestReport?report=mnhnl_btw_download_report.xml&reportSource=local&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth['nonce'] . "&mode=csv\">"; $r .= '<p>' . lang::get('LANG_Initial_Download') . '</p>'; $r .= "<input type=\"hidden\" id=\"params\" name=\"params\" value='{\"survey_id\":" . $args['survey_id'] . ", \"closed_attr_id\":" . $args['sample_closure_id'] . ", \"download\": \"INITIAL\"}' />"; $r .= "<input type=\"submit\" class=\"ui-state-default ui-corner-all\" value=\"" . lang::get('LANG_Initial_Download_Button') . "\">"; $r .= "</form>"; $r .= "<form method=\"post\" action=\"" . data_entry_helper::$base_url . "/index.php/services/report/requestReport?report=mnhnl_btw_download_report.xml&reportSource=local&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth['nonce'] . "&mode=csv\">"; $r .= '<p>' . lang::get('LANG_Confirm_Download') . '</p>'; $r .= "<input type=\"hidden\" id=\"params\" name=\"params\" value='{\"survey_id\":" . $args['survey_id'] . ", \"closed_attr_id\":" . $args['sample_closure_id'] . ", \"download\": \"CONFIRM\"}' />"; $r .= "<input type=\"submit\" class=\"ui-state-default ui-corner-all\" value=\"" . lang::get('LANG_Confirm_Download_Button') . "\">"; $r .= "</form>"; $r .= "<form method=\"post\" action=\"" . data_entry_helper::$base_url . "/index.php/services/report/requestReport?report=mnhnl_btw_download_report.xml&reportSource=local&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth['nonce'] . "&mode=csv\">"; $r .= '<p>' . lang::get('LANG_Final_Download') . '</p>'; $r .= "<input type=\"hidden\" id=\"params\" name=\"params\" value='{\"survey_id\":" . $args['survey_id'] . ", \"closed_attr_id\":" . $args['sample_closure_id'] . ", \"download\": \"FINAL\"}' />"; $r .= "<input type=\"submit\" class=\"ui-state-default ui-corner-all\" value=\"" . lang::get('LANG_Final_Download_Button') . "\">"; $r .= "</form></div>"; } // Create Map $r .= "<div class=\"mnhnl-btw-mappanel\">\n"; $r .= data_entry_helper::map_panel(array('presetLayers' => $presetLayers, 'layers' => array('baseLayer_1', 'baseLayer_2', 'locationLayer'), 'initialFeatureWkt' => null, 'width' => 'auto', 'height' => 490, 'editLayer' => false, 'initial_lat' => $args['map_centroid_lat'], 'initial_long' => $args['map_centroid_long'], 'initial_zoom' => (int) $args['map_zoom'], 'scroll_wheel_zoom' => false), array('projection' => $args['map_projection'])); // Add locations to the map on the locations layer. // Zoom in to area which contains the users locations. if ($locations != 'all') { data_entry_helper::$javascript .= "locationList = [" . implode(',', $locations) . "];\n"; } data_entry_helper::$javascript .= "\n// upload locations into map.\n// Change the location control requests the location's geometry to place on the map.\n\$.getJSON(\"{$svcUrl}\" + \"/data/location\" +\n \"?mode=json&view=detail&nonce=" . $readAuth['nonce'] . "&auth_token=" . $readAuth['auth_token'] . "\" +\n \"&parent_id=NULL&callback=?\", function(data) {\n // store value in saved field?\n locationLayer.destroyFeatures();\n if (data.length>0) {\n var newFeatures = [];\n var feature;\n var parser = new OpenLayers.Format.WKT();\n for (var i=0;i<data.length;i++)\n {\n"; if ($locations != 'all') { // include restriction on locations if user does not have full access. data_entry_helper::$javascript .= "\n for(var j=0; j<locationList.length; j++) {\n if(locationList[j] == data[i].id || locationList[j] == data[i].parent_id) {"; } data_entry_helper::$javascript .= "\n if(data[i].boundary_geom){\n " . self::readBoundaryJs('data[i].boundary_geom', $args['map_projection']) . "\n feature.style = {label: data[i].name,\n strokeColor: \"Blue\",\n strokeWidth: 2};\n newFeatures.push(feature);\n }\n"; if ($locations != 'all') { data_entry_helper::$javascript .= "\n }\n }\n"; } data_entry_helper::$javascript .= "\n }\n locationLayer.addFeatures(newFeatures);\n locationLayer.map.zoomToExtent(locationLayer.getDataExtent());\n }\n});\n\$('#controls').bind('tabsshow', function(event, ui) {\n var y = \$('.mnhnl-btw-datapanel:visible').outerHeight(true) + \$('.mnhnl-btw-datapanel:visible').position().top;\n if(y < \$('.mnhnl-btw-mappanel').outerHeight(true)+ \$('.mnhnl-btw-mappanel').position().top){\n y = \$('.mnhnl-btw-mappanel').outerHeight(true)+ \$('.mnhnl-btw-mappanel').position().top;\n }\n \$('#controls').height(y - \$('#controls').position().top);\n});\n"; $r .= "</div>\n"; if (count($tabs) > 1) { $r .= "</div>"; } return $r; } /////////////////////////////////////////////////////////////////// $occReadOnly = false; if ($childLoadID) { $url = $svcUrl . '/data/occurrence/' . $childLoadID; $url .= "?mode=json&view=detail&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"]; $session = curl_init($url); curl_setopt($session, CURLOPT_RETURNTRANSFER, true); $entity = json_decode(curl_exec($session), true); $childSample = array(); foreach ($entity[0] as $key => $value) { $childSample['occurrence:' . $key] = $value; } if ($entity[0]['downloaded_flag'] == 'F') { // Final download complete, now readonly $occReadOnly = true; } $url = $svcUrl . '/data/sample/' . $childSample['occurrence:sample_id']; $url .= "?mode=json&view=detail&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"]; $session = curl_init($url); curl_setopt($session, CURLOPT_RETURNTRANSFER, true); $entity = json_decode(curl_exec($session), true); foreach ($entity[0] as $key => $value) { $childSample['sample:' . $key] = $value; } $childSample['sample:geom'] = ''; // value received from db is not WKT, which is assumed by all the code. $thisOccID = $childLoadID; // this will be used to load the occurrence into the editlayer. $childSample['taxon'] = $childSample['occurrence:taxon']; $parentLoadID = $childSample['sample:parent_id']; } if ($parentLoadID) { $url = $svcUrl . '/data/sample/' . $parentLoadID; $url .= "?mode=json&view=detail&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"]; $session = curl_init($url); curl_setopt($session, CURLOPT_RETURNTRANSFER, true); $entity = json_decode(curl_exec($session), true); $parentSample = array(); foreach ($entity[0] as $key => $value) { $parentSample['sample:' . $key] = $value; } if (is_array($locations) && !in_array($entity[0]["location_id"], $locations)) { return '<p>' . lang::get('LANG_No_Access_To_Location') . '</p>'; } if ($entity[0]["parent_id"]) { return '<p>' . lang::get('LANG_No_Access_To_Sample') . '</p>'; } $parentSample['sample:date'] = $parentSample['sample:date_start']; // bit of a bodge // default values for attributes from DB are picked up automatically. } $childSample['sample:date'] = $parentSample['sample:date']; // enforce a match between child and parent sample dates data_entry_helper::$entity_to_load = $parentSample; data_entry_helper::$validation_errors = $parentErrors; $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' => $readAuth)); $closedFieldName = $attributes[$args['sample_closure_id']]['fieldname']; $closedFieldValue = data_entry_helper::check_default_value($closedFieldName, array_key_exists('default', $attributes[$args['sample_closure_id']]) ? $attributes[$args['sample_closure_id']]['default'] : '0'); // default is not closed $adminPerm = 'IForm node ' . $node->nid . ' admin'; if ($closedFieldValue == '1' && !user_access($adminPerm)) { // sample has been closed, no admin perms. Everything now set to read only. $readOnly = true; $disabledText = "disabled=\"disabled\""; $defAttrOptions = array('extraParams' => $readAuth, 'disabled' => $disabledText); } else { // sample open. $disabledText = ""; $defAttrOptions = array('extraParams' => $readAuth); } data_entry_helper::enable_validation('SurveyForm'); $r .= "<div id=\"controls\">\n"; $activeTab = 'survey'; if ($mode == 3 || $mode == 2) { $activeTab = 'occurrence'; } // Set Up form tabs. if ($mode == 4) { $activeTab = 'occurrenceList'; } $r .= data_entry_helper::enable_tabs(array('divId' => 'controls', 'active' => $activeTab)); $r .= "<div id=\"temp\"></div>"; $r .= data_entry_helper::tab_header(array('tabs' => array('#survey' => lang::get('LANG_Survey'), '#occurrence' => lang::get($readOnly || $occReadOnly ? 'LANG_Show_Occurrence' : (isset($childSample['sample:id']) ? 'LANG_Edit_Occurrence' : 'LANG_Add_Occurrence')), '#occurrenceList' => lang::get('LANG_Occurrence_List')))); // Set up main Survey Form. $r .= "<div id=\"survey\" class=\"mnhnl-btw-datapanel\">\n"; if ($readOnly) { $r .= "<strong>" . lang::get('LANG_Read_Only_Survey') . "</strong>"; } $r .= "<form id=\"SurveyForm\" method=\"post\">\n"; $r .= $writeAuth; $r .= "<input type=\"hidden\" id=\"website_id\" name=\"website_id\" value=\"" . $args['website_id'] . "\" />\n"; $r .= "<input type=\"hidden\" id=\"sample:survey_id\" name=\"sample:survey_id\" value=\"" . $args['survey_id'] . "\" />\n"; $r .= iform_user_get_hidden_inputs($args); if (array_key_exists('sample:id', data_entry_helper::$entity_to_load)) { $r .= "<input type=\"hidden\" id=\"sample:id\" name=\"sample:id\" value=\"" . data_entry_helper::$entity_to_load['sample:id'] . "\" />\n"; } $defAttrOptions['validation'] = array('required'); $defAttrOptions['suffixTemplate'] = 'requiredsuffix'; if ($locations == 'all') { $locOptions = array_merge(array('label' => lang::get('LANG_Transect')), $defAttrOptions); $locOptions['extraParams'] = array_merge(array('parent_id' => 'NULL', 'view' => 'detail', 'orderby' => 'name'), $locOptions['extraParams']); $r .= data_entry_helper::location_select($locOptions); } else { // can't use location select due to location filtering. $r .= "<label for=\"imp-location\">" . lang::get('LANG_Transect') . ":</label>\n<select id=\"imp-location\" name=\"sample:location_id\" " . $disabled_text . " class=\" \" >"; $url = $svcUrl . '/data/location'; $url .= "?mode=json&view=detail&parent_id=NULL&orderby=name&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"]; $session = curl_init($url); curl_setopt($session, CURLOPT_RETURNTRANSFER, true); $entities = json_decode(curl_exec($session), true); if (!empty($entities)) { foreach ($entities as $entity) { if (in_array($entity["id"], $locations)) { if ($entity["id"] == data_entry_helper::$entity_to_load['sample:location_id']) { $selected = 'selected="selected"'; } else { $selected = ''; } $r .= "<option value=\"" . $entity["id"] . "\" " . $selected . ">" . $entity["name"] . "</option>"; } } } $r .= "</select><span class=\"deh-required\">*</span><br />"; } $languageFilteredAttrOptions = $defAttrOptions + array('language' => iform_lang_iso_639_2($args['language'])); $r .= data_entry_helper::outputAttribute($attributes[$args['sample_walk_direction_id']], $languageFilteredAttrOptions); $r .= data_entry_helper::outputAttribute($attributes[$args['sample_reliability_id']], $languageFilteredAttrOptions); $r .= data_entry_helper::outputAttribute($attributes[$args['sample_visit_number_id']], array_merge($languageFilteredAttrOptions, array('default' => 1, 'noBlankText' => true))); if ($readOnly) { $r .= data_entry_helper::text_input(array_merge($defAttrOptions, array('label' => lang::get('LANG_Date'), 'fieldname' => 'sample:date', 'disabled' => $disabledText))); } else { $r .= data_entry_helper::date_picker(array('label' => lang::get('LANG_Date'), 'fieldname' => 'sample:date', 'class' => 'vague-date-picker', 'suffixTemplate' => 'requiredsuffix')); } $r .= data_entry_helper::outputAttribute($attributes[$args['sample_wind_id']], $languageFilteredAttrOptions); $r .= data_entry_helper::outputAttribute($attributes[$args['sample_precipitation_id']], $languageFilteredAttrOptions); $r .= data_entry_helper::outputAttribute($attributes[$args['sample_temperature_id']], array_merge($defAttrOptions, array('suffixTemplate' => 'nosuffix'))); $r .= " degC<span class=\"deh-required\">*</span><br />"; $r .= data_entry_helper::outputAttribute($attributes[$args['sample_cloud_id']], $defAttrOptions); $r .= data_entry_helper::outputAttribute($attributes[$args['sample_start_time_id']], array_merge($defAttrOptions, array('suffixTemplate' => 'nosuffix'))); $r .= " hh:mm<span class=\"deh-required\">*</span><br />"; $r .= data_entry_helper::outputAttribute($attributes[$args['sample_end_time_id']], array_merge($defAttrOptions, array('suffixTemplate' => 'nosuffix'))); $r .= " hh:mm<span class=\"deh-required\">*</span><br />"; unset($defAttrOptions['suffixTemplate']); unset($defAttrOptions['validation']); if (user_access($adminPerm)) { // users with admin permissions can override the closing of the // sample by unchecking the checkbox. // Because this is attached to the sample, we have to include the sample required fields in the // the post. This means they can't be disabled, so we enable all fields in this case. // Normal users can only set this to closed, and they do this using a button/hidden field. $r .= data_entry_helper::outputAttribute($attributes[$args['sample_closure_id']], $defAttrOptions); } else { // hidden closed $r .= "<input type=\"hidden\" id=\"" . $closedFieldName . "\" name=\"" . $closedFieldName . "\" value=\"" . $closedFieldValue . "\" />\n"; } if (!empty(data_entry_helper::$validation_errors)) { $r .= data_entry_helper::dump_remaining_errors(); } $escaped_id = str_replace(':', '\\\\:', $closedFieldName); if (!$readOnly) { $r .= "<input type=button id=\"close1\" class=\"ui-state-default ui-corner-all\" value=\"" . lang::get('LANG_Save_Survey_Details') . "\";\n onclick=\"var result = \$('#SurveyForm input').valid();\n var result2 = \$('#SurveyForm select').valid();\n if (!result || !result2) {\n return;\n }\n jQuery('#SurveyForm').submit();\">\n"; if (!user_access($adminPerm) && $mode != 1) { $r .= "<input type=button id=\"close2\" class=\"ui-state-default ui-corner-all\" value=\"" . lang::get('LANG_Save_Survey_And_Close') . "\"\n onclick=\"if(confirm('" . lang::get('LANG_Close_Survey_Confirm') . "')){\n var result = \$('#SurveyForm input').valid();\n var result2 = \$('#SurveyForm select').valid();\n if (!result || !result2) {\n return;\n }\n jQuery('#" . $escaped_id . "').val('1');\n jQuery('#SurveyForm').submit();\n };\">\n"; } } $r .= "</form>"; $r .= "</div>\n"; // Set up Occurrence List tab: don't include when creating a new sample as it will have no occurrences // Grid populated at a later point $r .= "<div id=\"occurrenceList\" class=\"mnhnl-btw-datapanel\">\n"; if ($mode != 1) { drupal_add_js(drupal_get_path('module', 'iform') . '/media/js/hasharray.js', 'module'); drupal_add_js(drupal_get_path('module', 'iform') . '/media/js/jquery.datagrid.js', 'module'); $r .= '<div id="occ_grid"></div>'; $r .= "<form method=\"post\" action=\"" . data_entry_helper::$base_url . "/index.php/services/report/requestReport?report=mnhnl_btw_occurrences_report.xml&reportSource=local&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth['nonce'] . "&mode=csv\">"; $r .= "<input type=\"hidden\" id=\"params\" name=\"params\" value='{\"survey_id\":" . $args['survey_id'] . ", \"sample_id\":" . data_entry_helper::$entity_to_load['sample:id'] . "}' />"; $r .= "<input type=\"submit\" class=\"ui-state-default ui-corner-all\" value=\"" . lang::get('LANG_Download_Occurrences') . "\">"; $r .= "</FORM>"; } else { $r .= '<p>' . lang::get('LANG_Page_Not_Available') . '</p>'; } $r .= '</div>'; // Set up Occurrence tab: don't allow entry of a new occurrence until after top level sample is saved. $r .= "<div id=\"occurrence\" class=\"mnhnl-btw-datapanel\">\n"; if ($mode != 1 && ($mode != 2 && $mode != 4 || $readOnly == false)) { data_entry_helper::$entity_to_load = $childSample; data_entry_helper::$validation_errors = $childErrors; $attributes = data_entry_helper::getAttributes(array('id' => data_entry_helper::$entity_to_load['occurrence:id'], 'valuetable' => 'occurrence_attribute_value', 'attrtable' => 'occurrence_attribute', 'key' => 'occurrence_id', 'fieldprefix' => 'occAttr', 'extraParams' => $readAuth)); if ($occReadOnly) { $r .= "<strong>" . lang::get('LANG_Read_Only_Occurrence') . "</strong>"; $disabledText = "disabled=\"disabled\""; $defAttrOptions['disabled'] = $disabledText; } else { if ($readOnly) { $r .= "<strong>" . lang::get('LANG_Read_Only_Survey') . "</strong>"; } } $r .= "<form method=\"post\">\n"; $r .= $writeAuth; $r .= "<input type=\"hidden\" id=\"website_id\" name=\"website_id\" value=\"" . $args['website_id'] . "\" />\n"; $r .= "<input type=\"hidden\" id=\"sample:survey_id\" name=\"sample:survey_id\" value=\"" . $args['survey_id'] . "\" />\n"; $r .= "<input type=\"hidden\" id=\"sample:parent_id\" name=\"sample:parent_id\" value=\"" . $parentSample['sample:id'] . "\" />\n"; $r .= "<input type=\"hidden\" id=\"sample:date\" name=\"sample:date\" value=\"" . data_entry_helper::$entity_to_load['sample:date'] . "\" />\n"; if (array_key_exists('sample:id', data_entry_helper::$entity_to_load)) { $r .= "<input type=\"hidden\" id=\"sample:id\" name=\"sample:id\" value=\"" . data_entry_helper::$entity_to_load['sample:id'] . "\" />\n"; } if (array_key_exists('occurrence:id', data_entry_helper::$entity_to_load)) { $r .= "<input type=\"hidden\" id=\"occurrence:id\" name=\"occurrence:id\" value=\"" . data_entry_helper::$entity_to_load['occurrence:id'] . "\" />\n"; } $r .= "<input type=\"hidden\" id=\"occurrence:record_status\" name=\"occurrence:record_status\" value=\"C\" />\n"; $r .= "<input type=\"hidden\" id=\"occurrence:downloaded_flag\" name=\"occurrence:downloaded_flag\" value=\"N\" />\n"; $extraParams = $readAuth + array('taxon_list_id' => $args['list_id']); $species_ctrl_args = array('label' => lang::get('LANG_Species'), 'fieldname' => 'occurrence:taxa_taxon_list_id', 'table' => 'taxa_taxon_list', 'captionField' => 'taxon', 'valueField' => 'id', 'columns' => 2, 'extraParams' => $extraParams, 'suffixTemplate' => 'requiredsuffix', 'disabled' => $disabledText, 'defaultCaption' => data_entry_helper::$entity_to_load['occurrence:taxon']); $r .= data_entry_helper::autocomplete($species_ctrl_args); $r .= data_entry_helper::outputAttribute($attributes[$args['occurrence_confidence_id']], array_merge($languageFilteredAttrOptions, array('noBlankText' => ''))); $r .= data_entry_helper::sref_and_system(array('label' => lang::get('LANG_Spatial_ref'), 'systems' => array('2169' => 'Luref (Gauss Luxembourg)'), 'suffixTemplate' => 'requiredsuffix')); $r .= "<p>" . lang::get('LANG_Click_on_map') . "</p>"; $r .= data_entry_helper::outputAttribute($attributes[$args['occurrence_count_id']], array_merge($defAttrOptions, array('default' => 1, 'suffixTemplate' => 'requiredsuffix'))); $r .= data_entry_helper::outputAttribute($attributes[$args['occurrence_approximation_id']], $defAttrOptions); $r .= data_entry_helper::outputAttribute($attributes[$args['occurrence_territorial_id']], array_merge($defAttrOptions, array('default' => 1))); $r .= data_entry_helper::outputAttribute($attributes[$args['occurrence_atlas_code_id']], $languageFilteredAttrOptions); $r .= data_entry_helper::outputAttribute($attributes[$args['occurrence_overflying_id']], $defAttrOptions); $r .= data_entry_helper::textarea(array('label' => lang::get('LANG_Comment'), 'fieldname' => 'occurrence:comment', 'disabled' => $disabledText)); if (!empty(data_entry_helper::$validation_errors)) { $r .= data_entry_helper::dump_remaining_errors(); } if (!$readOnly && !$occReadOnly) { $r .= "<input type=\"submit\" class=\"ui-state-default ui-corner-all\" value=\"" . lang::get('LANG_Save_Occurrence_Details') . "\" />\n"; } $r .= "</form>\n"; $escaped_terr_id = str_replace(':', '\\\\:', $attributes[$args['occurrence_territorial_id']]['fieldname']); $escaped_atlas_id = str_replace(':', '\\\\:', $attributes[$args['occurrence_atlas_code_id']]['fieldname']); data_entry_helper::$javascript .= "\nsetAtlasStatus = function() {\n if (jQuery(\"input[name='" . $escaped_terr_id . "']:checked\").val() == '0') {\n jQuery('#" . $escaped_atlas_id . "').val('');\n } else {\n if(jQuery('#" . $escaped_atlas_id . "').val() == '') {\n // Find the BB02 option (depends on the language what val it has)\n var bb02;\n jQuery.each(jQuery('#" . $escaped_atlas_id . " option'), function(index, option) {\n if (option.text.substr(0,4)=='BB02') {\n bb02 = option.value;\n return; // just from the each loop\n }\n });\n jQuery('#" . $escaped_atlas_id . "').val(bb02);\n }\n }\n};\nsetAtlasStatus();\njQuery(\"input[name='" . $escaped_terr_id . "']\").change(setAtlasStatus);\n"; } else { $r .= '<p>' . lang::get('LANG_Page_Not_Available') . '</p>'; } $r .= '</div>'; // add map panel. $r .= "<div class=\"mnhnl-btw-mappanel\">\n"; $r .= data_entry_helper::map_panel(array('presetLayers' => $presetLayers, 'layers' => array('baseLayer_1', 'baseLayer_2', 'locationLayer', 'occListLayer'), 'initialFeatureWkt' => null, 'width' => 'auto', 'height' => 490, 'initial_lat' => $args['map_centroid_lat'], 'initial_long' => $args['map_centroid_long'], 'initial_zoom' => (int) $args['map_zoom'], 'scroll_wheel_zoom' => false), array('projection' => $args['map_projection'])); // for timing reasons, all the following has to be done after the map is loaded. // 1) feature selector for occurrence list must have the map present to attach the control // 2) location placer must have the location layer populated and the map present in // order to zoom the map into the location. // 3) occurrence list feature adder must have map present in order to zoom into any // current selection. data_entry_helper::$onload_javascript .= "\nvar control = new OpenLayers.Control.SelectFeature(occListLayer);\noccListLayer.map.addControl(control);\nfunction onPopupClose(evt) {\n // 'this' is the popup.\n control.unselect(this.feature);\n}\nfunction onFeatureSelect(evt) {\n feature = evt.feature;\n popup = new OpenLayers.Popup.FramedCloud(\"featurePopup\",\n feature.geometry.getBounds().getCenterLonLat(),\n new OpenLayers.Size(100,100),\n feature.attributes.taxon + \" (\" + feature.attributes.count + \")\",\n null, true, onPopupClose);\n feature.popup = popup;\n popup.feature = feature;\n feature.layer.map.addPopup(popup);\n}\nfunction onFeatureUnselect(evt) {\n feature = evt.feature;\n if (feature.popup) {\n popup.feature = null;\n feature.layer.map.removePopup(feature.popup);\n feature.popup.destroy();\n feature.popup = null;\n }\n}\n\noccListLayer.events.on({\n 'featureselected': onFeatureSelect,\n 'featureunselected': onFeatureUnselect\n});\n\ncontrol.activate();\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=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["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 {\n if(data[i].centroid_geom){\n " . self::readBoundaryJs('data[i].centroid_geom', $args['map_projection']) . "\n feature.style = {label: data[i].name,\n\t\t\t\t\t\t strokeColor: \"Green\",\n strokeWidth: 2,\n fillOpacity: 0};\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 " . self::readBoundaryJs('data[i].boundary_geom', $args['map_projection']) . "\n feature.style = {strokeColor: \"Blue\", strokeWidth: 2};\n locationLayer.addFeatures([feature]);\n }\n locationLayer.map.zoomToExtent(locationLayer.getDataExtent());\n }\n }\n });\n jQuery.getJSON(\"" . $svcUrl . "\" + \"/data/location\" +\n \"?mode=json&view=detail&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"] . "&callback=?&parent_id=\"+obj.value, function(data) {\n if (data.length>0) {\n var parser = new OpenLayers.Format.WKT();\n for (var i=0;i<data.length;i++)\n {\n if(data[i].centroid_geom){\n " . self::readBoundaryJs('data[i].centroid_geom', $args['map_projection']) . "\n locationLayer.addFeatures([feature]);\n }\n if(data[i].boundary_geom){\n " . self::readBoundaryJs('data[i].boundary_geom', $args['map_projection']) . "\n feature.style = {label: data[i].name,\n labelAlign: \"cb\",\n strokeColor: \"Blue\",\n strokeWidth: 2};\n locationLayer.addFeatures([feature]);\n }\n }\n }\n });\n }\n};\n// upload location initial value into map.\njQuery('#imp-location').each(function(){\n locationChange(this);\n});\njQuery('#imp-location').unbind('change');\njQuery('#imp-location').change(function(){\n locationChange(this);\n});\nvar selected = \$('#controls').tabs('option', 'selected');\n\n// Only leave the click control activated for edit/add occurrence tab.\nif(selected != 1){\n locationLayer.map.editLayer.clickControl.deactivate();\n}\n\$('#controls').bind('tabsshow', function(event, ui) {\n if(ui.index == 1)\n {\n locationLayer.map.editLayer.clickControl.activate();\n }\n else\n {\n locationLayer.map.editLayer.clickControl.deactivate();\n }\n }\n);\n"; if ($mode != 1) { data_entry_helper::$onload_javascript .= "\nactivateAddList = 1;\n\naddListFeature = function(div, r, record, count) {\n if(activateAddList == 0)\n return;\n if(r == count)\n activateAddList = 0;\n var parser = new OpenLayers.Format.WKT();\n " . self::readBoundaryJs('record.geom', $args['map_projection']) . "\n if(record.id != " . $thisOccID . " || 1==" . ($readOnly ? 1 : 0) . " || 1==" . ($occReadOnly ? 1 : 0) . "){\n feature.attributes.id = record.id;\n feature.attributes.taxon = record.taxon;\n feature.attributes.count = record.count;\n occListLayer.addFeatures([feature]);\n if(record.id == " . $thisOccID . "){\n var bounds=feature.geometry.getBounds();\n locationLayer.map.setCenter(bounds.getCenterLonLat());\n }\n } else {\n if(" . ($displayThisOcc ? 1 : 0) . "){\n locationLayer.map.editLayer.destroyFeatures();\n locationLayer.map.editLayer.addFeatures([feature]);\n var bounds=feature.geometry.getBounds()\n var centre=bounds.getCenterLonLat();\n locationLayer.map.setCenter(centre);\n }\n }\n};\nhighlight = function(id){\n if(id == " . $thisOccID . "){\n if(occListLayer.map.editLayer.features.length > 0){\n var bounds=occListLayer.map.editLayer.features[0].geometry.getBounds()\n var centre=bounds.getCenterLonLat();\n occListLayer.map.setCenter(centre);\n return;\n }\n }\n for(var i = 0; i < occListLayer.features.length; i++){\n if(occListLayer.features[i].attributes.id == id){\n control.unselectAll();\n var bounds=occListLayer.features[i].geometry.getBounds()\n var centre=bounds.getCenterLonLat();\n occListLayer.map.setCenter(centre);\n control.select(occListLayer.features[i]);\n return;\n }\n }\n}\n\$('div#occ_grid').indiciaDataGrid('rpt:mnhnl_btw_list_occurrences', {\n indiciaSvc: '" . $svcUrl . "',\n dataColumns: ['taxon', 'territorial', 'count'],\n reportColumnTitles: {taxon : '" . lang::get('LANG_Species') . "', territorial : '" . lang::get('LANG_Territorial') . "', count : '" . lang::get('LANG_Count') . "'},\n actionColumns: {'" . lang::get('LANG_Show') . "' : \"" . url('node/' . $node->nid, array('query' => 'occurrence_id=£id£')) . "\",\n '" . lang::get('LANG_Highlight') . "' : \"script:highlight(£id£);\"},\n auth : { nonce : '" . $readAuth['nonce'] . "', auth_token : '" . $readAuth['auth_token'] . "'},\n parameters : { survey_id : '" . $args['survey_id'] . "',\n parent_id : '" . $parentSample['sample:id'] . "',\n territorial_attr_id : '" . $args['occurrence_territorial_id'] . "',\n count_attr_id : '" . $args['occurrence_count_id'] . "'},\n itemsPerPage : 12,\n callback : addListFeature ,\n cssOdd : ''\n });\n\n// activateAddList = 0;\n\n"; } $r .= "</div><div><form><input type=\"button\" value=\"" . lang::get('LANG_Return') . "\" onclick=\"window.location.href='" . url('node/' . $node->nid, array('query' => 'Main')) . "'\"></form></div></div>\n"; return $r; }
/** * Code to output a standardised report filtering panel. * * Filters can be saved and loaded by each user. Additionally, filters can define permissions to a certain task, e.g. they can be used to define the * context within which someone can verify. In this case they provide the "outer limit" of the available records. * Requires a [map] control on the page. If you don't want a map, the current option is to include one anyway and use css to hide the #map-container div. * * @param array $readAuth Pass read authorisation tokens. * @param array $options Options array with the following possibilities: * sharing - define the record sharing task that is being filtered against. Options are reporting (default), peer_review, verification, moderation, data_flow. * context_id - can also be passed as URL parameter. Force the initial selection of a particular context (a record which has defines_permissions=true in the * filters table. Set to "default" to select their profile verification settings when sharing=verification. * filter_id - can also be passed as URL parameter. Force the initial selection of a particular filter record in the filters table. * filterTypes - allows control of the list of filter panels available, e.g. to turn one off. Associative array keyed by category * so that the filter panels can be grouped (use a blank key if not required). The array values are an array of or strings with a comma separated list * of the filter types to included in the category - options are what, where, when, who, quality, source. * filter-#name# - set the initial value of a report filter parameter #name#. * allowLoad - set to false to disable the load bar at the top of the panel. * allowSave - set to false to disable the save bar at the foot of the panel. * presets - provide an array of preset filters to provide in the filters drop down. Choose from my-records, my-groups (uses * your list of taxon groups in the user account), my-locality (uses your recording locality from the user account), * my-groups-locality (uses taxon groups and recording locality from the user account), my-queried-records, queried-records, * answered-records, accepted-records, not-accepted-records. * @param integer $website_id The current website's warehouse ID. * @param string $hiddenStuff Output parameter which will contain the hidden popup HTML that will be shown * using fancybox during filter editing. Should be appended AFTER any form element on the page as nested forms are not allowed. * @return string HTML for the report filter panel */ function report_filter_panel($readAuth, $options, $website_id, &$hiddenStuff) { if (function_exists('iform_load_helpers')) { iform_load_helpers(array('report_helper')); } else { //When running on warehouse we don't have iform_load_helpers require_once DOCROOT . 'client_helpers/report_helper.php'; } if (!empty($_POST['filter:sharing'])) { $options['sharing'] = $_POST['filter:sharing']; } $options = array_merge(array('sharing' => 'reporting', 'admin' => false, 'adminCanSetSharingTo' => array('R' => 'reporting', 'V' => 'verification'), 'allowLoad' => true, 'allowSave' => true, 'redirect_on_success' => '', 'presets' => array('my-records', 'my-queried-records', 'my-queried-or-not-accepted-records', 'my-not-reviewed-records', 'my-accepted-records', 'my-groups', 'my-locality', 'my-groups-locality'), 'entity' => 'occurrence'), $options); // Introduce some extra quick filters useful for verifiers. if ($options['sharing'] === 'verification') { $options['presets'] = array_merge(array('queried-records', 'answered-records', 'accepted-records', 'not-accepted-records'), $options['presets']); } if ($options['entity'] === 'sample') { unset($options['presets']['my-groups']); unset($options['presets']['my-groups-locality']); } //If in the warehouse we don't need to worry about the iform master list. if (function_exists('variable_get')) { $options = array_merge(array('taxon_list_id' => variable_get('iform_master_checklist_id', 0)), $options); } $options['sharing'] = report_filters_sharing_code_to_full_term($options['sharing']); $options['sharingCode'] = report_filters_full_term_to_sharing_code($options['sharing']); if (!preg_match('/^(reporting|peer_review|verification|data_flow|moderation)$/', $options['sharing'])) { return 'The @sharing option must be one of reporting, peer_review, verification, data_flow or moderation (currently ' . $options['sharing'] . ').'; } report_helper::add_resource('reportfilters'); report_helper::add_resource('validation'); report_helper::add_resource('fancybox'); if (function_exists('hostsite_add_library')) { hostsite_add_library('collapse'); } $filterData = report_filters_load_existing($readAuth, $options['sharingCode']); $existing = ''; $contexts = ''; // add some preset filters in //If in the warehouse we don't need to worry about user specific preferences when setting up milestones. if (function_exists('hostsite_get_user_field')) { foreach ($options['presets'] as $preset) { $title = false; switch ($preset) { case 'my-records': if (hostsite_get_user_field('id')) { $title = lang::get('My records'); } break; case 'my-queried-records': if (hostsite_get_user_field('id')) { $title = lang::get('My queried records'); } break; case 'my-queried-or-not-accepted-records': if (hostsite_get_user_field('id')) { $title = lang::get('My not accepted or queried records'); } break; case 'my-not-reviewed-records': if (hostsite_get_user_field('id')) { $title = lang::get('My not reviewed records'); } break; case 'my-accepted-records': if (hostsite_get_user_field('id')) { $title = lang::get('My accepted records'); } break; case 'my-groups': if (hostsite_get_user_field('taxon_groups', false, true)) { $title = lang::get('Records in species groups I like to record'); } break; case 'my-locality': if (hostsite_get_user_field('location')) { $title = lang::get('Records in the locality I generally record in'); } break; case 'my-groups-locality': if (hostsite_get_user_field('taxon_groups', false, true) && hostsite_get_user_field('location')) { $title = lang::get('Records of my species groups in my locality'); } break; case 'queried-records': $title = lang::get('Queried records'); break; case 'answered-records': $title = lang::get('Records with answers'); break; case 'accepted-records': $title = lang::get('Accepted records'); break; case 'not-accepted-records': $title = lang::get('Not accepted records'); break; default: throw new exception("Unsupported preset {$preset} for the filter panel"); } if ($title) { $presetFilter = array('id' => $preset, 'title' => $title, 'defines_permissions' => 'f'); $filterData[] = $presetFilter; } } if (count($options['presets'])) { if ($groups = hostsite_get_user_field('taxon_groups', false, true)) { data_entry_helper::$javascript .= "indiciaData.userPrefsTaxonGroups='" . implode(',', $groups) . "';\n"; } if ($location = hostsite_get_user_field('location')) { data_entry_helper::$javascript .= "indiciaData.userPrefsLocation=" . $location . ";\n"; } } $contextDefs = array(); if ($options['sharing'] === 'verification') { // apply legacy verification settings from their profile $location_id = hostsite_get_user_field('location_expertise'); $taxon_group_ids = hostsite_get_user_field('taxon_groups_expertise', false, true); $survey_ids = hostsite_get_user_field('surveys_expertise', false, true); if ($location_id || $taxon_group_ids || $survey_ids) { $selected = !empty($options['context_id']) && $options['context_id'] === 'default' ? 'selected="selected" ' : ''; $contexts .= "<option value=\"default\" {$selected}>" . lang::get('My verification records') . "</option>"; $def = array(); if ($location_id) { // user profile geographic limits should always be based on an indexed location. $def['indexed_location_id'] = $location_id; } if ($taxon_group_ids) { $def['taxon_group_list'] = implode(',', $taxon_group_ids); $def['taxon_group_names'] = array(); $groups = data_entry_helper::get_population_data(array('table' => 'taxon_group', 'extraParams' => $readAuth + array('id' => $taxon_group_ids))); foreach ($groups as $group) { $def['taxon_group_names'][$group['id']] = $group['title']; } } if ($survey_ids) { $def['survey_list'] = implode(',', array_filter($survey_ids)); } $contextDefs['default'] = $def; } } } if (!empty($_GET['context_id'])) { $options['context_id'] = $_GET['context_id']; } if (!empty($_GET['filter_id'])) { $options['filter_id'] = $_GET['filter_id']; } if (!empty($_GET['filters_user_id'])) { $options['filters_user_id'] = $_GET['filters_user_id']; } foreach ($filterData as $filter) { if ($filter['defines_permissions'] === 't') { $selected = !empty($options['context_id']) && $options['context_id'] == $filter['id'] ? 'selected="selected" ' : ''; $contexts .= "<option value=\"{$filter['id']}\" {$selected}>{$filter['title']}</option>"; $contextDefs[$filter['id']] = json_decode($filter['definition']); } else { $selected = !empty($options['filter_id']) && $options['filter_id'] == $filter['id'] ? 'selected="selected" ' : ''; $existing .= "<option value=\"{$filter['id']}\" {$selected}>{$filter['title']}</option>"; } } $r = '<div id="standard-params" class="ui-widget">'; if ($options['allowSave'] && $options['admin']) { if (empty($_GET['filters_user_id'])) { // new filter to create, so sharing type can be edited $reload = data_entry_helper::get_reload_link_parts(); $reloadPath = $reload['path']; if (count($reload['params'])) { $reloadPath .= '?' . data_entry_helper::array_to_query_string($reload['params']); } $r .= "<form action=\"{$reloadPath}\" method=\"post\" >"; $r .= data_entry_helper::select(array('label' => lang::get('Select filter type'), 'fieldname' => 'filter:sharing', 'lookupValues' => $options['adminCanSetSharingTo'], 'afterControl' => '<input type="submit" value="Go"/>', 'default' => $options['sharingCode'])); $r .= '</form>'; } else { // existing filter to edit, type is therefore fixed. JS will fill these values in. $r .= '<p>' . lang::get('This filter is for <span id="sharing-type-label"></span>.') . '</p>'; $r .= data_entry_helper::hidden_text(array('fieldname' => 'filter:sharing')); } } if ($options['allowLoad']) { $r .= '<div class="header ui-toolbar ui-widget-header ui-helper-clearfix"><div><span id="active-filter-label">' . lang::get('New report') . '</span></div><span class="changed" style="display:none" title="This filter has been changed">*</span>'; $r .= '<div>'; if ($contexts) { data_entry_helper::$javascript .= "indiciaData.filterContextDefs = " . json_encode($contextDefs) . ";\n"; if (count($contextDefs) > 1) { $r .= '<label for="context-filter">' . lang::get('Context:') . "</label><select id=\"context-filter\">{$contexts}</select>"; } else { $keys = array_keys($contextDefs); $r .= '<input type="hidden" id="context-filter" value="' . $keys[0] . '" />'; } } $r .= '<label for="select-filter">' . lang::get('Filter:') . '</label><select id="select-filter"><option value="" selected="selected">' . lang::get('Select filter') . "...</option>{$existing}</select>"; $r .= '<button type="button" id="filter-apply">' . lang::get('Apply') . '</button>'; $r .= '<button type="button" id="filter-reset" class="disabled">' . lang::get('Reset') . '</button>'; $r .= '<button type="button" id="filter-build">' . lang::get('Create a filter') . '</button></div>'; $r .= '</div>'; $r .= '<div id="filter-details" style="display: none">'; $r .= '<img src="' . data_entry_helper::$images_path . 'nuvola/close-22px.png" width="22" height="22" alt="Close filter builder" title="Close filter builder" class="button" id="filter-done"/>' . "\n"; } else { $r .= '<div id="filter-details">'; if (!empty($options['filter_id'])) { $r .= "<input type=\"hidden\" id=\"select-filter\" value=\"{$options['filter_id']}\"/>"; } elseif (!empty($options['filters_user_id'])) { $r .= "<input type=\"hidden\" id=\"select-filters-user\" value=\"{$options['filters_user_id']}\"/>"; } } $r .= '<div id="filter-panes">'; if ($options['entity'] === 'occurrence') { $filters = array('filter_what' => new filter_what(), 'filter_where' => new filter_where(), 'filter_when' => new filter_when(), 'filter_who' => new filter_who(), 'filter_occurrence_id' => new filter_occurrence_id(), 'filter_quality' => new filter_quality(), 'filter_source' => new filter_source()); } elseif ($options['entity'] === 'sample') { $filters = array('filter_where' => new filter_where(), 'filter_when' => new filter_when(), 'filter_who' => new filter_who(), 'filter_sample_id' => new filter_sample_id(), 'filter_quality' => new filter_quality_sample(), 'filter_source' => new filter_source()); } if (!empty($options['filterTypes'])) { $filterModules = array(); foreach ($options['filterTypes'] as $category => $list) { // $list can be an array or comma separated list if (is_array($list)) { $list = implode(',', $list); } $paneNames = 'filter_' . str_replace(',', ',filter_', $list); $paneList = explode(',', $paneNames); $filterModules[$category] = array_intersect_key($filters, array_fill_keys($paneList, 1)); } } else { $filterModules = array('' => $filters); } foreach ($filterModules as $category => $list) { if ($category) { $r .= '<fieldset class="collapsible collapsed">' . '<legend>' . '<span class="fieldset-legend">' . $category . '</span>' . '</legend>' . '<div class="fieldset-wrapper">'; } foreach ($list as $moduleName => $module) { $r .= "<div class=\"pane\" id=\"pane-{$moduleName}\"><a class=\"fb-filter-link\" href=\"#controls-{$moduleName}\"><span class=\"pane-title\">" . $module->get_title() . '</span>'; $r .= '<span class="filter-desc"></span></a>'; $r .= "</div>"; } if ($category) { $r .= '</div></fieldset>'; } } $r .= '</div>'; // filter panes $r .= '<div class="toolbar">'; if ($options['allowSave']) { $r .= '<label for="filter:title">' . lang::get('Save filter as') . ':</label> <input id="filter:title" class="control-width-5"/>'; if ($options['admin']) { $r .= '<br/>'; if (empty($options['adminCanSetSharingTo'])) { throw new exception('Report standard params panel in admin mode so adminCanSetSharingTo option must be populated.'); } $r .= data_entry_helper::autocomplete(array('label' => 'For who?', 'fieldname' => 'filters_user:user_id', 'table' => 'user', 'valueField' => 'id', 'captionField' => 'person_name', 'formatFunction' => "function(item) { return item.person_name + ' (' + item.email_address + ')'; }", 'extraParams' => $readAuth + array('view' => 'detail'), 'class' => 'control-width-5')); $r .= data_entry_helper::textarea(array('label' => 'Description', 'fieldname' => 'filter:description')); } $r .= '<img src="' . data_entry_helper::$images_path . 'nuvola/save-22px.png" width="22" height="22" alt="Save filter" title="Save filter" class="button" id="filter-save"/>'; $r .= '<img src="' . data_entry_helper::$images_path . 'trash-22px.png" width="22" height="22" alt="Bin this filter" title="Bin this filter" class="button disabled" id="filter-delete"/>'; } $r .= '</div></div>'; // toolbar + clearfix if (!empty($options['filters_user_id'])) { // if we are preloading based on a filter user ID, we need to get the information now so that the sharing mode can be known // when loading controls $fu = data_entry_helper::get_population_data(array('table' => 'filters_user', 'extraParams' => $readAuth + array('id' => $options['filters_user_id']), 'caching' => false)); if (count($fu) !== 1) { throw new exception('Could not find filter user record'); } $options['sharing'] = report_filters_sharing_code_to_full_term($fu[0]['filter_sharing']); } report_helper::$javascript .= "indiciaData.lang={pleaseSelect:\"" . lang::get('Please select') . "\"};\n"; // create the hidden panels required to populate the popups for setting each type of filter up. $hiddenStuff = ''; foreach ($filterModules as $category => $list) { foreach ($list as $moduleName => $module) { $hiddenStuff .= "<div style=\"display: none\"><div class=\"filter-popup\" id=\"controls-{$moduleName}\"><form action=\"#\" class=\"filter-controls\"><fieldset>" . $module->get_controls($readAuth, $options) . '<button class="fb-close" type="button">Cancel</button>' . '<button class="fb-apply" type="submit">Apply</button></fieldset></form></div></div>'; $shortName = str_replace('filter_', '', $moduleName); report_helper::$javascript .= "indiciaData.lang.NoDescription{$shortName}='" . lang::get('Click to Filter ' . ucfirst($shortName)) . "';\n"; } } $r .= '</div>'; report_helper::$js_read_tokens = $readAuth; report_helper::$javascript .= "indiciaData.lang.CreateAFilter='" . lang::get('Create a filter') . "';\n"; report_helper::$javascript .= "indiciaData.lang.ModifyFilter='" . lang::get('Modify filter') . "';\n"; report_helper::$javascript .= "indiciaData.lang.FilterReport='" . lang::get('New report') . "';\n"; report_helper::$javascript .= "indiciaData.lang.FilterSaved='" . lang::get('The filter has been saved') . "';\n"; report_helper::$javascript .= "indiciaData.lang.FilterDeleted='" . lang::get('The filter has been deleted') . "';\n"; report_helper::$javascript .= "indiciaData.lang.ConfirmFilterChangedLoad='" . lang::get('Do you want to load the selected filter and lose your current changes?') . "';\n"; report_helper::$javascript .= "indiciaData.lang.FilterExistsOverwrite='" . lang::get('A filter with that name already exists. Would you like to overwrite it?') . "';\n"; report_helper::$javascript .= "indiciaData.lang.AutochecksFailed='" . lang::get('Automated checks failed') . "';\n"; report_helper::$javascript .= "indiciaData.lang.AutochecksPassed='" . lang::get('Automated checks passed') . "';\n"; report_helper::$javascript .= "indiciaData.lang.HasPhotos='" . lang::get('Records which have photos') . "';\n"; report_helper::$javascript .= "indiciaData.lang.ConfirmFilterDelete='" . lang::get('Are you sure you want to permanently delete the {title} filter?') . "';\n"; report_helper::$javascript .= "indiciaData.lang.MyRecords='" . lang::get('My records only') . "';\n"; if (function_exists('iform_ajaxproxy_url')) { report_helper::$javascript .= "indiciaData.filterPostUrl='" . iform_ajaxproxy_url(null, 'filter') . "';\n"; report_helper::$javascript .= "indiciaData.filterAndUserPostUrl='" . iform_ajaxproxy_url(null, 'filter_and_user') . "';\n"; } report_helper::$javascript .= "indiciaData.filterSharing='" . strtoupper(substr($options['sharing'], 0, 1)) . "';\n"; if (function_exists('hostsite_get_user_field')) { report_helper::$javascript .= "indiciaData.user_id='" . hostsite_get_user_field('indicia_user_id') . "';\n"; } else { report_helper::$javascript .= "indiciaData.user_id='" . $_SESSION['auth_user']->id . "';\n"; } if (!empty($website_id)) { report_helper::$javascript .= "indiciaData.website_id=" . $website_id . ";\n"; } report_helper::$javascript .= "indiciaData.redirectOnSuccess='{$options['redirect_on_success']}';\n"; // load up the filter, BEFORE any AJAX load of the grid code. First fetch any URL param overrides. $getParams = array(); $optionParams = array(); foreach ($_GET as $key => $value) { if (substr($key, 0, 7) === 'filter-') { $getParams[substr($key, 7)] = $value; } } foreach ($options as $key => $value) { if (substr($key, 0, 7) === 'filter-') { $optionParams[substr($key, 7)] = $value; } } $allParams = array_merge($optionParams, $getParams); if (!empty($allParams)) { $allParams = json_encode($allParams); report_helper::$onload_javascript .= "var params = {$allParams};\n"; report_helper::$onload_javascript .= "indiciaData.filter.def=\$.extend(indiciaData.filter.def, params);\n"; report_helper::$onload_javascript .= "indiciaData.filter.orig=\$.extend({}, params);\n"; } $getParams = empty($getParams) ? '{}' : json_encode($getParams); if (!empty($options['filters_user_id'])) { report_helper::$onload_javascript .= "loadFilterUser(" . json_encode($fu[0]) . ", {$getParams});\n"; } else { report_helper::$onload_javascript .= "if (\$('#select-filter').val()) {\n" . " loadFilter(\$('#select-filter').val(), {$getParams});\n" . "} else {\n" . " applyFilterToReports(false);\n" . "}\n"; } return $r; }
echo data_entry_helper::loading_block_start(); ?> <form method="post" enctype="multipart/form-data"> <?php // Get authorisation tokens to update and read from the Warehouse. $auth = data_entry_helper::get_read_write_auth($config['website_id'], $config['password']); echo $auth['write']; $readAuth = $auth['read']; ?> <input type='hidden' id='website_id' name='website_id' value='<?php echo $config['website_id']; ?> ' /> <input type='hidden' id='record_status' name='record_status' value='C' /> <?php echo data_entry_helper::autocomplete(array('label' => 'Species', 'fieldname' => 'occurrence:taxa_taxon_list_id', 'table' => 'taxa_taxon_list', 'captionField' => 'taxon', 'valueField' => 'id', 'extraParams' => $readAuth + array('taxon_list_id' => $config['species_checklist_taxon_list']))); echo data_entry_helper::date_picker(array('label' => 'Date', 'fieldname' => 'sample:date')); echo data_entry_helper::file_box(array('caption' => 'Upload your photos', 'resizeWidth' => 1024, 'resizeHeight' => 768, 'table' => 'occurrence_image', 'runtimes' => array('html4'))); echo data_entry_helper::sref_and_system(array('label' => 'Grid ref')); echo data_entry_helper::select(array('label' => 'Survey', 'fieldname' => 'sample:survey_id', 'table' => 'survey', 'captionField' => 'title', 'valueField' => 'id', 'extraParams' => $readAuth)); echo data_entry_helper::textarea(array('label' => 'Comment', 'fieldname' => 'sample:comment', 'class' => 'wide')); ?> <input type="submit" class="ui-state-default ui-corner-all" value="Save" /> </form> <?php echo data_entry_helper::loading_block_end(); echo data_entry_helper::dump_remaining_errors(); echo data_entry_helper::dump_javascript(); ?> </div>
alert(data); } else { // if OK, it returns the new record ID. Add it to the grid, using the global var created // when the grid was created. indiciaData.reports.termlists_term.grid_termlists_term.addRecords('id', data); } } ); }; /*]]>*/ </script> <?php require_once DOCROOT . 'client_helpers/data_entry_helper.php'; $readAuth = data_entry_helper::get_read_auth(0 - $_SESSION['auth_user']->id, kohana::config('indicia.private_key')); echo '<div class="linear-form">'; echo data_entry_helper::autocomplete(array('label' => 'Add term', 'fieldname' => 'add-from-parent', 'helpText' => 'Search for terms in the parent list to quickly add them into this list.', 'table' => 'termlists_term', 'captionField' => 'term', 'valueField' => 'id', 'extraParams' => $readAuth + array('termlist_id' => $parent_list_id), 'afterControl' => '<input type="button" value="Add" onclick="add_parent_term();" />')); echo '</div>'; } echo $grid; ?> <br/> <form action="<?php echo url::site() . 'termlists_term/create/' . $termlist_id; ?> " method="post"> <?php if (isset($parent_id)) { ?> <input type="hidden" value="<?php echo $parent_id; ?>
echo data_entry_helper::text_input(array('label' => 'Name', 'fieldname' => 'location:name', 'default' => html::initial_value($values, 'location:name'), 'validation' => 'required', 'disabled' => $disabled)); echo data_entry_helper::text_input(array('label' => 'Code', 'fieldname' => 'location:code', 'default' => html::initial_value($values, 'location:code'), 'disabled' => $disabled)); echo data_entry_helper::select(array('label' => 'Type', 'fieldname' => 'location:location_type_id', 'default' => html::initial_value($values, 'location:location_type_id'), 'lookupValues' => $other_data['type_terms'], 'blankText' => '<Please select>', 'disabled' => $disabled)); echo data_entry_helper::textarea(array('label' => 'Comment', 'fieldname' => 'location:comment', 'default' => html::initial_value($values, 'location:comment'), 'disabled' => $disabled)); echo data_entry_helper::sref_and_system(array('label' => 'Spatial Ref', 'fieldname' => 'location:centroid_sref', 'geomFieldname' => 'location:centroid_geom', 'default' => html::initial_value($values, 'location:centroid_sref'), 'defaultGeom' => html::initial_value($values, 'location:centroid_geom'), 'systems' => spatial_ref::system_list(), 'defaultSystem' => html::initial_value($values, 'location:centroid_sref_system'), 'class' => 'control-width-3', 'validation' => 'required', 'disabled' => $disabled)); ?> <input type="hidden" name="location:boundary_geom" id="imp-boundary-geom" value="<?php echo $boundary_geom; ?> "/> <p class="instruct">Zoom the map in by double-clicking then single click on the location's centre to set the spatial reference. The more you zoom in, the more accurate the reference will be.</p> <?php $readAuth = data_entry_helper::get_read_auth(0 - $_SESSION['auth_user']->id, kohana::config('indicia.private_key')); echo map_helper::map_panel(array('readAuth' => $readAuth, 'presetLayers' => array('osm'), 'editLayer' => true, 'layers' => array(), 'initial_lat' => 52, 'initial_long' => -2, 'initial_zoom' => 7, 'width' => 870, 'height' => 400, 'initialFeatureWkt' => $centroid_geom, 'standardControls' => $disabled_input === 'YES' ? array('layerSwitcher', 'panZoomBar') : array('layerSwitcher', 'panZoomBar', 'drawPolygon', 'drawLine', 'modifyFeature'), 'allowPolygonRecording' => true)); echo data_entry_helper::autocomplete(array('label' => 'Parent location', 'fieldname' => 'location:parent_id', 'table' => 'location', 'captionField' => 'name', 'valueField' => 'id', 'extraParams' => $readAuth, 'default' => html::initial_value($values, 'location:parent_id'), 'defaultCaption' => html::initial_value($values, 'parent:name'), 'disabled' => $disabled)); if ($this->auth->logged_in('CoreAdmin')) { //Only core admin can create public locations. echo data_entry_helper::checkbox(array('label' => 'Available to all websites', 'fieldname' => 'location:public', 'default' => html::initial_value($values, 'location:public'), 'disabled' => $disabled)); } ?> </fieldset> </div> <?php if (is_null($id) || $this->auth->logged_in('CoreAdmin') || $values['location:public'] === 'f') { //No need to display for public locations unless core admin. ?> <div id="websites"> <fieldset>
/** * Return the generated form output. * @return Form HTML. */ public static function get_form($args, $node, $response = null) { global $user; global $custom_terms; $logged_in = $user->uid > 0; $r = ''; // Get authorisation tokens to update and read from the Warehouse. $writeAuth = data_entry_helper::get_auth($args['website_id'], $args['password']); $readAuth = data_entry_helper::get_read_auth($args['website_id'], $args['password']); $svcUrl = data_entry_helper::$base_url . '/index.php/services'; $presetLayers = array(); // read out the activated preset layers if (isset($args['preset_layers'])) { foreach ($args['preset_layers'] as $layer => $active) { if ($active !== 0) { $presetLayers[] = $layer; } } } drupal_add_js(drupal_get_path('module', 'iform') . '/media/js/jquery.form.js', 'module'); data_entry_helper::link_default_stylesheet(); data_entry_helper::add_resource('jquery_ui'); if ($args['language'] != 'en') { data_entry_helper::add_resource('jquery_ui_' . $args['language']); } // If not logged in: Display an information message. // This form should only be called in POST mode when setting the location allocation. // All other posting is now done via AJAX. // When invoked by GET there are the following modes: // No additional arguments: mode 0. // Additional argument - newSample: mode 1. // Additional argument - sample_id=<id>: mode 2. // Additional argument - occurrence_id=<id>: mode 3. $mode = 0; // default mode : output survey selector // mode 1: output the main Data Entry page: occurrence list or add/edit occurrence tabs hidden. "Survey" tab active // mode 2: output the main Data Entry page, display existing sample. Active tab determined by iform params. No occurence details filled in. // mode 3: output the main Data Entry page, display existing occurrence. "Edit Occurrence" tab active. Occurence details filled in. $surveyReadOnly = false; // On top of this, things can be flagged as readonly. RO mode 2+4 means no Add Occurrence tab. if (!$logged_in) { return lang::get('LANG_not_logged_in'); } $parentSample = array(); $parentLoadID = null; $childSample = array(); $childLoadID = null; $thisOccID = -1; // IDs have to be >0, so this is outside the valid range 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('mnhnlbtw', $_POST)) { iform_loctools_deletelocations($node); foreach ($_POST as $key => $value) { $parts = explode(':', $key); if ($parts[0] == 'location' && $value) { iform_loctools_insertlocation($node, $value, $parts[1]); } } } } } else { if (array_key_exists('sample_id', $_GET)) { $mode = 2; $parentLoadID = $_GET['sample_id']; } else { if (array_key_exists('occurrence_id', $_GET)) { $mode = 3; $childLoadID = $_GET['occurrence_id']; $thisOccID = $childLoadID; } else { if (array_key_exists('newSample', $_GET)) { $mode = 1; } } } // else default to mode 0 } // define language strings so they can be used for validation translation. data_entry_helper::$javascript .= "var translations = [\n"; foreach ($custom_terms as $key => $value) { if (substr($key, 0, 4) != "LANG") { data_entry_helper::$javascript .= " {key: \"" . $key . "\", translated: \"" . $value . "\"},\n"; } } data_entry_helper::$javascript .= "];\n"; // define layers for all maps. // each argument is a comma separated list eg: // "Name:Lux Outline,URL:http://localhost/geoserver/wms,LAYERS:indicia:nation2,SRS:EPSG:2169,FORMAT:image/png,minScale:0,maxScale:1000000,units:m"; $optionArray_1 = array(); $optionArray_2 = array(); $optionArray_Location = array(); $options = explode(',', $args['layer1']); foreach ($options as $option) { $parts = explode(':', $option); $optionName = $parts[0]; unset($parts[0]); $optionsArray_1[$optionName] = implode(':', $parts); } $options = explode(',', $args['layer2']); foreach ($options as $option) { $parts = explode(':', $option); $optionName = $parts[0]; unset($parts[0]); $optionsArray_2[$optionName] = implode(':', $parts); } $options = explode(',', $args['locationLayer']); foreach ($options as $option) { $parts = explode(':', $option); $optionName = $parts[0]; unset($parts[0]); $optionsArray_Location[$optionName] = implode(':', $parts); } // Work out list of locations this user can see. $locations = iform_loctools_listlocations($node); if ($locations != 'all') { data_entry_helper::$javascript .= "locationList = [" . implode(',', $locations) . "];\n"; } data_entry_helper::$javascript .= "\n// Create Layers.\n// Base Layers first.\nvar WMSoptions = {\n LAYERS: '" . $optionsArray_1['LAYERS'] . "',\n SERVICE: 'WMS',\n VERSION: '1.1.0',\n STYLES: '',\n SRS: '" . $optionsArray_1['SRS'] . "',\n FORMAT: '" . $optionsArray_1['FORMAT'] . "'\n };\nbaseLayer_1 = new OpenLayers.Layer.WMS('" . $optionsArray_1['Name'] . "',\n '" . iform_proxy_url($optionsArray_1['URL']) . "',\n WMSoptions, {\n minScale: " . $optionsArray_1['minScale'] . ",\n maxScale: " . $optionsArray_1['maxScale'] . ",\n units: '" . $optionsArray_1['units'] . "',\n isBaseLayer: true,\n singleTile: true\n });\nWMSoptions = {\n LAYERS: '" . $optionsArray_2['LAYERS'] . "',\n SERVICE: 'WMS',\n VERSION: '1.1.0',\n STYLES: '',\n SRS: '" . $optionsArray_2['SRS'] . "',\n FORMAT: '" . $optionsArray_2['FORMAT'] . "'\n };\nbaseLayer_2 = new OpenLayers.Layer.WMS('" . $optionsArray_2['Name'] . "',\n '" . iform_proxy_url($optionsArray_2['URL']) . "',\n WMSoptions, {\n minScale: " . $optionsArray_2['minScale'] . ",\n maxScale: " . $optionsArray_2['maxScale'] . ",\n units: '" . $optionsArray_2['units'] . "',\n isBaseLayer: true,\n singleTile: true\n });\nWMSoptions = {\n SERVICE: 'WMS',\n VERSION: '1.1.0',\n STYLES: '',\n SRS: '" . $optionsArray_Location['SRS'] . "',\n FORMAT: '" . $optionsArray_Location['FORMAT'] . "',\n TRANSPARENT: 'true', "; if ($locations != 'all') { // when given a restricted feature list we have to use the feature id to filter in order to not go over 2000 char limit on the URL // Can only generate the feature id if we access a table directly, not through a view. Go direct to the locations table. // don't need to worry about parent_id in this case as we know exactly which features we want. // need to use btw_transects view for unrestricted so we can filter by parent_id. $locFeatures = array(); foreach ($locations as $location) { $locFeatures[] = "locations." . $location; } data_entry_helper::$javascript .= "\n LAYERS: 'indicia:locations',\n FEATUREID: '" . implode(',', $locFeatures) . "'"; } else { data_entry_helper::$javascript .= "\n LAYERS: '" . $optionsArray_Location['LAYERS'] . "'"; } data_entry_helper::$javascript .= "\n };\nlocationListLayer = new OpenLayers.Layer.WMS('" . $optionArray_Location['Name'] . "',\n '" . iform_proxy_url($optionsArray_Location['URL']) . "',\n WMSoptions, {\n minScale: " . $optionsArray_Location['minScale'] . ",\n maxScale: " . $optionsArray_Location['maxScale'] . ",\n units: '" . $optionsArray_Location['units'] . "',\n isBaseLayer: false,\n singleTile: true\n });\n// Create vector layers: one to display the location onto, and another for the occurrence list\n// the default edit layer is used for the occurrences themselves\nlocStyleMap = new OpenLayers.StyleMap({\n \"default\": new OpenLayers.Style({\n fillColor: \"Green\",\n strokeColor: \"Black\",\n fillOpacity: 0.2,\n strokeWidth: 1\n })\n });\nlocationLayer = new OpenLayers.Layer.Vector(\"" . lang::get("LANG_Location_Layer") . "\",\n {styleMap: locStyleMap});\noccStyleMap = new OpenLayers.StyleMap({\n \"default\": new OpenLayers.Style({\n pointRadius: 3,\n fillColor: \"Red\",\n fillOpacity: 0.3,\n strokeColor: \"Red\",\n strokeWidth: 1\n }) });\noccListLayer = new OpenLayers.Layer.Vector(\"" . lang::get("LANG_Occurrence_List_Layer") . "\",\n {styleMap: occStyleMap});\n"; drupal_add_js(drupal_get_path('module', 'iform') . '/media/js/hasharray.js', 'module'); drupal_add_js(drupal_get_path('module', 'iform') . '/media/js/jquery.datagrid.js', 'module'); // Work out list of locations this user can see. $locations = iform_loctools_listlocations($node); /////////////////////////////////////////////////////////////////// // default mode 0 : display a page with tabs for survey selector, // locations allocator and reports (last two require permissions) /////////////////////////////////////////////////////////////////// if ($mode == 0) { // If the user has permissions, add tabs so can choose to see // locations allocator $tabs = array('#surveyList' => lang::get('LANG_Surveys')); if (iform_loctools_checkaccess($node, 'admin')) { $tabs['#setLocations'] = lang::get('LANG_Allocate_Locations'); } if (iform_loctools_checkaccess($node, 'superuser')) { $tabs['#downloads'] = lang::get('LANG_Download'); } if (count($tabs) > 1) { $r .= "<div id=\"controls\">" . data_entry_helper::enable_tabs(array('divId' => 'controls', 'active' => '#surveyList')) . "<div id=\"temp\"></div>"; $r .= data_entry_helper::tab_header(array('tabs' => $tabs)); } if ($locations == 'all') { $useloclist = 'NO'; $loclist = '-1'; } else { // an empty list will cause an sql error, lids must be > 0, so push a -1 to prevent the error. if (empty($locations)) { $locations[] = -1; } $useloclist = 'YES'; $loclist = implode(',', $locations); } // Create the Survey list datagrid for this user. drupal_add_js("jQuery(document).ready(function(){\n \$('div#smp_grid').indiciaDataGrid('rpt:mnhnl_btw_list_samples', {\n indiciaSvc: '" . $svcUrl . "',\n dataColumns: ['location_name', 'date', 'num_visit', 'num_occurrences', 'num_taxa'],\n reportColumnTitles: {location_name : '" . lang::get('LANG_Transect') . "', date : '" . lang::get('LANG_Date') . "', num_visit : '" . lang::get('LANG_Visit_No') . "', num_occurrences : '" . lang::get('LANG_Num_Occurrences') . "', num_taxa : '" . lang::get('LANG_Num_Species') . "'},\n actionColumns: {" . lang::get('LANG_Show') . " : \"" . url('node/' . $node->nid, array('query' => 'sample_id=£id£')) . "\"},\n auth : { nonce : '" . $readAuth['nonce'] . "', auth_token : '" . $readAuth['auth_token'] . "'},\n parameters : { survey_id : '" . $args['survey_id'] . "', visit_attr_id : '" . $args['sample_visit_number_id'] . "', closed_attr_id : '" . $args['sample_closure_id'] . "', use_location_list : '" . $useloclist . "', locations : '" . $loclist . "'},\n itemsPerPage : 12,\n condCss : {field : 'closed', value : '0', css: 'mnhnl-btw-highlight'},\n cssOdd : ''\n });\n});\n ", 'inline'); $r .= ' <div id="surveyList" class="mnhnl-btw-datapanel"><div id="smp_grid"></div> <form><input type="button" value="' . lang::get('LANG_Add_Survey') . '" onclick="window.location.href=\'' . url('node/' . $node->nid, array('query' => 'newSample')) . '\'"></form></div>'; // Add the locations allocator if user has admin rights. if (iform_loctools_checkaccess($node, 'admin')) { $r .= ' <div id="setLocations" class="mnhnl-btw-datapanel"> <form method="post"> <input type="hidden" id="mnhnlbtw" name="mnhnlbtw" value="mnhnlbtw" />\\n'; $url = $svcUrl . '/data/location?mode=json&view=detail&auth_token=' . $readAuth['auth_token'] . "&nonce=" . $readAuth["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); if (!empty($entities)) { foreach ($entities as $entity) { if (!$entity["parent_id"]) { // only assign parent locations. $r .= "\n<label for=\"location:" . $entity["id"] . "\">" . $entity["name"] . ":</label><select id=\"location:" . $entity["id"] . "\" name=\"location:" . $entity["id"] . "\"><option value=\"\" ><" . lang::get('LANG_Not_Allocated') . "></option>"; $defaultuserid = iform_loctools_getuser($node, $entity["id"]); foreach ($userlist as $uid => $a_user) { $r .= "<option value=\"" . $uid . "\" " . ($uid == $defaultuserid ? 'selected="selected" ' : '') . ">" . $a_user->name . "</option>"; } $r .= "</select>"; } } } $r .= "\n <input type=\"submit\" class=\"ui-state-default ui-corner-all\" value=\"" . lang::get('LANG_Save_Location_Allocations') . "\" />\n </form>\n </div>"; } // Add the downloader if user has manager (superuser) rights. if (iform_loctools_checkaccess($node, 'superuser')) { $r .= ' <div id="downloads" class="mnhnl-btw-datapanel"> <form method="post" action="' . data_entry_helper::$base_url . '/index.php/services/report/requestReport?report=mnhnl_btw_transect_direction_report.xml&reportSource=local&auth_token=' . $readAuth['auth_token'] . '&nonce=' . $readAuth['nonce'] . '&mode=csv"> <p>' . lang::get('LANG_Direction_Report') . '</p> <input type="hidden" id="params" name="params" value=\'{"survey_id":' . $args['survey_id'] . ', "direction_attr_id":' . $args['sample_walk_direction_id'] . ', "closed_attr_id":' . $args['sample_closure_id'] . '}\' /> <input type="submit" class="ui-state-default ui-corner-all" value="' . lang::get('LANG_Direction_Report_Button') . '"> </form> <form method="post" action="' . data_entry_helper::$base_url . '/index.php/services/report/requestReport?report=mnhnl_btw_download_report.xml&reportSource=local&auth_token=' . $readAuth['auth_token'] . '&nonce=' . $readAuth['nonce'] . '&mode=csv\\"> <p>' . lang::get('LANG_Initial_Download') . '</p> <input type="hidden" id="params" name="params" value=\'{"survey_id":' . $args['survey_id'] . ', "closed_attr_id":' . $args['sample_closure_id'] . ', "download": "INITIAL"}\' /> <input type="submit" class=\\"ui-state-default ui-corner-all" value="' . lang::get('LANG_Initial_Download_Button') . '"> </form> <form method="post" action="' . data_entry_helper::$base_url . '/index.php/services/report/requestReport?report=mnhnl_btw_download_report.xml&reportSource=local&auth_token=' . $readAuth['auth_token'] . '&nonce=' . $readAuth['nonce'] . '&mode=csv\\"> <p>' . lang::get('LANG_Confirm_Download') . '</p> <input type="hidden" id="params" name="params" value=\'{"survey_id":' . $args['survey_id'] . ', "closed_attr_id":' . $args['sample_closure_id'] . ', "download": "CONFIRM"}\' /> <input type="submit" class="ui-state-default ui-corner-all" value="' . lang::get('LANG_Confirm_Download_Button') . '"> </form> <form method="post" action="' . data_entry_helper::$base_url . '/index.php/services/report/requestReport?report=mnhnl_btw_download_report.xml&reportSource=local&auth_token=' . $readAuth['auth_token'] . '&nonce=' . $readAuth['nonce'] . '&mode=csv\\"> <p>' . lang::get('LANG_Final_Download') . '</p> <input type="hidden" id="params" name="params" value=\'{"survey_id":' . $args['survey_id'] . ', "closed_attr_id":' . $args['sample_closure_id'] . ', "download": "FINAL"}\' /> <input type="submit" class="ui-state-default ui-corner-all" value="' . lang::get('LANG_Final_Download_Button') . '"> </form> </div>'; } // Create Map $r .= "<div class=\"mnhnl-btw-mappanel\">\n" . data_entry_helper::map_panel(array('presetLayers' => $presetLayers, 'layers' => array('baseLayer_1', 'baseLayer_2', 'locationListLayer'), 'initialFeatureWkt' => null, 'width' => 'auto', 'height' => 490, 'editLayer' => false, 'initial_lat' => $args['map_centroid_lat'], 'initial_long' => $args['map_centroid_long'], 'initial_zoom' => (int) $args['map_zoom'], 'scroll_wheel_zoom' => false), array('projection' => $args['map_projection'])) . "</div>\n"; data_entry_helper::$javascript .= "\n\$('#controls').bind('tabsshow', function(event, ui) {\n var y = \$('.mnhnl-btw-datapanel:visible').outerHeight(true) + \$('.mnhnl-btw-datapanel:visible').position().top;\n if(y < \$('.mnhnl-btw-mappanel').outerHeight(true)+ \$('.mnhnl-btw-mappanel').position().top){\n y = \$('.mnhnl-btw-mappanel').outerHeight(true)+ \$('.mnhnl-btw-mappanel').position().top;\n }\n \$('#controls').height(y - \$('#controls').position().top);\n});\n"; if (count($tabs) > 1) { // close tabs div if present $r .= "</div>"; } return $r; } /////////////////////////////////////////////////////////////////// $occReadOnly = false; if ($childLoadID) { // load the occurrence and its associated sample (which holds the position) $url = $svcUrl . '/data/occurrence/' . $childLoadID; $url .= "?mode=json&view=detail&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"]; $session = curl_init($url); curl_setopt($session, CURLOPT_RETURNTRANSFER, true); $entity = json_decode(curl_exec($session), true); $childSample = array(); foreach ($entity[0] as $key => $value) { $childSample['occurrence:' . $key] = $value; } if ($entity[0]['downloaded_flag'] == 'F') { // Final download complete, now readonly $occReadOnly = true; } $url = $svcUrl . '/data/sample/' . $childSample['occurrence:sample_id']; $url .= "?mode=json&view=detail&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"]; $session = curl_init($url); curl_setopt($session, CURLOPT_RETURNTRANSFER, true); $entity = json_decode(curl_exec($session), true); foreach ($entity[0] as $key => $value) { $childSample['sample:' . $key] = $value; } $childSample['sample:geom'] = ''; // value received from db is not WKT, which is assumed by all the code. $thisOccID = $childLoadID; // this will be used to load the occurrence into the editlayer. $childSample['taxon'] = $childSample['occurrence:taxon']; $parentLoadID = $childSample['sample:parent_id']; } if ($parentLoadID) { // load the container master sample $url = $svcUrl . '/data/sample/' . $parentLoadID; $url .= "?mode=json&view=detail&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"]; $session = curl_init($url); curl_setopt($session, CURLOPT_RETURNTRANSFER, true); $entity = json_decode(curl_exec($session), true); $parentSample = array(); foreach ($entity[0] as $key => $value) { $parentSample['sample:' . $key] = $value; } if (is_array($locations) && !in_array($entity[0]["location_id"], $locations)) { return '<p>' . lang::get('LANG_No_Access_To_Location') . '</p>'; } if ($entity[0]["parent_id"]) { return '<p>' . lang::get('LANG_No_Access_To_Sample') . '</p>'; } $parentSample['sample:date'] = $parentSample['sample:date_start']; // bit of a bodge // default values for attributes from DB are picked up automatically. } $childSample['sample:date'] = $parentSample['sample:date']; // enforce a match between child and parent sample dates data_entry_helper::$entity_to_load = $parentSample; $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' => $readAuth)); $closedFieldName = $attributes[$args['sample_closure_id']]['fieldname']; $closedFieldValue = data_entry_helper::check_default_value($closedFieldName, array_key_exists('default', $attributes[$args['sample_closure_id']]) ? $attributes[$args['sample_closure_id']]['default'] : '0'); // default is not closed $adminPerm = 'IForm node ' . $node->nid . ' admin'; if ($closedFieldValue == '1' && !user_access($adminPerm)) { // sample has been closed, no admin perms. Everything now set to read only. $surveyReadOnly = true; $disabledText = "disabled=\"disabled\""; $defAttrOptions = array('extraParams' => $readAuth, 'disabled' => $disabledText); } else { // sample open. $disabledText = ""; $defAttrOptions = array('extraParams' => $readAuth); } // with the AJAX code, we deal with the validation semi manually: Form name is meant be invalid as we only want code included. data_entry_helper::enable_validation('DummyForm'); $r .= "<div id=\"controls\">\n"; $activeTab = 'survey'; // mode 1 = new Sample, display sample. if ($mode == 2) { // have specified a sample ID if ($args["on_edit_survey_nav"] == "survey") { $activeTab = 'survey'; } else { if ($surveyReadOnly || $args["on_edit_survey_nav"] == "list") { $activeTab = 'occurrenceList'; } else { $activeTab = 'occurrence'; } } if ($surveyReadOnly) { data_entry_helper::$javascript .= "jQuery('#occ-form').hide();"; } } else { if ($mode == 3) { // have specified an occurrence ID $activeTab = 'occurrence'; } } // Set Up form tabs. $r .= data_entry_helper::enable_tabs(array('divId' => 'controls', 'active' => $activeTab)); $r .= "<div id=\"temp\"></div>"; $r .= data_entry_helper::tab_header(array('tabs' => array('#survey' => lang::get('LANG_Survey'), '#occurrence' => lang::get($surveyReadOnly || $occReadOnly ? 'LANG_Show_Occurrence' : (isset($childSample['sample:id']) ? 'LANG_Edit_Occurrence' : 'LANG_Add_Occurrence')), '#occurrenceList' => lang::get('LANG_Occurrence_List')))); // Set up main Survey Form. $r .= "<div id=\"survey\" class=\"mnhnl-btw-datapanel\">\n <p id=\"read-only-survey\"><strong>" . lang::get('LANG_Read_Only_Survey') . "</strong></p>\n <form id=\"SurveyForm\" action=\"" . iform_ajaxproxy_url($node, 'sample') . "\" method=\"post\">\n <input type=\"hidden\" id=\"website_id\" name=\"website_id\" value=\"" . $args['website_id'] . "\" />\n <input type=\"hidden\" id=\"sample:survey_id\" name=\"sample:survey_id\" value=\"" . $args['survey_id'] . "\" />\n " . iform_user_get_hidden_inputs($args); if (array_key_exists('sample:id', data_entry_helper::$entity_to_load)) { $r .= "<input type=\"hidden\" id=\"sample:id\" name=\"sample:id\" value=\"" . data_entry_helper::$entity_to_load['sample:id'] . "\" />\n"; } else { $r .= "<input type=\"hidden\" id=\"sample:id\" name=\"sample:id\" value=\"\" disabled=\"disabled\" />\n"; } $defAttrOptions['validation'] = array('required'); $defAttrOptions['suffixTemplate'] = 'requiredsuffix'; if ($locations == 'all') { $locOptions = array_merge(array('label' => lang::get('LANG_Transect')), $defAttrOptions); $locOptions['extraParams'] = array_merge(array('parent_id' => 'NULL', 'view' => 'detail', 'orderby' => 'name'), $locOptions['extraParams']); $r .= data_entry_helper::location_select($locOptions); } else { // can't use location select due to location filtering. $r .= "<label for=\"imp-location\">" . lang::get('LANG_Transect') . ":</label>\n<select id=\"imp-location\" name=\"sample:location_id\" " . $disabled_text . " class=\" \" >"; $url = $svcUrl . '/data/location?mode=json&view=detail&parent_id=NULL&orderby=name&auth_token=' . $readAuth['auth_token'] . '&nonce=' . $readAuth["nonce"]; $session = curl_init($url); curl_setopt($session, CURLOPT_RETURNTRANSFER, true); $entities = json_decode(curl_exec($session), true); if (!empty($entities)) { foreach ($entities as $entity) { if (in_array($entity["id"], $locations)) { if ($entity["id"] == data_entry_helper::$entity_to_load['sample:location_id']) { $selected = 'selected="selected"'; } else { $selected = ''; } $r .= "<option value=\"" . $entity["id"] . "\" " . $selected . ">" . $entity["name"] . "</option>"; } } } $r .= "</select><span class=\"deh-required\">*</span><br />"; } $languageFilteredAttrOptions = $defAttrOptions + array('language' => iform_lang_iso_639_2($args['language'])); $r .= data_entry_helper::outputAttribute($attributes[$args['sample_walk_direction_id']], $languageFilteredAttrOptions) . data_entry_helper::outputAttribute($attributes[$args['sample_reliability_id']], $languageFilteredAttrOptions) . data_entry_helper::outputAttribute($attributes[$args['sample_visit_number_id']], array_merge($languageFilteredAttrOptions, array('default' => 1, 'noBlankText' => true))); if ($surveyReadOnly) { $r .= data_entry_helper::text_input(array_merge($defAttrOptions, array('label' => lang::get('LANG_Date'), 'fieldname' => 'sample:date', 'disabled' => $disabledText))); } else { $r .= data_entry_helper::date_picker(array('label' => lang::get('LANG_Date'), 'fieldname' => 'sample:date', 'class' => 'vague-date-picker', 'suffixTemplate' => 'requiredsuffix')); } $r .= data_entry_helper::outputAttribute($attributes[$args['sample_wind_id']], $languageFilteredAttrOptions) . data_entry_helper::outputAttribute($attributes[$args['sample_precipitation_id']], $languageFilteredAttrOptions) . data_entry_helper::outputAttribute($attributes[$args['sample_temperature_id']], array_merge($defAttrOptions, array('suffixTemplate' => 'nosuffix'))) . " degC<span class=\"deh-required\">*</span><br />" . data_entry_helper::outputAttribute($attributes[$args['sample_cloud_id']], $defAttrOptions) . data_entry_helper::outputAttribute($attributes[$args['sample_start_time_id']], array_merge($defAttrOptions, array('suffixTemplate' => 'nosuffix'))) . " hh:mm<span class=\"deh-required\">*</span><br />" . data_entry_helper::outputAttribute($attributes[$args['sample_end_time_id']], array_merge($defAttrOptions, array('suffixTemplate' => 'nosuffix'))) . " hh:mm<span class=\"deh-required\">*</span><br />"; unset($defAttrOptions['suffixTemplate']); unset($defAttrOptions['validation']); if (user_access($adminPerm)) { // users with admin permissions can override the closing of the // sample by unchecking the checkbox. // Because this is attached to the sample, we have to include the sample required fields in the // the post. This means they can't be disabled, so we enable all fields in this case. // Normal users can only set this to closed, and they do this using a button/hidden field. $r .= data_entry_helper::outputAttribute($attributes[$args['sample_closure_id']], $defAttrOptions); } else { // hidden closed $r .= "<input type=\"hidden\" id=\"" . $closedFieldName . "\" name=\"" . $closedFieldName . "\" value=\"" . $closedFieldValue . "\" />\n"; } $escaped_id = str_replace(':', '\\\\:', $closedFieldName); if (!$surveyReadOnly) { // NB that we don't even include the buttons when readonly. data_entry_helper::$javascript .= "\njQuery('#read-only-survey').hide();\njQuery('#ro-sur-occ-warn').hide();\n"; $r .= "<input type=button id=\"close1\" class=\"ui-state-default ui-corner-all \" value=\"" . lang::get('LANG_Save_Survey_Details') . "\";\n onclick=\"var result = \$('#SurveyForm input').valid();\n var result2 = \$('#SurveyForm select').valid();\n if (!result || !result2) {\n return;\n }\n jQuery('#close1').addClass('loading-button');\n jQuery('#SurveyForm').submit();\">\n"; if (!user_access($adminPerm)) { if ($mode != 1) { data_entry_helper::$javascript .= "jQuery('#close2').hide();\n"; } $r .= "<input type=button id=\"close2\" class=\"ui-state-default ui-corner-all \" value=\"" . lang::get('LANG_Save_Survey_And_Close') . "\"\n onclick=\"if(confirm('" . lang::get('LANG_Close_Survey_Confirm') . "')){\n var result = \$('#SurveyForm input').valid();\n var result2 = \$('#SurveyForm select').valid();\n if (!result || !result2) {\n return;\n }\n jQuery('#" . $escaped_id . "').val('1');\n jQuery('#close2').addClass('loading-button');\n jQuery('#SurveyForm').submit();\n };\">\n"; } } $r .= "</form></div>\n"; data_entry_helper::$javascript .= "\nalertIndiciaError = function(data){\n\tvar errorString = \"" . lang::get('LANG_Indicia_Warehouse_Error') . "\";\n\tif(data.error){\terrorString = errorString + ' : ' + data.error;\t}\n\tif(data.errors){\n\t\tfor (var i in data.errors){\n\t\t\terrorString = errorString + ' : ' + data.errors[i];\n\t\t}\t\t\t\t\n\t}\n\talert(errorString);\n\t// the most likely cause is authentication failure - eg the read authentication has timed out.\n\t// prevent further use of the form:\n\t\$('.loading-panel').remove();\n\t\$('.loading-hide').removeClass('loading-hide');\n};\nerrorPos = null;\nclearErrors = function(formSel) {\n\tjQuery(formSel).find('.inline-error').remove();\n\terrorPos = null;\n};\nmyScrollTo = function(selector){\n\tjQuery(selector).filter(':visible').each(function(){\n\t\tif(errorPos == null || jQuery(this).offset().top < errorPos){\n\t\t\terrorPos = jQuery(this).offset().top;\n\t\t\twindow.scroll(0,errorPos);\n\t\t}\n\t});\n};\nmyScrollToError = function(){\n\tjQuery('.inline-error,.error').filter(':visible').prev().each(function(){\n\t\tif(errorPos == null || jQuery(this).offset().top < errorPos){\n\t\t\terrorPos = jQuery(this).offset().top;\n\t\t\twindow.scroll(0,errorPos);\n\t\t}\n\t});\n};\njQuery('#SurveyForm').ajaxForm({ \n\tasync: false,\n\tdataType: 'json', \n beforeSubmit: function(data, obj, options){\n \tvar valid = true;\n \tclearErrors('form#SurveyForm');\n \tif (!jQuery('form#SurveyForm > input').valid()) {\n\t\t\tmyScrollToError();\n \t\t\tjQuery('.loading-button').removeClass('loading-button');\n\t\t\treturn false;\n \t\t};\n\t\treturn true;\n\t},\n success: function(data){\n // this will leave all the fields populated.\n \tif(data.success == 'multiple records' && data.outer_table == 'sample'){\n\t\t\twindow.scroll(0,0);\n jQuery('#SurveyForm > input[name=sample\\:id]').removeAttr('disabled').val(data.outer_id);\n jQuery('#occ-form > input[name=sample\\:parent_id]').val(data.outer_id);\n jQuery('#occ-form > input[name=sample\\:date]').val(jQuery('#SurveyForm > input[name=sample\\:date]').val());\n jQuery('#occ-form').show();\n jQuery('#na-occ-warn').hide();"; if (!user_access($adminPerm)) { data_entry_helper::$javascript .= "\n\t\t\tif(jQuery('#" . $escaped_id . "').val() == '1'){\n\t\t\t\tjQuery('#read-only-survey').show();\n\t\t\t\tjQuery('#close1').hide();\n\t\t\t\tjQuery('#close2').hide();\n\t\t\t};\n"; } data_entry_helper::$javascript .= "\n\t\t\tswitch(\"" . $args["on_save_survey_nav"] . "\"){\n\t\t\t\tcase \"list\":\n\t\t\t\t\tvar a = \$('ul.ui-tabs-nav a')[2];\n\t\t\t\t\t\$(a).click();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"survey\":\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tvar a = \$('ul.ui-tabs-nav a')[1];\n\t\t\t\t\t\$(a).click();\n\t\t\t\t\tbreak;\n\t\t\t}\n } else {\n\t\t\tif(data.error){\n\t\t\t\tvar lastIndex = data.error.lastIndexOf('Validation error'); \n \t\t\tif (lastIndex != -1 && lastIndex == (data.error.length - 16)){ \n\t\t\t\t\tif(data.errors){\n\t\t\t\t\t\t// TODO translation\n\t\t\t\t\t\tfor (i in data.errors){\n\t\t\t\t\t\t\tvar label = \$('<p/>')\n\t\t\t\t\t\t\t\t.addClass('inline-error')\n\t\t\t\t\t\t\t\t.html(data.errors[i]);\n\t\t\t\t\t\t\tlabel.insertAfter('[name='+i+']');\n\t\t\t\t\t\t}\n\t\t\t\t\t\tmyScrollToError();\n\t\t\t\t\t\treturn;\n \t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\talertIndiciaError(data);\n }\n\t},\n complete: function (){\n \t\tjQuery('.loading-button').removeClass('loading-button');\n \t}\n});"; // Set up Occurrence List tab: don't include when creating a new sample as it will have no occurrences // Grid populated at a later point $r .= "<div id=\"occurrenceList\" class=\"mnhnl-btw-datapanel\"><div id=\"occ_grid\"></div>\n <form method=\"post\" action=\"" . data_entry_helper::$base_url . "/index.php/services/report/requestReport?report=mnhnl_btw_occurrences_report.xml&reportSource=local&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth['nonce'] . "&mode=csv\">\n <input type=\"hidden\" id=\"params\" name=\"params\" value='{\"survey_id\":" . $args['survey_id'] . ", \"sample_id\":" . data_entry_helper::$entity_to_load['sample:id'] . "}' />\n <input type=\"submit\" class=\"ui-state-default ui-corner-all\" value=\"" . lang::get('LANG_Download_Occurrences') . "\">\n </form></div>"; if ($occReadOnly) { // NB that we don't even include the buttons when readonly. data_entry_helper::$javascript .= "\njQuery('#ro-occ-occ-warn').show();\njQuery('#ro-sur-occ-warn').hide();\n"; } else { data_entry_helper::$javascript .= "\njQuery('#ro-occ-occ-warn').hide();\n"; } if ($mode == 1) { data_entry_helper::$javascript .= "jQuery('#occ-form').hide();"; } else { data_entry_helper::$javascript .= "jQuery('#na-occ-warn').hide();"; } // Set up Occurrence tab: don't allow entry of a new occurrence until after top level sample is saved. data_entry_helper::$entity_to_load = $childSample; $attributes = data_entry_helper::getAttributes(array('id' => data_entry_helper::$entity_to_load['occurrence:id'], 'valuetable' => 'occurrence_attribute_value', 'attrtable' => 'occurrence_attribute', 'key' => 'occurrence_id', 'fieldprefix' => 'occAttr', 'extraParams' => $readAuth)); $extraParams = $readAuth + array('taxon_list_id' => $args['list_id'], 'view' => 'detail', 'query' => urlencode(json_encode(array('in' => array('language_iso', array('lat', iform_lang_iso_639_2($args['language']))))))); if ($occReadOnly) { // if the occurrence has been downloaded, no one can modify it. $disabledText = "disabled=\"disabled\""; $defAttrOptions['disabled'] = $disabledText; } $species_ctrl_args = array('label' => lang::get('LANG_Species'), 'fieldname' => 'occurrence:taxa_taxon_list_id', 'table' => 'taxa_taxon_list', 'captionField' => 'taxon', 'valueField' => 'id', 'columns' => 2, 'extraParams' => $extraParams, 'suffixTemplate' => 'requiredsuffix', 'disabled' => $disabledText, 'defaultCaption' => data_entry_helper::$entity_to_load['occurrence:taxon']); $escaped_terr_id = str_replace(':', '\\\\:', $attributes[$args['occurrence_territorial_id']]['fieldname']); $r .= " <div id=\"occurrence\" class=\"mnhnl-btw-datapanel\">\n <p id=\"ro-occ-occ-warn\"><strong>" . lang::get('LANG_Read_Only_Occurrence') . "</strong></p>\n <p id=\"ro-sur-occ-warn\"><strong>" . lang::get('LANG_Read_Only_Survey') . "</strong></p>\n <p id=\"na-occ-warn\"><strong>" . lang::get('LANG_Page_Not_Available') . "</strong></p>\n <form method=\"post\" id=\"occ-form\" action=\"" . iform_ajaxproxy_url($node, 'smp-occ') . "\" >\n <input type=\"hidden\" id=\"website_id\" name=\"website_id\" value=\"" . $args['website_id'] . "\" />\n <input type=\"hidden\" id=\"sample:survey_id\" name=\"sample:survey_id\" value=\"" . $args['survey_id'] . "\" />\n <input type=\"hidden\" id=\"sample:parent_id\" name=\"sample:parent_id\" value=\"" . $parentSample['sample:id'] . "\" />\n <input type=\"hidden\" id=\"sample:date\" name=\"sample:date\" value=\"" . data_entry_helper::$entity_to_load['sample:date'] . "\" />\n <input type=\"hidden\" id=\"sample:id\" name=\"sample:id\" value=\"" . data_entry_helper::$entity_to_load['sample:id'] . "\" />\n <input type=\"hidden\" id=\"occurrence:id\" name=\"occurrence:id\" value=\"" . data_entry_helper::$entity_to_load['occurrence:id'] . "\" />\n <input type=\"hidden\" id=\"occurrence:record_status\" name=\"occurrence:record_status\" value=\"C\" />\n <input type=\"hidden\" id=\"occurrence:downloaded_flag\" name=\"occurrence:downloaded_flag\" value=\"N\" />\n " . data_entry_helper::autocomplete($species_ctrl_args) . "\n " . data_entry_helper::outputAttribute($attributes[$args['occurrence_confidence_id']], array_merge($languageFilteredAttrOptions, array('noBlankText' => ''))) . "\n " . data_entry_helper::sref_and_system(array('label' => lang::get('LANG_Spatial_ref'), 'systems' => array('2169' => 'Luref (Gauss Luxembourg)'), 'suffixTemplate' => 'requiredsuffix')) . "\n <p>" . lang::get('LANG_Click_on_map') . "</p>\n " . data_entry_helper::outputAttribute($attributes[$args['occurrence_count_id']], array_merge($defAttrOptions, array('default' => 1, 'suffixTemplate' => 'requiredsuffix'))) . "\n " . data_entry_helper::outputAttribute($attributes[$args['occurrence_approximation_id']], $defAttrOptions) . "\n " . data_entry_helper::outputAttribute($attributes[$args['occurrence_territorial_id']], array_merge($defAttrOptions, array('default' => 1))) . "\n " . data_entry_helper::outputAttribute($attributes[$args['occurrence_atlas_code_id']], $languageFilteredAttrOptions) . "\n " . data_entry_helper::outputAttribute($attributes[$args['occurrence_overflying_id']], $defAttrOptions) . "\n " . data_entry_helper::textarea(array('label' => lang::get('LANG_Comment'), 'fieldname' => 'occurrence:comment', 'disabled' => $disabledText)); if (!$surveyReadOnly && !$occReadOnly) { $r .= "<input type=\"submit\" id=\"occ-submit\" class=\"ui-state-default ui-corner-all\" value=\"" . lang::get('LANG_Save_Occurrence_Details') . "\" />"; } $r .= " </form>\n"; data_entry_helper::$javascript .= "\n// because of ID tracking it is easier to rebuild entire list etc.\nretriggerGrid = function(){\n \$('div#occ_grid').empty();\n occListLayer.destroyFeatures();\n activateAddList = 1;\n thisOccID = -1;\n \$('div#occ_grid').indiciaDataGrid('rpt:mnhnl_btw_list_occurrences', {\n indiciaSvc: '" . $svcUrl . "',\n dataColumns: ['taxon', 'territorial', 'count'],\n reportColumnTitles: {taxon : '" . lang::get('LANG_Species') . "', territorial : '" . lang::get('LANG_Territorial') . "', count : '" . lang::get('LANG_Count') . "'},\n actionColumns: {'" . lang::get('LANG_Show') . "' : \"" . url('node/' . $node->nid, array('query' => 'occurrence_id=£id£')) . "\",\n '" . lang::get('LANG_Highlight') . "' : \"script:highlight(£id£);\"},\n auth : { nonce : '" . $readAuth['nonce'] . "', auth_token : '" . $readAuth['auth_token'] . "'},\n parameters : { survey_id : '" . $args['survey_id'] . "',\n parent_id : jQuery('#SurveyForm [name=sample\\:id]').val(),\n territorial_attr_id : '" . $args['occurrence_territorial_id'] . "',\n count_attr_id : '" . $args['occurrence_count_id'] . "'},\n itemsPerPage : 12,\n callback : addListFeature ,\n cssOdd : ''\n });\n}\n\njQuery('#occ-form').ajaxForm({ \n\tasync: false,\n\tdataType: 'json', \n beforeSubmit: function(data, obj, options){\n \tvar valid = true;\n \tclearErrors('form#occ-form');\n \tif (!jQuery('form#occ-form > input').valid()) { valid = false; }\n \tif (!jQuery('form#occ-form > select').valid()) { valid = false; }\n \tif(!valid) {\n\t\t\tmyScrollToError();\n\t\t\treturn false;\n\t\t};\n\t\tjQuery('#occ-submit').addClass('loading-button');\n\t\treturn true;\n\t},\n success: function(data){\n // this will leave all the fields populated.\n \tif(data.success == 'multiple records' && data.outer_table == 'sample'){\n\t\t\twindow.scroll(0,0);\n\t\t\t// cant use reset form, as returns it to original values: if this was called with occurrence_id =<x> then it would repopulate with original occurrence's values\n\t\t\t// website_id, survey_id, record_status, downloaded_flag, sample:entered_sref_system are constants and are left alone. parent_id, date are only set referring to parent sample.\n\t\t\tjQuery('form#occ-form').find('[name^=occAttr\\:]').each(function(){\n\t\t\t\tvar name = jQuery(this).attr('name').split(':');\n\t\t\t\tjQuery(this).attr('name', name[0]+':'+name[1]);\n\t\t\t});\n\t\t\tjQuery('form#occ-form').find('[name=occurrence\\:id],[name=sample\\:id]').val('').attr('disabled', 'disabled');\n\t\t\tjQuery('form#occ-form').find('[name=occurrence\\:taxa_taxon_list_id],[name=occurrence\\:taxa_taxon_list_id\\:taxon],[name=sample\\:entered_sref],[name=sample\\:geom],[name=occurrence\\:comment]').val('');\n\t\t\tjQuery('form#occ-form').find('[name=occAttr\\:" . $args['occurrence_confidence_id'] . "]').find('option').removeAttr('selected');\n\t\t\tjQuery('form#occ-form').find('[name=occAttr\\:" . $args['occurrence_count_id'] . "]').val('1');\n\t\t\tjQuery('form#occ-form').find('input[name=occAttr\\:" . $args['occurrence_approximation_id'] . "],input[name=occAttr\\:" . $args['occurrence_overflying_id'] . "]').filter('[value=0]').attr('checked','checked');\n\t\t\tjQuery('form#occ-form').find('input[name=occAttr\\:" . $args['occurrence_territorial_id'] . "]').filter('[value=1]').attr('checked','checked');\n\t\t\tjQuery('form#occ-form').find('select[name=occAttr\\:" . $args['occurrence_atlas_code_id'] . "]').val('');\n\t\t\tsetAtlasStatus();\n\t\t\tretriggerGrid();\n\t\t\tlocationLayer.map.editLayer.destroyFeatures();\n\t\t\tvar a = \$('ul.ui-tabs-nav a')[1];\n\t\t\t\$(a).empty().html('<span>" . lang::get('LANG_Add_Occurrence') . "</span>');\n\t\t\tswitch(\"" . $args["on_save_occurrence_nav"] . "\"){\n\t\t\t\tcase \"list\":\n\t\t\t\t\ta = \$('ul.ui-tabs-nav a')[2];\n\t\t\t\t\t\$(a).click();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"survey\":\n\t\t\t\t\ta = \$('ul.ui-tabs-nav a')[0];\n\t\t\t\t\t\$(a).click();\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\n } else {\n\t\t\tif(data.error){\n\t\t\t\tvar lastIndex = data.error.lastIndexOf('Validation error'); \n \t\t\tif (lastIndex != -1 && lastIndex == (data.error.length - 16)){ \n\t\t\t\t\tif(data.errors){\n\t\t\t\t\t\t// TODO translation\n\t\t\t\t\t\tfor (i in data.errors){\n\t\t\t\t\t\t\tvar label = \$('<p/>')\n\t\t\t\t\t\t\t\t.addClass('inline-error')\n\t\t\t\t\t\t\t\t.html(data.errors[i]);\n\t\t\t\t\t\t\tlabel.insertAfter('[name='+i+']');\n\t\t\t\t\t\t}\n\t\t\t\t\t\tmyScrollToError();\n\t\t\t\t\t\treturn;\n \t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\talertIndiciaError(data);\n }\n\t},\n complete: function (){\n \t\tjQuery('.loading-button').removeClass('loading-button');\n \t}\n});\nsetAtlasStatus = function() {\n if (jQuery(\"input[name=occAttr\\:" . $args['occurrence_territorial_id'] . "]:checked,input[name^=occAttr\\:" . $args['occurrence_territorial_id'] . "\\:]:checked\").val() == '0') {\n jQuery(\"select[name=occAttr\\:" . $args['occurrence_atlas_code_id'] . "],select[name^=occAttr\\:" . $args['occurrence_atlas_code_id'] . "\\:]\").val('');\n } else {\n if(jQuery(\"select[name=occAttr\\:" . $args['occurrence_atlas_code_id'] . "],select[name^=occAttr\\:" . $args['occurrence_atlas_code_id'] . "\\:]\").val() == '') {\n // Find the BB02 option (depends on the language what val it has)\n var bb02;\n jQuery.each(jQuery(\"select[name=occAttr\\:" . $args['occurrence_atlas_code_id'] . "],select[name^=occAttr\\:" . $args['occurrence_atlas_code_id'] . "\\:]\").find('option'), function(index, option) {\n if (option.text.substr(0,4)=='BB02') {\n bb02 = option.value;\n return; // just from the each loop\n }\n });\n jQuery(\"select[name=occAttr\\:" . $args['occurrence_atlas_code_id'] . "],select[name^=occAttr\\:" . $args['occurrence_atlas_code_id'] . "\\:]\").val(bb02);\n }\n }\n};\njQuery(\"input[name='" . $escaped_terr_id . "']\").change(setAtlasStatus);\n"; $r .= '</div>'; // add map panel. $r .= "<div class=\"mnhnl-btw-mappanel\">\n"; $r .= data_entry_helper::map_panel(array('presetLayers' => $presetLayers, 'layers' => array('baseLayer_1', 'baseLayer_2', 'locationLayer', 'occListLayer'), 'initialFeatureWkt' => null, 'width' => 'auto', 'height' => 490, 'initial_lat' => $args['map_centroid_lat'], 'initial_long' => $args['map_centroid_long'], 'initial_zoom' => (int) $args['map_zoom'], 'scroll_wheel_zoom' => false), array('projection' => $args['map_projection'])); // for timing reasons, all the following has to be done after the map is loaded. // 1) feature selector for occurrence list must have the map present to attach the control // 2) location placer must have the location layer populated and the map present in // order to zoom the map into the location. // 3) occurrence list feature adder must have map present in order to zoom into any // current selection. data_entry_helper::$onload_javascript .= "\nvar control = new OpenLayers.Control.SelectFeature(occListLayer);\noccListLayer.map.addControl(control);\nfunction onPopupClose(evt) {\n // 'this' is the popup.\n control.unselect(this.feature);\n}\nfunction onFeatureSelect(evt) {\n feature = evt.feature;\n popup = new OpenLayers.Popup.FramedCloud(\"featurePopup\",\n feature.geometry.getBounds().getCenterLonLat(),\n new OpenLayers.Size(100,100),\n feature.attributes.taxon + \" (\" + feature.attributes.count + \")\",\n null, true, onPopupClose);\n feature.popup = popup;\n popup.feature = feature;\n feature.layer.map.addPopup(popup);\n}\nfunction onFeatureUnselect(evt) {\n feature = evt.feature;\n if (feature.popup) {\n popup.feature = null;\n feature.layer.map.removePopup(feature.popup);\n feature.popup.destroy();\n feature.popup = null;\n }\n}\n\noccListLayer.events.on({\n 'featureselected': onFeatureSelect,\n 'featureunselected': onFeatureUnselect\n});\n\ncontrol.activate();\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=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["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 {\n if(data[i].centroid_geom){\n " . self::readBoundaryJs('data[i].centroid_geom', $args['map_projection']) . "\n feature.style = {label: data[i].name,\n\t\t\t\t\t\t strokeColor: \"Green\",\n strokeWidth: 2,\n fillOpacity: 0};\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 " . self::readBoundaryJs('data[i].boundary_geom', $args['map_projection']) . "\n feature.style = {strokeColor: \"Blue\", strokeWidth: 2};\n locationLayer.addFeatures([feature]);\n }\n locationLayer.map.zoomToExtent(locationLayer.getDataExtent());\n }\n }\n });\n jQuery.getJSON(\"" . $svcUrl . "\" + \"/data/location\" +\n \"?mode=json&view=detail&auth_token=" . $readAuth['auth_token'] . "&nonce=" . $readAuth["nonce"] . "&callback=?&parent_id=\"+obj.value, function(data) {\n if (data.length>0) {\n var parser = new OpenLayers.Format.WKT();\n for (var i=0;i<data.length;i++)\n {\n if(data[i].centroid_geom){\n " . self::readBoundaryJs('data[i].centroid_geom', $args['map_projection']) . "\n locationLayer.addFeatures([feature]);\n }\n if(data[i].boundary_geom){\n " . self::readBoundaryJs('data[i].boundary_geom', $args['map_projection']) . "\n feature.style = {label: data[i].name,\n labelAlign: \"cb\",\n strokeColor: \"Blue\",\n strokeWidth: 2};\n locationLayer.addFeatures([feature]);\n }\n }\n }\n });\n }\n};\n// upload location initial value into map.\njQuery('#imp-location').each(function(){\n locationChange(this);\n});\njQuery('#imp-location').unbind('change');\njQuery('#imp-location').change(function(){\n locationChange(this);\n});\nvar selected = \$('#controls').tabs('option', 'selected');\n\n// Only leave the click control activated for edit/add occurrence tab.\nif(selected != 1){\n locationLayer.map.editLayer.clickControl.deactivate();\n}\n\$('#controls').bind('tabsshow', function(event, ui) {\n if(ui.index == 1)\n {\n locationLayer.map.editLayer.clickControl.activate();\n }\n else\n {\n locationLayer.map.editLayer.clickControl.deactivate();\n }\n }\n);\n"; if ($mode != 1) { data_entry_helper::$onload_javascript .= "\nactivateAddList = 1;\nthisOccID = " . $thisOccID . ";\n\naddListFeature = function(div, r, record, count) {\n if(activateAddList == 0)\n return;\n if(r == count)\n activateAddList = 0;\n var parser = new OpenLayers.Format.WKT();\n " . self::readBoundaryJs('record.geom', $args['map_projection']) . "\n if(record.id != thisOccID || 1==" . ($surveyReadOnly ? 1 : 0) . " || 1==" . ($occReadOnly ? 1 : 0) . "){\n feature.attributes.id = record.id;\n feature.attributes.taxon = record.taxon;\n feature.attributes.count = record.count;\n occListLayer.addFeatures([feature]);\n if(record.id == " . $thisOccID . "){\n var bounds=feature.geometry.getBounds();\n locationLayer.map.setCenter(bounds.getCenterLonLat());\n }\n } else {\n locationLayer.map.editLayer.destroyFeatures();\n locationLayer.map.editLayer.addFeatures([feature]);\n var bounds=feature.geometry.getBounds()\n var centre=bounds.getCenterLonLat();\n locationLayer.map.setCenter(centre);\n }\n};\nhighlight = function(id){\n if(id == " . $thisOccID . "){\n if(occListLayer.map.editLayer.features.length > 0){\n var bounds=occListLayer.map.editLayer.features[0].geometry.getBounds()\n var centre=bounds.getCenterLonLat();\n occListLayer.map.setCenter(centre);\n return;\n }\n }\n for(var i = 0; i < occListLayer.features.length; i++){\n if(occListLayer.features[i].attributes.id == id){\n control.unselectAll();\n var bounds=occListLayer.features[i].geometry.getBounds()\n var centre=bounds.getCenterLonLat();\n occListLayer.map.setCenter(centre);\n control.select(occListLayer.features[i]);\n return;\n }\n }\n}\n\$('div#occ_grid').indiciaDataGrid('rpt:mnhnl_btw_list_occurrences', {\n indiciaSvc: '" . $svcUrl . "',\n dataColumns: ['taxon', 'territorial', 'count'],\n reportColumnTitles: {taxon : '" . lang::get('LANG_Species') . "', territorial : '" . lang::get('LANG_Territorial') . "', count : '" . lang::get('LANG_Count') . "'},\n actionColumns: {'" . lang::get('LANG_Show') . "' : \"" . url('node/' . $node->nid, array('query' => 'occurrence_id=£id£')) . "\",\n '" . lang::get('LANG_Highlight') . "' : \"script:highlight(£id£);\"},\n auth : { nonce : '" . $readAuth['nonce'] . "', auth_token : '" . $readAuth['auth_token'] . "'},\n parameters : { survey_id : '" . $args['survey_id'] . "',\n parent_id : '" . $parentSample['sample:id'] . "',\n territorial_attr_id : '" . $args['occurrence_territorial_id'] . "',\n count_attr_id : '" . $args['occurrence_count_id'] . "'},\n itemsPerPage : 12,\n callback : addListFeature ,\n cssOdd : ''\n });\n\n// activateAddList = 0;\n\n"; } $r .= "</div><div><form><input type=\"button\" value=\"" . lang::get('LANG_Return') . "\" onclick=\"window.location.href='" . url('node/' . $node->nid, array('query' => 'Main')) . "'\"></form></div></div>\n"; return $r; }
?> <p>This page allows you to specify the details of a survey in which samples and records can be organised.</p> <form class="cmxform" action="<?php echo url::site() . 'survey/save'; ?> " method="post" id="survey-edit"> <?php echo $metadata; ?> <fieldset> <legend>Survey dataset details</legend> <?php echo data_entry_helper::hidden_text(array('fieldname' => 'survey:id', 'default' => html::initial_value($values, 'survey:id'))); echo data_entry_helper::text_input(array('label' => 'Title', 'fieldname' => 'survey:title', 'default' => html::initial_value($values, 'survey:title'), 'validation' => 'required', 'helpText' => 'Provide a title for your survey dataset')); echo data_entry_helper::textarea(array('label' => 'Description', 'fieldname' => 'survey:description', 'default' => html::initial_value($values, 'survey:description'), 'validation' => 'required', 'helpText' => 'Provide an optional description of your survey to help when browsing survey datasets on the warehouse')); echo data_entry_helper::autocomplete(array('label' => 'Parent survey', 'fieldname' => 'survey:parent_id', 'table' => 'survey', 'captionField' => 'title', 'valueField' => 'id', 'extraParams' => $readAuth, 'default' => html::initial_value($values, 'survey:parent_id'), 'defaultCaption' => html::initial_value($values, 'parent:title'), 'helpText' => 'Set a parent for your survey to allow grouping of survey datasets in reports')); echo data_entry_helper::select(array('label' => 'Website', 'fieldname' => 'survey:website_id', 'default' => html::initial_value($values, 'survey:website_id'), 'lookupValues' => $other_data['websites'], 'helpText' => 'The survey must belong to a website registration')); ?> </fieldset> <?php if (array_key_exists('attributes', $values) && count($values['attributes']) > 0) { ?> <fieldset> <legend>Custom attributes</legend> <ol> <?php foreach ($values['attributes'] as $attr) { $name = 'srvAttr:' . $attr['survey_attribute_id']; // if this is an existing attribute, tag it with the attribute value record id so we can re-save it if ($attr['id']) { $name .= ':' . $attr['id'];
echo $this->taxon_list_id; ?> , taxon_group_id: $('#add-group').val() }, function(data, textStatus) { if (isNaN(parseInt(data))) // if text returned, it is a message to display alert(data); else // if OK, it returns the new record ID. Add it to the grid. if (data!==0) indiciaData.reports.taxon_groups_taxon_list.grid_taxon_groups_taxon_list.addRecords('id', data); } ); } /*]]>*/ </script> <?php require_once DOCROOT . 'client_helpers/data_entry_helper.php'; $readAuth = data_entry_helper::get_read_auth(0 - $_SESSION['auth_user']->id, kohana::config('indicia.private_key')); echo '<div class="linear-form">'; echo data_entry_helper::autocomplete(array('label' => 'Add taxon group', 'fieldname' => 'add-group', 'helpText' => 'Search for taxon groups to quickly add them into this list.', 'table' => 'taxon_group', 'captionField' => 'title', 'valueField' => 'id', 'extraParams' => $readAuth, 'afterControl' => '<input type="button" value="Add" onclick="add_taxon_group();" />')); echo '</div>'; echo $grid; if (request::is_ajax()) { // When viewing as an AJAX loaded tab, don't reload jQuery as it is already on the page. data_entry_helper::$dumped_resources[] = 'jquery'; } data_entry_helper::link_default_stylesheet(); echo data_entry_helper::dump_javascript(true);
/** * Get the observer control as an autocomplete. */ protected static function get_control_observerautocomplete($auth, $args, $tabAlias, $options) { global $user; //Get the name of the currently logged in user $defaultUserData = data_entry_helper::get_report_data(array('dataSource' => 'library/users/get_people_details_for_website_or_user', 'readAuth' => $auth['read'], 'extraParams' => array('user_id' => hostsite_get_user_field('indicia_user_id'), 'website_id' => $args['website_id']))); //If we are in edit mode then we need to get the name of the saved observer for the sample if (!empty($_GET['sample_id']) && !empty($args['observer_name'])) { $existingUserData = data_entry_helper::get_population_data(array('table' => 'sample_attribute_value', 'extraParams' => $auth['read'] + array('sample_id' => $_GET['sample_id'], 'sample_attribute_id' => $args['observer_name']))); } $observer_list_args = array_merge_recursive(array('extraParams' => array_merge($auth['read'])), $options); $observer_list_args['label'] = t('Observer Name'); $observer_list_args['extraParams']['website_id'] = $args['website_id']; $observer_list_args['captionField'] = 'fullname_surname_first'; $observer_list_args['id'] = 'obSelect:' . $args['observer_name']; $observer_list_args['report'] = 'library/users/get_people_details_for_website_or_user'; //Auto-fill the observer name with the name of the observer of the existing saved sample if it exists, //else default to current user name if (!empty($existingUserData[0]['value'])) { $observer_list_args['defaultCaption'] = $existingUserData[0]['value']; } else { if (empty($_GET['sample_id'])) { $observer_list_args['defaultCaption'] = $defaultUserData[0]['fullname_surname_first']; } } return data_entry_helper::autocomplete($observer_list_args); }
?> <input type='hidden' id='website_id' name='website_id' value='<?php echo $config['website_id']; ?> ' /> <input type='hidden' id='survey_id' name='survey_id' value='<?php echo $config['survey_id']; ?> ' /> <input type='hidden' id='record_status' name='occurrence:record_status' value='C' /> <?php echo flickr_helper::flickr_selector(); ?> <label for='occurrence:taxa_taxon_list_id:taxon'>Taxon:</label> <?php echo data_entry_helper::autocomplete('occurrence:taxa_taxon_list_id', 'taxa_taxon_list', 'taxon', 'id', $readAuth); ?> <label for="date">Date:</label> <?php echo data_entry_helper::date_picker('sample:date'); echo data_entry_helper::map(); ?> <input type="submit" value="Save" /> </fieldset> </form> <?php echo data_entry_helper::dump_javascript(); ?> </body> </html>