/**
  * Return the generated form output.
  * @param array $args List of parameter values passed through to the form depending on how the form has been configured.
  * This array always contains a value for language.
  * @param object $node The Drupal node object.
  * @param array $response When this form is reloading after saving a submission, contains the response from the service call.
  * Note this does not apply when redirecting (in this case the details of the saved object are in the $_GET data).
  * @return Form HTML.
  */
 public static function get_form($args, $node, $response = null)
 {
     if (!($user_id = hostsite_get_user_field('indicia_user_id'))) {
         return self::abort('Please ensure that you\'ve filled in your surname on your user profile before leaving a group.', $args);
     }
     if (empty($_GET['group_id'])) {
         return self::abort('This form must be called with a group_id in the URL parameters.', $args);
     }
     $r = '';
     $auth = data_entry_helper::get_read_write_auth($args['website_id'], $args['password']);
     $group = data_entry_helper::get_population_data(array('table' => 'group', 'extraParams' => $auth['read'] + array('id' => $_GET['group_id']), 'nocache' => true));
     if (count($group) !== 1) {
         return self::abort('The group you\'ve requested membership of does not exist.', $args);
     }
     iform_load_helpers(array('submission_builder'));
     $group = $group[0];
     // Check for an existing group user record
     $existing = data_entry_helper::get_population_data(array('table' => 'groups_user', 'extraParams' => $auth['read'] + array('group_id' => $_GET['group_id'], 'user_id' => $user_id), 'nocache' => true));
     if (count($existing) !== 1) {
         return self::abort('You are not a member of this group.', $args);
     }
     if (!empty($_POST['response']) && $_POST['response'] === lang::get('Cancel')) {
         drupal_goto($args['groups_page_path']);
     } elseif (!empty($_POST['response']) && $_POST['response'] === lang::get('Confirm')) {
         $data = array('groups_user:id' => $existing[0]['id'], 'groups_user:group_id' => $group['id'], 'groups_user:user_id' => $user_id, 'deleted' => 't');
         $wrap = submission_builder::wrap($data, 'groups_user');
         $response = data_entry_helper::forward_post_to('groups_user', $wrap, $auth['write_tokens']);
         if (isset($response['success'])) {
             hostsite_show_message("You are no longer participating in {$group['title']}!");
             drupal_goto($args['groups_page_path']);
         } else {
             return self::abort('An error occurred whilst trying to update your group membership.');
         }
     } else {
         // First access of the form. Let's get confirmation
         $reload = data_entry_helper::get_reload_link_parts();
         $reloadpath = $reload['path'] . '?' . data_entry_helper::array_to_query_string($reload['params']);
         $r = '<form action="' . $reloadpath . '" method="POST"><fieldset>';
         $r .= '<legend>' . lang::get('Confirmation') . '</legend>';
         $r .= '<input type="hidden" name="leave" value="1" />';
         $r .= '<p>' . lang::get('Are you sure you want to stop participating in {1}?', $group['title']) . '</p>';
         $r .= '<input type="submit" value="' . lang::get('Confirm') . '" name="response" />';
         $r .= '<input type="submit" value="' . lang::get('Cancel') . '" name="response" />';
         $r .= '</fieldset></form>';
     }
     return $r;
 }
