Example #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;
}
 /**
  * Return the Indicia form code
  * @param array $args Input parameters.
  * @param array $node Drupal node object
  * @return HTML string
  */
 public static function get_form($args, $node)
 {
     iform_load_helpers(array('import_helper', 'report_helper'));
     $args['model'] = 'occurrence';
     $auth = import_helper::get_read_write_auth($args['website_id'], $args['password']);
     $model = $args['model'];
     if (isset($args['presetSettings'])) {
         $presets = get_options_array_with_user_data($args['presetSettings']);
         $presets = array_merge(array('website_id' => $args['website_id'], 'password' => $args['password']), $presets);
     } else {
         $presets = array('website_id' => $args['website_id'], 'password' => $args['password']);
     }
     $r = self::importer(array('model' => $model, 'auth' => $auth, 'presetSettings' => $presets), $args);
     return $r;
 }
Example #3
0
 /**
  * Return the Indicia form code
  * @param array $args Input parameters.
  * @param array $node Drupal node object
  * @param array $response Response from Indicia services after posting a verification.
  * @return HTML string
  */
 public static function get_form($args, $node, $response)
 {
     iform_load_helpers(array('import_helper'));
     $auth = import_helper::get_read_write_auth($args['website_id'], $args['password']);
     group_authorise_form($args, $auth['read']);
     if ($args['model'] == 'url') {
         if (!isset($_GET['type'])) {
             return "This form is configured so that it must be called with a type parameter in the URL";
         }
         $model = $_GET['type'];
     } else {
         $model = $args['model'];
     }
     if (isset($args['presetSettings'])) {
         $presets = get_options_array_with_user_data($args['presetSettings']);
         $presets = array_merge(array('website_id' => $args['website_id'], 'password' => $args['password']), $presets);
     } else {
         $presets = array('website_id' => $args['website_id'], 'password' => $args['password']);
     }
     if (!empty($_GET['group_id'])) {
         // loading data into a recording group.
         $group = data_entry_helper::get_population_data(array('table' => 'group', 'extraParams' => $auth['read'] + array('id' => $_GET['group_id'], 'view' => 'detail')));
         $group = $group[0];
         $presets['sample:group_id'] = $_GET['group_id'];
         hostsite_set_page_title(lang::get('Import data into the {1} group', $group['title']));
         // if a single survey specified for this group, then force the data into the correct survey
         $filterdef = json_decode($group['filter_definition'], true);
         if (!empty($filterdef['survey_list_op']) && $filterdef['survey_list_op'] === 'in' && !empty($filterdef['survey_list'])) {
             $surveys = explode(',', $filterdef['survey_list']);
             if (count($surveys) === 1) {
                 $presets['survey_id'] = $surveys[0];
             }
         }
     }
     try {
         $r = import_helper::importer(array('model' => $model, 'auth' => $auth, 'presetSettings' => $presets));
     } catch (Exception $e) {
         hostsite_show_message($e->getMessage(), 'warning');
         $reload = import_helper::get_reload_link_parts();
         unset($reload['params']['total']);
         unset($reload['params']['uploaded_csv']);
         $reloadpath = $reload['path'] . '?' . import_helper::array_to_query_string($reload['params']);
         $r = "<p>" . lang::get('Would you like to ') . "<a href=\"{$reloadpath}\">" . lang::get('import another file?') . "</a></p>";
     }
     return $r;
 }
