views_bulk_operations.module 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283
  1. <?php
  2. /**
  3. * @file
  4. * Allows operations to be performed on items selected in a view.
  5. */
  6. // Access operations.
  7. define('VBO_ACCESS_OP_VIEW', 0x01);
  8. define('VBO_ACCESS_OP_UPDATE', 0x02);
  9. define('VBO_ACCESS_OP_CREATE', 0x04);
  10. define('VBO_ACCESS_OP_DELETE', 0x08);
  11. /**
  12. * Implements hook_action_info().
  13. * Registers custom VBO actions as Drupal actions.
  14. */
  15. function views_bulk_operations_action_info() {
  16. $actions = array();
  17. $files = views_bulk_operations_load_action_includes();
  18. foreach ($files as $filename) {
  19. $action_info_fn = 'views_bulk_operations_'. str_replace('.', '_', basename($filename, '.inc')).'_info';
  20. $action_info = call_user_func($action_info_fn);
  21. if (is_array($action_info)) {
  22. $actions += $action_info;
  23. }
  24. }
  25. return $actions;
  26. }
  27. /**
  28. * Loads the VBO actions placed in their own include files (under actions/).
  29. *
  30. * @return
  31. * An array of containing filenames of the included actions.
  32. */
  33. function views_bulk_operations_load_action_includes() {
  34. static $loaded = FALSE;
  35. // The list of VBO actions is fairly static, so it's hardcoded for better
  36. // performance (hitting the filesystem with file_scan_directory(), and then
  37. // caching the result has its cost).
  38. $path = drupal_get_path('module', 'views_bulk_operations') . '/actions/';
  39. $files = array(
  40. 'archive.action.inc',
  41. 'argument_selector.action.inc',
  42. 'book.action.inc',
  43. 'delete.action.inc',
  44. 'modify.action.inc',
  45. 'script.action.inc',
  46. 'user_roles.action.inc',
  47. 'user_cancel.action.inc',
  48. );
  49. if (!$loaded) {
  50. foreach ($files as $file) {
  51. include_once $path . $file;
  52. }
  53. $loaded = TRUE;
  54. }
  55. return $files;
  56. }
  57. /**
  58. * Implements hook_cron().
  59. *
  60. * Deletes queue items belonging to VBO active queues (used by VBO's batches)
  61. * that are older than a day (since they can only be a result of VBO crashing
  62. * or the execution being interrupted in some other way). This is the interval
  63. * used to cleanup batches in system_cron(), so it can't be increased.
  64. *
  65. * Note: This code is specific to SystemQueue. Other queue implementations will
  66. * need to do their own garbage collection.
  67. */
  68. function views_bulk_operations_cron() {
  69. db_delete('queue')
  70. ->condition('name', db_like('views_bulk_operations_active_queue_'), 'LIKE')
  71. ->condition('created', REQUEST_TIME - 864000, '<')
  72. ->execute();
  73. }
  74. /**
  75. * Implements of hook_cron_queue_info().
  76. */
  77. function views_bulk_operations_cron_queue_info() {
  78. return array(
  79. 'views_bulk_operations' => array(
  80. 'worker callback' => 'views_bulk_operations_queue_item_process',
  81. 'time' => 30,
  82. ),
  83. );
  84. }
  85. /**
  86. * Implements hook_views_api().
  87. */
  88. function views_bulk_operations_views_api() {
  89. return array(
  90. 'api' => 3,
  91. 'path' => drupal_get_path('module', 'views_bulk_operations') . '/views',
  92. );
  93. }
  94. /**
  95. * Implements hook_theme().
  96. */
  97. function views_bulk_operations_theme() {
  98. $themes = array(
  99. 'views_bulk_operations_select_all' => array(
  100. 'variables' => array('view' => NULL, 'enable_select_all_pages' => TRUE),
  101. ),
  102. 'views_bulk_operations_confirmation' => array(
  103. 'variables' => array('rows' => NULL, 'vbo' => NULL, 'operation' => NULL, 'select_all_pages' => FALSE),
  104. ),
  105. );
  106. $files = views_bulk_operations_load_action_includes();
  107. foreach ($files as $filename) {
  108. $action_theme_fn = 'views_bulk_operations_'. str_replace('.', '_', basename($filename, '.inc')).'_theme';
  109. if (function_exists($action_theme_fn)) {
  110. $themes += call_user_func($action_theme_fn);
  111. }
  112. }
  113. return $themes;
  114. }
  115. /**
  116. * Implements hook_ctools_plugin_type().
  117. */
  118. function views_bulk_operations_ctools_plugin_type() {
  119. return array(
  120. 'operation_types' => array(
  121. 'classes' => array(
  122. 'handler',
  123. ),
  124. ),
  125. );
  126. }
  127. /**
  128. * Implements hook_ctools_plugin_directory().
  129. */
  130. function views_bulk_operations_ctools_plugin_directory($module, $plugin) {
  131. if ($module == 'views_bulk_operations') {
  132. return 'plugins/' . $plugin;
  133. }
  134. }
  135. /**
  136. * Fetch metadata for a specific operation type plugin.
  137. *
  138. * @param $operation_type
  139. * Name of the plugin.
  140. *
  141. * @return
  142. * An array with information about the requested operation type plugin.
  143. */
  144. function views_bulk_operations_get_operation_type($operation_type) {
  145. ctools_include('plugins');
  146. return ctools_get_plugins('views_bulk_operations', 'operation_types', $operation_type);
  147. }
  148. /**
  149. * Fetch metadata for all operation type plugins.
  150. *
  151. * @return
  152. * An array of arrays with information about all available operation types.
  153. */
  154. function views_bulk_operations_get_operation_types() {
  155. ctools_include('plugins');
  156. return ctools_get_plugins('views_bulk_operations', 'operation_types');
  157. }
  158. /**
  159. * Gets the info array of an operation from the provider plugin.
  160. *
  161. * @param $operation_id
  162. * The id of the operation for which the info shall be returned, or NULL
  163. * to return an array with info about all operations.
  164. */
  165. function views_bulk_operations_get_operation_info($operation_id = NULL) {
  166. $operations = &drupal_static(__FUNCTION__);
  167. if (!isset($operations)) {
  168. $operations = array();
  169. $plugins = views_bulk_operations_get_operation_types();
  170. foreach ($plugins as $plugin) {
  171. $operations += $plugin['list callback']();
  172. }
  173. uasort($operations, create_function('$a, $b', 'return strcasecmp($a["label"], $b["label"]);'));
  174. }
  175. if (!empty($operation_id)) {
  176. return $operations[$operation_id];
  177. }
  178. else {
  179. return $operations;
  180. }
  181. }
  182. /**
  183. * Returns an operation instance.
  184. *
  185. * @param $operation_id
  186. * The id of the operation to instantiate.
  187. * For example: action::node_publish_action.
  188. * @param $entity_type
  189. * The entity type on which the operation operates.
  190. * @param $options
  191. * Options for this operation (label, operation settings, etc.)
  192. */
  193. function views_bulk_operations_get_operation($operation_id, $entity_type, $options) {
  194. $operations = &drupal_static(__FUNCTION__);
  195. if (!isset($operations[$operation_id])) {
  196. // Intentionally not using views_bulk_operations_get_operation_info() here
  197. // since it's an expensive function that loads all the operations on the
  198. // system, despite the fact that we might only need a few.
  199. $id_fragments = explode('::', $operation_id);
  200. $plugin = views_bulk_operations_get_operation_type($id_fragments[0]);
  201. $operation_info = $plugin['list callback']($operation_id);
  202. if ($operation_info) {
  203. $operations[$operation_id] = new $plugin['handler']['class']($operation_id, $entity_type, $operation_info, $options);
  204. }
  205. else {
  206. $operations[$operation_id] = FALSE;
  207. }
  208. }
  209. return $operations[$operation_id];
  210. }
  211. /**
  212. * Get all operations that match the current entity type.
  213. *
  214. * @param $entity_type
  215. * Entity type.
  216. * @param $options
  217. * An array of options for all operations, in the form of
  218. * $operation_id => $operation_options.
  219. */
  220. function views_bulk_operations_get_applicable_operations($entity_type, $options) {
  221. $operations = array();
  222. foreach (views_bulk_operations_get_operation_info() as $operation_id => $operation_info) {
  223. if ($operation_info['type'] == $entity_type || $operation_info['type'] == 'entity' || $operation_info['type'] == 'system') {
  224. $options[$operation_id] = !empty($options[$operation_id]) ? $options[$operation_id] : array();
  225. $operations[$operation_id] = views_bulk_operations_get_operation($operation_id, $entity_type, $options[$operation_id]);
  226. }
  227. }
  228. return $operations;
  229. }
  230. /**
  231. * Gets the VBO field if it exists on the passed-in view.
  232. *
  233. * @return
  234. * The field object if found. Otherwise, FALSE.
  235. */
  236. function _views_bulk_operations_get_field($view) {
  237. foreach ($view->field as $field_name => $field) {
  238. if ($field instanceof views_bulk_operations_handler_field_operations) {
  239. // Add in the view object for convenience.
  240. $field->view = $view;
  241. return $field;
  242. }
  243. }
  244. return FALSE;
  245. }
  246. /**
  247. * Implements hook_views_form_substitutions().
  248. */
  249. function views_bulk_operations_views_form_substitutions() {
  250. // Views check_plains the column label, so VBO needs to do the same
  251. // in order for the replace operation to succeed.
  252. $select_all_placeholder = check_plain('<!--views-bulk-operations-select-all-->');
  253. $select_all = array(
  254. '#type' => 'checkbox',
  255. '#default_value' => FALSE,
  256. '#attributes' => array('class' => array('vbo-table-select-all')),
  257. );
  258. return array(
  259. $select_all_placeholder => drupal_render($select_all),
  260. );
  261. }
  262. /**
  263. * Implements hook_form_alter().
  264. */
  265. function views_bulk_operations_form_alter(&$form, &$form_state, $form_id) {
  266. if (strpos($form_id, 'views_form_') === 0) {
  267. $vbo = _views_bulk_operations_get_field($form_state['build_info']['args'][0]);
  268. }
  269. // Not a VBO-enabled views form.
  270. if (empty($vbo)) {
  271. return;
  272. }
  273. // Add basic VBO functionality.
  274. if ($form_state['step'] == 'views_form_views_form') {
  275. // The submit button added by Views Form API might be used by a non-VBO Views
  276. // Form handler. If there's no such handler on the view, hide the button.
  277. $has_other_views_form_handlers = FALSE;
  278. foreach ($vbo->view->field as $field) {
  279. if (property_exists($field, 'views_form_callback') || method_exists($field, 'views_form')) {
  280. if (!($field instanceof views_bulk_operations_handler_field_operations)) {
  281. $has_other_views_form_handlers = TRUE;
  282. }
  283. }
  284. }
  285. if (!$has_other_views_form_handlers) {
  286. $form['actions']['#access'] = FALSE;
  287. }
  288. // The VBO field is excluded from display, stop here.
  289. if (!empty($vbo->options['exclude'])) {
  290. return;
  291. }
  292. $form = views_bulk_operations_form($form, $form_state, $vbo);
  293. }
  294. // Cache the built form to prevent it from being rebuilt prior to validation
  295. // and submission, which could lead to data being processed incorrectly,
  296. // because the views rows (and thus, the form elements as well) have changed
  297. // in the meantime. Matching views issue: http://drupal.org/node/1473276.
  298. $form_state['cache'] = TRUE;
  299. if (empty($vbo->view->override_url)) {
  300. // If the VBO view is embedded using views_embed_view(), or in a block,
  301. // $view->get_url() doesn't point to the current page, which means that
  302. // the form doesn't get processed.
  303. if (!empty($vbo->view->preview) || $vbo->view->display_handler instanceof views_plugin_display_block) {
  304. $vbo->view->override_url = $_GET['q'];
  305. // We are changing the override_url too late, the form action was already
  306. // set by Views to the previous URL, so it needs to be overriden as well.
  307. $query = drupal_get_query_parameters($_GET, array('q'));
  308. $form['#action'] = url($_GET['q'], array('query' => $query));
  309. }
  310. }
  311. // Give other modules a chance to alter the form.
  312. drupal_alter('views_bulk_operations_form', $form, $form_state, $vbo);
  313. }
  314. /**
  315. * Implements hook_views_post_build().
  316. *
  317. * Hides the VBO field if no operations are available.
  318. * This causes the entire VBO form to be hidden.
  319. *
  320. * @see views_bulk_operations_form_alter().
  321. */
  322. function views_bulk_operations_views_post_build(&$view) {
  323. $vbo = _views_bulk_operations_get_field($view);
  324. if ($vbo && $vbo->get_selected_operations() < 1) {
  325. $vbo->options['exclude'] = TRUE;
  326. }
  327. }
  328. /**
  329. * Returns the 'select all' div that gets inserted below the table header row
  330. * (for table style plugins with grouping disabled), or above the view results
  331. * (for non-table style plugins), providing a choice between selecting items
  332. * on the current page, and on all pages.
  333. *
  334. * The actual insertion is done by JS, matching the degradation behavior
  335. * of Drupal core (no JS - no select all).
  336. */
  337. function theme_views_bulk_operations_select_all($variables) {
  338. $view = $variables['view'];
  339. $enable_select_all_pages = $variables['enable_select_all_pages'];
  340. $form = array();
  341. if ($view->style_plugin instanceof views_plugin_style_table && empty($view->style_plugin->options['grouping'])) {
  342. if (!$enable_select_all_pages) {
  343. return '';
  344. }
  345. $wrapper_class = 'vbo-table-select-all-markup';
  346. $this_page_count = format_plural(count($view->result), '1 row', '@count rows');
  347. $this_page = t('Selected <strong>!row_count</strong> in this page.', array('!row_count' => $this_page_count));
  348. $all_pages_count = format_plural($view->total_rows, '1 row', '@count rows');
  349. $all_pages = t('Selected <strong>!row_count</strong> in this view.', array('!row_count' => $all_pages_count));
  350. $form['select_all_pages'] = array(
  351. '#type' => 'button',
  352. '#attributes' => array('class' => array('vbo-table-select-all-pages')),
  353. '#value' => t('Select all !row_count in this view.', array('!row_count' => $all_pages_count)),
  354. '#prefix' => '<span class="vbo-table-this-page">' . $this_page . ' &nbsp;',
  355. '#suffix' => '</span>',
  356. );
  357. $form['select_this_page'] = array(
  358. '#type' => 'button',
  359. '#attributes' => array('class' => array('vbo-table-select-this-page')),
  360. '#value' => t('Select only !row_count in this page.', array('!row_count' => $this_page_count)),
  361. '#prefix' => '<span class="vbo-table-all-pages" style="display: none">' . $all_pages . ' &nbsp;',
  362. '#suffix' => '</span>',
  363. );
  364. }
  365. else {
  366. $wrapper_class = 'vbo-select-all-markup';
  367. $form['select_all'] = array(
  368. '#type' => 'fieldset',
  369. '#attributes' => array('class' => array('vbo-fieldset-select-all')),
  370. );
  371. $form['select_all']['this_page'] = array(
  372. '#type' => 'checkbox',
  373. '#title' => t('Select all items on this page'),
  374. '#default_value' => '',
  375. '#attributes' => array('class' => array('vbo-select-this-page')),
  376. );
  377. if ($enable_select_all_pages) {
  378. $form['select_all']['or'] = array(
  379. '#type' => 'markup',
  380. '#markup' => '<em>OR</em>',
  381. );
  382. $form['select_all']['all_pages'] = array(
  383. '#type' => 'checkbox',
  384. '#title' => t('Select all items on all pages'),
  385. '#default_value' => '',
  386. '#attributes' => array('class' => array('vbo-select-all-pages')),
  387. );
  388. }
  389. }
  390. $output = '<div class="' . $wrapper_class . '">';
  391. $output .= drupal_render($form);
  392. $output .= '</div>';
  393. return $output;
  394. }
  395. /**
  396. * Extend the views_form multistep form with elements for executing an operation.
  397. */
  398. function views_bulk_operations_form($form, &$form_state, $vbo) {
  399. $form['#attached']['js'][] = drupal_get_path('module', 'views_bulk_operations') . '/js/views_bulk_operations.js';
  400. $form['#attached']['css'][] = drupal_get_path('module', 'views_bulk_operations') . '/css/views_bulk_operations.css';
  401. // Wrap the form in a div with specific classes for JS targeting and theming.
  402. $class = 'vbo-views-form';
  403. if (empty($vbo->view->result)) {
  404. $class .= ' vbo-views-form-empty';
  405. }
  406. $form['#prefix'] = '<div class="' . $class . '">';
  407. $form['#suffix'] = '</div>';
  408. // Force browser to reload the page if Back is hit.
  409. if (!empty($_SERVER['HTTP_USER_AGENT']) && preg_match('/msie/i', $_SERVER['HTTP_USER_AGENT'])) {
  410. drupal_add_http_header('Cache-Control', 'no-cache'); // works for IE6+
  411. }
  412. else {
  413. drupal_add_http_header('Cache-Control', 'no-store'); // works for Firefox and other browsers
  414. }
  415. // Set by JS to indicate that all rows on all pages are selected.
  416. $form['select_all'] = array(
  417. '#type' => 'hidden',
  418. '#attributes' => array('class' => 'select-all-rows'),
  419. '#default_value' => FALSE,
  420. );
  421. $form['select'] = array(
  422. '#type' => 'fieldset',
  423. '#title' => t('Operations'),
  424. '#collapsible' => FALSE,
  425. '#attributes' => array('class' => array('container-inline')),
  426. );
  427. if ($vbo->get_vbo_option('display_type') == 0) {
  428. $options = array(0 => t('- Choose an operation -'));
  429. foreach ($vbo->get_selected_operations() as $operation_id => $operation) {
  430. $options[$operation_id] = $operation->label();
  431. }
  432. // Create dropdown and submit button.
  433. $form['select']['operation'] = array(
  434. '#type' => 'select',
  435. '#options' => $options,
  436. );
  437. $form['select']['submit'] = array(
  438. '#type' => 'submit',
  439. '#value' => t('Execute'),
  440. '#validate' => array('views_bulk_operations_form_validate'),
  441. '#submit' => array('views_bulk_operations_form_submit'),
  442. );
  443. }
  444. else {
  445. // Create buttons for operations.
  446. foreach ($vbo->get_selected_operations() as $operation_id => $operation) {
  447. $form['select'][$operation_id] = array(
  448. '#type' => 'submit',
  449. '#value' => $operation->label(),
  450. '#validate' => array('views_bulk_operations_form_validate'),
  451. '#submit' => array('views_bulk_operations_form_submit'),
  452. '#operation_id' => $operation_id,
  453. );
  454. }
  455. }
  456. // Adds the "select all" functionality if the view has results.
  457. // If the view is using a table style plugin, the markup gets moved to
  458. // a table row below the header.
  459. // If we are using radio buttons, we don't use select all at all.
  460. if (!empty($vbo->view->result) && !$vbo->get_vbo_option('force_single')) {
  461. $enable_select_all_pages = FALSE;
  462. // If the view is paginated, and "select all items on all pages" is
  463. // enabled, tell that to the theme function.
  464. if (count($vbo->view->result) != $vbo->view->total_rows && $vbo->get_vbo_option('enable_select_all_pages')) {
  465. $enable_select_all_pages = TRUE;
  466. }
  467. $form['select_all_markup'] = array(
  468. '#type' => 'markup',
  469. '#markup' => theme('views_bulk_operations_select_all', array('view' => $vbo->view, 'enable_select_all_pages' => $enable_select_all_pages)),
  470. );
  471. }
  472. return $form;
  473. }
  474. /**
  475. * Validation callback for the first step of the VBO form.
  476. */
  477. function views_bulk_operations_form_validate($form, &$form_state) {
  478. $vbo = _views_bulk_operations_get_field($form_state['build_info']['args'][0]);
  479. if (!empty($form_state['triggering_element']['#operation_id'])) {
  480. $form_state['values']['operation'] = $form_state['triggering_element']['#operation_id'];
  481. }
  482. if (!$form_state['values']['operation']) {
  483. form_set_error('operation', t('No operation selected. Please select an operation to perform.'));
  484. }
  485. $field_name = $vbo->options['id'];
  486. $selection = _views_bulk_operations_get_selection($vbo, $form_state);
  487. if (!$selection) {
  488. form_set_error($field_name, t('Please select at least one item.'));
  489. }
  490. }
  491. /**
  492. * Multistep form callback for the "configure" step.
  493. */
  494. function views_bulk_operations_config_form($form, &$form_state, $view, $output) {
  495. $vbo = _views_bulk_operations_get_field($view);
  496. $operation = $form_state['operation'];
  497. drupal_set_title(t('Set parameters for %operation', array('%operation' => $operation->label())), PASS_THROUGH);
  498. $context = array(
  499. 'entity_type' => $vbo->get_entity_type(),
  500. // Pass the View along.
  501. // Has no performance penalty since objects are passed by reference,
  502. // but needing the full views object in a core action is in most cases
  503. // a sign of a wrong implementation. Do it only if you have to.
  504. 'view' => $view,
  505. );
  506. $form += $operation->form($form, $form_state, $context);
  507. $query = drupal_get_query_parameters($_GET, array('q'));
  508. $form['actions'] = array(
  509. '#type' => 'container',
  510. '#attributes' => array('class' => array('form-actions')),
  511. '#weight' => 999,
  512. );
  513. $form['actions']['submit'] = array(
  514. '#type' => 'submit',
  515. '#value' => t('Next'),
  516. '#validate' => array('views_bulk_operations_config_form_validate'),
  517. '#submit' => array('views_bulk_operations_form_submit'),
  518. '#suffix' => l(t('Cancel'), $vbo->view->get_url(), array('query' => $query)),
  519. );
  520. return $form;
  521. }
  522. /**
  523. * Validation callback for the "configure" step.
  524. * Gives the operation a chance to validate its config form.
  525. */
  526. function views_bulk_operations_config_form_validate($form, &$form_state) {
  527. $operation = &$form_state['operation'];
  528. $operation->formValidate($form, $form_state);
  529. }
  530. /**
  531. * Multistep form callback for the "confirm" step.
  532. */
  533. function views_bulk_operations_confirm_form($form, &$form_state, $view, $output) {
  534. $vbo = _views_bulk_operations_get_field($view);
  535. $operation = $form_state['operation'];
  536. $rows = $form_state['selection'];
  537. $query = drupal_get_query_parameters($_GET, array('q'));
  538. $form = confirm_form($form,
  539. t('Are you sure you want to perform %operation on the selected items?', array('%operation' => $operation->label())),
  540. array('path' => $view->get_url(), 'query' => $query),
  541. theme('views_bulk_operations_confirmation', array('rows' => $rows, 'vbo' => $vbo, 'operation' => $operation, 'select_all_pages' => $form_state['select_all_pages']))
  542. );
  543. // Add VBO's submit handler to the Confirm button added by config_form().
  544. $form['actions']['submit']['#submit'] = array('views_bulk_operations_form_submit');
  545. return $form;
  546. }
  547. /**
  548. * Theme function to show the confirmation page before executing the operation.
  549. */
  550. function theme_views_bulk_operations_confirmation($variables) {
  551. $select_all_pages = $variables['select_all_pages'];
  552. $vbo = $variables['vbo'];
  553. $entity_type = $vbo->get_entity_type();
  554. $rows = $variables['rows'];
  555. $items = array();
  556. // Load the entities from the current page, and show their titles.
  557. $entities = _views_bulk_operations_entity_load($entity_type, array_values($rows), $vbo->revision);
  558. foreach ($entities as $entity) {
  559. $items[] = check_plain(_views_bulk_operations_entity_label($entity_type, $entity));
  560. }
  561. // All rows on all pages have been selected, so show a count of additional items.
  562. if ($select_all_pages) {
  563. $more_count = $vbo->view->total_rows - count($vbo->view->result);
  564. $items[] = t('...and <strong>!count</strong> more.', array('!count' => $more_count));
  565. }
  566. $count = format_plural(count($entities), 'item', '@count items');
  567. $output = theme('item_list', array('items' => $items, 'title' => t('You selected the following <strong>!count</strong>:', array('!count' => $count))));
  568. return $output;
  569. }
  570. /**
  571. * Goes through the submitted values, and returns
  572. * an array of selected rows, in the form of
  573. * $row_index => $entity_id.
  574. */
  575. function _views_bulk_operations_get_selection($vbo, $form_state) {
  576. $selection = array();
  577. $field_name = $vbo->options['id'];
  578. if (!empty($form_state['values'][$field_name])) {
  579. // If using "force single", the selection needs to be converted to an array.
  580. if (is_array($form_state['values'][$field_name])) {
  581. $selection = array_filter($form_state['values'][$field_name]);
  582. }
  583. else {
  584. $selection = array($form_state['values'][$field_name]);
  585. }
  586. }
  587. return $selection;
  588. }
  589. /**
  590. * Submit handler for all steps of the VBO multistep form.
  591. */
  592. function views_bulk_operations_form_submit($form, &$form_state) {
  593. $vbo = _views_bulk_operations_get_field($form_state['build_info']['args'][0]);
  594. $entity_type = $vbo->get_entity_type();
  595. switch ($form_state['step']) {
  596. case 'views_form_views_form':
  597. $form_state['selection'] = _views_bulk_operations_get_selection($vbo, $form_state);
  598. $form_state['select_all_pages'] = $form_state['values']['select_all'];
  599. $options = $vbo->get_operation_options($form_state['values']['operation']);
  600. $form_state['operation'] = $operation = views_bulk_operations_get_operation($form_state['values']['operation'], $entity_type, $options);
  601. if (!$operation->configurable() && $operation->getAdminOption('skip_confirmation')) {
  602. break; // Go directly to execution
  603. }
  604. $form_state['step'] = $operation->configurable() ? 'views_bulk_operations_config_form' : 'views_bulk_operations_confirm_form';
  605. $form_state['rebuild'] = TRUE;
  606. return;
  607. case 'views_bulk_operations_config_form':
  608. $form_state['step'] = 'views_bulk_operations_confirm_form';
  609. $operation = &$form_state['operation'];
  610. $operation->formSubmit($form, $form_state);
  611. if ($operation->getAdminOption('skip_confirmation')) {
  612. break; // Go directly to execution
  613. }
  614. $form_state['rebuild'] = TRUE;
  615. return;
  616. case 'views_bulk_operations_confirm_form':
  617. break;
  618. }
  619. // Execute the operation.
  620. views_bulk_operations_execute($vbo, $form_state['operation'], $form_state['selection'], $form_state['select_all_pages']);
  621. // Redirect.
  622. $query = drupal_get_query_parameters($_GET, array('q'));
  623. $form_state['redirect'] = array('path' => $vbo->view->get_url(), array('query' => $query));
  624. }
  625. /**
  626. * Entry point for executing the chosen operation upon selected rows.
  627. *
  628. * If the selected operation is an aggregate operation (requiring all selected
  629. * items to be passed at the same time), restricted to a single value, or has
  630. * the skip_batching option set, the operation is executed directly.
  631. * This means that there is no batching & queueing, the PHP execution
  632. * time limit is ignored (if allowed), all selected entities are loaded and
  633. * processed.
  634. *
  635. * Otherwise, the selected entity ids are divided into groups not larger than
  636. * $entity_load_capacity, and enqueued for processing.
  637. * If all items on all pages should be processed, a batch job runs that
  638. * collects and enqueues the items from all pages of the view, page by page.
  639. *
  640. * Based on the "Enqueue the operation instead of executing it directly"
  641. * VBO field setting, the newly filled queue is either processed at cron
  642. * time by the VBO worker function, or right away in a new batch job.
  643. *
  644. * @param $vbo
  645. * The VBO field, containing a reference to the view in $vbo->view.
  646. * @param $operation
  647. * The operation object.
  648. * @param $selection
  649. * An array in the form of $row_index => $entity_id.
  650. * @param $select_all_pages
  651. * Whether all items on all pages should be selected.
  652. */
  653. function views_bulk_operations_execute($vbo, $operation, $selection, $select_all_pages = FALSE) {
  654. global $user;
  655. // Determine if the operation needs to be executed directly.
  656. $aggregate = $operation->aggregate();
  657. $skip_batching = $vbo->get_vbo_option('skip_batching');
  658. $force_single = $vbo->get_vbo_option('force_single');
  659. $execute_directly = ($aggregate || $skip_batching || $force_single);
  660. // Try to load all rows without a batch if needed.
  661. if ($execute_directly && $select_all_pages) {
  662. views_bulk_operations_direct_adjust($selection, $vbo);
  663. }
  664. // Options that affect execution.
  665. $options = array(
  666. 'revision' => $vbo->revision,
  667. 'entity_load_capacity' => $vbo->get_vbo_option('entity_load_capacity', 10),
  668. // The information needed to recreate the view, to avoid serializing the
  669. // whole object. Passed to the executed operation. Also used by
  670. // views_bulk_operations_adjust_selection().
  671. 'view_info' => array(
  672. 'name' => $vbo->view->name,
  673. 'display' => $vbo->view->current_display,
  674. 'arguments' => $vbo->view->args,
  675. 'exposed_input' => $vbo->view->get_exposed_input(),
  676. ),
  677. );
  678. // Create an array of rows in the needed format.
  679. $rows = array();
  680. $current = 1;
  681. foreach ($selection as $row_index => $entity_id) {
  682. $rows[$row_index] = array(
  683. 'entity_id' => $entity_id,
  684. 'views_row' => array(),
  685. // Some operations rely on knowing the position of the current item
  686. // in the execution set (because of specific things that need to be done
  687. // at the beginning or the end of the set).
  688. 'position' => array(
  689. 'current' => $current++,
  690. 'total' => count($selection),
  691. ),
  692. );
  693. // Some operations require full selected rows.
  694. if ($operation->needsRows()) {
  695. $rows[$row_index]['views_row'] = $vbo->view->result[$row_index];
  696. }
  697. }
  698. if ($execute_directly) {
  699. // Execute the operation directly and stop here.
  700. views_bulk_operations_direct_process($operation, $rows, $options);
  701. return;
  702. }
  703. // Determine the correct queue to use.
  704. if ($operation->getAdminOption('postpone_processing')) {
  705. // Use the site queue processed on cron.
  706. $queue_name = 'views_bulk_operations';
  707. }
  708. else {
  709. // Use the active queue processed immediately by Batch API.
  710. $queue_name = 'views_bulk_operations_active_queue_' . db_next_id();
  711. }
  712. $batch = array(
  713. 'operations' => array(),
  714. 'finished' => 'views_bulk_operations_execute_finished',
  715. 'progress_message' => '',
  716. 'title' => t('Performing %operation on the selected items...', array('%operation' => $operation->label())),
  717. );
  718. // All items on all pages should be selected, add a batch job to gather
  719. // and enqueue them.
  720. if ($select_all_pages && $vbo->view->query->pager->has_more_records()) {
  721. $total_rows = $vbo->view->total_rows;
  722. $batch['operations'][] = array(
  723. 'views_bulk_operations_adjust_selection', array($queue_name, $operation, $options),
  724. );
  725. }
  726. else {
  727. $total_rows = count($rows);
  728. // We have all the items that we need, enqueue them right away.
  729. views_bulk_operations_enqueue_rows($queue_name, $rows, $operation, $options);
  730. // Provide a status message to the user, since this is the last step if
  731. // processing is postponed.
  732. if ($operation->getAdminOption('postpone_processing')) {
  733. drupal_set_message(t('Enqueued the selected operation (%operation).', array(
  734. '%operation' => $operation->label(),
  735. )));
  736. }
  737. }
  738. // Processing is not postponed, add a batch job to process the queue.
  739. if (!$operation->getAdminOption('postpone_processing')) {
  740. $batch['operations'][] = array(
  741. 'views_bulk_operations_active_queue_process', array($queue_name, $operation, $total_rows),
  742. );
  743. }
  744. // If there are batch jobs to be processed, create the batch set.
  745. if (count($batch['operations'])) {
  746. batch_set($batch);
  747. }
  748. }
  749. /**
  750. * Batch API callback: loads the view page by page and enqueues all items.
  751. *
  752. * @param $queue_name
  753. * The name of the queue to which the items should be added.
  754. * @param $operation
  755. * The operation object.
  756. * @param $options
  757. * An array of options that affect execution (revision, entity_load_capacity,
  758. * view_info). Passed along with each new queue item.
  759. */
  760. function views_bulk_operations_adjust_selection($queue_name, $operation, $options, &$context) {
  761. if (!isset($context['sandbox']['progress'])) {
  762. $context['sandbox']['progress'] = 0;
  763. $context['sandbox']['max'] = 0;
  764. }
  765. $view_info = $options['view_info'];
  766. $view = views_get_view($view_info['name']);
  767. $view->set_exposed_input($view_info['exposed_input']);
  768. $view->set_arguments($view_info['arguments']);
  769. $view->set_display($view_info['display']);
  770. $view->set_offset($context['sandbox']['progress']);
  771. $view->build();
  772. $view->execute($view_info['display']);
  773. // Note the total number of rows.
  774. if (empty($context['sandbox']['max'])) {
  775. $context['sandbox']['max'] = $view->total_rows;
  776. }
  777. $vbo = _views_bulk_operations_get_field($view);
  778. $rows = array();
  779. foreach ($view->result as $row_index => $result) {
  780. $rows[$row_index] = array(
  781. 'entity_id' => $vbo->get_value($result),
  782. 'views_row' => array(),
  783. 'position' => array(
  784. 'current' => ++$context['sandbox']['progress'],
  785. 'total' => $view->total_rows,
  786. ),
  787. );
  788. // Some operations require full selected rows.
  789. if ($operation->needsRows()) {
  790. $rows[$row_index]['views_row'] = $result;
  791. }
  792. }
  793. // Enqueue the gathered rows.
  794. views_bulk_operations_enqueue_rows($queue_name, $rows, $operation, $options);
  795. if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
  796. // Provide an estimation of the completion level we've reached.
  797. $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  798. $context['message'] = t('Prepared @current out of @total', array('@current' => $context['sandbox']['progress'], '@total' => $context['sandbox']['max']));
  799. }
  800. else {
  801. // Provide a status message to the user if this is the last batch job.
  802. if ($operation->getAdminOption('postpone_processing')) {
  803. $context['results']['log'][] = t('Enqueued the selected operation (%operation).', array(
  804. '%operation' => $operation->label(),
  805. ));
  806. }
  807. }
  808. }
  809. /**
  810. * Divides the passed rows into groups and enqueues each group for processing
  811. *
  812. * @param $queue_name
  813. * The name of the queue.
  814. * @param $rows
  815. * The rows to be enqueued.
  816. * @param $operation
  817. * The object representing the current operation.
  818. * Passed along with each new queue item.
  819. * @param $options
  820. * An array of options that affect execution (revision, entity_load_capacity).
  821. * Passed along with each new queue item.
  822. */
  823. function views_bulk_operations_enqueue_rows($queue_name, $rows, $operation, $options) {
  824. global $user;
  825. $queue = DrupalQueue::get($queue_name, TRUE);
  826. $row_groups = array_chunk($rows, $options['entity_load_capacity'], TRUE);
  827. foreach ($row_groups as $row_group) {
  828. $entity_ids = array();
  829. foreach ($row_group as $row) {
  830. $entity_ids[] = $row['entity_id'];
  831. }
  832. $job = array(
  833. 'title' => t('Perform %operation on @type !entity_ids.', array(
  834. '%operation' => $operation->label(),
  835. '@type' => $operation->entityType,
  836. '!entity_ids' => implode(',', $entity_ids),
  837. )),
  838. 'uid' => $user->uid,
  839. 'arguments' => array($row_group, $operation, $options),
  840. );
  841. $queue->createItem($job);
  842. }
  843. }
  844. /**
  845. * Batch API callback: processes the active queue.
  846. *
  847. * @param $queue_name
  848. * The name of the queue to process.
  849. * @param $operation
  850. * The object representing the current operation.
  851. * @param $total_rows
  852. * The total number of processable items (across all queue items), used
  853. * to report progress.
  854. *
  855. * @see views_bulk_operations_queue_item_process()
  856. */
  857. function views_bulk_operations_active_queue_process($queue_name, $operation, $total_rows, &$context) {
  858. static $queue;
  859. // It is still possible to hit the time limit.
  860. drupal_set_time_limit(0);
  861. // Prepare the sandbox.
  862. if (!isset($context['sandbox']['progress'])) {
  863. $context['sandbox']['progress'] = 0;
  864. $context['sandbox']['max'] = $total_rows;
  865. $context['results']['log'] = array();
  866. }
  867. // Instantiate the queue.
  868. if (!isset($queue)) {
  869. $queue = DrupalQueue::get($queue_name, TRUE);
  870. }
  871. // Process the queue as long as it has items for us.
  872. $queue_item = $queue->claimItem(3600);
  873. if ($queue_item) {
  874. // Process the queue item, and update the progress count.
  875. views_bulk_operations_queue_item_process($queue_item->data, $context['results']['log']);
  876. $queue->deleteItem($queue_item);
  877. // Provide an estimation of the completion level we've reached.
  878. $context['sandbox']['progress'] += count($queue_item->data['arguments'][0]);
  879. $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  880. $context['message'] = t('Processed @current out of @total', array('@current' => $context['sandbox']['progress'], '@total' => $context['sandbox']['max']));
  881. }
  882. if (!$queue_item || $context['finished'] === 1) {
  883. // All done. Provide a status message to the user.
  884. $context['results']['log'][] = t('Performed %operation on @items.', array(
  885. '%operation' => $operation->label(),
  886. '@items' => format_plural($context['sandbox']['progress'], '1 item', '@count items'),
  887. ));
  888. }
  889. }
  890. /**
  891. * Processes the provided queue item.
  892. *
  893. * Used as a worker callback defined by views_bulk_operations_cron_queue_info()
  894. * to process the site queue, as well as by
  895. * views_bulk_operations_active_queue_process() to process the active queue.
  896. *
  897. * @param $queue_item_arguments
  898. * The arguments of the queue item to process.
  899. * @param $log
  900. * An injected array of log messages, to be modified by reference.
  901. * If NULL, the function defaults to using watchdog.
  902. */
  903. function views_bulk_operations_queue_item_process($queue_item_data, &$log = NULL) {
  904. list($row_group, $operation, $options) = $queue_item_data['arguments'];
  905. $account = user_load($queue_item_data['uid']);
  906. $entity_type = $operation->entityType;
  907. $entity_ids = array();
  908. foreach ($row_group as $row_index => $row) {
  909. $entity_ids[] = $row['entity_id'];
  910. }
  911. $entities = _views_bulk_operations_entity_load($entity_type, $entity_ids, $options['revision']);
  912. foreach ($row_group as $row_index => $row) {
  913. $entity_id = $row['entity_id'];
  914. // A matching entity couldn't be loaded. Skip this item.
  915. if (!isset($entities[$entity_id])) {
  916. continue;
  917. }
  918. if ($options['revision']) {
  919. // Don't reload revisions for now, they are not statically cached and
  920. // usually don't run into the edge case described below.
  921. $entity = $entities[$entity_id];
  922. }
  923. else {
  924. // A previous action might have resulted in the entity being resaved
  925. // (e.g. node synchronization from a prior node in this batch), so try
  926. // to reload it. If no change occurred, the entity will be retrieved
  927. // from the static cache, resulting in no performance penalty.
  928. $entity = entity_load_single($entity_type, $entity_id);
  929. if (empty($entity)) {
  930. // The entity is no longer valid.
  931. continue;
  932. }
  933. }
  934. // If the current entity can't be accessed, skip it and log a notice.
  935. if (!_views_bulk_operations_entity_access($operation, $entity_type, $entity, $account)) {
  936. $message = 'Skipped %operation on @type %title due to insufficient permissions.';
  937. $arguments = array(
  938. '%operation' => $operation->label(),
  939. '@type' => $entity_type,
  940. '%title' => _views_bulk_operations_entity_label($entity_type, $entity),
  941. );
  942. if ($log) {
  943. $log[] = t($message, $arguments);
  944. }
  945. else {
  946. watchdog('views bulk operations', $message, $arguments, WATCHDOG_ALERT);
  947. }
  948. continue;
  949. }
  950. $operation_context = array(
  951. 'progress' => $row['position'],
  952. 'view_info' => $options['view_info'],
  953. );
  954. if ($operation->needsRows()) {
  955. $operation_context['rows'] = array($row_index => $row['views_row']);
  956. }
  957. $operation->execute($entity, $operation_context);
  958. unset($row_group[$row_index]);
  959. }
  960. }
  961. /**
  962. * Adjusts the selection for the direct execution method.
  963. *
  964. * Just like the direct method itself, this is legacy code, used only for
  965. * aggregate actions.
  966. */
  967. function views_bulk_operations_direct_adjust(&$selection, $vbo) {
  968. // Adjust selection to select all rows across pages.
  969. $view = views_get_view($vbo->view->name);
  970. $view->set_exposed_input($vbo->view->get_exposed_input());
  971. $view->set_arguments($vbo->view->args);
  972. $view->set_display($vbo->view->current_display);
  973. $view->display_handler->set_option('pager', array('type' => 'none', 'options' => array()));
  974. $view->build();
  975. // Unset every field except the VBO one (which holds the entity id).
  976. // That way the performance hit becomes much smaller, because there is no
  977. // chance of views_handler_field_field::post_execute() firing entity_load().
  978. foreach ($view->field as $field_name => $field) {
  979. if ($field_name != $vbo->options['id']) {
  980. unset($view->field[$field_name]);
  981. }
  982. }
  983. $view->execute($vbo->view->current_display);
  984. $results = array();
  985. foreach ($view->result as $row_index => $result) {
  986. $results[$row_index] = $vbo->get_value($result);
  987. }
  988. $selection = $results;
  989. }
  990. /**
  991. * Processes the passed rows directly (without batching and queueing).
  992. */
  993. function views_bulk_operations_direct_process($operation, $rows, $options) {
  994. global $user;
  995. drupal_set_time_limit(0);
  996. // Prepare an array of status information. Imitates the Batch API naming
  997. // for consistency. Passed to views_bulk_operations_execute_finished().
  998. $context = array();
  999. $context['results']['progress'] = 0;
  1000. $context['results']['log'] = array();
  1001. if ($operation->aggregate()) {
  1002. // Load all entities.
  1003. $entity_type = $operation->entityType;
  1004. $entity_ids = array();
  1005. foreach ($rows as $row_index => $row) {
  1006. $entity_ids[] = $row['entity_id'];
  1007. }
  1008. $entities = _views_bulk_operations_entity_load($entity_type, $entity_ids, $options['revision']);
  1009. // Filter out entities that can't be accessed.
  1010. foreach ($entities as $id => $entity) {
  1011. if (!_views_bulk_operations_entity_access($operation, $entity_type, $entity)) {
  1012. $context['results']['log'][] = t('Skipped %operation on @type %title due to insufficient permissions.', array(
  1013. '%operation' => $operation->label(),
  1014. '@type' => $entity_type,
  1015. '%title' => _views_bulk_operations_entity_label($entity_type, $entity),
  1016. ));
  1017. unset($entities[$id]);
  1018. }
  1019. }
  1020. // If there are any entities left, execute the operation on them.
  1021. if ($entities) {
  1022. $operation_context = array(
  1023. 'view_info' => $options['view_info'],
  1024. );
  1025. // Pass the selected rows to the operation if needed.
  1026. if ($operation->needsRows()) {
  1027. $operation_context['rows'] = array();
  1028. foreach ($rows as $row_index => $row) {
  1029. $operation_context['rows'][$row_index] = $row['views_row'];
  1030. }
  1031. }
  1032. $operation->execute($entities, $operation_context);
  1033. }
  1034. }
  1035. else {
  1036. // Imitate a queue and process the entities one by one.
  1037. $queue_item_data = array(
  1038. 'uid' => $user->uid,
  1039. 'arguments' => array($rows, $operation, $options),
  1040. );
  1041. views_bulk_operations_queue_item_process($queue_item_data, $context['results']['log']);
  1042. }
  1043. $context['results']['progress'] += count($rows);
  1044. $context['results']['log'][] = t('Performed %operation on @items.', array(
  1045. '%operation' => $operation->label(),
  1046. '@items' => format_plural(count($rows), '1 item', '@count items'),
  1047. ));
  1048. views_bulk_operations_execute_finished(TRUE, $context['results'], array());
  1049. }
  1050. /**
  1051. * Helper function that runs after the execution process is complete.
  1052. */
  1053. function views_bulk_operations_execute_finished($success, $results, $operations) {
  1054. if ($success) {
  1055. if (count($results['log']) > 1) {
  1056. $message = theme('item_list', array('items' => $results['log']));
  1057. }
  1058. else {
  1059. $message = reset($results['log']);
  1060. }
  1061. }
  1062. else {
  1063. // An error occurred.
  1064. // $operations contains the operations that remained unprocessed.
  1065. $error_operation = reset($operations);
  1066. $message = t('An error occurred while processing @operation with arguments: @arguments',
  1067. array('@operation' => $error_operation[0], '@arguments' => print_r($error_operation[0], TRUE)));
  1068. }
  1069. _views_bulk_operations_log($message);
  1070. }
  1071. /**
  1072. * Helper function to verify access permission to operate on an entity.
  1073. */
  1074. function _views_bulk_operations_entity_access($operation, $entity_type, $entity, $account = NULL) {
  1075. if (!entity_type_supports($entity_type, 'access')) {
  1076. return TRUE;
  1077. }
  1078. $access_ops = array(
  1079. VBO_ACCESS_OP_VIEW => 'view',
  1080. VBO_ACCESS_OP_UPDATE => 'update',
  1081. VBO_ACCESS_OP_CREATE => 'create',
  1082. VBO_ACCESS_OP_DELETE => 'delete',
  1083. );
  1084. foreach ($access_ops as $bit => $op) {
  1085. if ($operation->getAccessMask() & $bit) {
  1086. if (!entity_access($op, $entity_type, $entity, $account)) {
  1087. return FALSE;
  1088. }
  1089. }
  1090. }
  1091. return TRUE;
  1092. }
  1093. /**
  1094. * Loads multiple entities by their entity or revision ids, and returns them,
  1095. * keyed by the id used for loading.
  1096. */
  1097. function _views_bulk_operations_entity_load($entity_type, $ids, $revision = FALSE) {
  1098. if (!$revision) {
  1099. $entities = entity_load($entity_type, $ids);
  1100. }
  1101. else {
  1102. // D7 can't load multiple entities by revision_id. Lovely.
  1103. $info = entity_get_info($entity_type);
  1104. $entities = array();
  1105. foreach ($ids as $revision_id) {
  1106. $loaded_entities = entity_load($entity_type, array(), array($info['entity keys']['revision'] => $revision_id));
  1107. $entities[$revision_id] = reset($loaded_entities);
  1108. }
  1109. }
  1110. return $entities;
  1111. }
  1112. /**
  1113. * Label function for entities.
  1114. * Core entities don't declare the "label" key, so entity_label() fails,
  1115. * and a fallback is needed. This function provides that fallback.
  1116. */
  1117. function _views_bulk_operations_entity_label($entity_type, $entity) {
  1118. $label = entity_label($entity_type, $entity);
  1119. if (!$label) {
  1120. $entity_info = entity_get_info($entity_type);
  1121. $id_key = $entity_info['entity keys']['id'];
  1122. // Many entity types (e.g. "user") have a name which fits the label perfectly.
  1123. if (isset($entity->name)) {
  1124. $label = $entity->name;
  1125. }
  1126. elseif (isset($entity->{$id_key})) {
  1127. // Fallback to the id key.
  1128. $label = $entity->{$id_key};
  1129. }
  1130. }
  1131. return $label;
  1132. }
  1133. /**
  1134. * Helper function to report an error.
  1135. */
  1136. function _views_bulk_operations_report_error($msg, $arg) {
  1137. watchdog('views bulk operations', $msg, $arg, WATCHDOG_ERROR);
  1138. if (function_exists('drush_set_error')) {
  1139. drush_set_error('VIEWS_BULK_OPERATIONS_EXECUTION_ERROR', strip_tags(dt($msg, $arg)));
  1140. }
  1141. }
  1142. /**
  1143. * Display a message to the user through the relevant function.
  1144. */
  1145. function _views_bulk_operations_log($msg) {
  1146. // Is VBO being run through drush?
  1147. if (function_exists('drush_log')) {
  1148. drush_log(strip_tags($msg), 'ok');
  1149. }
  1150. else {
  1151. drupal_set_message($msg);
  1152. }
  1153. }