rules.core.inc 93 KB

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