Exemplo n.º 1
0
 /**
  * {@inheritdoc}
  */
 public function query($group_by = FALSE)
 {
     $required = FALSE;
     $this->queryParseSearchExpression($this->argument);
     if (!isset($this->searchQuery)) {
         $required = TRUE;
     } else {
         $words = $this->searchQuery->words();
         if (empty($words)) {
             $required = TRUE;
         }
     }
     if ($required) {
         if ($this->operator == 'required') {
             $this->query->addWhere(0, 'FALSE');
         }
     } else {
         $search_index = $this->ensureMyTable();
         $search_condition = db_and();
         // Create a new join to relate the 'search_total' table to our current 'search_index' table.
         $definition = array('table' => 'search_total', 'field' => 'word', 'left_table' => $search_index, 'left_field' => 'word');
         $join = Views::pluginManager('join')->createInstance('standard', $definition);
         $search_total = $this->query->addRelationship('search_total', $join, $search_index);
         // Add the search score field to the query.
         $this->search_score = $this->query->addField('', "{$search_index}.score * {$search_total}.count", 'score', array('function' => 'sum'));
         // Add the conditions set up by the search query to the views query.
         $search_condition->condition("{$search_index}.type", $this->searchType);
         $search_dataset = $this->query->addTable('node_search_dataset');
         $conditions = $this->searchQuery->conditions();
         $condition_conditions =& $conditions->conditions();
         foreach ($condition_conditions as $key => &$condition) {
             // Make sure we just look at real conditions.
             if (is_numeric($key)) {
                 // Replace the conditions with the table alias of views.
                 $this->searchQuery->conditionReplaceString('d.', "{$search_dataset}.", $condition);
             }
         }
         $search_conditions =& $search_condition->conditions();
         $search_conditions = array_merge($search_conditions, $condition_conditions);
         // Add the keyword conditions, as is done in
         // SearchQuery::prepareAndNormalize(), but simplified because we are
         // only concerned with relevance ranking so we do not need to normalize.
         $or = db_or();
         foreach ($words as $word) {
             $or->condition("{$search_index}.word", $word);
         }
         $search_condition->condition($or);
         // Add the GROUP BY and HAVING expressions to the query.
         $this->query->addWhere(0, $search_condition);
         $this->query->addGroupBy("{$search_index}.sid");
         $matches = $this->searchQuery->matches();
         $placeholder = $this->placeholder();
         $this->query->addHavingExpression(0, "COUNT(*) >= {$placeholder}", array($placeholder => $matches));
     }
     // Set to NULL to prevent PDO exception when views object is cached
     // and to clear out memory.
     $this->searchQuery = NULL;
 }
Exemplo n.º 2
0
 /**
  * {@inheritdoc}
  */
 public function query($group_by = FALSE)
 {
     $required = FALSE;
     $this->queryParseSearchExpression($this->argument);
     if (!isset($this->searchQuery)) {
         $required = TRUE;
     } else {
         $words = $this->searchQuery->words();
         if (empty($words)) {
             $required = TRUE;
         }
     }
     if ($required) {
         if ($this->operator == 'required') {
             $this->query->addWhere(0, 'FALSE');
         }
     } else {
         $search_index = $this->ensureMyTable();
         $search_condition = db_and();
         // Create a new join to relate the 'search_total' table to our current 'search_index' table.
         $definition = array('table' => 'search_total', 'field' => 'word', 'left_table' => $search_index, 'left_field' => 'word');
         $join = Views::pluginManager('join')->createInstance('standard', $definition);
         $search_total = $this->query->addRelationship('search_total', $join, $search_index);
         $this->search_score = $this->query->addField('', "SUM({$search_index}.score * {$search_total}.count)", 'score', array('aggregate' => TRUE));
         $search_condition->condition("{$search_index}.type", $this->searchType);
         if (!$this->searchQuery->simple()) {
             $search_dataset = $this->query->addTable('search_dataset');
             $conditions = $this->searchQuery->conditions();
             $condition_conditions =& $conditions->conditions();
             foreach ($condition_conditions as $key => &$condition) {
                 // Make sure we just look at real conditions.
                 if (is_numeric($key)) {
                     // Replace the conditions with the table alias of views.
                     $this->searchQuery->conditionReplaceString('d.', "{$search_dataset}.", $condition);
                 }
             }
             $search_conditions =& $search_condition->conditions();
             $search_conditions = array_merge($search_conditions, $condition_conditions);
         } else {
             // Stores each condition, so and/or on the filter level will still work.
             $or = db_or();
             foreach ($words as $word) {
                 $or->condition("{$search_index}.word", $word);
             }
             $search_condition->condition($or);
         }
         $this->query->addWhere(0, $search_condition);
         $this->query->addGroupBy("{$search_index}.sid");
         $matches = $this->searchQuery->matches();
         $placeholder = $this->placeholder();
         $this->query->addHavingExpression(0, "COUNT(*) >= {$placeholder}", array($placeholder => $matches));
     }
     // Set to NULL to prevent PDO exception when views object is cached
     // and to clear out memory.
     $this->searchQuery = NULL;
 }
Exemplo n.º 3
0
 /**
  * See _node_access_where_sql() for a non-views query based implementation.
  */
 public function query()
 {
     $account = $this->view->getUser();
     if (!$account->hasPermission('administer nodes')) {
         $table = $this->ensureMyTable();
         $grants = db_or();
         foreach (node_access_grants('view', $account) as $realm => $gids) {
             foreach ($gids as $gid) {
                 $grants->condition(db_and()->condition($table . '.gid', $gid)->condition($table . '.realm', $realm));
             }
         }
         $this->query->addWhere('AND', $grants);
         $this->query->addWhere('AND', $table . '.grant_view', 1, '>=');
     }
 }
Exemplo n.º 4
0
 function op_word($fulltext_field)
 {
     $where = $this->operator == 'word' ? db_or() : db_and();
     // Don't filter on empty strings.
     if (empty($this->value[0])) {
         return;
     }
     $value = Unicode::strtolower($this->value[0]);
     $words = preg_split('/ /', $value, -1, PREG_SPLIT_NO_EMPTY);
     foreach ($words as $word) {
         $placeholder = $this->placeholder();
         $where->where("{$fulltext_field} LIKE {$placeholder}", array($placeholder => '% ' . db_like($word) . '%'));
     }
     $this->query->addWhere($this->options['group'], $where);
 }
 /**
  * {@inheritdoc}
  */
 public function getQuery()
 {
     $query = parent::getQuery();
     // Add a query for meter_category.
     $field = field_info_field('field_group_node');
     $table_name = _field_sql_storage_tablename($field);
     $request = $this->getRequest();
     $query->leftJoin($table_name, 'gn', "message.mid = gn.entity_id AND gn.entity_type='message'");
     $query->innerJoin('field_data_field_node', 'fn', "message.mid = fn.entity_id AND fn.entity_type='message'");
     $query->innerJoin('node', 'node', "fn.field_node_target_id = node.nid");
     // Show only publish content in active stream.
     $query->condition('node.status', 1);
     if (!empty($request['topics'])) {
         // Join related to Articles tables to get V&V activities with user's
         // topics of interest.
         $query->innerJoin('field_data_c4m_vocab_topic', 'crt', "node.nid = crt.entity_id AND crt.entity_type='node'");
     }
     $query->addField('gn', 'field_group_node_target_id', 'group_node');
     if (!empty($request['group'])) {
         if (empty($request['hide_articles'])) {
             $or = db_or();
             $or->condition('gn.field_group_node_target_id', $request['group'], is_array($request['group']) ? 'IN' : '=');
             if (!empty($request['topics'])) {
                 $and = db_and();
                 $and->isNull('gn.field_group_node_target_id');
                 $and->condition('node.type', 'article');
                 $and->condition('crt.c4m_vocab_topic_tid', $request['topics'], is_array($request['topics']) ? 'IN' : '=');
                 $or->condition($and);
             } else {
                 $or->isNull('gn.field_group_node_target_id');
             }
             $query->condition($or);
         } else {
             $query->condition('gn.field_group_node_target_id', $request['group'], is_array($request['group']) ? 'IN' : '=');
         }
     }
     $query->addTag('activity_stream_entity_field_access');
     return $query;
 }