Beispiel #2
0
 private static function extractUserInfoFromFormValues(&$s, $values, $fieldname, $isAdmin)
 {
     $existingAdmins = preg_grep("/^groups_user\\:{$fieldname}\\:[0-9]+\$/", array_keys($values));
     if (!empty($values["groups_user:{$fieldname}"]) || !empty($existingAdmins)) {
         if (!isset($s['subModels'])) {
             $s['subModels'] = array();
         }
         if (!empty($values["groups_user:{$fieldname}"])) {
             foreach ($values["groups_user:{$fieldname}"] as $userId) {
                 $s['subModels'][] = array('fkId' => 'group_id', 'model' => submission_builder::wrap(array('user_id' => $userId, 'administrator' => $isAdmin), 'groups_user'));
             }
         }
         // for existing, we just need to look for deletions which will have an empty value
         foreach ($existingAdmins as $admin) {
             if (empty($values[$admin])) {
                 $id = substr($admin, 20);
                 $s['subModels'][] = array('fkId' => 'group_id', 'model' => submission_builder::wrap(array('id' => $id, 'deleted' => 't'), 'groups_user'));
             }
         }
     }
     return $s;
 }
 /**
  * Handles the construction of a submission array from a set of form values.
  * For example, the following represents a submission structure for a simple
  * sample and 1 occurrence submission
  * return data_entry_helper::build_sample_occurrence_submission($values);
  * @param array $values Associative array of form data values. 
  * @param array $args iform parameters. 
  * @return array Submission structure.
  * @todo: Implement this method
  */
 public static function get_submission($values, $args)
 {
     if (!isset($values['page']) || $values['page'] != 'grid') {
         // submitting the first page, with top level sample details
         if (!isset($values['sample:entered_sref'])) {
             // the sample does not have sref data, as the user has just picked a transect site at this point. Copy the
             // site's centroid across to the sample.
             $read = array('nonce' => $values['read_nonce'], 'auth_token' => $values['read_auth_token']);
             $site = data_entry_helper::get_population_data(array('table' => 'location', 'extraParams' => $read + array('view' => 'detail', 'id' => $values['sample:location_id'], 'deleted' => 'f')));
             $site = $site[0];
             $values['sample:entered_sref'] = $site['centroid_sref'];
             $values['sample:entered_sref_system'] = $site['centroid_sref_system'];
         }
     }
     $submission = submission_builder::build_submission($values, array('model' => 'sample'));
     return $submission;
 }
 /**
  * Handles the construction of a submission array from a set of form values.
  * @param array $values Associative array of form data values.
  * @param array $args iform parameters.
  * @return array Submission structure.
  */
 public static function get_submission($values, $args)
 {
     $values['sample:location_name'] = $values['sample:entered_sref'];
     $submission = submission_builder::build_submission($values, array('model' => 'sample'));
     return $submission;
 }
 /**
  * Handles the construction of a submission array from a set of form values.
  * @param array $values Associative array of form data values. 
  * @param array $args iform parameters. 
  * @return array Submission structure.
  */
 public static function get_submission($values, $args)
 {
     if (isset($values['source'])) {
         // comes from main Sites tab, Admins may create so need to check for locations_website entry
         $locModel = submission_builder::wrap_with_images($values, 'location');
         if (isset($values['locations_website:website_id'])) {
             // assume no other submodels
             $locModel['subModels'] = array(array('fkId' => 'location_id', 'model' => array('id' => 'locations_website', 'fields' => array('website_id' => array('value' => $values['locations_website:website_id'])))));
         }
         return $locModel;
     }
     if (isset($values['sample:location_id']) && $values['sample:location_id'] == '') {
         unset($values['sample:location_id']);
     }
     if (isset($values['sample:recorder_names'])) {
         if (is_array($values['sample:recorder_names'])) {
             $values['sample:recorder_names'] = implode("\r\n", $values['sample:recorder_names']);
         }
     }
     // else just load the string
     if (isset($values['location:name'])) {
         $values['sample:location_name'] = $values['location:name'];
     }
     $sampleMod = submission_builder::wrap_with_images($values, 'sample');
     if (!isset($values['sample:deleted'])) {
         if (isset($values['gridmode'])) {
             $subModels = self::wrap_species_checklist($values);
         } else {
             $subModels = submission_builder::wrap_with_images($values, 'occurrence');
         }
         foreach ($values as $key => $value) {
             $parts = explode(':', $key, 5);
             if ($parts[0] == 'targ' && $parts[3] == 'presence') {
                 $smp = array('fkId' => 'parent_id', 'model' => array('id' => 'sample', 'fields' => array()));
                 $smp['model']['fields']['survey_id'] = array('value' => $values['survey_id']);
                 $smp['model']['fields']['website_id'] = array('value' => $values['website_id']);
                 $smp['model']['fields']['date'] = array('value' => $values['sample:date']);
                 $smp['model']['fields']['smpAttr:' . $parts[4]] = array('value' => $parts[2]);
                 if (isset($values['sample:location_id'])) {
                     $smp['model']['fields']['location_id'] = array('value' => $values['sample:location_id']);
                 } else {
                     if (isset($values['location:parent_id'])) {
                         $smp['model']['fields']['location_id'] = array('value' => $values['location:parent_id']);
                     } else {
                         $smp['model']['fields']['geom'] = array('value' => $values['location:centroid_geom']);
                         $smp['model']['fields']['entered_sref'] = array('value' => $values['location:centroid_sref']);
                         $smp['model']['fields']['entered_sref_system'] = array('value' => $values['location:centroid_sref_system']);
                     }
                 }
                 if ($value != '1') {
                     $smp['model']['fields']['deleted'] = array('value' => 't');
                 }
                 if ($parts[1] != '-') {
                     $smp['model']['fields']['id'] = array('value' => $parts[1]);
                 }
                 foreach ($values as $key1 => $value1) {
                     $moreParts = explode(':', $key1, 5);
                     if ($moreParts[0] == 'targ' && $moreParts[1] == $parts[1] && $moreParts[2] == $parts[2] && $moreParts[3] == 'smpAttr') {
                         $smp['model']['fields']['smpAttr:' . $moreParts[4]] = array('value' => $value1);
                     }
                 }
                 if (isset($values['sample:location_id'])) {
                     $smp['model']['fields']['location_id'] = array('value' => $values['sample:location_id']);
                 } else {
                     $smp['model']['fields']['centroid_sref'] = array('value' => $values['sample:entered_sref']);
                     $smp['model']['fields']['centroid_sref_system'] = array('value' => $values['sample:entered_sref_system']);
                     $smp['model']['fields']['centroid_geom'] = array('value' => $values['sample:geom']);
                 }
                 if ($value == '1' || $parts[1] != '-') {
                     $subModels[] = $smp;
                 }
             }
         }
         if (count($subModels) > 0) {
             $sampleMod['subModels'] = $subModels;
         }
         if (isset($values['location:location_type_id'])) {
             $locationMod = submission_builder::wrap_with_images($values, 'location');
             $locationMod['subModels'] = array(array('fkId' => 'location_id', 'model' => $sampleMod));
             if (array_key_exists('locations_website:website_id', $_POST)) {
                 $lw = submission_builder::wrap_with_images($values, 'locations_website');
                 $locationMod['subModels'][] = array('fkId' => 'location_id', 'model' => $lw);
             }
             return $locationMod;
         }
     } else {
         if (isset($values['location:deleted'])) {
             $locationMod = submission_builder::wrap_with_images($values, 'location');
             $locationMod['subModels'] = array(array('fkId' => 'location_id', 'model' => $sampleMod));
             return $locationMod;
         }
     }
     return $sampleMod;
 }
 /**
  * Builds a submission for identifiers_subject_observation join data 
  * from the form values. Also adds identifier if it doesn't exist.
  * @param array $values Associative array of form data values. 
  * @param array $matches Associative array of stored identifiers which match submitted values. 
  * @param array $so The subject_observation submission we are adding to
  * @return array subject_observation Submission structure with identifier data added.
  */
 private static function build_identifier_observation_submission($values, $matches, $so)
 {
     // work out what to do, insert?, update? delete?
     $set = $values['identifier:checkbox'] == 1;
     $code = $values['identifier:coded_value'];
     $old_id = (int) $values['identifier:id'];
     $new_id = 0;
     $identifier_status = 'U';
     foreach ($matches as $match) {
         if ($match['coded_value'] === $code) {
             $new_id = (int) $match['id'];
             $identifier_status = $match['status'];
         }
     }
     // see if we have any updates on the isoAttr
     $isoAttrUpdated = count(preg_grep('/^isoAttr:[0-9]+$/', array_keys($values))) > 0;
     if (!$isoAttrUpdated) {
         $keys = preg_grep('/^isoAttr:[0-9]+:[0-9]+$/', array_keys($values));
         foreach ($keys as $key) {
             if ($values[$key] === '') {
                 $isoAttrUpdated = true;
                 break;
             }
         }
     }
     // this identifier exists but its identity has been changed
     if ($old_id > 0 && $old_id !== $new_id) {
         // unlink the old identifier
         $values['identifiers_subject_observation:deleted'] = 't';
         $iso = submission_builder::build_submission($values, array('model' => 'identifiers_subject_observation'));
         $so['subModels'][] = array('fkId' => 'subject_observation_id', 'model' => $iso);
     }
     // identifier submitted, has been edited and matches an existing identifier
     if ($set && $new_id > 0 && $old_id !== $new_id) {
         // create link to the new matching identifier
         unset($values['identifiers_subject_observation:id']);
         $values['identifiers_subject_observation:identifier_id'] = $new_id;
         $values['identifiers_subject_observation:matched'] = $identifier_status !== 'U' ? 't' : 'f';
         unset($values['identifiers_subject_observation:verified_status']);
         unset($values['identifiers_subject_observation:verified_by_id']);
         unset($values['identifiers_subject_observation:verified_on']);
         unset($values['identifiers_subject_observation:created_on']);
         unset($values['identifiers_subject_observation:created_by_id']);
         unset($values['identifiers_subject_observation:updated_on']);
         unset($values['identifiers_subject_observation:updated_by_id']);
         unset($values['identifiers_subject_observation:deleted']);
         $iso = submission_builder::build_submission($values, array('model' => 'identifiers_subject_observation'));
         $so['subModels'][] = array('fkId' => 'subject_observation_id', 'model' => $iso);
     }
     // identifier submitted and doesn't match an existing identifier
     if ($set && $new_id === 0) {
         // create new link to a new identifier which we also create here
         unset($values['identifiers_subject_observation:id']);
         unset($values['identifiers_subject_observation:identifier_id']);
         $values['identifiers_subject_observation:matched'] = 'f';
         unset($values['identifiers_subject_observation:verified_status']);
         unset($values['identifiers_subject_observation:verified_by_id']);
         unset($values['identifiers_subject_observation:verified_on']);
         unset($values['identifiers_subject_observation:created_on']);
         unset($values['identifiers_subject_observation:created_by_id']);
         unset($values['identifiers_subject_observation:updated_on']);
         unset($values['identifiers_subject_observation:updated_by_id']);
         unset($values['identifiers_subject_observation:deleted']);
         $iso = submission_builder::build_submission($values, array('model' => 'identifiers_subject_observation'));
         // now add the identifier
         unset($values['identifier:id']);
         unset($values['identifier:issue_authority_id']);
         unset($values['identifier:issue_scheme_id']);
         unset($values['identifier:issue_date']);
         unset($values['identifier:first_use_date']);
         unset($values['identifier:last_observed_date']);
         unset($values['identifier:final_date']);
         unset($values['identifier:summary']);
         unset($values['identifier:status']);
         unset($values['identifier:verified_by_id']);
         unset($values['identifier:verified_on']);
         unset($values['identifier:known_subject_id']);
         unset($values['identifier:created_on']);
         unset($values['identifier:created_by_id']);
         unset($values['identifier:updated_on']);
         unset($values['identifier:updated_by_id']);
         unset($values['identifier:deleted']);
         $i = submission_builder::build_submission($values, array('model' => 'identifier'));
         $iso['superModels'] = array(array('fkId' => 'identifier_id', 'model' => $i));
         $so['subModels'][] = array('fkId' => 'subject_observation_id', 'model' => $iso);
     }
     // identifier exists and is unchanged but has iso attributes which have changed
     if ($old_id > 0 && $old_id === $new_id && $isoAttrUpdated) {
         // update link to trigger update to isoAttr
         $iso = submission_builder::build_submission($values, array('model' => 'identifiers_subject_observation'));
         $so['subModels'][] = array('fkId' => 'subject_observation_id', 'model' => $iso);
     }
     return $so;
 }
 /**
  * Handles the construction of a submission array from a set of form values.
  * @param array $values Associative array of form data values. 
  * @param array $args iform parameters. 
  * @return array Submission structure.
  */
 public static function get_submission($values, $args)
 {
     //If the location_type_id is supplied in the url, then use this
     if (!empty($_GET['location_type_id'])) {
         $values['location:location_type_id'] = $_GET['location_type_id'];
     }
     $structure = array('model' => 'location');
     // Either an uploadable file, or a link to a Flickr external detail means include the submodel
     // (Copied from data_entry_helper::build_sample_occurrence_submission. If file_box control is used
     // then build_submission calls wrap_with_images instead)
     if (array_key_exists('location:medium', $values) && $values['location:medium'] || array_key_exists('location_medium:external_details', $values) && $values['location_medium:external_details']) {
         $structure['submodel'] = array('model' => 'location_medium', 'fk' => 'location_id');
     }
     $s = submission_builder::build_submission($values, $structure);
     // On first save of a new location, link it to the website.
     // Be careful not to over-write other subModels (e.g. images)
     if (empty($values['location:id'])) {
         $s['subModels'][] = array('fkId' => 'location_id', 'model' => array('id' => 'locations_website', 'fields' => array('website_id' => $args['website_id'])));
         // also, on first save we might be linking to a group
         if (!empty($values['group_id'])) {
             $s['subModels'][] = array('fkId' => 'location_id', 'model' => array('id' => 'groups_location', 'fields' => array('group_id' => $values['group_id'])));
         }
     }
     return $s;
 }
 /**
  * Helper function to simplify building of a submission. Does simple submissions that do not involve
  * species checklist grids.
  * @param array $values List of the posted values to create the submission from.
  * @param array $structure Describes the structure of the submission. The form should be:
  * array(
  *     'model' => 'main model name',
  *     'subModels' => array('child model name' =>  array(
  *         'fieldPrefix'=>'Optional prefix for HTML form fields in the sub model. If not specified then the sub model name is used.',
  *         'fk' => 'foreign key name',
  *         'image_entity' => 'name of image entity if present'
  *     )),
  *     'superModels' => array('child model name' =>  array(
  *         'fieldPrefix'=>'Optional prefix for HTML form fields in the sub model. If not specified then the sub model name is used.',
  *         'fk' => 'foreign key name',
  *         'image_entity' => 'name of image entity if present'
  *     )),
  *     'metaFields' => array('fieldname1', 'fieldname2', ...)
  * )
  */
 public static function build_submission($values, $structure)
 {
     return submission_builder::build_submission($values, $structure);
 }
 /**
  * Handles the construction of a submission array from a set of form values.
  * @param array $values Associative array of form data values.
  * @param array $args iform parameters.
  * @return array Submission structure.
  * @todo: Implement this method
  */
 public static function get_submission($values, $args)
 {
     $subsampleModels = array();
     if (isset($values['page']) && $values['page'] == 'speciesmap') {
         $submission = data_entry_helper::build_sample_subsamples_occurrences_submission($values);
     } else {
         if (!isset($values['page']) || $values['page'] == 'mainSample') {
             // submitting the first page, with top level sample details
             $read = array('nonce' => $values['read_nonce'], 'auth_token' => $values['read_auth_token']);
             if (!isset($values['sample:entered_sref'])) {
                 // the sample does not have sref data, as the user has just picked a transect site at this point. Copy the
                 // site's centroid across to the sample. Should this be cached?
                 $site = data_entry_helper::get_population_data(array('table' => 'location', 'extraParams' => $read + array('view' => 'detail', 'id' => $values['sample:location_id'], 'deleted' => 'f')));
                 $site = $site[0];
                 $values['sample:entered_sref'] = $site['centroid_sref'];
                 $values['sample:entered_sref_system'] = $site['centroid_sref_system'];
             }
             // Build the subsamples
             $sections = data_entry_helper::get_population_data(array('table' => 'location', 'extraParams' => $read + array('view' => 'detail', 'parent_id' => $values['sample:location_id'], 'deleted' => 'f'), 'nocache' => true));
             if (isset($values['sample:id'])) {
                 $existingSubSamples = data_entry_helper::get_population_data(array('table' => 'sample', 'extraParams' => $read + array('view' => 'detail', 'parent_id' => $values['sample:id'], 'deleted' => 'f'), 'nocache' => true));
             } else {
                 $existingSubSamples = array();
             }
             $sampleMethods = helper_base::get_termlist_terms(array('read' => $read), 'indicia:sample_methods', array('Transect Section'));
             $attributes = data_entry_helper::getAttributes(array('valuetable' => 'sample_attribute_value', 'attrtable' => 'sample_attribute', 'key' => 'sample_id', 'fieldprefix' => 'smpAttr', 'extraParams' => $read, 'survey_id' => $values['sample:survey_id'], 'sample_method_id' => $sampleMethods[0]['id'], 'multiValue' => false));
             $smpDate = self::parseSingleDate($values['sample:date']);
             foreach ($sections as $section) {
                 $smp = false;
                 $exists = false;
                 foreach ($existingSubSamples as $existingSubSample) {
                     if ($existingSubSample['location_id'] == $section['id']) {
                         $exists = $existingSubSample;
                         break;
                     }
                 }
                 if (!$exists) {
                     $smp = array('fkId' => 'parent_id', 'model' => array('id' => 'sample', 'fields' => array('survey_id' => array('value' => $values['sample:survey_id']), 'website_id' => array('value' => $values['website_id']), 'date' => array('value' => $values['sample:date']), 'location_id' => array('value' => $section['id']), 'entered_sref' => array('value' => $section['centroid_sref']), 'entered_sref_system' => array('value' => $section['centroid_sref_system']), 'sample_method_id' => array('value' => $sampleMethods[0]['id']))), 'copyFields' => array('date_start' => 'date_start', 'date_end' => 'date_end', 'date_type' => 'date_type'));
                     foreach ($attributes as $attr) {
                         foreach ($values as $key => $value) {
                             $parts = explode(':', $key);
                             if (count($parts) > 1 && $parts[0] == 'smpAttr' && $parts[1] == $attr['attributeId']) {
                                 $smp['model']['fields']['smpAttr:' . $attr['attributeId']] = array('value' => $value);
                             }
                         }
                     }
                 } else {
                     // need to ensure any date change is propagated: only do if date has changed for performance reasons.
                     $subSmpDate = self::parseSingleDate($exists['date_start']);
                     if (strcmp($smpDate, $subSmpDate)) {
                         $smp = array('fkId' => 'parent_id', 'model' => array('id' => 'sample', 'fields' => array('survey_id' => array('value' => $values['sample:survey_id']), 'website_id' => array('value' => $values['website_id']), 'id' => array('value' => $exists['id']), 'date' => array('value' => $values['sample:date']), 'location_id' => array('value' => $exists['location_id']))), 'copyFields' => array('date_start' => 'date_start', 'date_end' => 'date_end', 'date_type' => 'date_type'));
                     }
                 }
                 if ($smp) {
                     $subsampleModels[] = $smp;
                 }
             }
         }
         $submission = submission_builder::build_submission($values, array('model' => 'sample'));
         if (count($subsampleModels) > 0) {
             $submission['subModels'] = $subsampleModels;
         }
     }
     return $submission;
 }
 /**
  * Handles the construction of a submission array from a set of form values.
  * @param array $values Associative array of form data values. 
  * @param array $args iform parameters. 
  * @return array Submission structure.
  */
 public static function get_submission($values, $args)
 {
     $structure = array('model' => 'person');
     $s = submission_builder::build_submission($values, $structure);
     return $s;
 }
 /**
  * Handles the construction of a submission array from a set of form values.
  * @param array $values Associative array of form data values. 
  * @param array $args iform parameters. 
  * @return array Submission structure.
  */
 public static function get_submission($values, $args)
 {
     if (isset($values['source'])) {
         // comes from main Sites tab, Admins may create so need to check for locations_website entry
         $locModel = submission_builder::wrap_with_images($values, 'location');
         if (isset($values['locations_website:website_id'])) {
             // assume no other submodels
             $locModel['subModels'] = array(array('fkId' => 'location_id', 'model' => array('id' => 'locations_website', 'fields' => array('website_id' => array('value' => $values['locations_website:website_id'])))));
         }
         return $locModel;
     }
     if (isset($values['sample:recorder_names'])) {
         if (is_array($values['sample:recorder_names'])) {
             $values['sample:recorder_names'] = implode("\r\n", $values['sample:recorder_names']);
         }
     }
     // else just load the string
     $sampleMod = data_entry_helper::wrap_with_attrs($values, 'sample');
     if (isset($values['sample:deleted'])) {
         return $sampleMod;
     }
     $subsamples = array();
     $locations = array();
     foreach ($values as $key => $value) {
         $parts = explode(':', $key, 4);
         //     $cloneprefix='CG:--rownum--:--sampleid--:smpAttr:--attr_id--[:--attr_value_id--]
         //     $cloneprefix='CG:--rownum--:--sampleid--:smpAttr:--attr_id--\[\] for a multivalue checkbox group, with an array value
         if ($parts[0] == 'CG' && count($parts) > 1 && $parts[1] != '--rownum--' && $parts[1] != '') {
             $field = explode(':', $parts[3]);
             if ($field[0] == 'location') {
                 $locations[$parts[1]][$field[1]] = array('value' => $value);
                 $locations[$parts[1]]['website_id'] = array('value' => $values['website_id']);
                 $locations[$parts[1]]['survey_id'] = array('value' => $values['survey_id']);
             } else {
                 if ($parts[2] != "--sampleid--" && $parts[2] != "") {
                     $subsamples[$parts[1]]['id'] = array('value' => $parts[2]);
                 }
                 if (is_array($value)) {
                     for ($i = count($value) - 1; $i >= 0; $i--) {
                         // reverse order so we can unset array members.
                         $tokens = explode(':', $value[$i], 5);
                         // need to discard the CG prefix
                         if (count($tokens) > 1) {
                             unset($value[$i]);
                             $subsamples[$parts[1]][$tokens[4]] = array('value' => $tokens[0]);
                         }
                     }
                     if (count($value) > 0) {
                         // sweep up any new ones.
                         $subsamples[$parts[1]][$parts[3]] = array('value' => $value);
                     }
                 } else {
                     $subsamples[$parts[1]][$parts[3]] = array('value' => $value);
                 }
                 $subsamples[$parts[1]]['website_id'] = array('value' => $values['website_id']);
                 $subsamples[$parts[1]]['survey_id'] = array('value' => $values['survey_id']);
             }
         }
     }
     // locations and subsamples arrays are indexed by cgrownum.
     // next create an array of subsample models with their occurrences attached.
     $subsamples2 = array();
     $newsgrowContents = array();
     // array indexed on sgrownum of subarrays of samples which have new occurrences
     ksort($subsamples);
     // by cgrownum
     foreach ($subsamples as $sampleIndex => $subsampleFields) {
         if (isset($subsampleFields['date']) && $subsampleFields['date']['value'] != "") {
             $subsampleFields['location_name'] = $subsampleFields['name'];
             $subsample = array('fkId' => 'parent_id', 'model' => array('id' => 'sample', 'fields' => $subsampleFields));
             if (isset($locations[$sampleIndex])) {
                 $locweb = array('fkId' => 'location_id', 'model' => array('id' => 'locations_website', 'fields' => array('website_id' => array('value' => $values['website_id']))));
                 $locations[$sampleIndex]['name'] = $subsampleFields['name'];
                 $locations[$sampleIndex]['parent_id'] = array('value' => $values['sample:location_id']);
                 $locations[$sampleIndex]['centroid_sref_system'] = array('value' => $values['location:centroid_sref_system']);
                 $subsample['model']['superModels'] = array(array('fkId' => 'location_id', 'model' => array('id' => 'location', 'fields' => $locations[$sampleIndex], 'subModels' => array($locweb))));
             }
             $occs = array();
             foreach ($values as $key => $value) {
                 $parts = explode(':', $key, 7);
                 // SG:--sgrownum--:--cgrownum--:--sampleid--:--ttlid--:--occid--:occAttr:--attr_id--[:--attr_value_id--]
                 if ($parts[0] == 'SG' && count($parts) > 1 && $parts[4] != '--ttlid--' && $parts[4] != '' && $parts[2] == $sampleIndex && ($parts[5] != "--occid--" && $parts[5] != "" || $value != "")) {
                     $occ = array('fkId' => 'sample_id', 'model' => array('id' => 'occurrence', 'fields' => array('taxa_taxon_list_id' => array('value' => $parts[4]), 'website_id' => array('value' => $values['website_id']), 'survey_id' => array('value' => $values['survey_id']), $parts[6] => array('value' => $value))));
                     if ($value == "") {
                         $occ['model']['fields']['deleted'] = array('value' => 't');
                         unset($occ['model']['fields'][$parts[6]]);
                     }
                     if ($parts[5] != "--occid--" && $parts[5] != "") {
                         $occ['model']['fields']['id'] = array('value' => $parts[5]);
                     } else {
                         if (!isset($newsgrowContents[intval($parts[1])])) {
                             $newsgrowContents[intval($parts[1])] = array();
                         }
                         $newsgrowContents[intval($parts[1])][] = $sampleIndex;
                     }
                     $occs[] = $occ;
                 }
             }
             if (count($occs) > 0) {
                 $subsample['model']['subModels'] = $occs;
             }
             $subsamples2[$sampleIndex] = $subsample;
         } else {
             if (isset($subsampleFields['id']) && $subsampleFields['id']['value'] != "") {
                 $subsample = array('fkId' => 'parent_id', 'model' => array('id' => 'sample', 'fields' => array('id' => $subsampleFields['id'], 'deleted' => array('value' => 't'), 'website_id' => $subsampleFields['website_id'], 'survey_id' => $subsampleFields['survey_id'])));
                 $subsamples2[$sampleIndex] = $subsample;
             }
         }
     }
     // finally create an unindexed array of subsamples, in the order of sgrownum....
     // don't care about order of already saved occurrences, only new ones: in fact old ones may mess things up!
     // The order in which we need to save the occurrences is how they are displayed in the form. This allows us to recreate the form later on.
     $subsamples3 = array();
     // don't want this indexed
     $subsampleslist = array();
     // but need a list of those included so far!
     // new sgrowContents just has a list of cgrownums for that sgrow
     ksort($newsgrowContents);
     foreach ($newsgrowContents as $sgrownum => $list) {
         // this is done in sgrownum order.
         foreach ($list as $cgrow) {
             if (!isset($subsampleslist[$cgrow])) {
                 $subsampleslist[$cgrow] = true;
                 $subsamples3[] = $subsamples2[$cgrow];
             }
         }
     }
     // now we dump in any other subsamples
     foreach ($subsamples2 as $cgrownum => $subsample) {
         if (!isset($subsampleslist[$cgrownum])) {
             $subsampleslist[$cgrownum] = true;
             $subsamples3[] = $subsample;
         }
     }
     if (count($subsamples3) > 0) {
         $sampleMod['subModels'] = $subsamples3;
     }
     return $sampleMod;
 }
