Example #1
0
 /**
  * Given a permission string, check for access requirements
  *
  * @param string $str
  *   The permission to check.
  *
  * @return bool
  *   true if yes, else false
  */
 public function check($str)
 {
     $config = CRM_Core_Config::singleton();
     $translated = $this->translateJoomlaPermission($str);
     if ($translated === CRM_Core_Permission::ALWAYS_DENY_PERMISSION) {
         return FALSE;
     }
     if ($translated === CRM_Core_Permission::ALWAYS_ALLOW_PERMISSION) {
         return TRUE;
     }
     // ensure that we are running in a joomla context
     // we've not yet figured out how to bootstrap joomla, so we should
     // not execute hooks if joomla is not loaded
     if (defined('_JEXEC')) {
         $user = JFactory::getUser();
         $api_key = CRM_Utils_Request::retrieve('api_key', 'String', $store, FALSE, NULL, 'REQUEST');
         // If we are coming from REST we don't have a user but we do have the api_key for a user.
         if ($user->id === 0 && !is_null($api_key)) {
             // This is a codeblock copied from /Civicrm/Utils/REST
             $uid = NULL;
             if (!$uid) {
                 $store = NULL;
                 $contact_id = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key');
                 if ($contact_id) {
                     $uid = CRM_Core_BAO_UFMatch::getUFId($contact_id);
                 }
                 $user = JFactory::getUser($uid);
             }
         }
         return $user->authorise($translated[0], $translated[1]);
     } else {
         return FALSE;
     }
 }
function civicrm_invoke()
{
    civicrm_init();
    plugin_init();
    $user = JFactory::getUser();
    /* bypass synchronize if running upgrade
     * to avoid any serious non-recoverable error
     * which might hinder the upgrade process.
     */
    require_once 'CRM/Utils/Array.php';
    if (CRM_Utils_Array::value('task', $_REQUEST) != 'civicrm/upgrade') {
        require_once 'CRM/Core/BAO/UFMatch.php';
        CRM_Core_BAO_UFMatch::synchronize($user, FALSE, 'Joomla', 'Individual', TRUE);
    }
    require_once 'CRM/Utils/System/Joomla.php';
    CRM_Utils_System_Joomla::addHTMLHead(NULL, TRUE);
    if (isset($_GET['task'])) {
        $args = explode('/', trim($_GET['task']));
    } else {
        $_GET['task'] = 'civicrm/dashboard';
        $_GET['reset'] = 1;
        $args = array('civicrm', 'dashboard');
    }
    CRM_Core_Invoke::invoke($args);
}
function civicrm_invoke()
{
    civicrm_init();
    global $my;
    require_once 'CRM/Core/BAO/UFMatch.php';
    CRM_Core_BAO_UFMatch::synchronize($my, false, 'Mambo');
    $args = explode('/', trim($_GET['task']));
    CRM_Core_Invoke::invoke($args);
}
 function onUserAfterDelete($user, $succes, $msg)
 {
     $app = JFactory::getApplication();
     // Instantiate CiviCRM
     require_once JPATH_ROOT . '/administrator/components/com_civicrm/civicrm.settings.php';
     require_once 'CRM/Core/Config.php';
     $config = CRM_Core_Config::singleton();
     // Delete UFMatch
     CRM_Core_BAO_UFMatch::deleteUser($user['id']);
 }
Example #5
0
 /**
  * Function for synchronizing cms users with CiviCRM contacts
  *  
  * @param NULL
  * 
  * @return void
  * 
  * @static
  * @access public
  */
 static function synchronize()
 {
     //start of schronization code
     $config =& CRM_Core_Config::singleton();
     CRM_Core_Error::ignoreException();
     $db_uf =& self::dbHandle($config);
     if ($config->userFramework == 'Drupal') {
         $id = 'uid';
         $mail = 'mail';
         $name = 'name';
     } else {
         if ($config->userFramework == 'Joomla') {
             $id = 'id';
             $mail = 'email';
             $name = 'name';
         } else {
             CRM_Core_Error::fatal("CMS user creation not supported for this framework");
         }
     }
     set_time_limit(300);
     $sql = "SELECT {$id}, {$mail}, {$name} FROM {$config->userFrameworkUsersTableName} where {$mail} != ''";
     $query = $db_uf->query($sql);
     $user = new StdClass();
     $uf = $config->userFramework;
     $contactCount = 0;
     $contactCreated = 0;
     $contactMatching = 0;
     while ($row = $query->fetchRow(DB_FETCHMODE_ASSOC)) {
         $user->{$id} = $row[$id];
         $user->{$mail} = $row[$mail];
         $user->{$name} = $row[$name];
         $contactCount++;
         if ($match = CRM_Core_BAO_UFMatch::synchronizeUFMatch($user, $row[$id], $row[$mail], $uf, 1)) {
             $contactCreated++;
         } else {
             $contactMatching++;
         }
         if (is_object($match)) {
             $match->free();
         }
     }
     $db_uf->disconnect();
     //end of schronization code
     $status = ts('Synchronize Users to Contacts completed.');
     $status .= ' ' . ts('Checked one user record.', array('count' => $contactCount, 'plural' => 'Checked %count user records.'));
     if ($contactMatching) {
         $status .= ' ' . ts('Found one matching contact record.', array('count' => $contactMatching, 'plural' => 'Found %count matching contact records.'));
     }
     $status .= ' ' . ts('Created one new contact record.', array('count' => $contactCreated, 'plural' => 'Created %count new contact records.'));
     CRM_Core_Session::setStatus($status, true);
     CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/admin', 'reset=1'));
 }
Example #6
0
 /**
  * Create CMS user using Profile.
  *
  * @param array $params
  * @param string $mail
  *   Email id for cms user.
  *
  * @return int
  *   contact id that has been created
  */
 public static function create(&$params, $mail)
 {
     $config = CRM_Core_Config::singleton();
     $ufID = $config->userSystem->createUser($params, $mail);
     //if contact doesn't already exist create UF Match
     if ($ufID !== FALSE && isset($params['contactID'])) {
         // create the UF Match record
         $ufmatch['uf_id'] = $ufID;
         $ufmatch['contact_id'] = $params['contactID'];
         $ufmatch['uf_name'] = $params[$mail];
         CRM_Core_BAO_UFMatch::create($ufmatch);
     }
     return $ufID;
 }
 /**
  * Function for synchronizing drupal users with CiviCRM contacts
  *  
  * @param NULL
  * 
  * @return void
  * 
  * @static
  * @access public
  */
 function synchronize()
 {
     //start of schronization code
     $config =& CRM_Core_Config::singleton();
     /**
      * Update the next line with the correct Drupal database user, password, db_server and db name
      * for your Drupal installation.
      */
     $db_drupal = DB::connect($config->userFrameworkDSN);
     if (DB::isError($db_drupal)) {
         die("Cannot connect to UF db via {$dsn}, " . $db_drupal->getMessage());
     }
     if ($config->userFramework == 'Drupal') {
         $id = 'uid';
         $mail = 'mail';
     } else {
         if ($config->userFramework == 'Mambo') {
             $id = 'id';
             $mail = 'email';
         } else {
             die("Unknown user framework");
         }
     }
     $sql = "SELECT {$id}, {$mail} FROM {$config->userFrameworkUsersTableName} where {$mail} != ''";
     $query = $db_drupal->query($sql);
     $user = null;
     $uf = 'Drupal';
     $contactCount = 0;
     $contactCreated = 0;
     $contactMatching = 0;
     while ($row = $query->fetchRow(DB_FETCHMODE_ASSOC)) {
         $contactCount++;
         if (CRM_Core_BAO_UFMatch::synchronizeUFMatch($user, $row[$id], $row[$mail], $uf, 1)) {
             $contactCreated++;
         } else {
             $contactMatching++;
         }
     }
     $db_drupal->disconnect();
     //end of schronization code
     $status = ts('Synchronize Users to Contacts completed.');
     $status .= ' ' . ts('Checked one user record.', array('count' => $contactCount, 'plural' => 'Checked %count user records.'));
     if ($contactMatching) {
         $status .= ' ' . ts('Found one matching contact record.', array('count' => $contactMatching, 'plural' => 'Found %count matching contact records.'));
     }
     $status .= ' ' . ts('Created one new contact record.', array('count' => $contactCreated, 'plural' => 'Created %count new contact records.'));
     CRM_Core_Session::setStatus($status);
     CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/admin', 'reset=1'));
 }