/**
 * Alter the query selecting data from {xmlsitemap} during sitemap generation.
 *
 * @param $query
 *   A Query object describing the composite parts of a SQL query.
 *
 * @see hook_query_TAG_alter()
 */
function hook_query_xmlsitemap_generate_alter(QueryAlterableInterface $query) {
  $sitemap = $query->getMetaData('sitemap');
  if (!empty($sitemap->context['vocabulary'])) {
    $node_condition = db_and();
    $node_condition->condition('type', 'taxonomy_term');
    $node_condition->condition('subtype', $sitemap->context['vocabulary']);
    $normal_condition = db_and();
    $normal_condition->condition('type', 'taxonomy_term', '<>');
    $condition = db_or();
    $condition->condition($node_condition);
    $condition->condition($normal_condition);
    $query->condition($condition);
  }
}
Exemplo n.º 7
0
 public function addFilter()
 {
     if (empty($this->handler->value)) {
         return;
     }
     $this->handler->ensureMyTable();
     // Shorten some variables:
     $field = $this->getField();
     $options = $this->handler->options;
     $operator = $this->handler->operator;
     $formula = !empty($this->formula);
     $value = $this->handler->value;
     if (empty($options['group'])) {
         $options['group'] = 0;
     }
     // add_condition determines whether a single expression is enough(FALSE) or the
     // conditions should be added via an db_or()/db_and() (TRUE).
     $add_condition = TRUE;
     if ($operator == 'not') {
         $value = NULL;
         $operator = 'IS NULL';
         $add_condition = FALSE;
     } elseif ($operator == 'or' && empty($options['reduce_duplicates'])) {
         if (count($value) > 1) {
             $operator = 'IN';
         } else {
             $value = is_array($value) ? array_pop($value) : $value;
             $operator = '=';
         }
         $add_condition = FALSE;
     }
     if (!$add_condition) {
         if ($formula) {
             $placeholder = $this->placeholder();
             if ($operator == 'IN') {
                 $operator = "{$operator} IN({$placeholder})";
             } else {
                 $operator = "{$operator} {$placeholder}";
             }
             $placeholders = array($placeholder => $value) + $this->placeholders;
             $this->handler->query->addWhereExpression($options['group'], "{$field} {$operator}", $placeholders);
         } else {
             $placeholder = $this->placeholder();
             if (count($this->handler->value) > 1) {
                 $placeholder .= '[]';
                 if ($operator == 'IS NULL') {
                     $this->handler->query->addWhereExpression(0, "{$field} {$operator}");
                 } else {
                     $this->handler->query->addWhereExpression(0, "{$field} {$operator}({$placeholder})", array($placeholder => $value));
                 }
             } else {
                 if ($operator == 'IS NULL') {
                     $this->handler->query->addWhereExpression(0, "{$field} {$operator}");
                 } else {
                     $this->handler->query->addWhereExpression(0, "{$field} {$operator} {$placeholder}", array($placeholder => $value));
                 }
             }
         }
     }
     if ($add_condition) {
         $field = $this->handler->realField;
         $clause = $operator == 'or' ? db_or() : db_and();
         foreach ($this->handler->tableAliases as $value => $alias) {
             $clause->condition("{$alias}.{$field}", $value);
         }
         // implode on either AND or OR.
         $this->handler->query->addWhere($options['group'], $clause);
     }
 }
Exemplo n.º 8
0
 /**
  * Implements Drupal_SolrDevel_Queue::run().
  */
 public function run()
 {
     $queued = TRUE;
     $env_id = $this->_adapter->getOption('env_id');
     // Initialize the debug array.
     $this->_debug = array('read_only' => FALSE, 'bundle_excluded' => FALSE, 'in_table' => TRUE, 'processed' => FALSE, 'status_callbacks' => array(), 'status_callbacks_skipped' => array(), 'exclude_hooks' => array());
     // Return FALSE if index is read only.
     if (variable_get('apachesolr_read_only', 0)) {
         $this->_debug['read_only'] = TRUE;
         $queued = FALSE;
     }
     // Get bundles that are allowed to be indexed.
     $bundles = drupal_map_assoc(apachesolr_get_index_bundles($env_id, $this->_entityType));
     // Checks whether the bundle is excluded.
     if (!isset($bundles[$this->_bundle])) {
         $this->_debug['bundle_excluded'] = TRUE;
         $queued = FALSE;
     }
     // Get $last_entity_id and $last_changed.
     extract(apachesolr_get_last_index_position($env_id, $this->_entityType));
     $table = apachesolr_get_indexer_table($this->_entityType);
     // Build the queue query.
     $query = db_select($table, 'aie')->fields('aie')->condition('aie.bundle', $bundles)->condition('entity_id', $this->_entityId)->condition(db_or()->condition('aie.changed', $last_changed, '>')->condition(db_and()->condition('aie.changed', $last_changed, '<=')->condition('aie.entity_id', $last_entity_id, '>')));
     // Entity-specific tables don't need this condition.
     if ($table == 'apachesolr_index_entities') {
         $query->condition('aie.entity_type', $this->_entityType);
     }
     // If no records are returned, the item has been processed.
     if (!($record = $query->execute()->fetch())) {
         $this->_debug['processed'] = TRUE;
         $queued = FALSE;
     }
     // Loads index include, which is where the default status callbacks live.
     module_load_include('inc', 'apachesolr', 'apachesolr.index');
     // Ensure entry is in table. If not, we have a problem.
     $query = db_select($table, 'aie')->fields('aie', array('status'))->condition('aie.entity_type', $this->_entityType)->condition('aie.entity_id', $this->_entityId);
     // Invokes status callback to check whether entity should be excluded. For
     // example, the apachesolr_index_node_status_callback() tests if the node
     // status is 0, meaning it is unpublished.
     if ($record = $query->execute()->fetch()) {
         $status_callbacks = apachesolr_entity_get_callback($this->_entityType, 'status callback');
         if (is_array($status_callbacks)) {
             foreach ($status_callbacks as $status_callback) {
                 if (is_callable($status_callback)) {
                     $callback_value = $status_callback($this->_entityId, $this->_entityType);
                     $record->status = $record->status && $callback_value;
                     $this->_debug['status_callbacks'][$status_callback] = !$callback_value;
                     // FALSE
                 } else {
                     $this->_debug['status_callbacks_skipped'][$status_callback] = TRUE;
                 }
             }
         }
     } else {
         // There is a problem with the queue if the data is not here.
         $this->_debug['in_table'] = FALSE;
         $queued = FALSE;
     }
     // Invoke hook_apachesolr_exclude().
     foreach (module_implements('apachesolr_exclude') as $module) {
         $function = $module . '_apachesolr_exclude';
         $exclude = module_invoke($module, 'apachesolr_exclude', $record->entity_id, $this->_entityType, $record, $env_id);
         if (!empty($exclude)) {
             $this->_debug['exclude_hooks'][$function] = TRUE;
             $queued = FALSE;
         } else {
             $this->_debug['exclude_hooks'][$function] = FALSE;
         }
     }
     // Invoke hook_apachesolr_ENTITY_TYPE_exclude().
     foreach (module_implements('apachesolr_' . $this->_entityType . '_exclude') as $module) {
         $function = $module . '_apachesolr_' . $this->_entityType . '_exclude';
         $exclude = module_invoke($module, 'apachesolr_' . $this->_entityType . '_exclude', $record->entity_id, $record, $env_id);
         if (!empty($exclude)) {
             $this->_debug['exclude_hooks'][$function] = TRUE;
             $queued = FALSE;
         } else {
             $this->_debug['exclude_hooks'][$function] = FALSE;
         }
     }
     return $queued;
 }