Beispiel #12
0
 /**
  * Handles the construction of a submission array from a set of form values.
  * @param array $values Associative array of form data values. 
  * @param array $args iform parameters. 
  * @return array Submission structure.
  */
 public static function get_submission($values, $args)
 {
     if (isset($values['sample:recorder_names'])) {
         if (is_array($values['sample:recorder_names'])) {
             $values['sample:recorder_names'] = implode("\r\n", $values['sample:recorder_names']);
         }
     }
     // else just load the string
     if (isset($values['gridmode'])) {
         $occurrences = data_entry_helper::wrap_species_checklist($values);
     } else {
         $occurrences = submission_builder::wrap_with_images($values, 'occurrence');
     }
     // when a non admin selects an existing location they can not modify it or its attributes and the location record does not form part of the submission
     if (isset($values['location:name'])) {
         $sampleMod = submission_builder::wrap_with_images($values, 'sample');
         if (count($occurrences) > 0) {
             $sampleMod['subModels'] = $occurrences;
         }
         $locationMod = submission_builder::wrap_with_images($values, 'location');
         $locationMod['subModels'] = array(array('fkId' => 'location_id', 'model' => $sampleMod));
         if (array_key_exists('locations_website:website_id', $_POST)) {
             $lw = submission_builder::wrap_with_images($values, 'locations_website');
             $locationMod['subModels'][] = array('fkId' => 'location_id', 'model' => $lw);
         }
         return $locationMod;
     }
     $values['sample:location_id'] = $values['location:id'];
     $sampleMod = submission_builder::wrap_with_images($values, 'sample');
     if (count($occurrences) > 0) {
         $sampleMod['subModels'] = $occurrences;
     }
     return $sampleMod;
 }
