Example #1
0
/**
 * Uuid.Create API.
 *
 * @param array $params
 *   API parameters.
 *
 * @return array
 *   API result descriptor
 *
 * @see civicrm_api3_create_success
 * @see civicrm_api3_create_error
 *
 * @throws API_Exception
 *   It's an API_Exception.
 */
function civicrm_api3_uuid_create(array $params)
{
    $entry = array('module' => 'civicrm_configexport', 'entity_type' => $params['entity_type'], 'entity_id' => $params['entity_id'], 'name' => 'ConfigExport::' . $params['entity_type'] . '::' . $params['entity_id'], 'uuid' => Uuid::uuid4()->toString());
    $insert = CRM_Utils_SQL_Insert::into('civicrm_managed')->row($entry)->toSQL();
    $dao = CRM_Core_DAO::executeQuery($insert);
    if (!($api = civicrm_api3('Uuid', 'get', $params))) {
        throw new API_Exception('Unable to obtain UUID', 2900);
    }
    $result = array_merge($params, array('uuid' => $entry['uuid']));
    return civicrm_api3_create_success($result, $params, 'Uuid', 'get', $dao);
}
Example #2
0
 public function testRows()
 {
     $insert = CRM_Utils_SQL_Insert::into('foo')->row(array('first' => '1', 'second' => '2'))->rows(array(array('second' => '2b', 'first' => '1b'), array('first' => '1c', 'second' => '2c')))->row(array('second' => '2d', 'first' => '1d'));
     $expected = '
   INSERT INTO foo (`first`,`second`) VALUES
   ("1","2"),
   ("1b","2b"),
   ("1c","2c"),
   ("1d","2d")
 ';
     $this->assertLike($expected, $insert->toSQL());
 }
 /**
  * @param string $queryText
  * @param array $tables a list of places to query. Keys may be:
  *   - sql: an array of SQL queries to execute
  *   - final: an array of SQL queries to execute at the end
  *   - *: All other keys are treated as table names
  * @return array keys: match-descriptor
  *   - count: int
  *   - files: NULL | array
  */
 function runQueries($queryText, &$tables, $entityIDTableName, $limit)
 {
     $sql = "TRUNCATE {$entityIDTableName}";
     CRM_Core_DAO::executeQuery($sql);
     $files = NULL;
     foreach ($tables as $tableName => $tableValues) {
         if ($tableName == 'final') {
             continue;
         } else {
             if ($tableName == 'sql') {
                 foreach ($tableValues as $sqlStatement) {
                     $sql = "\nREPLACE INTO {$entityIDTableName} ( entity_id )\n{$sqlStatement}\n{$this->toLimit($limit)}\n";
                     CRM_Core_DAO::executeQuery($sql);
                 }
             } else {
                 if ($tableName == 'file') {
                     $searcher = CRM_Core_BAO_File::getSearchService();
                     if (!($searcher && CRM_Core_Permission::check('access uploaded files'))) {
                         continue;
                     }
                     $query = $tableValues + array('text' => CRM_Utils_QueryFormatter::singleton()->format($queryText, CRM_Utils_QueryFormatter::LANG_SOLR));
                     list($intLimit, $intOffset) = $this->parseLimitOffset($limit);
                     $files = $searcher->search($query, $intLimit, $intOffset);
                     $matches = array();
                     foreach ($files as $file) {
                         $matches[] = array('entity_id' => $file['xparent_id']);
                     }
                     if ($matches) {
                         $insertSql = CRM_Utils_SQL_Insert::into($entityIDTableName)->usingReplace()->rows($matches)->toSQL();
                         CRM_Core_DAO::executeQuery($insertSql);
                     }
                 } else {
                     $fullTextFields = array();
                     // array (string $sqlColumnName)
                     $clauses = array();
                     // array (string $sqlExpression)
                     foreach ($tableValues['fields'] as $fieldName => $fieldType) {
                         if ($fieldType == 'Int') {
                             if (is_numeric($queryText)) {
                                 $clauses[] = "{$fieldName} = {$queryText}";
                             }
                         } else {
                             $fullTextFields[] = $fieldName;
                         }
                     }
                     if (!empty($fullTextFields)) {
                         $clauses[] = $this->matchText($tableName, $fullTextFields, $queryText);
                     }
                     if (empty($clauses)) {
                         continue;
                     }
                     $whereClause = implode(' OR ', $clauses);
                     //resolve conflict between entity tables.
                     if ($tableName == 'civicrm_note' && ($entityTable = CRM_Utils_Array::value('entity_table', $tableValues))) {
                         $whereClause .= " AND entity_table = '{$entityTable}'";
                     }
                     $sql = "\nREPLACE  INTO {$entityIDTableName} ( entity_id )\nSELECT   {$tableValues['id']}\nFROM     {$tableName}\nWHERE    ( {$whereClause} )\nAND      {$tableValues['id']} IS NOT NULL\nGROUP BY {$tableValues['id']}\n{$this->toLimit($limit)}\n";
                     CRM_Core_DAO::executeQuery($sql);
                 }
             }
         }
     }
     if (isset($tables['final'])) {
         foreach ($tables['final'] as $sqlStatement) {
             CRM_Core_DAO::executeQuery($sqlStatement);
         }
     }
     return array('count' => CRM_Core_DAO::singleValueQuery("SELECT count(*) FROM {$entityIDTableName}"), 'files' => $files);
 }
