예제 #1
0
 /**
  * Test equals.
  *
  * @param string $timeA
  * @param string $timeB
  * @param int $threshold
  * @param bool $expectedResult
  *
  * @dataProvider equalCases
  */
 public function testEquals($timeA, $timeB, $threshold, $expectedResult)
 {
     $actual = CRM_Utils_Time::isEqual($timeA, $timeB, $threshold);
     $this->assertEquals($expectedResult, $actual);
     $actual = CRM_Utils_Time::isEqual($timeB, $timeA, $threshold);
     $this->assertEquals($expectedResult, $actual);
 }
예제 #2
0
 public function tearDown()
 {
     unset($this->queue);
     unset($this->queueService);
     CRM_Utils_Time::resetTime();
     $tablesToTruncate = array('civicrm_queue_item');
     $this->quickCleanup($tablesToTruncate);
 }
예제 #3
0
 public function testSequence()
 {
     $actStatuses = array_flip(\CRM_Core_PseudoConstant::activityStatus('name'));
     $caseStatuses = array_flip(\CRM_Case_PseudoConstant::caseStatus('name'));
     // Create case; schedule first activity
     \CRM_Utils_Time::setTime('2013-11-30 01:00:00');
     $case = $this->callAPISuccess('case', 'create', $this->_params);
     $analyzer = new \Civi\CCase\Analyzer($case['id']);
     $this->assertEquals($caseStatuses['Open'], self::ag($analyzer->getCase(), 'status_id'));
     $this->assertApproxTime('2013-11-30 01:00:00', self::ag($analyzer->getSingleActivity('Medical evaluation'), 'activity_date_time'));
     $this->assertEquals($actStatuses['Scheduled'], self::ag($analyzer->getSingleActivity('Medical evaluation'), 'status_id'));
     $this->assertFalse($analyzer->hasActivity('Mental health evaluation'));
     $this->assertFalse($analyzer->hasActivity('Secure temporary housing'));
     // Edit details of first activity -- but don't finish it yet!
     \CRM_Utils_Time::setTime('2013-11-30 01:30:00');
     $this->callApiSuccess('Activity', 'create', array('id' => self::ag($analyzer->getSingleActivity('Medical evaluation'), 'id'), 'subject' => 'This is the new subject'));
     $analyzer = new \Civi\CCase\Analyzer($case['id']);
     $this->assertEquals($caseStatuses['Open'], self::ag($analyzer->getCase(), 'status_id'));
     $this->assertApproxTime('2013-11-30 01:00:00', self::ag($analyzer->getSingleActivity('Medical evaluation'), 'activity_date_time'));
     $this->assertEquals($actStatuses['Scheduled'], self::ag($analyzer->getSingleActivity('Medical evaluation'), 'status_id'));
     $this->assertFalse($analyzer->hasActivity('Mental health evaluation'));
     $this->assertFalse($analyzer->hasActivity('Secure temporary housing'));
     // Complete first activity; schedule second
     \CRM_Utils_Time::setTime('2013-11-30 02:00:00');
     $this->callApiSuccess('Activity', 'create', array('id' => self::ag($analyzer->getSingleActivity('Medical evaluation'), 'id'), 'status_id' => $actStatuses['Completed']));
     $analyzer->flush();
     $this->assertEquals($caseStatuses['Open'], self::ag($analyzer->getCase(), 'status_id'));
     $this->assertApproxTime('2013-11-30 01:00:00', self::ag($analyzer->getSingleActivity('Medical evaluation'), 'activity_date_time'));
     $this->assertEquals($actStatuses['Completed'], self::ag($analyzer->getSingleActivity('Medical evaluation'), 'status_id'));
     $this->assertApproxTime('2013-11-30 02:00:00', self::ag($analyzer->getSingleActivity('Mental health evaluation'), 'activity_date_time'));
     $this->assertEquals($actStatuses['Scheduled'], self::ag($analyzer->getSingleActivity('Mental health evaluation'), 'status_id'));
     $this->assertFalse($analyzer->hasActivity('Secure temporary housing'));
     // Complete second activity; schedule third
     \CRM_Utils_Time::setTime('2013-11-30 03:00:00');
     $this->callApiSuccess('Activity', 'create', array('id' => self::ag($analyzer->getSingleActivity('Mental health evaluation'), 'id'), 'status_id' => $actStatuses['Completed']));
     $analyzer->flush();
     $this->assertEquals($caseStatuses['Open'], self::ag($analyzer->getCase(), 'status_id'));
     $this->assertApproxTime('2013-11-30 01:00:00', self::ag($analyzer->getSingleActivity('Medical evaluation'), 'activity_date_time'));
     $this->assertEquals($actStatuses['Completed'], self::ag($analyzer->getSingleActivity('Medical evaluation'), 'status_id'));
     $this->assertApproxTime('2013-11-30 02:00:00', self::ag($analyzer->getSingleActivity('Mental health evaluation'), 'activity_date_time'));
     $this->assertEquals($actStatuses['Completed'], self::ag($analyzer->getSingleActivity('Mental health evaluation'), 'status_id'));
     $this->assertApproxTime('2013-11-30 03:00:00', self::ag($analyzer->getSingleActivity('Secure temporary housing'), 'activity_date_time'));
     $this->assertEquals($actStatuses['Scheduled'], self::ag($analyzer->getSingleActivity('Secure temporary housing'), 'status_id'));
     // Complete third activity; close case
     \CRM_Utils_Time::setTime('2013-11-30 04:00:00');
     $this->callApiSuccess('Activity', 'create', array('id' => self::ag($analyzer->getSingleActivity('Secure temporary housing'), 'id'), 'status_id' => $actStatuses['Completed']));
     $analyzer->flush();
     $this->assertApproxTime('2013-11-30 01:00:00', self::ag($analyzer->getSingleActivity('Medical evaluation'), 'activity_date_time'));
     $this->assertEquals($actStatuses['Completed'], self::ag($analyzer->getSingleActivity('Medical evaluation'), 'status_id'));
     $this->assertApproxTime('2013-11-30 02:00:00', self::ag($analyzer->getSingleActivity('Mental health evaluation'), 'activity_date_time'));
     $this->assertEquals($actStatuses['Completed'], self::ag($analyzer->getSingleActivity('Mental health evaluation'), 'status_id'));
     $this->assertApproxTime('2013-11-30 03:00:00', self::ag($analyzer->getSingleActivity('Secure temporary housing'), 'activity_date_time'));
     $this->assertEquals($actStatuses['Completed'], self::ag($analyzer->getSingleActivity('Secure temporary housing'), 'status_id'));
     $this->assertEquals($caseStatuses['Closed'], self::ag($analyzer->getCase(), 'status_id'));
     // */
 }
예제 #4
0
파일: Env.php 프로젝트: hguru/224Civi
 public function checkMysqlTime()
 {
     $messages = array();
     $phpNow = date('Y-m-d H:i');
     $sqlNow = CRM_Core_DAO::singleValueQuery("SELECT date_format(now(), '%Y-%m-%d %H:%i')");
     if (!CRM_Utils_Time::isEqual($phpNow, $sqlNow, 2.5 * 60)) {
         $messages[] = new CRM_Utils_Check_Message('checkMysqlTime', ts('Timestamps reported by MySQL (eg "%2") and PHP (eg "%3" ) are mismatched.<br /><a href="%1">Read more about this warning</a>', array(1 => CRM_Utils_System::getWikiBaseURL() . 'checkMysqlTime', 2 => $sqlNow, 3 => $phpNow)), ts('Environment Settings'));
     }
     return $messages;
 }
