Пример #1
0
/**
 * Retreives the options array required to set up a report according to the default
 * report parameters.
 * @global <type> $indicia_templates
 * @param string $args
 * @param <type> $readAuth
 * @return string
 */
function iform_report_get_report_options($args, $readAuth)
{
    // handle auto_params_form for backwards compatibility
    if (empty($args['output']) && !empty($args['auto_params_form'])) {
        if (!$args['auto_params_form']) {
            $args['output'] = 'output';
        }
    }
    if (isset($args['map_toolbar_pos']) && $args['map_toolbar_pos'] == 'map') {
        // report params cannot go in the map toolbar if displayed as overlay on map
        $args['params_in_map_toolbar'] = false;
    }
    $r = '';
    require_once 'user.php';
    $presets = get_options_array_with_user_data($args['param_presets']);
    $defaults = get_options_array_with_user_data($args['param_defaults']);
    $ignores = isset($args['param_ignores']) ? helper_base::explode_lines($args['param_ignores']) : array();
    // default columns behaviour is to just include anything returned by the report
    $columns = array();
    // this can be overridden
    if (isset($args['columns_config']) && !empty($args['columns_config'])) {
        $columns = json_decode($args['columns_config'], true);
    }
    $reportOptions = array('id' => 'report-grid', 'reportGroup' => isset($args['report_group']) ? $args['report_group'] : '', 'rememberParamsReportGroup' => isset($args['remember_params_report_group']) ? $args['remember_params_report_group'] : '', 'dataSource' => $args['report_name'], 'mode' => 'report', 'readAuth' => $readAuth, 'columns' => $columns, 'itemsPerPage' => empty($args['items_per_page']) ? 20 : $args['items_per_page'], 'extraParams' => $presets, 'paramDefaults' => $defaults, 'ignoreParams' => $ignores, 'galleryColCount' => isset($args['gallery_col_count']) ? $args['gallery_col_count'] : 1, 'headers' => isset($args['gallery_col_count']) && $args['gallery_col_count'] > 1 ? false : true, 'paramsInMapToolbar' => isset($args['params_in_map_toolbar']) ? $args['params_in_map_toolbar'] : false);
    // put each param control in a div, which makes it easier to layout with CSS
    if (!isset($args['params_in_map_toolbar']) || !$args['params_in_map_toolbar']) {
        $reportOptions['paramPrefix'] = '<div id="container-{fieldname}" class="param-container">';
        $reportOptions['paramSuffix'] = '</div>';
    }
    // If in Drupal, allow the params panel to collapse.
    if (function_exists('drupal_add_js')) {
        if (function_exists('hostsite_add_library') && (!defined('DRUPAL_CORE_COMPATIBILITY') || DRUPAL_CORE_COMPATIBILITY !== '7.x')) {
            hostsite_add_library('collapse');
            $reportOptions['fieldsetClass'] = 'collapsible';
        }
    }
    if (empty($args['output']) || $args['output'] == 'default') {
        $reportOptions['autoParamsForm'] = true;
    } elseif ($args['output'] == 'form') {
        $reportOptions['autoParamsForm'] = true;
        $reportOptions['paramsOnly'] = true;
    } else {
        $reportOptions['autoParamsForm'] = false;
    }
    if (!empty($args['row_class'])) {
        $reportOptions['rowClass'] = $args['row_class'];
    }
    // Set up a page refresh for dynamic update of the report at set intervals
    if (isset($args['refresh_timer']) && $args['refresh_timer'] !== 0 && is_numeric($args['refresh_timer'])) {
        // is_numeric prevents injection
        if (isset($args['load_on_refresh']) && !empty($args['load_on_refresh'])) {
            report_helper::$javascript .= "setTimeout('window.location=\"" . $args['load_on_refresh'] . "\";', " . $args['refresh_timer'] . "*1000 );\n";
        } else {
            report_helper::$javascript .= "setTimeout('window.location.reload( false );', " . $args['refresh_timer'] . "*1000 );\n";
        }
    }
    return $reportOptions;
}
Пример #2
0
/**
 * Method to read a parameter from the arguments of a form that contains a list of key=value pairs on separate lines. 
 * Each value is checked for references to the user's data (either {user_id}, {username}, {email} or {profile_*})
 * and if found these substitutions are replaced.
 * @param string $listData Form argument data, with each key value pair on a separate line.
 * @return array Associative array.
 */
