handlers.inc 55 KB

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