function __construct()
 {
     // don’t display the ‘Add these Contacts to Group’ button
     $this->_add2groupSupported = FALSE;
     $dsn = defined('CIVICRM_LOGGING_DSN') ? DB::parseDSN(CIVICRM_LOGGING_DSN) : DB::parseDSN(CIVICRM_DSN);
     $this->db = $dsn['database'];
     $this->log_conn_id = CRM_Utils_Request::retrieve('log_conn_id', 'Integer', CRM_Core_DAO::$_nullObject);
     $this->log_date = CRM_Utils_Request::retrieve('log_date', 'String', CRM_Core_DAO::$_nullObject);
     $this->cid = CRM_Utils_Request::retrieve('cid', 'Integer', CRM_Core_DAO::$_nullObject);
     $this->raw = CRM_Utils_Request::retrieve('raw', 'Boolean', CRM_Core_DAO::$_nullObject);
     parent::__construct();
     CRM_Utils_System::resetBreadCrumb();
     $breadcrumb = array(array('title' => ts('Home'), 'url' => CRM_Utils_System::url()), array('title' => ts('CiviCRM'), 'url' => CRM_Utils_System::url('civicrm', 'reset=1')), array('title' => ts('View Contact'), 'url' => CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->cid}")), array('title' => ts('Search Results'), 'url' => CRM_Utils_System::url('civicrm/contact/search', "force=1")));
     CRM_Utils_System::appendBreadCrumb($breadcrumb);
     if (CRM_Utils_Request::retrieve('revert', 'Boolean', CRM_Core_DAO::$_nullObject)) {
         $reverter = new CRM_Logging_Reverter($this->log_conn_id, $this->log_date);
         $reverter->revert($this->tables);
         CRM_Core_Session::setStatus(ts('The changes have been reverted.'));
         if ($this->cid) {
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view', "reset=1&selectedChild=log&cid={$this->cid}", FALSE, NULL, FALSE));
         } else {
             CRM_Utils_System::redirect(CRM_Report_Utils_Report::getNextUrl($this->summary, 'reset=1', FALSE, TRUE));
         }
     }
     // make sure the report works even without the params
     if (!$this->log_conn_id or !$this->log_date) {
         $dao = new CRM_Core_DAO();
         $dao->query("SELECT log_conn_id, log_date FROM `{$this->db}`.log_{$this->tables[0]} WHERE log_action = 'Update' ORDER BY log_date DESC LIMIT 1");
         $dao->fetch();
         $this->log_conn_id = $dao->log_conn_id;
         $this->log_date = $dao->log_date;
     }
     $this->_columnHeaders = array('field' => array('title' => ts('Field')), 'from' => array('title' => ts('Changed From')), 'to' => array('title' => ts('Changed To')));
 }
示例#2
0
 public function buildQuickForm()
 {
     $config = CRM_Core_Config::singleton();
     global $tsLocale;
     $this->_locales = array_keys($config->languageLimit);
     // get the part of the database we want to edit and validate it
     $table = CRM_Utils_Request::retrieve('table', 'String', $this);
     $field = CRM_Utils_Request::retrieve('field', 'String', $this);
     $id = CRM_Utils_Request::retrieve('id', 'Int', $this);
     $this->_structure = CRM_Core_I18n_SchemaStructure::columns();
     if (!isset($this->_structure[$table][$field])) {
         CRM_Core_Error::fatal("{$table}.{$field} is not internationalized.");
     }
     $this->addElement('hidden', 'table', $table);
     $this->addElement('hidden', 'field', $field);
     $this->addElement('hidden', 'id', $id);
     $cols = array();
     foreach ($this->_locales as $locale) {
         $cols[] = "{$field}_{$locale} {$locale}";
     }
     $query = 'SELECT ' . implode(', ', $cols) . " FROM {$table} WHERE id = {$id}";
     $dao = new CRM_Core_DAO();
     $dao->query($query, FALSE);
     $dao->fetch();
     // get html type and attributes for this field
     $widgets = CRM_Core_I18n_SchemaStructure::widgets();
     $widget = $widgets[$table][$field];
     // attributes
     $attributes = array('class' => '');
     if (isset($widget['rows'])) {
         $attributes['rows'] = $widget['rows'];
     }
     if (isset($widget['cols'])) {
         $attributes['cols'] = $widget['cols'];
     }
     $required = !empty($widget['required']);
     if ($widget['type'] == 'RichTextEditor') {
         $widget['type'] = 'wysiwyg';
         $attributes['class'] .= ' collapsed';
     }
     $languages = CRM_Core_I18n::languages(TRUE);
     foreach ($this->_locales as $locale) {
         $attr = $attributes;
         $name = "{$field}_{$locale}";
         if ($locale == $tsLocale) {
             $attr['class'] .= ' default-lang';
         }
         $this->add($widget['type'], $name, $languages[$locale], $attr, $required);
         $this->_defaults[$name] = $dao->{$locale};
     }
     $this->addDefaultButtons(ts('Save'), 'next', NULL);
     CRM_Utils_System::setTitle(ts('Languages'));
     $this->assign('locales', $this->_locales);
     $this->assign('field', $field);
 }
 /**
  * Function to set variables up before form is built
  *
  * @return void
  * @access public
  */
 public function preProcess()
 {
     $values = $ids = array();
     $params = array('id' => $this->get('id'));
     CRM_Pledge_BAO_Pledge::getValues($params, $values, $ids);
     $values['frequencyUnit'] = ts('%1(s)', array(1 => $values['frequency_unit']));
     if (isset($values["honor_contact_id"]) && $values["honor_contact_id"]) {
         $sql = "SELECT display_name FROM civicrm_contact WHERE id = " . $values["honor_contact_id"];
         $dao = new CRM_Core_DAO();
         $dao->query($sql);
         if ($dao->fetch()) {
             $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$values['honor_contact_id']}");
             $values["honor_display"] = "<A href = {$url}>" . $dao->display_name . "</A>";
         }
         $honor = CRM_Core_PseudoConstant::get('CRM_Pledge_DAO_Pledge', 'honor_type_id');
         $values['honor_type'] = $honor[$values['honor_type_id']];
     }
     //handle custom data.
     $groupTree = CRM_Core_BAO_CustomGroup::getTree('Pledge', $this, $params['id']);
     CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree);
     if (!empty($values['contribution_page_id'])) {
         $values['contribution_page'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $values['contribution_page_id'], 'title');
     }
     $values['financial_type'] = CRM_Utils_Array::value($values['financial_type_id'], CRM_Contribute_PseudoConstant::financialType());
     if ($values['status_id']) {
         $values['pledge_status'] = CRM_Utils_Array::value($values['status_id'], CRM_Contribute_PseudoConstant::contributionStatus());
     }
     $url = CRM_Utils_System::url('civicrm/contact/view/pledge', "action=view&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home");
     $recentOther = array();
     if (CRM_Core_Permission::checkActionPermission('CiviPledge', CRM_Core_Action::UPDATE)) {
         $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/pledge', "action=update&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home");
     }
     if (CRM_Core_Permission::checkActionPermission('CiviPledge', CRM_Core_Action::DELETE)) {
         $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/pledge', "action=delete&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home");
     }
     $displayName = CRM_Contact_BAO_Contact::displayName($values['contact_id']);
     $this->assign('displayName', $displayName);
     $title = $displayName . ' - (' . ts('Pledged') . ' ' . CRM_Utils_Money::format($values['pledge_amount']) . ' - ' . $values['financial_type'] . ')';
     // add Pledge to Recent Items
     CRM_Utils_Recent::add($title, $url, $values['id'], 'Pledge', $values['contact_id'], NULL, $recentOther);
     // Check if this is default domain contact CRM-10482
     if (CRM_Contact_BAO_Contact::checkDomainContact($values['contact_id'])) {
         $displayName .= ' (' . ts('default organization') . ')';
     }
     // omitting contactImage from title for now since the summary overlay css doesn't work outside of our crm-container
     CRM_Utils_System::setTitle(ts('View Pledge by') . ' ' . $displayName);
     //do check for campaigns
     if ($campaignId = CRM_Utils_Array::value('campaign_id', $values)) {
         $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId);
         $values['campaign'] = $campaigns[$campaignId];
     }
     $this->assign($values);
 }
 function setDefaultValues()
 {
     $defaults = parent::setDefaultValues();
     if (!CRM_Utils_Array::value('weight', $defaults)) {
         $query = "SELECT max( `weight` ) as weight FROM `civicrm_booking_resource_config_set`";
         $dao = new CRM_Core_DAO();
         $dao->query($query);
         $dao->fetch();
         $defaults['weight'] = $dao->weight + 1;
     }
     return $defaults;
 }
示例#5
0
 /**  
  * Function to set variables up before form is built  
  *                                                            
  * @return void  
  * @access public  
  */
 public function preProcess()
 {
     require_once 'CRM/Pledge/BAO/Pledge.php';
     $values = $ids = array();
     $params = array('id' => $this->get('id'));
     CRM_Pledge_BAO_Pledge::getValues($params, $values, $ids);
     $values['frequencyUnit'] = ts('%1(s)', array(1 => $values['frequency_unit']));
     if (isset($values["honor_contact_id"]) && $values["honor_contact_id"]) {
         $sql = "SELECT display_name FROM civicrm_contact WHERE id = " . $values["honor_contact_id"];
         $dao = new CRM_Core_DAO();
         $dao->query($sql);
         if ($dao->fetch()) {
             $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$values['honor_contact_id']}");
             $values["honor_display"] = "<A href = {$url}>" . $dao->display_name . "</A>";
         }
         $honor = CRM_Core_PseudoConstant::honor();
         $values['honor_type'] = $honor[$values['honor_type_id']];
     }
     //handle custom data.
     $groupTree =& CRM_Core_BAO_CustomGroup::getTree('Pledge', $this, $params['id']);
     CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree);
     if (CRM_Utils_Array::value('contribution_page_id', $values)) {
         $values['contribution_page'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $values['contribution_page_id'], 'title');
     }
     $values['contribution_type'] = CRM_Utils_Array::value($values['contribution_type_id'], CRM_Contribute_PseudoConstant::contributionType());
     if ($values['status_id']) {
         $values['pledge_status'] = CRM_Utils_Array::value($values['status_id'], CRM_Contribute_PseudoConstant::contributionStatus());
     }
     require_once 'CRM/Utils/Recent.php';
     require_once 'CRM/Contact/BAO/Contact.php';
     $url = CRM_Utils_System::url('civicrm/contact/view/pledge', "action=view&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home");
     $recentOther = array();
     if (CRM_Core_Permission::checkActionPermission('CiviPledge', CRM_Core_Action::UPDATE)) {
         $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/pledge', "action=update&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home");
     }
     if (CRM_Core_Permission::checkActionPermission('CiviPledge', CRM_Core_Action::DELETE)) {
         $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/pledge', "action=delete&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home");
     }
     require_once 'CRM/Utils/Money.php';
     $displayName = CRM_Contact_BAO_Contact::displayName($values['contact_id']);
     $this->assign('displayName', $displayName);
     $title = $displayName . ' - (' . ts('Pledged') . ' ' . CRM_Utils_Money::format($values['pledge_amount']) . ' - ' . $values['contribution_type'] . ')';
     // add Pledge to Recent Items
     CRM_Utils_Recent::add($title, $url, $values['id'], 'Pledge', $values['contact_id'], null, $recentOther);
     $this->assign($values);
 }
 function __construct()
 {
     $this->_add2groupSupported = false;
     // don’t display the ‘Add these Contacts to Group’ button
     $dsn = defined('CIVICRM_LOGGING_DSN') ? DB::parseDSN(CIVICRM_LOGGING_DSN) : DB::parseDSN(CIVICRM_DSN);
     $this->loggingDB = $dsn['database'];
     $this->log_conn_id = CRM_Utils_Request::retrieve('log_conn_id', 'Integer', CRM_Core_DAO::$_nullObject);
     $this->log_date = CRM_Utils_Request::retrieve('log_date', 'String', CRM_Core_DAO::$_nullObject);
     // make sure the report works even without the params
     if (!$this->log_conn_id or !$this->log_date) {
         $dao = new CRM_Core_DAO();
         $dao->query("SELECT log_conn_id, log_date FROM `{$this->loggingDB}`.log_civicrm_contact WHERE log_action = 'Update' ORDER BY log_date DESC LIMIT 1");
         $dao->fetch();
         $this->log_conn_id = $dao->log_conn_id;
         $this->log_date = $dao->log_date;
     }
     $this->_columnHeaders = array('field' => array('title' => ts('Field')), 'from' => array('title' => ts('Changed From')), 'to' => array('title' => ts('Changed To')));
     parent::__construct();
 }
 function buildQuickForm()
 {
     $config = CRM_Core_Config::singleton();
     $this->_locales = array_keys($config->languageLimit);
     // get the part of the database we want to edit and validate it
     $table = CRM_Utils_Request::retrieve('table', 'String', $this);
     $field = CRM_Utils_Request::retrieve('field', 'String', $this);
     $id = CRM_Utils_Request::retrieve('id', 'Int', $this);
     $this->_structure = CRM_Core_I18n_SchemaStructure::columns();
     if (!isset($this->_structure[$table][$field])) {
         CRM_Core_Error::fatal("{$table}.{$field} is not internationalized.");
     }
     $this->addElement('hidden', 'table', $table);
     $this->addElement('hidden', 'field', $field);
     $this->addElement('hidden', 'id', $id);
     $cols = array();
     foreach ($this->_locales as $locale) {
         $cols[] = "{$field}_{$locale} {$locale}";
     }
     $query = 'SELECT ' . implode(', ', $cols) . " FROM {$table} WHERE id = {$id}";
     $dao = new CRM_Core_DAO();
     $dao->query($query, FALSE);
     $dao->fetch();
     // we want TEXTAREAs for long fields and INPUTs for short ones
     $this->_structure[$table][$field] == 'text' ? $type = 'textarea' : ($type = 'text');
     $languages = CRM_Core_I18n::languages(TRUE);
     foreach ($this->_locales as $locale) {
         $this->addElement($type, "{$field}_{$locale}", $languages[$locale], array('cols' => 60, 'rows' => 3));
         $this->_defaults["{$field}_{$locale}"] = $dao->{$locale};
     }
     $this->addButtons(array(array('type' => 'next', 'name' => ts('Save'), 'isDefault' => TRUE)));
     global $tsLocale;
     $this->assign('tsLocale', $tsLocale);
     $this->assign('locales', $this->_locales);
     $this->assign('field', $field);
     $this->assign('context', CRM_Utils_Request::retrieve('context', 'String', $this));
 }