Example #8
0
 static function contactID($ufID)
 {
     $contactID = CRM_Core_BAO_UFMatch::getContactId($ufID);
     if ($contactID) {
         return $contactID;
     }
     // else synchronize contact for this user
     $account = user_load($ufID);
     CRM_Core_BAO_UFMatch::synchronizeUFMatch($account, $ufID, $account->mail, 'Drupal');
     $contactID = CRM_Core_BAO_UFMatch::getContactId($ufID);
     if (!$contactID) {
         CRM_Core_Error::fatal();
     }
     return $contactID;
 }
Example #9
0
function civicrm_invoke()
{
    civicrm_init();
    plugin_init();
    $user = JFactory::getUser();
    require_once 'CRM/Core/BAO/UFMatch.php';
    CRM_Core_BAO_UFMatch::synchronize($user, false, 'Joomla', 'Individual');
    if (isset($_GET['task'])) {
        $args = explode('/', trim($_GET['task']));
        CRM_Core_Invoke::invoke($args);
    } else {
        $_GET['task'] = 'civicrm/dashboard';
        $_GET['reset'] = 1;
        $args = array('civicrm', 'dashboard');
        CRM_Core_Invoke::invoke($args);
    }
}
Example #10
0
 static function groupContact($groupID, $contactIDs, $op)
 {
     $config = CRM_Core_Config::singleton();
     $ogID = CRM_Bridge_OG_Utils::ogID($groupID, FALSE);
     if (!$ogID) {
         return;
     }
     foreach ($contactIDs as $contactID) {
         $drupalID = CRM_Core_BAO_UFMatch::getUFId($contactID);
         if ($drupalID) {
             if ($op == 'add') {
                 $group_membership = $config->userSystem->og_membership_create($ogID, $drupalID);
             } else {
                 $group_membership = $config->userSystem->og_membership_delete($ogID, $drupalID);
             }
         }
     }
 }
Example #11
0
function civicrm_invoke()
{
    civicrm_init();
    // check and ensure that we have a valid session
    if (!empty($_POST)) {
        // the session should not be empty
        // however for standalone forms, it will not have any CiviCRM variables in the
        // session either, so dont check for it
        if (count($_SESSION) <= 1) {
            require_once 'CRM/Utils/System.php';
            $config =& CRM_Core_Config::singleton();
            CRM_Utils_System::redirect($config->userFrameworkBaseURL);
        }
    }
    // add all the values from the itemId param
    // overrride the GET values if conflict
    if (CRM_Utils_Array::value('Itemid', $_GET)) {
        $component =& JComponentHelper::getComponent('com_civicrm');
        $menu =& JSite::getMenu();
        $item = $menu->getItems('componentid', $component->id, true);
        $params = $menu->getParams($_GET['Itemid']);
        $args = array('task', 'id', 'gid', 'reset', 'pageId', 'action');
        foreach ($args as $a) {
            $val = $params->get($a, null);
            if ($val !== null) {
                $_GET[$a] = $val;
            }
        }
    }
    $task = CRM_Utils_Array::value('task', $_GET, '');
    $args = explode('/', trim($task));
    // check permission
    if (!civicrm_check_permission($args)) {
        echo "You do not have permission to execute this url.";
        return;
    }
    require_once 'CRM/Utils/System/Joomla.php';
    CRM_Utils_System_Joomla::addHTMLHead(null, true);
    $user = JFactory::getUser();
    require_once 'CRM/Core/BAO/UFMatch.php';
    CRM_Core_BAO_UFMatch::synchronize($user, false, 'Joomla', 'Individual');
    CRM_Core_Invoke::invoke($args);
}
Example #12
0
function run()
{
    $openid = getOpenIDURL();
    $consumer = getConsumer();
    // Begin the OpenID authentication process.
    $auth_request = $consumer->begin($openid);
    // No auth request means we can't begin OpenID.
    if (!$auth_request) {
        // check for new install, if no, go to index, else goto new-install page
        require_once 'CRM/Core/BAO/UFMatch.php';
        $contactIds = CRM_Core_BAO_UFMatch::getContactIDs();
        if (count($contactIds) > 0) {
            displayError("Authentication error; not a valid OpenID.");
        } else {
            $session =& CRM_Core_Session::singleton();
            $session->set('new_install', true);
            include 'new_install.html';
            exit(1);
        }
    }
    $sreg_request = Auth_OpenID_SRegRequest::build(array('nickname'), array('fullname', 'email'));
    if ($sreg_request) {
        $auth_request->addExtension($sreg_request);
    }
    $policy_uris = null;
    if (isset($_REQUEST['policies'])) {
        $policy_uris = $_REQUEST['policies'];
    }
    $pape_request = new Auth_OpenID_PAPE_Request($policy_uris);
    if ($pape_request) {
        $auth_request->addExtension($pape_request);
    }
    $redirect_url = $auth_request->redirectURL(getTrustRoot(), getReturnTo());
    // If the redirect URL can't be built, display an error
    // message.
    if (Auth_OpenID::isFailure($redirect_url)) {
        displayError("Could not redirect to server: " . $redirect_url->message);
    } else {
        // Send redirect.
        header("Location: " . $redirect_url);
        exit(2);
    }
}
function civicrm_invoke()
{
    civicrm_init();
    // check and ensure that we have a valid session
    if (!empty($_POST)) {
        // the session should not be empty
        // however for standalone forms, it will not have any CiviCRM variables in the
        // session either, so dont check for it
        if (count($_SESSION) <= 1) {
            require_once 'CRM/Utils/System.php';
            $config = CRM_Core_Config::singleton();
            CRM_Utils_System::redirect($config->userFrameworkBaseURL);
        }
    }
    // add all the values from the itemId param
    // overrride the GET values if conflict
    if (CRM_Utils_Array::value('Itemid', $_GET)) {
        $component = JComponentHelper::getComponent('com_civicrm');
        $menu = JSite::getMenu();
        $params = $menu->getParams($_GET['Itemid']);
        $args = array('task', 'id', 'gid', 'pageId', 'action', 'csid');
        $view = CRM_Utils_Array::value('view', $_GET);
        if ($view) {
            $args[] = 'reset';
        }
        foreach ($args as $a) {
            $val = $params->get($a, NULL);
            if ($val !== NULL && $view) {
                $_GET[$a] = $val;
            }
        }
    }
    $task = CRM_Utils_Array::value('task', $_GET, '');
    $args = explode('/', trim($task));
    require_once 'CRM/Utils/System/Joomla.php';
    CRM_Utils_System_Joomla::addHTMLHead(NULL, TRUE);
    $user = JFactory::getUser();
    require_once 'CRM/Core/BAO/UFMatch.php';
    CRM_Core_BAO_UFMatch::synchronize($user, FALSE, 'Joomla', 'Individual', TRUE);
    CRM_Core_Invoke::invoke($args);
}
 static function groupContact($groupID, $contactIDs, $op)
 {
     $ogID = CRM_Bridge_OG_Utils::ogID($groupID, FALSE);
     if (!$ogID) {
         return;
     }
     foreach ($contactIDs as $contactID) {
         $drupalID = CRM_Core_BAO_UFMatch::getUFId($contactID);
         if ($drupalID) {
             if ($op == 'add') {
                 $group_membership = og_membership_create($ogID, 'user', $drupalID, array('is_active' => 1));
                 $group_membership->save();
             } else {
                 $membership = og_get_group_membership($ogID, 'user', $drupalID);
                 if ($membership) {
                     og_membership_delete($membership->id);
                 }
             }
         }
     }
 }
