/**
 * Output navigation script tag
 *
 * @param array $params
 *   - is_default: bool, true if this is normal/default instance of the menu (which may be subject to CIVICRM_DISABLE_DEFAULT_MENU)
 * @param CRM_Core_Smarty $smarty
 *   The Smarty object.
 *
 * @return string
 *   HTML
 */
function smarty_function_crmNavigationMenu($params, &$smarty)
{
    $config = CRM_Core_Config::singleton();
    //check if logged in user has access CiviCRM permission and build menu
    $buildNavigation = !CRM_Core_Config::isUpgradeMode() && CRM_Core_Permission::check('access CiviCRM');
    if (defined('CIVICRM_DISABLE_DEFAULT_MENU') && CRM_Utils_Array::value('is_default', $params, FALSE)) {
        $buildNavigation = FALSE;
    }
    if ($config->userFrameworkFrontend) {
        $buildNavigation = FALSE;
    }
    if ($buildNavigation) {
        $session = CRM_Core_Session::singleton();
        $contactID = $session->get('userID');
        if ($contactID) {
            // These params force the browser to refresh the js file when switching user, domain, or language
            // We don't put them as a query string because some browsers will refuse to cache a page with a ? in the url
            // @see CRM_Admin_Page_AJAX::getNavigationMenu
            $lang = CRM_Core_I18n::getLocale();
            $domain = CRM_Core_Config::domainID();
            $key = CRM_Core_BAO_Navigation::getCacheKey($contactID);
            $src = CRM_Utils_System::url("civicrm/ajax/menujs/{$contactID}/{$lang}/{$domain}/{$key}");
            // CRM-15493 QFkey needed for quicksearch bar - must be unique on each page refresh so adding it directly to markup
            $qfKey = CRM_Core_Key::get('CRM_Contact_Controller_Search', TRUE);
            return '<script id="civicrm-navigation-menu" type="text/javascript" src="' . $src . '" data-qfkey=' . json_encode($qfKey) . '></script>';
        }
    }
    return '';
}
Example #2
0
 public function buildQuickForm()
 {
     $parent = $this->controller->getParent();
     $nameTextLabel = $parent->_sms ? ts('SMS Name') : ts('Mailing Name');
     $this->add('text', 'mailing_name', $nameTextLabel, CRM_Core_DAO::getAttribute('CRM_Mailing_DAO_Mailing', 'title'));
     CRM_Core_Form_Date::buildDateRange($this, 'mailing', 1, '_from', '_to', ts('From'), FALSE);
     $this->add('text', 'sort_name', ts('Created or Sent by'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name'));
     CRM_Campaign_BAO_Campaign::addCampaignInComponentSearch($this);
     // CRM-15434 - Fix mailing search by status in non-English languages
     $statusVals = CRM_Core_SelectValues::getMailingJobStatus();
     foreach ($statusVals as $statusId => $statusName) {
         $this->addElement('checkbox', "mailing_status[{$statusId}]", NULL, $statusName);
     }
     $this->addElement('checkbox', 'status_unscheduled', NULL, ts('Draft / Unscheduled'));
     $this->addYesNo('is_archived', ts('Mailing is Archived'), TRUE);
     // Search by language, if multi-lingual
     $enabledLanguages = CRM_Core_I18n::languages(TRUE);
     if (count($enabledLanguages) > 1) {
         $this->addElement('select', 'language', ts('Language'), array('' => ts('- all languages -')) + $enabledLanguages, array('class' => 'crm-select2'));
     }
     if ($parent->_sms) {
         $this->addElement('hidden', 'sms', $parent->_sms);
     }
     $this->add('hidden', 'hidden_find_mailings', 1);
     $this->addButtons(array(array('type' => 'refresh', 'name' => ts('Search'), 'isDefault' => TRUE)));
 }
Example #3
0
 /**
  * This is the main function that is called on every click action and based on the argument
  * respective functions are called
  *
  * @param $args array this array contains the arguments of the url 
  * 
  * @static
  * @access public
  */
 function invoke($args)
 {
     require_once 'CRM/Core/I18n.php';
     require_once 'CRM/Utils/Wrapper.php';
     require_once 'CRM/Core/Action.php';
     require_once 'CRM/Utils/Request.php';
     if ($args[0] !== 'civicrm') {
         return;
     }
     $config =& CRM_Core_Config::singleton();
     // also initialize the i18n framework
     $i18n =& CRM_Core_I18n::singleton();
     if ($config->userFramework == 'Mambo') {
         require_once 'CRM/Core/Mambo.php';
         CRM_Core_Mambo::sidebarLeft();
     }
     switch ($args[1]) {
         case 'contact':
             CRM_Core_Invoke::contact($args);
             break;
         case 'admin':
             CRM_Core_Invoke::admin($args);
             break;
         case 'history':
             CRM_Core_Invoke::history($args);
             break;
         case 'group':
             CRM_Core_Invoke::group($args);
             break;
         case 'import':
             CRM_Core_Invoke::import($args);
             break;
         case 'export':
             CRM_Core_Invoke::export($args);
             break;
         case 'activity':
             CRM_Core_Invoke::activity($args);
             break;
         case 'profile':
             CRM_Core_Invoke::profile($args);
             break;
         case 'server':
             CRM_Core_Invoke::server($args);
             break;
         case 'mailing':
             require_once 'CRM/Mailing/Invoke.php';
             CRM_Mailing_Invoke::main($args);
             break;
         case 'contribute':
             require_once 'CRM/Contribute/Invoke.php';
             CRM_Contribute_Invoke::main($args);
             break;
         default:
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/search/basic', 'reset=1'));
             break;
     }
     return;
 }
Example #4
0
 public function buildQuickForm()
 {
     $config = CRM_Core_Config::singleton();
     global $tsLocale;
     $this->_locales = array_keys($config->languageLimit);
     // get the part of the database we want to edit and validate it
     $table = CRM_Utils_Request::retrieve('table', 'String', $this);
     $field = CRM_Utils_Request::retrieve('field', 'String', $this);
     $id = CRM_Utils_Request::retrieve('id', 'Int', $this);
     $this->_structure = CRM_Core_I18n_SchemaStructure::columns();
     if (!isset($this->_structure[$table][$field])) {
         CRM_Core_Error::fatal("{$table}.{$field} is not internationalized.");
     }
     $this->addElement('hidden', 'table', $table);
     $this->addElement('hidden', 'field', $field);
     $this->addElement('hidden', 'id', $id);
     $cols = array();
     foreach ($this->_locales as $locale) {
         $cols[] = "{$field}_{$locale} {$locale}";
     }
     $query = 'SELECT ' . implode(', ', $cols) . " FROM {$table} WHERE id = {$id}";
     $dao = new CRM_Core_DAO();
     $dao->query($query, FALSE);
     $dao->fetch();
     // get html type and attributes for this field
     $widgets = CRM_Core_I18n_SchemaStructure::widgets();
     $widget = $widgets[$table][$field];
     // attributes
     $attributes = array('class' => '');
     if (isset($widget['rows'])) {
         $attributes['rows'] = $widget['rows'];
     }
     if (isset($widget['cols'])) {
         $attributes['cols'] = $widget['cols'];
     }
     $required = !empty($widget['required']);
     if ($widget['type'] == 'RichTextEditor') {
         $widget['type'] = 'wysiwyg';
         $attributes['class'] .= ' collapsed';
     }
     $languages = CRM_Core_I18n::languages(TRUE);
     foreach ($this->_locales as $locale) {
         $attr = $attributes;
         $name = "{$field}_{$locale}";
         if ($locale == $tsLocale) {
             $attr['class'] .= ' default-lang';
         }
         $this->add($widget['type'], $name, $languages[$locale], $attr, $required);
         $this->_defaults[$name] = $dao->{$locale};
     }
     $this->addDefaultButtons(ts('Save'), 'next', NULL);
     CRM_Utils_System::setTitle(ts('Languages'));
     $this->assign('locales', $this->_locales);
     $this->assign('field', $field);
 }
 function buildQuickForm()
 {
     $config = CRM_Core_Config::singleton();
     $this->_locales = array_keys($config->languageLimit);
     // get the part of the database we want to edit and validate it
     $table = CRM_Utils_Request::retrieve('table', 'String', $this);
     $field = CRM_Utils_Request::retrieve('field', 'String', $this);
     $id = CRM_Utils_Request::retrieve('id', 'Int', $this);
     $this->_structure = CRM_Core_I18n_SchemaStructure::columns();
     if (!isset($this->_structure[$table][$field])) {
         CRM_Core_Error::fatal("{$table}.{$field} is not internationalized.");
     }
     $this->addElement('hidden', 'table', $table);
     $this->addElement('hidden', 'field', $field);
     $this->addElement('hidden', 'id', $id);
     $cols = array();
     foreach ($this->_locales as $locale) {
         $cols[] = "{$field}_{$locale} {$locale}";
     }
     $query = 'SELECT ' . implode(', ', $cols) . " FROM {$table} WHERE id = {$id}";
     $dao = new CRM_Core_DAO();
     $dao->query($query, FALSE);
     $dao->fetch();
     // we want TEXTAREAs for long fields and INPUTs for short ones
     $this->_structure[$table][$field] == 'text' ? $type = 'textarea' : ($type = 'text');
     $languages = CRM_Core_I18n::languages(TRUE);
     foreach ($this->_locales as $locale) {
         $this->addElement($type, "{$field}_{$locale}", $languages[$locale], array('cols' => 60, 'rows' => 3));
         $this->_defaults["{$field}_{$locale}"] = $dao->{$locale};
     }
     $this->addButtons(array(array('type' => 'next', 'name' => ts('Save'), 'isDefault' => TRUE)));
     global $tsLocale;
     $this->assign('tsLocale', $tsLocale);
     $this->assign('locales', $this->_locales);
     $this->assign('field', $field);
     $this->assign('context', CRM_Utils_Request::retrieve('context', 'String', $this));
 }
Example #6
0
 /**
  * @param CRM_Core_DAO $dao
  * @param bool $flip
  * @param bool $grouping
  * @param bool $localize
  * @param string $valueColumnName
  *
  * @return array
  */
 public static function &valuesCommon($dao, $flip = FALSE, $grouping = FALSE, $localize = FALSE, $valueColumnName = 'label')
 {
     self::$_values = array();
     while ($dao->fetch()) {
         if ($flip) {
             if ($grouping) {
                 self::$_values[$dao->value] = $dao->grouping;
             } else {
                 self::$_values[$dao->{$valueColumnName}] = $dao->value;
             }
         } else {
             if ($grouping) {
                 self::$_values[$dao->{$valueColumnName}] = $dao->grouping;
             } else {
                 self::$_values[$dao->value] = $dao->{$valueColumnName};
             }
         }
     }
     if ($localize) {
         $i18n = CRM_Core_I18n::singleton();
         $i18n->localizeArray(self::$_values);
     }
     return self::$_values;
 }
Example #7
0
 private function initialize()
 {
     $config = CRM_Core_Config::singleton();
     if (isset($config->customTemplateDir) && $config->customTemplateDir) {
         $this->template_dir = array_merge(array($config->customTemplateDir), $config->templateDir);
     } else {
         $this->template_dir = $config->templateDir;
     }
     $this->compile_dir = CRM_Utils_File::addTrailingSlash(CRM_Utils_File::addTrailingSlash($config->templateCompileDir) . $this->getLocale());
     CRM_Utils_File::createDir($this->compile_dir);
     CRM_Utils_File::restrictAccess($this->compile_dir);
     // check and ensure it is writable
     // else we sometime suppress errors quietly and this results
     // in blank emails etc
     if (!is_writable($this->compile_dir)) {
         echo "CiviCRM does not have permission to write temp files in {$this->compile_dir}, Exiting";
         exit;
     }
     //Check for safe mode CRM-2207
     if (ini_get('safe_mode')) {
         $this->use_sub_dirs = FALSE;
     } else {
         $this->use_sub_dirs = TRUE;
     }
     $customPluginsDir = NULL;
     if (isset($config->customPHPPathDir)) {
         $customPluginsDir = $config->customPHPPathDir . DIRECTORY_SEPARATOR . 'CRM' . DIRECTORY_SEPARATOR . 'Core' . DIRECTORY_SEPARATOR . 'Smarty' . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR;
         if (!file_exists($customPluginsDir)) {
             $customPluginsDir = NULL;
         }
     }
     $smartyDir = dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'packages' . DIRECTORY_SEPARATOR . 'Smarty' . DIRECTORY_SEPARATOR;
     $pluginsDir = __DIR__ . DIRECTORY_SEPARATOR . 'Smarty' . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR;
     if ($customPluginsDir) {
         $this->plugins_dir = array($customPluginsDir, $smartyDir . 'plugins', $pluginsDir);
     } else {
         $this->plugins_dir = array($smartyDir . 'plugins', $pluginsDir);
     }
     // add the session and the config here
     $session = CRM_Core_Session::singleton();
     $this->assign_by_ref('config', $config);
     $this->assign_by_ref('session', $session);
     global $tsLocale;
     $this->assign('tsLocale', $tsLocale);
     // CRM-7163 hack: we don’t display langSwitch on upgrades anyway
     if (!CRM_Core_Config::isUpgradeMode()) {
         $this->assign('langSwitch', CRM_Core_I18n::languages(TRUE));
     }
     $this->register_function('crmURL', array('CRM_Utils_System', 'crmURL'));
     $this->load_filter('pre', 'resetExtScope');
     $this->assign('crmPermissions', new CRM_Core_Smarty_Permissions());
 }
Example #8
0
 /**
  * Return full month names according to the locale.
  *
  * @return array
  *   1-based array with full month names
  *
  */
 public static function &getFullMonthNames()
 {
     static $fullMonthNames;
     if (!isset($fullMonthNames)) {
         // set LC_TIME and build the arrays from locale-provided names
         CRM_Core_I18n::setLcTime();
         for ($i = 1; $i <= 12; $i++) {
             $fullMonthNames[$i] = strftime('%B', mktime(0, 0, 0, $i, 10, 1970));
         }
     }
     return $fullMonthNames;
 }
Example #9
0
 /**
  *  Get Menu name
  */
 function getMenuName(&$value, &$skipMenuItems)
 {
     // we need to localise the menu labels (CRM-5456) and don’t
     // want to use ts() as it would throw the ts-extractor off
     $i18n =& CRM_Core_I18n::singleton();
     $name = $i18n->crm_translate($value['attributes']['label']);
     $url = str_replace('&', '&amp;', $value['attributes']['url']);
     $permission = $value['attributes']['permission'];
     $operator = $value['attributes']['operator'];
     $parentID = $value['attributes']['parentID'];
     $navID = $value['attributes']['navID'];
     $active = $value['attributes']['active'];
     if (in_array($parentID, $skipMenuItems) || !$active) {
         $skipMenuItems[] = $navID;
         return false;
     }
     $makeLink = false;
     if (isset($url) && $url) {
         if (substr($url, 0, 4) === 'http') {
             $url = $url;
         } else {
             $url = CRM_Utils_System::url($url);
         }
         $makeLink = true;
     }
     if (isset($permission) && $permission) {
         $permissions = explode(',', $permission);
         $config =& CRM_Core_Config::singleton();
         $hasPermission = false;
         foreach ($permissions as $key) {
             $showItem = true;
             //hack to determine if it's a component related permission
             if ($key != 'access CiviCRM' && substr($key, 0, 6) === 'access') {
                 $componentName = trim(substr($key, 6));
                 if (!in_array($componentName, $config->enableComponents) || !CRM_Core_Permission::check($key)) {
                     $showItem = false;
                     if ($operator == 'AND') {
                         $skipMenuItems[] = $navID;
                         return $showItem;
                     }
                 } else {
                     $hasPermission = true;
                 }
             } else {
                 if (!CRM_Core_Permission::check($key)) {
                     $showItem = false;
                     if ($operator == 'AND') {
                         $skipMenuItems[] = $navID;
                         return $showItem;
                     }
                 } else {
                     $hasPermission = true;
                 }
             }
         }
         if (!$showItem && !$hasPermission) {
             $skipMenuItems[] = $navID;
             return false;
         }
     }
     if ($makeLink) {
         return $name = "<a href=\"{$url}\">{$name}</a>";
     }
     return $name;
 }
Example #10
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 #11
0
 static function get($path)
 {
     // return null if menu rebuild
     $config = CRM_Core_Config::singleton();
     $params = array();
     $args = explode('/', $path);
     $elements = array();
     while (!empty($args)) {
         $string = implode('/', $args);
         $string = CRM_Core_DAO::escapeString($string);
         $elements[] = "'{$string}'";
         array_pop($args);
     }
     $queryString = implode(', ', $elements);
     $domainID = CRM_Core_Config::domainID();
     $domainWhereClause = " AND domain_id = {$domainID} ";
     if ($config->isUpgradeMode() && !CRM_Core_DAO::checkFieldExists('civicrm_menu', 'domain_id')) {
         //domain_id wouldn't be available for earlier version of
         //3.0 and therefore can't be used as part of query for
         //upgrade case
         $domainWhereClause = "";
     }
     $query = "\n(\n  SELECT *\n  FROM     civicrm_menu\n  WHERE    path in ( {$queryString} )\n           {$domainWhereClause}\n  ORDER BY length(path) DESC\n  LIMIT    1\n)\n";
     if ($path != 'navigation') {
         $query .= "\nUNION (\n  SELECT *\n  FROM   civicrm_menu\n  WHERE  path IN ( 'navigation' )\n         {$domainWhereClause}\n)\n";
     }
     $menu = new CRM_Core_DAO_Menu();
     $menu->query($query);
     self::$_menuCache = array();
     $menuPath = NULL;
     while ($menu->fetch()) {
         self::$_menuCache[$menu->path] = array();
         CRM_Core_DAO::storeValues($menu, self::$_menuCache[$menu->path]);
         foreach (self::$_serializedElements as $element) {
             self::$_menuCache[$menu->path][$element] = unserialize($menu->{$element});
             if (strpos($path, $menu->path) !== FALSE) {
                 $menuPath =& self::$_menuCache[$menu->path];
             }
         }
     }
     if (strstr($path, 'report/instance')) {
         $args = explode('/', $path);
         if (is_numeric(end($args))) {
             $menuPath['path'] .= '/' . end($args);
         }
     }
     // *FIXME* : hack for 2.1 -> 2.2 upgrades.
     if ($path == 'civicrm/upgrade') {
         $menuPath['page_callback'] = 'CRM_Upgrade_Page_Upgrade';
         $menuPath['access_arguments'][0][] = 'administer CiviCRM';
         $menuPath['access_callback'] = array('CRM_Core_Permission', 'checkMenu');
     }
     // *FIXME* : hack for 4.1 -> 4.2 upgrades.
     if (preg_match('/^civicrm\\/(upgrade\\/)?queue\\//', $path)) {
         CRM_Queue_Menu::alter($path, $menuPath);
     }
     // Part of upgrade framework but not run inside main upgrade because it deletes data
     // Once we have another example of a 'cleanup' we should generalize the clause below so it grabs string
     // which follows upgrade/ and checks for existence of a function in Cleanup class.
     if ($path == 'civicrm/upgrade/cleanup425') {
         $menuPath['page_callback'] = array('CRM_Upgrade_Page_Cleanup', 'cleanup425');
         $menuPath['access_arguments'][0][] = 'administer CiviCRM';
         $menuPath['access_callback'] = array('CRM_Core_Permission', 'checkMenu');
     }
     if (!empty($menuPath)) {
         $i18n = CRM_Core_I18n::singleton();
         $i18n->localizeTitles($menuPath);
     }
     return $menuPath;
 }
 /**
  * Build the form object.
  *
  * @return void
  */
 public function buildQuickForm()
 {
     $config = CRM_Core_Config::singleton();
     $i18n = CRM_Core_I18n::singleton();
     CRM_Utils_System::setTitle(ts('Settings - Localization'));
     $locales = CRM_Core_I18n::languages();
     $warningTitle = json_encode(ts("Warning"));
     $domain = new CRM_Core_DAO_Domain();
     $domain->find(TRUE);
     if ($domain->locales) {
         // for multi-lingual sites, populate default language drop-down with available languages
         $lcMessages = array();
         foreach ($locales as $loc => $lang) {
             if (substr_count($domain->locales, $loc)) {
                 $lcMessages[$loc] = $lang;
             }
         }
         $this->addElement('select', 'lcMessages', ts('Default Language'), $lcMessages);
         // add language limiter and language adder
         $this->addCheckBox('languageLimit', ts('Available Languages'), array_flip($lcMessages), NULL, NULL, NULL, NULL, ' &nbsp; ');
         $this->addElement('select', 'addLanguage', ts('Add Language'), array_merge(array('' => ts('- select -')), array_diff($locales, $lcMessages)));
         // add the ability to return to single language
         $warning = ts('This will make your CiviCRM installation a single-language one again. THIS WILL DELETE ALL DATA RELATED TO LANGUAGES OTHER THAN THE DEFAULT ONE SELECTED ABOVE (and only that language will be preserved).');
         $this->assign('warning', $warning);
         $warning = json_encode($warning);
         $this->addElement('checkbox', 'makeSinglelingual', ts('Return to Single Language'), NULL, array('onChange' => "if (this.checked) CRM.alert({$warning}, {$warningTitle})"));
     } else {
         // for single-lingual sites, populate default language drop-down with all languages
         $this->addElement('select', 'lcMessages', ts('Default Language'), $locales);
         $warning = ts('Enabling multiple languages changes the schema of your database, so make sure you know what you are doing when enabling this function; making a database backup is strongly recommended.');
         $this->assign('warning', $warning);
         $warning = json_encode($warning);
         $validTriggerPermission = CRM_Core_DAO::checkTriggerViewPermission(TRUE);
         if ($validTriggerPermission && !$config->logging) {
             $this->addElement('checkbox', 'makeMultilingual', ts('Enable Multiple Languages'), NULL, array('onChange' => "if (this.checked) CRM.alert({$warning}, {$warningTitle})"));
         }
     }
     $this->addElement('checkbox', 'inheritLocale', ts('Inherit CMS Language'));
     $this->addElement('text', 'monetaryThousandSeparator', ts('Thousands Separator'), array('size' => 2));
     $this->addElement('text', 'monetaryDecimalPoint', ts('Decimal Delimiter'), array('size' => 2));
     $this->addElement('text', 'moneyformat', ts('Monetary Amount Display'));
     $this->addElement('text', 'moneyvalueformat', ts('Monetary Value Display'));
     $country = array();
     CRM_Core_PseudoConstant::populate($country, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active');
     $i18n->localizeArray($country, array('context' => 'country'));
     asort($country);
     $includeCountry =& $this->addElement('advmultiselect', 'countryLimit', ts('Available Countries') . ' ', $country, array('size' => 5, 'style' => 'width:150px', 'class' => 'advmultiselect'));
     $includeCountry->setButtonAttributes('add', array('value' => ts('Add >>')));
     $includeCountry->setButtonAttributes('remove', array('value' => ts('<< Remove')));
     $includeState =& $this->addElement('advmultiselect', 'provinceLimit', ts('Available States and Provinces') . ' ', $country, array('size' => 5, 'style' => 'width:150px', 'class' => 'advmultiselect'));
     $includeState->setButtonAttributes('add', array('value' => ts('Add >>')));
     $includeState->setButtonAttributes('remove', array('value' => ts('<< Remove')));
     $this->addElement('select', 'defaultContactCountry', ts('Default Country'), array('' => ts('- select -')) + $country);
     $this->addChainSelect('defaultContactStateProvince', array('label' => ts('Default State/Province')));
     // we do this only to initialize currencySymbols, kinda hackish but works!
     $config->defaultCurrencySymbol();
     $symbol = $config->currencySymbols;
     foreach ($symbol as $key => $value) {
         $this->_currencySymbols[$key] = "{$key}";
         if ($value) {
             $this->_currencySymbols[$key] .= " ({$value})";
         }
     }
     $this->addElement('select', 'defaultCurrency', ts('Default Currency'), $this->_currencySymbols);
     $includeCurrency =& $this->addElement('advmultiselect', 'currencyLimit', ts('Available Currencies') . ' ', $this->_currencySymbols, array('size' => 5, 'style' => 'width:150px', 'class' => 'advmultiselect'));
     $includeCurrency->setButtonAttributes('add', array('value' => ts('Add >>')));
     $includeCurrency->setButtonAttributes('remove', array('value' => ts('<< Remove')));
     $this->addElement('text', 'legacyEncoding', ts('Legacy Encoding'));
     $this->addElement('text', 'customTranslateFunction', ts('Custom Translate Function'));
     $this->addElement('text', 'fieldSeparator', ts('Import / Export Field Separator'), array('size' => 2));
     $this->addFormRule(array('CRM_Admin_Form_Setting_Localization', 'formRule'));
     parent::buildQuickForm();
 }
Example #13
0
 /**
  * @return array
  */
 public function findLocales()
 {
     require_once 'CRM/Core/Config.php';
     $config = CRM_Core_Config::singleton(FALSE);
     $locales = array();
     $localeDir = CRM_Core_I18n::getResourceDir();
     if (file_exists($localeDir)) {
         $locales = preg_grep('/^[a-z][a-z]_[A-Z][A-Z]$/', scandir($localeDir));
     }
     $localesMask = getenv('CIVICRM_LOCALES');
     if (!empty($localesMask)) {
         $mask = explode(',', $localesMask);
         $locales = array_intersect($locales, $mask);
     }
     if (!in_array('en_US', $locales)) {
         array_unshift($locales, 'en_US');
     }
     return $locales;
 }
Example #14
0
 /**
  * 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'])) {
         // A case could be made for checking isset rather than empty but this is more consistent with previous behaviour.
         if (empty($params['preferred_language']) && ($language = CRM_Core_I18n::getContactDefaultLanguage()) != FALSE) {
             $params['preferred_language'] = $language;
         }
         // CRM-9739: set greeting & addressee if unset and we’re creating a contact.
         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 weird 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 (Civi::settings()->get('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;
     }
     if (!empty($params['updateBlankLocInfo'])) {
         $skipDelete = TRUE;
     }
     //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;
 }
 public static function &stateProvinceForCountry($countryID)
 {
     $query = "\nSELECT civicrm_state_province.name name, civicrm_state_province.id id\n  FROM civicrm_state_province\nWHERE country_id = %1\nORDER BY name";
     $params = array(1 => array($countryID, 'Integer'));
     $dao = CRM_Core_DAO::executeQuery($query, $params);
     $result = array();
     while ($dao->fetch()) {
         $result[$dao->id] = $dao->name;
     }
     // localise the stateProvince names if in an non-en_US locale
     $config = CRM_Core_Config::singleton();
     global $tsLocale;
     if ($tsLocale != '' and $tsLocale != 'en_US') {
         $i18n =& CRM_Core_I18n::singleton();
         $i18n->localizeArray($result);
         asort($result);
     }
     return $result;
 }
Example #16
0
 /**
  * Return languages available in this instance of CiviCRM.
  *
  * @param bool $justEnabled
  *   whether to return all languages or just the enabled ones.
  *
  * @return array
  *   Array of code/language name mappings
  */
 public static function languages($justEnabled = FALSE)
 {
     static $all = NULL;
     static $enabled = NULL;
     if (!$all) {
         $all = CRM_Contact_BAO_Contact::buildOptions('preferred_language');
         // check which ones are available; add them to $all if not there already
         $codes = array();
         if (is_dir(CRM_Core_I18n::getResourceDir()) && ($dir = opendir(CRM_Core_I18n::getResourceDir()))) {
             while ($filename = readdir($dir)) {
                 if (preg_match('/^[a-z][a-z]_[A-Z][A-Z]$/', $filename)) {
                     $codes[] = $filename;
                     if (!isset($all[$filename])) {
                         $all[$filename] = $filename;
                     }
                 }
             }
             closedir($dir);
         }
         // drop the unavailable languages (except en_US)
         foreach (array_keys($all) as $code) {
             if ($code == 'en_US') {
                 continue;
             }
             if (!in_array($code, $codes)) {
                 unset($all[$code]);
             }
         }
     }
     if ($enabled === NULL) {
         $config = CRM_Core_Config::singleton();
         $enabled = array();
         if (isset($config->languageLimit) and $config->languageLimit) {
             foreach ($all as $code => $name) {
                 if (in_array($code, array_keys($config->languageLimit))) {
                     $enabled[$code] = $name;
                 }
             }
         }
     }
     return $justEnabled ? $enabled : $all;
 }
 public static function &stateProvinceForCountry($countryID, $field = 'name')
 {
     static $_cache = NULL;
     $cacheKey = "{$countryID}_{$field}";
     if (!$_cache) {
         $_cache = array();
     }
     if (!empty($_cache[$cacheKey])) {
         return $_cache[$cacheKey];
     }
     $query = "\nSELECT civicrm_state_province.{$field} name, civicrm_state_province.id id\n  FROM civicrm_state_province\nWHERE country_id = %1\nORDER BY name";
     $params = array(1 => array($countryID, 'Integer'));
     $dao = CRM_Core_DAO::executeQuery($query, $params);
     $result = array();
     while ($dao->fetch()) {
         $result[$dao->id] = $dao->name;
     }
     // localise the stateProvince names if in an non-en_US locale
     $config = CRM_Core_Config::singleton();
     global $tsLocale;
     if ($tsLocale != '' and $tsLocale != 'en_US') {
         $i18n = CRM_Core_I18n::singleton();
         $i18n->localizeArray($result, array('context' => 'province'));
         $result = CRM_Utils_Array::asort($result);
     }
     $_cache[$cacheKey] = $result;
     CRM_Utils_Hook::buildStateProvinceForCountry($countryID, $result);
     return $result;
 }
Example #18
0
/**
 * Short-named function for string translation, defined in global scope so it's available everywhere.
 * @param  $text   string  string for translating
 * @param  $params array   an array of additional parameters
 * @return         string  the translated string
 */
function ts($text, $params = array())
{
    static $config = null;
    static $locale = null;
    static $i18n = null;
    static $function = null;
    if ($text == '') {
        return '';
    }
    if (!$config) {
        $config = CRM_Core_Config::singleton();
    }
    global $tsLocale;
    if (!$i18n or $locale != $tsLocale) {
        $i18n =& CRM_Core_I18n::singleton();
        $locale = $tsLocale;
        if (isset($config->customTranslateFunction) and function_exists($config->customTranslateFunction)) {
            $function = $config->customTranslateFunction;
        }
    }
    if ($function) {
        return $function($text, $params);
    } else {
        return $i18n->crm_translate($text, $params);
    }
}
Example #19
0
// This is mostly sympbolic, since nothing we do during the install
// really requires CIVICRM_UF to be defined.
$installTypeToUF = array('wordpress' => 'WordPress', 'drupal' => 'Drupal');
$uf = isset($installTypeToUF[$installType]) ? $installTypeToUF[$installType] : 'Drupal';
define('CIVICRM_UF', $uf);
global $tsLocale;
$tsLocale = 'en_US';
$seedLanguage = 'en_US';
if (isset($_REQUEST['seedLanguage']) and isset($langs[$_REQUEST['seedLanguage']])) {
    $seedLanguage = $_REQUEST['seedLanguage'];
    $tsLocale = $_REQUEST['seedLanguage'];
}
$config = CRM_Core_Config::singleton(FALSE);
$GLOBALS['civicrm_default_error_scope'] = NULL;
// The translation files are in the parent directory (l10n)
$i18n = CRM_Core_I18n::singleton();
global $cmsPath;
if ($installType == 'drupal') {
    //CRM-6840 -don't force to install in sites/all/modules/
    $object = new CRM_Utils_System_Drupal();
    $cmsPath = $object->cmsRootPath();
    $siteDir = getSiteDir($cmsPath, $_SERVER['SCRIPT_FILENAME']);
    $alreadyInstalled = file_exists($cmsPath . CIVICRM_DIRECTORY_SEPARATOR . 'sites' . CIVICRM_DIRECTORY_SEPARATOR . $siteDir . CIVICRM_DIRECTORY_SEPARATOR . 'civicrm.settings.php');
} elseif ($installType == 'wordpress') {
    $cmsPath = WP_PLUGIN_DIR . DIRECTORY_SEPARATOR . 'civicrm';
    $alreadyInstalled = file_exists($cmsPath . CIVICRM_DIRECTORY_SEPARATOR . 'civicrm.settings.php');
}
if ($installType == 'drupal') {
    // Lets check only /modules/.
    $pattern = '/' . preg_quote(CIVICRM_DIRECTORY_SEPARATOR . 'modules', CIVICRM_DIRECTORY_SEPARATOR) . '/';
    if (!preg_match($pattern, str_replace("\\", "/", $_SERVER['SCRIPT_FILENAME']))) {
 /**
  * @param string $phase
  * @return \CRM_Utils_SQL_Select
  * @throws \CRM_Core_Exception
  */
 protected function prepareQuery($phase)
 {
     $defaultParams = array('casActionScheduleId' => $this->actionSchedule->id, 'casMappingId' => $this->mapping->getId(), 'casMappingEntity' => $this->mapping->getEntity(), 'casNow' => $this->now);
     /** @var \CRM_Utils_SQL_Select $query */
     $query = $this->mapping->createQuery($this->actionSchedule, $phase, $defaultParams);
     if ($this->actionSchedule->limit_to) {
         $query->merge($this->prepareContactFilter($query['casContactIdField']));
     }
     if (empty($query['casContactTableAlias'])) {
         $query['casContactTableAlias'] = 'c';
         $query->join('c', "INNER JOIN civicrm_contact c ON c.id = !casContactIdField AND c.is_deleted = 0 AND c.is_deceased = 0 ");
     }
     $multilingual = \CRM_Core_I18n::isMultilingual();
     if ($multilingual && !empty($this->actionSchedule->filter_contact_language)) {
         $query->where($this->prepareLanguageFilter($query['casContactTableAlias']));
     }
     return $query;
 }
Example #21
0
 /**
  * @return array
  */
 public static function getDefaultLocaleOptions()
 {
     $domain = new CRM_Core_DAO_Domain();
     $domain->find(TRUE);
     $locales = CRM_Core_I18n::languages();
     if ($domain->locales) {
         // for multi-lingual sites, populate default language drop-down with available languages
         $defaultLocaleOptions = array();
         foreach ($locales as $loc => $lang) {
             if (substr_count($domain->locales, $loc)) {
                 $defaultLocaleOptions[$loc] = $lang;
             }
         }
     } else {
         $defaultLocaleOptions = $locales;
     }
     return $defaultLocaleOptions;
 }
Example #22
0
 /**
  * class constructor
  *
  * @return CRM_Core_Smarty
  * @access private
  */
 function __construct()
 {
     parent::__construct();
     $config =& CRM_Core_Config::singleton();
     if (isset($config->customTemplateDir) && $config->customTemplateDir) {
         $this->template_dir = array($config->customTemplateDir, $config->templateDir);
     } else {
         $this->template_dir = $config->templateDir;
     }
     $this->compile_dir = $config->templateCompileDir;
     //Check for safe mode CRM-2207
     if (ini_get('safe_mode')) {
         $this->use_sub_dirs = false;
     } else {
         $this->use_sub_dirs = true;
     }
     $this->plugins_dir = array($config->smartyDir . 'plugins', $config->pluginsDir);
     // add the session and the config here
     $session =& CRM_Core_Session::singleton();
     $this->assign_by_ref('config', $config);
     $this->assign_by_ref('session', $session);
     // check default editor and assign to template, store it in session to reduce db calls
     $defaultWysiwygEditor = $session->get('defaultWysiwygEditor');
     if (!$defaultWysiwygEditor && !CRM_Core_Config::isUpgradeMode()) {
         require_once 'CRM/Core/BAO/Preferences.php';
         $defaultWysiwygEditor = CRM_Core_BAO_Preferences::value('editor_id');
         $session->set('defaultWysiwygEditor', $defaultWysiwygEditor);
     }
     $this->assign('defaultWysiwygEditor', $defaultWysiwygEditor);
     global $tsLocale;
     $this->assign('langSwitch', CRM_Core_I18n::languages(true));
     $this->assign('tsLocale', $tsLocale);
     //check if logged in use has access CiviCRM permission and build menu
     require_once 'CRM/Core/Permission.php';
     $buildNavigation = CRM_Core_Permission::check('access CiviCRM');
     $this->assign('buildNavigation', $buildNavigation);
     if (!CRM_Core_Config::isUpgradeMode() && $buildNavigation) {
         require_once 'CRM/Core/BAO/Navigation.php';
         $contactID = $session->get('userID');
         if ($contactID) {
             $navigation =& CRM_Core_BAO_Navigation::createNavigation($contactID);
             $this->assign('navigation', $navigation);
         }
     }
     $this->register_function('crmURL', array('CRM_Utils_System', 'crmURL'));
     $printerFriendly = CRM_Utils_System::makeURL('snippet', false, false) . '2';
     $this->assign('printerFriendly', $printerFriendly);
 }
 /**
  * Build the form object.
  */
 public function buildQuickForm()
 {
     parent::buildQuickForm();
     $this->_mappingID = $mappingID = NULL;
     $providersCount = CRM_SMS_BAO_Provider::activeProviderCount();
     $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
     //CRM-16777: Don't provide access to administer schedule reminder page, with user that does not have 'administer CiviCRM' permission
     if (empty($this->_context) && !CRM_Core_Permission::check('administer CiviCRM')) {
         CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
     } else {
         $this->_compId = CRM_Utils_Request::retrieve('compId', 'Integer', $this);
         if (!CRM_Event_BAO_Event::checkPermission($this->_compId, CRM_Core_Permission::EDIT)) {
             CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
         }
     }
     if ($this->_action & CRM_Core_Action::DELETE) {
         $reminderName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_ActionSchedule', $this->_id, 'title');
         if ($this->_context == 'event') {
             $this->_compId = CRM_Utils_Request::retrieve('compId', 'Integer', $this);
         }
         $this->assign('reminderName', $reminderName);
         return;
     } elseif ($this->_action & CRM_Core_Action::UPDATE) {
         $this->_mappingID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_ActionSchedule', $this->_id, 'mapping_id');
         if ($this->_context == 'event') {
             $this->_compId = CRM_Utils_Request::retrieve('compId', 'Integer', $this);
         }
     } elseif (!empty($this->_context)) {
         if ($this->_context == 'event') {
             $this->_compId = CRM_Utils_Request::retrieve('compId', 'Integer', $this);
             $isTemplate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_compId, 'is_template');
             $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array('id' => $isTemplate ? CRM_Event_ActionMapping::EVENT_TPL_MAPPING_ID : CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID)));
             if ($mapping) {
                 $this->_mappingID = $mapping->getId();
             } else {
                 CRM_Core_Error::fatal('Could not find mapping for event scheduled reminders.');
             }
         }
     }
     if (!empty($_POST) && !empty($_POST['entity']) && empty($this->_context)) {
         $mappingID = $_POST['entity'][0];
     } elseif ($this->_mappingID) {
         $mappingID = $this->_mappingID;
     }
     $this->add('text', 'title', ts('Title'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_ActionSchedule', 'title'), TRUE);
     $mappings = CRM_Core_BAO_ActionSchedule::getMappings();
     $selectedMapping = $mappings[$mappingID ? $mappingID : 1];
     $entityRecipientLabels = $selectedMapping->getRecipientTypes() + CRM_Core_BAO_ActionSchedule::getAdditionalRecipients();
     $this->assign('entityMapping', json_encode(CRM_Utils_Array::collectMethod('getEntity', $mappings)));
     $this->assign('recipientMapping', json_encode(array_combine(array_keys($entityRecipientLabels), array_keys($entityRecipientLabels))));
     if (empty($this->_context)) {
         $sel =& $this->add('hierselect', 'entity', ts('Entity'), array('name' => 'entity[0]', 'style' => 'vertical-align: top;'));
         $sel->setOptions(array(CRM_Utils_Array::collectMethod('getLabel', $mappings), CRM_Core_BAO_ActionSchedule::getAllEntityValueLabels(), CRM_Core_BAO_ActionSchedule::getAllEntityStatusLabels()));
         if (is_a($sel->_elements[1], 'HTML_QuickForm_select')) {
             // make second selector a multi-select -
             $sel->_elements[1]->setMultiple(TRUE);
             $sel->_elements[1]->setSize(5);
         }
         if (is_a($sel->_elements[2], 'HTML_QuickForm_select')) {
             // make third selector a multi-select -
             $sel->_elements[2]->setMultiple(TRUE);
             $sel->_elements[2]->setSize(5);
         }
     } else {
         // Dig deeper - this code is sublimely stupid.
         $allEntityStatusLabels = CRM_Core_BAO_ActionSchedule::getAllEntityStatusLabels();
         $options = $allEntityStatusLabels[$this->_mappingID][0];
         $attributes = array('multiple' => 'multiple', 'class' => 'crm-select2 huge', 'placeholder' => $options[0]);
         unset($options[0]);
         $this->add('select', 'entity', ts('Recipient(s)'), $options, TRUE, $attributes);
         $this->assign('context', $this->_context);
     }
     //get the frequency units.
     $this->_freqUnits = CRM_Core_SelectValues::getRecurringFrequencyUnits();
     $numericOptions = CRM_Core_SelectValues::getNumericOptions(0, 30);
     //reminder_interval
     $this->add('select', 'start_action_offset', ts('When'), $numericOptions);
     $isActive = ts('Send email');
     $recordActivity = ts('Record activity for automated email');
     if ($providersCount) {
         $this->assign('sms', $providersCount);
         $isActive = ts('Send email or SMS');
         $recordActivity = ts('Record activity for automated email or SMS');
         $options = CRM_Core_OptionGroup::values('msg_mode');
         $this->add('select', 'mode', ts('Send as'), $options);
         $providers = CRM_SMS_BAO_Provider::getProviders(NULL, NULL, TRUE, 'is_default desc');
         $providerSelect = array();
         foreach ($providers as $provider) {
             $providerSelect[$provider['id']] = $provider['title'];
         }
         $this->add('select', 'sms_provider_id', ts('SMS Provider'), $providerSelect, TRUE);
     }
     foreach ($this->_freqUnits as $val => $label) {
         $freqUnitsDisplay[$val] = ts('%1(s)', array(1 => $label));
     }
     $this->addDate('absolute_date', ts('Start Date'), FALSE, array('formatType' => 'mailing'));
     //reminder_frequency
     $this->add('select', 'start_action_unit', ts('Frequency'), $freqUnitsDisplay, TRUE);
     $condition = array('before' => ts('before'), 'after' => ts('after'));
     //reminder_action
     $this->add('select', 'start_action_condition', ts('Action Condition'), $condition);
     $this->add('select', 'start_action_date', ts('Date Field'), $selectedMapping->getDateFields(), TRUE);
     $this->addElement('checkbox', 'record_activity', $recordActivity);
     $this->addElement('checkbox', 'is_repeat', ts('Repeat'), NULL, array('onchange' => "return showHideByValue('is_repeat',true,'repeatFields','table-row','radio',false);"));
     $this->add('select', 'repetition_frequency_unit', ts('every'), $freqUnitsDisplay);
     $this->add('select', 'repetition_frequency_interval', ts('every'), $numericOptions);
     $this->add('select', 'end_frequency_unit', ts('until'), $freqUnitsDisplay);
     $this->add('select', 'end_frequency_interval', ts('until'), $numericOptions);
     $this->add('select', 'end_action', ts('Repetition Condition'), $condition, TRUE);
     $this->add('select', 'end_date', ts('Date Field'), $selectedMapping->getDateFields(), TRUE);
     $this->add('text', 'from_name', ts('From Name'));
     $this->add('text', 'from_email', ts('From Email'));
     $recipientListingOptions = array();
     if ($mappingID) {
         $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array('id' => $mappingID)));
     }
     $limitOptions = array('' => '-neither-', 1 => ts('Limit to'), 0 => ts('Also include'));
     $recipientLabels = array('activity' => ts('Recipients'), 'other' => ts('Limit or Add Recipients'));
     $this->assign('recipientLabels', $recipientLabels);
     $this->add('select', 'limit_to', ts('Limit Options'), $limitOptions, FALSE, array('onChange' => "showHideByValue('limit_to','','recipient', 'select','select',true);"));
     $this->add('select', 'recipient', $recipientLabels['other'], $entityRecipientLabels, FALSE, array('onchange' => "showHideByValue('recipient','manual','recipientManual','table-row','select',false); showHideByValue('recipient','group','recipientGroup','table-row','select',false);"));
     if (!empty($this->_submitValues['recipient_listing'])) {
         if (!empty($this->_context)) {
             $recipientListingOptions = CRM_Core_BAO_ActionSchedule::getRecipientListing($this->_mappingID, $this->_submitValues['recipient']);
         } else {
             $recipientListingOptions = CRM_Core_BAO_ActionSchedule::getRecipientListing($_POST['entity'][0], $_POST['recipient']);
         }
     } elseif (!empty($this->_values['recipient_listing'])) {
         $recipientListingOptions = CRM_Core_BAO_ActionSchedule::getRecipientListing($this->_values['mapping_id'], $this->_values['recipient']);
     }
     $this->add('select', 'recipient_listing', ts('Recipient Roles'), $recipientListingOptions, FALSE, array('multiple' => TRUE, 'class' => 'crm-select2 huge', 'placeholder' => TRUE));
     $this->addEntityRef('recipient_manual_id', ts('Manual Recipients'), array('multiple' => TRUE, 'create' => TRUE));
     $this->add('select', 'group_id', ts('Group'), CRM_Core_PseudoConstant::nestedGroup('Mailing'), FALSE, array('class' => 'crm-select2 huge'));
     // multilingual only options
     $multilingual = CRM_Core_I18n::isMultilingual();
     if ($multilingual) {
         $smarty = CRM_Core_Smarty::singleton();
         $smarty->assign('multilingual', $multilingual);
         $languages = CRM_Core_I18n::languages(TRUE);
         $languageFilter = $languages + array(CRM_Core_I18n::NONE => ts('Contacts with no preferred language'));
         $element = $this->add('select', 'filter_contact_language', ts('Recipients language'), $languageFilter, FALSE, array('multiple' => TRUE, 'class' => 'crm-select2', 'placeholder' => TRUE));
         $communicationLanguage = array('' => ts('System default language'), CRM_Core_I18n::AUTO => ts('Follow recipient preferred language'));
         $communicationLanguage = $communicationLanguage + $languages;
         $this->add('select', 'communication_language', ts('Communication language'), $communicationLanguage);
     }
     CRM_Mailing_BAO_Mailing::commonCompose($this);
     $this->add('text', 'subject', ts('Subject'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_ActionSchedule', 'subject'));
     $this->add('checkbox', 'is_active', $isActive);
     $this->addFormRule(array('CRM_Admin_Form_ScheduleReminders', 'formRule'), $this);
     $this->setPageTitle(ts('Scheduled Reminder'));
 }
Example #24
0
 static function get($path)
 {
     // return null if menu rebuild
     $config =& CRM_Core_Config::singleton();
     $params = array();
     $args = explode('/', $path);
     $elements = array();
     while (!empty($args)) {
         $string = implode('/', $args);
         $string = CRM_Core_DAO::escapeString($string);
         $elements[] = "'{$string}'";
         array_pop($args);
     }
     $queryString = implode(', ', $elements);
     $domainID = CRM_Core_Config::domainID();
     $domainWhereClause = " AND domain_id = {$domainID} ";
     if ($path == 'civicrm/upgrade' && !CRM_Core_DAO::checkFieldExists('civicrm_menu', 'domain_id')) {
         //domain_id wouldn't be available for earlier version of
         //3.0 and therefore can't be used as part of query for
         //upgrade case
         $domainWhereClause = "";
     }
     $query = "\n( \n  SELECT * \n  FROM     civicrm_menu \n  WHERE    path in ( {$queryString} )\n           {$domainWhereClause}\n  ORDER BY length(path) DESC\n  LIMIT    1 \n)\n";
     if ($path != 'navigation') {
         $query .= "\nUNION ( \n  SELECT *\n  FROM   civicrm_menu \n  WHERE  path IN ( 'navigation' )\n         {$domainWhereClause}\n)\n";
     }
     require_once "CRM/Core/DAO/Menu.php";
     $menu =& new CRM_Core_DAO_Menu();
     $menu->query($query);
     self::$_menuCache = array();
     $menuPath = null;
     while ($menu->fetch()) {
         self::$_menuCache[$menu->path] = array();
         CRM_Core_DAO::storeValues($menu, self::$_menuCache[$menu->path]);
         foreach (self::$_serializedElements as $element) {
             self::$_menuCache[$menu->path][$element] = unserialize($menu->{$element});
             if (strpos($path, $menu->path) !== false) {
                 $menuPath =& self::$_menuCache[$menu->path];
             }
         }
     }
     // *FIXME* : hack for 2.1 -> 2.2 upgrades.
     if ($path == 'civicrm/upgrade') {
         $menuPath['page_callback'] = 'CRM_Upgrade_Page_Upgrade';
         $menuPath['access_arguments'][0][] = 'administer CiviCRM';
         $menuPath['access_callback'] = array('CRM_Core_Permission', 'checkMenu');
     }
     $i18n =& CRM_Core_I18n::singleton();
     $i18n->localizeTitles($menuPath);
     return $menuPath;
 }
$seedLanguage = 'en_US';
// CRM-16801 This validates that seedLanguage is valid by looking in $langs.
// NB: the variable is initial a $_REQUEST for the initial page reload,
// then becomes a $_POST when the installation form is submitted.
if (isset($_REQUEST['seedLanguage']) and isset($langs[$_REQUEST['seedLanguage']])) {
    $seedLanguage = $_REQUEST['seedLanguage'];
    $tsLocale = $_REQUEST['seedLanguage'];
}
$config = CRM_Core_Config::singleton(FALSE);
$GLOBALS['civicrm_default_error_scope'] = NULL;
// The translation files are in the parent directory (l10n)
$i18n = CRM_Core_I18n::singleton();
// Support for Arabic, Hebrew, Farsi, etc.
// Used in the template.html
$short_lang_code = CRM_Core_I18n_PseudoConstant::shortForLong($tsLocale);
$text_direction = CRM_Core_I18n::isLanguageRTL($tsLocale) ? 'rtl' : 'ltr';
global $cmsPath;
if ($installType == 'drupal') {
    //CRM-6840 -don't force to install in sites/all/modules/
    $object = new CRM_Utils_System_Drupal();
    $cmsPath = $object->cmsRootPath();
    $siteDir = getSiteDir($cmsPath, $_SERVER['SCRIPT_FILENAME']);
    $alreadyInstalled = file_exists($cmsPath . CIVICRM_DIRECTORY_SEPARATOR . 'sites' . CIVICRM_DIRECTORY_SEPARATOR . $siteDir . CIVICRM_DIRECTORY_SEPARATOR . 'civicrm.settings.php');
} elseif ($installType == 'wordpress') {
    $cmsPath = WP_PLUGIN_DIR . DIRECTORY_SEPARATOR . 'civicrm';
    $upload_dir = wp_upload_dir();
    $files_dirname = $upload_dir['basedir'] . DIRECTORY_SEPARATOR . 'civicrm';
    $wp_civi_settings = $upload_dir['basedir'] . DIRECTORY_SEPARATOR . 'civicrm' . DIRECTORY_SEPARATOR . 'civicrm.settings.php';
    $wp_civi_settings_deprectated = CIVICRM_PLUGIN_DIR . 'civicrm.settings.php';
    if (file_exists($wp_civi_settings_deprectated)) {
        $alreadyInstalled = $wp_civi_settings_deprectated;
Example #26
0
 /**
  * return full month names according to the locale
  *
  * @return array  1-based array with full month names
  *
  * @static
  */
 function &getFullMonthNames()
 {
     if (!isset($GLOBALS['_CRM_UTILS_DATE']['fullMonthNames'])) {
         // set LC_TIME and build the arrays from locale-provided names
         CRM_Core_I18n::setLcTime();
         for ($i = 1; $i <= 12; $i++) {
             $GLOBALS['_CRM_UTILS_DATE']['fullMonthNames'][$i] = strftime('%B', mktime(0, 0, 0, $i, 10, 1970));
         }
     }
     return $GLOBALS['_CRM_UTILS_DATE']['fullMonthNames'];
 }
 /**
  * Perform general setup
  *
  * @param array $args list of path parts
  * @void
  */
 public static function init($args)
 {
     // first fire up IDS and check for bad stuff
     $config = CRM_Core_Config::singleton();
     if (!CRM_Core_Permission::check('skip IDS check')) {
         $ids = new CRM_Core_IDS();
         $ids->check($args);
     }
     // also initialize the i18n framework
     require_once 'CRM/Core/I18n.php';
     $i18n = CRM_Core_I18n::singleton();
 }
Example #28
0
 /**
  * Function to get the list the export fields
  *
  * @param int    $selectAll user preference while export
  * @param array  $ids  contact ids
  * @param array  $params associated array of fields
  * @param string $order order by clause
  * @param array  $associated array of fields
  * @param array  $moreReturnProperties additional return fields
  * @param int    $exportMode export mode
  * @param string $componentClause component clause
  *
  * @static
  * @access public
  */
 static function exportComponents($selectAll, $ids, $params, $order = null, $fields = null, $moreReturnProperties = null, $exportMode = CRM_Export_Form_Select::CONTACT_EXPORT, $componentClause = null)
 {
     $headerRows = array();
     $primary = false;
     $returnProperties = array();
     $origFields = $fields;
     $queryMode = null;
     $paymentFields = false;
     $phoneTypes = CRM_Core_PseudoConstant::phoneType();
     $imProviders = CRM_Core_PseudoConstant::IMProvider();
     $contactRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(null, null, null, null, true, 'label', false);
     $queryMode = CRM_Contact_BAO_Query::MODE_CONTACTS;
     switch ($exportMode) {
         case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE;
             break;
         case CRM_Export_Form_Select::EVENT_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_EVENT;
             break;
         case CRM_Export_Form_Select::MEMBER_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_MEMBER;
             break;
         case CRM_Export_Form_Select::PLEDGE_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_PLEDGE;
             break;
         case CRM_Export_Form_Select::CASE_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_CASE;
             break;
         case CRM_Export_Form_Select::GRANT_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_GRANT;
             break;
     }
     require_once 'CRM/Core/BAO/CustomField.php';
     if ($fields) {
         //construct return properties
         $locationTypes =& CRM_Core_PseudoConstant::locationType();
         $locationTypeFields = array('street_address', 'supplemental_address_1', 'supplemental_address_2', 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2', 'state_province', 'country', 'phone', 'email', 'im');
         foreach ($fields as $key => $value) {
             $phoneTypeId = null;
             $imProviderId = null;
             $relationshipTypes = $fieldName = CRM_Utils_Array::value(1, $value);
             if (!$fieldName) {
                 continue;
             }
             // get phoneType id and IM service provider id seperately
             if ($fieldName == 'phone') {
                 $phoneTypeId = CRM_Utils_Array::value(3, $value);
             } else {
                 if ($fieldName == 'im') {
                     $imProviderId = CRM_Utils_Array::value(3, $value);
                 }
             }
             if (array_key_exists($relationshipTypes, $contactRelationshipTypes)) {
                 if (CRM_Utils_Array::value(2, $value)) {
                     $relationField = CRM_Utils_Array::value(2, $value);
                     if (trim(CRM_Utils_Array::value(3, $value))) {
                         $relLocTypeId = CRM_Utils_Array::value(3, $value);
                     } else {
                         $relLocTypeId = 1;
                     }
                     if ($relationField == 'phone') {
                         $relPhoneTypeId = CRM_Utils_Array::value(4, $value);
                     } else {
                         if ($relationField == 'im') {
                             $relIMProviderId = CRM_Utils_Array::value(4, $value);
                         }
                     }
                 } else {
                     if (CRM_Utils_Array::value(4, $value)) {
                         $relationField = CRM_Utils_Array::value(4, $value);
                         $relLocTypeId = CRM_Utils_Array::value(5, $value);
                         if ($relationField == 'phone') {
                             $relPhoneTypeId = CRM_Utils_Array::value(6, $value);
                         } else {
                             if ($relationField == 'im') {
                                 $relIMProviderId = CRM_Utils_Array::value(6, $value);
                             }
                         }
                     }
                 }
             }
             $contactType = CRM_Utils_Array::value(0, $value);
             $locTypeId = CRM_Utils_Array::value(2, $value);
             $phoneTypeId = CRM_Utils_Array::value(3, $value);
             if ($relationField) {
                 if (in_array($relationField, $locationTypeFields)) {
                     if ($relPhoneTypeId) {
                         $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1;
                     } else {
                         if ($relIMProviderId) {
                             $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['im-' . $relIMProviderId] = 1;
                         } else {
                             $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]][$relationField] = 1;
                         }
                     }
                     $relPhoneTypeId = $relIMProviderId = null;
                 } else {
                     $returnProperties[$relationshipTypes][$relationField] = 1;
                 }
             } else {
                 if (is_numeric($locTypeId)) {
                     if ($phoneTypeId) {
                         $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . $phoneTypeId] = 1;
                     } else {
                         if (isset($imProviderId)) {
                             //build returnProperties for IM service provider
                             $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . $imProviderId] = 1;
                         } else {
                             $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1;
                         }
                     }
                 } else {
                     //hack to fix component fields
                     if ($fieldName == 'event_id') {
                         $returnProperties['event_title'] = 1;
                     } else {
                         $returnProperties[$fieldName] = 1;
                     }
                 }
             }
         }
         // hack to add default returnproperty based on export mode
         if ($exportMode == CRM_Export_Form_Select::CONTRIBUTE_EXPORT) {
             $returnProperties['contribution_id'] = 1;
         } else {
             if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
                 $returnProperties['participant_id'] = 1;
             } else {
                 if ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) {
                     $returnProperties['membership_id'] = 1;
                 } else {
                     if ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) {
                         $returnProperties['pledge_id'] = 1;
                     } else {
                         if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) {
                             $returnProperties['case_id'] = 1;
                         } else {
                             if ($exportMode == CRM_Export_Form_Select::GRANT_EXPORT) {
                                 $returnProperties['grant_id'] = 1;
                             }
                         }
                     }
                 }
             }
         }
     } else {
         $primary = true;
         $fields = CRM_Contact_BAO_Contact::exportableFields('All', true, true);
         foreach ($fields as $key => $var) {
             if ($key && substr($key, 0, 6) != 'custom') {
                 //for CRM=952
                 $returnProperties[$key] = 1;
             }
         }
         if ($primary) {
             $returnProperties['location_type'] = 1;
             $returnProperties['im_provider'] = 1;
             $returnProperties['phone_type_id'] = 1;
             $returnProperties['provider_id'] = 1;
             $returnProperties['current_employer'] = 1;
         }
         $extraReturnProperties = array();
         $paymentFields = false;
         switch ($queryMode) {
             case CRM_Contact_BAO_Query::MODE_EVENT:
                 $paymentFields = true;
                 $paymentTableId = "participant_id";
                 break;
             case CRM_Contact_BAO_Query::MODE_MEMBER:
                 $paymentFields = true;
                 $paymentTableId = "membership_id";
                 break;
             case CRM_Contact_BAO_Query::MODE_PLEDGE:
                 require_once 'CRM/Pledge/BAO/Query.php';
                 $extraReturnProperties = CRM_Pledge_BAO_Query::extraReturnProperties($queryMode);
                 $paymentFields = true;
                 $paymentTableId = "pledge_payment_id";
                 break;
             case CRM_Contact_BAO_Query::MODE_CASE:
                 require_once 'CRM/Case/BAO/Query.php';
                 $extraReturnProperties = CRM_Case_BAO_Query::extraReturnProperties($queryMode);
                 break;
         }
         if ($queryMode != CRM_Contact_BAO_Query::MODE_CONTACTS) {
             $componentReturnProperties =& CRM_Contact_BAO_Query::defaultReturnProperties($queryMode);
             $returnProperties = array_merge($returnProperties, $componentReturnProperties);
             if (!empty($extraReturnProperties)) {
                 $returnProperties = array_merge($returnProperties, $extraReturnProperties);
             }
             // unset groups, tags, notes for components
             foreach (array('groups', 'tags', 'notes') as $value) {
                 unset($returnProperties[$value]);
             }
         }
     }
     if ($moreReturnProperties) {
         $returnProperties = array_merge($returnProperties, $moreReturnProperties);
     }
     $query =& new CRM_Contact_BAO_Query(0, $returnProperties, null, false, false, $queryMode);
     list($select, $from, $where) = $query->query();
     $allRelContactArray = $relationQuery = array();
     foreach ($contactRelationshipTypes as $rel => $dnt) {
         if ($relationReturnProperties = CRM_Utils_Array::value($rel, $returnProperties)) {
             $allRelContactArray[$rel] = array();
             // build Query for each relationship
             $relationQuery[$rel] =& new CRM_Contact_BAO_Query(0, $relationReturnProperties, null, false, false, $queryMode);
             list($relationSelect, $relationFrom, $relationWhere) = $relationQuery[$rel]->query();
             list($id, $direction) = explode('_', $rel, 2);
             // identify the relationship direction
             $contactA = 'contact_id_a';
             $contactB = 'contact_id_b';
             if ($direction == 'b_a') {
                 $contactA = 'contact_id_b';
                 $contactB = 'contact_id_a';
             }
             $relIDs = implode(',', $ids);
             $relSQL = "SELECT {$contactB} as relContact,{$contactA} as refContact  FROM civicrm_relationship \n                           WHERE  relationship_type_id = {$id} AND\n                                  {$contactA} IN ({$relIDs})\n                           GROUP BY {$contactA}";
             // Get the related contacts
             $relContactDAO = CRM_Core_DAO::executeQuery($relSQL);
             $relContactArray = array();
             while ($relContactDAO->fetch()) {
                 $relContactArray[$relContactDAO->refContact] = $relContactDAO->relContact;
             }
             $uniqueContacts = array_unique($relContactArray);
             if (!empty($uniqueContacts)) {
                 $relationWhere = " WHERE contact_a.id IN (" . implode(',', $uniqueContacts) . ") GROUP BY contact_id";
                 $relationQueryString = "{$relationSelect} {$relationFrom} {$relationWhere}";
                 $allRelContactDAO = CRM_Core_DAO::executeQuery($relationQueryString);
                 while ($allRelContactDAO->fetch()) {
                     foreach ($relContactArray as $k => $v) {
                         if ($allRelContactDAO->contact_id == $v) {
                             //$allRelContactArray[$rel][$k] = array();
                             // build the array of all related contacts
                             $allRelContactArray[$rel][$k] = clone $allRelContactDAO;
                         }
                     }
                 }
             }
         }
     }
     // make sure the groups stuff is included only if specifically specified
     // by the fields param (CRM-1969), else we limit the contacts outputted to only
     // ones that are part of a group
     if (CRM_Utils_Array::value('groups', $returnProperties)) {
         $oldClause = "contact_a.id = civicrm_group_contact.contact_id";
         $newClause = " ( {$oldClause} AND civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) ";
         // total hack for export, CRM-3618
         $from = str_replace($oldClause, $newClause, $from);
     }
     if ($componentClause) {
         if (empty($where)) {
             $where = "WHERE {$componentClause}";
         } else {
             $where .= " AND {$componentClause}";
         }
     }
     $queryString = "{$select} {$from} {$where}";
     if (CRM_Utils_Array::value('tags', $returnProperties) || CRM_Utils_Array::value('groups', $returnProperties) || CRM_Utils_Array::value('notes', $returnProperties) || $query->_useGroupBy) {
         $queryString .= " GROUP BY contact_a.id";
     }
     if ($order) {
         list($field, $dir) = explode(' ', $order, 2);
         $field = trim($field);
         if (CRM_Utils_Array::value($field, $returnProperties)) {
             $queryString .= " ORDER BY {$order}";
         }
     }
     //hack for student data
     require_once 'CRM/Core/OptionGroup.php';
     $multipleSelectFields = array('preferred_communication_method' => 1);
     if (CRM_Core_Permission::access('Quest')) {
         require_once 'CRM/Quest/BAO/Student.php';
         $studentFields = array();
         $studentFields = CRM_Quest_BAO_Student::$multipleSelectFields;
         $multipleSelectFields = array_merge($multipleSelectFields, $studentFields);
     }
     $dao =& CRM_Core_DAO::executeQuery($queryString, CRM_Core_DAO::$_nullArray);
     $header = false;
     $addPaymentHeader = false;
     if ($paymentFields) {
         $addPaymentHeader = true;
         //special return properties for event and members
         $paymentHeaders = array(ts('Total Amount'), ts('Contribution Status'), ts('Received Date'), ts('Payment Instrument'), ts('Transaction ID'));
         // get payment related in for event and members
         require_once 'CRM/Contribute/BAO/Contribution.php';
         $paymentDetails = CRM_Contribute_BAO_Contribution::getContributionDetails($exportMode, $ids);
     }
     $componentDetails = $headerRows = array();
     $setHeader = true;
     while ($dao->fetch()) {
         $row = array();
         //first loop through returnproperties so that we return what is required, and in same order.
         $relationshipField = 0;
         foreach ($returnProperties as $field => $value) {
             //we should set header only once
             if ($setHeader) {
                 if (isset($query->_fields[$field]['title'])) {
                     $headerRows[] = $query->_fields[$field]['title'];
                 } else {
                     if ($field == 'phone_type_id') {
                         $headerRows[] = 'Phone Type';
                     } else {
                         if ($field == 'provider_id') {
                             $headerRows[] = 'Im Service Provider';
                         } else {
                             if (is_array($value) && $field == 'location') {
                                 // fix header for location type case
                                 foreach ($value as $ltype => $val) {
                                     foreach (array_keys($val) as $fld) {
                                         $type = explode('-', $fld);
                                         $hdr = "{$ltype}-" . $query->_fields[$type[0]]['title'];
                                         if (CRM_Utils_Array::value(1, $type)) {
                                             if (CRM_Utils_Array::value(0, $type) == 'phone') {
                                                 $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
                                             } else {
                                                 if (CRM_Utils_Array::value(0, $type) == 'im') {
                                                     $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders);
                                                 }
                                             }
                                         }
                                         $headerRows[] = $hdr;
                                     }
                                 }
                             } else {
                                 if (substr($field, 0, 5) == 'case_') {
                                     if ($query->_fields['case'][$field]['title']) {
                                         $headerRows[] = $query->_fields['case'][$field]['title'];
                                     } else {
                                         if ($query->_fields['activity'][$field]['title']) {
                                             $headerRows[] = $query->_fields['activity'][$field]['title'];
                                         }
                                     }
                                 } else {
                                     if (array_key_exists($field, $contactRelationshipTypes)) {
                                         $relName = CRM_Utils_Array::value($field, $contactRelationshipTypes);
                                         foreach ($value as $relationField => $relationValue) {
                                             // below block is same as primary block (duplicate)
                                             if (isset($relationQuery[$field]->_fields[$relationField]['title'])) {
                                                 $headerRows[] = $relName . '-' . $relationQuery[$field]->_fields[$relationField]['title'];
                                             } else {
                                                 if ($relationField == 'phone_type_id') {
                                                     $headerRows[] = $relName . '-' . 'Phone Type';
                                                 } else {
                                                     if ($relationField == 'provider_id') {
                                                         $headerRows[] = $relName . '-' . 'Im Service Provider';
                                                     } else {
                                                         if (is_array($relationValue) && $relationField == 'location') {
                                                             // fix header for location type case
                                                             foreach ($relationValue as $ltype => $val) {
                                                                 foreach (array_keys($val) as $fld) {
                                                                     $type = explode('-', $fld);
                                                                     $hdr = "{$ltype}-" . $relationQuery[$field]->_fields[$type[0]]['title'];
                                                                     if (CRM_Utils_Array::value(1, $type)) {
                                                                         if (CRM_Utils_Array::value(0, $type) == 'phone') {
                                                                             $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
                                                                         } else {
                                                                             if (CRM_Utils_Array::value(0, $type) == 'im') {
                                                                                 $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders);
                                                                             }
                                                                         }
                                                                     }
                                                                     $headerRows[] = $relName . '-' . $hdr;
                                                                 }
                                                             }
                                                         }
                                                     }
                                                 }
                                             }
                                         }
                                     } else {
                                         $headerRows[] = $field;
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
             //build row values (data)
             if (property_exists($dao, $field)) {
                 $fieldValue = $dao->{$field};
                 // to get phone type from phone type id
                 if ($field == 'phone_type_id') {
                     $fieldValue = $phoneTypes[$fieldValue];
                 } else {
                     if ($field == 'provider_id') {
                         $fieldValue = CRM_Utils_Array::value($fieldValue, $imProviders);
                     }
                 }
             } else {
                 $fieldValue = '';
             }
             if ($field == 'id') {
                 $row[$field] = $dao->contact_id;
             } else {
                 if ($field == 'pledge_balance_amount') {
                     //special case for calculated field
                     $row[$field] = $dao->pledge_amount - $dao->pledge_total_paid;
                 } else {
                     if ($field == 'pledge_next_pay_amount') {
                         //special case for calculated field
                         $row[$field] = $dao->pledge_next_pay_amount + $dao->pledge_outstanding_amount;
                     } else {
                         if (is_array($value) && $field == 'location') {
                             // fix header for location type case
                             foreach ($value as $ltype => $val) {
                                 foreach (array_keys($val) as $fld) {
                                     $type = explode('-', $fld);
                                     $fldValue = "{$ltype}-" . $type[0];
                                     if (CRM_Utils_Array::value(1, $type)) {
                                         $fldValue .= "-" . $type[1];
                                     }
                                     $row[$fldValue] = $dao->{$fldValue};
                                 }
                             }
                         } else {
                             if (array_key_exists($field, $contactRelationshipTypes)) {
                                 $relDAO = $allRelContactArray[$field][$dao->contact_id];
                                 foreach ($value as $relationField => $relationValue) {
                                     if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
                                         $fieldValue = $relDAO->{$relationField};
                                         if ($relationField == 'phone_type_id') {
                                             $fieldValue = $phoneTypes[$relationValue];
                                         } else {
                                             if ($relationField == 'provider_id') {
                                                 $fieldValue = CRM_Utils_Array::value($relationValue, $imProviders);
                                             }
                                         }
                                     } else {
                                         $fieldValue = '';
                                     }
                                     if ($relationField == 'id') {
                                         $row[$field . $relationField] = $relDAO->contact_id;
                                     } else {
                                         if (is_array($relationValue) && $relationField == 'location') {
                                             foreach ($relationValue as $ltype => $val) {
                                                 foreach (array_keys($val) as $fld) {
                                                     $type = explode('-', $fld);
                                                     $fldValue = "{$ltype}-" . $type[0];
                                                     if (CRM_Utils_Array::value(1, $type)) {
                                                         $fldValue .= "-" . $type[1];
                                                     }
                                                     $row[$field . $fldValue] = $relDAO->{$fldValue};
                                                 }
                                             }
                                         } else {
                                             if (isset($fieldValue) && $fieldValue != '') {
                                                 //check for custom data
                                                 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationField)) {
                                                     $row[$field . $relationField] = CRM_Core_BAO_CustomField::getDisplayValue($fieldValue, $cfID, $relationQuery[$field]->_options);
                                                 } else {
                                                     if (in_array($relationField, array('email_greeting', 'postal_greeting', 'addressee'))) {
                                                         //special case for greeting replacement
                                                         $fldValue = "{$relationField}_display";
                                                         $row[$field . $relationField] = $relDAO->{$fldValue};
                                                     } else {
                                                         //normal relationship fields
                                                         $row[$field . $relationField] = $fieldValue;
                                                     }
                                                 }
                                             } else {
                                                 // if relation field is empty or null
                                                 $row[$field . $relationField] = '';
                                             }
                                         }
                                     }
                                 }
                             } else {
                                 if (isset($fieldValue) && $fieldValue != '') {
                                     //check for custom data
                                     if ($cfID = CRM_Core_BAO_CustomField::getKeyID($field)) {
                                         $row[$field] = CRM_Core_BAO_CustomField::getDisplayValue($fieldValue, $cfID, $query->_options);
                                     } else {
                                         if (array_key_exists($field, $multipleSelectFields)) {
                                             //option group fixes
                                             $paramsNew = array($field => $fieldValue);
                                             if ($field == 'test_tutoring') {
                                                 $name = array($field => array('newName' => $field, 'groupName' => 'test'));
                                             } else {
                                                 if (substr($field, 0, 4) == 'cmr_') {
                                                     //for  readers group
                                                     $name = array($field => array('newName' => $field, 'groupName' => substr($field, 0, -3)));
                                                 } else {
                                                     $name = array($field => array('newName' => $field, 'groupName' => $field));
                                                 }
                                             }
                                             CRM_Core_OptionGroup::lookupValues($paramsNew, $name, false);
                                             $row[$field] = $paramsNew[$field];
                                         } else {
                                             if (in_array($field, array('email_greeting', 'postal_greeting', 'addressee'))) {
                                                 //special case for greeting replacement
                                                 $fldValue = "{$field}_display";
                                                 $row[$field] = $dao->{$fldValue};
                                             } else {
                                                 //normal fields
                                                 $row[$field] = $fieldValue;
                                             }
                                         }
                                     }
                                 } else {
                                     // if field is empty or null
                                     $row[$field] = '';
                                 }
                             }
                         }
                     }
                 }
             }
         }
         //build header only once
         $setHeader = false;
         // add payment headers if required
         if ($addPaymentHeader && $paymentFields) {
             $headerRows = array_merge($headerRows, $paymentHeaders);
             $addPaymentHeader = false;
         }
         // add payment related information
         if ($paymentFields && isset($paymentDetails[$row[$paymentTableId]])) {
             $row = array_merge($row, $paymentDetails[$row[$paymentTableId]]);
         }
         //remove organization name for individuals if it is set for current employer
         if (CRM_Utils_Array::value('contact_type', $row) && $row['contact_type'] == 'Individual') {
             $row['organization_name'] = '';
         }
         // CRM-3157: localise the output
         // FIXME: we should move this to multilingual stack some day
         require_once 'CRM/Core/I18n.php';
         $i18n =& CRM_Core_I18n::singleton();
         $translatable = array('preferred_communication_method', 'preferred_mail_format', 'gender', 'state_province', 'country', 'world_region');
         foreach ($translatable as $column) {
             if (isset($row[$column]) and $row[$column]) {
                 $row[$column] = $i18n->translate($row[$column]);
             }
         }
         // add component info
         $componentDetails[] = $row;
     }
     require_once 'CRM/Core/Report/Excel.php';
     CRM_Core_Report_Excel::writeCSVFile(self::getExportFileName('csv', $exportMode), $headerRows, $componentDetails);
     exit;
 }
Example #29
0
 /**
  * Get the list the export fields.
  *
  * @param int $selectAll
  *   User preference while export.
  * @param array $ids
  *   Contact ids.
  * @param array $params
  *   Associated array of fields.
  * @param string $order
  *   Order by clause.
  * @param array $fields
  *   Associated array of fields.
  * @param array $moreReturnProperties
  *   Additional return fields.
  * @param int $exportMode
  *   Export mode.
  * @param string $componentClause
  *   Component clause.
  * @param string $componentTable
  *   Component table.
  * @param bool $mergeSameAddress
  *   Merge records if they have same address.
  * @param bool $mergeSameHousehold
  *   Merge records if they belong to the same household.
  *
  * @param array $exportParams
  * @param string $queryOperator
  *
  */
 public static function exportComponents($selectAll, $ids, $params, $order = NULL, $fields = NULL, $moreReturnProperties = NULL, $exportMode = CRM_Export_Form_Select::CONTACT_EXPORT, $componentClause = NULL, $componentTable = NULL, $mergeSameAddress = FALSE, $mergeSameHousehold = FALSE, $exportParams = array(), $queryOperator = 'AND')
 {
     $headerRows = $returnProperties = array();
     $primary = $paymentFields = $selectedPaymentFields = FALSE;
     $origFields = $fields;
     $relationField = NULL;
     $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
     $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
     $contactRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE, 'name', FALSE);
     $queryMode = self::getQueryMode($exportMode);
     if ($fields) {
         //construct return properties
         $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
         $locationTypeFields = array('street_address', 'supplemental_address_1', 'supplemental_address_2', 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2', 'state_province', 'country', 'phone', 'email', 'im');
         foreach ($fields as $key => $value) {
             $phoneTypeId = $imProviderId = NULL;
             $relationshipTypes = $fieldName = CRM_Utils_Array::value(1, $value);
             if (!$fieldName) {
                 continue;
             }
             // get phoneType id and IM service provider id separately
             if ($fieldName == 'phone') {
                 $phoneTypeId = CRM_Utils_Array::value(3, $value);
             } elseif ($fieldName == 'im') {
                 $imProviderId = CRM_Utils_Array::value(3, $value);
             }
             if (array_key_exists($relationshipTypes, $contactRelationshipTypes)) {
                 if (!empty($value[2])) {
                     $relationField = CRM_Utils_Array::value(2, $value);
                     if (trim(CRM_Utils_Array::value(3, $value))) {
                         $relLocTypeId = CRM_Utils_Array::value(3, $value);
                     } else {
                         $relLocTypeId = 'Primary';
                     }
                     if ($relationField == 'phone') {
                         $relPhoneTypeId = CRM_Utils_Array::value(4, $value);
                     } elseif ($relationField == 'im') {
                         $relIMProviderId = CRM_Utils_Array::value(4, $value);
                     }
                 } elseif (!empty($value[4])) {
                     $relationField = CRM_Utils_Array::value(4, $value);
                     $relLocTypeId = CRM_Utils_Array::value(5, $value);
                     if ($relationField == 'phone') {
                         $relPhoneTypeId = CRM_Utils_Array::value(6, $value);
                     } elseif ($relationField == 'im') {
                         $relIMProviderId = CRM_Utils_Array::value(6, $value);
                     }
                 }
             }
             $contactType = CRM_Utils_Array::value(0, $value);
             $locTypeId = CRM_Utils_Array::value(2, $value);
             if ($relationField) {
                 if (in_array($relationField, $locationTypeFields) && is_numeric($relLocTypeId)) {
                     if ($relPhoneTypeId) {
                         $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1;
                     } elseif ($relIMProviderId) {
                         $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['im-' . $relIMProviderId] = 1;
                     } else {
                         $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]][$relationField] = 1;
                     }
                     $relPhoneTypeId = $relIMProviderId = NULL;
                 } else {
                     $returnProperties[$relationshipTypes][$relationField] = 1;
                 }
             } elseif (is_numeric($locTypeId)) {
                 if ($phoneTypeId) {
                     $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . $phoneTypeId] = 1;
                 } elseif ($imProviderId) {
                     $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . $imProviderId] = 1;
                 } else {
                     $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1;
                 }
             } else {
                 //hack to fix component fields
                 //revert mix of event_id and title
                 if ($fieldName == 'event_id') {
                     $returnProperties['event_id'] = 1;
                 } elseif ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT && array_key_exists($fieldName, self::componentPaymentFields())) {
                     $selectedPaymentFields = TRUE;
                     $paymentTableId = 'participant_id';
                     $returnProperties[$fieldName] = 1;
                 } else {
                     $returnProperties[$fieldName] = 1;
                 }
             }
         }
         $returnProperties[self::defaultReturnProperty($exportMode)] = 1;
     } else {
         $primary = TRUE;
         $fields = CRM_Contact_BAO_Contact::exportableFields('All', TRUE, TRUE);
         foreach ($fields as $key => $var) {
             if ($key && substr($key, 0, 6) != 'custom') {
                 //for CRM=952
                 $returnProperties[$key] = 1;
             }
         }
         if ($primary) {
             $returnProperties['location_type'] = 1;
             $returnProperties['im_provider'] = 1;
             $returnProperties['phone_type_id'] = 1;
             $returnProperties['provider_id'] = 1;
             $returnProperties['current_employer'] = 1;
         }
         $extraReturnProperties = array();
         $paymentFields = FALSE;
         switch ($queryMode) {
             case CRM_Contact_BAO_Query::MODE_EVENT:
                 $paymentFields = TRUE;
                 $paymentTableId = 'participant_id';
                 break;
             case CRM_Contact_BAO_Query::MODE_MEMBER:
                 $paymentFields = TRUE;
                 $paymentTableId = 'membership_id';
                 break;
             case CRM_Contact_BAO_Query::MODE_PLEDGE:
                 $extraReturnProperties = CRM_Pledge_BAO_Query::extraReturnProperties($queryMode);
                 $paymentFields = TRUE;
                 $paymentTableId = 'pledge_payment_id';
                 break;
             case CRM_Contact_BAO_Query::MODE_CASE:
                 $extraReturnProperties = CRM_Case_BAO_Query::extraReturnProperties($queryMode);
                 break;
         }
         if ($queryMode != CRM_Contact_BAO_Query::MODE_CONTACTS) {
             $componentReturnProperties = CRM_Contact_BAO_Query::defaultReturnProperties($queryMode);
             if ($queryMode == CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
                 // soft credit columns are not automatically populated, because contribution search doesn't require them by default
                 $componentReturnProperties = array_merge($componentReturnProperties, CRM_Contribute_BAO_Query::softCreditReturnProperties(TRUE));
             }
             $returnProperties = array_merge($returnProperties, $componentReturnProperties);
             if (!empty($extraReturnProperties)) {
                 $returnProperties = array_merge($returnProperties, $extraReturnProperties);
             }
             // unset non exportable fields for components
             $nonExpoFields = array('groups', 'tags', 'notes', 'contribution_status_id', 'pledge_status_id', 'pledge_payment_status_id');
             foreach ($nonExpoFields as $value) {
                 unset($returnProperties[$value]);
             }
         }
     }
     if ($mergeSameAddress) {
         //make sure the addressee fields are selected
         //while using merge same address feature
         $returnProperties['addressee'] = 1;
         $returnProperties['postal_greeting'] = 1;
         $returnProperties['email_greeting'] = 1;
         $returnProperties['street_name'] = 1;
         $returnProperties['household_name'] = 1;
         $returnProperties['street_address'] = 1;
         $returnProperties['city'] = 1;
         $returnProperties['state_province'] = 1;
         // some columns are required for assistance incase they are not already present
         $exportParams['merge_same_address']['temp_columns'] = array();
         $tempColumns = array('id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id');
         foreach ($tempColumns as $column) {
             if (!array_key_exists($column, $returnProperties)) {
                 $returnProperties[$column] = 1;
                 $column = $column == 'id' ? 'civicrm_primary_id' : $column;
                 $exportParams['merge_same_address']['temp_columns'][$column] = 1;
             }
         }
     }
     if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
         // If an Additional Group is selected, then all contacts in that group are
         // added to the export set (filtering out duplicates).
         $query = "\nINSERT INTO {$componentTable} SELECT distinct gc.contact_id FROM civicrm_group_contact gc WHERE gc.group_id = {$exportParams['additional_group']} ON DUPLICATE KEY UPDATE {$componentTable}.contact_id = gc.contact_id";
         CRM_Core_DAO::executeQuery($query);
     }
     if ($moreReturnProperties) {
         // fix for CRM-7066
         if (!empty($moreReturnProperties['group'])) {
             unset($moreReturnProperties['group']);
             $moreReturnProperties['groups'] = 1;
         }
         $returnProperties = array_merge($returnProperties, $moreReturnProperties);
     }
     $exportParams['postal_mailing_export']['temp_columns'] = array();
     if ($exportParams['exportOption'] == 2 && isset($exportParams['postal_mailing_export']) && CRM_Utils_Array::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1) {
         $postalColumns = array('is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1');
         foreach ($postalColumns as $column) {
             if (!array_key_exists($column, $returnProperties)) {
                 $returnProperties[$column] = 1;
                 $exportParams['postal_mailing_export']['temp_columns'][$column] = 1;
             }
         }
     }
     // rectify params to what proximity search expects if there is a value for prox_distance
     // CRM-7021
     if (!empty($params)) {
         CRM_Contact_BAO_ProximityQuery::fixInputParams($params);
     }
     $query = new CRM_Contact_BAO_Query($params, $returnProperties, NULL, FALSE, FALSE, $queryMode, FALSE, TRUE, TRUE, NULL, $queryOperator);
     //sort by state
     //CRM-15301
     $query->_sort = $order;
     list($select, $from, $where, $having) = $query->query();
     if ($mergeSameHousehold == 1) {
         if (!$returnProperties['id']) {
             $returnProperties['id'] = 1;
         }
         //also merge Head of Household
         $relationKeyMOH = CRM_Utils_Array::key('Household Member of', $contactRelationshipTypes);
         $relationKeyHOH = CRM_Utils_Array::key('Head of Household for', $contactRelationshipTypes);
         foreach ($returnProperties as $key => $value) {
             if (!array_key_exists($key, $contactRelationshipTypes)) {
                 $returnProperties[$relationKeyMOH][$key] = $value;
                 $returnProperties[$relationKeyHOH][$key] = $value;
             }
         }
         unset($returnProperties[$relationKeyMOH]['location_type']);
         unset($returnProperties[$relationKeyMOH]['im_provider']);
         unset($returnProperties[$relationKeyHOH]['location_type']);
         unset($returnProperties[$relationKeyHOH]['im_provider']);
     }
     $allRelContactArray = $relationQuery = array();
     foreach ($contactRelationshipTypes as $rel => $dnt) {
         if ($relationReturnProperties = CRM_Utils_Array::value($rel, $returnProperties)) {
             $allRelContactArray[$rel] = array();
             // build Query for each relationship
             $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties, NULL, FALSE, FALSE, $queryMode);
             list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query();
             list($id, $direction) = explode('_', $rel, 2);
             // identify the relationship direction
             $contactA = 'contact_id_a';
             $contactB = 'contact_id_b';
             if ($direction == 'b_a') {
                 $contactA = 'contact_id_b';
                 $contactB = 'contact_id_a';
             }
             if ($exportMode == CRM_Export_Form_Select::CONTACT_EXPORT) {
                 $relIDs = $ids;
             } elseif ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) {
                 $sourceID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
                 $query = "SELECT contact_id FROM civicrm_activity_contact\n                              WHERE activity_id IN ( " . implode(',', $ids) . ") AND\n                              record_type_id = {$sourceID}";
                 $dao = CRM_Core_DAO::executeQuery($query);
                 while ($dao->fetch()) {
                     $relIDs[] = $dao->contact_id;
                 }
             } else {
                 $component = self::exportComponent($exportMode);
                 if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) {
                     $relIDs = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($ids);
                 } else {
                     $relIDs = CRM_Core_DAO::getContactIDsFromComponent($ids, $component);
                 }
             }
             $relationshipJoin = $relationshipClause = '';
             if (!$selectAll && $componentTable) {
                 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
             } elseif (!empty($relIDs)) {
                 $relID = implode(',', $relIDs);
                 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
             }
             $relationFrom = " {$relationFrom}\n                INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}\n                {$relationshipJoin} ";
             //check for active relationship status only
             $today = date('Ymd');
             $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
             $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
             $relationGroupBy = " GROUP BY crel.{$contactA}";
             $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
             $relationQueryString = "{$relationSelect} {$relationFrom} {$relationWhere} {$relationHaving} {$relationGroupBy}";
             $allRelContactDAO = CRM_Core_DAO::executeQuery($relationQueryString);
             while ($allRelContactDAO->fetch()) {
                 //FIX Me: Migrate this to table rather than array
                 // build the array of all related contacts
                 $allRelContactArray[$rel][$allRelContactDAO->refContact] = clone $allRelContactDAO;
             }
             $allRelContactDAO->free();
         }
     }
     // make sure the groups stuff is included only if specifically specified
     // by the fields param (CRM-1969), else we limit the contacts outputted to only
     // ones that are part of a group
     if (!empty($returnProperties['groups'])) {
         $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
         $newClause = " ( {$oldClause} AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
         // total hack for export, CRM-3618
         $from = str_replace($oldClause, $newClause, $from);
     }
     if (!$selectAll && $componentTable) {
         $from .= " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = contact_a.id ";
     } elseif ($componentClause) {
         if (empty($where)) {
             $where = "WHERE {$componentClause}";
         } else {
             $where .= " AND {$componentClause}";
         }
     }
     // CRM-13982 - check if is deleted
     $excludeTrashed = TRUE;
     foreach ($params as $value) {
         if ($value[0] == 'contact_is_deleted') {
             $excludeTrashed = FALSE;
         }
     }
     $trashClause = $excludeTrashed ? "contact_a.is_deleted != 1" : "( 1 )";
     if (empty($where)) {
         $where = "WHERE {$trashClause}";
     } else {
         $where .= " AND {$trashClause}";
     }
     $queryString = "{$select} {$from} {$where} {$having}";
     $groupBy = "";
     if (!empty($returnProperties['tags']) || !empty($returnProperties['groups']) || CRM_Utils_Array::value('notes', $returnProperties) || $queryMode & CRM_Contact_BAO_Query::MODE_CONTACTS && $query->_useGroupBy) {
         $groupBy = " GROUP BY contact_a.id";
     }
     switch ($exportMode) {
         case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
             $groupBy = 'GROUP BY civicrm_contribution.id';
             if (CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled()) {
                 // especial group by  when soft credit columns are included
                 $groupBy = 'GROUP BY contribution_search_scredit_combined.id, contribution_search_scredit_combined.scredit_id';
             }
             break;
         case CRM_Export_Form_Select::EVENT_EXPORT:
             $groupBy = 'GROUP BY civicrm_participant.id';
             break;
         case CRM_Export_Form_Select::MEMBER_EXPORT:
             $groupBy = " GROUP BY civicrm_membership.id";
             break;
     }
     if ($queryMode & CRM_Contact_BAO_Query::MODE_ACTIVITY) {
         $groupBy = " GROUP BY civicrm_activity.id ";
     }
     $queryString .= $groupBy;
     // always add contact_a.id to the ORDER clause
     // so the order is deterministic
     //CRM-15301
     if (strpos('contact_a.id', $order) === FALSE) {
         $order .= ", contact_a.id";
     }
     if ($order) {
         list($field, $dir) = explode(' ', $order, 2);
         $field = trim($field);
         if (!empty($returnProperties[$field])) {
             //CRM-15301
             $queryString .= " ORDER BY {$order}";
         }
     }
     $multipleSelectFields = array('preferred_communication_method' => 1);
     $addPaymentHeader = FALSE;
     $paymentDetails = array();
     if ($paymentFields || $selectedPaymentFields) {
         // get payment related in for event and members
         $paymentDetails = CRM_Contribute_BAO_Contribution::getContributionDetails($exportMode, $ids);
         //get all payment headers.
         // If we haven't selected specific payment fields, load in all the
         // payment headers.
         if (!$selectedPaymentFields) {
             $paymentHeaders = self::componentPaymentFields();
             if (!empty($paymentDetails)) {
                 $addPaymentHeader = TRUE;
             }
         } else {
             $paymentHeaders = array();
         }
         $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL);
     }
     $componentDetails = $headerRows = $sqlColumns = array();
     $setHeader = TRUE;
     $rowCount = self::EXPORT_ROW_COUNT;
     $offset = 0;
     // we write to temp table often to avoid using too much memory
     $tempRowCount = 100;
     $count = -1;
     // for CRM-3157 purposes
     $i18n = CRM_Core_I18n::singleton();
     $outputColumns = array();
     //@todo - it would be clearer to start defining output columns earlier in this function rather than stick with return properties until this point
     // as the array is not actually 'returnProperties' after the sql query is formed - making the alterations to it confusing
     foreach ($returnProperties as $key => $value) {
         $outputColumns[$key] = $value;
     }
     while (1) {
         $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
         $dao = CRM_Core_DAO::executeQuery($limitQuery);
         if ($dao->N <= 0) {
             break;
         }
         while ($dao->fetch()) {
             $count++;
             $row = array();
             //convert the pseudo constants
             // CRM-14398 there is problem in this architecture that is not easily solved. For now we are using the cloned
             // temporary iterationDAO object to get around it.
             // the issue is that the convertToPseudoNames function is adding additional properties (e.g for campaign) to the DAO object
             // these additional properties are NOT reset when the $dao cycles through the while loop
             // nor are they overwritten as they are not in the loop
             // the convertToPseudoNames will not adequately over-write them either as it doesn't 'kick-in' unless the
             // relevant property is set.
             // It may be that a long-term fix could be introduced there - however, it's probably necessary to figure out how to test the
             // export class before tackling a better architectural fix
             $iterationDAO = clone $dao;
             $query->convertToPseudoNames($iterationDAO);
             //first loop through output columns so that we return what is required, and in same order.
             $relationshipField = 0;
             foreach ($outputColumns as $field => $value) {
                 //we should set header only once
                 if ($setHeader) {
                     $sqlDone = FALSE;
                     // Split campaign into 2 fields for id and title
                     if (substr($field, -14) == 'campaign_title') {
                         $headerRows[] = ts('Campaign Title');
                     } elseif (substr($field, -11) == 'campaign_id') {
                         $headerRows[] = ts('Campaign ID');
                     } elseif (isset($query->_fields[$field]['title'])) {
                         $headerRows[] = $query->_fields[$field]['title'];
                     } elseif ($field == 'phone_type_id') {
                         $headerRows[] = ts('Phone Type');
                     } elseif ($field == 'provider_id') {
                         $headerRows[] = ts('IM Service Provider');
                     } elseif (is_array($value) && $field == 'location') {
                         // fix header for location type case
                         foreach ($value as $ltype => $val) {
                             foreach (array_keys($val) as $fld) {
                                 $type = explode('-', $fld);
                                 $hdr = "{$ltype}-" . $query->_fields[$type[0]]['title'];
                                 if (!empty($type[1])) {
                                     if (CRM_Utils_Array::value(0, $type) == 'phone') {
                                         $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
                                     } elseif (CRM_Utils_Array::value(0, $type) == 'im') {
                                         $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders);
                                     }
                                 }
                                 $headerRows[] = $hdr;
                                 self::sqlColumnDefn($query, $sqlColumns, $hdr);
                             }
                             $sqlDone = TRUE;
                         }
                     } elseif (substr($field, 0, 5) == 'case_') {
                         if ($query->_fields['case'][$field]['title']) {
                             $headerRows[] = $query->_fields['case'][$field]['title'];
                         } elseif ($query->_fields['activity'][$field]['title']) {
                             $headerRows[] = $query->_fields['activity'][$field]['title'];
                         }
                     } elseif (array_key_exists($field, $contactRelationshipTypes)) {
                         $relName = $field;
                         foreach ($value as $relationField => $relationValue) {
                             // below block is same as primary block (duplicate)
                             if (isset($relationQuery[$field]->_fields[$relationField]['title'])) {
                                 if ($relationQuery[$field]->_fields[$relationField]['name'] == 'name') {
                                     $headerName = $field . '-' . $relationField;
                                 } else {
                                     if ($relationField == 'current_employer') {
                                         $headerName = $field . '-' . 'current_employer';
                                     } else {
                                         $headerName = $field . '-' . $relationQuery[$field]->_fields[$relationField]['name'];
                                     }
                                 }
                                 $headerRows[] = $headerName;
                                 self::sqlColumnDefn($query, $sqlColumns, $headerName);
                             } elseif ($relationField == 'phone_type_id') {
                                 $headerName = $field . '-' . 'Phone Type';
                                 $headerRows[] = $headerName;
                                 self::sqlColumnDefn($query, $sqlColumns, $headerName);
                             } elseif ($relationField == 'provider_id') {
                                 $headerName = $field . '-' . 'Im Service Provider';
                                 $headerRows[] = $headerName;
                                 self::sqlColumnDefn($query, $sqlColumns, $headerName);
                             } elseif ($relationField == 'state_province_id') {
                                 $headerName = $field . '-' . 'state_province_id';
                                 $headerRows[] = $headerName;
                                 self::sqlColumnDefn($query, $sqlColumns, $headerName);
                             } elseif (is_array($relationValue) && $relationField == 'location') {
                                 // fix header for location type case
                                 foreach ($relationValue as $ltype => $val) {
                                     foreach (array_keys($val) as $fld) {
                                         $type = explode('-', $fld);
                                         $hdr = "{$ltype}-" . $relationQuery[$field]->_fields[$type[0]]['title'];
                                         if (!empty($type[1])) {
                                             if (CRM_Utils_Array::value(0, $type) == 'phone') {
                                                 $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
                                             } elseif (CRM_Utils_Array::value(0, $type) == 'im') {
                                                 $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders);
                                             }
                                         }
                                         $headerName = $field . '-' . $hdr;
                                         $headerRows[] = $headerName;
                                         self::sqlColumnDefn($query, $sqlColumns, $headerName);
                                     }
                                 }
                             }
                         }
                     } elseif ($selectedPaymentFields && array_key_exists($field, self::componentPaymentFields())) {
                         $headerRows[] = CRM_Utils_Array::value($field, self::componentPaymentFields());
                     } else {
                         $headerRows[] = $field;
                     }
                     if (!$sqlDone) {
                         self::sqlColumnDefn($query, $sqlColumns, $field);
                     }
                 }
                 // add im_provider to $dao object
                 if ($field == 'im_provider' && property_exists($iterationDAO, 'provider_id')) {
                     $iterationDAO->im_provider = $iterationDAO->provider_id;
                 }
                 //build row values (data)
                 $fieldValue = NULL;
                 if (property_exists($iterationDAO, $field)) {
                     $fieldValue = $iterationDAO->{$field};
                     // to get phone type from phone type id
                     if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
                         $fieldValue = $phoneTypes[$fieldValue];
                     } elseif ($field == 'provider_id' || $field == 'im_provider') {
                         $fieldValue = CRM_Utils_Array::value($fieldValue, $imProviders);
                     } elseif ($field == 'master_id') {
                         $masterAddressId = NULL;
                         if (isset($iterationDAO->master_id)) {
                             $masterAddressId = $iterationDAO->master_id;
                         }
                         // get display name of contact that address is shared.
                         $fieldValue = CRM_Contact_BAO_Contact::getMasterDisplayName($masterAddressId, $iterationDAO->contact_id);
                     }
                 }
                 if ($field == 'id') {
                     $row[$field] = $iterationDAO->contact_id;
                     // special case for calculated field
                 } elseif ($field == 'source_contact_id') {
                     $row[$field] = $iterationDAO->contact_id;
                 } elseif ($field == 'pledge_balance_amount') {
                     $row[$field] = $iterationDAO->pledge_amount - $iterationDAO->pledge_total_paid;
                     // special case for calculated field
                 } elseif ($field == 'pledge_next_pay_amount') {
                     $row[$field] = $iterationDAO->pledge_next_pay_amount + $iterationDAO->pledge_outstanding_amount;
                 } elseif (is_array($value) && $field == 'location') {
                     // fix header for location type case
                     foreach ($value as $ltype => $val) {
                         foreach (array_keys($val) as $fld) {
                             $type = explode('-', $fld);
                             $fldValue = "{$ltype}-" . $type[0];
                             // CRM-14076 - fix label to work as the query object expects
                             // FIXME: We should not be using labels as keys!
                             $daoField = CRM_Utils_String::munge($ltype) . '-' . $type[0];
                             if (!empty($type[1])) {
                                 $fldValue .= "-" . $type[1];
                                 $daoField .= "-" . $type[1];
                             }
                             // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
                             switch ($fld) {
                                 case 'country':
                                 case 'world_region':
                                     $row[$fldValue] = $i18n->crm_translate($iterationDAO->{$daoField}, array('context' => 'country'));
                                     break;
                                 case 'state_province':
                                     $row[$fldValue] = $i18n->crm_translate($iterationDAO->{$daoField}, array('context' => 'province'));
                                     break;
                                 case 'im_provider':
                                     $imFieldvalue = $daoField . "-provider_id";
                                     $row[$fldValue] = CRM_Utils_Array::value($iterationDAO->{$imFieldvalue}, $imProviders);
                                     break;
                                 default:
                                     $row[$fldValue] = $iterationDAO->{$daoField};
                                     break;
                             }
                         }
                     }
                 } elseif (array_key_exists($field, $contactRelationshipTypes)) {
                     $relDAO = CRM_Utils_Array::value($iterationDAO->contact_id, $allRelContactArray[$field]);
                     $relationQuery[$field]->convertToPseudoNames($relDAO);
                     foreach ($value as $relationField => $relationValue) {
                         if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
                             $fieldValue = $relDAO->{$relationField};
                             if ($relationField == 'phone_type_id') {
                                 $fieldValue = $phoneTypes[$relationValue];
                             } elseif ($relationField == 'provider_id') {
                                 $fieldValue = CRM_Utils_Array::value($relationValue, $imProviders);
                             } elseif (is_object($relDAO) && in_array($relationField, array('email_greeting', 'postal_greeting', 'addressee'))) {
                                 //special case for greeting replacement
                                 $fldValue = "{$relationField}_display";
                                 $fieldValue = $relDAO->{$fldValue};
                             }
                         } elseif (is_object($relDAO) && $relationField == 'state_province') {
                             $fieldValue = CRM_Core_PseudoConstant::stateProvince($relDAO->state_province_id);
                         } elseif (is_object($relDAO) && $relationField == 'country') {
                             $fieldValue = CRM_Core_PseudoConstant::country($relDAO->country_id);
                         } else {
                             $fieldValue = '';
                         }
                         $field = $field . '_';
                         if (array_key_exists($relationField, $multipleSelectFields)) {
                             $param = array($relationField => $fieldValue);
                             $names = array($relationField => array('newName' => $relationField, 'groupName' => $relationField));
                             CRM_Core_OptionGroup::lookupValues($param, $names, FALSE);
                             $fieldValue = $param[$relationField];
                         }
                         if (is_object($relDAO) && $relationField == 'id') {
                             $row[$field . $relationField] = $relDAO->contact_id;
                         } elseif (is_array($relationValue) && $relationField == 'location') {
                             foreach ($relationValue as $ltype => $val) {
                                 foreach (array_keys($val) as $fld) {
                                     $type = explode('-', $fld);
                                     $fldValue = "{$ltype}-" . $type[0];
                                     if (!empty($type[1])) {
                                         $fldValue .= "-" . $type[1];
                                     }
                                     // CRM-3157: localise country, region (both have ‘country’ context)
                                     // and state_province (‘province’ context)
                                     switch (TRUE) {
                                         case !is_object($relDAO):
                                             $row[$field . '_' . $fldValue] = '';
                                             break;
                                         case in_array('country', $type):
                                         case in_array('world_region', $type):
                                             $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->{$fldValue}, array('context' => 'country'));
                                             break;
                                         case in_array('state_province', $type):
                                             $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->{$fldValue}, array('context' => 'province'));
                                             break;
                                         default:
                                             $row[$field . '_' . $fldValue] = $relDAO->{$fldValue};
                                             break;
                                     }
                                 }
                             }
                         } elseif (isset($fieldValue) && $fieldValue != '') {
                             //check for custom data
                             if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationField)) {
                                 $row[$field . $relationField] = CRM_Core_BAO_CustomField::getDisplayValue($fieldValue, $cfID, $relationQuery[$field]->_options);
                             } else {
                                 //normal relationship fields
                                 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
                                 switch ($relationField) {
                                     case 'country':
                                     case 'world_region':
                                         $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
                                         break;
                                     case 'state_province':
                                         $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
                                         break;
                                     default:
                                         $row[$field . $relationField] = $fieldValue;
                                         break;
                                 }
                             }
                         } else {
                             // if relation field is empty or null
                             $row[$field . $relationField] = '';
                         }
                     }
                 } elseif (isset($fieldValue) && $fieldValue != '') {
                     //check for custom data
                     if ($cfID = CRM_Core_BAO_CustomField::getKeyID($field)) {
                         $row[$field] = CRM_Core_BAO_CustomField::getDisplayValue($fieldValue, $cfID, $query->_options);
                     } elseif (array_key_exists($field, $multipleSelectFields)) {
                         //option group fixes
                         $paramsNew = array($field => $fieldValue);
                         if ($field == 'test_tutoring') {
                             $name = array($field => array('newName' => $field, 'groupName' => 'test'));
                             // for  readers group
                         } elseif (substr($field, 0, 4) == 'cmr_') {
                             $name = array($field => array('newName' => $field, 'groupName' => substr($field, 0, -3)));
                         } else {
                             $name = array($field => array('newName' => $field, 'groupName' => $field));
                         }
                         CRM_Core_OptionGroup::lookupValues($paramsNew, $name, FALSE);
                         $row[$field] = $paramsNew[$field];
                     } elseif (in_array($field, array('email_greeting', 'postal_greeting', 'addressee'))) {
                         //special case for greeting replacement
                         $fldValue = "{$field}_display";
                         $row[$field] = $iterationDAO->{$fldValue};
                     } else {
                         //normal fields with a touch of CRM-3157
                         switch ($field) {
                             case 'country':
                             case 'world_region':
                                 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
                                 break;
                             case 'state_province':
                                 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
                                 break;
                             case 'gender':
                             case 'preferred_communication_method':
                             case 'preferred_mail_format':
                             case 'communication_style':
                                 $row[$field] = $i18n->crm_translate($fieldValue);
                                 break;
                             default:
                                 $row[$field] = $fieldValue;
                                 break;
                         }
                     }
                 } elseif ($selectedPaymentFields && array_key_exists($field, self::componentPaymentFields())) {
                     $paymentData = CRM_Utils_Array::value($iterationDAO->{$paymentTableId}, $paymentDetails);
                     $payFieldMapper = array('componentPaymentField_total_amount' => 'total_amount', 'componentPaymentField_contribution_status' => 'contribution_status', 'componentPaymentField_payment_instrument' => 'pay_instru', 'componentPaymentField_transaction_id' => 'trxn_id', 'componentPaymentField_received_date' => 'receive_date');
                     $row[$field] = CRM_Utils_Array::value($payFieldMapper[$field], $paymentData, '');
                 } else {
                     // if field is empty or null
                     $row[$field] = '';
                 }
             }
             // add payment headers if required
             if ($addPaymentHeader && $paymentFields) {
                 $headerRows = array_merge($headerRows, $paymentHeaders);
                 foreach (array_keys($paymentHeaders) as $paymentHdr) {
                     self::sqlColumnDefn($query, $sqlColumns, $paymentHdr);
                 }
             }
             if ($setHeader) {
                 $exportTempTable = self::createTempTable($sqlColumns);
             }
             //build header only once
             $setHeader = FALSE;
             // If specific payment fields have been selected for export, payment
             // data will already be in $row. Otherwise, add payment related
             // information, if appropriate.
             if ($addPaymentHeader) {
                 if (!$selectedPaymentFields) {
                     if ($paymentFields) {
                         $paymentData = CRM_Utils_Array::value($row[$paymentTableId], $paymentDetails);
                         if (!is_array($paymentData) || empty($paymentData)) {
                             $paymentData = $nullContributionDetails;
                         }
                         $row = array_merge($row, $paymentData);
                     } elseif (!empty($paymentDetails)) {
                         $row = array_merge($row, $nullContributionDetails);
                     }
                 }
             }
             //remove organization name for individuals if it is set for current employer
             if (!empty($row['contact_type']) && $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)) {
                 $row['organization_name'] = '';
             }
             // add component info
             // write the row to a file
             $componentDetails[] = $row;
             // output every $tempRowCount rows
             if ($count % $tempRowCount == 0) {
                 self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
                 $componentDetails = array();
             }
         }
         $dao->free();
         $offset += $rowCount;
     }
     if ($exportTempTable) {
         self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
         // do merge same address and merge same household processing
         if ($mergeSameAddress) {
             self::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams);
         }
         // merge the records if they have corresponding households
         if ($mergeSameHousehold) {
             self::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyMOH);
             self::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyHOH);
         }
         // fix the headers for rows with relationship type
         if (!empty($relName)) {
             self::manipulateHeaderRows($headerRows, $contactRelationshipTypes);
         }
         // if postalMailing option is checked, exclude contacts who are deceased, have
         // "Do not mail" privacy setting, or have no street address
         if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) && $exportParams['postal_mailing_export']['postal_mailing_export'] == 1) {
             self::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode);
         }
         // call export hook
         CRM_Utils_Hook::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
         // now write the CSV file
         self::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
         // delete the export temp table and component table
         $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
         CRM_Core_DAO::executeQuery($sql);
         CRM_Utils_System::civiExit();
     } else {
         CRM_Core_Error::fatal(ts('No records to export'));
     }
 }