function get_options_array_with_user_data($listData)
{
    global $user;
    $r = array();
    if ($listData != '') {
        $params = helper_base::explode_lines($listData);
        foreach ($params as $param) {
            if (!empty($param)) {
                $tokens = explode('=', $param, 2);
                if (count($tokens) == 2) {
                    $tokens[1] = apply_user_replacements($tokens[1]);
                } else {
                    throw new Exception('Some of the preset or default parameters defined for this page are not of the form param=value.');
                }
                $r[$tokens[0]] = $tokens[1];
            }
        }
    }
    return $r;
}
 private static function get_control_speciesidentifier($auth, $args, $tabalias, $options)
 {
     static $taxIdx = 0;
     // we need to control which items are lockable if locking requested
     if (!empty($options['lockable']) && $options['lockable'] == true) {
         $options['identifiers_lockable'] = $options['lockable'];
     } else {
         $options['identifiers_lockable'] = '';
     }
     unset($options['lockable']);
     // get the identifier type data
     $filter = array('termlist_external_key' => 'indicia:assoc:identifier_type');
     $dataOpts = array('table' => 'termlists_term', 'extraParams' => $auth['read'] + $filter);
     $options['identifierTypes'] = data_entry_helper::get_population_data($dataOpts);
     // get the identifier attribute type data
     $dataOpts = array('table' => 'identifier_attribute', 'extraParams' => $auth['read']);
     $options['idnAttributeTypes'] = data_entry_helper::get_population_data($dataOpts);
     // set up the known system types for identifier attributes
     $options['baseColourId'] = -1;
     $options['textColourId'] = -1;
     $options['sequenceId'] = -1;
     $options['positionId'] = -1;
     foreach ($options['idnAttributeTypes'] as $idnAttributeType) {
         if (!empty($idnAttributeType['system_function'])) {
             switch ($idnAttributeType['system_function']) {
                 case 'base_colour':
                     $options['baseColourId'] = $idnAttributeType['id'];
                     break;
                 case 'text_colour':
                     $options['textColourId'] = $idnAttributeType['id'];
                     break;
                 case 'sequence':
                     $options['sequenceId'] = $idnAttributeType['id'];
                     break;
                 case 'position':
                     $options['positionId'] = $idnAttributeType['id'];
                     break;
             }
         }
     }
     // get the subject observation attribute type data
     $dataOpts = array('table' => 'subject_observation_attribute', 'extraParams' => $auth['read']);
     $options['sjoAttributeTypes'] = data_entry_helper::get_population_data($dataOpts);
     // set up the known system types for subject_observation attributes
     $options['attachmentId'] = -1;
     $options['genderId'] = -1;
     $options['stageId'] = -1;
     $options['lifeStatusId'] = -1;
     foreach ($options['sjoAttributeTypes'] as $sjoAttributeType) {
         if (!empty($sjoAttributeType['system_function'])) {
             switch ($sjoAttributeType['system_function']) {
                 case 'attachment':
                     $options['attachmentId'] = $sjoAttributeType['id'];
                     break;
                 case 'gender':
                     $options['genderId'] = $sjoAttributeType['id'];
                     break;
                 case 'stage':
                     $options['stageId'] = $sjoAttributeType['id'];
                     break;
                 case 'life_status':
                     $options['lifeStatusId'] = $sjoAttributeType['id'];
                     break;
             }
         }
     }
     // get the identifiers subject observation attribute type data
     $dataOpts = array('table' => 'identifiers_subject_observation_attribute', 'extraParams' => $auth['read']);
     $options['isoAttributeTypes'] = data_entry_helper::get_population_data($dataOpts);
     // set up the known system types for subject_observation attributes
     $options['conditionsId'] = -1;
     foreach ($options['isoAttributeTypes'] as $isoAttributeType) {
         if (!empty($isoAttributeType['system_function'])) {
             switch ($isoAttributeType['system_function']) {
                 case 'identifier_condition':
                     $options['conditionsId'] = $isoAttributeType['id'];
                     break;
             }
         }
     }
     // throw an exception if any of the required custom attributes is missing
     $errorMessages = array();
     foreach (array('baseColourId', 'textColourId', 'sequenceId', 'positionId', 'attachmentId', 'genderId', 'stageId', 'lifeStatusId', 'conditionsId') as $attrId) {
         if ($options[$attrId] === -1) {
             $errorMessages[] = lang::get('Required custom attribute for ' . $attrId . ' has not been found. ' . 'Please check this has been created on the warehouse and is associated with the correct system function.');
         }
     }
     if (count($errorMessages) > 0) {
         $errorMessage = implode('<br />', $errorMessages);
         throw new exception($errorMessage);
     }
     // configure the identifiers javascript
     // write it late so it happens after any locked values are applied
     if (!$options['inNewIndividual']) {
         data_entry_helper::$late_javascript .= "indicia.wwt.initForm (\n        '" . $options['baseColourId'] . "',\n        '" . $options['textColourId'] . "',\n        '" . $options['sequenceId'] . "',\n        '" . $options['positionId'] . "',\n        '" . $args['default_leg_vertical'] . "',\n        '" . (!empty($args['neck_collar_regex']) ? $args['neck_collar_regex'] : '') . "',\n        '" . (!empty($args['enscribed_colour_ring_regex']) ? $args['enscribed_colour_ring_regex'] : '') . "',\n        '" . (!empty($args['metal_ring_regex']) ? $args['metal_ring_regex'] : '') . "',\n        '" . ($args['clientSideValidation'] ? 'true' : 'false') . "',\n        '" . ($args['subjectAccordion'] ? 'true' : 'false') . "'\n" . ");\n";
     }
     $r = '';
     $options['fieldprefix'] = 'idn:' . $taxIdx . ':';
     if (!$options['inNewIndividual']) {
         $r .= '<div id="idn:subject:accordion" class="idn-subject-accordion">';
     }
     if ($args['subjectAccordion']) {
         $r .= '<h3 id="' . $options['fieldprefix'] . 'individual:header" class="individual_header"><a href="" data-heading="' . lang::get('Colour-marked Individual') . ' ' . ($taxIdx + 1) . '">' . lang::get('Colour-marked Individual') . ' ' . ($taxIdx + 1) . '</a></h3>';
     } else {
         $r .= '<h3 id="' . $options['fieldprefix'] . 'individual:header" class="individual_header" data-heading="' . lang::get('Colour-marked Individual') . ' ' . ($taxIdx + 1) . '">' . lang::get('Colour-marked Individual') . ' ' . ($taxIdx + 1) . '</h3>';
     }
     $r .= '<div id="' . $options['fieldprefix'] . 'individual:panel" class="individual_panel ui-corner-all">';
     $r .= '<div class="ui-helper-clearfix">';
     $r .= '<fieldset id="' . $options['fieldprefix'] . 'individual:fieldset" class="taxon_individual ui-corner-all">';
     $r .= '<legend id="' . $options['fieldprefix'] . 'individual:legend">Individual details</legend>';
     // output the hiddens
     if (isset(data_entry_helper::$entity_to_load[$options['fieldprefix'] . 'subject_observation:id'])) {
         $r .= '<input type="hidden" id="' . $options['fieldprefix'] . 'subject_observation:id" name="' . $options['fieldprefix'] . 'subject_observation:id" ' . 'value="' . data_entry_helper::$entity_to_load[$options['fieldprefix'] . 'subject_observation:id'] . '" />' . "\n";
     }
     if (isset(data_entry_helper::$entity_to_load[$options['fieldprefix'] . 'occurrences_subject_observation:id'])) {
         $r .= '<input type="hidden" id="' . $options['fieldprefix'] . 'occurrences_subject_observation:id" name="' . $options['fieldprefix'] . 'occurrences_subject_observation:id" ' . 'value="' . data_entry_helper::$entity_to_load[$options['fieldprefix'] . 'occurrences_subject_observation:id'] . '" />' . "\n";
     }
     if (isset(data_entry_helper::$entity_to_load[$options['fieldprefix'] . 'occurrence:id'])) {
         $r .= '<input type="hidden" id="' . $options['fieldprefix'] . 'occurrence:id" name="' . $options['fieldprefix'] . 'occurrence:id" ' . 'value="' . data_entry_helper::$entity_to_load[$options['fieldprefix'] . 'occurrence:id'] . '" />' . "\n";
     }
     // Check if Record Status is included as a control. If not, then add it as a hidden.
     $arr = helper_base::explode_lines($args['structure']);
     if (!in_array('[record status]', $arr)) {
         if (isset(data_entry_helper::$entity_to_load[$options['fieldprefix'] . 'occurrence:record_status'])) {
             $value = data_entry_helper::$entity_to_load[$options['fieldprefix'] . 'occurrence:record_status'];
         } else {
             $value = isset($args['defaults']['occurrence:record_status']) ? $args['defaults']['occurrence:record_status'] : 'C';
         }
         $r .= '<input type="hidden" id="' . $options['fieldprefix'] . 'occurrence:record_status" ' . 'name="' . $options['fieldprefix'] . 'occurrence:record_status" value="' . $value . '" />' . "\n";
     }
     // add subject type and count as a hidden
     $value = '';
     if (isset(data_entry_helper::$entity_to_load[$options['fieldprefix'] . 'subject_observation:subject_type_id'])) {
         $value = data_entry_helper::$entity_to_load[$options['fieldprefix'] . 'subject_observation:subject_type_id'];
     } else {
         if (isset($args['subject_type_id'])) {
             $value = $args['subject_type_id'];
         }
     }
     if ($value !== '') {
         $r .= '<input type="hidden" id="' . $options['fieldprefix'] . 'subject_observation:subject_type_id" ' . 'name="' . $options['fieldprefix'] . 'subject_observation:subject_type_id" value="' . $value . '" />' . "\n";
     }
     if (isset(data_entry_helper::$entity_to_load[$options['fieldprefix'] . 'subject_observation:count'])) {
         $value = data_entry_helper::$entity_to_load[$options['fieldprefix'] . 'subject_observation:count'];
     } else {
         $value = '1';
     }
     if ($value !== '') {
         $r .= '<input type="hidden" id="' . $options['fieldprefix'] . 'subject_observation:count" ' . 'name="' . $options['fieldprefix'] . 'subject_observation:count" value="' . $value . '" />' . "\n";
     }
     // output the species selection control
     $options['blankText'] = '<Please select>';
     $options['lockable'] = $options['identifiers_lockable'];
     if ($args['species_ctrl'] == 'autocomplete') {
         $temp = data_entry_helper::$javascript;
     }
     $r .= self::get_control_species($auth, $args, $tabalias, $options + array('validation' => array('required'), 'class' => 'select_taxon'));
     if ($args['species_ctrl'] == 'autocomplete') {
         if (!$options['inNewIndividual']) {
             $autoJavascript = substr(data_entry_helper::$javascript, strlen($temp));
         } else {
             data_entry_helper::$javascript = $temp;
         }
         unset($temp);
     } else {
         $autoJavascript = '';
     }
     unset($options['lockable']);
     // gender
     if ($options['genderId'] > 0 && !empty($args['request_gender_values']) && count($args['request_gender_values']) > 0) {
         // filter the genders available
         $query = array('in' => array('id', $args['request_gender_values']));
         $filter = array('query' => json_encode($query), 'orderby' => 'sort_order');
         $extraParams = array_merge($filter, $auth['read']);
         $options['lockable'] = $options['identifiers_lockable'];
         $fieldname = $options['fieldprefix'] . 'sjoAttr:' . $options['genderId'];
         $idname = $fieldname;
         // if this attribute exists on DB, we need to append id to fieldname
         if (is_array(data_entry_helper::$entity_to_load)) {
             $stored_keys = preg_grep('/^' . $fieldname . ':[0-9]+$/', array_keys(data_entry_helper::$entity_to_load));
             if (count($stored_keys) === 1) {
                 foreach ($stored_keys as $stored_key) {
                     $fieldname = $stored_key;
                 }
             }
         }
         $r .= data_entry_helper::select(array_merge(array('label' => lang::get('Sex of the bird'), 'fieldname' => $fieldname, 'id' => $idname, 'table' => 'termlists_term', 'captionField' => 'term', 'valueField' => 'id', 'default' => $args['default_gender'], 'extraParams' => $extraParams), $options));
         unset($options['lockable']);
     }
     // age
     if ($options['stageId'] > 0 && !empty($args['request_stage_values']) && count($args['request_stage_values']) > 0) {
         // filter the stages available
         $query = array('in' => array('id', $args['request_stage_values']));
         $filter = array('query' => json_encode($query), 'orderby' => 'sort_order');
         $extraParams = array_merge($filter, $auth['read']);
         $options['lockable'] = $options['identifiers_lockable'];
         $fieldname = $options['fieldprefix'] . 'sjoAttr:' . $options['stageId'];
         $idname = $fieldname;
         // if this attribute exists on DB, we need to append id to fieldname
         if (is_array(data_entry_helper::$entity_to_load)) {
             $stored_keys = preg_grep('/^' . $fieldname . ':[0-9]+$/', array_keys(data_entry_helper::$entity_to_load));
             if (count($stored_keys) === 1) {
                 foreach ($stored_keys as $stored_key) {
                     $fieldname = $stored_key;
                 }
             }
         }
         $r .= data_entry_helper::select(array_merge(array('label' => lang::get('Age of the bird'), 'fieldname' => $fieldname, 'id' => $idname, 'table' => 'termlists_term', 'captionField' => 'term', 'valueField' => 'id', 'default' => $args['default_stage'], 'extraParams' => $extraParams), $options));
         unset($options['lockable']);
     }
     // subject status
     if ($options['lifeStatusId'] > 0 && !empty($args['request_life_status_values']) && count($args['request_life_status_values']) > 0) {
         // filter the life status's available
         $query = array('in' => array('id', $args['request_life_status_values']));
         $filter = array('query' => json_encode($query), 'orderby' => 'sort_order');
         $extraParams = array_merge($filter, $auth['read']);
         $options['lockable'] = $options['identifiers_lockable'];
         $fieldname = $options['fieldprefix'] . 'sjoAttr:' . $options['lifeStatusId'];
         $idname = $fieldname;
         // if this attribute exists on DB, we need to append id to fieldname
         if (is_array(data_entry_helper::$entity_to_load)) {
             $stored_keys = preg_grep('/^' . $fieldname . ':[0-9]+$/', array_keys(data_entry_helper::$entity_to_load));
             if (count($stored_keys) === 1) {
                 foreach ($stored_keys as $stored_key) {
                     $fieldname = $stored_key;
                 }
             }
         }
         $r .= data_entry_helper::select(array_merge(array('label' => lang::get('This bird was'), 'fieldname' => $fieldname, 'id' => $idname, 'table' => 'termlists_term', 'captionField' => 'term', 'valueField' => 'id', 'default' => $args['default_life_status'], 'extraParams' => $extraParams), $options));
         unset($options['lockable']);
     }
     // output each required identifier
     $r .= '<div id="' . $options['fieldprefix'] . 'accordion" class="idn-accordion">';
     // setup and call function for neck collar
     $options['identifierName'] = '';
     $options['identifierTypeId'] = '';
     foreach ($options['identifierTypes'] as $identifier_type) {
         if ($identifier_type['id'] == $args['neck_collar_type']) {
             $options['identifierName'] = $identifier_type['term'];
             $options['identifierTypeId'] = $identifier_type['id'];
             break;
         }
     }
     $options['attrList'] = array(array('attrType' => 'idn', 'typeId' => $options['baseColourId'], 'lockable' => true, 'hidden' => false), array('attrType' => 'idn', 'typeId' => $options['textColourId'], 'lockable' => true, 'hidden' => false), array('attrType' => 'idn', 'typeId' => $options['sequenceId'], 'lockable' => false, 'hidden' => false), array('attrType' => 'idn', 'typeId' => $options['positionId'], 'lockable' => false, 'hidden' => true, 'hiddenValue' => $args['neck_collar_position']), array('attrType' => 'iso', 'typeId' => $options['conditionsId'], 'lockable' => false, 'hidden' => false));
     $options['fieldprefix'] = 'idn:' . $taxIdx . ':neck-collar:';
     $options['classprefix'] = 'idn-neck-collar-';
     $options['seq_maxlength'] = !empty($args['neck_collar_max_length']) ? $args['neck_collar_max_length'] : '';
     if (!empty($args['neck_collar_regex'])) {
         $options['seq_format_class'] = 'collarFormat';
     }
     $r .= self::get_control_identifier($auth, $args, $tabalias, $options);
     if (!empty($args['neck_collar_regex'])) {
         unset($options['seq_format_class']);
     }
     // setup and call function for left enscribed colour ring
     $options['identifierName'] = '';
     $options['identifierTypeId'] = '';
     foreach ($options['identifierTypes'] as $identifier_type) {
         if ($identifier_type['id'] == $args['enscribed_colour_ring_type']) {
             $options['identifierName'] = $identifier_type['term'] . lang::get(' (Left leg)');
             $options['identifierTypeId'] = $identifier_type['id'];
             break;
         }
     }
     $options['attrList'] = array(array('attrType' => 'idn', 'typeId' => $options['baseColourId'], 'lockable' => true, 'hidden' => false), array('attrType' => 'idn', 'typeId' => $options['textColourId'], 'lockable' => true, 'hidden' => false), array('attrType' => 'idn', 'typeId' => $options['sequenceId'], 'lockable' => false, 'hidden' => false), array('attrType' => 'idn', 'typeId' => $options['positionId'], 'lockable' => false, 'hidden' => true, 'hiddenValue' => $args['left_enscribed_colour_ring_position']), array('attrType' => 'iso', 'typeId' => $options['conditionsId'], 'lockable' => false, 'hidden' => false));
     $options['fieldprefix'] = 'idn:' . $taxIdx . ':colour-left:';
     $options['classprefix'] = 'idn-colour-left-';
     $options['seq_maxlength'] = !empty($args['enscribed_colour_ring_max_length']) ? $args['enscribed_colour_ring_max_length'] : '';
     if (!empty($args['enscribed_colour_ring_regex'])) {
         $options['seq_format_class'] = 'colourRingFormat';
     }
     $r .= self::get_control_identifier($auth, $args, $tabalias, $options);
     if (!empty($args['enscribed_colour_ring_regex'])) {
         unset($options['seq_format_class']);
     }
     // setup and call function for right enscribed colour ring
     $options['identifierName'] = '';
     $options['identifierTypeId'] = '';
     foreach ($options['identifierTypes'] as $identifier_type) {
         if ($identifier_type['id'] == $args['enscribed_colour_ring_type']) {
             $options['identifierName'] = $identifier_type['term'] . lang::get(' (Right leg)');
             $options['identifierTypeId'] = $identifier_type['id'];
             break;
         }
     }
     $options['attrList'] = array(array('attrType' => 'idn', 'typeId' => $options['baseColourId'], 'lockable' => true, 'hidden' => false), array('attrType' => 'idn', 'typeId' => $options['textColourId'], 'lockable' => true, 'hidden' => false), array('attrType' => 'idn', 'typeId' => $options['sequenceId'], 'lockable' => false, 'hidden' => false), array('attrType' => 'idn', 'typeId' => $options['positionId'], 'lockable' => false, 'hidden' => true, 'hiddenValue' => $args['right_enscribed_colour_ring_position']), array('attrType' => 'iso', 'typeId' => $options['conditionsId'], 'lockable' => false, 'hidden' => false));
     $options['fieldprefix'] = 'idn:' . $taxIdx . ':colour-right:';
     $options['classprefix'] = 'idn-colour-right-';
     $options['seq_maxlength'] = !empty($args['enscribed_colour_ring_max_length']) ? $args['enscribed_colour_ring_max_length'] : '';
     if (!empty($args['enscribed_colour_ring_regex'])) {
         $options['seq_format_class'] = 'colourRingFormat';
     }
     $r .= self::get_control_identifier($auth, $args, $tabalias, $options);
     if (!empty($args['enscribed_colour_ring_regex'])) {
         unset($options['seq_format_class']);
     }
     // setup and call function for metal ring
     $options['identifierName'] = '';
     $options['identifierTypeId'] = '';
     foreach ($options['identifierTypes'] as $identifier_type) {
         if ($identifier_type['id'] == $args['metal_ring_type']) {
             $options['identifierName'] = $identifier_type['term'];
             $options['identifierTypeId'] = $identifier_type['id'];
             break;
         }
     }
     $options['attrList'] = array(array('attrType' => 'idn', 'typeId' => $options['positionId'], 'lockable' => true, 'hidden' => false), array('attrType' => 'idn', 'typeId' => $options['sequenceId'], 'lockable' => false, 'hidden' => false), array('attrType' => 'iso', 'typeId' => $options['conditionsId'], 'lockable' => false, 'hidden' => false));
     $options['fieldprefix'] = 'idn:' . $taxIdx . ':metal:';
     $options['classprefix'] = 'idn-metal-';
     $options['seq_maxlength'] = !empty($args['metal_ring_max_length']) ? $args['metal_ring_max_length'] : '';
     $options['seq_maxlength'] = !empty($args['metal_ring_max_length']) ? $args['metal_ring_max_length'] : '';
     if (!empty($args['metal_ring_regex'])) {
         $options['seq_format_class'] = 'metalRingFormat';
     }
     $r .= self::get_control_identifier($auth, $args, $tabalias, $options);
     if (!empty($args['metal_ring_regex'])) {
         unset($options['seq_format_class']);
     }
     unset($options['seq_maxlength']);
     $r .= '</div>';
     // end of identifier accordion
     // other devices (trackers etc.)
     if ($options['attachmentId'] > 0 && !empty($args['other_devices']) && count($args['other_devices']) > 0) {
         // reset prefix
         $options['fieldprefix'] = 'idn:' . $taxIdx . ':';
         // filter the devices available
         $query = array('in' => array('id', $args['other_devices']));
         $filter = array('query' => json_encode($query), 'orderby' => 'sort_order');
         $extraParams = array_merge($filter, $auth['read']);
         $fieldname = $options['fieldprefix'] . 'sjoAttr:' . $options['attachmentId'];
         $default = array();
         // if this attribute exists on DB, we need to write a hidden with id appended to fieldname and set defaults for checkboxes
         if (is_array(data_entry_helper::$entity_to_load)) {
             $stored_keys = preg_grep('/^' . $fieldname . ':[0-9]+$/', array_keys(data_entry_helper::$entity_to_load));
             foreach ($stored_keys as $stored_key) {
                 $r .= '<input type="hidden" name="' . $stored_key . '" value="" />';
                 $default[] = array('fieldname' => $stored_key, 'default' => data_entry_helper::$entity_to_load[$stored_key]);
                 unset(data_entry_helper::$entity_to_load[$stored_key]);
             }
         }
         $r .= data_entry_helper::checkbox_group(array_merge(array('label' => lang::get('What other devices did you see on the bird'), 'fieldname' => $fieldname, 'table' => 'termlists_term', 'captionField' => 'term', 'valueField' => 'id', 'default' => $default, 'extraParams' => $extraParams), $options));
     }
     // subject_observation comment
     if ($args['observation_comment']) {
         $r .= self::get_control_observationcomment($auth, $args, $tabalias, $options);
     }
     $r .= '</fieldset>';
     // output identifier visualisations
     $r .= '<div id="idn:' . $taxIdx . ':neck-collar:colourbox" class="neck-collar-indentifier-colourbox ui-corner-all">&nbsp;</div>';
     $r .= '<div id="idn:' . $taxIdx . ':colour-left:colourbox" class="colour-left-indentifier-colourbox ui-corner-all">&nbsp;</div>';
     $r .= '<div id="idn:' . $taxIdx . ':colour-right:colourbox" class="colour-right-indentifier-colourbox ui-corner-all">&nbsp;</div>';
     $r .= '</div>';
     // close clearfix div
     // occurrence images
     $opts = array('table' => 'idn:' . $taxIdx . ':' . 'occurrence_image', 'label' => lang::get('Upload your photos'));
     if ($args['interface'] !== 'one_page') {
         $opts['tabDiv'] = $tabalias;
     }
     $opts['resizeWidth'] = isset($options['resizeWidth']) ? $options['resizeWidth'] : 1600;
     $opts['resizeHeight'] = isset($options['resizeHeight']) ? $options['resizeHeight'] : 1600;
     $opts['caption'] = lang::get('Photos');
     $opts['readAuth'] = $auth['read'];
     $opts['imageWidth'] = '168';
     // $opts['id'] = 'idn:0';
     if ($options['inNewIndividual']) {
         $opts['codeGenerated'] = 'php';
     }
     $r .= data_entry_helper::file_box($opts);
     // remove bird button - don't show if bird is being edited or only bird on the form
     $r .= '<input type="button" id="idn:0:remove-individual" class="idn-remove-individual" value="' . lang::get('Remove This Bird') . '" />';
     $r .= '</div>';
     // recursive call to get a template for the 'individual panel' markup for a new observation so we can add another bird
     if (!$options['inNewIndividual']) {
         $r .= '</div>';
         $temp = data_entry_helper::$entity_to_load;
         data_entry_helper::$entity_to_load = null;
         $options['inNewIndividual'] = true;
         $options['lockable'] = $options['identifiers_lockable'];
         $new_individual = self::get_control_speciesidentifier($auth, $args, $tabalias, $options);
         unset($options['lockable']);
         $opts['codeGenerated'] = 'js';
         $photoJavascript = data_entry_helper::file_box($opts);
         data_entry_helper::$entity_to_load = $temp;
         unset($options['inNewIndividual']);
         data_entry_helper::$javascript .= "window.indicia.wwt.newIndividual = '" . str_replace(array('\'', "\n"), array('\\\'', ' '), $new_individual) . "';\n";
         // save the javascript needed for an additional colour-marked individual
         // process it to sanitise the string and remove comments (works now but not 100% reliable)
         data_entry_helper::$javascript .= "window.indicia.wwt.newJavascript = '" . str_replace(array('\'', "\n"), array('\\\'', ' '), str_replace('\\', '\\\\', preg_replace('#^\\s*//.+$#m', '', $photoJavascript))) . str_replace(array('\'', "\n", "\r"), array('\\\'', ' ', ' '), str_replace('\\', '\\\\', preg_replace('#^\\s*//.+$#m', '', $autoJavascript))) . "';\n";
         $r .= '<input type="button" id="idn:add-another" class="ui-state-default ui-corner-all" ' . 'value="' . lang::get('Add Another Bird at the Same Date and Location') . '" /><br />';
     }
     return $r;
 }
 /**
  * Returns a control for picking a single species
  * @global type $indicia_templates
  * @param array $auth Read authorisation tokens
  * @param array $args Form configuration
  * @param array $extraParams Extra parameters pre-configured with taxon and taxon name type filters.
  * @param array $options additional options for the control, e.g. those configured in the form structure.
  * @return string HTML for the control.
  */
 protected static function get_control_species_single($auth, $args, $extraParams, $options)
 {
     $r = '';
     if ($args['extra_list_id'] === '' && $args['list_id'] !== '') {
         $extraParams['taxon_list_id'] = $args['list_id'];
     } elseif ($args['extra_list_id'] !== '' && $args['list_id'] === '') {
         $extraParams['taxon_list_id'] = $args['extra_list_id'];
     } elseif ($args['extra_list_id'] !== '' && $args['list_id'] !== '') {
         $extraParams['query'] = json_encode(array('in' => array('taxon_list_id' => array($args['list_id'], $args['extra_list_id']))));
     }
     if (isset($options['taxonGroupSelect']) && $options['taxonGroupSelect']) {
         $label = isset($options['taxonGroupSelectLabel']) ? $options['taxonGroupSelectLabel'] : 'Species Group';
         $helpText = isset($options['taxonGroupSelectHelpText']) ? $options['taxonGroupSelectHelpText'] : 'Choose which species group you want to pick a species from.';
         $default = '';
         if (!empty(data_entry_helper::$entity_to_load['occurrence:taxa_taxon_list_id'])) {
             // need to find the default value
             $species = data_entry_helper::get_population_data(array('table' => 'cache_taxa_taxon_list', 'extraParams' => $auth['read'] + array('id' => data_entry_helper::$entity_to_load['occurrence:taxa_taxon_list_id'])));
             data_entry_helper::$entity_to_load['taxon_group_id'] = $species[0]['taxon_group_id'];
         }
         $r .= data_entry_helper::select(array('fieldname' => 'taxon_group_id', 'id' => 'taxon_group_id', 'label' => lang::get($label), 'helpText' => lang::get($helpText), 'report' => 'library/taxon_groups/taxon_groups_used_in_checklist', 'valueField' => 'id', 'captionField' => 'title', 'extraParams' => $auth['read'] + array('taxon_list_id' => $extraParams['taxon_list_id'])));
         // update the select box to link to the species group picker. It must be a select box!
         $args['species_ctrl'] = 'select';
         $options['parentControlId'] = 'taxon_group_id';
         $options['parentControlLabel'] = lang::get($label);
         $options['filterField'] = 'taxon_group_id';
     }
     $options['speciesNameFilterMode'] = self::getSpeciesNameFilterMode($args);
     global $indicia_templates;
     $ctrl = $args['species_ctrl'] === 'autocomplete' ? 'species_autocomplete' : $args['species_ctrl'];
     $species_ctrl_opts = array_merge(array('fieldname' => 'occurrence:taxa_taxon_list_id', 'label' => lang::get('occurrence:taxa_taxon_list_id'), 'columns' => 2, 'parentField' => 'parent_id', 'blankText' => lang::get('Please select'), 'cacheLookup' => $args['cache_lookup']), $options);
     if (isset($species_ctrl_opts['extraParams'])) {
         $species_ctrl_opts['extraParams'] = array_merge($extraParams, $species_ctrl_opts['extraParams']);
     } else {
         $species_ctrl_opts['extraParams'] = $extraParams;
     }
     if (!empty($args['taxon_filter'])) {
         $species_ctrl_opts['taxonFilterField'] = $args['taxon_filter_field'];
         // applies to autocompletes
         $species_ctrl_opts['taxonFilter'] = helper_base::explode_lines($args['taxon_filter']);
         // applies to autocompletes
     }
     // obtain table to query and hence fields to use
     $db = data_entry_helper::get_species_lookup_db_definition($args['cache_lookup']);
     // get local vars for the array
     extract($db);
     if ($ctrl !== 'species_autocomplete') {
         // The species autocomplete has built in support for the species name filter.
         // For other controls we need to apply the species name filter to the params used for population
         if (!empty($species_ctrl_opts['taxonFilter']) || $options['speciesNameFilterMode']) {
             $species_ctrl_opts['extraParams'] = array_merge($species_ctrl_opts['extraParams'], data_entry_helper::get_species_names_filter($species_ctrl_opts));
         }
         // for controls which don't know how to do the lookup, we need to tell them
         $species_ctrl_opts = array_merge(array('table' => $tblTaxon, 'captionField' => $colTaxon, 'valueField' => $colId), $species_ctrl_opts);
     }
     // if using something other than an autocomplete, then set the caption template to include the appropriate names. Autocompletes
     // use a JS function instead.
     if ($ctrl !== 'autocomplete' && isset($args['species_include_both_names']) && $args['species_include_both_names']) {
         if ($args['species_names_filter'] === 'all') {
             $indicia_templates['species_caption'] = "{{$colTaxon}}";
         } elseif ($args['species_names_filter'] === 'language') {
             $indicia_templates['species_caption'] = "{{$colTaxon}} - {{$colPreferred}}";
         } else {
             $indicia_templates['species_caption'] = "{{$colTaxon}} - {{$colCommon}}";
         }
         $species_ctrl_opts['captionTemplate'] = 'species_caption';
     }
     if ($ctrl == 'tree_browser') {
         // change the node template to include images
         $indicia_templates['tree_browser_node'] = '<div>' . '<img src="' . data_entry_helper::$base_url . '/upload/thumb-{image_path}" alt="Image of {caption}" width="80" /></div>' . '<span>{caption}</span>';
     }
     // Dynamically generate the species selection control required.
     $r .= call_user_func(array('data_entry_helper', $ctrl), $species_ctrl_opts);
     return $r;
 }
