Example #1
0
/**
 * implementation of CiviCRM tokenValues hook.
 */
function windowsill_civicrm_tokenValues(&$values, &$contactIDs, $jobID, $tokens = array(), $context = NULL)
{
    // Get settings from civicrm
    $settings = CRM_Core_BAO_Setting::getItem('windowsill', 'settings');
    $decode = json_decode(utf8_decode($settings), TRUE);
    // Loop settings
    foreach ($decode as &$value) {
        // Check if tab is configured
        if ($value['token']) {
            $name = str_replace(' ', '_', $value['name']);
            $view = explode(':', $value['view']);
            // Rendered
            $rendered = views_embed_view($view[0], $view[1]);
            /*
            // absolute paths are set to url paths (Anchor tags)
            //$rendered['windowsill:'.$name] = preg_replace('/<\s*a\s(.*?)href="\/(.*?)"(.*?)>/i', '<a $1href="'.$base_url.$base_path.'$2"$3>', $rendered['windowsill:'.$name]);
            //$rendered['windowsill:'.$name] = preg_replace('/<\s*img\s(.*?)src="\/(.*?)"(.*?)>/i', '<img $1src="'.$base_url.$base_path.'$2"$3>', $rendered['windowsill:'.$name]);
            */
            // Set token
            foreach ($contactIDs as $contactID) {
                $values[$contactID]['windowsill.' . $name] = $rendered;
            }
        }
    }
}
 /**
  * Identify all the households to check and do it
  *
  * If max_count is set, it will stop after that amount,
  * saving the last household id for the next call
  */
 public function checkAllHouseholds($max_count = NULL)
 {
     $max_count = (int) $max_count;
     $activity_type_id = CRM_Householdmerge_Logic_Configuration::getCheckHouseholdActivityTypeID();
     $activity_status_ids = CRM_Householdmerge_Logic_Configuration::getLiveActivityStatusIDs();
     if ($max_count) {
         $contact_id_minimum = CRM_Core_BAO_Setting::getItem(CRM_Householdmerge_Logic_Configuration::$HHMERGE_SETTING_DOMAIN, 'hh_check_last_id');
         if (!$contact_id_minimum) {
             $contact_id_minimum = 0;
         }
         $limit_clause = "LIMIT {$max_count}";
     } else {
         $contact_id_minimum = 0;
         $limit_clause = '';
     }
     $last_contact_id_processed = 0;
     $selector_sql = "SELECT civicrm_contact.id AS contact_id\n                     FROM civicrm_contact\n                     LEFT JOIN civicrm_activity_contact ON civicrm_activity_contact.contact_id = civicrm_contact.id\n                     LEFT JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id AND civicrm_activity.activity_type_id = {$activity_type_id} AND civicrm_activity.status_id IN ({$activity_status_ids})\n                     WHERE contact_type = 'Household'\n                       AND civicrm_activity.id IS NULL                       \n                       AND (civicrm_contact.is_deleted IS NULL or civicrm_contact.is_deleted = 0)\n                       AND civicrm_contact.id > {$contact_id_minimum}\n                     GROUP BY civicrm_contact.id\n                     ORDER BY civicrm_contact.id ASC\n                     {$limit_clause}";
     $query = CRM_Core_DAO::executeQuery($selector_sql);
     while ($query->fetch()) {
         $last_contact_id_processed = $query->contact_id;
         $this->checkHousehold($last_contact_id_processed);
         $max_count--;
     }
     // done
     if ($max_count > 0) {
         // we're through the whole list, reset marker
         CRM_Core_BAO_Setting::setItem('0', CRM_Householdmerge_Logic_Configuration::$HHMERGE_SETTING_DOMAIN, 'hh_check_last_id');
     } else {
         CRM_Core_BAO_Setting::setItem($last_contact_id_processed, CRM_Householdmerge_Logic_Configuration::$HHMERGE_SETTING_DOMAIN, 'hh_check_last_id');
     }
     return;
 }
Example #3
0
 function run()
 {
     $this->setActivityStatusIds();
     $this->setValues();
     $contactParams = array('is_opt_out' => 1);
     $groupId = CRM_Core_BAO_Setting::getItem('Speakcivi API Preferences', 'group_id');
     $location = '';
     if ($this->isGroupContactAdded($this->contactId, $groupId)) {
         $this->setGroupContactRemoved($this->contactId, $groupId);
         $location = 'removed from Members after optout link';
         if (CRM_Speakcivi_Cleanup_Leave::hasJoins($this->contactId)) {
             CRM_Speakcivi_Logic_Activity::leave($this->contactId, 'confirmation_link', $this->campaignId, $this->activityId, '', 'Added by SpeakCivi Optout');
         }
     }
     if ($this->campaignId) {
         $campaign = new CRM_Speakcivi_Logic_Campaign($this->campaignId);
         $locale = $campaign->getLanguage();
         $language = substr($locale, 0, 2);
         $this->setLanguageTag($this->contactId, $language);
     }
     CRM_Speakcivi_Logic_Contact::set($this->contactId, $contactParams);
     $aids = $this->findActivitiesIds($this->activityId, $this->campaignId, $this->contactId);
     $this->setActivitiesStatuses($this->activityId, $aids, 'optout', $location);
     $country = $this->getCountry($this->campaignId);
     $url = "{$country}/post_optout";
     CRM_Utils_System::redirect($url);
 }