示例#8
0
 /**
  * @param CRM_Core_DAO $dao
  * @param bool $flip
  * @param bool $grouping
  * @param bool $localize
  * @param string $valueColumnName
  *
  * @return array
  */
 public static function &valuesCommon($dao, $flip = FALSE, $grouping = FALSE, $localize = FALSE, $valueColumnName = 'label')
 {
     self::$_values = array();
     while ($dao->fetch()) {
         if ($flip) {
             if ($grouping) {
                 self::$_values[$dao->value] = $dao->grouping;
             } else {
                 self::$_values[$dao->{$valueColumnName}] = $dao->value;
             }
         } else {
             if ($grouping) {
                 self::$_values[$dao->{$valueColumnName}] = $dao->grouping;
             } else {
                 self::$_values[$dao->value] = $dao->{$valueColumnName};
             }
         }
     }
     if ($localize) {
         $i18n = CRM_Core_I18n::singleton();
         $i18n->localizeArray(self::$_values);
     }
     return self::$_values;
 }
 static function getZipCodeInfo()
 {
     $stateID = mt_rand(1000, 5132);
     $offset = mt_rand(1, 4132);
     $query = "SELECT id, country_id from civicrm_state_province LIMIT {$offset}, 1";
     $dao = new CRM_Core_DAO();
     $dao->query($query);
     while ($dao->fetch()) {
         return array($dao->country_id, $dao->id);
     }
     return array();
 }
示例#10
0
 /**
  * Get row count for the event selector.
  *
  * @param int $mailing_id
  *   ID of the mailing.
  * @param int $job_id
  *   Optional ID of a job to filter on.
  * @param bool $is_distinct
  *   Group by queue ID?.
  *
  * @param string $org_unsubscribe
  *
  * @param string $toDate
  *
  * @return int
  *   Number of rows in result set
  */
 public static function getTotalCount($mailing_id, $job_id = NULL, $is_distinct = FALSE, $org_unsubscribe = NULL, $toDate = NULL)
 {
     $dao = new CRM_Core_DAO();
     $unsub = self::$_tableName;
     $queueObject = new CRM_Mailing_Event_BAO_Queue();
     $queue = $queueObject->getTableName();
     $mailingObject = new CRM_Mailing_BAO_Mailing();
     $mailing = $mailingObject->getTableName();
     $jobObject = new CRM_Mailing_BAO_MailingJob();
     $job = $jobObject->getTableName();
     $query = "\n            SELECT      COUNT({$unsub}.id) as unsubs\n            FROM        {$unsub}\n            INNER JOIN  {$queue}\n                    ON  {$unsub}.event_queue_id = {$queue}.id\n            INNER JOIN  {$job}\n                    ON  {$queue}.job_id = {$job}.id\n            INNER JOIN  {$mailing}\n                    ON  {$job}.mailing_id = {$mailing}.id\n                    AND {$job}.is_test = 0\n            WHERE       {$mailing}.id = " . CRM_Utils_Type::escape($mailing_id, 'Integer');
     if (!empty($toDate)) {
         $query .= " AND {$unsub}.time_stamp <= {$toDate}";
     }
     if (!empty($job_id)) {
         $query .= " AND {$job}.id = " . CRM_Utils_Type::escape($job_id, 'Integer');
     }
     if ($org_unsubscribe !== NULL) {
         $query .= " AND {$unsub}.org_unsubscribe = " . ($org_unsubscribe ? 0 : 1);
     }
     if ($is_distinct) {
         $query .= " GROUP BY {$queue}.id ";
     }
     $dao->query($query);
     $dao->fetch();
     if ($is_distinct) {
         return $dao->N;
     } else {
         return $dao->unsubs ? $dao->unsubs : 0;
     }
 }
示例#11
0
 /**
  * @return array
  */
 public function getZipCodeInfo()
 {
     if (!$this->stateMap) {
         $query = 'SELECT id, name, abbreviation from civicrm_state_province where country_id = 1228';
         $dao = new CRM_Core_DAO();
         $dao->query($query);
         $this->stateMap = array();
         while ($dao->fetch()) {
             $this->stateMap[$dao->abbreviation] = $dao->id;
             $this->states[$dao->id] = $dao->name;
         }
         $dao->free();
     }
     $offset = mt_rand(1, 43000);
     $query = "SELECT city, state, zip, latitude, longitude FROM zipcodes LIMIT {$offset}, 1";
     $dao = new CRM_Core_DAO();
     $dao->query($query);
     while ($dao->fetch()) {
         if ($this->stateMap[$dao->state]) {
             $stateID = $this->stateMap[$dao->state];
         } else {
             $stateID = 1004;
         }
         $zip = str_pad($dao->zip, 5, '0', STR_PAD_LEFT);
         return array(1228, $stateID, $dao->city, $zip, $dao->latitude, $dao->longitude);
     }
 }
示例#12
0
 /**
  * function to get the information to map a event
  *
  * @param  array  $ids    the list of ids for which we want map info
  *
  * @return null|string     title of the event
  * @static
  * @access public
  */
 static function &getMapInfo(&$id)
 {
     $sql = "\nSELECT \n   civicrm_event.id AS event_id, \n   civicrm_event.title AS display_name, \n   civicrm_address.street_address AS street_address, \n   civicrm_address.city AS city, \n   civicrm_address.postal_code AS postal_code, \n   civicrm_address.postal_code_suffix AS postal_code_suffix, \n   civicrm_address.geo_code_1 AS latitude, \n   civicrm_address.geo_code_2 AS longitude, \n   civicrm_state_province.abbreviation AS state, \n   civicrm_country.name AS country, \n   civicrm_location_type.name AS location_type\nFROM \n   civicrm_event\n   LEFT JOIN civicrm_loc_block ON ( civicrm_event.loc_block_id = civicrm_loc_block.id )\n   LEFT JOIN civicrm_address ON ( civicrm_loc_block.address_id = civicrm_address.id )\n   LEFT JOIN civicrm_state_province ON ( civicrm_address.state_province_id = civicrm_state_province.id )\n   LEFT JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id\n   LEFT JOIN civicrm_location_type ON ( civicrm_location_type.id = civicrm_address.location_type_id )\nWHERE civicrm_address.geo_code_1 IS NOT NULL \n  AND civicrm_address.geo_code_2 IS NOT NULL \n  AND civicrm_event.id = " . CRM_Utils_Type::escape($id, 'Integer');
     $dao = new CRM_Core_DAO();
     $dao->query($sql);
     $locations = array();
     $config = CRM_Core_Config::singleton();
     while ($dao->fetch()) {
         $location = array();
         $location['displayName'] = addslashes($dao->display_name);
         $location['lat'] = $dao->latitude;
         $location['marker_class'] = 'Event';
         $location['lng'] = $dao->longitude;
         $address = '';
         CRM_Utils_String::append($address, '<br />', array($dao->street_address, $dao->city));
         CRM_Utils_String::append($address, ', ', array($dao->state, $dao->postal_code));
         CRM_Utils_String::append($address, '<br /> ', array($dao->country));
         $location['address'] = addslashes($address);
         $location['url'] = CRM_Utils_System::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id);
         $location['location_type'] = $dao->location_type;
         $eventImage = '<img src="' . $config->resourceBase . 'i/contact_org.gif" alt="Organization " height="20" width="15" />';
         $location['image'] = $eventImage;
         $location['displayAddress'] = str_replace('<br />', ', ', $address);
         $locations[] = $location;
     }
     return $locations;
 }
