ui.forms.inc 34 KB

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