Example #30
0
 /**
  * Get Menu name
  *
  * @param $value
  * @param $skipMenuItems
  * @return bool|string
  */
 static function getMenuName(&$value, &$skipMenuItems)
 {
     // we need to localise the menu labels (CRM-5456) and don’t
     // want to use ts() as it would throw the ts-extractor off
     $i18n = CRM_Core_I18n::singleton();
     $name = $i18n->crm_translate($value['attributes']['label'], array('context' => 'menu'));
     $url = $value['attributes']['url'];
     $permission = $value['attributes']['permission'];
     $operator = $value['attributes']['operator'];
     $parentID = $value['attributes']['parentID'];
     $navID = $value['attributes']['navID'];
     $active = $value['attributes']['active'];
     $menuName = $value['attributes']['name'];
     $target = CRM_Utils_Array::value('target', $value['attributes']);
     if (in_array($parentID, $skipMenuItems) || !$active) {
         $skipMenuItems[] = $navID;
         return FALSE;
     }
     //we need to check core view/edit or supported acls.
     if (in_array($menuName, array('Search...', 'Contacts'))) {
         if (!CRM_Core_Permission::giveMeAllACLs()) {
             $skipMenuItems[] = $navID;
             return FALSE;
         }
     }
     $config = CRM_Core_Config::singleton();
     $makeLink = FALSE;
     if (isset($url) && $url) {
         if (substr($url, 0, 4) === 'http') {
             $url = $url;
         } else {
             //CRM-7656 --make sure to separate out url path from url params,
             //as we'r going to validate url path across cross-site scripting.
             $urlParam = CRM_Utils_System::explode('&', str_replace('?', '&', $url), 2);
             $url = CRM_Utils_System::url($urlParam[0], $urlParam[1], FALSE, NULL, TRUE);
         }
         $makeLink = TRUE;
     }
     static $allComponents;
     if (!$allComponents) {
         $allComponents = CRM_Core_Component::getNames();
     }
     if (isset($permission) && $permission) {
         $permissions = explode(',', $permission);
         $hasPermission = FALSE;
         foreach ($permissions as $key) {
             $key = trim($key);
             $showItem = TRUE;
             //get the component name from permission.
             $componentName = CRM_Core_Permission::getComponentName($key);
             if ($componentName) {
                 if (!in_array($componentName, $config->enableComponents) || !CRM_Core_Permission::check($key)) {
                     $showItem = FALSE;
                     if ($operator == 'AND') {
                         $skipMenuItems[] = $navID;
                         return $showItem;
                     }
                 } else {
                     $hasPermission = TRUE;
                 }
             } elseif (!CRM_Core_Permission::check($key)) {
                 $showItem = FALSE;
                 if ($operator == 'AND') {
                     $skipMenuItems[] = $navID;
                     return $showItem;
                 }
             } else {
                 $hasPermission = TRUE;
             }
         }
         if (!$showItem && !$hasPermission) {
             $skipMenuItems[] = $navID;
             return FALSE;
         }
     }
     if ($makeLink) {
         if ($target) {
             $name = "<a href=\"{$url}\" target=\"{$target}\">{$name}</a>";
         } else {
             $name = "<a href=\"{$url}\">{$name}</a>";
         }
     }
     return $name;
 }