Example #15
0
function invoke()
{
    $session =& CRM_Core_Session::singleton();
    $config =& CRM_Core_Config::singleton();
    // display error if any
    showError($session);
    $urlVar = $config->userFrameworkURLVar;
    require_once 'CRM/Core/Invoke.php';
    if ($session->get('userID') == null || $session->get('userID') == '') {
        if ($_GET[$urlVar] == "") {
            require_once "CRM/Core/BAO/UFMatch.php";
            if (CRM_Core_BAO_UFMatch::isEmptyTable() == false) {
                include 'login.html';
            } else {
                $session->set('new_install', true);
                include 'new_install.html';
            }
            exit(1);
        } else {
            $str = '';
            if ($session->get('new_install') !== true && $_GET[$urlVar] !== "civicrm/standalone/register") {
                $str = "<a href=\"{$config->userFrameworkBaseURL}\">Login here</a> if you have an account.\n";
            } elseif ($_GET[$urlVar] == "civicrm/standalone/register" && isset($_GET['reset'])) {
                // this is when user first registers with civicrm
                print "<head><style type=\"text/css\"> body {border: 1px #CCC solid;margin: 3em;padding: 1em 1em 1em 2em;} </style></head>\n";
            }
            print $str . CRM_Core_Invoke::invoke(explode('/', $_GET[$urlVar]));
        }
    } else {
        if ($_GET[$urlVar] == "") {
            print CRM_Core_Invoke::invoke(array("civicrm", "dashboard"));
        } else {
            print CRM_Core_Invoke::invoke(explode('/', $_GET[$urlVar]));
        }
    }
}
 /**
 * Authenticate the user against the wordpress db
 *
 * @param string $name     the user name
 * @param string $password the password for the above user name
 *
 * @return mixed false if no auth
 *               array(
    contactID, ufID, unique string ) if success
 * @access public
 * @static
 */
 function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL)
 {
     $config = CRM_Core_Config::singleton();
     if ($loadCMSBootstrap) {
         $config->userSystem->loadBootStrap($name, $password);
     }
     $user = wp_authenticate($name, $password);
     if (is_a($user, 'WP_Error')) {
         return FALSE;
     }
     // need to change this to make sure we matched only one row
     CRM_Core_BAO_UFMatch::synchronizeUFMatch($user->data, $user->data->ID, $user->data->user_email, 'WordPress');
     $contactID = CRM_Core_BAO_UFMatch::getContactId($user->data->ID);
     if (!$contactID) {
         return FALSE;
     }
     return array($contactID, $user->data->ID, mt_rand());
 }
Example #17
0
File: REST.php Project: kidaa30/yes
 /**
  * @return array|NULL
  *   NULL if execution should proceed; array if the response is already known
  */
 public function loadCMSBootstrap()
 {
     $requestParams = CRM_Utils_Request::exportValues();
     $q = CRM_Utils_array::value('q', $requestParams);
     $args = explode('/', $q);
     // Proceed with bootstrap for "?entity=X&action=Y"
     // Proceed with bootstrap for "?q=civicrm/X/Y" but not "?q=civicrm/ping"
     if (!empty($q)) {
         if (count($args) == 2 && $args[1] == 'ping') {
             return NULL;
             // this is pretty wonky but maybe there's some reason I can't see
         }
         if (count($args) != 3) {
             return self::error('ERROR: Malformed REST path');
         }
         if ($args[0] != 'civicrm') {
             return self::error('ERROR: Malformed REST path');
         }
         // Therefore we have reasonably well-formed "?q=civicrm/X/Y"
     }
     if (!CRM_Utils_System::authenticateKey(FALSE)) {
         // FIXME: At time of writing, this doesn't actually do anything because
         // authenticateKey abends, but that's a bad behavior which sends a
         // malformed response.
         return self::error('Failed to authenticate key');
     }
     $uid = NULL;
     if (!$uid) {
         $store = NULL;
         $api_key = CRM_Utils_Request::retrieve('api_key', 'String', $store, FALSE, NULL, 'REQUEST');
         if (empty($api_key)) {
             return self::error("FATAL: mandatory param 'api_key' (user key) missing");
         }
         $contact_id = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key');
         if ($contact_id) {
             $uid = CRM_Core_BAO_UFMatch::getUFId($contact_id);
         }
     }
     if ($uid) {
         CRM_Utils_System::loadBootStrap(array('uid' => $uid), TRUE, FALSE);
         return NULL;
     } else {
         return self::error('ERROR: No CMS user associated with given api-key');
     }
 }
Example #18
0
 /**
  * @inheritDoc
  */
 public function synchronizeUsers()
 {
     $config = CRM_Core_Config::singleton();
     if (PHP_SAPI != 'cli') {
         set_time_limit(300);
     }
     $id = 'ID';
     $mail = 'user_email';
     $uf = $config->userFramework;
     $contactCount = 0;
     $contactCreated = 0;
     $contactMatching = 0;
     global $wpdb;
     $wpUserIds = $wpdb->get_col("SELECT {$wpdb->users}.ID FROM {$wpdb->users}");
     foreach ($wpUserIds as $wpUserId) {
         $wpUserData = get_userdata($wpUserId);
         $contactCount++;
         if ($match = CRM_Core_BAO_UFMatch::synchronizeUFMatch($wpUserData, $wpUserData->{$id}, $wpUserData->{$mail}, $uf, 1, 'Individual', TRUE)) {
             $contactCreated++;
         } else {
             $contactMatching++;
         }
         if (is_object($match)) {
             $match->free();
         }
     }
     return array('contactCount' => $contactCount, 'contactMatching' => $contactMatching, 'contactCreated' => $contactCreated);
 }
