<?php
	/**
	 * Rules ListModule
	 * Module will be used to retrieve rules information from rules table
	 */
	class RulesListModule extends ListModule
	{
		/**
		 * Constructor
		 * @param int $id unique id.
		 * @param array $data list of all actions.
		 */
		function RulesListModule($id, $data)
		{
			$this->properties = $GLOBALS['properties']->getRulesProperties();

			parent::ListModule($id, $data);
		}

		/**
		 * Executes all the actions in the $data variable.
		 * @return boolean true on success of false on fialure.
		 */
		function execute()
		{
			foreach($this->data as $actionType => $action)
			{
				try {
					switch($actionType) {
						case 'list':
							$store = $GLOBALS['mapisession']->getDefaultMessageStore();
							$rules = $this->getRules($store);

							if($rules) {
								$this->addActionData('list', $rules);
								$GLOBALS['bus']->addData($this->getResponseData());
							}
							break;
						default:
							$this->handleUnknownActionType($actionType);
					}
				} catch (MAPIException $e) {
					$this->processException($e, $actionType);
				}
			}
		}

		/**
		 * Get all rules of a store
		 *
		 * This function opens the rules table for the specified store, and reads
		 * all rules with PR_RULE_PROVIDER equal to 'RuleOrganizer'. These are the rules
		 * that the user sees when managing rules from Outlook.
		 *
		 * @param {MAPIStore} $store Store in which rules reside
		 * @return {Array} rules data
		*/
		function getRules($store)
		{
			$inbox = mapi_msgstore_getreceivefolder($store);

			$rulesTable = mapi_folder_openmodifytable($inbox);
			$rulesTable = mapi_rules_gettable($rulesTable);

			// Create a restriction to search for rules which have a rule provider
			// which starts with RuleOrganizer. Outlook will generate some rules
			// with PR_RULE_PROVIDER RuleOrganizer2 for client-only rules, however
			// we still want to show these in the client, hence we perform a prefix
			// search.
			mapi_table_restrict($rulesTable,
				array(RES_CONTENT,
					array(
						FUZZYLEVEL	=>	FL_PREFIX | FL_IGNORECASE,
						ULPROPTAG	=>	PR_RULE_PROVIDER,
						VALUE		=>	array(
							PR_RULE_PROVIDER	=>	'RuleOrganizer'
						)
					)
				),
				TBL_BATCH
			);

			mapi_table_sort($rulesTable, array(PR_RULE_SEQUENCE => TABLE_SORT_ASCEND), TBL_BATCH);
			$rows = mapi_table_queryallrows($rulesTable, $this->properties);

			$rules = array();

			foreach($rows as $row) {
				$rules[] = Conversion::mapMAPI2XML($this->properties, $row);
			}
			unset($row);

			return Array('item' => $rules);
		}
	}
?>
