From dd0e140ea3d9ebbfd73c3c47e8529851c4649fd9 Mon Sep 17 00:00:00 2001
From: Erik Hommel <hommel@ee-atwork.nl>
Date: Tue, 10 Mar 2015 10:44:02 +0100
Subject: [PATCH] added api CiviRuleRule Get and Create

---
 CRM/Civirules/BAO/Rule.php                    |  18 +
 CRM/Civirules/BAO/RuleAction.php              |  15 +
 CRM/Civirules/BAO/RuleCondition.php           |  15 +
 CRM/Civirules/Form/Rule.php                   |  89 +++--
 CRM/Civirules/Form/RuleCondition.php          | 333 ++++++++++++++++++
 api/v3/CiviRuleRule/Create.php                |  37 ++
 api/v3/CiviRuleRule/Get.php                   |  15 +
 templates/CRM/Civirules/Form/Rule.tpl         |   6 +-
 .../Form/RuleBlocks/ConditionBlock.tpl        |  21 +-
 .../CRM/Civirules/Form/RuleCondition.tpl      |  17 +
 templates/CRM/Civirules/Page/Rule.tpl         |   4 +-
 xml/Menu/civirules.xml                        |   6 +
 12 files changed, 532 insertions(+), 44 deletions(-)
 create mode 100755 CRM/Civirules/Form/RuleCondition.php
 create mode 100755 api/v3/CiviRuleRule/Create.php
 create mode 100755 api/v3/CiviRuleRule/Get.php
 create mode 100755 templates/CRM/Civirules/Form/RuleCondition.tpl

diff --git a/CRM/Civirules/BAO/Rule.php b/CRM/Civirules/BAO/Rule.php
index d87a941..23cf5af 100755
--- a/CRM/Civirules/BAO/Rule.php
+++ b/CRM/Civirules/BAO/Rule.php
@@ -72,6 +72,8 @@ class CRM_Civirules_BAO_Rule extends CRM_Civirules_DAO_Rule {
     if (empty($ruleId)) {
       throw new Exception('rule id can not be empty when attempting to delete a civirule rule');
     }
+    CRM_Civirules_BAO_RuleAction::deleteWithRuleId($ruleId);
+    CRM_Civirules_BAO_RuleCondition::deleteWithRuleId($ruleId);
     $rule = new CRM_Civirules_BAO_Rule();
     $rule->id = $ruleId;
     $rule->delete();
@@ -148,4 +150,20 @@ class CRM_Civirules_BAO_Rule extends CRM_Civirules_DAO_Rule {
     }
     return FALSE;
   }
+
+  /**
+   * Function to get latest rule id
+   *
+   * @return int $ruleId
+   * @access public
+   * @static
+   */
+  public static function getLatestRuleId() {
+    $rule = new CRM_Civirules_BAO_Rule();
+    $query = 'SELECT MAX(id) AS maxId FROM '.$rule->tableName();
+    $dao = CRM_Core_DAO::executeQuery($query);
+    if ($dao->fetch()) {
+      return $dao->maxId;
+    }
+  }
 }
\ No newline at end of file
diff --git a/CRM/Civirules/BAO/RuleAction.php b/CRM/Civirules/BAO/RuleAction.php
index 036db24..21277df 100755
--- a/CRM/Civirules/BAO/RuleAction.php
+++ b/CRM/Civirules/BAO/RuleAction.php
@@ -113,4 +113,19 @@ class CRM_Civirules_BAO_RuleAction extends CRM_Civirules_DAO_RuleAction {
     $ruleAction->find(true);
     self::add(array('id' => $ruleAction->id, 'is_active' => 1));
   }
+
+  /**
+   * Function to delete all rule actions with rule id
+   *
+   * @param int $ruleId
+   * @access public
+   * @static
+   */
+  public static function deleteWithRuleId($ruleId) {
+    $ruleAction = new CRM_Civirules_BAO_RuleAction();
+    $ruleAction->rule_id = $ruleId;
+    while ($ruleAction->fetch()) {
+      self::deleteWithId($ruleAction->id);
+    }
+  }
 }
