views_bulk_operations.module 44 KB

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