Example #19
0
 function preProcess()
 {
     if (!CRM_Core_Permission::check('merge duplicate contacts')) {
         CRM_Core_Error::fatal(ts('You do not have access to this page'));
     }
     $rows = array();
     $cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
     $oid = CRM_Utils_Request::retrieve('oid', 'Positive', $this, TRUE);
     $flip = CRM_Utils_Request::retrieve('flip', 'Positive', $this, FALSE);
     $this->_rgid = $rgid = CRM_Utils_Request::retrieve('rgid', 'Positive', $this, FALSE);
     $this->_gid = $gid = CRM_Utils_Request::retrieve('gid', 'Positive', $this, FALSE);
     $this->_mergeId = CRM_Utils_Request::retrieve('mergeId', 'Positive', $this, FALSE);
     if (!CRM_Dedupe_BAO_Rule::validateContacts($cid, $oid)) {
         CRM_Core_Error::statusBounce(ts('The selected pair of contacts are marked as non duplicates. If these records should be merged, you can remove this exception on the <a href=\'%1\'>Dedupe Exceptions</a> page.', array(1 => CRM_Utils_System::url('civicrm/dedupe/exception', 'reset=1'))));
     }
     //load cache mechanism
     $contactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $cid, 'contact_type');
     $cacheKey = "merge {$contactType}";
     $cacheKey .= $rgid ? "_{$rgid}" : '_0';
     $cacheKey .= $gid ? "_{$gid}" : '_0';
     $join = "LEFT JOIN civicrm_dedupe_exception de ON ( pn.entity_id1 = de.contact_id1 AND\n                                                             pn.entity_id2 = de.contact_id2 )";
     $where = "de.id IS NULL";
     $pos = CRM_Core_BAO_PrevNextCache::getPositions($cacheKey, $cid, $oid, $this->_mergeId, $join, $where, $flip);
     // Block access if user does not have EDIT permissions for both contacts.
     if (!(CRM_Contact_BAO_Contact_Permission::allow($cid, CRM_Core_Permission::EDIT) && CRM_Contact_BAO_Contact_Permission::allow($oid, CRM_Core_Permission::EDIT))) {
         CRM_Utils_System::permissionDenied();
     }
     // get user info of main contact.
     $config = CRM_Core_Config::singleton();
     $config->doNotResetCache = 1;
     $viewUser = CRM_Core_Permission::check('access user profiles');
     $mainUfId = CRM_Core_BAO_UFMatch::getUFId($cid);
     $mainUser = NULL;
     if ($mainUfId) {
         // d6 compatible
         if ($config->userSystem->is_drupal == '1') {
             $mainUser = user_load($mainUfId);
         } elseif ($config->userFramework == 'Joomla') {
             $mainUser = JFactory::getUser($mainUfId);
         }
         $this->assign('mainUfId', $mainUfId);
         $this->assign('mainUfName', $mainUser ? $mainUser->name : NULL);
     }
     $flipUrl = CRM_Utils_System::url('civicrm/contact/merge', "reset=1&action=update&cid={$oid}&oid={$cid}&rgid={$rgid}&gid={$gid}");
     if (!$flip) {
         $flipUrl .= '&flip=1';
     }
     $this->assign('flip', $flipUrl);
     $this->prev = $this->next = NULL;
     foreach (array('prev', 'next') as $position) {
         if (!empty($pos[$position])) {
             if ($pos[$position]['id1'] && $pos[$position]['id2']) {
                 $urlParam = "reset=1&cid={$pos[$position]['id1']}&oid={$pos[$position]['id2']}&mergeId={$pos[$position]['mergeId']}&action=update";
                 if ($rgid) {
                     $urlParam .= "&rgid={$rgid}";
                 }
                 if ($gid) {
                     $urlParam .= "&gid={$gid}";
                 }
                 $this->{$position} = CRM_Utils_System::url('civicrm/contact/merge', $urlParam);
                 $this->assign($position, $this->{$position});
             }
         }
     }
     // get user info of other contact.
     $otherUfId = CRM_Core_BAO_UFMatch::getUFId($oid);
     $otherUser = NULL;
     if ($otherUfId) {
         // d6 compatible
         if ($config->userSystem->is_drupal == '1') {
             $otherUser = user_load($otherUfId);
         } elseif ($config->userFramework == 'Joomla') {
             $otherUser = JFactory::getUser($otherUfId);
         }
         $this->assign('otherUfId', $otherUfId);
         $this->assign('otherUfName', $otherUser ? $otherUser->name : NULL);
     }
     $cmsUser = $mainUfId && $otherUfId ? TRUE : FALSE;
     $this->assign('user', $cmsUser);
     $session = CRM_Core_Session::singleton();
     // context fixed.
     if ($rgid) {
         $urlParam = "reset=1&action=browse&rgid={$rgid}";
         if ($gid) {
             $urlParam .= "&gid={$gid}";
         }
         $session->pushUserContext(CRM_Utils_System::url('civicrm/contact/dedupefind', $urlParam));
     }
     // ensure that oid is not the current user, if so refuse to do the merge
     if ($session->get('userID') == $oid) {
         $display_name = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $oid, 'display_name');
         $message = ts('The contact record which is linked to the currently logged in user account - \'%1\' - cannot be deleted.', array(1 => $display_name));
         CRM_Core_Error::statusBounce($message);
     }
     $rowsElementsAndInfo = CRM_Dedupe_Merger::getRowsElementsAndInfo($cid, $oid);
     $main =& $rowsElementsAndInfo['main_details'];
     $other =& $rowsElementsAndInfo['other_details'];
     if ($main['contact_id'] != $cid) {
         CRM_Core_Error::fatal(ts('The main contact record does not exist'));
     }
     if ($other['contact_id'] != $oid) {
         CRM_Core_Error::fatal(ts('The other contact record does not exist'));
     }
     $subtypes = CRM_Contact_BAO_ContactType::subTypePairs(NULL, TRUE, '');
     $this->assign('contact_type', $main['contact_type']);
     if (!empty($main['contact_sub_type'])) {
         $this->assign('main_contact_subtype', CRM_Utils_Array::value('contact_sub_type', $subtypes[$main['contact_sub_type'][0]]));
     }
     if (!empty($other['contact_sub_type'])) {
         $this->assign('other_contact_subtype', CRM_Utils_Array::value('contact_sub_type', $subtypes[$other['contact_sub_type'][0]]));
     }
     $this->assign('main_name', $main['display_name']);
     $this->assign('other_name', $other['display_name']);
     $this->assign('main_cid', $main['contact_id']);
     $this->assign('other_cid', $other['contact_id']);
     $this->assign('rgid', $rgid);
     $this->_cid = $cid;
     $this->_oid = $oid;
     $this->_rgid = $rgid;
     $this->_contactType = $main['contact_type'];
     $this->addElement('checkbox', 'toggleSelect', NULL, NULL, array('onclick' => "return toggleCheckboxVals('move_',this);"));
     $this->assign('mainLocBlock', json_encode($rowsElementsAndInfo['main_loc_block']));
     $this->assign('rows', $rowsElementsAndInfo['rows']);
     $this->_locBlockIds = array('main' => $rowsElementsAndInfo['main_details']['loc_block_ids'], 'other' => $rowsElementsAndInfo['other_details']['loc_block_ids']);
     // add elements
     foreach ($rowsElementsAndInfo['elements'] as $element) {
         $this->addElement($element[0], $element[1], array_key_exists('2', $element) ? $element[2] : NULL, array_key_exists('3', $element) ? $element[3] : NULL, array_key_exists('4', $element) ? $element[4] : NULL, array_key_exists('5', $element) ? $element[5] : NULL);
     }
     // add related table elements
     foreach ($rowsElementsAndInfo['rel_table_elements'] as $relTableElement) {
         $element = $this->addElement($relTableElement[0], $relTableElement[1]);
         $element->setChecked(TRUE);
     }
     $this->assign('rel_tables', $rowsElementsAndInfo['rel_tables']);
     $this->assign('userContextURL', $session->readUserContext());
 }
Example #20
0
 static function getUserID($user)
 {
     //FIXME: look here a bit closer when testing UFMatch
     require_once 'CRM/Core/BAO/UFMatch.php';
     // this puts the appropriate values in the session, so
     // no need to return anything
     CRM_Core_BAO_UFMatch::synchronize($user, true, 'Standalone', 'Individual');
 }