Exemplo n.º 9
0
 /**
  * {@inheritdoc}
  */
 public function query()
 {
     // Since attachment views don't validate the exposed input, parse the search
     // expression if required.
     if (!$this->parsed) {
         $this->queryParseSearchExpression($this->value);
     }
     $required = FALSE;
     if (!isset($this->searchQuery)) {
         $required = TRUE;
     } else {
         $words = $this->searchQuery->words();
         if (empty($words)) {
             $required = TRUE;
         }
     }
     if ($required) {
         if ($this->operator == 'required') {
             $this->query->addWhere($this->options['group'], 'FALSE');
         }
     } else {
         $search_index = $this->ensureMyTable();
         $search_condition = db_and();
         // Create a new join to relate the 'search_total' table to our current
         // 'search_index' table.
         $definition = array('table' => 'search_total', 'field' => 'word', 'left_table' => $search_index, 'left_field' => 'word');
         $join = Views::pluginManager('join')->createInstance('standard', $definition);
         $search_total = $this->query->addRelationship('search_total', $join, $search_index);
         $this->search_score = $this->query->addField('', "{$search_index}.score * {$search_total}.count", 'score', array('function' => 'sum'));
         $search_condition->condition("{$search_index}.type", $this->searchType);
         $search_dataset = $this->query->addTable('node_search_dataset');
         $conditions = $this->searchQuery->conditions();
         $condition_conditions =& $conditions->conditions();
         foreach ($condition_conditions as $key => &$condition) {
             // Make sure we just look at real conditions.
             if (is_numeric($key)) {
                 // Replace the conditions with the table alias of views.
                 $this->searchQuery->conditionReplaceString('d.', "{$search_dataset}.", $condition);
             }
         }
         $search_conditions =& $search_condition->conditions();
         $search_conditions = array_merge($search_conditions, $condition_conditions);
         $this->query->addWhere($this->options['group'], $search_condition);
         $this->query->addGroupBy("{$search_index}.sid");
         $matches = $this->searchQuery->matches();
         $placeholder = $this->placeholder();
         $this->query->addHavingExpression($this->options['group'], "COUNT(*) >= {$placeholder}", array($placeholder => $matches));
     }
     // Set to NULL to prevent PDO exception when views object is cached.
     $this->searchQuery = NULL;
 }
Exemplo n.º 10
0
/**
 * Deletes contents that don't have titles, "Document Moved", "Export.gov Page Not Found" and "The Web site cannot be found".
 * These contents are scrapped from export.gov and should not be indexed in solr search engine,
 * Unless otherwise they are properly rendering searched contents.
 */
function export_gov_micro_page_cleanup()
{
    $query = db_select('node', 'n');
    $query->join('field_data_field_exportrip_origin', 'origin', 'n.nid = origin.entity_id');
    $query->fields('n', array('nid', 'title'))->condition('n.type', 'export_gov_micro_site_page', '=')->condition(db_and()->condition(db_or()->condition('n.status', 0, '=')->condition('n.status', 1, '=')))->condition(db_and()->condition(db_or()->condition('n.title', '', '=')->condition('n.title', ' ', '=')->condition('n.title', NULL, '=')->condition('n.title', 'Export.gov Page Not Found', '=')->condition('n.title', 'Document Moved', '=')->condition('n.title', 'The Web site cannot be found', '=')))->range(0, 100);
    $result = $query->execute();
    $results = $result->fetchAll();
    $w = 0;
    $x = 0;
    $y = 0;
    $z = 0;
    foreach ($results as $record) {
        if ($record->title == '' || $record->title == ' ' || $record->title == NULL) {
            $a[] = $record->nid;
            $x++;
        } elseif ($record->title == 'Export.gov Page Not Found') {
            $b[] = $record->nid;
            $y++;
        } elseif ($record->title == 'Document Moved') {
            $c[] = $record->nid;
            $z++;
        } elseif ($record->title == 'The Web site cannot be found') {
            $d[] = $record->nid;
            $w++;
        }
    }
    drupal_set_message(t('Total # of contents to be deleted: %count', array('%count' => count($results))), 'warning');
    if (!empty($results)) {
        if (count($a) > 0) {
            node_delete_multiple($a);
            drupal_set_message(t('Deleted %count contents that don\'t have titles.', array('%count' => count($a))), 'warning');
        }
        if (count($b) > 0) {
            node_delete_multiple($b);
            drupal_set_message(t('Deleted %count content that says "Export.gov Page Not Found".', array('%count' => count($b))), 'warning');
        }
        if (count($c) > 0) {
            node_delete_multiple($c);
            drupal_set_message(t('Deleted %count content that has "Document Moved".', array('%count' => count($c))), 'warning');
        }
        if (count($d) > 0) {
            node_delete_multiple($d);
            drupal_set_message(t('Deleted %count content that has "The Web site cannot be found".', array('%count' => count($d))), 'warning');
        }
    } else {
        drupal_set_message(t('Contents found in DB for deletion: %count', array('%count' => count($w + $x + $y + $z) - 1)), 'warning');
    }
}
Exemplo n.º 11
0
 static function removeGroup($type, $id)
 {
     if (!isValidOrganisationType($type)) {
         drupal_set_message(tt('This (%1$s) is not something you can remove.', t_type($type)), 'error');
         return FALSE;
     }
     if (!self::isOwner($type, $id)) {
         drupal_set_message(t('You are not authorised to perform this action'), 'error');
         return FALSE;
     }
     if (self::hasMembers($type, $id)) {
         drupal_set_message(tt('There are already members in this %1$s. You can still edit the %1$s though.', t_type($type)), 'error');
         return FALSE;
     }
     if ($type == _ORGANISATION_GROUP && db_query("SELECT pid FROM soc_projects WHERE org_id = {$id}")->rowCount()) {
         drupal_set_message(tt('There are already projects for this %1$s. You should delete these first.', t_type($type)), 'error');
         return FALSE;
     }
     if ($type == _INSTITUTE_GROUP && db_query("SELECT pid FROM soc_studentgroups WHERE inst_id = {$id}")->rowCount()) {
         drupal_set_message(tt('There are already student groups for this %1$s. You should delete these first.', t_type($type)), 'error');
         return FALSE;
     }
     try {
         if ($type != _PROJECT_OBJ) {
             $num_deleted2 = db_delete("soc_user_membership")->condition('group_id', $id)->condition('type', $type)->execute();
             if (!$num_deleted2) {
                 drupal_set_message(tt('The group had no members.', $type), 'status');
             }
             $subtype = $type == _ORGANISATION_GROUP ? _MENTOR_TYPE : ($type == _INSTITUTE_GROUP ? _SUPERVISOR_TYPE : _STUDENT_GROUP);
             $code_field = $subtype == _STUDENT_GROUP ? 'studentgroup_id' : 'entity_id';
             $num_deleted3 = db_delete("soc_codes")->condition(db_and()->condition($code_field, $id)->condition(db_or()->condition('type', $subtype)->condition('type', "{$type}_admin")))->execute();
             if (!$num_deleted3) {
                 drupal_set_message(tt('The %1$s had no code attached.', $type), 'status');
             }
         }
     } catch (Exception $e) {
         drupal_set_message(tt(' We could not delete the %1$s', t_type($type)) . (_DEBUG ? $ex->getMessage() : ''), 'error');
         return FALSE;
     }
     try {
         $num_deleted = db_delete(tableName($type))->condition(self::keyField($type), $id)->execute();
         if ($num_deleted) {
             drupal_set_message(tt('The %1$s has been deleted.', $type), 'status');
             return TRUE;
         } else {
             drupal_set_message(tt('The %1$s seems to have been deleted already, refresh your screen to see if this is true.', $type), 'error');
             return 0;
         }
     } catch (Exception $e) {
         drupal_set_message(tt(' We could not delete the %1$s', t_type($type)) . (_DEBUG ? $ex->getMessage() : ''), 'error');
         return FALSE;
     }
 }