示例#13
0
 /**
  * Get the display name and image of a contact.
  *
  * @param int $id
  *   The contactId.
  *
  * @param bool $includeTypeInReturnParameters
  *   Should type be part of the returned array?
  *
  * @return array
  *   the displayName and contactImage for this contact
  */
 public static function getDisplayAndImage($id, $includeTypeInReturnParameters = FALSE)
 {
     //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
     $sql = "\nSELECT    civicrm_contact.*,\n          civicrm_email.email          as email\nFROM      civicrm_contact\nLEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id\n     AND  civicrm_email.is_primary = 1\nWHERE     civicrm_contact.id = " . CRM_Utils_Type::escape($id, 'Integer');
     $dao = new CRM_Core_DAO();
     $dao->query($sql);
     if ($dao->fetch()) {
         $image = CRM_Contact_BAO_Contact_Utils::getImage($dao->contact_sub_type ? $dao->contact_sub_type : $dao->contact_type, FALSE, $id);
         $imageUrl = CRM_Contact_BAO_Contact_Utils::getImage($dao->contact_sub_type ? $dao->contact_sub_type : $dao->contact_type, TRUE, $id);
         // use email if display_name is empty
         if (empty($dao->display_name)) {
             $displayName = $dao->email;
         } else {
             $displayName = $dao->display_name;
         }
         CRM_Utils_Hook::alterDisplayName($displayName, $id, $dao);
         return $includeTypeInReturnParameters ? array($displayName, $image, $dao->contact_type, $dao->contact_sub_type, $imageUrl) : array($displayName, $image, $imageUrl);
     }
     return NULL;
 }
 /**
  * Class constructor
  *
  * @access private
  */
 function __construct()
 {
     global $civicrm_root;
     $config = CRM_Core_Config::singleton();
     $localfile = $civicrm_root . DIRECTORY_SEPARATOR . self::LOCALFILE_NAME;
     $cachefile = $config->uploadDir . self::CACHEFILE_NAME;
     if ($config->versionCheck && file_exists($localfile)) {
         require_once $localfile;
         if (function_exists('civicrmVersion')) {
             $info = civicrmVersion();
             $this->localVersion = $info['version'];
         }
         $expiryTime = time() - self::CACHEFILE_EXPIRE;
         // if there's a cachefile and it's not stale use it to
         // read the latestVersion, else read it from the Internet
         if (file_exists($cachefile) and filemtime($cachefile) > $expiryTime) {
             $this->latestVersion = file_get_contents($cachefile);
         } else {
             // we have to set the error handling to a dummy function, otherwise
             // if the URL is not working (e.g., due to our server being down)
             // the users would be presented with an unsuppressable warning
             ini_set('default_socket_timeout', self::CHECK_TIMEOUT);
             set_error_handler(array('CRM_Utils_VersionCheck', 'downloadError'));
             $hash = md5($config->userFrameworkBaseURL);
             $url = self::LATEST_VERSION_AT . "?version={$this->localVersion}&uf={$config->userFramework}&hash={$hash}&lang={$config->lcMessages}&ufv={$config->userFrameworkVersion}";
             // add PHP and MySQL versions
             $dao = new CRM_Core_DAO();
             $dao->query('SELECT VERSION() AS version');
             $dao->fetch();
             $url .= '&MySQL=' . $dao->version . '&PHP=' . phpversion();
             $tables = array('CRM_Activity_DAO_Activity' => 'is_test = 0', 'CRM_Case_DAO_Case' => NULL, 'CRM_Contact_DAO_Contact' => NULL, 'CRM_Contact_DAO_Relationship' => NULL, 'CRM_Contribute_DAO_Contribution' => 'is_test = 0', 'CRM_Contribute_DAO_ContributionPage' => 'is_active = 1', 'CRM_Contribute_DAO_ContributionProduct' => NULL, 'CRM_Contribute_DAO_Widget' => 'is_active = 1', 'CRM_Core_DAO_Discount' => NULL, 'CRM_Price_DAO_SetEntity' => NULL, 'CRM_Core_DAO_UFGroup' => 'is_active = 1', 'CRM_Event_DAO_Event' => 'is_active = 1', 'CRM_Event_DAO_Participant' => 'is_test = 0', 'CRM_Friend_DAO_Friend' => 'is_active = 1', 'CRM_Grant_DAO_Grant' => NULL, 'CRM_Mailing_DAO_Mailing' => 'is_completed = 1', 'CRM_Member_DAO_Membership' => 'is_test = 0', 'CRM_Member_DAO_MembershipBlock' => 'is_active = 1', 'CRM_Pledge_DAO_Pledge' => 'is_test = 0', 'CRM_Pledge_DAO_PledgeBlock' => NULL);
             // add &key=count pairs to $url, where key is the last part of the DAO
             foreach ($tables as $daoName => $where) {
                 require_once str_replace('_', '/', $daoName) . '.php';
                 eval("\$dao = new {$daoName};");
                 if ($where) {
                     $dao->whereAdd($where);
                 }
                 $url .= '&' . array_pop(explode('_', $daoName)) . "={$dao->count()}";
             }
             // get active payment processor types
             $dao = new CRM_Core_DAO_PaymentProcessor();
             $dao->is_active = 1;
             $dao->find();
             $ppTypes = array();
             while ($dao->fetch()) {
                 $ppTypes[] = $dao->payment_processor_type;
             }
             // add the .-separated list of the processor types (urlencoded just in case)
             $url .= '&PPTypes=' . urlencode(implode('.', array_unique($ppTypes)));
             // get the latest version using the stats-carrying $url
             $this->latestVersion = file_get_contents($url);
             ini_restore('default_socket_timeout');
             restore_error_handler();
             if (!preg_match('/^\\d+\\.\\d+\\.\\d+$/', $this->latestVersion)) {
                 $this->latestVersion = NULL;
             }
             if (!$this->latestVersion) {
                 return;
             }
             $fp = @fopen($cachefile, 'w');
             if (!$fp) {
                 $message = ts('Do not have permission to write to file: %1', array(1 => $cachefile));
                 CRM_Core_Session::setStatus($message);
                 return;
             }
             fwrite($fp, $this->latestVersion);
             fclose($fp);
         }
     }
 }
示例#15
0
文件: Schema.php 项目: ksecor/civicrm
 /**
  * Rebuild multilingual indices, views and triggers (useful for upgrades)
  *
  * @param $locales array  locales to be rebuilt
  * @param $version string version of schema structure to use
  * @return void
  */
 static function rebuildMultilingualSchema($locales, $version = null)
 {
     if ($version) {
         // fetch all the SchemaStructure versions we ship and sort by version
         $schemas = array();
         foreach (scandir(dirname(__FILE__)) as $file) {
             $matches = array();
             if (preg_match('/^SchemaStructure_([0-9a-z_]+)\\.php$/', $file, $matches)) {
                 $schemas[] = str_replace('_', '.', $matches[1]);
             }
         }
         usort($schemas, 'version_compare');
         // find the latest schema structure older than (or equal to) $version
         do {
             $latest = array_pop($schemas);
         } while (version_compare($latest, $version, '>'));
         $latest = str_replace('.', '_', $latest);
         $class = "CRM_Core_I18n_SchemaStructure_{$latest}";
         require_once "CRM/Core/I18n/SchemaStructure_{$latest}.php";
     } else {
         $class = 'CRM_Core_I18n_SchemaStructure';
         require_once 'CRM/Core/I18n/SchemaStructure.php';
     }
     eval("\$indices =& {$class}::indices();");
     eval("\$tables  =& {$class}::tables();");
     $queries = array();
     $dao = new CRM_Core_DAO();
     // get all of the already existing indices
     $existing = array();
     foreach (array_keys($indices) as $table) {
         $existing[$table] = array();
         $dao->query("SHOW INDEX FROM {$table}", false);
         while ($dao->fetch()) {
             if (preg_match('/_[a-z][a-z]_[A-Z][A-Z]$/', $dao->Key_name)) {
                 $existing[$table][] = $dao->Key_name;
             }
         }
     }
     // from all of the CREATE INDEX queries fetch the ones creating missing indices
     foreach ($locales as $locale) {
         foreach (array_keys($indices) as $table) {
             $allQueries = self::createIndexQueries($locale, $table, $class);
             foreach ($allQueries as $name => $query) {
                 if (!in_array("{$name}_{$locale}", $existing[$table])) {
                     $queries[] = $query;
                 }
             }
         }
     }
     // rebuild views
     foreach ($locales as $locale) {
         foreach ($tables as $table) {
             $queries[] = self::createViewQuery($locale, $table, $dao, $class);
         }
     }
     // rebuild triggers
     $last = array_pop($locales);
     $queries = array_merge($queries, self::createTriggerQueries($locales, $last, $class));
     foreach ($queries as $query) {
         $dao->query($query, false);
     }
 }
示例#16
0
 /**
  * Browse all rule groups
  *  
  * @return void
  * @access public
  */
 function run()
 {
     $gid = CRM_Utils_Request::retrieve('gid', 'Positive', $this, false, 0);
     $action = CRM_Utils_Request::retrieve('action', 'String', $this, false, 0);
     $context = CRM_Utils_Request::retrieve('context', 'String', $this);
     $session = CRM_Core_Session::singleton();
     $contactIds = $session->get('selectedSearchContactIds');
     if ($context == 'search' || !empty($contactIds)) {
         $context = 'search';
         $this->assign('backURL', $session->readUserContext());
     }
     if ($action & CRM_Core_Action::UPDATE || $action & CRM_Core_Action::BROWSE) {
         $cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this, false, 0);
         $rgid = CRM_Utils_Request::retrieve('rgid', 'Positive', $this, false, 0);
         $this->action = CRM_Core_Action::UPDATE;
         if ($gid) {
             $foundDupes = $this->get("dedupe_dupes_{$gid}");
             if (!$foundDupes) {
                 $foundDupes = CRM_Dedupe_Finder::dupesInGroup($rgid, $gid);
             }
             $this->set("dedupe_dupes_{$gid}", $foundDupes);
         } else {
             if (!empty($contactIds)) {
                 $foundDupes = $this->get("search_dedupe_dupes_{$gid}");
                 if (!$foundDupes) {
                     $foundDupes = CRM_Dedupe_Finder::dupes($rgid, $contactIds);
                 }
                 $this->get("search_dedupe_dupes_{$gid}", $foundDupes);
             } else {
                 $foundDupes = $this->get("dedupe_dupes");
                 if (!$foundDupes) {
                     $foundDupes = CRM_Dedupe_Finder::dupes($rgid);
                 }
                 $this->set("dedupe_dupes", $foundDupes);
             }
         }
         if (!$foundDupes) {
             $ruleGroup = new CRM_Dedupe_BAO_RuleGroup();
             $ruleGroup->id = $rgid;
             $ruleGroup->find(true);
             $session = CRM_Core_Session::singleton();
             $session->setStatus("No possible duplicates were found using {$ruleGroup->name} rule.");
             $url = CRM_Utils_System::url('civicrm/contact/deduperules', "reset=1");
             if ($context == 'search') {
                 $url = $session->readUserContext();
             }
             CRM_Utils_System::redirect($url);
         } else {
             $cids = array();
             foreach ($foundDupes as $dupe) {
                 $cids[$dupe[0]] = 1;
                 $cids[$dupe[1]] = 1;
             }
             $cidString = implode(', ', array_keys($cids));
             $sql = "SELECT id, display_name FROM civicrm_contact WHERE id IN ({$cidString}) ORDER BY sort_name";
             $dao = new CRM_Core_DAO();
             $dao->query($sql);
             $displayNames = array();
             while ($dao->fetch()) {
                 $displayNames[$dao->id] = $dao->display_name;
             }
             // FIXME: sort the contacts; $displayName
             // is already sort_name-sorted, so use that
             // (also, consider sorting by dupe count first)
             // lobo - change the sort to by threshold value
             // so the more likely dupes are sorted first
             $session = CRM_Core_Session::singleton();
             $userId = $session->get('userID');
             $mainContacts = array();
             foreach ($foundDupes as $dupes) {
                 $srcID = $dupes[0];
                 $dstID = $dupes[1];
                 if ($dstID == $userId) {
                     $srcID = $dupes[1];
                     $dstID = $dupes[0];
                 }
                 $canMerge = CRM_Contact_BAO_Contact_Permission::allow($dstID, CRM_Core_Permission::EDIT) && CRM_Contact_BAO_Contact_Permission::allow($srcID, CRM_Core_Permission::EDIT);
                 $mainContacts[] = array('srcID' => $srcID, 'srcName' => $displayNames[$srcID], 'dstID' => $dstID, 'dstName' => $displayNames[$dstID], 'weight' => $dupes[2], 'canMerge' => $canMerge);
             }
             if ($cid) {
                 $this->_cid = $cid;
             }
             if ($gid) {
                 $this->_gid = $gid;
             }
             $this->_rgid = $rgid;
             $this->_mainContacts = $mainContacts;
             $session = CRM_Core_Session::singleton();
             if ($this->_cid) {
                 $session->pushUserContext(CRM_Utils_System::url('civicrm/contact/deduperules', "action=update&rgid={$this->_rgid}&gid={$this->_gid}&cid={$this->_cid}"));
             } else {
                 $session->pushUserContext(CRM_Utils_System::url('civicrm/contact/dedupefind', "reset=1&action=update&rgid={$this->_rgid}"));
             }
         }
         $this->assign('action', $this->action);
         $this->browse();
     } else {
         $this->action = CRM_Core_Action::UPDATE;
         $this->edit($this->action);
         $this->assign('action', $this->action);
     }
     $this->assign('context', $context);
     // parent run
     parent::run();
 }
示例#17
0
文件: Schema.php 项目: hguru/224Civi
 /**
  * Rebuild multilingual indices, views and triggers (useful for upgrades)
  *
  * @param $locales array  locales to be rebuilt
  * @param $version string version of schema structure to use
  *
  * @return void
  */
 static function rebuildMultilingualSchema($locales, $version = NULL)
 {
     if ($version) {
         $latest = self::getLatestSchema($version);
         require_once "CRM/Core/I18n/SchemaStructure_{$latest}.php";
         $class = "CRM_Core_I18n_SchemaStructure_{$latest}";
     } else {
         $class = 'CRM_Core_I18n_SchemaStructure';
     }
     $indices =& $class::indices();
     $tables =& $class::tables();
     $queries = array();
     $dao = new CRM_Core_DAO();
     // get all of the already existing indices
     $existing = array();
     foreach (array_keys($indices) as $table) {
         $existing[$table] = array();
         $dao->query("SHOW INDEX FROM {$table}", FALSE);
         while ($dao->fetch()) {
             if (preg_match('/_[a-z][a-z]_[A-Z][A-Z]$/', $dao->Key_name)) {
                 $existing[$table][] = $dao->Key_name;
             }
         }
     }
     // from all of the CREATE INDEX queries fetch the ones creating missing indices
     foreach ($locales as $locale) {
         foreach (array_keys($indices) as $table) {
             $allQueries = self::createIndexQueries($locale, $table, $class);
             foreach ($allQueries as $name => $query) {
                 if (!in_array("{$name}_{$locale}", $existing[$table])) {
                     $queries[] = $query;
                 }
             }
         }
     }
     // rebuild views
     foreach ($locales as $locale) {
         foreach ($tables as $table) {
             $queries[] = self::createViewQuery($locale, $table, $dao, $class);
         }
     }
     // rebuild triggers
     $last = array_pop($locales);
     foreach ($queries as $query) {
         $dao->query($query, FALSE);
     }
     // invoke the meta trigger creation call
     CRM_Core_DAO::triggerRebuild();
 }