예제 #5
0
/**
 * Generate a secure signature
 *
 * {code}
 * {crmSigner var=mySig extra=123}
 * var urlParams = ts={$mySig.ts}&extra={$mySig.extra}&sig={$mySig.signature}
 * {endcode}
 *
 * @param $params array with keys:
 *   - var: string, a smarty variable to generate
 *   - ts: int, the current time (if omitted, autogenerated)
 *   - any other vars are put into the signature (sorted)
 */
function smarty_function_crmSigner($params, &$smarty)
{
    $var = $params['var'];
    unset($params['var']);
    $params['ts'] = CRM_Utils_Time::getTimeRaw();
    $fields = array_keys($params);
    sort($fields);
    $signer = new CRM_Utils_Signer(CRM_Core_Key::privateKey(), $fields);
    $params['signature'] = $signer->sign($params);
    $smarty->assign($var, $params);
}
예제 #6
0
 /**
  * Check that the MySQL time settings match the PHP time settings.
  *
  * @return array<CRM_Utils_Check_Message> an empty array, or a list of warnings
  */
 public function checkMysqlTime()
 {
     //CRM-19115 - Always set MySQL time before checking it.
     CRM_Core_Config::singleton()->userSystem->setMySQLTimeZone();
     $messages = array();
     $phpNow = date('Y-m-d H:i');
     $sqlNow = CRM_Core_DAO::singleValueQuery("SELECT date_format(now(), '%Y-%m-%d %H:%i')");
     if (!CRM_Utils_Time::isEqual($phpNow, $sqlNow, 2.5 * 60)) {
         $messages[] = new CRM_Utils_Check_Message(__FUNCTION__, ts('Timestamps reported by MySQL (eg "%2") and PHP (eg "%3" ) are mismatched.<br /><a href="%1">Read more about this warning</a>', array(1 => CRM_Utils_System::getWikiBaseURL() . 'checkMysqlTime', 2 => $sqlNow, 3 => $phpNow)), ts('Timestamp Mismatch'), \Psr\Log\LogLevel::ERROR, 'fa-server');
     }
     return $messages;
 }
예제 #7
0
파일: Http.php 프로젝트: kidaa30/yes
 /**
  * Parse the expiration time from a series of HTTP headers.
  *
  * @param array $headers
  * @return int|NULL
  *   Expiration tme as seconds since epoch, or NULL if not cacheable.
  */
 public static function parseExpiration($headers)
 {
     $headers = CRM_Utils_Array::rekey($headers, function ($k, $v) {
         return strtolower($k);
     });
     if (!empty($headers['cache-control'])) {
         $cc = self::parseCacheControl($headers['cache-control']);
         if ($cc['max-age'] && is_numeric($cc['max-age'])) {
             return CRM_Utils_Time::getTimeRaw() + $cc['max-age'];
         }
     }
     return NULL;
 }
 /**
  * Get the next item, even if there's an active lease
  *
  * @param $lease_time seconds
  *
  * @return object with key 'data' that matches the inputted data
  */
 function stealItem($lease_time = 3600)
 {
     $sql = "\n      SELECT id, queue_name, submit_time, release_time, data\n      FROM civicrm_queue_item\n      WHERE queue_name = %1\n      ORDER BY weight ASC, release_time ASC, id ASC\n      LIMIT 1\n    ";
     $params = array(1 => array($this->getName(), 'String'));
     $dao = CRM_Core_DAO::executeQuery($sql, $params, TRUE, 'CRM_Queue_DAO_QueueItem');
     if ($dao->fetch()) {
         $nowEpoch = CRM_Utils_Time::getTimeRaw();
         CRM_Core_DAO::executeQuery("UPDATE civicrm_queue_item SET release_time = %1 WHERE id = %2", array('1' => array(date('YmdHis', $nowEpoch + $lease_time), 'String'), '2' => array($dao->id, 'Integer')));
         $dao->data = unserialize($dao->data);
         return $dao;
     } else {
         CRM_Core_Error::debug_var('no items found');
         return FALSE;
     }
 }
예제 #9
0
 /**
  * @param string $file
  *   Local file path.
  * @param string $mimeType
  * @param int $ttl
  *   Time to live (seconds).
  */
 protected function download($file, $mimeType, $ttl)
 {
     if (!file_exists($file)) {
         header("HTTP/1.0 404 Not Found");
         return;
     } elseif (!is_readable($file)) {
         header('HTTP/1.0 403 Forbidden');
         return;
     }
     CRM_Utils_System::setHttpHeader('Expires', gmdate('D, d M Y H:i:s \\G\\M\\T', CRM_Utils_Time::getTimeRaw() + $ttl));
     CRM_Utils_System::setHttpHeader("Content-Type", $mimeType);
     CRM_Utils_System::setHttpHeader("Content-Disposition", "inline; filename=\"" . basename($file) . "\"");
     CRM_Utils_System::setHttpHeader("Cache-Control", "max-age={$ttl}, public");
     CRM_Utils_System::setHttpHeader('Pragma', 'public');
     readfile($file);
 }
예제 #10
0
 /**
  * @param string $verb
  * @param string $url
  * @param string $blob
  * @param array $headers
  *   Array of headers (e.g. "Content-type" => "text/plain").
  * @return array
  *   array($headers, $blob, $code)
  */
 public function send($verb, $url, $blob, $headers = array())
 {
     $lowVerb = strtolower($verb);
     if ($lowVerb === 'get' && $this->cache) {
         $cachePath = 'get/' . md5($url);
         $cacheLine = $this->cache->get($cachePath);
         if ($cacheLine && $cacheLine['expires'] > CRM_Utils_Time::getTimeRaw()) {
             return $cacheLine['data'];
         }
     }
     $result = parent::send($verb, $url, $blob, $headers);
     if ($lowVerb === 'get' && $this->cache) {
         $expires = CRM_Utils_Http::parseExpiration($result[0]);
         if ($expires !== NULL) {
             $cachePath = 'get/' . md5($url);
             $cacheLine = array('url' => $url, 'expires' => $expires, 'data' => $result);
             $this->cache->set($cachePath, $cacheLine);
         }
     }
     return $result;
 }
