handlers.inc 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840
  1. <?php
  2. /**
  3. * @file
  4. * Defines the various handler objects to help build and display views.
  5. */
  6. /**
  7. * Instantiate and construct a new handler.
  8. */
  9. function _views_create_handler($definition, $type = 'handler', $handler_type = NULL) {
  10. // debug('Instantiating handler ' . $definition['handler']);
  11. if (empty($definition['handler'])) {
  12. vpr('_views_create_handler - type: @type - failed: handler has not been provided.',
  13. array('@type' => isset($handler_type) ? ($type . '(handler type: ' . $handler_type . ')') : $type)
  14. );
  15. return;
  16. }
  17. // class_exists will automatically load the code file.
  18. if (!empty($definition['override handler']) &&
  19. !class_exists($definition['override handler'])) {
  20. vpr(
  21. '_views_create_handler - loading override handler @type failed: class @override_handler could not be loaded. ' .
  22. 'Verify the class file has been registered in the corresponding .info-file (files[]).',
  23. array(
  24. '@type' => isset($handler_type) ? ($type . '(handler type: ' . $handler_type . ')') : $type,
  25. '@override_handler' => $definition['override handler'],
  26. )
  27. );
  28. return;
  29. }
  30. if (!class_exists($definition['handler'])) {
  31. vpr(
  32. '_views_create_handler - loading handler @type failed: class @handler could not be loaded. ' .
  33. 'Verify the class file has been registered in the corresponding .info-file (files[]).',
  34. array(
  35. '@type' => isset($handler_type) ? ($type . '(handler type: ' . $handler_type . ')') : $type,
  36. '@handler' => $definition['handler'],
  37. )
  38. );
  39. return;
  40. }
  41. if (!empty($definition['override handler'])) {
  42. $handler = new $definition['override handler'];
  43. }
  44. else {
  45. $handler = new $definition['handler'];
  46. }
  47. $handler->set_definition($definition);
  48. if ($type == 'handler') {
  49. $handler->is_handler = TRUE;
  50. $handler->handler_type = $handler_type;
  51. }
  52. else {
  53. $handler->is_plugin = TRUE;
  54. $handler->plugin_type = $type;
  55. $handler->plugin_name = $definition['name'];
  56. }
  57. // let the handler have something like a constructor.
  58. $handler->construct();
  59. return $handler;
  60. }
  61. /**
  62. * Prepare a handler's data by checking defaults and such.
  63. */
  64. function _views_prepare_handler($definition, $data, $field, $type) {
  65. foreach (array('group', 'title', 'title short', 'help', 'real field') as $key) {
  66. if (!isset($definition[$key])) {
  67. // First check the field level.
  68. if (!empty($data[$field][$key])) {
  69. $definition[$key] = $data[$field][$key];
  70. }
  71. // Then if that doesn't work, check the table level.
  72. elseif (!empty($data['table'][$key])) {
  73. $definition[$key] = $data['table'][$key];
  74. }
  75. }
  76. }
  77. return _views_create_handler($definition, 'handler', $type);
  78. }
  79. /**
  80. * Fetch a handler to join one table to a primary table from the data cache.
  81. */
  82. function views_get_table_join($table, $base_table) {
  83. $data = views_fetch_data($table);
  84. if (isset($data['table']['join'][$base_table])) {
  85. $h = $data['table']['join'][$base_table];
  86. if (!empty($h['handler']) && class_exists($h['handler'])) {
  87. $handler = new $h['handler'];
  88. }
  89. else {
  90. $handler = new views_join();
  91. }
  92. // Fill in some easy defaults.
  93. $handler->definition = $h;
  94. if (empty($handler->definition['table'])) {
  95. $handler->definition['table'] = $table;
  96. }
  97. // If this is empty, it's a direct link.
  98. if (empty($handler->definition['left_table'])) {
  99. $handler->definition['left_table'] = $base_table;
  100. }
  101. if (isset($h['arguments'])) {
  102. call_user_func_array(array(&$handler, 'construct'), $h['arguments']);
  103. }
  104. else {
  105. $handler->construct();
  106. }
  107. return $handler;
  108. }
  109. // DEBUG -- identify missing handlers.
  110. vpr("Missing join: @table @base_table", array('@table' => $table, '@base_table' => $base_table));
  111. }
  112. /**
  113. * Base handler, from which all the other handlers are derived.
  114. * It creates a common interface to create consistency amongst
  115. * handlers and data.
  116. *
  117. * This class would be abstract in PHP5, but PHP4 doesn't understand that.
  118. *
  119. * Definition terms:
  120. * - table: The actual table this uses; only specify if different from
  121. * the table this is attached to.
  122. * - real field: The actual field this uses; only specify if different from
  123. * the field this item is attached to.
  124. * - group: A text string representing the 'group' this item is attached to,
  125. * for display in the UI. Examples: "Node", "Taxonomy", "Comment",
  126. * "User", etc. This may be inherited from the parent definition or
  127. * the 'table' definition.
  128. * - title: The title for this handler in the UI. This may be inherited from
  129. * the parent definition or the 'table' definition.
  130. * - help: A more informative string to give to the user to explain what this
  131. * field/handler is or does.
  132. * - access callback: If this field should have access control, this could
  133. * be a function to use. 'user_access' is a common
  134. * public function to use here. If not specified, no access
  135. * control is provided.
  136. * - access arguments: An array of arguments for the access callback.
  137. */
  138. class views_handler extends views_object {
  139. /**
  140. * The top object of a view.
  141. *
  142. * @var view
  143. */
  144. public $view = NULL;
  145. /**
  146. * Where the $query object will reside:.
  147. *
  148. * @var views_plugin_query
  149. */
  150. public $query = NULL;
  151. /**
  152. * The type of the handler, for example filter/footer/field.
  153. */
  154. public $handler_type = NULL;
  155. /**
  156. * The alias of the table of this handler which is used in the query.
  157. */
  158. public $table_alias;
  159. /**
  160. * The actual field in the database table, maybe different
  161. * on other kind of query plugins/special handlers.
  162. */
  163. public $real_field;
  164. /**
  165. * The relationship used for this field.
  166. */
  167. public $relationship = NULL;
  168. /**
  169. * Init the handler with necessary data.
  170. *
  171. * @param view $view
  172. * The $view object this handler is attached to.
  173. * @param array $options
  174. * The item from the database; the actual contents of this will vary
  175. * based upon the type of handler.
  176. */
  177. public function init(&$view, &$options) {
  178. $this->view = &$view;
  179. $display_id = $this->view->current_display;
  180. // Check to see if this handler type is defaulted. Note that
  181. // we have to do a lookup because the type is singular but the
  182. // option is stored as the plural.
  183. // If the 'moved to' keyword moved our handler, let's fix that now.
  184. if (isset($this->actual_table)) {
  185. $options['table'] = $this->actual_table;
  186. }
  187. if (isset($this->actual_field)) {
  188. $options['field'] = $this->actual_field;
  189. }
  190. $types = views_object_types();
  191. $plural = $this->handler_type;
  192. if (isset($types[$this->handler_type]['plural'])) {
  193. $plural = $types[$this->handler_type]['plural'];
  194. }
  195. if ($this->view->display_handler->is_defaulted($plural)) {
  196. $display_id = 'default';
  197. }
  198. $this->localization_keys = array(
  199. $display_id,
  200. $this->handler_type,
  201. $options['table'],
  202. $options['id'],
  203. );
  204. $this->unpack_options($this->options, $options);
  205. // This exist on most handlers, but not all. So they are still optional.
  206. if (isset($options['table'])) {
  207. $this->table = $options['table'];
  208. }
  209. if (isset($this->definition['real field'])) {
  210. $this->real_field = $this->definition['real field'];
  211. }
  212. if (isset($this->definition['field'])) {
  213. $this->real_field = $this->definition['field'];
  214. }
  215. if (isset($options['field'])) {
  216. $this->field = $options['field'];
  217. if (!isset($this->real_field)) {
  218. $this->real_field = $options['field'];
  219. }
  220. }
  221. $this->query = &$view->query;
  222. }
  223. /**
  224. * {@inheritdoc}
  225. */
  226. public function option_definition() {
  227. $options = parent::option_definition();
  228. $options['id'] = array('default' => '');
  229. $options['table'] = array('default' => '');
  230. $options['field'] = array('default' => '');
  231. $options['relationship'] = array('default' => 'none');
  232. $options['group_type'] = array('default' => 'group');
  233. $options['ui_name'] = array('default' => '');
  234. return $options;
  235. }
  236. /**
  237. * Return a string representing this handler's name in the UI.
  238. */
  239. public function ui_name($short = FALSE) {
  240. if (!empty($this->options['ui_name'])) {
  241. $title = check_plain($this->options['ui_name']);
  242. return $title;
  243. }
  244. $title = ($short && isset($this->definition['title short'])) ? $this->definition['title short'] : $this->definition['title'];
  245. if (empty($this->definition['group'])) {
  246. return $title;
  247. }
  248. return t('!group: !title', array('!group' => $this->definition['group'], '!title' => $title));
  249. }
  250. /**
  251. * Shortcut to get a handler's raw field value.
  252. *
  253. * This should be overridden for handlers with formulae or other
  254. * non-standard fields. Because this takes an argument, fields
  255. * overriding this can just call return parent::get_field($formula)
  256. */
  257. public function get_field($field = NULL) {
  258. if (!isset($field)) {
  259. if (!empty($this->formula)) {
  260. $field = $this->get_formula();
  261. }
  262. else {
  263. $field = $this->table_alias . '.' . $this->real_field;
  264. }
  265. }
  266. // If grouping, check to see if the aggregation method needs to modify the
  267. // field.
  268. if ($this->view->display_handler->use_group_by()) {
  269. $this->view->init_query();
  270. if ($this->query) {
  271. $info = $this->query->get_aggregation_info();
  272. if (!empty($info[$this->options['group_type']]['method']) && function_exists($info[$this->options['group_type']]['method'])) {
  273. return $info[$this->options['group_type']]['method']($this->options['group_type'], $field);
  274. }
  275. }
  276. }
  277. return $field;
  278. }
  279. /**
  280. * Sanitize the value for output.
  281. *
  282. * @param string $value
  283. * The value being rendered.
  284. * @param string $type
  285. * The type of sanitization needed. If not provided, check_plain() is used.
  286. *
  287. * @return string
  288. * Returns the safe value.
  289. */
  290. public function sanitize_value($value, $type = NULL) {
  291. switch ($type) {
  292. case 'xss':
  293. $value = filter_xss($value);
  294. break;
  295. case 'xss_admin':
  296. $value = filter_xss_admin($value);
  297. break;
  298. case 'url':
  299. $value = check_url($value);
  300. break;
  301. default:
  302. $value = check_plain($value);
  303. break;
  304. }
  305. return $value;
  306. }
  307. /**
  308. * Transform a string by a certain method.
  309. *
  310. * @param string $string
  311. * The input you want to transform.
  312. * @param array $option
  313. * How do you want to transform it, possible values:
  314. * - upper: Uppercase the string.
  315. * - lower: lowercase the string.
  316. * - ucfirst: Make the first char uppercase.
  317. * - ucwords: Make each word in the string uppercase.
  318. *
  319. * @return string
  320. * The transformed string.
  321. */
  322. public function case_transform($string, $option) {
  323. global $multibyte;
  324. switch ($option) {
  325. default:
  326. return $string;
  327. case 'upper':
  328. return drupal_strtoupper($string);
  329. case 'lower':
  330. return drupal_strtolower($string);
  331. case 'ucfirst':
  332. return drupal_strtoupper(drupal_substr($string, 0, 1)) . drupal_substr($string, 1);
  333. case 'ucwords':
  334. if ($multibyte == UNICODE_MULTIBYTE) {
  335. return mb_convert_case($string, MB_CASE_TITLE);
  336. }
  337. else {
  338. return ucwords($string);
  339. }
  340. }
  341. }
  342. /**
  343. * Validate the options form.
  344. */
  345. public function options_validate(&$form, &$form_state) {
  346. }
  347. /**
  348. * Build the options form.
  349. */
  350. public function options_form(&$form, &$form_state) {
  351. // Some form elements belong in a fieldset for presentation, but can't
  352. // be moved into one because of the form_state['values'] hierarchy. Those
  353. // elements can add a #fieldset => 'fieldset_name' property, and they'll
  354. // be moved to their fieldset during pre_render.
  355. $form['#pre_render'][] = 'views_ui_pre_render_add_fieldset_markup';
  356. $form['ui_name'] = array(
  357. '#type' => 'textfield',
  358. '#title' => t('Administrative title'),
  359. '#description' => t('This title will be displayed on the views edit page instead of the default one. This might be useful if you have the same item twice.'),
  360. '#default_value' => $this->options['ui_name'],
  361. '#fieldset' => 'more',
  362. );
  363. // This form is long and messy enough that the "Administrative title" option
  364. // belongs in a "more options" fieldset at the bottom of the form.
  365. $form['more'] = array(
  366. '#type' => 'fieldset',
  367. '#title' => t('More'),
  368. '#collapsible' => TRUE,
  369. '#collapsed' => TRUE,
  370. '#weight' => 150,
  371. );
  372. // Allow to alter the default values brought into the form.
  373. // Triggers hook_views_handler_options_alter().
  374. drupal_alter('views_handler_options', $this->options, $this);
  375. }
  376. /**
  377. * Perform any necessary changes to the form values prior to storage.
  378. * There is no need for this function to actually store the data.
  379. */
  380. public function options_submit(&$form, &$form_state) {
  381. }
  382. /**
  383. * Provides the handler some groupby.
  384. */
  385. public function use_group_by() {
  386. return TRUE;
  387. }
  388. /**
  389. * Provide a form for aggregation settings.
  390. */
  391. public function groupby_form(&$form, &$form_state) {
  392. $view = &$form_state['view'];
  393. $display_id = $form_state['display_id'];
  394. $types = views_object_types();
  395. $type = $form_state['type'];
  396. $id = $form_state['id'];
  397. $form['#title'] = check_plain($view->display[$display_id]->display_title) . ': ';
  398. $form['#title'] .= t('Configure aggregation settings for @type %item', array('@type' => $types[$type]['lstitle'], '%item' => $this->ui_name()));
  399. $form['#section'] = $display_id . '-' . $type . '-' . $id;
  400. $view->init_query();
  401. $info = $view->query->get_aggregation_info();
  402. foreach ($info as $id => $aggregate) {
  403. $group_types[$id] = $aggregate['title'];
  404. }
  405. $form['group_type'] = array(
  406. '#type' => 'select',
  407. '#title' => t('Aggregation type'),
  408. '#default_value' => $this->options['group_type'],
  409. '#description' => t('Select the aggregation function to use on this field.'),
  410. '#options' => $group_types,
  411. );
  412. }
  413. /**
  414. * Perform any necessary changes to the form values prior to storage.
  415. * There is no need for this function to actually store the data.
  416. */
  417. public function groupby_form_submit(&$form, &$form_state) {
  418. $item =& $form_state['handler']->options;
  419. $item['group_type'] = $form_state['values']['options']['group_type'];
  420. }
  421. /**
  422. * If a handler has 'extra options' it will get a little settings widget and
  423. * another form called extra_options.
  424. */
  425. public function has_extra_options() {
  426. return FALSE;
  427. }
  428. /**
  429. * Provide defaults for the handler.
  430. */
  431. public function extra_options(&$option) {
  432. }
  433. /**
  434. * Provide a form for setting options.
  435. */
  436. public function extra_options_form(&$form, &$form_state) {
  437. }
  438. /**
  439. * Validate the options form.
  440. */
  441. public function extra_options_validate($form, &$form_state) {
  442. }
  443. /**
  444. * Perform any necessary changes to the form values prior to storage.
  445. * There is no need for this function to actually store the data.
  446. */
  447. public function extra_options_submit($form, &$form_state) {
  448. }
  449. /**
  450. * Determine if a handler can be exposed.
  451. */
  452. public function can_expose() {
  453. return FALSE;
  454. }
  455. /**
  456. * Set new exposed option defaults when exposed setting is flipped
  457. * on.
  458. */
  459. public function expose_options() {
  460. }
  461. /**
  462. * Get information about the exposed form for the form renderer.
  463. */
  464. public function exposed_info() {
  465. }
  466. /**
  467. * Render our chunk of the exposed handler form when selecting.
  468. */
  469. public function exposed_form(&$form, &$form_state) {
  470. }
  471. /**
  472. * Validate the exposed handler form.
  473. */
  474. public function exposed_validate(&$form, &$form_state) {
  475. }
  476. /**
  477. * Submit the exposed handler form.
  478. */
  479. public function exposed_submit(&$form, &$form_state) {
  480. }
  481. /**
  482. * Form for exposed handler options.
  483. */
  484. public function expose_form(&$form, &$form_state) {
  485. }
  486. /**
  487. * Validate the options form.
  488. */
  489. public function expose_validate($form, &$form_state) {
  490. }
  491. /**
  492. * Perform any necessary changes to the form exposes prior to storage.
  493. * There is no need for this function to actually store the data.
  494. */
  495. public function expose_submit($form, &$form_state) {
  496. }
  497. /**
  498. * Shortcut to display the expose/hide button.
  499. */
  500. public function show_expose_button(&$form, &$form_state) {
  501. }
  502. /**
  503. * Shortcut to display the exposed options form.
  504. */
  505. public function show_expose_form(&$form, &$form_state) {
  506. if (empty($this->options['exposed'])) {
  507. return;
  508. }
  509. $this->expose_form($form, $form_state);
  510. // When we click the expose button, we add new gadgets to the form but they
  511. // have no data in $_POST so their defaults get wiped out. This prevents
  512. // these defaults from getting wiped out. This setting will only be TRUE
  513. // during a 2nd pass rerender.
  514. if (!empty($form_state['force_expose_options'])) {
  515. foreach (element_children($form['expose']) as $id) {
  516. if (isset($form['expose'][$id]['#default_value']) && !isset($form['expose'][$id]['#value'])) {
  517. $form['expose'][$id]['#value'] = $form['expose'][$id]['#default_value'];
  518. }
  519. }
  520. }
  521. }
  522. /**
  523. * Check whether current user has access to this handler.
  524. *
  525. * @return bool
  526. */
  527. public function access() {
  528. if (isset($this->definition['access callback']) && function_exists($this->definition['access callback'])) {
  529. if (isset($this->definition['access arguments']) && is_array($this->definition['access arguments'])) {
  530. return call_user_func_array($this->definition['access callback'], $this->definition['access arguments']);
  531. }
  532. return $this->definition['access callback']();
  533. }
  534. return TRUE;
  535. }
  536. /**
  537. * Run before the view is built.
  538. *
  539. * This gives all the handlers some time to set up before any handler has
  540. * been fully run.
  541. */
  542. public function pre_query() {
  543. }
  544. /**
  545. * Run after the view is executed, before the result is cached.
  546. *
  547. * This gives all the handlers some time to modify values. This is primarily
  548. * used so that handlers that pull up secondary data can put it in the
  549. * $values so that the raw data can be utilized externally.
  550. */
  551. public function post_execute(&$values) {
  552. }
  553. /**
  554. * Provides a unique placeholders for handlers.
  555. */
  556. public function placeholder() {
  557. return $this->query->placeholder($this->options['table'] . '_' . $this->options['field']);
  558. }
  559. /**
  560. * Called just prior to query(), this lets a handler set up any relationship
  561. * it needs.
  562. */
  563. public function set_relationship() {
  564. // Ensure this gets set to something.
  565. $this->relationship = NULL;
  566. // Don't process non-existant relationships.
  567. if (empty($this->options['relationship']) || $this->options['relationship'] == 'none') {
  568. return;
  569. }
  570. $relationship = $this->options['relationship'];
  571. // Ignore missing/broken relationships.
  572. if (empty($this->view->relationship[$relationship])) {
  573. return;
  574. }
  575. // Check to see if the relationship has already processed. If not, then we
  576. // cannot process it.
  577. if (empty($this->view->relationship[$relationship]->alias)) {
  578. return;
  579. }
  580. // Finally!
  581. $this->relationship = $this->view->relationship[$relationship]->alias;
  582. }
  583. /**
  584. * Ensure the main table for this handler is in the query. This is used
  585. * a lot.
  586. */
  587. public function ensure_my_table() {
  588. if (!isset($this->table_alias)) {
  589. if (!method_exists($this->query, 'ensure_table')) {
  590. vpr(t('Ensure my table called but query has no ensure_table method.'));
  591. return;
  592. }
  593. $this->table_alias = $this->query->ensure_table($this->table, $this->relationship);
  594. }
  595. return $this->table_alias;
  596. }
  597. /**
  598. * Provide text for the administrative summary.
  599. */
  600. public function admin_summary() {
  601. }
  602. /**
  603. * Determine if the argument needs a style plugin.
  604. *
  605. * @return bool
  606. */
  607. public function needs_style_plugin() {
  608. return FALSE;
  609. }
  610. /**
  611. * Determine if this item is 'exposed', meaning it provides form elements
  612. * to let users modify the view.
  613. *
  614. * @return bool
  615. */
  616. public function is_exposed() {
  617. return !empty($this->options['exposed']);
  618. }
  619. /**
  620. * Returns TRUE if the exposed filter works like a grouped filter.
  621. */
  622. public function is_a_group() {
  623. return FALSE;
  624. }
  625. /**
  626. * Define if the exposed input has to be submitted multiple times.
  627. * This is TRUE when exposed filters grouped are using checkboxes as
  628. * widgets.
  629. */
  630. public function multiple_exposed_input() {
  631. return FALSE;
  632. }
  633. /**
  634. * Take input from exposed handlers and assign to this handler, if necessary.
  635. */
  636. public function accept_exposed_input($input) {
  637. return TRUE;
  638. }
  639. /**
  640. * If set to remember exposed input in the session, store it there.
  641. */
  642. public function store_exposed_input($input, $status) {
  643. return TRUE;
  644. }
  645. /**
  646. * Get the join object that should be used for this handler.
  647. *
  648. * This method isn't used a great deal, but it's very handy for easily
  649. * getting the join if it is necessary to make some changes to it, such
  650. * as adding an 'extra'.
  651. */
  652. public function get_join() {
  653. // get the join from this table that links back to the base table.
  654. // Determine the primary table to seek.
  655. if (empty($this->query->relationships[$this->relationship])) {
  656. $base_table = $this->query->base_table;
  657. }
  658. else {
  659. $base_table = $this->query->relationships[$this->relationship]['base'];
  660. }
  661. $join = views_get_table_join($this->table, $base_table);
  662. if ($join) {
  663. return clone $join;
  664. }
  665. }
  666. /**
  667. * Validates the handler against the complete View.
  668. *
  669. * This is called when the complete View is being validated. For validating
  670. * the handler options form use options_validate().
  671. *
  672. * @see views_handler::options_validate()
  673. *
  674. * @return array
  675. * Empty array if the handler is valid; an array of error strings if it is
  676. * not.
  677. */
  678. public function validate() {
  679. return array();
  680. }
  681. /**
  682. * Determine if the handler is considered 'broken'.
  683. *
  684. * Generally only returns TRUE if the handler can't be found.
  685. *
  686. * @return bool
  687. * The handler could not be loaded.
  688. */
  689. public function broken() {
  690. }
  691. }
  692. /**
  693. * This many to one helper object is used on both arguments and filters.
  694. *
  695. * @todo This requires extensive documentation on how this class is to
  696. * be used. For now, look at the arguments and filters that use it. Lots
  697. * of stuff is just pass-through but there are definitely some interesting
  698. * areas where they interact.
  699. *
  700. * Any handler that uses this can have the following possibly additional
  701. * definition terms:
  702. * - numeric: If true, treat this field as numeric, using %d instead of %s in
  703. * queries.
  704. */
  705. class views_many_to_one_helper {
  706. /**
  707. * Contains possible existing placeholders used by the query.
  708. *
  709. * @var array
  710. */
  711. public $placeholders = array();
  712. /**
  713. * {@inheritdoc}
  714. */
  715. public function __construct(&$handler) {
  716. $this->handler = &$handler;
  717. }
  718. /**
  719. * {@inheritdoc}
  720. */
  721. static function option_definition(&$options) {
  722. $options['reduce_duplicates'] = array('default' => FALSE, 'bool' => TRUE);
  723. }
  724. /**
  725. * {@inheritdoc}
  726. */
  727. public function options_form(&$form, &$form_state) {
  728. $form['reduce_duplicates'] = array(
  729. '#type' => 'checkbox',
  730. '#title' => t('Reduce duplicates'),
  731. '#description' => t('This filter can cause items that have more than one of the selected options to appear as duplicate results. If this filter causes duplicate results to occur, this checkbox can reduce those duplicates; however, the more terms it has to search for, the less performant the query will be, so use this with caution. Shouldn\'t be set on single-value fields, as it may cause values to disappear from display, if used on an incompatible field.'),
  732. '#default_value' => !empty($this->handler->options['reduce_duplicates']),
  733. '#weight' => 4,
  734. );
  735. }
  736. /**
  737. * Provide an option to use a formula.
  738. *
  739. * If it wants us to do this, it must set $helper->formula = TRUE and
  740. * implement handler->get_formula();.
  741. */
  742. public function get_field() {
  743. if (!empty($this->formula)) {
  744. return $this->handler->get_formula();
  745. }
  746. else {
  747. return $this->handler->table_alias . '.' . $this->handler->real_field;
  748. }
  749. }
  750. /**
  751. * Add a table to the query.
  752. *
  753. * This is an advanced concept; not only does it add a new instance of the
  754. * table, but it follows the relationship path all the way down to the
  755. * relationship link point and adds *that* as a new relationship and then adds
  756. * the table to the relationship, if necessary.
  757. */
  758. public function add_table($join = NULL, $alias = NULL) {
  759. // This is used for lookups in the many_to_one table.
  760. $field = $this->handler->relationship . '_' . $this->handler->table . '.' . $this->handler->field;
  761. if (empty($join)) {
  762. $join = $this->get_join();
  763. }
  764. // See if there's a chain between us and the base relationship. If so, we
  765. // need to create a new relationship to use.
  766. $relationship = $this->handler->relationship;
  767. // Determine the primary table to seek.
  768. if (empty($this->handler->query->relationships[$relationship])) {
  769. $base_table = $this->handler->query->base_table;
  770. }
  771. else {
  772. $base_table = $this->handler->query->relationships[$relationship]['base'];
  773. }
  774. // Cycle through the joins. This isn't as error-safe as the normal
  775. // ensure_path logic. Perhaps it should be.
  776. $r_join = clone $join;
  777. while (!empty($r_join) && $r_join->left_table != $base_table) {
  778. $r_join = views_get_table_join($r_join->left_table, $base_table);
  779. }
  780. // If we found that there are tables in between, add the relationship.
  781. if ($r_join->table != $join->table) {
  782. $relationship = $this->handler->query->add_relationship($this->handler->table . '_' . $r_join->table, $r_join, $r_join->table, $this->handler->relationship);
  783. }
  784. // And now add our table, using the new relationship if one was used.
  785. $alias = $this->handler->query->add_table($this->handler->table, $relationship, $join, $alias);
  786. // Store what values are used by this table chain so that other chains can
  787. // automatically discard those values.
  788. if (empty($this->handler->view->many_to_one_tables[$field])) {
  789. $this->handler->view->many_to_one_tables[$field] = $this->handler->value;
  790. }
  791. else {
  792. $this->handler->view->many_to_one_tables[$field] = array_merge($this->handler->view->many_to_one_tables[$field], $this->handler->value);
  793. }
  794. return $alias;
  795. }
  796. /**
  797. * {@inheritdoc}
  798. */
  799. public function get_join() {
  800. return $this->handler->get_join();
  801. }
  802. /**
  803. * Provide the proper join for summary queries.
  804. *
  805. * This is important in part because it will cooperate with other arguments if
  806. * possible.
  807. */
  808. public function summary_join() {
  809. $field = $this->handler->relationship . '_' . $this->handler->table . '.' . $this->handler->field;
  810. $join = $this->get_join();
  811. // Shortcuts.
  812. $options = $this->handler->options;
  813. $view = &$this->handler->view;
  814. $query = &$this->handler->query;
  815. if (!empty($options['require_value'])) {
  816. $join->type = 'INNER';
  817. }
  818. if (empty($options['add_table']) || empty($view->many_to_one_tables[$field])) {
  819. return $query->ensure_table($this->handler->table, $this->handler->relationship, $join);
  820. }
  821. else {
  822. if (!empty($view->many_to_one_tables[$field])) {
  823. foreach ($view->many_to_one_tables[$field] as $value) {
  824. $join->extra = array(
  825. array(
  826. 'field' => $this->handler->real_field,
  827. 'operator' => '!=',
  828. 'value' => $value,
  829. 'numeric' => !empty($this->definition['numeric']),
  830. ),
  831. );
  832. }
  833. }
  834. return $this->add_table($join);
  835. }
  836. }
  837. /**
  838. * Override ensure_my_table so we can control how this joins in.
  839. *
  840. * The operator actually has influence over joining.
  841. */
  842. public function ensure_my_table() {
  843. if (!isset($this->handler->table_alias)) {
  844. // Case 1: Operator is an 'or' and we're not reducing duplicates.
  845. // We hence get the absolute simplest.
  846. $field = $this->handler->relationship . '_' . $this->handler->table . '.' . $this->handler->field;
  847. if ($this->handler->operator == 'or' && empty($this->handler->options['reduce_duplicates'])) {
  848. if (empty($this->handler->options['add_table']) && empty($this->handler->view->many_to_one_tables[$field])) {
  849. // Query optimization, INNER joins are slightly faster, so use them
  850. // when we know we can.
  851. $join = $this->get_join();
  852. if (isset($join)) {
  853. $join->type = 'INNER';
  854. }
  855. $this->handler->table_alias = $this->handler->query->ensure_table($this->handler->table, $this->handler->relationship, $join);
  856. $this->handler->view->many_to_one_tables[$field] = $this->handler->value;
  857. }
  858. else {
  859. $join = $this->get_join();
  860. $join->type = 'LEFT';
  861. if (!empty($this->handler->view->many_to_one_tables[$field])) {
  862. foreach ($this->handler->view->many_to_one_tables[$field] as $value) {
  863. $join->extra = array(
  864. array(
  865. 'field' => $this->handler->real_field,
  866. 'operator' => '!=',
  867. 'value' => $value,
  868. 'numeric' => !empty($this->handler->definition['numeric']),
  869. ),
  870. );
  871. }
  872. }
  873. $this->handler->table_alias = $this->add_table($join);
  874. }
  875. return $this->handler->table_alias;
  876. }
  877. // Case 2: it's anything but an 'or'.
  878. // We do one join per selected value.
  879. // Clone the join for each table:
  880. $this->handler->table_aliases = array();
  881. $values = $this->handler->operator === 'not' ? array($this->handler->value) : $this->handler->value;
  882. foreach ($values as $value) {
  883. $join = $this->get_join();
  884. if ($this->handler->operator == 'and') {
  885. $join->type = 'INNER';
  886. }
  887. if (empty($join->extra)) {
  888. $join->extra = array();
  889. }
  890. $join->extra[] = array(
  891. 'field' => $this->handler->real_field,
  892. 'value' => $value,
  893. 'numeric' => !empty($this->handler->definition['numeric']),
  894. );
  895. if (($this->handler->is_a_group() && is_array($value)) || $this->handler->operator === 'not') {
  896. $value = serialize($value);
  897. }
  898. // The table alias needs to be unique to this value across the
  899. // multiple times the filter or argument is called by the view.
  900. if (!isset($this->handler->view->many_to_one_aliases[$field][$value])) {
  901. if (!isset($this->handler->view->many_to_one_count[$this->handler->table])) {
  902. $this->handler->view->many_to_one_count[$this->handler->table] = 0;
  903. }
  904. $this->handler->view->many_to_one_aliases[$field][$value] = $this->handler->table . '_value_' . ($this->handler->view->many_to_one_count[$this->handler->table]++);
  905. $alias = $this->handler->table_aliases[$value] = $this->add_table($join,
  906. $this->handler->view->many_to_one_aliases[$field][$value]);
  907. // and set table_alias to the first of these.
  908. if (empty($this->handler->table_alias)) {
  909. $this->handler->table_alias = $alias;
  910. }
  911. }
  912. else {
  913. $this->handler->table_aliases[$value] = $this->handler->view->many_to_one_aliases[$field][$value];
  914. }
  915. }
  916. }
  917. return $this->handler->table_alias;
  918. }
  919. /**
  920. * Provides a unique placeholders for handlers.
  921. */
  922. public function placeholder() {
  923. return $this->handler->query->placeholder($this->handler->options['table'] . '_' . $this->handler->options['field']);
  924. }
  925. /**
  926. *
  927. */
  928. public function add_filter() {
  929. if (empty($this->handler->value)) {
  930. return;
  931. }
  932. $this->handler->ensure_my_table();
  933. // Shorten some variables.
  934. $field = $this->get_field();
  935. $options = $this->handler->options;
  936. $operator = $this->handler->operator;
  937. $formula = !empty($this->formula);
  938. $value = $this->handler->value;
  939. if (empty($options['group'])) {
  940. $options['group'] = 0;
  941. }
  942. // Determine whether a single expression is enough(FALSE) or the conditions
  943. // should be added via an db_or()/db_and() (TRUE).
  944. $add_condition = TRUE;
  945. if ($operator == 'or' && empty($options['reduce_duplicates'])) {
  946. if (count($value) > 1) {
  947. $operator = 'IN';
  948. }
  949. else {
  950. $value = is_array($value) ? array_pop($value) : $value;
  951. if (is_array($value) && count($value) > 1) {
  952. $operator = 'IN';
  953. }
  954. else {
  955. $operator = '=';
  956. }
  957. }
  958. $add_condition = FALSE;
  959. }
  960. if (!$add_condition) {
  961. if ($formula) {
  962. $placeholder = $this->placeholder();
  963. if ($operator == 'IN') {
  964. $operator = "$operator IN($placeholder)";
  965. }
  966. else {
  967. $operator = "$operator $placeholder";
  968. }
  969. $placeholders = array(
  970. $placeholder => $value,
  971. ) + $this->placeholders;
  972. $this->handler->query->add_where_expression($options['group'], "$field $operator", $placeholders);
  973. }
  974. else {
  975. $this->handler->query->add_where($options['group'], $field, $value, $operator);
  976. }
  977. }
  978. if ($add_condition) {
  979. $field = $this->handler->real_field;
  980. $clause = $operator == 'or' ? db_or() : db_and();
  981. foreach ($this->handler->table_aliases as $value => $alias) {
  982. if ($operator == 'not') {
  983. $value = NULL;
  984. }
  985. $clause->condition("$alias.$field", $value);
  986. }
  987. // Implode on either AND or OR.
  988. $this->handler->query->add_where($options['group'], $clause);
  989. }
  990. }
  991. }
  992. /**
  993. * Break x,y,z and x+y+z into an array. Works for strings.
  994. *
  995. * @param string $str
  996. * The string to parse.
  997. * @param object $object
  998. * The object to use as a base. If not specified one will be created.
  999. *
  1000. * @return object
  1001. * An object containing
  1002. * - operator: Either 'and' or 'or'
  1003. * - value: An array of numeric values.
  1004. */
  1005. function views_break_phrase_string($str, &$handler = NULL) {
  1006. if (!$handler) {
  1007. $handler = new stdClass();
  1008. }
  1009. // Set up defaults.
  1010. if (!isset($handler->value)) {
  1011. $handler->value = array();
  1012. }
  1013. if (!isset($handler->operator)) {
  1014. $handler->operator = 'or';
  1015. }
  1016. if ($str == '') {
  1017. return $handler;
  1018. }
  1019. // Determine if the string has 'or' operators (plus signs) or 'and' operators
  1020. // (commas) and split the string accordingly. If we have an 'and' operator,
  1021. // spaces are treated as part of the word being split, but otherwise they are
  1022. // treated the same as a plus sign.
  1023. $or_wildcard = '[^\s+,]';
  1024. $and_wildcard = '[^+,]';
  1025. if (preg_match("/^({$or_wildcard}+[+ ])+{$or_wildcard}+$/", $str)) {
  1026. $handler->operator = 'or';
  1027. $handler->value = preg_split('/[+ ]/', $str);
  1028. }
  1029. elseif (preg_match("/^({$and_wildcard}+,)*{$and_wildcard}+$/", $str)) {
  1030. $handler->operator = 'and';
  1031. $handler->value = explode(',', $str);
  1032. }
  1033. // Keep an 'error' value if invalid strings were given.
  1034. if (!empty($str) && (empty($handler->value) || !is_array($handler->value))) {
  1035. $handler->value = array(-1);
  1036. return $handler;
  1037. }
  1038. // Doubly ensure that all values are strings only.
  1039. foreach ($handler->value as $id => $value) {
  1040. $handler->value[$id] = (string) $value;
  1041. }
  1042. return $handler;
  1043. }
  1044. /**
  1045. * Break x,y,z and x+y+z into an array. Numeric only.
  1046. *
  1047. * @param string $str
  1048. * The string to parse.
  1049. * @param object $handler
  1050. * The handler object to use as a base. If not specified one will be created.
  1051. *
  1052. * @return $handler
  1053. * The new handler object.
  1054. */
  1055. function views_break_phrase($str, &$handler = NULL) {
  1056. if (!$handler) {
  1057. $handler = new stdClass();
  1058. }
  1059. // Set up defaults.
  1060. if (!isset($handler->value)) {
  1061. $handler->value = array();
  1062. }
  1063. if (!isset($handler->operator)) {
  1064. $handler->operator = 'or';
  1065. }
  1066. if (empty($str)) {
  1067. return $handler;
  1068. }
  1069. if (preg_match('/^([0-9]+[+ ])+[0-9]+$/', $str)) {
  1070. // The '+' character in a query string may be parsed as ' '.
  1071. $handler->operator = 'or';
  1072. $handler->value = preg_split('/[+ ]/', $str);
  1073. }
  1074. elseif (preg_match('/^([0-9]+,)*[0-9]+$/', $str)) {
  1075. $handler->operator = 'and';
  1076. $handler->value = explode(',', $str);
  1077. }
  1078. // Keep an 'error' value if invalid strings were given.
  1079. if (!empty($str) && (empty($handler->value) || !is_array($handler->value))) {
  1080. $handler->value = array(-1);
  1081. return $handler;
  1082. }
  1083. // Doubly ensure that all values are numeric only.
  1084. foreach ($handler->value as $id => $value) {
  1085. $handler->value[$id] = intval($value);
  1086. }
  1087. return $handler;
  1088. }
  1089. // --------------------------------------------------------------------------
  1090. // Date helper functions.
  1091. /**
  1092. * Figure out what timezone we're in; needed for some date manipulations.
  1093. */
  1094. function views_get_timezone() {
  1095. global $user;
  1096. if (variable_get('configurable_timezones', 1) && $user->uid && strlen($user->timezone)) {
  1097. $timezone = $user->timezone;
  1098. }
  1099. else {
  1100. $timezone = variable_get('date_default_timezone', 0);
  1101. }
  1102. // Set up the database timezone.
  1103. $db_type = Database::getConnection()->databaseType();
  1104. if (in_array($db_type, array('mysql', 'pgsql'))) {
  1105. $offset = '+00:00';
  1106. static $already_set = FALSE;
  1107. if (!$already_set) {
  1108. if ($db_type == 'pgsql') {
  1109. db_query("SET TIME ZONE INTERVAL '$offset' HOUR TO MINUTE");
  1110. }
  1111. elseif ($db_type == 'mysql') {
  1112. db_query("SET @@session.time_zone = '$offset'");
  1113. }
  1114. $already_set = TRUE;
  1115. }
  1116. }
  1117. return $timezone;
  1118. }
  1119. /**
  1120. * Helper function to create cross-database SQL dates.
  1121. *
  1122. * @param string $field
  1123. * The real table and field name, like 'tablename.fieldname'.
  1124. * @param string $field_type
  1125. * The type of date field, 'int' or 'datetime'.
  1126. * @param string $set_offset
  1127. * The name of a field that holds the timezone offset or a fixed timezone
  1128. * offset value. If not provided, the normal Drupal timezone handling
  1129. * will be used, i.e. $set_offset = 0 will make no timezone adjustment.
  1130. *
  1131. * @return string
  1132. * An appropriate SQL string for the db type and field type.
  1133. */
  1134. function views_date_sql_field($field, $field_type = 'int', $set_offset = NULL) {
  1135. $db_type = Database::getConnection()->databaseType();
  1136. $offset = $set_offset !== NULL ? $set_offset : views_get_timezone();
  1137. if (isset($offset) && !is_numeric($offset)) {
  1138. $dtz = new DateTimeZone($offset);
  1139. $dt = new DateTime("now", $dtz);
  1140. $offset_seconds = $dtz->getOffset($dt);
  1141. }
  1142. switch ($db_type) {
  1143. case 'mysql':
  1144. switch ($field_type) {
  1145. case 'int':
  1146. $field = "DATE_ADD('19700101', INTERVAL $field SECOND)";
  1147. break;
  1148. case 'datetime':
  1149. break;
  1150. }
  1151. if (!empty($offset)) {
  1152. $field = "($field + INTERVAL $offset_seconds SECOND)";
  1153. }
  1154. return $field;
  1155. case 'pgsql':
  1156. switch ($field_type) {
  1157. case 'int':
  1158. $field = "TO_TIMESTAMP($field)";
  1159. break;
  1160. case 'datetime':
  1161. break;
  1162. }
  1163. if (!empty($offset)) {
  1164. $field = "($field + INTERVAL '$offset_seconds SECONDS')";
  1165. }
  1166. return $field;
  1167. case 'sqlite':
  1168. if (!empty($offset)) {
  1169. $field = "($field + '$offset_seconds')";
  1170. }
  1171. return $field;
  1172. }
  1173. }
  1174. /**
  1175. * Helper function to create cross-database SQL date formatting.
  1176. *
  1177. * @param string $format
  1178. * A format string for the result, like 'Y-m-d H:i:s'.
  1179. * @param string $field
  1180. * The real table and field name, like 'tablename.fieldname'.
  1181. * @param string $field_type
  1182. * The type of date field, 'int' or 'datetime'.
  1183. * @param string $set_offset
  1184. * The name of a field that holds the timezone offset or a fixed timezone
  1185. * offset value. If not provided, the normal Drupal timezone handling will be
  1186. * used, i.e. $set_offset = 0 will make no timezone adjustment.
  1187. *
  1188. * @return string
  1189. * An appropriate SQL string for the db type and field type.
  1190. */
  1191. function views_date_sql_format($format, $field, $field_type = 'int', $set_offset = NULL) {
  1192. $db_type = Database::getConnection()->databaseType();
  1193. $field = views_date_sql_field($field, $field_type, $set_offset);
  1194. switch ($db_type) {
  1195. case 'mysql':
  1196. $replace = array(
  1197. 'Y' => '%Y',
  1198. 'y' => '%y',
  1199. 'M' => '%b',
  1200. 'm' => '%m',
  1201. 'n' => '%c',
  1202. 'F' => '%M',
  1203. 'D' => '%a',
  1204. 'd' => '%d',
  1205. 'l' => '%W',
  1206. 'j' => '%e',
  1207. 'W' => '%v',
  1208. 'H' => '%H',
  1209. 'h' => '%h',
  1210. 'i' => '%i',
  1211. 's' => '%s',
  1212. 'A' => '%p',
  1213. );
  1214. $format = strtr($format, $replace);
  1215. return "DATE_FORMAT($field, '$format')";
  1216. case 'pgsql':
  1217. $replace = array(
  1218. 'Y' => 'YYYY',
  1219. 'y' => 'YY',
  1220. 'M' => 'Mon',
  1221. 'm' => 'MM',
  1222. // No format for Numeric representation of a month, without leading
  1223. // zeros.
  1224. 'n' => 'MM',
  1225. 'F' => 'Month',
  1226. 'D' => 'Dy',
  1227. 'd' => 'DD',
  1228. 'l' => 'Day',
  1229. // No format for Day of the month without leading zeros.
  1230. 'j' => 'DD',
  1231. 'W' => 'WW',
  1232. 'H' => 'HH24',
  1233. 'h' => 'HH12',
  1234. 'i' => 'MI',
  1235. 's' => 'SS',
  1236. 'A' => 'AM',
  1237. );
  1238. $format = strtr($format, $replace);
  1239. return "TO_CHAR($field, '$format')";
  1240. case 'sqlite':
  1241. $replace = array(
  1242. // 4 digit year number.
  1243. 'Y' => '%Y',
  1244. // No format for 2 digit year number.
  1245. 'y' => '%Y',
  1246. // No format for 3 letter month name.
  1247. 'M' => '%m',
  1248. // Month number with leading zeros.
  1249. 'm' => '%m',
  1250. // No format for month number without leading zeros.
  1251. 'n' => '%m',
  1252. // No format for full month name.
  1253. 'F' => '%m',
  1254. // No format for 3 letter day name.
  1255. 'D' => '%d',
  1256. // Day of month number with leading zeros.
  1257. 'd' => '%d',
  1258. // No format for full day name.
  1259. 'l' => '%d',
  1260. // No format for day of month number without leading zeros.
  1261. 'j' => '%d',
  1262. // ISO week number.
  1263. 'W' => '%W',
  1264. // 24 hour hour with leading zeros.
  1265. 'H' => '%H',
  1266. // No format for 12 hour hour with leading zeros.
  1267. 'h' => '%H',
  1268. // Minutes with leading zeros.
  1269. 'i' => '%M',
  1270. // Seconds with leading zeros.
  1271. 's' => '%S',
  1272. // No format for AM/PM.
  1273. 'A' => '',
  1274. );
  1275. $format = strtr($format, $replace);
  1276. return "strftime('$format', $field, 'unixepoch')";
  1277. }
  1278. }
  1279. /**
  1280. * Helper function to create cross-database SQL date extraction.
  1281. *
  1282. * @param string $extract_type
  1283. * The type of value to extract from the date, like 'MONTH'.
  1284. * @param string $field
  1285. * The real table and field name, like 'tablename.fieldname'.
  1286. * @param string $field_type
  1287. * The type of date field, 'int' or 'datetime'.
  1288. * @param string $set_offset
  1289. * The name of a field that holds the timezone offset or a fixed timezone
  1290. * offset value. If not provided, the normal Drupal timezone handling
  1291. * will be used, i.e. $set_offset = 0 will make no timezone adjustment.
  1292. *
  1293. * @return string
  1294. * An appropriate SQL string for the db type and field type.
  1295. */
  1296. function views_date_sql_extract($extract_type, $field, $field_type = 'int', $set_offset = NULL) {
  1297. $db_type = Database::getConnection()->databaseType();
  1298. $field = views_date_sql_field($field, $field_type, $set_offset);
  1299. // Note there is no space after FROM to avoid db_rewrite problems
  1300. // @see http://drupal.org/node/79904.
  1301. switch ($extract_type) {
  1302. case('DATE'):
  1303. return $field;
  1304. case('YEAR'):
  1305. return "EXTRACT(YEAR FROM($field))";
  1306. case('MONTH'):
  1307. return "EXTRACT(MONTH FROM($field))";
  1308. case('DAY'):
  1309. return "EXTRACT(DAY FROM($field))";
  1310. case('HOUR'):
  1311. return "EXTRACT(HOUR FROM($field))";
  1312. case('MINUTE'):
  1313. return "EXTRACT(MINUTE FROM($field))";
  1314. case('SECOND'):
  1315. return "EXTRACT(SECOND FROM($field))";
  1316. case('WEEK'):
  1317. // ISO week number for date.
  1318. switch ($db_type) {
  1319. case('mysql'):
  1320. // WEEK using arg 3 in mysql should return the same value as postgres
  1321. // EXTRACT.
  1322. return "WEEK($field, 3)";
  1323. case('pgsql'):
  1324. return "EXTRACT(WEEK FROM($field))";
  1325. }
  1326. case('DOW'):
  1327. switch ($db_type) {
  1328. // MySQL returns 1 for Sunday through 7 for Saturday.
  1329. case('mysql'):
  1330. return "INTEGER(DAYOFWEEK($field) - 1)";
  1331. // PHP date functions and postgres use 0 for Sunday and 6 for Saturday.
  1332. case('pgsql'):
  1333. return "EXTRACT(DOW FROM($field))";
  1334. }
  1335. case('DOY'):
  1336. switch ($db_type) {
  1337. case('mysql'):
  1338. return "DAYOFYEAR($field)";
  1339. case('pgsql'):
  1340. return "EXTRACT(DOY FROM($field))";
  1341. }
  1342. }
  1343. }
  1344. /**
  1345. * @}
  1346. */
  1347. /**
  1348. * @defgroup views_join_handlers Views join handlers
  1349. * @{
  1350. * Handlers to tell Views how to join tables together.
  1351. *
  1352. * Here is how you do complex joins:
  1353. *
  1354. * @code
  1355. * class views_join_complex extends views_join {
  1356. * // PHP 4 doesn't call constructors of the base class automatically from a
  1357. * // constructor of a derived class. It is your responsibility to propagate
  1358. * // the call to constructors upstream where appropriate.
  1359. * public function construct($table = NULL, $left_table = NULL, $left_field = NULL, $field = NULL, $extra = array(), $type = 'LEFT') {
  1360. * parent::construct($table, $left_table, $left_field, $field, $extra, $type);
  1361. * }
  1362. *
  1363. * public function build_join($select_query, $table, $view_query) {
  1364. * $this->extra = 'foo.bar = baz.boing';
  1365. * parent::build_join($select_query, $table, $view_query);
  1366. * }
  1367. * }
  1368. * @endcode
  1369. */
  1370. /**
  1371. * A function class to represent a join and create the SQL necessary
  1372. * to implement the join.
  1373. *
  1374. * This is the Delegation pattern. If we had PHP5 exclusively, we would
  1375. * declare this an interface.
  1376. *
  1377. * Extensions of this class can be used to create more interesting joins.
  1378. *
  1379. * 'join' definition:
  1380. * - table: table to join (right table)
  1381. * - field: field to join on (right field)
  1382. * - left_table: The table we join to
  1383. * - left_field: The field we join to
  1384. * - type: either LEFT (default) or INNER
  1385. * - extra: An array of extra conditions on the join. Each condition is
  1386. * either a string that's directly added, or an array of items:
  1387. * - - table: If not set, current table; if NULL, no table. If you specify a
  1388. * table in cached definition, Views will try to load from an existing
  1389. * alias. If you use realtime joins, it works better.
  1390. * - - field: Field or formula
  1391. * in formulas we can reference the right table by using %alias
  1392. *
  1393. * @see SelectQueryInterface::addJoin()
  1394. * - operator: Defaults to =.
  1395. * - value: Must be set. If an array, operator will be defaulted to IN.
  1396. * - numeric: If true, the value will not be surrounded in quotes.
  1397. * - extra type: How all the extras will be combined. Either AND or OR.
  1398. * Defaults to AND.
  1399. */
  1400. class views_join {
  1401. public $table = NULL;
  1402. public $left_table = NULL;
  1403. public $left_field = NULL;
  1404. public $field = NULL;
  1405. public $extra = NULL;
  1406. public $type = NULL;
  1407. public $definition = array();
  1408. /**
  1409. * Construct the views_join object.
  1410. */
  1411. public function construct($table = NULL, $left_table = NULL, $left_field = NULL, $field = NULL, $extra = array(), $type = 'LEFT') {
  1412. $this->extra_type = 'AND';
  1413. if (!empty($table)) {
  1414. $this->table = $table;
  1415. $this->left_table = $left_table;
  1416. $this->left_field = $left_field;
  1417. $this->field = $field;
  1418. $this->extra = $extra;
  1419. $this->type = strtoupper($type);
  1420. }
  1421. elseif (!empty($this->definition)) {
  1422. // If no arguments, construct from definition. These four must exist or
  1423. // it will throw notices.
  1424. $this->table = $this->definition['table'];
  1425. $this->left_table = $this->definition['left_table'];
  1426. $this->left_field = $this->definition['left_field'];
  1427. $this->field = $this->definition['field'];
  1428. if (!empty($this->definition['extra'])) {
  1429. $this->extra = $this->definition['extra'];
  1430. }
  1431. if (!empty($this->definition['extra type'])) {
  1432. $this->extra_type = strtoupper($this->definition['extra type']);
  1433. }
  1434. $this->type = !empty($this->definition['type']) ? strtoupper($this->definition['type']) : 'LEFT';
  1435. }
  1436. }
  1437. /**
  1438. * Build the SQL for the join this object represents.
  1439. *
  1440. * When possible, try to use table alias instead of table names.
  1441. *
  1442. * @param SelectQueryInterface $select_query
  1443. * An Implements SelectQueryInterface.
  1444. * @param string $table
  1445. * The base table to join.
  1446. * @param views_plugin_query $view_query
  1447. * The source query, Implements views_plugin_query.
  1448. */
  1449. public function build_join($select_query, $table, $view_query) {
  1450. if (empty($this->definition['table formula'])) {
  1451. $right_table = $this->table;
  1452. }
  1453. else {
  1454. $right_table = $this->definition['table formula'];
  1455. }
  1456. if ($this->left_table) {
  1457. $left = $view_query->get_table_info($this->left_table);
  1458. $left_field = "$left[alias].$this->left_field";
  1459. }
  1460. else {
  1461. // This can be used if left_field is a formula or something. It should be
  1462. // used only *very* rarely.
  1463. $left_field = $this->left_field;
  1464. }
  1465. $condition = "$left_field = $table[alias].$this->field";
  1466. $arguments = array();
  1467. // Tack on the extra.
  1468. if (isset($this->extra)) {
  1469. // If extra has been provided as string instead of an array, convert it
  1470. // to an array.
  1471. if (!is_array($this->extra)) {
  1472. $this->extra = array($this->extra);
  1473. }
  1474. $extras = array();
  1475. foreach ($this->extra as $info) {
  1476. if (is_array($info)) {
  1477. $extra = '';
  1478. // Figure out the table name. Remember, only use aliases provided if
  1479. // at all possible.
  1480. $join_table = '';
  1481. if (!array_key_exists('table', $info)) {
  1482. $join_table = $table['alias'] . '.';
  1483. }
  1484. elseif (isset($info['table'])) {
  1485. // If we're aware of a table alias for this table, use the table
  1486. // alias instead of the table name.
  1487. if (isset($left) && $left['table'] == $info['table']) {
  1488. $join_table = $left['alias'] . '.';
  1489. }
  1490. else {
  1491. $join_table = $info['table'] . '.';
  1492. }
  1493. }
  1494. // Convert a single-valued array of values to the single-value case,
  1495. // and transform from IN() notation to = notation.
  1496. if (is_array($info['value']) && count($info['value']) == 1) {
  1497. if (empty($info['operator'])) {
  1498. $operator = '=';
  1499. }
  1500. else {
  1501. $operator = $info['operator'] == 'NOT IN' ? '!=' : '=';
  1502. }
  1503. $info['value'] = array_shift($info['value']);
  1504. }
  1505. if (is_array($info['value'])) {
  1506. $value_placeholders = array();
  1507. // With an array of values, we need multiple placeholders and the
  1508. // 'IN' operator is implicit.
  1509. foreach ($info['value'] as $value) {
  1510. $placeholder_i = $view_query->placeholder('views_join_condition_');
  1511. $value_placeholders[] = $placeholder_i;
  1512. $arguments[$placeholder_i] = $value;
  1513. }
  1514. $operator = !empty($info['operator']) ? $info['operator'] : 'IN';
  1515. $placeholder = '( ' . implode(', ', $value_placeholders) . ' )';
  1516. }
  1517. else {
  1518. // With a single value, the '=' operator is implicit.
  1519. $operator = !empty($info['operator']) ? $info['operator'] : '=';
  1520. $placeholder = $view_query->placeholder('views_join_condition_');
  1521. $arguments[$placeholder] = $info['value'];
  1522. }
  1523. $extras[] = "$join_table$info[field] $operator $placeholder";
  1524. }
  1525. elseif (is_string($info)) {
  1526. $extras[] = $info;
  1527. }
  1528. }
  1529. if ($extras) {
  1530. if (count($extras) == 1) {
  1531. $condition .= ' AND (' . array_shift($extras) . ')';
  1532. }
  1533. else {
  1534. $condition .= ' AND (' . implode(' ' . $this->extra_type . ' ', $extras) . ')';
  1535. }
  1536. }
  1537. }
  1538. $select_query->addJoin($this->type, $right_table, $table['alias'], $condition, $arguments);
  1539. }
  1540. }
  1541. /**
  1542. * Join handler for relationships that join with a subquery as the left field.
  1543. *
  1544. * For example:
  1545. * LEFT JOIN node node_term_data ON ([YOUR SUBQUERY HERE]) = node_term_data.nid
  1546. *
  1547. * 'join' definition:
  1548. * Same as views_join class above, except:
  1549. * - left_query: The subquery to use in the left side of the join clause.
  1550. */
  1551. class views_join_subquery extends views_join {
  1552. /**
  1553. * {@inheritdoc}
  1554. */
  1555. public function construct($table = NULL, $left_table = NULL, $left_field = NULL, $field = NULL, $extra = array(), $type = 'LEFT') {
  1556. parent::construct($table, $left_table, $left_field, $field, $extra, $type);
  1557. $this->left_query = $this->definition['left_query'];
  1558. }
  1559. /**
  1560. * Build the SQL for the join this object represents.
  1561. *
  1562. * @param object $select_query
  1563. * An Implements SelectQueryInterface.
  1564. * @param string $table
  1565. * The base table to join.
  1566. * @param array $view_query
  1567. * The source query, Implements views_plugin_query.
  1568. */
  1569. public function build_join($select_query, $table, $view_query) {
  1570. if (empty($this->definition['table formula'])) {
  1571. $right_table = "{" . $this->table . "}";
  1572. }
  1573. else {
  1574. $right_table = $this->definition['table formula'];
  1575. }
  1576. // Add our join condition, using a subquery on the left instead of a field.
  1577. $condition = "($this->left_query) = $table[alias].$this->field";
  1578. $arguments = array();
  1579. // Tack on the extra.
  1580. // This is just copied verbatim from the parent class, which itself has a
  1581. // bug.
  1582. // @see http://drupal.org/node/1118100
  1583. if (isset($this->extra)) {
  1584. // If extra has been provided as string instead of an array, convert it
  1585. // to an array.
  1586. if (!is_array($this->extra)) {
  1587. $this->extra = array($this->extra);
  1588. }
  1589. $extras = array();
  1590. foreach ($this->extra as $info) {
  1591. if (is_array($info)) {
  1592. $extra = '';
  1593. // Figure out the table name. Remember, only use aliases provided if
  1594. // at all possible.
  1595. $join_table = '';
  1596. if (!array_key_exists('table', $info)) {
  1597. $join_table = $table['alias'] . '.';
  1598. }
  1599. elseif (isset($info['table'])) {
  1600. $join_table = $info['table'] . '.';
  1601. }
  1602. $placeholder = ':views_join_condition_' . $select_query->nextPlaceholder();
  1603. if (is_array($info['value'])) {
  1604. $operator = !empty($info['operator']) ? $info['operator'] : 'IN';
  1605. // Transform from IN() notation to = notation if just one value.
  1606. if (count($info['value']) == 1) {
  1607. $info['value'] = array_shift($info['value']);
  1608. $operator = $operator == 'NOT IN' ? '!=' : '=';
  1609. }
  1610. }
  1611. else {
  1612. $operator = !empty($info['operator']) ? $info['operator'] : '=';
  1613. }
  1614. $extras[] = "$join_table$info[field] $operator $placeholder";
  1615. $arguments[$placeholder] = $info['value'];
  1616. }
  1617. elseif (is_string($info)) {
  1618. $extras[] = $info;
  1619. }
  1620. }
  1621. if ($extras) {
  1622. if (count($extras) == 1) {
  1623. $condition .= ' AND (' . array_shift($extras) . ')';
  1624. }
  1625. else {
  1626. $condition .= ' AND (' . implode(' ' . $this->extra_type . ' ', $extras) . ')';
  1627. }
  1628. }
  1629. }
  1630. $select_query->addJoin($this->type, $right_table, $table['alias'], $condition, $arguments);
  1631. }
  1632. }
  1633. /**
  1634. * @}
  1635. */