Example #4
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();
 }
 /**
  * Generate action_log's for repeated, follow-up alerts to additional contacts.
  *
  * @throws \CRM_Core_Exception
  * @throws \Exception
  */
 protected function buildAddlRepeatPass()
 {
     $query = $this->prepareQuery(self::PHASE_ADDITION_REPEAT);
     $addlCheck = \CRM_Utils_SQL_Select::from($query['casAddlCheckFrom'])->select('*')->merge($query, array('wheres'))->merge($this->prepareRepetitionEndFilter($query['casDateField']))->limit(1)->strict()->toSQL();
     $daoCheck = \CRM_Core_DAO::executeQuery($addlCheck);
     if ($daoCheck->fetch()) {
         $repeatInsertAddl = \CRM_Utils_SQL_Select::from('civicrm_contact c')->merge($this->selectActionLogFields(self::PHASE_ADDITION_REPEAT, $query))->merge($this->joinReminder('INNER JOIN', 'addl', $query))->select("MAX(reminder.action_date_time) as latest_log_time")->merge($this->prepareAddlFilter('c.id'))->where("c.is_deleted = 0 AND c.is_deceased = 0")->groupBy("reminder.contact_id")->having("TIMESTAMPDIFF(HOUR, latest_log_time, CAST(!casNow AS datetime)) >= TIMESTAMPDIFF(HOUR, latest_log_time, DATE_ADD(latest_log_time, INTERVAL !casRepetitionInterval)")->param(array('casRepetitionInterval' => $this->parseRepetitionInterval()))->strict()->toSQL();
         // For unknown reasons, we manually insert each row. Why not change
         // selectActionLogFields() to selectIntoActionLog() above?
         $addValues = \CRM_Core_DAO::executeQuery($repeatInsertAddl)->fetchAll();
         if ($addValues) {
             \CRM_Core_DAO::executeQuery(\CRM_Utils_SQL_Insert::into('civicrm_action_log')->columns(array('contact_id', 'entity_id', 'entity_table', 'action_schedule_id'))->rows($addValues)->toSQL());
         }
     }
 }
Example #6
0
 /**
  * Store an item in the DB cache.
  *
  * @param object $data
  *   (required) A reference to the data that will be serialized and stored.
  * @param string $group
  *   (required) The group name of the item.
  * @param string $path
  *   (required) The path under which this item is stored.
  * @param int $componentID
  *   The optional component ID (so componenets can share the same name space).
  */
 public static function setItem(&$data, $group, $path, $componentID = NULL)
 {
     if (self::$_cache === NULL) {
         self::$_cache = array();
     }
     // get a lock so that multiple ajax requests on the same page
     // dont trample on each other
     // CRM-11234
     $lock = Civi::lockManager()->acquire("cache.{$group}_{$path}._{$componentID}");
     if (!$lock->isAcquired()) {
         CRM_Core_Error::fatal();
     }
     $table = self::getTableName();
     $where = self::whereCache($group, $path, $componentID);
     $id = CRM_Core_DAO::singleValueQuery("SELECT id FROM {$table} WHERE {$where}");
     $now = date('Y-m-d H:i:s');
     // FIXME - Use SQL NOW() or CRM_Utils_Time?
     $dataSerialized = serialize($data);
     // This table has a wonky index, so we cannot use REPLACE or
     // "INSERT ... ON DUPE". Instead, use SELECT+(INSERT|UPDATE).
     if ($id) {
         $sql = "UPDATE {$table} SET data = %1, created_date = %2 WHERE id = %3";
         $dao = CRM_Core_DAO::executeQuery($sql, array(1 => array($dataSerialized, 'String'), 2 => array($now, 'String'), 3 => array($id, 'Int')));
     } else {
         $insert = CRM_Utils_SQL_Insert::into($table)->row(array('group_name' => $group, 'path' => $path, 'component_id' => $componentID, 'data' => $dataSerialized, 'created_date' => $now));
         $dao = CRM_Core_DAO::executeQuery($insert->toSQL());
     }
     $lock->release();
     $dao->free();
     // cache coherency - refresh or remove dependent caches
     $argString = "CRM_CT_{$group}_{$path}_{$componentID}";
     $cache = CRM_Utils_Cache::singleton();
     $data = unserialize($dataSerialized);
     self::$_cache[$argString] = $data;
     $cache->set($argString, $data);
     $argString = "CRM_CT_CI_{$group}_{$componentID}";
     unset(self::$_cache[$argString]);
     $cache->delete($argString);
 }