/** * Implements LinkitSearchPluginInterface::fetchResults(). */ public function fetchResults($search_string) { // If the $search_string is not a string, something is wrong and an empty // array is returned. $matches = array(); // Get the EntityFieldQuery instance. $this->getQueryInstance(); $or = db_or(); $or->condition('n.title', '%' . db_like($search_string) . '%', 'LIKE'); $or->condition('bcd.name', '%' . db_like($search_string) . '%', 'LIKE'); $or->condition('b.biblio_secondary_title', '%' . db_like($search_string) . '%', 'LIKE'); $or->condition('bkd.word', '%' . db_like($search_string) . '%', 'LIKE'); $this->query->condition($or); $this->query->orderBy('b.biblio_year', 'DESC'); //ORDER BY created // Add the search condition to the query object. /*$this->query->propertyCondition($this->entity_field_label, '%' . db_like($search_string) . '%', 'LIKE') ->addTag('linkit_entity_autocomplete') ->addTag('linkit_' . $this->plugin['entity_type'] . '_autocomplete');*/ /* $matches[] = array( 'title' => $this->entity_field_label, 'description' => '', 'path' => '', 'group' => '', 'addClass' => '', ); return $matches; */ /* // Add access tag for the query. // There is also a runtime access check that uses entity_access(). $this->query->addTag($this->plugin['entity_type'] . '_access'); // Bundle check. if (isset($this->entity_key_bundle) && isset($this->conf['bundles']) ) { $bundles = array_filter($this->conf['bundles']); if ($bundles) { $this->query->propertyCondition($this->entity_key_bundle, $bundles, 'IN'); } }*/ // Execute the query. $result = $this->query->execute()->fetchAllAssoc('nid'); /*if (!isset($result[$this->plugin['entity_type']])) { return array(); }*/ $ids = array_keys($result); // Load all the entities with all the ids we got. $entities = entity_load('node', $ids); foreach ($entities as $key => $entity) { // Check the access againt the definded entity access callback. if (entity_access('view', 'node', $entity) === FALSE) { continue; } $matches[] = array('title' => biblio_remove_brace($this->createLabel($entity)), 'description' => $this->createDescription($entity) . ' <span class="name">' . $result[$key]->name . '</span> <span class="year">' . $result[$key]->biblio_year . '</span>', 'path' => $this->createPath($entity), 'group' => $this->createGroup($entity), 'addClass' => $this->createRowClass($entity)); } return $matches; }
/** * Overrides OgSelectionHandler::entityFieldQueryAlter(). * * Add the user's groups along with the rest of the "public" groups. */ public function entityFieldQueryAlter(SelectQueryInterface $query) { $gids = og_get_entity_groups(); if (empty($gids['node'])) { return; } $conditions =& $query->conditions(); // Find the condition for the "field_data_field_privacy_settings" query, and // the one for the "node.nid", so we can later db_or() them. $public_condition = array(); foreach ($conditions as $key => $condition) { if ($key !== '#conjunction' && is_string($condition['field'])) { if (strpos($condition['field'], 'field_data_field_og_subscribe_settings') === 0) { $public_condition = $condition; unset($conditions[$key]); } if ($condition['field'] === 'node.nid') { unset($conditions[$key]); } } } if (!$public_condition) { return; } $or = db_or(); $or->condition($public_condition['field'], $public_condition['value'], $public_condition['operator']); $or->condition('node.nid', $gids['node'], 'IN'); $query->condition($or); }
/** * Get content changed after the deployment date. * * @return object[] * Object containing an array of NID and node type. */ public function getLatestContent() { // EECA subsite case where changed column is having entries equal to 0. $or = db_or()->condition('n.created', self::DEPLOYMENT_DATE, '>=')->condition('n.changed', self::DEPLOYMENT_DATE, '>='); $query = db_select('node', 'n')->fields('n', ['nid', 'type'])->condition($or); return $query->execute()->fetchAll(); }
/** * Alter the term DB query. * * @param SelectQuery $query * The query object ot alter. */ function hook_query_rules_autotag_terms_alter($query) { // Join the original term query from rules_autotag with our field table to // exclude terms that should not be tagged. $query->leftJoin('field_data_field_dont_autotag', 'fd', "t.tid = fd.entity_id AND fd.entity_type = 'taxonomy_term'"); $query->condition(db_or()->condition('fd.field_dont_autotag_value', NULL)->condition('fd.field_dont_autotag_value', '1', '<>')); }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $form['customer_type'] = array('#type' => 'radios', '#options' => array('search' => t('Search for an existing customer.'), 'create' => t('Create a new customer account.'), 'none' => t('No customer account required.')), '#required' => TRUE, '#default_value' => 'search', '#ajax' => array('callback' => array($this, 'customerSelect'), 'wrapper' => 'uc-order-customer', 'progress' => array('type' => 'throbber'))); $form['customer'] = array('#prefix' => '<div id="uc-order-customer">', '#suffix' => '</div>', '#tree' => TRUE); // Create form elements needed for customer search. // Shown only when the 'Search for an existing customer.' radio is selected. if (!$form_state->hasValue('customer_type') || $form_state->getValue('customer_type') == 'search') { // Container for customer search fields. $form['customer'] += array('#type' => 'fieldset', '#title' => t('Customer search'), '#description' => t('Enter full or partial information in one or more of the following fields, then press the "Search" button. Search results will match all the provided information.')); // Customer first name. $form['customer']['first_name'] = array('#type' => 'textfield', '#title' => t('First name'), '#size' => 24, '#maxlength' => 32); // Customer last name. $form['customer']['last_name'] = array('#type' => 'textfield', '#title' => t('Last name'), '#size' => 24, '#maxlength' => 32); // Customer e-mail address. $form['customer']['email'] = array('#type' => 'textfield', '#title' => t('E-mail'), '#size' => 24, '#maxlength' => 96); // Customer username. $form['customer']['username'] = array('#type' => 'textfield', '#title' => t('Username'), '#size' => 24, '#maxlength' => 96); $form['customer']['search'] = array('#type' => 'button', '#value' => t('Search'), '#limit_validation_errors' => array(), '#submit' => array(), '#ajax' => array('callback' => array($this, 'customerSearch'), 'wrapper' => 'uc-order-customer-results', 'progress' => array('type' => 'throbber'))); $form['customer']['uid'] = array('#prefix' => '<div id="uc-order-customer-results">', '#suffix' => '</div>'); // Search for existing customer by e-mail address. if ($form_state->getValue('customer')) { $query = db_select('users_field_data', 'u')->distinct(); $query->leftJoin('uc_orders', 'o', 'u.uid = o.uid'); $query->fields('u', array('uid', 'name', 'mail'))->fields('o', array('billing_first_name', 'billing_last_name'))->condition('u.uid', 0, '>')->condition(db_or()->isNull('o.billing_first_name')->condition('o.billing_first_name', db_like(trim($form_state->getValue(['customer', 'first_name']))) . '%', 'LIKE'))->condition(db_or()->isNull('o.billing_last_name')->condition('o.billing_last_name', db_like(trim($form_state->getValue(['customer', 'last_name']))) . '%', 'LIKE'))->condition(db_or()->condition('o.primary_email', db_like(trim($form_state->getValue(['customer', 'email']))) . '%', 'LIKE')->condition('u.mail', db_like(trim($form_state->getValue(['customer', 'email']))) . '%', 'LIKE'))->condition('u.name', db_like(trim($form_state->getValue(['customer', 'username']))) . '%', 'LIKE')->orderBy('o.created', 'DESC')->range(0, $limit = 11); $result = $query->execute(); $options = array(); foreach ($result as $user) { $name = ''; if (!empty($user->billing_first_name) && !empty($user->billing_last_name)) { $name = $user->billing_first_name . ' ' . $user->billing_last_name . ' '; } // Options formatted as "First Last <*****@*****.**> (username)". $options[$user->uid] = $name . '<' . $user->mail . '>' . ' (' . $user->name . ')'; } $max = FALSE; if (count($options) == $limit) { array_pop($options); $max = TRUE; } if (!empty($options)) { // Display search results. $form['customer']['uid'] += array('#type' => 'radios', '#title' => t('Select customer'), '#description' => $max ? t('More than @limit results found. Refine your search to find other customers.', ['@limit' => $limit - 1]) : '', '#options' => $options, '#default_value' => key($options)); } else { // No search results found. $form['customer']['uid'] += array('#markup' => '<p>' . t('Search returned no results.') . '</p>'); } } } elseif ($form_state->getValue('customer_type') == 'create') { // Container for new customer information. $form['customer'] += array('#type' => 'fieldset', '#title' => t('New customer details')); // Customer e-mail address. $form['customer']['email'] = array('#type' => 'email', '#title' => t('Customer e-mail address'), '#size' => 24, '#maxlength' => 96); // Option to notify customer. $form['customer']['sendmail'] = array('#type' => 'checkbox', '#title' => t('E-mail account details to customer.')); } $form['actions'] = array('#type' => 'actions'); $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('Create order')); return $form; }
public function query() { $this->ensureMyTable(); $subselect = db_select('comment_field_data', 'c'); $subselect->addField('c', 'cid'); $subselect->condition('c.uid', $this->value, $this->operator); $entity_id = $this->definition['entity_id']; $entity_type = $this->definition['entity_type']; $subselect->where("c.entity_id = {$this->tableAlias}.{$entity_id}"); $subselect->condition('c.entity_type', $entity_type); $condition = db_or()->condition("{$this->tableAlias}.uid", $this->value, $this->operator)->exists($subselect); $this->query->addWhere($this->options['group'], $condition); }
public static function addProjectCondition(&$query, $project_alias = 'p.') { // we want to deliver all the non-draft projects except for the owner (or colleagues) of these projects $myorgs = Organisations::getMyOrganisations(); if (gettype($query) == 'string') { $query .= " AND ({$project_alias}state <> 'draft'" . ($myorgs ? " OR {$project_alias}org_id IN (" . implode($myorgs, ',') . "))" : ")"); } else { if ($myorgs) { $query->condition(db_or()->condition("{$project_alias}state", 'draft', '<>')->condition("{$project_alias}org_id", $myorgs, 'IN')); } else { $query->condition('state', 'draft', '<>'); } } }
public function query() { // If no filter values are present, then do nothing. if (count($this->value) == 0) { return; } elseif (count($this->value) == 1) { // Sometimes $this->value is an array with a single element so convert it. if (is_array($this->value)) { $this->value = current($this->value); } $operator = '='; } else { $operator = 'IN'; # " IN (" . implode(', ', array_fill(0, sizeof($this->value), '%d')) . ")"; } // The normal use of ensureMyTable() here breaks Views. // So instead we trick the filter into using the alias of the base table. // See http://drupal.org/node/271833 // If a relationship is set, we must use the alias it provides. if (!empty($this->relationship)) { $this->tableAlias = $this->relationship; } elseif (isset($this->query->table_queue[$this->view->storage->get('base_table')]['alias'])) { $this->tableAlias = $this->query->table_queue[$this->view->storage->get('base_table')]['alias']; } else { return; } // Now build the subqueries. $subquery = db_select('taxonomy_index', 'tn'); $subquery->addField('tn', 'nid'); $where = db_or()->condition('tn.tid', $this->value, $operator); $last = "tn"; if ($this->options['depth'] > 0) { $subquery->leftJoin('taxonomy_term_hierarchy', 'th', "th.tid = tn.tid"); $last = "th"; foreach (range(1, abs($this->options['depth'])) as $count) { $subquery->leftJoin('taxonomy_term_hierarchy', "th{$count}", "{$last}.parent = th{$count}.tid"); $where->condition("th{$count}.tid", $this->value, $operator); $last = "th{$count}"; } } elseif ($this->options['depth'] < 0) { foreach (range(1, abs($this->options['depth'])) as $count) { $subquery->leftJoin('taxonomy_term_hierarchy', "th{$count}", "{$last}.tid = th{$count}.parent"); $where->condition("th{$count}.tid", $this->value, $operator); $last = "th{$count}"; } } $subquery->condition($where); $this->query->addWhere($this->options['group'], "{$this->tableAlias}.{$this->realField}", $subquery, 'IN'); }
public function query() { $this->ensureMyTable(); $field = $this->tableAlias . '.' . $this->realField . ' '; $or = db_or(); if (empty($this->value)) { $or->condition($field, '***CURRENT_USER***', '<>'); if ($this->accept_null) { $or->isNull($field); } } else { $or->condition($field, '***CURRENT_USER***', '='); } $this->query->addWhere($this->options['group'], $or); }
/** * 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, '>='); } }
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 convert(TargetInterface $target) { $indexer = $target->getIndexer('function'); // @FIXME This is not working (returns empty result set)...don't know why. $alter_hooks = $indexer->getQuery()->condition(db_or()->condition('id', $target->id() . '_form_alter')->condition('id', db_like($target->id() . '_form_%_alter'), 'LIKE'))->execute(); foreach ($alter_hooks as $alter_hook) { /** @var \Pharborist\Functions\FunctionDeclarationNode $function */ $function = $indexer->get($alter_hook->id); $parameters = $function->getParameters(); if (sizeof($parameters) > 1) { $parameters[1]->setTypeHint('\\Drupal\\Core\\Form\\FormStateInterface'); $target->save($function); } } }
public function query($group_by = FALSE) { $this->ensureMyTable(); // Use the table definition to correctly add this user ID condition. if ($this->table != 'comment_field_data') { $subselect = $this->database->select('comment_field_data', 'c'); $subselect->addField('c', 'cid'); $subselect->condition('c.uid', $this->argument); $entity_id = $this->definition['entity_id']; $entity_type = $this->definition['entity_type']; $subselect->where("c.entity_id = {$this->tableAlias}.{$entity_id}"); $subselect->condition('c.entity_type', $entity_type); $condition = db_or()->condition("{$this->tableAlias}.uid", $this->argument, '=')->exists($subselect); $this->query->addWhere(0, $condition); } }
public function query($group_by = FALSE) { $this->ensureMyTable(); if (!empty($this->options['break_phrase'])) { $tids = new \stdClass(); $tids->value = $this->argument; $tids = $this->breakPhrase($this->argument, $tids); if ($tids->value == array(-1)) { return FALSE; } if (count($tids->value) > 1) { $operator = 'IN'; } else { $operator = '='; } $tids = $tids->value; } else { $operator = "="; $tids = $this->argument; } // Now build the subqueries. $subquery = db_select('taxonomy_index', 'tn'); $subquery->addField('tn', 'nid'); $where = db_or()->condition('tn.tid', $tids, $operator); $last = "tn"; if ($this->options['depth'] > 0) { $subquery->leftJoin('taxonomy_term_hierarchy', 'th', "th.tid = tn.tid"); $last = "th"; foreach (range(1, abs($this->options['depth'])) as $count) { $subquery->leftJoin('taxonomy_term_hierarchy', "th{$count}", "{$last}.parent = th{$count}.tid"); $where->condition("th{$count}.tid", $tids, $operator); $last = "th{$count}"; } } elseif ($this->options['depth'] < 0) { foreach (range(1, abs($this->options['depth'])) as $count) { $subquery->leftJoin('taxonomy_term_hierarchy', "th{$count}", "{$last}.tid = th{$count}.parent"); $where->condition("th{$count}.tid", $tids, $operator); $last = "th{$count}"; } } $subquery->condition($where); $this->query->addWhere(0, "{$this->tableAlias}.{$this->realField}", $subquery, 'IN'); }
/** * {@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']); } } }
/** * {@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; }
/** * {@inheritdoc} */ public function getSupportedLanguagePairs(TranslatorInterface $translator) { if (!empty($this->language_pairs)) { return $this->language_pairs; } $roles = user_roles(TRUE, 'provide translation services'); $query = db_select('field_data_tmgmt_translation_skills', 'ts'); $query->join('users', 'u', 'u.uid = ts.entity_id AND u.status = 1'); $query->addField('ts', 'tmgmt_translation_skills_language_from', 'source_language'); $query->addField('ts', 'tmgmt_translation_skills_language_to', 'target_language'); $query->condition('ts.deleted', 0); $query->condition('ts.entity_type', 'user'); if (!in_array(DRUPAL_AUTHENTICATED_RID, array_keys($roles))) { $query->join('users_roles', 'ur', 'ur.uid = u.uid AND ur.rid'); $or_conditions = db_or()->condition('ur.rid', array_keys($roles), 'IN')->condition('u.uid', 1); $query->condition($or_conditions); } foreach ($query->execute()->fetchAll() as $item) { $this->language_pairs[] = array('source_language' => $item->source_language, 'target_language' => $item->target_language); } return $this->language_pairs; }
/** *Gets the url for the next image to display by retrieving a random entry from the manifest entries table *Used when operating within Drupal when question subsetting is in place *nodeid is the node id for the current question *threshold is the number of answers required before the manifest entry is considered no longer to be a candidate **/ function getNextDbImageId($nodeid, $threshold = 1) { try { $query = db_select("yesno_manifest_entries", "m")->fields("m", array("url", "objectid"))->condition(db_or()->condition("s.responsecount", $threshold, "<")->isNull("s.responsecount"))->condition("m.nodeid", $nodeid); $query->leftJoin("yesno_response_summaries", "s", "m.objectidhash = s.objectidhash and m.nodeid = s.nodeid"); //Count the available candidates $numcandidates = $query->countQuery()->execute()->fetchField(); if ($numcandidates > 0) { //Pick a random number within the range of available candidates $ix = mt_rand(1, $numcandidates) - 1; //Get the data for the selected row $result = $query->range($ix, 1)->execute()->fetchAssoc(); $r = json_encode(array(status => 1, "url" => $result["url"], "objectid" => $result["objectid"])); } else { //This indicates that the task is complete $r = json_encode(array(status => 2)); } } catch (PDOException $e) { $r = json_encode(array(status => 0, message => "Problem looking up next image! Reason: {$e->getMessage()}")); } echo $r; exit; }
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); } } } }
/** * {@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); } } } }
/** * Builds a SELECT query with multiple conditions and fields. * * The query uses both 'locales_source' and 'locales_target' tables. * Note that by default, as we are selecting both translated and untranslated * strings target field's conditions will be modified to match NULL rows too. * * @param array $conditions * An associative array with field => value conditions that may include * NULL values. If a language condition is included it will be used for * joining the 'locales_target' table. * @param array $options * An associative array of additional options. It may contain any of the * options used by Drupal\locale\StringStorageInterface::getStrings() and * these additional ones: * - 'translation', Whether to include translation fields too. Defaults to * FALSE. * * @return \Drupal\Core\Database\Query\Select * Query object with all the tables, fields and conditions. */ protected function dbStringSelect(array $conditions, array $options = array()) { // Start building the query with source table and check whether we need to // join the target table too. $query = $this->connection->select('locales_source', 's', $this->options)->fields('s'); // Figure out how to join and translate some options into conditions. if (isset($conditions['translated'])) { // This is a meta-condition we need to translate into simple ones. if ($conditions['translated']) { // Select only translated strings. $join = 'innerJoin'; } else { // Select only untranslated strings. $join = 'leftJoin'; $conditions['translation'] = NULL; } unset($conditions['translated']); } else { $join = !empty($options['translation']) ? 'leftJoin' : FALSE; } if ($join) { if (isset($conditions['language'])) { // If we've got a language condition, we use it for the join. $query->{$join}('locales_target', 't', "t.lid = s.lid AND t.language = :langcode", array(':langcode' => $conditions['language'])); unset($conditions['language']); } else { // Since we don't have a language, join with locale id only. $query->{$join}('locales_target', 't', "t.lid = s.lid"); } if (!empty($options['translation'])) { // We cannot just add all fields because 'lid' may get null values. $query->fields('t', array('language', 'translation', 'customized')); } } // If we have conditions for location's type or name, then we need the // location table, for which we add a subquery. We cast any scalar value to // array so we can consistently use IN conditions. if (isset($conditions['type']) || isset($conditions['name'])) { $subquery = $this->connection->select('locales_location', 'l', $this->options)->fields('l', array('sid')); foreach (array('type', 'name') as $field) { if (isset($conditions[$field])) { $subquery->condition('l.' . $field, (array) $conditions[$field], 'IN'); unset($conditions[$field]); } } $query->condition('s.lid', $subquery, 'IN'); } // Add conditions for both tables. foreach ($conditions as $field => $value) { $table_alias = $this->dbFieldTable($field); $field_alias = $table_alias . '.' . $field; if (is_null($value)) { $query->isNull($field_alias); } elseif ($table_alias == 't' && $join === 'leftJoin') { // Conditions for target fields when doing an outer join only make // sense if we add also OR field IS NULL. $query->condition(db_or()->condition($field_alias, (array) $value, 'IN')->isNull($field_alias)); } else { $query->condition($field_alias, (array) $value, 'IN'); } } // Process other options, string filter, query limit, etc. if (!empty($options['filters'])) { if (count($options['filters']) > 1) { $filter = db_or(); $query->condition($filter); } else { // If we have a single filter, just add it to the query. $filter = $query; } foreach ($options['filters'] as $field => $string) { $filter->condition($this->dbFieldTable($field) . '.' . $field, '%' . db_like($string) . '%', 'LIKE'); } } if (!empty($options['pager limit'])) { $query = $query->extend('Drupal\\Core\\Database\\Query\\PagerSelectExtender')->limit($options['pager limit']); } return $query; }
/** * 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; } }
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); }
/** * 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; } }
/** * Prepares the query and calculates the normalization factor. * * After the query is normalized the keywords are weighted to give the results * a relevancy score. The query is ready for execution after this. * * Error and warning conditions can apply. Call getStatus() after calling * this method to retrieve them. * * @return bool * TRUE if at least one keyword matched the search index; FALSE if not. */ public function prepareAndNormalize() { $this->parseSearchExpression(); $this->executedPrepare = TRUE; if (count($this->words) == 0) { // Although the query could proceed, there is no point in joining // with other tables and attempting to normalize if there are no // keywords present. $this->status |= SearchQuery::NO_POSITIVE_KEYWORDS; return FALSE; } // Build the basic search query: match the entered keywords. $or = db_or(); foreach ($this->words as $word) { $or->condition('i.word', $word); } $this->condition($or); // Add keyword normalization information to the query. $this->join('search_total', 't', 'i.word = t.word'); $this->condition('i.type', $this->type)->groupBy('i.type')->groupBy('i.sid')->having('COUNT(*) >= :matches', array(':matches' => $this->matches)); // Clone the query object to calculate normalization. $normalize_query = clone $this->query; // For complex search queries, add the LIKE conditions; if the query is // simple, we do not need them for normalization. if (!$this->simple) { $normalize_query->join('search_dataset', 'd', 'i.sid = d.sid AND i.type = d.type AND i.langcode = d.langcode'); if (count($this->conditions)) { $normalize_query->condition($this->conditions); } } // Calculate normalization, which is the max of all the search scores for // positive keywords in the query. And note that the query could have other // fields added to it by the user of this extension. $normalize_query->addExpression('SUM(i.score * t.count)', 'calculated_score'); $result = $normalize_query->range(0, 1)->orderBy('calculated_score', 'DESC')->execute()->fetchObject(); if (isset($result->calculated_score)) { $this->normalize = (double) $result->calculated_score; } if ($this->normalize) { return TRUE; } // If the normalization value was zero, that indicates there were no // matches to the supplied positive keywords. $this->status |= SearchQuery::NO_KEYWORD_MATCHES; return FALSE; }
/** * {@inheritdoc} */ public function query() { if (!empty($this->view->live_preview)) { return; } // Make sure the id field is included in the results. $id_field = $this->view->storage->get('base_field'); $this->id_field_alias = $this->view->query->addField($this->view->storage->get('base_table'), $id_field); $options = $this->getOption('entity_reference_options'); // Restrict the autocomplete options based on what's been typed already. if (isset($options['match'])) { $style_options = $this->getOption('style'); $value = db_like($options['match']) . '%'; if ($options['match_operator'] != 'STARTS_WITH') { $value = '%' . $value; } // Multiple search fields are OR'd together. $conditions = db_or(); // Build the condition using the selected search fields. foreach ($style_options['options']['search_fields'] as $field_id) { if (!empty($field_id)) { // Get the table and field names for the checked field. $field_handler = $this->view->field[$field_id]; $field_alias = $this->view->query->addField($field_handler->table, $field_handler->realField); $field = $this->view->query->fields[$field_alias]; // Add an OR condition for the field. $conditions->condition($field['table'] . '.' . $field['field'], $value, 'LIKE'); } } $this->view->query->addWhere(0, $conditions); } // Add an IN condition for validation. if (!empty($options['ids'])) { $this->view->query->addWhere(0, $id_field, $options['ids'], 'IN'); } $this->view->setItemsPerPage($options['limit']); }
/** * {@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); // 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); $this->query->addWhere($this->options['group'], $search_condition); // Add the GROUP BY and HAVING expressions to the query. $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; }
/** * Confirms that we can properly nest conditional clauses. */ function testNestedConditions() { // This query should translate to: // "SELECT job FROM {test} WHERE name = 'Paul' AND (age = 26 OR age = 27)" // That should find only one record. Yes it's a non-optimal way of writing // that query but that's not the point! $query = db_select('test'); $query->addField('test', 'job'); $query->condition('name', 'Paul'); $query->condition(db_or()->condition('age', 26)->condition('age', 27)); $job = $query->execute()->fetchField(); $this->assertEqual($job, 'Songwriter', 'Correct data retrieved.'); }
/** * Executes a facet query. */ public function execute() { $this->parseSearchExpression(); // Adds OR conditions. if (!empty($this->words)) { $or = db_or(); foreach ($this->words as $word) { $or->condition('i.word', $word); } $this->condition($or); } // Build query for keyword normalization. $this->join('search_total', 't', 'i.word = t.word'); $this->condition('i.type', $this->type)->groupBy('i.langcode')->groupBy('value')->groupBy('i.type')->groupBy('i.sid')->having('COUNT(*) >= :matches', array(':matches' => $this->matches)); // For complex search queries, add the LIKE conditions. /*if (!$this->simple) { $this->join('search_dataset', 'd', 'i.sid = d.sid AND i.type = d.type'); $this->condition($this->conditions); }*/ // Add conditions to query. $this->join('search_dataset', 'd', 'i.sid = d.sid AND i.type = d.type AND i.langcode = d.langcode'); $this->condition($this->conditions); // Add tag and useful metadata. $this->addTag('search_' . $this->type)->addMetaData('normalize', $this->normalize); // Adds subquery to group the results in the r table. $subquery = db_select($this->query, 'r')->fields('r', array('value'))->groupBy('r.value'); // Adds COUNT() expression to get facet counts. $subquery->addExpression('COUNT(r.value)', 'count'); $subquery->orderBy('count', 'DESC'); // Executes the subquery. return $subquery->execute(); }
/** * Tests updates with OR conditionals. */ function testOrConditionUpdate() { $update = db_update('test')->fields(array('job' => 'Musician'))->condition(db_or()->condition('name', 'John')->condition('name', 'Paul')); $num_updated = $update->execute(); $this->assertIdentical($num_updated, 2, 'Updated 2 records.'); $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField(); $this->assertIdentical($num_matches, '2', 'Updated fields successfully.'); }