Exemplo n.º 12
0
 protected function opContainsWord($field)
 {
     $where = $this->operator == 'word' ? db_or() : db_and();
     // Don't filter on empty strings.
     if (empty($this->value)) {
         return;
     }
     preg_match_all('/ (-?)("[^"]+"|[^" ]+)/i', ' ' . $this->value, $matches, PREG_SET_ORDER);
     foreach ($matches as $match) {
         $phrase = FALSE;
         // Strip off phrase quotes
         if ($match[2][0] == '"') {
             $match[2] = substr($match[2], 1, -1);
             $phrase = TRUE;
         }
         $words = trim($match[2], ',?!();:-');
         $words = $phrase ? array($words) : preg_split('/ /', $words, -1, PREG_SPLIT_NO_EMPTY);
         foreach ($words as $word) {
             $where->condition($field, '%' . db_like(trim($word, " ,!?")) . '%', 'LIKE');
         }
     }
     if (!$where) {
         return;
     }
     // previously this was a call_user_func_array but that's unnecessary
     // as views will unpack an array that is a single arg.
     $this->query->addWhere($this->options['group'], $where);
 }
Exemplo n.º 13
0
Arquivo: db.php Projeto: 318io/318-io
function get_claim_by_id_and_vcond($claim_id, $vcond)
{
    db_set_active(CLAIM_DB);
    if (!db_table_exists(CLAIM_COLL)) {
        db_set_active();
        return array();
    }
    $query = db_select(CLAIM_COLL, 'c');
    $query->join(CLAIM_AUTHOR, 'a', 'c.uid = a.uid');
    //JOIN
    $query->fields('c', array('id', 'cid', 'hd', 'copyright', 'display', 'note', 'created', 'verified', 'openmosaic'))->fields('a', array('real_name', 'email', 'phone', 'address', '4digitid'))->condition(db_and()->condition('id', $claim_id, '=')->condition('verified', $vcond, '='));
    //$query->fields('c', array('cid', 'uid', 'open', 'note', 'created', 'verified')) // SELECT the fields from CLAIM_COLL
    //      ->condition('id', $claim_id, '=');                                        // WHERE id = $claim_id
    $result = $query->execute();
    $num_of_result = $result->rowCount();
    // should be 1 if fetching is successful.
    $record = array();
    // empty array
    if ($num_of_result > 0) {
        $record = $result->fetchAssoc();
    }
    db_set_active();
    return $record;
    // if no record found, an empty array is returned;
}
Exemplo n.º 14
0
 private function __filterEvents($filter, $fields = NULL)
 {
     $filteredEventIds = array();
     $numFilter = 0;
     $filteredTags = array();
     $filteredBezirke = array();
     $filteredTags = array();
     if (isset($filter['mustHaveGps'])) {
         $numFilters++;
         $resultEvents = db_query("SELECT EID, ADID\n     FROM {aae_data_adresse} ad\n     JOIN {aae_data_event} e\n     WHERE ad.gps_long != '' AND ad.gps_lat != '' AND ad.ADID = e.ort");
         foreach ($resultEvents->fetchAll() as $event) {
             $filteredEventIds[] = $event->EID;
         }
     }
     // end empty-GPS-jumper
     if (isset($filter['tags'])) {
         $tags = db_select($this->tbl_event_sparte, 'hs')->fields('hs', array('hat_EID'));
         $and = db_and();
         foreach ($filter['tags'] as $tag) {
             $tag = $this->clearContent($tag);
             $filteredTags[$tag] = $tag;
             $and->condition('hat_KID', $tag);
             $numFilters++;
         }
         $filterTags = $tags->condition($and)->execute()->fetchAll();
         foreach ($filterTags as $tag) {
             $filteredEventIds[] = $tag->hat_EID;
         }
     }
     // end Tag-Filter
     if (isset($filter['bezirke'])) {
         foreach ($filter['bezirke'] as $bezirk) {
             $numFilters++;
             $bezirk_id = $this->clearContent($bezirk);
             $filteredBezirke[$bezirkId] = $bezirkId;
             $adressen = db_select($this->tbl_adresse, 'a')->fields('a', array('ADID'))->condition('bezirk', $bezirk_id)->execute()->fetchAll();
             foreach ($adressen as $adresse) {
                 $filterBezirke = db_select($this->tbl_event, 'e')->fields('e', array('EID'))->condition('ort', $adresse->ADID)->execute()->fetchAll();
                 foreach ($filterBezirke as $bezirk) {
                     $filteredEventIds[] = $bezirk->EID;
                 }
             }
         }
     }
     // end Bezirke-Filter
     if (isset($filter['keyword'])) {
         $numFilters++;
         $or = db_or()->condition('name', '%' . $filter['keyword'] . '%', 'LIKE')->condition('kurzbeschreibung', '%' . $filter['keyword'] . '%', 'LIKE');
         $filterKeyword = db_select($this->tbl_event, 'e')->fields('e', array('EID'))->condition($or)->execute()->fetchAll();
         foreach ($filterKeyword as $keyword) {
             $filteredEventIds[] = $keyword->EID;
         }
     }
     // end Keyword-Filter
     if (isset($filter['day'])) {
         // Search for the exact date OR multiple-days-events in between
         $numFilters++;
         $resultDays = db_query('SELECT EID FROM {aae_data_event} WHERE (start_ts <= :start AND ende_ts >= :start AND ende_ts NOT LIKE :zeroLike) OR start_ts LIKE :startLike', array(':start' => $filter['day'], ':startLike' => $filter['day'] . '%', ':zeroLike' => '1000-01-01 00:00:0%'));
         foreach ($resultDays as $day) {
             $filteredEventIds[] = $day->EID;
         }
     }
     // end Day-Filter
     if (isset($filter['AID'])) {
         $numFilters++;
         $resultAkteur = db_select($this->tbl_akteur_events, 'ae')->fields('ae')->condition('AID', $filter['AID'])->execute()->fetchAll();
         foreach ($resultAkteur as $akteur) {
             $filteredEventIds[] = $akteur->EID;
         }
     }
     // end AkteurID-Filter
     if (!empty($filteredEventIds) && $fields == 'complete') {
         $filteredEventChildrenIds = db_select($this->tbl_event, 'e')->fields('e', array('EID'))->condition('parent_EID', $filteredEventIds)->execute();
         foreach ($filteredEventChildrenIds->fetchAll() as $child) {
             $filteredEventIds[] = $child->EID;
         }
     }
     return $this->getDuplicates($filteredEventIds, $numFilters);
 }
 function getQueue($show_system_tasks = FALSE)
 {
     if (!empty($this->_userId) and $this->_userId > 0) {
         /* Instance where the user id is known.  need to see if there is a processID given.
          * This means that the mode in which we're working is user based.. we only care about a user in this case
          */
         $queries = array();
         //query to get the user assigned to this task
         if ($this->_mode != 'admin') {
             $this->_mode = 'user';
         }
         if ($this->_debug) {
             watchdog('maestro', "Entering getQueue - {$this->_mode} mode");
         }
         $this->_userTaskCount = 0;
         $query = db_select('maestro_queue', 'a');
         $query->join('maestro_template_data', 'b', 'a.template_data_id = b.id');
         $query->leftJoin('maestro_production_assignments', 'c', 'a.id = c.task_id');
         $query->join('maestro_process', 'd', 'a.process_id = d.id');
         $query->fields('a', array('id', 'template_data_id', 'process_id', 'is_interactive', 'handler', 'task_data', 'created_date', 'started_date'));
         $query->fields('b', array('task_class_name', 'template_id', 'taskname', 'is_dynamic_taskname', 'dynamic_taskname_variable_id'));
         if ($this->_mode == 'admin') {
             $query->fields('c', array('assign_id', 'assign_type'));
             $query->fields('e', array('name'));
             $query->leftJoin('users', 'e', 'c.assign_id = e.uid');
         }
         $query->addField('d', 'pid', 'parent_process_id');
         $query->fields('d', array('tracking_id', 'flow_name'));
         if ($this->_mode != 'admin') {
             $query->condition('c.assign_id', $this->_userId, '=');
         }
         if ($show_system_tasks == FALSE) {
             $query->condition('a.is_interactive', MaestroInteractiveFlag::IS_INTERACTIVE);
         }
         $query->condition(db_or()->condition('a.archived', 0)->condition('a.archived', NULL));
         $query->condition(db_and()->condition('a.status', 0, '>='));
         $query->condition('c.assign_type', MaestroAssignmentTypes::USER, '=');
         $query->orderBy('a.id', 'DESC');
         $queries[MaestroAssignmentTypes::USER] = $query;
         //query to get the users associated with a role assigned to this task
         $query = db_select('maestro_queue', 'a');
         $query->join('maestro_template_data', 'b', 'a.template_data_id = b.id');
         $query->leftJoin('maestro_production_assignments', 'c', 'a.id = c.task_id');
         $query->join('maestro_process', 'd', 'a.process_id = d.id');
         $query->leftJoin('users_roles', 'f', 'c.assign_id = f.rid');
         $query->fields('a', array('id', 'template_data_id', 'process_id', 'is_interactive', 'handler', 'task_data', 'created_date', 'started_date'));
         $query->fields('b', array('task_class_name', 'template_id', 'taskname', 'is_dynamic_taskname', 'dynamic_taskname_variable_id'));
         if ($this->_mode == 'admin') {
             $query->fields('c', array('assign_id', 'assign_type'));
             $query->fields('g', array('name'));
             $query->leftJoin('users', 'e', 'f.uid = e.uid');
             $query->leftJoin('role', 'g', 'c.assign_id = g.rid');
         }
         $query->addField('d', 'pid', 'parent_process_id');
         $query->fields('d', array('tracking_id', 'flow_name'));
         if ($this->_mode != 'admin') {
             $query->condition('f.uid', $this->_userId, '=');
         }
         if ($show_system_tasks == FALSE) {
             $query->condition('a.is_interactive', MaestroInteractiveFlag::IS_INTERACTIVE);
         }
         $query->condition(db_or()->condition('a.archived', 0)->condition('a.archived', NULL));
         $query->condition(db_and()->condition('a.status', 0, '>='));
         $query->condition('c.assign_type', MaestroAssignmentTypes::ROLE, '=');
         $query->orderBy('a.id', 'DESC');
         $queries[MaestroAssignmentTypes::ROLE] = $query;
         if (module_exists('og')) {
             //query gets all og's assigned to this task, up to the logic to determine whether or not they are assigned
             $query = db_select('maestro_queue', 'a');
             $query->join('maestro_template_data', 'b', 'a.template_data_id = b.id');
             $query->leftJoin('maestro_production_assignments', 'c', 'a.id = c.task_id');
             $query->join('maestro_process', 'd', 'a.process_id = d.id');
             $query->leftJoin('users_roles', 'f', 'c.assign_id = f.rid');
             $query->fields('a', array('id', 'template_data_id', 'process_id', 'is_interactive', 'handler', 'task_data', 'created_date', 'started_date'));
             $query->fields('b', array('task_class_name', 'template_id', 'taskname', 'is_dynamic_taskname', 'dynamic_taskname_variable_id'));
             $query->fields('c', array('assign_id', 'assign_type', 'process_variable'));
             if ($this->_mode == 'admin') {
                 $og_values = MaestroOgCommon::getOgTableValues();
                 $query->leftJoin($og_values['table'], 'g', 'c.assign_id = g.' . $og_values['gid_column']);
                 $query->addField('g', $og_values['title_column'], 'name');
             }
             $query->addField('d', 'pid', 'parent_process_id');
             $query->fields('d', array('tracking_id', 'flow_name'));
             if ($show_system_tasks == FALSE) {
                 $query->condition('a.is_interactive', MaestroInteractiveFlag::IS_INTERACTIVE);
             }
             $query->condition(db_or()->condition('a.archived', 0)->condition('a.archived', NULL));
             $query->condition(db_and()->condition('a.status', 0, '>='));
             $query->condition('c.assign_type', MaestroAssignmentTypes::GROUP, '=');
             $query->orderBy('a.id', 'DESC');
             $queries[MaestroAssignmentTypes::GROUP] = $query;
         }
         foreach ($queries as $assign_type => $query) {
             $userTaskResult = $query->execute();
             $numTaskRows = $query->countQuery()->execute()->fetchField();
             if ($numTaskRows > 0) {
                 // Return a semi-colon delimited list of queue id's for that user.
                 foreach ($userTaskResult as $userTaskRecord) {
                     if ($assign_type == MaestroAssignmentTypes::GROUP && $this->_mode != 'admin') {
                         // Test if group name has been set to use a variable for this task
                         if ($userTaskRecord->assign_id == 0 or $userTaskRecord->process_variable > 0) {
                             // The group variable is expected to contain the group name
                             $group_variable = $this->getProcessVariable($userTaskRecord->process_variable, $userTaskRecord->process_id);
                             $og_groups = MaestroOgCommon::getAllGroups();
                             foreach ($og_groups as $og_group) {
                                 if ($og_group->label == $group_variable) {
                                     $userTaskRecord->assign_id = $og_group->gid;
                                 }
                             }
                         }
                         if ($userTaskRecord->assign_id > 0) {
                             if (MaestroOgCommon::getOGVersion() === MaestroOgCommon::OG_VERSION_2) {
                                 $query = db_select("og_membership", "a");
                                 $query->fields("a", array("gid"));
                                 $query->condition("a.gid", $userTaskRecord->assign_id);
                                 $query->condition("a.etid", $this->_userId);
                                 $res = $query->execute()->fetchAssoc();
                                 if (count($res) == 0) {
                                     continue;
                                 }
                             } else {
                                 $og_query = new EntityFieldQuery();
                                 $og_query->entityCondition('entity_type', 'user')->fieldCondition(OG_AUDIENCE_FIELD, 'gid', $userTaskRecord->assign_id, '=');
                                 $og_res = $og_query->execute();
                                 if (!array_key_exists($this->_userId, $og_res['user'])) {
                                     continue;
                                 }
                             }
                         } else {
                             watchdog('maestro', "maestro->getQueue could not resolve the assigned to user id for queue record {$userTaskRecord->id}");
                             break;
                         }
                     }
                     if ($this->_queueId == '') {
                         $this->_queueId = $userTaskRecord->id;
                     } else {
                         $this->_queueId .= ";" . $userTaskRecord->id;
                     }
                     // Simple test to determine if the task ID already exists for this user
                     $flag = 0;
                     for ($flagcntr = 0; $flagcntr <= $this->_userTaskCount; $flagcntr++) {
                         if (isset($this->_userTaskObject[$flagcntr]->queue_id) and $this->_userTaskObject[$flagcntr]->queue_id == $userTaskRecord->id) {
                             $flag = 1;
                         }
                     }
                     if ($flag == 0) {
                         $taskObject = new stdClass();
                         $templatename = db_query("SELECT template_name FROM {maestro_template} WHERE id = :tid", array(':tid' => $userTaskRecord->template_id))->fetchField();
                         // Determine if this task is for a regenerated workflow and we need to update the main project/request record
                         $taskObject->regen = FALSE;
                         if ($userTaskRecord->parent_process_id > 0) {
                             // Now check if this same template task id was executed in the previous process - if so then it is a recycled task
                             // Don't show the re-generated attribute if in this instance of the process we proceed further and are executing new tasks
                             $regenquery = db_select('maestro_queue', 'a');
                             $regenquery->addExpression('COUNT(id)', 'rec_count');
                             $regenquery->condition('a.process_id', $userTaskRecord->parent_process_id, '=');
                             $regenquery->condition(db_and()->condition('a.template_data_id', $userTaskRecord->template_data_id, '='));
                             if ($regenquery->execute()->fetchField() > 0) {
                                 $taskObject->regen = TRUE;
                             }
                         }
                         $queueRecDates = array('created' => $userTaskRecord->created_date, 'started' => $userTaskRecord->started_date);
                         $queueRecFlags = array('is_interactive' => $userTaskRecord->is_interactive);
                         $taskObject->task_data = $userTaskRecord->task_data;
                         $taskObject->queue_id = $userTaskRecord->id;
                         $taskObject->task_id = $userTaskRecord->template_data_id;
                         $taskObject->process_id = $userTaskRecord->process_id;
                         $taskObject->parent_process_id = $userTaskRecord->parent_process_id;
                         $taskObject->template_id = $userTaskRecord->template_id;
                         $taskObject->template_name = $templatename;
                         $taskObject->flow_name = $userTaskRecord->flow_name;
                         $taskObject->tracking_id = $userTaskRecord->tracking_id;
                         $taskObject->url = $userTaskRecord->handler;
                         $taskObject->dates = $queueRecDates;
                         $taskObject->flags = $queueRecFlags;
                         if ($this->_mode == 'admin') {
                             $taskObject->assign_type = $userTaskRecord->assign_type;
                             $taskObject->uid = $userTaskRecord->assign_id;
                             $taskObject->username = $userTaskRecord->name != '' ? $userTaskRecord->name : '[' . t('nobody assigned') . ']';
                         }
                         // Handle dynamic task name based on a variable's value
                         $taskname = '';
                         if ($userTaskRecord->is_dynamic_taskname == 1) {
                             $q2 = db_select('maestro_process_variables', 'a');
                             $q2->addField('a', 'variable_value');
                             $q2->condition('a.process_id', $userTaskRecord->process_id, '=');
                             $q2->condition('a.template_variable_id', $userTaskRecord->dynamic_taskname_variable_id, '=');
                             $res1 = $query->execute()->fetchObject();
                             if ($res1) {
                                 $userTaskRecord->taskname = $res1->variable_value;
                             }
                         }
                         /* @TODO: Need to look at using a module HOOK that can be used in a similar way to define an custom taskname */
                         /*
                         if (function_exists('PLG_Nexflow_taskname')) {
                         $parms = array('pid' => $A['nf_processID'], 'tid' => $A['nf_templateDataID'], 'qid' => $A['id'], 'user' => $this->_nfUserId);
                         if (!empty($taskame)) {
                         $apiRetval = PLG_Nexflow_taskname($parms,$taskname);
                         } else {
                         $apiRetval = PLG_Nexflow_taskname($parms,$A['taskname']);
                         }
                         $taskname = $apiRetval['taskname'];
                         }
                         */
                         $taskObject->taskname = $userTaskRecord->taskname;
                         $taskObject->tasktype = $userTaskRecord->task_class_name;
                         $this->_userTaskObject[$this->_userTaskCount] = $taskObject;
                         $this->_userTaskCount += 1;
                         // Increment the total user task counter
                     }
                 }
             }
         }
     }
     if ($this->_debug) {
         watchdog('maestro', "Exiting getQueue - user mode");
     }
     // Now sort the array of task objects so that the newest task (highest queue_id_) is first
     $sorted = array();
     if (is_array($this->_userTaskObject) and count($this->_userTaskObject) > 0) {
         foreach ($this->_userTaskObject as $task) {
             $sorted[$task->queue_id] = $task;
         }
         krsort($sorted);
     }
     return $sorted;
 }
 /**
  * This function takes an array from a DatabaseCondition::conditions() call
  * and use that info to create a new DatabaseCondition. it then replace the
  * original array with a single item that is the new DatabaseCondition.
  *
  * This is used to move conditions out of the base where and having parts of
  * a query, so that the class of the DatabaseCondition can  be changed
  *
  * @param $condition_info array
  *   an array from a DatabaseCondition::conditions()
  *
  * @return void NULL
  */
 protected function encapCondition(&$condition_info)
 {
     if (isset($condition_info[0])) {
         $where_info = $condition_info;
         $replacement = db_and();
         $relacement_info =& $replacement->conditions();
         $relacement_info = $where_info;
         $condition_info = array('#conjunction' => 'AND', 0 => array('field' => $replacement, 'operator' => '=', 'value' => array()));
     }
 }