Example #4
0
 function run()
 {
     $json = array();
     // get action
     $data = json_decode(file_get_contents("php://input"));
     // switch
     switch ($data->action) {
         case 'views':
             // variables
             $view_array = views_get_all_views($reset = FALSE);
             // build array for each view and their display
             foreach ($view_array as $view => $v) {
                 foreach ($view_array[$view]->display as $display => $d) {
                     $arr = array('id' => "{$v->name}:{$display}", 'name' => "{$v->human_name} ({$d->display_title})");
                     $json[] = $arr;
                 }
             }
             break;
         case 'settings':
             // variables
             // log
             $settings = CRM_Core_BAO_Setting::getItem('windowsill', 'settings');
             $json = json_decode(utf8_decode($settings), true);
             break;
     }
     // return JSON
     // http://wiki.civicrm.org/confluence/display/CRMDOC/Create+a+Module+Extension
     // http://civicrm.stackexchange.com/questions/2348/how-to-display-a-drupal-view-in-a-civicrm-tab
     print json_encode($json, JSON_PRETTY_PRINT);
     // exit
     CRM_Utils_System::civiExit();
 }
Example #5
0
 /**
  * Build the form
  *
  * @access public
  *
  * @return void
  */
 function buildQuickForm()
 {
     // text for sort_name or email criteria
     $config = CRM_Core_Config::singleton();
     $label = empty($config->includeEmailInName) ? ts('Name') : ts('Name or Email');
     $this->add('text', 'sort_name', $label);
     $searchOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'advanced_search_options');
     if (!empty($searchOptions['contactType'])) {
         $contactTypes = array('' => ts('- any contact type -')) + CRM_Contact_BAO_ContactType::getSelectElements();
         $this->add('select', 'contact_type', ts('is...'), $contactTypes);
     }
     if (!empty($searchOptions['groups'])) {
         // Arrange groups into hierarchical listing (child groups follow their parents and have indentation spacing in title)
         $groupHierarchy = CRM_Contact_BAO_Group::getGroupsHierarchy($this->_group, NULL, '&nbsp;&nbsp;', TRUE);
         // add select for groups
         $group = array('' => ts('- any group -')) + $groupHierarchy;
         $this->_groupElement =& $this->addElement('select', 'group', ts('in'), $group);
     }
     if (!empty($searchOptions['tags'])) {
         // tag criteria
         if (!empty($this->_tag)) {
             $tag = array('' => ts('- any tag -')) + $this->_tag;
             $this->_tagElement =& $this->addElement('select', 'tag', ts('with'), $tag);
         }
     }
     parent::buildQuickForm();
 }
Example #6
0
 /**
  * Build the form
  *
  * @access public
  *
  * @return void
  */
 function buildQuickForm()
 {
     // text for sort_name or email criteria
     $config = CRM_Core_Config::singleton();
     $label = empty($config->includeEmailInName) ? ts('Name') : ts('Name or Email');
     $this->add('text', 'sort_name', $label);
     $searchOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'advanced_search_options');
     $shortCuts = array();
     //@todo FIXME - using the CRM_Core_DAO::VALUE_SEPARATOR creates invalid html - if you can find the form
     // this is loaded onto then replace with something like '__' & test
     $separator = CRM_Core_DAO::VALUE_SEPARATOR;
     if (!empty($searchOptions['contactType'])) {
         $contactTypes = array('' => ts('- any contact type -')) + CRM_Contact_BAO_ContactType::getSelectElements(FALSE, TRUE, $separator);
         $this->add('select', 'contact_type', ts('is...'), $contactTypes, FALSE, array('class' => 'crm-select2'));
     }
     if (!empty($searchOptions['groups'])) {
         // Arrange groups into hierarchical listing (child groups follow their parents and have indentation spacing in title)
         $groupHierarchy = CRM_Contact_BAO_Group::getGroupsHierarchy($this->_group, NULL, '&nbsp;&nbsp;', TRUE);
         // add select for groups
         $group = array('' => ts('- any group -')) + $groupHierarchy;
         $this->add('select', 'group', ts('in'), $group, FALSE, array('class' => 'crm-select2'));
     }
     if (!empty($searchOptions['tags'])) {
         // tag criteria
         if (!empty($this->_tag)) {
             $tag = array('' => ts('- any tag -')) + $this->_tag;
             $this->add('select', 'tag', ts('with'), $tag, FALSE, array('class' => 'crm-select2'));
         }
     }
     parent::buildQuickForm();
 }
 /**
  * Process a webhook request from Mailchimp.
  *
  * The only documentation for this *sigh* is (May 2016) at
  * https://apidocs.mailchimp.com/webhooks/
  */
 public function run()
 {
     CRM_Mailchimp_Utils::checkDebug("Webhook POST: " . serialize($_POST));
     // Empty response object, default response code.
     try {
         $expected_key = CRM_Core_BAO_Setting::getItem(self::MC_SETTING_GROUP, 'security_key', NULL, FALSE);
         $given_key = isset($_GET['key']) ? $_GET['key'] : null;
         list($response_code, $response_object) = $this->processRequest($expected_key, $given_key, $_POST);
         CRM_Mailchimp_Utils::checkDebug("Webhook response code {$response_code} (200 = ok)");
     } catch (RuntimeException $e) {
         $response_code = $e->getCode();
         $response_object = NULL;
         CRM_Mailchimp_Utils::checkDebug("Webhook RuntimeException code {$response_code} (200 means OK): " . $e->getMessage());
     } catch (Exception $e) {
         // Broad catch.
         $response_code = 500;
         $response_object = NULL;
         CRM_Mailchimp_Utils::checkDebug("Webhook " . get_class($e) . ": " . $e->getMessage());
     }
     // Serve HTTP response.
     if ($response_code != 200) {
         // Some fault.
         header("HTTP/1.1 {$response_code}");
     } else {
         // Return the JSON output
         header('Content-type: application/json');
         print json_encode($response_object);
     }
     CRM_Utils_System::civiExit();
 }
Example #8
0
/**
 * Set defaults for api.getlist
 *
 * @param $entity string
 * @param $request array
 */