\ No newline at end of file
diff --git a/CRM/Civirules/BAO/RuleCondition.php b/CRM/Civirules/BAO/RuleCondition.php
index cb0e589..e04c3d2 100755
--- a/CRM/Civirules/BAO/RuleCondition.php
+++ b/CRM/Civirules/BAO/RuleCondition.php
@@ -113,4 +113,19 @@ class CRM_Civirules_BAO_RuleCondition extends CRM_Civirules_DAO_RuleCondition {
     $ruleCondition->find(true);
     self::add(array('id' => $ruleCondition->id, 'is_active' => 1));
   }
+
+  /**
+   * Function to delete all rule conditions with rule id
+   *
+   * @param int $ruleId
+   * @access public
+   * @static
+   */
+  public static function deleteWithRuleId($ruleId) {
+    $ruleCondition = new CRM_Civirules_BAO_RuleCondition();
+    $ruleCondition->rule_id = $ruleId;
+    while ($ruleCondition->fetch()) {
+      self::deleteWithId($ruleCondition->id);
+    }
+  }
 }
\ No newline at end of file
diff --git a/CRM/Civirules/Form/Rule.php b/CRM/Civirules/Form/Rule.php
index 77f543e..b28eb28 100755
--- a/CRM/Civirules/Form/Rule.php
+++ b/CRM/Civirules/Form/Rule.php
@@ -19,7 +19,9 @@ class CRM_Civirules_Form_Rule extends CRM_Core_Form {
    * @access public
    */
   function buildQuickForm() {
-    $this->setPageTitle();
+    $ruleConditionAddUrl = CRM_Utils_System::url('civicrm/civirule/form/rule_condition', 'action=add&rid='.$this->ruleId, TRUE);
+    $this->assign('ruleConditionAddUrl', $ruleConditionAddUrl);
+    $this->setFormTitle();
     $this->createFormElements();
     parent::buildQuickForm();
   }
@@ -33,22 +35,20 @@ class CRM_Civirules_Form_Rule extends CRM_Core_Form {
     if ($this->_action != CRM_Core_Action::ADD) {
       $this->ruleId = CRM_Utils_Request::retrieve('id', 'Positive');
     }
+    $session = CRM_Core_Session::singleton();
     switch($this->_action) {
       case CRM_Core_Action::DELETE:
         CRM_Civirules_BAO_Rule::deleteWithId($this->ruleId);
-        $session = CRM_Core_Session::singleton();
         $session->setStatus('CiviRule deleted', 'Delete', 'success');
         CRM_Utils_System::redirect($session->readUserContext());
         break;
       case CRM_Core_Action::DISABLE:
         CRM_Civirules_BAO_Rule::disable($this->ruleId);
-        $session = CRM_Core_Session::singleton();
         $session->setStatus('CiviRule disabled', 'Disable', 'success');
         CRM_Utils_System::redirect($session->readUserContext());
         break;
       case CRM_Core_Action::ENABLE:
         CRM_Civirules_BAO_Rule::enable($this->ruleId);
-        $session = CRM_Core_Session::singleton();
         $session->setStatus('CiviRule enabled', 'Enable', 'success');
         CRM_Utils_System::redirect($session->readUserContext());
         break;
@@ -63,12 +63,16 @@ class CRM_Civirules_Form_Rule extends CRM_Core_Form {
   function postProcess() {
     $session = CRM_Core_Session::singleton();
     $userId = $session->get('userID');
+    $this->saveRule($this->_submitValues, $userId);
+    $this->saveRuleEvent($this->_submitValues);
+    $session->setStatus('Rule with linked Event saved succesfully', 'CiviRule saved', 'success');
     /*
-     * always save
+     * if add mode, set user context to form in edit mode to add conditions and actions
      */
-    $this->saveRule($this->_submitValues, $userId);
-    $saveMessage = 'Rule ';
-    $session->setStatus($saveMessage. ' saved succesfully', 'CiviRule saved', 'success');
+    if ($this->_action == CRM_Core_Action::ADD) {
+      $editUrl = CRM_Utils_System::url('civicrm/civirule/form/rule', 'action=update&id='.$this->ruleId, TRUE);
+      $session->pushUserContext($editUrl);
+    }
     parent::postProcess();
   }
 
@@ -99,13 +103,32 @@ class CRM_Civirules_Form_Rule extends CRM_Core_Form {
    */
   function addRules() {
     $this->addFormRule(array('CRM_Civirules_Form_Rule', 'validateRuleLabelExists'));
+    if ($this->_action == CRM_Core_Action::ADD) {
+      $this->addFormRule(array('CRM_Civirules_Form_Rule', 'validateEventEmpty'));
+    }
+  }
+
+  /**
+   * Function to validate that event is not empty in add mode
+   *
+   * @param array $fields
+   * @return array|bool
+   * @access static
+   */
+  static function validateEventEmpty($fields) {
+    if (empty($fields['rule_event_select'])) {
+      $errors['rule_event_select'] = ts('You have to select an event for the rule');
+      return $errors;
+    }
+    return TRUE;
   }
 
   /**
    * Function to validate if rule label already exists
    *
-   * @param type $fields
-   * @return type
+   * @param array $fields
+   * @return array|bool
+   * @access static
    */
   static function validateRuleLabelExists($fields) {
     /*
@@ -118,12 +141,12 @@ class CRM_Civirules_Form_Rule extends CRM_Core_Form {
       $currentLabel = CRM_Civirules_BAO_Rule::getRuleLabelWithId($fields['id']);
       if ($fields['rule_label'] != $currentLabel &&
         CRM_Civirules_BAO_Rule::labelExists($fields['rule_label']) == TRUE) {
-        $errors['rule_label'] = 'There is already a rule with this name';
+        $errors['rule_label'] = ts('There is already a rule with this name');
         return $errors;
       }
     } else {
       if (CRM_Civirules_BAO_Rule::labelExists($fields['rule_label']) == TRUE) {
-        $errors['rule_label'] = 'There is already a rule with this name';
+        $errors['rule_label'] = ts('There is already a rule with this name');
         return $errors;
       }
     }
@@ -143,13 +166,19 @@ class CRM_Civirules_Form_Rule extends CRM_Core_Form {
     $this->add('text', 'rule_created_contact', ts('Created By'));
     $eventList = array_merge(array(' - select - '), CRM_Civirules_Utils::buildEventList());
     asort($eventList);
-    $this->add('select', 'rule_event_select', ts('Select Event'), $eventList, TRUE);
+    $this->add('select', 'rule_event_select', ts('Select Event'), $eventList);
     if ($this->_action == CRM_Core_Action::UPDATE) {
       $this->createUpdateFormElements();
     }
-    $this->addButtons(array(
-      array('type' => 'next', 'name' => ts('Save'), 'isDefault' => TRUE,),
-      array('type' => 'cancel', 'name' => ts('Cancel'))));
+    if ($this->_action == CRM_Core_Action::ADD) {
+      $this->addButtons(array(
+        array('type' => 'next', 'name' => ts('Next'), 'isDefault' => TRUE,),
+        array('type' => 'cancel', 'name' => ts('Cancel'))));
+    } else {
+      $this->addButtons(array(
+        array('type' => 'next', 'name' => ts('Save'), 'isDefault' => TRUE,),
+        array('type' => 'cancel', 'name' => ts('Cancel'))));
+    }
   }
 
   /**
@@ -162,11 +191,11 @@ class CRM_Civirules_Form_Rule extends CRM_Core_Form {
   }
 
   /**
-   * Function to set the page title based on action and data coming in
+   * Function to set the form title based on action and data coming in
    * 
    * @access protected
    */
-  protected function setPageTitle() {
+  protected function setFormTitle() {
     $title = 'CiviRules '.  ucfirst(CRM_Core_Action::description($this->_action)).' Rule';
     CRM_Utils_System::setTitle($title);
   }
@@ -278,16 +307,14 @@ class CRM_Civirules_Form_Rule extends CRM_Core_Form {
   }
 
   /**
-   * Function to set the html for the delete event action
+   * Function to set the html for the delete event action and delete the event
    *
    * @param int $eventId
    * @return string $deleteHtml
    * @access protected
    */
   protected function setEventDeleteAction($eventId) {
-    $deleteUrl = CRM_Utils_System::url('civicrm/civirule/form/event', 'action=delete&id='.
-      $eventId);
-    $deleteHtml = '<a class="action-item" title="Delete" href="'.$deleteUrl.'">Delete</a>';
+    $deleteHtml = '<a class="action-item" title="Delete" href="javascript:deleteEvent('.$this->ruleId.')">Delete</a>';
     return $deleteHtml;
   }
 
@@ -330,6 +357,22 @@ class CRM_Civirules_Form_Rule extends CRM_Core_Form {
     $ruleParams['label'] = $formValues['rule_label'];
     $ruleParams['name'] = CRM_Civirules_Utils::buildNameFromLabel($formValues['rule_label']);
     $ruleParams['is_active'] = $formValues['rule_is_active'];
-    CRM_Civirules_BAO_Rule::add($ruleParams);
+    $savedRule = CRM_Civirules_BAO_Rule::add($ruleParams);
+    $this->ruleId = $savedRule['id'];
+  }
+
+  /**
+   * Function to link an event to a rule
+   *
+   * @param array $formValues
+   */
+  protected function saveRuleEvent($formValues) {
+    if (isset($formValues['rule_event_select'])) {
+      $ruleParams = array(
+        'id' => $this->ruleId,
+        'event_id' => $formValues['rule_event_select']
+      );
+      CRM_Civirules_BAO_Rule::add($ruleParams);
+    }
   }
 }
diff --git a/CRM/Civirules/Form/RuleCondition.php b/CRM/Civirules/Form/RuleCondition.php
new file mode 100755
index 0000000..4cf2d3f
--- /dev/null
+++ b/CRM/Civirules/Form/RuleCondition.php
@@ -0,0 +1,333 @@
+<?php
+/**
+ * Form controller class to manage CiviRule/RuleCondition
+ *
+ * @see http://wiki.civicrm.org/confluence/display/CRMDOC43/QuickForm+Reference
+ *
+ * @author Erik Hommel (CiviCooP) <erik.hommel@civicoop.org>
+ * @license http://www.gnu.org/licenses/agpl-3.0.html
+ */
+require_once 'CRM/Core/Form.php';
+
+class CRM_Civirules_Form_RuleCondition extends CRM_Core_Form {
+
+  protected $ruleId = NULL;
+
+  /**
+   * Function to buildQuickForm (extends parent function)
+   *
+   * @access public
+   */
+  function buildQuickForm() {
+    $this->setFormTitle();
+    $this->createFormElements();
+    parent::buildQuickForm();
+  }
+
+  /**
+   * Function to perform processing before displaying form (overrides parent function)
+   *
+   * @access public
+   */
+  function preProcess() {
+    $this->ruleId = CRM_Utils_Request::retrieve('rid', 'Positive');
+    /*
+     * if no rid in request, then add mode without known ruleId. In that case
+     * get latest rule id @todo test with more tabs open
+     */
+    if (empty($this->ruleId)) {
+      $this->ruleId = CRM_Civirules_BAO_Rule::getLatestRuleId();
+    }
+  }
+
+  /**
+   * Function to perform post save processing (extends parent function)
+   *
+   * @access public
+   */
+  function postProcess() {
+    $session = CRM_Core_Session::singleton();
+    $userId = $session->get('userID');
+    $this->saveRule($this->_submitValues, $userId);
+    $this->saveRuleEvent($this->_submitValues);
+    $session->setStatus('Rule with linked Event, Condition(s) and Action(s) saved succesfully', 'CiviRule saved', 'success');
+    parent::postProcess();
+  }
+
+  /**
+   * Function to set default values (overrides parent function)
+   *
+   * @return array $defaults
+   * @access public
+   */
+  function setDefaultValues() {
+    $defaults = array();
+    $defaults['id'] = $this->ruleId;
+    switch ($this->_action) {
+      case CRM_Core_Action::ADD:
+        $this->setAddDefaults($defaults);
+        break;
+      case CRM_Core_Action::UPDATE:
+        $this->setUpdateDefaults($defaults);
+        break;
+    }
+    return $defaults;
+  }
+
+  /**
+   * Function to add validation rules (overrides parent function)
+   *
+   * @access public
+   */
+  function addRules() {
+    $this->addFormRule(array('CRM_Civirules_Form_Rule', 'validateRuleLabelExists'));
+  }
+
+  /**
+   * Function to validate if rule label already exists
+   *
+   * @param type $fields
+   * @return type
+   */
+  static function validateRuleLabelExists($fields) {
+    /*
+     * if id not empty, edit mode. Check if changed before check if exists
+     */
+    if (!empty($fields['id'])) {
+      /*
+       * check if values have changed against database label
+       */
+      $currentLabel = CRM_Civirules_BAO_Rule::getRuleLabelWithId($fields['id']);
+      if ($fields['rule_label'] != $currentLabel &&
+        CRM_Civirules_BAO_Rule::labelExists($fields['rule_label']) == TRUE) {
+        $errors['rule_label'] = 'There is already a rule with this name';
+        return $errors;
+      }
+    } else {
+      if (CRM_Civirules_BAO_Rule::labelExists($fields['rule_label']) == TRUE) {
+        $errors['rule_label'] = 'There is already a rule with this name';
+        return $errors;
+      }
+    }
+    return TRUE;
+  }
+
+  /**
+   * Function to add the form elements
+   *
+   * @access protected
+   */
+  protected function createFormElements() {
+    $this->add('hidden', 'id');
+    $this->add('text', 'rule_label', ts('Name'), array('size' => CRM_Utils_Type::HUGE), TRUE);
+    $this->add('checkbox', 'rule_is_active', ts('Enabled'));
+    $this->add('text', 'rule_created_date', ts('Created Date'));
+    $this->add('text', 'rule_created_contact', ts('Created By'));
+    $eventList = array_merge(array(' - select - '), CRM_Civirules_Utils::buildEventList());
+    asort($eventList);
+    $this->add('select', 'rule_event_select', ts('Select Event'), $eventList);
+    if ($this->_action == CRM_Core_Action::UPDATE) {
+      $this->createUpdateFormElements();
+    }
+    $this->addButtons(array(
+      array('type' => 'next', 'name' => ts('Save'), 'isDefault' => TRUE,),
+      array('type' => 'cancel', 'name' => ts('Cancel'))));
+  }
+
+  /**
+   * Function to add the form elements specific for the update action
+   */
+  protected function createUpdateFormElements() {
+    $this->add('text', 'rule_event_label', '', array('size' => CRM_Utils_Type::HUGE));
+    $this->assign('ruleConditions', $this->getRuleConditions());
+    $this->assign('ruleActions', $this->getRuleActions());
+  }
+
+  /**
+   * Function to set the form title based on action and data coming in
+   *
+   * @access protected
+   */
+  protected function setFormTitle() {
+    $title = 'CiviRules '.  ucfirst(CRM_Core_Action::description($this->_action)).' Rule';
+    CRM_Utils_System::setTitle($title);
+  }
+
+  /**
+   * Function to set default values if action is add
+   *
+   * @param array $defaults
+   * @access protected
+   */
+  protected function setAddDefaults(&$defaults) {
+    $defaults['rule_is_active'] = 1;
+    $defaults['rule_created_date'] = date('d-m-Y');
+    $session = CRM_Core_Session::singleton();
+    $defaults['rule_created_contact'] = CRM_Civirules_Utils::getContactName($session->get('userID'));
+  }
+
+  /**
+   * Function to set default values if action is update
+   *
+   * @param array $defaults
+   * @access protected
+   */
+  protected function setUpdateDefaults(&$defaults) {
+    $ruleData = CRM_Civirules_BAO_Rule::getValues(array('id' => $this->ruleId));
+    if (!empty($ruleData)) {
+      $defaults['rule_label'] = $ruleData[$this->ruleId]['label'];
+      $defaults['rule_is_active'] = $ruleData[$this->ruleId]['is_active'];
+      $defaults['rule_created_date'] = date('d-m-Y',
+        strtotime($ruleData[$this->ruleId]['created_date']));
+      $defaults['rule_created_contact'] = CRM_Civirules_Utils::
+      getContactName($ruleData[$this->ruleId]['created_user_id']);
+      if (!empty($ruleData[$this->ruleId]['event_id'])) {
+        $this->setEventDefaults($ruleData[$this->ruleId]['event_id'], $defaults);
+      }
+    }
+  }
+
+  /**
+   * Function to get event defaults
+   *
+   * @param int $eventId
+   * @param array $defaults
+   * @access protected
+   */
+  protected function setEventDefaults($eventId, &$defaults) {
+    if (!empty($eventId)) {
+      $defaults['rule_event_label'] = CRM_Civirules_BAO_Event::getEventLabelWithId($eventId);
+      $this->assign('deleteEventUrl', $this->setEventDeleteAction($eventId));
+    }
+  }
+
+  /**
+   * Function to get the rule conditions for the rule
+   *
+   * @return array $ruleConditions
+   * @access protected
+   */
+  protected function getRuleConditions() {
+    $conditionParams = array(
+      'is_active' => 1,
+      'rule_id' => $this->ruleId);
+    $ruleConditions = CRM_Civirules_BAO_RuleCondition::getValues($conditionParams);
+    foreach ($ruleConditions as $ruleConditionId => $ruleCondition) {
+      $ruleConditions[$ruleConditionId]['name'] =
+        CRM_Civirules_BAO_Condition::getConditionLabelWithId($ruleCondition['condition_id']);
+      $ruleConditions[$ruleConditionId]['comparison'] =
+        CRM_Civirules_BAO_Comparison::getComparisonLabelWithId($ruleCondition['comparison_id']);
+      $ruleConditions[$ruleConditionId]['actions'] = $this->setRuleConditionActions($ruleConditionId);
+    }
+    return $ruleConditions;
+  }
+
+  /**
+   * Function to get the rule actions for the rule
+   *
+   * @return array $ruleActions
+   * @access protected
+   */
+  protected function getRuleActions() {
+    $actionParams = array(
+      'is_active' => 1,
+      'rule_id' => $this->ruleId);
+    $ruleActions = CRM_Civirules_BAO_RuleAction::getValues($actionParams);
+    foreach ($ruleActions as $ruleActionId => $ruleAction) {
+      $ruleActions[$ruleActionId]['label'] =
+        CRM_Civirules_BAO_Action::getActionLabelWithId($ruleAction['action_id']);
+      $ruleActions[$ruleActionId]['actions'] = $this->setRuleActionActions($ruleActionId);
+    }
+    return $ruleActions;
+  }
+
+  /**
+   * Function to set the actions for each rule condition
+   *
+   * @param int $ruleConditionId
+   * @return array
+   * @access protected
+   */
+  protected function setRuleConditionActions($ruleConditionId) {
+    $conditionActions = array();
+    $updateUrl = CRM_Utils_System::url('civicrm/civirule/form/rulecondition', 'action=update&id='.
+      $ruleConditionId);
+    $deleteUrl = CRM_Utils_System::url('civicrm/civirule/form/rulecondition', 'action=delete&id='.
+      $ruleConditionId);
+    $conditionActions[] = '<a class="action-item" title="Update" href="'.$updateUrl.'">Edit</a>';
+    $conditionActions[] = '<a class="action-item" title="Delete" href="'.$deleteUrl.'">Delete</a>';
+    return $conditionActions;
+  }
+
+  /**
+   * Function to set the html for the delete event action
+   *
+   * @param int $eventId
+   * @return string $deleteHtml
+   * @access protected
+   */
+  protected function setEventDeleteAction($eventId) {
+    $deleteUrl = CRM_Utils_System::url('civicrm/civirule/form/event', 'action=delete&id='.
+      $eventId);
+    $deleteHtml = '<a class="action-item" title="Delete" href="'.$deleteUrl.'">Delete</a>';
+    return $deleteHtml;
+  }
+
+  /**
+   * Function to set the actions for each rule action
+   *
+   * @param int $ruleActionId
+   * @return array
+   * @access protected
+   */
+  protected function setRuleActionActions($ruleActionId) {
+    $actionActions = array();
+    $updateUrl = CRM_Utils_System::url('civicrm/civirule/form/ruleaction', 'action=update&id='.
+      $ruleActionId);
+    $deleteUrl = CRM_Utils_System::url('civicrm/civirule/form/ruleaction', 'action=delete&id='.
+      $ruleActionId);
+    $actionActions[] = '<a class="action-item" title="Update" href="'.$updateUrl.'">Edit</a>';
+    $actionActions[] = '<a class="action-item" title="Delete" href="'.$deleteUrl.'">Delete</a>';
+    return $actionActions;
+  }
+
+  /**
+   * Function to save rule
+   *
+   * @param array $formValues
+   * @param int $userId
+   * @access protected
+   */
+  protected function saveRule($formValues, $userId) {
+    if ($this->_action == CRM_Core_Action::ADD) {
+      $ruleParams = array(
+        'created_date' => date('Ymd'),
+        'created_user_id' => $userId);
+    } else {
+      $ruleParams = array(
+        'modified_date' => date('Ymd'),
+        'modified_user_id' => $userId,
+        'id' => $formValues['id']);
+    }
+    $ruleParams['label'] = $formValues['rule_label'];
+    $ruleParams['name'] = CRM_Civirules_Utils::buildNameFromLabel($formValues['rule_label']);
+    $ruleParams['is_active'] = $formValues['rule_is_active'];
+    $savedRule = CRM_Civirules_BAO_Rule::add($ruleParams);
+    $this->ruleId = $savedRule['id'];
+  }
+
+  /**
+   * Function to link an event to a rule
+   *
+   * @param array $formValues
+   */
+  protected function saveRuleEvent($formValues) {
+    if (isset($formValues['rule_event_select'])) {
+      $ruleParams = array(
+        'id' => $this->ruleId,
+        'event_id' => $formValues['rule_event_select']
+      );
+      CRM_Civirules_BAO_Rule::add($ruleParams);
+    }
+  }
+}
diff --git a/api/v3/CiviRuleRule/Create.php b/api/v3/CiviRuleRule/Create.php
new file mode 100755
index 0000000..527f1ea
--- /dev/null
+++ b/api/v3/CiviRuleRule/Create.php
@@ -0,0 +1,37 @@
+<?php
+/**
+ * CiviRuleRule.Create API
+ *
+ * @param array $params
+ * @return array API result descriptor
+ * @see civicrm_api3_create_success
+ * @see civicrm_api3_create_error
+ * @throws API_Exception when label is empty and id is not set (label is required for create)
+ *
+ */
+function civicrm_api3_civi_rule_rule_create($params) {
+  if (!isset($params['id']) && empty($params['label'])) {
+    throw new API_Exception('Label can not be empty when adding a new CiviRule');
+  }
+  /*
+   * replace event_id when value is 0 to prevent restraint conflict
+   */
+  if (isset($params['event_id']) && $params['event_id'] == 0) {
+    $params['event_id'] = null;
+  }
+  /*
+   * set created or modified date and user_id
+   */
+  $session = CRM_Core_Session::singleton();
+  $userId = $session->get('userID');
+  if (isset($params['id'])) {
+    $params['modified_date'] = date('Ymd');
+    $params['modified_user_id'] = $userId;
+  } else {
+    $params['created_date'] = date('Ymd');
+    $params['created_user_id'] = $userId;
+  }
+  $returnValues = CRM_Civirules_BAO_Rule::add($params);
+  return civicrm_api3_create_success($returnValues, $params, 'CiviRuleRule', 'Create');
+}
+
diff --git a/api/v3/CiviRuleRule/Get.php b/api/v3/CiviRuleRule/Get.php
new file mode 100755
index 0000000..a8df8cc
--- /dev/null
+++ b/api/v3/CiviRuleRule/Get.php
@@ -0,0 +1,15 @@
+<?php
+/**
+ * CiviRuleRule.Get API
+ *
+ * @param array $params
+ * @return array API result descriptor
+ * @see civicrm_api3_create_success
+ * @see civicrm_api3_create_error
+ * @throws API_Exception
+ */
+function civicrm_api3_civi_rule_rule_get($params) {
+  $returnValues = CRM_Civirules_BAO_Rule::getValues($params);
+  return civicrm_api3_create_success($returnValues, $params, 'CiviRuleRule', 'Get');
+}
+
diff --git a/templates/CRM/Civirules/Form/Rule.tpl b/templates/CRM/Civirules/Form/Rule.tpl
index 6742558..63c5d6c 100755
--- a/templates/CRM/Civirules/Form/Rule.tpl
+++ b/templates/CRM/Civirules/Form/Rule.tpl
@@ -4,8 +4,10 @@
 
 {include file="CRM/Civirules/Form/RuleBlocks/RuleBlock.tpl"}
 {include file="CRM/Civirules/Form/RuleBlocks/EventBlock.tpl"}
-{include file="CRM/Civirules/Form/RuleBlocks/ConditionBlock.tpl"}
-{include file="CRM/Civirules/Form/RuleBlocks/ActionBlock.tpl"}
+{if $action ne 1}
+  {include file="CRM/Civirules/Form/RuleBlocks/ConditionBlock.tpl"}
+  {include file="CRM/Civirules/Form/RuleBlocks/ActionBlock.tpl"}
+{/if}
   
 <div class="crm-submit-buttons">
   {include file="CRM/common/formButtons.tpl" location="bottom"}
diff --git a/templates/CRM/Civirules/Form/RuleBlocks/ConditionBlock.tpl b/templates/CRM/Civirules/Form/RuleBlocks/ConditionBlock.tpl
index 5cdee31..4296b4f 100755
--- a/templates/CRM/Civirules/Form/RuleBlocks/ConditionBlock.tpl
+++ b/templates/CRM/Civirules/Form/RuleBlocks/ConditionBlock.tpl
@@ -36,21 +36,8 @@
       </table>
     </div>
   </div>
-  {if $action eq 1 or empty($ruleConditions)}
-    <div class="crm-submit-buttons">
-      <span class="crm-button crm-button-type-next crm-button_qf_Rule_next">
-        <input id="_qf_Rule_next-bottom" class="validate form-submit" type="submit" value="Add Condition" name="_qf_Rule_next">
-      </span>
-    </div>
-  {else}
-    <div class="crm-submit-buttons">
-      <span class="crm-button crm-button-type-next crm-button_qf_Rule_next">
-        <input id="_qf_Rule_next-bottom" class="validate form-submit" type="submit" value="Add Or" name="_qf_Rule_next">
-      </span>
-      <span class="crm-button crm-button-type-next crm-button_qf_Rule_next">
-        <input id="_qf_Rule_next-bottom" class="validate form-submit" type="submit" value="Add And" name="_qf_Rule_next">
-      </span>
-
-    </div>
-  {/if}
+  <div class="crm-submit-buttons">
+    <a class="add button" title="Add Condition" href="{$ruleConditionAddUrl}">
+      <span><div class="icon add-icon"></div>Add Condition</span></a>
+  </div>
 </div>
diff --git a/templates/CRM/Civirules/Form/RuleCondition.tpl b/templates/CRM/Civirules/Form/RuleCondition.tpl
new file mode 100755
index 0000000..4c61b4f
--- /dev/null
+++ b/templates/CRM/Civirules/Form/RuleCondition.tpl
@@ -0,0 +1,17 @@
+{* block for rule condition data *}
+<h3>{$ruleConditionHeader}</h3>
+<div class="crm-block crm-form-block crm-civirule-rule_condition-block">
+  <div class="crm-section">
+    <div class="label">{$form.rule_condition_link_select.label}</div>
+    <div class="content">{$form.rule_condition_link_select.html}</div>
+    <div class="clear"></div>
+  </div>
+  <div class="crm-section">
+    <div class="label">{$form.rule_condition_select.label}</div>
+    <div class="content">{$form.rule_condition_select.html}</div>
+    <div class="clear"></div>
+  </div>
+</div>
+<div class="crm-submit-buttons">
+  {include file="CRM/common/formButtons.tpl" location="bottom"}
+</div>
diff --git a/templates/CRM/Civirules/Page/Rule.tpl b/templates/CRM/Civirules/Page/Rule.tpl
index a6024e7..d4655f8 100755
--- a/templates/CRM/Civirules/Page/Rule.tpl
+++ b/templates/CRM/Civirules/Page/Rule.tpl
@@ -4,7 +4,7 @@
   </div>
   <div class="action-link">
     <a class="button new-option" href="{$add_url}">
-      <span><div class="icon add-icon"></div>{ts}Add CivRule{/ts}</span>
+      <span><div class="icon add-icon"></div>{ts}Add CiviRule{/ts}</span>
     </a>
   </div>
   <div id="civirule_wrapper" class="dataTables_wrapper">
@@ -47,7 +47,7 @@
   </div>
   <div class="action-link">
     <a class="button new-option" href="{$add_url}">
-      <span><div class="icon add-icon"></div>{ts}Add CivRule{/ts}</span>
+      <span><div class="icon add-icon"></div>{ts}Add CiviRule{/ts}</span>
     </a>
   </div>
 </div>
diff --git a/xml/Menu/civirules.xml b/xml/Menu/civirules.xml
index d1baa07..7a94464 100755
--- a/xml/Menu/civirules.xml
+++ b/xml/Menu/civirules.xml
@@ -12,4 +12,10 @@
     <title>Rule</title>
     <access_arguments>access CiviCRM</access_arguments>
   </item>
+  <item>
+    <path>civicrm/civirule/form/rule_condition</path>
+    <page_callback>CRM_Civirules_Form_RuleCondition</page_callback>
+    <title>RuleCondition</title>
+    <access_arguments>access CiviCRM</access_arguments>
+  </item>
 </menu>
-- 
GitLab