Example #4
0
 /**
  * Return the Indicia form code
  * @param array $args Input parameters.
  * @param array $node Drupal node object
  * @param array $response Response from Indicia services after posting a verification.
  * @return HTML string
  */
 public static function get_form($args, $node, $response)
 {
     iform_load_helpers(array('import_helper'));
     $auth = import_helper::get_read_write_auth($args['website_id'], $args['password']);
     if ($args['model'] == 'url') {
         if (!isset($_GET['type'])) {
             return "This form is configured so that it must be called with a type parameter in the URL";
         }
         $model = $_GET['type'];
     } else {
         $model = $args['model'];
     }
     if (isset($args['presetSettings'])) {
         $presets = get_options_array_with_user_data($args['presetSettings']);
         $presets = array_merge(array('website_id' => $args['website_id'], 'password' => $args['password']), $presets);
     } else {
         $presets = array('website_id' => $args['website_id'], 'password' => $args['password']);
     }
     $r = import_helper::importer(array('model' => $model, 'auth' => $auth, 'presetSettings' => $presets));
     return $r;
 }
 private static function build_filter($args, $readAuth, $format, $useStandardParams)
 {
     require_once 'includes/user.php';
     $filterToApply = $_POST['user-filter'];
     $availableFilters = self::get_filters($args, $readAuth);
     if (!array_key_exists($filterToApply, $availableFilters)) {
         throw new exception('Selected filter type not authorised');
     }
     if ($filterToApply === 'expert') {
         require_once 'includes/user.php';
         $location_expertise = hostsite_get_user_field('location_expertise');
         $taxon_groups_expertise = hostsite_get_user_field('taxon_groups_expertise');
         $taxon_groups_expertise = $taxon_groups_expertise ? unserialize($taxon_groups_expertise) : null;
         $surveys_expertise = hostsite_get_user_field('surveys_expertise');
         $available_surveys = $surveys_expertise ? unserialize($surveys_expertise) : null;
     } else {
         // Default is no filter by survey, locality, taxon group
         $location_expertise = '';
         $available_surveys = '';
         $taxon_groups_expertise = '';
         $surveys_expertise = '';
     }
     // We are downloading either a configured survey, a selected single survey, or the surveys the
     // user can see. The field name used will depend on which of the survey selects were active -
     // either we are selecting from a list of surveys the user is an expert for, or a list of
     // all surveys.
     $surveyFieldName = 'survey_id_' . (preg_match('/^expert/', $filterToApply) ? 'expert' : 'all');
     if (empty($args['survey_id'])) {
         $surveys = empty($_POST[$surveyFieldName]) ? implode(',', $available_surveys) : $_POST[$surveyFieldName];
     } else {
         // survey to load is preconfigured for the form
         $surveys = $args['survey_id'];
     }
     $ownData = $filterToApply === 'mine' ? 1 : 0;
     // depending on if we are using the old explore report format or the new filterable format, the filter field names differ
     $userIdField = $useStandardParams ? 'user_id' : 'currentUser';
     $myRecordsField = $useStandardParams ? 'my_records' : 'ownData';
     $locationIdField = $useStandardParams ? 'indexed_location_id' : 'location_id';
     $surveysListField = $useStandardParams ? 'survey_list' : 'surveys';
     $taxonGroupListField = $useStandardParams ? 'taxon_group_list' : 'taxon_groups';
     $filters = array_merge(array($userIdField => hostsite_get_user_field('indicia_user_id'), $myRecordsField => $ownData, $locationIdField => $location_expertise, 'ownLocality' => !empty($location_expertise) && $filterToApply === 'expert' ? 1 : 0, $taxonGroupListField => !empty($taxon_groups_expertise) ? implode(',', $taxon_groups_expertise) : '', 'ownGroups' => !empty($taxon_groups_expertise) && $taxon_groups_expertise && $filterToApply === 'expert' ? 1 : 0, $surveysListField => $surveys, 'ownSurveys' => empty($surveys) ? 0 : 1), get_options_array_with_user_data($args["report_params_{$format}"]));
     // some of these filter fields are not required for standard params
     if ($useStandardParams) {
         unset($filters['ownLocality']);
         unset($filters['ownGroups']);
         unset($filters['ownSurveys']);
     }
     if (!empty($_POST['date_from']) && $_POST['date_from'] !== lang::get('Click here')) {
         $filters['date_from'] = $_POST['date_from'];
     } else {
         if (!$useStandardParams) {
             $filters['date_from'] = '';
         }
     }
     if (!empty($_POST['date_to']) && $_POST['date_to'] !== lang::get('Click here')) {
         $filters['date_to'] = $_POST['date_to'];
     } else {
         if (!$useStandardParams) {
             $filters['date_to'] = '';
         }
     }
     // now, if they have a verification context filter in force, then apply it
     $filters = array_merge(self::get_filter_verification_context($filterToApply, $readAuth), $filters);
     return $filters;
 }
 /**
  * Performs the download.
  * @global array $indicia_templates
  * @param type $args
  * @param type $node
  */
 private static function do_data_services_download($args, $node)
 {
     iform_load_helpers(array('report_helper'));
     $format = $_POST['format'];
     $isCustom = preg_match('/^custom-(\\d+)$/', $_POST['format'], $matches);
     if ($isCustom) {
         $customFormats = json_decode($args['custom_formats'], true);
         $customFormat = $customFormats[$matches[1]];
         $report = $customFormat['report'];
         // strip unnecessary .xml from end of report name if provided
         $report = preg_replace('/\\.xml$/', '', $report);
         $format = $customFormat['format'];
         $additionalParamText = $customFormat['params'];
     } else {
         $report = $args["report_{$format}"];
         $additionalParamText = $args["report_params_{$format}"];
     }
     $params = self::build_params($args);
     $params = array_merge($params, get_options_array_with_user_data($additionalParamText));
     $conn = iform_get_connection_details($node);
     global $indicia_templates;
     // let's just get the URL, not the whole anchor element
     $indicia_templates['report_download_link'] = '{link}';
     $limit = $args['limit'] == 0 ? '' : $args['limit'];
     // unlimited or limited
     $sharing = substr($_POST['download-type'], 0, 1);
     $url = report_helper::report_download_link(array('readAuth' => data_entry_helper::$js_read_tokens, 'dataSource' => $report, 'extraParams' => $params, 'format' => $format, 'sharing' => self::expand_sharing_mode($sharing), 'itemsPerPage' => $limit));
     if ($args['reverse_proxy'] == true) {
         // Rewrite the url to pass through proxy.php
         $relative_proxy_path = iform_client_helpers_path() . 'proxy.php?url=' . report_helper::$base_url;
         global $base_url;
         $proxy_path = $base_url . substr($relative_proxy_path, 1);
         // remove report_helper::$base_url from $url
         $url = substr($url, strlen(report_helper::$base_url));
         // add $proxy_path to $url
         $url = $proxy_path . $url;
     }
     header("Location: {$url}");
 }