function _civicrm_api3_generic_getList_defaults($entity, &$request)
{
    $config = CRM_Core_Config::singleton();
    $fields = _civicrm_api_get_fields($entity);
    $defaults = array('page_num' => 1, 'input' => '', 'image_field' => NULL, 'id_field' => 'id', 'params' => array());
    // Find main field from meta
    foreach (array('sort_name', 'title', 'label', 'name') as $field) {
        if (isset($fields[$field])) {
            $defaults['label_field'] = $defaults['search_field'] = $field;
            break;
        }
    }
    foreach (array('description') as $field) {
        if (isset($fields[$field])) {
            $defaults['description_field'] = $field;
            break;
        }
    }
    $resultsPerPage = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'search_autocomplete_count', NULL, 10);
    $request += $defaults;
    // Default api params
    $params = array('options' => array('limit' => $resultsPerPage + 1, 'offset' => ($request['page_num'] - 1) * $resultsPerPage, 'sort' => $request['label_field']), 'sequential' => 1);
    // When searching e.g. autocomplete
    if ($request['input']) {
        $params[$request['search_field']] = array('LIKE' => ($config->includeWildCardInName ? '%' : '') . $request['input'] . '%');
    }
    // When looking up a field e.g. displaying existing record
    if (!empty($request['id'])) {
        if (is_string($request['id']) && strpos(',', $request['id'])) {
            $request['id'] = explode(',', $request['id']);
        }
        $params[$request['id_field']] = is_array($request['id']) ? array('IN' => $request['id']) : $request['id'];
    }
    $request['params'] += $params;
}
 /**
  * Form submission of new/edit api is processed.
  *
  * @access public
  *
  * @return None
  */
 public function postProcess()
 {
     //get the submitted values in an array
     $params = $this->controller->exportValues($this->_name);
     // Save the API Key & Save the Security Key
     if (CRM_Utils_Array::value('api_key', $params)) {
         CRM_Core_BAO_Setting::setItem($params['api_key'], self::MC_SETTING_GROUP, 'api_key');
     }
     $session = CRM_Core_Session::singleton();
     $message = "Api Key has been Saved!";
     $session->setStatus($message, ts('Api Key Saved'), 'success');
     $urlParams = null;
     $session->replaceUserContext(CRM_Utils_System::url('civicrm/mailchimp/apikeyregister', $urlParams));
     try {
         $mcClient = new Mailchimp($params['api_key']);
         $mcHelper = new Mailchimp_Helper($mcClient);
         $details = $mcHelper->accountDetails();
     } catch (Mailchimp_Invalid_ApiKey $e) {
         CRM_Core_Session::setStatus($e->getMessage());
         return FALSE;
     } catch (Mailchimp_HttpError $e) {
         CRM_Core_Session::setStatus($e->getMessage());
         return FALSE;
     }
     $message = "Following is the account information received from API callback:<br/>\n        <table class='mailchimp-table'>\n        <tr><td>Company:</td><td>{$details['contact']['company']}</td></tr>\n        <tr><td>First Name:</td><td>{$details['contact']['fname']}</td></tr>\n        <tr><td>Last Name:</td><td>{$details['contact']['lname']}</td></tr>\n        </table>";
     CRM_Core_Session::setStatus($message);
 }
Example #10
0
 public function setDefaultValues()
 {
     $defaults = array();
     try {
         $defaults['rood_mtype'] = civicrm_api3('MembershipType', 'getvalue', array('return' => 'id', 'name' => 'Lid SP en ROOD'));
     } catch (Exception $e) {
         //do nothing
     }
     try {
         $defaults['rood_mstatus'] = civicrm_api3('MembershipStatus', 'getvalue', array('return' => 'id', 'name' => 'Correctie'));
     } catch (Exception $e) {
         //do nothing
     }
     try {
         $defaults['sp_mtype'] = civicrm_api3('MembershipType', 'getvalue', array('return' => 'id', 'name' => 'Lid SP'));
     } catch (Exception $e) {
         //do nothing
     }
     try {
         $status = civicrm_api3('MembershipStatus', 'getvalue', array('return' => 'id', 'name' => 'current'));
         $defaults['member_status_id'][$status] = $status;
     } catch (Exception $e) {
         //do nothing
     }
     $date = new DateTime();
     $date->modify('-26 years');
     $date->modify('first day of this year');
     list($defaults['birth_date_from']) = CRM_Utils_Date::setDateDefaults($date->format('Y-m-d'));
     $date->modify('last day of this year');
     list($defaults['birth_date_to']) = CRM_Utils_Date::setDateDefaults($date->format('Y-m-d'));
     $minimum_fee = CRM_Core_BAO_Setting::getItem('nl.sp.rood', 'minimum_fee', null, '5.00');
     $defaults['minimum_fee'] = $minimum_fee;
     return $defaults;
 }
