function gd_ext () {

    ob_get_clean();

    if ( !empty($_REQUEST['datasource']) ) {
        gd_datasource_set_active($_REQUEST['datasource']);
    }

    $ext = array();
    $dashboards = gd_dashboard_findall_by_datasource(LOAD_ENTITY);
    foreach ( $dashboards as $dashboard ) {
        $ext[] = array('id'=>$dashboard->nid,'title'=>$dashboard->title);
    }

    $response = new stdClass();
    $response->status = new stdClass();
    $response->status->code = 200;
    $response->status->message = 'OK';

    if ( isset($_REQUEST['id']) ) {
        $response->data = array('id'=>$_REQUEST['id'], 'title'=>$dashboards[$_REQUEST['id']]->title);
    }
    else {
        $response->data = $ext;
    }

    module_invoke_all('gd_ext_response_alter',$response);

    echo \GD\Utility\Json::getPayload($response,$_GET['callback']);

    gd_get_session_messages();

    drupal_exit();
}
/**
 * @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 export ( ExportStream $stream, ExportContext $context ) {
        $datasourceName = $context->get('datasourceName');
        if (!$datasourceName) {
            throw new \Exception('Missing required datasource name.');
        }
        gd_datasource_set_active($datasourceName);

        foreach ( $this->handlers as $h ) {
            $handler = new $h['class']();
            $handler->export($stream,$context);
        }
    }
    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);
    }
/**
 * @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();
}
/**
 * @param $form
 * @param $form_state
 * @throws Exception
 */
function gd_sync_import_create_form_submit ( $form, &$form_state ) {
    try {
        $content = json_decode($form_state['values']['content']);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception('Invalid JSON');
        }

        $datasourceName = gd_datasource_create(array(
            'publicName' => $form_state['values']['name'],
            'description' => 'Imported Datamart.'
        ));

        gd_datasource_set_active($datasourceName);
        $importContext = new GD\Sync\Import\ImportContext(array('datasourceName'=>$datasourceName,'operation'=>'create'));
        $importStream = new GD\Sync\Import\ImportStream();
        $importStream->set(null,$content);

        $importController = new \GD\Sync\Import\ImportController();
        $importController->import($importStream,$importContext);

        drupal_set_message('Datamart Created Successfully');
    } catch ( Exception $e ) {
        LogHelper::log_error($e);
        drupal_set_message($e->getMessage(),'error');
    }
}
/**
 * @param $dashboardNode
 * @param $reportNid
 * @return int|null
 */