Example #7
0
/**
 * Function similar to get_options_array_with_user_data, but accepts input data in a format read from the form structure
 * definition for a block of attributes in a dynamic form and returns data in a format ready for passing to the code which
 * builds the attribute html.
 */
function get_attr_options_array_with_user_data($listData)
{
    $r = array();
    $data = get_options_array_with_user_data($listData);
    foreach ($data as $key => $value) {
        $tokens = explode('|', $key);
        $r[$tokens[0]][$tokens[1]] = $value;
    }
    return $r;
}
 /**
  * Return the Indicia form code
  * @param array $args Input parameters.
  * @param array $node Drupal node object
  * @param array $response Response from Indicia services after posting a verification.
  * @return HTML string
  */
 public static function get_form($args, $node, $response)
 {
     global $user;
     $retVal = '';
     $logged_in = $user->uid > 0;
     if (!$logged_in) {
         return '<p>' . lang::get('Please log in before attempting to use this form.') . '</p>';
     }
     // can't really do this automatically: better to give warning
     if (isset($args['locationTypeFilter'])) {
         return '<p>' . lang::get('Please contact the site administrator. This version of the form uses a different method of specifying the location types.') . '</p>';
     }
     iform_load_helpers(array('report_helper'));
     $auth = report_helper::get_read_auth($args['website_id'], $args['password']);
     if (!self::set_up_survey($args, $auth)) {
         return lang::get('set_up_survey returned false: survey_id missing from presets or location_type definition.');
     }
     $reportOptions = self::get_report_calendar_2_options($args, $auth);
     $reportOptions['id'] = 'calendar-summary-' . $node->nid;
     if (!empty($args['removable_params'])) {
         self::$removableParams = get_options_array_with_user_data($args['removable_params']);
     }
     self::copy_args($args, $reportOptions, array('weekstart', 'weekOneContains', 'weekNumberFilter', 'outputTable', 'outputChart', 'tableHeaders', 'chartLabels', 'disableableSeries', 'chartType', 'rowGroupColumn', 'rowGroupID', 'width', 'height', 'includeChartTotalSeries', 'includeChartItemSeries', 'includeRawData', 'includeSummaryData', 'includeEstimatesData', 'includeRawGridDownload', 'includeSummaryGridDownload', 'includeEstimatesGridDownload', 'sampleFields'));
     if (isset($_GET['outputSeries'])) {
         $reportOptions['outputSeries'] = $_GET['outputSeries'];
     }
     // default is all
     // Advanced Chart options
     $rendererOptions = trim($args['renderer_options']);
     if (!empty($rendererOptions)) {
         $reportOptions['rendererOptions'] = json_decode($rendererOptions, true);
     }
     $axesOptions = trim($args['axes_options']);
     if (!empty($axesOptions)) {
         $reportOptions['axesOptions'] = json_decode($axesOptions, true);
     }
     if (isset($args['countColumn']) && $args['countColumn'] != '') {
         $reportOptions['countColumn'] = 'attr_occurrence_' . str_replace(' ', '_', strtolower($args['countColumn']));
         // assume that this is an occurrence attribute.
         $reportOptions['extraParams']['occattrs'] = $args['countColumn'];
     }
     // for a normal user, we can only link to those samples we have created
     $reportOptions['location_list'] = array();
     // for a branch user, we have an allowed list of locations for which we can link to the sample.
     self::$branchLocationList = array();
     if (isset($args['branch_manager_permission']) && $args['branch_manager_permission'] != "" && user_access($args['branch_manager_permission'])) {
         // Get list of locations attached to this user via the branch cms user id attribute
         // first need to scan param_presets for survey_id..
         $attrArgs = array('valuetable' => 'location_attribute_value', 'attrtable' => 'location_attribute', 'key' => 'location_id', 'fieldprefix' => 'locAttr', 'extraParams' => $auth, 'survey_id' => self::$siteUrlParams[self::$SurveyKey]);
         if (isset($args['locationTypesFilter']) && $args['locationTypesFilter'] != "") {
             $attrArgs['location_type_id'] = self::$siteUrlParams[self::$locationTypeKey]['value'];
         }
         $locationAttributes = data_entry_helper::getAttributes($attrArgs, false);
         $cmsAttr = self::extract_attr($locationAttributes, $args['branchFilterAttribute']);
         if (!$cmsAttr) {
             return lang::get('Branch Manager location list lookup: missing Branch allocation attribute') . ' {' . print_r($attrArgs, true) . '} : ' . $args['branchFilterAttribute'];
         }
         $attrListArgs = array('extraParams' => array_merge(array('view' => 'list', 'website_id' => $args['website_id'], 'location_attribute_id' => $cmsAttr['attributeId'], 'raw_value' => $user->uid), $auth), 'table' => 'location_attribute_value');
         $attrList = data_entry_helper::get_population_data($attrListArgs);
         if (isset($attrList['error'])) {
             return $attrList['error'];
         }
         if (count($attrList) > 0) {
             foreach ($attrList as $attr) {
                 self::$branchLocationList[] = $attr['location_id'];
             }
         }
         $reportOptions['location_list'] = self::$branchLocationList;
     }
     // for an admin, we can link to all samples.
     if (isset($args['manager_permission']) && $args['manager_permission'] != "" && user_access($args['manager_permission'])) {
         $reportOptions['location_list'] = 'all';
     }
     // Add controls first: set up a control bar
     $retVal .= "\n<table id=\"controls-table\" class=\"ui-widget ui-widget-content ui-corner-all controls-table\"><thead class=\"ui-widget-header\"><tr>";
     $retVal .= self::year_control($args, $auth, $node, $reportOptions);
     $retVal .= '<th>' . self::user_control($args, $auth, $node, $reportOptions) . '</th>';
     $retVal .= '<th>' . self::location_control($args, $auth, $node, $reportOptions) . '</th>';
     // note this includes the location_type control if needed
     $siteUrlParams = self::get_site_url_params();
     if (!empty($args['removable_params'])) {
         foreach (self::$removableParams as $param => $caption) {
             $checked = isset($_GET[$param]) && $_GET[$param] === 'true' ? ' checked="checked"' : '';
             $retVal .= '<th><input type="checkbox" name="removeParam-' . $param . '" id="removeParam-' . $param . '" class="removableParam"' . $checked . '/>' . '<label for="removeParam-' . $param . '" >' . lang::get($caption) . '</label></th>';
             if ($checked != '') {
                 $reportOptions['downloadFilePrefix'] .= 'RM' . preg_replace('/[^A-Za-z0-9]/i', '', $param) . '_';
             }
         }
         self::set_up_control_change('removeParam-' . $param, $param, array(), true);
     }
     // are there any params that should be set to blank using one of the removable params tickboxes?
     foreach (self::$removableParams as $param => $caption) {
         if (isset($_GET[$param]) && $_GET[$param] === 'true') {
             $reportOptions[$param] = '';
             $reportOptions['extraParams'][$param] = '';
         }
     }
     if (self::$siteUrlParams[self::$locationTypeKey]['value'] == '') {
         if (isset($args['locationTypesFilter']) && $args['locationTypesFilter'] != "") {
             $types = explode(',', $args['locationTypesFilter']);
             $terms = self::get_sorted_termlist_terms(array('read' => $auth), 'indicia:location_types', array($types[0]));
             $reportOptions['extraParams']['location_type_id'] = $terms[0]['id'];
         }
     } else {
         $reportOptions['extraParams']['location_type_id'] = self::$siteUrlParams[self::$locationTypeKey]['value'];
     }
     if (isset($args['linkURL'])) {
         $reportOptions['linkURL'] = $args['linkURL'] . (isset($siteUrlParams[self::$URLExtensionKey]) ? $siteUrlParams[self::$URLExtensionKey] : '');
         $reportOptions['linkURL'] .= (strpos($reportOptions['linkURL'], '?') !== FALSE ? '&' : '?') . 'sample_id=';
     }
     $reportOptions['includeReportTimeStamp'] = isset($args['includeFilenameTimestamps']) && $args['includeFilenameTimestamps'];
     $retVal .= '</tr></thead></table>';
     $reportOptions['survey_id'] = self::$siteUrlParams[self::$SurveyKey];
     // Sort of assuming that only one location type recorded against per survey.
     $reportOptions['downloads'] = array();
     if (isset($args['manager_permission']) && $args['manager_permission'] != "" && user_access($args['manager_permission']) || $reportOptions['extraParams']['location_list'] != '' || $reportOptions['extraParams']['user_id'] != '') {
         // if user specified - either me in normal or branch mode, or a manager
         for ($i = 1; $i <= 4; $i++) {
             if (isset($args['Download' . $i . 'Caption']) && $args['Download' . $i . 'Caption'] != "" && isset($args['download_report_' . $i]) && $args['download_report_' . $i] != "") {
                 $reportOpts = array('caption' => $args['Download' . $i . 'Caption'], 'dataSource' => $args['download_report_' . $i], 'filename' => $reportOptions['downloadFilePrefix'] . preg_replace('/[^A-Za-z0-9]/i', '', $args['Download' . $i . 'Caption']) . (isset($reportOptions['includeReportTimeStamp']) && $reportOptions['includeReportTimeStamp'] ? '_' . date('YmdHis') : ''));
                 if (isset($args['download_report_' . $i . '_format'])) {
                     $reportOpts['format'] = $args['download_report_' . $i . '_format'];
                 }
                 $reportOptions['downloads'][] = $reportOpts;
             }
         }
     } else {
         $reportOptions['includeRawGridDownload'] = false;
     }
     $retVal .= report_helper::report_calendar_summary2($reportOptions);
     return $retVal;
 }
 /**
  * Return the Indicia form code
  * @param array $args Input parameters.
  * @param array $node Drupal node object
  * @param array $response Response from Indicia services after posting a verification.
  * @return HTML string
  */
 public static function get_form($args, $node, $response)
 {
     global $user;
     $logged_in = $user->uid > 0;
     if (!$logged_in) {
         return '<p>' . lang::get('Please log in before attempting to use this form.') . '</p>';
     }
     // can't really do this automatically: better to give warning
     if (isset($args['locationTypeFilter'])) {
         return '<p>' . lang::get('Please contact the site administrator. This version of the form uses a different method of specifying the location types.') . '</p>';
     }
     iform_load_helpers(array('report_helper'));
     $auth = report_helper::get_read_auth($args['website_id'], $args['password']);
     if (!self::set_up_survey($args, $auth)) {
         return lang::get('set_up_survey returned false: survey_id missing from presets or location_type definition.');
     }
     $reportOptions = self::get_report_calendar_options($args, $auth);
     $reportOptions['id'] = 'calendar-summary-' . $node->nid;
     if (!empty($args['removable_params'])) {
         self::$removableParams = get_options_array_with_user_data($args['removable_params']);
     }
     self::copy_args($args, $reportOptions, array('weekstart', 'weekOneContains', 'weekNumberFilter', 'outputTable', 'outputChart', 'simultaneousOutput', 'tableHeaders', 'chartLabels', 'disableableSeries', 'chartType', 'rowGroupColumn', 'rowGroupID', 'width', 'height', 'includeTableTotalRow', 'includeTableTotalColumn', 'includeChartTotalSeries', 'includeChartItemSeries', 'includeRawData', 'includeSummaryData', 'includeEstimatesData', 'summaryDataCombining', 'dataRound', 'zeroPointAnchor', 'interpolation', 'firstValue', 'lastValue', 'linkURL', 'includeRawGridDownload', 'includeRawListDownload', 'includeSummaryGridDownload', 'includeEstimatesGridDownload', 'includeListDownload', 'avgFields'));
     if (isset($_GET['outputSource'])) {
         $reportOptions['outputSource'] = $_GET['outputSource'];
     }
     if (isset($_GET['outputFormat'])) {
         $reportOptions['outputFormat'] = $_GET['outputFormat'];
     } else {
         $reportOptions['outputFormat'] = $args['defaultOutput'];
     }
     if (isset($_GET['outputSeries'])) {
         $reportOptions['outputSeries'] = $_GET['outputSeries'];
     }
     // default is all
     // Advanced Chart options
     $rendererOptions = trim($args['renderer_options']);
     if (!empty($rendererOptions)) {
         $reportOptions['rendererOptions'] = json_decode($rendererOptions, true);
     }
     $legendOptions = trim($args['legend_options']);
     if (!empty($legendOptions)) {
         $reportOptions['legendOptions'] = json_decode($legendOptions, true);
     }
     $axesOptions = trim($args['axes_options']);
     if (!empty($axesOptions)) {
         $reportOptions['axesOptions'] = json_decode($axesOptions, true);
     }
     if (isset($args['countColumn']) && $args['countColumn'] != '') {
         $reportOptions['countColumn'] = 'attr_occurrence_' . str_replace(' ', '_', strtolower($args['countColumn']));
         // assume that this is an occurrence attribute.
         $reportOptions['extraParams']['occattrs'] = $args['countColumn'];
     }
     // for a normal user, we can only link to those samples we have created
     $reportOptions['location_list'] = array();
     // for a branch user, we have an allowed list of locations for which we can link to the sample.
     self::$branchLocationList = array();
     if (isset($args['branchManagerPermission']) && $args['branchManagerPermission'] != "" && user_access($args['branchManagerPermission'])) {
         // Get list of locations attached to this user via the branch cms user id attribute
         // first need to scan param_presets for survey_id..
         $attrArgs = array('valuetable' => 'location_attribute_value', 'attrtable' => 'location_attribute', 'key' => 'location_id', 'fieldprefix' => 'locAttr', 'extraParams' => $auth, 'survey_id' => self::$siteUrlParams[self::$SurveyKey]);
         if (isset($args['locationTypesFilter']) && $args['locationTypesFilter'] != "") {
             $attrArgs['location_type_id'] = self::$siteUrlParams[self::$locationTypeKey]['value'];
         }
         $locationAttributes = data_entry_helper::getAttributes($attrArgs, false);
         $cmsAttr = self::extract_attr($locationAttributes, $args['branchFilterAttribute']);
         if (!$cmsAttr) {
             return lang::get('Branch Manager location list lookup: missing Branch allocation attribute') . ' {' . print_r($attrArgs, true) . '} : ' . $args['branchFilterAttribute'];
         }
         $attrListArgs = array('extraParams' => array_merge(array('view' => 'list', 'website_id' => $args['website_id'], 'location_attribute_id' => $cmsAttr['attributeId'], 'raw_value' => $user->uid), $auth), 'table' => 'location_attribute_value');
         $attrList = data_entry_helper::get_population_data($attrListArgs);
         if (isset($attrList['error'])) {
             return $attrList['error'];
         }
         if (count($attrList) > 0) {
             foreach ($attrList as $attr) {
                 self::$branchLocationList[] = $attr['location_id'];
             }
         }
         $reportOptions['location_list'] = self::$branchLocationList;
     }
     // for an admin, we can link to all samples.
     if (isset($args['managerPermission']) && $args['managerPermission'] != "" && user_access($args['managerPermission'])) {
         $reportOptions['location_list'] = 'all';
     }
     if (function_exists('module_exists') && module_exists('easy_login') && function_exists('hostsite_get_user_field')) {
         $reportOptions['my_user_id'] = hostsite_get_user_field('indicia_user_id');
     } else {
         $reportOptions['my_user_id'] = $user->uid;
     }
     $retVal = '';
     // Add controls first: set up a control bar
     $retVal .= "\n<table id=\"controls-table\" class=\"ui-widget ui-widget-content ui-corner-all controls-table\"><thead class=\"ui-widget-header\"><tr>";
     $retVal .= self::date_control($args, $auth, $node, $reportOptions);
     $retVal .= '<th>' . self::user_control($args, $auth, $node, $reportOptions) . '</th>';
     $retVal .= '<th>' . self::location_control($args, $auth, $node, $reportOptions) . '</th>';
     // note this includes the location_type control if needed
     $siteUrlParams = self::get_site_url_params();
     if (!empty($args['removable_params'])) {
         foreach (self::$removableParams as $param => $caption) {
             $checked = isset($_GET[$param]) && $_GET[$param] === 'true' ? ' checked="checked"' : '';
             $retVal .= '<th><input type="checkbox" name="removeParam-' . $param . '" id="removeParam-' . $param . '" class="removableParam"' . $checked . '/>' . '<label for="removeParam-' . $param . '" >' . lang::get($caption) . '</label></th>';
         }
         self::set_up_control_change('removeParam-' . $param, $param, array(), true);
     }
     // are there any params that should be set to blank using one of the removable params tickboxes?
     foreach (self::$removableParams as $param => $caption) {
         if (isset($_GET[$param]) && $_GET[$param] === 'true') {
             $reportOptions['extraParams'][$param] = '';
         }
     }
     if (self::$siteUrlParams[self::$userKey]['value'] == '' && self::$siteUrlParams[self::$locationKey]['value'] == '') {
         $checked = self::$siteUrlParams[self::$cacheKey]['value'] === 'true' ? ' checked="checked"' : '';
         $retVal .= '<th><input type="checkbox" name="cachingParam" id="cachingParam" class="cachingParam"' . $checked . '/>' . '<label for="cachingParam" title="' . lang::get("When fetching the full data set, selcting this improves performance by not going to the warehouse to get the data. Occassionally, even when selected, the data will be refreshed, which will appear to slow down the response.") . '" >' . lang::get("Use cached data") . '</label></th>';
         $reportOptions['caching'] = self::$siteUrlParams[self::$cacheKey]['value'] === 'true' ? true : 'store';
         self::set_up_control_change('cachingParam', self::$cacheKey, array(), true);
         $checked = self::$siteUrlParams[self::$downloadKey]['value'] === 'true' ? ' checked="checked"' : '';
         if (self::$siteUrlParams[self::$downloadKey]['value'] !== 'true' && isset($reportOptions['includeListDownload']) && $reportOptions['includeListDownload'] == true) {
             $reportOptions['includeRawGridDownload'] = false;
             $reportOptions['includeRawListDownload'] = false;
             $reportOptions['includeSummaryGridDownload'] = false;
             $reportOptions['includeEstimatesGridDownload'] = false;
             $reportOptions['includeListDownload'] = false;
             for ($i = 1; $i <= 4; $i++) {
                 unset($args['Download' . $i . 'Caption']);
                 unset($args['download_report_' . $i]);
             }
             data_entry_helper::$javascript .= "jQuery('.downloads-table-label').remove();\n" . "jQuery('#downloads-table thead tr').prepend('<th>" . "<label for=\"downloadParam\" title=\"" . lang::get("When fetching the full data set, unselecting this improves performance by not including the download data in the page. This extra data can lead to a significantly increase in download time.") . "\" >" . lang::get("Include Downloads") . "</label>" . "<input type=\"checkbox\" name=\"downloadParam\" id=\"downloadParam\" class=\"downloadParam\"" . $checked . "/>" . "</th>');\n";
             self::set_up_control_change('downloadParam', self::$downloadKey, array(), true);
         }
     }
     if (self::$siteUrlParams[self::$locationTypeKey]['value'] == '') {
         if (isset($args['locationTypesFilter']) && $args['locationTypesFilter'] != "") {
             $types = explode(',', $args['locationTypesFilter']);
             $terms = self::get_sorted_termlist_terms(array('read' => $auth), 'indicia:location_types', array($types[0]));
             $reportOptions['extraParams']['location_type_id'] = $terms[0]['id'];
         }
     } else {
         $reportOptions['extraParams']['location_type_id'] = self::$siteUrlParams[self::$locationTypeKey]['value'];
     }
     $reportOptions['includeReportTimeStamp'] = isset($args['includeFilenameTimestamps']) && $args['includeFilenameTimestamps'];
     $retVal .= '</tr></thead></table>';
     $reportOptions['highlightEstimates'] = true;
     $retVal .= report_helper::report_calendar_summary($reportOptions);
     // upto this point the report options holds the cms user id as user_id: the report_helper converts this to the indicia
     // user_id if relevant to this installation. We now need to do the same for the report links.
     if (isset($reportOptions['extraParams']['user_id'])) {
         $reportOptions['extraParams']['cms_user_id'] = $reportOptions['extraParams']['user_id'];
         if (function_exists('module_exists') && module_exists('easy_login')) {
             $account = user_load($reportOptions['extraParams']['user_id']);
             if (function_exists('profile_load_profile')) {
                 profile_load_profile($account);
             }
             /* will not be invoked for Drupal7 where the fields are already in the account object */
             if (isset($account->profile_indicia_user_id)) {
                 $reportOptions['extraParams']['user_id'] = $account->profile_indicia_user_id;
             }
         }
     }
     if (isset($args['managerPermission']) && $args['managerPermission'] != "" && user_access($args['managerPermission']) || $reportOptions['extraParams']['location_list'] != '' || $reportOptions['extraParams']['user_id'] != '') {
         // if user specified - either me in normal or branch mode, or a manager
         global $indicia_templates;
         $indicia_templates['report_download_link'] = '<th><a href="{link}"><button type="button">{caption}</button></a></th>';
         // format is assumed to be CSV
         $downloadOptions = array('readAuth' => $auth, 'extraParams' => array_merge($reportOptions['extraParams'], array('date_from' => $reportOptions['date_start'], 'date_to' => $reportOptions['date_end'])), 'itemsPerPage' => false);
         // there are problems dealing with location_list as an array if empty, so connvert
         if ($downloadOptions['extraParams']['location_list'] == "") {
             $downloadOptions['extraParams']['location_list'] = "(-1)";
         } else {
             $downloadOptions['extraParams']['location_list'] = '(' . $downloadOptions['extraParams']['location_list'] . ')';
         }
         for ($i = 1; $i <= 4; $i++) {
             if (isset($args['Download' . $i . 'Caption']) && $args['Download' . $i . 'Caption'] != "" && isset($args['download_report_' . $i]) && $args['download_report_' . $i] != "") {
                 $downloadOptions['caption'] = $args['Download' . $i . 'Caption'];
                 $downloadOptions['dataSource'] = $args['download_report_' . $i];
                 $downloadOptions['filename'] = $reportOptions['downloadFilePrefix'] . preg_replace('/[^A-Za-z0-9]/i', '', $args['Download' . $i . 'Caption']);
                 $downloadOptions['filename'] .= isset($reportOptions['includeReportTimeStamp']) && $reportOptions['includeReportTimeStamp'] ? '_' . date('YmdHis') : '';
                 if (isset($args['download_report_' . $i . '_format'])) {
                     $downloadOptions['format'] = $args['download_report_' . $i . '_format'];
                 }
                 data_entry_helper::$javascript .= "\nif(jQuery('#downloads-table th').length==0)\n  jQuery('#downloads-table thead tr').append('<th class=\"downloads-table-label\">" . lang::get("Downloads") . "</th>');\njQuery('#downloads-table thead tr').append('" . report_helper::report_download_link($downloadOptions) . "');\n";
             }
         }
     }
     return $retVal;
 }
 /**
  * Performs the download.
  * URL arguments date_from, date_to, survey_list, format, download-type
  * @global array $indicia_templates
  * @param type $args
  * @param type $node
  */
 private static function do_data_services_download($args, $node)
 {
     iform_load_helpers(array('report_helper'));
     // default data format JSON
     if (!array_key_exists('format', $_GET)) {
         $_GET['format'] = 'json';
     }
     $format = $_GET['format'];
     // download type set to Reporting by default
     if (!array_key_exists('download-type', $_GET)) {
         $_GET['download-type'] = 'R';
     }
     $isCustom = preg_match('/^custom-(\\d+)$/', $_GET['format'], $matches);
     if ($isCustom) {
         $customFormats = json_decode($args['custom_formats'], true);
         $customFormat = $customFormats[$matches[1]];
         $report = $customFormat['report'];
         // strip unnecessary .xml from end of report name if provided
         $report = preg_replace('/\\.xml$/', '', $report);
         $format = $customFormat['format'];
         $additionalParamText = $customFormat['params'];
     } else {
         if ($format == 'json') {
             $report = $args["report_csv"];
             $additionalParamText = $args["report_params_csv"];
         } else {
             $report = $args["report_{$format}"];
             $additionalParamText = $args["report_params_{$format}"];
         }
     }
     //Getting the form params first and then allowing the user to
     //overwrite then through $args
     require_once 'includes/user.php';
     $params = get_options_array_with_user_data($additionalParamText);
     $params = array_merge($params, self::build_params($args));
     $conn = iform_get_connection_details($node);
     global $indicia_templates;
     // let's just get the URL, not the whole anchor element
     $indicia_templates['report_download_link'] = '{link}';
     $limit = $args['limit'] == 0 ? '' : $args['limit'];
     // unlimited or limited
     $sharing = substr($_GET['download-type'], 0, 1);
     $url = report_helper::report_download_link(array('readAuth' => data_entry_helper::$js_read_tokens, 'dataSource' => $report, 'extraParams' => $params, 'format' => $format, 'sharing' => self::expand_sharing_mode($sharing), 'itemsPerPage' => $limit));
     header("Location: {$url}");
 }
