rules.core.inc 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593
  1. <?php
  2. /**
  3. * @file
  4. * Rules base classes and interfaces needed for any rule evaluation.
  5. */
  6. // This is not necessary as the classes are autoloaded via the registry. However
  7. // it saves some possible update headaches until the registry is rebuilt.
  8. // @todo
  9. // Remove for a future release.
  10. require_once dirname(__FILE__) . '/faces.inc';
  11. /**
  12. * Make sure loaded rule configs are instantiated right.
  13. */
  14. class RulesEntityController extends EntityAPIControllerExportable {
  15. /**
  16. * Overriden.
  17. * @see DrupalDefaultEntityController::attachLoad()
  18. */
  19. protected function attachLoad(&$queried_entities, $revision_id = FALSE) {
  20. // Retrieve stdClass records and turn them in rules objects stored in 'data'
  21. $ids = array_keys($queried_entities);
  22. $result = db_select('rules_tags')
  23. ->fields('rules_tags', array('id', 'tag'))
  24. ->condition('id', $ids, 'IN')
  25. ->execute();
  26. foreach ($result as $row) {
  27. $tags[$row->id][] = $row->tag;
  28. }
  29. $result = db_select('rules_dependencies')
  30. ->fields('rules_dependencies', array('id', 'module'))
  31. ->condition('id', $ids, 'IN')
  32. ->execute();
  33. foreach ($result as $row) {
  34. $modules[$row->id][] = $row->module;
  35. }
  36. $entities = array();
  37. foreach ($queried_entities as $record) {
  38. $entity = $record->data;
  39. // Set the values of the other columns.
  40. foreach ($this->entityInfo['schema_fields_sql']['base table'] as $field) {
  41. $entity->$field = $record->$field;
  42. }
  43. unset($entity->data, $entity->plugin);
  44. // Add any tags or dependencies.
  45. $entity->dependencies = isset($modules[$entity->id]) ? $modules[$entity->id] : array();
  46. $entity->tags = isset($tags[$entity->id]) ? $tags[$entity->id] : array();
  47. $entities[$entity->id] = $entity;
  48. }
  49. $queried_entities = $entities;
  50. parent::attachLoad($queried_entities, $revision_id);
  51. }
  52. /**
  53. * Override to support having events and tags as conditions.
  54. * @see EntityAPIController::applyConditions($entities, $conditions)
  55. * @see rules_query_rules_config_load_multiple_alter()
  56. */
  57. protected function applyConditions($entities, $conditions = array()) {
  58. if (isset($conditions['event']) || isset($conditions['plugin'])) {
  59. foreach ($entities as $key => $entity) {
  60. if (isset($conditions['event']) && (!($entity instanceof RulesTriggerableInterface) || !in_array($conditions['event'], $entity->events()))) {
  61. unset($entities[$key]);
  62. }
  63. if (isset($conditions['plugin']) && !is_array($conditions['plugin'])) {
  64. $conditions['plugin'] = array($conditions['plugin']);
  65. }
  66. if (isset($conditions['plugin']) && !in_array($entity->plugin(), $conditions['plugin'])) {
  67. unset($entities[$key]);
  68. }
  69. }
  70. unset($conditions['event'], $conditions['plugin']);
  71. }
  72. if (!empty($conditions['tags'])) {
  73. foreach ($entities as $key => $entity) {
  74. foreach ($conditions['tags'] as $tag) {
  75. if (in_array($tag, $entity->tags)) {
  76. continue 2;
  77. }
  78. }
  79. unset($entities[$key]);
  80. }
  81. unset($conditions['tags']);
  82. }
  83. return parent::applyConditions($entities, $conditions);
  84. }
  85. /**
  86. * Overridden to work with Rules' custom export format.
  87. *
  88. * @param $export
  89. * A serialized string in JSON format as produced by the
  90. * RulesPlugin::export() method, or the PHP export as usual PHP array.
  91. */
  92. public function import($export, &$error_msg = '') {
  93. $export = is_array($export) ? $export : drupal_json_decode($export);
  94. if (!is_array($export)) {
  95. $error_msg = t('Unable to parse the pasted export.');
  96. return FALSE;
  97. }
  98. // The key ist the configuration name and the value the actual export.
  99. list($name, $export) = each($export);
  100. if (!isset($export['PLUGIN'])) {
  101. $error_msg = t('Export misses plugin information.');
  102. return FALSE;
  103. }
  104. // Create an empty configuration, re-set basic keys and import.
  105. $config = rules_plugin_factory($export['PLUGIN']);
  106. $config->name = $name;
  107. foreach (array('label', 'active', 'weight', 'tags', 'access_exposed') as $key) {
  108. if (isset($export[strtoupper($key)])) {
  109. $config->$key = $export[strtoupper($key)];
  110. }
  111. }
  112. if (!empty($export['REQUIRES'])) {
  113. foreach ($export['REQUIRES'] as $module) {
  114. if (!module_exists($module)) {
  115. $error_msg = t('Missing the required module %module.', array('%module' => $module));
  116. return FALSE;
  117. }
  118. }
  119. $config->dependencies = $export['REQUIRES'];
  120. }
  121. $config->import($export);
  122. return $config;
  123. }
  124. public function save($rules_config, DatabaseTransaction $transaction = NULL) {
  125. $transaction = isset($transaction) ? $transaction : db_transaction();
  126. $return = parent::save($rules_config, $transaction);
  127. $this->storeTags($rules_config);
  128. if ($rules_config instanceof RulesTriggerableInterface) {
  129. $this->storeEvents($rules_config);
  130. }
  131. $this->storeDependencies($rules_config);
  132. return $return;
  133. }
  134. /**
  135. * Save tagging information to the rules_tags table.
  136. */
  137. protected function storeTags($rules_config) {
  138. db_delete('rules_tags')
  139. ->condition('id', $rules_config->id)
  140. ->execute();
  141. if (!empty($rules_config->tags)) {
  142. foreach ($rules_config->tags as $tag) {
  143. db_insert('rules_tags')
  144. ->fields(array('id', 'tag'), array($rules_config->id, $tag))
  145. ->execute();
  146. }
  147. }
  148. }
  149. /**
  150. * Save event information to the rules_trigger table.
  151. */
  152. protected function storeEvents(RulesTriggerableInterface $rules_config) {
  153. db_delete('rules_trigger')
  154. ->condition('id', $rules_config->id)
  155. ->execute();
  156. foreach ($rules_config->events() as $event) {
  157. db_insert('rules_trigger')
  158. ->fields(array(
  159. 'id' => $rules_config->id,
  160. 'event' => $event,
  161. ))
  162. ->execute();
  163. }
  164. }
  165. protected function storeDependencies($rules_config) {
  166. db_delete('rules_dependencies')
  167. ->condition('id', $rules_config->id)
  168. ->execute();
  169. if (!empty($rules_config->dependencies)) {
  170. foreach ($rules_config->dependencies as $dependency) {
  171. db_insert('rules_dependencies')
  172. ->fields(array(
  173. 'id' => $rules_config->id,
  174. 'module' => $dependency,
  175. ))
  176. ->execute();
  177. }
  178. }
  179. }
  180. /**
  181. * Overridden to support tags and events in $conditions.
  182. * @see EntityAPIControllerExportable::buildQuery()
  183. */
  184. protected function buildQuery($ids, $conditions = array(), $revision_id = FALSE) {
  185. $query = parent::buildQuery($ids, $conditions, $revision_id);
  186. $query_conditions =& $query->conditions();
  187. foreach ($query_conditions as &$condition) {
  188. // One entry in $query_conditions is a string with key '#conjunction'.
  189. // @see QueryConditionInterface::conditions().
  190. if (is_array($condition)) {
  191. // Support using 'tags' => array('tag1', 'tag2') as condition.
  192. if ($condition['field'] == 'base.tags') {
  193. $query->join('rules_tags', 'rt', 'base.id = rt.id');
  194. $condition['field'] = 'rt.tag';
  195. }
  196. // Support using 'event' => $name as condition.
  197. if ($condition['field'] == 'base.event') {
  198. $query->join('rules_trigger', 'tr', "base.id = tr.id");
  199. $condition['field'] = 'tr.event';
  200. }
  201. }
  202. }
  203. return $query;
  204. }
  205. /**
  206. * Overridden to also delete tags and events.
  207. * @see EntityAPIControllerExportable::delete()
  208. */
  209. public function delete($ids, DatabaseTransaction $transaction = NULL) {
  210. $transaction = isset($transaction) ? $transaction : db_transaction();
  211. // Use entity-load as ids may be the names as well as the ids.
  212. $configs = $ids ? entity_load('rules_config', $ids) : array();
  213. if ($configs) {
  214. foreach ($configs as $config) {
  215. db_delete('rules_trigger')
  216. ->condition('id', $config->id)
  217. ->execute();
  218. db_delete('rules_tags')
  219. ->condition('id', $config->id)
  220. ->execute();
  221. db_delete('rules_dependencies')
  222. ->condition('id', $config->id)
  223. ->execute();
  224. }
  225. }
  226. return parent::delete($ids, $transaction);
  227. }
  228. }
  229. /**
  230. * The RulesExtendable uses the rules cache to setup the defined extenders
  231. * and overrides automatically.
  232. * As soon faces is used the faces information is autoloaded using setUp().
  233. */
  234. abstract class RulesExtendable extends FacesExtendable {
  235. /**
  236. * The name of the info definitions associated with info about this class.
  237. * This would be defined abstract, if possible. Common rules hooks with class
  238. * info are e.g. plugin_info and data_info.
  239. */
  240. protected $hook;
  241. /**
  242. * The name of the item this class represents in the info hook.
  243. */
  244. protected $itemName;
  245. protected $cache, $itemInfo = array();
  246. public function __construct() {
  247. $this->setUp();
  248. }
  249. protected function setUp() {
  250. // Keep a reference on the cache, so elements created during cache
  251. // rebuilding end up with a complete cache in the end too.
  252. $this->cache = &rules_get_cache();
  253. if (isset($this->cache[$this->hook][$this->itemName])) {
  254. $this->itemInfo = &$this->cache[$this->hook][$this->itemName];
  255. }
  256. // Set up the Faces Extenders
  257. if (!empty($this->itemInfo['faces_cache'])) {
  258. list($this->facesMethods, $this->facesIncludes, $this->faces) = $this->itemInfo['faces_cache'];
  259. }
  260. }
  261. /**
  262. * Force the object to be setUp, this executes setUp() if not done yet.
  263. */
  264. public function forceSetUp() {
  265. if (!isset($this->cache) || (!empty($this->itemInfo['faces_cache']) && !$this->faces)) {
  266. $this->setUp();
  267. }
  268. }
  269. /**
  270. * Magic method: Invoke the dynamically implemented methods.
  271. */
  272. public function __call($name, $arguments = array()) {
  273. $this->forceSetUp();
  274. return parent::__call($name, $arguments);
  275. }
  276. public function facesAs($interface = NULL) {
  277. $this->forceSetUp();
  278. return parent::facesAs($interface);
  279. }
  280. /**
  281. * Allows items to add something to the rules cache.
  282. */
  283. public function rebuildCache(&$itemInfo, &$cache) {
  284. // Speed up setting up items by caching the faces methods.
  285. if (!empty($itemInfo['extenders'])) {
  286. // Apply extenders and overrides.
  287. $itemInfo += array('overrides' => array());
  288. foreach ($itemInfo['extenders'] as $face => $data) {
  289. $data += array('file' => array());
  290. if (isset($data['class'])) {
  291. $this->extendByClass($face, $data['class'], $data['file']);
  292. }
  293. elseif (isset($data['methods'])) {
  294. $this->extend($face, $data['methods'], $data['file']);
  295. }
  296. }
  297. foreach ($itemInfo['overrides'] as $data) {
  298. $data += array('file' => array());
  299. $this->override($data['methods'], $data['file']);
  300. }
  301. $itemInfo['faces_cache'] = array($this->facesMethods, $this->facesIncludes, $this->faces);
  302. // We don't need that any more.
  303. unset($itemInfo['extenders'], $itemInfo['overrides']);
  304. }
  305. }
  306. /**
  307. * Returns whether the a RuleExtendable supports the given interface.
  308. *
  309. * @param $itemInfo
  310. * The info about the item as specified in the hook.
  311. * @param $interface
  312. * The interface to check for.
  313. * @return
  314. * Whether it supports the given interface.
  315. */
  316. public static function itemFacesAs(&$itemInfo, $interface) {
  317. return in_array($interface, class_implements($itemInfo['class'])) || isset($itemInfo['faces_cache'][2][$interface]);
  318. }
  319. }
  320. /**
  321. * Base class for rules plugins.
  322. *
  323. * We cannot inherit from EntityDB at the same time, so we implement our own
  324. * entity related methods. Any CRUD related actions performed on contained
  325. * plugins are applied and the root element representing the configuration is
  326. * saved.
  327. */
  328. abstract class RulesPlugin extends RulesExtendable {
  329. /**
  330. * If this is a configuration saved to the db, the id of it.
  331. */
  332. public $id = NULL;
  333. public $weight = 0;
  334. public $name = NULL;
  335. /**
  336. * An array of settings for this element.
  337. */
  338. public $settings = array();
  339. /**
  340. * Info about this element. Usage depends on the plugin.
  341. */
  342. protected $info = array();
  343. /**
  344. * The parent element, if any.
  345. * @var RulesContainerPlugin
  346. */
  347. protected $parent = NULL;
  348. protected $cache = NULL, $hook = 'plugin_info';
  349. /**
  350. * Identifies an element inside a configuration.
  351. */
  352. protected $elementId = NULL;
  353. /**
  354. * Static cache for availableVariables().
  355. */
  356. protected $availableVariables;
  357. /**
  358. * Sets a new parent element.
  359. */
  360. public function setParent(RulesContainerPlugin $parent) {
  361. if ($this->parent == $parent) {
  362. return;
  363. }
  364. if (isset($this->parent) && ($key = array_search($this, $this->parent->children)) !== FALSE) {
  365. // Remove element from any previous parent.
  366. unset($this->parent->children[$key]);
  367. $this->parent->resetInternalCache();
  368. }
  369. // Make sure the interface matches the type of the container.
  370. if (($parent instanceof RulesActionContainer && $this instanceof RulesActionInterface) ||
  371. ($parent instanceof RulesConditionContainer && $this instanceof RulesConditionInterface)) {
  372. $this->parent = $parent;
  373. $parent->children[] = $this;
  374. $this->parent->resetInternalCache();
  375. }
  376. else {
  377. throw new RulesEvaluationException('The given container is incompatible with this element.', array(), $this, RulesLog::ERROR);
  378. }
  379. }
  380. /**
  381. * Gets the root element of the configuration.
  382. */
  383. public function root() {
  384. $element = $this;
  385. while (!$element->isRoot()) {
  386. $element = $element->parent;
  387. }
  388. return $element;
  389. }
  390. /**
  391. * Returns whether the element is the root of the configuration.
  392. */
  393. public function isRoot() {
  394. return empty($this->parent) || isset($this->name);
  395. }
  396. /**
  397. * Returns the element's parent.
  398. */
  399. public function parentElement() {
  400. return $this->parent;
  401. }
  402. /**
  403. * Returns the element id, which identifies the element inside the config.
  404. */
  405. public function elementId() {
  406. if (!isset($this->elementId)) {
  407. $this->elementMap()->index();
  408. }
  409. return $this->elementId;
  410. }
  411. /**
  412. * Gets the element map helper object, which helps mapping elements to ids.
  413. *
  414. * @return RulesElementMap
  415. */
  416. public function elementMap() {
  417. $config = $this->root();
  418. if (empty($config->map)) {
  419. $config->map = new RulesElementMap($config);
  420. }
  421. return $config->map;
  422. }
  423. /**
  424. * Iterate over all elements nested below the current element.
  425. *
  426. * This helper can be used to recursively iterate over all elements of a
  427. * configuration. To iterate over the children only, just regulary iterate
  428. * over the object.
  429. *
  430. * @param $mode
  431. * (optional) The iteration mode used. See
  432. * RecursiveIteratorIterator::construct(). Defaults to SELF_FIRST.
  433. *
  434. * @return RecursiveIteratorIterator
  435. */
  436. public function elements($mode = RecursiveIteratorIterator::SELF_FIRST) {
  437. return new RecursiveIteratorIterator($this, $mode);
  438. }
  439. /**
  440. * Do a deep clone.
  441. */
  442. public function __clone() {
  443. // Make sure the element map is cleared.
  444. // @see self::elementMap()
  445. unset($this->map);
  446. }
  447. /**
  448. * Returns the depth of this element in the configuration.
  449. */
  450. public function depth() {
  451. $element = $this;
  452. $i = 0;
  453. while (!empty($element->parent)) {
  454. $element = $element->parent;
  455. $i++;
  456. }
  457. return $i;
  458. }
  459. /**
  460. * Execute the configuration.
  461. *
  462. * @param ...
  463. * Arguments to pass to the configuration.
  464. */
  465. public function execute() {
  466. return $this->executeByArgs(func_get_args());
  467. }
  468. /**
  469. * Execute the configuration by passing arguments in a single array.
  470. */
  471. abstract public function executeByArgs($args = array());
  472. /**
  473. * Evaluate the element on a given rules evaluation state.
  474. */
  475. abstract function evaluate(RulesState $state);
  476. protected static function compare(RulesPlugin $a, RulesPlugin $b) {
  477. if ($a->weight == $b->weight) {
  478. return 0;
  479. }
  480. return ($a->weight < $b->weight) ? -1 : 1;
  481. }
  482. /**
  483. * Returns info about parameters needed by the plugin.
  484. *
  485. * Note that not necessarily all parameters are needed when executing the
  486. * plugin, as values for the parameter might have been already configured via
  487. * the element settings.
  488. *
  489. * @see self::parameterInfo()
  490. */
  491. public function pluginParameterInfo() {
  492. return isset($this->info['parameter']) ? $this->info['parameter'] : array();
  493. }
  494. /**
  495. * Returns info about parameters needed for executing the configured plugin.
  496. *
  497. * @param $optional
  498. * Whether optional parameters should be included.
  499. *
  500. * @see self::pluginParameterInfo()
  501. */
  502. public function parameterInfo($optional = FALSE) {
  503. // We have to filter out parameters that are already configured.
  504. foreach ($this->pluginParameterInfo() as $name => $info) {
  505. if (!isset($this->settings[$name . ':select']) && !isset($this->settings[$name]) && ($optional || (empty($info['optional']) && $info['type'] != 'hidden'))) {
  506. $vars[$name] = $info;
  507. }
  508. }
  509. return isset($vars) ? $vars : array();
  510. }
  511. /**
  512. * Returns the about variables the plugin provides for later evaluated elements.
  513. *
  514. * Note that this method returns info about the provided variables as defined
  515. * by the plugin. Thus this resembles the original info, which may be
  516. * adapted via configuration.
  517. *
  518. * @see self::providesVariables()
  519. */
  520. public function pluginProvidesVariables() {
  521. return isset($this->info['provides']) ? $this->info['provides'] : array();
  522. }
  523. /**
  524. * Returns info about all variables provided for later evaluated elements.
  525. *
  526. * @see self::pluginProvidesVariables()
  527. */
  528. public function providesVariables() {
  529. foreach ($this->pluginProvidesVariables() as $name => $info) {
  530. $info['source name'] = $name;
  531. $info['label'] = isset($this->settings[$name . ':label']) ? $this->settings[$name . ':label'] : $info['label'];
  532. if (isset($this->settings[$name . ':var'])) {
  533. $name = $this->settings[$name . ':var'];
  534. }
  535. $provides[$name] = $info;
  536. }
  537. return isset($provides) ? $provides : array();
  538. }
  539. /**
  540. * Returns the info of the plugin.
  541. */
  542. public function info() {
  543. return $this->info;
  544. }
  545. /**
  546. * When converted to a string, just use the export format.
  547. */
  548. public function __toString() {
  549. return $this->isRoot() ? $this->export() : entity_var_json_export($this->export());
  550. }
  551. /**
  552. * Gets variables to return once the configuration has been executed.
  553. */
  554. protected function returnVariables(RulesState $state, $result = NULL) {
  555. $var_info = $this->providesVariables();
  556. foreach ($var_info as $name => $info) {
  557. try {
  558. $vars[$name] = $this->getArgument($name, $info, $state);
  559. }
  560. catch (RulesEvaluationException $e) {
  561. // Ignore not existing variables.
  562. $vars[$name] = NULL;
  563. }
  564. $var_info[$name] += array('allow null' => TRUE);
  565. }
  566. return isset($vars) ? array_values(rules_unwrap_data($vars, $var_info)) : array();
  567. }
  568. /**
  569. * Sets up the execution state for the given arguments.
  570. */
  571. public function setUpState(array $args) {
  572. $state = new RulesState();
  573. $vars = $this->setUpVariables();
  574. // Fix numerically indexed args to start with 0.
  575. if (!isset($args[rules_array_key($vars)])) {
  576. $args = array_values($args);
  577. }
  578. $offset = 0;
  579. foreach (array_keys($vars) as $i => $name) {
  580. $info = $vars[$name];
  581. if (!empty($info['handler']) || (isset($info['parameter']) && $info['parameter'] === FALSE)) {
  582. $state->addVariable($name, NULL, $info);
  583. // Count the variables that are not passed as parameters.
  584. $offset++;
  585. }
  586. // Support numerically indexed arrays as well as named parameter style.
  587. // The index is reduced to exclude non-parameter variables.
  588. elseif (isset($args[$i - $offset])) {
  589. $state->addVariable($name, $args[$i - $offset], $info);
  590. }
  591. elseif (isset($args[$name])) {
  592. $state->addVariable($name, $args[$name], $info);
  593. }
  594. elseif (empty($info['optional']) && $info['type'] != 'hidden') {
  595. throw new RulesEvaluationException('Argument %name is missing.', array('%name' => $name), $this, RulesLog::ERROR);
  596. }
  597. }
  598. return $state;
  599. }
  600. /**
  601. * Returns info about all variables that have to be setup in the state.
  602. */
  603. protected function setUpVariables() {
  604. return $this->parameterInfo(TRUE);
  605. }
  606. /**
  607. * Returns info about variables available to be used as arguments for this element.
  608. *
  609. * As this is called very often, e.g. during integrity checks, we statically
  610. * cache the results.
  611. *
  612. * @see RulesPlugin::resetInternalCache()
  613. */
  614. public function availableVariables() {
  615. if (!isset($this->availableVariables)) {
  616. $this->availableVariables = !$this->isRoot() ? $this->parent->stateVariables($this) : RulesState::defaultVariables();
  617. }
  618. return $this->availableVariables;
  619. }
  620. /**
  621. * Returns asserted additions to the available variable info. Any returned
  622. * info is merged into the variable info, in case the execution flow passes
  623. * the element.
  624. * E.g. this is used to assert the content type of a node if the condition
  625. * is met, such that the per node type properties are available.
  626. */
  627. protected function variableInfoAssertions() {
  628. return array();
  629. }
  630. /**
  631. * Get the name of this plugin instance. The returned name should identify
  632. * the code which drives this plugin.
  633. */
  634. public function getPluginName() {
  635. return $this->itemName;
  636. }
  637. /**
  638. * Calculates an array of required modules.
  639. *
  640. * You can use $this->dependencies to access dependencies for saved
  641. * configurations.
  642. */
  643. public function dependencies() {
  644. $this->processSettings();
  645. $modules = isset($this->itemInfo['module']) && $this->itemInfo['module'] != 'rules' ? array($this->itemInfo['module'] => 1) : array();
  646. foreach ($this->pluginParameterInfo() as $name => $info) {
  647. if (isset($this->settings[$name . ':process']) && $this->settings[$name . ':process'] instanceof RulesDataProcessor) {
  648. $modules += array_flip($this->settings[$name . ':process']->dependencies());
  649. }
  650. }
  651. return array_keys($modules);
  652. }
  653. /**
  654. * Whether the currently logged in user has access to all configured elements.
  655. *
  656. * Note that this only checks whether the current user has permission to all
  657. * configured elements, but not whether a user has access to configure Rule
  658. * configurations in general. Use rules_config_access() for that.
  659. *
  660. * Use this to determine access permissions for configuring or triggering the
  661. * execution of certain configurations independent of the Rules UI.
  662. *
  663. * @see rules_config_access()
  664. */
  665. public function access() {
  666. $this->processSettings();
  667. foreach ($this->pluginParameterInfo() as $name => $info) {
  668. if (isset($this->settings[$name . ':select']) && $wrapper = $this->applyDataSelector($this->settings[$name . ':select'])) {
  669. if ($wrapper->access('view') === FALSE) {
  670. return FALSE;
  671. }
  672. }
  673. // Incorporate access checks for data processors and input evaluators.
  674. if (isset($this->settings[$name . ':process']) && $this->settings[$name . ':process'] instanceof RulesDataProcessor && !$this->settings[$name . ':process']->editAccess()) {
  675. return FALSE;
  676. }
  677. }
  678. return TRUE;
  679. }
  680. /**
  681. * Processes the settings e.g. to prepare input evaluators.
  682. *
  683. * Usually settings get processed automatically, however if $this->settings
  684. * has been altered manually after element construction, it needs to be
  685. * invoked explicitly with $force set to TRUE.
  686. *
  687. */
  688. public function processSettings($force = FALSE) {
  689. // Process if not done yet.
  690. if ($force || !empty($this->settings['#_needs_processing'])) {
  691. $var_info = $this->availableVariables();
  692. foreach ($this->pluginParameterInfo() as $name => $info) {
  693. // Prepare input evaluators.
  694. if (isset($this->settings[$name])) {
  695. $this->settings[$name . ':process'] = $this->settings[$name];
  696. RulesDataInputEvaluator::prepareSetting($this->settings[$name . ':process'], $info, $var_info);
  697. }
  698. // Prepare data processors.
  699. elseif (isset($this->settings[$name . ':select']) && !empty($this->settings[$name . ':process'])) {
  700. RulesDataProcessor::prepareSetting($this->settings[$name . ':process'], $info, $var_info);
  701. }
  702. // Clean up.
  703. if (empty($this->settings[$name . ':process'])) {
  704. unset($this->settings[$name . ':process']);
  705. }
  706. }
  707. unset($this->settings['#_needs_processing']);
  708. }
  709. }
  710. /**
  711. * Makes sure the plugin is configured right, e.g. all needed variables
  712. * are available in the element's scope and dependent modules are enabled.
  713. *
  714. * @return RulesPlugin
  715. * Returns $this to support chained usage.
  716. *
  717. * @throws RulesIntegrityException
  718. * In case of a failed integraty check, a RulesIntegrityException exception
  719. * is thrown.
  720. */
  721. public function integrityCheck() {
  722. // First process the settings if not done yet.
  723. $this->processSettings();
  724. // Check dependencies using the pre-calculated dependencies stored in
  725. // $this->dependencies. Fail back to calculation them on the fly, e.g.
  726. // during creation.
  727. $dependencies = empty($this->dependencies) ? $this->dependencies() : $this->dependencies;
  728. foreach ($dependencies as $module) {
  729. if (!module_exists($module)) {
  730. throw new RulesDependencyException(t('Missing required module %name.', array('%name' => $module)));
  731. }
  732. }
  733. // Check the parameter settings.
  734. $this->checkParameterSettings();
  735. // Check variable names for provided variables to be valid.
  736. foreach ($this->pluginProvidesVariables() as $name => $info) {
  737. if (isset($this->settings[$name . ':var'])) {
  738. $this->checkVarName($this->settings[$name . ':var']);
  739. }
  740. }
  741. return $this;
  742. }
  743. protected function checkVarName($name) {
  744. if (!preg_match('/^[0-9a-zA-Z_]*$/', $name)) {
  745. throw new RulesIntegrityException(t('%plugin: The variable name %name contains not allowed characters.', array('%plugin' => $this->getPluginName(), '%name' => $name)), $this);
  746. }
  747. }
  748. /**
  749. * Checks whether parameters are correctly configured.
  750. */
  751. protected function checkParameterSettings() {
  752. foreach ($this->pluginParameterInfo() as $name => $info) {
  753. if (isset($info['restriction']) && $info['restriction'] == 'selector' && isset($this->settings[$name])) {
  754. throw new RulesIntegrityException(t("The parameter %name may only be configured using a selector.", array('%name' => $name)), array($this, 'parameter', $name));
  755. }
  756. elseif (isset($info['restriction']) && $info['restriction'] == 'input' && isset($this->settings[$name . ':select'])) {
  757. throw new RulesIntegrityException(t("The parameter %name may not be configured using a selector.", array('%name' => $name)), array($this, 'parameter', $name));
  758. }
  759. elseif (!empty($this->settings[$name . ':select']) && !$this->applyDataSelector($this->settings[$name . ':select'])) {
  760. throw new RulesIntegrityException(t("Data selector %selector for parameter %name is invalid.", array('%selector' => $this->settings[$name . ':select'], '%name' => $name)), array($this, 'parameter', $name));
  761. }
  762. elseif ($arg_info = $this->getArgumentInfo($name)) {
  763. // If we have enough metadata, check whether the types match.
  764. if (!RulesData::typesMatch($arg_info, $info)) {
  765. throw new RulesIntegrityException(t("The data type of the configured argument does not match the parameter's %name requirement.", array('%name' => $name)), array($this, 'parameter', $name));
  766. }
  767. }
  768. elseif (!$this->isRoot() && !isset($this->settings[$name]) && empty($info['optional']) && $info['type'] != 'hidden') {
  769. throw new RulesIntegrityException(t('Missing configuration for parameter %name.', array('%name' => $name)), array($this, 'parameter', $name));
  770. }
  771. //TODO: Make sure used values are allowed. (key/value pairs + allowed values)
  772. }
  773. }
  774. /**
  775. * Returns the argument as configured in the element settings for the
  776. * parameter $name described with $info.
  777. *
  778. * @param $name
  779. * The name of the parameter for which to get the argument.
  780. * @param $info
  781. * Info about the parameter.
  782. * @param RulesState $state
  783. * The current evaluation state.
  784. * @param $langcode
  785. * (optional) The language code used to get the argument value if the
  786. * argument value should be translated. By default (NULL) the current
  787. * interface language will be used.
  788. *
  789. * @return
  790. * The argument, possibly wrapped.
  791. *
  792. * @throws RulesEvaluationException
  793. * In case the argument cannot be retrieved an exception is thrown.
  794. */
  795. protected function getArgument($name, $info, RulesState $state, $langcode = NULL) {
  796. // Only apply the langcode if the parameter has been marked translatable.
  797. if (empty($info['translatable'])) {
  798. $langcode = LANGUAGE_NONE;
  799. }
  800. elseif (!isset($langcode)) {
  801. $langcode = $GLOBALS['language']->language;
  802. }
  803. if (!empty($this->settings[$name . ':select'])) {
  804. $arg = $state->applyDataSelector($this->settings[$name . ':select'], $langcode);
  805. }
  806. elseif (isset($this->settings[$name])) {
  807. $arg = rules_wrap_data($this->settings[$name], $info);
  808. // We don't sanitize directly specified values.
  809. $skip_sanitize = TRUE;
  810. }
  811. elseif ($state->varinfo($name)) {
  812. $arg = $state->get($name);
  813. }
  814. elseif (empty($info['optional']) && $info['type'] != 'hidden') {
  815. throw new RulesEvaluationException('Required parameter %name is missing.', array('%name' => $name), $this, RulesLog::ERROR);
  816. }
  817. else {
  818. $arg = isset($info['default value']) ? $info['default value'] : NULL;
  819. $skip_sanitize = TRUE;
  820. $info['allow null'] = TRUE;
  821. }
  822. // Make sure the given value is set if required (default).
  823. if (!isset($arg) && empty($info['allow null'])) {
  824. throw new RulesEvaluationException('The provided argument for parameter %name is empty.', array('%name' => $name), $this);
  825. }
  826. // Support passing already sanitized values.
  827. if ($info['type'] == 'text' && !isset($skip_sanitize) && !empty($info['sanitize']) && !($arg instanceof EntityMetadataWrapper)) {
  828. $arg = check_plain((string) $arg);
  829. }
  830. // Apply any configured data processors.
  831. if (!empty($this->settings[$name . ':process'])) {
  832. // For processing, make sure the data is unwrapped now.
  833. $return = rules_unwrap_data(array($arg), array($info));
  834. // @todo for Drupal 8: Refactor to add the name and language code as
  835. // separate parameter to process().
  836. $info['#name'] = $name;
  837. $info['#langcode'] = $langcode;
  838. return isset($return[0]) ? $this->settings[$name . ':process']->process($return[0], $info, $state, $this) : NULL;
  839. }
  840. return $arg;
  841. }
  842. /**
  843. * Gets the right arguments for executing the element.
  844. *
  845. * @throws RulesEvaluationException
  846. * If case an argument cannot be retrieved an exception is thrown.
  847. */
  848. protected function getExecutionArguments(RulesState $state) {
  849. $parameters = $this->pluginParameterInfo();
  850. // If there is language parameter, get its value first so it can be used
  851. // for getting other translatable values.
  852. $langcode = NULL;
  853. if (isset($parameters['language'])) {
  854. $lang_arg = $this->getArgument('language', $parameters['language'], $state);
  855. $langcode = $lang_arg instanceof EntityMetadataWrapper ? $lang_arg->value() : $lang_arg;
  856. }
  857. // Now get all arguments.
  858. foreach ($parameters as $name => $info) {
  859. $args[$name] = $name == 'language' ? $lang_arg : $this->getArgument($name, $info, $state, $langcode);
  860. }
  861. // Append the settings and the execution state. Faces will append $this.
  862. $args['settings'] = $this->settings;
  863. $args['state'] = $state;
  864. // Make the wrapped variables for the arguments available in the state.
  865. $state->currentArguments = $args;
  866. return rules_unwrap_data($args, $parameters);
  867. }
  868. /**
  869. * Apply the given data selector by using the info about available variables.
  870. * Thus it doesn't require an actual evaluation state.
  871. *
  872. * @param $selector
  873. * The selector string, e.g. "node:author:mail".
  874. *
  875. * @return EntityMetadataWrapper
  876. * An empty wrapper for the given selector or FALSE if the selector couldn't
  877. * be applied.
  878. */
  879. public function applyDataSelector($selector) {
  880. $parts = explode(':', str_replace('-', '_', $selector), 2);
  881. if (($vars = $this->availableVariables()) && isset($vars[$parts[0]]['type'])) {
  882. $wrapper = rules_wrap_data(NULL, $vars[$parts[0]], TRUE);
  883. if (count($parts) > 1 && $wrapper instanceof EntityMetadataWrapper) {
  884. try {
  885. foreach (explode(':', $parts[1]) as $name) {
  886. if ($wrapper instanceof EntityListWrapper || $wrapper instanceof EntityStructureWrapper) {
  887. $wrapper = $wrapper->get($name);
  888. }
  889. else {
  890. return FALSE;
  891. }
  892. }
  893. }
  894. // In case of an exception or we were unable to get a wrapper, return FALSE.
  895. catch (EntityMetadataWrapperException $e) {
  896. return FALSE;
  897. }
  898. }
  899. }
  900. return isset($wrapper) ? $wrapper : FALSE;
  901. }
  902. /**
  903. * Returns info about the configured argument.
  904. *
  905. * @return
  906. * The determined info. If it's not known NULL is returned.
  907. */
  908. public function getArgumentInfo($name) {
  909. $vars = $this->availableVariables();
  910. if (!empty($this->settings[$name . ':select']) && !empty($vars[$this->settings[$name . ':select']])) {
  911. return $vars[$this->settings[$name . ':select']];
  912. }
  913. elseif (!empty($this->settings[$name . ':select'])) {
  914. if ($wrapper = $this->applyDataSelector($this->settings[$name . ':select'])) {
  915. return $wrapper->info();
  916. }
  917. return;
  918. }
  919. elseif (isset($this->settings[$name . ':type'])) {
  920. return array('type' => $this->settings[$name . ':type']);
  921. }
  922. elseif (!isset($this->settings[$name]) && isset($vars[$name])) {
  923. return $vars[$name];
  924. }
  925. }
  926. /**
  927. * Saves the configuration to the database, regardless whether this is invoked
  928. * on the rules configuration or a contained rule element.
  929. */
  930. public function save($name = NULL, $module = 'rules') {
  931. if (isset($this->parent)) {
  932. $this->parent->sortChildren();
  933. return $this->parent->save($name, $module);
  934. }
  935. else {
  936. // Update the dirty flag before saving.
  937. // However, this operation depends on a fully built Rules-cache, so skip
  938. // it when entities in code are imported to the database.
  939. // @see _rules_rebuild_cache()
  940. if (empty($this->is_rebuild)) {
  941. rules_config_update_dirty_flag($this, FALSE);
  942. // In case the config is not dirty, pre-calculate the dependencies for
  943. // later checking. Note that this also triggers processing settings if
  944. // necessary.
  945. // @see rules_modules_enabled()
  946. if (empty($this->dirty)) {
  947. $this->dependencies = $this->dependencies();
  948. }
  949. }
  950. $this->plugin = $this->itemName;
  951. $this->name = isset($name) ? $name : $this->name;
  952. $this->module = !isset($this->module) || $module != 'rules' ? $module : $this->module;
  953. $this->ensureNameExists();
  954. $this->data = $this;
  955. $return = entity_get_controller('rules_config')->save($this);
  956. unset($this->data);
  957. // Care about clearing necessary caches.
  958. if (!empty($this->is_rebuild)) {
  959. rules_clear_cache();
  960. }
  961. else {
  962. $plugin_info = $this->pluginInfo();
  963. if (!empty($plugin_info['component'])) {
  964. // When component variables changes rebuild the complete cache so the
  965. // changes to the provided action/condition take affect.
  966. if (empty($this->original) || $this->componentVariables() != $this->original->componentVariables()) {
  967. rules_clear_cache();
  968. }
  969. // Clear components cached for evaluation.
  970. cache_clear_all('comp_', 'cache_rules', TRUE);
  971. }
  972. elseif ($this->plugin == 'reaction rule') {
  973. // Clear event sets cached for evaluation.
  974. cache_clear_all('event_', 'cache_rules', TRUE);
  975. variable_del('rules_empty_sets');
  976. }
  977. drupal_static_reset('rules_get_cache');
  978. drupal_static_reset('rules_config_update_dirty_flag');
  979. }
  980. return $return;
  981. }
  982. }
  983. /**
  984. * Ensure the configuration has a name. If not, generate one.
  985. */
  986. protected function ensureNameExists() {
  987. if (!isset($this->module)) {
  988. $this->module = 'rules';
  989. }
  990. if (!isset($this->name)) {
  991. // Find a unique name for this configuration.
  992. $this->name = $this->module . '_';
  993. for ($i = 0; $i < 8; $i++) {
  994. // Alphanumeric name generation.
  995. $rnd = mt_rand(97, 122);
  996. $this->name .= chr($rnd);
  997. }
  998. }
  999. }
  1000. public function __sleep() {
  1001. // Keep the id always as we need it for the recursion prevention.
  1002. $array = drupal_map_assoc(array('parent', 'id', 'elementId', 'weight', 'settings'));
  1003. // Keep properties related to configurations if they are there.
  1004. foreach (array('name', 'module', 'status', 'label', 'recursion', 'tags') as $key) {
  1005. if (isset($this->$key)) {
  1006. $array[$key] = $key;
  1007. }
  1008. }
  1009. return $array;
  1010. }
  1011. /**
  1012. * Optimizes a rule configuration in order to speed up evaluation.
  1013. *
  1014. * Additional optimization methods may be inserted by an extender
  1015. * implementing the RulesOptimizationInterface. By default, there is no
  1016. * optimization extender.
  1017. *
  1018. * An optimization method may rearrange the internal structure of a
  1019. * configuration in order to speed up the evaluation. As the configuration may
  1020. * change optimized configurations should not be saved permanently, except
  1021. * when saving it temporary, for later execution only.
  1022. *
  1023. * @see RulesOptimizationInterface
  1024. */
  1025. public function optimize() {
  1026. // Make sure settings are processed before configs are cached.
  1027. $this->processSettings();
  1028. if ($this->facesAs('RulesOptimizationInterface')) {
  1029. $this->__call('optimize');
  1030. }
  1031. }
  1032. /**
  1033. * If invoked on a rules configuration it is deleted from database. If
  1034. * invoked on a contained rule element, it's removed from the configuration.
  1035. */
  1036. public function delete() {
  1037. if (isset($this->parent)) {
  1038. foreach ($this->parent->children as $key => $child) {
  1039. if ($child === $this) {
  1040. unset($this->parent->children[$key]);
  1041. break;
  1042. }
  1043. }
  1044. }
  1045. elseif (isset($this->id)) {
  1046. entity_get_controller('rules_config')->delete(array($this->name));
  1047. rules_clear_cache();
  1048. }
  1049. }
  1050. public function internalIdentifier() {
  1051. return isset($this->id) ? $this->id : NULL;
  1052. }
  1053. /**
  1054. * Returns the config name.
  1055. */
  1056. public function identifier() {
  1057. return isset($this->name) ? $this->name : NULL;
  1058. }
  1059. public function entityInfo() {
  1060. return entity_get_info('rules_config');
  1061. }
  1062. public function entityType() {
  1063. return 'rules_config';
  1064. }
  1065. /**
  1066. * Checks if the configuration has a certain exportable status.
  1067. *
  1068. * @param $status
  1069. * A status constant, i.e. one of ENTITY_CUSTOM, ENTITY_IN_CODE,
  1070. * ENTITY_OVERRIDDEN or ENTITY_FIXED.
  1071. *
  1072. * @return
  1073. * TRUE if the configuration has the status, else FALSE.
  1074. *
  1075. * @see entity_has_status()
  1076. */
  1077. public function hasStatus($status) {
  1078. return $this->isRoot() && isset($this->status) && ($this->status & $status) == $status;
  1079. }
  1080. /**
  1081. * Remove circular object references so the PHP garbage collector does its
  1082. * work.
  1083. */
  1084. public function destroy() {
  1085. parent::destroy();
  1086. $this->parent = NULL;
  1087. }
  1088. /**
  1089. * Seamlessy invokes the method implemented via faces without having to think
  1090. * about references.
  1091. */
  1092. public function form(&$form, &$form_state, array $options = array()) {
  1093. $this->__call('form', array(&$form, &$form_state, $options));
  1094. }
  1095. public function form_validate($form, &$form_state) {
  1096. $this->__call('form_validate', array($form, &$form_state));
  1097. }
  1098. public function form_submit($form, &$form_state) {
  1099. $this->__call('form_submit', array($form, &$form_state));
  1100. }
  1101. /**
  1102. * Returns the label of the element.
  1103. */
  1104. public function label() {
  1105. if (!empty($this->label) && $this->label != t('unlabeled')) {
  1106. return $this->label;
  1107. }
  1108. $info = $this->info();
  1109. return isset($info['label']) ? $info['label'] : (!empty($this->name) ? $this->name : t('unlabeled'));
  1110. }
  1111. /**
  1112. * Returns the name of the element's plugin.
  1113. */
  1114. public function plugin() {
  1115. return $this->itemName;
  1116. }
  1117. /**
  1118. * Returns info about the element's plugin.
  1119. */
  1120. public function pluginInfo() {
  1121. $this->forceSetUp();
  1122. return $this->itemInfo;
  1123. }
  1124. /**
  1125. * Applies the given export.
  1126. */
  1127. public function import(array $export) {
  1128. $this->importSettings($export[strtoupper($this->plugin())]);
  1129. }
  1130. protected function importSettings($export) {
  1131. // Import parameter settings.
  1132. $export += array('USING' => array(), 'PROVIDE' => array());
  1133. foreach ($export['USING'] as $name => $param_export) {
  1134. $this->importParameterSetting($name, $param_export);
  1135. }
  1136. foreach ($export['PROVIDE'] as $name => $var_export) {
  1137. // The key of $var_export is the variable name, the value the label.
  1138. $this->settings[$name . ':var'] = rules_array_key($var_export);
  1139. $this->settings[$name . ':label'] = reset($var_export);
  1140. }
  1141. }
  1142. protected function importParameterSetting($name, $export) {
  1143. if (is_array($export) && isset($export['select'])) {
  1144. $this->settings[$name . ':select'] = $export['select'];
  1145. if (count($export) > 1) {
  1146. // Add in processor settings.
  1147. unset($export['select']);
  1148. $this->settings[$name . ':process'] = $export;
  1149. }
  1150. }
  1151. // Convert back the [selector] strings being an array with one entry.
  1152. elseif (is_array($export) && count($export) == 1 && isset($export[0])) {
  1153. $this->settings[$name . ':select'] = $export[0];
  1154. }
  1155. elseif (is_array($export) && isset($export['value'])) {
  1156. $this->settings[$name] = $export['value'];
  1157. }
  1158. else {
  1159. $this->settings[$name] = $export;
  1160. }
  1161. }
  1162. /**
  1163. * Exports a rule configuration.
  1164. *
  1165. * @param $prefix
  1166. * An optional prefix for each line.
  1167. * @param $php
  1168. * Optional. Set to TRUE to format the export using PHP arrays. By default
  1169. * JSON is used.
  1170. * @return
  1171. * The exported confiugration.
  1172. *
  1173. * @see rules_import()
  1174. */
  1175. public function export($prefix = '', $php = FALSE) {
  1176. $export = $this->exportToArray();
  1177. return $this->isRoot() ? $this->returnExport($export, $prefix, $php) : $export;
  1178. }
  1179. protected function exportToArray() {
  1180. $export[strtoupper($this->plugin())] = $this->exportSettings();
  1181. return $export;
  1182. }
  1183. protected function exportSettings() {
  1184. $export = array();
  1185. if (!$this->isRoot()) {
  1186. foreach ($this->pluginParameterInfo() as $name => $info) {
  1187. if (($return = $this->exportParameterSetting($name, $info)) !== NULL) {
  1188. $export['USING'][$name] = $return;
  1189. }
  1190. }
  1191. foreach ($this->providesVariables() as $name => $info) {
  1192. if (!empty($info['source name'])) {
  1193. $export['PROVIDE'][$info['source name']][$name] = $info['label'];
  1194. }
  1195. }
  1196. }
  1197. return $export;
  1198. }
  1199. protected function exportParameterSetting($name, $info) {
  1200. if (isset($this->settings[$name]) && (empty($info['optional']) || !isset($info['default value']) || $this->settings[$name] != $info['default value'])) {
  1201. // In case of an array-value wrap the value into another array, such that
  1202. // the value cannot be confused with an exported data selector.
  1203. return is_array($this->settings[$name]) ? array('value' => $this->settings[$name]) : $this->settings[$name];
  1204. }
  1205. elseif (isset($this->settings[$name . ':select'])) {
  1206. if (isset($this->settings[$name . ':process']) && $processor = $this->settings[$name . ':process']) {
  1207. $export['select'] = $this->settings[$name . ':select'];
  1208. $export += $processor instanceof RulesDataProcessor ? $processor->getChainSettings() : $processor;
  1209. return $export;
  1210. }
  1211. // If there is no processor use a simple array to abbreviate this usual
  1212. // case. In JSON this turns to a nice [selector] string.
  1213. return array($this->settings[$name . ':select']);
  1214. }
  1215. }
  1216. /**
  1217. * Finalizies the configuration export by adding general attributes regarding
  1218. * the configuration and returns it in the right format.
  1219. */
  1220. protected function returnExport($export, $prefix = '', $php = FALSE) {
  1221. $this->ensureNameExists();
  1222. if (!empty($this->label) && $this->label != t('unlabeled')) {
  1223. $export_cfg[$this->name]['LABEL'] = $this->label;
  1224. }
  1225. $export_cfg[$this->name]['PLUGIN'] = $this->plugin();
  1226. if (!empty($this->weight)) {
  1227. $export_cfg[$this->name]['WEIGHT'] = $this->weight;
  1228. }
  1229. if (isset($this->active) && !$this->active) {
  1230. $export_cfg[$this->name]['ACTIVE'] = FALSE;
  1231. }
  1232. if (!empty($this->tags)) {
  1233. $export_cfg[$this->name]['TAGS'] = $this->tags;
  1234. }
  1235. if ($modules = $this->dependencies()) {
  1236. $export_cfg[$this->name]['REQUIRES'] = $modules;
  1237. }
  1238. if (!empty($this->access_exposed)) {
  1239. $export_cfg[$this->name]['ACCESS_EXPOSED'] = $this->access_exposed;
  1240. };
  1241. $export_cfg[$this->name] += $export;
  1242. return $php ? entity_var_export($export_cfg, $prefix) : entity_var_json_export($export_cfg, $prefix);
  1243. }
  1244. /**
  1245. * Resets any internal static caches.
  1246. *
  1247. * This function does not reset regular caches as retrieved via
  1248. * rules_get_cache(). Usually, it's invoked automatically when a Rules
  1249. * configuration is modified.
  1250. *
  1251. * Static caches are reset for the element and any elements down the tree. To
  1252. * clear static caches of the whole configuration, invoke the function at the
  1253. * root.
  1254. *
  1255. * @see RulesPlugin::availableVariables()
  1256. */
  1257. public function resetInternalCache() {
  1258. $this->availableVariables = NULL;
  1259. }
  1260. }
  1261. /**
  1262. * Defines a common base class for so called "Abstract Plugins" like actions.
  1263. * Thus modules have to provide the concrete plugin implementation.
  1264. */
  1265. abstract class RulesAbstractPlugin extends RulesPlugin {
  1266. protected $elementName;
  1267. protected $info = array('parameter' => array(), 'provides' => array());
  1268. protected $infoLoaded = FALSE;
  1269. /**
  1270. * @param $name
  1271. * The plugin implementation's name.
  1272. * @param $info
  1273. * Further information provided about the plugin. Optional.
  1274. * @throws RulesException
  1275. * If validation of the passed settings fails RulesExceptions are thrown.
  1276. */
  1277. function __construct($name = NULL, $settings = array()) {
  1278. $this->elementName = $name;
  1279. $this->settings = (array) $settings + array('#_needs_processing' => TRUE);
  1280. $this->setUp();
  1281. }
  1282. protected function setUp() {
  1283. parent::setUp();
  1284. if (isset($this->cache[$this->itemName . '_info'][$this->elementName])) {
  1285. $this->info = $this->cache[$this->itemName . '_info'][$this->elementName];
  1286. // Remember that the info has been correctly setup.
  1287. // @see self::forceSetup().
  1288. $this->infoLoaded = TRUE;
  1289. // Add in per-plugin implementation callbacks if any.
  1290. if (!empty($this->info['faces_cache'])) {
  1291. foreach ($this->info['faces_cache'] as $face => $data) {
  1292. list($methods, $file_names) = $data;
  1293. foreach ($methods as $method => $callback) {
  1294. $this->facesMethods[$method] = $callback;
  1295. }
  1296. foreach ((array) $file_names as $method => $name) {
  1297. $this->facesIncludes[$method] = array('module' => $this->info['module'], 'name' => $name);
  1298. }
  1299. }
  1300. // Invoke the info_alter callback, but only if it has been implemented.
  1301. if ($this->facesMethods['info_alter'] != $this->itemInfo['faces_cache'][0]['info_alter']) {
  1302. $this->__call('info_alter', array(&$this->info));
  1303. }
  1304. }
  1305. }
  1306. elseif (!empty($this->itemInfo['faces_cache']) && function_exists($this->elementName)) {
  1307. // We don't have any info, so just add the name as execution callback.
  1308. $this->override(array('execute' => $this->elementName));
  1309. }
  1310. }
  1311. public function forceSetUp() {
  1312. if (!isset($this->cache) || (!empty($this->itemInfo['faces_cache']) && !$this->faces)) {
  1313. $this->setUp();
  1314. }
  1315. // In case we have element specific information, which is not loaded yet,
  1316. // do so now. This might happen if the element has been initially loaded
  1317. // with an incomplete cache, i.e. during cache rebuilding.
  1318. elseif (!$this->infoLoaded && isset($this->cache[$this->itemName . '_info'][$this->elementName])) {
  1319. $this->setUp();
  1320. }
  1321. }
  1322. /**
  1323. * Returns the label of the element.
  1324. */
  1325. public function label() {
  1326. $info = $this->info();
  1327. return isset($info['label']) ? $info['label'] : t('@plugin "@name"', array('@name' => $this->elementName, '@plugin' => $this->plugin()));
  1328. }
  1329. public function access() {
  1330. $info = $this->info();
  1331. $this->loadBasicInclude();
  1332. if (!empty($info['access callback']) && !call_user_func($info['access callback'], $this->itemName, $this->getElementName())) {
  1333. return FALSE;
  1334. }
  1335. return parent::access() && $this->__call('access');
  1336. }
  1337. public function integrityCheck() {
  1338. // Do the usual integrity check first so the implementation's validation
  1339. // handler can rely on that already.
  1340. parent::integrityCheck();
  1341. // Make sure the element is known.
  1342. $this->forceSetUp();
  1343. if (!isset($this->cache[$this->itemName . '_info'][$this->elementName])) {
  1344. throw new RulesIntegrityException(t('Unknown @plugin %name.', array('@plugin' => $this->plugin(), '%name' => $this->elementName)));
  1345. }
  1346. $this->validate();
  1347. return $this;
  1348. }
  1349. public function processSettings($force = FALSE) {
  1350. // Process if not done yet.
  1351. if ($force || !empty($this->settings['#_needs_processing'])) {
  1352. $this->resetInternalCache();
  1353. // In case the element implements the info alteration callback, (re-)run
  1354. // the alteration so that any settings depending info alterations are
  1355. // applied.
  1356. if ($this->facesMethods && $this->facesMethods['info_alter'] != $this->itemInfo['faces_cache'][0]['info_alter']) {
  1357. $this->__call('info_alter', array(&$this->info));
  1358. }
  1359. // First let the plugin implementation do processing, so data types of the
  1360. // parameters are fixed when we process the settings.
  1361. $this->process();
  1362. parent::processSettings($force);
  1363. }
  1364. }
  1365. public function pluginParameterInfo() {
  1366. // Ensure the info alter callback has been executed.
  1367. $this->forceSetup();
  1368. return parent::pluginParameterInfo();
  1369. }
  1370. public function pluginProvidesVariables() {
  1371. // Ensure the info alter callback has been executed.
  1372. $this->forceSetup();
  1373. return parent::pluginProvidesVariables();
  1374. }
  1375. public function info() {
  1376. // Ensure the info alter callback has been executed.
  1377. $this->forceSetup();
  1378. return $this->info;
  1379. }
  1380. protected function variableInfoAssertions() {
  1381. // Get the implementation's assertions and map them to the variable names.
  1382. if ($assertions = $this->__call('assertions')) {
  1383. foreach ($assertions as $param_name => $data) {
  1384. $name = isset($this->settings[$param_name . ':select']) ? $this->settings[$param_name . ':select'] : $param_name;
  1385. $return[$name] = $data;
  1386. }
  1387. return $return;
  1388. }
  1389. }
  1390. public function import(array $export) {
  1391. // The key is the element name and the value the actual export.
  1392. $this->elementName = rules_array_key($export);
  1393. $export = reset($export);
  1394. // After setting the element name, setup the element again so the right
  1395. // element info is loaded.
  1396. $this->setUp();
  1397. if (!isset($export['USING']) && !isset($export['PROVIDES']) && !empty($export)) {
  1398. // The export has been abbreviated to skip "USING".
  1399. $export = array('USING' => $export);
  1400. }
  1401. $this->importSettings($export);
  1402. }
  1403. protected function exportToArray() {
  1404. $export = $this->exportSettings();
  1405. if (!$this->providesVariables()) {
  1406. // Abbreviate the export making "USING" implicit.
  1407. $export = isset($export['USING']) ? $export['USING'] : array();
  1408. }
  1409. return array($this->elementName => $export);
  1410. }
  1411. public function dependencies() {
  1412. $modules = array_flip(parent::dependencies());
  1413. $modules += array_flip((array) $this->__call('dependencies'));
  1414. return array_keys($modules + (isset($this->info['module']) ? array($this->info['module'] => 1) : array()));
  1415. }
  1416. public function executeByArgs($args = array()) {
  1417. $replacements = array('%label' => $this->label(), '@plugin' => $this->itemName);
  1418. rules_log('Executing @plugin %label.', $replacements, RulesLog::INFO, $this, TRUE);
  1419. $this->processSettings();
  1420. // If there is no element info, just pass through the passed arguments.
  1421. // That way we support executing actions without any info at all.
  1422. if ($this->info()) {
  1423. $state = $this->setUpState($args);
  1424. module_invoke_all('rules_config_execute', $this);
  1425. $result = $this->evaluate($state);
  1426. $return = $this->returnVariables($state, $result);
  1427. }
  1428. else {
  1429. rules_log('Unable to execute @plugin %label.', $replacements, RulesLog::ERROR, $this);
  1430. }
  1431. $state->cleanUp();
  1432. rules_log('Finished executing of @plugin %label.', $replacements, RulesLog::INFO, $this, FALSE);
  1433. return $return;
  1434. }
  1435. /**
  1436. * Execute the configured execution callback and log that.
  1437. */
  1438. abstract protected function executeCallback(array $args, RulesState $state = NULL);
  1439. public function evaluate(RulesState $state) {
  1440. $this->processSettings();
  1441. try {
  1442. // Get vars as needed for execute and call it.
  1443. return $this->executeCallback($this->getExecutionArguments($state), $state);
  1444. }
  1445. catch (RulesEvaluationException $e) {
  1446. rules_log($e->msg, $e->args, $e->severity);
  1447. rules_log('Unable to evaluate %name.', array('%name' => $this->getPluginName()), RulesLog::WARN, $this);
  1448. }
  1449. // Catch wrapper exceptions that might occur due to failures loading an
  1450. // entity or similar.
  1451. catch (EntityMetadataWrapperException $e) {
  1452. rules_log('Unable to get a data value. Error: !error', array('!error' => $e->getMessage()), RulesLog::WARN);
  1453. rules_log('Unable to evaluate %name.', array('%name' => $this->getPluginName()), RulesLog::WARN, $this);
  1454. }
  1455. }
  1456. public function __sleep() {
  1457. return parent::__sleep() + array('elementName' => 'elementName');
  1458. }
  1459. public function getPluginName() {
  1460. return $this->itemName ." ". $this->elementName;
  1461. }
  1462. /**
  1463. * Gets the name of the configured action or condition.
  1464. */
  1465. public function getElementName() {
  1466. return $this->elementName;
  1467. }
  1468. /**
  1469. * Add in the data provided by the info hooks to the cache.
  1470. */
  1471. public function rebuildCache(&$itemInfo, &$cache) {
  1472. parent::rebuildCache($itemInfo, $cache);
  1473. // Include all declared files so we can find all implementations.
  1474. self::includeFiles();
  1475. // Get the plugin's own info data.
  1476. $cache[$this->itemName .'_info'] = rules_fetch_data($this->itemName .'_info');
  1477. foreach ($cache[$this->itemName .'_info'] as $name => &$info) {
  1478. $info += array(
  1479. 'parameter' => isset($info['arguments']) ? $info['arguments'] : array(),
  1480. 'provides' => isset($info['new variables']) ? $info['new variables'] : array(),
  1481. 'base' => $name,
  1482. 'callbacks' => array(),
  1483. );
  1484. unset($info['arguments'], $info['new variables']);
  1485. $info['callbacks'] += array('execute' => $info['base']);
  1486. // Build up the per plugin implementation faces cache.
  1487. foreach ($this->faces as $interface) {
  1488. $methods = $file_names = array();
  1489. $includes = self::getIncludeFiles($info['module']);
  1490. foreach (get_class_methods($interface) as $method) {
  1491. if (isset($info['callbacks'][$method]) && ($function = $info['callbacks'][$method])) {
  1492. $methods[$method][0] = $function;
  1493. $file_names[$method] = $this->getFileName($function, $includes);
  1494. }
  1495. elseif (function_exists($function = $info['base'] . '_' . $method)) {
  1496. $methods[$method][0] = $function;
  1497. $file_names[$method] = $this->getFileName($function, $includes);
  1498. }
  1499. }
  1500. // Cache only the plugin implementation specific callbacks.
  1501. $info['faces_cache'][$interface] = array($methods, array_filter($file_names));
  1502. }
  1503. // Filter out interfaces with no overriden methods.
  1504. $info['faces_cache'] = rules_filter_array($info['faces_cache'], 0, TRUE);
  1505. // We don't need that any more.
  1506. unset($info['callbacks'], $info['base']);
  1507. }
  1508. }
  1509. /**
  1510. * Makes sure the providing modules' .rules.inc file is included as diverse
  1511. * callbacks may reside in that file.
  1512. */
  1513. protected function loadBasicInclude() {
  1514. static $included = array();
  1515. if (isset($this->info['module']) && !isset($included[$this->info['module']])) {
  1516. $module = $this->info['module'];
  1517. module_load_include('inc', $module, $module . '.rules');
  1518. $included[$module] = TRUE;
  1519. }
  1520. }
  1521. /**
  1522. * Make sure all supported destinations are included.
  1523. */
  1524. protected static function includeFiles() {
  1525. static $included;
  1526. if (!isset($included)) {
  1527. foreach (module_implements('rules_file_info') as $module) {
  1528. // rules.inc are already included thanks to the rules_hook_info() group.
  1529. foreach (self::getIncludeFiles($module, FALSE) as $name) {
  1530. module_load_include('inc', $module, $name);
  1531. }
  1532. }
  1533. $included = TRUE;
  1534. }
  1535. }
  1536. /**
  1537. * Returns all include files for a module. If $all is set to FALSE the
  1538. * $module.rules.inc file isn't added.
  1539. */
  1540. protected static function getIncludeFiles($module, $all = TRUE) {
  1541. $files = (array)module_invoke($module, 'rules_file_info');
  1542. // Automatically add "$module.rules_forms.inc" and "$module.rules.inc".
  1543. $files[] = $module . '.rules_forms';
  1544. if ($all) {
  1545. $files[] = $module . '.rules';
  1546. }
  1547. return $files;
  1548. }
  1549. protected function getFileName($function, $includes) {
  1550. $reflector = new ReflectionFunction($function);
  1551. // On windows the path contains backslashes instead of slashes, fix that.
  1552. $file = str_replace('\\', '/', $reflector->getFileName());
  1553. foreach ($includes as $include) {
  1554. $pos = strpos($file, $include . '.inc');
  1555. // Test whether the file ends with the given filename.inc.
  1556. if ($pos !== FALSE && strlen($file) - $pos == strlen($include) + 4) {
  1557. return $include;
  1558. }
  1559. }
  1560. }
  1561. }
  1562. /**
  1563. * Interface for objects that can be used as action.
  1564. */
  1565. interface RulesActionInterface {
  1566. /**
  1567. * @return As specified.
  1568. *
  1569. * @throws RulesEvaluationException
  1570. * Throws an exception if not all necessary arguments have been provided.
  1571. */
  1572. public function execute();
  1573. }
  1574. /**
  1575. * Interface for objects that can be used as condition.
  1576. */
  1577. interface RulesConditionInterface {
  1578. /**
  1579. * @return Boolean.
  1580. *
  1581. * @throws RulesEvaluationException
  1582. * Throws an exception if not all necessary arguments have been provided.
  1583. */
  1584. public function execute();
  1585. /**
  1586. * Negate the result.
  1587. */
  1588. public function negate($negate = TRUE);
  1589. /**
  1590. * Returns whether the element is configured to negate the result.
  1591. */
  1592. public function isNegated();
  1593. }
  1594. interface RulesTriggerableInterface {
  1595. /**
  1596. * Returns a reference on the array of event names associated with this
  1597. * object.
  1598. */
  1599. public function &events();
  1600. /**
  1601. * Adds the specified event.
  1602. *
  1603. * @return RulesTriggerableInterface
  1604. */
  1605. public function event($event);
  1606. }
  1607. /**
  1608. * Provides the interface used for implementing an abstract plugin by using
  1609. * the Faces extension mechanism.
  1610. */
  1611. interface RulesPluginImplInterface {
  1612. /**
  1613. * Execute the action or condition making use of the parameters as specified.
  1614. */
  1615. public function execute();
  1616. /**
  1617. * Validates $settings independent from a form submission.
  1618. *
  1619. * @throws RulesIntegrityException
  1620. * In case of validation errors, RulesIntegrityExceptions are thrown.
  1621. */
  1622. public function validate();
  1623. /**
  1624. * Processes settings independent from a form submission.
  1625. *
  1626. * Processing results may be stored and accessed on execution time in $settings.
  1627. */
  1628. public function process();
  1629. /**
  1630. * Allows altering of the element's action/condition info.
  1631. *
  1632. * Note that this method is also invoked on evaluation time, thus any costly
  1633. * operations should be avoided.
  1634. *
  1635. * @param $element_info
  1636. * A reference on the element's info as returned by RulesPlugin::info().
  1637. */
  1638. public function info_alter(&$element_info);
  1639. /**
  1640. * Checks whether the user has access to configure this element.
  1641. *
  1642. * Note that this only covers access for already created elements. In order to
  1643. * control access for creating or using elements specify an 'access callback'
  1644. * in the element's info array.
  1645. *
  1646. * @see hook_rules_action_info()
  1647. */
  1648. public function access();
  1649. /**
  1650. * Returns an array of required modules.
  1651. */
  1652. public function dependencies();
  1653. /**
  1654. * Alter the generated configuration form of the element.
  1655. *
  1656. * Validation and processing of the settings should be untied from the form
  1657. * and implemented in validate() and process() wherever it makes sense.
  1658. * For the remaining cases where form tied validation and processing is needed
  1659. * make use of the form API #element_validate and #value_callback properties.
  1660. */
  1661. public function form_alter(&$form, $form_state, $options);
  1662. /**
  1663. * Optionally returns an array of info assertions for the specified
  1664. * parameters. This allows conditions to assert additional metadata, such as
  1665. * info about the fields of a bundle.
  1666. *
  1667. * @see RulesPlugin::variableInfoAssertions()
  1668. */
  1669. public function assertions();
  1670. }
  1671. /**
  1672. * Interface for optimizing evaluation.
  1673. *
  1674. * @see RulesContainerPlugin::optimize()
  1675. */
  1676. interface RulesOptimizationInterface {
  1677. /**
  1678. * Optimizes a rule configuration in order to speed up evaluation.
  1679. */
  1680. public function optimize();
  1681. }
  1682. /**
  1683. * Class providing default implementations of the methods of the RulesPluginImplInterface.
  1684. *
  1685. * If a plugin implementation does not provide a function for a method, the
  1686. * default method of this class will be invoked.
  1687. *
  1688. * @see RulesPluginImplInterface
  1689. * @see RulesAbstractPlugin
  1690. */
  1691. class RulesAbstractPluginDefaults extends FacesExtender implements RulesPluginImplInterface {
  1692. public function execute() {
  1693. throw new RulesEvaluationException($this->object->getPluginName() .": Execution implementation is missing.", array(), $this->object, RulesLog::ERROR);
  1694. }
  1695. /**
  1696. * Implements RulesPluginImplInterface.
  1697. */
  1698. public function access() {
  1699. return TRUE;
  1700. }
  1701. public function validate() {}
  1702. public function process() {}
  1703. public function info_alter(&$element_info) {}
  1704. public function dependencies() {}
  1705. public function form_alter(&$form, $form_state, $options) {}
  1706. public function assertions() {}
  1707. }
  1708. /**
  1709. * A RecursiveIterator for rule elements.
  1710. */
  1711. class RulesRecursiveElementIterator extends ArrayIterator implements RecursiveIterator {
  1712. public function getChildren() {
  1713. return $this->current()->getIterator();
  1714. }
  1715. public function hasChildren() {
  1716. return $this->current() instanceof IteratorAggregate;
  1717. }
  1718. }
  1719. /**
  1720. * Base class for ContainerPlugins like Rules, Logical Operations or Loops.
  1721. */
  1722. abstract class RulesContainerPlugin extends RulesPlugin implements IteratorAggregate {
  1723. protected $children = array();
  1724. public function __construct($variables = array()) {
  1725. $this->setUp();
  1726. if (!empty($variables) && $this->isRoot()) {
  1727. $this->info['variables'] = $variables;
  1728. }
  1729. }
  1730. /**
  1731. * Returns the specified variables, in case the plugin is used as component.
  1732. */
  1733. public function &componentVariables() {
  1734. if ($this->isRoot()) {
  1735. $this->info += array('variables' => array());
  1736. return $this->info['variables'];
  1737. }
  1738. // We have to return a reference in any case.
  1739. $return = NULL;
  1740. return $return;
  1741. }
  1742. /**
  1743. * Allow access to the children through the iterator.
  1744. *
  1745. * @return RulesRecursiveElementIterator
  1746. */
  1747. public function getIterator() {
  1748. return new RulesRecursiveElementIterator($this->children);
  1749. }
  1750. /**
  1751. * @return RulesContainerPlugin
  1752. */
  1753. public function integrityCheck() {
  1754. if (!empty($this->info['variables']) && !$this->isRoot()) {
  1755. throw new RulesIntegrityException(t('%plugin: Specifying state variables is not possible for child elements.', array('%plugin' => $this->getPluginName())), $this);
  1756. }
  1757. parent::integrityCheck();
  1758. foreach ($this->children as $child) {
  1759. $child->integrityCheck();
  1760. }
  1761. return $this;
  1762. }
  1763. public function dependencies() {
  1764. $modules = array();
  1765. foreach ($this->children as $child) {
  1766. $modules += array_flip($child->dependencies());
  1767. }
  1768. return array_keys($modules);
  1769. }
  1770. public function parameterInfo($optional = FALSE) {
  1771. $params = parent::parameterInfo($optional);
  1772. if (isset($this->info['variables'])) {
  1773. foreach ($this->info['variables'] as $name => $var_info) {
  1774. if (empty($var_info['handler']) && (!isset($var_info['parameter']) || $var_info['parameter'])) {
  1775. $params[$name] = $var_info;
  1776. // For lists allow empty variables by default.
  1777. if (entity_property_list_extract_type($var_info['type'])) {
  1778. $params[$name] += array('allow null' => TRUE);
  1779. }
  1780. }
  1781. }
  1782. }
  1783. return $params;
  1784. }
  1785. public function availableVariables() {
  1786. if (!isset($this->availableVariables)) {
  1787. if ($this->isRoot()) {
  1788. $this->availableVariables = RulesState::defaultVariables();
  1789. if (isset($this->info['variables'])) {
  1790. $this->availableVariables += $this->info['variables'];
  1791. }
  1792. }
  1793. else {
  1794. $this->availableVariables = $this->parent->stateVariables($this);
  1795. }
  1796. }
  1797. return $this->availableVariables;
  1798. }
  1799. /**
  1800. * Returns info about variables available in the evaluation state for any
  1801. * children elements or if given for a special child element.
  1802. *
  1803. * @param $element
  1804. * The element for which the available state variables should be returned.
  1805. * If NULL is given, the variables available before any children are invoked
  1806. * are returned. If set to TRUE, the variables available after evaluating
  1807. * all children will be returned.
  1808. */
  1809. protected function stateVariables($element = NULL) {
  1810. $vars = $this->availableVariables();
  1811. if (isset($element)) {
  1812. // Add in variables provided by siblings executed before the element.
  1813. foreach ($this->children as $child) {
  1814. if ($child === $element) {
  1815. break;
  1816. }
  1817. $vars += $child->providesVariables();
  1818. // Take variable info assertions into account.
  1819. if ($assertions = $child->variableInfoAssertions()) {
  1820. $vars = RulesData::addMetadataAssertions($vars, $assertions);
  1821. }
  1822. }
  1823. }
  1824. return $vars;
  1825. }
  1826. protected function variableInfoAssertions() {
  1827. $assertions = array();
  1828. foreach ($this->children as $child) {
  1829. if ($add = $child->variableInfoAssertions()) {
  1830. $assertions = rules_update_array($assertions, $add);
  1831. }
  1832. }
  1833. return $assertions;
  1834. }
  1835. protected function setUpVariables() {
  1836. return isset($this->info['variables']) ? parent::parameterInfo(TRUE) + $this->info['variables'] : $this->parameterInfo(TRUE);
  1837. }
  1838. /**
  1839. * Condition containers just return a boolean while action containers return
  1840. * the configured provided variables as an array of variables.
  1841. */
  1842. public function executeByArgs($args = array()) {
  1843. $replacements = array('%label' => $this->label(), '@plugin' => $this->itemName);
  1844. rules_log('Executing @plugin %label.', $replacements, RulesLog::INFO, $this, TRUE);
  1845. $this->processSettings();
  1846. $state = $this->setUpState($args);
  1847. // Handle recursion prevention.
  1848. if ($state->isBlocked($this)) {
  1849. return rules_log('Not evaluating @plugin %label to prevent recursion.', array('%label' => $this->label(), '@plugin' => $this->plugin()), RulesLog::INFO);
  1850. }
  1851. // Block the config to prevent any future recursion.
  1852. $state->block($this);
  1853. module_invoke_all('rules_config_execute', $this);
  1854. $result = $this->evaluate($state);
  1855. $return = $this->returnVariables($state, $result);
  1856. $state->unblock($this);
  1857. $state->cleanUp();
  1858. rules_log('Finished executing of @plugin %label.', $replacements, RulesLog::INFO, $this, FALSE);
  1859. return $return;
  1860. }
  1861. public function access() {
  1862. foreach ($this->children as $key => $child) {
  1863. if (!$child->access()) {
  1864. return FALSE;
  1865. }
  1866. }
  1867. return TRUE;
  1868. }
  1869. public function destroy() {
  1870. foreach ($this->children as $key => $child) {
  1871. $child->destroy();
  1872. }
  1873. parent::destroy();
  1874. }
  1875. /**
  1876. * By default we do a deep clone.
  1877. */
  1878. public function __clone() {
  1879. parent::__clone();
  1880. foreach ($this->children as $key => $child) {
  1881. $this->children[$key] = clone $child;
  1882. $this->children[$key]->parent = $this;
  1883. }
  1884. }
  1885. /**
  1886. * Override delete to keep the children alive, if possible.
  1887. */
  1888. public function delete($keep_children = TRUE) {
  1889. if (isset($this->parent) && $keep_children) {
  1890. foreach ($this->children as $child) {
  1891. $child->setParent($this->parent);
  1892. }
  1893. }
  1894. parent::delete();
  1895. }
  1896. public function __sleep() {
  1897. return parent::__sleep() + array('children' => 'children', 'info' => 'info');
  1898. }
  1899. /**
  1900. * Sorts all child elements by their weight.
  1901. *
  1902. * @param $deep
  1903. * If enabled a deep sort is performed, thus the whole element tree below
  1904. * this element is sorted.
  1905. */
  1906. public function sortChildren($deep = FALSE) {
  1907. // Make sure the array order is kept in case two children have the same
  1908. // weight by ensuring later childrens would have higher weights.
  1909. foreach (array_values($this->children) as $i => $child) {
  1910. $child->weight += $i / 1000;
  1911. }
  1912. usort($this->children, array('RulesPlugin', 'compare'));
  1913. // Fix up the weights afterwards to be unique integers.
  1914. foreach (array_values($this->children) as $i => $child) {
  1915. $child->weight = $i * 2;
  1916. }
  1917. if ($deep) {
  1918. foreach (new ParentIterator($this->getIterator()) as $child) {
  1919. $child->sortChildren(TRUE);
  1920. }
  1921. }
  1922. $this->resetInternalCache();
  1923. }
  1924. protected function exportChildren($key = NULL) {
  1925. $key = isset($key) ? $key : strtoupper($this->plugin());
  1926. $export[$key] = array();
  1927. foreach ($this->children as $child) {
  1928. $export[$key][] = $child->export();
  1929. }
  1930. return $export;
  1931. }
  1932. /**
  1933. * Determines whether the element should be exported in flat style. Flat style
  1934. * means that the export keys are written directly into the export array,
  1935. * whereas else the export is written into a sub-array.
  1936. */
  1937. protected function exportFlat() {
  1938. // By default we always use flat style for plugins without any parameters
  1939. // or provided variables, as then only children have to be exported. E.g.
  1940. // this applies to the OR and AND plugins.
  1941. return $this->isRoot() || (!$this->pluginParameterInfo() && !$this->providesVariables());
  1942. }
  1943. protected function exportToArray() {
  1944. $export = array();
  1945. if (!empty($this->info['variables'])) {
  1946. $export['USES VARIABLES'] = $this->info['variables'];
  1947. }
  1948. if ($this->exportFlat()) {
  1949. $export += $this->exportSettings() + $this->exportChildren();
  1950. }
  1951. else {
  1952. $export[strtoupper($this->plugin())] = $this->exportSettings() + $this->exportChildren();
  1953. }
  1954. return $export;
  1955. }
  1956. public function import(array $export) {
  1957. if (!empty($export['USES VARIABLES'])) {
  1958. $this->info['variables'] = $export['USES VARIABLES'];
  1959. }
  1960. // Care for exports having the export array nested in a sub-array.
  1961. if (!$this->exportFlat()) {
  1962. $export = reset($export);
  1963. }
  1964. $this->importSettings($export);
  1965. $this->importChildren($export);
  1966. }
  1967. protected function importChildren($export, $key = NULL) {
  1968. $key = isset($key) ? $key : strtoupper($this->plugin());
  1969. foreach ($export[$key] as $child_export) {
  1970. $plugin = _rules_import_get_plugin(rules_array_key($child_export), $this instanceof RulesActionInterface ? 'action' : 'condition');
  1971. $child = rules_plugin_factory($plugin);
  1972. $child->setParent($this);
  1973. $child->import($child_export);
  1974. }
  1975. }
  1976. public function resetInternalCache() {
  1977. $this->availableVariables = NULL;
  1978. foreach ($this->children as $child) {
  1979. $child->resetInternalCache();
  1980. }
  1981. }
  1982. }
  1983. /**
  1984. * Base class for all action containers.
  1985. */
  1986. abstract class RulesActionContainer extends RulesContainerPlugin implements RulesActionInterface {
  1987. public function __construct($variables = array(), $providesVars = array()) {
  1988. parent::__construct($variables);
  1989. // The provided vars of a component are the names of variables, which should
  1990. // be provided to the caller. See rule().
  1991. if ($providesVars) {
  1992. $this->info['provides'] = $providesVars;
  1993. }
  1994. }
  1995. /**
  1996. * Add an action. Pass either an instance of the RulesActionInterface
  1997. * or the arguments as needed by rules_action().
  1998. *
  1999. * @return RulesActionContainer
  2000. * Returns $this to support chained usage.
  2001. */
  2002. public function action($name, $settings = array()) {
  2003. $action = (is_object($name) && $name instanceof RulesActionInterface) ? $name : rules_action($name, $settings);
  2004. $action->setParent($this);
  2005. return $this;
  2006. }
  2007. /**
  2008. * Evaluate, whereas by default new vars are visible in the parent's scope.
  2009. */
  2010. public function evaluate(RulesState $state) {
  2011. foreach ($this->children as $action) {
  2012. $action->evaluate($state);
  2013. }
  2014. }
  2015. public function pluginProvidesVariables() {
  2016. return array();
  2017. }
  2018. public function providesVariables() {
  2019. $provides = parent::providesVariables();
  2020. if (isset($this->info['provides']) && $vars = $this->componentVariables()) {
  2021. // Determine the full variable info for the provided variables. Note that
  2022. // we only support providing variables list in the component vars.
  2023. $provides += array_intersect_key($vars, array_flip($this->info['provides']));
  2024. }
  2025. return $provides;
  2026. }
  2027. /**
  2028. * Returns an array of variable names, which are provided by passing through
  2029. * the provided variables of the children.
  2030. */
  2031. public function &componentProvidesVariables() {
  2032. $this->info += array('provides' => array());
  2033. return $this->info['provides'];
  2034. }
  2035. protected function exportToArray() {
  2036. $export = parent::exportToArray();
  2037. if (!empty($this->info['provides'])) {
  2038. $export['PROVIDES VARIABLES'] = $this->info['provides'];
  2039. }
  2040. return $export;
  2041. }
  2042. public function import(array $export) {
  2043. parent::import($export);
  2044. if (!empty($export['PROVIDES VARIABLES'])) {
  2045. $this->info['provides'] = $export['PROVIDES VARIABLES'];
  2046. }
  2047. }
  2048. }
  2049. /**
  2050. * Base class for all condition containers.
  2051. */
  2052. abstract class RulesConditionContainer extends RulesContainerPlugin implements RulesConditionInterface {
  2053. protected $negate = FALSE;
  2054. /**
  2055. * Add a condition. Pass either an instance of the RulesConditionInterface
  2056. * or the arguments as needed by rules_condition().
  2057. *
  2058. * @return RulesConditionContainer
  2059. * Returns $this to support chained usage.
  2060. */
  2061. public function condition($name, $settings = array()) {
  2062. $condition = (is_object($name) && $name instanceof RulesConditionInterface) ? $name : rules_condition($name, $settings);
  2063. $condition->setParent($this);
  2064. return $this;
  2065. }
  2066. /**
  2067. * Negate this condition.
  2068. *
  2069. * @return RulesConditionContainer
  2070. */
  2071. public function negate($negate = TRUE) {
  2072. $this->negate = (bool) $negate;
  2073. return $this;
  2074. }
  2075. public function isNegated() {
  2076. return $this->negate;
  2077. }
  2078. public function __sleep() {
  2079. return parent::__sleep() + array('negate' => 'negate');
  2080. }
  2081. /**
  2082. * Just return the condition container's result.
  2083. */
  2084. protected function returnVariables(RulesState $state, $result = NULL) {
  2085. return $result;
  2086. }
  2087. protected function exportChildren($key = NULL) {
  2088. $key = isset($key) ? $key : strtoupper($this->plugin());
  2089. return parent::exportChildren($this->negate ? 'NOT ' . $key : $key);
  2090. }
  2091. protected function importChildren($export, $key = NULL) {
  2092. $key = isset($key) ? $key : strtoupper($this->plugin());
  2093. // Care for negated elements.
  2094. if (!isset($export[$key]) && isset($export['NOT ' . $key])) {
  2095. $this->negate = TRUE;
  2096. $key = 'NOT ' . $key;
  2097. }
  2098. parent::importChildren($export, $key);
  2099. }
  2100. /**
  2101. * Overridden to exclude variable assertions of negated conditions.
  2102. */
  2103. protected function stateVariables($element = NULL) {
  2104. $vars = $this->availableVariables();
  2105. if (isset($element)) {
  2106. // Add in variables provided by siblings executed before the element.
  2107. foreach ($this->children as $child) {
  2108. if ($child === $element) {
  2109. break;
  2110. }
  2111. $vars += $child->providesVariables();
  2112. // Take variable info assertions into account.
  2113. if (!$this->negate && !$child->isNegated() && ($assertions = $child->variableInfoAssertions())) {
  2114. $vars = RulesData::addMetadataAssertions($vars, $assertions);
  2115. }
  2116. }
  2117. }
  2118. return $vars;
  2119. }
  2120. }
  2121. /**
  2122. * The rules default logging class.
  2123. */
  2124. class RulesLog {
  2125. const INFO = 1;
  2126. const WARN = 2;
  2127. const ERROR = 3;
  2128. static protected $logger;
  2129. /**
  2130. * @return RulesLog
  2131. * Returns the rules logger instance.
  2132. */
  2133. static function logger() {
  2134. if (!isset(self::$logger)) {
  2135. $class = __CLASS__;
  2136. self::$logger = new $class(variable_get('rules_log_level', self::INFO));
  2137. }
  2138. return self::$logger;
  2139. }
  2140. protected $log = array();
  2141. protected $logLevel, $line = 0;
  2142. /**
  2143. * This is a singleton.
  2144. */
  2145. protected function __construct($logLevel = self::WARN) {
  2146. $this->logLevel = $logLevel;
  2147. }
  2148. public function __clone() {
  2149. throw new Exception("Cannot clone the logger.");
  2150. }
  2151. /**
  2152. * Logs a log message.
  2153. *
  2154. * @see rules_log()
  2155. */
  2156. public function log($msg, $args = array(), $logLevel = self::INFO, $scope = NULL, $path = NULL) {
  2157. if ($logLevel >= $this->logLevel) {
  2158. $this->log[] = array($msg, $args, $logLevel, microtime(TRUE), $scope, $path);
  2159. }
  2160. }
  2161. /**
  2162. * Checks the log and throws an exception if there were any problems.
  2163. */
  2164. function checkLog($logLevel = self::WARN) {
  2165. foreach ($this->log as $entry) {
  2166. if ($entry[2] >= $logLevel) {
  2167. throw new Exception($this->render());
  2168. }
  2169. }
  2170. }
  2171. /**
  2172. * Checks the log for (error) messages with a log level equal or higher than the given one.
  2173. *
  2174. * @return
  2175. * Whether the an error has been logged.
  2176. */
  2177. public function hasErrors($logLevel = self::WARN) {
  2178. foreach ($this->log as $entry) {
  2179. if ($entry[2] >= $logLevel) {
  2180. return TRUE;
  2181. }
  2182. }
  2183. return FALSE;
  2184. }
  2185. /**
  2186. * Gets an array of logged messages.
  2187. */
  2188. public function get() {
  2189. return $this->log;
  2190. }
  2191. /**
  2192. * Renders the whole log.
  2193. */
  2194. public function render() {
  2195. $line = 0;
  2196. $output = array();
  2197. while (isset($this->log[$line])) {
  2198. $vars['head'] = t($this->log[$line][0], $this->log[$line][1]);
  2199. $vars['log'] = $this->renderHelper($line);
  2200. $output[] = theme('rules_debug_element', $vars);
  2201. $line++;
  2202. }
  2203. return implode('', $output);
  2204. }
  2205. /**
  2206. * Renders the log of one event invocation.
  2207. */
  2208. protected function renderHelper(&$line = 0) {
  2209. $startTime = isset($this->log[$line][3]) ? $this->log[$line][3] : 0;
  2210. $output = array();
  2211. while ($line < count($this->log)) {
  2212. if ($output && !empty($this->log[$line][4])) {
  2213. // The next entry stems from another evaluated set, add in its log
  2214. // messages here.
  2215. $vars['head'] = t($this->log[$line][0], $this->log[$line][1]);
  2216. if (isset($this->log[$line][5])) {
  2217. $vars['link'] = '[' . l('edit', $this->log[$line][5]) . ']';
  2218. }
  2219. $vars['log'] = $this->renderHelper($line);
  2220. $output[] = theme('rules_debug_element', $vars);
  2221. }
  2222. else {
  2223. $formatted_diff = round(($this->log[$line][3] - $startTime) * 1000, 3) .' ms';
  2224. $msg = $formatted_diff .' '. t($this->log[$line][0], $this->log[$line][1]);
  2225. if ($this->log[$line][2] >= RulesLog::WARN) {
  2226. $level = $this->log[$line][2] == RulesLog::WARN ? 'warn' : 'error';
  2227. $msg = '<span class="rules-debug-' . $level . '">'. $msg .'</span>';
  2228. }
  2229. if (isset($this->log[$line][5]) && !isset($this->log[$line][4])) {
  2230. $msg .= ' [' . l('edit', $this->log[$line][5]) . ']';
  2231. }
  2232. $output[] = $msg;
  2233. if (isset($this->log[$line][4]) && !$this->log[$line][4]) {
  2234. // This was the last log entry of this set.
  2235. return theme('item_list', array('items' => $output));
  2236. }
  2237. }
  2238. $line++;
  2239. }
  2240. return theme('item_list', array('items' => $output));
  2241. }
  2242. /**
  2243. * Clears the logged messages.
  2244. */
  2245. public function clear() {
  2246. $this->log = array();
  2247. }
  2248. }
  2249. /**
  2250. * A common exception for Rules.
  2251. *
  2252. * This class can be used to catch all exceptions thrown by Rules.
  2253. */
  2254. abstract class RulesException extends Exception {}
  2255. /**
  2256. * An exception that is thrown during evaluation.
  2257. *
  2258. * Messages are prepared to be logged to the watchdog, thus not yet translated.
  2259. *
  2260. * @see watchdog()
  2261. */
  2262. class RulesEvaluationException extends RulesException {
  2263. public $msg, $args, $severity, $element, $keys = array();
  2264. /**
  2265. * @param $msg
  2266. * The exception message containing placeholder as t().
  2267. * @param $args
  2268. * Replacement arguments such as for t().
  2269. * @param $element
  2270. * The element of a configuration causing the exception or an array
  2271. * consisting of the element and keys specifying a setting value causing
  2272. * the exception.
  2273. * @param $severity
  2274. * The RulesLog severity. Defaults to RulesLog::WARN.
  2275. */
  2276. function __construct($msg, array $args = array(), $element = NULL, $severity = RulesLog::WARN) {
  2277. $this->element = is_array($element) ? array_shift($element) : $element;
  2278. $this->keys = is_array($element) ? $element : array();
  2279. $this->msg = $msg;
  2280. $this->args = $args;
  2281. $this->severity = $severity;
  2282. // If an error happened, run the integrity check on the rules configuration
  2283. // and mark it as dirty if it the check fails.
  2284. if ($severity == RulesLog::ERROR && isset($this->element)) {
  2285. $rules_config = $this->element->root();
  2286. rules_config_update_dirty_flag($rules_config);
  2287. // If we discovered a broken configuration, exclude it in future.
  2288. if ($rules_config->dirty) {
  2289. rules_clear_cache();
  2290. }
  2291. }
  2292. // @todo fix _drupal_decode_exception() to use __toString() and override it.
  2293. $this->message = t($this->msg, $this->args);
  2294. }
  2295. }
  2296. /**
  2297. * An exception that is thrown for Rules configurations that fail the integrity check.
  2298. *
  2299. * @see RulesPlugin::integrityCheck()
  2300. */
  2301. class RulesIntegrityException extends RulesException {
  2302. public $msg, $element, $keys = array();
  2303. /**
  2304. * @param string $msg
  2305. * The exception message, already translated.
  2306. * @param $element
  2307. * The element of a configuration causing the exception or an array
  2308. * consisting of the element and keys specifying a parameter or provided
  2309. * variable causing the exception, e.g.
  2310. * @code array($element, 'parameter', 'node') @endcode.
  2311. */
  2312. function __construct($msg, $element = NULL) {
  2313. $this->element = is_array($element) ? array_shift($element) : $element;
  2314. $this->keys = is_array($element) ? $element : array();
  2315. parent::__construct($msg);
  2316. }
  2317. }
  2318. /**
  2319. * An exception that is thrown for missing module dependencies.
  2320. */
  2321. class RulesDependencyException extends RulesIntegrityException {}
  2322. /**
  2323. * Determines the plugin to be used for importing a child element.
  2324. *
  2325. * @param $key
  2326. * The key to look for, e.g. 'OR' or 'DO'.
  2327. * @param $default
  2328. * The default to return if no special plugin can be found.
  2329. */
  2330. function _rules_import_get_plugin($key, $default = 'action') {
  2331. $map = &drupal_static(__FUNCTION__);
  2332. if (!isset($map)) {
  2333. $cache = rules_get_cache();
  2334. foreach ($cache['plugin_info'] as $name => $info) {
  2335. if (!empty($info['embeddable'])) {
  2336. $info += array('import keys' => array(strtoupper($name)));
  2337. foreach ($info['import keys'] as $k) {
  2338. $map[$k] = $name;
  2339. }
  2340. }
  2341. }
  2342. }
  2343. // Cut of any leading NOT from the key.
  2344. if (strpos($key, 'NOT ') === 0) {
  2345. $key = substr($key, 4);
  2346. }
  2347. if (isset($map[$key])) {
  2348. return $map[$key];
  2349. }
  2350. return $default;
  2351. }