Пример #5
0
 /**
  * Performs the sending of invitation emails.
  * @param array $args Form configuration arguments
  * @param array $auth Authorisation tokens
  * @todo Integrate with notifications for logged in users.
  */
 private static function sendInvites($args, $auth)
 {
     $emails = helper_base::explode_lines($_POST['invitee_emails']);
     // first task is to populate the groups_invitations table
     $base = uniqid();
     $success = true;
     $failedRecipients = array();
     foreach ($emails as $idx => $email) {
         $values = array('group_invitation:group_id' => $_GET['group_id'], 'group_invitation:email' => $email, 'group_invitation:token' => $base . $idx, 'website_id' => $args['website_id']);
         $s = submission_builder::build_submission($values, array('model' => 'group_invitation'));
         $r = data_entry_helper::forward_post_to('group_invitation', $s, $auth['write_tokens']);
         $pathParam = function_exists('variable_get') && variable_get('clean_url', 0) == '0' ? 'q' : '';
         $rootFolder = data_entry_helper::getRootFolder() . (empty($pathParam) ? '' : "?{$pathParam}=");
         $protocol = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' || $_SERVER['SERVER_PORT'] == 443 ? "https://" : "http://";
         $acceptUrl = $protocol . $_SERVER['HTTP_HOST'] . $rootFolder . $args['accept_invite_path'] . (empty($pathParam) ? '?' : '&') . 'token=' . $base . $idx;
         $body = $_POST['invite_message'] . "<br/><br/>" . '<a href="' . $acceptUrl . '">' . lang::get('Accept this invitation') . '</a>';
         $message = array('id' => 'iform_group_invite', 'to' => implode(',', $emails), 'subject' => 'Invitation to join a recording group', 'body' => $body, 'headers' => array('MIME-Version' => '1.0', 'Content-type' => 'text/html; charset=iso-8859-1'));
         $mimeheaders = array();
         foreach ($message['headers'] as $name => $value) {
             $mimeheaders[] = $name . ': ' . mime_header_encode($value);
         }
         $thismailsuccess = mail($message['to'], mime_header_encode($message['subject']), str_replace("\r", '', $message['body']), join("\n", $mimeheaders));
         if (!$thismailsuccess) {
             $failedRecipients[$message['to']] = $acceptUrl;
         }
         $success = $success && $thismailsuccess;
     }
     if ($success) {
         drupal_set_message(lang::get('Invitation emails sent'));
     } else {
         drupal_set_message(lang::get('The emails could not be sent due to a server configuration issue. Please contact the site admin. ' . 'The list below gives the emails and the links you need to send to each invitee which they need to click on in order to join the group.'), 'warning');
         $list = array();
         foreach ($failedRecipients as $email => $link) {
             $list[] = lang::get("Send link {1} to {2}.", $link, $email);
         }
         drupal_set_message(implode('<br/>', $list), 'warning');
     }
     drupal_goto($args['redirect_on_success']);
 }
Пример #6
0
 /**
  * Finds the list of all tab names that are going to be required, either by the form
  * structure, or by custom attributes.
  */
 protected static function get_all_tabs($structure, $attrTabs)
 {
     $structureArr = helper_base::explode_lines($structure);
     $structureTabs = array();
     // A default 'tab' for content that must appear above the set of tabs.
     $currentTab = '-';
     foreach ($structureArr as $component) {
         if (preg_match('/^=[A-Za-z0-9, \'\\-\\*\\?]+=$/', trim($component), $matches) === 1) {
             $currentTab = substr($matches[0], 1, -1);
             $structureTabs[$currentTab] = array();
         } else {
             $structureTabs[$currentTab][] = $component;
         }
     }
     // If any additional tabs are required by attributes, add them to the position marked by a dummy tab named [*].
     // First get rid of any tabs already in the structure
     foreach ($attrTabs as $tab => $tabContent) {
         // case -insensitive check if attribute tab already in form structure
         if (in_array(strtolower($tab), array_map('strtolower', array_keys($structureTabs)))) {
             unset($attrTabs[$tab]);
         }
     }
     // Now we have a list of form structure tabs, with the position of the $attrTabs marked by *. So join it all together.
     // Maybe there is a better way to do this?
     $allTabs = array();
     foreach ($structureTabs as $tab => $tabContent) {
         if ($tab == '*') {
             $allTabs += $attrTabs;
         } else {
             $allTabs[$tab] = $tabContent;
         }
     }
     return $allTabs;
 }
 /**
  * Finds a record cleaner server index page and returns the list of files it refers to.
  */
 private function fetch_server_file_list($server)
 {
     // as redirections cause a recursion, let's set a limit
     static $curl_loops = 0;
     static $curl_max_loops = 20;
     if ($curl_loops++ >= $curl_max_loops) {
         $curl_loops = 0;
         throw new exception("cUrl request to {$server} resulted in too many redirections");
     }
     $session = curl_init($server);
     curl_setopt($session, CURLOPT_HEADER, true);
     curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($session, CURLOPT_SSL_VERIFYPEER, false);
     $files = array();
     $response = curl_exec($session);
     if (curl_errno($session)) {
         kohana::log('error', 'cUrl error : ' . curl_errno($session));
         kohana::log('error', 'cUrl message : ' . curl_error($session));
         throw new exception("cUrl request to {$server} failed");
     }
     $http_code = curl_getinfo($session, CURLINFO_HTTP_CODE);
     // did we get a redirect response?
     if ($http_code == 301 || $http_code == 302) {
         // find the redirect location in the response
         preg_match('/Location:(.*?)\\n/', $response, $matches);
         $url = @parse_url(trim(array_pop($matches)));
         if (!$url) {
             throw new exception("Redirect from {$server} failed");
         }
         $last_url = parse_url(curl_getinfo($session, CURLINFO_EFFECTIVE_URL));
         if (!$url['scheme']) {
             $url['scheme'] = $last_url['scheme'];
         }
         if (!$url['host']) {
             $url['host'] = $last_url['host'];
         }
         if (!$url['path']) {
             $url['path'] = $last_url['path'];
         }
         $newUrl = $url['scheme'] . '://' . $url['host'] . $url['path'] . (isset($url['query']) ? '?' . $url['query'] : '');
         return self::fetch_server_file_list($newUrl);
     }
     list($header, $data) = explode("\r\n\r\n", $response, 2);
     foreach (helper_base::explode_lines($data) as $line) {
         $tokens = explode('#', $line);
         $files[] = array('file' => $tokens[0], 'title' => $tokens[1], 'date' => $tokens[2]);
     }
     return $files;
 }
