views_field_view_handler_field_view.inc 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. <?php
  2. /**
  3. * @file
  4. * Views field view field handler class.
  5. *
  6. */
  7. class views_field_view_handler_field_view extends views_handler_field {
  8. /**
  9. * If query aggregation is used, all of the arguments for the child view.
  10. *
  11. * This is a multidimensional array containing field_aliases for the argument's
  12. * fields and containing a linear array of all of the results to be used as
  13. * arguments in various fields.
  14. */
  15. public $child_arguments = array();
  16. /**
  17. * If query aggregation is used, this attribute contains an array of the results
  18. * of the aggregated child views.
  19. */
  20. public $child_view_results = array();
  21. /**
  22. * If query aggregation is enabled, one instance of the child view to be reused.
  23. *
  24. * Note, it should never contain arguments or results because they will be
  25. * injected into it for rendering.
  26. */
  27. public $child_view = FALSE;
  28. /**
  29. * Disable this handler from being used as a 'group by'.
  30. */
  31. function use_string_group_by() {
  32. return FALSE;
  33. }
  34. function option_definition() {
  35. $options = parent::option_definition();
  36. $options['view'] = array('default' => '');
  37. $options['display'] = array('default' => 'default');
  38. $options['arguments'] = array('default' => '');
  39. $options['query_aggregation'] = array('default' => FALSE, 'bool' => TRUE);
  40. return $options;
  41. }
  42. function options_form(&$form, &$form_state) {
  43. parent::options_form($form, $form_state);
  44. $view_options = views_get_views_as_options(TRUE);
  45. $form['views_field_view'] = array(
  46. '#type' => 'fieldset',
  47. '#title' => t("View settings"),
  48. '#collapsible' => TRUE,
  49. '#collapsed' => FALSE,
  50. );
  51. $form['view'] = array(
  52. '#type' => 'select',
  53. '#title' => t('View'),
  54. '#description' => t('Select a view to embed.'),
  55. '#default_value' => $this->options['view'],
  56. '#options' => $view_options,
  57. '#ajax' => array(
  58. 'path' => views_ui_build_form_url($form_state),
  59. ),
  60. '#submit' => array('views_ui_config_item_form_submit_temporary'),
  61. '#executes_submit_callback' => TRUE,
  62. '#fieldset' => 'views_field_view',
  63. );
  64. // If there is no view set, use the first one for now.
  65. if (count($view_options) && empty($this->options['view'])) {
  66. $this->options['view'] = reset(array_keys($view_options));
  67. }
  68. if ($this->options['view']) {
  69. $view = views_get_view($this->options['view']);
  70. $display_options = array();
  71. foreach ($view->display as $name => $display) {
  72. // Allow to embed a different display as the current one.
  73. if ($this->options['view'] != $this->view->name || ($this->view->current_display != $name)) {
  74. $display_options[$name] = $display->display_title;
  75. }
  76. }
  77. $form['display'] = array(
  78. '#type' => 'select',
  79. '#title' => t('Display'),
  80. '#description' => t('Select a view display to use.'),
  81. '#default_value' => $this->options['display'],
  82. '#options' => $display_options,
  83. '#ajax' => array(
  84. 'path' => views_ui_build_form_url($form_state),
  85. ),
  86. '#submit' => array('views_ui_config_item_form_submit_temporary'),
  87. '#executes_submit_callback' => TRUE,
  88. '#fieldset' => 'views_field_view',
  89. );
  90. // Provide a way to directly access the views edit link of the child view.
  91. // Don't show this link if the current view is the selected child view.
  92. if ($this->options['view'] && $this->options['display'] && ($this->view->name != $this->options['view'])) {
  93. // use t() here, and set HTML on #link options.
  94. $link_text = t('Edit "%view (@display)" view', array('%view' => $view_options[$this->options['view']], '@display' => $this->options['display']));
  95. $form['view_edit'] = array(
  96. '#type' => 'container',
  97. '#fieldset' => 'views_field_view',
  98. );
  99. $form['view_edit']['view_edit_link'] = array(
  100. '#theme' => 'link',
  101. '#text' => $link_text,
  102. '#path' => 'admin/structure/views/view/' . $this->options['view'] . '/edit/' . $this->options['display'],
  103. '#options' => array(
  104. 'attributes' => array(
  105. 'target' => '_blank',
  106. 'class' => array('views-field-view-child-view-edit'),
  107. ),
  108. 'html' => TRUE,
  109. ),
  110. '#attached' => array(
  111. 'css' => array(
  112. drupal_get_path('module', 'views_field_view') . '/views_field_view.css',
  113. ),
  114. ),
  115. '#prefix' => '<span>[</span>',
  116. '#suffix' => '<span>]</span>',
  117. );
  118. $form['view_edit']['description'] = array(
  119. '#markup' => t('Use this link to open the current child view\'s edit page in a new window.'),
  120. '#prefix' => '<div class="description">',
  121. '#suffix' => '</div>',
  122. );
  123. }
  124. $form['arguments'] = array(
  125. '#title' => t('Contextual filters'),
  126. '#description' => t('Use a comma (,) or forwardslash (/) separated list of each contextual filter which should be forwared to the view.
  127. See below list of available replacement tokens. Static values are also be passed to child views if they do not match a token format.
  128. You could pass static ID\'s or taxonomy terms in this way. E.g. 123 or "my taxonomy term".'),
  129. '#type' => 'textfield',
  130. '#default_value' => $this->options['arguments'],
  131. '#fieldset' => 'views_field_view',
  132. );
  133. $form['available_tokens'] = array(
  134. '#type' => 'fieldset',
  135. '#title' => t('Replacement patterns'),
  136. '#collapsible' => TRUE,
  137. '#collapsed' => TRUE,
  138. '#value' => $this->get_token_info(),
  139. '#fieldset' => 'views_field_view',
  140. );
  141. // It doesn't make sense to allow aggregation unless it's a field handler.
  142. if (($this->handler_type == 'field')) {
  143. $form['query_aggregation'] = array(
  144. '#title' => t('Aggregate queries'),
  145. '#description' => t('Views Field View usually runs a separate query for each instance of this field on each row and that can mean a lot of queries.
  146. This option attempts to aggregate these queries into one query per instance of this field (regardless of how many rows are displayed).
  147. <strong>Currently child views must be configured to "Display all results for the specified field" if no contextual filter is present and
  148. query aggregation is enabled.</strong>. This may only work on simple views, please test thoroughly.'),
  149. '#type' => 'checkbox',
  150. '#default_value' => $this->options['query_aggregation'],
  151. '#fieldset' => 'views_field_view',
  152. );
  153. }
  154. // Ensure we're working with a SQL view.
  155. $views_data = views_fetch_data($view->base_table);
  156. if ($views_data['table']['base']['query class'] == 'views_query') {
  157. $form['query_aggregation']['#disabled'] = TRUE;
  158. }
  159. }
  160. $form['alter']['#access'] = FALSE;
  161. }
  162. function query() {
  163. $this->add_additional_fields();
  164. }
  165. /**
  166. * Run before any fields are rendered.
  167. *
  168. * This gives the handlers some time to set up before any handler has
  169. * been rendered.
  170. *
  171. * @param array $values
  172. * An array of all objects returned from the query.
  173. */
  174. function pre_render(&$values) {
  175. // Only act if we are attempting to aggregate all of the field
  176. // instances into a single query.
  177. if ($this->options['view'] && $this->options['query_aggregation']) {
  178. // Note: Unlike render, pre_render will be run exactly once per
  179. // views_field_view field (not once for each row).
  180. $child_view_name = $this->options['view'];
  181. $child_view_display = $this->options['display'];
  182. // Add each argument token configured for this view_field.
  183. foreach ($this->split_tokens($this->options['arguments']) as $token) {
  184. // Remove the brackets around the token etc..
  185. $token_info = $this->get_token_argument($token);
  186. $argument = $token_info['arg'];
  187. $token_type = $token_info['type'];
  188. // Collect all of the values that we intend to use as arguments of our single query.
  189. // TODO: Get this to be handled by get_token_value() method too.
  190. if (isset($this->view->field[$argument])) {
  191. if (isset($this->view->field[$argument]->field_info)) {
  192. $field_alias = 'field_' . $this->view->field[$argument]->field;
  193. $field_key = key($this->view->field[$argument]->field_info['columns']);
  194. }
  195. elseif (isset($this->view->field[$argument]->field_alias)) {
  196. $field_alias = $this->view->field[$argument]->field_alias;
  197. $field_key = 'value';
  198. }
  199. foreach ($values as $value) {
  200. if (isset($value->$field_alias)) {
  201. $this->child_arguments[$field_alias]['argument_name'] = $field_alias;
  202. if (is_array($value->$field_alias)) {
  203. $field_values = array();
  204. foreach ($value->$field_alias as $field_item) {
  205. switch ($token_type) {
  206. case '%':
  207. $field_values[] = $field_item['rendered']['#markup'];
  208. break;
  209. case '!':
  210. default:
  211. $field_values[] = $field_item['raw'][$field_key];
  212. }
  213. }
  214. $field_value = (count($field_values) > 1) ? $field_values : reset($field_values);
  215. $this->child_arguments[$field_alias]['values'][] = $field_value;
  216. }
  217. else {
  218. $this->child_arguments[$field_alias]['values'][] = $value->$field_alias;
  219. }
  220. }
  221. }
  222. }
  223. }
  224. // If we don't have child arguments we should not try to do any of our magic.
  225. if (count($this->child_arguments)) {
  226. // Cache the child_view in this object to minize our calls to views_get_view.
  227. $this->child_view = views_get_view($child_view_name);
  228. $child_view = $this->child_view;
  229. // Set the appropriate display.
  230. $child_view->access($child_view_display);
  231. // Find the arguments on the child view that we're going to need if the
  232. // arguments have been overridden.
  233. foreach ($child_view->display['default']->display_options['arguments'] as $argument_name => $argument_value) {
  234. if (isset($child_view->display[$child_view_display]->display_options['arguments'][$argument_name])) {
  235. $configured_arguments[$argument_name] = $child_view->display[$child_view_display]->display_options['arguments'][$argument_name];
  236. }
  237. else {
  238. $configured_arguments[$argument_name] = $child_view->display['default']->display_options['arguments'][$argument_name];
  239. }
  240. }
  241. $argument_ids = array();
  242. foreach ($this->child_arguments as $child_argument_name => $child_argument) {
  243. // Work with the arguments on the child view in the order they are
  244. // specified in our views_field_view field settings.
  245. $configured_argument = array_shift($configured_arguments);
  246. // To be able to later split up our results among the appropriate rows,
  247. // we need to add whatever argument fields we're using to the query.
  248. $argument_ids[$child_argument_name] = $child_view->add_item($child_view_display, 'field', $configured_argument['table'], $configured_argument['field'], array('exclude' => TRUE));
  249. if (isset($child_view->pager['items_per_page'])) {
  250. $child_view->pager['items_per_page'] = 0;
  251. }
  252. $child_view->build();
  253. // Add the WHERE IN clause to this query.
  254. $child_view->query->add_where(0, $configured_argument['table'] . '.' . $configured_argument['field'], $child_argument['values']);
  255. }
  256. // Initialize the query object so that we have it to alter.
  257. // The child view may have been limited but our result set here should not be.
  258. $child_view->build_info['query'] = $child_view->query->query();
  259. $child_view->build_info['count_query'] = $child_view->query->query(TRUE);
  260. $child_view->build_info['query_args'] = $child_view->query->get_where_args();
  261. // Execute the query to retrieve the results.
  262. $child_view->execute();
  263. // Now that the query has run, we need to get the field alias for each argument field
  264. // so that it can be identified later.
  265. foreach ($argument_ids as $child_argument_name => $argument_id) {
  266. $child_alias = (isset($child_view->field[$argument_id]->field_alias) && $child_view->field[$argument_id]->field_alias !== 'unknown') ? $child_view->field[$argument_id]->field_alias : $child_view->field[$argument_id]->real_field;
  267. $this->child_arguments[$child_argument_name]['child_view_field_alias'] = $child_alias;
  268. }
  269. $results = $child_view->result;
  270. // Finally: Cache the results so that they're easily accessible for the render function.
  271. // Loop through the results from the main view so that we can cache the results
  272. // relevant to each row.
  273. foreach ($values as $value) {
  274. // Add an element to the child_view_results array for each of the rows keyed by this view's base_field.
  275. $this->child_view_results[$value->{$this->view->base_field}] = array();
  276. $child_view_result_row =& $this->child_view_results[$value->{$this->view->base_field}];
  277. // Loop through the actual result set looking for matches to these arguments.
  278. foreach ($results as $result) {
  279. // Assume that we have a matching item until we know that we don't.
  280. $matching_item = TRUE;
  281. // Check each argument that we care about to ensure that it matches.
  282. foreach ($this->child_arguments as $child_argument_field_alias => $child_argument) {
  283. // If one of our arguments does not match the argument of this field,
  284. // do not add it to this row.
  285. if (isset($value->$child_argument_field_alias) && $value->$child_argument_field_alias != $result->{$child_argument['child_view_field_alias']}) {
  286. $matching_item = FALSE;
  287. }
  288. }
  289. if ($matching_item) {
  290. $child_view_result_row[] = $result;
  291. }
  292. }
  293. // Make a best effort attempt at paging.
  294. if (isset($this->child_view->pager['items_per_page'])) {
  295. $item_limit = $this->child_view->pager['items_per_page'];
  296. // If the item limit exists but is set to zero, do not split up the results.
  297. if ($item_limit != 0) {
  298. $results = array_chunk($results, $item_limit);
  299. $offset = (isset($this->child_view->pager['offset']) ? $this->child_view->pager['offset'] : 0);
  300. $results = $results[$offset];
  301. }
  302. }
  303. unset($child_view_result_row);
  304. }
  305. // We have essentially built and executed the child view member of this view.
  306. // Set it accordingly so that it is not rebuilt during the rendering of each row below.
  307. $this->child_view->built = TRUE;
  308. $this->child_view->executed = TRUE;
  309. }
  310. }
  311. }
  312. function render($values) {
  313. $output = NULL;
  314. // If it's not a field handler and there are no values
  315. // Get the first result row from the view and use that.
  316. if (($this->handler_type !== 'field') && empty($values) && isset($this->view->result)) {
  317. $values = reset($this->view->result);
  318. }
  319. static $running = array();
  320. // Protect against the evil / recursion.
  321. // Set the variable for yourself, this is not for the normal "user".
  322. if (empty($running[$this->options['view']][$this->options['display']]) || variable_get('views_field_view_evil', FALSE)) {
  323. if ($this->options['view'] && !$this->options['query_aggregation']) {
  324. $running[$this->options['view']][$this->options['display']] = TRUE;
  325. $args = array();
  326. // Only perform this loop if there are actually arguments present.
  327. if (!empty($this->options['arguments'])) {
  328. // Create array of tokens.
  329. foreach ($this->split_tokens($this->options['arguments']) as $token) {
  330. $args[] = $this->get_token_value($token, $values, $this->view);
  331. }
  332. }
  333. // get view etc… and execute.
  334. $view = views_get_view($this->options['view']);
  335. // Only execute and render the view if the user has access.
  336. if ($view->access($this->options['display'])) {
  337. $view->set_display($this->options['display']);
  338. if ($view->display_handler->use_pager()) {
  339. // Check whether the pager IDs should be rewritten.
  340. $view->init_query();
  341. // Find a proper start value for the ascening pager IDs.
  342. $start = 0;
  343. $pager = $view->display_handler->get_option('pager');
  344. if (isset($this->query->pager->options)) {
  345. $start = (int) $this->query->pager->options['id'];
  346. }
  347. // Set the pager ID before initializing the pager, so
  348. // views_plugin_pager::set_current_page works as expected, which is
  349. // called from view::init_pager()
  350. $pager['options']['id'] = $start + 1 + $this->view->row_index;
  351. $view->display_handler->set_option('pager', $pager);
  352. $view->init_pager();
  353. }
  354. $view->pre_execute($args);
  355. $view->execute();
  356. // If there are no results and hide_empty is set.
  357. if (empty($view->result) && $this->options['hide_empty']) {
  358. $output = '';
  359. }
  360. // Else just call render on the view object.
  361. else {
  362. $output = $view->render();
  363. }
  364. }
  365. $running[$this->options['view']][$this->options['display']] = FALSE;
  366. }
  367. // Verify we have a child view (if there were no arguments specified we
  368. // won't have one), and that query aggregation was enabled.
  369. elseif ($this->child_view && $this->options['view'] && $this->options['query_aggregation']) {
  370. $running[$this->options['view']][$this->options['display']] = TRUE;
  371. $child_view = $this->child_view;
  372. // Only execute and render the view if the user has access.
  373. if ($child_view->access($this->options['display'])) {
  374. $results = $this->child_view_results[$values->{$this->view->base_field}];
  375. // If there are no results and hide_empty is set.
  376. if (empty($results) && $this->options['hide_empty']) {
  377. $output = '';
  378. }
  379. else {
  380. // Inject the appropriate result set before rendering the view.
  381. $child_view->result = $results;
  382. if (isset($child_view->style_plugin->rendered_fields)) {
  383. unset($child_view->style_plugin->rendered_fields);
  384. }
  385. $output = $child_view->render();
  386. }
  387. $running[$this->options['view']][$this->options['display']] = FALSE;
  388. }
  389. }
  390. }
  391. else {
  392. $output = t('Recursion, stop!');
  393. }
  394. if (!empty($output)) {
  395. // Add the rendered output back to the $values object
  396. // so it is available in $view->result objects.
  397. $values->{'views_field_view_' . $this->options['id']} = $output;
  398. }
  399. return $output;
  400. }
  401. /**
  402. * Get field values from tokens.
  403. *
  404. * @param string $token
  405. * token string. E.g. explode(',', $this->options['args']);
  406. * @param View $view
  407. * Full view object to get token values from.
  408. *
  409. * @return array
  410. * An array of raw argument values, returned in the same order as the token
  411. * were passed in.
  412. */
  413. function get_token_value($token, $values, $view) {
  414. $token_info = $this->get_token_argument($token);
  415. $arg = $token_info['arg'];
  416. $token_type = $token_info['type'];
  417. // Collect all of the values that we intend to use as arguments of our single query.
  418. if (isset($view->field[$arg])) {
  419. switch ($token_type) {
  420. case '%':
  421. $value = $view->field[$arg]->last_render;
  422. break;
  423. case '!':
  424. default:
  425. $value = $view->field[$arg]->get_value($values);
  426. break;
  427. }
  428. }
  429. elseif (isset($view->args[$arg - 1])) {
  430. switch ($token_type) {
  431. case '%':
  432. // Get an array of argument keys. So we can use the index as an
  433. // identifier.
  434. $keys = array_keys($view->argument);
  435. $value = $view->argument[$keys[$arg - 1]]->get_title();
  436. break;
  437. case '!':
  438. default:
  439. $value = $view->args[$arg - 1];
  440. break;
  441. }
  442. }
  443. else {
  444. $value = check_plain(trim($token, '\'"'));
  445. }
  446. return $value;
  447. }
  448. /**
  449. * Return the argument type and raw argument from a token.
  450. * E.g. [!test_token] will return "array('type' => '!', 'arg' => test_token)".
  451. *
  452. * @param string $token
  453. * A single token string.
  454. *
  455. * @return array
  456. * An array containing type and arg (As described above).
  457. */
  458. function get_token_argument($token) {
  459. // Trim whitespace and remove the brackets around the token.
  460. $argument = trim(trim($token), '[]');
  461. $diff = ltrim($argument, '!..%');
  462. $token_type = '';
  463. if ($argument != $diff) {
  464. $token_type = $argument[0];
  465. // Make the new argument the diff (without token type character).
  466. $argument = $diff;
  467. }
  468. return array(
  469. 'type' => $token_type,
  470. 'arg' => $argument,
  471. );
  472. }
  473. /**
  474. * Returns array of tokens/values to be used in child views.
  475. * String containing tokens is split on either "," or "/" characters.
  476. *
  477. * @param string $token_string
  478. * The string of tokens to split.
  479. *
  480. * @return array
  481. * An array of split token strings.
  482. */
  483. function split_tokens($token_string) {
  484. return preg_split('/,|\//', $token_string);
  485. }
  486. /**
  487. * Get available field tokens, code/logic stolen from views_handler_field.inc.
  488. *
  489. * @return string
  490. * A full HTML string, containing a list of available tokens.
  491. */
  492. public function get_token_info() {
  493. // Get a list of the available fields and arguments for token replacement.
  494. $options = array();
  495. foreach ($this->view->display_handler->get_handlers('field') as $field => $handler) {
  496. $options[t('Fields')]["[!$field]"] = $handler->ui_name() . ' (' . t('raw') . ')';
  497. $options[t('Fields')]["[%$field]"] = $handler->ui_name() . ' (' . t('rendered') . ')';
  498. // We only use fields up to (and including) this one.
  499. if ($field == $this->options['id']) {
  500. break;
  501. }
  502. }
  503. // This lets us prepare the key as we want it printed.
  504. $count = 0;
  505. foreach ($this->view->display_handler->get_handlers('argument') as $arg => $handler) {
  506. $options[t('Arguments')]['%' . ++$count] = t('@argument title', array('@argument' => $handler->ui_name()));
  507. $options[t('Arguments')]['!' . $count] = t('@argument input', array('@argument' => $handler->ui_name()));
  508. }
  509. // Add replacements for query string parameters.
  510. foreach ($_GET as $param => $val) {
  511. if (is_array($val)) {
  512. $val = implode(', ', $val);
  513. }
  514. $options[t('Query string')]["[%$param]"] = strip_tags(decode_entities($val));
  515. }
  516. $this->document_self_tokens($options[t('Fields')]);
  517. // Default text.
  518. $output = '<p>' . t('You must add some additional fields to this display before using this field.
  519. These fields may be marked as <em>Exclude from display</em> if you prefer. Note that due to rendering order,
  520. you cannot use fields that come after this field; if you need a field not listed here, rearrange your fields.') . '</p>';
  521. // We have some options, so make a list.
  522. if (!empty($options)) {
  523. $output = '<p>' . t('The following tokens are available for this field. Note that due to rendering order,
  524. you cannot use fields that come after this field; if you need a field that is not listed here, re-arrange your fields.') . '</p>';
  525. foreach (array_keys($options) as $type) {
  526. if (!empty($options[$type])) {
  527. $items = array();
  528. foreach ($options[$type] as $key => $value) {
  529. $items[] = $key . ' == ' . $value;
  530. }
  531. $output .= theme('item_list',
  532. array(
  533. 'items' => $items,
  534. 'type' => $type
  535. ));
  536. }
  537. }
  538. }
  539. $output .= '<p><em>' . t('Using rendered (%) tokens can cause unexpected behaviour, as this will use the last output of the field.
  540. This could be re written output also. If no prefix is used in the token pattern, "!" will be used as a default.') . '</em></p>';
  541. return $output;
  542. }
  543. } // views_field_view_handler_field_view.