Beispiel #13
0
 /**
  * Handles the construction of a submission array from a set of form values.
  * @param array $values Associative array of form data values. 
  * @param array $args iform parameters. 
  * @return array Submission structure.
  */
 public static function get_submission($values, $args)
 {
     if (isset($values['source'])) {
         // comes from main Sites tab, Admins may create so need to check for locations_website entry
         $locModel = submission_builder::wrap_with_images($values, 'location');
         if (isset($values['locations_website:website_id'])) {
             // assume no other submodels
             $locModel['subModels'] = array(array('fkId' => 'location_id', 'model' => array('id' => 'locations_website', 'fields' => array('website_id' => array('value' => $values['locations_website:website_id'])))));
         }
         return $locModel;
     }
     if (isset($values['sample:recorder_names'])) {
         if (is_array($values['sample:recorder_names'])) {
             $values['sample:recorder_names'] = implode("\r\n", $values['sample:recorder_names']);
         }
     }
     // else just load the string
     $sampleMod = submission_builder::wrap_with_images($values, 'sample');
     if (!isset($values['sample:deleted'])) {
         if (isset($values['gridmode'])) {
             $occurrences = data_entry_helper::wrap_species_checklist($values);
         } else {
             $occurrences = submission_builder::wrap_with_images($values, 'occurrence');
         }
         // when a non admin selects an existing location they can not modify it or its attributes and the location record does not form part of the submission
         if (isset($values['location:location_type_id'])) {
             if (count($occurrences) > 0) {
                 $sampleMod['subModels'] = $occurrences;
             }
             $locationMod = submission_builder::wrap_with_images($values, 'location');
             $locationMod['subModels'] = array(array('fkId' => 'location_id', 'model' => $sampleMod));
             if (array_key_exists('locations_website:website_id', $_POST)) {
                 $lw = submission_builder::wrap_with_images($values, 'locations_website');
                 $locationMod['subModels'][] = array('fkId' => 'location_id', 'model' => $lw);
             }
             return $locationMod;
         }
         //      $values['sample:location_id'] = $values['location:id'];
         if (count($occurrences) > 0) {
             $sampleMod['subModels'] = $occurrences;
         }
     }
     return $sampleMod;
 }
 /**
  * Builds the special submission format required for seasearch data
  * @param array $values
  * @param array $args
  * @return array
  * @throws \Exception
  */
 public static function get_submission($values, $args)
 {
     // First, build an array of the field values for each habitat sample.
     $habitatSamples = array();
     foreach ($values as $key => $value) {
         if (substr_count($key, ':') === 3) {
             $parts = explode(':', $key, 4);
             if ($parts[0] === 'smpAttr') {
                 // If the last part of a habitat field is not a number, this is just a dummy field used
                 // when cloning habitat controls.
                 if (preg_match('/^\\d+$/', $parts[3])) {
                     // habitat number is the last part of the attribute field name
                     $id = array_pop($parts);
                     if (!isset($habitatSamples["habitat{$id}"])) {
                         $habitatSamples["habitat{$id}"] = array();
                     }
                     // Skip empty new attribute values.
                     if (!empty($parts[2]) || !empty($value)) {
                         // remove empty stuff from the attribute name (e.g. an unused space for the existing value ID, if a new attribute value).
                         while (empty($parts[count($parts) - 1])) {
                             array_pop($parts);
                         }
                         $fieldname = implode(':', $parts);
                         $habitatSamples["habitat{$id}"][$fieldname] = $value;
                     }
                 }
                 unset($values[$key]);
             }
         }
         // Also check for habitat photos, attached to a fake table name indicating the habitat index
         if (preg_match('/^sample_medium(?P<id>\\d)/', $key, $matches)) {
             $parts = explode(':', $key);
             if (!isset($habitatSamples["habitat{$matches['id']}"])) {
                 $habitatSamples["habitat{$matches['id']}"] = array();
             }
             $parts[0] = 'sample_medium';
             $habitatSamples["habitat{$matches['id']}"][implode(':', $parts)] = $value;
         }
         $parts = explode(':', $key);
         // For the group_name, the autocomplete functionality needs to be removed from the submission.
         // So copy the edit box into the underlying field which gets posted.
         if (array_pop($parts) === 'group_name') {
             $values[implode(':', $parts)] = $value;
         }
     }
     // Find the attribute which contains SACFORP habitat data.
     $readAuth = data_entry_helper::get_read_auth(variable_get('indicia_website_id'), variable_get('indicia_password'));
     $attributeOpts = array('valuetable' => 'occurrence_attribute_value', 'attrtable' => 'occurrence_attribute', 'key' => 'occurrence_id', 'fieldprefix' => 'occAttr', 'extraParams' => $readAuth + array('caption' => 'SACFOR/P'), 'survey_id' => $args['survey_id']);
     $attributes = data_entry_helper::getAttributes($attributeOpts, false);
     $values['habitat-count'] = count($habitatSamples);
     $buddyPairSubmission = submission_builder::wrap_with_images($values, 'sample');
     unset($buddyPairSubmission['fields']['habitat-count']);
     // Get the list of records implied by the SACFOR data for each habitat. At this point we'll create 1 big list and split
     // it across the habitats later.
     $occurrences = data_entry_helper::wrap_species_checklist($values, true, array(), array());
     // now work out which habitat contains which occurrence
     $habitatOccurrences = array();
     foreach (array_keys($habitatSamples) as $habitatId) {
         $habitatOccurrences[$habitatId] = array();
     }
     foreach ($occurrences as $uniqueId => $occurrence) {
         // for existing occurrences, they are already linked to a sample via the SampleIDX field.
         if (!empty($occurrence['model']['fields']['sampleIDX'])) {
             $habitatOccurrences['habitat' . ($occurrence['model']['fields']['sampleIDX']['value'] + 1)][] = $occurrence;
         } else {
             // search the posted data for a habitat SACFOR value for the occurrence row
             foreach (array_keys($habitatSamples) as $habitatId) {
                 $habitatIdx = str_replace('habitat', '', $habitatId);
                 if (!empty($values["{$uniqueId}:habitat-{$habitatIdx}"])) {
                     $thisOccurrence = array_merge($occurrence);
                     $thisOccurrence['model']['fields'][$attributes[0]['fieldname']] = array('value' => $values["{$uniqueId}:habitat-{$habitatIdx}"]);
                     $habitatOccurrences[$habitatId][] = $thisOccurrence;
                 }
             }
         }
     }
     // now create the submodel data for each habitat.
     $buddyPairSubmission['subModels'] = array();
     // copy the basic sample data into each set of habitat subsample values
     foreach ($habitatSamples as $habitatId => &$habitatSample) {
         $habitatIdx = str_replace('habitat', '', $habitatId);
         $habitatSample['website_id'] = $values['website_id'];
         $habitatSample['survey_id'] = $values['survey_id'];
         if (isset($_POST["habitat_sample_id:{$habitatIdx}"])) {
             $habitatSample['sample:id'] = $_POST["habitat_sample_id:{$habitatIdx}"];
         }
         $habitatSample['sample:date'] = $values['sample:date'];
         $habitatSample['sample:entered_sref'] = $values['sample:entered_sref'];
         $habitatSample['sample:entered_sref_system'] = $values['sample:entered_sref_system'];
         $habitatSample['sample:input_form'] = $values['sample:input_form'];
         if (isset($_POST["sample:comment:{$habitatIdx}"])) {
             $habitatSample['sample:comment'] = $_POST["sample:comment:{$habitatIdx}"];
             unset($buddyPairSubmission['fields']["comment:{$habitatIdx}"]);
         }
         $habitatSubmission = submission_builder::wrap_with_images($habitatSample, 'sample');
         if (!isset($habitatSubmission['subModels'])) {
             $habitatSubmission['subModels'] = array();
         }
         $habitatSubmission['subModels'] += $habitatOccurrences[$habitatId];
         $buddyPairSubmission['subModels'][] = array('fkId' => 'parent_id', 'model' => $habitatSubmission);
     }
     return $buddyPairSubmission;
 }