예제 #11
0
 /**
  * Get the messages document (either from the cache or by downloading)
  *
  * @return NULL|array
  */
 public function getDocument()
 {
     $isChanged = FALSE;
     $document = $this->cache->get('communityMessages');
     if (empty($document) || !is_array($document)) {
         $document = array('messages' => array(), 'expires' => 0, 'ttl' => self::DEFAULT_RETRY, 'retry' => self::DEFAULT_RETRY);
         $isChanged = TRUE;
     }
     if ($document['expires'] <= CRM_Utils_Time::getTimeRaw()) {
         $newDocument = $this->fetchDocument();
         if ($newDocument && $this->validateDocument($newDocument)) {
             $document = $newDocument;
             $document['expires'] = CRM_Utils_Time::getTimeRaw() + $document['ttl'];
         } else {
             // keep the old messages for now, try again later
             $document['expires'] = CRM_Utils_Time::getTimeRaw() + $document['retry'];
         }
         $isChanged = TRUE;
     }
     if ($isChanged) {
         $this->cache->set('communityMessages', $document);
     }
     return $document;
 }
 /**
  * Save an action into a queue for delayed processing
  *
  * @param \DateTime $delayTo
  * @param \CRM_Civirules_Action $action
  * @param \CRM_Civirules_TriggerData_TriggerData $triggerData
  */
 protected static function delayAction(DateTime $delayTo, CRM_Civirules_Action $action, CRM_Civirules_TriggerData_TriggerData $triggerData)
 {
     $queue = CRM_Queue_Service::singleton()->create(array('type' => 'Civirules', 'name' => self::QUEUE_NAME, 'reset' => false));
     //create a task with the action and eventData as parameters
     $task = new CRM_Queue_Task(array('CRM_Civirules_Engine', 'executeDelayedAction'), array($action, $triggerData));
     //save the task with a delay
     $dao = new CRM_Queue_DAO_QueueItem();
     $dao->queue_name = $queue->getName();
     $dao->submit_time = CRM_Utils_Time::getTime('YmdHis');
     $dao->data = serialize($task);
     $dao->weight = 0;
     //weight, normal priority
     $dao->release_time = $delayTo->format('YmdHis');
     $dao->save();
 }
예제 #13
0
 /**
  * Run a series of cron jobs and make an assertion about email deliveries.
  *
  * @param array $cronRuns
  *   array specifying when to run cron and what messages to expect; each item is an array with keys:
  *   - time: string, e.g. '2012-06-15 21:00:01'
  *   - recipients: array(array(string)), list of email addresses which should receive messages
  */
 public function assertCronRuns($cronRuns)
 {
     foreach ($cronRuns as $cronRun) {
         CRM_Utils_Time::setTime($cronRun['time']);
         $this->callAPISuccess('job', 'send_reminder', array());
         $this->mut->assertRecipients($cronRun['recipients']);
         if (array_key_exists('subjects', $cronRun)) {
             $this->mut->assertSubjects($cronRun['subjects']);
         }
         $this->mut->clearMessages();
     }
 }
예제 #14
0
 /**
  * Update the DB record for this setting.
  *
  * @param string $name
  *   The simple name of the setting.
  * @param mixed $value
  *   The new value of the setting.
  */
 protected function setDb($name, $value)
 {
     if (\CRM_Core_BAO_Setting::isUpgradeFromPreFourOneAlpha1()) {
         // civicrm_setting table is not going to be present.
         return;
     }
     $fields = array();
     $fieldsToSet = \CRM_Core_BAO_Setting::validateSettingsInput(array($name => $value), $fields);
     //We haven't traditionally validated inputs to setItem, so this breaks things.
     //foreach ($fieldsToSet as $settingField => &$settingValue) {
     //  self::validateSetting($settingValue, $fields['values'][$settingField]);
     //}
     $metadata = $fields['values'][$name];
     $dao = new \CRM_Core_DAO_Setting();
     $dao->name = $name;
     $dao->domain_id = $this->domainId;
     if ($this->contactId) {
         $dao->contact_id = $this->contactId;
         $dao->is_domain = 0;
     } else {
         $dao->is_domain = 1;
     }
     $dao->find(TRUE);
     if (isset($metadata['on_change'])) {
         foreach ($metadata['on_change'] as $callback) {
             call_user_func(\Civi\Core\Resolver::singleton()->get($callback), unserialize($dao->value), $value, $metadata, $this->domainId);
         }
     }
     if (!is_array($value) && \CRM_Utils_System::isNull($value)) {
         $dao->value = 'null';
     } else {
         $dao->value = serialize($value);
     }
     if (!isset(\Civi::$statics[__CLASS__]['upgradeMode'])) {
         \Civi::$statics[__CLASS__]['upgradeMode'] = \CRM_Core_Config::isUpgradeMode();
     }
     if (\Civi::$statics[__CLASS__]['upgradeMode'] && \CRM_Core_DAO::checkFieldExists('civicrm_setting', 'group_name')) {
         $dao->group_name = 'placeholder';
     }
     $dao->created_date = \CRM_Utils_Time::getTime('YmdHis');
     $session = \CRM_Core_Session::singleton();
     if (\CRM_Contact_BAO_Contact_Utils::isContactId($session->get('userID'))) {
         $dao->created_id = $session->get('userID');
     }
     if ($dao->id) {
         $dao->save();
     } else {
         // Cannot use $dao->save(); in upgrade mode (eg WP + Civi 4.4=>4.7), the DAO will refuse
         // to save the field `group_name`, which is required in older schema.
         \CRM_Core_DAO::executeQuery(\CRM_Utils_SQL_Insert::dao($dao)->toSQL());
     }
     $dao->free();
 }
예제 #15
0
 /**
  * Update the DB record for this setting.
  *
  * @param string $name
  *   The simple name of the setting.
  * @param mixed $value
  *   The new value of the setting.
  */
 protected function setDb($name, $value)
 {
     if (\CRM_Core_BAO_Setting::isUpgradeFromPreFourOneAlpha1()) {
         // civicrm_setting table is not going to be present.
         return;
     }
     $fields = array();
     $fieldsToSet = \CRM_Core_BAO_Setting::validateSettingsInput(array($name => $value), $fields);
     //We haven't traditionally validated inputs to setItem, so this breaks things.
     //foreach ($fieldsToSet as $settingField => &$settingValue) {
     //  self::validateSetting($settingValue, $fields['values'][$settingField]);
     //}
     $metadata = $fields['values'][$name];
     $dao = new \CRM_Core_DAO_Setting();
     $dao->name = $name;
     $dao->domain_id = $this->domainId;
     if ($this->contactId) {
         $dao->contact_id = $this->contactId;
         $dao->is_domain = 0;
     } else {
         $dao->is_domain = 1;
     }
     $dao->find(TRUE);
     if (isset($metadata['on_change'])) {
         foreach ($metadata['on_change'] as $callback) {
             call_user_func(\Civi\Core\Resolver::singleton()->get($callback), unserialize($dao->value), $value, $metadata, $this->domainId);
         }
     }
     if (\CRM_Utils_System::isNull($value)) {
         $dao->value = 'null';
     } else {
         $dao->value = serialize($value);
     }
     $dao->created_date = \CRM_Utils_Time::getTime('Ymdhis');
     $session = \CRM_Core_Session::singleton();
     if (\CRM_Contact_BAO_Contact_Utils::isContactId($session->get('userID'))) {
         $dao->created_id = $session->get('userID');
     }
     $dao->save();
     $dao->free();
 }
예제 #16
0
 /**
  * @param null $now
  * @param array $params
  *
  * @return array
  */
 static function processQueue($now = NULL, $params = array())
 {
     $now = $now ? CRM_Utils_Time::setTime($now) : CRM_Utils_Time::getTime();
     $mappings = self::getMapping();
     foreach ($mappings as $mappingID => $mapping) {
         self::buildRecipientContacts($mappingID, $now, $params);
         self::sendMailings($mappingID, $now);
     }
     $result = array('is_error' => 0, 'messages' => ts('Sent all scheduled reminders successfully'));
     return $result;
 }