Example #11
0
 /**
  * Compute any messages which should be displayed before upgrade.
  *
  * @param string $preUpgradeMessage
  *   alterable.
  * @param $currentVer
  * @param $latestVer
  */
 public static function setPreUpgradeMessage(&$preUpgradeMessage, $currentVer, $latestVer)
 {
     if (version_compare(phpversion(), self::MIN_RECOMMENDED_PHP_VER) < 0) {
         $preUpgradeMessage .= '<br />' . ts('This webserver is running an outdated version of PHP (%1). The recommended version is %2 or later.', array(1 => phpversion(), 2 => self::MIN_RECOMMENDED_PHP_VER)) . '<br />' . ts('You may proceed with the upgrade and CiviCRM %1 will continue working normally, but future releases will require PHP %2.', array(1 => $latestVer, 2 => self::MIN_RECOMMENDED_PHP_VER));
     }
     // http://issues.civicrm.org/jira/browse/CRM-13572
     // Depending on how the code was upgraded, some sites may still have copies of old
     // source files left behind. This is often a forgivable offense, but it's quite
     // dangerous for CIVI-SA-2013-001.
     global $civicrm_root;
     $ofcFile = "{$civicrm_root}/packages/OpenFlashChart/php-ofc-library/ofc_upload_image.php";
     if (file_exists($ofcFile)) {
         if (@unlink($ofcFile)) {
             $preUpgradeMessage .= '<br />' . ts('This system included an outdated, insecure script (%1). The file was automatically deleted.', array(1 => $ofcFile));
         } else {
             $preUpgradeMessage .= '<br />' . ts('This system includes an outdated, insecure script (%1). Please delete it.', array(1 => $ofcFile));
         }
     }
     if (CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SEARCH_PREFERENCES_NAME, 'enable_innodb_fts', NULL, FALSE)) {
         // The FTS indexing feature dynamically manipulates the schema which could
         // cause conflicts with other layers that manipulate the schema. The
         // simplest thing is to turn it off and back on.
         // It may not always be necessary to do this -- but I doubt we're going to test
         // systematically in future releases.  When it is necessary, one could probably
         // ignore the matter and simply run CRM_Core_InnoDBIndexer::fixSchemaDifferences
         // after the upgrade.  But that's speculative.  For now, we'll leave this
         // advanced feature in the hands of the sysadmin.
         $preUpgradeMessage .= '<br />' . ts('This database uses InnoDB Full Text Search for optimized searching. The upgrade procedure has not been tested with this feature. You should disable (and later re-enable) the feature by navigating to "Administer => System Settings => Miscellaneous".');
     }
 }
 /**
  * @return array
  */
 public static function getSettings()
 {
     if (is_null(static::$settings)) {
         static::$settings = (array) CRM_Core_BAO_Setting::getItem('Extension', 'uk.co.compucorp.civicrm.giftaid:settings');
     }
     return static::$settings;
 }
Example #13
0
/**
+--------------------------------------------------------------------+
| CiviCRM version 4.6                                                |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2015                                |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM.                                    |
|                                                                    |
| CiviCRM is free software; you can copy, modify, and distribute it  |
| under the terms of the GNU Affero General Public License           |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
|                                                                    |
| CiviCRM is distributed in the hope that it will be useful, but     |
| WITHOUT ANY WARRANTY; without even the implied warranty of         |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
| See the GNU Affero General Public License for more details.        |
|                                                                    |
| You should have received a copy of the GNU Affero General Public   |
| License and the CiviCRM Licensing Exception along                  |
| with this program; if not, contact CiviCRM LLC                     |
| at info[AT]civicrm[DOT]org. If you have questions about the        |
| GNU Affero General Public License or the licensing of CiviCRM,     |
| see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+--------------------------------------------------------------------+
*/
function civicrm_api3_prevem_login($params)
{
    $prevemUrl = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME, 'prevem_url');
    $prevemURL = !empty($prevemUrl) ? CRM_Utils_URL::mask($prevemUrl, array('user', 'pass')) : NULL;
    if (!$prevemURL) {
        return civicrm_api3_create_error("prevemURL is not configured. Go to Administer>CiviMail>CiviMail Component Settings to configure prevemURL");
    }
    $prevemConsumer = parse_url($prevemUrl, PHP_URL_USER);
    $prevemSecret = parse_url($prevemUrl, PHP_URL_PASS);
    /** TODO Parse $prevemUrl. Send login request to get token. **/
    /** To send login request, see eg http://stackoverflow.com/questions/2445276/how-to-post-data-in-php-using-file-get-contents **/
    $postdata = http_build_query(array('email' => $prevemConsumer . "@foo.com", 'password' => $prevemSecret));
    $opts = array('http' => array('method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata));
    $context = stream_context_create($opts);
    $result = file_get_contents($prevemURL . '/api/Users/login', FALSE, $context);
    if ($result === FALSE) {
        return civicrm_api3_create_error("Failed to login. Check if Preview Manager is running on " . $prevemURL);
    } else {
        $accessToken = json_decode($result)->{'id'};
        if (!$accessToken) {
            return civicrm_api3_create_error("Failed to parse access token. Check if Preview Manager is running on " . $prevemURL);
        }
        $returnValues = array('url' => $prevemURL, 'consumerId' => $prevemConsumer, 'token' => $accessToken, 'password' => $prevemSecret);
        return civicrm_api3_create_success($returnValues, $params, 'Prevem', 'login');
    }
}
/**
 * Implements hook_civicrm_install().
 *
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_install
 */
function overrides_civicrm_install()
{
    CRM_Core_DAO::executeQuery("\n    CREATE TABLE `klangsoft_overrides` (\n      `snapshot` text NOT NULL\n    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
    CRM_Core_DAO::executeQuery("INSERT INTO `klangsoft_overrides` VALUES ('a:0:{}');");
    CRM_Core_BAO_Setting::setItem('', 'com.klangsoft_overrides', 'last_snapshot');
    _overrides_civix_civicrm_install();
}
Example #15
0
 /**
  * @param array $cxn
  * @param string $entity
  * @param string $action
  * @param array $params
  * @return mixed
  */
 public static function route($cxn, $entity, $action, $params)
 {
     $SUPER_PERM = array('administer CiviCRM');
     require_once 'api/v3/utils.php';
     // FIXME: Shouldn't the X-Forwarded-Proto check be part of CRM_Utils_System::isSSL()?
     if (CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'enableSSL') && !CRM_Utils_System::isSSL() && strtolower(CRM_Utils_Array::value('X_FORWARDED_PROTO', CRM_Utils_System::getRequestHeaders())) != 'https') {
         return civicrm_api3_create_error('System policy requires HTTPS.');
     }
     // Note: $cxn and cxnId are authenticated before router is called.
     $dao = new CRM_Cxn_DAO_Cxn();
     $dao->cxn_id = $cxn['cxnId'];
     if (empty($cxn['cxnId']) || !$dao->find(TRUE) || !$dao->cxn_id) {
         return civicrm_api3_create_error('Failed to lookup connection authorizations.');
     }
     if (!$dao->is_active) {
         return civicrm_api3_create_error('Connection is inactive.');
     }
     if (!is_string($entity) || !is_string($action) || !is_array($params)) {
         return civicrm_api3_create_error('API parameters are malformed.');
     }
     if (empty($cxn['perm']['api']) || !is_array($cxn['perm']['api']) || empty($cxn['perm']['grant']) || !(is_array($cxn['perm']['grant']) || is_string($cxn['perm']['grant']))) {
         return civicrm_api3_create_error('Connection has no permissions.');
     }
     $whitelist = \Civi\API\WhitelistRule::createAll($cxn['perm']['api']);
     \Civi::service('dispatcher')->addSubscriber(new \Civi\API\Subscriber\WhitelistSubscriber($whitelist));
     CRM_Core_Config::singleton()->userPermissionTemp = new CRM_Core_Permission_Temp();
     if ($cxn['perm']['grant'] === '*') {
         CRM_Core_Config::singleton()->userPermissionTemp->grant($SUPER_PERM);
     } else {
         CRM_Core_Config::singleton()->userPermissionTemp->grant($cxn['perm']['grant']);
     }
     $params['check_permissions'] = 'whitelist';
     return civicrm_api($entity, $action, $params);
 }
Example #16
0
 /**
  * Add an ics attachment to the input array.
  *
  * @param array $attachments
  *   Reference to array in same format returned from CRM_Core_BAO_File::getEntityFile().
  * @param array $contacts
  *   Array of contacts (attendees).
  *
  * @return string|null
  *   Array index of the added attachment in the $attachments array, else NULL.
  */
 public function addAttachment(&$attachments, $contacts)
 {
     // Check preferences setting
     if (CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'activity_assignee_notification_ics')) {
         $config =& CRM_Core_Config::singleton();
         $this->icsfile = tempnam($config->customFileUploadDir, 'ics');
         if ($this->icsfile !== FALSE) {
             rename($this->icsfile, $this->icsfile . '.ics');
             $this->icsfile .= '.ics';
             $icsFileName = basename($this->icsfile);
             // get logged in user's primary email
             // TODO: Is there a better way to do this?
             $organizer = $this->getPrimaryEmail();
             $template = CRM_Core_Smarty::singleton();
             $template->assign('activity', $this->activity);
             $template->assign('organizer', $organizer);
             $template->assign('contacts', $contacts);
             $template->assign('timezone', date_default_timezone_get());
             $calendar = $template->fetch('CRM/Activity/Calendar/ICal.tpl');
             if (file_put_contents($this->icsfile, $calendar) !== FALSE) {
                 if (empty($attachments)) {
                     $attachments = array();
                 }
                 $attachments['activity_ics'] = array('mime_type' => 'text/calendar', 'fileName' => $icsFileName, 'cleanName' => $icsFileName, 'fullPath' => $this->icsfile);
                 return 'activity_ics';
             }
         }
     }
     return NULL;
 }