Beispiel #15
0
 /**
  * Handles the construction of a submission array from a set of form values.
  * @param array $values Associative array of form data values. 
  * @param array $args iform parameters. 
  * @return array Submission structure.
  */
 public static function get_submission($values, $args)
 {
     $subSampleIds = array('path', 'square', 'linear');
     //Need to supply false as the third parameter, this explicitely tells the system that there are no
     //attributes to check as zero abundance even though we have already given the system the rowInclusionCheck=hasData option
     //which tells the system that only species with data should be considered as an occurrence.
     //If we don't do this, the system will always create an occurrence for every species, even if the Paths checkbox is off.
     $submission = data_entry_helper::build_sample_occurrences_list_submission($values, true, false);
     // Now because it is not standard, we need to attach the sub-samples for each plot.
     // First, extract the attributes for each subsample into their own arrays.
     $subSamples = array();
     foreach ($values as $key => $value) {
         if (strpos($key, ':')) {
             $parts = explode(':', $key);
             if (in_array($parts[0], $subSampleIds)) {
                 $subSamples[$parts[0]][substr($key, strlen($parts[0]) + 1)] = $value;
             }
         }
     }
     // Now wrap each of the subsample arrays and attach them to the main submission.
     foreach ($subSamples as $prefix => $s) {
         if (isset($values[$prefix . '_sample_id'])) {
             $s['sample:id'] = $values[$prefix . '_sample_id'];
         }
         // specify some default values
         $s['sample:entered_sref_system'] = $values['sample:entered_sref_system'];
         $s['sample:entered_sref'] = $values['sample:entered_sref'];
         $s['sample:geom'] = $values['sample:geom'];
         $s['sample:date'] = $values['sample:date'];
         $s['sample:survey_id'] = $values['survey_id'];
         $s['location_name'] = $prefix;
         $wrapped = submission_builder::wrap_with_attrs($s, 'sample', $prefix);
         $submission['subModels'][] = array('fkId' => 'parent_id', 'model' => $wrapped);
     }
     return $submission;
 }
 public static function create_submission($values, $args)
 {
     $structure = array('model' => 'location');
     // Either an uploadable file, or a link to a Flickr external detail means include the submodel
     // (Copied from data_entry_helper::build_sample_occurrence_submission. If file_box control is used
     // then build_submission calls wrap_with_images instead)
     if (array_key_exists('location:image', $values) && $values['location:image'] || array_key_exists('location_image:external_details', $values) && $values['location_image:external_details']) {
         $structure['submodel'] = array('model' => 'location_image', 'fk' => 'location_id');
     }
     $s = submission_builder::build_submission($values, $structure);
     // On first save of a new location, link it to the website.
     // Be careful not to over-write other subModels (e.g. images)
     if (empty($values['location:id'])) {
         $s['subModels'][] = array('fkId' => 'location_id', 'model' => array('id' => 'locations_website', 'fields' => array('website_id' => $args['website_id'])));
     }
     return $s;
 }
 /** 
  * Extracts the sub-models required to populate member and administrator info from the form data.
  */
 private static function extractUserInfoFromFormValues(&$s, $values, $fieldname, $isAdmin)
 {
     $count = 0;
     if (!empty($values["groups_user:{$fieldname}"])) {
         if (!isset($s['subModels'])) {
             $s['subModels'] = array();
         }
         if (!empty($values["groups_user:{$fieldname}"])) {
             foreach ($values["groups_user:{$fieldname}"] as $userId) {
                 if ($userId) {
                     $values = array('user_id' => $userId, 'administrator' => $isAdmin);
                     $s['subModels'][] = array('fkId' => 'group_id', 'model' => submission_builder::wrap($values, 'groups_user'));
                     $count++;
                 }
             }
         }
     }
     return $count;
 }
 /**
  * Helper function to simplify building of a submission that contains a single supersample,
  * with multiple subsamples, each of which has multiple occurrences records, as generated 
  * by a species_checklist control.
  *
  * @param array $values List of the posted values to create the submission from.
  * @param integer $section_id_attribute The attribute ID that holds the section this record is against
  * @param boolean $include_if_any_data If true, then any list entry which has any data
  * set will be included in the submission. Set this to true when hiding the select checkbox
  * in the grid.
  * @param array $zero_attrs Set to an array of abundance attribute field IDs that can be
  * treated as abundances. Alternatively set to true to treat all occurrence custom attributes
  * as possible zero abundance indicators.
  * @param array $zero_values Set to an array of values which are considered to indicate a 
  * zero abundance record if found for one of the zero_attrs. Values are case-insensitive. Defaults to 
  * array('0','None','Absent').
  * of values that can be treated as meaning a zero abundance record. E.g.
  * array('
  * @return array Sample submission array
  */
 public static function build_sample_subsamples_occurrences_submission($values, $section_id_attribute, $include_if_any_data = false, $zero_attrs = true, $zero_values = array('0', 'None', 'Absent'))
 {
     $subsites = json_decode($values['subsites'], true);
     unset($values['subsites']);
     $subSampleIds = json_decode($values['subSampleIds'], true);
     unset($values['subSampleIds']);
     // We're mainly submitting to the sample model
     $sampleMod = submission_builder::wrap_with_images($values, 'sample');
     $subModels = self::wrap_species_checklist_with_subsamples($values, $section_id_attribute, $subsites, $subSampleIds, $include_if_any_data, $zero_attrs, $zero_values);
     // Add the subsamples/occurrences in as subModels without overwriting others such as a sample image
     if (array_key_exists('subModels', $sampleMod)) {
         $sampleMod['subModels'] = array_merge($sampleMod['subModels'], $subModels);
     } else {
         $sampleMod['subModels'] = $subModels;
     }
     return $sampleMod;
 }
 /**
  * Converts the posted form values for a group into a warehouse submission.
  * @param array $values Form values
  * @param array $args Form configuration arguments
  * @return array Submission data
  */
 public static function get_submission($values, $args)
 {
     $struct = array('model' => 'user_trust');
     return submission_builder::build_submission($values, $struct);
 }