Example #11
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;
}
 private static function location_control($args, $readAuth, $node)
 {
     global $user;
     $siteUrlParams = self::get_site_url_params();
     $ctrl = '';
     // survey_id either comes from the location_type control, or from presets; in that order.
     // loctools is not appropriate here as it is based on a node, for which this is a very simple one, invoking other nodes for the sample creation
     // need to scan param_presets for survey_id..
     $presets = get_options_array_with_user_data($args['param_presets']);
     if ($siteUrlParams[self::$SurveyKey]['value'] == '') {
         return '<p>' . lang::get('The location selection control requires that survey_id {' . $siteUrlParams[self::$SurveyKey]['value'] . '} is set in either the presets or mapped against the location_type, in the form parameters.') . '</p>';
     }
     $attrArgs = array('valuetable' => 'location_attribute_value', 'attrtable' => 'location_attribute', 'key' => 'location_id', 'fieldprefix' => 'locAttr', 'extraParams' => $readAuth, 'survey_id' => $siteUrlParams[self::$SurveyKey]['value']);
     if ($siteUrlParams[self::$locationTypeKey]['value'] != "") {
         $attrArgs['location_type_id'] = $siteUrlParams[self::$locationTypeKey]['value'];
     }
     $locationAttributes = data_entry_helper::getAttributes($attrArgs, false);
     $cmsAttr = extract_cms_user_attr($locationAttributes, false);
     if (!$cmsAttr) {
         return '<p>' . lang::get('The location selection control requires that CMS User ID location attribute is defined for locations in this survey {' . $siteUrlParams[self::$SurveyKey]['value'] . '}. If restricting to a particular location type, this must be set in the parameters page for this form instance.') . '</p>';
     }
     $attrListArgs = array('nocache' => true, 'extraParams' => array_merge(array('view' => 'list', 'website_id' => $args['website_id'], 'location_attribute_id' => $cmsAttr['attributeId'], 'raw_value' => $user->uid), $readAuth), 'table' => 'location_attribute_value');
     $attrList = data_entry_helper::get_population_data($attrListArgs);
     if (isset($attrList['error'])) {
         return $attrList['error'];
     }
     $locationIDList = array();
     foreach ($attrList as $attr) {
         $locationIDList[] = $attr['location_id'];
     }
     $locationListArgs = array('nocache' => true, 'extraParams' => array_merge(array('view' => 'list', 'website_id' => $args['website_id'], 'id' => $locationIDList, 'orderby' => 'name'), $readAuth), 'table' => 'location');
     if ($siteUrlParams[self::$locationTypeKey]['value'] != "") {
         $locationListArgs['extraParams']['location_type_id'] = $siteUrlParams[self::$locationTypeKey]['value'];
     }
     $locationList = data_entry_helper::get_population_data($locationListArgs);
     if (isset($locationList['error'])) {
         return $locationList['error'];
     }
     $ctrlid = 'calendar-location-select-' . $node->nid;
     $ctrl .= '<label for="' . $ctrlid . '" class="location-select-label">' . lang::get('Filter by site') . ':</label> <select id="' . $ctrlid . '" class="location-select">' . '<option value="" class="location-select-option" ' . (self::$siteUrlParams[self::$locationKey]['value'] == null ? 'selected=\\"selected\\" ' : '') . '>' . lang::get('All sites') . '</option>';
     foreach ($locationList as $location) {
         $ctrl .= '<option value=' . $location['id'] . ' class="location-select-option" ' . (self::$siteUrlParams[self::$locationKey]['value'] == $location['id'] ? 'selected=\\"selected\\" ' : '') . '>' . $location['name'] . (isset($args['includeSrefInLocationFilter']) && $args['includeSrefInLocationFilter'] ? ' (' . $location['centroid_sref'] . ')' : '') . '</option>';
     }
     $ctrl .= '</select>';
     /*
         // get the url parameters. Don't use $_GET, because it contains any parameters that are not in the
         // URL when search friendly URLs are used (e.g. a Drupal path node/123 is mapped to index.php?q=node/123
         // using Apache mod_alias but we don't want to know about that)
         $reloadUrl = data_entry_helper::get_reload_link_parts();
         // find the names of the params we must not include
         foreach ($reloadUrl['params'] as $key => $value) {
           if (!array_key_exists($key, self::$siteUrlParams)){
             $reloadUrl['path'] .= (strpos($reloadUrl['path'],'?')===false ? '?' : '&')."$key=$value";
           }
         }
         $param=(strpos($reloadUrl['path'],'?')===false ? '?' : '&').self::$locationKey.'='; */
     self::set_up_control_change($ctrlid, self::$locationKey, array());
     return $ctrl;
 }