public static function findEntities ( array $params = array() ) {
        $sql = 'SELECT entityId, entityType FROM {gd_role_permission} ';

        $binds = array();
        $where = array();
        if ( !empty($params) ) {
            foreach ( $params as $key => $value ) {
                $binds[':'.$key] = $value;
                $where[] = $key .' = :'.$key;
            }
        }

        if ( !empty($where) ) {
            $sql .= 'WHERE '.implode(' AND ',$where);
        }

        $result = db_query($sql,$binds);

        if ( !$result || !$result->rowCount() ) {
            return array();
        }

        $results = $result->fetchAll();

        $entities = array();
        if ( isset($params['entityType']) && $params['entityType'] === 'datasource' ) {
            $datasources = gd_datasource_get_all();
            foreach ( $datasources as $datasourceName => $DS ) {
                foreach ( $results as $record ) {
                    if ( $record->entityId === $datasourceName ) {
                        $entities[$datasourceName] = $DS;
                    }
                }
            }
        } else if ( isset($params['entityType']) && $params['entityType'] === 'dashboard' ) {
            $dashboard_nids = array();
            foreach ( $results as $record ) {
                $dashboard_nids[] = $record->entityId;
            }
            $entities = node_load_multiple($dashboard_nids);
        } else {
            throw new \Exception('Unsupported EntityType');
        }

        return $entities;
    }
/**
 * @return array
 */
function gd_sync_get_datasource_options () {
    $options = array();
    $datasources = gd_datasource_get_all();
    foreach ( $datasources as $datasource ) {
        $options[$datasource->name] = $datasource->publicName;
    }
    return $options;
}
/**
 * @return array
 * @throws Exception
 * @throws IllegalArgumentException
 */