function civicrm_api3_mailchimp_synchronize($params)
{
    $return = $tags = $createdContact = array();
    $apiKey = CRM_Core_BAO_Setting::getItem('MailChimp Preferences', 'api_key', NULL, FALSE);
    $tagsCount = civicrm_api3('Tag', 'getcount', array('sequential' => 1));
    $tagsGet = civicrm_api3('Tag', 'get', array('sequential' => 1, 'rowCount' => $tagsCount));
    foreach ($tagsGet['values'] as $tagIds => $tagsValues) {
        $tags[$tagsValues['id']] = $tagsValues['name'];
    }
    $mcClient = new Mailchimp($apiKey);
    $mcLists = new Mailchimp_Lists($mcClient);
    $lists = $mcLists->getList();
    foreach ($lists['data'] as $listsDetails) {
        if (!in_array($listsDetails['name'], $tags)) {
            $tagsCreate = civicrm_api3('Tag', 'create', array('sequential' => 1, 'name' => $listsDetails['name']));
        }
        $tagsCount = civicrm_api3('Tag', 'getcount', array('sequential' => 1));
        $tagsGet = civicrm_api3('Tag', 'get', array('sequential' => 1, 'rowCount' => $tagsCount));
        foreach ($tagsGet['values'] as $tagIds => $tagsValues) {
            $tags[$tagsValues['id']] = $tagsValues['name'];
        }
        if (in_array($listsDetails['name'], $tags)) {
            $keyTags = array_search($listsDetails['name'], $tags);
            $members = $mcLists->members($listsDetails['id']);
            foreach ($members['data'] as $key => $value) {
                try {
                    $createdContact = civicrm_api3('Contact', 'create', array('sequential' => 1, 'contact_type' => "Individual", 'first_name' => $value['merges']['FNAME'], 'last_name' => $value['merges']['LNAME'], 'email' => $value['merges']['EMAIL'], 'api.EntityTag.create' => array('entity_id' => "\$value.id", 'entity_table' => "civicrm_contact", 'tag_id' => $keyTags), 'dupe_check' => true));
                } catch (CiviCRM_API3_Exception $e) {
                    $result = civicrm_api3('EntityTag', 'create', array('contact_id' => $e->getExtraParams()['ids'][0], 'tag_id' => $keyTags));
                }
            }
        }
    }
    return civicrm_api3_create_success();
}
/**
 * Metrics.collate API
 *
 * @param array $params
 * @return array API result descriptor
 * @see civicrm_api3_create_success
 * @see civicrm_api3_create_error
 * @throws API_Exception
 */