예제 #17
0
 /**
  * @param string $token
  *   A token supplied by the user.
  * @return bool
  *   TRUE if the token is valid for submitting attachments
  * @throws Exception
  */
 public static function checkToken($token)
 {
     list($signature, $ts) = explode(';;;', $token);
     $signer = new CRM_Utils_Signer(CRM_Core_Key::privateKey(), array('for', 'ts'));
     if (!is_numeric($ts) || CRM_Utils_Time::getTimeRaw() > $ts + self::ATTACHMENT_TOKEN_TTL) {
         return FALSE;
     }
     return $signer->validate($signature, array('for' => 'crmAttachment', 'ts' => $ts));
 }
예제 #18
0
 /**
  * Execute the default schedule, without any special recipient selections.
  *
  * @dataProvider createTestCases
  *
  * @param string $targetDate
  * @param string $setupFuncs
  * @param array $expectMessages
  *
  * @throws \Exception
  */
 public function testDefault($targetDate, $setupFuncs, $expectMessages)
 {
     $this->targetDate = $targetDate;
     foreach (explode(' ', $setupFuncs) as $setupFunc) {
         $this->{$setupFunc}();
     }
     $this->schedule->save();
     $actualMessages = array();
     foreach ($this->cronTimes() as $time) {
         \CRM_Utils_Time::setTime($time);
         $this->callAPISuccess('job', 'send_reminder', array());
         foreach ($this->mut->getAllMessages('ezc') as $message) {
             /** @var \ezcMail $message */
             $simpleMessage = array('time' => $time, 'to' => \CRM_Utils_Array::collect('email', $message->to), 'subject' => $message->subject);
             sort($simpleMessage['to']);
             $actualMessages[] = $simpleMessage;
             $this->mut->clearMessages();
         }
     }
     $errorText = "Incorrect messages: " . print_r(array('actualMessages' => $actualMessages, 'expectMessages' => $expectMessages), 1);
     $this->assertEquals(count($expectMessages), count($actualMessages), $errorText);
     usort($expectMessages, array(__CLASS__, 'compareSimpleMsgs'));
     usort($actualMessages, array(__CLASS__, 'compareSimpleMsgs'));
     foreach ($expectMessages as $offset => $expectMessage) {
         $actualMessage = $actualMessages[$offset];
         $this->assertApproxEquals(strtotime($expectMessage['time']), strtotime($actualMessage['time']), $this->dateTolerance, $errorText);
         if (isset($expectMessage['to'])) {
             sort($expectMessage['to']);
             $this->assertEquals($expectMessage['to'], $actualMessage['to'], $errorText);
         }
         if (isset($expectMessage['subject'])) {
             $this->assertRegExp($expectMessage['subject'], $actualMessage['subject'], $errorText);
         }
     }
 }
예제 #19
0
파일: AJAX.php 프로젝트: hguru/224Civi
 /**
  *Function to check the CMS username
  *
  */
 public static function checkUserName()
 {
     $signer = new CRM_Utils_Signer(CRM_Core_Key::privateKey(), array('for', 'ts'));
     if (CRM_Utils_Time::getTimeRaw() > $_REQUEST['ts'] + self::CHECK_USERNAME_TTL || $_REQUEST['for'] != 'civicrm/ajax/cmsuser' || !$signer->validate($_REQUEST['sig'], $_REQUEST)) {
         $user = array('name' => 'error');
         echo json_encode($user);
         CRM_Utils_System::civiExit();
     }
     $config = CRM_Core_Config::singleton();
     $username = trim($_REQUEST['cms_name']);
     $params = array('name' => $username);
     $errors = array();
     $config->userSystem->checkUserNameEmailExists($params, $errors);
     if (isset($errors['cms_name']) || isset($errors['name'])) {
         //user name is not availble
         $user = array('name' => 'no');
         echo json_encode($user);
     } else {
         //user name is available
         $user = array('name' => 'yes');
         echo json_encode($user);
     }
     CRM_Utils_System::civiExit();
 }
예제 #20
0
 /**
  * Save a record about the delivery of a reminder email.
  *
  * WISHLIST: Instead of saving $actionSchedule->body_html, call this immediately after
  * sending the message and pass in the fully rendered text of the message.
  *
  * @param CRM_Core_DAO_ActionSchedule $actionSchedule
  * @param Civi\ActionSchedule\Mapping $mapping
  * @param int $contactID
  * @param int $entityID
  * @param int|NULL $caseID
  * @throws CRM_Core_Exception
  */
 protected static function createMailingActivity($actionSchedule, $mapping, $contactID, $entityID, $caseID)
 {
     $session = CRM_Core_Session::singleton();
     if ($mapping->getEntity() == 'civicrm_membership') {
         $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'Membership Renewal Reminder', 'name');
     } else {
         $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'Reminder Sent', 'name');
     }
     $activityParams = array('subject' => $actionSchedule->title, 'details' => $actionSchedule->body_html, 'source_contact_id' => $session->get('userID') ? $session->get('userID') : $contactID, 'target_contact_id' => $contactID, 'activity_date_time' => CRM_Utils_Time::getTime('YmdHis'), 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name'), 'activity_type_id' => $activityTypeID, 'source_record_id' => $entityID);
     $activity = CRM_Activity_BAO_Activity::create($activityParams);
     //file reminder on case if source activity is a case activity
     if (!empty($caseID)) {
         $caseActivityParams = array();
         $caseActivityParams['case_id'] = $caseID;
         $caseActivityParams['activity_id'] = $activity->id;
         CRM_Case_BAO_Case::processCaseActivity($caseActivityParams);
     }
 }
예제 #21
0
 /**
  * @param Analyzer $analyzer
  *   The case being analyzed -- to which we want to add an activity.
  * @param \SimpleXMLElement $actXML the <ActivityType> tag which describes the new activity
  */
 public function createActivity(Analyzer $analyzer, \SimpleXMLElement $actXML)
 {
     $params = array('activity_type_id' => (string) $actXML->name, 'status_id' => 'Scheduled', 'activity_date_time' => \CRM_Utils_Time::getTime('YmdHis'), 'case_id' => $analyzer->getCaseId());
     $r = civicrm_api3('Activity', 'create', $params);
     $analyzer->flush();
 }
예제 #22
0
 /**
  * Get the next item
  *
  * @param int|\seconds $leaseTime seconds
  *
  * @return object with key 'data' that matches the inputted data
  */
 function stealItem($leaseTime = 3600)
 {
     // foreach hits the items in order -- but we short-circuit after the first
     foreach ($this->items as $id => $data) {
         $nowEpoch = CRM_Utils_Time::getTimeRaw();
         $this->releaseTimes[$id] = $nowEpoch + $leaseTime;
         $item = new stdClass();
         $item->id = $id;
         $item->data = unserialize($data);
         return $item;
     }
     // nothing in queue
     return FALSE;
 }