Example #21
0
 /**
  * @inheritDoc
  */
 public function getUserRecordUrl($contactID)
 {
     $uid = CRM_Core_BAO_UFMatch::getUFId($contactID);
     if (CRM_Core_Session::singleton()->get('userID') == $contactID || CRM_Core_Permission::checkAnyPerm(array('cms:administer users'))) {
         return CRM_Core_Config::singleton()->userFrameworkBaseURL . "wp-admin/user-edit.php?user_id=" . $uid;
     }
 }
    if ($contact['values'][$row->civicrm_address_contact_id]['api.Phone.get']['count'] != 0) {
        foreach ($contact['values'][$row->civicrm_address_contact_id]['api.Phone.get']['values'] as $phones) {
            $phoneDiv .= "<a href='tel:" . $phones['phone'] . "'>" . $phones['phone'] . "</a><br/>";
        }
    }
    $tempArray = $areas = array();
    // Display Name
    if (!empty($contact['values'][$row->civicrm_address_contact_id]['api.CustomValue.get']['values']) && !empty($contact['values'][$row->civicrm_address_contact_id]['api.CustomValue.get']['values'][8]['latest'])) {
        $disName = $contact['values'][$row->civicrm_address_contact_id]['api.CustomValue.get']['values'][8]['latest'];
        $disName = "<a href='" . $contactLink . "'>" . $disName . "</a>";
    }
    if ($disName == '') {
        $disName = $displayName;
    }
    // Drupal Image
    $uid = CRM_Core_BAO_UFMatch::getUFId($row->civicrm_address_contact_id);
    if (!empty($uid)) {
        $user = user_load($uid);
    }
    $state = $row->civicrm_address_city;
    if (isset($row->civicrm_address_state_province_id)) {
        $state .= ', ' . CRM_Core_PseudoConstant::stateProvinceAbbreviation($row->civicrm_address_state_province_id);
    }
    // Distance
    if (isset($row->field_data_field_geo_code_1_field_geofield_distance)) {
        $distance = round($row->field_data_field_geo_code_1_field_geofield_distance, 1) . ' miles away';
    }
}
if ($memberships['membership_type_id'] == 5) {
    $cert_output = "<div class='views-field-views-conditional-1'><div class='mcfm_certified'><a href='/mediation/mcfm-certified-mediators' target='_blank'>\n    <img src='/sites/default/files/icons/mcfm-certified-member_38h.png' title='MCFM Certified Mediators have additional mediation experience. Click to learn more.'></a></div></div>";
} else {
 /**
  * Create contact.
  *
  * takes an associative array and creates a contact object and all the associated
  * derived objects (i.e. individual, location, email, phone etc)
  *
  * This function is invoked from within the web form layer and also from the api layer
  *
  * @param array $params
  *   (reference ) an assoc array of name/value pairs.
  * @param bool $fixAddress
  *   If we need to fix address.
  * @param bool $invokeHooks
  *   If we need to invoke hooks.
  *
  * @param bool $skipDelete
  *   Unclear parameter, passed to website create
  *
  * @todo explain this parameter
  *
  * @throws Exception
  * @return CRM_Contact_BAO_Contact|CRM_Core_Error
  *   Created or updated contribution object. We are deprecating returning an error in
  *   favour of exceptions
  */
 public static function &create(&$params, $fixAddress = TRUE, $invokeHooks = TRUE, $skipDelete = FALSE)
 {
     $contact = NULL;
     if (empty($params['contact_type']) && empty($params['contact_id'])) {
         return $contact;
     }
     $isEdit = TRUE;
     if ($invokeHooks) {
         if (!empty($params['contact_id'])) {
             CRM_Utils_Hook::pre('edit', $params['contact_type'], $params['contact_id'], $params);
         } else {
             CRM_Utils_Hook::pre('create', $params['contact_type'], NULL, $params);
             $isEdit = FALSE;
         }
     }
     $config = CRM_Core_Config::singleton();
     // CRM-6942: set preferred language to the current language if it’s unset (and we’re creating a contact).
     if (empty($params['contact_id']) && empty($params['preferred_language'])) {
         $params['preferred_language'] = $config->lcMessages;
     }
     // CRM-9739: set greeting & addressee if unset and we’re creating a contact.
     if (empty($params['contact_id'])) {
         foreach (self::$_greetingTypes as $greeting) {
             if (empty($params[$greeting . '_id'])) {
                 if ($defaultGreetingTypeId = CRM_Contact_BAO_Contact_Utils::defaultGreeting($params['contact_type'], $greeting)) {
                     $params[$greeting . '_id'] = $defaultGreetingTypeId;
                 }
             }
         }
     }
     $transaction = new CRM_Core_Transaction();
     $contact = self::add($params);
     if (!$contact) {
         // Not dying here is stupid, since we get into wierd situation and into a bug that
         // is impossible to figure out for the user or for us
         // CRM-7925
         CRM_Core_Error::fatal();
     }
     $params['contact_id'] = $contact->id;
     if (CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MULTISITE_PREFERENCES_NAME, 'is_enabled')) {
         // Enabling multisite causes the contact to be added to the domain group.
         $domainGroupID = CRM_Core_BAO_Domain::getGroupId();
         if (!empty($domainGroupID)) {
             if (!empty($params['group']) && is_array($params['group'])) {
                 $params['group'][$domainGroupID] = 1;
             } else {
                 $params['group'] = array($domainGroupID => 1);
             }
         }
     }
     if (array_key_exists('group', $params)) {
         $contactIds = array($params['contact_id']);
         foreach ($params['group'] as $groupId => $flag) {
             if ($flag == 1) {
                 CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId);
             } elseif ($flag == -1) {
                 CRM_Contact_BAO_GroupContact::removeContactsFromGroup($contactIds, $groupId);
             }
         }
     }
     // Add location Block data.
     $blocks = CRM_Core_BAO_Location::create($params, $fixAddress);
     foreach ($blocks as $name => $value) {
         $contact->{$name} = $value;
     }
     //add website
     CRM_Core_BAO_Website::create($params['website'], $contact->id, $skipDelete);
     //get userID from session
     $session = CRM_Core_Session::singleton();
     $userID = $session->get('userID');
     // add notes
     if (!empty($params['note'])) {
         if (is_array($params['note'])) {
             foreach ($params['note'] as $note) {
                 $contactId = $contact->id;
                 if (isset($note['contact_id'])) {
                     $contactId = $note['contact_id'];
                 }
                 //if logged in user, overwrite contactId
                 if ($userID) {
                     $contactId = $userID;
                 }
                 $noteParams = array('entity_id' => $contact->id, 'entity_table' => 'civicrm_contact', 'note' => $note['note'], 'subject' => CRM_Utils_Array::value('subject', $note), 'contact_id' => $contactId);
                 CRM_Core_BAO_Note::add($noteParams, CRM_Core_DAO::$_nullArray);
             }
         } else {
             $contactId = $contact->id;
             if (isset($note['contact_id'])) {
                 $contactId = $note['contact_id'];
             }
             //if logged in user, overwrite contactId
             if ($userID) {
                 $contactId = $userID;
             }
             $noteParams = array('entity_id' => $contact->id, 'entity_table' => 'civicrm_contact', 'note' => $params['note'], 'subject' => CRM_Utils_Array::value('subject', $params), 'contact_id' => $contactId);
             CRM_Core_BAO_Note::add($noteParams, CRM_Core_DAO::$_nullArray);
         }
     }
     // update the UF user_unique_id if that has changed
     CRM_Core_BAO_UFMatch::updateUFName($contact->id);
     if (!empty($params['custom']) && is_array($params['custom'])) {
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contact', $contact->id);
     }
     // make a civicrm_subscription_history entry only on contact create (CRM-777)
     if (empty($params['contact_id'])) {
         $subscriptionParams = array('contact_id' => $contact->id, 'status' => 'Added', 'method' => 'Admin');
         CRM_Contact_BAO_SubscriptionHistory::create($subscriptionParams);
     }
     $transaction->commit();
     // CRM-6367: fetch the right label for contact type’s display
     $contact->contact_type_display = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_ContactType', $contact->contact_type, 'label', 'name');
     if (!$config->doNotResetCache) {
         // Note: doNotResetCache flag is currently set by import contact process and merging,
         // since resetting and
         // rebuilding cache could be expensive (for many contacts). We might come out with better
         // approach in future.
         CRM_Contact_BAO_Contact_Utils::clearContactCaches($contact->id);
     }
     if ($invokeHooks) {
         if ($isEdit) {
             CRM_Utils_Hook::post('edit', $params['contact_type'], $contact->id, $contact);
         } else {
             CRM_Utils_Hook::post('create', $params['contact_type'], $contact->id, $contact);
         }
     }
     // process greetings CRM-4575, cache greetings
     self::processGreetings($contact);
     return $contact;
 }
