/**
  * 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;
 }
Exemple #2
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;
 }
 /**
  * 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();
 }
$uf = isset($installTypeToUF[$installType]) ? $installTypeToUF[$installType] : 'Drupal';
define('CIVICRM_UF', $uf);
global $tsLocale;
$tsLocale = 'en_US';
$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';
Exemple #5
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('&', '&', $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;
 }
 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;
 }
Exemple #7
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;
 }
Exemple #8
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;
 }
Exemple #9
0
 /**
  * Function to build the form
  *
  * @return None
  * @access public
  */
 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();
     $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('WARNING: 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);
         $this->addElement('checkbox', 'makeSinglelingual', ts('Return to Single Language'), null, array('onChange' => "if (this.checked) alert('{$warning}')"));
     } else {
         // for single-lingual sites, populate default language drop-down with all languages
         $this->addElement('select', 'lcMessages', ts('Default Language'), $locales);
         $warning = ts('WARNING: As of CiviCRM 3.0, this is still an experimental functionality. Enabling multiple languages irreversibly 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);
         // test for create view and trigger permissions and if allowed, add the option to go multilingual
         CRM_Core_Error::ignoreException();
         $dao = new CRM_Core_DAO();
         $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
         $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
         $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
         $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
         CRM_Core_Error::setCallback();
         if (!$dao->_lastError) {
             $this->addElement('checkbox', 'makeMultilingual', ts('Enable Multiple Languages'), null, array('onChange' => "if (this.checked) alert('{$warning}')"));
         }
     }
     $this->addElement('select', 'lcMonetary', ts('Monetary Locale'), $locales);
     $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);
     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);
     // we do this only to initialize currencySymbols, kinda hackish but works!
     $config->defaultCurrencySymbol();
     $symbol = $config->currencySymbols;
     foreach ($symbol as $key => $value) {
         $currencySymbols[$key] = "{$key}";
         if ($value) {
             $currencySymbols[$key] .= " ({$value})";
         }
     }
     $this->addElement('select', 'defaultCurrency', ts('Default Currency'), $currencySymbols);
     $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();
 }
 /**
  * @param $communication_language
  * @param $preferred_language
  */
 public static function setCommunicationLanguage($communication_language, $preferred_language)
 {
     $currentLocale = CRM_Core_I18n::getLocale();
     $language = $currentLocale;
     // prepare the language for the email
     if ($communication_language == CRM_Core_I18n::AUTO) {
         if (!empty($preferred_language)) {
             $language = $preferred_language;
         }
     } else {
         $language = $communication_language;
     }
     // language not in the existing language, use default
     $languages = CRM_Core_I18n::languages(TRUE);
     if (!array_key_exists($language, $languages)) {
         $language = $currentLocale;
     }
     // change the language
     $i18n = CRM_Core_I18n::singleton();
     $i18n->setLocale($language);
 }
 protected static function _invoke($args)
 {
     if ($args[0] !== 'civicrm') {
         return;
     }
     require_once 'CRM/Core/I18n.php';
     $config = CRM_Core_Config::singleton();
     if (isset($args[1]) and $args[1] == 'menu' and isset($args[2]) and $args[2] == 'rebuild') {
         // ensure that the user has a good privilege level
         if (CRM_Core_Permission::check('administer CiviCRM')) {
             self::rebuildMenuAndCaches();
             CRM_Core_Session::setStatus(ts('Menu has been rebuilt'));
             return CRM_Utils_System::redirect();
         } else {
             CRM_Core_Error::fatal('You do not have permission to execute this url');
         }
     }
     // first fire up IDS and check for bad stuff
     if ($config->useIDS) {
         $ids = new CRM_Core_IDS();
         $ids->check($args);
     }
     // also initialize the i18n framework
     $i18n = CRM_Core_I18n::singleton();
     if ($config->userFramework == 'Standalone') {
         $session = CRM_Core_Session::singleton();
         if ($session->get('new_install') !== TRUE) {
             CRM_Core_Standalone::sidebarLeft();
         } elseif ($args[1] == 'standalone' && $args[2] == 'register') {
             CRM_Core_Menu::store();
         }
     }
     // get the menu items
     $path = implode('/', $args);
     $item = CRM_Core_Menu::get($path);
     // we should try to compute menus, if item is empty and stay on the same page,
     // rather than compute and redirect to dashboard.
     if (!$item) {
         CRM_Core_Menu::store(FALSE);
         $item = CRM_Core_Menu::get($path);
     }
     if ($config->userFramework == 'Joomla' && $item) {
         $config->userFrameworkURLVar = 'task';
         // joomla 1.5RC1 seems to push this in the POST variable, which messes
         // QF and checkboxes
         unset($_POST['option']);
         CRM_Core_Joomla::sidebarLeft();
     }
     // set active Component
     $template = CRM_Core_Smarty::singleton();
     $template->assign('activeComponent', 'CiviCRM');
     $template->assign('formTpl', 'default');
     if ($item) {
         // CRM-7656 - make sure we send a clean sanitized path to create printer friendly url
         $printerFriendly = CRM_Utils_System::makeURL('snippet', FALSE, FALSE, CRM_Utils_Array::value('path', $item)) . '2';
         $template->assign('printerFriendly', $printerFriendly);
         if (!array_key_exists('page_callback', $item)) {
             CRM_Core_Error::debug('Bad item', $item);
             CRM_Core_Error::fatal(ts('Bad menu record in database'));
         }
         // check that we are permissioned to access this page
         if (!CRM_Core_Permission::checkMenuItem($item)) {
             CRM_Utils_System::permissionDenied();
             return;
         }
         // check if ssl is set
         if (CRM_Utils_Array::value('is_ssl', $item)) {
             CRM_Utils_System::redirectToSSL();
         }
         if (isset($item['title'])) {
             CRM_Utils_System::setTitle($item['title']);
         }
         if (isset($item['breadcrumb']) && !isset($item['is_public'])) {
             CRM_Utils_System::appendBreadCrumb($item['breadcrumb']);
         }
         $pageArgs = NULL;
         if (CRM_Utils_Array::value('page_arguments', $item)) {
             $pageArgs = CRM_Core_Menu::getArrayForPathArgs($item['page_arguments']);
         }
         $template = CRM_Core_Smarty::singleton();
         if (isset($item['is_public']) && $item['is_public']) {
             $template->assign('urlIsPublic', TRUE);
         } else {
             $template->assign('urlIsPublic', FALSE);
         }
         if (isset($item['return_url'])) {
             $session = CRM_Core_Session::singleton();
             $args = CRM_Utils_Array::value('return_url_args', $item, 'reset=1');
             $session->pushUserContext(CRM_Utils_System::url($item['return_url'], $args));
         }
         // CRM_Core_Error::debug( $item ); exit( );
         $result = NULL;
         if (is_array($item['page_callback'])) {
             $newArgs = explode('/', $_GET[$config->userFrameworkURLVar]);
             require_once str_replace('_', DIRECTORY_SEPARATOR, $item['page_callback'][0]) . '.php';
             $result = call_user_func($item['page_callback'], $newArgs);
         } elseif (strstr($item['page_callback'], '_Form')) {
             $wrapper = new CRM_Utils_Wrapper();
             $result = $wrapper->run(CRM_Utils_Array::value('page_callback', $item), CRM_Utils_Array::value('title', $item), isset($pageArgs) ? $pageArgs : NULL);
         } else {
             $newArgs = explode('/', $_GET[$config->userFrameworkURLVar]);
             require_once str_replace('_', DIRECTORY_SEPARATOR, $item['page_callback']) . '.php';
             $mode = 'null';
             if (isset($pageArgs['mode'])) {
                 $mode = $pageArgs['mode'];
                 unset($pageArgs['mode']);
             }
             $title = CRM_Utils_Array::value('title', $item);
             if (strstr($item['page_callback'], '_Page')) {
                 eval("\$object = new {$item['page_callback']}( \$title, \$mode );");
             } elseif (strstr($item['page_callback'], '_Controller')) {
                 $addSequence = 'false';
                 if (isset($pageArgs['addSequence'])) {
                     $addSequence = $pageArgs['addSequence'];
                     $addSequence = $addSequence ? 'true' : 'false';
                     unset($pageArgs['addSequence']);
                 }
                 eval("\$object = new {$item['page_callback']}( \$title, true, \$mode, null, \$addSequence );");
             } else {
                 CRM_Core_Error::fatal();
             }
             $result = $object->run($newArgs, $pageArgs);
         }
         CRM_Core_Session::storeSessionObjects();
         return $result;
     }
     CRM_Core_Menu::store();
     CRM_Core_Session::setStatus(ts('Menu has been rebuilt'));
     return CRM_Utils_System::redirect();
 }
 /**
  * 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)
 {
     //$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']);
             if (is_numeric($fieldArray[1])) {
                 $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] . "`";
                 }
             }
             $varArray[$key] = $field;
         }
     }
     $sort->_vars = $varArray;
     $result = $this->_query->searchQuery($offset, $rowCount, $sort, null, null, null, null, null);
     // process the result of the query
     $rows = array();
     $mask = CRM_Core_Action::mask(CRM_Core_Permission::getPermission());
     require_once 'CRM/Core/PseudoConstant.php';
     $locationTypes = CRM_Core_PseudoConstant::locationType();
     $links =& CRM_Profile_Selector_Listings::links();
     $names = array();
     foreach ($this->_fields as $key => $field) {
         if ($field['in_selector'] && !in_array($key, $GLOBALS['_CRM_PROFILE_SELECTOR_LISTINGS']['skipFields'])) {
             if (strpos($key, '-') !== false) {
                 list($fieldName, $id, $type) = explode('-', $key);
                 $locationTypeName = CRM_Utils_Array::value($id, $locationTypes);
                 if (!$locationTypeName) {
                     continue;
                 }
                 if (in_array($fieldName, array('phone', 'im', 'email'))) {
                     if ($type) {
                         $names[] = "{$locationTypeName}-{$fieldName}-{$type}";
                     } else {
                         $names[] = "{$locationTypeName}-{$fieldName}-1";
                     }
                 } else {
                     $names[] = "{$locationTypeName}-{$fieldName}";
                 }
             } else {
                 $names[] = $field['name'];
             }
         }
     }
     while ($result->fetch()) {
         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::getImage($result->contact_type);
         $row['sort_name'] = $result->sort_name;
         foreach ($names as $name) {
             if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name)) {
                 $row[] = CRM_Core_BAO_CustomField::getDisplayValue($result->{$name}, $cfID, $this->_options);
             } else {
                 $row[] = $result->{$name};
             }
             if (!empty($result->{$name})) {
                 $empty = false;
             }
         }
         $row[] = CRM_Core_Action::formLink(CRM_Profile_Selector_Listings::links(), $mask, array('id' => $result->contact_id, 'gid' => $this->_gid));
         if (!$empty) {
             $rows[] = $row;
         }
     }
     return $rows;
 }
Exemple #13
0
function ts($text, $params = array())
{
    $i18n =& CRM_Core_I18n::singleton();
    return $i18n->crm_translate($text, $params);
}
Exemple #14
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  $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
  *
  * @static
  * @access 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)
 {
     $headerRows = $returnProperties = array();
     $primary = $paymentFields = false;
     $origFields = $fields;
     $queryMode = null;
     $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;
         case CRM_Export_Form_Select::ACTIVITY_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_ACTIVITY;
             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 = $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 = 'Primary';
                     }
                     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) && is_numeric($relLocTypeId)) {
                     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;
                 if ($returnProperties['participant_role']) {
                     unset($returnProperties['participant_role']);
                     $returnProperties['participant_role_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 {
                                 if ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) {
                                     $returnProperties['activity_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 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) {
         $drop = false;
         //make sure the addressee fields are selected
         //while using merge same address feature
         $returnProperties['addressee'] = 1;
         $returnProperties['street_name'] = 1;
         if (!CRM_Utils_Array::value('last_name', $returnProperties)) {
             $returnProperties['last_name'] = 1;
             $drop = 'last_name';
         }
         $returnProperties['household_name'] = 1;
         $returnProperties['street_address'] = 1;
     }
     if ($moreReturnProperties) {
         // fix for CRM-7066
         if (CRM_Utils_Array::value('group', $moreReturnProperties)) {
             unset($moreReturnProperties['group']);
             $moreReturnProperties['groups'] = 1;
         }
         $returnProperties = array_merge($returnProperties, $moreReturnProperties);
     }
     $query = new CRM_Contact_BAO_Query(0, $returnProperties, null, false, false, $queryMode);
     list($select, $from, $where) = $query->query();
     if ($mergeSameHousehold == 1) {
         if (!$returnProperties['id']) {
             $returnProperties['id'] = 1;
             $setId = true;
         } else {
             $setId = false;
         }
         $relationKey = CRM_Utils_Array::key('Household Member of', $contactRelationshipTypes);
         foreach ($returnProperties as $key => $value) {
             if (!array_key_exists($key, $contactRelationshipTypes)) {
                 $returnProperties[$relationKey][$key] = $value;
             }
         }
         unset($returnProperties[$relationKey]['location_type']);
         unset($returnProperties[$relationKey]['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(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';
             }
             if ($exportMode == CRM_Export_Form_Select::CONTACT_EXPORT) {
                 $relIDs = $ids;
             } else {
                 if ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) {
                     $query = "SELECT source_contact_id FROM civicrm_activity\n                              WHERE id IN ( " . implode(',', $ids) . ")";
                     $dao = CRM_Core_DAO::executeQuery($query);
                     while ($dao->fetch()) {
                         $relIDs[] = $dao->source_contact_id;
                     }
                 } else {
                     switch ($exportMode) {
                         case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
                             $component = 'civicrm_contribution';
                             break;
                         case CRM_Export_Form_Select::EVENT_EXPORT:
                             $component = 'civicrm_participant';
                             break;
                         case CRM_Export_Form_Select::MEMBER_EXPORT:
                             $component = 'civicrm_membership';
                             break;
                         case CRM_Export_Form_Select::PLEDGE_EXPORT:
                             $component = 'civicrm_pledge';
                             break;
                         case CRM_Export_Form_Select::CASE_EXPORT:
                             $component = 'civicrm_case';
                             break;
                         case CRM_Export_Form_Select::GRANT_EXPORT:
                             $component = 'civicrm_grant';
                             break;
                     }
                     $relIDs = CRM_Core_DAO::getContactIDsFromComponent($ids, $component);
                 }
             }
             $relationshipJoin = $relationshipClause = '';
             if ($componentTable) {
                 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
             } else {
                 $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} ";
             $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause}";
             $relationGroupBy = " GROUP BY crel.{$contactA}";
             $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
             $relationQueryString = "{$relationSelect} {$relationFrom} {$relationWhere} {$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 (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 ($componentTable) {
         $from .= " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = contact_a.id ";
     } else {
         if ($componentClause) {
             if (empty($where)) {
                 $where = "WHERE {$componentClause}";
             } else {
                 $where .= " AND {$componentClause}";
             }
         }
     }
     $queryString = "{$select} {$from} {$where}";
     $groupBy = "";
     if (CRM_Utils_Array::value('tags', $returnProperties) || CRM_Utils_Array::value('groups', $returnProperties) || CRM_Utils_Array::value('notes', $returnProperties) || $query->_useGroupBy) {
         $groupBy = " GROUP BY contact_a.id";
     }
     if ($queryMode & CRM_Contact_BAO_Query::MODE_ACTIVITY) {
         $groupBy = " GROUP BY civicrm_activity.id ";
     }
     $queryString .= $groupBy;
     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);
     }
     $header = $addPaymentHeader = false;
     if ($paymentFields) {
         //special return properties for event and members
         $paymentHeaders = array('total_amount' => ts('Total Amount'), 'contribution_status' => ts('Contribution Status'), 'received_date' => ts('Received Date'), 'payment_instrument' => ts('Payment Instrument'), 'transaction_id' => 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);
         if (!empty($paymentDetails)) {
             $addPaymentHeader = true;
         }
         $nullContributionDetails = array_fill_keys($paymentHeaders, null);
     }
     $componentDetails = $headerRows = $sqlColumns = array();
     $setHeader = true;
     $rowCount = self::EXPORT_ROW_COUNT;
     $offset = 0;
     $count = -1;
     // for CRM-3157 purposes
     require_once 'CRM/Core/I18n.php';
     $i18n =& CRM_Core_I18n::singleton();
     while (1) {
         $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
         $dao = CRM_Core_DAO::executeQuery($limitQuery);
         if ($dao->N <= 0) {
             break;
         }
         while ($dao->fetch()) {
             $count++;
             $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) {
                     $sqlDone = false;
                     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;
                                             self::sqlColumnDefn($query, $sqlColumns, $hdr);
                                         }
                                         $sqlDone = true;
                                     }
                                 } 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 = $field;
                                             foreach ($value as $relationField => $relationValue) {
                                                 // below block is same as primary block (duplicate)
                                                 if (isset($relationQuery[$field]->_fields[$relationField]['title'])) {
                                                     $headerName = $field . '-' . $relationQuery[$field]->_fields[$relationField]['title'];
                                                     $headerRows[] = $headerName;
                                                     self::sqlColumnDefn($query, $sqlColumns, $headerName);
                                                 } else {
                                                     if ($relationField == 'phone_type_id') {
                                                         $headerName = $field . '-' . 'Phone Type';
                                                         $headerRows[] = $headerName;
                                                         self::sqlColumnDefn($query, $sqlColumns, $headerName);
                                                     } else {
                                                         if ($relationField == 'provider_id') {
                                                             $headerName = $field . '-' . 'Im Service Provider';
                                                             $headerRows[] = $headerName;
                                                             self::sqlColumnDefn($query, $sqlColumns, $headerName);
                                                         } 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);
                                                                                 }
                                                                             }
                                                                         }
                                                                         $headerName = $field . '-' . $hdr;
                                                                         $headerRows[] = $headerName;
                                                                         self::sqlColumnDefn($query, $sqlColumns, $headerName);
                                                                     }
                                                                 }
                                                             }
                                                         }
                                                     }
                                                 }
                                             }
                                         } else {
                                             $headerRows[] = $field;
                                         }
                                     }
                                 }
                             }
                         }
                     }
                     if (!$sqlDone) {
                         self::sqlColumnDefn($query, $sqlColumns, $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 {
                             if ($field == 'participant_role_id') {
                                 require_once 'CRM/Event/PseudoConstant.php';
                                 $participantRoles = CRM_Event_PseudoConstant::participantRole();
                                 $sep = CRM_Core_DAO::VALUE_SEPARATOR;
                                 $viewRoles = array();
                                 foreach (explode($sep, $dao->{$field}) as $k => $v) {
                                     $viewRoles[] = $participantRoles[$v];
                                 }
                                 $fieldValue = implode(',', $viewRoles);
                             }
                         }
                     }
                 } else {
                     if ($field == 'master_address_belongs_to') {
                         $masterAddressId = null;
                         if (isset($dao->master_id)) {
                             $masterAddressId = $dao->master_id;
                         }
                         // get display name of contact that address is shared.
                         $fieldValue = CRM_Contact_BAO_Contact::getMasterDisplayName($masterAddressId, $dao->contact_id);
                     } 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];
                                         }
                                         // 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($dao->{$fldValue}, array('context' => 'country'));
                                                 break;
                                             case 'state_province':
                                                 $row[$fldValue] = $i18n->crm_translate($dao->{$fldValue}, array('context' => 'province'));
                                                 break;
                                             default:
                                                 $row[$fldValue] = $dao->{$fldValue};
                                                 break;
                                         }
                                     }
                                 }
                             } 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];
                                                         }
                                                         // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
                                                         switch (true) {
                                                             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;
                                                         }
                                                     }
                                                 }
                                             } 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
                                                             // 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] = '';
                                                 }
                                             }
                                         }
                                     }
                                 } 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 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':
                                                             $row[$field] = $i18n->crm_translate($fieldValue);
                                                             break;
                                                         default:
                                                             $row[$field] = $fieldValue;
                                                             break;
                                                     }
                                                 }
                                             }
                                         }
                                     } else {
                                         // if field is empty or null
                                         $row[$field] = '';
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
             // add payment headers if required
             if ($addPaymentHeader && $paymentFields) {
                 $headerRows = array_merge($headerRows, $paymentHeaders);
                 foreach ($paymentHeaders as $paymentHdr) {
                     self::sqlColumnDefn($query, $sqlColumns, $paymentHdr);
                 }
                 $addPaymentHeader = false;
             }
             if ($setHeader) {
                 $exportTempTable = self::createTempTable($sqlColumns);
             }
             //build header only once
             $setHeader = false;
             // add payment related information
             if ($paymentFields && isset($paymentDetails[$row[$paymentTableId]])) {
                 $row = array_merge($row, $paymentDetails[$row[$paymentTableId]]);
             } else {
                 if ($paymentDetails) {
                     $row = array_merge($row, $nullContributionDetails);
                 }
             }
             //remove organization name for individuals if it is set for current employer
             if (CRM_Utils_Array::value('contact_type', $row) && $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 $rowCount rows
             if ($count % $rowCount == 0) {
                 self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
                 $componentDetails = array();
             }
         }
         $dao->free();
         $offset += $rowCount;
     }
     self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
     // do merge same address and merge same household processing
     if ($mergeSameAddress) {
         self::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $drop);
     }
     // merge the records if they have corresponding households
     if ($mergeSameHousehold) {
         self::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKey);
     }
     // fix the headers for rows with relationship type
     if ($relName) {
         self::manipulateHeaderRows($headerRows, $contactRelationshipTypes);
     }
     // call export hook
     require_once 'CRM/Utils/Hook.php';
     CRM_Utils_Hook::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
     // now write the CSV file
     self::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
     CRM_Utils_System::civiExit();
 }
 /**
  *  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'], array('context' => 'menu'));
     $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'];
     $menuName = $value['attributes']['name'];
     if (in_array($parentID, $skipMenuItems) || !$active) {
         $skipMenuItems[] = $navID;
         return false;
     }
     //we need to check core view/edit or supported acls.
     require_once 'CRM/Core/Permission.php';
     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 {
             $url = CRM_Utils_System::url($url);
         }
         $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;
                 }
             } 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;
 }
 /**
  * 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();
 }
Exemple #17
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;
 }
Exemple #18
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)
 {
     //$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']);
             if (is_numeric(CRM_Utils_Array::value('1', $fieldArray))) {
                 $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] . "`";
                 }
             }
             $varArray[$key] = $field;
         }
     }
     $sort->_vars = $varArray;
     $result = $this->_query->searchQuery($offset, $rowCount, $sort, null, null, null, null, null);
     // 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->_gid);
     require_once 'CRM/Core/PseudoConstant.php';
     $locationTypes = CRM_Core_PseudoConstant::locationType();
     $names = array();
     static $skipFields = array('group', 'tag');
     foreach ($this->_fields as $key => $field) {
         if (CRM_Utils_Array::value('in_selector', $field) && !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);
                 $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 {
                 if ($field['name'] == 'id') {
                     $names[] = 'contact_id';
                 } else {
                     $names[] = $field['name'];
                 }
             }
         }
     }
     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';
         $multipleSelectFields = CRM_Quest_BAO_Student::$multipleSelectFields;
     }
     if ($this->_linkToUF) {
         require_once 'api/UFGroup.php';
     }
     require_once 'CRM/Contact/BAO/Contact/Utils.php';
     while ($result->fetch()) {
         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);
         if ($result->sort_name) {
             $row['sort_name'] = $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);
             } else {
                 if ($name == 'home_URL' && !empty($result->{$name})) {
                     $url = CRM_Utils_System::fixURL($result->{$name});
                     $row[] = "<a href=\"{$url}\">{$result->{$name}}</a>";
                 } else {
                     if ($multipleSelectFields && array_key_exists($name, $multipleSelectFields)) {
                         //fix to display student checkboxes
                         $key = $name;
                         $paramsNew = array($key => $result->{$name});
                         if ($key == 'test_tutoring') {
                             $name = array($key => array('newName' => $key, 'groupName' => 'test'));
                         } else {
                             if (substr($key, 0, 4) == 'cmr_') {
                                 //for  readers group
                                 $name = array($key => array('newName' => $key, 'groupName' => substr($key, 0, -3)));
                             } else {
                                 $name = array($key => array('newName' => $key, 'groupName' => $key));
                             }
                         }
                         CRM_Core_OptionGroup::lookupValues($paramsNew, $name, false);
                         $row[] = $paramsNew[$key];
                     } else {
                         if (strpos($name, '-im')) {
                             if (!empty($result->{$name})) {
                                 $imProviders = CRM_Core_PseudoConstant::IMProvider();
                                 $providerId = $name . "-provider_id";
                                 $providerName = $imProviders[$result->{$providerId}];
                                 $row[] = $result->{$name} . " ({$providerName})";
                             } else {
                                 $row[] = '';
                             }
                         } 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' => $this->_gid);
         if ($this->_linkToUF) {
             $ufID = crm_uf_get_uf_id($result->contact_id);
             if (!$ufID) {
                 unset($newLinks[CRM_Core_Action::PROFILE]);
             } else {
                 $params['ufID'] = $ufID;
             }
         }
         $row[] = CRM_Core_Action::formLink($newLinks, $mask, $params);
         if (!$empty) {
             $rows[] = $row;
         }
     }
     return $rows;
 }
Exemple #19
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;
 }
Exemple #20
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
  */
 static 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';
     require_once 'CRM/Core/Menu.php';
     require_once 'CRM/Core/Component.php';
     require_once 'CRM/Core/Permission.php';
     if ($args[0] !== 'civicrm') {
         return;
     }
     if (isset($args[1]) and $args[1] == 'menu' and isset($args[2]) and $args[2] == 'rebuild') {
         CRM_Core_Menu::store();
         CRM_Core_Session::setStatus(ts('Menu has been rebuilt'));
         // also reset navigation
         require_once 'CRM/Core/BAO/Navigation.php';
         CRM_Core_BAO_Navigation::resetNavigation();
         return CRM_Utils_System::redirect();
     }
     // first fire up IDS and check for bad stuff
     require_once 'CRM/Core/IDS.php';
     $ids = new CRM_Core_IDS();
     $ids->check($args);
     $config =& CRM_Core_Config::singleton();
     // also initialize the i18n framework
     $i18n =& CRM_Core_I18n::singleton();
     if ($config->userFramework == 'Standalone') {
         require_once 'CRM/Core/Session.php';
         $session =& CRM_Core_Session::singleton();
         if ($session->get('new_install') !== true) {
             require_once 'CRM/Core/Standalone.php';
             CRM_Core_Standalone::sidebarLeft();
         } else {
             if ($args[1] == 'standalone' && $args[2] == 'register') {
                 CRM_Core_Menu::store();
             }
         }
     }
     // get the menu items
     $path = implode('/', $args);
     $item =& CRM_Core_Menu::get($path);
     // we should try to compute menus, if item is empty and stay on the same page,
     // rather than compute and redirect to dashboard.
     if (!$item) {
         CRM_Core_Menu::store(false);
         $item =& CRM_Core_Menu::get($path);
     }
     if ($config->userFramework == 'Joomla' && $item) {
         $config->userFrameworkURLVar = 'task';
         require_once 'CRM/Core/Joomla.php';
         // joomla 1.5RC1 seems to push this in the POST variable, which messes
         // QF and checkboxes
         unset($_POST['option']);
         CRM_Core_Joomla::sidebarLeft();
     }
     // set active Component
     $template =& CRM_Core_Smarty::singleton();
     $template->assign('activeComponent', 'CiviCRM');
     $template->assign('formTpl', 'default');
     if ($item) {
         if (!array_key_exists('page_callback', $item)) {
             CRM_Core_Error::debug('Bad item', $item);
             CRM_Core_Error::fatal(ts('Bad menu record in database'));
         }
         // check that we are permissioned to access this page
         if (!CRM_Core_Permission::checkMenuItem($item)) {
             CRM_Utils_System::permissionDenied();
             return;
         }
         // check if ssl is set
         if (CRM_Utils_Array::value('is_ssl', $item)) {
             CRM_Utils_System::redirectToSSL();
         }
         if (isset($item['title'])) {
             CRM_Utils_System::setTitle($item['title']);
         }
         if (isset($item['breadcrumb']) && !isset($item['is_public'])) {
             CRM_Utils_System::appendBreadCrumb($item['breadcrumb']);
         }
         $pageArgs = null;
         if (CRM_Utils_Array::value('page_arguments', $item)) {
             $pageArgs = CRM_Core_Menu::getArrayForPathArgs($item['page_arguments']);
         }
         $template =& CRM_Core_Smarty::singleton();
         if (isset($item['is_public']) && $item['is_public']) {
             $template->assign('urlIsPublic', true);
         } else {
             $template->assign('urlIsPublic', false);
         }
         if (isset($item['return_url'])) {
             $session =& CRM_Core_Session::singleton();
             $args = CRM_Utils_Array::value('return_url_args', $item, 'reset=1');
             $session->pushUserContext(CRM_Utils_System::url($item['return_url'], $args));
         }
         if (is_array($item['page_callback'])) {
             $newArgs = explode('/', $_GET[$config->userFrameworkURLVar]);
             require_once str_replace('_', DIRECTORY_SEPARATOR, $item['page_callback'][0]) . '.php';
             return call_user_func($item['page_callback'], $newArgs);
         } else {
             if (strstr($item['page_callback'], '_Form')) {
                 $wrapper =& new CRM_Utils_Wrapper();
                 return $wrapper->run(CRM_Utils_Array::value('page_callback', $item), CRM_Utils_Array::value('title', $item), isset($pageArgs) ? $pageArgs : null);
             } else {
                 $newArgs = explode('/', $_GET[$config->userFrameworkURLVar]);
                 require_once str_replace('_', DIRECTORY_SEPARATOR, $item['page_callback']) . '.php';
                 $mode = 'null';
                 if (isset($pageArgs['mode'])) {
                     $mode = $pageArgs['mode'];
                     unset($pageArgs['mode']);
                 }
                 $title = CRM_Utils_Array::value('title', $item);
                 if (strstr($item['page_callback'], '_Page')) {
                     eval('$object =& ' . "new {$item['page_callback']}( \$title, \$mode );");
                 } else {
                     if (strstr($item['page_callback'], '_Controller')) {
                         $addSequence = 'false';
                         if (isset($pageArgs['addSequence'])) {
                             $addSequence = $pageArgs['addSequence'];
                             $addSequence = $addSequence ? 'true' : 'false';
                             unset($pageArgs['addSequence']);
                         }
                         eval('$object =& ' . "new {$item['page_callback']} ( \$title, true, \$mode, null, \$addSequence );");
                     } else {
                         CRM_Core_Error::fatal();
                     }
                 }
                 return $object->run($newArgs, $pageArgs);
             }
         }
     }
     CRM_Core_Menu::store();
     CRM_Core_Session::setStatus(ts('Menu has been rebuilt'));
     return CRM_Utils_System::redirect();
 }
