ui.forms.inc 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  1. <?php
  2. /**
  3. * @file Rules UI forms
  4. */
  5. /**
  6. * Ajax callback for reloading the whole form.
  7. */
  8. function rules_ui_form_ajax_reload_form($form, $form_state) {
  9. return $form;
  10. }
  11. /**
  12. * Defines #ajax properties.
  13. */
  14. function rules_ui_form_default_ajax($effect = 'slide') {
  15. return array(
  16. 'callback' => 'rules_ui_form_ajax_reload_form',
  17. 'wrapper' => 'rules-form-wrapper',
  18. 'effect' => $effect,
  19. 'speed' => 'fast',
  20. );
  21. }
  22. /**
  23. * Submit handler for switching the parameter input mode.
  24. */
  25. function rules_ui_parameter_replace_submit($form, &$form_state) {
  26. if (isset($form_state['triggering_element'])) {
  27. $name = $form_state['triggering_element']['#parameter'];
  28. $form_state['parameter_mode'][$name] = $form_state['parameter_mode'][$name] == 'selector' ? 'input' : 'selector';
  29. }
  30. $form_state['rebuild'] = TRUE;
  31. }
  32. /**
  33. * General form submit handler, that rebuilds the form
  34. */
  35. function rules_form_submit_rebuild($form, &$form_state) {
  36. $form_state['rebuild'] = TRUE;
  37. }
  38. /**
  39. * Edit a rules configuration.
  40. */
  41. function rules_ui_form_edit_rules_config($form, &$form_state, $rules_config, $base_path) {
  42. RulesPluginUI::$basePath = $base_path;
  43. $form_state += array('rules_element' => $rules_config);
  44. // Add the rule configuration's form.
  45. $rules_config->form($form, $form_state, array('show settings' => TRUE, 'button' => TRUE));
  46. $form['#validate'] = array('rules_ui_form_rules_config_validate');
  47. return $form;
  48. }
  49. /**
  50. * General rules configuration form validation callback. Also populates the
  51. * rules configuration with the form values.
  52. */
  53. function rules_ui_form_rules_config_validate($form, &$form_state) {
  54. $form_state['rules_element']->form_validate($form, $form_state);
  55. }
  56. /**
  57. * Edit a rules configuration form submit callback.
  58. */
  59. function rules_ui_form_edit_rules_config_submit($form, &$form_state) {
  60. $form_state['rules_element']->form_submit($form, $form_state);
  61. drupal_set_message(t('Your changes have been saved.'));
  62. if (empty($form_state['redirect'])) {
  63. $form_state['redirect'] = RulesPluginUI::defaultRedirect($form_state['rules_element']);
  64. }
  65. }
  66. /**
  67. * Clone a rules configuration form.
  68. */
  69. function rules_ui_form_clone_rules_config($form, &$form_state, $rules_config, $base_path) {
  70. RulesPluginUI::$basePath = $base_path;
  71. $rules_config = clone $rules_config;
  72. $rules_config->id = NULL;
  73. $rules_config->name = '';
  74. $rules_config->label .= ' (' . t('cloned') . ')';
  75. $rules_config->status = ENTITY_CUSTOM;
  76. $form['#validate'][] = 'rules_ui_form_rules_config_validate';
  77. $form['#submit'][] = 'rules_ui_form_edit_rules_config_submit';
  78. $form_state += array('rules_element' => $rules_config, 'op' => 'clone');
  79. // Add the rule configuration's form.
  80. $rules_config->form($form, $form_state, array('show settings' => TRUE, 'button' => TRUE, 'init' => TRUE));
  81. // Open the settings fieldset so altering the name is easier.
  82. $form['settings']['#collapsed'] = FALSE;
  83. return $form;
  84. }
  85. /**
  86. * A simple form just showing a textarea with the export.
  87. */
  88. function rules_ui_form_export_rules_config($form, &$form_state, $rules_config, $base_path) {
  89. $form['export'] = array(
  90. '#type' => 'textarea',
  91. '#title' => t('Export'),
  92. '#description' => t('For importing copy the content of the text area and paste it into the import page.'),
  93. '#rows' => 25,
  94. '#default_value' => $rules_config->export(),
  95. );
  96. return $form;
  97. }
  98. /**
  99. * Configuration form to directly execute a rules configuration.
  100. */
  101. function rules_ui_form_execute_rules_config($form, &$form_state, $rules_config, $base_path) {
  102. // Only components can be executed.
  103. if (!($rules_config instanceof RulesTriggerableInterface)) {
  104. RulesPluginUI::$basePath = $base_path;
  105. // Create either the appropriate action or condition element.
  106. $element = rules_plugin_factory($rules_config instanceof RulesActionInterface ? 'action' : 'condition', 'component_' . $rules_config->name);
  107. $form['exec_help'] = array(
  108. '#prefix' => '<p>',
  109. '#markup' => t('This form allows you to manually trigger the execution of the @plugin "%label". If this component requires any parameters, input the suiting execution arguments below.', array('@plugin' => $rules_config->plugin(), '%label' => $rules_config->label())),
  110. '#suffix' => '</p>',
  111. );
  112. $element->form($form, $form_state);
  113. // For conditions hide the option to negate them.
  114. if (isset($form['negate'])) {
  115. $form['negate']['#access'] = FALSE;
  116. }
  117. $form['submit'] = array(
  118. '#type' => 'submit',
  119. '#value' => t('Execute'),
  120. '#weight' => 20,
  121. );
  122. // Re-use the validation callback, which will also populate the action with
  123. // the configuration settings in the form.
  124. $form['#validate'] = array('rules_ui_form_rules_config_validate');
  125. return $form;
  126. }
  127. drupal_not_found();
  128. exit;
  129. }
  130. /**
  131. * Submit callback for directly executing a component.
  132. */
  133. function rules_ui_form_execute_rules_config_submit($form, &$form_state) {
  134. $element = $form_state['rules_element'];
  135. $result = $element->execute();
  136. if ($element instanceof RulesActionInterface) {
  137. drupal_set_message(t('Component %label has been executed.', array('%label' => $element->label())));
  138. }
  139. else {
  140. drupal_set_message(t('Component %label evaluated to %result.', array('%label' => $element->label(), '%result' => $result ? 'true' : 'false')));
  141. }
  142. }
  143. /**
  144. * Gets the confirmation question for valid operations, or else FALSE.
  145. */
  146. function rules_ui_confirm_operations($op, $rules_config) {
  147. $vars = array('%plugin' => $rules_config->plugin(), '%label' => $rules_config->label());
  148. switch ($op) {
  149. case 'enable':
  150. return array(t('Are you sure you want to enable the %plugin %label?', $vars), '');
  151. case 'disable':
  152. return array(t('Are you sure you want to disable the %plugin %label?', $vars), '');
  153. case 'revert':
  154. return array(t('Are you sure you want to revert the %plugin %label?', $vars), t('This action cannot be undone.'));
  155. case 'delete':
  156. return array(t('Are you sure you want to delete the %plugin %label?', $vars), t('This action cannot be undone.'));
  157. default:
  158. return FALSE;
  159. }
  160. }
  161. /**
  162. * Confirmation form for applying the operation to the config.
  163. */
  164. function rules_ui_form_rules_config_confirm_op($form, &$form_state, $rules_config, $op, $base_path) {
  165. if (list($confirm_question, $description) = rules_ui_confirm_operations($op, $rules_config)) {
  166. RulesPluginUI::$basePath = $base_path;
  167. $form_state += array('rules_config' => $rules_config, 'op' => $op);
  168. return confirm_form($form, $confirm_question, $base_path, $description, t('Confirm'), t('Cancel'));
  169. }
  170. else {
  171. drupal_not_found();
  172. exit;
  173. }
  174. }
  175. /**
  176. * Applies the operation and returns the message to show to the user. Also the
  177. * operation is logged to the watchdog. Note that the string is defined two
  178. * times so that the translation extractor can find it.
  179. */
  180. function rules_ui_confirm_operation_apply($op, $rules_config) {
  181. $vars = array('%plugin' => $rules_config->plugin(), '%label' => $rules_config->label());
  182. $edit_link = l(t('edit'), RulesPluginUI::path($rules_config->name));
  183. switch ($op) {
  184. case 'enable':
  185. $rules_config->active = TRUE;
  186. $rules_config->save();
  187. watchdog('rules', 'Enabled %plugin %label.', $vars, WATCHDOG_NOTICE, $edit_link);
  188. return t('Enabled %plugin %label.', $vars);
  189. case 'disable':
  190. $rules_config->active = FALSE;
  191. $rules_config->save();
  192. watchdog('rules', 'Disabled %plugin %label.', $vars, WATCHDOG_NOTICE, $edit_link);
  193. return t('Disabled %plugin %label.', $vars);
  194. case 'revert':
  195. $rules_config->delete();
  196. watchdog('rules', 'Reverted %plugin %label to the defaults.', $vars, WATCHDOG_NOTICE, $edit_link);
  197. return t('Reverted %plugin %label to the defaults.', $vars);
  198. case 'delete':
  199. $rules_config->delete();
  200. watchdog('rules', 'Deleted %plugin %label.', $vars);
  201. return t('Deleted %plugin %label.', $vars);
  202. }
  203. }
  204. /**
  205. * Rule config deletion form submit callback.
  206. */
  207. function rules_ui_form_rules_config_confirm_op_submit($form, &$form_state) {
  208. if ($form_state['values']['confirm']) {
  209. $msg = rules_ui_confirm_operation_apply($form_state['op'], $form_state['rules_config']);
  210. drupal_set_message($msg);
  211. }
  212. }
  213. /**
  214. * Add a new element a rules configuration.
  215. */
  216. function rules_ui_add_element($form, &$form_state, $rules_config, $plugin_name, RulesContainerPlugin $parent, $base_path) {
  217. $cache = rules_get_cache();
  218. if (!isset($cache['plugin_info'][$plugin_name]['class'])) {
  219. drupal_not_found();
  220. exit;
  221. }
  222. RulesPluginUI::$basePath = $base_path;
  223. $plugin_is_abstract = in_array('RulesAbstractPlugin', class_parents($cache['plugin_info'][$plugin_name]['class']));
  224. // In the first step create the element and in the second step show its edit
  225. // form.
  226. if ($plugin_is_abstract && !isset($form_state['rules_element'])) {
  227. RulesPluginUI::formDefaults($form, $form_state);
  228. $form_state += array('parent_element' => $parent, 'plugin' => $plugin_name);
  229. $form['element_name'] = array(
  230. '#type' => 'select',
  231. '#title' => t('Select the %element to add', array('%element' => $plugin_name)),
  232. '#options' => RulesPluginUI::getOptions($plugin_name),
  233. '#ajax' => rules_ui_form_default_ajax() + array(
  234. 'trigger_as' => array('name' => 'continue'),
  235. ),
  236. );
  237. $form['continue'] = array(
  238. '#type' => 'submit',
  239. '#name' => 'continue',
  240. '#value' => t('Continue'),
  241. '#ajax' => rules_ui_form_default_ajax(),
  242. );
  243. }
  244. elseif (!$plugin_is_abstract) {
  245. // Create the initial, empty element.
  246. $element = rules_plugin_factory($plugin_name);
  247. // Always add the new element at the bottom, thus set an appropriate weight.
  248. $iterator = $parent->getIterator();
  249. if ($sibling = end($iterator)) {
  250. $element->weight = $sibling->weight + 1;
  251. }
  252. $element->setParent($parent);
  253. $form_state['rules_element'] = $element;
  254. }
  255. if (isset($form_state['rules_element'])) {
  256. $form_state['rules_element']->form($form, $form_state, array('button' => TRUE, 'init' => TRUE));
  257. $form['#validate'][] = 'rules_ui_edit_element_validate';
  258. $form['#submit'][] = 'rules_ui_edit_element_submit';
  259. }
  260. return $form;
  261. }
  262. /**
  263. * Add element submit callback.
  264. * Used for "abstract plugins" to create the initial element object with the
  265. * given implemenation name and rebuild the form.
  266. */
  267. function rules_ui_add_element_submit($form, &$form_state) {
  268. $element = rules_plugin_factory($form_state['plugin'], $form_state['values']['element_name']);
  269. // Always add the new element at the bottom, thus set an appropriate weight.
  270. $iterator = $form_state['parent_element']->getIterator();
  271. if ($sibling = end($iterator)) {
  272. $element->weight = $sibling->weight + 1;
  273. }
  274. // Clear the element settings so they won't be processed on serialization as
  275. // there is nothing to be processed yet.
  276. $element->settings = array();
  277. $element->setParent($form_state['parent_element']);
  278. $form_state['rules_element'] = $element;
  279. $form_state['rebuild'] = TRUE;
  280. }
  281. /**
  282. * Delete elements.
  283. */
  284. function rules_ui_delete_element($form, &$form_state, $rules_config, $rules_element, $base_path) {
  285. RulesPluginUI::$basePath = $base_path;
  286. if (empty($form_state['rules_config'])) {
  287. // Before modifying the rules config we have to clone it, so any
  288. // modifications won't appear in the static cache of the loading controller.
  289. $rules_config = clone $rules_config;
  290. // Also get the element from the cloned config.
  291. $rules_element = $rules_config->elementMap()->lookup($rules_element->elementId());
  292. $form_state['rules_config'] = $rules_config;
  293. $form_state['rules_element'] = $rules_element;
  294. $form_state['element_parent'] = $rules_element->parentElement();
  295. }
  296. // Try deleting the element and warn the user if something breaks, but
  297. // save the parent for determining the right redirect target on submit.
  298. $removed_plugin = $form_state['rules_element']->plugin();
  299. $rules_element->delete();
  300. if (empty($rules_config->dirty) && empty($form_state['input'])) {
  301. try {
  302. $rules_config->integrityCheck();
  303. }
  304. catch (RulesIntegrityException $e) {
  305. $args = array(
  306. '@plugin' => $e->element->plugin(),
  307. '%label' => $e->element->label(),
  308. '@removed-plugin' => $removed_plugin,
  309. '!url' => url(RulesPluginUI::path($form_state['rules_config']->name, 'edit', $e->element)),
  310. );
  311. drupal_set_message(t('Deleting this @removed-plugin would break your configuration as some of its provided variables are utilized by the @plugin <a href="!url">%label</a>.', $args), 'warning');
  312. }
  313. }
  314. $confirm_question = t('Are you sure you want to delete the %element_plugin %element_name?', array('%element_plugin' => $rules_element->plugin(), '%element_name' => $rules_element->label(), '%plugin' => $rules_config->plugin(), '%label' => $rules_config->label()));
  315. return confirm_form($form, $confirm_question, RulesPluginUI::path($rules_config->name), t('This action cannot be undone.'), t('Delete'), t('Cancel'));
  316. }
  317. /**
  318. * Rule config deletion form submit callback.
  319. */
  320. function rules_ui_delete_element_submit($form, &$form_state) {
  321. $rules_config = $form_state['rules_config'];
  322. $rules_config->save();
  323. if (empty($form_state['redirect'])) {
  324. $form_state['redirect'] = RulesPluginUI::defaultRedirect($form_state['element_parent']);
  325. }
  326. }
  327. /**
  328. * Configure a rule element.
  329. */
  330. function rules_ui_edit_element($form, &$form_state, $rules_config, $element, $base_path) {
  331. RulesPluginUI::$basePath = $base_path;
  332. $form_state += array('rules_element' => $element);
  333. $form_state['rules_element']->form($form, $form_state, array('button' => TRUE));
  334. return $form;
  335. }
  336. /**
  337. * Validate the element configuration.
  338. */
  339. function rules_ui_edit_element_validate($form, &$form_state) {
  340. $form_state['rules_element']->form_validate($form, $form_state);
  341. }
  342. /**
  343. * Submit the element configuration.
  344. */
  345. function rules_ui_edit_element_submit($form, &$form_state) {
  346. $form_state['rules_element']->form_submit($form, $form_state);
  347. drupal_set_message(t('Your changes have been saved.'));
  348. if (empty($form_state['redirect'])) {
  349. $form_state['redirect'] = RulesPluginUI::defaultRedirect($form_state['rules_element']);
  350. }
  351. }
  352. /**
  353. * Form builder for the "add event" page.
  354. */
  355. function rules_ui_add_event_page($form, &$form_state, RulesTriggerableInterface $rules_config, $base_path) {
  356. RulesPluginUI::$basePath = $base_path;
  357. RulesPluginUI::formDefaults($form, $form_state);
  358. $form = rules_ui_add_event($form, $form_state, $rules_config, $base_path);
  359. $form['#validate'][] = 'rules_ui_add_event_validate';
  360. return $form;
  361. }
  362. /**
  363. * Submit the event configuration.
  364. */
  365. function rules_ui_add_event_page_submit($form, &$form_state) {
  366. rules_ui_add_event_apply($form, $form_state);
  367. $rules_config = $form_state['rules_config'];
  368. // Tell the user if this breaks something, but let him proceed.
  369. if (empty($rules_config->dirty)) {
  370. try {
  371. $rules_config->integrityCheck();
  372. }
  373. catch (RulesIntegrityException $e) {
  374. $warning = TRUE;
  375. drupal_set_message(t('Added the event, but it does not provide all variables utilized.'), 'warning');
  376. }
  377. }
  378. $rules_config->save();
  379. if (!isset($warning)) {
  380. $events = rules_fetch_data('event_info');
  381. $label = $events[$form_state['values']['event']]['label'];
  382. drupal_set_message(t('Added event %event.', array('%event' => $label)));
  383. }
  384. }
  385. /**
  386. * Add a new event.
  387. */
  388. function rules_ui_add_event($form, &$form_state, RulesReactionRule $rules_config, $base_path) {
  389. $form_state += array('rules_config' => $rules_config);
  390. $events = array_diff_key(rules_fetch_data('event_info'), array_flip($rules_config->events()));
  391. $form['help'] = array(
  392. '#markup' => t('Select the event to add. However note that all added events need to provide all variables that should be available to your rule.'),
  393. );
  394. $form['event'] = array(
  395. '#type' => 'select',
  396. '#title' => t('React on event'),
  397. '#options' => RulesPluginUI::getOptions('event', $events),
  398. '#description' => t('Whenever the event occurs, rule evaluation is triggered.'),
  399. '#ajax' => rules_ui_form_default_ajax(),
  400. '#required' => TRUE,
  401. );
  402. if (!empty($form_state['values']['event'])) {
  403. $handler = rules_get_event_handler($form_state['values']['event']);
  404. $form['event_settings'] = $handler->buildForm($form_state);
  405. }
  406. else {
  407. $form['event_settings'] = array();
  408. }
  409. $form['submit'] = array(
  410. '#type' => 'submit',
  411. '#value' => t('Add'),
  412. );
  413. $form_state['redirect'] = RulesPluginUI::path($rules_config->name);
  414. return $form;
  415. }
  416. /**
  417. * Validation callback for adding an event.
  418. */
  419. function rules_ui_add_event_validate($form, $form_state) {
  420. $handler = rules_get_event_handler($form_state['values']['event']);
  421. $handler->extractFormValues($form['event_settings'], $form_state);
  422. try {
  423. $handler->validate();
  424. }
  425. catch (RulesIntegrityException $e) {
  426. form_set_error(implode('][', $e->keys), $e->getMessage());
  427. }
  428. }
  429. /**
  430. * Submit callback that just adds the selected event.
  431. *
  432. * @see rules_admin_add_reaction_rule()
  433. */
  434. function rules_ui_add_event_apply($form, &$form_state) {
  435. $handler = rules_get_event_handler($form_state['values']['event']);
  436. $handler->extractFormValues($form['event_settings'], $form_state);
  437. $form_state['rules_config']->event($form_state['values']['event'], $handler->getSettings());
  438. }
  439. /**
  440. * Form to remove a event from a rule.
  441. */
  442. function rules_ui_remove_event($form, &$form_state, $rules_config, $event, $base_path) {
  443. RulesPluginUI::$basePath = $base_path;
  444. $form_state += array('rules_config' => $rules_config, 'rules_event' => $event);
  445. $event_info = rules_get_event_info($event);
  446. $form_state['event_label'] = $event_info['label'];
  447. $confirm_question = t('Are you sure you want to remove the event?');
  448. return confirm_form($form, $confirm_question, RulesPluginUI::path($rules_config->name), t('You are about to remove the event %event.', array('%event' => $form_state['event_label'])), t('Remove'), t('Cancel'));
  449. }
  450. /**
  451. * Submit the event configuration.
  452. */
  453. function rules_ui_remove_event_submit($form, &$form_state) {
  454. $rules_config = $form_state['rules_config'];
  455. $rules_config->removeEvent($form_state['rules_event']);
  456. // Tell the user if this breaks something, but let him proceed.
  457. if (empty($rules_config->dirty)) {
  458. try {
  459. $rules_config->integrityCheck();
  460. }
  461. catch (RulesIntegrityException $e) {
  462. $warning = TRUE;
  463. drupal_set_message(t('Removed the event, but it had provided some variables which are now missing.'), 'warning');
  464. }
  465. }
  466. $rules_config->save();
  467. if (!isset($warning)) {
  468. drupal_set_message(t('Event %event has been removed.', array('%event' => $form_state['event_label'])));
  469. }
  470. $form_state['redirect'] = RulesPluginUI::path($rules_config->name);
  471. }
  472. /**
  473. * Import form for rule configurations.
  474. */
  475. function rules_ui_import_form($form, &$form_state, $base_path) {
  476. RulesPluginUI::$basePath = $base_path;
  477. RulesPluginUI::formDefaults($form, $form_state);
  478. $form['import'] = array(
  479. '#type' => 'textarea',
  480. '#title' => t('Import'),
  481. '#description' => t('Paste an exported Rules configuration here.'),
  482. '#rows' => 20,
  483. );
  484. $form['overwrite'] = array(
  485. '#title' => t('Overwrite'),
  486. '#type' => 'checkbox',
  487. '#description' => t('If checked, any existing configuration with the same identifier will be replaced by the import.'),
  488. '#default_value' => FALSE,
  489. );
  490. $form['submit'] = array(
  491. '#type' => 'submit',
  492. '#value' => t('Import'),
  493. );
  494. return $form;
  495. }
  496. /**
  497. * Validation callback for the import form.
  498. */
  499. function rules_ui_import_form_validate($form, &$form_state) {
  500. if ($rules_config = rules_import($form_state['values']['import'], $error_msg)) {
  501. // Store the successfully imported entity in $form_state.
  502. $form_state['rules_config'] = $rules_config;
  503. if (!$form_state['values']['overwrite']) {
  504. // Check for existing entities with the same identifier.
  505. if (rules_config_load($rules_config->name)) {
  506. $vars = array('@entity' => t('Rules configuration'), '%label' => $rules_config->label());
  507. form_set_error('import', t('Import of @entity %label failed, a @entity with the same machine name already exists. Check the overwrite option to replace it.', $vars));
  508. }
  509. }
  510. try {
  511. $rules_config->integrityCheck();
  512. }
  513. catch (RulesIntegrityException $e) {
  514. form_set_error('import', t('Integrity check for the imported configuration failed. Error message: %message.', array('%message' => $e->getMessage())));
  515. }
  516. if (!user_access('bypass rules access') && !$rules_config->access()) {
  517. form_set_error('import', t('You have insufficient access permissions for importing this Rules configuration.'));
  518. }
  519. }
  520. else {
  521. form_set_error('import', t('Import failed.'));
  522. if ($error_msg) {
  523. drupal_set_message($error_msg, 'error');
  524. }
  525. }
  526. }
  527. /**
  528. * Submit callback for the import form.
  529. */
  530. function rules_ui_import_form_submit($form, &$form_state) {
  531. $rules_config = $form_state['rules_config'];
  532. if ($existing_config = rules_config_load($rules_config->name)) {
  533. // Copy DB id and remove the new indicator to overwrite the existing record.
  534. $rules_config->id = $existing_config->id;
  535. unset($rules_config->is_new);
  536. }
  537. $rules_config->save();
  538. $vars = array('@entity' => t('Rules configuration'), '%label' => $rules_config->label());
  539. watchdog('rules_config', 'Imported @entity %label.', $vars);
  540. drupal_set_message(t('Imported @entity %label.', $vars));
  541. $form_state['redirect'] = RulesPluginUI::$basePath;
  542. }
  543. /**
  544. * FAPI process callback for the data selection widget.
  545. * This finalises the auto completion callback path by appending the form build
  546. * id.
  547. */
  548. function rules_data_selection_process($element, &$form_state, $form) {
  549. $element['#autocomplete_path'] .= '/' . $form['#build_id'];
  550. $form_state['cache'] = TRUE;
  551. return $element;
  552. }
  553. /**
  554. * Autocomplete data selection results.
  555. */
  556. function rules_ui_form_data_selection_auto_completion($parameter, $form_build_id, $string = '') {
  557. // Get the form and its state from the cache to get the currently edited
  558. // or created element.
  559. $form_state = form_state_defaults();
  560. $form = form_get_cache($form_build_id, $form_state);
  561. if (!isset($form_state['rules_element'])) {
  562. return;
  563. }
  564. $element = $form_state['rules_element'];
  565. $params = $element->pluginParameterInfo();
  566. $matches = array();
  567. if (isset($params[$parameter])) {
  568. $parts = explode(':', $string);
  569. // Remove the last part as it might be unfinished.
  570. $last_part = array_pop($parts);
  571. $selector = implode(':', $parts);
  572. // Start with the partly given selector or from scratch.
  573. $result = array();
  574. if ($selector && $wrapper = $element->applyDataSelector($selector)) {
  575. $result = RulesData::matchingDataSelector($wrapper, $params[$parameter], $selector . ':', 0);
  576. }
  577. elseif (!$selector) {
  578. $result = RulesData::matchingDataSelector($element->availableVariables(), $params[$parameter], '', 0);
  579. }
  580. foreach ($result as $selector => $info) {
  581. // If we have an uncomplete last part, take it into account now.
  582. $attributes = array();
  583. if (!$last_part || strpos($selector, $string) === 0) {
  584. $attributes['class'][] = 'rules-dsac-item';
  585. $attributes['title'] = isset($info['description']) ? strip_tags($info['description']) : '';
  586. if ($selector[strlen($selector) - 1] == ':') {
  587. $attributes['class'][] = 'rules-dsac-group';
  588. $text = check_plain($selector) . '... (' . check_plain($info['label']) . ')';
  589. }
  590. else {
  591. $text = check_plain($selector) . ' (' . check_plain($info['label']) . ')';
  592. }
  593. $matches[$selector] = "<div" . drupal_attributes($attributes) . ">$text</div>";
  594. }
  595. }
  596. }
  597. drupal_json_output($matches);
  598. }
  599. /**
  600. * FAPI validation of an integer element. Copy of the private function
  601. * _element_validate_integer().
  602. */
  603. function rules_ui_element_integer_validate($element, &$form_state) {;
  604. $value = $element['#value'];
  605. if (isset($value) && $value !== '' && (!is_numeric($value) || intval($value) != $value)) {
  606. form_error($element, t('%name must be an integer value.', array('%name' => isset($element['#title']) ? $element['#title'] : t('Element'))));
  607. }
  608. }
  609. /**
  610. * FAPI validation of a decimal element. Improved version of the private
  611. * function _element_validate_number().
  612. */
  613. function rules_ui_element_decimal_validate($element, &$form_state) {
  614. // Substitute the decimal separator ",".
  615. $value = strtr($element['#value'], ',', '.');
  616. if ($value != '' && !is_numeric($value)) {
  617. form_error($element, t('%name must be a number.', array('%name' => $element['#title'])));
  618. }
  619. elseif ($value != $element['#value']) {
  620. form_set_value($element, $value, $form_state);
  621. }
  622. }
  623. /**
  624. * FAPI callback to validate an IP address.
  625. */
  626. function rules_ui_element_ip_address_validate($element, &$form_state) {
  627. $value = $element['#value'];
  628. if ($value != '' && !filter_var($value, FILTER_VALIDATE_IP)) {
  629. form_error($element, t('%name is not a valid IP address.', array('%name' => $element['#title'])));
  630. }
  631. }
  632. /**
  633. * FAPI validation of a date element. Makes sure the specified date format is
  634. * correct and converts date values specifiy a fixed (= non relative) date to
  635. * a timestamp. Relative dates are handled by the date input evaluator.
  636. */
  637. function rules_ui_element_date_validate($element, &$form_state) {
  638. $value = $element['#value'];
  639. if ($value == '' || (is_numeric($value) && intval($value) == $value)) {
  640. // The value is a timestamp.
  641. return;
  642. }
  643. elseif (is_string($value) && RulesDateInputEvaluator::gmstrtotime($value) === FALSE) {
  644. form_error($element, t('Wrong date format. Specify the date in the format %format.', array('%format' => gmdate('Y-m-d H:i:s', time() + 86400))));
  645. }
  646. elseif (is_string($value) && RulesDateInputEvaluator::isFixedDateString($value)) {
  647. // As the date string specifies a fixed format, we can convert it now.
  648. $value = RulesDateInputEvaluator::gmstrtotime($value);
  649. form_set_value($element, $value, $form_state);
  650. }
  651. }
  652. /**
  653. * FAPI process callback for the duration element type.
  654. */
  655. function rules_ui_element_duration_process($element, &$form_state) {
  656. $element['value'] = array(
  657. '#type' => 'textfield',
  658. '#size' => 8,
  659. '#element_validate' => array('rules_ui_element_integer_validate'),
  660. '#default_value' => $element['#default_value'],
  661. '#required' => !empty($element['#required']),
  662. );
  663. $element['multiplier'] = array(
  664. '#type' => 'select',
  665. '#options' => rules_ui_element_duration_multipliers(),
  666. '#default_value' => 1,
  667. );
  668. // Put the child elements in a container-inline div.
  669. $element['value']['#prefix'] = '<div class="rules-duration container-inline">';
  670. $element['multiplier']['#suffix'] = '</div>';
  671. // Set an appropriate multiplier.
  672. if (!empty($element['value']['#default_value'])) {
  673. foreach (array_keys(rules_ui_element_duration_multipliers()) as $m) {
  674. if ($element['value']['#default_value'] % $m == 0) {
  675. $element['multiplier']['#default_value'] = $m;
  676. }
  677. }
  678. // Divide value by the multiplier, so the display is correct.
  679. $element['value']['#default_value'] /= $element['multiplier']['#default_value'];
  680. }
  681. return $element;
  682. }
  683. /**
  684. * Defines possible duration multiplier.
  685. */
  686. function rules_ui_element_duration_multipliers() {
  687. return array(
  688. 1 => t('seconds'),
  689. 60 => t('minutes'),
  690. 3600 => t('hours'),
  691. // Just use approximate numbers for days (might last 23h on DST change),
  692. // months and years.
  693. 86400 => t('days'),
  694. 86400 * 30 => t('months'),
  695. 86400 * 30 * 12 => t('years'),
  696. );
  697. }
  698. /**
  699. * Helper function to determine the value for a rules duration form
  700. * element.
  701. */
  702. function rules_ui_element_duration_value($element, $input = FALSE) {
  703. // This runs before child elements are processed, so we cannot calculate the
  704. // value here. But we have to make sure the value is an array, so the form
  705. // API is able to process the children to set their values in the array. Thus
  706. // once the form API has finished processing the element, the value is an
  707. // array containing the child element values. Then finally the after build
  708. // callback converts it back to the numeric value and sets that.
  709. return array();
  710. }
  711. /**
  712. * FAPI after build callback for the duration parameter type form.
  713. * Fixes up the form value by applying the multiplier.
  714. */
  715. function rules_ui_element_duration_after_build($element, &$form_state) {
  716. if ($element['value']['#value'] !== '') {
  717. $element['#value'] = $element['value']['#value'] * $element['multiplier']['#value'];
  718. form_set_value($element, $element['#value'], $form_state);
  719. }
  720. else {
  721. $element['#value'] = NULL;
  722. form_set_value($element, NULL, $form_state);
  723. }
  724. return $element;
  725. }
  726. /**
  727. * FAPI after build callback to ensure empty form elements result in no value.
  728. */
  729. function rules_ui_element_fix_empty_after_build($element, &$form_state) {
  730. if (isset($element['#value']) && $element['#value'] === '') {
  731. $element['#value'] = NULL;
  732. form_set_value($element, NULL, $form_state);
  733. }
  734. // Work-a-round for the text_format element.
  735. elseif ($element['#type'] == 'text_format' && !isset($element['value']['#value'])) {
  736. form_set_value($element, NULL, $form_state);
  737. }
  738. return $element;
  739. }
  740. /**
  741. * FAPI after build callback for specifying a list of values.
  742. *
  743. * Turns the textual value in an array by splitting the text in chunks using the
  744. * delimiter set at $element['#delimiter'].
  745. */
  746. function rules_ui_list_textarea_after_build($element, &$form_state) {
  747. $element['#value'] = $element['#value'] ? explode($element['#delimiter'], $element['#value']) : array();
  748. $element['#value'] = array_map('trim', $element['#value']);
  749. form_set_value($element, $element['#value'], $form_state);
  750. return $element;
  751. }
  752. /**
  753. * FAPI pre render callback. Turns the value back to a string for rendering.
  754. *
  755. * @see rules_ui_list_textarea_after_build()
  756. */
  757. function rules_ui_list_textarea_pre_render($element) {
  758. $element['#value'] = implode($element['#delimiter'], $element['#value']);
  759. return $element;
  760. }
  761. /**
  762. * FAPI callback to validate a list of integers.
  763. */
  764. function rules_ui_element_integer_list_validate($element, &$form_state) {
  765. foreach ($element['#value'] as $value) {
  766. if ($value !== '' && (!is_numeric($value) || intval($value) != $value)) {
  767. form_error($element, t('Each value must be an integer.'));
  768. }
  769. }
  770. }
  771. /**
  772. * FAPI callback to validate a token.
  773. */
  774. function rules_ui_element_token_validate($element) {
  775. $value = $element['#value'];
  776. if (isset($value) && $value !== '' && !entity_property_verify_data_type($value, 'token')) {
  777. form_error($element, t('%name may only contain lowercase letters, numbers, and underscores and has to start with a letter.', array('%name' => isset($element['#title']) ? $element['#title'] : t('Element'))));
  778. }
  779. }
  780. /**
  781. * FAPI callback to validate a list of tokens.
  782. */
  783. function rules_ui_element_token_list_validate($element, &$form_state) {
  784. foreach ($element['#value'] as $value) {
  785. if ($value !== '' && !entity_property_verify_data_type($value, 'token')) {
  786. form_error($element, t('Each value may only contain lowercase letters, numbers, and underscores and has to start with a letter.'));
  787. }
  788. }
  789. }
  790. /**
  791. * FAPI callback to validate a machine readable name.
  792. */
  793. function rules_ui_element_machine_name_validate($element, &$form_state) {
  794. if ($element['#value'] && !preg_match('!^[a-z0-9_]+$!', $element['#value'])) {
  795. form_error($element, t('Machine-readable names must contain only lowercase letters, numbers, and underscores.'));
  796. }
  797. }
  798. /**
  799. * FAPI callback to validate the form for editing variable info.
  800. * @see RulesPluginUI::getVariableForm()
  801. */
  802. function rules_ui_element_variable_form_validate($elements, &$form_state) {
  803. $names = array();
  804. foreach (element_children($elements['items']) as $item_key) {
  805. $element = &$elements['items'][$item_key];
  806. if ($element['name']['#value'] || $element['type']['#value'] || $element['label']['#value']) {
  807. foreach (array('name' => t('Machine name'), 'label' => t('Label'), 'type' => t('Data type')) as $key => $title) {
  808. if (!$element[$key]['#value']) {
  809. form_error($element[$key], t('!name field is required.', array('!name' => $title)));
  810. }
  811. }
  812. if (isset($names[$element['name']['#value']])) {
  813. form_error($element['name'], t('The machine-readable name %name is already taken.', array('%name' => $element['name']['#value'])));
  814. }
  815. $names[$element['name']['#value']] = TRUE;
  816. }
  817. }
  818. }
  819. /**
  820. * Helper to sort elements by their 'weight' key.
  821. */
  822. function rules_element_sort_helper($a, $b) {
  823. $a += array('weight' => 0);
  824. $b += array('weight' => 0);
  825. if ($a['weight'] == $b['weight']) {
  826. return 0;
  827. }
  828. return ($a['weight'] < $b['weight']) ? -1 : 1;
  829. }
  830. /**
  831. * Form after build handler to set the static base path.
  832. *
  833. * @see RulesPluginUI::formDefaults()
  834. */
  835. function rules_form_after_build_restore_base_path($form, &$form_state) {
  836. if (isset($form_state['_rules_base_path'])) {
  837. RulesPluginUI::$basePath = $form_state['_rules_base_path'];
  838. }
  839. return $form;
  840. }
  841. /**
  842. * AJAX page callback to load tag suggestions.
  843. *
  844. * Largely copied from taxonomy_autocomplete().
  845. */
  846. function rules_autocomplete_tags($tags_typed = '') {
  847. // The user enters a comma-separated list of tags. We only autocomplete the
  848. // last tag.
  849. $tags_typed = drupal_explode_tags($tags_typed);
  850. $tag_last = drupal_strtolower(array_pop($tags_typed));
  851. $tag_matches = array();
  852. if ($tag_last != '') {
  853. $query = db_select('rules_tags', 'rt');
  854. // Do not select already entered terms.
  855. if (!empty($tags_typed)) {
  856. $query->condition('rt.tag', $tags_typed, 'NOT IN');
  857. }
  858. // Select rows that match by tag name.
  859. $tags_return = $query
  860. ->distinct()
  861. ->fields('rt', array('tag'))
  862. ->condition('rt.tag', '%' . db_like($tag_last) . '%', 'LIKE')
  863. ->groupBy('rt.tag')
  864. ->range(0, 10)
  865. ->execute()
  866. ->fetchCol('rt.tag');
  867. $prefix = count($tags_typed) ? drupal_implode_tags($tags_typed) . ', ' : '';
  868. foreach ($tags_return as $name) {
  869. $n = $name;
  870. // Tag names containing commas or quotes must be wrapped in quotes.
  871. if (strpos($name, ',') !== FALSE || strpos($name, '"') !== FALSE) {
  872. $n = '"' . str_replace('"', '""', $name) . '"';
  873. }
  874. $tag_matches[$prefix . $n] = check_plain($name);
  875. }
  876. }
  877. drupal_json_output($tag_matches);
  878. }