views_plugin_style.inc 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. <?php
  2. /**
  3. * @file
  4. * Definition of views_plugin_style.
  5. */
  6. /**
  7. * @defgroup views_style_plugins Views style plugins
  8. * @{
  9. * Style plugins control how a view is rendered. For example, they can choose to
  10. * display a collection of fields, node_view() output, table output, or any kind
  11. * of crazy output they want.
  12. *
  13. * Many style plugins can have an optional 'row' plugin, that displays a single
  14. * record. Not all style plugins can utilize this, so it is up to the plugin to
  15. * set this up and call through to the row plugin.
  16. *
  17. * @see hook_views_plugins()
  18. */
  19. /**
  20. * Base class to define a style plugin handler.
  21. */
  22. class views_plugin_style extends views_plugin {
  23. /**
  24. * Store all available tokens row rows.
  25. */
  26. public $row_tokens = array();
  27. /**
  28. * The row plugin, if it's initialized and the style itself supports it.
  29. *
  30. * @var views_plugin_row
  31. */
  32. public $row_plugin;
  33. /**
  34. * Initialize a style plugin.
  35. *
  36. * @param view $view
  37. * @param object $display
  38. * @param array $options
  39. * The style options might come externally as the style can be sourced
  40. * from at least two locations. If it's not included, look on the display.
  41. */
  42. public function init(&$view, &$display, $options = NULL) {
  43. $this->view = &$view;
  44. $this->display = &$display;
  45. // Overlay incoming options on top of defaults
  46. $this->unpack_options($this->options, isset($options) ? $options : $display->handler->get_option('style_options'));
  47. if ($this->uses_row_plugin() && $display->handler->get_option('row_plugin')) {
  48. $this->row_plugin = $display->handler->get_plugin('row');
  49. }
  50. $this->options += array(
  51. 'grouping' => array(),
  52. );
  53. $this->definition += array(
  54. 'uses grouping' => TRUE,
  55. );
  56. }
  57. /**
  58. *
  59. */
  60. public function destroy() {
  61. parent::destroy();
  62. if (isset($this->row_plugin)) {
  63. $this->row_plugin->destroy();
  64. }
  65. }
  66. /**
  67. * Return TRUE if this style also uses a row plugin.
  68. */
  69. public function uses_row_plugin() {
  70. return !empty($this->definition['uses row plugin']);
  71. }
  72. /**
  73. * Return TRUE if this style also uses a row plugin.
  74. */
  75. public function uses_row_class() {
  76. return !empty($this->definition['uses row class']);
  77. }
  78. /**
  79. * Return TRUE if this style also uses fields.
  80. *
  81. * @return bool
  82. */
  83. public function uses_fields() {
  84. // If we use a row plugin, ask the row plugin. Chances are, we don't
  85. // care, it does.
  86. $row_uses_fields = FALSE;
  87. if ($this->uses_row_plugin() && !empty($this->row_plugin)) {
  88. $row_uses_fields = $this->row_plugin->uses_fields();
  89. }
  90. // Otherwise, check the definition or the option.
  91. return $row_uses_fields || !empty($this->definition['uses fields']) || !empty($this->options['uses_fields']);
  92. }
  93. /**
  94. * Return TRUE if this style uses tokens.
  95. *
  96. * Used to ensure we don't fetch tokens when not needed for performance.
  97. */
  98. public function uses_tokens() {
  99. if ($this->uses_row_class()) {
  100. $class = $this->options['row_class'];
  101. if (strpos($class, '[') !== FALSE || strpos($class, '!') !== FALSE || strpos($class, '%') !== FALSE) {
  102. return TRUE;
  103. }
  104. }
  105. }
  106. /**
  107. * Return the token replaced row class for the specified row.
  108. */
  109. public function get_row_class($row_index) {
  110. if ($this->uses_row_class()) {
  111. $class = $this->options['row_class'];
  112. if ($this->uses_fields() && $this->view->field) {
  113. $classes = array();
  114. // Explode the value by whitespace, this allows the function to handle
  115. // a single class name and multiple class names that are then tokenized.
  116. foreach (explode(' ', $class) as $token_class) {
  117. $classes = array_merge($classes, explode(' ', strip_tags($this->tokenize_value($token_class, $row_index))));
  118. }
  119. }
  120. else {
  121. $classes = explode(' ', $class);
  122. }
  123. // Convert whatever the result is to a nice clean class name
  124. foreach ($classes as &$class) {
  125. $class = drupal_clean_css_identifier($class);
  126. }
  127. return implode(' ', $classes);
  128. }
  129. }
  130. /**
  131. * Take a value and apply token replacement logic to it.
  132. */
  133. public function tokenize_value($value, $row_index) {
  134. if (strpos($value, '[') !== FALSE || strpos($value, '!') !== FALSE || strpos($value, '%') !== FALSE) {
  135. $fake_item = array(
  136. 'alter_text' => TRUE,
  137. 'text' => $value,
  138. );
  139. // Row tokens might be empty, for example for node row style.
  140. $tokens = isset($this->row_tokens[$row_index]) ? $this->row_tokens[$row_index] : array();
  141. if (!empty($this->view->build_info['substitutions'])) {
  142. $tokens += $this->view->build_info['substitutions'];
  143. }
  144. if ($tokens) {
  145. $value = strtr($value, $tokens);
  146. }
  147. }
  148. return $value;
  149. }
  150. /**
  151. * Should the output of the style plugin be rendered even if it's empty.
  152. */
  153. public function even_empty() {
  154. return !empty($this->definition['even empty']);
  155. }
  156. /**
  157. * {@inheritdoc}
  158. */
  159. public function option_definition() {
  160. $options = parent::option_definition();
  161. $options['grouping'] = array('default' => array());
  162. if ($this->uses_row_class()) {
  163. $options['row_class'] = array('default' => '');
  164. $options['default_row_class'] = array('default' => TRUE, 'bool' => TRUE);
  165. $options['row_class_special'] = array('default' => TRUE, 'bool' => TRUE);
  166. }
  167. $options['uses_fields'] = array('default' => FALSE, 'bool' => TRUE);
  168. return $options;
  169. }
  170. /**
  171. * {@inheritdoc}
  172. */
  173. public function options_form(&$form, &$form_state) {
  174. parent::options_form($form, $form_state);
  175. // Only fields-based views can handle grouping. Style plugins can also
  176. // exclude themselves from being groupable by setting their "use grouping"
  177. // definition key to FALSE.
  178. // @todo Document "uses grouping" in docs.php when docs.php is written.
  179. if ($this->uses_fields() && $this->definition['uses grouping']) {
  180. $options = array('' => t('- None -'));
  181. $field_labels = $this->display->handler->get_field_labels(TRUE);
  182. $options += $field_labels;
  183. // If there are no fields, we can't group on them.
  184. if (count($options) > 1) {
  185. // This is for backward compatibility, when there was just a single
  186. // select form.
  187. if (is_string($this->options['grouping'])) {
  188. $grouping = $this->options['grouping'];
  189. $this->options['grouping'] = array();
  190. $this->options['grouping'][0]['field'] = $grouping;
  191. }
  192. if (isset($this->options['group_rendered']) && is_string($this->options['group_rendered'])) {
  193. $this->options['grouping'][0]['rendered'] = $this->options['group_rendered'];
  194. unset($this->options['group_rendered']);
  195. }
  196. $c = count($this->options['grouping']);
  197. // Add a form for every grouping, plus one.
  198. for ($i = 0; $i <= $c; $i++) {
  199. $grouping = !empty($this->options['grouping'][$i]) ? $this->options['grouping'][$i] : array();
  200. $grouping += array('field' => '', 'rendered' => TRUE, 'rendered_strip' => FALSE);
  201. $form['grouping'][$i]['field'] = array(
  202. '#type' => 'select',
  203. '#title' => t('Grouping field Nr.@number', array('@number' => $i + 1)),
  204. '#options' => $options,
  205. '#default_value' => $grouping['field'],
  206. '#description' => t('You may optionally specify a field by which to group the records. Leave blank to not group.'),
  207. );
  208. $form['grouping'][$i]['rendered'] = array(
  209. '#type' => 'checkbox',
  210. '#title' => t('Use rendered output to group rows'),
  211. '#default_value' => $grouping['rendered'],
  212. '#description' => t('If enabled the rendered output of the grouping field is used to group the rows.'),
  213. '#dependency' => array(
  214. 'edit-style-options-grouping-' . $i . '-field' => array_keys($field_labels),
  215. )
  216. );
  217. $form['grouping'][$i]['rendered_strip'] = array(
  218. '#type' => 'checkbox',
  219. '#title' => t('Remove tags from rendered output'),
  220. '#default_value' => $grouping['rendered_strip'],
  221. '#description' => t('Some modules add HTML to the rendered output and prevent the rows from grouping correctly. Stripping the HTML tags should correct this.'),
  222. '#dependency' => array(
  223. 'edit-style-options-grouping-' . $i . '-field' => array_keys($field_labels),
  224. )
  225. );
  226. }
  227. }
  228. }
  229. if ($this->uses_row_class()) {
  230. $form['row_class'] = array(
  231. '#title' => t('Row class'),
  232. '#description' => t('The class to provide on each row.'),
  233. '#type' => 'textfield',
  234. '#default_value' => $this->options['row_class'],
  235. );
  236. if ($this->uses_fields()) {
  237. $form['row_class']['#description'] .= ' ' . t('You may use field tokens from as per the "Replacement patterns" used in "Rewrite the output of this field" for all fields.');
  238. }
  239. $form['default_row_class'] = array(
  240. '#title' => t('Add views row classes'),
  241. '#description' => t('Add the default row classes like views-row-1 to the output. You can use this to quickly reduce the amount of markup the view provides by default, at the cost of making it more difficult to apply CSS.'),
  242. '#type' => 'checkbox',
  243. '#default_value' => $this->options['default_row_class'],
  244. );
  245. $form['row_class_special'] = array(
  246. '#title' => t('Add striping (odd/even), first/last row classes'),
  247. '#description' => t('Add css classes to the first and last line, as well as odd/even classes for striping.'),
  248. '#type' => 'checkbox',
  249. '#default_value' => $this->options['row_class_special'],
  250. );
  251. }
  252. if (!$this->uses_fields() || !empty($this->options['uses_fields'])) {
  253. $form['uses_fields'] = array(
  254. '#type' => 'checkbox',
  255. '#title' => t('Force using fields'),
  256. '#description' => t('If neither the row nor the style plugin supports fields, this field allows to enable them, so you can for example use groupby.'),
  257. '#default_value' => $this->options['uses_fields'],
  258. );
  259. }
  260. }
  261. /**
  262. * {@inheritdoc}
  263. */
  264. public function options_validate(&$form, &$form_state) {
  265. // Don't run validation on style plugins without the grouping setting.
  266. if (isset($form_state['values']['style_options']['grouping'])) {
  267. // Don't save grouping if no field is specified.
  268. foreach ($form_state['values']['style_options']['grouping'] as $index => $grouping) {
  269. if (empty($grouping['field'])) {
  270. unset($form_state['values']['style_options']['grouping'][$index]);
  271. }
  272. }
  273. }
  274. }
  275. /**
  276. * Called by the view builder to see if this style handler wants to
  277. * interfere with the sorts. If so it should build; if it returns
  278. * any non-TRUE value, normal sorting will NOT be added to the query.
  279. */
  280. public function build_sort() {
  281. return TRUE;
  282. }
  283. /**
  284. * Called by the view builder to let the style build a second set of
  285. * sorts that will come after any other sorts in the view.
  286. */
  287. public function build_sort_post() {
  288. }
  289. /**
  290. * Allow the style to do stuff before each row is rendered.
  291. *
  292. * @param array $result
  293. * The full array of results from the query.
  294. */
  295. public function pre_render($result) {
  296. if (!empty($this->row_plugin)) {
  297. $this->row_plugin->pre_render($result);
  298. }
  299. }
  300. /**
  301. * Render the display in this style.
  302. */
  303. public function render() {
  304. if ($this->uses_row_plugin() && empty($this->row_plugin)) {
  305. debug('views_plugin_style_default: Missing row plugin');
  306. return;
  307. }
  308. // Group the rows according to the grouping instructions, if specified.
  309. $sets = $this->render_grouping(
  310. $this->view->result,
  311. $this->options['grouping'],
  312. TRUE
  313. );
  314. return $this->render_grouping_sets($sets);
  315. }
  316. /**
  317. * Render the grouping sets.
  318. *
  319. * Plugins may override this method if they wish some other way of handling
  320. * grouping.
  321. *
  322. * @param array $sets
  323. * Array containing the grouping sets to render.
  324. * @param int $level
  325. * Integer indicating the hierarchical level of the grouping.
  326. *
  327. * @return string
  328. * Rendered output of given grouping sets.
  329. */
  330. public function render_grouping_sets($sets, $level = 0) {
  331. $output = '';
  332. foreach ($sets as $set) {
  333. $row = reset($set['rows']);
  334. // Render as a grouping set.
  335. if (is_array($row) && isset($row['group'])) {
  336. $output .= theme(views_theme_functions('views_view_grouping', $this->view, $this->display),
  337. array(
  338. 'view' => $this->view,
  339. 'grouping' => $this->options['grouping'][$level],
  340. 'grouping_level' => $level,
  341. 'rows' => $set['rows'],
  342. 'title' => $set['group'])
  343. );
  344. }
  345. // Render as a record set.
  346. else {
  347. if ($this->uses_row_plugin()) {
  348. foreach ($set['rows'] as $index => $row) {
  349. $this->view->row_index = $index;
  350. $set['rows'][$index] = $this->row_plugin->render($row);
  351. }
  352. }
  353. $output .= theme($this->theme_functions(),
  354. array(
  355. 'view' => $this->view,
  356. 'options' => $this->options,
  357. 'grouping_level' => $level,
  358. 'rows' => $set['rows'],
  359. 'title' => $set['group'])
  360. );
  361. }
  362. }
  363. unset($this->view->row_index);
  364. return $output;
  365. }
  366. /**
  367. * Group records as needed for rendering.
  368. *
  369. * @param array $records
  370. * An array of records from the view to group.
  371. * @param array $groupings
  372. * An array of grouping instructions on which fields to group. If empty, the
  373. * result set will be given a single group with an empty string as a label.
  374. * @param bool $group_rendered
  375. * Boolean value whether to use the rendered or the raw field value for
  376. * grouping. If set to NULL the return is structured as before
  377. * Views 7.x-3.0-rc2. After Views 7.x-3.0 this boolean is only used if
  378. * $groupings is an old-style string or if the rendered option is missing
  379. * for a grouping instruction.
  380. *
  381. * @return array
  382. * The grouped record set.
  383. * A nested set structure is generated if multiple grouping fields are used.
  384. *
  385. * @code
  386. * array(
  387. * 'grouping_field_1:grouping_1' => array(
  388. * 'group' => 'grouping_field_1:content_1',
  389. * 'rows' => array(
  390. * 'grouping_field_2:grouping_a' => array(
  391. * 'group' => 'grouping_field_2:content_a',
  392. * 'rows' => array(
  393. * $row_index_1 => $row_1,
  394. * $row_index_2 => $row_2,
  395. * // ...
  396. * )
  397. * ),
  398. * ),
  399. * ),
  400. * 'grouping_field_1:grouping_2' => array(
  401. * // ...
  402. * ),
  403. * )
  404. * @endcode
  405. */
  406. public function render_grouping($records, $groupings = array(), $group_rendered = NULL) {
  407. // This is for backward compatibility, when $groupings was a string
  408. // containing the ID of a single field.
  409. if (is_string($groupings)) {
  410. $rendered = $group_rendered === NULL ? TRUE : $group_rendered;
  411. $groupings = array(array('field' => $groupings, 'rendered' => $rendered));
  412. }
  413. // Make sure fields are rendered
  414. $this->render_fields($this->view->result);
  415. $sets = array();
  416. if ($groupings) {
  417. foreach ($records as $index => $row) {
  418. // Iterate through configured grouping fields to determine the
  419. // hierarchically positioned set where the current row belongs to.
  420. // While iterating, parent groups, that do not exist yet, are added.
  421. $set = &$sets;
  422. foreach ($groupings as $info) {
  423. $field = $info['field'];
  424. $rendered = isset($info['rendered']) ? $info['rendered'] : $group_rendered;
  425. $rendered_strip = isset($info['rendered_strip']) ? $info['rendered_strip'] : FALSE;
  426. $grouping = '';
  427. $group_content = '';
  428. // Group on the rendered version of the field, not the raw. That way,
  429. // we can control any special formatting of the grouping field through
  430. // the admin or theme layer or anywhere else we'd like.
  431. if (isset($this->view->field[$field])) {
  432. $group_content = $this->get_field($index, $field);
  433. if ($this->view->field[$field]->options['label']) {
  434. $group_content = $this->view->field[$field]->options['label'] . ': ' . $group_content;
  435. }
  436. if ($rendered) {
  437. $grouping = $group_content;
  438. if ($rendered_strip) {
  439. $group_content = $grouping = strip_tags(htmlspecialchars_decode($group_content));
  440. }
  441. }
  442. else {
  443. $grouping = $this->get_field_value($index, $field);
  444. // Not all field handlers return a scalar value,
  445. // e.g. views_handler_field_field.
  446. if (!is_scalar($grouping)) {
  447. $grouping = md5(serialize($grouping));
  448. }
  449. }
  450. }
  451. // Create the group if it does not exist yet.
  452. if (empty($set[$grouping])) {
  453. $set[$grouping]['group'] = $group_content;
  454. $set[$grouping]['rows'] = array();
  455. }
  456. // Move the set reference into the row set of the group we just
  457. // determined.
  458. $set = &$set[$grouping]['rows'];
  459. }
  460. // Add the row to the hierarchically positioned row set we just
  461. // determined.
  462. $set[$index] = $row;
  463. }
  464. }
  465. else {
  466. // Create a single group with an empty grouping field.
  467. $sets[''] = array(
  468. 'group' => '',
  469. 'rows' => $records,
  470. );
  471. }
  472. // If this parameter isn't explicitly set modify the output to be fully
  473. // backward compatible to code before Views 7.x-3.0-rc2.
  474. // @todo Remove this as soon as possible e.g. October 2020
  475. if ($group_rendered === NULL) {
  476. $old_style_sets = array();
  477. foreach ($sets as $group) {
  478. $old_style_sets[$group['group']] = $group['rows'];
  479. }
  480. $sets = $old_style_sets;
  481. }
  482. return $sets;
  483. }
  484. /**
  485. * Render all of the fields for a given style and store them on the object.
  486. *
  487. * @param array $result
  488. * The result array from $view->result
  489. */
  490. public function render_fields($result) {
  491. if (!$this->uses_fields()) {
  492. return;
  493. }
  494. if (!isset($this->rendered_fields)) {
  495. $this->rendered_fields = array();
  496. $this->view->row_index = 0;
  497. $keys = array_keys($this->view->field);
  498. // If all fields have a field::access FALSE there might be no fields, so
  499. // there is no reason to execute this code.
  500. if (!empty($keys)) {
  501. foreach ($result as $count => $row) {
  502. $this->view->row_index = $count;
  503. foreach ($keys as $id) {
  504. $this->rendered_fields[$count][$id] = $this->view->field[$id]->theme($row);
  505. }
  506. $this->row_tokens[$count] = $this->view->field[$id]->get_render_tokens(array());
  507. }
  508. }
  509. unset($this->view->row_index);
  510. }
  511. return $this->rendered_fields;
  512. }
  513. /**
  514. * Get a rendered field.
  515. *
  516. * @param int $index
  517. * The index count of the row.
  518. * @param string $field
  519. * The id of the field.
  520. */
  521. public function get_field($index, $field) {
  522. if (!isset($this->rendered_fields)) {
  523. $this->render_fields($this->view->result);
  524. }
  525. if (isset($this->rendered_fields[$index][$field])) {
  526. return $this->rendered_fields[$index][$field];
  527. }
  528. }
  529. /**
  530. * Get the raw field value.
  531. *
  532. * @param int $index
  533. * The index count of the row.
  534. * @param string $field
  535. * The id of the field.
  536. */
  537. public function get_field_value($index, $field) {
  538. $this->view->row_index = $index;
  539. $value = $this->view->field[$field]->get_value($this->view->result[$index]);
  540. unset($this->view->row_index);
  541. return $value;
  542. }
  543. /**
  544. * {@inheritdoc}
  545. */
  546. public function validate() {
  547. $errors = parent::validate();
  548. if ($this->uses_row_plugin()) {
  549. $plugin = $this->display->handler->get_plugin('row');
  550. if (empty($plugin)) {
  551. $errors[] = t('Style @style requires a row style but the row plugin is invalid.', array('@style' => $this->definition['title']));
  552. }
  553. else {
  554. $result = $plugin->validate();
  555. if (!empty($result) && is_array($result)) {
  556. $errors = array_merge($errors, $result);
  557. }
  558. }
  559. }
  560. return $errors;
  561. }
  562. /**
  563. * {@inheritdoc}
  564. */
  565. public function query() {
  566. parent::query();
  567. if (isset($this->row_plugin)) {
  568. $this->row_plugin->query();
  569. }
  570. }
  571. }
  572. /**
  573. * @}
  574. */