function gd_dashboard_index_variables () {
    $dashboards = array();
    $active_datasource_name = gd_datasource_find_active();
    $current_dashboard = gd_dashboard_get_current();
    global $user;

    if ( gd_account_user_is_admin() ) {

        // can see all datasources
        $datasources = gd_datasource_get_all();

        if ( $current_dashboard ) {
            gd_datasource_set_active(get_node_field_value($current_dashboard,'field_dashboard_datasource'));
        } else if ( !$active_datasource_name ) {
            if (isset($_GET['ds'])) {
                gd_datasource_set_active($_GET['ds']);
            } else {
                gd_datasource_set_active(key($datasources));
            }
        }

        // don't pick up any dashboards if there are no published datamarts - causes logic bomb further down
        if ( !empty($datasources) ) {
            $dashboards = gd_dashboard_findall_by_datasource(LOAD_ENTITY);
        }

    } else if ( $user->uid ) {

        // get view privileges for all dashboards
        $results = gd_account_user_get_dashboards();

        // pick up the datasources from the dashboards
        $datasources = gd_account_user_get_datasources();
        foreach ( $results as $dashboard ) {
            if ( !isset($datasources[get_node_field_value($dashboard,'field_dashboard_datasource')]) ) {
                $datasource = gd_datasource_get(get_node_field_value($dashboard,'field_dashboard_datasource'));
                $datasources[$datasource->name] = $datasource;
            }
        }

        // set current datasource
        if ( $current_dashboard ) {
            gd_datasource_set_active(get_node_field_value($current_dashboard,'field_dashboard_datasource'));
        } else {
            if ( !$active_datasource_name ) {
                if ( isset($_GET['ds']) && isset($datasources[$_GET['ds']]) ) {
                    gd_datasource_set_active($_GET['ds']);
                } else {
                    reset($results);
                    try {
                        if (!empty($results[key($results)])) {
                            $active_datasource_name = get_node_field_value($results[key($results)],'field_dashboard_datasource');
                            gd_datasource_set_active($active_datasource_name);
                        } else {
                            return 'You have not been granted permission to view any dashboards.';
                        }
                    } catch (Exception $e) {
                        drupal_set_message('No default datasource set.', 'error');
                        LogHelper::log_error($e->getMessage());
                    }
                }
            }
        }

        // remove dashboards that do not belong to datasource of current dashboard
        $active_datasource_name = gd_datasource_get_active();
        $dashboards = array();
        foreach ( $results as $key => $dashboard ) {
            if ( $active_datasource_name === get_node_field_value($dashboard,'field_dashboard_datasource') ) {
                $dashboards[$key] = $dashboard;
            }
        }

        // remove dashboards that were not created by the user
        if ( gd_datasource_is_property($active_datasource_name, 'personal') ) {
            global $user;
            $userCreatedDashboards = array();
            foreach ( $dashboards as $key => $dashboard ) {
                if ( $user->uid == $dashboard->uid ) {
                    $userCreatedDashboards[$key] = $dashboard;
                }
            }
            $dashboards = $userCreatedDashboards; // overwrite dashboard list
        }

    } else {

        // get datasources that belong to the dashboards
        // weed out dashboards with missing datasource
        $datasources = array();
        $publicDashboards = array();
        foreach ( gd_dashboard_get_dashboards_public(LOAD_ENTITY) as $dashboard ) {
            $datasourceName = get_node_field_value($dashboard,'field_dashboard_datasource');
            $datasource = gd_datasource_find($datasourceName);
            if ( !$datasource ) {
                continue;
            }
            $publicDashboards[$dashboard->nid] = $dashboard;
            if ( !isset($datasources[$datasourceName]) ) {
                $datasources[$datasource->name] = $datasource;
            }
        }

        // set current datamart
        if ( $current_dashboard ) {
            gd_datasource_set_active(get_node_field_value($current_dashboard,'field_dashboard_datasource'));
        } else {
            if ( isset($_GET['ds']) && isset($datasources[$_GET['ds']]) ) {
                gd_datasource_set_active($_GET['ds']);
            } else {
                gd_datasource_set_active(get_node_field_value($publicDashboards[key($publicDashboards)],'field_dashboard_datasource'));
            }
        }

        // remove dashboards that do not belong to datamart of current dashboard
        $active_datasource_name = gd_datasource_get_active();
        $dashboards = array();
        foreach ( $publicDashboards as $key => $dashboard ) {
            if ( $active_datasource_name === get_node_field_value($dashboard,'field_dashboard_datasource') ) {
                $dashboards[$key] = $dashboard;
            }
        }
    }

    reset($datasources);
    reset($dashboards);

    // sort the dashboard list by name
    usort($dashboards, function($a, $b) {
        if (strtolower($a->title) === strtolower($b->title)){
            return strnatcmp($a->title,$b->title);
        }
        return strnatcasecmp($a->title,$b->title);
    });

    // which dashboard to display
    if ( $current_dashboard ) {
        $dashboard = $current_dashboard;
    } else if (!empty($dashboards) ) {
        $dashboard = $dashboards[0];
    } else {
        $dashboard = null;
    }

    $display_dashboards = array();
    if ( !empty($dashboards) ) {
        $dashboard_ids = array(); // index of any parents from $dashboards
        $drilldown_dashboard_ids = array();
        foreach ( $dashboards as $d ) {
            $config = new GD_DashboardConfig($d);
            $dashboard_ids[] = (int)$d->nid;
            foreach( $config->drilldowns as $drilldown) {
                if ( is_object($drilldown->dashboard) ) {
                    $drilldown_dashboard_ids[] = (int)$drilldown->dashboard->id; // for backwards compatibility
                } else {
                    $drilldown_dashboard_ids[] = (int)$drilldown->dashboard;
                }
            }
        }
        $drilldown_dashboard_ids = array_unique($drilldown_dashboard_ids);
        $display_dashboard_ids = array_diff($dashboard_ids, $drilldown_dashboard_ids);
        $display_dashboards = array();
        foreach ( $dashboards as $d ) {
            if ( in_array($d->nid,$display_dashboard_ids) ) {
                $display_dashboards[] = $d;
            }
        }
        // if initial dashboard is a drilldown dashboard, load first non-drilldown dashboard instead
        if ( in_array($dashboard->nid, $drilldown_dashboard_ids) && empty($_GET['id']) ) {
            $dashboardKeys = array_keys($display_dashboard_ids);
            $dashboard = $dashboards[array_shift($dashboardKeys)];
        }
    }

    // force a dashboard id into the url for javascript libs
    // TODO doing a redirect is wasteful, find some other way
    if ( empty($_GET['id']) &&  isset($dashboard) ) {
        drupal_goto('dashboards',array('query'=>array('id'=>$dashboard->nid)));
    }

    foreach ( $datasources as $k => $ds ) {
        if ( $ds->name == gd_datasource_get_active() ) {
            $datasources[$k]->active = true;
        }
    }

    return array($datasources, $dashboard, $display_dashboards);
}
    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);
            }
        }
    }
        } catch ( Exception $e ) {
            LogHelper::log_error($e);
            $errors[] = $e->getMessage();
        }
    }
}

?>
<div id="content-inside">
    <div style="float: left; width: 85%"><h2>Create Topic</h2></div>
    <div style="float: right; width: 15%">
        <div><a href='/account_datamart_statistics_charts' class="fancyCpButton">Back to Statistics</a></div>
    </div>
    <br clear="all">
<?php
if (variable_get("account_settings_maxdms") > count(gd_datasource_get_all())) {
    ?>
    <form id="dmcreate" action="/account_datamart_create_datamart" method="post">
        <table border="0" width="93%">
            <?php if ( !empty($errors) ) { ?>
            <tr>
                <td colspan="2">
                    <div class="alert alert-danger">
                    <h4>Error!</h4>
                    <?php
                    foreach ($errors as $message) {
                        echo $message.'<br/>';
                    }
                    ?>
                    </div>
                </td>