示例#18
0
 /**
  * Count up events given a mailing id and optional job id.
  *
  * @param int $mailing_id
  *   ID of the mailing to count.
  * @param int $job_id
  *   Optional ID of a job to limit results.
  *
  * @return int
  *   Number of matching events
  */
 public static function getTotalCount($mailing_id, $job_id = NULL)
 {
     $dao = new CRM_Core_DAO();
     $queue = self::getTableName();
     $mailing = CRM_Mailing_BAO_Mailing::getTableName();
     $job = CRM_Mailing_BAO_MailingJob::getTableName();
     $dao->query("\n            SELECT      COUNT(*) as queued\n            FROM        {$queue}\n            INNER JOIN  {$job}\n                    ON  {$queue}.job_id = {$job}.id\n            INNER JOIN  {$mailing}\n                    ON  {$job}.mailing_id = {$mailing}.id\n                    AND {$job}.is_test = 0\n            WHERE       {$mailing}.id = " . CRM_Utils_Type::escape($mailing_id, 'Integer') . ($job_id ? " AND {$job}.id = " . CRM_Utils_Type::escape($job_id, 'Integer') : ''));
     $dao->fetch();
     return $dao->queued;
 }
示例#19
0
 /**
  * Check if profile Group used by any module.
  *
  * @param int $id
  *   Profile Id.
  *
  * @return bool
  *
  */
 public static function usedByModule($id)
 {
     //check whether this group is used by any module(check uf join records)
     $sql = "SELECT id\n                 FROM civicrm_uf_join\n                 WHERE civicrm_uf_join.uf_group_id={$id}";
     $dao = new CRM_Core_DAO();
     $dao->query($sql);
     if ($dao->fetch()) {
         return TRUE;
     } else {
         return FALSE;
     }
 }
示例#20
0
 /**
  * Send a response email informing the contact of the groups to which he/she
  * has been resubscribed.
  *
  * @param string $queue_id
  *   The queue event ID.
  * @param array $groups
  *   List of group IDs.
  * @param bool $is_domain
  *   Is this domain-level?.
  * @param int $job
  *   The job ID.
  */
 public static function send_resub_response($queue_id, $groups, $is_domain = FALSE, $job)
 {
     // param is_domain is not supported as of now.
     $config = CRM_Core_Config::singleton();
     $domain = CRM_Core_BAO_Domain::getDomain();
     $jobTable = CRM_Mailing_BAO_MailingJob::getTableName();
     $mailingTable = CRM_Mailing_DAO_Mailing::getTableName();
     $contacts = CRM_Contact_DAO_Contact::getTableName();
     $email = CRM_Core_DAO_Email::getTableName();
     $queue = CRM_Mailing_Event_BAO_Queue::getTableName();
     //get the default domain email address.
     list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail();
     $dao = new CRM_Mailing_BAO_Mailing();
     $dao->query("   SELECT * FROM {$mailingTable}\n                        INNER JOIN {$jobTable} ON\n                            {$jobTable}.mailing_id = {$mailingTable}.id\n                        WHERE {$jobTable}.id = {$job}");
     $dao->fetch();
     $component = new CRM_Mailing_BAO_Component();
     $component->id = $dao->resubscribe_id;
     $component->find(TRUE);
     $html = $component->body_html;
     if ($component->body_text) {
         $text = $component->body_text;
     } else {
         $text = CRM_Utils_String::htmlToText($component->body_html);
     }
     $eq = new CRM_Core_DAO();
     $eq->query("SELECT     {$contacts}.preferred_mail_format as format,\n                    {$contacts}.id as contact_id,\n                    {$email}.email as email,\n                    {$queue}.hash as hash\n        FROM        {$contacts}\n        INNER JOIN  {$queue} ON {$queue}.contact_id = {$contacts}.id\n        INNER JOIN  {$email} ON {$queue}.email_id = {$email}.id\n        WHERE       {$queue}.id = " . CRM_Utils_Type::escape($queue_id, 'Integer'));
     $eq->fetch();
     foreach ($groups as $key => $value) {
         if (!$value) {
             unset($groups[$key]);
         }
     }
     $message = new Mail_mime("\n");
     list($addresses, $urls) = CRM_Mailing_BAO_Mailing::getVerpAndUrls($job, $queue_id, $eq->hash, $eq->email);
     $bao = new CRM_Mailing_BAO_Mailing();
     $bao->body_text = $text;
     $bao->body_html = $html;
     $tokens = $bao->getTokens();
     if ($eq->format == 'HTML' || $eq->format == 'Both') {
         $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, TRUE, $tokens['html']);
         $html = CRM_Utils_Token::replaceResubscribeTokens($html, $domain, $groups, TRUE, $eq->contact_id, $eq->hash);
         $html = CRM_Utils_Token::replaceActionTokens($html, $addresses, $urls, TRUE, $tokens['html']);
         $html = CRM_Utils_Token::replaceMailingTokens($html, $dao, NULL, $tokens['html']);
         $message->setHTMLBody($html);
     }
     if (!$html || $eq->format == 'Text' || $eq->format == 'Both') {
         $text = CRM_Utils_Token::replaceDomainTokens($html, $domain, TRUE, $tokens['text']);
         $text = CRM_Utils_Token::replaceResubscribeTokens($text, $domain, $groups, FALSE, $eq->contact_id, $eq->hash);
         $text = CRM_Utils_Token::replaceActionTokens($text, $addresses, $urls, FALSE, $tokens['text']);
         $text = CRM_Utils_Token::replaceMailingTokens($text, $dao, NULL, $tokens['text']);
         $message->setTxtBody($text);
     }
     $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
     $headers = array('Subject' => $component->subject, 'From' => "\"{$domainEmailName}\" <do-not-reply@{$emailDomain}>", 'To' => $eq->email, 'Reply-To' => "do-not-reply@{$emailDomain}", 'Return-Path' => "do-not-reply@{$emailDomain}");
     CRM_Mailing_BAO_Mailing::addMessageIdHeader($headers, 'e', $job, $queue_id, $eq->hash);
     $b = CRM_Utils_Mail::setMimeParams($message);
     $h = $message->headers($headers);
     $mailer = \Civi::service('pear_mail');
     if (is_object($mailer)) {
         $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
         $mailer->send($eq->email, $h, $b);
         unset($errorScope);
     }
 }
示例#21
0
 /**
  * This function sets the default values for the form. Relationship that in edit/view mode
  * the default values are retrieved from the database
  * 
  * @access public
  * @return None
  */
 function setDefaultValues()
 {
     if ($this->_cdType) {
         return CRM_Custom_Form_CustomData::setDefaultValues($this);
     }
     $defaults = array();
     if ($this->_action & CRM_Core_Action::UPDATE) {
         if (!empty($this->_values)) {
             $defaults['relationship_type_id'] = $this->_rtypeId;
             if (CRM_Utils_Array::value('start_date', $this->_values)) {
                 list($defaults['start_date']) = CRM_Utils_Date::setDateDefaults($this->_values['start_date']);
             }
             if (CRM_Utils_Array::value('end_date', $this->_values)) {
                 list($defaults['end_date']) = CRM_Utils_Date::setDateDefaults($this->_values['end_date']);
             }
             $defaults['description'] = CRM_Utils_Array::value('description', $this->_values);
             $defaults['is_active'] = CRM_Utils_Array::value('is_active', $this->_values);
             $defaults['is_permission_a_b'] = CRM_Utils_Array::value('is_permission_a_b', $this->_values);
             $defaults['is_permission_b_a'] = CRM_Utils_Array::value('is_permission_b_a', $this->_values);
             $contact = new CRM_Contact_DAO_Contact();
             if ($this->_rtype == 'a_b' && $this->_values['contact_id_a'] == $this->_contactId) {
                 $contact->id = $this->_values['contact_id_b'];
             } else {
                 $contact->id = $this->_values['contact_id_a'];
             }
             if ($contact->find(true)) {
                 $this->_display_name_b = $contact->display_name;
                 $this->assign('sort_name_b', $this->_display_name_b);
                 //is current employee/employer.
                 if ($this->_allRelationshipNames[$this->_relationshipTypeId]["name_{$this->_rtype}"] == 'Employee of' && $contact->id == CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId, 'employer_id')) {
                     $defaults['is_current_employer'] = 1;
                     $this->_values['current_employee_id'] = $this->_contactId;
                     $this->_values['current_employer_id'] = $contact->id;
                 } else {
                     if ($this->_allRelationshipNames[$this->_relationshipTypeId]["name_{$this->_rtype}"] == 'Employer of' && $this->_contactId == $contact->employer_id) {
                         $defaults['is_current_employer'] = 1;
                         $this->_values['current_employee_id'] = $contact->id;
                         $this->_values['current_employer_id'] = $this->_contactId;
                     }
                 }
             }
             $relationshipID = $this->_values['id'];
             $query = "SELECT id, note FROM civicrm_note where entity_table = 'civicrm_relationship' and entity_id = {$relationshipID}  order by modified_date desc";
             $dao = new CRM_Core_DAO();
             $dao->query($query);
             if ($dao->fetch($query)) {
                 $defaults['note'] = $dao->note;
             }
         }
     } else {
         $defaults['is_active'] = 1;
         $defaults['relationship_type_id'] = $this->_rtypeId;
     }
     return $defaults;
 }
示例#22
0
 /**
  * Get row count for the event selector.
  *
  * @param int $mailing_id
  *   ID of the mailing.
  * @param int $job_id
  *   Optional ID of a job to filter on.
  * @param bool $is_distinct
  *   Group by queue ID?.
  *
  * @return int
  *   Number of rows in result set
  */
 public static function getTotalCount($mailing_id, $job_id = NULL, $is_distinct = FALSE, $toDate = NULL)
 {
     $dao = new CRM_Core_DAO();
     $delivered = self::getTableName();
     $bounce = CRM_Mailing_Event_BAO_Bounce::getTableName();
     $queue = CRM_Mailing_Event_BAO_Queue::getTableName();
     $mailing = CRM_Mailing_BAO_Mailing::getTableName();
     $job = CRM_Mailing_BAO_MailingJob::getTableName();
     $query = "\n            SELECT      COUNT({$delivered}.id) as delivered\n            FROM        {$delivered}\n            INNER JOIN  {$queue}\n                    ON  {$delivered}.event_queue_id = {$queue}.id\n            LEFT JOIN   {$bounce}\n                    ON  {$delivered}.event_queue_id = {$bounce}.event_queue_id\n            INNER JOIN  {$job}\n                    ON  {$queue}.job_id = {$job}.id\n                    AND {$job}.is_test = 0\n            INNER JOIN  {$mailing}\n                    ON  {$job}.mailing_id = {$mailing}.id\n            WHERE       {$bounce}.id IS null\n                AND     {$mailing}.id = " . CRM_Utils_Type::escape($mailing_id, 'Integer');
     if (!empty($toDate)) {
         $query .= " AND {$delivered}.time_stamp <= {$toDate}";
     }
     if (!empty($job_id)) {
         $query .= " AND {$job}.id = " . CRM_Utils_Type::escape($job_id, 'Integer');
     }
     if ($is_distinct) {
         $query .= " GROUP BY {$queue}.id ";
     }
     // query was missing
     $dao->query($query);
     if ($dao->fetch()) {
         return $dao->delivered;
     }
     return NULL;
 }
示例#23
0
 /**
  * Get row count for the event selector
  *
  * @param int $mailing_id       ID of the mailing
  * @param int $job_id           Optional ID of a job to filter on
  * @param boolean $is_distinct  Group by queue ID?
  *
  * @return int                  Number of rows in result set
  * @access public
  * @static
  */
 public static function getTotalCount($mailing_id, $job_id = NULL, $is_distinct = FALSE)
 {
     $dao = new CRM_Core_DAO();
     $bounce = self::getTableName();
     $queue = CRM_Mailing_Event_BAO_Queue::getTableName();
     $mailing = CRM_Mailing_BAO_Mailing::getTableName();
     $job = CRM_Mailing_BAO_MailingJob::getTableName();
     $query = "\n            SELECT      COUNT({$bounce}.id) as bounce\n            FROM        {$bounce}\n            INNER JOIN  {$queue}\n                    ON  {$bounce}.event_queue_id = {$queue}.id\n            INNER JOIN  {$job}\n                    ON  {$queue}.job_id = {$job}.id\n            INNER JOIN  {$mailing}\n                    ON  {$job}.mailing_id = {$mailing}.id\n            WHERE       {$mailing}.id = " . CRM_Utils_Type::escape($mailing_id, 'Integer');
     if (!empty($job_id)) {
         $query .= " AND {$job}.id = " . CRM_Utils_Type::escape($job_id, 'Integer');
     }
     if ($is_distinct) {
         $query .= " GROUP BY {$queue}.id ";
     }
     // query was missing
     $dao->query($query);
     if ($dao->fetch()) {
         return $dao->bounce;
     }
     return NULL;
 }