Exemplo n.º 17
0
 private function __filterAkteure($filter)
 {
     $filteredAkteurIds = array();
     $numFilter = 0;
     $filteredTags = array();
     $filteredBezirke = array();
     if (isset($filter['uid'])) {
         // TODO: Make filterable for multiple users & test
         $numFilters++;
         global $user;
         $akteure = db_select($this->tbl_hat_user, 'hu')->fields('hu');
         if (!array_intersect(array('administrator'), $user->roles)) {
             $akteure->condition('hat_UID', $filter['uid']);
         }
         foreach ($akteure->execute()->fetchAll() as $akteur) {
             $filteredAkteurIds[] = $akteur->hat_AID;
         }
     }
     // end UserID-Filter
     if (isset($filter['mustHaveGps'])) {
         $numFilters++;
         $resultAkteure = db_query("SELECT AID, ADID\n     FROM {aae_data_adresse} ad\n     JOIN {aae_data_akteur} a\n     WHERE ad.gps_long != '' AND ad.gps_lat != '' AND ad.ADID = a.adresse");
         foreach ($resultAkteure->fetchAll() as $akteur) {
             $filteredAkteurIds[] = $akteur->AID;
         }
     }
     // end empty-GPS-jumper
     if (isset($filter['tags'])) {
         $sparten = db_select($this->tbl_hat_sparte, 'hs')->fields('hs', array('hat_AID'));
         $and = db_and();
         foreach ($filter['tags'] as $tag) {
             $numFilters++;
             $tag = $this->clearContent($tag);
             $filteredTags[$tag] = $tag;
             $and->condition('hat_KID', $tag);
         }
         $filterSparten = $sparten->condition($and)->execute()->fetchAll();
         foreach ($filterSparten as $sparte) {
             $filteredAkteurIds[] = $sparte->hat_AID;
         }
     }
     // end Tags-Filter
     if (isset($filter['bezirke'])) {
         foreach ($filter['bezirke'] as $bezirk) {
             $numFilters++;
             $bezirkId = $this->clearContent($bezirk);
             $filteredBezirke[$bezirkId] = $bezirkId;
             $adressen = db_select($this->tbl_adresse, 'a')->fields('a', array('ADID'))->condition('bezirk', $bezirkId)->execute()->fetchAll();
             foreach ($adressen as $adresse) {
                 $filterBezirke = db_select($this->tbl_akteur, 'a')->fields('a', array('AID'))->condition('adresse', $adresse->ADID)->execute()->fetchAll();
                 foreach ($filterBezirke as $bezirk) {
                     $filteredAkteurIds[] = $bezirk->AID;
                 }
             }
         }
     }
     // end Bezirke-Filter
     if (isset($filter['keyword'])) {
         $numFilters++;
         $or = db_or()->condition('name', '%' . $filter['keyword'] . '%', 'LIKE')->condition('beschreibung', '%' . $filter['keyword'] . '%', 'LIKE');
         $filterKeyword = db_select($this->tbl_akteur, 'e')->fields('e', array('AID'))->condition($or)->execute()->fetchAll();
         foreach ($filterKeyword as $keyword) {
             $filteredAkteurIds[] = $keyword->AID;
         }
     }
     // end Keyword-Filter
     return $this->getDuplicates($filteredAkteurIds, $numFilters);
 }