Пример #8
0
 /**
  * Parses a data cleaner verification rule test file into an array of sections, 
  * each contining an array of key value pairs.
  * Very similar to PHP's parse_ini_string but a bit more tolerant, e.g of comments used.
  * @param type $content Content of the verification rule test file.
  * @return array File structure array.
  */
 public static function parse_test_file($content)
 {
     // break into lines, tolerating different line ending forms;
     $lines = helper_base::explode_lines($content);
     $currentSection = '';
     $currentSectionData = array();
     $r = array();
     foreach ($lines as $line) {
         $line = trim($line);
         // skip comments and blank lines plus the end of the metadata section
         if (substr($line, 1) === ';' || empty($line) || $line === '[EndMetadata]') {
             continue;
         }
         if (preg_match('/^\\[(?P<section>.+)\\]$/', $line, $matches)) {
             if (!empty($currentSectionData)) {
                 $r[$currentSection] = $currentSectionData;
             }
             // reset for the next section
             $currentSection = trim(strtolower($matches['section']));
             $currentSectionData = array();
         } elseif (preg_match('/^([^=\\r\\n]+)=([^\\r\\n]*)$/', $line, $matches)) {
             $currentSectionData[trim(strtolower($matches[1]))] = trim($matches[2]);
         } elseif (preg_match('/^(?P<key>.+)$/', $line, $matches)) {
             $currentSectionData[trim(strtolower($matches['key']))] = '-';
         }
     }
     // set the final section content
     if (!empty($currentSectionData)) {
         $r[$currentSection] = $currentSectionData;
     }
     return $r;
 }
 /**
  * The species filter can be taken from the edit tab or overridden by a URL
  * filter. This method determines the filter to be used.
  * @param array $args Form arguments
  * @return array List of items to filter against, e.g. species names or
  * meaning IDs.
  */
 protected static function get_species_filter($args)
 {
     // we must have a filter field specified in order to apply a filter
     if (!empty($args['taxon_filter_field'])) {
         // if URL params are enabled and we have one, then this is the top
         // priority filter to apply
         if (!empty($_GET['taxon']) && $args['use_url_taxon_parameter']) {
             // convert commas to newline, so url provided filters are the same
             // format as those on the edit tab, also allowing for url encoding.
             return explode(',', urldecode($_GET['taxon']));
         } elseif (!empty($args['taxon_filter'])) {
             // filter is provided on the edit tab
             return helper_base::explode_lines($args['taxon_filter']);
         }
     }
     // default - no filter to apply
     return array();
 }
 /**
  * Returns the species checklist input control.
  * @param array $auth Read authorisation tokens
  * @param array $args Form configuration
  * @param array $extraParams Extra parameters array, pre-configured with filters for taxa and name types.
  * @param array $options additional options for the control, e.g. those configured in the form structure.
  * @return HTML for the species_checklist control.
  */
 protected static function get_control_species_checklist($auth, $args, $extraParams, $options)
 {
     global $user;
     // Build the configuration options
     if (isset($options['view'])) {
         $extraParams['view'] = $options['view'];
     }
     // make sure that if extraParams is specified as a config option, it does not replace the essential stuff
     if (isset($options['extraParams'])) {
         $options['extraParams'] = array_merge($extraParams, $options['extraParams']);
     }
     $species_ctrl_opts = array_merge(array('occAttrOptions' => array(), 'listId' => '', 'label' => lang::get('occurrence:taxa_taxon_list_id'), 'columns' => 1, 'extraParams' => $extraParams, 'survey_id' => $args['survey_id'], 'occurrenceComment' => $args['occurrence_comment'], 'occurrenceSensitivity' => isset($args['occurrence_sensitivity']) ? $args['occurrence_sensitivity'] : false, 'occurrenceImages' => $args['occurrence_images'], 'PHPtaxonLabel' => true, 'language' => iform_lang_iso_639_2(hostsite_get_user_field('language')), 'cacheLookup' => $args['cache_lookup'], 'speciesNameFilterMode' => self::getSpeciesNameFilterMode($args), 'userControlsTaxonFilter' => false, 'subSpeciesColumn' => false, 'copyDataFromPreviousRow' => false, 'editTaxaNames' => !empty($args['edit_taxa_names']) && $args['edit_taxa_names']), $options);
     if ($groups = hostsite_get_user_field('taxon_groups')) {
         $species_ctrl_opts['usersPreferredGroups'] = unserialize($groups);
     }
     if ($args['map_taxon_list_id']) {
         $species_ctrl_opts['lookupListId'] = $args['map_taxon_list_id'];
     }
     //We only do the work to setup the filter if the user has specified a filter in the box
     if (!empty($args['map_taxon_filter_field']) && !empty($args['map_taxon_filter'])) {
         $species_ctrl_opts['taxonFilterField'] = $args['map_taxon_filter_field'];
         $filterLines = helper_base::explode_lines($args['map_taxon_filter']);
         $species_ctrl_opts['taxonFilter'] = $filterLines;
     }
     if (isset($args['col_widths']) && $args['col_widths']) {
         $species_ctrl_opts['colWidths'] = explode(',', $args['col_widths']);
     }
     self::build_grid_taxon_label_function($args, $options);
     // Start by outputting a hidden value that tells us we are using a grid when the data is posted,
     // then output the grid control
     return '<input type="hidden" value="true" name="gridmode" />' . data_entry_helper::species_checklist($species_ctrl_opts);
 }
 /**
  * Returns the species checklist input control.
  * @param array $auth Read authorisation tokens
  * @param array $args Form configuration
  * @param array $extraParams Extra parameters array, pre-configured with filters for taxa and name types.
  * @param array $options additional options for the control, e.g. those configured in the form structure.
  * @return HTML for the species_checklist control.
  * Again, this is an altered copy of the one found in dynamic_sample_occurrence with support for preloading a species grid with sample images from second level samples
  * and then loading it with occurrence images attached to occurrences which are attached to third level samples.
  * May contain coded that is not needed and can be removed if possible
  */
 protected static function get_control_species_checklist($auth, $args, $extraParams, $options)
 {
     global $user;
     // Build the configuration options
     if (isset($options['view'])) {
         $extraParams['view'] = $options['view'];
     }
     // There may be options in the form occAttr:n|param => value targetted at specific attributes
     $occAttrOptions = array();
     $optionToUnset = array();
     foreach ($options as $option => $value) {
         // split the id of the option into the attribute name and option name.
         $optionParts = explode('|', $option);
         if ($optionParts[0] != $option) {
             // an occurrence attribute option was found
             $attrName = $optionParts[0];
             $optName = $optionParts[1];
             // split the attribute name into the type and id (type will always be occAttr)
             $attrParts = explode(':', $attrName);
             $attrId = $attrParts[1];
             if (!isset($occAttrOptions[$attrId])) {
                 $occAttrOptions[$attrId] = array();
             }
             $occAttrOptions[$attrId][$optName] = apply_user_replacements($value);
             $optionToUnset[] = $option;
         }
     }
     // tidy up options array
     foreach ($optionToUnset as $value) {
         unset($options[$value]);
     }
     // make sure that if extraParams is specified as a config option, it does not replace the essential stuff
     if (isset($options['extraParams'])) {
         $options['extraParams'] = array_merge($extraParams, $options['extraParams']);
     }
     $species_ctrl_opts = array_merge(array('occAttrOptions' => $occAttrOptions, 'listId' => $args['list_id'], 'label' => lang::get('occurrence:taxa_taxon_list_id'), 'columns' => 1, 'extraParams' => $extraParams, 'survey_id' => $args['survey_id'], 'occurrenceComment' => $args['occurrence_comment'], 'occurrenceSensitivity' => isset($args['occurrence_sensitivity']) ? $args['occurrence_sensitivity'] : false, 'occurrenceImages' => $args['occurrence_images'], 'PHPtaxonLabel' => true, 'language' => iform_lang_iso_639_2(hostsite_get_user_field('language')), 'cacheLookup' => $args['cache_lookup'], 'speciesNameFilterMode' => self::getSpeciesNameFilterMode($args), 'userControlsTaxonFilter' => isset($args['user_controls_taxon_filter']) ? $args['user_controls_taxon_filter'] : false, 'subSpeciesColumn' => $args['sub_species_column'], 'copyDataFromPreviousRow' => !empty($args['copy_species_row_data_to_new_rows']) && $args['copy_species_row_data_to_new_rows'], 'previousRowColumnsToInclude' => empty($args['previous_row_columns_to_include']) ? '' : $args['previous_row_columns_to_include'], 'editTaxaNames' => !empty($args['edit_taxa_names']) && $args['edit_taxa_names'], 'includeSpeciesGridLinkPage' => !empty($args['include_species_grid_link_page']) && $args['include_species_grid_link_page'], 'speciesGridPageLinkUrl' => $args['species_grid_page_link_url'], 'speciesGridPageLinkParameter' => $args['species_grid_page_link_parameter'], 'speciesGridPageLinkTooltip' => $args['species_grid_page_link_tooltip']), $options);
     if ($groups = hostsite_get_user_field('taxon_groups')) {
         $species_ctrl_opts['usersPreferredGroups'] = unserialize($groups);
     }
     if ($args['extra_list_id']) {
         $species_ctrl_opts['lookupListId'] = $args['extra_list_id'];
     }
     //We only do the work to setup the filter if the user has specified a filter in the box
     if (!empty($args['taxon_filter_field']) && !empty($args['taxon_filter'])) {
         $species_ctrl_opts['taxonFilterField'] = $args['taxon_filter_field'];
         $filterLines = helper_base::explode_lines($args['taxon_filter']);
         $species_ctrl_opts['taxonFilter'] = $filterLines;
     }
     if (isset($args['col_widths']) && $args['col_widths']) {
         $species_ctrl_opts['colWidths'] = explode(',', $args['col_widths']);
     }
     call_user_func(array(self::$called_class, 'build_grid_taxon_label_function'), $args, $options);
     if (self::$mode == self::MODE_CLONE) {
         $species_ctrl_opts['useLoadedExistingRecords'] = true;
     }
     return self::species_checklist($species_ctrl_opts);
 }
Пример #12
0
 /**
  * Draw the Species Details section of the page.
  * @return string The output html string.
  * 
  * @package    Client
  * @subpackage PrebuiltForms
  */
 protected static function get_control_speciesdetails($auth, $args, $tabalias, $options)
 {
     $fields = helper_base::explode_lines($args['fields']);
     $fieldsLower = helper_base::explode_lines(strtolower($args['fields']));
     //If the user sets the option to exclude particular fields then we set to the hide flag
     //on the name types they have specified.
     if ($args['operator'] == 'not in') {
         $hidePreferred = false;
         $hideCommon = false;
         $hideSynonym = false;
         $hideTaxonomy = false;
         foreach ($fieldsLower as $theField) {
             if ($theField == 'preferred names' || $theField == 'preferred name' || $theField == 'preferred') {
                 $hidePreferred = true;
             } elseif ($theField == 'common names' || $theField == 'common name' || $theField == 'common') {
                 $hideCommon = true;
             } elseif ($theField == 'synonym names' || $theField == 'synonym name' || $theField == 'synonym') {
                 $hideSynonym = true;
             } elseif ($theField == 'taxonomy') {
                 $hideTaxonomy = true;
             }
         }
     }
     //If the user sets the option to only include particular fields then we set to the hide flag
     //to true unless they have specified the name type.
     if ($args['operator'] == 'in') {
         $hidePreferred = true;
         $hideCommon = true;
         $hideSynonym = true;
         $hideTaxonomy = true;
         foreach ($fieldsLower as $theField) {
             if ($theField == 'preferred names' || $theField == 'preferred name' || $theField == 'preferred') {
                 $hidePreferred = false;
             } elseif ($theField == 'common names' || $theField == 'common name' || $theField == 'common') {
                 $hideCommon = false;
             } elseif ($theField == 'synonym names' || $theField == 'synonym name' || $theField == 'synonym') {
                 $hideSynonym = false;
             } elseif ($theField == 'taxonomy') {
                 $hideTaxonomy = true;
             }
         }
     }
     //Draw the names on the page
     $details_report = self::draw_names($auth['read'], $hidePreferred, $hideCommon, $hideSynonym, $hideTaxonomy);
     $attrsTemplate = '<div class="field ui-helper-clearfix"><span>{caption}:</span><span>{value}</span></div>';
     //draw any custom attributes for the species added by the user
     $attrs_report = report_helper::freeform_report(array('readAuth' => $auth['read'], 'class' => 'species-details-fields', 'dataSource' => 'library/taxa/taxon_attributes_with_hiddens', 'bands' => array(array('content' => $attrsTemplate)), 'extraParams' => array('taxa_taxon_list_id' => self::$taxa_taxon_list_id, 'attrs' => strtolower(self::convert_array_to_set($fields)), 'testagainst' => $args['testagainst'], 'operator' => $args['operator'], 'sharing' => 'reporting')));
     $r = '<div class="detail-panel" id="detail-panel-speciesdetails"><h3>' . lang::get('Species Details') . '</h3><div class="record-details-fields ui-helper-clearfix">';
     //draw the species names and custom attributes
     if (isset($details_report)) {
         $r .= $details_report;
     }
     if (isset($attrs_report)) {
         $r .= $attrs_report;
     }
     $r .= '</div></div>';
     return $r;
 }
Пример #13
0
/**
 * Retreives the options array required to set up a report according to the default
 * report parameters.
 * @global <type> $indicia_templates
 * @param string $args
 * @param <type> $readAuth
 * @return string
 */