Example #24
0
 /**
  * Get the html for the form that represents this particular group.
  *
  * @param int $userID
  *   The user id that we are actually editing.
  * @param string $title
  *   The title of the group we are interested in.
  * @param int $action
  *   The action of the form.
  * @param bool $register
  *   Is this the registration form.
  * @param bool $reset
  *   Should we reset the form?.
  * @param int $profileID
  *   Do we have the profile ID?.
  *
  * @param bool $doNotProcess
  * @param null $ctype
  *
  * @return string
  *   the html for the form on success, otherwise empty string
  */
 public static function getEditHTML($userID, $title, $action = NULL, $register = FALSE, $reset = FALSE, $profileID = NULL, $doNotProcess = FALSE, $ctype = NULL)
 {
     if ($register) {
         $controller = new CRM_Core_Controller_Simple('CRM_Profile_Form_Dynamic', ts('Dynamic Form Creator'), $action);
         if ($reset || $doNotProcess) {
             // hack to make sure we do not process this form
             $oldQFDefault = CRM_Utils_Array::value('_qf_default', $_POST);
             unset($_POST['_qf_default']);
             unset($_REQUEST['_qf_default']);
             if ($reset) {
                 $controller->reset();
             }
         }
         $controller->set('id', $userID);
         $controller->set('register', 1);
         $controller->set('skipPermission', 1);
         $controller->set('ctype', $ctype);
         $controller->process();
         if ($doNotProcess || !empty($_POST)) {
             $controller->validate();
         }
         $controller->setEmbedded(TRUE);
         //CRM-5839 - though we want to process form, get the control back.
         $controller->setSkipRedirection($doNotProcess ? FALSE : TRUE);
         $controller->run();
         // we are done processing so restore the POST/REQUEST vars
         if (($reset || $doNotProcess) && $oldQFDefault) {
             $_POST['_qf_default'] = $_REQUEST['_qf_default'] = $oldQFDefault;
         }
         $template = CRM_Core_Smarty::singleton();
         // Hide CRM error messages if they are displayed using drupal form_set_error.
         if (!empty($_POST)) {
             $template->assign('suppressForm', TRUE);
         }
         return trim($template->fetch('CRM/Profile/Form/Dynamic.tpl'));
     } else {
         if (!$profileID) {
             // make sure we have a valid group
             $group = new CRM_Core_DAO_UFGroup();
             $group->title = $title;
             if ($group->find(TRUE)) {
                 $profileID = $group->id;
             }
         }
         if ($profileID) {
             // make sure profileID and ctype match if ctype exists
             if ($ctype) {
                 $profileType = CRM_Core_BAO_UFField::getProfileType($profileID);
                 if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) {
                     $profileType = CRM_Contact_BAO_ContactType::getBasicType($profileType);
                 }
                 if ($profileType != 'Contact' && $profileType != $ctype) {
                     return NULL;
                 }
             }
             $controller = new CRM_Core_Controller_Simple('CRM_Profile_Form_Dynamic', ts('Dynamic Form Creator'), $action);
             if ($reset) {
                 $controller->reset();
             }
             $controller->set('gid', $profileID);
             $controller->set('id', $userID);
             $controller->set('register', 0);
             $controller->set('skipPermission', 1);
             if ($ctype) {
                 $controller->set('ctype', $ctype);
             }
             $controller->process();
             $controller->setEmbedded(TRUE);
             //CRM-5846 - give the control back to drupal.
             $controller->setSkipRedirection($doNotProcess ? FALSE : TRUE);
             $controller->run();
             $template = CRM_Core_Smarty::singleton();
             // Hide CRM error messages if they are displayed using drupal form_set_error.
             if (!empty($_POST) && CRM_Core_Config::singleton()->userFramework == 'Drupal') {
                 if (arg(0) == 'user' || arg(0) == 'admin' && arg(1) == 'people') {
                     $template->assign('suppressForm', TRUE);
                 }
             }
             $templateFile = "CRM/Profile/Form/{$profileID}/Dynamic.tpl";
             if (!$template->template_exists($templateFile)) {
                 $templateFile = 'CRM/Profile/Form/Dynamic.tpl';
             }
             return trim($template->fetch($templateFile));
         } else {
             $userEmail = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
             // if post not empty then only proceed
             if (!empty($_POST)) {
                 // get the new email
                 $config = CRM_Core_Config::singleton();
                 $email = CRM_Utils_Array::value('mail', $_POST);
                 if (CRM_Utils_Rule::email($email) && $email != $userEmail[1]) {
                     CRM_Core_BAO_UFMatch::updateContactEmail($userID, $email);
                 }
             }
         }
     }
     return '';
 }