Exemple #21
0
/**
 * Short-named function for string translation, defined in global scope so it's available everywhere.
 *
 * @param string $text
 *   String string for translating.
 * @param array $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);
    }
}
 public static function exportComponents($selectAll, $ids, $params, $order = NULL, $fields = NULL, $moreReturnProperties = NULL, $exportMode = CRM_Export_Form_Select_Relationship::RELATIONSHIP_EXPORT, $componentClause = NULL, $componentTable = NULL, $mergeSameAddress = FALSE, $mergeSameHousehold = FALSE, $exportParams = array(), $queryOperator = 'AND')
 {
     $headerRows = $returnProperties = array();
     $queryMode = CRM_Relationship_BAO_Query::MODE_RELATIONSHIPS;
     //Welke velden exporteren, gezet bij een mapping, indien niet gezet, primary fields.
     if ($fields) {
         foreach ($fields as $key => $value) {
             $fieldName = CRM_Utils_Array::value(0, $value);
             if (!$fieldName) {
                 continue;
             }
             $returnProperties[$fieldName] = 1;
         }
     } else {
         // Copied from CRM_Relationship_BAO_QUERY should be refactored to seperate
         // method.
         $fields = CRM_Contact_BAO_Relationship::fields();
         // Add display_name for both contacts
         $contact_fields = CRM_Contact_BAO_Contact::exportableFields('All', FALSE, TRUE, TRUE);
         $fields['contact_a'] = $contact_fields['display_name'];
         $fields['contact_a']['where'] = 'contact_a.display_name';
         $fields['contact_b'] = $contact_fields['display_name'];
         $fields['contact_b']['where'] = 'contact_b.display_name';
         // Add relationship type field
         $relationship_type_fields = CRM_Contact_BAO_RelationshipType::fields();
         $fields['relationship_type'] = $relationship_type_fields['label_a_b'];
         $fields['relationship_type']['where'] = 'relationship_type.label_a_b';
         // Add custom fields
         $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Relationship'));
         $returnProperties = CRM_Relationship_BAO_Query::defaultReturnProperties();
     }
     if ($moreReturnProperties) {
         $returnProperties = array_merge($returnProperties, $moreReturnProperties);
     }
     $query = new CRM_Relationship_BAO_Query($params, $returnProperties, NULL, FALSE, FALSE, FALSE, TRUE, $queryOperator);
     //sort by state
     //CRM-15301
     $query->_sort = $order;
     list($select, $from, $where, $having) = $query->query();
     $allRelContactArray = $relationQuery = array();
     if (!$selectAll && $componentTable) {
         // TODO For not select all
         //$from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
     } elseif ($componentClause) {
         if (empty($where)) {
             $where = "WHERE {$componentClause}";
         } else {
             $where .= " AND {$componentClause}";
         }
     }
     $queryString = "{$select} {$from} {$where} {$having}";
     $groupBy = "";
     if ($queryMode & CRM_Relationship_BAO_Query::MODE_RELATIONSHIPS && $query->_useGroupBy) {
         $groupBy = " GROUP BY relationship.id";
     }
     $queryString .= $groupBy;
     // always add relationship.id to the ORDER clause
     // so the order is deterministic
     if (strpos('relationship.id', $order) === FALSE) {
         $order .= ", relationship.id";
     }
     if ($order) {
         list($field, $dir) = explode(' ', $order, 2);
         $field = trim($field);
         if (!empty($returnProperties[$field])) {
             //CRM-15301
             $queryString .= " ORDER BY {$order}";
         }
     }
     $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;
             //first loop through output columns so that we return what is required, and in same order.
             foreach ($outputColumns as $field => $value) {
                 //we should set header only once
                 if ($setHeader) {
                     $sqlDone = FALSE;
                     $headerRows[] = $query->_fields[$field]['title'];
                     if (!$sqlDone) {
                         self::sqlColumnDefn($query, $sqlColumns, $field);
                     }
                 }
                 //build row values (data)
                 $fieldValue = NULL;
                 if (property_exists($iterationDAO, $field)) {
                     $fieldValue = $iterationDAO->{$field};
                 }
                 if ($field == 'id') {
                     $row[$field] = $iterationDAO->relationship_id;
                 } 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);
                     } else {
                         //normal fields with a touch of CRM-3157
                         $row[$field] = $fieldValue;
                     }
                 } else {
                     // if field is empty or null
                     $row[$field] = '';
                 }
             }
             if ($setHeader) {
                 $exportTempTable = self::createTempTable($sqlColumns);
             }
             //build header only once
             $setHeader = FALSE;
             // 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);
         }
         // 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'));
     }
 }
 /**
  * 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;
 }
 /**
  * Get all the countries from database.
  *
  * The static array country is returned, and if it's
  * called the first time, the <b>Country DAO</b> is used 
  * to get all the countries.
  *
  * Note: any database errors will be trapped by the DAO.
  *
  * @access public
  * @static
  *
  * @param int $id - Optional id to return
  * @return array - array reference of all countries.
  *
  */
 function &country($id = false)
 {
     if (!$GLOBALS['_CRM_CORE_PSEUDOCONSTANT']['country']) {
         $config =& CRM_Core_Config::singleton();
         // limit the country list to the countries specified in CIVICRM_COUNTRY_LIMIT
         // (ensuring it's a subset of the legal values)
         $limitCodes = $config->countryLimit;
         $limitCodes = array_intersect(CRM_Core_PseudoConstant::countryIsoCode(), $limitCodes);
         if (count($limitCodes)) {
             $whereClause = "iso_code IN ('" . implode("', '", $limitCodes) . "')";
         } else {
             $whereClause = null;
         }
         CRM_Core_PseudoConstant::populate($GLOBALS['_CRM_CORE_PSEUDOCONSTANT']['country'], 'CRM_Core_DAO_Country', true, 'name', 'is_active', $whereClause);
         // localise the country names if in an non-en_US locale
         if ($config->lcMessages != '' and $config->lcMessages != 'en_US') {
             $i18n =& CRM_Core_I18n::singleton();
             $i18n->localizeArray($GLOBALS['_CRM_CORE_PSEUDOCONSTANT']['country']);
             asort($GLOBALS['_CRM_CORE_PSEUDOCONSTANT']['country']);
         }
     }
     if ($id) {
         if (array_key_exists($id, $GLOBALS['_CRM_CORE_PSEUDOCONSTANT']['country'])) {
             return $GLOBALS['_CRM_CORE_PSEUDOCONSTANT']['country'][$id];
         } else {
             return null;
         }
     }
     return $GLOBALS['_CRM_CORE_PSEUDOCONSTANT']['country'];
 }