function iform_report_get_report_options($args, $readAuth)
{
    // handle auto_params_form for backwards compatibility
    if (empty($args['output']) && !empty($args['auto_params_form'])) {
        if (!$args['auto_params_form']) {
            $args['output'] = 'output';
        }
    }
    if (isset($args['map_toolbar_pos']) && $args['map_toolbar_pos'] == 'map') {
        // report params cannot go in the map toolbar if displayed as overlay on map
        $args['params_in_map_toolbar'] = false;
    }
    $r = '';
    require_once 'user.php';
    $presets = get_options_array_with_user_data($args['param_presets']);
    $defaults = get_options_array_with_user_data($args['param_defaults']);
    $ignores = isset($args['param_ignores']) ? helper_base::explode_lines($args['param_ignores']) : array();
    $param_lookup_extras = array();
    if (isset($args['param_lookup_extras'])) {
        $paramlx = helper_base::explode_lines($args['param_lookup_extras']);
        foreach ($paramlx as $param) {
            if (!empty($param)) {
                $tokens = explode(':', $param, 2);
                if (count($tokens) == 2) {
                    $tokens2 = explode('=', $tokens[1], 2);
                    if (count($tokens2) == 2) {
                        if (!isset($param_lookup_extras[$tokens[0]])) {
                            $param_lookup_extras[$tokens[0]] = array();
                        }
                        $param_lookup_extras[$tokens[0]][$tokens2[0]] = explode(',', $tokens2[1]);
                    } else {
                        throw new Exception('One of the param_lookup_extras defined for this page are not of the form key:param=value[,value...] : ' . $param . '. (No equals)');
                    }
                } else {
                    throw new Exception('One of the param_lookup_extras defined for this page are not of the form key:param=value[,value...] : ' . $param . '. (No colon)');
                }
            }
        }
    } else {
        $param_lookup_extras = array();
    }
    // default columns behaviour is to just include anything returned by the report
    $columns = array();
    // this can be overridden
    if (isset($args['columns_config']) && !empty($args['columns_config'])) {
        $columns = json_decode($args['columns_config'], true);
    }
    // do the form arguments request that certain columns are globally skipped?
    if (!empty($args['skipped_report_columns'])) {
        // look for configured columns that should be skipped
        foreach ($columns as &$column) {
            if (array_key_exists($column['fieldname'], $args['skipped_report_columns'])) {
                $column['visible'] = false;
                unset($args['skipped_report_columns']);
            }
        }
        // add configurations to hide any remaining columns that should be skipped
        foreach ($args['skipped_report_columns'] as $fieldname) {
            $columns[] = array('fieldname' => $fieldname, 'visible' => false);
        }
    }
    $reportOptions = array('id' => 'report-grid', 'reportGroup' => isset($args['report_group']) ? $args['report_group'] : '', 'rememberParamsReportGroup' => isset($args['remember_params_report_group']) ? $args['remember_params_report_group'] : '', 'dataSource' => isset($args['report_name']) ? $args['report_name'] : '', 'mode' => 'report', 'readAuth' => $readAuth, 'columns' => $columns, 'itemsPerPage' => empty($args['items_per_page']) ? 20 : $args['items_per_page'], 'extraParams' => $presets, 'paramDefaults' => $defaults, 'ignoreParams' => $ignores, 'param_lookup_extras' => $param_lookup_extras, 'galleryColCount' => isset($args['gallery_col_count']) ? $args['gallery_col_count'] : 1, 'headers' => isset($args['gallery_col_count']) && $args['gallery_col_count'] > 1 ? false : true, 'paramsInMapToolbar' => isset($args['params_in_map_toolbar']) ? $args['params_in_map_toolbar'] : false);
    // put each param control in a div, which makes it easier to layout with CSS
    if (!isset($args['params_in_map_toolbar']) || !$args['params_in_map_toolbar']) {
        $reportOptions['paramPrefix'] = '<div id="container-{fieldname}" class="param-container">';
        $reportOptions['paramSuffix'] = '</div>';
    }
    // If in Drupal, allow the params panel to collapse.
    if (function_exists('drupal_add_js')) {
        if (function_exists('hostsite_add_library') && (!defined('DRUPAL_CORE_COMPATIBILITY') || DRUPAL_CORE_COMPATIBILITY !== '7.x')) {
            hostsite_add_library('collapse');
            $reportOptions['fieldsetClass'] = 'collapsible';
        }
    }
    if (empty($args['output']) || $args['output'] == 'default') {
        $reportOptions['autoParamsForm'] = true;
    } elseif ($args['output'] == 'form') {
        $reportOptions['autoParamsForm'] = true;
        $reportOptions['paramsOnly'] = true;
    } else {
        $reportOptions['autoParamsForm'] = false;
    }
    if (!empty($args['row_class'])) {
        $reportOptions['rowClass'] = $args['row_class'];
    }
    // Set up a page refresh for dynamic update of the report at set intervals
    if (isset($args['refresh_timer']) && $args['refresh_timer'] !== 0 && is_numeric($args['refresh_timer'])) {
        // is_numeric prevents injection
        if (isset($args['load_on_refresh']) && !empty($args['load_on_refresh'])) {
            report_helper::$javascript .= "setTimeout('window.location=\"" . $args['load_on_refresh'] . "\";', " . $args['refresh_timer'] . "*1000 );\n";
        } else {
            report_helper::$javascript .= "setTimeout('window.location.reload( false );', " . $args['refresh_timer'] . "*1000 );\n";
        }
    }
    return $reportOptions;
}
Пример #14
0
 private static function get_site_trees_tab($auth, $args, $settings)
 {
     global $indicia_templates;
     $r = '<div id="site-trees" class="ui-helper-clearfix">';
     $r .= '<form method="post" id="tree-form" action="' . self::$ajaxFormUrl . '">';
     $help = '<p>' . lang::get('To add a tree, click on the "Add Tree" button. You can then use the map\'s Location Tool to select the approximate location of your tree on the map. A new tree will then appear on the map.') . '</p>' . '<p>' . lang::get('To select a tree from the existing list of trees at this site you can either:') . '</p>' . '<ol><li>' . lang::get('Click on the button for the tree you wish to view, or') . '</li>' . '<li>' . lang::get('Use the map\'s Query Tool to click on the tree you wish to view on the map.') . '</li></ol>' . '<p>' . lang::get('To remove a tree, first select the tree you wish to remove, then click on the "Remove Tree" button. It will remove the current tree you are viewing completely.') . '</p>';
     $r .= '<div class="ui-state-highlight page-notice ui-corner-all">' . $help . '</div>';
     $r .= self::tree_selector($settings);
     $r .= '<input type="button" value="' . lang::get('Remove Tree') . '" class="remove-tree form-button right" title="' . lang::get('Completely remove the highlighted tree. The total number of tree will be reduced by one. The form will be reloaded after the tree is deleted.') . '">';
     $r .= '<input type="button" value="' . lang::get('Add Tree') . '" class="insert-tree form-button right" title="' . lang::get('This inserts an extra tree.') . '">';
     $r .= '<div id="cols" class="ui-helper-clearfix"><div class="left" style="width: ' . (98 - (isset($args['percent_width']) ? $args['percent_width'] : 50)) . '%">';
     $r .= '<fieldset><legend>' . lang::get('Tree Details') . '</legend>';
     $r .= '<input type="hidden" name="location:id" value="" id="tree-location-id" />';
     $r .= '<input type="hidden" name="locations_website:website_id" value="' . $args['website_id'] . '" id="locations-website-website-id" />';
     $r .= '<input type="hidden" name="location:parent_id" value="' . $settings['locationId'] . '" />';
     $r .= '<input type="hidden" name="location:location_type_id" value="' . $settings['TreeLocationType'][0]['id'] . '" />';
     $r .= '<input type="hidden" name="website_id" value="' . $args['website_id'] . "\" />\n";
     $r .= data_entry_helper::text_input(array('fieldname' => 'location:name', 'label' => lang::get('Tree ID'), 'class' => 'control-width-4 required'));
     $systems = array();
     $list = explode(',', str_replace(' ', '', $args['spatial_systems']));
     foreach ($list as $system) {
         $systems[$system] = lang::get($system);
     }
     $srefOptions = array('id' => 'imp-sref-tree', 'fieldname' => 'location:centroid_sref', 'geomid' => 'imp-geom-tree', 'geomFieldname' => 'location:centroid_geom', 'label' => 'Grid Ref', 'labelClass' => 'auto', 'class' => 'required', 'helpText' => lang::get('You can also click on the map to set the grid reference. If directly entering the coordinates from a GPS device, set the format to "Lat/Long" first. To enter an OS Grid square, choose the "OSGB" or "OSIE" formats.'));
     data_entry_helper::$javascript .= "\n\$('#imp-sref-tree').attr('title',\n    '" . lang::get("When directly entering coordinates as a GPS Lat/Long reading, there should be no spaces between the numbers and the letter. " . "The degrees, minutes and seconds must all be separated by a colon (:). The direction letter can be placed at the start or the end of the number (e.g. N56.532 or 56.532N). " . "The figures may be entered as decimal degrees (e.g. 56.532), degrees and decimal minutes (e.g. 56:31.92), or degrees, minutes and decimal seconds (e.g. 56:31:55.2). " . "You can mix the formats of the Latitude and Longitude, provided they each follow the previous guidelines and a space separates them (e.g. N56.532 2:30W).") . "  " . lang::get("When directly entering an OS map reference, there should be no spaces between any of the characters. " . "An OSGB reference should comprise of 2 letters followed by an even number of digits (e.g. NT274628). " . "An OSIE reference should comprise of of 1 letter followed by an even number of digits (e.g. J081880).") . "');\n";
     // Output the sref control
     $r .= data_entry_helper::sref_textbox($srefOptions);
     $srefOptions = array('id' => 'imp-sref-system-tree', 'fieldname' => 'location:centroid_sref_system', 'class' => 'required', 'systems' => $systems);
     // Output the system control
     if (count($systems) < 2) {
         // Hidden field for the system
         $keys = array_keys($options['systems']);
         $r .= "<input type=\"hidden\" id=\"imp-sref-system-tree\" name=\"" . $options['fieldname'] . "\" value=\"" . $keys[0] . "\" />\n";
         // TODO    	self::include_sref_handler_js($options['systems']);
     } else {
         $r .= data_entry_helper::sref_system_select($srefOptions);
     }
     $r .= '<input type="hidden" name="survey_id" value="' . $args['survey_id'] . '" />';
     $r .= '<input type="hidden" name="sample:survey_id" value="' . $args['survey_id'] . '" />';
     $r .= '<input type="hidden" name="sample:id" value="" />';
     // this sample will reference the location id.
     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
         // @todo The date format should be a global configurable option. It should also be applied to reloading of custom date attributes.
         $d = new DateTime(data_entry_helper::$entity_to_load['sample:date']);
         data_entry_helper::$entity_to_load['sample:date'] = $d->format('d/m/Y');
     }
     $r .= data_entry_helper::date_picker(array('label' => lang::get('Date Tree Selected'), 'fieldname' => 'sample:date', 'class' => 'control-width-2 required'));
     $r .= '<input type="hidden" id="sample:sample_method_id" value="' . $settings['treeSampleMethod']['id'] . '" name="sample:sample_method_id">';
     $r .= '<input type="hidden" id="sample:location_name" value="" name="sample:location_name">';
     $r .= '<input type="hidden" name="occurrence:id" value="" id="occurrence:id" />';
     $r .= '<input type="hidden" name="occurrence:record_status" value="C" id="occurrence:record_status" />';
     $extraParams = $auth['read'];
     $extraParams['taxon_list_id'] = $args['taxon_list_id'];
     $options = array('speciesNameFilterMode' => $args['speciesNameFilterMode']);
     $ctrl = $args['species_ctrl'];
     $species_ctrl_opts = array_merge(array('fieldname' => 'occurrence:taxa_taxon_list_id', 'label' => lang::get('Tree Species'), 'columns' => 1, 'parentField' => 'parent_id', 'blankText' => lang::get('Please select'), 'cacheLookup' => false), $options);
     if (isset($species_ctrl_opts['extraParams'])) {
         $species_ctrl_opts['extraParams'] = array_merge($extraParams, $species_ctrl_opts['extraParams']);
     } else {
         $species_ctrl_opts['extraParams'] = $extraParams;
     }
     if (!empty($args['taxon_filter'])) {
         $species_ctrl_opts['taxonFilterField'] = $args['taxon_filter_field'];
         // applies to autocompletes
         $species_ctrl_opts['taxonFilter'] = helper_base::explode_lines($args['taxon_filter']);
         // applies to autocompletes
     }
     // obtain table to query and hence fields to use
     $db = data_entry_helper::get_species_lookup_db_definition(false);
     // get local vars for the array
     extract($db);
     if ($ctrl !== 'species_autocomplete') {
         // The species autocomplete has built in support for the species name filter.
         // For other controls we need to apply the species name filter to the params used for population
         if (!empty($species_ctrl_opts['taxonFilter']) || $options['speciesNameFilterMode']) {
             $species_ctrl_opts['extraParams'] = array_merge($species_ctrl_opts['extraParams'], data_entry_helper::get_species_names_filter($species_ctrl_opts));
         }
         // for controls which don't know how to do the lookup, we need to tell them
         $species_ctrl_opts = array_merge(array('table' => $tblTaxon, 'captionField' => $colTaxon, 'valueField' => $colId), $species_ctrl_opts);
     }
     // if using something other than an autocomplete, then set the caption template to include the appropriate names. Autocompletes
     // use a JS function instead.
     if ($ctrl !== 'autocomplete' && isset($args['species_include_both_names']) && $args['species_include_both_names']) {
         if ($args['speciesNameFilterMode'] === 'all') {
             $indicia_templates['species_caption'] = "{{$colTaxon}}";
         } elseif ($args['speciesNameFilterMode'] === 'language') {
             $indicia_templates['species_caption'] = "{{$colTaxon}} - {{$colPreferred}}";
         } else {
             $indicia_templates['species_caption'] = "{{$colTaxon}} - {{$colCommon}}";
         }
         $species_ctrl_opts['captionTemplate'] = 'species_caption';
     }
     if ($ctrl == 'tree_browser') {
         // change the node template to include images
         $indicia_templates['tree_browser_node'] = '<div>' . '<img src="' . data_entry_helper::$base_url . '/upload/thumb-{image_path}" alt="Image of {caption}" width="80" /></div>' . '<span>{caption}</span>';
     }
     // Dynamically generate the species selection control required.
     $r .= call_user_func(array('data_entry_helper', $ctrl), $species_ctrl_opts);
     $ctrlOptions = array('extraParams' => $auth['read']);
     $attrSpecificOptions = array();
     $options = helper_base::explode_lines_key_value_pairs($args['attrOptions']);
     self::parseForAttrSpecificOptions($options, $ctrlOptions, $attrSpecificOptions);
     $r .= get_attribute_html($settings['tree_attributes'], $args, $ctrlOptions, '', $attrSpecificOptions);
     $r .= '</fieldset>';
     $r .= "</div>" . '<div class="right" style="width: ' . (isset($args['percent_width']) ? $args['percent_width'] : 50) . '%">';
     $olOptions = iform_map_get_ol_options($args);
     $options = iform_map_get_map_options($args, $auth['read']);
     $options['divId'] = 'trees-map';
     $options['toolbarDiv'] = 'top';
     $options['tabDiv'] = 'site-trees';
     $options['gridRefHint'] = true;
     $options['latLongFormat'] = 'DMS';
     // TODO drive from args or user.
     if (array_key_exists('standard_controls_trees', $args) && $args['standard_controls_trees']) {
         $standard_controls_trees = str_replace("\r\n", "\n", $args['standard_controls_trees']);
         $options['standardControls'] = explode("\n", $standard_controls_trees);
         // If drawing controls are enabled, then allow polygon recording.
         if (in_array('drawPolygon', $options['standardControls']) || in_array('drawLine', $options['standardControls'])) {
             $options['allowPolygonRecording'] = true;
         }
     }
     // also let the user click on a feature to select it. The highlighter just makes it easier to select one.
     // these controls are not present in read-only mode: all you can do is look at the map.
     $options['switchOffSrefRetrigger'] = true;
     $options['clickForSpatialRef'] = true;
     // override the opacity so the parent square does not appear filled in.
     $options['fillOpacity'] = 0;
     // override the map height and buffer size, which are specific to this map.
     $options['height'] = $args['tree_map_height'];
     $options['maxZoomBuffer'] = $args['tree_map_buffer'];
     $options['srefId'] = 'imp-sref-tree';
     $options['geomId'] = 'imp-geom-tree';
     $options['srefSystemId'] = 'imp-sref-system-tree';
     $help = '<p>' . lang::get('Add your trees using the appropriate tools in the top right of the map') . ':</p>' . '<ol><li>' . lang::get('Navigation Tool.') . '</li>' . '<li>' . lang::get('Query Tool. This tool allows you to click on a tree on the map to view its tree details.') . '</li>' . '<li>' . lang::get('Location Tool. This tool allows you to select the approximate location of a new tree on your site map. You can also reposition existing trees by first clicking on the tree and then clicking on its new location on the map.') . '</li></ol>';
     $r .= '<div class="ui-state-highlight page-notice ui-corner-all">' . $help . '</div>';
     $r .= map_helper::map_panel($options, $olOptions);
     $r .= data_entry_helper::file_box(array('table' => 'location_medium', 'readAuth' => $auth['read'], 'caption' => lang::get('Photos of Tree'), 'readAuth' => $auth['read']));
     $r .= "</div>";
     // right
     $r .= '<div class="follow_on_block" style="clear:both;">';
     $r .= get_attribute_html($settings['tree_attributes'], $args, $ctrlOptions, 'Lower Block', $attrSpecificOptions);
     data_entry_helper::$javascript .= "\n\$('#fieldset-optional-external-sc').prepend(\"" . lang::get('If you choose to record this tree for one of the citizen science projects below, please submit the tree ID used for that scheme.') . "\");\n";
     $r .= data_entry_helper::textarea(array('id' => 'location-comment', 'fieldname' => 'location:comment', 'label' => lang::get("Additional information"), 'labelClass' => 'autowidth')) . "<br />";
     $r .= '<input type="submit" value="' . lang::get('Save') . '" class="form-button right" id="submit-tree" />';
     $r .= '</div></form></div>';
     data_entry_helper::$onload_javascript .= "\$('#current-tree').change(selectTree);\n";
     return $r;
 }