Example #25
0
 /**
  * Takes an associative array and adds email.
  *
  * @param array $params
  *   (reference ) an assoc array of name/value pairs.
  *
  * @return object
  *   CRM_Core_BAO_Email object on success, null otherwise
  */
 public static function add(&$params)
 {
     $hook = empty($params['id']) ? 'create' : 'edit';
     CRM_Utils_Hook::pre($hook, 'Email', CRM_Utils_Array::value('id', $params), $params);
     $email = new CRM_Core_DAO_Email();
     $email->copyValues($params);
     // lower case email field to optimize queries
     $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
     $email->email = $strtolower($email->email);
     /*
      * since we're setting bulkmail for 1 of this contact's emails, first reset all their other emails to is_bulkmail false
      *  We shouldn't not set the current email to false even though we
      *  are about to reset it to avoid contaminating the changelog if logging is enabled
      * (only 1 email address can have is_bulkmail = true)
      */
     if ($email->is_bulkmail != 'null' && $params['contact_id'] && !self::isMultipleBulkMail()) {
         $sql = "\nUPDATE civicrm_email\nSET    is_bulkmail = 0\nWHERE  contact_id = {$params['contact_id']}\n";
         if ($hook == 'edit') {
             $sql .= " AND id <> {$params['id']}";
         }
         CRM_Core_DAO::executeQuery($sql);
     }
     // handle if email is on hold
     self::holdEmail($email);
     $email->save();
     if ($email->is_primary) {
         // update the UF user email if that has changed
         CRM_Core_BAO_UFMatch::updateUFName($email->contact_id);
     }
     CRM_Utils_Hook::post($hook, 'Email', $email->id, $email);
     return $email;
 }
 /**
  * Set variables up before form is built.
  *
  * @return void
  */
 public function preProcess()
 {
     $session = CRM_Core_Session::singleton();
     $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
     $contributionParams = $requestParams = $_REQUEST;
     $contactID = $session->get('userID');
     if ($contactID && empty($contributionParams['email'])) {
         $emailDetails = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
         if (!empty($emailDetails)) {
             $contributionParams['email'] = $emailDetails[1];
             // for email to be prefilled
             $this->assign('email', $emailDetails[1]);
         }
     }
     $pageConfig = civicrm_api3('ContributionPage', 'getsingle', array('id' => $this->_id));
     if (is_array($pageConfig['payment_processor'])) {
         CRM_Core_Error::fatal(ts('Multiple payment processors not supported with quick donate.'));
     }
     $processorDetails = CRM_Financial_BAO_PaymentProcessor::getPayment($pageConfig['payment_processor'], 'live');
     //MV: get amount details if other amount enabled for contribution page.
     if ($pageConfig['amount_block_is_active']) {
         $sql = "SELECT cpfv.amount, cpfv.is_default, cpfv.weight \n        FROM civicrm_price_field_value cpfv \n        INNER JOIN civicrm_price_field cpf ON (cpf.id = cpfv.price_field_id)\n        INNER JOIN civicrm_price_set_entity cpse ON (cpse.price_set_id = cpf.price_set_id)\n        WHERE cpse.entity_id = %1 AND cpf.name = 'contribution_amount'\n      ";
         $dao = CRM_Core_DAO::executeQuery($sql, array(1 => array($pageConfig['id'], 'Integer')));
         $amount = 0;
         while ($dao->fetch()) {
             if ($dao->weight == 1 || $dao->is_default == 1) {
                 $amount = $dao->amount;
             }
         }
     }
     $pageConfig['default_amount'] = $amount ? $amount : $pageConfig['min_amount'];
     $pageConfig['currency_symbol'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_Currency', $pageConfig['currency'], 'symbol', 'name');
     $this->assign('pageConfig', $pageConfig);
     $this->assign('key', $processorDetails['password']);
     $this->assign('currency', strtolower($pageConfig['currency']));
     if (!empty($requestParams['stripe_token'])) {
         //FIXME: could go in post process
         if (!$contributionParams['email']) {
             CRM_Core_Error::fatal(ts('Email address is required'));
         }
         $contributionParams['financial_type_id'] = $pageConfig['financial_type_id'];
         if (!$contactID) {
             $contactParams = array('email' => $contributionParams['email'], 'contact_type' => 'Individual');
             $dedupeParams = CRM_Dedupe_Finder::formatParams($contactParams, 'Individual');
             $dedupeParams['check_permission'] = FALSE;
             $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual');
             // if we find more than one contact, use the first one
             $contactID = CRM_Utils_Array::value(0, $ids);
             if (!$contactID) {
                 $cont = civicrm_api3('Contact', 'create', $contactParams);
                 $contactID = $cont['id'];
             }
         }
         $contributionParams['contact_id'] = $contactID;
         $contributionParams['payment_processor_id'] = $pageConfig['payment_processor'];
         $contributionParams['currencyID'] = $pageConfig['currency'];
         //gift aid
         //get gift aid custom field id
         $sqlCF = "SELECT cf.id \n      FROM civicrm_custom_field cf \n      INNER JOIN civicrm_custom_group cg ON (cg.id = cf.custom_group_id) \n      WHERE cg.name = %1 AND cf.name = %2";
         $sqlCFParams = array(1 => array(self::C_CUSTOM_GROUP_GIFT_AID, 'String'), 2 => array(self::C_CUSTOM_FIELD_GIFT_AID, 'String'));
         $cfId = CRM_Core_DAO::singleValueQuery($sqlCF, $sqlCFParams);
         if ($cfId && $contributionParams['donation_form']['gift_aid']) {
             $contributionParams["custom_{$cfId}"] = 1;
         }
         //gift aid end
         //campaign
         if ($pageConfig['campaign_id']) {
             $contributionParams['campaign_id'] = $pageConfig['campaign_id'];
         }
         try {
             $result = civicrm_api3('Contribution', 'transact', $contributionParams);
         } catch (CiviCRM_API3_Exception $e) {
             $error = $e->getMessage();
             $this->assign('error', $error);
             CRM_Utils_System::setTitle(ts('Oops! There was a problem'));
         }
         if (!empty($result['error'])) {
             $this->assign('error', $result['error']);
             CRM_Utils_System::setTitle(ts('Oops! There was a problem'));
         } else {
             if ($result) {
                 $contributionID = $result['id'];
                 $contactID = $result['values'][$contributionID]['contact_id'];
                 // Send receipt
                 civicrm_api3('contribution', 'sendconfirmation', array('id' => $contributionID) + $pageConfig);
                 CRM_Utils_System::setTitle(ts('Thank you'));
                 $this->assign('status', 'thankyou');
                 $profileID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', 'Supporter Profile', 'id', 'title');
                 // Link (button) for users to create their own Personal Campaign page
                 if ($profileID && !$session->get('userID')) {
                     $ufId = CRM_Core_BAO_UFMatch::getUFId($contactID);
                     if ($ufId) {
                         $config = CRM_Core_Config::singleton();
                         $loginURL = $config->userSystem->getLoginURL();
                         $this->assign('loginURL', $loginURL);
                     } else {
                         $linkTextUrl = CRM_Utils_System::url('civicrm/profile/create', "gid={$profileID}&reset=1", FALSE, NULL, TRUE);
                         $this->assign('linkTextUrl', $linkTextUrl);
                     }
                 }
                 //redirect if the logged in user
                 if ($session->get('userID')) {
                     $urlParams = array('pageId' => $this->_id, 'component' => 'contribute', 'reset' => 1);
                     $sql = "SELECT pcp.id FROM civicrm_pcp pcp \n          INNER JOIN  civicrm_pcp_block cpb ON (cpb.id = pcp.pcp_block_id)\n          WHERE cpb.entity_id = %1 AND pcp.contact_id = %2\n          ";
                     $sqlparams = array(1 => array($pageConfig['id'], 'Integer'), 2 => array($contactID, 'Integer'));
                     $pcpId = CRM_Core_DAO::singleValueQuery($sql, $sqlparams);
                     if ($pcpId) {
                         $urlParams['id'] = $pcpId;
                     }
                     $url = CRM_Utils_System::url('civicrm/pcp/setup', $urlParams);
                     CRM_Utils_System::redirect($url);
                 }
             }
         }
     } else {
         if (!empty($requestParams['_qf_Main_display'])) {
             //$this->assign('error', $error);
             CRM_Utils_System::setTitle(ts('Oops! There was a problem'));
         } else {
             $this->assign('status', 'quickdonate');
             CRM_Core_Resources::singleton()->addStyleFile('uk.co.vedaconsulting.quickdonate', 'css/quickdonatebox.css');
         }
     }
 }
Example #27
0
 /**
  * returns all the rows in the given offset and rowCount
  *
  * @param enum   $action   the action being performed
  * @param int    $offset   the row number to start from
  * @param int    $rowCount the number of rows to return
  * @param string $sort     the sql string that describes the sort order
  * @param enum   $output   what should the result set include (web/email/csv)
  *
  * @return int   the total number of rows for this action
  */
 function &getRows($action, $offset, $rowCount, $sort, $output = NULL)
 {
     $multipleFields = array('url');
     //$sort object processing for location fields
     if ($sort) {
         $vars = $sort->_vars;
         $varArray = array();
         foreach ($vars as $key => $field) {
             $field = $vars[$key];
             $fieldArray = explode('-', $field['name']);
             $fieldType = CRM_Utils_Array::value('2', $fieldArray);
             if (is_numeric(CRM_Utils_Array::value('1', $fieldArray))) {
                 if (!in_array($fieldType, $multipleFields)) {
                     $locationType = new CRM_Core_DAO_LocationType();
                     $locationType->id = $fieldArray[1];
                     $locationType->find(TRUE);
                     if ($fieldArray[0] == 'email' || $fieldArray[0] == 'im' || $fieldArray[0] == 'phone') {
                         $field['name'] = "`" . $locationType->name . "-" . $fieldArray[0] . "-1`";
                     } else {
                         $field['name'] = "`" . $locationType->name . "-" . $fieldArray[0] . "`";
                     }
                 } else {
                     $field['name'] = "`website-" . $fieldArray[1] . "-{$fieldType}`";
                 }
             }
             $varArray[$key] = $field;
         }
         $sort->_vars = $varArray;
     }
     $additionalWhereClause = 'contact_a.is_deleted = 0';
     $returnQuery = NULL;
     if ($this->_multiRecordTableName) {
         $returnQuery = TRUE;
     }
     $result = $this->_query->searchQuery($offset, $rowCount, $sort, NULL, NULL, NULL, NULL, $returnQuery, $additionalWhereClause);
     if ($returnQuery) {
         $resQuery = preg_replace('/GROUP BY contact_a.id[\\s]+ORDER BY/', ' ORDER BY', $result);
         $result = CRM_Core_DAO::executeQuery($resQuery);
     }
     // process the result of the query
     $rows = array();
     // check if edit is configured in profile settings
     if ($this->_gid) {
         $editLink = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid, 'is_edit_link');
     }
     //FIXME : make sure to handle delete separately. CRM-4418
     $mask = CRM_Core_Action::mask(array(CRM_Core_Permission::getPermission()));
     if ($editLink && $mask & CRM_Core_Permission::EDIT) {
         // do not allow edit for anon users in joomla frontend, CRM-4668
         $config = CRM_Core_Config::singleton();
         if (!$config->userFrameworkFrontend) {
             $this->_editLink = TRUE;
         }
     }
     $links = self::links($this->_map, $this->_editLink, $this->_linkToUF, $this->_profileIds);
     $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
     $names = array();
     static $skipFields = array('group', 'tag');
     foreach ($this->_fields as $key => $field) {
         // skip pseudo fields
         if (substr($key, 0, 9) == 'phone_ext') {
             continue;
         }
         if (!empty($field['in_selector']) && !in_array($key, $skipFields)) {
             if (strpos($key, '-') !== FALSE) {
                 $value = explode('-', $key);
                 $fieldName = CRM_Utils_Array::value(0, $value);
                 $id = CRM_Utils_Array::value(1, $value);
                 $type = CRM_Utils_Array::value(2, $value);
                 if (!in_array($fieldName, $multipleFields)) {
                     $locationTypeName = NULL;
                     if (is_numeric($id)) {
                         $locationTypeName = CRM_Utils_Array::value($id, $locationTypes);
                     } else {
                         if ($id == 'Primary') {
                             $locationTypeName = 1;
                         }
                     }
                     if (!$locationTypeName) {
                         continue;
                     }
                     $locationTypeName = str_replace(' ', '_', $locationTypeName);
                     if (in_array($fieldName, array('phone', 'im', 'email'))) {
                         if ($type) {
                             $names[] = "{$locationTypeName}-{$fieldName}-{$type}";
                         } else {
                             $names[] = "{$locationTypeName}-{$fieldName}";
                         }
                     } else {
                         $names[] = "{$locationTypeName}-{$fieldName}";
                     }
                 } else {
                     $names[] = "website-{$id}-{$fieldName}";
                 }
             } elseif ($field['name'] == 'id') {
                 $names[] = 'contact_id';
             } else {
                 $names[] = $field['name'];
             }
         }
     }
     $multipleSelectFields = array('preferred_communication_method' => 1);
     $multiRecordTableId = NULL;
     if ($this->_multiRecordTableName) {
         $multiRecordTableId = "{$this->_multiRecordTableName}_id";
     }
     // we need to determine of overlay profile should be shown
     $showProfileOverlay = CRM_Core_BAO_UFGroup::showOverlayProfile();
     while ($result->fetch()) {
         $this->_query->convertToPseudoNames($result);
         if (isset($result->country)) {
             // the query returns the untranslated country name
             $i18n = CRM_Core_I18n::singleton();
             $result->country = $i18n->translate($result->country);
         }
         $row = array();
         $empty = TRUE;
         $row[] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type, FALSE, $result->contact_id, $showProfileOverlay);
         if ($result->sort_name) {
             $row[] = $result->sort_name;
             $empty = FALSE;
         } else {
             continue;
         }
         foreach ($names as $name) {
             if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name)) {
                 $row[] = CRM_Core_BAO_CustomField::getDisplayValue($result->{$name}, $cfID, $this->_options, $result->contact_id);
             } elseif (substr($name, -4) == '-url' && !empty($result->{$name})) {
                 $url = CRM_Utils_System::fixURL($result->{$name});
                 $typeId = substr($name, 0, -4) . "-website_type_id";
                 $typeName = CRM_Core_PseudoConstant::getLabel('CRM_Core_DAO_Website', 'website_type_id', $result->{$typeId});
                 if ($typeName) {
                     $row[] = "<a href=\"{$url}\">{$result->{$name}} ({$typeName})</a>";
                 } else {
                     $row[] = "<a href=\"{$url}\">{$result->{$name}}</a>";
                 }
             } elseif ($name == 'preferred_language') {
                 $row[] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $result->{$name});
             } elseif ($multipleSelectFields && array_key_exists($name, $multipleSelectFields)) {
                 $paramsNew = array($name => $result->{$name});
                 $name = array($name => array('newName' => $name, 'groupName' => $name));
                 CRM_Core_OptionGroup::lookupValues($paramsNew, $name, FALSE);
                 $row[] = $paramsNew[$key];
             } elseif (strpos($name, '-im')) {
                 if (!empty($result->{$name})) {
                     $providerId = $name . "-provider_id";
                     $providerName = CRM_Core_PseudoConstant::getLabel('CRM_Core_DAO_IM', 'provider_id', $result->{$providerId});
                     $row[] = $result->{$name} . " ({$providerName})";
                 } else {
                     $row[] = '';
                 }
             } elseif (strpos($name, '-phone-')) {
                 $phoneExtField = str_replace('phone', 'phone_ext', $name);
                 if (isset($result->{$phoneExtField})) {
                     $row[] = $result->{$name} . " (" . $result->{$phoneExtField} . ")";
                 } else {
                     $row[] = $result->{$name};
                 }
             } elseif (in_array($name, array('addressee', 'email_greeting', 'postal_greeting'))) {
                 $dname = $name . '_display';
                 $row[] = $result->{$dname};
             } elseif (in_array($name, array('birth_date', 'deceased_date'))) {
                 $row[] = CRM_Utils_Date::customFormat($result->{$name});
             } elseif (isset($result->{$name})) {
                 $row[] = $result->{$name};
             } else {
                 $row[] = '';
             }
             if (!empty($result->{$name})) {
                 $empty = FALSE;
             }
         }
         $newLinks = $links;
         $params = array('id' => $result->contact_id, 'gid' => implode(',', $this->_profileIds));
         // pass record id param to view url for multi record view
         if ($multiRecordTableId && $newLinks) {
             if ($result->{$multiRecordTableId}) {
                 if ($newLinks[CRM_Core_Action::VIEW]['url'] == 'civicrm/profile/view') {
                     $newLinks[CRM_Core_Action::VIEW]['qs'] .= "&multiRecord=view&recordId=%%recordId%%&allFields=1";
                     $params['recordId'] = $result->{$multiRecordTableId};
                 }
             }
         }
         if ($this->_linkToUF) {
             $ufID = CRM_Core_BAO_UFMatch::getUFId($result->contact_id);
             if (!$ufID) {
                 unset($newLinks[CRM_Core_Action::PROFILE]);
             } else {
                 $params['ufID'] = $ufID;
             }
         }
         $row[] = CRM_Core_Action::formLink($newLinks, $mask, $params, ts('more'), FALSE, 'profile.selector.row', 'Contact', $result->contact_id);
         if (!$empty) {
             $rows[] = $row;
         }
     }
     return $rows;
 }
