webform_civirules_trigger.inc 1.95 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
<?php

class webform_civirules_trigger {

  private static $singleton;

  private $submission;

  private function __construct() {

  }

  /**
   * @return \webform_civirules_trigger
   */
  public static function getSingleton() {
    if (!self::$singleton) {
      self::$singleton = new webform_civirules_trigger();
    }
    return self::$singleton;
  }

  /**
   * @return \webform_civirules_trigger
   */
  public function setSubmission($submission) {
    $this->submission = $submission;
    return $this;
  }

  public function trigger() {
    if (!$this->submission || !$this->submission->sid || !$this->submission->nid) {
      return;
    }

    $db = db_query('SELECT * FROM {webform_civicrm_submissions_civirules_trigger} WHERE sid = :sid', array(':sid' => $this->submission->sid));
    if (($row = $db->fetchAssoc()) && $row->trigger_fired) {
      // This submission did already fire a civirules trigger.
      return;
    }

    $db = db_query('SELECT * FROM {webform_civicrm_submissions} WHERE sid = :sid', array(':sid' => $this->submission->sid));
    if ($row = $db->fetchAssoc()) {
      // First update webform_civicrm_submissions_civirules_trigger so that we do not trigger again on this submission.
      $webform_civicrm_submissions_civirules_trigger = array(
        'sid' => $this->submission->sid,
        'trigger_fired' => 1,
      );
      drupal_write_record('webform_civicrm_submissions_civirules_trigger',$webform_civicrm_submissions_civirules_trigger);

      $data = unserialize($row['civicrm_data']);
      $contacts = array();
      if ($row['contact_id']) {
        foreach (explode('-', trim($row['contact_id'], '-')) as $c => $cid) {
          $contacts[$c] = $cid;
        }
        foreach($contacts as $c => $cid) {
          if ($cid) {
            $trigger = new CRM_WebformCivirules_Trigger();
            $trigger->triggerTrigger($cid, $c, $data, $contacts, $this->submission->sid, $this->submission->nid);
          }
        }
      }
    }
  }

}