views_plugin_query_default.inc 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716
  1. <?php
  2. /**
  3. * @file
  4. * Definition of views_plugin_query_default.
  5. */
  6. /**
  7. * Object used to create a SELECT query.
  8. *
  9. * @ingroup views_query_plugins
  10. */
  11. class views_plugin_query_default extends views_plugin_query {
  12. /**
  13. * A list of tables in the order they should be added, keyed by alias.
  14. */
  15. public $table_queue = array();
  16. /**
  17. * Holds an array of tables and counts added so that we can create aliases.
  18. */
  19. public $tables = array();
  20. /**
  21. * Holds an array of relationships, which are aliases of the primary
  22. * table that represent different ways to join the same table in.
  23. */
  24. public $relationships = array();
  25. /**
  26. * An array of sections of the WHERE query. Each section is in itself
  27. * an array of pieces and a flag as to whether or not it should be AND
  28. * or OR.
  29. */
  30. public $where = array();
  31. /**
  32. * An array of sections of the HAVING query. Each section is in itself
  33. * an array of pieces and a flag as to whether or not it should be AND
  34. * or OR.
  35. */
  36. public $having = array();
  37. /**
  38. * The default operator to use when connecting the WHERE groups. May be
  39. * AND or OR.
  40. */
  41. public $group_operator = 'AND';
  42. /**
  43. * A simple array of order by clauses.
  44. */
  45. public $orderby = array();
  46. /**
  47. * A simple array of group by clauses.
  48. */
  49. public $groupby = array();
  50. /**
  51. * An array of fields.
  52. */
  53. public $fields = array();
  54. /**
  55. * The table header to use for tablesort. This matters because tablesort
  56. * needs to modify the query and needs the header.
  57. */
  58. public $header = array();
  59. /**
  60. * A flag as to whether or not to make the primary field distinct.
  61. */
  62. public $distinct = FALSE;
  63. /**
  64. *
  65. */
  66. public $has_aggregate = FALSE;
  67. /**
  68. * Should this query be optimized for counts, for example no sorts.
  69. */
  70. public $get_count_optimized = NULL;
  71. /**
  72. * The current used pager plugin.
  73. *
  74. * @var views_plugin_pager
  75. */
  76. public $pager = NULL;
  77. /**
  78. * An array mapping table aliases and field names to field aliases.
  79. */
  80. public $field_aliases = array();
  81. /**
  82. * Query tags which will be passed over to the dbtng query object.
  83. */
  84. public $tags = array();
  85. /**
  86. * Is the view marked as not distinct.
  87. *
  88. * @var bool
  89. */
  90. public $no_distinct;
  91. /**
  92. * Defines the distinct type.
  93. * - FALSE if it's distinct by base field.
  94. * - TRUE if it just adds the sql distinct keyword.
  95. *
  96. * @var bool
  97. */
  98. public $pure_distinct = FALSE;
  99. /**
  100. * {@inheritdoc}
  101. */
  102. public function init($base_table = 'node', $base_field = 'nid', $options) {
  103. parent::init($base_table, $base_field, $options);
  104. $this->base_table = $base_table;
  105. // Predefine these above, for clarity.
  106. $this->base_field = $base_field;
  107. $this->relationships[$base_table] = array(
  108. 'link' => NULL,
  109. 'table' => $base_table,
  110. 'alias' => $base_table,
  111. 'base' => $base_table,
  112. );
  113. // Unit the table queue with our primary table.
  114. $this->table_queue[$base_table] = array(
  115. 'alias' => $base_table,
  116. 'table' => $base_table,
  117. 'relationship' => $base_table,
  118. 'join' => NULL,
  119. );
  120. // Init the tables with our primary table.
  121. $this->tables[$base_table][$base_table] = array(
  122. 'count' => 1,
  123. 'alias' => $base_table,
  124. );
  125. // We no longer want the base field to appear automatically.
  126. // if ($base_field) {
  127. // $this->fields[$base_field] = array(
  128. // 'table' => $base_table,
  129. // 'field' => $base_field,
  130. // 'alias' => $base_field,
  131. // );
  132. // }
  133. $this->count_field = array(
  134. 'table' => $base_table,
  135. 'field' => $base_field,
  136. 'alias' => $base_field,
  137. 'count' => TRUE,
  138. );
  139. }
  140. /**
  141. * Utility methods to set flags and data.
  142. */
  143. /**
  144. * Set the view to be distinct.
  145. *
  146. * There are either distinct per base field or distinct in the pure sql way,
  147. * based on $pure_distinct.
  148. *
  149. * @param bool $value
  150. * Should the view by distincted.
  151. * @param bool $pure_distinct
  152. * Should only the sql keyword be added.
  153. */
  154. public function set_distinct($value = TRUE, $pure_distinct = FALSE) {
  155. if (!(isset($this->no_distinct) && $value)) {
  156. $this->distinct = $value;
  157. $this->pure_distinct = $pure_distinct;
  158. }
  159. }
  160. /**
  161. * Set what field the query will count() on for paging.
  162. */
  163. public function set_count_field($table, $field, $alias = NULL) {
  164. if (empty($alias)) {
  165. $alias = $table . '_' . $field;
  166. }
  167. $this->count_field = array(
  168. 'table' => $table,
  169. 'field' => $field,
  170. 'alias' => $alias,
  171. 'count' => TRUE,
  172. );
  173. }
  174. /**
  175. * Set the table header.
  176. *
  177. * Used for click-sorting because it's needed info to modify the ORDER BY
  178. * clause.
  179. */
  180. public function set_header($header) {
  181. $this->header = $header;
  182. }
  183. /**
  184. * {@inheritdoc}
  185. */
  186. public function option_definition() {
  187. $options = parent::option_definition();
  188. $options['disable_sql_rewrite'] = array(
  189. 'default' => FALSE,
  190. 'translatable' => FALSE,
  191. 'bool' => TRUE,
  192. );
  193. $options['distinct'] = array(
  194. 'default' => FALSE,
  195. 'bool' => TRUE,
  196. );
  197. $options['pure_distinct'] = array(
  198. 'default' => FALSE,
  199. 'bool' => TRUE,
  200. );
  201. $options['slave'] = array(
  202. 'default' => FALSE,
  203. 'bool' => TRUE,
  204. );
  205. $options['query_comment'] = array(
  206. 'default' => '',
  207. );
  208. $options['query_tags'] = array(
  209. 'default' => array(),
  210. );
  211. return $options;
  212. }
  213. /**
  214. * Add settings for the ui.
  215. */
  216. public function options_form(&$form, &$form_state) {
  217. parent::options_form($form, $form_state);
  218. $form['disable_sql_rewrite'] = array(
  219. '#title' => t('Disable SQL rewriting'),
  220. '#description' => t('Disabling SQL rewriting will disable node_access checks as well as other modules that implement hook_query_alter().'),
  221. '#type' => 'checkbox',
  222. '#default_value' => !empty($this->options['disable_sql_rewrite']),
  223. '#suffix' => '<div class="messages warning sql-rewrite-warning js-hide">'
  224. . t('WARNING: Disabling SQL rewriting means that node access security is disabled. This may allow users to see data they should not be able to see if your view is misconfigured. Please use this option only if you understand and accept this security risk.')
  225. . '</div>',
  226. );
  227. $form['distinct'] = array(
  228. '#type' => 'checkbox',
  229. '#title' => t('Distinct'),
  230. '#description' => t('This will make the view display only distinct items. If there are multiple identical items, each will be displayed only once. You can use this to try and remove duplicates from a view, though it does not always work. Note that this can slow queries down, so use it with caution.'),
  231. '#default_value' => !empty($this->options['distinct']),
  232. );
  233. $form['pure_distinct'] = array(
  234. '#type' => 'checkbox',
  235. '#title' => t('Pure Distinct'),
  236. '#description' => t('This will prevent views from adding the base column to the distinct field. If this is not selected and the base column is a primary key, then a non-pure distinct will not function properly because the primary key is always unique.'),
  237. '#default_value' => !empty($this->options['pure_distinct']),
  238. '#dependency' => array('edit-query-options-distinct' => '1'),
  239. );
  240. $form['slave'] = array(
  241. '#type' => 'checkbox',
  242. '#title' => t('Use Slave Server'),
  243. '#description' => t('This will make the query attempt to connect to a slave server if available. If no slave server is defined or available, it will fall back to the default server.'),
  244. '#default_value' => !empty($this->options['slave']),
  245. );
  246. $form['query_comment'] = array(
  247. '#type' => 'textfield',
  248. '#title' => t('Query Comment'),
  249. '#description' => t('If set, this comment will be embedded in the query and passed to the SQL server. This can be helpful for logging or debugging.'),
  250. '#default_value' => $this->options['query_comment'],
  251. );
  252. $form['query_tags'] = array(
  253. '#type' => 'textfield',
  254. '#title' => t('Query Tags'),
  255. '#description' => t('If set, these tags will be appended to the query and can be used to identify the query in a module. This can be helpful for altering queries.'),
  256. '#default_value' => implode(', ', $this->options['query_tags']),
  257. '#element_validate' => array('views_element_validate_tags'),
  258. );
  259. }
  260. /**
  261. * Special submit handling.
  262. */
  263. public function options_submit(&$form, &$form_state) {
  264. $element = array('#parents' => array('query', 'options', 'query_tags'));
  265. $value = explode(',', drupal_array_get_nested_value($form_state['values'], $element['#parents']));
  266. $value = array_filter(array_map('trim', $value));
  267. form_set_value($element, $value, $form_state);
  268. }
  269. /**
  270. * Table/join adding.
  271. */
  272. /**
  273. * A relationship is an alternative endpoint to a series of table joins.
  274. *
  275. * Relationships must be aliases of the primary table and they must join
  276. * either to the primary table or to a pre-existing relationship.
  277. *
  278. * An example of a relationship would be a nodereference table. If you have a
  279. * nodereference named 'book_parent' which links to a parent node, you could
  280. * set up a relationship 'node_book_parent' to 'node'. Then, anything that
  281. * links to 'node' can link to 'node_book_parent' instead, thus allowing all
  282. * properties of both nodes to be available in the query.
  283. *
  284. * @param string $alias
  285. * What this relationship will be called, and is also the alias for the
  286. * table.
  287. * @param views_join $join
  288. * A views_join object (or derived object) to join the alias in.
  289. * @param string $base
  290. * The name of the 'base' table this relationship represents; this tells the
  291. * join search which path to attempt to use when finding the path to this
  292. * relationship.
  293. * @param string $link_point
  294. * If this relationship links to something other than the primary table,
  295. * specify that table here. For example, a 'track' node might have a
  296. * relationship to an 'album' node, which might have a relationship to an
  297. * 'artist' node.
  298. */
  299. public function add_relationship($alias, $join, $base, $link_point = NULL) {
  300. if (empty($link_point)) {
  301. $link_point = $this->base_table;
  302. }
  303. elseif (!array_key_exists($link_point, $this->relationships)) {
  304. return FALSE;
  305. }
  306. // Make sure $alias isn't already used; if it, start adding stuff.
  307. $alias_base = $alias;
  308. $count = 1;
  309. while (!empty($this->relationships[$alias])) {
  310. $alias = $alias_base . '_' . $count++;
  311. }
  312. // Make sure this join is adjusted for our relationship.
  313. if ($link_point && isset($this->relationships[$link_point])) {
  314. $join = $this->adjust_join($join, $link_point);
  315. }
  316. // Add the table directly to the queue to avoid accidentally marking it.
  317. $this->table_queue[$alias] = array(
  318. 'table' => $join->table,
  319. 'num' => 1,
  320. 'alias' => $alias,
  321. 'join' => $join,
  322. 'relationship' => $link_point,
  323. );
  324. $this->relationships[$alias] = array(
  325. 'link' => $link_point,
  326. 'table' => $join->table,
  327. 'base' => $base,
  328. );
  329. $this->tables[$this->base_table][$alias] = array(
  330. 'count' => 1,
  331. 'alias' => $alias,
  332. );
  333. return $alias;
  334. }
  335. /**
  336. * Add a table to the query, ensuring the path exists.
  337. *
  338. * This function will test to ensure that the path back to the primary table
  339. * is valid and exists; if you do not wish for this testing to occur, use
  340. * $query->queue_table() instead.
  341. *
  342. * @param string $table
  343. * The name of the table to add. It needs to exist in the global table
  344. * array.
  345. * @param string $relationship
  346. * An alias of a table; if this is set, the path back to this table will be
  347. * tested prior to adding the table, making sure that all intermediary
  348. * tables exist and are properly aliased. If set to NULL the path to the
  349. * primary table will be ensured. If the path cannot be made, the table
  350. * will NOT be added.
  351. * @param views_join $join
  352. * In some join configurations this table may actually join back through a
  353. * different method; this is most likely to be used when tracing a
  354. * hierarchy path. (node->parent->parent2->parent3). This parameter will
  355. * specify how this table joins if it is not the default.
  356. * @param string $alias
  357. * A specific alias to use, rather than the default alias.
  358. *
  359. * @return string
  360. * The alias of the table; this alias can be used to access information
  361. * about the table and should always be used to refer to the table when
  362. * adding parts to the query. Or FALSE if the table was not able to be
  363. * added.
  364. */
  365. public function add_table($table, $relationship = NULL, $join = NULL, $alias = NULL) {
  366. if (!$this->ensure_path($table, $relationship, $join)) {
  367. return FALSE;
  368. }
  369. if ($join && $relationship) {
  370. $join = $this->adjust_join($join, $relationship);
  371. }
  372. return $this->queue_table($table, $relationship, $join, $alias);
  373. }
  374. /**
  375. * Add a table to the query without ensuring the path.
  376. *
  377. * This is a pretty internal function to Views and add_table() or
  378. * ensure_table() should be used instead of this one, unless you are
  379. * absolutely sure this is what you want.
  380. *
  381. * @param string $table
  382. * The name of the table to add. It needs to exist in the global table
  383. * array.
  384. * @param string $relationship
  385. * The primary table alias this table is related to. If not set, the
  386. * primary table will be used.
  387. * @param views_join $join
  388. * In some join configurations this table may actually join back through a
  389. * different method; this is most likely to be used when tracing a
  390. * hierarchy path. (node->parent->parent2->parent3). This parameter will
  391. * specify how this table joins if it is not the default.
  392. * @param string $alias
  393. * A specific alias to use, rather than the default alias.
  394. *
  395. * @return string
  396. * The alias of the table; this alias can be used to access information
  397. * about the table and should always be used to refer to the table when
  398. * adding parts to the query. Or FALSE if the table was not able to be
  399. * added.
  400. */
  401. public function queue_table($table, $relationship = NULL, $join = NULL, $alias = NULL) {
  402. // If the alias is set, make sure it doesn't already exist.
  403. if (isset($this->table_queue[$alias])) {
  404. return $alias;
  405. }
  406. if (empty($relationship)) {
  407. $relationship = $this->base_table;
  408. }
  409. if (!array_key_exists($relationship, $this->relationships)) {
  410. return FALSE;
  411. }
  412. if (!$alias && $join && $relationship && !empty($join->adjusted) && $table != $join->table) {
  413. if ($relationship == $this->base_table) {
  414. $alias = $table;
  415. }
  416. else {
  417. $alias = $relationship . '_' . $table;
  418. }
  419. }
  420. // Check this again to make sure we don't blow up existing aliases for
  421. // already adjusted joins.
  422. if (isset($this->table_queue[$alias])) {
  423. return $alias;
  424. }
  425. $alias = $this->mark_table($table, $relationship, $alias);
  426. // If no alias is specified, give it the default.
  427. if (!isset($alias)) {
  428. $alias = $this->tables[$relationship][$table]['alias'] . $this->tables[$relationship][$table]['count'];
  429. }
  430. // If this is a relationship based table, add a marker with the
  431. // relationship as a primary table for the alias.
  432. if ($table != $alias) {
  433. $this->mark_table($alias, $this->base_table, $alias);
  434. }
  435. // If no join is specified, pull it from the table data.
  436. if (!isset($join)) {
  437. $join = $this->get_join_data($table, $this->relationships[$relationship]['base']);
  438. if (empty($join)) {
  439. return FALSE;
  440. }
  441. $join = $this->adjust_join($join, $relationship);
  442. }
  443. $this->table_queue[$alias] = array(
  444. 'table' => $table,
  445. 'num' => $this->tables[$relationship][$table]['count'],
  446. 'alias' => $alias,
  447. 'join' => $join,
  448. 'relationship' => $relationship,
  449. );
  450. return $alias;
  451. }
  452. /**
  453. *
  454. */
  455. public function mark_table($table, $relationship, $alias) {
  456. // Mark that this table has been added.
  457. if (empty($this->tables[$relationship][$table])) {
  458. if (!isset($alias)) {
  459. $alias = '';
  460. if ($relationship != $this->base_table) {
  461. // Double underscore will help prevent accidental name space
  462. // collisions.
  463. $alias = $relationship . '__';
  464. }
  465. $alias .= $table;
  466. }
  467. $this->tables[$relationship][$table] = array(
  468. 'count' => 1,
  469. 'alias' => $alias,
  470. );
  471. }
  472. else {
  473. $this->tables[$relationship][$table]['count']++;
  474. }
  475. return $alias;
  476. }
  477. /**
  478. * Ensure a table exists in the queue; if it already exists it won't do
  479. * anything, but if it doesn't it will add the table queue. It will ensure a
  480. * path leads back to the relationship table.
  481. *
  482. * @param string $table
  483. * The unaliased name of the table to ensure.
  484. * @param string $relationship
  485. * The relationship to ensure the table links to. Each relationship will
  486. * get a unique instance of the table being added. If not specified, will
  487. * be the primary table.
  488. * @param views_join $join
  489. * A views_join object (or derived object) to join the alias in.
  490. *
  491. * @return string
  492. * The alias used to refer to this specific table, or NULL if the table
  493. * cannot be ensured.
  494. */
  495. public function ensure_table($table, $relationship = NULL, $join = NULL) {
  496. // Ensure a relationship.
  497. if (empty($relationship)) {
  498. $relationship = $this->base_table;
  499. }
  500. // If the relationship is the primary table, this actually be a relationship
  501. // link back from an alias. We store all aliases along with the primary
  502. // table to detect this state, because eventually it'll hit a table we
  503. // already have and that's when we want to stop.
  504. if ($relationship == $this->base_table && !empty($this->tables[$relationship][$table])) {
  505. return $this->tables[$relationship][$table]['alias'];
  506. }
  507. if (!array_key_exists($relationship, $this->relationships)) {
  508. return FALSE;
  509. }
  510. if ($table == $this->relationships[$relationship]['base']) {
  511. return $relationship;
  512. }
  513. // If we do not have join info, fetch it.
  514. if (!isset($join)) {
  515. $join = $this->get_join_data($table, $this->relationships[$relationship]['base']);
  516. }
  517. // If it can't be fetched, this won't work.
  518. if (empty($join)) {
  519. return;
  520. }
  521. // Adjust this join for the relationship, which will ensure that the 'base'
  522. // table it links to is correct. Tables adjoined to a relationship
  523. // join to a link point, not the base table.
  524. $join = $this->adjust_join($join, $relationship);
  525. if ($this->ensure_path($table, $relationship, $join)) {
  526. // Attempt to eliminate redundant joins. If this table's relationship
  527. // and join exactly matches an existing table's relationship and join, we
  528. // do not have to join to it again; just return the existing table's
  529. // alias.
  530. // @see http://groups.drupal.org/node/11288
  531. //
  532. // This can be done safely here but not lower down in queue_table(),
  533. // because queue_table() is also used by add_table() which requires the
  534. // ability to intentionally add the same table with the same join
  535. // multiple times. For example, a view that filters on 3 taxonomy terms
  536. // using AND needs to join taxonomy_term_data 3 times with the same join.
  537. // scan through the table queue to see if a matching join and
  538. // relationship exists. If so, use it instead of this join.
  539. // @todo Scanning through $this->table_queue results in an O(N^2)
  540. // algorithm, and this code runs every time the view is instantiated
  541. // (Views 2 does not currently cache queries). There are a couple
  542. // possible "improvements" but we should do some performance testing
  543. // before picking one.
  544. foreach ($this->table_queue as $queued_table) {
  545. // In PHP 4 and 5, the == operation returns TRUE for two objects if
  546. // they are instances of the same class and have the same attributes
  547. // and values.
  548. if ($queued_table['relationship'] == $relationship && $queued_table['join'] == $join) {
  549. return $queued_table['alias'];
  550. }
  551. }
  552. return $this->queue_table($table, $relationship, $join);
  553. }
  554. }
  555. /**
  556. * Make sure that the specified table can be properly linked to the primary
  557. * table in the JOINs. This function uses recursion. If the tables needed
  558. * to complete the path back to the primary table are not in the query they
  559. * will be added, but additional copies will NOT be added if the table is
  560. * already there.
  561. */
  562. public function ensure_path($table, $relationship = NULL, $join = NULL, $traced = array(), $add = array()) {
  563. if (!isset($relationship)) {
  564. $relationship = $this->base_table;
  565. }
  566. if (!array_key_exists($relationship, $this->relationships)) {
  567. return FALSE;
  568. }
  569. // If we do not have join info, fetch it.
  570. if (!isset($join)) {
  571. $join = $this->get_join_data($table, $this->relationships[$relationship]['base']);
  572. }
  573. // If it can't be fetched, this won't work.
  574. if (empty($join)) {
  575. return FALSE;
  576. }
  577. // Does a table along this path exist?
  578. if (isset($this->tables[$relationship][$table]) ||
  579. ($join && $join->left_table == $relationship) ||
  580. ($join && $join->left_table == $this->relationships[$relationship]['table'])) {
  581. // Make sure that we're linking to the correct table for our relationship.
  582. foreach (array_reverse($add) as $table => $path_join) {
  583. $this->queue_table($table, $relationship, $this->adjust_join($path_join, $relationship));
  584. }
  585. return TRUE;
  586. }
  587. // Have we been this way?
  588. if (isset($traced[$join->left_table])) {
  589. // We looped. Broked.
  590. return FALSE;
  591. }
  592. // Do we have to add this table?
  593. $left_join = $this->get_join_data($join->left_table, $this->relationships[$relationship]['base']);
  594. if (!isset($this->tables[$relationship][$join->left_table])) {
  595. $add[$join->left_table] = $left_join;
  596. }
  597. // Keep looking.
  598. $traced[$join->left_table] = TRUE;
  599. return $this->ensure_path($join->left_table, $relationship, $left_join, $traced, $add);
  600. }
  601. /**
  602. * Fix a join to adhere to the proper relationship.
  603. *
  604. * The left table can vary based upon what relationship items are joined in
  605. * on.
  606. */
  607. public function adjust_join($join, $relationship) {
  608. if (!empty($join->adjusted)) {
  609. return $join;
  610. }
  611. if (empty($relationship) || empty($this->relationships[$relationship])) {
  612. return $join;
  613. }
  614. // Adjusts the left table for our relationship.
  615. if ($relationship != $this->base_table) {
  616. // If we're linking to the primary table, the relationship to use will
  617. // be the prior relationship. Unless it's a direct link. Safety! Don't
  618. // modify an original here.
  619. $join = clone $join;
  620. // Do we need to try to ensure a path?
  621. if ($join->left_table != $this->relationships[$relationship]['table'] &&
  622. $join->left_table != $this->relationships[$relationship]['base'] &&
  623. !isset($this->tables[$relationship][$join->left_table]['alias'])) {
  624. $this->ensure_table($join->left_table, $relationship);
  625. }
  626. // First, if this is our link point/anchor table, just use the
  627. // relationship.
  628. if ($join->left_table == $this->relationships[$relationship]['table']) {
  629. $join->left_table = $relationship;
  630. }
  631. // then, try the base alias.
  632. elseif (isset($this->tables[$relationship][$join->left_table]['alias'])) {
  633. $join->left_table = $this->tables[$relationship][$join->left_table]['alias'];
  634. }
  635. // But if we're already looking at an alias, use that instead.
  636. elseif (isset($this->table_queue[$relationship]['alias'])) {
  637. $join->left_table = $this->table_queue[$relationship]['alias'];
  638. }
  639. }
  640. $join->adjusted = TRUE;
  641. return $join;
  642. }
  643. /**
  644. * Retrieve join data from the larger join data cache.
  645. *
  646. * @param string $table
  647. * The table to get the join information for.
  648. * @param string $base_table
  649. * The path we're following to get this join.
  650. *
  651. * @return views_join
  652. * A views_join object or child object, if one exists.
  653. */
  654. public function get_join_data($table, $base_table) {
  655. // Check to see if we're linking to a known alias. If so, get the real
  656. // table's data instead.
  657. if (!empty($this->table_queue[$table])) {
  658. $table = $this->table_queue[$table]['table'];
  659. }
  660. return views_get_table_join($table, $base_table);
  661. }
  662. /**
  663. * Get the information associated with a table.
  664. *
  665. * If you need the alias of a table with a particular relationship, use
  666. * ensure_table().
  667. */
  668. public function get_table_info($table) {
  669. if (!empty($this->table_queue[$table])) {
  670. return $this->table_queue[$table];
  671. }
  672. // In rare cases we might *only* have aliased versions of the table.
  673. if (!empty($this->tables[$this->base_table][$table])) {
  674. $alias = $this->tables[$this->base_table][$table]['alias'];
  675. if (!empty($this->table_queue[$alias])) {
  676. return $this->table_queue[$alias];
  677. }
  678. }
  679. }
  680. /**
  681. * Add a field to the query table, possibly with an alias. This will
  682. * automatically call ensure_table to make sure the required table exists,
  683. * *unless* $table is unset.
  684. *
  685. * @param string $table
  686. * The table this field is attached to. If NULL, it is assumed this will be
  687. * a formula; otherwise, ensure_table is used to make sure the table exists.
  688. * @param string $field
  689. * The name of the field to add. This may be a real field or a formula.
  690. * @param string $alias
  691. * The alias to create. If not specified, the alias will be $table_$field
  692. * unless $table is NULL. When adding formulae, it is recommended that an
  693. * alias be used.
  694. * @param array $params
  695. * An array of parameters additional to the field that will control items
  696. * such as aggregation functions and DISTINCT.
  697. *
  698. * @return string
  699. * The name that this field can be referred to as, usually the alias.
  700. */
  701. public function add_field($table, $field, $alias = '', $params = array()) {
  702. // We check for this specifically because it gets a special alias.
  703. if ($table == $this->base_table && $field == $this->base_field && empty($alias)) {
  704. $alias = $this->base_field;
  705. }
  706. if ($table && empty($this->table_queue[$table])) {
  707. $this->ensure_table($table);
  708. }
  709. if (!$alias && $table) {
  710. $alias = $table . '_' . $field;
  711. }
  712. // Make sure an alias is assigned.
  713. $alias = $alias ? $alias : $field;
  714. // PostgreSQL truncates aliases to 63 characters.
  715. // @see http://drupal.org/node/571548
  716. // We limit the length of the original alias up to 60 characters
  717. // to get a unique alias later if its have duplicates.
  718. $alias = strtolower(substr($alias, 0, 60));
  719. // Create a field info array.
  720. $field_info = array(
  721. 'field' => $field,
  722. 'table' => $table,
  723. 'alias' => $alias,
  724. ) + $params;
  725. // Test to see if the field is actually the same or not. Due to differing
  726. // parameters changing the aggregation function, we need to do some
  727. // automatic alias collision detection.
  728. $base = $alias;
  729. $counter = 0;
  730. while (!empty($this->fields[$alias]) && $this->fields[$alias] != $field_info) {
  731. $field_info['alias'] = $alias = $base . '_' . ++$counter;
  732. }
  733. if (empty($this->fields[$alias])) {
  734. $this->fields[$alias] = $field_info;
  735. }
  736. // Keep track of all aliases used.
  737. $this->field_aliases[$table][$field] = $alias;
  738. return $alias;
  739. }
  740. /**
  741. * Remove all fields that may've been added.
  742. *
  743. * Primarily used for summary mode where we're changing the query because we
  744. * didn't get data we needed.
  745. */
  746. public function clear_fields() {
  747. $this->fields = array();
  748. }
  749. /**
  750. * Add a simple WHERE clause to the query.
  751. *
  752. * The caller is responsible for ensuring that all fields are fully qualified
  753. * (TABLE.FIELD) and that the table already exists in the query.
  754. *
  755. * @param string $group
  756. * The WHERE group to add these to; groups are used to create AND/OR
  757. * sections. Groups cannot be nested. Use 0 as the default group. If the
  758. * group does not yet exist it will be created as an AND group.
  759. * @param string $field
  760. * The name of the field to check.
  761. * @param string $value
  762. * The value to test the field against. In most cases, this is a scalar. For
  763. * more complex options, it is an array. The meaning of each element in the
  764. * array is dependent on the $operator.
  765. * @param string $operator
  766. * The comparison operator, such as =, <, or >=. It also accepts more
  767. * complex options such as IN, LIKE, or BETWEEN. Defaults to IN if $value is
  768. * an array = otherwise. If $field is a string you have to use 'formula'
  769. * here.
  770. *
  771. * The $field, $value and $operator arguments can also be passed in with a
  772. * single DatabaseCondition object, like this:
  773. *
  774. * @code
  775. * $this->query->add_where(
  776. * $this->options['group'],
  777. * db_or()
  778. * ->condition($field, $value, 'NOT IN')
  779. * ->condition($field, $value, 'IS NULL')
  780. * );
  781. * @endcode
  782. *
  783. * @see QueryConditionInterface::condition()
  784. * @see DatabaseCondition
  785. */
  786. public function add_where($group, $field, $value = NULL, $operator = NULL) {
  787. // Ensure all variants of 0 are actually 0. Thus '', 0 and NULL are all the
  788. // default group.
  789. if (empty($group)) {
  790. $group = 0;
  791. }
  792. // Check for a group.
  793. if (!isset($this->where[$group])) {
  794. $this->set_where_group('AND', $group);
  795. }
  796. $this->where[$group]['conditions'][] = array(
  797. 'field' => $field,
  798. 'value' => $value,
  799. 'operator' => $operator,
  800. );
  801. }
  802. /**
  803. * Add a complex WHERE clause to the query.
  804. *
  805. * The caller is responsible for ensuring that all fields are fully qualified
  806. * (TABLE.FIELD) and that the table already exists in the query. Internally
  807. * the dbtng method "where" is used.
  808. *
  809. * @param string $group
  810. * The WHERE group to add these to; groups are used to create AND/OR
  811. * sections. Groups cannot be nested. Use 0 as the default group. If the
  812. * group does not yet exist it will be created as an AND group.
  813. * @param string $snippet
  814. * The snippet to check. This can be either a column or a complex expression
  815. * like "UPPER(table.field) = 'value'".
  816. * @param array $args
  817. * An associative array of arguments.
  818. *
  819. * @see QueryConditionInterface::where()
  820. */
  821. public function add_where_expression($group, $snippet, $args = array()) {
  822. // Ensure all variants of 0 are actually 0. Thus '', 0 and NULL are all
  823. // the default group.
  824. if (empty($group)) {
  825. $group = 0;
  826. }
  827. // Check for a group.
  828. if (!isset($this->where[$group])) {
  829. $this->set_where_group('AND', $group);
  830. }
  831. $this->where[$group]['conditions'][] = array(
  832. 'field' => $snippet,
  833. 'value' => $args,
  834. 'operator' => 'formula',
  835. );
  836. }
  837. /**
  838. * Add a simple HAVING clause to the query.
  839. *
  840. * The caller is responsible for ensuring that all fields are fully qualified
  841. * (TABLE.FIELD) and that the table and an appropriate GROUP BY already exist
  842. * in the query. Internally the dbtng method "havingCondition" is used.
  843. *
  844. * @param string $group
  845. * The HAVING group to add these to; groups are used to create AND/OR
  846. * sections. Groups cannot be nested. Use 0 as the default group. If the
  847. * group does not yet exist it will be created as an AND group.
  848. * @param string $field
  849. * The name of the field to check.
  850. * @param string $value
  851. * The value to test the field against. In most cases, this is a scalar. For
  852. * more complex options, it is an array. The meaning of each element in the
  853. * array is dependent on the $operator.
  854. * @param string $operator
  855. * The comparison operator, such as =, <, or >=. It also accepts more
  856. * complex options such as IN, LIKE, or BETWEEN. Defaults to IN if $value is
  857. * an array = otherwise. If $field is a string you have to use 'formula'
  858. * here.
  859. *
  860. * @see SelectQueryInterface::havingCondition()
  861. */
  862. public function add_having($group, $field, $value = NULL, $operator = NULL) {
  863. // Ensure all variants of 0 are actually 0. Thus '', 0 and NULL are all the
  864. // default group.
  865. if (empty($group)) {
  866. $group = 0;
  867. }
  868. // Check for a group.
  869. if (!isset($this->having[$group])) {
  870. $this->set_where_group('AND', $group, 'having');
  871. }
  872. // Add the clause and the args.
  873. $this->having[$group]['conditions'][] = array(
  874. 'field' => $field,
  875. 'value' => $value,
  876. 'operator' => $operator,
  877. );
  878. }
  879. /**
  880. * Add a complex HAVING clause to the query.
  881. *
  882. * The caller is responsible for ensuring that all fields are fully qualified
  883. * (TABLE.FIELD) and that the table and an appropriate GROUP BY already exist
  884. * in the query. Internally the dbtng method "having" is used.
  885. *
  886. * @param string $group
  887. * The HAVING group to add these to; groups are used to create AND/OR
  888. * sections. Groups cannot be nested. Use 0 as the default group. If the
  889. * group does not yet exist it will be created as an AND group.
  890. * @param string $snippet
  891. * The snippet to check. This can be either a column or a complex
  892. * expression like "COUNT(table.field) > 3"
  893. * @param array $args
  894. * An associative array of arguments.
  895. *
  896. * @see QueryConditionInterface::having()
  897. */
  898. public function add_having_expression($group, $snippet, $args = array()) {
  899. // Ensure all variants of 0 are actually 0. Thus '', 0 and NULL are all
  900. // the default group.
  901. if (empty($group)) {
  902. $group = 0;
  903. }
  904. // Check for a group.
  905. if (!isset($this->having[$group])) {
  906. $this->set_where_group('AND', $group, 'having');
  907. }
  908. // Add the clause and the args.
  909. $this->having[$group]['conditions'][] = array(
  910. 'field' => $snippet,
  911. 'value' => $args,
  912. 'operator' => 'formula',
  913. );
  914. }
  915. /**
  916. * Add an ORDER BY clause to the query.
  917. *
  918. * @param string $table
  919. * The table this field is part of. If a formula, enter NULL. If you want to
  920. * orderby random use "rand" as table and nothing else.
  921. * @param string $field
  922. * The field or formula to sort on. If already a field, enter NULL and put
  923. * in the alias.
  924. * @param string $order
  925. * Either ASC or DESC.
  926. * @param string $alias
  927. * The alias to add the field as. In SQL, all fields in the order by must
  928. * also be in the SELECT portion. If an $alias isn't specified one will be
  929. * generated for from the $field; however, if the $field is a formula, this
  930. * alias will likely fail.
  931. * @param string $params
  932. * Any params that should be passed through to the add_field.
  933. */
  934. public function add_orderby($table, $field = NULL, $order = 'ASC', $alias = '', $params = array()) {
  935. // Only ensure the table if it's not the special random key.
  936. // @todo Maybe it would make sense to just add a add_orderby_rand or
  937. // something similar.
  938. if ($table && $table != 'rand') {
  939. $this->ensure_table($table);
  940. }
  941. // Only fill out this aliasing if there is a table; otherwise we assume it
  942. // is a formula.
  943. if (!$alias && $table) {
  944. $as = $table . '_' . $field;
  945. }
  946. else {
  947. $as = $alias;
  948. }
  949. if ($field) {
  950. $as = $this->add_field($table, $field, $as, $params);
  951. }
  952. $this->orderby[] = array(
  953. 'field' => $as,
  954. 'direction' => strtoupper($order),
  955. );
  956. }
  957. /**
  958. * Add a simple GROUP BY clause to the query.
  959. *
  960. * The caller is responsible for ensuring that the fields are fully qualified
  961. * and the table is properly added.
  962. */
  963. public function add_groupby($clause) {
  964. // Only add it if it's not already in there.
  965. if (!in_array($clause, $this->groupby)) {
  966. $this->groupby[] = $clause;
  967. }
  968. }
  969. /**
  970. * Returns the alias for the given field added to $table.
  971. *
  972. * @see views_plugin_query_default::add_field()
  973. */
  974. public function get_field_alias($table_alias, $field) {
  975. return isset($this->field_aliases[$table_alias][$field]) ? $this->field_aliases[$table_alias][$field] : FALSE;
  976. }
  977. /**
  978. * Adds a query tag to the sql object.
  979. *
  980. * @see SelectQuery::addTag()
  981. */
  982. public function add_tag($tag) {
  983. $this->tags[] = $tag;
  984. }
  985. /**
  986. * Generates a unique placeholder used in the db query.
  987. */
  988. public function placeholder($base = 'views') {
  989. static $placeholders = array();
  990. if (!isset($placeholders[$base])) {
  991. $placeholders[$base] = 0;
  992. return ':' . $base;
  993. }
  994. else {
  995. return ':' . $base . ++$placeholders[$base];
  996. }
  997. }
  998. /**
  999. * Construct the "WHERE" or "HAVING" part of the query.
  1000. *
  1001. * As views has to wrap the conditions from arguments with AND, a special
  1002. * group is wrapped around all conditions. This special group has the ID 0.
  1003. * There is other code in filters which makes sure that the group IDs are
  1004. * higher than zero.
  1005. *
  1006. * @param string $where
  1007. * Either 'where' or 'having'.
  1008. */
  1009. public function build_condition($where = 'where') {
  1010. $has_condition = FALSE;
  1011. $has_arguments = FALSE;
  1012. $has_filter = FALSE;
  1013. $main_group = db_and();
  1014. $filter_group = $this->group_operator == 'OR' ? db_or() : db_and();
  1015. foreach ($this->$where as $group => $info) {
  1016. if (!empty($info['conditions'])) {
  1017. $sub_group = $info['type'] == 'OR' ? db_or() : db_and();
  1018. foreach ($info['conditions'] as $key => $clause) {
  1019. // DBTNG doesn't support to add the same subquery twice to the main
  1020. // query and the count query, so clone the subquery to have two
  1021. // instances of the same object.
  1022. // @see http://drupal.org/node/1112854
  1023. if (is_object($clause['value']) && $clause['value'] instanceof SelectQuery) {
  1024. $clause['value'] = clone $clause['value'];
  1025. }
  1026. if ($clause['operator'] == 'formula') {
  1027. $has_condition = TRUE;
  1028. $sub_group->where($clause['field'], $clause['value']);
  1029. }
  1030. else {
  1031. $has_condition = TRUE;
  1032. $sub_group->condition($clause['field'], $clause['value'], $clause['operator']);
  1033. }
  1034. }
  1035. // Add the item to the filter group.
  1036. if ($group != 0) {
  1037. $has_filter = TRUE;
  1038. $filter_group->condition($sub_group);
  1039. }
  1040. else {
  1041. $has_arguments = TRUE;
  1042. $main_group->condition($sub_group);
  1043. }
  1044. }
  1045. }
  1046. if ($has_filter) {
  1047. $main_group->condition($filter_group);
  1048. }
  1049. if (!$has_arguments && $has_condition) {
  1050. return $filter_group;
  1051. }
  1052. if ($has_arguments && $has_condition) {
  1053. return $main_group;
  1054. }
  1055. }
  1056. /**
  1057. * Build fields array.
  1058. */
  1059. public function compile_fields($fields_array, $query) {
  1060. $non_aggregates = array();
  1061. foreach ($fields_array as $field) {
  1062. $string = '';
  1063. if (!empty($field['table'])) {
  1064. $string .= $field['table'] . '.';
  1065. }
  1066. $string .= $field['field'];
  1067. $fieldname = (!empty($field['alias']) ? $field['alias'] : $string);
  1068. if (!empty($field['distinct'])) {
  1069. throw new Exception("Column-level distinct is not supported anymore.");
  1070. }
  1071. if (!empty($field['count'])) {
  1072. // Retained for compatibility.
  1073. $field['function'] = 'count';
  1074. // It seems there's no way to abstract the table+column reference
  1075. // without adding a field, aliasing, and then using the alias.
  1076. }
  1077. if (!empty($field['function'])) {
  1078. $info = $this->get_aggregation_info();
  1079. if (!empty($info[$field['function']]['method']) && function_exists($info[$field['function']]['method'])) {
  1080. $string = $info[$field['function']]['method']($field['function'], $string);
  1081. $placeholders = !empty($field['placeholders']) ? $field['placeholders'] : array();
  1082. $query->addExpression($string, $fieldname, $placeholders);
  1083. }
  1084. $this->has_aggregate = TRUE;
  1085. }
  1086. // This is a formula, using no tables.
  1087. elseif (empty($field['table'])) {
  1088. if (!in_array($fieldname, $non_aggregates)) {
  1089. $non_aggregates[] = $fieldname;
  1090. }
  1091. $placeholders = !empty($field['placeholders']) ? $field['placeholders'] : array();
  1092. $query->addExpression($string, $fieldname, $placeholders);
  1093. }
  1094. elseif ($this->distinct && !in_array($fieldname, $this->groupby)) {
  1095. // d7cx: This code was there, apparently needed for PostgreSQL
  1096. // $string = db_driver() == 'pgsql' ? "FIRST($string)" : $string;
  1097. if (!in_array($string, $non_aggregates)) {
  1098. $non_aggregates[] = $string;
  1099. }
  1100. $query->addField(!empty($field['table']) ? $field['table'] : $this->base_table, $field['field'], $fieldname);
  1101. }
  1102. elseif (empty($field['aggregate'])) {
  1103. if (!in_array($string, $non_aggregates)) {
  1104. $non_aggregates[] = $string;
  1105. }
  1106. $query->addField(!empty($field['table']) ? $field['table'] : $this->base_table, $field['field'], $fieldname);
  1107. }
  1108. // @todo Remove this old code.
  1109. if (!empty($field['distinct']) && empty($field['function'])) {
  1110. $distinct[] = $string;
  1111. }
  1112. else {
  1113. $fields[] = $string;
  1114. }
  1115. if ($this->get_count_optimized) {
  1116. // We only want the first field in this case.
  1117. break;
  1118. }
  1119. }
  1120. return array(
  1121. $non_aggregates,
  1122. );
  1123. }
  1124. /**
  1125. * Generate a query and a countquery from all of the information supplied
  1126. * to the object.
  1127. *
  1128. * @param bool $get_count
  1129. * Provide a countquery if this is true, otherwise provide a normal query.
  1130. *
  1131. * @return SelectQuery
  1132. * A SelectQuery object.
  1133. */
  1134. public function query($get_count = FALSE) {
  1135. // Check query distinct value.
  1136. if (empty($this->no_distinct) && $this->distinct && !empty($this->fields)) {
  1137. if ($this->pure_distinct === FALSE) {
  1138. $base_field_alias = $this->add_field($this->base_table, $this->base_field);
  1139. $this->add_groupby($base_field_alias);
  1140. }
  1141. $distinct = TRUE;
  1142. }
  1143. // An optimized count query includes just the base field instead of all the
  1144. // fields. Determine of this query qualifies by checking for a groupby or
  1145. // distinct.
  1146. $fields_array = $this->fields;
  1147. if ($get_count && !$this->groupby) {
  1148. foreach ($fields_array as $field) {
  1149. if (!empty($field['distinct']) || !empty($field['function'])) {
  1150. $this->get_count_optimized = FALSE;
  1151. break;
  1152. }
  1153. }
  1154. }
  1155. else {
  1156. $this->get_count_optimized = FALSE;
  1157. }
  1158. if (!isset($this->get_count_optimized)) {
  1159. $this->get_count_optimized = TRUE;
  1160. }
  1161. $options = array();
  1162. $target = 'default';
  1163. $key = 'default';
  1164. // Detect an external database and set the.
  1165. if (isset($this->view->base_database)) {
  1166. $key = $this->view->base_database;
  1167. }
  1168. // Set the slave target if the slave option is set.
  1169. if (!empty($this->options['slave'])) {
  1170. $target = 'slave';
  1171. }
  1172. // Go ahead and build the query. db_select doesn't support to specify the
  1173. // key, so use getConnection directly.
  1174. $query = Database::getConnection($target, $key)
  1175. ->select($this->base_table, $this->base_table, $options)
  1176. ->addTag('views')
  1177. ->addTag('views_' . $this->view->name);
  1178. // Add the tags added to the view itself.
  1179. foreach ($this->tags as $tag) {
  1180. $query->addTag($tag);
  1181. }
  1182. if (!empty($distinct)) {
  1183. $query->distinct();
  1184. }
  1185. $joins = $where = $having = $orderby = $groupby = '';
  1186. $fields = $distinct = array();
  1187. // Add all the tables to the query via joins. We assume all LEFT joins.
  1188. foreach ($this->table_queue as $table) {
  1189. if (is_object($table['join'])) {
  1190. $table['join']->build_join($query, $table, $this);
  1191. }
  1192. }
  1193. $this->has_aggregate = FALSE;
  1194. $non_aggregates = array();
  1195. list($non_aggregates) = $this->compile_fields($fields_array, $query);
  1196. if (count($this->having)) {
  1197. $this->has_aggregate = TRUE;
  1198. }
  1199. elseif (!$this->has_aggregate) {
  1200. // Allow 'GROUP BY' even no aggregation function has been set.
  1201. $this->has_aggregate = $this->view->display_handler->get_option('group_by');
  1202. }
  1203. if ($this->has_aggregate && (!empty($this->groupby) || !empty($non_aggregates))) {
  1204. $groupby = array_unique(array_merge($this->groupby, $non_aggregates));
  1205. foreach ($groupby as $field) {
  1206. $query->groupBy($field);
  1207. }
  1208. if (!empty($this->having) && $condition = $this->build_condition('having')) {
  1209. $query->havingCondition($condition);
  1210. }
  1211. }
  1212. if (!$this->get_count_optimized) {
  1213. // We only add the orderby if we're not counting.
  1214. if ($this->orderby) {
  1215. foreach ($this->orderby as $order) {
  1216. if ($order['field'] == 'rand_') {
  1217. $query->orderRandom();
  1218. }
  1219. else {
  1220. $query->orderBy($order['field'], $order['direction']);
  1221. }
  1222. }
  1223. }
  1224. }
  1225. if (!empty($this->where) && $condition = $this->build_condition('where')) {
  1226. $query->condition($condition);
  1227. }
  1228. // Add a query comment.
  1229. if (!empty($this->options['query_comment'])) {
  1230. $query->comment($this->options['query_comment']);
  1231. }
  1232. // Add the query tags.
  1233. if (!empty($this->options['query_tags'])) {
  1234. foreach ($this->options['query_tags'] as $tag) {
  1235. $query->addTag($tag);
  1236. }
  1237. }
  1238. // Add all query substitutions as metadata.
  1239. $query->addMetaData('views_substitutions', module_invoke_all('views_query_substitutions', $this->view));
  1240. if (!$get_count) {
  1241. if (!empty($this->limit) || !empty($this->offset)) {
  1242. // We can't have an offset without a limit, so provide a very large
  1243. // limit instead.
  1244. $limit = intval(!empty($this->limit) ? $this->limit : 999999);
  1245. $offset = intval(!empty($this->offset) ? $this->offset : 0);
  1246. $query->range($offset, $limit);
  1247. }
  1248. }
  1249. return $query;
  1250. }
  1251. /**
  1252. * Get the arguments attached to the WHERE and HAVING clauses of this query.
  1253. */
  1254. public function get_where_args() {
  1255. $args = array();
  1256. foreach ($this->where as $group => $where) {
  1257. $args = array_merge($args, $where['args']);
  1258. }
  1259. foreach ($this->having as $group => $having) {
  1260. $args = array_merge($args, $having['args']);
  1261. }
  1262. return $args;
  1263. }
  1264. /**
  1265. * Let modules modify the query just prior to finalizing it.
  1266. */
  1267. public function alter(&$view) {
  1268. foreach (module_implements('views_query_alter') as $module) {
  1269. $function = $module . '_views_query_alter';
  1270. $function($view, $this);
  1271. }
  1272. }
  1273. /**
  1274. * Builds the necessary info to execute the query.
  1275. */
  1276. public function build(&$view) {
  1277. // Make the query distinct if the option was set.
  1278. if (!empty($this->options['distinct'])) {
  1279. $this->set_distinct(TRUE, !empty($this->options['pure_distinct']));
  1280. }
  1281. // Store the view in the object to be able to use it later.
  1282. $this->view = $view;
  1283. $view->init_pager();
  1284. // Let the pager modify the query to add limits.
  1285. $this->pager->query();
  1286. $view->build_info['query'] = $this->query();
  1287. $view->build_info['count_query'] = $this->query(TRUE);
  1288. }
  1289. /**
  1290. * Executes the query and fills the associated view object with according
  1291. * values.
  1292. *
  1293. * Values to set: $view->result, $view->total_rows, $view->execute_time,
  1294. * $view->current_page.
  1295. */
  1296. public function execute(&$view) {
  1297. // Whether this query will run against an external database.
  1298. $external = FALSE;
  1299. $query = $view->build_info['query'];
  1300. $count_query = $view->build_info['count_query'];
  1301. $query->addMetaData('view', $view);
  1302. $count_query->addMetaData('view', $view);
  1303. if (empty($this->options['disable_sql_rewrite'])) {
  1304. $base_table_data = views_fetch_data($this->base_table);
  1305. if (isset($base_table_data['table']['base']['access query tag'])) {
  1306. $access_tag = $base_table_data['table']['base']['access query tag'];
  1307. $query->addTag($access_tag);
  1308. $count_query->addTag($access_tag);
  1309. }
  1310. }
  1311. $items = array();
  1312. if ($query) {
  1313. $additional_arguments = module_invoke_all('views_query_substitutions', $view);
  1314. // Count queries must be run through the preExecute() method.
  1315. // If not, then hook_query_node_access_alter() may munge the count by
  1316. // adding a distinct against an empty query string
  1317. // (e.g. COUNT DISTINCT(1) ...) and no pager will return.
  1318. // @see pager.inc > PagerDefault::execute()
  1319. // @see http://api.drupal.org/api/drupal/includes--pager.inc/function/PagerDefault::execute/7
  1320. // @see http://drupal.org/node/1046170.
  1321. $count_query->preExecute();
  1322. // Build the count query.
  1323. $count_query = $count_query->countQuery();
  1324. // Add additional arguments as a fake condition.
  1325. // XXX: this doesn't work... because PDO mandates that all bound arguments
  1326. // are used on the query. TODO: Find a better way to do this.
  1327. if (!empty($additional_arguments)) {
  1328. // $query->where('1 = 1', $additional_arguments);
  1329. // $count_query->where('1 = 1', $additional_arguments);
  1330. }
  1331. $start = microtime(TRUE);
  1332. try {
  1333. if ($this->pager->use_count_query() || !empty($view->get_total_rows)) {
  1334. $this->pager->execute_count_query($count_query);
  1335. }
  1336. $this->pager->pre_execute($query);
  1337. $result = $query->execute();
  1338. $view->result = array();
  1339. foreach ($result as $item) {
  1340. $view->result[] = $item;
  1341. }
  1342. $this->pager->post_execute($view->result);
  1343. if ($this->pager->use_count_query() || !empty($view->get_total_rows)) {
  1344. $view->total_rows = $this->pager->get_total_items();
  1345. }
  1346. }
  1347. catch (Exception $e) {
  1348. $view->result = array();
  1349. if (!empty($view->live_preview)) {
  1350. drupal_set_message($e->getMessage(), 'error');
  1351. }
  1352. else {
  1353. vpr('Exception in @human_name[@view_name]: @message', array('@human_name' => $view->human_name, '@view_name' => $view->name, '@message' => $e->getMessage()));
  1354. }
  1355. }
  1356. }
  1357. else {
  1358. $start = microtime(TRUE);
  1359. }
  1360. $view->execute_time = microtime(TRUE) - $start;
  1361. }
  1362. /**
  1363. *
  1364. */
  1365. public function add_signature(&$view) {
  1366. $view->query->add_field(NULL, "'" . $view->name . ':' . $view->current_display . "'", 'view_name');
  1367. }
  1368. /**
  1369. *
  1370. */
  1371. public function get_aggregation_info() {
  1372. // @todo Need a way to get database specific and customized aggregation
  1373. // functions into here.
  1374. return array(
  1375. 'group' => array(
  1376. 'title' => t('Group results together'),
  1377. 'is aggregate' => FALSE,
  1378. ),
  1379. 'count' => array(
  1380. 'title' => t('Count'),
  1381. 'method' => 'views_query_default_aggregation_method_simple',
  1382. 'handler' => array(
  1383. 'argument' => 'views_handler_argument_group_by_numeric',
  1384. 'field' => 'views_handler_field_numeric',
  1385. 'filter' => 'views_handler_filter_group_by_numeric',
  1386. 'sort' => 'views_handler_sort_group_by_numeric',
  1387. ),
  1388. ),
  1389. 'count_distinct' => array(
  1390. 'title' => t('Count DISTINCT'),
  1391. 'method' => 'views_query_default_aggregation_method_distinct',
  1392. 'handler' => array(
  1393. 'argument' => 'views_handler_argument_group_by_numeric',
  1394. 'field' => 'views_handler_field_numeric',
  1395. 'filter' => 'views_handler_filter_group_by_numeric',
  1396. 'sort' => 'views_handler_sort_group_by_numeric',
  1397. ),
  1398. ),
  1399. 'sum' => array(
  1400. 'title' => t('Sum'),
  1401. 'method' => 'views_query_default_aggregation_method_simple',
  1402. 'handler' => array(
  1403. 'argument' => 'views_handler_argument_group_by_numeric',
  1404. 'filter' => 'views_handler_filter_group_by_numeric',
  1405. 'sort' => 'views_handler_sort_group_by_numeric',
  1406. ),
  1407. ),
  1408. 'avg' => array(
  1409. 'title' => t('Average'),
  1410. 'method' => 'views_query_default_aggregation_method_simple',
  1411. 'handler' => array(
  1412. 'argument' => 'views_handler_argument_group_by_numeric',
  1413. 'filter' => 'views_handler_filter_group_by_numeric',
  1414. 'sort' => 'views_handler_sort_group_by_numeric',
  1415. ),
  1416. ),
  1417. 'min' => array(
  1418. 'title' => t('Minimum'),
  1419. 'method' => 'views_query_default_aggregation_method_simple',
  1420. 'handler' => array(
  1421. 'argument' => 'views_handler_argument_group_by_numeric',
  1422. 'filter' => 'views_handler_filter_group_by_numeric',
  1423. 'sort' => 'views_handler_sort_group_by_numeric',
  1424. ),
  1425. ),
  1426. 'max' => array(
  1427. 'title' => t('Maximum'),
  1428. 'method' => 'views_query_default_aggregation_method_simple',
  1429. 'handler' => array(
  1430. 'argument' => 'views_handler_argument_group_by_numeric',
  1431. 'filter' => 'views_handler_filter_group_by_numeric',
  1432. 'sort' => 'views_handler_sort_group_by_numeric',
  1433. ),
  1434. ),
  1435. 'stddev_pop' => array(
  1436. 'title' => t('Standard deviation'),
  1437. 'method' => 'views_query_default_aggregation_method_simple',
  1438. 'handler' => array(
  1439. 'argument' => 'views_handler_argument_group_by_numeric',
  1440. 'filter' => 'views_handler_filter_group_by_numeric',
  1441. 'sort' => 'views_handler_sort_group_by_numeric',
  1442. ),
  1443. ),
  1444. ) + views_fetch_plugin_data('query_aggregate');
  1445. }
  1446. /**
  1447. * Returns the according entity objects for the given query results.
  1448. */
  1449. public function get_result_entities($results, $relationship = NULL) {
  1450. $base_table = $this->base_table;
  1451. $base_table_alias = $base_table;
  1452. if (!empty($relationship)) {
  1453. foreach ($this->view->relationship as $current) {
  1454. if ($current->alias == $relationship) {
  1455. $base_table = $current->definition['base'];
  1456. $base_table_alias = $relationship;
  1457. break;
  1458. }
  1459. }
  1460. }
  1461. $table_data = views_fetch_data($base_table);
  1462. // Bail out if the table has not specified the according entity-type.
  1463. if (!isset($table_data['table']['entity type'])) {
  1464. return FALSE;
  1465. }
  1466. $entity_type = $table_data['table']['entity type'];
  1467. $info = entity_get_info($entity_type);
  1468. $is_revision = !empty($table_data['table']['revision']);
  1469. $id_alias = $this->get_field_alias($base_table_alias, $info['entity keys'][$is_revision ? 'revision' : 'id']);
  1470. // Assemble the ids of the entities to load.
  1471. $ids = array();
  1472. foreach ($results as $key => $result) {
  1473. if (isset($result->$id_alias)) {
  1474. $ids[$key] = $result->$id_alias;
  1475. }
  1476. }
  1477. if (!$is_revision) {
  1478. $entities = entity_load($entity_type, $ids);
  1479. // Re-key the array by row-index.
  1480. $result = array();
  1481. foreach ($ids as $key => $id) {
  1482. $result[$key] = isset($entities[$id]) ? $entities[$id] : FALSE;
  1483. }
  1484. }
  1485. else {
  1486. // There's no way in core to load revisions in bulk.
  1487. $result = array();
  1488. foreach ($ids as $key => $id) {
  1489. // Nodes can be dealt with in core.
  1490. if ($entity_type == 'node') {
  1491. $result[$key] = node_load(NULL, $id);
  1492. }
  1493. // Otherwise see if entity is enabled.
  1494. elseif (module_exists('entity')) {
  1495. $result[$key] = entity_revision_load($entity_type, $id);
  1496. }
  1497. else {
  1498. // Otherwise this isn't supported.
  1499. watchdog('views', 'Attempt to load a revision on an unsupported entity type @entity_type.', array('@entity_type' => $entity_type), WATCHDOG_WARNING);
  1500. }
  1501. }
  1502. }
  1503. return array($entity_type, $result);
  1504. }
  1505. }
  1506. /**
  1507. *
  1508. */
  1509. function views_query_default_aggregation_method_simple($group_type, $field) {
  1510. return strtoupper($group_type) . '(' . $field . ')';
  1511. }
  1512. /**
  1513. *
  1514. */
  1515. function views_query_default_aggregation_method_distinct($group_type, $field) {
  1516. $group_type = str_replace('_distinct', '', $group_type);
  1517. return strtoupper($group_type) . '(DISTINCT ' . $field . ')';
  1518. }
  1519. /**
  1520. * Validation callback for query tags.
  1521. */
  1522. function views_element_validate_tags($element, &$form_state) {
  1523. $values = array_map('trim', explode(',', $element['#value']));
  1524. foreach ($values as $value) {
  1525. if (preg_match("/[^a-z_]/", $value)) {
  1526. form_error($element, t('The query tags may only contain lower-case alphabetical characters and underscores.'));
  1527. return;
  1528. }
  1529. }
  1530. }