Exemplo n.º 18
0
<?php

$post = new stdClass();
$post->postBody = '';
$post->postTitle = '';
$post->slug = '';
if ($id) {
    $post = db_select('post', 'p')->where()->condition('postId', $id)->getSingleResult();
    if ($post) {
        $post = _getTranslationStrings($post, array('postTitle', 'postBody'), $lang);
    } else {
        _redirect('admin/property/list');
    }
}
$condition = array('deleted' => null);
if ($id) {
    $condition[] = db_and(array('catId' => $post->catId, 'deleted !=' => null));
}
$categories = db_select('category')->orWhere($condition)->orderBy('catName')->getResult();
 /**
  * {@inheritdoc}
  */
 public function entityQueryAlter(SelectInterface $query)
 {
     if (\Drupal::currentUser()->hasPermission('administer users')) {
         // In addition, if the user is administrator, we need to make sure to
         // match the anonymous user, that doesn't actually have a name in the
         // database.
         $conditions =& $query->conditions();
         foreach ($conditions as $key => $condition) {
             if ($key !== '#conjunction' && is_string($condition['field']) && $condition['field'] === 'users_field_data.name') {
                 // Remove the condition.
                 unset($conditions[$key]);
                 // Re-add the condition and a condition on uid = 0 so that we end up
                 // with a query in the form:
                 // WHERE (name LIKE :name) OR (:anonymous_name LIKE :name AND uid = 0)
                 $or = db_or();
                 $or->condition($condition['field'], $condition['value'], $condition['operator']);
                 // Sadly, the Database layer doesn't allow us to build a condition
                 // in the form ':placeholder = :placeholder2', because the 'field'
                 // part of a condition is always escaped.
                 // As a (cheap) workaround, we separately build a condition with no
                 // field, and concatenate the field and the condition separately.
                 $value_part = db_and();
                 $value_part->condition('anonymous_name', $condition['value'], $condition['operator']);
                 $value_part->compile(Database::getConnection(), $query);
                 $or->condition(db_and()->where(str_replace('anonymous_name', ':anonymous_name', (string) $value_part), $value_part->arguments() + array(':anonymous_name' => user_format_name(user_load(0))))->condition('base_table.uid', 0));
                 $query->condition($or);
             }
         }
     }
     // Add the filter by role option.
     if (!empty($this->fieldDefinition->getSetting('handler_settings')['filter'])) {
         $filter_settings = $this->fieldDefinition->getSetting('handler_settings')['filter'];
         if ($filter_settings['type'] == 'role') {
             $tables = $query->getTables();
             $base_table = $tables['base_table']['alias'];
             $query->join('users_roles', 'ur', $base_table . '.uid = ur.uid');
             $query->condition('ur.rid', $filter_settings['role']);
         }
     }
 }