Beispiel #20
0
 /**
  * Handles the construction of a submission array from a set of form values. 
  * @param array $values Associative array of form data values. 
  * @param array $args iform parameters. 
  * @return array Submission structure.
  */
 public static function get_submission($values, $args)
 {
     iform_load_helpers(array('submission_builder'));
     return submission_builder::build_submission($values, array('model' => 'termlists_term', 'superModels' => array('meaning' => array('fk' => 'meaning_id'), 'term' => array('fk' => 'term_id'))));
 }
Beispiel #21
0
 /**
  * Return the generated form output.
  * @param array $args List of parameter values passed through to the form depending on how the form has been configured.
  * This array always contains a value for language.
  * @param object $node The Drupal node object.
  * @param array $response When this form is reloading after saving a submission, contains the response from the service call.
  * Note this does not apply when redirecting (in this case the details of the saved object are in the $_GET data).
  * @return Form HTML.
  */
 public static function get_form($args, $node, $response = null)
 {
     if (!($user_id = hostsite_get_user_field('indicia_user_id'))) {
         return self::abort('Please ensure that you\'ve filled in your surname on your user profile before joining a group.', $args);
     }
     if (empty($_GET['group_id'])) {
         return self::abort('This form must be called with a group_id in the URL parameters.', $args);
     }
     $r = '';
     $auth = data_entry_helper::get_read_write_auth($args['website_id'], $args['password']);
     $group = data_entry_helper::get_population_data(array('table' => 'group', 'extraParams' => $auth['read'] + array('id' => $_GET['group_id']), 'nocache' => true));
     if (count($group) !== 1) {
         return self::abort('The group you\'ve requested membership of does not exist.', $args);
     }
     iform_load_helpers(array('submission_builder'));
     $group = $group[0];
     // Check for an existing group user record
     $existing = data_entry_helper::get_population_data(array('table' => 'groups_user', 'extraParams' => $auth['read'] + array('group_id' => $_GET['group_id'], 'user_id' => $user_id), 'nocache' => true));
     if (count($existing)) {
         if ($existing[0]['pending'] === 'true') {
             // if a previous request was made and unapproved when the group was request only, but the group is now public, we can approve their existing
             // groups_user record.
             if ($group['joining_method'] === 'P') {
                 $data = array('groups_user:id' => $existing[0]['id'], 'groups_user:pending' => 'f');
                 $wrap = submission_builder::wrap($data, 'groups_user');
                 $r = data_entry_helper::forward_post_to('groups_user', $wrap, $auth['write_tokens']);
                 return self::success($auth, $group, $args);
             } else {
                 return self::abort("You've already got a membership request for {$group['title']} pending approval.", $args);
             }
         } else {
             return self::abort("You're already a member of {$group['title']}.", $args);
         }
     } else {
         $data = array('groups_user:group_id' => $group['id'], 'groups_user:user_id' => $user_id);
         // request only, so make the groups_user record pending approval
         if ($group['joining_method'] === 'R') {
             $data['groups_user:pending'] = 't';
         }
         $wrap = submission_builder::wrap($data, 'groups_user');
         $r = data_entry_helper::forward_post_to('groups_user', $wrap, $auth['write_tokens']);
         if (!isset($r['success'])) {
             return self::abort('An error occurred whilst trying to update your group membership.', $args);
         } elseif ($group['joining_method'] === 'R') {
             return self::abort("Your request to join {$group['title']} is now awaiting approval.", $args);
         } else {
             return self::success($auth, $group, $args);
         }
     }
     return $r;
 }
 /**
  * Handles the construction of a submission array from a set of form values.
  * @param array $values Associative array of form data values.
  * @param array $args iform parameters.
  * @return array Submission structure.
  */
 public static function get_submission($values, $args)
 {
     $subsampleModels = array();
     $read = array('nonce' => $values['read_nonce'], 'auth_token' => $values['read_auth_token']);
     if (!isset($values['page']) || $values['page'] == 'site') {
         // submitting the first page, with top level sample details
         // keep the first count date on a subsample for use later.
         // only create if a new sample: if existing, then this will already exist.
         if (isset($values['C1:sample:date']) && !isset($values['sample:id'])) {
             $sampleMethods = helper_base::get_termlist_terms(array('read' => $read), 'indicia:sample_methods', array('Timed Count Count'));
             $smp = array('fkId' => 'parent_id', 'model' => array('id' => 'sample', 'fields' => array('survey_id' => array('value' => $values['sample:survey_id']), 'website_id' => array('value' => $values['website_id']), 'date' => array('value' => $values['C1:sample:date']), 'sample_method_id' => array('value' => $sampleMethods[0]['id']))), 'copyFields' => array('entered_sref' => 'entered_sref', 'entered_sref_system' => 'entered_sref_system'));
             //                   'copyFields' => array('date_start'=>'date_start','date_end'=>'date_end','date_type'=>'date_type'));
             $subsampleModels[] = $smp;
         }
     } else {
         if ($values['page'] == 'occurrences') {
             // at this point there is a parent supersample.
             // loop from 1 to numberOfCounts, or number of existing subsamples, whichever is bigger.
             $subSamples = data_entry_helper::get_population_data(array('table' => 'sample', 'extraParams' => $read + array('parent_id' => $values['sample:id']), 'nocache' => true));
             for ($i = 1; $i <= max(count($subSamples), $args['numberOfCounts']); $i++) {
                 if (isset($values['C' . $i . ':sample:id']) || isset($values['C' . $i . ':sample:date']) && $values['C' . $i . ':sample:date'] != '') {
                     $subSample = array('website_id' => $values['website_id'], 'survey_id' => $values['sample:survey_id']);
                     $occurrences = array();
                     $occModels = array();
                     foreach ($values as $field => $value) {
                         $parts = explode(':', $field, 2);
                         if ($parts[0] == 'C' . $i) {
                             $subSample[$parts[1]] = $value;
                         }
                         if ($parts[0] == 'O' . $i) {
                             $occurrences[$parts[1]] = $value;
                         }
                     }
                     ksort($occurrences);
                     foreach ($occurrences as $field => $value) {
                         // have take off O<i> do is now <j>:<ttlid>:<occid>:<attrid>:<attrvalid> - sorted in <j> order
                         $parts = explode(':', $field);
                         $occurrence = array('website_id' => $values['website_id']);
                         if ($parts[1] != '--ttlid--') {
                             $occurrence['taxa_taxon_list_id'] = $parts[1];
                         }
                         if ($parts[2] != '--occid--') {
                             $occurrence['id'] = $parts[2];
                         }
                         if ($value == '') {
                             $occurrence['deleted'] = 't';
                         } else {
                             if ($parts[4] == '--valid--') {
                                 $occurrence['occAttr:' . $parts[3]] = $value;
                             } else {
                                 $occurrence['occAttr:' . $parts[3] . ':' . $parts[4]] = $value;
                             }
                         }
                         if (array_key_exists('occurrence:determiner_id', $values)) {
                             $occurrence['determiner_id'] = $values['occurrence:determiner_id'];
                         }
                         if (array_key_exists('occurrence:record_status', $values)) {
                             $occurrence['record_status'] = $values['occurrence:record_status'];
                         }
                         if (isset($occurrence['id']) || !isset($occurrence['deleted'])) {
                             $occ = data_entry_helper::wrap($occurrence, 'occurrence');
                             $occModels[] = array('fkId' => 'sample_id', 'model' => $occ);
                         }
                     }
                     $smp = array('fkId' => 'parent_id', 'model' => data_entry_helper::wrap($subSample, 'sample'), 'copyFields' => array('entered_sref' => 'entered_sref', 'entered_sref_system' => 'entered_sref_system'));
                     // from parent->to child
                     if (!isset($subSample['sample:deleted']) && count($occModels) > 0) {
                         $smp['model']['subModels'] = $occModels;
                     }
                     $subsampleModels[] = $smp;
                 }
             }
         }
     }
     $sampleMod = submission_builder::build_submission($values, array('model' => 'sample'));
     if (count($subsampleModels) > 0) {
         $sampleMod['subModels'] = $subsampleModels;
     }
     return $sampleMod;
 }
 /**
  * Construct a submission for the location.
  * @param array $values Associative array of form data values. 
  * @param array $args iform parameters. 
  * @return array Submission structure.
  */
 public static function get_submission($values, $args)
 {
     $s = submission_builder::build_submission($values, array('model' => 'location'));
     // on first save of a new transect, link it to the website.
     if (empty($values['location:id'])) {
         $s['subModels'] = array(array('fkId' => 'location_id', 'model' => array('id' => 'locations_website', 'fields' => array('website_id' => $args['website_id']))));
     }
     return $s;
 }
 /**
  * Handles the construction of a submission array from a set of form values.
  * @param array $values Associative array of form data values. 
  * @param array $args iform parameters. 
  * @return array Submission structure.
  */
 public static function get_submission($values, $args)
 {
     return submission_builder::build_submission($values, array('model' => 'occurrence'));
 }
 public static function get_submission($values, $args)
 {
     $values['habitat-count'] = 2;
     $habitatSamples = array();
     for ($i = 1; $i <= $values['habitat-count']; $i++) {
         $habitatSamples["habitat{$i}"] = array();
     }
     foreach ($values as $key => $value) {
         if (substr_count($key, ':') === 3) {
             $parts = explode(':', $key, 4);
             if ($parts[0] === 'smpAttr') {
                 // If the last part of a habitat field is not a number, this is just a dummy field used
                 // when cloning habitat controls. We also skip empty new attribute values.
                 if (preg_match('/^\\d+$/', $parts[3]) && (!empty($parts[2]) || !empty($value))) {
                     // habitat number is the last part of the attribute field name
                     $id = array_pop($parts);
                     // remove empty stuff from the attribute name (e.g. an unused space for the existing value ID, if a new attribute value).
                     while (empty($parts[count($parts) - 1])) {
                         array_pop($parts);
                     }
                     $fieldname = implode(':', $parts);
                     $habitatSamples["habitat{$id}"][$fieldname] = $value;
                 }
                 unset($values[$key]);
             }
         }
         $parts = explode(':', $key);
         // For the group_name, the autocomplete functionality needs to be removed from the submission.
         // So copy the edit box into the underlying field which gets posted.
         if (array_pop($parts) === 'group_name') {
             $values[implode(':', $parts)] = $value;
         }
     }
     $buddyPairSubmission = submission_builder::wrap_with_images($values, 'sample');
     unset($buddyPairSubmission['fields']['habitat-count']);
     // Get the list of records implied by the SACFOR data for each habitat. At this point we'll create 1 big list and split
     // it across the habitats later.
     $occurrences = data_entry_helper::wrap_species_checklist($values, true, array(), array());
     // now work out which habitat contains which occurrence
     $habitatOccurrences = array();
     foreach (array_keys($habitatSamples) as $habitatId) {
         $habitatOccurrences[$habitatId] = array();
     }
     foreach ($occurrences as $occurrence) {
         // take a copy of the fields with all habitat data
         $fields = array_merge($occurrence['model']['fields']);
         // @todo Remove hard coded field ID.
         $habitatFields = preg_grep('/occAttr:243(:\\d+)?/', array_keys($fields));
         if (count($habitatFields)) {
             $habitatId = $fields[array_pop($habitatFields)]['value'];
         } else {
             // this case occurs when deleting an occurrence, as the habitat ID input field is disabled. Therefore
             // we need to revert to the original hidden sampleIdx field for the loaded record.
             $habitatId = $fields['sampleIDX']['value'] + 1;
         }
         // zero indexed
         $habitatOccurrences["habitat{$habitatId}"][] = $occurrence;
     }
     // now create the submodel data for each habitat.
     $buddyPairSubmission['subModels'] = array();
     // copy the basic sample data into each set of habitat subsample values
     foreach ($habitatSamples as $habitatId => &$habitatSample) {
         $habitatIdx = str_replace('habitat', '', $habitatId);
         $habitatSample['website_id'] = $values['website_id'];
         $habitatSample['survey_id'] = $values['survey_id'];
         if (isset($_POST["habitat_sample_id:{$habitatIdx}"])) {
             $habitatSample['sample:id'] = $_POST["habitat_sample_id:{$habitatIdx}"];
         }
         $habitatSample['sample:date'] = $values['sample:date'];
         $habitatSample['sample:entered_sref'] = $values['sample:entered_sref'];
         $habitatSample['sample:entered_sref_system'] = $values['sample:entered_sref_system'];
         $habitatSample['sample:input_form'] = $values['sample:input_form'];
         if (isset($_POST["sample:comment:{$habitatIdx}"])) {
             $habitatSample['sample:comment'] = $_POST["sample:comment:{$habitatIdx}"];
             unset($buddyPairSubmission['fields']["comment:{$habitatIdx}"]);
         }
         $habitatSubmission = submission_builder::wrap($habitatSample, 'sample');
         $habitatSubmission['subModels'] = $habitatOccurrences[$habitatId];
         $buddyPairSubmission['subModels'][] = array('fkId' => 'parent_id', 'model' => $habitatSubmission);
     }
     return $buddyPairSubmission;
 }
 /**
  * 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']);
 }
 /**
  * Given a reject response, delete the invite, and redirect to the groups home page.
  * @param array $args Form config arguments
  * @param array $invite Invitation record
  */
 private static function reject($args, $invite, $auth)
 {
     $values = array('id' => $invite['id'], 'deleted' => 't');
     $s = submission_builder::build_submission($values, array('model' => 'group_invitation'));
     $r = data_entry_helper::forward_post_to('group_invitation', $s, $auth['write_tokens']);
     hostsite_show_message(lang::get("OK, thanks anyway. We've removed your invitation to join this group."));
     hostsite_goto_page($args['groups_page_path']);
 }