Пример #15
0
 protected static function tab_other_species($args, $auth)
 {
     $r = '';
     $indicia_templates['taxon_label'] = '<div class="biota nobreak"><span class="vernacular">{common}</span>' . '<br/><span class="sci binomial"><em>{taxon}</em></span> {authority}</div>';
     $extraParams = $auth['read'];
     $species_ctrl_opts = array('id' => "species-other", 'label' => 'Species', 'lookupListId' => $args['other_list_id'], 'cacheLookup' => isset($args['cache_lookup']) && $args['cache_lookup'], 'PHPtaxonLabel' => true, 'class' => 'checklist', 'survey_id' => $args['survey_id'], 'extraParams' => $extraParams, 'language' => 'eng', 'occAttrClasses' => array('coverage'), 'reloadExtraParams' => array('taxon_list_id' => $args['other_list_id']), 'speciesNameFilterMode' => 'excludeSynonyms', 'helpText' => 'Please provide details of any additional species you would like to record that you observed during your wildflower count. ' . 'Type the species name into the box on the left of the grid then select the correct name from the drop-down list of suggestions. ' . 'Make sure you input the information about whether the species was recorded on the path or linear/square transect.');
     if (!empty($args['taxon_filter_field']) && !empty($args['taxon_filter'])) {
         $filterLines = helper_base::explode_lines($args['taxon_filter']);
         $species_ctrl_opts['taxonFilterField'] = $args['taxon_filter_field'];
         $species_ctrl_opts['taxonFilter'] = $filterLines;
     }
     self::build_grid_taxon_label_function($args);
     self::build_grid_autocomplete_function($args);
     $r .= data_entry_helper::species_checklist($species_ctrl_opts);
     $r .= '<p class="highlight">' . lang::get('Please review all tabs of the form before submitting the survey.') . '</p>';
     $r .= data_entry_helper::wizard_buttons(array('divId' => 'tabs', 'page' => 'last', 'captionSave' => 'Submit'));
     return $r;
 }