function gd_dashboard_report_view ( $dashboardNode, $reportNid ) {
    ob_start();
    try {
        if ( !gd_dashboard_access_view($dashboardNode) ) {
            return MENU_ACCESS_DENIED;
        }

        $DashboardConfig = new GD_DashboardConfig($dashboardNode);
        gd_datasource_set_active($DashboardConfig->getDatasource());

        foreach ( $DashboardConfig->items as $item ) {
            if ( $reportNid == $item->content ) {
                $options = array();

                if (isset($_GET['dashboardBuilder']) && $_GET['dashboardBuilder'] == TRUE) {
                    $options['admin'] = TRUE;
                }

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

                $html = $DashboardConfig->getItemReportView($item, $options);
                $output = array('header'=>$html->header, 'body'=>$html->body, 'footer'=>$html->footer);

                $response = new stdClass();
                $response->status = new stdClass();
                $response->status->code = 200;
                $response->status->message = 'OK';

                $response->data = $output;

                module_invoke_all('gd_ext_response_alter',$response);

                $messages = gd_get_session_messages();
                if ( !empty($messages['error']) ) {
                    $response->status->code = 500;
                    $response->status->message = $messages['error'];
                } else {
                    if ( !isset($_GET['callback']) && $DashboardConfig->isPublic() && 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));
                    }
                }

                echo \GD\Utility\Json::getPayload($response,$_GET['callback']);
            }
        }

        echo ob_get_clean();
        drupal_exit();
    } catch ( Exception $e ) {
        gd_exception_handler($e);
        $response = new stdClass();
        $response->status->code = 500;
        $response->status->message = $e->getMessage();
        echo \GD\Utility\Json::getPayload($response,$_GET['callback']);
        echo ob_get_clean();
        drupal_exit();
    }
}
 * GNU General Public License for more details.
 * 
 * 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" ) {
    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);
    }
    public function postAuthenticate() {
        if ($this->disabled) return;

        $attributes = $this->getIdentity();
        \LogHelper::log_debug('ADFS Attributes');
        \LogHelper::log_debug($attributes);

        if ( $attributes ) {
            global $user;
            $roles = array();
            $r = user_roles(true);

            $db_user = db_select('users')
              ->fields('users', array('uid'))
              ->condition('name', db_like($attributes[ADFS_EMAIL_SCHEMA][0]), 'LIKE')
              ->range(0, 1)
              ->execute()
              ->fetchField();

            if (isset($attributes[ADFS_GROUP_SCHEMA])) {
                $groups = $attributes[ADFS_GROUP_SCHEMA];
                $defaultDatasource = null;
                foreach ($groups as $group) {
                    if (isset($this->roleMappings[$group])) {
                        foreach ($this->roleMappings[$group] as $role) {
                            $roles[array_search($role, $r)] = TRUE;
                        }
                    }
                    if (!isset($defaultDatasource) && isset($this->dsMappings[$group])) {
                        $defaultDatasource = $this->dsMappings[$group][0];
                    }
                }

                foreach ($this->requiredGroups as $requiredGroup) {
                    if (!in_array($requiredGroup, $groups)) {
                        drupal_goto('forbidden');
                    }
                }
            }

            if (isset($defaultDatasource)) {
                $datasources = gd_datasource_get_all();
                foreach ($datasources as $ds) {
                    if ($ds->publicName == $defaultDatasource) {
                        $defaultDatasource = $ds->name;
                        break;
                    }
                }
            }

            //  Load user if it exists
            if ((bool) $db_user) {
                $u = user_load($db_user);

                //  If user is blocked
                if ($u->status == 0) {
                    drupal_goto('forbidden');
                }

                foreach ($u->roles as $role) {
                    if (in_array($role, $r)) {
                        $roles[array_search($role, $r)] = TRUE;
                    }
                }

                //  Keep user roles the same. Sync the first and last name from ADFS
                $info = array(
                    'roles' => $roles,
                    'mail' => $attributes[ADFS_EMAIL_SCHEMA][0],
                    'field_gd_user_first_name' => array(
                        LANGUAGE_NONE => array(
                            0 => array(
                                'value' => $attributes[ADFS_COMMON_NAME_SCHEMA][0]
                            )
                        )
                    ),
                    'field_gd_user_last_name' => array(
                        LANGUAGE_NONE => array(
                            0 => array(
                                'value' => $attributes[ADFS_SURNAME_SCHEMA][0]
                            )
                        )
                    )
                );
                $user = user_save($u, $info);
            } else if ($this->autoCreate) {
                //  Always give new users the authenticated user role
                $roles[array_search('authenticated user', $r)] = TRUE;

                $info = array(
                    'name' => $attributes[ADFS_EMAIL_SCHEMA][0],
                    'pass' => user_password(),
                    'mail' => $attributes[ADFS_EMAIL_SCHEMA][0],
                    'status' => 1,
                    'roles' => $roles,
                    'field_gd_user_first_name' => array(
                        LANGUAGE_NONE => array(
                            0 => array(
                                'value' => $attributes[ADFS_COMMON_NAME_SCHEMA][0]
                            )
                        )
                    ),
                    'field_gd_user_last_name' => array(
                        LANGUAGE_NONE => array(
                            0 => array(
                                'value' => $attributes[ADFS_SURNAME_SCHEMA][0]
                            )
                        )
                    )
                );
                $user = user_save(drupal_anonymous_user(), $info);
            } else {
                $message = t('Unauthorized account: @email', array('@email' => $attributes[ADFS_EMAIL_SCHEMA][0]));
                \LogHelper::log_error($message);
                drupal_goto('forbidden');
            }

            user_login_finalize($info);

            if (isset($defaultDatasource)) {
                gd_datasource_set_active($defaultDatasource);
            }
        }
    }
    protected function update(Import\ImportStream $stream, Import\ImportContext $context) {
        $datasets = $stream->get('datasets');
        if (empty($datasets)) {
            return;
        }

        gd_datasource_set_active($context->get('datasourceName'));
        $metamodel = data_controller_get_metamodel();

        $environment_metamodel = data_controller_get_environment_metamodel();
        $datasource = $environment_metamodel->getDataSource($context->get('datasourceName'));

        foreach ( $datasets as $dataset ) {
            $existingDataset = GD_DatasetMetaModelLoaderHelper::findDatasetByUUID($metamodel->datasets, $dataset->uuid);
            if ( !$existingDataset ) {

                // map for re-linking dependent objects
                $dataset->originalName = $dataset->name;

                // create new name
                $newDatasetName = GD_NamingConvention::generateDatasetName();
                $dataset->name = $newDatasetName;
                $dataset->source = $newDatasetName;
                $dataset->datasourceName = $datasource->name;
            } else {
                // map for re-linking dependent objects
                $dataset->originalName = $dataset->name;

                $dataset->name = $existingDataset->name;
                $dataset->source = $existingDataset->source;
                $dataset->datasourceName = $existingDataset->datasourceName;
            }
        }

        // prepare dataset columns for import
        $this->prepareColumns($datasets);

        // prepares the metadata object, has to be of type RecordMetaData
        foreach ( $datasets as $key => $dataset ) {
            $metadata = new DatasetMetaData();
            $metadata->initializeFrom($dataset);
            $datasets[$key] = $metadata;
        }

        // ensure datasets are created in order to satisfy dependencies
        usort($datasets, array(new ReferencedDatasetComparator(), 'compare'));

        foreach ( $datasets as $dataset ) {
            $existingDataset = GD_DatasetMetaModelLoaderHelper::findDatasetByUUID($metamodel->datasets, $dataset->uuid);
            if ($existingDataset) {
                gd_data_controller_ddl_modify_dataset($dataset);
            } else {
                MetaModelFactory::getInstance()->startGlobalModification();
                try {
                    $transaction = db_transaction();
                    try {
                        gd_data_controller_ddl_create_dataset($dataset);
                    } catch (Exception $e) {
                        $transaction->rollback();
                        throw $e;
                    }
                } catch (Exception $e) {
                    MetaModelFactory::getInstance()->finishGlobalModification(false);
                    throw $e;
                }
                MetaModelFactory::getInstance()->finishGlobalModification(true);
            }
        }

        $stream->set('datasets',$datasets);
    }
/**
 * @param $datamartName
 * @param $export
 * @return services_error|stdClass
 * @throws Exception
 */
function gd_sync_resource_import ( $datamartName, $export ) {
    try {
        $content = json_decode($export);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception('Invalid JSON');
        }

        $datasourceName = gd_datasource_create(array(
            'publicName' => $datamartName,
            'description' => 'Imported Topic'
        ));

        gd_datasource_set_active($datasourceName);
        $importContext = new GD\Sync\Import\ImportContext(array('datasourceName'=>$datasourceName,'operation'=>'create'));
        $importStream = new GD\Sync\Import\ImportStream();
        $importStream->set(null,$content);

        $importController = new \GD\Sync\Import\ImportController();
        $importController->import($importStream,$importContext);

        $apiObject = new stdClass();
        $apiObject->name = $datasourceName;
        $apiObject->messages = gd_get_session_messages();
        return $apiObject;
    } catch ( Exception $e ) {
        return gd_admin_ui_service_exception_handler($e);
    }
}