예제 #23
0
 /**
  * First download of new doc is OK.
  * The update fails (due to some bad web response).
  * The old data is retained in the cache.
  * The failure eventually expires.
  * A new update succeeds.
  *
  * @dataProvider badWebResponses
  * @param array $badWebResponse
  *   Description of a web request that returns some kind of failure.
  */
 public function testGetDocument_NewOK_UpdateFailure_CacheOK_UpdateOK($badWebResponse)
 {
     $this->assertNotEmpty($badWebResponse);
     // first try, good response
     CRM_Utils_Time::setTime('2013-03-01 10:00:00');
     $communityMessages = new CRM_Core_CommunityMessages($this->cache, $this->expectOneHttpRequest(self::$webResponses['first-valid-response']));
     $doc1 = $communityMessages->getDocument();
     $this->assertEquals('<h1>First valid response</h1>', $doc1['messages'][0]['markup']);
     $this->assertApproxEquals(strtotime('2013-03-01 10:10:00'), $doc1['expires'], self::APPROX_TIME_EQUALITY);
     // second try, $doc1 has expired; bad response; keep old data
     CRM_Utils_Time::setTime('2013-03-01 12:00:02');
     // more than 2 hours later (DEFAULT_RETRY)
     $communityMessages = new CRM_Core_CommunityMessages($this->cache, $this->expectOneHttpRequest($badWebResponse));
     $doc2 = $communityMessages->getDocument();
     $this->assertEquals('<h1>First valid response</h1>', $doc2['messages'][0]['markup']);
     $this->assertTrue($doc2['expires'] > CRM_Utils_Time::getTimeRaw());
     // third try, $doc2 hasn't expired yet; no request; keep old data
     CRM_Utils_Time::setTime('2013-03-01 12:09:00');
     $communityMessages = new CRM_Core_CommunityMessages($this->cache, $this->expectNoHttpRequest());
     $doc3 = $communityMessages->getDocument();
     $this->assertEquals('<h1>First valid response</h1>', $doc3['messages'][0]['markup']);
     $this->assertEquals($doc2['expires'], $doc3['expires']);
     // fourth try, $doc2 has expired yet; new request; replace data
     CRM_Utils_Time::setTime('2013-03-01 12:10:02');
     $communityMessages = new CRM_Core_CommunityMessages($this->cache, $this->expectOneHttpRequest(self::$webResponses['second-valid-response']));
     $doc4 = $communityMessages->getDocument();
     $this->assertEquals('<h1>Second valid response</h1>', $doc4['messages'][0]['markup']);
     $this->assertApproxEquals(strtotime('2013-03-01 12:20:02'), $doc4['expires'], self::APPROX_TIME_EQUALITY);
 }
예제 #24
0
 /**
  * Test that item leases can be ignored.
  *
  * @dataProvider getQueueSpecs
  * @param $queueSpec
  */
 public function testStealItem($queueSpec)
 {
     $this->queue = $this->queueService->create($queueSpec);
     $this->assertTrue($this->queue instanceof CRM_Queue_Queue);
     require_once 'CRM/Utils/Time.php';
     CRM_Utils_Time::setTime('2012-04-01 1:00:00');
     $this->queue->createItem(array('test-key' => 'a'));
     $item = $this->queue->claimItem();
     $this->assertEquals('a', $item->data['test-key']);
     $this->assertEquals(1, $this->queue->numberOfItems());
     // forget to release
     // haven't reached expiration yet, so claimItem fails
     CRM_Utils_Time::setTime('2012-04-01 1:59:00');
     $item2 = $this->queue->claimItem();
     $this->assertEquals(FALSE, $item2);
     // but stealItem works
     $item3 = $this->queue->stealItem();
     $this->assertEquals('a', $item3->data['test-key']);
     $this->assertEquals(1, $this->queue->numberOfItems());
     $this->queue->deleteItem($item3);
     $this->assertEquals(0, $this->queue->numberOfItems());
 }
예제 #25
0
/**
 * Send graph detail for A/B tests mail.
 *
 * @param array $params
 *
 * @return array
 * @throws API_Exception
 */
function civicrm_api3_mailing_a_b_graph_stats($params)
{
    civicrm_api3_verify_mandatory($params, 'CRM_Mailing_DAO_MailingAB', array('id'), FALSE);
    $defaults = array('criteria' => 'Open', 'target_date' => CRM_Utils_Time::getTime('YmdHis'), 'split_count' => 6, 'split_count_select' => 1);
    $params = array_merge($defaults, $params);
    $mailingAB = civicrm_api3('MailingAB', 'getsingle', array('id' => $params['id']));
    $graphStats = array();
    $ABFormat = array('A' => 'mailing_id_a', 'B' => 'mailing_id_b');
    foreach ($ABFormat as $name => $column) {
        switch (strtolower($params['criteria'])) {
            case 'open':
                $result = CRM_Mailing_Event_BAO_Opened::getRows($mailingAB['mailing_id_a'], NULL, TRUE, 0, 1, "civicrm_mailing_event_opened.time_stamp ASC");
                $startDate = CRM_Utils_Date::processDate($result[0]['date']);
                $targetDate = CRM_Utils_Date::processDate($params['target_date']);
                $dateDuration = round(round(strtotime($targetDate) - strtotime($startDate)) / $params['split_count']);
                $toDate = strtotime($startDate) + $dateDuration * $params['split_count_select'];
                $toDate = date('YmdHis', $toDate);
                $graphStats[$name] = array($params['split_count_select'] => array('count' => CRM_Mailing_Event_BAO_Opened::getTotalCount($mailingAB[$column], NULL, TRUE, $toDate), 'time' => CRM_Utils_Date::customFormat($toDate)));
                break;
            case 'total unique clicks':
                $result = CRM_Mailing_Event_BAO_TrackableURLOpen::getRows($mailingAB['mailing_id_a'], NULL, TRUE, 0, 1, "civicrm_mailing_event_trackable_url_open.time_stamp ASC");
                $startDate = CRM_Utils_Date::processDate($result[0]['date']);
                $targetDate = CRM_Utils_Date::processDate($params['target_date']);
                $dateDuration = round(abs(strtotime($targetDate) - strtotime($startDate)) / $params['split_count']);
                $toDate = strtotime($startDate) + $dateDuration * $params['split_count_select'];
                $toDate = date('YmdHis', $toDate);
                $graphStats[$name] = array($params['split_count_select'] => array('count' => CRM_Mailing_Event_BAO_TrackableURLOpen::getTotalCount($params['mailing_id'], NULL, FALSE, NULL, $toDate), 'time' => CRM_Utils_Date::customFormat($toDate)));
                break;
            case 'total clicks on a particular link':
                if (empty($params['target_url'])) {
                    throw new API_Exception("Provide url to get stats result for total clicks on a particular link");
                }
                // FIXME: doesn't make sense to get url_id mailing_id_(a|b) while getting start date in mailing_id_a
                $url_id = CRM_Mailing_BAO_TrackableURL::getTrackerURLId($mailingAB[$column], $params['target_url']);
                $result = CRM_Mailing_Event_BAO_TrackableURLOpen::getRows($mailingAB['mailing_id_a'], NULL, FALSE, $url_id, 0, 1, "civicrm_mailing_event_trackable_url_open.time_stamp ASC");
                $startDate = CRM_Utils_Date::processDate($result[0]['date']);
                $targetDate = CRM_Utils_Date::processDate($params['target_date']);
                $dateDuration = round(abs(strtotime($targetDate) - strtotime($startDate)) / $params['split_count']);
                $toDate = strtotime($startDate) + $dateDuration * $params['split_count_select'];
                $toDate = CRM_Utils_Date::processDate($toDate);
                $graphStats[$name] = array($params['split_count_select'] => array('count' => CRM_Mailing_Event_BAO_TrackableURLOpen::getTotalCount($params['mailing_id'], NULL, FALSE, $url_id, $toDate), 'time' => CRM_Utils_Date::customFormat($toDate)));
                break;
        }
    }
    return civicrm_api3_create_success($graphStats);
}
예제 #26
0
 /**
  * Remove any time overrides.
  */
 public static function resetTime()
 {
     self::$_delta = 0;
 }