示例#24
0
 /**
  * Get tracked url count for each mailing for a given set of mailing IDs.
  *
  * @param int $mailingIDs
  *   IDs of the mailing (comma separated).
  * @param int $contactID
  *   ID of the contact.
  *
  * @return array
  *   Count per mailing ID
  */
 public static function getMailingContactCount($mailingIDs, $contactID)
 {
     $dao = new CRM_Core_DAO();
     $clickCount = array();
     $click = self::getTableName();
     $queue = CRM_Mailing_Event_BAO_Queue::getTableName();
     $job = CRM_Mailing_BAO_MailingJob::getTableName();
     $mailingIDs = implode(',', $mailingIDs);
     $query = "\n      SELECT {$job}.mailing_id as mailingID, COUNT({$click}.id) as opened\n      FROM {$click}\n      INNER JOIN {$queue}\n        ON  {$click}.event_queue_id = {$queue}.id\n        AND {$queue}.contact_id = {$contactID}\n      INNER JOIN {$job}\n        ON  {$queue}.job_id = {$job}.id\n        AND {$job}.is_test = 0\n      WHERE {$job}.mailing_id IN ({$mailingIDs})\n      GROUP BY civicrm_mailing_job.mailing_id\n    ";
     $dao->query($query);
     while ($dao->fetch()) {
         $clickCount[$dao->mailingID] = $dao->opened;
     }
     return $clickCount;
 }
示例#25
0
 /**
  * Update contribution as well as related objects.
  *
  * This function by-passes hooks - to address this - don't use this function.
  *
  * @deprecated
  *
  * Use api contribute.completetransaction
  * For failures use failPayment (preferably exposing by api in the process).
  *
  * @param array $params
  * @param bool $processContributionObject
  *
  * @return array
  * @throws \Exception
  */
 public static function transitionComponents($params, $processContributionObject = FALSE)
 {
     // get minimum required values.
     $contactId = CRM_Utils_Array::value('contact_id', $params);
     $componentId = CRM_Utils_Array::value('component_id', $params);
     $componentName = CRM_Utils_Array::value('componentName', $params);
     $contributionId = CRM_Utils_Array::value('contribution_id', $params);
     $contributionStatusId = CRM_Utils_Array::value('contribution_status_id', $params);
     // if we already processed contribution object pass previous status id.
     $previousContriStatusId = CRM_Utils_Array::value('previous_contribution_status_id', $params);
     $updateResult = array();
     $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     // we process only ( Completed, Cancelled, or Failed ) contributions.
     if (!$contributionId || !in_array($contributionStatusId, array(array_search('Completed', $contributionStatuses), array_search('Cancelled', $contributionStatuses), array_search('Failed', $contributionStatuses)))) {
         return $updateResult;
     }
     if (!$componentName || !$componentId) {
         // get the related component details.
         $componentDetails = self::getComponentDetails($contributionId);
     } else {
         $componentDetails['contact_id'] = $contactId;
         $componentDetails['component'] = $componentName;
         if ($componentName == 'event') {
             $componentDetails['participant'] = $componentId;
         } else {
             $componentDetails['membership'] = $componentId;
         }
     }
     if (!empty($componentDetails['contact_id'])) {
         $componentDetails['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'contact_id');
     }
     // do check for required ids.
     if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) || empty($componentDetails['contact_id'])) {
         return $updateResult;
     }
     //now we are ready w/ required ids, start processing.
     $baseIPN = new CRM_Core_Payment_BaseIPN();
     $input = $ids = $objects = array();
     $input['component'] = CRM_Utils_Array::value('component', $componentDetails);
     $ids['contribution'] = $contributionId;
     $ids['contact'] = CRM_Utils_Array::value('contact_id', $componentDetails);
     $ids['membership'] = CRM_Utils_Array::value('membership', $componentDetails);
     $ids['participant'] = CRM_Utils_Array::value('participant', $componentDetails);
     $ids['event'] = CRM_Utils_Array::value('event', $componentDetails);
     $ids['pledge_payment'] = CRM_Utils_Array::value('pledge_payment', $componentDetails);
     $ids['contributionRecur'] = NULL;
     $ids['contributionPage'] = NULL;
     if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
         CRM_Core_Error::fatal();
     }
     $memberships =& $objects['membership'];
     $participant =& $objects['participant'];
     $pledgePayment =& $objects['pledge_payment'];
     $contribution =& $objects['contribution'];
     if ($pledgePayment) {
         $pledgePaymentIDs = array();
         foreach ($pledgePayment as $key => $object) {
             $pledgePaymentIDs[] = $object->id;
         }
         $pledgeID = $pledgePayment[0]->pledge_id;
     }
     $membershipStatuses = CRM_Member_PseudoConstant::membershipStatus();
     if ($participant) {
         $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
         $oldStatus = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participant->id, 'status_id');
     }
     // we might want to process contribution object.
     $processContribution = FALSE;
     if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
         if (is_array($memberships)) {
             foreach ($memberships as $membership) {
                 if ($membership) {
                     $membership->status_id = array_search('Cancelled', $membershipStatuses);
                     $membership->save();
                     $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
                     if ($processContributionObject) {
                         $processContribution = TRUE;
                     }
                 }
             }
         }
         if ($participant) {
             $updatedStatusId = array_search('Cancelled', $participantStatuses);
             CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
             $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
             if ($processContributionObject) {
                 $processContribution = TRUE;
             }
         }
         if ($pledgePayment) {
             CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
             $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
             if ($processContributionObject) {
                 $processContribution = TRUE;
             }
         }
     } elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
         if (is_array($memberships)) {
             foreach ($memberships as $membership) {
                 if ($membership) {
                     $membership->status_id = array_search('Expired', $membershipStatuses);
                     $membership->save();
                     $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
                     if ($processContributionObject) {
                         $processContribution = TRUE;
                     }
                 }
             }
         }
         if ($participant) {
             $updatedStatusId = array_search('Cancelled', $participantStatuses);
             CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
             $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
             if ($processContributionObject) {
                 $processContribution = TRUE;
             }
         }
         if ($pledgePayment) {
             CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
             $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
             if ($processContributionObject) {
                 $processContribution = TRUE;
             }
         }
     } elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
         // only pending contribution related object processed.
         if ($previousContriStatusId && $previousContriStatusId != array_search('Pending', $contributionStatuses)) {
             // this is case when we already processed contribution object.
             return $updateResult;
         } elseif (!$previousContriStatusId && $contribution->contribution_status_id != array_search('Pending', $contributionStatuses)) {
             // this is case when we are going to process contribution object later.
             return $updateResult;
         }
         if (is_array($memberships)) {
             foreach ($memberships as $membership) {
                 if ($membership) {
                     $format = '%Y%m%d';
                     //CRM-4523
                     $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id, $membership->membership_type_id, $membership->is_test, $membership->id);
                     // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
                     // this picks up membership type changes during renewals
                     $sql = "\n              SELECT    membership_type_id\n              FROM      civicrm_membership_log\n              WHERE     membership_id={$membership->id}\n              ORDER BY  id DESC\n              LIMIT     1;";
                     $dao = new CRM_Core_DAO();
                     $dao->query($sql);
                     if ($dao->fetch()) {
                         if (!empty($dao->membership_type_id)) {
                             $membership->membership_type_id = $dao->membership_type_id;
                             $membership->save();
                         }
                     }
                     // else fall back to using current membership type
                     $dao->free();
                     // Figure out number of terms
                     $numterms = 1;
                     $lineitems = CRM_Price_BAO_LineItem::getLineItems($contributionId, 'contribution');
                     foreach ($lineitems as $lineitem) {
                         if ($membership->membership_type_id == CRM_Utils_Array::value('membership_type_id', $lineitem)) {
                             $numterms = CRM_Utils_Array::value('membership_num_terms', $lineitem);
                             // in case membership_num_terms comes through as null or zero
                             $numterms = $numterms >= 1 ? $numterms : 1;
                             break;
                         }
                     }
                     // CRM-15735-to update the membership status as per the contribution receive date
                     $joinDate = NULL;
                     if (!empty($params['receive_date'])) {
                         $joinDate = $params['receive_date'];
                         $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($membership->start_date, $membership->end_date, $membership->join_date, $params['receive_date'], FALSE, $membership->membership_type_id, (array) $membership);
                         $membership->status_id = CRM_Utils_Array::value('id', $status, $membership->status_id);
                         $membership->save();
                     }
                     if ($currentMembership) {
                         CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, NULL);
                         $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, NULL, NULL, $numterms);
                         $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
                     } else {
                         $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, $joinDate, NULL, NULL, $numterms);
                     }
                     //get the status for membership.
                     $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', TRUE, $membership->membership_type_id, (array) $membership);
                     $formattedParams = array('status_id' => CRM_Utils_Array::value('id', $calcStatus, array_search('Current', $membershipStatuses)), 'join_date' => CRM_Utils_Date::customFormat($dates['join_date'], $format), 'start_date' => CRM_Utils_Date::customFormat($dates['start_date'], $format), 'end_date' => CRM_Utils_Date::customFormat($dates['end_date'], $format));
                     CRM_Utils_Hook::pre('edit', 'Membership', $membership->id, $formattedParams);
                     $membership->copyValues($formattedParams);
                     $membership->save();
                     //updating the membership log
                     $membershipLog = array();
                     $membershipLog = $formattedParams;
                     $logStartDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('log_start_date', $dates), $format);
                     $logStartDate = $logStartDate ? CRM_Utils_Date::isoToMysql($logStartDate) : $formattedParams['start_date'];
                     $membershipLog['start_date'] = $logStartDate;
                     $membershipLog['membership_id'] = $membership->id;
                     $membershipLog['modified_id'] = $membership->contact_id;
                     $membershipLog['modified_date'] = date('Ymd');
                     $membershipLog['membership_type_id'] = $membership->membership_type_id;
                     CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
                     //update related Memberships.
                     CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formattedParams);
                     $updateResult['membership_end_date'] = CRM_Utils_Date::customFormat($dates['end_date'], '%B %E%f, %Y');
                     $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
                     if ($processContributionObject) {
                         $processContribution = TRUE;
                     }
                     CRM_Utils_Hook::post('edit', 'Membership', $membership->id, $membership);
                 }
             }
         }
         if ($participant) {
             $updatedStatusId = array_search('Registered', $participantStatuses);
             CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
             $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
             if ($processContributionObject) {
                 $processContribution = TRUE;
             }
         }
         if ($pledgePayment) {
             CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
             $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
             if ($processContributionObject) {
                 $processContribution = TRUE;
             }
         }
     }
     // process contribution object.
     if ($processContribution) {
         $contributionParams = array();
         $fields = array('contact_id', 'total_amount', 'receive_date', 'is_test', 'campaign_id', 'payment_instrument_id', 'trxn_id', 'invoice_id', 'financial_type_id', 'contribution_status_id', 'non_deductible_amount', 'receipt_date', 'check_number');
         foreach ($fields as $field) {
             if (empty($params[$field])) {
                 continue;
             }
             $contributionParams[$field] = $params[$field];
         }
         $ids = array('contribution' => $contributionId);
         $contribution = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
     }
     return $updateResult;
 }