Exemple #25
0
 /**
  * @return array
  */
 public static function getAvailableCountries()
 {
     $i18n = CRM_Core_I18n::singleton();
     $country = array();
     CRM_Core_PseudoConstant::populate($country, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active');
     $i18n->localizeArray($country, array('context' => 'country'));
     asort($country);
     return $country;
 }
 public function buildQuickForm()
 {
     CRM_Utils_System::setTitle(ts('Sepa Direct Debit - Settings'));
     $customFields = CRM_Core_BAO_CustomField::getFields();
     $cf = array();
     foreach ($customFields as $k => $v) {
         $cf[$k] = $v['label'];
     }
     // add all form elements and validation rules
     foreach ($this->config_fields as $key => $value) {
         $elementName = $this->domainToString($value[0]);
         $elem = $this->addElement('text', $elementName, $value[1], isset($value[2]) ? $value[2] : array());
         if (!in_array($elementName, array('cycledays', 'custom_txmsg'))) {
             // integer only rules, except for cycledays (list)
             $this->addRule($this->domainToString($value[0]), sprintf(ts("Please enter the %s as number (integers only)."), $value[1]), 'positiveInteger');
             $this->addRule($this->domainToString($value[0]), sprintf(ts("Please enter the %s as number (integers only)."), $value[1]), 'required');
         }
     }
     // country drop down field
     $config = CRM_Core_Config::singleton();
     $i18n = CRM_Core_I18n::singleton();
     $climit = array();
     $cnames = array();
     $ciso = array();
     $filtered = array();
     $climit = $config->countryLimit();
     CRM_Core_PseudoConstant::populate($cnames, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active');
     CRM_Core_PseudoConstant::populate($ciso, 'CRM_Core_DAO_Country', TRUE, 'iso_code');
     foreach ($ciso as $key => $value) {
         foreach ($climit as $active_country) {
             if ($active_country == $value) {
                 $filtered[$key] = $cnames[$key];
             }
         }
     }
     $i18n->localizeArray($filtered, array('context' => 'country'));
     asort($filtered);
     // do not use array_merge() because it discards the original indizes
     $country_ids = array('' => ts('- select -')) + $filtered;
     $exw = CRM_Core_BAO_Setting::getItem('SEPA Direct Debit Preferences', 'exclude_weekends');
     if ($exw) {
         $exw = array('checked' => 'checked');
     } else {
         $exw = array();
     }
     // add creditor form elements
     $this->addElement('text', 'addcreditor_creditor_id', ts("Creditor Contact"));
     $this->addElement('text', 'addcreditor_name', ts("Name"));
     $this->addElement('text', 'addcreditor_id', ts("Identifier"));
     $this->addElement('text', 'addcreditor_address', ts("Address"));
     $this->addElement('select', 'addcreditor_country_id', ts("Country"), $country_ids);
     $this->addElement('text', 'addcreditor_bic', ts("BIC"));
     $this->addElement('text', 'addcreditor_iban', ts("IBAN"));
     $this->addElement('select', 'addcreditor_pain_version', ts("PAIN Version"), array('' => ts('- select -')) + CRM_Core_OptionGroup::values('sepa_file_format'));
     $this->addElement('checkbox', 'is_test_creditor', ts("Is a Test Creditor"), "", array('value' => '0'));
     $this->addElement('checkbox', 'exclude_weekends', ts("Exclude Weekends"), "", $exw);
     $this->addElement('hidden', 'edit_creditor_id', '', array('id' => 'edit_creditor_id'));
     $this->addElement('hidden', 'add_creditor_id', '', array('id' => 'add_creditor_id'));
     // add custom form elements and validation rules
     $index = 0;
     foreach ($this->custom_fields as $key => $value) {
         $this->addElement('text', $this->domainToString($value[0]), $value[1], array('placeholder' => CRM_Core_BAO_Setting::getItem('SEPA Direct Debit Preferences', $this->domainToString($this->config_fields[$index][0]))));
         $elementName = $this->domainToString($value[0]);
         if (!in_array($elementName, array('custom_cycledays', 'custom_txmsg'))) {
             // integer only rules, except for cycledays (list)
             $this->addRule($elementName, sprintf(ts("Please enter the %s as number (integers only)."), $value[1]), 'positiveInteger');
         }
         $index++;
     }
     // register and add extra validation rules
     $this->registerRule('sepa_cycle_day_list', 'callback', 'sepa_cycle_day_list', 'CRM_Sepa_Logic_Settings');
     $this->addRule('cycledays', ts('Please give a comma separated list of valid days.'), 'sepa_cycle_day_list');
     $this->addRule('custom_cycledays', ts('Please give a comma separated list of valid days.'), 'sepa_cycle_day_list');
     // get creditor list
     $creditors_default_list = array();
     $creditor_query = civicrm_api('SepaCreditor', 'get', array('version' => 3, 'option.limit' => 99999));
     if (!empty($creditor_query['is_error'])) {
         return civicrm_api3_create_error("Cannot get creditor list: " . $creditor_query['error_message']);
     } else {
         $creditors = array();
         foreach ($creditor_query['values'] as $creditor) {
             $creditors[] = $creditor;
             $creditors_default_list[$creditor['id']] = $creditor['name'];
         }
     }
     $this->assign('creditors', $creditors);
     $default_creditors = $this->addElement('select', 'batching_default_creditor', ts("Default Creditor"), array('' => ts('- select -')) + $creditors_default_list);
     $default_creditors->setSelected(CRM_Sepa_Logic_Settings::getSetting('batching.default.creditor'));
     // add general config options
     $amm_options = CRM_Sepa_Logic_Settings::getSetting('allow_mandate_modification') ? array('checked' => 'checked') : array();
     $this->addElement('checkbox', 'allow_mandate_modification', ts("Mandate Modifications"), NULL, $amm_options);
     parent::buildQuickForm();
 }
 /**
  * @param $communication_language
  * @param $preferred_language
  */
 public static function setCommunicationLanguage($communication_language, $preferred_language)
 {
     $config = CRM_Core_Config::singleton();
     $language = $config->lcMessages;
     // prepare the language for the email
     if ($communication_language == CRM_Core_I18n::AUTO) {
         if (!empty($preferred_language)) {
             $language = $preferred_language;
         }
     } else {
         $language = $communication_language;
     }
     // language not in the existing language, use default
     $languages = CRM_Core_I18n::languages(TRUE);
     if (!in_array($language, $languages)) {
         $language = $config->lcMessages;
     }
     // change the language
     $i18n = CRM_Core_I18n::singleton();
     $i18n->setLanguage($language);
 }
 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;
 }
Exemple #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'));
     }
 }
 /**
  * given an id return the relevant contact details
  *
  * @param int $id           contact id
  *
  * @return the contact object
  * @static
  * @access public
  */
 function contactDetails($id, &$options, $returnProperties = null)
 {
     if (!$id) {
         return null;
     }
     $params = array('id' => CRM_Utils_Type::escape($id, 'Integer'));
     $query =& new CRM_Contact_BAO_Query($params, $returnProperties, null, false, false);
     $options = $query->_options;
     list($select, $from, $where) = $query->query();
     $sql = "{$select} {$from} {$where}";
     $dao = CRM_Core_DAO::executeQuery($sql);
     if ($dao->fetch()) {
         if (isset($dao->country)) {
             // the query returns the untranslated country name
             $i18n =& CRM_Core_I18n::singleton();
             $dao->country = $i18n->translate($dao->country);
         }
         return $dao;
     } else {
         return null;
     }
 }