Example #28
0
 function loadUser($username)
 {
     global $user;
     $user = user_load_by_name($username);
     if (empty($user->uid)) {
         return FALSE;
     }
     $uid = $user->uid;
     $contact_id = CRM_Core_BAO_UFMatch::getContactId($uid);
     // lets store contact id and user id in session
     $session = CRM_Core_Session::singleton();
     $session->set('ufID', $uid);
     $session->set('userID', $contact_id);
     return TRUE;
 }
Example #29
0
 /**
  * Add urls for display in the actions menu.
  * @param CRM_Core_Page $obj
  * @param int $cid
  */
 public static function addUrls(&$obj, $cid)
 {
     $uid = CRM_Core_BAO_UFMatch::getUFId($cid);
     if ($uid) {
         $userRecordUrl = CRM_Core_Config::singleton()->userSystem->getUserRecordUrl($cid);
         $obj->assign('userRecordUrl', $userRecordUrl);
         $obj->assign('userRecordId', $uid);
     } elseif (CRM_Core_Config::singleton()->userSystem->checkPermissionAddUser()) {
         $userAddUrl = CRM_Utils_System::url('civicrm/contact/view/useradd', 'reset=1&action=add&cid=' . $cid);
         $obj->assign('userAddUrl', $userAddUrl);
     }
     if (CRM_Core_Permission::check('access Contact Dashboard')) {
         $dashboardURL = CRM_Utils_System::url('civicrm/user', "reset=1&id={$cid}");
         $obj->assign('dashboardURL', $dashboardURL);
     }
     // See if other modules want to add links to the activtity bar
     $hookLinks = array();
     CRM_Utils_Hook::links('view.contact.activity', 'Contact', $cid, $hookLinks, CRM_Core_DAO::$_nullObject, CRM_Core_DAO::$_nullObject);
     if (is_array($hookLinks)) {
         $obj->assign('hookLinks', $hookLinks);
     }
 }
/**
 * Get contact id for the order's customer.
 *
 * @param object $order
 *   Wordpress Order Object
 *
 * @return false|integer
 *   > 0: existing contact
 *   = 0: create new contact
 *   FALSE: error
 */
function _woocommerce_civicrm_get_cid($order)
{
    $user_id = get_current_user_id();
    if ($user_id > 0) {
        // Logged in user
        global $current_user;
        get_currentuserinfo();
        $match = CRM_Core_BAO_UFMatch::synchronizeUFMatch($current_user, $current_user->ID, $current_user->user_email, 'WordPress', FALSE, 'Individual');
        if (!is_object($match)) {
            return FALSE;
        }
        return $match->contact_id;
    }
    // The customer is anonymous.  Look in the CiviCRM contacts table for a
    // contact that matches the billing email.
    $params = array('email' => $order->billing_email, 'return.contact_id' => TRUE, 'sequential' => 1);
    try {
        $contact = civicrm_api3('contact', 'get', $params);
    } catch (Exception $e) {
        return FALSE;
    }
    // No matches found, so we will need to create a contact.
    if (count($contact) == 0) {
        return 0;
    }
    $cid = $contact['values'][0]['id'];
    return $cid;
}