예제 #27
0
 /**
  *  check the CMS username.
  */
 public static function checkUserName()
 {
     $signer = new CRM_Utils_Signer(CRM_Core_Key::privateKey(), array('for', 'ts'));
     $sig = CRM_Utils_Request::retrieve('sig', 'String', CRM_Core_DAO::$_nullObject);
     $for = CRM_Utils_Request::retrieve('for', 'String', CRM_Core_DAO::$_nullObject);
     if (CRM_Utils_Time::getTimeRaw() > $_REQUEST['ts'] + self::CHECK_USERNAME_TTL || $for != 'civicrm/ajax/cmsuser' || !$signer->validate($sig, $_REQUEST)) {
         $user = array('name' => 'error');
         CRM_Utils_JSON::output($user);
     }
     $config = CRM_Core_Config::singleton();
     $username = trim(CRM_Utils_Array::value('cms_name', $_REQUEST));
     $params = array('name' => $username);
     $errors = array();
     $config->userSystem->checkUserNameEmailExists($params, $errors);
     if (isset($errors['cms_name']) || isset($errors['name'])) {
         //user name is not available
         $user = array('name' => 'no');
         CRM_Utils_JSON::output($user);
     } else {
         //user name is available
         $user = array('name' => 'yes');
         CRM_Utils_JSON::output($user);
     }
     // Not reachable: JSON::output() above exits.
     CRM_Utils_System::civiExit();
 }
/**
 * Implementation of hook_civicrm_postProcess()
 *
 * Record information about a discount use.
 */
