Exemple #1
0
 /** 
  * Function to set variables up before form is built 
  *                                                           
  * @return void 
  * @access public 
  */
 public function preProcess()
 {
     //Test database user privilege to create table(Temporary) CRM-4725
     CRM_Core_Error::ignoreException();
     $daoTestPrivilege = new CRM_Core_DAO();
     $daoTestPrivilege->query("CREATE TEMPORARY TABLE import_job_permission_one(test int) ENGINE=InnoDB");
     $daoTestPrivilege->query("CREATE TEMPORARY TABLE import_job_permission_two(test int) ENGINE=InnoDB");
     $daoTestPrivilege->query("DROP TABLE IF EXISTS import_job_permission_one, import_job_permission_two");
     CRM_Core_Error::setCallback();
     if ($daoTestPrivilege->_lastError) {
         CRM_Core_Error::fatal(ts('Database Configuration Error: Insufficient permissions. Import requires that the CiviCRM database user has permission to create temporary tables. Contact your site administrator for assistance.'));
     }
     $this->_dataSourceIsValid = false;
     $this->_dataSource = CRM_Utils_Request::retrieve('dataSource', 'String', CRM_Core_DAO::$_nullObject);
     $this->_params = $this->controller->exportValues($this->_name);
     if (!$this->_dataSource) {
         //considering dataSource as base criteria instead of hidden_dataSource.
         $this->_dataSource = CRM_Utils_Array::value('dataSource', $_POST, CRM_Utils_Array::value('dataSource', $this->_params));
         $this->assign('showOnlyDataSourceFormPane', false);
     } else {
         $this->assign('showOnlyDataSourceFormPane', true);
     }
     if (strpos($this->_dataSource, 'CRM_Import_DataSource_') === 0) {
         $this->_dataSourceIsValid = true;
         $this->assign('showDataSourceFormPane', true);
         $dataSourcePath = split('_', $this->_dataSource);
         $templateFile = "CRM/Import/Form/" . $dataSourcePath[3] . ".tpl";
         $this->assign('dataSourceFormTemplateFile', $templateFile);
     }
 }
 /**
  * Set variables up before form is built.
  */
 public function preProcess()
 {
     //Test database user privilege to create table(Temporary) CRM-4725
     $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
     $daoTestPrivilege = new CRM_Core_DAO();
     $daoTestPrivilege->query("CREATE TEMPORARY TABLE import_job_permission_one(test int) ENGINE=InnoDB");
     $daoTestPrivilege->query("CREATE TEMPORARY TABLE import_job_permission_two(test int) ENGINE=InnoDB");
     $daoTestPrivilege->query("DROP TEMPORARY TABLE IF EXISTS import_job_permission_one, import_job_permission_two");
     unset($errorScope);
     if ($daoTestPrivilege->_lastError) {
         CRM_Core_Error::fatal(ts('Database Configuration Error: Insufficient permissions. Import requires that the CiviCRM database user has permission to create temporary tables. Contact your site administrator for assistance.'));
     }
     $results = array();
     $config = CRM_Core_Config::singleton();
     $handler = opendir($config->uploadDir);
     $errorFiles = array('sqlImport.errors', 'sqlImport.conflicts', 'sqlImport.duplicates', 'sqlImport.mismatch');
     // check for post max size avoid when called twice
     $snippet = CRM_Utils_Array::value('snippet', $_GET, 0);
     if (empty($snippet)) {
         CRM_Utils_Number::formatUnitSize(ini_get('post_max_size'), TRUE);
     }
     while ($file = readdir($handler)) {
         if ($file != '.' && $file != '..' && in_array($file, $errorFiles) && !is_writable($config->uploadDir . $file)) {
             $results[] = $file;
         }
     }
     closedir($handler);
     if (!empty($results)) {
         CRM_Core_Error::fatal(ts('<b>%1</b> file(s) in %2 directory are not writable. Listed file(s) might be used during the import to log the errors occurred during Import process. Contact your site administrator for assistance.', array(1 => implode(', ', $results), 2 => $config->uploadDir)));
     }
     $this->_dataSourceIsValid = FALSE;
     $this->_dataSource = CRM_Utils_Request::retrieve('dataSource', 'String', CRM_Core_DAO::$_nullObject, FALSE, NULL, 'GET');
     $this->_params = $this->controller->exportValues($this->_name);
     if (!$this->_dataSource) {
         //considering dataSource as base criteria instead of hidden_dataSource.
         $this->_dataSource = CRM_Utils_Array::value('dataSource', $_POST, CRM_Utils_Array::value('dataSource', $this->_params));
         $this->assign('showOnlyDataSourceFormPane', FALSE);
     } else {
         $this->assign('showOnlyDataSourceFormPane', TRUE);
     }
     $dataSources = $this->_getDataSources();
     if ($this->_dataSource && isset($dataSources[$this->_dataSource])) {
         $this->_dataSourceIsValid = TRUE;
         $this->assign('showDataSourceFormPane', TRUE);
         $dataSourcePath = explode('_', $this->_dataSource);
         $templateFile = "CRM/Contact/Import/Form/" . $dataSourcePath[3] . ".tpl";
         $this->assign('dataSourceFormTemplateFile', $templateFile);
     } elseif ($this->_dataSource) {
         throw new \CRM_Core_Exception("Invalid data source");
     }
 }
 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')));
 }
 /** 
  * Function to set variables up before form is built 
  *                                                           
  * @return void 
  * @access public 
  */
 public function preProcess()
 {
     //Test database user privilege to create table(Temporary) CRM-4725
     CRM_Core_Error::ignoreException();
     $daoTestPrivilege = new CRM_Core_DAO();
     $daoTestPrivilege->query("CREATE TEMPORARY TABLE import_job_permission_one(test int) ENGINE=InnoDB");
     $daoTestPrivilege->query("CREATE TEMPORARY TABLE import_job_permission_two(test int) ENGINE=InnoDB");
     $daoTestPrivilege->query("DROP TABLE IF EXISTS import_job_permission_one, import_job_permission_two");
     CRM_Core_Error::setCallback();
     if ($daoTestPrivilege->_lastError) {
         CRM_Core_Error::fatal(ts('Database Configuration Error: Insufficient permissions. Import requires that the CiviCRM database user has permission to create temporary tables. Contact your site administrator for assistance.'));
     }
     $results = array();
     $config = CRM_Core_Config::singleton();
     $handler = opendir($config->uploadDir);
     $errorFiles = array('sqlImport.errors', 'sqlImport.conflicts', 'sqlImport.duplicates', 'sqlImport.mismatch');
     while ($file = readdir($handler)) {
         if ($file != '.' && $file != '..' && in_array($file, $errorFiles) && !is_writable($config->uploadDir . $file)) {
             $results[] = $file;
         }
     }
     closedir($handler);
     if (!empty($results)) {
         CRM_Core_Error::fatal(ts('<b>%1</b> file(s) in %2 directory are not writable. Listed file(s) might be used during the import to log the errors occurred during Import process. Contact your site administrator for assistance.', array(1 => implode(', ', $results), 2 => $config->uploadDir)));
     }
     $this->_dataSourceIsValid = false;
     $this->_dataSource = CRM_Utils_Request::retrieve('dataSource', 'String', CRM_Core_DAO::$_nullObject);
     $this->_params = $this->controller->exportValues($this->_name);
     if (!$this->_dataSource) {
         //considering dataSource as base criteria instead of hidden_dataSource.
         $this->_dataSource = CRM_Utils_Array::value('dataSource', $_POST, CRM_Utils_Array::value('dataSource', $this->_params));
         $this->assign('showOnlyDataSourceFormPane', false);
     } else {
         $this->assign('showOnlyDataSourceFormPane', true);
     }
     if (strpos($this->_dataSource, 'CRM_Import_DataSource_') === 0) {
         $this->_dataSourceIsValid = true;
         $this->assign('showDataSourceFormPane', true);
         $dataSourcePath = explode('_', $this->_dataSource);
         $templateFile = "CRM/Import/Form/" . $dataSourcePath[3] . ".tpl";
         $this->assign('dataSourceFormTemplateFile', $templateFile);
     }
 }
 /**
  * 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;
 }
 /**  
  * 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();
 }
Exemple #9
0
 /**
  * @param int $newState
  * @void
  */
 public function finish($newState = self::F_DONE)
 {
     if ($this->state == self::F_FORCED) {
         return;
     }
     assert('$this->state === self::F_ACTIVE');
     $this->state = $newState;
     if ($this->doCommit) {
         $this->invokeCallbacks(\CRM_Core_Transaction::PHASE_PRE_COMMIT);
         if ($this->commitStmt) {
             $this->dao->query($this->commitStmt);
         }
         $this->invokeCallbacks(\CRM_Core_Transaction::PHASE_POST_COMMIT);
     } else {
         $this->invokeCallbacks(\CRM_Core_Transaction::PHASE_PRE_ROLLBACK);
         if ($this->rollbackStmt) {
             $this->dao->query($this->rollbackStmt);
         }
         $this->invokeCallbacks(\CRM_Core_Transaction::PHASE_POST_ROLLBACK);
     }
 }
 /**
  * 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;
 }
Exemple #11
0
 /**
  * @param bool $view
  * @param bool $trigger
  *
  * @return bool
  */
 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE)
 {
     // test for create view and trigger permissions and if allowed, add the option to go multilingual
     // and logging
     // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
     $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
     $dao = new CRM_Core_DAO();
     if ($view) {
         $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
         if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
             return FALSE;
         }
     }
     if ($trigger) {
         $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
         if (PEAR::getStaticProperty('DB_DataObject', 'lastError') || is_a($result, 'DB_Error')) {
             if ($view) {
                 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
             }
             return FALSE;
         }
         $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
         if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
             if ($view) {
                 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
             }
             return FALSE;
         }
     }
     if ($view) {
         $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
         if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
             return FALSE;
         }
     }
     return TRUE;
 }
