/**
 * @return array|int
 * @throws Exception
 */
function gd_report_admin_page_new() {
    $datasource = gd_datasource_find($_GET['ds']);
    if ( !$datasource ) {
        return MENU_NOT_FOUND;
    }

    gd_datasource_set_active($datasource->name);

    if ( !gd_account_user_is_admin() && !gd_account_user_is_datasource_admin(null,gd_datasource_get_active()) ) {
        return MENU_ACCESS_DENIED;
    }

    drupal_add_library('gd_report_admin', 'GD_Admin_ReportSection_Builder');

    if ( !empty($_GET['title']) ) {
        $report = new stdClass();
        $report->title = check_plain($_GET['title']);
    } else {
        $report = null;
    }

    if ( !empty($_GET['dataset']) ) {
        $reportDataset = gd_data_controller_ui_metadata_get_dataset_ui_metadata($_GET['dataset']);
    } else {
        $reportDataset = null;
    }

    return gd_report_admin_page($report,$reportDataset);
}
    public function record($requestId, AbstractEvent $event) {
        $duration = $event->getDuration();

        global $user;
        $referencedDataSourceName = gd_datasource_get_active();

        if (!isset($this->recordsHolder)) {
            $this->recordsHolder = new IndexedRecordsHolder();
        }

        $recordInstance = $this->recordsHolder->initiateRecordInstance();
        $recordInstance->initializeFrom(array(
            NULL, $requestId, $user->uid, $referencedDataSourceName, $event->type, $event->owner, $event->getStartDateTime(), $duration));
        $this->recordsHolder->registerRecordInstance($recordInstance);
    }
    public static function getExportables($datasourceName) {
        if ( $datasourceName != gd_datasource_get_active() ) {
            gd_datasource_set_active($datasourceName);
        }

        $metamodel = data_controller_get_metamodel();
        // get datasets
        $datasetNids = array();
        foreach ($metamodel->datasets as $dataset) {
            if (!isset($dataset->nid)) {
                continue;
            }
            $datasetNids[] = $dataset->nid;
        }

        return node_load_multiple($datasetNids);
    }
    public function getView( array $options = array() ) {
        $scrollHeight = 400;
        $heightAdj = 0;
        if ( $this->ReportConfig->showTitle() || $this->ReportConfig->showMenu() ) {
            $heightAdj = (GD_REPORT_TITLE_HEIGHT);
        }

        $reportSize = $this->ReportConfig->getDisplaySize();
        if ( !empty($reportSize) ) {
            $scrollHeight = $reportSize->height;
        }

        if ( isset($_REQUEST['h']) && isset($_REQUEST['w']) ) {
            $scrollHeight = $_REQUEST['h'];
        }

        $scrollHeight -= $heightAdj;
        $width = isset($_REQUEST['w']) ? $_REQUEST['w'] . 'px' : '100%';

        $datasourceName = $this->ReportConfig->getNode() != null ? get_node_field_value($this->ReportConfig->getNode(), 'field_report_datasource') : null;
        if (!isset($datasourceName)) {
            $datasourceName = gd_datasource_get_active();
        }
        $viewStart = gd_datasource_is_property($datasourceName, 'draft') ?
          '<img id="report-'.intval($this->ReportConfig->getId()).'-overlay" class="report-draft-overlay" src="/sites/all/modules/custom/report/includes/images/draft.png"/>
          <script type="text/javascript">
            jQuery("#report-'.intval($this->ReportConfig->getId()).'-overlay").bind("mouseenter mouseleave click dblclick foucsout hover mousedown mousemove mouseout mouseover mouseup", function (e) {
                if (navigator.appName == "Microsoft Internet Explorer") {
                    jQuery("#report-'.intval($this->ReportConfig->getId()).'-overlay").hide();
                    var target = document.elementFromPoint(e.clientX, e.clientY);
                    jQuery(target).trigger(e.type);
                    jQuery("#report-'.intval($this->ReportConfig->getId()).'-overlay").show();
                }
            });
          </script>' : '';
        $viewStart .= '<div class="report report-custom" id="report-'.intval($this->ReportConfig->getId()).'" style="width:' . $width . ';height:' . $scrollHeight . 'px;clear:both; overflow:hidden;position:relative;">';
        $viewEnd = '</div>';
        $viewBody = $this->getBody($options);

        return
          $viewStart.
            $viewBody.
          $viewEnd;
    }