Exemplo n.º 20
0
  /**
   * Construct the "WHERE" or "HAVING" part of the query.
   *
   * As views has to wrap the conditions from arguments with AND, a special
   * group is wrapped around all conditions. This special group has the ID 0.
   * There is other code in filters which makes sure that the group IDs are
   * higher than zero.
   *
   * @param $where
   *   'where' or 'having'.
   */
  protected function buildCondition($where = 'where') {
    $has_condition = FALSE;
    $has_arguments = FALSE;
    $has_filter = FALSE;

    $main_group = db_and();
    $filter_group = $this->groupOperator == 'OR' ? db_or() : db_and();

    foreach ($this->$where as $group => $info) {

      if (!empty($info['conditions'])) {
        $sub_group = $info['type'] == 'OR' ? db_or() : db_and();
        foreach ($info['conditions'] as $clause) {
          if ($clause['operator'] == 'formula') {
            $has_condition = TRUE;
            $sub_group->where($clause['field'], $clause['value']);
          }
          else {
            $has_condition = TRUE;
            $sub_group->condition($clause['field'], $clause['value'], $clause['operator']);
          }
        }

        // Add the item to the filter group.
        if ($group != 0) {
          $has_filter = TRUE;
          $filter_group->condition($sub_group);
        }
        else {
          $has_arguments = TRUE;
          $main_group->condition($sub_group);
        }
      }
    }

    if ($has_filter) {
      $main_group->condition($filter_group);
    }

    if (!$has_arguments && $has_condition) {
      return $filter_group;
    }
    if ($has_arguments && $has_condition) {
      return $main_group;
    }
  }
Exemplo n.º 21
0
/**
 * Perform alterations to a structured query for a given tag.
 *
 * @param $query
 *   An Query object describing the composite parts of a SQL query.
 *
 * @see hook_query_alter()
 * @see node_query_node_access_alter()
 * @see QueryAlterableInterface
 * @see SelectQueryInterface
 */
function hook_query_TAG_alter(QueryAlterableInterface $query)
{
    // Skip the extra expensive alterations if site has no node access control modules.
    if (!node_access_view_all_nodes()) {
        // Prevent duplicates records.
        $query->distinct();
        // The recognized operations are 'view', 'update', 'delete'.
        if (!($op = $query->getMetaData('op'))) {
            $op = 'view';
        }
        // Skip the extra joins and conditions for node admins.
        if (!user_access('bypass node access')) {
            // The node_access table has the access grants for any given node.
            $access_alias = $query->join('node_access', 'na', '%alias.nid = n.nid');
            $or = db_or();
            // If any grant exists for the specified user, then user has access to the node for the specified operation.
            foreach (node_access_grants($op, $query->getMetaData('account')) as $realm => $gids) {
                foreach ($gids as $gid) {
                    $or->condition(db_and()->condition($access_alias . '.gid', $gid)->condition($access_alias . '.realm', $realm));
                }
            }
            if (count($or->conditions())) {
                $query->condition($or);
            }
            $query->condition($access_alias . 'grant_' . $op, 1, '>=');
        }
    }
}
 function drawLineFalse()
 {
     if (!drupal_valid_token($this->_security_token, 'maestro_admin')) {
         return array('message' => t('Illegal line connection attempt.'), 'success' => 0, 'task_id' => $this->_task_id);
     }
     $res = db_select('maestro_template_data_next_step', 'a');
     $res->fields('a', array('id'));
     $cond1 = db_or()->condition('a.template_data_to', intval($_POST['line_to']), '=')->condition('a.template_data_to_false', intval($_POST['line_to']), '=');
     $cond1fin = db_and()->condition('a.template_data_from', $this->_task_id, '=')->condition($cond1);
     $cond2 = db_or()->condition('a.template_data_to', $this->_task_id, '=')->condition('a.template_data_to_false', $this->_task_id, '=');
     $cond2fin = db_and()->condition('a.template_data_from', intval($_POST['line_to']), '=')->condition($cond2);
     $cond = db_or()->condition($cond1fin)->condition($cond2fin);
     $res->condition($cond);
     $rec = current($res->execute()->fetchAll());
     if ($rec == '') {
         $rec = new stdClass();
         $rec->template_data_from = $this->_task_id;
         $rec->template_data_to = 0;
         $rec->template_data_to_false = intval($_POST['line_to']);
         drupal_write_record('maestro_template_data_next_step', $rec);
         return array('success' => '1');
     } else {
         return array('success' => '0');
     }
 }
Exemplo n.º 23
0
 /**
  * Sets the search query expression.
  *
  * @param $expression
  *   A search string, which can contain keywords and options.
  * @param $type
  *   The search type. This maps to {search_index}.type in the database.
  *
  * @return $this
  */
 public function searchExpression($expression, $type)
 {
     $this->searchExpression = $expression;
     $this->type = $type;
     // Add query tag.
     $this->addTag('search_' . $type);
     // Initialize conditions and status.
     $this->conditions = db_and();
     $this->status = 0;
     return $this;
 }
Exemplo n.º 24
0
/**
 * Hooks the condition function in the QueryConditionInterface to check for
 * empty sets in an IN or NOT IN statement.
 * 
 * @param string $field The field the condition refers to.
 * @param mixed $value The value to compare against.
 * @param string $operation The operation to apply to the value.
 */
function condition_hook(&$field, &$value, &$operation)
{
    //We only care about IN or NOT IN statements.
    if (($operation === null && is_array($value) || strtoupper($operation) === 'IN' || strtoupper($operation) === 'NOT IN') && empty($value)) {
        //Nothing is in the empty set.
        if (is_null($operation) || strtoupper($operation) === 'IN') {
            $value = null;
            $field = db_and()->where('FALSE');
        } else {
            if (strtoupper($operation) === 'NOT IN') {
                $value = null;
                $field = db_and()->where('TRUE');
            }
        }
    }
}
Exemplo n.º 25
0
 /**
  * Construct the "WHERE" or "HAVING" part of the query.
  *
  * As views has to wrap the conditions from arguments with AND, a special
  * group is wrapped around all conditions. This special group has the ID 0.
  * There is other code in filters which makes sure that the group IDs are
  * higher than zero.
  *
  * @param $where
  *   'where' or 'having'.
  */
 protected function buildCondition($where = 'where')
 {
     $has_condition = FALSE;
     $has_arguments = FALSE;
     $has_filter = FALSE;
     $main_group = db_and();
     $filter_group = $this->groupOperator == 'OR' ? db_or() : db_and();
     foreach ($this->{$where} as $group => $info) {
         if (!empty($info['conditions'])) {
             $sub_group = $info['type'] == 'OR' ? db_or() : db_and();
             foreach ($info['conditions'] as $clause) {
                 // DBTNG doesn't support to add the same subquery twice to the main
                 // query and the count query, so clone the subquery to have two instances
                 // of the same object. - http://drupal.org/node/1112854
                 if (is_object($clause['value']) && $clause['value'] instanceof SelectQuery) {
                     $clause['value'] = clone $clause['value'];
                 }
                 if ($clause['operator'] == 'formula') {
                     $has_condition = TRUE;
                     $sub_group->where($clause['field'], $clause['value']);
                 } else {
                     $has_condition = TRUE;
                     $sub_group->condition($clause['field'], $clause['value'], $clause['operator']);
                 }
             }
             // Add the item to the filter group.
             if ($group != 0) {
                 $has_filter = TRUE;
                 $filter_group->condition($sub_group);
             } else {
                 $has_arguments = TRUE;
                 $main_group->condition($sub_group);
             }
         }
     }
     if ($has_filter) {
         $main_group->condition($filter_group);
     }
     if (!$has_arguments && $has_condition) {
         return $filter_group;
     }
     if ($has_arguments && $has_condition) {
         return $main_group;
     }
 }