Beispiel #28
0
 /**
  * Wraps a standard $_POST type array into a save array suitable for use in saving
  * records.
  *
  * @param array $array Array to wrap
  * @param bool $fkLink=false Link foreign keys?
  * @return array Wrapped array
  */
 protected function wrap($array, $fkLink = false)
 {
     // share the wrapping library with the client helpers
     require_once DOCROOT . 'client_helpers/submission_builder.php';
     $r = submission_builder::build_submission($array, $this->get_submission_structure());
     // Map fk_* fields to the looked up id
     if ($fkLink) {
         $r = $this->getFkFields($r, $array);
     }
     if (array_key_exists('superModels', $r)) {
         $idx = 0;
         foreach ($r['superModels'] as $super) {
             $r['superModels'][$idx]['model'] = $this->getFkFields($super['model'], $array);
             $idx++;
         }
     }
     return $r;
 }
 /**
  * Handles the construction of a submission array from a set of form values.
  * @param array $values Associative array of form data values.
  * @param array $args iform parameters.
  * @return array Submission structure.
  */
 public static function get_submission($values, $args)
 {
     global $user;
     $subsampleModels = array();
     $submission = submission_builder::build_submission($values, array('model' => 'sample'));
     // this handles the photos as well.
     // deal with any species grid options.
     foreach ($values as $key => $value) {
         $parts = explode(':', $key, 5);
         if ($parts[0] == 'Grid') {
             $details = explode(':', $parts[4], 3);
             if (!isset($subsampleModels[$parts[1]])) {
                 $smp = array('fkId' => 'parent_id', 'model' => array('id' => 'sample', 'fields' => array('sample_method_id' => array('value' => $args['quadrat_level_sample_method_id']))), 'data' => $parts[2] != '', 'copyFields' => array('survey_id' => 'survey_id', 'date_start' => 'date_start', 'date_end' => 'date_end', 'date_type' => 'date_type', 'entered_sref_system' => 'entered_sref_system', 'entered_sref' => 'entered_sref', 'location_name' => 'location_name'));
                 // from parent->to child
                 if ($parts[2] != '') {
                     // set any existing subsample id
                     $smp['model']['fields']['id'] = array('value' => $parts[2]);
                 }
                 $subsampleModels[$parts[1]] = $smp;
             }
             if ($parts[3] == 'smpAttr') {
                 $subsampleModels[$parts[1]]['model']['fields']['smpAttr:' . $parts[4]] = array('value' => $value);
                 if ($details[0] != $args['sample_attribute_id_1'] && (!isset($args['sample_attribute_id_2']) || $args['sample_attribute_id_2'] == '' || $details[0] != $args['sample_attribute_id_2'])) {
                     $subsampleModels[$parts[1]]['data'] = $subsampleModels[$parts[1]]['data'] || $value != '';
                 }
             } else {
                 if ($parts[3] == 'occ') {
                     $occ = array('fkId' => 'sample_id', 'model' => array('id' => 'occurrence', 'fields' => array('taxa_taxon_list_id' => array('value' => $details[0]), 'website_id' => array('value' => $values['website_id']), 'record_status' => array('value' => $values['occurrence:record_status']), 'zero_abundance' => array('value' => $value != '0' ? 'f' : 't'), $details[2] => array('value' => $value))));
                     if ($details[1] != '') {
                         $occ['model']['fields']['id'] = array('value' => $details[1]);
                     }
                     if ($value != '' || $details[1] != '') {
                         if (!isset($subsampleModels[$parts[1]]['model']['subModels'])) {
                             $subsampleModels[$parts[1]]['model']['subModels'] = array($occ);
                         } else {
                             $subsampleModels[$parts[1]]['model']['subModels'][] = $occ;
                         }
                         $subsampleModels[$parts[1]]['data'] = true;
                     }
                 }
             }
         }
     }
     foreach ($subsampleModels as $row => $data) {
         if (!$subsampleModels[$row]['data']) {
             unset($subsampleModels[$row]);
         }
     }
     if (count($subsampleModels) > 0) {
         $submission['subModels'] = array_merge(isset($submission['subModels']) && is_array($submission['subModels']) ? $submission['subModels'] : array(), array_values($subsampleModels));
         //if($user->uid == 1)
         //	drupal_set_message(print_r($submission,true), 'warning');
     }
     return $submission;
 }
Beispiel #30
0
 public function testCreateUser()
 {
     $array = array('person:first_name' => 'Test', 'person:surname' => 'Person', 'person:email_address' => '*****@*****.**');
     $s = submission_builder::build_submission($array, array('model' => 'person'));
     $r = data_entry_helper::forward_post_to('person', $s, $this->auth['write_tokens']);
     $this->assertTrue(isset($r['success']), 'Submitting a new person did not work');
     $personId = $r['success'];
     $array = array('user:person_id' => $personId, 'user:email_visible' => 'f', 'user:core_role_id' => 1, 'user:username' => 'testUser');
     $s = submission_builder::build_submission($array, array('model' => 'user'));
     $r = data_entry_helper::forward_post_to('user', $s, $this->auth['write_tokens']);
     $this->assertTrue(isset($r['success']), 'Submitting a new user did not work');
     $userId = $r['success'];
     ORM::Factory('user', $userId)->delete();
     ORM::Factory('person', $personId)->delete();
 }