Пример #16
0
 /**
  * Draw Record Details section of the page.
  * @return string The output freeform report.
  * 
  * @package    Client
  * @subpackage PrebuiltForms
  */
 protected static function get_control_recorddetails($auth, $args, $tabalias, $options)
 {
     iform_load_helpers(array('report_helper'));
     $options = array_merge(array('dataSource' => 'reports_for_prebuilt_forms/record_details_2/record_data_attributes_with_hiddens'), $options);
     $fields = helper_base::explode_lines($args['fields']);
     $fieldsLower = helper_base::explode_lines(strtolower($args['fields']));
     //Draw the Record Details, but only if they aren't requested as hidden by the administrator
     $detailstemplateHtml = '';
     $attrsTemplate = '<div class="field ui-helper-clearfix"><span>{caption}:</span><span>{value}</span></div>';
     $test = $args['operator'] === 'in';
     $availableFields = array('occurrence_id' => 'Record ID', 'taxon' => 'Species', 'preferred_taxon' => 'Preferred species name', 'taxonomy' => 'Taxonomy', 'survey_title' => 'Survey', 'recorder' => 'Recorder', 'inputter' => 'Input by', 'record_status' => 'Record status', 'verifier' => 'Verified by', 'date' => 'Date', 'entered_sref' => 'Grid ref', 'occurrence_comment' => 'Record comment', 'location_name' => 'Site name', 'sample_comment' => 'Sample comment');
     self::load_record($auth);
     $details_report = '<div class="record-details-fields ui-helper-clearfix">';
     foreach ($availableFields as $field => $caption) {
         if ($test === in_array(strtolower($caption), $fieldsLower) && !empty(self::$record[$field])) {
             $details_report .= str_replace(array('{caption}', '{value}'), array($caption, self::$record[$field]), $attrsTemplate);
         }
     }
     $created = date('jS F Y \\a\\t H:i', strtotime(self::$record['created_on']));
     $updated = date('jS F Y \\a\\t H:i', strtotime(self::$record['updated_on']));
     $dateInfo = lang::get('Entered on {1}', $created);
     if ($created !== $updated) {
         $dateInfo .= lang::get(' and last updated on {1}', $updated);
     }
     $details_report .= str_replace(array('{caption}', '{value}'), array(lang::get('Submission date'), $dateInfo), $attrsTemplate);
     $details_report .= '</div>';
     if (!self::$record['sensitivity_precision']) {
         //draw any custom attributes added by the user, but only for a non-sensitive record
         $attrs_report = report_helper::freeform_report(array('readAuth' => $auth['read'], 'class' => 'record-details-fields ui-helper-clearfix', 'dataSource' => $options['dataSource'], 'bands' => array(array('content' => $attrsTemplate)), 'extraParams' => array('occurrence_id' => $_GET['occurrence_id'], 'attrs' => strtolower(self::convert_array_to_set($fields)), 'testagainst' => $args['testagainst'], 'operator' => $args['operator'], 'sharing' => 'reporting')));
     }
     $r = '<div class="detail-panel" id="detail-panel-recorddetails"><h3>Record Details</h3>';
     $r .= $details_report;
     if (isset($attrs_report)) {
         $r .= $attrs_report;
     }
     $r .= '</div>';
     return $r;
 }
 public static function get_occurrences_form($args, $node, $response)
 {
     global $user;
     if (!module_exists('iform_ajaxproxy')) {
         return 'This form must be used in Drupal with the Indicia AJAX Proxy module enabled.';
     }
     drupal_add_js('misc/tableheader.js');
     // for sticky heading
     data_entry_helper::add_resource('jquery_form');
     $auth = data_entry_helper::get_read_write_auth($args['website_id'], $args['password']);
     // did the parent sample previously exist? Default is no.
     $existing = false;
     $url = explode('?', $args['my_obs_page'], 2);
     $params = NULL;
     $fragment = NULL;
     // fragment is always at the end.
     if (count($url) > 1) {
         $params = explode('#', $url[1], 2);
         if (count($params) > 1) {
             $fragment = $params[1];
         }
         $params = $params[0];
     } else {
         $url = explode('#', $url[0], 2);
         if (count($url) > 1) {
             $fragment = $url[1];
         }
     }
     $args['my_obs_page'] = url($url[0], array('query' => $params, 'fragment' => $fragment, 'absolute' => TRUE));
     if (isset($_POST['sample:id'])) {
         // have just posted an edit to the existing sample
         $sampleId = $_POST['sample:id'];
         $existing = true;
         data_entry_helper::load_existing_record($auth['read'], 'sample', $sampleId);
     } else {
         if (isset($response['outer_id'])) {
             // have just posted a new sample.
             $sampleId = $response['outer_id'];
         } else {
             $sampleId = $_GET['sample_id'];
             $existing = true;
         }
     }
     $sample = data_entry_helper::get_population_data(array('table' => 'sample', 'extraParams' => $auth['read'] + array('view' => 'detail', 'id' => $sampleId, 'deleted' => 'f')));
     $sample = $sample[0];
     $date = $sample['date_start'];
     if (!function_exists('module_exists') || !module_exists('easy_login')) {
         // work out the CMS User sample ID.
         $sampleMethods = helper_base::get_termlist_terms($auth, 'indicia:sample_methods', array('Field Observation'));
         $attributes = data_entry_helper::getAttributes(array('valuetable' => 'sample_attribute_value', 'attrtable' => 'sample_attribute', 'key' => 'sample_id', 'fieldprefix' => 'smpAttr', 'extraParams' => $auth['read'], 'survey_id' => $args['survey_id'], 'sample_method_id' => $sampleMethods[0]['id']));
         if (false == ($cmsUserAttr = extract_cms_user_attr($attributes))) {
             return 'Easy Login not active: This form is designed to be used with the CMS User ID attribute setup for samples in the survey.';
         }
     }
     $allTaxonMeaningIdsAtSample = array();
     if ($existing) {
         // Only need to load the occurrences for a pre-existing sample
         $o = data_entry_helper::get_population_data(array('report' => 'reports_for_prebuilt_forms/UKBMS/ukbms_occurrences_list_for_sample', 'extraParams' => $auth['read'] + array('view' => 'detail', 'sample_id' => $sampleId, 'survey_id' => $args['survey_id'], 'date_from' => '', 'date_to' => '', 'taxon_group_id' => '', 'smpattrs' => '', 'occattrs' => $args['occurrence_attribute_ids']), 'nocache' => true));
         // build an array keyed for easy lookup
         $occurrences = array();
         $attrs = explode(',', $args['occurrence_attribute_ids']);
         if (!isset($o['error'])) {
             foreach ($o as $occurrence) {
                 if (!in_array($occurrence['taxon_meaning_id'], $allTaxonMeaningIdsAtSample)) {
                     $allTaxonMeaningIdsAtSample[] = $occurrence['taxon_meaning_id'];
                 }
                 $occurrences[$occurrence['taxon_meaning_id']] = array('ttl_id' => $occurrence['taxa_taxon_list_id'], 'ttl_id' => $occurrence['taxa_taxon_list_id'], 'preferred_ttl_id' => $occurrence['preferred_ttl_id'], 'o_id' => $occurrence['occurrence_id'], 'processed' => false);
                 foreach ($attrs as $attr) {
                     $occurrences[$occurrence['taxon_meaning_id']]['value_' . $attr] = $occurrence['attr_occurrence_' . $attr];
                     $occurrences[$occurrence['taxon_meaning_id']]['a_id_' . $attr] = $occurrence['attr_id_occurrence_' . $attr];
                 }
             }
         }
         // store it in data for JS to read when populating the grid
         data_entry_helper::$javascript .= "indiciaData.existingOccurrences = " . json_encode($occurrences) . ";\n";
     } else {
         data_entry_helper::$javascript .= "indiciaData.existingOccurrences = {};\n";
     }
     $occ_attributes = data_entry_helper::getAttributes(array('valuetable' => 'occurrence_attribute_value', 'attrtable' => 'occurrence_attribute', 'key' => 'occurrence_id', 'fieldprefix' => 'occAttr', 'extraParams' => $auth['read'], 'survey_id' => $args['survey_id'], 'multiValue' => false));
     data_entry_helper::$javascript .= "indiciaData.occurrence_totals = [];\n";
     data_entry_helper::$javascript .= "indiciaData.occurrence_attribute = [];\n";
     data_entry_helper::$javascript .= "indiciaData.occurrence_attribute_ctrl = [];\n";
     $defAttrOptions = array('extraParams' => $auth['read'] + array('orderby' => 'id'), 'suffixTemplate' => 'nosuffix');
     $occ_attributes_captions = array();
     foreach (explode(',', $args['occurrence_attribute_ids']) as $idx => $attr) {
         $occ_attributes_captions[$idx] = $occ_attributes[$attr]['caption'];
         unset($occ_attributes[$attr]['caption']);
         $ctrl = data_entry_helper::outputAttribute($occ_attributes[$attr], $defAttrOptions);
         data_entry_helper::$javascript .= "indiciaData.occurrence_totals[" . $idx . "] = [];\n";
         data_entry_helper::$javascript .= "indiciaData.occurrence_attribute[" . $idx . "] = {$attr};\n";
         data_entry_helper::$javascript .= "indiciaData.occurrence_attribute_ctrl[" . $idx . "] = jQuery('" . str_replace("\n", "", $ctrl) . "');\n";
     }
     //    $r = "<h2>".$location[0]['name']." on ".$date."</h2>\n";
     $r = '<div id="tabs">';
     $tabs = array('#grid1' => t($args['species_tab_1']));
     // tab 1 is required.
     if (isset($args['taxon_list_id_2']) && $args['taxon_list_id_2'] != '') {
         $tabs['#grid2'] = t(isset($args['species_tab_2']) && $args['species_tab_2'] != '' ? $args['species_tab_2'] : 'Species Tab 2');
     }
     if (isset($args['taxon_list_id_3']) && $args['taxon_list_id_3'] != '') {
         $tabs['#grid3'] = t(isset($args['species_tab_3']) && $args['species_tab_3'] != '' ? $args['species_tab_3'] : 'Species Tab 3');
     }
     if (isset($args['taxon_list_id_4']) && $args['taxon_list_id_4'] != '') {
         $tabs['#grid4'] = t(isset($args['species_tab_4']) && $args['species_tab_4'] != '' ? $args['species_tab_4'] : 'Species Tab 4');
     }
     $tabs['#notes'] = lang::get('Notes');
     $r .= data_entry_helper::tab_header(array('tabs' => $tabs));
     data_entry_helper::enable_tabs(array('divId' => 'tabs', 'style' => 'Tabs'));
     // will assume that first table is based on abundance count, so do totals
     $r .= '<div id="grid1"><table id="observation-input1" class="ui-widget species-grid"><thead class="table-header"><tr><th class="ui-widget-header"></th>';
     foreach (explode(',', $args['occurrence_attribute_ids']) as $idx => $attr) {
         $r .= '<th class="ui-widget-header col-' . ($idx + 1) . '">' . $occ_attributes_captions[$idx] . '</th>';
     }
     $r .= '<th class="ui-widget-header">' . lang::get('Total') . '</th></tr></thead>';
     $r .= '<tbody class="ui-widget-content occs-body"></tbody><tfoot><tr><td>Total</td>';
     foreach (explode(',', $args['occurrence_attribute_ids']) as $idx => $attr) {
         $r .= '<td class="col-' . ($idx + 1) . ' ' . ($idx % 5 == 0 ? 'first' : '') . ' col-total"></td>';
     }
     $r .= '<td class="ui-state-disabled first"></td></tr></tfoot></table><br /><a href="' . $args['my_obs_page'] . '" class="button">' . lang::get('Finish') . '</a></div>';
     $extraParams = array_merge($auth['read'], array('taxon_list_id' => $args['taxon_list_id_1'], 'preferred' => 't', 'allow_data_entry' => 't', 'view' => 'cache', 'orderby' => 'taxonomic_sort_order'));
     if (!empty($args['taxon_filter_field_1']) && !empty($args['taxon_filter_1'])) {
         $extraParams[$args['taxon_filter_field_1']] = helper_base::explode_lines($args['taxon_filter_1']);
     }
     $taxa = data_entry_helper::get_population_data(array('table' => 'taxa_taxon_list', 'extraParams' => $extraParams));
     data_entry_helper::$javascript .= "indiciaData.speciesList1List = [";
     $first = true;
     foreach ($taxa as $taxon) {
         data_entry_helper::$javascript .= ($first ? "\n" : ",\n") . "{'id':" . $taxon['id'] . ",'taxon_meaning_id':" . $taxon['taxon_meaning_id'] . ",'preferred_language_iso':'" . $taxon["preferred_language_iso"] . "','default_common_name':'" . str_replace("'", "\\'", $taxon["default_common_name"]) . "'}";
         $first = false;
     }
     data_entry_helper::$javascript .= "];\n";
     data_entry_helper::$javascript .= "indiciaData.allTaxonMeaningIdsAtSample = [" . implode(',', $allTaxonMeaningIdsAtSample) . "];\n";
     if (isset($args['taxon_list_id_2']) && $args['taxon_list_id_2'] != '') {
         $r .= '<div id="grid2"><p id="grid2-loading">' . lang::get('Loading - Please Wait') . '</p><table id="observation-input2" class="ui-widget species-grid"><thead class="table-header"><tr><th class="ui-widget-header"></th>';
         foreach (explode(',', $args['occurrence_attribute_ids']) as $idx => $attr) {
             $r .= '<th class="ui-widget-header col-' . ($idx + 1) . '">' . $occ_attributes_captions[$idx] . '</th>';
         }
         $r .= '<th class="ui-widget-header">' . lang::get('Total') . '</th></tr></thead><tbody class="ui-widget-content occs-body"></tbody><tfoot><tr><td>Total</td>';
         foreach (explode(',', $args['occurrence_attribute_ids']) as $idx => $attr) {
             $r .= '<td class="col-' . ($idx + 1) . ' ' . ($idx % 5 == 0 ? 'first' : '') . ' col-total"></td>';
         }
         $r .= '<td class="ui-state-disabled first"></td></tr></tfoot></table><br /><a href="' . $args['my_obs_page'] . '" class="button">' . lang::get('Finish') . '</a></div>';
     }
     if (isset($args['taxon_list_id_3']) && $args['taxon_list_id_3'] != '') {
         $r .= '<div id="grid3"><p id="grid3-loading">' . lang::get('Loading - Please Wait') . '</p><table id="observation-input3" class="ui-widget species-grid"><thead class="table-header"><tr><th class="ui-widget-header"></th>';
         foreach (explode(',', $args['occurrence_attribute_ids']) as $idx => $attr) {
             $r .= '<th class="ui-widget-header col-' . ($idx + 1) . '">' . $occ_attributes_captions[$idx] . '</th>';
         }
         $r .= '<th class="ui-widget-header">' . lang::get('Total') . '</th></tr></thead><tbody class="ui-widget-content occs-body"></tbody><tfoot><tr><td>Total</td>';
         foreach (explode(',', $args['occurrence_attribute_ids']) as $idx => $attr) {
             $r .= '<td class="col-' . ($idx + 1) . ' ' . ($idx % 5 == 0 ? 'first' : '') . ' col-total"></td>';
         }
         $r .= '<td class="ui-state-disabled first"></td></tr></tfoot></table><br /><a href="' . $args['my_obs_page'] . '" class="button">' . lang::get('Finish') . '</a></div>';
     }
     if (isset($args['taxon_list_id_4']) && $args['taxon_list_id_4'] != '') {
         $r .= '<div id="grid4"><p id="grid4-loading">' . lang::get('Loading - Please Wait') . '</p><table id="observation-input4" class="ui-widget species-grid"><thead class="table-header"><tr><th class="ui-widget-header"></th>';
         foreach (explode(',', $args['occurrence_attribute_ids']) as $idx => $attr) {
             $r .= '<th class="ui-widget-header col-' . ($idx + 1) . '">' . $occ_attributes_captions[$idx] . '</th>';
         }
         $r .= '<th class="ui-widget-header">' . lang::get('Total') . '</th></tr></thead><tbody class="ui-widget-content occs-body"></tbody><tfoot><tr><td>Total</td>';
         foreach (explode(',', $args['occurrence_attribute_ids']) as $idx => $attr) {
             $r .= '<td class="col-' . ($idx + 1) . ' ' . ($idx % 5 == 0 ? 'first' : '') . ' col-total"></td>';
         }
         $r .= '<td class="ui-state-disabled first"></td></tr></tfoot></table>';
         $r .= '<label for="taxonLookupControl4" class="auto-width">' . lang::get('Add species to list') . ':</label> <input id="taxonLookupControl4" name="taxonLookupControl4" >';
         $r .= '<br /><a href="' . $args['my_obs_page'] . '" class="button">' . lang::get('Finish') . '</a></div>';
     }
     // for the comment form, we want to ensure that if there is a timeout error that it reloads the
     // data as stored in the DB.
     $reload = data_entry_helper::get_reload_link_parts();
     $reload['params']['sample_id'] = $parentSampleId;
     unset($reload['params']['new']);
     $reloadPath = $reload['path'];
     if (count($reload['params'])) {
         // decode params prior to encoding to prevent double encoding.
         foreach ($reload['params'] as $key => $param) {
             $reload['params'][$key] = urldecode($param);
         }
         $reloadPath .= '?' . http_build_query($reload['params']);
     }
     // fragment is always at the end. discard this.
     $reloadPath = explode('#', $reloadPath, 2);
     $reloadPath = $reloadPath[0];
     $r .= "<div id=\"notes\"><form method=\"post\" id=\"notes_form\" action=\"" . $reloadPath . "#notes\">\n";
     $r .= $auth['write'];
     $r .= '<input type="hidden" name="sample:id" value="' . $sampleId . '" />' . '<input type="hidden" name="website_id" value="' . $args['website_id'] . '"/>' . '<input type="hidden" name="survey_id" value="' . $args['survey_id'] . '"/>' . '<input type="hidden" name="page" value="notes"/>';
     $r .= '<p class="page-notice ui-state-highlight ui-corner-all">' . lang::get('When using this page, please remember that the data is not saved to the database as you go (which is the case for the previous tabs). In order to save the data entered in this page you must click on the Submit button at the bottom of the page.') . '</p>';
     $r .= data_entry_helper::textarea(array('fieldname' => 'sample:comment', 'label' => lang::get('Notes'), 'helpText' => "Use this space to input comments about this week's walk."));
     $r .= '<input type="submit" value="' . lang::get('Submit') . '" id="save-button"/></form>';
     $r .= '<br /><a href="' . $args['my_walks_page'] . '" class="button">' . lang::get('Finish') . '</a></div></div>';
     // enable validation on the comments form in order to include the simplified ajax queuing for the autocomplete.
     data_entry_helper::enable_validation('notes_form');
     // A stub form for AJAX posting when we need to create an occurrence
     $r .= '<form style="display: none" id="occ-form" method="post" action="' . iform_ajaxproxy_url($node, 'occurrence') . '">';
     $r .= '<input name="website_id" value="' . $args['website_id'] . '"/>';
     $r .= '<input name="occurrence:id" id="occid" />';
     $r .= '<input name="occurrence:taxa_taxon_list_id" id="ttlid" />';
     $r .= '<input name="occurrence:sample_id" value="' . $sampleId . '"/>';
     $r .= '<input name="occAttr:" id="occattr"/>';
     $r .= '<input name="transaction_id" id="transaction_id"/>';
     $r .= '<input name="user_id" value="' . hostsite_get_user_field('user_id', 1) . '"/>';
     $r .= '</form>';
     // tell the Javascript where to get species from.
     data_entry_helper::add_resource('jquery_ui');
     data_entry_helper::add_resource('json');
     data_entry_helper::add_resource('autocomplete');
     data_entry_helper::$javascript .= "indiciaData.speciesList1 = " . $args['taxon_list_id_1'] . ";\n";
     if (!empty($args['taxon_filter_field_1']) && !empty($args['taxon_filter_1'])) {
         data_entry_helper::$javascript .= "indiciaData.speciesList1FilterField = '" . $args['taxon_filter_field_1'] . "';\n";
         $filterLines = helper_base::explode_lines($args['taxon_filter_1']);
         data_entry_helper::$javascript .= "indiciaData.speciesList1FilterValues = '" . json_encode($filterLines) . "';\n";
     }
     data_entry_helper::$javascript .= "indiciaData.speciesList2 = " . (isset($args['taxon_list_id_2']) && $args['taxon_list_id_2'] != "" ? $args['taxon_list_id_2'] : "-1") . ";\n";
     if (!empty($args['taxon_filter_field_2']) && !empty($args['taxon_filter_2'])) {
         data_entry_helper::$javascript .= "indiciaData.speciesList2FilterField = '" . $args['taxon_filter_field_2'] . "';\n";
         $filterLines = helper_base::explode_lines($args['taxon_filter_2']);
         data_entry_helper::$javascript .= "indiciaData.speciesList2FilterValues = " . json_encode($filterLines) . ";\n";
     }
     data_entry_helper::$javascript .= "indiciaData.speciesList3 = " . (isset($args['taxon_list_id_3']) && $args['taxon_list_id_3'] != "" ? $args['taxon_list_id_3'] : "-1") . ";\n";
     if (!empty($args['taxon_filter_field_3']) && !empty($args['taxon_filter_3'])) {
         data_entry_helper::$javascript .= "indiciaData.speciesList3FilterField = '" . $args['taxon_filter_field_3'] . "';\n";
         $filterLines = helper_base::explode_lines($args['taxon_filter_3']);
         data_entry_helper::$javascript .= "indiciaData.speciesList3FilterValues = " . json_encode($filterLines) . ";\n";
     }
     data_entry_helper::$javascript .= "indiciaData.speciesList4 = " . (isset($args['taxon_list_id_4']) && $args['taxon_list_id_4'] != "" ? $args['taxon_list_id_4'] : "-1") . ";\n";
     if (!empty($args['taxon_filter_field_4']) && !empty($args['taxon_filter_4'])) {
         data_entry_helper::$javascript .= "indiciaData.speciesList4FilterField = '" . $args['taxon_filter_field_4'] . "';\n";
         $filterLines = helper_base::explode_lines($args['taxon_filter_4']);
         data_entry_helper::$javascript .= "indiciaData.speciesList4FilterValues = " . json_encode($filterLines) . ";\n";
     }
     // allow js to do AJAX by passing in the information it needs to post forms
     data_entry_helper::$javascript .= "bindSpeciesAutocomplete(\"taxonLookupControl4\",\"table#observation-input4\",\"" . data_entry_helper::$base_url . "index.php/services/data\", indiciaData.speciesList4,\n  indiciaData.speciesList4FilterField, indiciaData.speciesList4FilterValues, {\"auth_token\" : \"" . $auth['read']['auth_token'] . "\", \"nonce\" : \"" . $auth['read']['nonce'] . "\"},\n  \"" . lang::get('LANG_Duplicate_Taxon') . "\", 25, 4);\n\n";
     data_entry_helper::$javascript .= "indiciaData.indiciaSvc = '" . data_entry_helper::$base_url . "';\n";
     data_entry_helper::$javascript .= "indiciaData.readAuth = {nonce: '" . $auth['read']['nonce'] . "', auth_token: '" . $auth['read']['auth_token'] . "'};\n";
     data_entry_helper::$javascript .= "indiciaData.sample = " . $sampleId . ";\n";
     if (function_exists('module_exists') && module_exists('easy_login')) {
         data_entry_helper::$javascript .= "indiciaData.easyLogin = true;\n";
         $userId = hostsite_get_user_field('indicia_user_id');
         if (!empty($userId)) {
             data_entry_helper::$javascript .= "indiciaData.UserID = " . $userId . ";\n";
         } else {
             return '<p>Easy Login active but could not identify user</p>';
         }
         // something is wrong
     } else {
         data_entry_helper::$javascript .= "indiciaData.easyLogin = false;\n";
         data_entry_helper::$javascript .= "indiciaData.CMSUserAttrID = " . $cmsUserAttr['attributeId'] . ";\n";
         data_entry_helper::$javascript .= "indiciaData.CMSUserID = " . $user->uid . ";\n";
     }
     // Do an AJAX population of the grid rows.
     data_entry_helper::$javascript .= "loadSpeciesList();\njQuery('#tabs').bind('tabsshow', function(event, ui) {\n    var target = ui.panel;\n    // first get rid of any previous tables\n    jQuery('table.sticky-header').remove();\n    jQuery('table.sticky-enabled thead.tableHeader-processed').removeClass('tableHeader-processed');\n    jQuery('table.sticky-enabled.tableheader-processed').removeClass('tableheader-processed');\n    jQuery('table.species-grid.sticky-enabled').removeClass('sticky-enabled');\n    var table = jQuery('#'+target.id+' table.species-grid');\n    if(table.length > 0) {\n        table.addClass('sticky-enabled');\n        if(typeof Drupal.behaviors.tableHeader == 'object') // Drupal 7\n          Drupal.behaviors.tableHeader.attach(table.parent());\n        else // Drupal6 : it is a function\n          Drupal.behaviors.tableHeader(target);\n    }\n    // remove any hanging autocomplete select list.\n    jQuery('.ac_results').hide();\n});";
     return $r;
 }