/**
 * @return array
 */
function gd_dashboard_admin_page_new() {
    $datasource = gd_datasource_find($_GET['ds']);
    if ( !$datasource ) {
        return MENU_NOT_FOUND;
    }

    gd_datasource_set_active($datasource->name);

    if ( !gd_account_user_is_admin() && !gd_account_user_is_datasource_admin(null,gd_datasource_get_active()) ) {
        return MENU_ACCESS_DENIED;
    }

    drupal_add_library('gd_dashboard_admin', 'GD_Admin_DashboardSection_Builder');

    drupal_add_library('gd','datatables');
    drupal_add_library('gd','highcharts');
    drupal_add_js('sites/all/libraries/sparkline/jquery.sparkline.min.js');

    return gd_dashboard_admin_page();
}
 url: urlOptions,
 allowDragDrop: <?php echo $disableDrag; ?>,
 callType: "<?php echo ( isset($admin) ? "POST" : "GET" ) ?>",
 getDataObject: function(columns, measure) {
     if (!columns) {
         columns = [];
     }
     if (measure) {
         columns.push(measure);
     }
     <?php if (isset($admin) && !isset($dashboard)) {
         echo 'var config = GovdashReportBuilder.getReport().getConfig();';
         echo "config['config']['model']['columns'] = columns;";
     } ?>
     return {
         "ds": "<?php echo gd_datasource_get_active(); ?>",
         <?php if (isset($admin)) {
             if (isset($dashboard)) {
                 echo '"dashboard": JSON.stringify(GovdashDashboardBuilder.getDashboard().getConfig()),';
                 echo '"reportId":' . $reportId . ',';
                 echo '"columns": columns';
             } else {
                 echo '"report": JSON.stringify(config)';
             }
         } else {
             echo '"columns": columns,';
             echo '"reportId":' . $reportId . ',';
             echo '"origin": location.pathname,';
             $filters = array();
             foreach ( $ReportConfig->getFilters() as $f ) {
                 if ( !empty($f->name) && !empty($_REQUEST['t']) ) {
/**
 * @return array
 */
function gd_dashboard_page_index () {
    global $user;
    $event = new DefaultEvent();

    if ( arg(0) == 'public' && !gd_dashboard_get_setting('public') ) {
        return MENU_NOT_FOUND;
    }

    if ( !empty($_GET['id']) ) {
        $dashboardNode = gd_dashboard_load($_GET['id']);
        if ( $dashboardNode ) {
            gd_datasource_set_active(get_node_field_value($dashboardNode,'field_dashboard_datasource'));
            if ( !gd_dashboard_access_view($dashboardNode) ) {
                return MENU_ACCESS_DENIED;
            }
        } else {
            return MENU_NOT_FOUND;
        }
    }

    if ( arg(0) == 'public' ) {
        list($datasources, $dashboardNode, $dashboards) = gd_dashboard_public_index_variables();
    } else {
        list($datasources, $dashboardNode, $dashboards) = gd_dashboard_index_variables();
    }

    ob_start();

    if ( arg(0) == 'public' ) {
        drupal_add_http_header('Cache-Control','no-transform,public,max-age=3600,s-maxage=3600');
        drupal_add_http_header('Expires',gmdate('D, d M Y H:i:s \G\M\T', time() + 3600));
    }

    if ( empty($datasources) ) {
        echo '<div id="dashboard-view" class="gd-container"><p>There are no topics. Please contact your site administrator to create a topic.</p></div>';
    } else if ( empty($dashboards) ) {
        echo '<div id="dashboard-view" class="gd-container"><p>There are no dashboards set up for this topic.</p></div>';
    } else {
        try {
            $DashboardConfig = new GD_DashboardConfig($dashboardNode, $_GET);

            drupal_add_library('gd_dashboard', 'GD_Dashboard_View');

            echo '<div id="dashboard-view" class="gd-container">';

            echo '<div class="row">';

            echo '  <div class="col-md-6">';
            echo '    <h2>'.$dashboardNode->title.'</h2>';
            if ( get_node_field_value($dashboardNode, 'field_dashboard_desc') ) {
                echo '<p>'.get_node_field_value($dashboardNode, 'field_dashboard_desc').'</p>';
            }
            echo '  </div>';
            echo '  <div class="col-md-6">';

            echo '<div class="pull-right">';
            if ( arg(0) != 'public' && (gd_account_user_is_admin() || gd_account_user_is_datasource_admin($user, gd_datasource_get_active())) ) {
                echo '<a role="button" type="button" id="editButton" tabindex="100" class="btn btn-default gd-dashboard-editbtn" href="/cp/dashboard/'.$dashboardNode->nid.'">Edit</a>';
            }

            if ( gd_dashboard_get_setting('export') && $DashboardConfig->isExportable() ) {
                echo ' <button role="button" type="button" id="exportButton" tabindex="100" class="btn btn-default btn-gd-dashboard-export" data-dashboard="'.$dashboardNode->nid.'">Export</button>';
            }
            if ( gd_dashboard_get_setting('print') && $DashboardConfig->isPrintable() ) {
                echo '<button role="button" type="button" style="margin-left:3px;" id="printButton" tabindex="100" class="btn btn-default btn-gd-dashboard-print" href='."javascript:void(0)".'>Print</button>';
            }

            echo '</div>';

            echo '  </div>';
            echo '</div>';

            $options = array();
            if ( $DashboardConfig->isPublic() && arg(0) == 'public' ) {
                $options['public'] = TRUE;
            }

            $configView = new GD_DashboardView($DashboardConfig);
            echo $configView->getView($options);
            echo '</div>';

            $DashboardConfig->attachRequiredLibs(); // must be called after building view, or libs won't be set yet

        } catch (Exception $e) {
            LogHelper::log_error($e);
            echo '<div id="dashboard-view" class="gd-container"><p class="messages error">Dashboard could not be rendered. '.$e->getMessage().'</p></div>';
        }
    }

    if ( arg(0) == 'public' ) {
        module_invoke_all('gd_dashboard_public_index_alter');
    } else {
        module_invoke_all('gd_dashboard_index_alter');
    }

    if (!empty($_REQUEST['export-view'])) {
        $page = array(
            '#show_messages' => false,
            '#theme' => 'page__dashboard__export__view',
            '#type' => 'page',
            'content' => array(
                'system_main' => array(
                    '#markup' => ob_get_clean()
                )
            ),
            'variables' => array(
                'datasources' => $datasources,
                'dashboard' => $dashboardNode,
                'dashboards' => $dashboards
            )
        );
    } else {
        $page = array(
            '#show_messages' => false,
            '#theme' => 'page__dashboard',
            '#type' => 'page',
            'content' => array(
                'system_main' => array(
                    '#markup' => ob_get_clean()
                )
            ),
            'variables' => array(
                'datasources' => $datasources,
                'dashboard' => $dashboardNode,
                'dashboards' => $dashboards
            )
        );
    }

    if (isset($dashboardNode->nid)) {
        $event->type = 1; // see gd_health_monitoring_database_install() for more details
        $event->owner = $dashboardNode->nid;

        EventRecorderFactory::getInstance()->record($event);
    }

    return $page;
}
 * You should have received a copy of the GNU General Public License
 * along with GovDashboard.  If not, see <http://www.gnu.org/licenses/>.
 */


if ( isset($_GET['datasource']) ) {
    $datasourceName = $_REQUEST['datasource'];
}

if ( isset($_POST['datasourceName']) ) {
    $datasourceName = $_POST['datasourceName'];
}

gd_datasource_set_active($datasourceName);

if ( !gd_account_user_is_admin() && !gd_account_user_is_datasource_admin(null,gd_datasource_get_active()) ) {
    echo "<h3>Access Denied</h3>";
    drupal_exit();
}

$datasource = gd_datasource_get($datasourceName);


$deleteWarningMessage = "Are you sure you want to delete \'".($datasource->publicName)."\'? ".
                        "This will delete all the associated Dashboards, Reports and Datasets from that topic. ".
                        "This action cannot be undone.";

if ( isset($_POST['editdatamart']) && $_POST['editdatamart'] == "yes" ) {

    $errors = array();
    public static function getExportables($datasourceName) {
        if ( $datasourceName != gd_datasource_get_active() ) {
            gd_datasource_set_active($datasourceName);
        }

        $metamodel = data_controller_get_metamodel();
        // get datasets
        $datasetNames = array();
        foreach ($metamodel->datasets as $dataset) {
            if (!isset($dataset->nid)) {
                continue;
            }
            $datasetNames[] = $dataset->name;
        }

        $referencePointNids = gd_reference_get_reference_points_by_dataset($datasetNames);

        return gd_reference_get_references_by_reference_points($referencePointNids,LOAD_ENTITY);
    }
    protected function getServerArgs( $admin ) {
        $args = array();
        $args[] = '"ds": "' . gd_datasource_get_active() . '"';

        if ( $admin ) {
            if ( $this->ReportConfig->dashboard ) {
                $args[] = '"dashboard": JSON.stringify(GovdashDashboardBuilder.getDashboard().getConfig())';
                $args[] = '"reportId":' . $this->ReportConfig->getId();
            } else {
                $args[] = '"report": GovdashReportBuilder.getReport().getConfig()';
            }
        } else {
            $args[] = '"reportId":' . $this->ReportConfig->getId();
            $args[] = '"origin": location.pathname';
            $filters = array();
            $filter_args = '"filter": [';
            foreach ( $this->ReportConfig->getFilters() as $f ) {
                if ( !empty($f->name) && !empty($_REQUEST['t']) ) {
                    foreach ( $_REQUEST['t'] as $dashboard => $filter ) {
                        foreach ($filter as $name => $t) {
                            if ($dashboard == $this->ReportConfig->dashboard || isset($t['ddf'])) {
                                if ( $f->name == $name ) {
                                    if (is_array($t)) {
                                        $filters[] =
                                            '{"dashboard":' . $dashboard . ',
                                            "name": "' . $name . '",
                                            "operator": "' . $t['o'] . '"
                                            '. (isset($t['v']) ? ',"value": ' . (is_array($t['v']) ? '["' . implode('","', $t['v']) . '"]' : '"' . htmlspecialchars($t['v']) . '"') : '') . '
                                            '.(isset($t['ddf']) ? ',"ddf": true' : '').'}';
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if ( count($filters) > 0 ) {
                $filter_args .= count($filters) > 1 ? implode(',', $filters) : $filters[0];
            }
            $filter_args .= ']';
            $args[] = $filter_args;

            if (isset($_REQUEST['bc'])) {
                $args[] = '"bc":"' .  $_REQUEST['bc'] . '"';
            }
        }
        return implode(',', $args);
    }
    protected function processConfig ( &$config ) {
        //  TODO Services casts everything to array not objects
        $config = (object) $config;
        $config->model = (object) $config->model;
        $metamodel = data_controller_get_metamodel();
        if ( !empty($config->model->datasets) ) {
            foreach ( $config->model->datasets as $key => $datasetIdentifier ) {
                $dataset = GD_DatasetMetaModelLoaderHelper::findDatasetByUUID($this->datasets,$datasetIdentifier);
                if (!isset($dataset)) {
                    $datasetName = NameSpaceHelper::addNameSpace(gd_datasource_get_active(), $datasetIdentifier);
                    $dataset = $metamodel->getDataset($datasetName);
                }
                $config->model->datasets[$key] = $dataset->name;
            }
        }

        // update columns
        if ( !empty($config->model->columns) ) {
            foreach ( $config->model->columns as $key => $value ) {
                $config->model->columns[$key] = DatasetImportHelper::getNewColumnName($value,$this->datasets);
            }
        }

        // update column configs
        if ( !empty($config->columnConfigs) ) {
            foreach ( $config->columnConfigs as $key => $value ) {
                $config->columnConfigs[$key]->columnId = DatasetImportHelper::getNewColumnName($value->columnId,$this->datasets);
            }
        }

        // update column orders
        if ( !empty($config->model->columnOrder) ) {
            foreach ( $config->model->columnOrder as $key => $value ) {
                $config->model->columnOrder[$key] = DatasetImportHelper::getNewColumnName($value,$this->datasets);
            }
        }

        // update column sorts
        if ( !empty($config->model->orderBy) ) {
            foreach ( $config->model->orderBy as $key => $value ) {
                $config->model->orderBy[$key]->column = DatasetImportHelper::getNewColumnName($value->column,$this->datasets);
            }
        }

        // update filters
        if ( !empty($config->model->filters) ) {
            foreach ( $config->model->filters as $key => $value ) {
                $config->model->filters[$key]->column = DatasetImportHelper::getNewColumnName($value->column,$this->datasets);
            }
        }

        // update visual series
        if ( !empty($config->visual->series) ) {
            $newSeries = array();
            foreach ( $config->visual->series as $key => $value ) {
                $newSeries[DatasetImportHelper::getNewColumnName($key,$this->datasets)] = $value;
            }
            $config->visual->series = $newSeries;
        }

        // update traffic column
        if ( !empty($config->visual->trafficColumn) ) {
            $config->visual->trafficColumn = DatasetImportHelper::getNewColumnName($config->visual->trafficColumn,$this->datasets);
        }

        // update color column
        if ( !empty($config->visual->useColumnDataForColor) ) {
            $config->visual->useColumnDataForColor = DatasetImportHelper::getNewColumnName($config->visual->useColumnDataForColor,$this->datasets);
        }

        // update traffic columns
        if ( !empty($config->visual->traffic) ) {
            $newTraffic = array();
            foreach ( $config->visual->traffic as $key => $value ) {
                $newName = DatasetImportHelper::getNewColumnName($key,$this->datasets);
                $value->trafficColumn = $newName;
                $newTraffic[$newName] = $value;
            }
            $config->visual->traffic = $newTraffic;
        }
    }
                        getDataObject: function (columns, measure) {
                            if (!columns) {
                                columns = [];
                            }
                            if (measure) {
                                columns.push(measure);
                            }
                            <?php 
if (isset($admin) && !isset($dashboard)) {
    echo 'var config = GovdashReportBuilder.getReport().getConfig();';
    echo "config['config']['model']['columns'] = columns;";
}
?>
                            return {
                                "ds": "<?php 
echo gd_datasource_get_active();
?>
",
                                <?php 
if (isset($admin)) {
    if (isset($dashboard)) {
        echo '"dashboard": JSON.stringify(GovdashDashboardBuilder.getDashboard().getConfig()),';
        echo '"reportId":' . $reportId . ',';
        echo '"columns": columns';
    } else {
        echo '"report": JSON.stringify(config)';
    }
} else {
    echo '"columns": columns,';
    echo '"reportId":' . $reportId . ',';
    echo '"origin": location.pathname,';