Exemplo n.º 26
0
 /**
  * Add this filter to the query.
  *
  * Due to the nature of fapi, the value and the operator have an unintended
  * level of indirection. You will find them in $this->operator
  * and $this->value respectively.
  */
 public function query($group_by = FALSE)
 {
     $this->ensureMyTable();
     // Get the moodle - drupal uid mapping.
     $uid = $this->getDrupalMoodleUidMapping();
     // Build the subquery to add extra data so as to retrieve courses for a user.
     $subquery = db_select('context', 'ctxt');
     $subquery->addField('ctxt', 'instanceid');
     $subquery->innerJoin('role_assignments', 'ra', 'ra.contextid = ctxt.id');
     $subquery->innerJoin('role', 'r', 'r.id = ra.roleid');
     $subquery->innerJoin('user', 'u', 'u.id = ra.userid');
     $where = db_and()->condition('ctxt.contextlevel', $this->options['contextlevel'], '=');
     $where->condition("u.id", $uid, '=');
     $subquery->condition($where);
     $this->query->addWhere(0, "{$this->tableAlias}.{$this->realField}", $subquery, 'IN');
 }
Exemplo n.º 27
0
 /**
  * {@inheritdoc}
  */
 public function entityQueryAlter(SelectInterface $query)
 {
     // Bail out early if we do not need to match the Anonymous user.
     $handler_settings = $this->configuration['handler_settings'];
     if (isset($handler_settings['include_anonymous']) && !$handler_settings['include_anonymous']) {
         return;
     }
     if ($this->currentUser->hasPermission('administer users')) {
         // In addition, if the user is administrator, we need to make sure to
         // match the anonymous user, that doesn't actually have a name in the
         // database.
         $conditions =& $query->conditions();
         foreach ($conditions as $key => $condition) {
             if ($key !== '#conjunction' && is_string($condition['field']) && $condition['field'] === 'users_field_data.name') {
                 // Remove the condition.
                 unset($conditions[$key]);
                 // Re-add the condition and a condition on uid = 0 so that we end up
                 // with a query in the form:
                 // WHERE (name LIKE :name) OR (:anonymous_name LIKE :name AND uid = 0)
                 $or = db_or();
                 $or->condition($condition['field'], $condition['value'], $condition['operator']);
                 // Sadly, the Database layer doesn't allow us to build a condition
                 // in the form ':placeholder = :placeholder2', because the 'field'
                 // part of a condition is always escaped.
                 // As a (cheap) workaround, we separately build a condition with no
                 // field, and concatenate the field and the condition separately.
                 $value_part = db_and();
                 $value_part->condition('anonymous_name', $condition['value'], $condition['operator']);
                 $value_part->compile($this->connection, $query);
                 $or->condition(db_and()->where(str_replace('anonymous_name', ':anonymous_name', (string) $value_part), $value_part->arguments() + array(':anonymous_name' => user_format_name($this->userStorage->load(0))))->condition('base_table.uid', 0));
                 $query->condition($or);
             }
         }
     }
 }
Exemplo n.º 28
0
 /**
  * Test that join conditions can use Condition objects.
  */
 public function testJoinConditionObject()
 {
     // Same test as testDefaultJoin, but with a Condition object.
     $query = db_select('test_task', 't');
     $join_cond = db_and()->where('t.pid = p.id');
     $people_alias = $query->join('test', 'p', $join_cond);
     $name_field = $query->addField($people_alias, 'name', 'name');
     $query->addField('t', 'task', 'task');
     $priority_field = $query->addField('t', 'priority', 'priority');
     $query->orderBy($priority_field);
     $result = $query->execute();
     $num_records = 0;
     $last_priority = 0;
     foreach ($result as $record) {
         $num_records++;
         $this->assertTrue($record->{$priority_field} >= $last_priority, 'Results returned in correct order.');
         $this->assertNotEqual($record->{$name_field}, 'Ringo', 'Taskless person not selected.');
         $last_priority = $record->{$priority_field};
     }
     $this->assertEqual($num_records, 7, 'Returned the correct number of rows.');
     // Test a condition object that creates placeholders.
     $t1_name = 'John';
     $t2_name = 'George';
     $join_cond = db_and()->condition('t1.name', $t1_name)->condition('t2.name', $t2_name);
     $query = db_select('test', 't1');
     $query->innerJoin('test', 't2', $join_cond);
     $query->addField('t1', 'name', 't1_name');
     $query->addField('t2', 'name', 't2_name');
     $num_records = $query->countQuery()->execute()->fetchField();
     $this->assertEqual($num_records, 1, 'Query expected to return 1 row. Actual: ' . $num_records);
     if ($num_records == 1) {
         $record = $query->execute()->fetchObject();
         $this->assertEqual($record->t1_name, $t1_name, 'Query expected to retrieve name ' . $t1_name . ' from table t1. Actual: ' . $record->t1_name);
         $this->assertEqual($record->t2_name, $t2_name, 'Query expected to retrieve name ' . $t2_name . ' from table t2. Actual: ' . $record->t2_name);
     }
 }
 public function entityFieldQueryAlter(SelectQueryInterface $query)
 {
     if (user_access('administer users')) {
         // In addition, if the user is administrator, we need to make sure to
         // match the anonymous user, that doesn't actually have a name in the
         // database.
         $conditions =& $query->conditions();
         foreach ($conditions as $key => $condition) {
             if ($key !== '#conjunction' && is_string($condition['field']) && $condition['field'] === 'users.name') {
                 // Remove the condition.
                 unset($conditions[$key]);
                 // Re-add the condition and a condition on uid = 0 so that we end up
                 // with a query in the form:
                 //    WHERE (name LIKE :name) OR (:anonymous_name LIKE :name AND uid = 0)
                 $or = db_or();
                 $or->condition($condition['field'], $condition['value'], $condition['operator']);
                 // Sadly, the Database layer doesn't allow us to build a condition
                 // in the form ':placeholder = :placeholder2', because the 'field'
                 // part of a condition is always escaped.
                 // As a (cheap) workaround, we separately build a condition with no
                 // field, and concatenate the field and the condition separately.
                 $value_part = db_and();
                 $value_part->condition('anonymous_name', $condition['value'], $condition['operator']);
                 $value_part->compile(Database::getConnection(), $query);
                 $or->condition(db_and()->where(str_replace('anonymous_name', ':anonymous_name', (string) $value_part), $value_part->arguments() + array(':anonymous_name' => format_username(user_load(0))))->condition('users.uid', 0));
                 $query->condition($or);
             }
         }
     }
 }
Exemplo n.º 30
0
 /**
  * {@inheritdoc}
  */
 public function opWithin($field_from, $field_to)
 {
     $operators = array('<', '>', '<=', '>=');
     $inlude_endpoints = !($this->options['include_endpoints'] xor $this->operator == 'within');
     list($op_left, $op_right) = array_slice($operators, $inlude_endpoints ? 2 : 0, 2);
     if ($this->operator == 'within') {
         $this->query->setWhereGroup($this->options['group'], db_and()->condition($field_from, $this->value, $op_left)->condition($field_to, $this->value, $op_right));
     } else {
         $this->query->setWhereGroup($this->options['group'], db_or()->condition($field_from, $this->value, $op_right)->condition($field_to, $this->value, $op_left));
     }
 }