Exemple #12
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;
     }
 }
 /**
  * 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;
 }
 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);
 }
 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");
 }
 /**
  * @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);
     }
 }
Exemple #18
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;
 }
 function postProcess()
 {
     $values = $this->exportValues();
     $table = $values['table'];
     $field = $values['field'];
     // validate table and field
     if (!isset($this->_structure[$table][$field])) {
         CRM_Core_Error::fatal("{$table}.{$field} is not internationalized.");
     }
     $cols = array();
     $params = array(array($values['id'], 'Int'));
     $i = 1;
     foreach ($this->_locales as $locale) {
         $cols[] = "{$field}_{$locale} = %{$i}";
         $params[$i] = array($values["{$field}_{$locale}"], 'String');
         $i++;
     }
     $query = "UPDATE {$table} SET " . implode(', ', $cols) . " WHERE id = %0";
     $dao = new CRM_Core_DAO();
     $query = CRM_Core_DAO::composeQuery($query, $params, TRUE);
     $dao->query($query, FALSE);
     CRM_Utils_System::civiExit();
 }
 /**
  * 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;
     }
 }
 /**
  * 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;
 }
 public function fillTable()
 {
     // get the list of queries handy
     $tableQueries = $this->tableQuery();
     if ($this->params && !$this->noRules) {
         $tempTableQuery = "CREATE TEMPORARY TABLE dedupe (id1 int, weight int, UNIQUE UI_id1 (id1)) ENGINE=MyISAM";
         $insertClause = "INSERT INTO dedupe (id1, weight)";
         $groupByClause = "GROUP BY id1";
         $dupeCopyJoin = " JOIN dedupe_copy ON dedupe_copy.id1 = t1.column WHERE ";
     } else {
         $tempTableQuery = "CREATE TEMPORARY TABLE dedupe (id1 int, id2 int, weight int, UNIQUE UI_id1_id2 (id1, id2)) ENGINE=MyISAM";
         $insertClause = "INSERT INTO dedupe (id1, id2, weight)";
         $groupByClause = "GROUP BY id1, id2";
         $dupeCopyJoin = " JOIN dedupe_copy ON dedupe_copy.id1 = t1.column AND dedupe_copy.id2 = t2.column WHERE ";
     }
     $patternColumn = '/t1.(\\w+)/';
     $exclWeightSum = array();
     // create temp table
     $dao = new CRM_Core_DAO();
     $dao->query($tempTableQuery);
     CRM_Utils_Hook::dupeQuery($this, 'table', $tableQueries);
     while (!empty($tableQueries)) {
         list($isInclusive, $isDie) = self::isQuerySetInclusive($tableQueries, $this->threshold, $exclWeightSum);
         if ($isInclusive) {
             // order queries by table count
             self::orderByTableCount($tableQueries);
             $weightSum = array_sum($exclWeightSum);
             $searchWithinDupes = !empty($exclWeightSum) ? 1 : 0;
             while (!empty($tableQueries)) {
                 // extract the next query ( and weight ) to be executed
                 $fieldWeight = array_keys($tableQueries);
                 $fieldWeight = $fieldWeight[0];
                 $query = array_shift($tableQueries);
                 if ($searchWithinDupes) {
                     // get prepared to search within already found dupes if $searchWithinDupes flag is set
                     $dao->query("DROP TEMPORARY TABLE IF EXISTS dedupe_copy");
                     $dao->query("CREATE TEMPORARY TABLE dedupe_copy SELECT * FROM dedupe WHERE weight >= {$weightSum}");
                     $dao->free();
                     preg_match($patternColumn, $query, $matches);
                     $query = str_replace(' WHERE ', str_replace('column', $matches[1], $dupeCopyJoin), $query);
                 }
                 $searchWithinDupes = 1;
                 // construct and execute the intermediate query
                 $query = "{$insertClause} {$query} {$groupByClause} ON DUPLICATE KEY UPDATE weight = weight + VALUES(weight)";
                 $dao->query($query);
                 // FIXME: we need to be more acurate with affected rows, especially for insert vs duplicate insert.
                 // And that will help optimize further.
                 $affectedRows = $dao->affectedRows();
                 $dao->free();
                 // In an inclusive situation, failure of any query means no further processing -
                 if ($affectedRows == 0) {
                     // reset to make sure no further execution is done.
                     $tableQueries = array();
                     break;
                 }
                 $weightSum = substr($fieldWeight, strrpos($fieldWeight, '.') + 1) + $weightSum;
             }
             // An exclusive situation -
         } elseif (!$isDie) {
             // since queries are already sorted by weights, we can continue as is
             $fieldWeight = array_keys($tableQueries);
             $fieldWeight = $fieldWeight[0];
             $query = array_shift($tableQueries);
             $query = "{$insertClause} {$query} {$groupByClause} ON DUPLICATE KEY UPDATE weight = weight + VALUES(weight)";
             $dao->query($query);
             if ($dao->affectedRows() >= 1) {
                 $exclWeightSum[] = substr($fieldWeight, strrpos($fieldWeight, '.') + 1);
             }
             $dao->free();
         } else {
             // its a die situation
             break;
         }
     }
 }
 /**
  * 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;
 }
 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();
 }
Exemple #25
0
 /**
  * Error reporting mechanism.
  *
  * @param string $message
  *   Error Message.
  * @param int $code
  *   Error Code.
  * @param CRM_Core_DAO $dao
  *   A data access object on which we perform a rollback if non - empty.
  */
 public function error($message, $code = NULL, $dao = NULL)
 {
     if ($dao) {
         $dao->query('ROLLBACK');
     }
     $error = CRM_Core_Error::singleton();
     $error->push($code, $message);
 }
