rules.core.inc 91 KB

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