function civicrm_api3_metrics_collate($params)
{
    $data = array();
    CRM_Metricclient_Hook::collateMetrics($data);
    if (!empty($data)) {
        $header = array();
        $header['site_url'] = $_SERVER['SERVER_NAME'];
        $metricSettings = CRM_Core_BAO_Setting::getItem("metrics");
        $header['site_name'] = $metricSettings['metrics_site_name'];
        $header['data'] = $data;
        $curl = curl_init($metricSettings['metrics_reporting_url']);
        curl_setopt($curl, CURLOPT_POST, true);
        if (array_key_exists("metrics_ignore_verify_peer", $metricSettings) && $metricSettings['metrics_ignore_verify_peer'] == 1) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        }
        if (array_key_exists("metrics_ignore_verify_host", $metricSettings) && $metricSettings['metrics_ignore_verify_host'] == 1) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        } else {
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
        }
        if (array_key_exists("metrics_ca_path", $metricSettings) && $metricSettings['metrics_ca_path']) {
            curl_setopt($curl, CURLOPT_CAPATH, $metricSettings['metrics_ca_path']);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, array("json" => json_encode($header)));
        $response = curl_exec($curl);
        $error = curl_error($curl);
        if ($error) {
            throw new API_Exception($error, 1);
        }
        return civicrm_api3_create_success(count($data), $params, 'Metrics', 'collate');
    }
    return civicrm_api3_create_success(0, $params, 'Metrics', 'collate');
}
Example #19
0
 /**
  * This function will manipulate the URLs in Emails, so they point
  *  to the correct proxy addresses
  */
 static function mendURLs(&$value)
 {
     // check if the proxy is enabled
     $enabled = CRM_Core_BAO_Setting::getItem('CiviProxy Settings', 'proxy_enabled');
     if (!$enabled) {
         return;
     }
     // get the URLs
     $config = CRM_Core_Config::singleton();
     $system_base = $config->userFrameworkBaseURL;
     $proxy_base = CRM_Core_BAO_Setting::getItem('CiviProxy Settings', 'proxy_url');
     // General external functions
     $value = preg_replace("#{$system_base}sites/all/modules/civicrm/extern/url.php#i", $proxy_base . '/url.php', $value);
     $value = preg_replace("#{$system_base}sites/all/modules/civicrm/extern/open.php#i", $proxy_base . '/open.php', $value);
     $value = preg_replace("#{$system_base}sites/default/files/civicrm/persist/#i", $proxy_base . '/file.php?id=', $value);
     // Mailing related functions
     $value = preg_replace("#{$system_base}civicrm/mailing/view#i", $proxy_base . '/mailing/mail.php', $value);
     $custom_mailing_base = CRM_Core_BAO_Setting::getItem('CiviProxy Settings', 'custom_mailing_base');
     $other_mailing_functions = array('subscribe', 'confirm', 'unsubscribe', 'resubscribe', 'optout');
     foreach ($other_mailing_functions as $function) {
         if (empty($custom_mailing_base)) {
             $new_url = "{$proxy_base}/mailing/{$function}.php";
         } else {
             $new_url = "{$custom_mailing_base}/{$function}.php";
         }
         $value = preg_replace("#{$system_base}civicrm/mailing/{$function}#i", $new_url, $value);
     }
 }
Example #20
0
 /**
  * Execute "checkAll".
  *
  * @param array|NULL $messages
  *   List of CRM_Utils_Check_Message; or NULL if the default list should be fetched.
  * @param array|string|callable $filter
  *   Restrict messages using a callback filter.
  *   By default, only show warnings and errors.
  *   Set TRUE to show all messages.
  */
 public function showPeriodicAlerts($messages = NULL, $filter = array(__CLASS__, 'severityMap'))
 {
     if (CRM_Core_Permission::check('administer CiviCRM') && CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'securityAlert', NULL, TRUE)) {
         $session = CRM_Core_Session::singleton();
         if ($session->timer('check_' . __CLASS__, self::CHECK_TIMER)) {
             // Best attempt at re-securing folders
             $config = CRM_Core_Config::singleton();
             $config->cleanup(0, FALSE);
             if ($messages === NULL) {
                 $messages = $this->checkAll();
             }
             $statusMessages = array();
             $statusType = 'alert';
             foreach ($messages as $message) {
                 if ($filter === TRUE || $message->getSeverity() >= 3) {
                     $statusType = $message->getSeverity() >= 4 ? 'error' : $statusType;
                     $statusMessage = $message->getMessage();
                     $statusMessages[] = $statusTitle = $message->getTitle();
                 }
             }
             if (count($statusMessages)) {
                 if (count($statusMessages) > 1) {
                     $statusTitle = ts('Multiple Alerts');
                     $statusMessage = '<ul><li>' . implode('</li><li>', $statusMessages) . '</li></ul>';
                 }
                 // TODO: add link to status page
                 CRM_Core_Session::setStatus($statusMessage, $statusTitle, $statusType);
             }
         }
     }
 }
 /**
  * Function to list memberships for the UF user
  *
  * return null
  * @access public
  */
 function listMemberships()
 {
     $membership = array();
     $dao = new CRM_Member_DAO_Membership();
     $dao->contact_id = $this->_contactId;
     $dao->is_test = 0;
     $dao->find();
     while ($dao->fetch()) {
         $membership[$dao->id] = array();
         CRM_Core_DAO::storeValues($dao, $membership[$dao->id]);
         //get the membership status and type values.
         $statusANDType = CRM_Member_BAO_Membership::getStatusANDTypeValues($dao->id);
         foreach (array('status', 'membership_type') as $fld) {
             $membership[$dao->id][$fld] = CRM_Utils_Array::value($fld, $statusANDType[$dao->id]);
         }
         if (!empty($statusANDType[$dao->id]['is_current_member'])) {
             $membership[$dao->id]['active'] = TRUE;
         }
         $membership[$dao->id]['renewPageId'] = CRM_Member_BAO_Membership::getContributionPageId($dao->id);
         if (!$membership[$dao->id]['renewPageId']) {
             // Membership payment was not done via online contribution page or free membership. Check for default membership renewal page from CiviMember Settings
             $defaultRenewPageId = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MEMBER_PREFERENCES_NAME, 'default_renewal_contribution_page');
             if ($defaultRenewPageId) {
                 $membership[$dao->id]['renewPageId'] = $defaultRenewPageId;
             }
         }
     }
     $activeMembers = CRM_Member_BAO_Membership::activeMembers($membership);
     $inActiveMembers = CRM_Member_BAO_Membership::activeMembers($membership, 'inactive');
     $this->assign('activeMembers', $activeMembers);
     $this->assign('inActiveMembers', $inActiveMembers);
 }