示例#26
0
 /**
  * Browse all rule groups.
  */
 public function run()
 {
     $gid = CRM_Utils_Request::retrieve('gid', 'Positive', $this, FALSE, 0);
     $action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 0);
     $context = CRM_Utils_Request::retrieve('context', 'String', $this);
     $session = CRM_Core_Session::singleton();
     $contactIds = $session->get('selectedSearchContactIds');
     if ($context == 'search' || !empty($contactIds)) {
         $context = 'search';
         $this->assign('backURL', $session->readUserContext());
     }
     if ($action & CRM_Core_Action::RENEW) {
         // empty cache
         $rgid = CRM_Utils_Request::retrieve('rgid', 'Positive', $this, FALSE, 0);
         if ($rgid) {
             $contactType = CRM_Core_DAO::getFieldValue('CRM_Dedupe_DAO_RuleGroup', $rgid, 'contact_type');
             $cacheKeyString = "merge {$contactType}";
             $cacheKeyString .= $rgid ? "_{$rgid}" : '_0';
             $cacheKeyString .= $gid ? "_{$gid}" : '_0';
             CRM_Core_BAO_PrevNextCache::deleteItem(NULL, $cacheKeyString);
         }
         $urlQry = "reset=1&action=update&rgid={$rgid}";
         if ($gid) {
             $urlQry .= "&gid={$gid}";
         }
         CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/dedupefind', $urlQry));
     } elseif ($action & CRM_Core_Action::MAP) {
         // do a batch merge if requested
         $rgid = CRM_Utils_Request::retrieve('rgid', 'Positive', $this, FALSE, 0);
         $result = CRM_Dedupe_Merger::batchMerge($rgid, $gid, 'safe', TRUE, 75);
         $skippedCount = CRM_Utils_Request::retrieve('skipped', 'Positive', $this, FALSE, 0);
         $skippedCount = $skippedCount + count($result['skipped']);
         $mergedCount = CRM_Utils_Request::retrieve('merged', 'Positive', $this, FALSE, 0);
         $mergedCount = $mergedCount + count($result['merged']);
         if (empty($result['merged']) && empty($result['skipped'])) {
             $message = '';
             if ($mergedCount >= 1) {
                 $message = ts("%1 pairs of duplicates were merged", array(1 => $mergedCount));
             }
             if ($skippedCount >= 1) {
                 $message = $message ? "{$message} and " : '';
                 $message .= ts("%1 pairs of duplicates were skipped due to conflict", array(1 => $skippedCount));
             }
             $message .= ts(" during the batch merge process with safe mode.");
             CRM_Core_Session::setStatus($message, ts('Merge Complete'), 'success');
             $urlQry = "reset=1&action=update&rgid={$rgid}";
             if ($gid) {
                 $urlQry .= "&gid={$gid}";
             }
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/dedupefind', $urlQry));
         } else {
             $urlQry = "reset=1&action=map&rgid={$rgid}";
             if ($gid) {
                 $urlQry .= "&gid={$gid}";
             }
             $urlQry .= "&skipped={$skippedCount}&merged={$mergedCount}";
             CRM_Utils_System::jsRedirect(CRM_Utils_System::url('civicrm/contact/dedupefind', $urlQry), ts('Batch Merge Task in progress'), ts('The batch merge task is still in progress. This page will be refreshed automatically.'));
         }
     }
     if ($action & CRM_Core_Action::UPDATE || $action & CRM_Core_Action::BROWSE) {
         $cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this, FALSE, 0);
         $rgid = CRM_Utils_Request::retrieve('rgid', 'Positive', $this, FALSE, 0);
         $this->action = CRM_Core_Action::UPDATE;
         //calculate the $contactType
         if ($rgid) {
             $contactType = CRM_Core_DAO::getFieldValue('CRM_Dedupe_DAO_RuleGroup', $rgid, 'contact_type');
         }
         $sourceParams = 'snippet=4';
         if ($gid) {
             $sourceParams .= "&gid={$gid}";
         }
         if ($rgid) {
             $sourceParams .= "&rgid={$rgid}";
         }
         if ($context == 'conflicts') {
             $sourceParams .= "&selected=1";
         }
         $this->assign('sourceUrl', CRM_Utils_System::url('civicrm/ajax/dedupefind', $sourceParams, FALSE, NULL, FALSE));
         //reload from cache table
         $cacheKeyString = "merge {$contactType}";
         $cacheKeyString .= $rgid ? "_{$rgid}" : '_0';
         $cacheKeyString .= $gid ? "_{$gid}" : '_0';
         $stats = CRM_Dedupe_Merger::getMergeStatsMsg($cacheKeyString);
         if ($stats) {
             CRM_Core_Session::setStatus($stats);
             // reset so we not displaying same message again
             CRM_Dedupe_Merger::resetMergeStats($cacheKeyString);
         }
         $join = "LEFT JOIN civicrm_dedupe_exception de ON ( pn.entity_id1 = de.contact_id1 AND\n                                                                 pn.entity_id2 = de.contact_id2 )";
         $where = "de.id IS NULL";
         if ($context == 'conflicts') {
             $where .= " AND pn.is_selected = 1";
         }
         $this->_mainContacts = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where);
         if (empty($this->_mainContacts)) {
             if ($context == 'conflicts') {
                 // if the current screen was intended to list only selected contacts, move back to full dupe list
                 $sourceParams = 'reset=1&action=update';
                 if ($gid) {
                     $sourceParams .= "&gid={$gid}";
                 }
                 if ($rgid) {
                     $sourceParams .= "&rgid={$rgid}";
                 }
                 CRM_Utils_System::redirect(CRM_Utils_System::url(CRM_Utils_System::currentPath(), $sourceParams));
             }
             if ($gid) {
                 $foundDupes = $this->get("dedupe_dupes_{$gid}");
                 if (!$foundDupes) {
                     $foundDupes = CRM_Dedupe_Finder::dupesInGroup($rgid, $gid);
                 }
                 $this->set("dedupe_dupes_{$gid}", $foundDupes);
             } elseif (!empty($contactIds)) {
                 $foundDupes = $this->get("search_dedupe_dupes_{$gid}");
                 if (!$foundDupes) {
                     $foundDupes = CRM_Dedupe_Finder::dupes($rgid, $contactIds);
                 }
                 $this->get("search_dedupe_dupes_{$gid}", $foundDupes);
             } else {
                 $foundDupes = $this->get('dedupe_dupes');
                 if (!$foundDupes) {
                     $foundDupes = CRM_Dedupe_Finder::dupes($rgid);
                 }
                 $this->set('dedupe_dupes', $foundDupes);
             }
             if (!$foundDupes) {
                 $ruleGroup = new CRM_Dedupe_BAO_RuleGroup();
                 $ruleGroup->id = $rgid;
                 $ruleGroup->find(TRUE);
                 $session = CRM_Core_Session::singleton();
                 $session->setStatus(ts('No possible duplicates were found using %1 rule.', array(1 => $ruleGroup->name)), ts('None Found'), 'info');
                 $url = CRM_Utils_System::url('civicrm/contact/deduperules', 'reset=1');
                 if ($context == 'search') {
                     $url = $session->readUserContext();
                 }
                 CRM_Utils_System::redirect($url);
             } else {
                 $cids = array();
                 foreach ($foundDupes as $dupe) {
                     $cids[$dupe[0]] = 1;
                     $cids[$dupe[1]] = 1;
                 }
                 $cidString = implode(', ', array_keys($cids));
                 $sql = "SELECT id, display_name FROM civicrm_contact WHERE id IN ({$cidString}) ORDER BY sort_name";
                 $dao = new CRM_Core_DAO();
                 $dao->query($sql);
                 $displayNames = array();
                 while ($dao->fetch()) {
                     $displayNames[$dao->id] = $dao->display_name;
                 }
                 // FIXME: sort the contacts; $displayName
                 // is already sort_name-sorted, so use that
                 // (also, consider sorting by dupe count first)
                 // lobo - change the sort to by threshold value
                 // so the more likely dupes are sorted first
                 $session = CRM_Core_Session::singleton();
                 $userId = $session->get('userID');
                 $mainContacts = $permission = array();
                 foreach ($foundDupes as $dupes) {
                     $srcID = $dupes[0];
                     $dstID = $dupes[1];
                     if ($dstID == $userId) {
                         $srcID = $dupes[1];
                         $dstID = $dupes[0];
                     }
                     /***
                      * Eliminate this since it introduces 3 queries PER merge row
                      * and hence is very expensive
                      * CRM-8822
                      * if ( !array_key_exists( $srcID, $permission ) ) {
                      * $permission[$srcID] = CRM_Contact_BAO_Contact_Permission::allow( $srcID, CRM_Core_Permission::EDIT );
                      * }
                      * if ( !array_key_exists( $dstID, $permission ) ) {
                      * $permission[$dstID] = CRM_Contact_BAO_Contact_Permission::allow( $dstID, CRM_Core_Permission::EDIT );
                      * }
                      *
                      * $canMerge = ( $permission[$dstID] && $permission[$srcID] );
                      *
                      */
                     // we'll do permission checking during the merge process
                     $canMerge = TRUE;
                     $mainContacts[] = $row = array('srcID' => $srcID, 'srcName' => $displayNames[$srcID], 'dstID' => $dstID, 'dstName' => $displayNames[$dstID], 'weight' => $dupes[2], 'canMerge' => $canMerge);
                     $data = CRM_Core_DAO::escapeString(serialize($row));
                     $values[] = " ( 'civicrm_contact', {$srcID}, {$dstID}, '{$cacheKeyString}', '{$data}' ) ";
                 }
                 if ($cid) {
                     $this->_cid = $cid;
                 }
                 if ($gid) {
                     $this->_gid = $gid;
                 }
                 $this->_rgid = $rgid;
                 $this->_mainContacts = $mainContacts;
                 CRM_Core_BAO_PrevNextCache::setItem($values);
                 $session = CRM_Core_Session::singleton();
                 if ($this->_cid) {
                     $session->pushUserContext(CRM_Utils_System::url('civicrm/contact/deduperules', "action=update&rgid={$this->_rgid}&gid={$this->_gid}&cid={$this->_cid}"));
                 } else {
                     $session->pushUserContext(CRM_Utils_System::url('civicrm/contact/dedupefind', "reset=1&action=update&rgid={$this->_rgid}"));
                 }
             }
         } else {
             if ($cid) {
                 $this->_cid = $cid;
             }
             if ($gid) {
                 $this->_gid = $gid;
             }
             $this->_rgid = $rgid;
         }
         $this->assign('action', $this->action);
         $this->browse();
     } else {
         $this->action = CRM_Core_Action::UPDATE;
         $this->edit($this->action);
         $this->assign('action', $this->action);
     }
     $this->assign('context', $context);
     // parent run
     return parent::run();
 }
 function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE)
 {
     $contribution =& $objects['contribution'];
     $memberships =& $objects['membership'];
     if (is_numeric($memberships)) {
         $memberships = array($objects['membership']);
     }
     $participant =& $objects['participant'];
     $event =& $objects['event'];
     $changeToday = CRM_Utils_Array::value('trxn_date', $input, self::$_now);
     $recurContrib =& $objects['contributionRecur'];
     $values = array();
     if ($input['component'] == 'contribute') {
         if ($contribution->contribution_page_id) {
             CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values);
             $source = ts('Online Contribution') . ': ' . $values['title'];
         } elseif ($recurContrib->id) {
             $contribution->contribution_page_id = NULL;
             $values['amount'] = $recurContrib->amount;
             $values['contribution_type_id'] = $objects['contributionType']->id;
             $values['title'] = $source = ts('Offline Recurring Contribution');
             $values['is_email_receipt'] = $recurContrib->is_email_receipt;
             $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
             $values['receipt_from_name'] = $domainValues[0];
             $values['receipt_from_email'] = $domainValues[1];
         }
         $contribution->source = $source;
         if (CRM_Utils_Array::value('is_email_receipt', $values)) {
             $contribution->receipt_date = self::$_now;
         }
         if (!empty($memberships)) {
             foreach ($memberships as $membershipTypeIdKey => $membership) {
                 if ($membership) {
                     $format = '%Y%m%d';
                     $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id, $membership->membership_type_id, $membership->is_test, $membership->id);
                     // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
                     // this picks up membership type changes during renewals
                     $sql = "\nSELECT    membership_type_id\nFROM      civicrm_membership_log\nWHERE     membership_id={$membership->id}\nORDER BY  id DESC\nLIMIT 1;";
                     $dao = new CRM_Core_DAO();
                     $dao->query($sql);
                     if ($dao->fetch()) {
                         if (!empty($dao->membership_type_id)) {
                             $membership->membership_type_id = $dao->membership_type_id;
                             $membership->save();
                         }
                         // else fall back to using current membership type
                     }
                     // else fall back to using current membership type
                     $dao->free();
                     if ($currentMembership) {
                         /*
                          * Fixed FOR CRM-4433
                          * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
                          * when Contribution mode is notify and membership is for renewal )
                          */
                         CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
                         $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, $changeToday);
                         $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
                     } else {
                         $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id);
                     }
                     //get the status for membership.
                     $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', TRUE);
                     $formatedParams = array('status_id' => CRM_Utils_Array::value('id', $calcStatus, 2), 'join_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('join_date', $dates), $format), 'start_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('start_date', $dates), $format), 'end_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $dates), $format), 'reminder_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('reminder_date', $dates), $format));
                     //we might be renewing membership,
                     //so make status override false.
                     $formatedParams['is_override'] = FALSE;
                     $membership->copyValues($formatedParams);
                     $membership->save();
                     //updating the membership log
                     $membershipLog = array();
                     $membershipLog = $formatedParams;
                     $logStartDate = $formatedParams['start_date'];
                     if (CRM_Utils_Array::value('log_start_date', $dates)) {
                         $logStartDate = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
                         $logStartDate = CRM_Utils_Date::isoToMysql($logStartDate);
                     }
                     $membershipLog['start_date'] = $logStartDate;
                     $membershipLog['membership_id'] = $membership->id;
                     $membershipLog['modified_id'] = $membership->contact_id;
                     $membershipLog['modified_date'] = date('Ymd');
                     $membershipLog['membership_type_id'] = $membership->membership_type_id;
                     CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
                     //update related Memberships.
                     CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formatedParams);
                     //update the membership type key of membership relatedObjects array
                     //if it has changed after membership update
                     if ($membershipTypeIdKey != $membership->membership_type_id) {
                         $memberships[$membership->membership_type_id] = $membership;
                         $contribution->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
                         unset($contribution->_relatedObjects['membership'][$membershipTypeIdKey]);
                         unset($memberships[$membershipTypeIdKey]);
                     }
                 }
             }
         }
     } else {
         // event
         $eventParams = array('id' => $objects['event']->id);
         $values['event'] = array();
         CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
         $eventParams = array('id' => $objects['event']->id);
         $values['event'] = array();
         CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
         //get location details
         $locationParams = array('entity_id' => $objects['event']->id, 'entity_table' => 'civicrm_event');
         $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
         $ufJoinParams = array('entity_table' => 'civicrm_event', 'entity_id' => $ids['event'], 'module' => 'CiviEvent');
         list($custom_pre_id, $custom_post_ids) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
         $values['custom_pre_id'] = $custom_pre_id;
         $values['custom_post_id'] = $custom_post_ids;
         $contribution->source = ts('Online Event Registration') . ': ' . $values['event']['title'];
         if ($values['event']['is_email_confirm']) {
             $contribution->receipt_date = self::$_now;
             $values['is_email_receipt'] = 1;
         }
         $participant->status_id = 1;
         $participant->save();
     }
     if (CRM_Utils_Array::value('net_amount', $input, 0) == 0 && CRM_Utils_Array::value('fee_amount', $input, 0) != 0) {
         $input['net_amount'] = $input['amount'] - $input['fee_amount'];
     }
     $addLineItems = FALSE;
     if (empty($contribution->id)) {
         $addLineItems = TRUE;
     }
     $contribution->contribution_status_id = 1;
     $contribution->is_test = $input['is_test'];
     $contribution->fee_amount = CRM_Utils_Array::value('fee_amount', $input, 0);
     $contribution->net_amount = CRM_Utils_Array::value('net_amount', $input, 0);
     $contribution->trxn_id = $input['trxn_id'];
     $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
     $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
     $contribution->cancel_date = 'null';
     if (CRM_Utils_Array::value('check_number', $input)) {
         $contribution->check_number = $input['check_number'];
     }
     if (CRM_Utils_Array::value('payment_instrument_id', $input)) {
         $contribution->payment_instrument_id = $input['payment_instrument_id'];
     }
     $contribution->save();
     //add lineitems for recurring payments
     if (CRM_Utils_Array::value('contributionRecur', $objects) && $objects['contributionRecur']->id && $addLineItems) {
         $this->addrecurLineItems($objects['contributionRecur']->id, $contribution->id);
     }
     // next create the transaction record
     $paymentProcessor = '';
     if (isset($objects['paymentProcessor'])) {
         if (is_array($objects['paymentProcessor'])) {
             $paymentProcessor = $objects['paymentProcessor']['payment_processor_type'];
         } else {
             $paymentProcessor = $objects['paymentProcessor']->payment_processor_type;
         }
     }
     if ($contribution->trxn_id) {
         $trxnParams = array('contribution_id' => $contribution->id, 'trxn_date' => isset($input['trxn_date']) ? $input['trxn_date'] : self::$_now, 'trxn_type' => 'Debit', 'total_amount' => $input['amount'], 'fee_amount' => $contribution->fee_amount, 'net_amount' => $contribution->net_amount, 'currency' => $contribution->currency, 'payment_processor' => $paymentProcessor, 'trxn_id' => $contribution->trxn_id);
         $trxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
     }
     self::updateRecurLinkedPledge($contribution);
     // create an activity record
     if ($input['component'] == 'contribute') {
         //CRM-4027
         $targetContactID = NULL;
         if (CRM_Utils_Array::value('related_contact', $ids)) {
             $targetContactID = $contribution->contact_id;
             $contribution->contact_id = $ids['related_contact'];
         }
         CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
         // event
     } else {
         CRM_Activity_BAO_Activity::addActivity($participant);
     }
     CRM_Core_Error::debug_log_message("Contribution record updated successfully");
     $transaction->commit();
     // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
     // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
     if (!array_key_exists('is_email_receipt', $values) || $values['is_email_receipt'] == 1) {
         self::sendMail($input, $ids, $objects, $values, $recur, FALSE);
     }
     CRM_Core_Error::debug_log_message("Success: Database updated and mail sent");
 }
