rules.core.inc 91 KB

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