Example #22
0
 function run()
 {
     $this->setValues();
     $this->setIsOptOut($this->contactId, 0);
     $groupId = CRM_Core_BAO_Setting::getItem('Speakcivi API Preferences', 'group_id');
     $activityStatus = 'Completed';
     // Completed existing member
     if (!$this->isGroupContactAdded($this->contactId, $groupId)) {
         CRM_Speakcivi_Logic_Activity::join($this->contactId, 'confirmation_link', $this->campaignId);
         $this->setGroupContactAdded($this->contactId, $groupId);
         $activityStatus = 'optin';
         // Completed new member
     }
     if ($this->campaignId) {
         $campaign = new CRM_Speakcivi_Logic_Campaign($this->campaignId);
         $locale = $campaign->getLanguage();
         $language = substr($locale, 0, 2);
         $this->setLanguageGroup($this->contactId, $language);
         $this->setLanguageTag($this->contactId, $language);
     }
     $aids = $this->findActivitiesIds($this->activityId, $this->campaignId, $this->contactId);
     $this->setActivitiesStatuses($this->activityId, $aids, $activityStatus);
     $email = CRM_Speakcivi_Logic_Contact::getEmail($this->contactId);
     $speakcivi = new CRM_Speakcivi_Page_Speakcivi();
     $speakcivi->sendConfirm($email, $this->contactId, $this->activityId, $this->campaignId, false);
     $country = $this->getCountry($this->campaignId);
     $url = "{$country}/post_confirm";
     CRM_Utils_System::redirect($url);
 }
 /**
  * Basic page run function.
  */
 public function run()
 {
     // Get link options for managing events.
     $enableCart = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::EVENT_PREFERENCES_NAME, 'enable_cart');
     $tabs = CRM_Event_Page_ManageEvent::tabs($enableCart);
     foreach ($tabs as $tab => $tabInfo) {
         $tabs[$tab]['name'] = $tabInfo['title'];
         $tabs[$tab]['qs'] = $tab == 'reminder' ? 'reset=1&action=browse&setTab=1&id=%%id%%' : 'reset=1&action=update&id=%%id%%';
     }
     // Get link options for participant listings.
     $statusTypes = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
     $statusTypesPending = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 0');
     $participantLinks = array();
     if (1 || !empty($statusTypes)) {
         $participantLinks[2] = array('name' => implode(', ', array_values($statusTypes)), 'url' => 'civicrm/event/search', 'qs' => 'reset=1&force=1&status=true&event=%%id%%', 'title' => ts('Counted', array('domain' => 'com.aghstrategies.eventpermissions')));
     }
     if (!empty($statusTypesPending)) {
         $participantLinks[3] = array('name' => implode(', ', array_values($statusTypesPending)), 'url' => 'civicrm/event/search', 'qs' => 'reset=1&force=1&status=false&event=%%id%%', 'title' => ts('Not Counted', array('domain' => 'com.aghstrategies.eventpermissions')));
     }
     $participantLinks[4] = array('name' => ts('Public Participant Listing', array('domain' => 'com.aghstrategies.eventpermissions')), 'url' => 'civicrm/event/participant', 'qs' => 'reset=1&id=%%id%%', 'title' => ts('Public Participant Listing', array('domain' => 'com.aghstrategies.eventpermissions')));
     // Get link options for event links.
     $eventLinks = array(array('name' => ts('Register Participant', array('domain' => 'com.aghstrategies.eventpermissions')), 'url' => 'civicrm/participant/add', 'qs' => 'reset=1&action=add&context=standalone&eid=%%id%%', 'title' => ts('Register Participant', array('domain' => 'com.aghstrategies.eventpermissions'))), array('name' => ts('Event Info', array('domain' => 'com.aghstrategies.eventpermissions')), 'url' => 'civicrm/event/info', 'qs' => 'reset=1&id=%%id%%', 'title' => ts('Event Info', array('domain' => 'com.aghstrategies.eventpermissions'))), array('name' => ts('Online Registration (Test-drive)', array('domain' => 'com.aghstrategies.eventpermissions')), 'url' => 'civicrm/event/register', 'qs' => 'reset=1&action=preview&id=%%id%%', 'title' => ts('Online Registration (Test-drive)', array('domain' => 'com.aghstrategies.eventpermissions'))), array('name' => ts('Online Registration (Live)', array('domain' => 'com.aghstrategies.eventpermissions')), 'url' => 'civicrm/event/register', 'qs' => 'reset=1&id=%%id%%', 'title' => ts('Online Registration (Live)', array('domain' => 'com.aghstrategies.eventpermissions'))));
     $utils = new CRM_Eventpermissions_Utils();
     $events = array();
     foreach ($utils->myUpcomingEvents() as $id => $event) {
         $events[] = array('title' => CRM_Utils_System::href($event['title'], 'civicrm/event/info', "id={$id}&reset=1"), 'links' => CRM_Core_Action::formLink($tabs, NULL, array('id' => $id), ts('Configure', array('domain' => 'com.aghstrategies.eventpermissions')), TRUE, 'eventpermissions.myevents.configure', 'Event', $id), 'participantLinks' => CRM_Core_Action::formLink($participantLinks, $event['participant_listing_id'] ? 6 : 3, array('id' => $id), ts('Participants', array('domain' => 'com.aghstrategies.eventpermissions')), TRUE, 'eventpermissions.myevents.participants', 'Event', $id), 'eventLinks' => CRM_Core_Action::formLink($eventLinks, NULL, array('id' => $id), ts('Event Links', array('domain' => 'com.aghstrategies.eventpermissions')), TRUE, 'eventpermissions.myevents.links', 'Event', $id));
     }
     $this->assign('events', $events);
     parent::run();
 }
 function run()
 {
     // title
     CRM_Utils_System::setTitle(ts('WindowSill'));
     // config
     // https://github.com/kreynen/civicrm-min/blob/master/CRM/Core/Extensions.php
     $config = CRM_Core_Config::singleton();
     if ($config->userFramework != 'Drupal') {
         $error = "<div class='messages status no-popup'><div class='icon inform-icon'></div>Not a Drupal installation</div>";
     } else {
         $error = "<div class='messages status no-popup'><div class='icon inform-icon'></div>Drupal installation</div>";
     }
     // error
     $this->assign('error', $error);
     // on form action update settings
     if (isset($_REQUEST['settings'])) {
         // set
         CRM_Core_BAO_Setting::setItem($_REQUEST['settings'], 'windowsill', 'settings');
         // notice
         CRM_Core_Session::setStatus(ts('Windowsill settings changed'), ts('Saved'), 'success');
     }
     // url
     $url = CRM_Utils_System::url() . "civicrm/ctrl/windowsill";
     $this->assign('url', $url);
     // render
     parent::run();
 }