示例#28
0
 /**
  * Send a reponse email informing the contact of the groups to which he/she
  * has been resubscribed.
  *
  * @param string $queue_id      The queue event ID
  * @param array $groups         List of group IDs
  * @param bool $is_domain       Is this domain-level?
  * @param int $job              The job ID
  * @return void
  * @access public
  * @static
  */
 public static function send_resub_response($queue_id, $groups, $is_domain = false, $job)
 {
     // param is_domain is not supported as of now.
     $config = CRM_Core_Config::singleton();
     $domain =& CRM_Core_BAO_Domain::getDomain();
     $jobTable = CRM_Mailing_BAO_Job::getTableName();
     $mailingTable = CRM_Mailing_DAO_Mailing::getTableName();
     $contacts = CRM_Contact_DAO_Contact::getTableName();
     $email = CRM_Core_DAO_Email::getTableName();
     $queue = CRM_Mailing_Event_BAO_Queue::getTableName();
     //get the default domain email address.
     list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail();
     $dao = new CRM_Mailing_BAO_Mailing();
     $dao->query("   SELECT * FROM {$mailingTable} \n                        INNER JOIN {$jobTable} ON\n                            {$jobTable}.mailing_id = {$mailingTable}.id \n                        WHERE {$jobTable}.id = {$job}");
     $dao->fetch();
     $component = new CRM_Mailing_BAO_Component();
     $component->id = $dao->resubscribe_id;
     $component->find(true);
     $html = $component->body_html;
     if ($component->body_text) {
         $text = $component->body_text;
     } else {
         $text = CRM_Utils_String::htmlToText($component->body_html);
     }
     $eq = new CRM_Core_DAO();
     $eq->query("SELECT     {$contacts}.preferred_mail_format as format,\n                    {$contacts}.id as contact_id,\n                    {$email}.email as email,\n                    {$queue}.hash as hash\n        FROM        {$contacts}\n        INNER JOIN  {$queue} ON {$queue}.contact_id = {$contacts}.id\n        INNER JOIN  {$email} ON {$queue}.email_id = {$email}.id\n        WHERE       {$queue}.id = " . CRM_Utils_Type::escape($queue_id, 'Integer'));
     $eq->fetch();
     foreach ($groups as $key => $value) {
         if (!$value) {
             unset($groups[$key]);
         }
     }
     $message = new Mail_mime("\n");
     list($addresses, $urls) = CRM_Mailing_BAO_Mailing::getVerpAndUrls($job, $queue_id, $eq->hash, $eq->email);
     $bao = new CRM_Mailing_BAO_Mailing();
     $bao->body_text = $text;
     $bao->body_html = $html;
     $tokens = $bao->getTokens();
     require_once 'CRM/Utils/Token.php';
     if ($eq->format == 'HTML' || $eq->format == 'Both') {
         $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, true, $tokens['html']);
         $html = CRM_Utils_Token::replaceResubscribeTokens($html, $domain, $groups, true, $eq->contact_id, $eq->hash);
         $html = CRM_Utils_Token::replaceActionTokens($html, $addresses, $urls, true, $tokens['html']);
         $html = CRM_Utils_Token::replaceMailingTokens($html, $dao, null, $tokens['html']);
         $message->setHTMLBody($html);
     }
     if (!$html || $eq->format == 'Text' || $eq->format == 'Both') {
         $text = CRM_Utils_Token::replaceDomainTokens($html, $domain, true, $tokens['text']);
         $text = CRM_Utils_Token::replaceResubscribeTokens($text, $domain, $groups, false, $eq->contact_id, $eq->hash);
         $text = CRM_Utils_Token::replaceActionTokens($text, $addresses, $urls, false, $tokens['text']);
         $text = CRM_Utils_Token::replaceMailingTokens($text, $dao, null, $tokens['text']);
         $message->setTxtBody($text);
     }
     require_once 'CRM/Core/BAO/MailSettings.php';
     $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
     $headers = array('Subject' => $component->subject, 'From' => "\"{$domainEmailName}\" <do-not-reply@{$emailDomain}>", 'To' => $eq->email, 'Reply-To' => "do-not-reply@{$emailDomain}", 'Return-Path' => "do-not-reply@{$emailDomain}");
     $b =& CRM_Utils_Mail::setMimeParams($message);
     $h =& $message->headers($headers);
     $mailer =& $config->getMailer();
     PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array('CRM_Core_Error', 'nullHandler'));
     if (is_object($mailer)) {
         $mailer->send($eq->email, $h, $b);
         CRM_Core_Error::setCallback();
     }
 }