Exemple #26
0
 /**
  * Process the form when submitted
  *
  * @return void
  * @access public
  */
 public function postProcess()
 {
     // step 1: copy and create dstField and column
     require_once 'CRM/Core/BAO/CustomField.php';
     $field = new CRM_Core_DAO_CustomField();
     $field->id = $this->_srcFID;
     if (!$field->find(true)) {
         CRM_Core_Error::fatal();
     }
     // now change the field group ID and save it, also unset the id
     unset($field->id);
     // step 2: copy data from srcColumn to dstColumn
     $query = "\nINSERT INTO {$dstTable} ( {$entityID}, {$dstColumn} )\nSELECT {$entityID}, {$srcColumn}\nFROM   {$srcTable}\nON DUPLICATE KEY UPDATE {$dstColumn} = {$srcColumn}";
     CRM_Core_DAO::query($query, CRM_Core_DAO::$_nullArray);
     // step 3: remove srcField (which should also delete the srcColumn
     require_once 'CRM/Core/BAO/CustomField.php';
     $field = new CRM_Core_DAO_CustomField();
     $field->id = $this->_srcFID;
     CRM_Core_BAO_CustomField::deleteField($field);
 }
Exemple #27
0
 /**
  * Used during case component enablement and during ugprade
  */
 static function createCaseViews()
 {
     $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
     $dao = new CRM_Core_DAO();
     $sql = self::createCaseViewsQuery('upcoming');
     $dao->query($sql);
     if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
         return FALSE;
     }
     // Above error doesn't get caught?
     $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_upcoming");
     if (is_null($doublecheck)) {
         return FALSE;
     }
     $sql = self::createCaseViewsQuery('recent');
     $dao->query($sql);
     if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
         return FALSE;
     }
     // Above error doesn't get caught?
     $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_recent");
     if (is_null($doublecheck)) {
         return FALSE;
     }
     return TRUE;
 }
 /**
  * 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);
         }
     }
 }
 static function createIndexes(&$tables, $createIndexPrefix = 'index', $substrLenghts = array())
 {
     $queries = array();
     require_once 'CRM/Core/DAO/Domain.php';
     $domain = new CRM_Core_DAO_Domain();
     $domain->find(TRUE);
     $locales = explode(CRM_Core_DAO::VALUE_SEPARATOR, $domain->locales);
     // if we're multilingual, cache the information on internationalised fields
     static $columns = NULL;
     if (!CRM_Utils_System::isNull($locales) and $columns === NULL) {
         $columns = CRM_Core_I18n_SchemaStructure::columns();
     }
     foreach ($tables as $table => $fields) {
         $query = "SHOW INDEX FROM {$table}";
         $dao = CRM_Core_DAO::executeQuery($query);
         $currentIndexes = array();
         while ($dao->fetch()) {
             $currentIndexes[] = $dao->Key_name;
         }
         // now check for all fields if the index exists
         foreach ($fields as $field) {
             // handle indices over substrings, CRM-6245
             // $lengthName is appended to index name, $lengthSize is the field size modifier
             $lengthName = isset($substrLenghts[$table][$field]) ? "_{$substrLenghts[$table][$field]}" : '';
             $lengthSize = isset($substrLenghts[$table][$field]) ? "({$substrLenghts[$table][$field]})" : '';
             $names = array("index_{$field}{$lengthName}", "FK_{$table}_{$field}{$lengthName}", "UI_{$field}{$lengthName}", "{$createIndexPrefix}_{$field}{$lengthName}");
             // skip to the next $field if one of the above $names exists; handle multilingual for CRM-4126
             foreach ($names as $name) {
                 $regex = '/^' . preg_quote($name) . '(_[a-z][a-z]_[A-Z][A-Z])?$/';
                 if (preg_grep($regex, $currentIndexes)) {
                     continue 2;
                 }
             }
             // the index doesn't exist, so create it
             // if we're multilingual and the field is internationalised, do it for every locale
             if (!CRM_Utils_System::isNull($locales) and isset($columns[$table][$field])) {
                 foreach ($locales as $locale) {
                     $queries[] = "CREATE INDEX {$createIndexPrefix}_{$field}{$lengthName}_{$locale} ON {$table} ({$field}_{$locale}{$lengthSize})";
                 }
             } else {
                 $queries[] = "CREATE INDEX {$createIndexPrefix}_{$field}{$lengthName} ON {$table} ({$field}{$lengthSize})";
             }
         }
     }
     // run the queries without i18n-rewriting
     $dao = new CRM_Core_DAO();
     foreach ($queries as $query) {
         $dao->query($query, FALSE);
     }
 }
Exemple #30
0
 static function createIndexes(&$tables, $createIndexPrefix = 'index')
 {
     $queries = array();
     $domain = new CRM_Core_DAO_Domain();
     $domain->find(true);
     $locales = explode(CRM_Core_DAO::VALUE_SEPARATOR, $domain->locales);
     // if we're multilingual, cache the information on internationalised fields
     static $columns = null;
     require_once 'CRM/Utils/System.php';
     if (!CRM_Utils_System::isNull($locales) and $columns === null) {
         require_once 'CRM/Core/I18n/SchemaStructure.php';
         $columns =& CRM_Core_I18n_SchemaStructure::columns();
     }
     foreach ($tables as $table => $fields) {
         $query = "SHOW INDEX FROM {$table}";
         $dao = CRM_Core_DAO::executeQuery($query);
         $currentIndexes = array();
         while ($dao->fetch()) {
             $currentIndexes[] = $dao->Key_name;
         }
         // now check for all fields if the index exists
         foreach ($fields as $field) {
             $names = array("index_{$field}", "FK_{$table}_{$field}", "UI_{$field}", "{$createIndexPrefix}_{$field}");
             // skip to the next $field if one of the above $names exists; handle multilingual for CRM-4126
             foreach ($names as $name) {
                 $regex = '/^' . preg_quote($name) . '(_[a-z][a-z]_[A-Z][A-Z])?$/';
                 if (preg_grep($regex, $currentIndexes)) {
                     continue 2;
                 }
             }
             // the index doesn't exist, so create it
             // if we're multilingual and the field is internationalised, do it for every locale
             if (!CRM_Utils_System::isNull($locales) and isset($columns[$table][$field])) {
                 foreach ($locales as $locale) {
                     $queries[] = "CREATE INDEX {$createIndexPrefix}_{$field}_{$locale} ON {$table} ({$field}_{$locale})";
                 }
             } else {
                 $queries[] = "CREATE INDEX {$createIndexPrefix}_{$field} ON {$table} ({$field})";
             }
         }
     }
     // run the queries without i18n-rewriting
     $dao = new CRM_Core_DAO();
     foreach ($queries as $query) {
         $dao->query($query, false);
     }
 }