Example #25
0
function _civicrm_api3_speakcivi_sendconfirm_spec(&$params)
{
    $params['toEmail']['api.required'] = 1;
    $params['contact_id']['api.required'] = 1;
    $params['campaign_id']['api.required'] = 1;
    $params['from']['api.default'] = html_entity_decode(CRM_Core_BAO_Setting::getItem('Speakcivi API Preferences', 'from'));
}
Example #26
0
 /**
  * Build the form object.
  *
  *
  * @return void
  */
 public function buildQuickForm()
 {
     // text for sort_name or email criteria
     $config = CRM_Core_Config::singleton();
     $label = empty($config->includeEmailInName) ? ts('Name') : ts('Name or Email');
     $this->add('text', 'sort_name', $label);
     $searchOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'advanced_search_options');
     $shortCuts = array();
     //@todo FIXME - using the CRM_Core_DAO::VALUE_SEPARATOR creates invalid html - if you can find the form
     // this is loaded onto then replace with something like '__' & test
     $separator = CRM_Core_DAO::VALUE_SEPARATOR;
     if (!empty($searchOptions['contactType'])) {
         $contactTypes = array('' => ts('- any contact type -')) + CRM_Contact_BAO_ContactType::getSelectElements(FALSE, TRUE, $separator);
         $this->add('select', 'contact_type', ts('is...'), $contactTypes, FALSE, array('class' => 'crm-select2'));
     }
     // add select for groups
     if (!empty($searchOptions['groups'])) {
         $this->addSelect('group', array('entity' => 'group_contact', 'label' => ts('in'), 'context' => 'search', 'placeholder' => ts('- any group -')));
     }
     if (!empty($searchOptions['tags'])) {
         // tag criteria
         if (!empty($this->_tag)) {
             $this->addSelect('tag', array('entity' => 'entity_tag', 'label' => ts('with'), 'context' => 'search', 'placeholder' => ts('- any tag -')));
         }
     }
     parent::buildQuickForm();
 }
 public function testSetValueOptions()
 {
     $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'address_options');
     $addressOptions['county'] = 1;
     CRM_Core_BAO_Setting::setValueOption(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'address_options', $addressOptions);
     $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'address_options');
     $this->assertEquals($addressOptions['county'], 1, 'County was set but did not stick in db');
 }
Example #28
0
 /**
  * @param bool $fresh
  * @return CRM_Utils_QueryFormatter
  */
 public static function singleton($fresh = FALSE)
 {
     if ($fresh || self::$singleton === NULL) {
         $mode = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SEARCH_PREFERENCES_NAME, 'fts_query_mode', NULL, self::MODE_NONE);
         self::$singleton = new CRM_Utils_QueryFormatter($mode);
     }
     return self::$singleton;
 }
 /**
  * This function sets the default values for the form.
  * default values are retrieved from the database
  *
  * @access public
  *
  * @return void
  */
 function setDefaultValues()
 {
     $domainID = CRM_Core_Config::domainID();
     $settings = civicrm_api3('Setting', 'get', array('domain_id' => $domainID, 'return' => "simple_donation_page"));
     $this->_defaults['simpleDonation'] = CRM_Utils_Array::value('simple_donation_page', $settings['values'][$domainID]);
     $this->_defaults['ziptastic'] = CRM_Core_BAO_Setting::getItem('Simple Donation', 'ziptastic_enable');
     return $this->_defaults;
 }
 public function getCurrentValue($key)
 {
     if (!empty($this->_submitValues[$key])) {
         return $this->_submitValues[$key];
     } else {
         return CRM_Core_BAO_Setting::getItem('CiviBanking', $key);
     }
 }