Пример #18
0
 public static function get_occurrences_form($args, $node, $response)
 {
     global $user;
     data_entry_helper::add_resource('jquery_form');
     data_entry_helper::add_resource('jquery_ui');
     data_entry_helper::add_resource('json');
     data_entry_helper::add_resource('autocomplete');
     $auth = data_entry_helper::get_read_write_auth($args['website_id'], $args['password']);
     // did the parent sample previously exist? Default is no.
     $parentSampleId = null;
     $existing = false;
     if (isset($_POST['sample:id'])) {
         // have just posted an edit to the existing parent sample, so can use it to get the parent location id.
         $parentSampleId = $_POST['sample:id'];
         $existing = true;
     } else {
         if (isset($response['outer_id'])) {
             // have just posted a new parent sample, so can use it to get the parent location id.
             $parentSampleId = $response['outer_id'];
         } else {
             $parentSampleId = $_GET['sample_id'];
             $existing = true;
         }
     }
     if (!$parentSampleId || $parentSampleId == '') {
         return 'Could not determine the parent sample.';
     }
     // find any attributes that apply to Timed Count Count samples.
     $sampleMethods = helper_base::get_termlist_terms($auth, 'indicia:sample_methods', array('Timed Count Count'));
     if (count($sampleMethods) == 0) {
         return 'The sample method "Timed Count Count" must be defined in the termlist in order to use this form.';
     }
     $attributes = data_entry_helper::getAttributes(array('valuetable' => 'sample_attribute_value', 'attrtable' => 'sample_attribute', 'key' => 'sample_id', 'fieldprefix' => 'smpAttr', 'extraParams' => $auth['read'], 'survey_id' => $args['survey_id'], 'sample_method_id' => $sampleMethods[0]['id'], 'multiValue' => false));
     if (!isset(data_entry_helper::$validation_errors)) {
         // the parent sample and at least one sub-sample have already been created: can't cache in case a new subsample (Count) added.
         data_entry_helper::load_existing_record($auth['read'], 'sample', $parentSampleId);
         $d = new DateTime(data_entry_helper::$entity_to_load['sample:date']);
         data_entry_helper::$entity_to_load['sample:date'] = $d->format('Y');
         // using the report returns the attributes as well.
         $subSamples = data_entry_helper::get_population_data(array('report' => 'library/samples/samples_list_for_parent_sample', 'extraParams' => $auth['read'] + array('sample_id' => $parentSampleId, 'date_from' => '', 'date_to' => '', 'sample_method_id' => '', 'smpattrs' => implode(',', array_keys($attributes))), 'nocache' => true));
         // subssamples ordered by id desc, so reorder by date asc.
         usort($subSamples, "iform_timed_count_subsample_cmp");
         for ($i = 0; $i < count($subSamples); $i++) {
             data_entry_helper::$entity_to_load['C' . ($i + 1) . ':sample:id'] = $subSamples[$i]['sample_id'];
             data_entry_helper::$entity_to_load['C' . ($i + 1) . ':sample:date'] = $subSamples[$i]['date'];
             // this is in correct format
             foreach ($subSamples[$i] as $field => $value) {
                 if (preg_match('/^attr_sample_/', $field)) {
                     $parts = explode('_', $field);
                     if ($subSamples[$i]['attr_id_sample_' . $parts[2]] != null) {
                         data_entry_helper::$entity_to_load['C' . ($i + 1) . ':smpAttr:' + $parts[2] + ':' + $subSamples[$i]['attr_id_sample_' . $parts[2]]] = $value;
                     }
                 }
             }
         }
     }
     data_entry_helper::$javascript .= "indiciaData.speciesList = " . $args['taxon_list_id'] . ";\n";
     if (!empty($args['taxon_filter_field']) && !empty($args['taxon_filter'])) {
         data_entry_helper::$javascript .= "indiciaData.speciesListFilterField = '" . $args['taxon_filter_field'] . "';\n";
         $filterLines = helper_base::explode_lines($args['taxon_filter']);
         data_entry_helper::$javascript .= "indiciaData.speciesListFilterValues = '" . json_encode($filterLines) . "';\n";
     }
     data_entry_helper::$javascript .= "\r\nindiciaData.indiciaSvc = '" . data_entry_helper::$base_url . "';\n";
     data_entry_helper::$javascript .= "indiciaData.readAuth = {nonce: '" . $auth['read']['nonce'] . "', auth_token: '" . $auth['read']['auth_token'] . "'};\n";
     data_entry_helper::$javascript .= "indiciaData.parentSample = " . $parentSampleId . ";\n";
     data_entry_helper::$javascript .= "indiciaData.occAttrId = " . $args['occurrence_attribute_id'] . ";\n";
     if ($existing) {
         // Only need to load the occurrences for a pre-existing sample
         $o = data_entry_helper::get_population_data(array('report' => 'library/occurrences/occurrences_list_for_parent_sample', 'extraParams' => $auth['read'] + array('view' => 'detail', 'sample_id' => $parentSampleId, 'survey_id' => '', 'date_from' => '', 'date_to' => '', 'taxon_group_id' => '', 'smpattrs' => '', 'occattrs' => $args['occurrence_attribute_id']), 'nocache' => true));
         // the report is ordered id desc. REverse it
         $o = array_reverse($o);
     } else {
         $o = array();
     }
     // empty array of occurrences when no creating a new sample.
     // we pass through the read auth. This makes it possible for the get_submission method to authorise against the warehouse
     // without an additional (expensive) warehouse call.
     // pass a param that sets the next page to display
     $r = "<form method='post' id='subsamples'>" . $auth['write'] . "\r\n<input type='hidden' name='page' value='occurrences'/>\r\n<input type='hidden' name='read_nonce' value='" . $auth['read']['nonce'] . "'/>\r\n<input type='hidden' name='read_auth_token' value='" . $auth['read']['auth_token'] . "'/>\r\n<input type='hidden' name='website_id' value='" . $args['website_id'] . "'/>\r\n<input type='hidden' name='sample:id' value='" . data_entry_helper::$entity_to_load['sample:id'] . "'/>\r\n<input type='hidden' name='sample:survey_id' value='" . $args['survey_id'] . "'/>\r\n<input type='hidden' name='sample:date' value='" . data_entry_helper::$entity_to_load['sample:date'] . "'/>\r\n<input type='hidden' name='sample:entered_sref' value='" . data_entry_helper::$entity_to_load['sample:entered_sref'] . "'/>\r\n<input type='hidden' name='sample:entered_sref_system' value='" . data_entry_helper::$entity_to_load['sample:entered_sref_system'] . "'/>\r\n<input type='hidden' name='sample:geom' value='" . data_entry_helper::$entity_to_load['sample:geom'] . "'/>\r\n";
     if (isset($args['custom_attribute_options']) && $args['custom_attribute_options']) {
         $blockOptions = get_attr_options_array_with_user_data($args['custom_attribute_options']);
     } else {
         $blockOptions = array();
     }
     for ($i = 0; $i < $args['numberOfCounts']; $i++) {
         $subSampleId = isset($subSamples[$i]) ? $subSamples[$i]['sample_id'] : null;
         $r .= "<fieldset id=\"count-{$i}\"><legend>" . lang::get('Count ') . ($i + 1) . "</legend>";
         if ($subSampleId) {
             $r .= "<input type='hidden' name='C" . ($i + 1) . ":sample:id' value='" . $subSampleId . "'/>";
         }
         $r .= '<input type="hidden" name="C' . ($i + 1) . ':sample:sample_method_id" value="' . $sampleMethods[0]['id'] . '" />';
         if ($subSampleId || isset(data_entry_helper::$entity_to_load['C' . ($i + 1) . ':sample:date']) && data_entry_helper::$entity_to_load['C' . ($i + 1) . ':sample:date'] != '') {
             $dateValidation = array('required', 'date');
         } else {
             $dateValidation = array('date');
         }
         $r .= data_entry_helper::date_picker(array('label' => lang::get('Date'), 'fieldname' => 'C' . ($i + 1) . ':sample:date', 'validation' => $dateValidation));
         data_entry_helper::$javascript .= "\$('#C" . ($i + 1) . "\\\\:sample\\\\:date' ).datepicker( 'option', 'minDate', new Date(" . data_entry_helper::$entity_to_load['sample:date'] . ", 1 - 1, 1) );\r\n\$('#C" . ($i + 1) . "\\\\:sample\\\\:date' ).datepicker( 'option', 'maxDate', new Date(" . data_entry_helper::$entity_to_load['sample:date'] . ", 12 - 1, 31) );\n";
         if (!$subSampleId && $i) {
             $r .= "<p>" . lang::get('You must enter the date before you can enter any further information.') . '</p>';
             data_entry_helper::$javascript .= "\$('#C" . ($i + 1) . "\\\\:sample\\\\:date' ).change(function(){\r\n  myFieldset = \$(this).addClass('required').closest('fieldset');\r\n  myFieldset.find('.smp-input,[name=taxonLookupControl]').removeAttr('disabled'); // leave the count fields as are.\r\n});\n";
         }
         if ($subSampleId && $i) {
             $r .= "<label for='C" . ($i + 1) . ":sample:deleted'>Delete this count:</label>\r\n<input id='C" . ($i + 1) . ":sample:deleted' type='checkbox' value='t' name='C" . ($i + 1) . ":sample:deleted'><br />\r\n<p>" . lang::get('Setting this will delete this count when the page is saved.') . '</p>';
         }
         foreach ($attributes as $attr) {
             if (strcasecmp($attr['untranslatedCaption'], 'Unconfirmed Individuals') == 0) {
                 continue;
             }
             // output the attribute - tag it with a class & id to make it easy to find from JS.
             $attrOpts = array_merge(isset($blockOptions[$attr['fieldname']]) ? $blockOptions[$attr['fieldname']] : array(), array('class' => 'smp-input smpAttr-' . ($i + 1), 'id' => 'C' . ($i + 1) . ':' . $attr['fieldname'], 'fieldname' => 'C' . ($i + 1) . ':' . $attr['fieldname'], 'extraParams' => $auth['read']));
             // we need process validation specially: deh expects an array, we have a string...
             if (isset($attrOpts['validation']) && is_string($attrOpts['validation'])) {
                 $attrOpts['validation'] = explode(';', $attrOpts['validation']);
             }
             // if there is an existing value, set it and also ensure the attribute name reflects the attribute value id.
             if (isset($subSampleId)) {
                 // but have to take into account possibility that this field has been blanked out, so deleting the attribute.
                 if (isset($subSamples[$i]['attr_id_sample_' . $attr['attributeId']]) && $subSamples[$i]['attr_id_sample_' . $attr['attributeId']] != '') {
                     $attrOpts['fieldname'] = 'C' . ($i + 1) . ':' . $attr['fieldname'] . ':' . $subSamples[$i]['attr_id_sample_' . $attr['attributeId']];
                     $attr['default'] = $subSamples[$i]['attr_sample_' . $attr['attributeId']];
                 }
             } else {
                 if ($i) {
                     $attrOpts['disabled'] = "disabled=\"disabled\"";
                 }
             }
             $r .= data_entry_helper::outputAttribute($attr, $attrOpts);
         }
         $r .= '<table id="timed-counts-input-' . $i . '" class="ui-widget">';
         $r .= '<thead><tr><th class="ui-widget-header">' . lang::get('Species') . '</th><th class="ui-widget-header">' . lang::get('Count') . '</th><th class="ui-widget-header"></th></tr></thead>';
         $r .= '<tbody class="ui-widget-content">';
         $occs = array();
         // not very many occurrences so no need to optimise.
         if (isset($subSampleId) && $existing && count($o) > 0) {
             foreach ($o as $oc) {
                 if ($oc['sample_id'] == $subSampleId) {
                     $occs[] = $oc;
                 }
             }
         }
         for ($j = 0; $j < $args['numberOfSpecies']; $j++) {
             $rowClass = '';
             // O<i>:<j>:<ttlid>:<occid>:<attrid>:<attrvalid>
             if (isset($occs[$j])) {
                 $taxon = $occs[$j]['common'] . ' (' . $occs[$j]['taxon'] . ')';
                 $fieldname = 'O' . ($i + 1) . ':' . ($j + 1) . ':' . $occs[$j]['taxa_taxon_list_id'] . ':' . $occs[$j]['occurrence_id'] . ':' . $args['occurrence_attribute_id'] . ':' . $occs[$j]['attr_id_occurrence_' . $args['occurrence_attribute_id']];
                 $value = $occs[$j]['attr_occurrence_' . $args['occurrence_attribute_id']];
             } else {
                 $taxon = '';
                 $fieldname = 'O' . ($i + 1) . ':' . ($j + 1) . ':--ttlid--:--occid--:' . $args['occurrence_attribute_id'] . ':--valid--';
                 $value = '';
             }
             $r .= '<tr ' . $rowClass . '>' . '<td><input id="TLC-' . ($i + 1) . '-' . ($j + 1) . '" name="taxonLookupControl" value="' . $taxon . '" ' . (!$j && (!$i || $subSampleId) || $taxon ? 'class="required"' : '') . ' ' . (!$subSampleId && $i ? 'disabled="disabled"' : '') . '>' . (!$j && (!$i || $subSampleId) || $taxon ? '<span class="deh-required">*</span>' : '') . '</td>' . '<td><input name="' . $fieldname . '" id="occ-' . ($i + 1) . '-' . ($j + 1) . '" value="' . $value . '" class="occValField integer ' . (!$j && (!$i || $subSampleId) || $taxon ? 'required' : '') . '" ' . (!$subSampleId && $i || $taxon == '' && ($i || $j) ? 'disabled="disabled"' : '') . ' min=0 >' . (!$j && (!$i || $subSampleId) || $taxon ? '<span class="deh-required">*</span>' : '') . '</td>' . '<td>' . (!$j ? '' : '<div class="ui-state-default remove-button">' . lang::get('Remove this Species entry') . '</div>') . '</td>' . '</tr>';
             $rowClass = $rowClass == '' ? 'class="alt-row"' : '';
             data_entry_helper::$javascript .= "bindSpeciesAutocomplete(\"TLC-" . ($i + 1) . "-" . ($j + 1) . "\",\"occ-" . ($i + 1) . "-" . ($j + 1) . "\",\"" . data_entry_helper::$base_url . "index.php/services/data\", \"" . $args['taxon_list_id'] . "\",\r\n  indiciaData.speciesListFilterField, indiciaData.speciesListFilterValues, {\"auth_token\" : \"" . $auth['read']['auth_token'] . "\", \"nonce\" : \"" . $auth['read']['nonce'] . "\"}, 25);\n";
         }
         foreach ($attributes as $attr) {
             if (strcasecmp($attr['untranslatedCaption'], 'Unconfirmed Individuals')) {
                 continue;
             }
             // output the attribute - tag it with a class & id to make it easy to find from JS.
             $attrOpts = array('class' => 'smp-input smpAttr-' . ($i + 1), 'id' => 'C' . ($i + 1) . ':' . $attr['fieldname'], 'fieldname' => 'C' . ($i + 1) . ':' . $attr['fieldname'], 'extraParams' => $auth['read']);
             // if there is an existing value, set it and also ensure the attribute name reflects the attribute value id.
             if (isset($subSampleId)) {
                 // but have to take into account possibility that this field has been blanked out, so deleting the attribute.
                 if (isset($subSamples[$i]['attr_id_sample_' . $attr['attributeId']]) && $subSamples[$i]['attr_id_sample_' . $attr['attributeId']] != '') {
                     $attrOpts['fieldname'] = 'C' . ($i + 1) . ':' . $attr['fieldname'] . ':' . $subSamples[$i]['attr_id_sample_' . $attr['attributeId']];
                     $attr['default'] = $subSamples[$i]['attr_sample_' . $attr['attributeId']];
                 }
             } else {
                 if ($i) {
                     $attrOpts['disabled'] = "disabled=\"disabled\"";
                 }
             }
             $r .= '<tr ' . $rowClass . '>' . '<td>' . $attr['caption'] . '</td>';
             unset($attr['caption']);
             $r .= '<td>' . data_entry_helper::outputAttribute($attr, $attrOpts) . '</td>' . '<td></td>' . '</tr>';
         }
         $r .= '</tbody></table>';
         if ($i && !$subSampleId) {
             $r .= '<button type="button" class="clear-button ui-state-default ui-corner-all smp-input" disabled="disabled" />' . lang::get('Clear this count') . '</button>';
         }
         $r .= '</fieldset>';
     }
     $r .= '<input type="submit" value="' . lang::get('Save') . '" />';
     $r .= '<a href="' . $args['summary_page'] . '"><button type="button" class="ui-state-default ui-corner-all" />' . lang::get('Cancel') . '</button></a></form>';
     data_entry_helper::enable_validation('subsamples');
     data_entry_helper::$javascript .= "initButtons();\n";
     return $r;
 }