示例#29
0
 function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE)
 {
     $contribution =& $objects['contribution'];
     $primaryContributionID = isset($contribution->id) ? $contribution->id : $objects['first_contribution']->id;
     $memberships =& $objects['membership'];
     if (is_numeric($memberships)) {
         $memberships = array($objects['membership']);
     }
     $participant =& $objects['participant'];
     $event =& $objects['event'];
     $changeToday = CRM_Utils_Array::value('trxn_date', $input, self::$_now);
     $recurContrib =& $objects['contributionRecur'];
     $values = array();
     if (isset($input['is_email_receipt'])) {
         $values['is_email_receipt'] = $input['is_email_receipt'];
     }
     $source = NULL;
     if ($input['component'] == 'contribute') {
         if ($contribution->contribution_page_id) {
             CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values);
             $source = ts('Online Contribution') . ': ' . $values['title'];
         } elseif ($recurContrib && $recurContrib->id) {
             $contribution->contribution_page_id = NULL;
             $values['amount'] = $recurContrib->amount;
             $values['financial_type_id'] = $objects['contributionType']->id;
             $values['title'] = $source = ts('Offline Recurring Contribution');
             $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
             $values['receipt_from_name'] = $domainValues[0];
             $values['receipt_from_email'] = $domainValues[1];
         }
         if ($recurContrib && $recurContrib->id && !isset($input['is_email_receipt'])) {
             //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
             // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
             $values['is_email_receipt'] = $recurContrib->is_email_receipt;
         }
         $contribution->source = $source;
         if (CRM_Utils_Array::value('is_email_receipt', $values)) {
             $contribution->receipt_date = self::$_now;
         }
         if (!empty($memberships)) {
             $membershipsUpdate = array();
             foreach ($memberships as $membershipTypeIdKey => $membership) {
                 if ($membership) {
                     $format = '%Y%m%d';
                     $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id, $membership->membership_type_id, $membership->is_test, $membership->id);
                     // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
                     // this picks up membership type changes during renewals
                     $sql = "\nSELECT    membership_type_id\nFROM      civicrm_membership_log\nWHERE     membership_id={$membership->id}\nORDER BY  id DESC\nLIMIT 1;";
                     $dao = new CRM_Core_DAO();
                     $dao->query($sql);
                     if ($dao->fetch()) {
                         if (!empty($dao->membership_type_id)) {
                             $membership->membership_type_id = $dao->membership_type_id;
                             $membership->save();
                         }
                         // else fall back to using current membership type
                     }
                     // else fall back to using current membership type
                     $dao->free();
                     $num_terms = $contribution->getNumTermsByContributionAndMembershipType($membership->membership_type_id, $primaryContributionID);
                     if ($currentMembership) {
                         /*
                          * Fixed FOR CRM-4433
                          * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
                          * when Contribution mode is notify and membership is for renewal )
                          */
                         CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
                         // @todo - we should pass membership_type_id instead of null here but not
                         // adding as not sure of testing
                         $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, $changeToday, NULL, $num_terms);
                         $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
                     } else {
                         $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, NULL, NULL, NULL, $num_terms);
                     }
                     //get the status for membership.
                     $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', TRUE, $membership->membership_type_id, (array) $membership);
                     $formatedParams = array('status_id' => CRM_Utils_Array::value('id', $calcStatus, 2), 'join_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('join_date', $dates), $format), 'start_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('start_date', $dates), $format), 'end_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $dates), $format));
                     //we might be renewing membership,
                     //so make status override false.
                     $formatedParams['is_override'] = FALSE;
                     $membership->copyValues($formatedParams);
                     $membership->save();
                     //updating the membership log
                     $membershipLog = array();
                     $membershipLog = $formatedParams;
                     $logStartDate = $formatedParams['start_date'];
                     if (CRM_Utils_Array::value('log_start_date', $dates)) {
                         $logStartDate = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
                         $logStartDate = CRM_Utils_Date::isoToMysql($logStartDate);
                     }
                     $membershipLog['start_date'] = $logStartDate;
                     $membershipLog['membership_id'] = $membership->id;
                     $membershipLog['modified_id'] = $membership->contact_id;
                     $membershipLog['modified_date'] = date('Ymd');
                     $membershipLog['membership_type_id'] = $membership->membership_type_id;
                     CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
                     //update related Memberships.
                     CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formatedParams);
                     //update the membership type key of membership relatedObjects array
                     //if it has changed after membership update
                     if ($membershipTypeIdKey != $membership->membership_type_id) {
                         $membershipsUpdate[$membership->membership_type_id] = $membership;
                         $contribution->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
                         unset($contribution->_relatedObjects['membership'][$membershipTypeIdKey]);
                         unset($memberships[$membershipTypeIdKey]);
                     }
                 }
             }
             //update the memberships object with updated membershipTypeId data
             //if membershipTypeId has changed after membership update
             if (!empty($membershipsUpdate)) {
                 $memberships = $memberships + $membershipsUpdate;
             }
         }
     } else {
         // event
         $eventParams = array('id' => $objects['event']->id);
         $values['event'] = array();
         CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
         //get location details
         $locationParams = array('entity_id' => $objects['event']->id, 'entity_table' => 'civicrm_event');
         $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
         $ufJoinParams = array('entity_table' => 'civicrm_event', 'entity_id' => $ids['event'], 'module' => 'CiviEvent');
         list($custom_pre_id, $custom_post_ids) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
         $values['custom_pre_id'] = $custom_pre_id;
         $values['custom_post_id'] = $custom_post_ids;
         //for tasks 'Change Participant Status' and 'Batch Update Participants Via Profile' case
         //and cases involving status updation through ipn
         $values['totalAmount'] = $input['amount'];
         $contribution->source = ts('Online Event Registration') . ': ' . $values['event']['title'];
         if ($values['event']['is_email_confirm']) {
             $contribution->receipt_date = self::$_now;
             $values['is_email_receipt'] = 1;
         }
         if (!CRM_Utils_Array::value('skipComponentSync', $input)) {
             $participant->status_id = 1;
         }
         $participant->save();
     }
     if (CRM_Utils_Array::value('net_amount', $input, 0) == 0 && CRM_Utils_Array::value('fee_amount', $input, 0) != 0) {
         $input['net_amount'] = $input['amount'] - $input['fee_amount'];
     }
     // This complete transaction function is being overloaded to create new contributions too.
     // here we record if it is a new contribution.
     // @todo separate the 2 more appropriately.
     $isNewContribution = FALSE;
     if (empty($contribution->id)) {
         $isNewContribution = TRUE;
         if (!empty($input['amount']) && $input['amount'] != $contribution->total_amount) {
             $contribution->total_amount = $input['amount'];
             // The BAO does this stuff but we are actually kinda bypassing it here (bad code! go sit in the corner)
             // so we have to handle net_amount in this (naughty) code.
             if (isset($input['fee_amount']) && is_numeric($input['fee_amount'])) {
                 $contribution->fee_amount = $input['fee_amount'];
             }
             $contribution->net_amount = $contribution->total_amount - $contribution->fee_amount;
         }
         if (!empty($input['campaign_id'])) {
             $contribution->campaign_id = $input['campaign_id'];
         }
     }
     $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array('labelColumn' => 'name', 'flip' => 1));
     // @todo this section should call the api  in order to have hooks called &
     // because all this 'messiness' setting variables could be avoided
     // by letting the api resolve pseudoconstants & copy set values and format dates.
     $contribution->contribution_status_id = $contributionStatuses['Completed'];
     $contribution->is_test = $input['is_test'];
     // CRM-15960 If we don't have a value we 'want' for the amounts, leave it to the BAO to sort out.
     if (isset($input['net_amount'])) {
         $contribution->fee_amount = CRM_Utils_Array::value('fee_amount', $input, 0);
     }
     if (isset($input['net_amount'])) {
         $contribution->net_amount = $input['net_amount'];
     }
     $contribution->trxn_id = $input['trxn_id'];
     $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
     $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
     $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date);
     $contribution->cancel_date = 'null';
     if (CRM_Utils_Array::value('check_number', $input)) {
         $contribution->check_number = $input['check_number'];
     }
     if (CRM_Utils_Array::value('payment_instrument_id', $input)) {
         $contribution->payment_instrument_id = $input['payment_instrument_id'];
     }
     if (!empty($contribution->id)) {
         $contributionId['id'] = $contribution->id;
         $input['prevContribution'] = CRM_Contribute_BAO_Contribution::getValues($contributionId, CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
     }
     $contribution->save();
     //add line items for recurring payments
     if (!empty($contribution->contribution_recur_id)) {
         if ($isNewContribution) {
             $input['line_item'] = $this->addRecurLineItems($contribution->contribution_recur_id, $contribution);
         } else {
             // this is just to prevent e-notices when we call recordFinancialAccounts - per comments on that line - intention is somewhat unclear
             $input['line_item'] = array();
         }
         if (!empty($memberships) && $primaryContributionID != $contribution->id) {
             foreach ($memberships as $membership) {
                 try {
                     $membershipPayment = array('membership_id' => $membership->id, 'contribution_id' => $contribution->id);
                     if (!civicrm_api3('membership_payment', 'getcount', $membershipPayment)) {
                         civicrm_api3('membership_payment', 'create', $membershipPayment);
                     }
                 } catch (CiviCRM_API3_Exception $e) {
                     echo $e->getMessage();
                     // we are catching & ignoring errors as an extra precaution since lost IPNs may be more serious that lost membership_payment data
                     // this fn is unit-tested so risk of changes elsewhere breaking it are otherwise mitigated
                 }
             }
         }
     }
     //copy initial contribution custom fields for recurring contributions
     if ($recurContrib && $recurContrib->id) {
         $this->copyCustomValues($recurContrib->id, $contribution->id);
     }
     // next create the transaction record
     $paymentProcessor = $paymentProcessorId = '';
     if (isset($objects['paymentProcessor'])) {
         if (is_array($objects['paymentProcessor'])) {
             $paymentProcessor = $objects['paymentProcessor']['payment_processor_type'];
             $paymentProcessorId = $objects['paymentProcessor']['id'];
         } else {
             $paymentProcessor = $objects['paymentProcessor']->payment_processor_type;
             $paymentProcessorId = $objects['paymentProcessor']->id;
         }
     }
     //it's hard to see how it could reach this point without a contributon id as it is saved in line 511 above
     // which raised the question as to whether this check preceded line 511 & if so whether something could be broken
     // From a lot of code reading /debugging I'm still not sure the intent WRT first & subsequent payments in this code
     // it would be good if someone added some comments or refactored this
     if ($contribution->id) {
         $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
         if (empty($input['prevContribution']) && $paymentProcessorId || !$input['prevContribution']->is_pay_later && $input['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatuses)) {
             $input['payment_processor'] = $paymentProcessorId;
         }
         $input['contribution_status_id'] = array_search('Completed', $contributionStatuses);
         $input['total_amount'] = $input['amount'];
         $input['contribution'] = $contribution;
         $input['financial_type_id'] = $contribution->financial_type_id;
         if (CRM_Utils_Array::value('participant', $contribution->_relatedObjects)) {
             $input['contribution_mode'] = 'participant';
             $input['participant_id'] = $contribution->_relatedObjects['participant']->id;
             $input['skipLineItem'] = 1;
         }
         //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
         // and subsequent payments. In this case the line items are created at $this->addRecurLineItems
         // and since the contribution is saved prior to this line there is always a contribution-id,
         // however there is never a prevContribution (which appears to mean original contribution not previous
         // contribution - or preUpdateContributionObject most accurately)
         // so, this is always called & only appears to succeed when prevContribution exists - which appears
         // to mean "are we updating an exisitng pending contribution"
         //I was able to make the unit test complete as fataling here doesn't prevent
         // the contribution being created - but activities would not be created or emails sent
         CRM_Contribute_BAO_Contribution::recordFinancialAccounts($input, NULL);
     }
     self::updateRecurLinkedPledge($contribution);
     // create an activity record
     if ($input['component'] == 'contribute') {
         //CRM-4027
         $targetContactID = NULL;
         if (CRM_Utils_Array::value('related_contact', $ids)) {
             $targetContactID = $contribution->contact_id;
             $contribution->contact_id = $ids['related_contact'];
         }
         CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
         // event
     } else {
         CRM_Activity_BAO_Activity::addActivity($participant);
     }
     CRM_Core_Error::debug_log_message("Contribution record updated successfully");
     $transaction->commit();
     // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
     // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
     if (!array_key_exists('is_email_receipt', $values) || $values['is_email_receipt'] == 1) {
         self::sendMail($input, $ids, $objects, $values, $recur, FALSE);
         CRM_Core_Error::debug_log_message("Receipt sent");
     }
     CRM_Core_Error::debug_log_message("Success: Database updated");
 }
 /**
  * Return an array of possible dupes, based on the provided array of
  * params, using the default rule group for the given contact type and
  * level.
  *
  * check_permission is a boolean flag to indicate if permission should be considered.
  * default is to always check permissioning but public pages for example might not want
  * permission to be checked for anonymous users. Refer CRM-6211. We might be beaking
  * Multi-Site dedupe for public pages.
  *
  * @param array  $params  array of params of the form $params[$table][$field] == $value
  * @param string $ctype   contact type to match against
  * @param string $level   dedupe rule group level ('Fuzzy' or 'Strict')
  * @param array  $except  array of contacts that shouldn't be considered dupes
  * @param int    $ruleGroupID the id of the dedupe rule we should be using
  *
  * @return array  matching contact ids
  */
 static function dupesByParams($params, $ctype, $level = 'Strict', $except = array(), $ruleGroupID = NULL)
 {
     // If $params is empty there is zero reason to proceed.
     if (!$params) {
         return array();
     }
     $foundByID = FALSE;
     if ($ruleGroupID) {
         $rgBao = new CRM_Dedupe_BAO_RuleGroup();
         $rgBao->id = $ruleGroupID;
         $rgBao->contact_type = $ctype;
         if ($rgBao->find(TRUE)) {
             $foundByID = TRUE;
         }
     }
     if (!$foundByID) {
         $rgBao = new CRM_Dedupe_BAO_RuleGroup();
         $rgBao->contact_type = $ctype;
         $rgBao->level = $level;
         $rgBao->is_default = 1;
         if (!$rgBao->find(TRUE)) {
             CRM_Core_Error::fatal("{$level} rule for {$ctype} does not exist");
         }
     }
     $params['check_permission'] = CRM_Utils_Array::value('check_permission', $params, TRUE);
     $rgBao->params = $params;
     $rgBao->fillTable();
     $dao = new CRM_Core_DAO();
     $dao->query($rgBao->thresholdQuery($params['check_permission']));
     $dupes = array();
     while ($dao->fetch()) {
         if (isset($dao->id) && $dao->id) {
             $dupes[] = $dao->id;
         }
     }
     $dao->query($rgBao->tableDropQuery());
     return array_diff($dupes, $except);
 }