function cividiscount_civicrm_postProcess($class, &$form)
{
    if (!in_array($class, array('CRM_Contribute_Form_Contribution_Confirm', 'CRM_Event_Form_Participant', 'CRM_Event_Form_Registration_Confirm', 'CRM_Member_Form_Membership', 'CRM_Member_Form_MembershipRenewal', 'CRM_Event_Form_ParticipantFeeSelection'))) {
        return;
    }
    $discountInfo = $form->get('_discountInfo');
    if (!$discountInfo) {
        return;
    }
    $ts = CRM_Utils_Time::getTime();
    $discount = $discountInfo['discount'];
    $params = $form->getVar('_params');
    $description = CRM_Utils_Array::value('amount_level', $params);
    // Online event registration.
    // Note that CRM_Event_Form_Registration_Register is an intermediate form.
    // CRM_Event_Form_Registration_Confirm completes the transaction.
    if ($class == 'CRM_Event_Form_Registration_Confirm') {
        $pids = $form->getVar('_participantIDS');
        // if multiple participant discount is not enabled then only use primary participant info for discount
        // and ignore additional participants
        if (!_cividiscount_allow_multiple()) {
            $pids = array($pids[0]);
        }
        foreach ($pids as $pid) {
            $participant = _cividiscount_get_participant($pid);
            $contact_id = $participant['contact_id'];
            $participant_payment = _cividiscount_get_participant_payment($pid);
            $contribution_id = $participant_payment['contribution_id'];
            CRM_CiviDiscount_BAO_Item::incrementUsage($discount['id']);
            $track = new CRM_CiviDiscount_DAO_Track();
            $track->item_id = $discount['id'];
            $track->contact_id = $contact_id;
            $track->contribution_id = $contribution_id;
            $track->entity_table = 'civicrm_participant';
            $track->entity_id = $pid;
            $track->used_date = $ts;
            $track->description = $description;
            $track->save();
        }
        // Online membership.
        // Note that CRM_Contribute_Form_Contribution_Main is an intermediate
        // form - CRM_Contribute_Form_Contribution_Confirm completes the
        // transaction.
    } else {
        if ($class == 'CRM_Contribute_Form_Contribution_Confirm') {
            $membership_type = $params['selectMembership'];
            $membershipId = $params['membershipID'];
            if (!is_array($membership_type)) {
                $membership_type = array($membership_type);
            }
            $discount_membership_matches = array_intersect($membership_type, $discount['memberships']);
            // check to make sure the discount actually applied to this membership.
            if (empty($discount_membership_matches) || !$membershipId) {
                return;
            }
            $description = CRM_Utils_Array::value('description', $params);
            $membership = _cividiscount_get_membership($membershipId);
            $contact_id = $membership['contact_id'];
            $membership_payment = _cividiscount_get_membership_payment($membershipId);
            $contribution_id = $membership_payment['contribution_id'];
            CRM_CiviDiscount_BAO_Item::incrementUsage($discount['id']);
            $track = new CRM_CiviDiscount_DAO_Track();
            $track->item_id = $discount['id'];
            $track->contact_id = $contact_id;
            $track->contribution_id = $contribution_id;
            $track->entity_table = 'civicrm_membership';
            $track->entity_id = $membershipId;
            $track->used_date = $ts;
            $track->description = $description;
            $track->save();
        } else {
            $contribution_id = NULL;
            // Offline event registration.
            if (in_array($class, array('CRM_Event_Form_Participant', 'CRM_Event_Form_ParticipantFeeSelection'))) {
                if ($class == 'CRM_Event_Form_ParticipantFeeSelection') {
                    $entity_id = $form->getVar('_participantId');
                } else {
                    $entity_id = $form->getVar('_id');
                }
                $participant_payment = _cividiscount_get_participant_payment($entity_id);
                $contribution_id = $participant_payment['contribution_id'];
                $entity_table = 'civicrm_participant';
                $participant = _cividiscount_get_participant($entity_id);
                $contact_id = $participant['contact_id'];
            } elseif (in_array($class, array('CRM_Member_Form_Membership', 'CRM_Member_Form_MembershipRenewal'))) {
                $membership_types = $form->getVar('_memTypeSelected');
                $membership_type = isset($membership_types[0]) ? $membership_types[0] : NULL;
                if (!$membership_type) {
                    $membership_type = $form->getVar('_memType');
                }
                // Check to make sure the discount actually applied to this membership.
                if (!CRM_Utils_Array::value($membership_type, $discount['memberships'])) {
                    return;
                }
                $entity_table = 'civicrm_membership';
                $entity_id = $form->getVar('_id');
                $membership_payment = _cividiscount_get_membership_payment($entity_id);
                $contribution_id = $membership_payment['contribution_id'];
                $description = CRM_Utils_Array::value('description', $params);
                $membership = _cividiscount_get_membership($entity_id);
                $contact_id = $membership['contact_id'];
            } else {
                $entity_table = 'civicrm_contribution';
                $entity_id = $contribution_id;
            }
            CRM_CiviDiscount_BAO_Item::incrementUsage($discount['id']);
            $track = new CRM_CiviDiscount_DAO_Track();
            $track->item_id = $discount['id'];
            $track->contact_id = $contact_id;
            $track->contribution_id = $contribution_id;
            $track->entity_table = $entity_table;
            $track->entity_id = $entity_id;
            $track->used_date = $ts;
            $track->description = $description;
            $track->save();
        }
    }
}
예제 #29
0
 /**
  * Migrate any last remaining options from `civicrm_domain.config_backend` to `civicrm_setting`.
  * Cleanup setting schema.
  *
  * @param CRM_Queue_TaskContext $ctx
  * @return bool
  */
 public static function migrateSettings(CRM_Queue_TaskContext $ctx)
 {
     // Tip: If there are problems with adding the new uniqueness index, try inspecting:
     // SELECT name, domain_id, contact_id, count(*) AS dupes FROM civicrm_setting cs GROUP BY name, domain_id, contact_id HAVING dupes > 1;
     // Nav records are expendable. https://forum.civicrm.org/index.php?topic=36933.0
     CRM_Core_DAO::executeQuery('DELETE FROM civicrm_setting WHERE contact_id IS NOT NULL AND name = "navigation"');
     CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_setting DROP INDEX index_group_name');
     CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_setting DROP COLUMN group_name');
     // Handle Strange activity_tab_filter settings.
     CRM_Core_DAO::executeQuery('CREATE TABLE civicrm_activity_setting LIKE civicrm_setting');
     CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_activity_setting ADD UNIQUE INDEX index_domain_contact_name (domain_id, contact_id, name)');
     CRM_Core_DAO::executeQuery('INSERT INTO civicrm_activity_setting (name, contact_id, domain_id, value)
  SELECT DISTINCT name, contact_id, domain_id, value
  FROM civicrm_setting
  WHERE name = "activity_tab_filter"
  AND value is not NULL');
     CRM_Core_DAO::executeQuery('DELETE FROM civicrm_setting WHERE name = "activity_tab_filter"');
     $date = CRM_Utils_Time::getTime('Y-m-d H:i:s');
     CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_setting ADD UNIQUE INDEX index_domain_contact_name (domain_id, contact_id, name)');
     CRM_Core_DAO::executeQuery("INSERT INTO civicrm_setting (name, contact_id, domain_id, value, is_domain, created_id, created_date)\n     SELECT name, contact_id, domain_id, value, 0, contact_id,'{$date}'\n     FROM civicrm_activity_setting\n     WHERE name = 'activity_tab_filter'\n     AND value is not NULL");
     CRM_Core_DAO::executeQuery('DROP TABLE civicrm_activity_setting');
     $domainDao = CRM_Core_DAO::executeQuery('SELECT id, config_backend FROM civicrm_domain');
     while ($domainDao->fetch()) {
         $settings = CRM_Upgrade_Incremental_php_FourSeven::convertBackendToSettings($domainDao->id, $domainDao->config_backend);
         CRM_Core_Error::debug_var('convertBackendToSettings', array('domainId' => $domainDao->id, 'backend' => $domainDao->config_backend, 'settings' => $settings));
         foreach ($settings as $name => $value) {
             $rowParams = array(1 => array($domainDao->id, 'Positive'), 2 => array($name, 'String'), 3 => array(serialize($value), 'String'));
             $settingId = CRM_Core_DAO::singleValueQuery('SELECT id FROM civicrm_setting WHERE domain_id = %1 AND name = %2', $rowParams);
             if (!$settingId) {
                 CRM_Core_DAO::executeQuery('INSERT INTO civicrm_setting (domain_id, name, value, is_domain) VALUES (%1,%2,%3,1)', $rowParams);
             }
         }
     }
     CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_domain DROP COLUMN config_backend');
     return TRUE;
 }
 /**
  * This function for building custom fields
  *
  * @param object  $qf             form object (reference)
  * @param string  $elementName    name of the custom field
  * @param boolean $inactiveNeeded
  * @param boolean $userRequired   true if required else false
  * @param boolean $search         true if used for search else false
  * @param string  $label          label for custom field
  *
  * @access public
  * @static
  */
 public static function addQuickFormElement(&$qf, $elementName, $fieldId, $inactiveNeeded = FALSE, $useRequired = TRUE, $search = FALSE, $label = NULL)
 {
     // we use $_POST directly, since we dont want to use session memory, CRM-4677
     if (isset($_POST['_qf_Relationship_refresh']) && ($_POST['_qf_Relationship_refresh'] == 'Search' || $_POST['_qf_Relationship_refresh'] == 'Search Again')) {
         $useRequired = FALSE;
     }
     $field = self::getFieldObject($fieldId);
     // Custom field HTML should indicate group+field name
     $groupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id);
     $dataCrmCustomVal = $groupName . ':' . $field->name;
     $dataCrmCustomAttr = 'data-crm-custom="' . $dataCrmCustomVal . '"';
     $field->attributes .= $dataCrmCustomAttr;
     // Fixed for Issue CRM-2183
     if ($field->html_type == 'TextArea' && $search) {
         $field->html_type = 'Text';
     }
     if (!isset($label)) {
         $label = $field->label;
     }
     /**
      * at some point in time we might want to split the below into small functions
      **/
     switch ($field->html_type) {
         case 'Text':
             if ($field->is_search_range && $search) {
                 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes);
                 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes);
             } else {
                 $element =& $qf->add(strtolower($field->html_type), $elementName, $label, $field->attributes, $useRequired && !$search);
             }
             break;
         case 'TextArea':
             $attributes = $dataCrmCustomAttr;
             if ($field->note_rows) {
                 $attributes .= 'rows=' . $field->note_rows;
             } else {
                 $attributes .= 'rows=4';
             }
             if ($field->note_columns) {
                 $attributes .= ' cols=' . $field->note_columns;
             } else {
                 $attributes .= ' cols=60';
             }
             if ($field->text_length) {
                 $attributes .= ' maxlength=' . $field->text_length;
             }
             $element =& $qf->add(strtolower($field->html_type), $elementName, $label, $attributes, $useRequired && !$search);
             break;
         case 'Select Date':
             if ($field->is_search_range && $search) {
                 $qf->addDate($elementName . '_from', $label . ' - ' . ts('From'), FALSE, array('format' => $field->date_format, 'timeFormat' => $field->time_format, 'startOffset' => $field->start_date_years, 'endOffset' => $field->end_date_years, 'data-crm-custom' => $dataCrmCustomVal));
                 $qf->addDate($elementName . '_to', ts('To'), FALSE, array('format' => $field->date_format, 'timeFormat' => $field->time_format, 'startOffset' => $field->start_date_years, 'endOffset' => $field->end_date_years, 'data-crm-custom' => $dataCrmCustomVal));
             } else {
                 $required = $useRequired && !$search;
                 $qf->addDate($elementName, $label, $required, array('format' => $field->date_format, 'timeFormat' => $field->time_format, 'startOffset' => $field->start_date_years, 'endOffset' => $field->end_date_years, 'data-crm-custom' => $dataCrmCustomVal));
             }
             break;
         case 'Radio':
             $choice = array();
             if ($field->data_type != 'Boolean') {
                 $customOption =& CRM_Core_BAO_CustomOption::valuesByID($field->id, $field->option_group_id);
                 foreach ($customOption as $v => $l) {
                     $choice[] = $qf->createElement('radio', NULL, '', $l, (string) $v, $field->attributes);
                 }
                 $qf->addGroup($choice, $elementName, $label);
             } else {
                 $choice[] = $qf->createElement('radio', NULL, '', ts('Yes'), '1', $field->attributes);
                 $choice[] = $qf->createElement('radio', NULL, '', ts('No'), '0', $field->attributes);
                 $qf->addGroup($choice, $elementName, $label);
             }
             if ($useRequired && !$search) {
                 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
             }
             break;
         case 'Select':
             $selectOption =& CRM_Core_BAO_CustomOption::valuesByID($field->id, $field->option_group_id);
             $qf->add('select', $elementName, $label, array('' => ts('- select -')) + $selectOption, $useRequired && !$search, $dataCrmCustomAttr);
             break;
             //added for select multiple
         //added for select multiple
         case 'AdvMulti-Select':
             $selectOption =& CRM_Core_BAO_CustomOption::valuesByID($field->id, $field->option_group_id);
             if ($search && count($selectOption) > 1) {
                 $selectOption['CiviCRM_OP_OR'] = ts('Select to match ANY; unselect to match ALL');
             }
             $include =& $qf->addElement('advmultiselect', $elementName, $label, $selectOption, array('size' => 5, 'style' => '', 'class' => 'advmultiselect', 'data-crm-custom' => $dataCrmCustomVal));
             $include->setButtonAttributes('add', array('value' => ts('Add >>')));
             $include->setButtonAttributes('remove', array('value' => ts('<< Remove')));
             if ($useRequired && !$search) {
                 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
             }
             break;
         case 'Multi-Select':
             $selectOption =& CRM_Core_BAO_CustomOption::valuesByID($field->id, $field->option_group_id);
             if ($search && count($selectOption) > 1) {
                 $selectOption['CiviCRM_OP_OR'] = ts('Select to match ANY; unselect to match ALL');
             }
             $qf->addElement('select', $elementName, $label, $selectOption, array('size' => '5', 'multiple', 'data-crm-custom' => $dataCrmCustomVal));
             if ($useRequired && !$search) {
                 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
             }
             break;
         case 'CheckBox':
             $customOption = CRM_Core_BAO_CustomOption::valuesByID($field->id, $field->option_group_id);
             $check = array();
             foreach ($customOption as $v => $l) {
                 $check[] =& $qf->addElement('advcheckbox', $v, NULL, $l, array('data-crm-custom' => $dataCrmCustomVal));
             }
             if ($search && count($check) > 1) {
                 $check[] =& $qf->addElement('advcheckbox', 'CiviCRM_OP_OR', NULL, ts('Check to match ANY; uncheck to match ALL'), array('data-crm-custom' => $dataCrmCustomVal));
             }
             $qf->addGroup($check, $elementName, $label);
             if ($useRequired && !$search) {
                 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
             }
             break;
         case 'File':
             // we should not build upload file in search mode
             if ($search) {
                 return;
             }
             $qf->add(strtolower($field->html_type), $elementName, $label, $field->attributes, $useRequired && !$search);
             $qf->addUploadElement($elementName);
             break;
         case 'Select State/Province':
             //Add State
             $stateOption = array('' => ts('- select -')) + CRM_Core_PseudoConstant::stateProvince();
             $qf->add('select', $elementName, $label, $stateOption, $useRequired && !$search, $dataCrmCustomAttr);
             break;
         case 'Multi-Select State/Province':
             //Add Multi-select State/Province
             $stateOption = CRM_Core_PseudoConstant::stateProvince();
             $qf->addElement('select', $elementName, $label, $stateOption, array('size' => '5', 'multiple', 'data-crm-custom' => $dataCrmCustomVal));
             if ($useRequired && !$search) {
                 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
             }
             break;
         case 'Select Country':
             //Add Country
             $countryOption = array('' => ts('- select -')) + CRM_Core_PseudoConstant::country();
             $qf->add('select', $elementName, $label, $countryOption, $useRequired && !$search, $dataCrmCustomAttr);
             break;
         case 'Multi-Select Country':
             //Add Country
             $countryOption = CRM_Core_PseudoConstant::country();
             $qf->addElement('select', $elementName, $label, $countryOption, array('size' => '5', 'multiple', 'data-crm-custom' => $dataCrmCustomVal));
             if ($useRequired && !$search) {
                 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
             }
             break;
         case 'RichTextEditor':
             $attributes = array('rows' => $field->note_rows, 'cols' => $field->note_columns, 'data-crm-custom' => $dataCrmCustomVal);
             if ($field->text_length) {
                 $attributes['maxlength'] = $field->text_length;
             }
             $qf->addWysiwyg($elementName, $label, $attributes, $search);
             break;
         case 'Autocomplete-Select':
             $qf->add('text', $elementName, $label, $field->attributes, $useRequired && !$search);
             $hiddenEleName = $elementName . '_id';
             if (substr($elementName, -1) == ']') {
                 $hiddenEleName = substr($elementName, 0, -1) . '_id]';
             }
             $qf->addElement('hidden', $hiddenEleName, '', array('id' => str_replace(array(']', '['), array('', '_'), $hiddenEleName)));
             static $customUrls = array();
             if ($field->data_type == 'ContactReference') {
                 //$urlParams = "className=CRM_Contact_Page_AJAX&fnName=getContactList&json=1&reset=1&context=customfield&id={$field->id}";
                 $urlParams = "context=customfield&id={$field->id}";
                 $customUrls[$elementName] = CRM_Utils_System::url('civicrm/ajax/contactref', $urlParams, FALSE, NULL, FALSE);
                 $actualElementValue = $qf->getSubmitValue($hiddenEleName);
                 $qf->addRule($elementName, ts('Select a valid contact for %1.', array(1 => $label)), 'validContact', $actualElementValue);
             } else {
                 $signer = new CRM_Utils_Signer(CRM_Core_Key::privateKey(), array('cfid', 'ogid', 'sigts'));
                 $signParams = array('reset' => 1, 'sigts' => CRM_Utils_Time::getTimeRaw(), 'ogid' => $field->option_group_id, 'cfid' => $field->id);
                 $signParams['sig'] = $signer->sign($signParams);
                 $customUrls[$elementName] = CRM_Utils_System::url('civicrm/ajax/auto', $signParams, FALSE, NULL, FALSE);
                 $qf->addRule($elementName, ts('Select a valid value for %1.', array(1 => $label)), 'autocomplete', array('fieldID' => $field->id, 'optionGroupID' => $field->option_group_id));
             }
             $qf->assign('customUrls', $customUrls);
             break;
     }
     switch ($field->data_type) {
         case 'Int':
             // integers will have numeric rule applied to them.
             if ($field->is_search_range && $search) {
                 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', array(1 => $label)), 'integer');
                 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', array(1 => $label)), 'integer');
             } else {
                 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', array(1 => $label)), 'integer');
             }
             break;
         case 'Float':
             if ($field->is_search_range && $search) {
                 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
                 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
             } else {
                 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
             }
             break;
         case 'Money':
             if ($field->is_search_range && $search) {
                 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
                 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
             } else {
                 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
             }
             break;
         case 'Link':
             $qf->add('text', $elementName, $label, array('onfocus' => "if (!this.value) {  this.value='http://';} else return false", 'onblur' => "if ( this.value == 'http://') {  this.value='';} else return false", 'data-crm-custom' => $dataCrmCustomVal), $useRequired && !$search);
             $qf->addRule($elementName, ts('Enter a valid Website.'), 'wikiURL');
             break;
     }
     if ($field->is_view && !$search) {
         $qf->freeze($elementName);
     }
 }