First commit

This commit is contained in:
Theodotos Andreou 2018-01-14 13:10:16 +00:00
commit c6e2478c40
13918 changed files with 2303184 additions and 0 deletions

View file

@ -0,0 +1,349 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* The core concept of the system is an action performed on an object. Typically this will be a "data model" object
* as specified in the API specs. We attempt to keep the number and type of actions consistent
* and similar across all objects (thus providing both reuse and standards)
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
class CRM_Core_Action {
/**
* Different possible actions are defined here. Keep in sync with the
* constant from CRM_Core_Form for various modes.
*
* @var integer const
*/
const
NONE = 0,
ADD = 1,
UPDATE = 2,
VIEW = 4,
DELETE = 8,
BROWSE = 16,
ENABLE = 32,
DISABLE = 64,
EXPORT = 128,
BASIC = 256,
ADVANCED = 512,
PREVIEW = 1024,
FOLLOWUP = 2048,
MAP = 4096,
PROFILE = 8192,
COPY = 16384,
RENEW = 32768,
DETACH = 65536,
REVERT = 131072,
CLOSE = 262144,
REOPEN = 524288,
MAX_ACTION = 1048575;
//make sure MAX_ACTION = 2^n - 1 ( n = total number of actions )
/**
* Map the action names to the relevant constant. We perform
* bit manipulation operations so we can perform multiple
* actions on the same object if needed
*
* @var array $_names type of variable name to action constant
*
*/
static $_names = array(
'add' => self::ADD,
'update' => self::UPDATE,
'view' => self::VIEW,
'delete' => self::DELETE,
'browse' => self::BROWSE,
'enable' => self::ENABLE,
'disable' => self::DISABLE,
'export' => self::EXPORT,
'preview' => self::PREVIEW,
'map' => self::MAP,
'copy' => self::COPY,
'profile' => self::PROFILE,
'renew' => self::RENEW,
'detach' => self::DETACH,
'revert' => self::REVERT,
'close' => self::CLOSE,
'reopen' => self::REOPEN,
);
/**
* The flipped version of the names array, initialized when used
*
* @var array
*/
static $_description;
/**
* Called by the request object to translate a string into a mask.
*
* @param string $str
* The action to be resolved.
*
* @return int
* the action mask corresponding to the input string
*/
public static function resolve($str) {
$action = 0;
if ($str) {
$items = explode('|', $str);
$action = self::map($items);
}
return $action;
}
/**
* Given a string or an array of strings, determine the bitmask
* for this set of actions
*
* @param mixed $item
* Either a single string or an array of strings.
*
* @return int
* the action mask corresponding to the input args
*/
public static function map($item) {
$mask = 0;
if (is_array($item)) {
foreach ($item as $it) {
$mask |= self::mapItem($it);
}
return $mask;
}
else {
return self::mapItem($item);
}
}
/**
* Given a string determine the bitmask for this specific string.
*
* @param string $item
* The input action to process.
*
* @return int
* the action mask corresponding to the input string
*/
public static function mapItem($item) {
$mask = CRM_Utils_Array::value(trim($item), self::$_names);
return $mask ? $mask : 0;
}
/**
*
* Given an action mask, find the corresponding description
*
* @param int $mask
* The action mask.
*
* @return string
* the corresponding action description
*/
public static function description($mask) {
if (!isset(self::$_description)) {
self::$_description = array_flip(self::$_names);
}
return CRM_Utils_Array::value($mask, self::$_description, 'NO DESCRIPTION SET');
}
/**
* Given a set of links and a mask, return the html action string for
* the links associated with the mask
*
* @param array $links
* The set of link items.
* @param int $mask
* The mask to be used. a null mask means all items.
* @param array $values
* The array of values for parameter substitution in the link items.
* @param string $extraULName
* Enclosed extra links in this UL.
* @param bool $enclosedAllInSingleUL
* Force to enclosed all links in single UL.
*
* @param null $op
* @param null $objectName
* @param int $objectId
*
* @return string
* the html string
*/
public static function formLink(
$links,
$mask,
$values,
$extraULName = 'more',
$enclosedAllInSingleUL = FALSE,
$op = NULL,
$objectName = NULL,
$objectId = NULL
) {
if (empty($links)) {
return NULL;
}
// make links indexed sequentially instead of by bitmask
// otherwise it's next to impossible to reliably add new ones
$seqLinks = array();
foreach ($links as $bit => $link) {
$link['bit'] = $bit;
$seqLinks[] = $link;
}
if ($op && $objectName && $objectId) {
CRM_Utils_Hook::links($op, $objectName, $objectId, $seqLinks, $mask, $values);
}
$url = array();
foreach ($seqLinks as $i => $link) {
if (!$mask || !array_key_exists('bit', $link) || ($mask & $link['bit'])) {
$extra = isset($link['extra']) ? self::replace($link['extra'], $values) : NULL;
$frontend = (isset($link['fe'])) ? TRUE : FALSE;
if (isset($link['qs']) && !CRM_Utils_System::isNull($link['qs'])) {
$urlPath = CRM_Utils_System::url(self::replace($link['url'], $values),
self::replace($link['qs'], $values), FALSE, NULL, TRUE, $frontend
);
}
else {
$urlPath = CRM_Utils_Array::value('url', $link, '#');
}
$classes = 'action-item crm-hover-button';
if (isset($link['ref'])) {
$classes .= ' ' . strtolower($link['ref']);
}
//get the user specified classes in.
if (isset($link['class'])) {
$className = is_array($link['class']) ? implode(' ', $link['class']) : $link['class'];
$classes .= ' ' . strtolower($className);
}
if ($urlPath !== '#' && $frontend) {
$extra .= ' target="_blank"';
}
// Hack to make delete dialogs smaller
if (strpos($urlPath, '/delete') || strpos($urlPath, 'action=delete')) {
$classes .= " small-popup";
}
$url[] = sprintf('<a href="%s" class="%s" %s' . $extra . '>%s</a>',
$urlPath,
$classes,
!empty($link['title']) ? "title='{$link['title']}' " : '',
$link['name']
);
}
}
$mainLinks = $url;
if ($enclosedAllInSingleUL) {
$allLinks = '';
CRM_Utils_String::append($allLinks, '</li><li>', $mainLinks);
$allLinks = "{$extraULName}<ul class='panel'><li>{$allLinks}</li></ul>";
$result = "<span class='btn-slide crm-hover-button'>{$allLinks}</span>";
}
else {
$extra = '';
$extraLinks = array_splice($url, 2);
if (count($extraLinks) > 1) {
$mainLinks = array_slice($url, 0, 2);
CRM_Utils_String::append($extra, '</li><li>', $extraLinks);
$extra = "{$extraULName}<ul class='panel'><li>{$extra}</li></ul>";
}
$resultLinks = '';
CRM_Utils_String::append($resultLinks, '', $mainLinks);
if ($extra) {
$result = "<span>{$resultLinks}</span><span class='btn-slide crm-hover-button'>{$extra}</span>";
}
else {
$result = "<span>{$resultLinks}</span>";
}
}
return $result;
}
/**
* Given a string and an array of values, substitute the real values
* in the placeholder in the str in the CiviCRM format
*
* @param string $str
* The string to be replaced.
* @param array $values
* The array of values for parameter substitution in the str.
*
* @return string
* the substituted string
*/
public static function &replace(&$str, &$values) {
foreach ($values as $n => $v) {
$str = str_replace("%%$n%%", $v, $str);
}
return $str;
}
/**
* Get the mask for a permission (view, edit or null)
*
* @param array $permissions
*
* @return int
* The mask for the above permission
*/
public static function mask($permissions) {
$mask = NULL;
if (!is_array($permissions) || CRM_Utils_System::isNull($permissions)) {
return $mask;
}
//changed structure since we are handling delete separately - CRM-4418
if (in_array(CRM_Core_Permission::VIEW, $permissions)) {
$mask |= self::VIEW | self::EXPORT | self::BASIC | self::ADVANCED | self::BROWSE | self::MAP | self::PROFILE;
}
if (in_array(CRM_Core_Permission::DELETE, $permissions)) {
$mask |= self::DELETE;
}
if (in_array(CRM_Core_Permission::EDIT, $permissions)) {
//make sure we make self::MAX_ACTION = 2^n - 1
//if we add more actions; ( n = total number of actions )
$mask |= (self::MAX_ACTION & ~self::DELETE);
}
return $mask;
}
}

View file

@ -0,0 +1,75 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class contains functions for managing Action Logs
*/
class CRM_Core_BAO_ActionLog extends CRM_Core_DAO_ActionLog {
/**
* Create or update an action log entry.
*
* @param array $params
*
* @return array
*/
public static function create($params) {
$actionLog = new CRM_Core_DAO_ActionLog();
$params['action_date_time'] = CRM_Utils_Array::value('action_date_time', $params, date('YmdHis'));
$actionLog->copyValues($params);
$edit = ($actionLog->id) ? TRUE : FALSE;
if ($edit) {
CRM_Utils_Hook::pre('edit', 'ActionLog', $actionLog->id, $actionLog);
}
else {
CRM_Utils_Hook::pre('create', 'ActionLog', NULL, $actionLog);
}
$actionLog->save();
if ($edit) {
CRM_Utils_Hook::post('edit', 'ActionLog', $actionLog->id, $actionLog);
}
else {
CRM_Utils_Hook::post('create', 'ActionLog', NULL, $actionLog);
}
return $actionLog;
}
}

View file

@ -0,0 +1,700 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class contains functions for managing Scheduled Reminders
*/
class CRM_Core_BAO_ActionSchedule extends CRM_Core_DAO_ActionSchedule {
/**
* @param array $filters
* Filter by property (e.g. 'id').
* @return array
* Array(scalar $id => Mapping $mapping).
*/
public static function getMappings($filters = NULL) {
static $_action_mapping;
if ($_action_mapping === NULL) {
$event = \Civi\Core\Container::singleton()->get('dispatcher')
->dispatch(\Civi\ActionSchedule\Events::MAPPINGS,
new \Civi\ActionSchedule\Event\MappingRegisterEvent());
$_action_mapping = $event->getMappings();
}
if (empty($filters)) {
return $_action_mapping;
}
elseif (isset($filters['id'])) {
return array(
$filters['id'] => $_action_mapping[$filters['id']],
);
}
else {
throw new CRM_Core_Exception("getMappings() called with unsupported filter: " . implode(', ', array_keys($filters)));
}
}
/**
* @param string|int $id
* @return \Civi\ActionSchedule\Mapping|NULL
*/
public static function getMapping($id) {
$mappings = self::getMappings();
return isset($mappings[$id]) ? $mappings[$id] : NULL;
}
/**
* For each entity, get a list of entity-value labels.
*
* @return array
* Ex: $entityValueLabels[$mappingId][$valueId] = $valueLabel.
* @throws CRM_Core_Exception
*/
public static function getAllEntityValueLabels() {
$entityValueLabels = array();
foreach (CRM_Core_BAO_ActionSchedule::getMappings() as $mapping) {
/** @var \Civi\ActionSchedule\Mapping $mapping */
$entityValueLabels[$mapping->getId()] = $mapping->getValueLabels();
$valueLabel = array('- ' . strtolower($mapping->getValueHeader()) . ' -');
$entityValueLabels[$mapping->getId()] = $valueLabel + $entityValueLabels[$mapping->getId()];
}
return $entityValueLabels;
}
/**
* For each entity, get a list of entity-status labels.
*
* @return array
* Ex: $entityValueLabels[$mappingId][$valueId][$statusId] = $statusLabel.
*/
public static function getAllEntityStatusLabels() {
$entityValueLabels = self::getAllEntityValueLabels();
$entityStatusLabels = array();
foreach (CRM_Core_BAO_ActionSchedule::getMappings() as $mapping) {
/** @var \Civi\ActionSchedule\Mapping $mapping */
$statusLabel = array('- ' . strtolower($mapping->getStatusHeader()) . ' -');
$entityStatusLabels[$mapping->getId()] = $entityValueLabels[$mapping->getId()];
foreach ($entityStatusLabels[$mapping->getId()] as $kkey => & $vval) {
$vval = $statusLabel + $mapping->getStatusLabels($kkey);
}
}
return $entityStatusLabels;
}
/**
* Retrieve list of Scheduled Reminders.
*
* @param bool $namesOnly
* Return simple list of names.
*
* @param \Civi\ActionSchedule\Mapping|NULL $filterMapping
* Filter by the schedule's mapping type.
* @param int $filterValue
* Filter by the schedule's entity_value.
*
* @return array
* (reference) reminder list
*/
public static function &getList($namesOnly = FALSE, $filterMapping = NULL, $filterValue = NULL) {
$query = "
SELECT
title,
cas.id as id,
cas.mapping_id,
cas.entity_value as entityValueIds,
cas.entity_status as entityStatusIds,
cas.start_action_date as entityDate,
cas.start_action_offset,
cas.start_action_unit,
cas.start_action_condition,
cas.absolute_date,
is_repeat,
is_active
FROM civicrm_action_schedule cas
";
$queryParams = array();
$where = " WHERE 1 ";
if ($filterMapping and $filterValue) {
$where .= " AND cas.entity_value = %1 AND cas.mapping_id = %2";
$queryParams[1] = array($filterValue, 'Integer');
$queryParams[2] = array($filterMapping->getId(), 'String');
}
$where .= " AND cas.used_for IS NULL";
$query .= $where;
$dao = CRM_Core_DAO::executeQuery($query, $queryParams);
while ($dao->fetch()) {
/** @var Civi\ActionSchedule\Mapping $filterMapping */
$filterMapping = CRM_Utils_Array::first(self::getMappings(array(
'id' => $dao->mapping_id,
)));
$list[$dao->id]['id'] = $dao->id;
$list[$dao->id]['title'] = $dao->title;
$list[$dao->id]['start_action_offset'] = $dao->start_action_offset;
$list[$dao->id]['start_action_unit'] = $dao->start_action_unit;
$list[$dao->id]['start_action_condition'] = $dao->start_action_condition;
$list[$dao->id]['entityDate'] = ucwords(str_replace('_', ' ', $dao->entityDate));
$list[$dao->id]['absolute_date'] = $dao->absolute_date;
$list[$dao->id]['entity'] = $filterMapping->getLabel();
$list[$dao->id]['value'] = implode(', ', CRM_Utils_Array::subset(
$filterMapping->getValueLabels(),
explode(CRM_Core_DAO::VALUE_SEPARATOR, $dao->entityValueIds)
));
$list[$dao->id]['status'] = implode(', ', CRM_Utils_Array::subset(
$filterMapping->getStatusLabels($dao->entityValueIds),
explode(CRM_Core_DAO::VALUE_SEPARATOR, $dao->entityStatusIds)
));
$list[$dao->id]['is_repeat'] = $dao->is_repeat;
$list[$dao->id]['is_active'] = $dao->is_active;
}
return $list;
}
/**
* Add the schedules reminders in the db.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $ids
* Unused variable.
*
* @return CRM_Core_DAO_ActionSchedule
*/
public static function add(&$params, $ids = array()) {
$actionSchedule = new CRM_Core_DAO_ActionSchedule();
$actionSchedule->copyValues($params);
return $actionSchedule->save();
}
/**
* Retrieve DB object based on input parameters.
*
* It also stores all the retrieved values in the default array.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $values
* (reference ) an assoc array to hold the flattened values.
*
* @return CRM_Core_DAO_ActionSchedule|null
* object on success, null otherwise
*/
public static function retrieve(&$params, &$values) {
if (empty($params)) {
return NULL;
}
$actionSchedule = new CRM_Core_DAO_ActionSchedule();
$actionSchedule->copyValues($params);
if ($actionSchedule->find(TRUE)) {
$ids['actionSchedule'] = $actionSchedule->id;
CRM_Core_DAO::storeValues($actionSchedule, $values);
return $actionSchedule;
}
return NULL;
}
/**
* Delete a Reminder.
*
* @param int $id
* ID of the Reminder to be deleted.
*
*/
public static function del($id) {
if ($id) {
$dao = new CRM_Core_DAO_ActionSchedule();
$dao->id = $id;
if ($dao->find(TRUE)) {
$dao->delete();
return;
}
}
CRM_Core_Error::fatal(ts('Invalid value passed to delete function.'));
}
/**
* Update the is_active flag in the db.
*
* @param int $id
* Id of the database record.
* @param bool $is_active
* Value we want to set the is_active field.
*
* @return Object
* DAO object on success, null otherwise
*/
public static function setIsActive($id, $is_active) {
return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_ActionSchedule', $id, 'is_active', $is_active);
}
/**
* @param int $mappingID
* @param $now
*
* @throws CRM_Core_Exception
*/
public static function sendMailings($mappingID, $now) {
$mapping = CRM_Utils_Array::first(self::getMappings(array(
'id' => $mappingID,
)));
$actionSchedule = new CRM_Core_DAO_ActionSchedule();
$actionSchedule->mapping_id = $mappingID;
$actionSchedule->is_active = 1;
$actionSchedule->find(FALSE);
while ($actionSchedule->fetch()) {
$query = CRM_Core_BAO_ActionSchedule::prepareMailingQuery($mapping, $actionSchedule);
$dao = CRM_Core_DAO::executeQuery($query,
array(1 => array($actionSchedule->id, 'Integer'))
);
$multilingual = CRM_Core_I18n::isMultilingual();
while ($dao->fetch()) {
// switch language if necessary
if ($multilingual) {
$preferred_language = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $dao->contactID, 'preferred_language');
CRM_Core_BAO_ActionSchedule::setCommunicationLanguage($actionSchedule->communication_language, $preferred_language);
}
$errors = array();
try {
$tokenProcessor = self::createTokenProcessor($actionSchedule, $mapping);
$tokenProcessor->addRow()
->context('contactId', $dao->contactID)
->context('actionSearchResult', (object) $dao->toArray());
foreach ($tokenProcessor->evaluate()->getRows() as $tokenRow) {
if ($actionSchedule->mode == 'SMS' or $actionSchedule->mode == 'User_Preference') {
CRM_Utils_Array::extend($errors, self::sendReminderSms($tokenRow, $actionSchedule, $dao->contactID));
}
if ($actionSchedule->mode == 'Email' or $actionSchedule->mode == 'User_Preference') {
CRM_Utils_Array::extend($errors, self::sendReminderEmail($tokenRow, $actionSchedule, $dao->contactID));
}
// insert activity log record if needed
if ($actionSchedule->record_activity && empty($errors)) {
$caseID = empty($dao->case_id) ? NULL : $dao->case_id;
CRM_Core_BAO_ActionSchedule::createMailingActivity($tokenRow, $mapping, $dao->contactID, $dao->entityID, $caseID);
}
}
}
catch (\Civi\Token\TokenException $e) {
$errors['token_exception'] = $e->getMessage();
}
// update action log record
$logParams = array(
'id' => $dao->reminderID,
'is_error' => !empty($errors),
'message' => empty($errors) ? "null" : implode(' ', $errors),
'action_date_time' => $now,
);
CRM_Core_BAO_ActionLog::create($logParams);
}
$dao->free();
}
}
/**
* @param int $mappingID
* @param $now
* @param array $params
*
* @throws API_Exception
*/
public static function buildRecipientContacts($mappingID, $now, $params = array()) {
$actionSchedule = new CRM_Core_DAO_ActionSchedule();
$actionSchedule->mapping_id = $mappingID;
$actionSchedule->is_active = 1;
if (!empty($params)) {
_civicrm_api3_dao_set_filter($actionSchedule, $params, FALSE);
}
$actionSchedule->find();
while ($actionSchedule->fetch()) {
/** @var \Civi\ActionSchedule\Mapping $mapping */
$mapping = CRM_Utils_Array::first(self::getMappings(array(
'id' => $mappingID,
)));
$builder = new \Civi\ActionSchedule\RecipientBuilder($now, $actionSchedule, $mapping);
$builder->build();
}
}
/**
* @param null $now
* @param array $params
*
* @return array
*/
public static function processQueue($now = NULL, $params = array()) {
$now = $now ? CRM_Utils_Time::setTime($now) : CRM_Utils_Time::getTime();
$mappings = CRM_Core_BAO_ActionSchedule::getMappings();
foreach ($mappings as $mappingID => $mapping) {
CRM_Core_BAO_ActionSchedule::buildRecipientContacts($mappingID, $now, $params);
CRM_Core_BAO_ActionSchedule::sendMailings($mappingID, $now);
}
$result = array(
'is_error' => 0,
'messages' => ts('Sent all scheduled reminders successfully'),
);
return $result;
}
/**
* @param int $id
* @param int $mappingID
*
* @return null|string
*/
public static function isConfigured($id, $mappingID) {
$queryString = "SELECT count(id) FROM civicrm_action_schedule
WHERE mapping_id = %1 AND
entity_value = %2";
$params = array(
1 => array($mappingID, 'String'),
2 => array($id, 'Integer'),
);
return CRM_Core_DAO::singleValueQuery($queryString, $params);
}
/**
* @param int $mappingID
* @param $recipientType
*
* @return array
*/
public static function getRecipientListing($mappingID, $recipientType) {
if (!$mappingID) {
return array();
}
/** @var \Civi\ActionSchedule\Mapping $mapping */
$mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array(
'id' => $mappingID,
)));
return $mapping->getRecipientListing($recipientType);
}
/**
* @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);
}
/**
* 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 object $tokenRow
* @param Civi\ActionSchedule\Mapping $mapping
* @param int $contactID
* @param int $entityID
* @param int|NULL $caseID
* @throws CRM_Core_Exception
*/
protected static function createMailingActivity($tokenRow, $mapping, $contactID, $entityID, $caseID) {
$session = CRM_Core_Session::singleton();
if ($mapping->getEntity() == 'civicrm_membership') {
// @todo - not required with api
$activityTypeID
= CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Membership Renewal Reminder');
}
else {
// @todo - not required with api
$activityTypeID
= CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Reminder Sent');
}
$activityParams = array(
'subject' => $tokenRow->render('subject'),
'details' => $tokenRow->render('body_html'),
'source_contact_id' => $session->get('userID') ? $session->get('userID') : $contactID,
'target_contact_id' => $contactID,
// @todo - not required with api
'activity_date_time' => CRM_Utils_Time::getTime('YmdHis'),
// @todo - not required with api
'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
'activity_type_id' => $activityTypeID,
'source_record_id' => $entityID,
);
// @todo use api, remove all the above wrangling
$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);
}
}
/**
* @param \Civi\ActionSchedule\MappingInterface $mapping
* @param \CRM_Core_DAO_ActionSchedule $actionSchedule
* @return string
*/
protected static function prepareMailingQuery($mapping, $actionSchedule) {
$select = CRM_Utils_SQL_Select::from('civicrm_action_log reminder')
->select("reminder.id as reminderID, reminder.contact_id as contactID, reminder.entity_table as entityTable, reminder.*, e.id AS entityID")
->join('e', "!casMailingJoinType !casMappingEntity e ON !casEntityJoinExpr")
->select("e.id as entityID, e.*")
->where("reminder.action_schedule_id = #casActionScheduleId")
->where("reminder.action_date_time IS NULL")
->param(array(
'casActionScheduleId' => $actionSchedule->id,
'casMailingJoinType' => ($actionSchedule->limit_to == 0) ? 'LEFT JOIN' : 'INNER JOIN',
'casMappingId' => $mapping->getId(),
'casMappingEntity' => $mapping->getEntity(),
'casEntityJoinExpr' => 'e.id = reminder.entity_id',
));
if ($actionSchedule->limit_to == 0) {
$select->where("e.id = reminder.entity_id OR reminder.entity_table = 'civicrm_contact'");
}
\Civi\Core\Container::singleton()->get('dispatcher')
->dispatch(
\Civi\ActionSchedule\Events::MAILING_QUERY,
new \Civi\ActionSchedule\Event\MailingQueryEvent($actionSchedule, $mapping, $select)
);
return $select->toSQL();
}
/**
* @param \Civi\Token\TokenRow $tokenRow
* @param CRM_Core_DAO_ActionSchedule $schedule
* @param int $toContactID
* @throws CRM_Core_Exception
* @return array
* List of error messages.
*/
protected static function sendReminderSms($tokenRow, $schedule, $toContactID) {
$toPhoneNumber = self::pickSmsPhoneNumber($toContactID);
if (!$toPhoneNumber) {
return array("sms_phone_missing" => "Couldn't find recipient's phone number.");
}
$messageSubject = $tokenRow->render('subject');
$sms_body_text = $tokenRow->render('sms_body_text');
$session = CRM_Core_Session::singleton();
$userID = $session->get('userID') ? $session->get('userID') : $tokenRow->context['contactId'];
$smsParams = array(
'To' => $toPhoneNumber,
'provider_id' => $schedule->sms_provider_id,
'activity_subject' => $messageSubject,
);
$activityTypeID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'SMS');
$activityParams = array(
'source_contact_id' => $userID,
'activity_type_id' => $activityTypeID,
'activity_date_time' => date('YmdHis'),
'subject' => $messageSubject,
'details' => $sms_body_text,
'status_id' => CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name'),
);
$activity = CRM_Activity_BAO_Activity::create($activityParams);
CRM_Activity_BAO_Activity::sendSMSMessage($tokenRow->context['contactId'],
$sms_body_text,
$smsParams,
$activity->id,
$userID
);
return array();
}
/**
* @param CRM_Core_DAO_ActionSchedule $actionSchedule
* @return string
* Ex: "Alice <alice@example.org>".
*/
protected static function pickFromEmail($actionSchedule) {
$domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
$fromEmailAddress = "$domainValues[0] <$domainValues[1]>";
if ($actionSchedule->from_email) {
$fromEmailAddress = "$actionSchedule->from_name <$actionSchedule->from_email>";
return $fromEmailAddress;
}
return $fromEmailAddress;
}
/**
* @param \Civi\Token\TokenRow $tokenRow
* @param CRM_Core_DAO_ActionSchedule $schedule
* @param int $toContactID
* @return array
* List of error messages.
*/
protected static function sendReminderEmail($tokenRow, $schedule, $toContactID) {
$toEmail = CRM_Contact_BAO_Contact::getPrimaryEmail($toContactID);
if (!$toEmail) {
return array("email_missing" => "Couldn't find recipient's email address.");
}
$body_text = $tokenRow->render('body_text');
$body_html = $tokenRow->render('body_html');
if (!$schedule->body_text) {
$body_text = CRM_Utils_String::htmlToText($body_html);
}
// set up the parameters for CRM_Utils_Mail::send
$mailParams = array(
'groupName' => 'Scheduled Reminder Sender',
'from' => self::pickFromEmail($schedule),
'toName' => $tokenRow->context['contact']['display_name'],
'toEmail' => $toEmail,
'subject' => $tokenRow->render('subject'),
'entity' => 'action_schedule',
'entity_id' => $schedule->id,
);
if (!$body_html || $tokenRow->context['contact']['preferred_mail_format'] == 'Text' ||
$tokenRow->context['contact']['preferred_mail_format'] == 'Both'
) {
// render the &amp; entities in text mode, so that the links work
$mailParams['text'] = str_replace('&amp;', '&', $body_text);
}
if ($body_html && ($tokenRow->context['contact']['preferred_mail_format'] == 'HTML' ||
$tokenRow->context['contact']['preferred_mail_format'] == 'Both'
)
) {
$mailParams['html'] = $body_html;
}
$result = CRM_Utils_Mail::send($mailParams);
if (!$result || is_a($result, 'PEAR_Error')) {
return array('email_fail' => 'Failed to send message');
}
return array();
}
/**
* @param CRM_Core_DAO_ActionSchedule $schedule
* @param \Civi\ActionSchedule\Mapping $mapping
* @return \Civi\Token\TokenProcessor
*/
protected static function createTokenProcessor($schedule, $mapping) {
$tp = new \Civi\Token\TokenProcessor(\Civi\Core\Container::singleton()->get('dispatcher'), array(
'controller' => __CLASS__,
'actionSchedule' => $schedule,
'actionMapping' => $mapping,
'smarty' => TRUE,
));
$tp->addMessage('body_text', $schedule->body_text, 'text/plain');
$tp->addMessage('body_html', $schedule->body_html, 'text/html');
$tp->addMessage('sms_body_text', $schedule->sms_body_text, 'text/plain');
$tp->addMessage('subject', $schedule->subject, 'text/plain');
return $tp;
}
/**
* Pick SMS phone number.
*
* @param int $smsToContactId
*
* @return NULL|string
*/
protected static function pickSmsPhoneNumber($smsToContactId) {
$toPhoneNumbers = CRM_Core_BAO_Phone::allPhones($smsToContactId, FALSE, 'Mobile', array(
'is_deceased' => 0,
'is_deleted' => 0,
'do_not_sms' => 0,
));
//to get primary mobile ph,if not get a first mobile phONE
if (!empty($toPhoneNumbers)) {
$toPhoneNumberDetails = reset($toPhoneNumbers);
$toPhoneNumber = CRM_Utils_Array::value('phone', $toPhoneNumberDetails);
return $toPhoneNumber;
}
return NULL;
}
/**
* Get the list of generic recipient types supported by all entities/mappings.
*
* @return array
* array(mixed $value => string $label).
*/
public static function getAdditionalRecipients() {
return array(
'manual' => ts('Choose Recipient(s)'),
'group' => ts('Select Group'),
);
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,491 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
* Add static functions to include some common functionality used across location sub object BAO classes.
*/
class CRM_Core_BAO_Block {
/**
* Fields that are required for a valid block.
*/
static $requiredBlockFields = array(
'email' => array('email'),
'phone' => array('phone'),
'im' => array('name'),
'openid' => array('openid'),
);
/**
* Given the list of params in the params array, fetch the object
* and store the values in the values array
*
* @param string $blockName
* Name of the above object.
* @param array $params
* Input parameters to find object.
*
* @return array
* Array of $block objects.
*/
public static function &getValues($blockName, $params) {
if (empty($params)) {
return NULL;
}
$BAOString = 'CRM_Core_BAO_' . $blockName;
$block = new $BAOString();
$blocks = array();
if (!isset($params['entity_table'])) {
$block->contact_id = $params['contact_id'];
if (!$block->contact_id) {
CRM_Core_Error::fatal();
}
$blocks = self::retrieveBlock($block, $blockName);
}
else {
$blockIds = self::getBlockIds($blockName, NULL, $params);
if (empty($blockIds)) {
return $blocks;
}
$count = 1;
foreach ($blockIds as $blockId) {
$block = new $BAOString();
$block->id = $blockId['id'];
$getBlocks = self::retrieveBlock($block, $blockName);
$blocks[$count++] = array_pop($getBlocks);
}
}
return $blocks;
}
/**
* Given the list of params in the params array, fetch the object
* and store the values in the values array
*
* @param Object $block
* Typically a Phone|Email|IM|OpenID object.
* @param string $blockName
* Name of the above object.
*
* @return array
* Array of $block objects.
*/
public static function retrieveBlock(&$block, $blockName) {
// we first get the primary location due to the order by clause
$block->orderBy('is_primary desc, id');
$block->find();
$count = 1;
$blocks = array();
while ($block->fetch()) {
CRM_Core_DAO::storeValues($block, $blocks[$count]);
//unset is_primary after first block. Due to some bug in earlier version
//there might be more than one primary blocks, hence unset is_primary other than first
if ($count > 1) {
unset($blocks[$count]['is_primary']);
}
$count++;
}
return $blocks;
}
/**
* Check if the current block object has any valid data.
*
* @param array $blockFields
* Array of fields that are of interest for this object.
* @param array $params
* Associated array of submitted fields.
*
* @return bool
* true if the block has data, otherwise false
*/
public static function dataExists($blockFields, &$params) {
foreach ($blockFields as $field) {
if (CRM_Utils_System::isNull(CRM_Utils_Array::value($field, $params))) {
return FALSE;
}
}
return TRUE;
}
/**
* Check if the current block exits.
*
* @param string $blockName
* Bloack name.
* @param array $params
* Associated array of submitted fields.
*
* @return bool
* true if the block exits, otherwise false
*/
public static function blockExists($blockName, &$params) {
// return if no data present
if (empty($params[$blockName]) || !is_array($params[$blockName])) {
return FALSE;
}
return TRUE;
}
/**
* Get all block ids for a contact.
*
* @param string $blockName
* Block name.
* @param int $contactId
* Contact id.
*
* @param null $entityElements
* @param bool $updateBlankLocInfo
*
* @return array
* formatted array of block ids
*
*/
public static function getBlockIds($blockName, $contactId = NULL, $entityElements = NULL, $updateBlankLocInfo = FALSE) {
$allBlocks = array();
$name = ucfirst($blockName);
if ($blockName == 'im') {
$name = 'IM';
}
elseif ($blockName == 'openid') {
$name = 'OpenID';
}
$baoString = 'CRM_Core_BAO_' . $name;
if ($contactId) {
//@todo a cleverer way to do this would be to use the same fn name on each
// BAO rather than constructing the fn
// it would also be easier to grep for
// e.g $bao = new $baoString;
// $bao->getAllBlocks()
$baoFunction = 'all' . $name . 's';
$allBlocks = $baoString::$baoFunction($contactId, $updateBlankLocInfo);
}
elseif (!empty($entityElements) && $blockName != 'openid') {
$baoFunction = 'allEntity' . $name . 's';
$allBlocks = $baoString::$baoFunction($entityElements);
}
return $allBlocks;
}
/**
* Takes an associative array and creates a block.
*
* @param string $blockName
* Block name.
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param null $entity
* @param int $contactId
*
* @return object
* CRM_Core_BAO_Block object on success, null otherwise
*/
public static function create($blockName, &$params, $entity = NULL, $contactId = NULL) {
if (!self::blockExists($blockName, $params)) {
return NULL;
}
$name = ucfirst($blockName);
$isPrimary = $isBilling = TRUE;
$entityElements = $blocks = array();
$resetPrimaryId = NULL;
$primaryId = FALSE;
if ($entity) {
$entityElements = array(
'entity_table' => $params['entity_table'],
'entity_id' => $params['entity_id'],
);
}
else {
$contactId = $params['contact_id'];
}
$updateBlankLocInfo = CRM_Utils_Array::value('updateBlankLocInfo', $params, FALSE);
$isIdSet = CRM_Utils_Array::value('isIdSet', $params[$blockName], FALSE);
//get existing block ids.
$blockIds = self::getBlockIds($blockName, $contactId, $entityElements);
foreach ($params[$blockName] as $count => $value) {
$blockId = CRM_Utils_Array::value('id', $value);
if ($blockId) {
if (is_array($blockIds) && array_key_exists($blockId, $blockIds)) {
unset($blockIds[$blockId]);
}
else {
unset($value['id']);
}
}
//lets allow to update primary w/ more cleanly.
if (!$resetPrimaryId && !empty($value['is_primary'])) {
$primaryId = TRUE;
if (is_array($blockIds)) {
foreach ($blockIds as $blockId => $blockValue) {
if (!empty($blockValue['is_primary'])) {
$resetPrimaryId = $blockId;
break;
}
}
}
if ($resetPrimaryId) {
$baoString = 'CRM_Core_BAO_' . $blockName;
$block = new $baoString();
$block->selectAdd();
$block->selectAdd("id, is_primary");
$block->id = $resetPrimaryId;
if ($block->find(TRUE)) {
$block->is_primary = FALSE;
$block->save();
}
$block->free();
}
}
}
foreach ($params[$blockName] as $count => $value) {
if (!is_array($value)) {
continue;
}
// if in some cases (eg. email used in Online Conribution Page, Profiles, etc.) id is not set
// lets try to add using the previous method to avoid any false creation of existing data.
foreach ($blockIds as $blockId => $blockValue) {
if (empty($value['id']) && $blockValue['locationTypeId'] == CRM_Utils_Array::value('location_type_id', $value) && !$isIdSet) {
$valueId = FALSE;
if ($blockName == 'phone') {
$phoneTypeBlockValue = CRM_Utils_Array::value('phoneTypeId', $blockValue);
if ($phoneTypeBlockValue == CRM_Utils_Array::value('phone_type_id', $value)) {
$valueId = TRUE;
}
}
elseif ($blockName == 'im') {
$providerBlockValue = CRM_Utils_Array::value('providerId', $blockValue);
if (!empty($value['provider_id']) && $providerBlockValue == $value['provider_id']) {
$valueId = TRUE;
}
}
else {
$valueId = TRUE;
}
if ($valueId) {
$value['id'] = $blockValue['id'];
if (!$primaryId && !empty($blockValue['is_primary'])) {
$value['is_primary'] = $blockValue['is_primary'];
}
break;
}
}
}
$dataExists = self::dataExists(self::$requiredBlockFields[$blockName], $value);
// Note there could be cases when block info already exist ($value[id] is set) for a contact/entity
// BUT info is not present at this time, and therefore we should be really careful when deleting the block.
// $updateBlankLocInfo will help take appropriate decision. CRM-5969
if (!empty($value['id']) && !$dataExists && $updateBlankLocInfo) {
//delete the existing record
self::blockDelete($blockName, array('id' => $value['id']));
continue;
}
elseif (!$dataExists) {
continue;
}
$contactFields = array(
'contact_id' => $contactId,
'location_type_id' => CRM_Utils_Array::value('location_type_id', $value),
);
$contactFields['is_primary'] = 0;
if ($isPrimary && !empty($value['is_primary'])) {
$contactFields['is_primary'] = $value['is_primary'];
$isPrimary = FALSE;
}
$contactFields['is_billing'] = 0;
if ($isBilling && !empty($value['is_billing'])) {
$contactFields['is_billing'] = $value['is_billing'];
$isBilling = FALSE;
}
$blockFields = array_merge($value, $contactFields);
$baoString = 'CRM_Core_BAO_' . $name;
$blocks[] = $baoString::add($blockFields);
}
return $blocks;
}
/**
* Delete block.
*
* @param string $blockName
* Block name.
* @param int $params
* Associates array.
*/
public static function blockDelete($blockName, $params) {
$name = ucfirst($blockName);
if ($blockName == 'im') {
$name = 'IM';
}
elseif ($blockName == 'openid') {
$name = 'OpenID';
}
$baoString = 'CRM_Core_DAO_' . $name;
$block = new $baoString();
$block->copyValues($params);
// CRM-11006 add call to pre and post hook for delete action
CRM_Utils_Hook::pre('delete', $name, $block->id, CRM_Core_DAO::$_nullArray);
$block->delete();
CRM_Utils_Hook::post('delete', $name, $block->id, $block);
}
/**
* Handling for is_primary.
* $params is_primary could be
* # 1 - find other entries with is_primary = 1 & reset them to 0
* # 0 - make sure at least one entry is set to 1
* - if no other entry is 1 change to 1
* - if one other entry exists change that to 1
* - if more than one other entry exists change first one to 1
* @fixme - perhaps should choose by location_type
* # empty - same as 0 as once we have checked first step
* we know if it should be 1 or 0
*
* if $params['id'] is set $params['contact_id'] may need to be retrieved
*
* @param array $params
* @param $class
*
* @throws API_Exception
*/
public static function handlePrimary(&$params, $class) {
$table = CRM_Core_DAO_AllCoreTables::getTableForClass($class);
if (!$table) {
throw new API_Exception("Failed to locate table for class [$class]");
}
// contact_id in params might be empty or the string 'null' so cast to integer
$contactId = (int) CRM_Utils_Array::value('contact_id', $params);
// If id is set & we haven't been passed a contact_id, retrieve it
if (!empty($params['id']) && !isset($params['contact_id'])) {
$entity = new $class();
$entity->id = $params['id'];
$entity->find(TRUE);
$contactId = $entity->contact_id;
}
// If entity is not associated with contact, concept of is_primary not relevant
if (!$contactId) {
return;
}
// if params is_primary then set all others to not be primary & exit out
// if is_primary = 1
if (!empty($params['is_primary'])) {
$sql = "UPDATE $table SET is_primary = 0 WHERE contact_id = %1";
$sqlParams = array(1 => array($contactId, 'Integer'));
// we don't want to create unnecessary entries in the log_ tables so exclude the one we are working on
if (!empty($params['id'])) {
$sql .= " AND id <> %2";
$sqlParams[2] = array($params['id'], 'Integer');
}
CRM_Core_DAO::executeQuery($sql, $sqlParams);
return;
}
//Check what other emails exist for the contact
$existingEntities = new $class();
$existingEntities->contact_id = $contactId;
$existingEntities->orderBy('is_primary DESC');
if (!$existingEntities->find(TRUE) || (!empty($params['id']) && $existingEntities->id == $params['id'])) {
// ie. if no others is set to be primary then this has to be primary set to 1 so change
$params['is_primary'] = 1;
return;
}
else {
/*
* If the only existing email is the one we are editing then we must set
* is_primary to 1
* CRM-10451
*/
if ($existingEntities->N == 1 && $existingEntities->id == CRM_Utils_Array::value('id', $params)) {
$params['is_primary'] = 1;
return;
}
if ($existingEntities->is_primary == 1) {
return;
}
// so at this point we are only dealing with ones explicity setting is_primary to 0
// since we have reverse sorted by email we can either set the first one to
// primary or return if is already is
$existingEntities->is_primary = 1;
$existingEntities->save();
}
}
/**
* Sort location array so primary element is first.
*
* @param array $locations
*/
public static function sortPrimaryFirst(&$locations) {
uasort($locations, 'self::primaryComparison');
}
/**
* compare 2 locations to see which should go first based on is_primary
* (sort function for sortPrimaryFirst)
* @param array $location1
* @param array $location2
* @return int
*/
public static function primaryComparison($location1, $location2) {
$l1 = CRM_Utils_Array::value('is_primary', $location1);
$l2 = CRM_Utils_Array::value('is_primary', $location2);
if ($l1 == $l2) {
return 0;
}
return ($l1 < $l2) ? -1 : 1;
}
}

View file

@ -0,0 +1,228 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This file contains functions for synchronizing cms users with CiviCRM contacts.
*/
/**
* Class CRM_Core_BAO_CMSUser
*/
class CRM_Core_BAO_CMSUser {
/**
* Create CMS user using Profile.
*
* @param array $params
* @param string $mail
* Email id for cms user.
*
* @return int
* contact id that has been created
*/
public static function create(&$params, $mail) {
$config = CRM_Core_Config::singleton();
$ufID = $config->userSystem->createUser($params, $mail);
//if contact doesn't already exist create UF Match
if ($ufID !== FALSE &&
isset($params['contactID'])
) {
// create the UF Match record
$ufmatch['uf_id'] = $ufID;
$ufmatch['contact_id'] = $params['contactID'];
$ufmatch['uf_name'] = $params[$mail];
CRM_Core_BAO_UFMatch::create($ufmatch);
}
return $ufID;
}
/**
* Create Form for CMS user using Profile.
*
* @param CRM_Core_Form $form
* @param int $gid
* Id of group of profile.
* @param bool $emailPresent
* True if the profile field has email(primary).
* @param \const|int $action
*
* @return FALSE|void
* WTF
*
*/
public static function buildForm(&$form, $gid, $emailPresent, $action = CRM_Core_Action::NONE) {
$config = CRM_Core_Config::singleton();
$showCMS = FALSE;
$isDrupal = $config->userSystem->is_drupal;
$isJoomla = ucfirst($config->userFramework) == 'Joomla' ? TRUE : FALSE;
$isWordPress = $config->userFramework == 'WordPress' ? TRUE : FALSE;
if (!$config->userSystem->isUserRegistrationPermitted()) {
// Do not build form if CMS is not configured to allow creating users.
return FALSE;
}
if ($gid) {
$isCMSUser = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $gid, 'is_cms_user');
}
// $cms is true when there is email(primary location) is set in the profile field.
$userID = CRM_Core_Session::singleton()->get('userID');
$showUserRegistration = FALSE;
if ($action) {
$showUserRegistration = TRUE;
}
elseif (!$action && !$userID) {
$showUserRegistration = TRUE;
}
if ($isCMSUser && $emailPresent) {
if ($showUserRegistration) {
if ($isCMSUser != 2) {
$extra = array(
'onclick' => "return showHideByValue('cms_create_account','','details','block','radio',false );",
);
$form->addElement('checkbox', 'cms_create_account', ts('Create an account?'), NULL, $extra);
$required = FALSE;
}
else {
$form->add('hidden', 'cms_create_account', 1);
$required = TRUE;
}
$form->assign('isCMS', $required);
if (!$userID || $action & CRM_Core_Action::PREVIEW || $action & CRM_Core_Action::PROFILE) {
$form->add('text', 'cms_name', ts('Username'), NULL, $required);
if ($config->userSystem->isPasswordUserGenerated()) {
$form->add('password', 'cms_pass', ts('Password'));
$form->add('password', 'cms_confirm_pass', ts('Confirm Password'));
}
$form->addFormRule(array('CRM_Core_BAO_CMSUser', 'formRule'), $form);
}
$showCMS = TRUE;
}
}
$destination = $config->userSystem->getLoginDestination($form);
$loginURL = $config->userSystem->getLoginURL($destination);
$form->assign('loginURL', $loginURL);
$form->assign('showCMS', $showCMS);
}
/**
* Checks that there is a valid username & email
* optionally checks password is present & matches DB & gets the CMS to validate
*
* @param array $fields
* Posted values of form.
* @param array $files
* Uploaded files if any.
* @param CRM_Core_Form $form
*
* @return array|bool
*/
public static function formRule($fields, $files, $form) {
if (empty($fields['cms_create_account'])) {
return TRUE;
}
$config = CRM_Core_Config::singleton();
$isDrupal = $config->userSystem->is_drupal;
$isJoomla = ucfirst($config->userFramework) == 'Joomla' ? TRUE : FALSE;
$isWordPress = $config->userFramework == 'WordPress' ? TRUE : FALSE;
$errors = array();
if ($isDrupal || $isJoomla || $isWordPress) {
$emailName = NULL;
if (!empty($form->_bltID) && array_key_exists("email-{$form->_bltID}", $fields)) {
// this is a transaction related page
$emailName = 'email-' . $form->_bltID;
}
else {
// find the email field in a profile page
foreach ($fields as $name => $dontCare) {
if (substr($name, 0, 5) == 'email') {
$emailName = $name;
break;
}
}
}
if ($emailName == NULL) {
$errors['_qf_default'] = ts('Could not find an email address.');
return $errors;
}
if (empty($fields['cms_name'])) {
$errors['cms_name'] = ts('Please specify a username.');
}
if (empty($fields[$emailName])) {
$errors[$emailName] = ts('Please specify a valid email address.');
}
if ($config->userSystem->isPasswordUserGenerated()) {
if (empty($fields['cms_pass']) ||
empty($fields['cms_confirm_pass'])
) {
$errors['cms_pass'] = ts('Please enter a password.');
}
if ($fields['cms_pass'] != $fields['cms_confirm_pass']) {
$errors['cms_pass'] = ts('Password and Confirm Password values are not the same.');
}
}
if (!empty($errors)) {
return $errors;
}
// now check that the cms db does not have the user name and/or email
if ($isDrupal OR $isJoomla OR $isWordPress) {
$params = array(
'name' => $fields['cms_name'],
'mail' => $fields[$emailName],
);
}
$config->userSystem->checkUserNameEmailExists($params, $errors, $emailName);
}
return (!empty($errors)) ? $errors : TRUE;
}
}

View file

@ -0,0 +1,393 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* BAO object for civicrm_cache table.
*
* This is a database cache and is persisted across sessions. Typically we use
* this to store meta data (like profile fields, custom fields etc).
*
* The group_name column is used for grouping together all cache elements that logically belong to the same set.
* Thus all session cache entries are grouped under 'CiviCRM Session'. This allows us to delete all entries of
* a specific group if needed.
*
* The path column allows us to differentiate between items in that group. Thus for the session cache, the path is
* the unique form name for each form (per user)
*/
class CRM_Core_BAO_Cache extends CRM_Core_DAO_Cache {
/**
* @var array ($cacheKey => $cacheValue)
*/
static $_cache = NULL;
/**
* Retrieve an item from the DB cache.
*
* @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).
*
* @return object
* The data if present in cache, else null
*/
public static function &getItem($group, $path, $componentID = NULL) {
if (self::$_cache === NULL) {
self::$_cache = array();
}
$argString = "CRM_CT_{$group}_{$path}_{$componentID}";
if (!array_key_exists($argString, self::$_cache)) {
$cache = CRM_Utils_Cache::singleton();
self::$_cache[$argString] = $cache->get($argString);
if (!self::$_cache[$argString]) {
$table = self::getTableName();
$where = self::whereCache($group, $path, $componentID);
$rawData = CRM_Core_DAO::singleValueQuery("SELECT data FROM $table WHERE $where");
$data = $rawData ? unserialize($rawData) : NULL;
self::$_cache[$argString] = $data;
$cache->set($argString, self::$_cache[$argString]);
}
}
return self::$_cache[$argString];
}
/**
* Retrieve all items in a group.
*
* @param string $group
* (required) The group name of the item.
* @param int $componentID
* The optional component ID (so componenets can share the same name space).
*
* @return object
* The data if present in cache, else null
*/
public static function &getItems($group, $componentID = NULL) {
if (self::$_cache === NULL) {
self::$_cache = array();
}
$argString = "CRM_CT_CI_{$group}_{$componentID}";
if (!array_key_exists($argString, self::$_cache)) {
$cache = CRM_Utils_Cache::singleton();
self::$_cache[$argString] = $cache->get($argString);
if (!self::$_cache[$argString]) {
$table = self::getTableName();
$where = self::whereCache($group, NULL, $componentID);
$dao = CRM_Core_DAO::executeQuery("SELECT path, data FROM $table WHERE $where");
$result = array();
while ($dao->fetch()) {
$result[$dao->path] = unserialize($dao->data);
}
$dao->free();
self::$_cache[$argString] = $result;
$cache->set($argString, self::$_cache[$argString]);
}
}
return self::$_cache[$argString];
}
/**
* 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);
$dataExists = CRM_Core_DAO::singleValueQuery("SELECT COUNT(*) 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 ($dataExists) {
$sql = "UPDATE $table SET data = %1, created_date = %2 WHERE {$where}";
$args = array(
1 => array($dataSerialized, 'String'),
2 => array($now, 'String'),
);
$dao = CRM_Core_DAO::executeQuery($sql, $args, TRUE, NULL, FALSE, FALSE);
}
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(), array(), TRUE, NULL, FALSE, FALSE);
}
$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);
}
/**
* Delete all the cache elements that belong to a group OR delete the entire cache if group is not specified.
*
* @param string $group
* The group name of the entries to be deleted.
* @param string $path
* Path of the item that needs to be deleted.
* @param bool $clearAll clear all caches
*/
public static function deleteGroup($group = NULL, $path = NULL, $clearAll = TRUE) {
$table = self::getTableName();
$where = self::whereCache($group, $path, NULL);
CRM_Core_DAO::executeQuery("DELETE FROM $table WHERE $where");
if ($clearAll) {
// also reset ACL Cache
CRM_ACL_BAO_Cache::resetCache();
// also reset memory cache if any
CRM_Utils_System::flushCache();
}
}
/**
* The next two functions are internal functions used to store and retrieve session from
* the database cache. This keeps the session to a limited size and allows us to
* create separate session scopes for each form in a tab
*/
/**
* This function takes entries from the session array and stores it in the cache.
*
* It also deletes the entries from the $_SESSION object (for a smaller session size)
*
* @param array $names
* Array of session values that should be persisted.
* This is either a form name + qfKey or just a form name
* (in the case of profile)
* @param bool $resetSession
* Should session state be reset on completion of DB store?.
*/
public static function storeSessionToCache($names, $resetSession = TRUE) {
foreach ($names as $key => $sessionName) {
if (is_array($sessionName)) {
$value = NULL;
if (!empty($_SESSION[$sessionName[0]][$sessionName[1]])) {
$value = $_SESSION[$sessionName[0]][$sessionName[1]];
}
self::setItem($value, 'CiviCRM Session', "{$sessionName[0]}_{$sessionName[1]}");
if ($resetSession) {
$_SESSION[$sessionName[0]][$sessionName[1]] = NULL;
unset($_SESSION[$sessionName[0]][$sessionName[1]]);
}
}
else {
$value = NULL;
if (!empty($_SESSION[$sessionName])) {
$value = $_SESSION[$sessionName];
}
self::setItem($value, 'CiviCRM Session', $sessionName);
if ($resetSession) {
$_SESSION[$sessionName] = NULL;
unset($_SESSION[$sessionName]);
}
}
}
self::cleanup();
}
/* Retrieve the session values from the cache and populate the $_SESSION array
*
* @param array $names
* Array of session values that should be persisted.
* This is either a form name + qfKey or just a form name
* (in the case of profile)
*/
/**
* Restore session from cache.
*
* @param string $names
*/
public static function restoreSessionFromCache($names) {
foreach ($names as $key => $sessionName) {
if (is_array($sessionName)) {
$value = self::getItem('CiviCRM Session',
"{$sessionName[0]}_{$sessionName[1]}"
);
if ($value) {
$_SESSION[$sessionName[0]][$sessionName[1]] = $value;
}
}
else {
$value = self::getItem('CiviCRM Session',
$sessionName
);
if ($value) {
$_SESSION[$sessionName] = $value;
}
}
}
}
/**
* Do periodic cleanup of the CiviCRM session table.
*
* Also delete all session cache entries which are a couple of days old.
* This keeps the session cache to a manageable size
* Delete Contribution page session caches more energetically.
*
* @param bool $session
* @param bool $table
* @param bool $prevNext
*/
public static function cleanup($session = FALSE, $table = FALSE, $prevNext = FALSE) {
// first delete all sessions more than 20 minutes old which are related to any potential transaction
$timeIntervalMins = (int) Civi::settings()->get('secure_cache_timeout_minutes');
if ($timeIntervalMins && $session) {
$transactionPages = array(
'CRM_Contribute_Controller_Contribution',
'CRM_Event_Controller_Registration',
);
$params = array(
1 => array(
date('Y-m-d H:i:s', time() - $timeIntervalMins * 60),
'String',
),
);
foreach ($transactionPages as $trPage) {
$params[] = array("%${trPage}%", 'String');
$where[] = 'path LIKE %' . count($params);
}
$sql = "
DELETE FROM civicrm_cache
WHERE group_name = 'CiviCRM Session'
AND created_date <= %1
AND (" . implode(' OR ', $where) . ")";
CRM_Core_DAO::executeQuery($sql, $params);
}
// clean up the session cache every $cacheCleanUpNumber probabilistically
$cleanUpNumber = 757;
// clean up all sessions older than $cacheTimeIntervalDays days
$timeIntervalDays = 2;
if (mt_rand(1, 100000) % $cleanUpNumber == 0) {
$session = $table = $prevNext = TRUE;
}
if (!$session && !$table && !$prevNext) {
return;
}
if ($prevNext) {
// delete all PrevNext caches
CRM_Core_BAO_PrevNextCache::cleanupCache();
}
if ($table) {
CRM_Core_Config::clearTempTables($timeIntervalDays . ' day');
}
if ($session) {
$sql = "
DELETE FROM civicrm_cache
WHERE group_name = 'CiviCRM Session'
AND created_date < date_sub( NOW( ), INTERVAL $timeIntervalDays DAY )
";
CRM_Core_DAO::executeQuery($sql);
}
}
/**
* Compose a SQL WHERE clause for the cache.
*
* Note: We need to use the cache during bootstrap, so we don't have
* full access to DAO services.
*
* @param string $group
* @param string|NULL $path
* Filter by path. If NULL, then return any paths.
* @param int|NULL $componentID
* Filter by component. If NULL, then look for explicitly NULL records.
* @return string
*/
protected static function whereCache($group, $path, $componentID) {
$clauses = array();
$clauses[] = ('group_name = "' . CRM_Core_DAO::escapeString($group) . '"');
if ($path) {
$clauses[] = ('path = "' . CRM_Core_DAO::escapeString($path) . '"');
}
if ($componentID && is_numeric($componentID)) {
$clauses[] = ('component_id = ' . (int) $componentID);
}
return $clauses ? implode(' AND ', $clauses) : '(1)';
}
}

View file

@ -0,0 +1,431 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* File contains functions used in civicrm configuration.
*/
class CRM_Core_BAO_ConfigSetting {
/**
* Create civicrm settings. This is the same as add but it clears the cache and
* reloads the config object
*
* @param array $params
* Associated array of civicrm variables.
*/
public static function create($params) {
self::add($params);
$cache = CRM_Utils_Cache::singleton();
$cache->delete('CRM_Core_Config');
$cache->delete('CRM_Core_Config' . CRM_Core_Config::domainID());
$config = CRM_Core_Config::singleton(TRUE, TRUE);
}
/**
* Add civicrm settings.
*
* @param array $params
* Associated array of civicrm variables.
*/
public static function add(&$params) {
$domain = new CRM_Core_DAO_Domain();
$domain->id = CRM_Core_Config::domainID();
$domain->find(TRUE);
if ($domain->config_backend) {
$params = array_merge(unserialize($domain->config_backend), $params);
}
$params = CRM_Core_BAO_ConfigSetting::filterSkipVars($params);
// also skip all Dir Params, we dont need to store those in the DB!
foreach ($params as $name => $val) {
if (substr($name, -3) == 'Dir') {
unset($params[$name]);
}
}
$domain->config_backend = serialize($params);
$domain->save();
}
/**
* Retrieve the settings values from db.
*
* @param $defaults
*
* @return array
*/
public static function retrieve(&$defaults) {
$domain = new CRM_Core_DAO_Domain();
$isUpgrade = CRM_Core_Config::isUpgradeMode();
//we are initializing config, really can't use, CRM-7863
$urlVar = 'q';
if (defined('CIVICRM_UF') && CIVICRM_UF == 'Joomla') {
$urlVar = 'task';
}
if ($isUpgrade && CRM_Core_DAO::checkFieldExists('civicrm_domain', 'config_backend')) {
$domain->selectAdd('config_backend');
}
else {
$domain->selectAdd('locales');
}
$domain->id = CRM_Core_Config::domainID();
$domain->find(TRUE);
if ($domain->config_backend) {
$defaults = unserialize($domain->config_backend);
if ($defaults === FALSE || !is_array($defaults)) {
$defaults = array();
return FALSE;
}
$skipVars = self::skipVars();
foreach ($skipVars as $skip) {
if (array_key_exists($skip, $defaults)) {
unset($defaults[$skip]);
}
}
}
if (!$isUpgrade) {
CRM_Core_BAO_ConfigSetting::applyLocale(Civi::settings($domain->id), $domain->locales);
}
}
/**
* Evaluate locale preferences and activate a chosen locale by
* updating session+global variables.
*
* @param \Civi\Core\SettingsBag $settings
* @param string $activatedLocales
* Imploded list of locales which are supported in the DB.
*/
public static function applyLocale($settings, $activatedLocales) {
// are we in a multi-language setup?
$multiLang = $activatedLocales ? TRUE : FALSE;
// set the current language
$chosenLocale = NULL;
$session = CRM_Core_Session::singleton();
// on multi-lang sites based on request and civicrm_uf_match
if ($multiLang) {
$languageLimit = array();
if (is_array($settings->get('languageLimit'))) {
$languageLimit = $settings->get('languageLimit');
}
$requestLocale = CRM_Utils_Request::retrieve('lcMessages', 'String');
if (in_array($requestLocale, array_keys($languageLimit))) {
$chosenLocale = $requestLocale;
//CRM-8559, cache navigation do not respect locale if it is changed, so reseting cache.
// Ed: This doesn't sound good.
CRM_Core_BAO_Cache::deleteGroup('navigation');
}
else {
$requestLocale = NULL;
}
if (!$requestLocale) {
$sessionLocale = $session->get('lcMessages');
if (in_array($sessionLocale, array_keys($languageLimit))) {
$chosenLocale = $sessionLocale;
}
else {
$sessionLocale = NULL;
}
}
if ($requestLocale) {
$ufm = new CRM_Core_DAO_UFMatch();
$ufm->contact_id = $session->get('userID');
if ($ufm->find(TRUE)) {
$ufm->language = $chosenLocale;
$ufm->save();
}
$session->set('lcMessages', $chosenLocale);
}
if (!$chosenLocale and $session->get('userID')) {
$ufm = new CRM_Core_DAO_UFMatch();
$ufm->contact_id = $session->get('userID');
if ($ufm->find(TRUE) &&
in_array($ufm->language, array_keys($languageLimit))
) {
$chosenLocale = $ufm->language;
}
$session->set('lcMessages', $chosenLocale);
}
}
global $dbLocale;
// try to inherit the language from the hosting CMS
if ($settings->get('inheritLocale')) {
// FIXME: On multilanguage installs, CRM_Utils_System::getUFLocale() in many cases returns nothing if $dbLocale is not set
$dbLocale = $multiLang ? ("_" . $settings->get('lcMessages')) : '';
$chosenLocale = CRM_Utils_System::getUFLocale();
if ($activatedLocales and !in_array($chosenLocale, explode(CRM_Core_DAO::VALUE_SEPARATOR, $activatedLocales))) {
$chosenLocale = NULL;
}
}
if (empty($chosenLocale)) {
//CRM-11993 - if a single-lang site, use default
$chosenLocale = $settings->get('lcMessages');
}
// set suffix for table names - use views if more than one language
$dbLocale = $multiLang ? "_{$chosenLocale}" : '';
// FIXME: an ugly hack to fix CRM-4041
global $tsLocale;
$tsLocale = $chosenLocale;
// FIXME: as bad aplace as any to fix CRM-5428
// (to be moved to a sane location along with the above)
if (function_exists('mb_internal_encoding')) {
mb_internal_encoding('UTF-8');
}
}
/**
* @param array $defaultValues
*
* @return string
* @throws Exception
*/
public static function doSiteMove($defaultValues = array()) {
$moveStatus = ts('Beginning site move process...') . '<br />';
$settings = Civi::settings();
foreach (array_merge(self::getPathSettings(), self::getUrlSettings()) as $key) {
$value = $settings->get($key);
if ($value && $value != $settings->getDefault($key)) {
if ($settings->getMandatory($key) === NULL) {
$settings->revert($key);
$moveStatus .= ts("WARNING: The setting (%1) has been reverted.", array(
1 => $key,
));
$moveStatus .= '<br />';
}
else {
$moveStatus .= ts("WARNING: The setting (%1) is overridden and could not be reverted.", array(
1 => $key,
));
$moveStatus .= '<br />';
}
}
}
$config = CRM_Core_Config::singleton();
// clear the template_c and upload directory also
$config->cleanup(3, TRUE);
$moveStatus .= ts('Template cache and upload directory have been cleared.') . '<br />';
// clear all caches
CRM_Core_Config::clearDBCache();
$moveStatus .= ts('Database cache tables cleared.') . '<br />';
$resetSessionTable = CRM_Utils_Request::retrieve('resetSessionTable',
'Boolean',
CRM_Core_DAO::$_nullArray,
FALSE,
FALSE,
'REQUEST'
);
if ($config->userSystem->is_drupal &&
$resetSessionTable
) {
db_query("DELETE FROM {sessions} WHERE 1");
$moveStatus .= ts('Drupal session table cleared.') . '<br />';
}
else {
$session = CRM_Core_Session::singleton();
$session->reset(2);
$moveStatus .= ts('Session has been reset.') . '<br />';
}
return $moveStatus;
}
/**
* Takes a componentName and enables it in the config.
* Primarily used during unit testing
*
* @param string $componentName
* Name of the component to be enabled, needs to be valid.
*
* @return bool
* true if valid component name and enabling succeeds, else false
*/
public static function enableComponent($componentName) {
$config = CRM_Core_Config::singleton();
if (in_array($componentName, $config->enableComponents)) {
// component is already enabled
return TRUE;
}
// return if component does not exist
if (!array_key_exists($componentName, CRM_Core_Component::getComponents())) {
return FALSE;
}
// get enabled-components from DB and add to the list
$enabledComponents = Civi::settings()->get('enable_components');
$enabledComponents[] = $componentName;
self::setEnabledComponents($enabledComponents);
return TRUE;
}
/**
* Disable specified component.
*
* @param string $componentName
*
* @return bool
*/
public static function disableComponent($componentName) {
$config = CRM_Core_Config::singleton();
if (!in_array($componentName, $config->enableComponents) ||
!array_key_exists($componentName, CRM_Core_Component::getComponents())
) {
// Post-condition is satisfied.
return TRUE;
}
// get enabled-components from DB and add to the list
$enabledComponents = Civi::settings()->get('enable_components');
$enabledComponents = array_diff($enabledComponents, array($componentName));
self::setEnabledComponents($enabledComponents);
return TRUE;
}
/**
* Set enabled components.
*
* @param array $enabledComponents
*/
public static function setEnabledComponents($enabledComponents) {
// fix the config object. update db.
Civi::settings()->set('enable_components', $enabledComponents);
// also force reset of component array
CRM_Core_Component::getEnabledComponents(TRUE);
}
/**
* @return array
*/
public static function skipVars() {
return array(
'dsn',
'templateCompileDir',
'userFrameworkDSN',
'userFramework',
'userFrameworkBaseURL',
'userFrameworkClass',
'userHookClass',
'userPermissionClass',
'userPermissionTemp',
'userFrameworkURLVar',
'userFrameworkVersion',
'newBaseURL',
'newBaseDir',
'newSiteName',
'configAndLogDir',
'qfKey',
'gettextResourceDir',
'cleanURL',
'entryURL',
'locale_custom_strings',
'localeCustomStrings',
'autocompleteContactSearch',
'autocompleteContactReference',
'checksumTimeout',
'checksum_timeout',
);
}
/**
* @param array $params
* @return array
*/
public static function filterSkipVars($params) {
$skipVars = self::skipVars();
foreach ($skipVars as $var) {
unset($params[$var]);
}
foreach (array_keys($params) as $key) {
if (preg_match('/^_qf_/', $key)) {
unset($params[$key]);
}
}
return $params;
}
/**
* @return array
*/
private static function getUrlSettings() {
return array(
'userFrameworkResourceURL',
'imageUploadURL',
'customCSSURL',
'extensionsURL',
);
}
/**
* @return array
*/
private static function getPathSettings() {
return array(
'uploadDir',
'imageUploadDir',
'customFileUploadDir',
'customTemplateDir',
'customPHPPathDir',
'extensionsDir',
);
}
}

View file

@ -0,0 +1,167 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class contains functions for managing Action Logs
*/
class CRM_Core_BAO_Country extends CRM_Core_DAO_Country {
/**
* Get the list of countries for which we offer provinces.
*
* @return mixed
*/
public static function provinceLimit() {
if (!isset(Civi::$statics[__CLASS__]['provinceLimit'])) {
$countryIsoCodes = CRM_Core_PseudoConstant::countryIsoCode();
$provinceLimit = Civi::settings()->get('provinceLimit');
$country = array();
if (is_array($provinceLimit)) {
foreach ($provinceLimit as $val) {
// CRM-12007
// some countries have disappeared and hence they might be in country limit
// but not in the country table
if (isset($countryIsoCodes[$val])) {
$country[] = $countryIsoCodes[$val];
}
}
}
else {
$country[] = $countryIsoCodes[$provinceLimit];
}
Civi::$statics[__CLASS__]['provinceLimit'] = $country;
}
return Civi::$statics[__CLASS__]['provinceLimit'];
}
/**
* Get the list of countries (with names) which are available to user.
*
* @return mixed
*/
public static function countryLimit() {
if (!isset(Civi::$statics[__CLASS__]['countryLimit'])) {
$countryIsoCodes = CRM_Core_PseudoConstant::countryIsoCode();
$country = array();
$countryLimit = Civi::settings()->get('countryLimit');
if (is_array($countryLimit)) {
foreach ($countryLimit as $val) {
// CRM-12007
// some countries have disappeared and hence they might be in country limit
// but not in the country table
if (isset($countryIsoCodes[$val])) {
$country[] = $countryIsoCodes[$val];
}
}
}
else {
$country[] = $countryIsoCodes[$countryLimit];
}
Civi::$statics[__CLASS__]['countryLimit'] = $country;
}
return Civi::$statics[__CLASS__]['countryLimit'];
}
/**
* Provide cached default contact country.
*
* @return string
*/
public static function defaultContactCountry() {
static $cachedContactCountry = NULL;
$defaultContactCountry = Civi::settings()->get('defaultContactCountry');
if (!empty($defaultContactCountry) && !$cachedContactCountry) {
$countryIsoCodes = CRM_Core_PseudoConstant::countryIsoCode();
$cachedContactCountry = CRM_Utils_Array::value($defaultContactCountry,
$countryIsoCodes
);
}
return $cachedContactCountry;
}
/**
* Provide cached default country name.
*
* @return string
*/
public static function defaultContactCountryName() {
static $cachedContactCountryName = NULL;
$defaultContactCountry = Civi::settings()->get('defaultContactCountry');
if (!$cachedContactCountryName && $defaultContactCountry) {
$countryCodes = CRM_Core_PseudoConstant::country();
$cachedContactCountryName = $countryCodes[$defaultContactCountry];
}
return $cachedContactCountryName;
}
/**
* Provide cached default currency symbol.
*
* @param string $defaultCurrency
*
* @return string
*/
public static function defaultCurrencySymbol($defaultCurrency = NULL) {
static $cachedSymbol = NULL;
if (!$cachedSymbol || $defaultCurrency) {
$currency = $defaultCurrency ? $defaultCurrency : Civi::settings()->get('defaultCurrency');
if ($currency) {
$currencySymbols = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'currency', array(
'labelColumn' => 'symbol',
'orderColumn' => TRUE,
));
$cachedSymbol = CRM_Utils_Array::value($currency, $currencySymbols, '');
}
else {
$cachedSymbol = '$';
}
}
return $cachedSymbol;
}
/**
* Get the default currency symbol.
*
* @param string $k Unused variable
*
* @return string
*/
public static function getDefaultCurrencySymbol($k = NULL) {
$config = CRM_Core_Config::singleton();
return $config->defaultCurrencySymbol(Civi::settings()->get('defaultCurrency'));
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,346 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* Business objects for managing custom data options.
*
*/
class CRM_Core_BAO_CustomOption {
/**
* Fetch object based on array of properties.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $defaults
* (reference ) an assoc array to hold the flattened values.
*
* @return CRM_Core_BAO_CustomOption
*/
public static function retrieve(&$params, &$defaults) {
$customOption = new CRM_Core_DAO_OptionValue();
$customOption->copyValues($params);
if ($customOption->find(TRUE)) {
CRM_Core_DAO::storeValues($customOption, $defaults);
return $customOption;
}
return NULL;
}
/**
* Returns all active options ordered by weight for a given field.
*
* @param int $fieldID
* Field whose options are needed.
* @param bool $inactiveNeeded Do we need inactive options ?.
* Do we need inactive options ?.
*
* @return array
* all active options for fieldId
*/
public static function getCustomOption(
$fieldID,
$inactiveNeeded = FALSE
) {
$options = array();
if (!$fieldID) {
return $options;
}
$optionValues = CRM_Core_PseudoConstant::get('CRM_Core_BAO_CustomField', 'custom_' . $fieldID, array(), $inactiveNeeded ? 'get' : 'create');
foreach ((array) $optionValues as $value => $label) {
$options[] = array(
'label' => $label,
'value' => $value,
);
}
return $options;
}
/**
* Wrapper for ajax option selector.
*
* @param array $params
* Associated array for params record id.
*
* @return array
* associated array of option list
* -rp = rowcount
* -page= offset
*/
static public function getOptionListSelector(&$params) {
$options = array();
$field = CRM_Core_BAO_CustomField::getFieldObject($params['fid']);
$defVal = CRM_Utils_Array::explodePadded($field->default_value);
// format the params
$params['offset'] = ($params['page'] - 1) * $params['rp'];
$params['rowCount'] = $params['rp'];
if (!$field->option_group_id) {
return $options;
}
$queryParams = array(1 => array($field->option_group_id, 'Integer'));
$total = "SELECT COUNT(*) FROM civicrm_option_value WHERE option_group_id = %1";
$params['total'] = CRM_Core_DAO::singleValueQuery($total, $queryParams);
$limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
$orderBy = ' ORDER BY options.weight asc';
$query = "SELECT * FROM civicrm_option_value as options WHERE option_group_id = %1 {$orderBy} {$limit}";
$dao = CRM_Core_DAO::executeQuery($query, $queryParams);
$links = CRM_Custom_Page_Option::actionLinks();
$fields = array('id', 'label', 'value');
$config = CRM_Core_Config::singleton();
while ($dao->fetch()) {
$options[$dao->id] = array();
foreach ($fields as $k) {
$options[$dao->id][$k] = $dao->$k;
}
$action = array_sum(array_keys($links));
$class = 'crm-entity';
// update enable/disable links depending on custom_field properties.
if ($dao->is_active) {
$action -= CRM_Core_Action::ENABLE;
}
else {
$class .= ' disabled';
$action -= CRM_Core_Action::DISABLE;
}
if (in_array($field->html_type, array('CheckBox', 'AdvMulti-Select', 'Multi-Select'))) {
if (isset($defVal) && in_array($dao->value, $defVal)) {
$options[$dao->id]['is_default'] = '<img src="' . $config->resourceBase . 'i/check.gif" />';
}
else {
$options[$dao->id]['is_default'] = '';
}
}
else {
if ($field->default_value == $dao->value) {
$options[$dao->id]['is_default'] = '<img src="' . $config->resourceBase . 'i/check.gif" />';
}
else {
$options[$dao->id]['is_default'] = '';
}
}
$options[$dao->id]['class'] = $dao->id . ',' . $class;
$options[$dao->id]['is_active'] = empty($dao->is_active) ? ts('No') : ts('Yes');
$options[$dao->id]['links'] = CRM_Core_Action::formLink($links,
$action,
array(
'id' => $dao->id,
'fid' => $params['fid'],
'gid' => $params['gid'],
),
ts('more'),
FALSE,
'customOption.row.actions',
'customOption',
$dao->id
);
}
return $options;
}
/**
* Delete Option.
*
* @param $optionId integer
* option id
*
*/
public static function del($optionId) {
// get the customFieldID
$query = "
SELECT f.id as id, f.data_type as dataType
FROM civicrm_option_value v,
civicrm_option_group g,
civicrm_custom_field f
WHERE v.id = %1
AND g.id = f.option_group_id
AND g.id = v.option_group_id";
$params = array(1 => array($optionId, 'Integer'));
$dao = CRM_Core_DAO::executeQuery($query, $params);
if ($dao->fetch()) {
if (in_array($dao->dataType,
array('Int', 'Float', 'Money', 'Boolean')
)) {
$value = 0;
}
else {
$value = '';
}
$params = array(
'optionId' => $optionId,
'fieldId' => $dao->id,
'value' => $value,
);
// delete this value from the tables
self::updateCustomValues($params);
// also delete this option value
$query = "
DELETE
FROM civicrm_option_value
WHERE id = %1";
$params = array(1 => array($optionId, 'Integer'));
CRM_Core_DAO::executeQuery($query, $params);
}
}
/**
* @param array $params
*
* @throws Exception
*/
public static function updateCustomValues($params) {
$optionDAO = new CRM_Core_DAO_OptionValue();
$optionDAO->id = $params['optionId'];
$optionDAO->find(TRUE);
$oldValue = $optionDAO->value;
// get the table, column, html_type and data type for this field
$query = "
SELECT g.table_name as tableName ,
f.column_name as columnName,
f.data_type as dataType,
f.html_type as htmlType
FROM civicrm_custom_group g,
civicrm_custom_field f
WHERE f.custom_group_id = g.id
AND f.id = %1";
$queryParams = array(1 => array($params['fieldId'], 'Integer'));
$dao = CRM_Core_DAO::executeQuery($query, $queryParams);
if ($dao->fetch()) {
if ($dao->dataType == 'Money') {
$params['value'] = CRM_Utils_Rule::cleanMoney($params['value']);
}
switch ($dao->htmlType) {
case 'Autocomplete-Select':
case 'Select':
case 'Radio':
$query = "
UPDATE {$dao->tableName}
SET {$dao->columnName} = %1
WHERE id = %2";
if ($dao->dataType == 'Auto-complete') {
$dataType = "String";
}
else {
$dataType = $dao->dataType;
}
$queryParams = array(
1 => array(
$params['value'],
$dataType,
),
2 => array(
$params['optionId'],
'Integer',
),
);
break;
case 'AdvMulti-Select':
case 'Multi-Select':
case 'CheckBox':
$oldString = CRM_Core_DAO::VALUE_SEPARATOR . $oldValue . CRM_Core_DAO::VALUE_SEPARATOR;
$newString = CRM_Core_DAO::VALUE_SEPARATOR . $params['value'] . CRM_Core_DAO::VALUE_SEPARATOR;
$query = "
UPDATE {$dao->tableName}
SET {$dao->columnName} = REPLACE( {$dao->columnName}, %1, %2 )";
$queryParams = array(
1 => array($oldString, 'String'),
2 => array($newString, 'String'),
);
break;
default:
CRM_Core_Error::fatal();
}
$dao = CRM_Core_DAO::executeQuery($query, $queryParams);
}
}
/**
* When changing the value of an option this is called to update all corresponding custom data
*
* @param int $optionId
* @param string $newValue
*/
public static function updateValue($optionId, $newValue) {
$optionValue = new CRM_Core_DAO_OptionValue();
$optionValue->id = $optionId;
$optionValue->find(TRUE);
$oldValue = $optionValue->value;
if ($oldValue == $newValue) {
return;
}
$customField = new CRM_Core_DAO_CustomField();
$customField->option_group_id = $optionValue->option_group_id;
$customField->find();
while ($customField->fetch()) {
$customGroup = new CRM_Core_DAO_CustomGroup();
$customGroup->id = $customField->custom_group_id;
$customGroup->find(TRUE);
if (CRM_Core_BAO_CustomField::isSerialized($customField)) {
$params = array(
1 => array(CRM_Utils_Array::implodePadded($oldValue), 'String'),
2 => array(CRM_Utils_Array::implodePadded($newValue), 'String'),
3 => array('%' . CRM_Utils_Array::implodePadded($oldValue) . '%', 'String'),
);
}
else {
$params = array(
1 => array($oldValue, 'String'),
2 => array($newValue, 'String'),
3 => array($oldValue, 'String'),
);
}
$sql = "UPDATE `{$customGroup->table_name}` SET `{$customField->column_name}` = REPLACE(`{$customField->column_name}`, %1, %2) WHERE `{$customField->column_name}` LIKE %3";
$customGroup->free();
CRM_Core_DAO::executeQuery($sql, $params);
}
$customField->free();
}
}

View file

@ -0,0 +1,492 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_Core_BAO_CustomQuery {
const PREFIX = 'custom_value_';
/**
* The set of custom field ids.
*
* @var array
*/
protected $_ids;
/**
* The select clause.
*
* @var array
*/
public $_select;
/**
* The name of the elements that are in the select clause.
* used to extract the values
*
* @var array
*/
public $_element;
/**
* The tables involved in the query.
*
* @var array
*/
public $_tables;
public $_whereTables;
/**
* The where clause.
*
* @var array
*/
public $_where;
/**
* The english language version of the query.
*
* @var array
*/
public $_qill;
/**
* @deprecated
* No longer needed due to CRM-17646 refactoring, but still used in some places
*
* @var array
*/
public $_options;
/**
* The custom fields information.
*
* @var array
*/
public $_fields;
/**
* Searching for contacts?
*
* @var boolean
*/
protected $_contactSearch;
protected $_locationSpecificCustomFields;
/**
* This stores custom data group types and tables that it extends.
*
* @var array
*/
static $extendsMap = array(
'Contact' => 'civicrm_contact',
'Individual' => 'civicrm_contact',
'Household' => 'civicrm_contact',
'Organization' => 'civicrm_contact',
'Contribution' => 'civicrm_contribution',
'ContributionRecur' => 'civicrm_contribution_recur',
'Membership' => 'civicrm_membership',
'Participant' => 'civicrm_participant',
'Group' => 'civicrm_group',
'Relationship' => 'civicrm_relationship',
'Event' => 'civicrm_event',
'Case' => 'civicrm_case',
'Activity' => 'civicrm_activity',
'Pledge' => 'civicrm_pledge',
'Grant' => 'civicrm_grant',
'Address' => 'civicrm_address',
'Campaign' => 'civicrm_campaign',
'Survey' => 'civicrm_survey',
);
/**
* Class constructor.
*
* Takes in a set of custom field ids andsets up the data structures to
* generate a query
*
* @param array $ids
* The set of custom field ids.
*
* @param bool $contactSearch
* @param array $locationSpecificFields
*/
public function __construct($ids, $contactSearch = FALSE, $locationSpecificFields = array()) {
$this->_ids = &$ids;
$this->_locationSpecificCustomFields = $locationSpecificFields;
$this->_select = array();
$this->_element = array();
$this->_tables = array();
$this->_whereTables = array();
$this->_where = array();
$this->_qill = array();
$this->_options = array();
$this->_fields = array();
$this->_contactSearch = $contactSearch;
if (empty($this->_ids)) {
return;
}
// initialize the field array
$tmpArray = array_keys($this->_ids);
$idString = implode(',', $tmpArray);
$query = "
SELECT f.id, f.label, f.data_type,
f.html_type, f.is_search_range,
f.option_group_id, f.custom_group_id,
f.column_name, g.table_name,
f.date_format,f.time_format
FROM civicrm_custom_field f,
civicrm_custom_group g
WHERE f.custom_group_id = g.id
AND g.is_active = 1
AND f.is_active = 1
AND f.id IN ( $idString )";
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
// get the group dao to figure which class this custom field extends
$extends = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $dao->custom_group_id, 'extends');
if (array_key_exists($extends, self::$extendsMap)) {
$extendsTable = self::$extendsMap[$extends];
}
elseif (in_array($extends, CRM_Contact_BAO_ContactType::subTypes())) {
// if $extends is a subtype, refer contact table
$extendsTable = self::$extendsMap['Contact'];
}
$this->_fields[$dao->id] = array(
'id' => $dao->id,
'label' => $dao->label,
'extends' => $extendsTable,
'data_type' => $dao->data_type,
'html_type' => $dao->html_type,
'is_search_range' => $dao->is_search_range,
'column_name' => $dao->column_name,
'table_name' => $dao->table_name,
'option_group_id' => $dao->option_group_id,
);
// Deprecated (and poorly named) cache of field attributes
$this->_options[$dao->id] = array(
'attributes' => array(
'label' => $dao->label,
'data_type' => $dao->data_type,
'html_type' => $dao->html_type,
),
);
$options = CRM_Core_PseudoConstant::get('CRM_Core_BAO_CustomField', 'custom_' . $dao->id, array(), 'search');
if ($options) {
$this->_options[$dao->id] += $options;
}
if ($dao->html_type == 'Select Date') {
$this->_options[$dao->id]['attributes']['date_format'] = $dao->date_format;
$this->_options[$dao->id]['attributes']['time_format'] = $dao->time_format;
}
}
}
/**
* Generate the select clause and the associated tables.
*/
public function select() {
if (empty($this->_fields)) {
return;
}
foreach ($this->_fields as $id => $field) {
$name = $field['table_name'];
$fieldName = 'custom_' . $field['id'];
$this->_select["{$name}_id"] = "{$name}.id as {$name}_id";
$this->_element["{$name}_id"] = 1;
$this->_select[$fieldName] = "{$field['table_name']}.{$field['column_name']} as $fieldName";
$this->_element[$fieldName] = 1;
$joinTable = NULL;
// CRM-14265
if ($field['extends'] == 'civicrm_group') {
return;
}
elseif ($field['extends'] == 'civicrm_contact') {
$joinTable = 'contact_a';
}
elseif ($field['extends'] == 'civicrm_contribution') {
$joinTable = $field['extends'];
}
elseif (in_array($field['extends'], self::$extendsMap)) {
$joinTable = $field['extends'];
}
else {
return;
}
$this->_tables[$name] = "\nLEFT JOIN $name ON $name.entity_id = $joinTable.id";
if ($this->_ids[$id]) {
$this->_whereTables[$name] = $this->_tables[$name];
}
if ($joinTable) {
$joinClause = 1;
$joinTableAlias = $joinTable;
// Set location-specific query
if (isset($this->_locationSpecificCustomFields[$id])) {
list($locationType, $locationTypeId) = $this->_locationSpecificCustomFields[$id];
$joinTableAlias = "$locationType-address";
$joinClause = "\nLEFT JOIN $joinTable `$locationType-address` ON (`$locationType-address`.contact_id = contact_a.id AND `$locationType-address`.location_type_id = $locationTypeId)";
}
$this->_tables[$name] = "\nLEFT JOIN $name ON $name.entity_id = `$joinTableAlias`.id";
if ($this->_ids[$id]) {
$this->_whereTables[$name] = $this->_tables[$name];
}
if ($joinTable != 'contact_a') {
$this->_whereTables[$joinTableAlias] = $this->_tables[$joinTableAlias] = $joinClause;
}
elseif ($this->_contactSearch) {
CRM_Contact_BAO_Query::$_openedPanes[ts('Custom Fields')] = TRUE;
}
}
}
}
/**
* Generate the where clause and also the english language equivalent.
*/
public function where() {
foreach ($this->_ids as $id => $values) {
// Fixed for Issue CRM 607
if (CRM_Utils_Array::value($id, $this->_fields) === NULL ||
!$values
) {
continue;
}
$strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
foreach ($values as $tuple) {
list($name, $op, $value, $grouping, $wildcard) = $tuple;
$field = $this->_fields[$id];
$fieldName = "{$field['table_name']}.{$field['column_name']}";
$isSerialized = CRM_Core_BAO_CustomField::isSerialized($field);
// fix $value here to escape sql injection attacks
$qillValue = NULL;
if (!is_array($value)) {
$value = CRM_Core_DAO::escapeString(trim($value));
$qillValue = CRM_Core_BAO_CustomField::displayValue($value, $id);
}
elseif (count($value) && in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
$op = key($value);
$qillValue = strstr($op, 'NULL') ? NULL : CRM_Core_BAO_CustomField::displayValue($value[$op], $id);
}
else {
$op = strstr($op, 'IN') ? $op : 'IN';
$qillValue = CRM_Core_BAO_CustomField::displayValue($value, $id);
}
$qillOp = CRM_Utils_Array::value($op, CRM_Core_SelectValues::getSearchBuilderOperators(), $op);
switch ($field['data_type']) {
case 'String':
case 'StateProvince':
case 'Country':
if ($field['is_search_range'] && is_array($value)) {
//didn't found any field under any of these three data-types as searchable by range
}
else {
// fix $value here to escape sql injection attacks
if (!is_array($value)) {
if ($field['data_type'] == 'String') {
$value = CRM_Utils_Type::escape($strtolower($value), 'String');
}
elseif ($value) {
$value = CRM_Utils_Type::escape($value, 'Integer');
}
$value = str_replace(array('[', ']', ','), array('\[', '\]', '[:comma:]'), $value);
$value = str_replace('|', '[:separator:]', $value);
}
elseif ($isSerialized) {
if (in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
$op = key($value);
$value = $value[$op];
}
// CRM-19006: escape characters like comma, | before building regex pattern
$value = (array) $value;
foreach ($value as $key => $val) {
$value[$key] = str_replace(array('[', ']', ','), array('\[', '\]', '[:comma:]'), $val);
$value[$key] = str_replace('|', '[:separator:]', $value[$key]);
}
$value = implode(',', $value);
}
// CRM-14563,CRM-16575 : Special handling of multi-select custom fields
if ($isSerialized && !CRM_Utils_System::isNull($value) && !strstr($op, 'NULL') && !strstr($op, 'LIKE')) {
$sp = CRM_Core_DAO::VALUE_SEPARATOR;
$value = str_replace(",", "$sp|$sp", $value);
$value = str_replace(array('[:comma:]', '(', ')'), array(',', '[[.left-parenthesis.]]', '[[.right-parenthesis.]]'), $value);
$op = (strstr($op, '!') || strstr($op, 'NOT')) ? 'NOT RLIKE' : 'RLIKE';
$value = $sp . $value . $sp;
if (!$wildcard) {
foreach (explode("|", $value) as $val) {
$val = str_replace('[:separator:]', '\|', $val);
$this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $val, 'String');
}
}
else {
$value = str_replace('[:separator:]', '\|', $value);
$this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'String');
}
}
else {
//FIX for custom data query fired against no value(NULL/NOT NULL)
$this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'String');
}
$this->_qill[$grouping][] = $field['label'] . " $qillOp $qillValue";
}
break;
case 'ContactReference':
$label = $value ? CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name') : '';
$this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'String');
$this->_qill[$grouping][] = $field['label'] . " $qillOp $label";
break;
case 'Int':
$this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'Integer');
$this->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $field['label'], 2 => $qillOp, 3 => $qillValue));;
break;
case 'Boolean':
if (!is_array($value)) {
if (strtolower($value) == 'yes' || strtolower($value) == strtolower(ts('Yes'))) {
$value = 1;
}
else {
$value = (int) $value;
}
$value = ($value == 1) ? 1 : 0;
$qillValue = $value ? 'Yes' : 'No';
}
$this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'Integer');
$this->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $field['label'], 2 => $qillOp, 3 => $qillValue));
break;
case 'Link':
case 'Memo':
$this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'String');
$this->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $field['label'], 2 => $qillOp, 3 => $qillValue));
break;
case 'Money':
$value = CRM_Utils_Array::value($op, (array) $value, $value);
if (is_array($value)) {
foreach ($value as $key => $val) {
$value[$key] = CRM_Utils_Rule::cleanMoney($value[$key]);
}
}
else {
$value = CRM_Utils_Rule::cleanMoney($value);
}
case 'Float':
$this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'Float');
$this->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $field['label'], 2 => $qillOp, 3 => $qillValue));
break;
case 'Date':
$this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'String');
list($qillOp, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue(NULL, $field['label'], $value, $op, array(), CRM_Utils_Type::T_DATE);
$this->_qill[$grouping][] = "{$field['label']} $qillOp '$qillVal'";
break;
case 'File':
if ($op == 'IS NULL' || $op == 'IS NOT NULL' || $op == 'IS EMPTY' || $op == 'IS NOT EMPTY') {
switch ($op) {
case 'IS EMPTY':
$op = 'IS NULL';
break;
case 'IS NOT EMPTY':
$op = 'IS NOT NULL';
break;
}
$this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op);
$this->_qill[$grouping][] = $field['label'] . " {$qillOp} ";
}
break;
}
}
}
}
/**
* Function that does the actual query generation.
* basically ties all the above functions together
*
* @return array
* array of strings
*/
public function query() {
$this->select();
$this->where();
$whereStr = NULL;
if (!empty($this->_where)) {
$clauses = array();
foreach ($this->_where as $grouping => $values) {
if (!empty($values)) {
$clauses[] = ' ( ' . implode(' AND ', $values) . ' ) ';
}
}
if (!empty($clauses)) {
$whereStr = ' ( ' . implode(' OR ', $clauses) . ' ) ';
}
}
return array(
implode(' , ', $this->_select),
implode(' ', $this->_tables),
$whereStr,
);
}
}

View file

@ -0,0 +1,221 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* Business objects for managing custom data values.
*/
class CRM_Core_BAO_CustomValue extends CRM_Core_DAO {
/**
* Validate a value against a CustomField type.
*
* @param string $type
* The type of the data.
* @param string $value
* The data to be validated.
*
* @return bool
* True if the value is of the specified type
*/
public static function typecheck($type, $value) {
switch ($type) {
case 'Memo':
return TRUE;
case 'String':
return CRM_Utils_Rule::string($value);
case 'Int':
return CRM_Utils_Rule::integer($value);
case 'Float':
case 'Money':
return CRM_Utils_Rule::numeric($value);
case 'Date':
if (is_numeric($value)) {
return CRM_Utils_Rule::dateTime($value);
}
else {
return CRM_Utils_Rule::date($value);
}
case 'Boolean':
return CRM_Utils_Rule::boolean($value);
case 'ContactReference':
return CRM_Utils_Rule::validContact($value);
case 'StateProvince':
//fix for multi select state, CRM-3437
$valid = FALSE;
$mulValues = explode(',', $value);
foreach ($mulValues as $key => $state) {
$valid = array_key_exists(strtolower(trim($state)),
array_change_key_case(array_flip(CRM_Core_PseudoConstant::stateProvinceAbbreviation()), CASE_LOWER)
) || array_key_exists(strtolower(trim($state)),
array_change_key_case(array_flip(CRM_Core_PseudoConstant::stateProvince()), CASE_LOWER)
);
if (!$valid) {
break;
}
}
return $valid;
case 'Country':
//fix multi select country, CRM-3437
$valid = FALSE;
$mulValues = explode(',', $value);
foreach ($mulValues as $key => $country) {
$valid = array_key_exists(strtolower(trim($country)),
array_change_key_case(array_flip(CRM_Core_PseudoConstant::countryIsoCode()), CASE_LOWER)
) || array_key_exists(strtolower(trim($country)),
array_change_key_case(array_flip(CRM_Core_PseudoConstant::country()), CASE_LOWER)
);
if (!$valid) {
break;
}
}
return $valid;
case 'Link':
return CRM_Utils_Rule::url($value);
}
return FALSE;
}
/**
* Given a 'civicrm' type string, return the mysql data store area
*
* @param string $type
* The civicrm type string.
*
* @return string|null
* the mysql data store placeholder
*/
public static function typeToField($type) {
switch ($type) {
case 'String':
case 'File':
return 'char_data';
case 'Boolean':
case 'Int':
case 'StateProvince':
case 'Country':
case 'Auto-complete':
return 'int_data';
case 'Float':
return 'float_data';
case 'Money':
return 'decimal_data';
case 'Memo':
return 'memo_data';
case 'Date':
return 'date_data';
case 'Link':
return 'char_data';
default:
return NULL;
}
}
/**
* @param array $formValues
* @return null
*/
public static function fixCustomFieldValue(&$formValues) {
if (empty($formValues)) {
return NULL;
}
foreach (array_keys($formValues) as $key) {
if (substr($key, 0, 7) != 'custom_') {
continue;
}
elseif (empty($formValues[$key])) {
continue;
}
$htmlType = CRM_Core_DAO::getFieldValue('CRM_Core_BAO_CustomField',
substr($key, 7), 'html_type'
);
$dataType = CRM_Core_DAO::getFieldValue('CRM_Core_BAO_CustomField',
substr($key, 7), 'data_type'
);
if (is_array($formValues[$key])) {
if (!in_array(key($formValues[$key]), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
$formValues[$key] = array('IN' => $formValues[$key]);
}
}
elseif (($htmlType == 'TextArea' ||
($htmlType == 'Text' && $dataType == 'String')
) && strstr($formValues[$key], '%')
) {
$formValues[$key] = array('LIKE' => $formValues[$key]);
}
}
}
/**
* Delete option value give an option value and custom group id.
*
* @param int $customValueID
* Custom value ID.
* @param int $customGroupID
* Custom group ID.
*/
public static function deleteCustomValue($customValueID, $customGroupID) {
// first we need to find custom value table, from custom group ID
$tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupID, 'table_name');
// delete custom value from corresponding custom value table
$sql = "DELETE FROM {$tableName} WHERE id = {$customValueID}";
CRM_Core_DAO::executeQuery($sql);
CRM_Utils_Hook::custom('delete',
$customGroupID,
NULL,
$customValueID
);
}
}

View file

@ -0,0 +1,741 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
class CRM_Core_BAO_CustomValueTable {
/**
* @param array $customParams
*
* @throws Exception
*/
public static function create(&$customParams) {
if (empty($customParams) ||
!is_array($customParams)
) {
return;
}
foreach ($customParams as $tableName => $tables) {
foreach ($tables as $index => $fields) {
$sqlOP = NULL;
$hookID = NULL;
$hookOP = NULL;
$entityID = NULL;
$isMultiple = FALSE;
$set = array();
$params = array();
$count = 1;
foreach ($fields as $field) {
if (!$sqlOP) {
$entityID = $field['entity_id'];
$hookID = $field['custom_group_id'];
$isMultiple = $field['is_multiple'];
if (array_key_exists('id', $field)) {
$sqlOP = "UPDATE $tableName ";
$where = " WHERE id = %{$count}";
$params[$count] = array($field['id'], 'Integer');
$count++;
$hookOP = 'edit';
}
else {
$sqlOP = "INSERT INTO $tableName ";
$where = NULL;
$hookOP = 'create';
}
}
// fix the value before we store it
$value = $field['value'];
$type = $field['type'];
switch ($type) {
case 'StateProvince':
$type = 'Integer';
if (is_array($value)) {
$value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $value) . CRM_Core_DAO::VALUE_SEPARATOR;
$type = 'String';
}
elseif (!is_numeric($value) && !strstr($value, CRM_Core_DAO::VALUE_SEPARATOR)) {
//fix for multi select state, CRM-3437
$mulValues = explode(',', $value);
$validStates = array();
foreach ($mulValues as $key => $stateVal) {
$states = array();
$states['state_province'] = trim($stateVal);
CRM_Utils_Array::lookupValue($states, 'state_province',
CRM_Core_PseudoConstant::stateProvince(), TRUE
);
if (empty($states['state_province_id'])) {
CRM_Utils_Array::lookupValue($states, 'state_province',
CRM_Core_PseudoConstant::stateProvinceAbbreviation(), TRUE
);
}
$validStates[] = CRM_Utils_Array::value('state_province_id', $states);
}
$value = implode(CRM_Core_DAO::VALUE_SEPARATOR,
$validStates
);
$type = 'String';
}
elseif (!$value) {
// CRM-3415
// using type of timestamp allows us to sneak in a null into db
// gross but effective hack
$value = NULL;
$type = 'Timestamp';
}
else {
$type = 'String';
}
break;
case 'Country':
$type = 'Integer';
$mulValues = explode(',', $value);
if (is_array($value)) {
$value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $value) . CRM_Core_DAO::VALUE_SEPARATOR;
$type = 'String';
}
elseif (!is_numeric($value) && !strstr($value, CRM_Core_DAO::VALUE_SEPARATOR)) {
//fix for multi select country, CRM-3437
$mulValues = explode(',', $value);
$validCountries = array();
foreach ($mulValues as $key => $countryVal) {
$countries = array();
$countries['country'] = trim($countryVal);
CRM_Utils_Array::lookupValue($countries, 'country',
CRM_Core_PseudoConstant::country(), TRUE
);
if (empty($countries['country_id'])) {
CRM_Utils_Array::lookupValue($countries, 'country',
CRM_Core_PseudoConstant::countryIsoCode(), TRUE
);
}
$validCountries[] = CRM_Utils_Array::value('country_id', $countries);
}
$value = implode(CRM_Core_DAO::VALUE_SEPARATOR,
$validCountries
);
$type = 'String';
}
elseif (!$value) {
// CRM-3415
// using type of timestamp allows us to sneak in a null into db
// gross but effective hack
$value = NULL;
$type = 'Timestamp';
}
else {
$type = 'String';
}
break;
case 'File':
if (!$field['file_id']) {
CRM_Core_Error::fatal();
}
// need to add/update civicrm_entity_file
$entityFileDAO = new CRM_Core_DAO_EntityFile();
$entityFileDAO->file_id = $field['file_id'];
$entityFileDAO->find(TRUE);
$entityFileDAO->entity_table = $field['table_name'];
$entityFileDAO->entity_id = $field['entity_id'];
$entityFileDAO->file_id = $field['file_id'];
$entityFileDAO->save();
$entityFileDAO->free();
$value = $field['file_id'];
$type = 'String';
break;
case 'Date':
$value = CRM_Utils_Date::isoToMysql($value);
break;
case 'Int':
if (is_numeric($value)) {
$type = 'Integer';
}
else {
$type = 'Timestamp';
}
break;
case 'ContactReference':
if ($value == NULL) {
$type = 'Timestamp';
}
else {
$type = 'Integer';
}
break;
case 'RichTextEditor':
$type = 'String';
break;
case 'Boolean':
//fix for CRM-3290
$value = CRM_Utils_String::strtoboolstr($value);
if ($value === FALSE) {
$type = 'Timestamp';
}
break;
default:
break;
}
if (strtolower($value) === "null") {
// when unsetting a value to null, we don't need to validate the type
// https://projectllr.atlassian.net/browse/VGQBMP-20
$set[$field['column_name']] = $value;
}
else {
$set[$field['column_name']] = "%{$count}";
$params[$count] = array($value, $type);
$count++;
}
}
if (!empty($set)) {
$setClause = array();
foreach ($set as $n => $v) {
$setClause[] = "$n = $v";
}
$setClause = implode(',', $setClause);
if (!$where) {
// do this only for insert
$set['entity_id'] = "%{$count}";
$params[$count] = array($entityID, 'Integer');
$count++;
$fieldNames = implode(',', CRM_Utils_Type::escapeAll(array_keys($set), 'MysqlColumnNameOrAlias'));
$fieldValues = implode(',', array_values($set));
$query = "$sqlOP ( $fieldNames ) VALUES ( $fieldValues )";
// for multiple values we dont do on duplicate key update
if (!$isMultiple) {
$query .= " ON DUPLICATE KEY UPDATE $setClause";
}
}
else {
$query = "$sqlOP SET $setClause $where";
}
$dao = CRM_Core_DAO::executeQuery($query, $params);
CRM_Utils_Hook::custom($hookOP,
$hookID,
$entityID,
$fields
);
}
}
}
}
/**
* Given a field return the mysql data type associated with it.
*
* @param string $type
* @param int $maxLength
*
* @return string
* the mysql data store placeholder
*/
public static function fieldToSQLType($type, $maxLength = 255) {
if (!isset($maxLength) ||
!is_numeric($maxLength) ||
$maxLength <= 0
) {
$maxLength = 255;
}
switch ($type) {
case 'String':
case 'Link':
return "varchar($maxLength)";
case 'Boolean':
return 'tinyint';
case 'Int':
return 'int';
// the below three are FK's, and have constraints added to them
case 'ContactReference':
case 'StateProvince':
case 'Country':
case 'File':
return 'int unsigned';
case 'Float':
return 'double';
case 'Money':
return 'decimal(20,2)';
case 'Memo':
case 'RichTextEditor':
return 'text';
case 'Date':
return 'datetime';
default:
CRM_Core_Error::fatal();
}
}
/**
* @param array $params
* @param $entityTable
* @param int $entityID
*/
public static function store(&$params, $entityTable, $entityID) {
$cvParams = array();
foreach ($params as $fieldID => $param) {
foreach ($param as $index => $customValue) {
$cvParam = array(
'entity_table' => $entityTable,
'entity_id' => $entityID,
'value' => $customValue['value'],
'type' => $customValue['type'],
'custom_field_id' => $customValue['custom_field_id'],
'custom_group_id' => $customValue['custom_group_id'],
'table_name' => $customValue['table_name'],
'column_name' => $customValue['column_name'],
'is_multiple' => CRM_Utils_Array::value('is_multiple', $customValue),
'file_id' => $customValue['file_id'],
);
// Fix Date type to be timestamp, since that is how we store in db.
if ($cvParam['type'] == 'Date') {
$cvParam['type'] = 'Timestamp';
}
if (!empty($customValue['id'])) {
$cvParam['id'] = $customValue['id'];
}
if (!array_key_exists($customValue['table_name'], $cvParams)) {
$cvParams[$customValue['table_name']] = array();
}
if (!array_key_exists($index, $cvParams[$customValue['table_name']])) {
$cvParams[$customValue['table_name']][$index] = array();
}
$cvParams[$customValue['table_name']][$index][] = $cvParam;
}
}
if (!empty($cvParams)) {
self::create($cvParams);
}
}
/**
* Post process function.
*
* @param array $params
* @param $entityTable
* @param int $entityID
* @param $customFieldExtends
*/
public static function postProcess(&$params, $entityTable, $entityID, $customFieldExtends) {
$customData = CRM_Core_BAO_CustomField::postProcess($params,
$entityID,
$customFieldExtends
);
if (!empty($customData)) {
self::store($customData, $entityTable, $entityID);
}
}
/**
* Return an array of all custom values associated with an entity.
*
* @param int $entityID
* Identification number of the entity.
* @param string $entityType
* Type of entity that the entityID corresponds to, specified.
* as a string with format "'<EntityName>'". Comma separated
* list may be used to specify OR matches. Allowable values
* are enumerated types in civicrm_custom_group.extends field.
* Optional. Default value assumes entityID references a
* contact entity.
* @param array $fieldIDs
* Optional list of fieldIDs that we want to retrieve. If this.
* is set the entityType is ignored
*
* @param bool $formatMultiRecordField
* @param array $DTparams - CRM-17810 dataTable params for the multiValued custom fields.
*
* @return array
* Array of custom values for the entity with key=>value
* pairs specified as civicrm_custom_field.id => custom value.
* Empty array if no custom values found.
*/
public static function &getEntityValues($entityID, $entityType = NULL, $fieldIDs = NULL, $formatMultiRecordField = FALSE, $DTparams = NULL) {
if (!$entityID) {
// adding this here since an empty contact id could have serious repurcussions
// like looping forever
CRM_Core_Error::fatal('Please file an issue with the backtrace');
return NULL;
}
$cond = array();
if ($entityType) {
$cond[] = "cg.extends IN ( '$entityType' )";
}
if ($fieldIDs &&
is_array($fieldIDs)
) {
$fieldIDList = implode(',', $fieldIDs);
$cond[] = "cf.id IN ( $fieldIDList )";
}
if (empty($cond)) {
$cond[] = "cg.extends IN ( 'Contact', 'Individual', 'Household', 'Organization' )";
}
$cond = implode(' AND ', $cond);
$limit = $orderBy = '';
if (!empty($DTparams['rowCount']) && $DTparams['rowCount'] > 0) {
$limit = " LIMIT " . CRM_Utils_Type::escape($DTparams['offset'], 'Integer') . ", " . CRM_Utils_Type::escape($DTparams['rowCount'], 'Integer');
}
if (!empty($DTparams['sort'])) {
$orderBy = ' ORDER BY ' . CRM_Utils_Type::escape($DTparams['sort'], 'String');
}
// First find all the fields that extend this type of entity.
$query = "
SELECT cg.table_name,
cg.id as groupID,
cg.is_multiple,
cf.column_name,
cf.id as fieldID,
cf.data_type as fieldDataType
FROM civicrm_custom_group cg,
civicrm_custom_field cf
WHERE cf.custom_group_id = cg.id
AND cg.is_active = 1
AND cf.is_active = 1
AND $cond
";
$dao = CRM_Core_DAO::executeQuery($query);
$select = $fields = $isMultiple = array();
while ($dao->fetch()) {
if (!array_key_exists($dao->table_name, $select)) {
$fields[$dao->table_name] = array();
$select[$dao->table_name] = array();
}
$fields[$dao->table_name][] = $dao->fieldID;
$select[$dao->table_name][] = "{$dao->column_name} AS custom_{$dao->fieldID}";
$isMultiple[$dao->table_name] = $dao->is_multiple ? TRUE : FALSE;
$file[$dao->table_name][$dao->fieldID] = $dao->fieldDataType;
}
$result = $sortedResult = array();
foreach ($select as $tableName => $clauses) {
if (!empty($DTparams['sort'])) {
$query = CRM_Core_DAO::executeQuery("SELECT id FROM {$tableName} WHERE entity_id = {$entityID}");
$count = 1;
while ($query->fetch()) {
$sortedResult["{$query->id}"] = $count;
$count++;
}
}
$query = "SELECT SQL_CALC_FOUND_ROWS id, " . implode(', ', $clauses) . " FROM $tableName WHERE entity_id = $entityID {$orderBy} {$limit}";
$dao = CRM_Core_DAO::executeQuery($query);
if (!empty($DTparams)) {
$result['count'] = CRM_Core_DAO::singleValueQuery('SELECT FOUND_ROWS()');
}
while ($dao->fetch()) {
foreach ($fields[$tableName] as $fieldID) {
$fieldName = "custom_{$fieldID}";
if ($isMultiple[$tableName]) {
if ($formatMultiRecordField) {
$result["{$dao->id}"]["{$fieldID}"] = $dao->$fieldName;
}
else {
$result["{$fieldID}_{$dao->id}"] = $dao->$fieldName;
}
}
else {
$result[$fieldID] = $dao->$fieldName;
}
}
}
}
if (!empty($sortedResult)) {
$result['sortedResult'] = $sortedResult;
}
return $result;
}
/**
* Take in an array of entityID, custom_XXX => value
* and set the value in the appropriate table. Should also be able
* to set the value to null. Follows api parameter/return conventions
*
* @array $params
*
* @param array $params
*
* @throws Exception
* @return array
*/
public static function setValues(&$params) {
if (!isset($params['entityID']) ||
CRM_Utils_Type::escape($params['entityID'], 'Integer', FALSE) === NULL
) {
return CRM_Core_Error::createAPIError(ts('entityID needs to be set and of type Integer'));
}
// first collect all the id/value pairs. The format is:
// custom_X => value or custom_X_VALUEID => value (for multiple values), VALUEID == -1, -2 etc for new insertions
$values = array();
$fieldValues = array();
foreach ($params as $n => $v) {
if ($customFieldInfo = CRM_Core_BAO_CustomField::getKeyID($n, TRUE)) {
$fieldID = (int ) $customFieldInfo[0];
if (CRM_Utils_Type::escape($fieldID, 'Integer', FALSE) === NULL) {
return CRM_Core_Error::createAPIError(ts('field ID needs to be of type Integer for index %1',
array(1 => $fieldID)
));
}
if (!array_key_exists($fieldID, $fieldValues)) {
$fieldValues[$fieldID] = array();
}
$id = -1;
if ($customFieldInfo[1]) {
$id = (int ) $customFieldInfo[1];
}
$fieldValues[$fieldID][] = array(
'value' => $v,
'id' => $id,
);
}
}
$fieldIDList = implode(',', array_keys($fieldValues));
// format it so that we can just use create
$sql = "
SELECT cg.table_name as table_name ,
cg.id as cg_id ,
cg.is_multiple as is_multiple,
cf.column_name as column_name,
cf.id as cf_id ,
cf.data_type as data_type
FROM civicrm_custom_group cg,
civicrm_custom_field cf
WHERE cf.custom_group_id = cg.id
AND cf.id IN ( $fieldIDList )
";
$dao = CRM_Core_DAO::executeQuery($sql);
$cvParams = array();
while ($dao->fetch()) {
$dataType = $dao->data_type == 'Date' ? 'Timestamp' : $dao->data_type;
foreach ($fieldValues[$dao->cf_id] as $fieldValue) {
// Format null values correctly
if ($fieldValue['value'] === NULL || $fieldValue['value'] === '') {
switch ($dataType) {
case 'String':
case 'Int':
case 'Link':
case 'Boolean':
$fieldValue['value'] = '';
break;
case 'Timestamp':
$fieldValue['value'] = NULL;
break;
case 'StateProvince':
case 'Country':
case 'Money':
case 'Float':
$fieldValue['value'] = (int) 0;
break;
}
}
// Ensure that value is of the right data type
elseif (CRM_Utils_Type::escape($fieldValue['value'], $dataType, FALSE) === NULL) {
return CRM_Core_Error::createAPIError(ts('value: %1 is not of the right field data type: %2',
array(
1 => $fieldValue['value'],
2 => $dao->data_type,
)
));
}
$cvParam = array(
'entity_id' => $params['entityID'],
'value' => $fieldValue['value'],
'type' => $dataType,
'custom_field_id' => $dao->cf_id,
'custom_group_id' => $dao->cg_id,
'table_name' => $dao->table_name,
'column_name' => $dao->column_name,
'is_multiple' => $dao->is_multiple,
);
if ($cvParam['type'] == 'File') {
$cvParam['file_id'] = $fieldValue['value'];
}
if (!array_key_exists($dao->table_name, $cvParams)) {
$cvParams[$dao->table_name] = array();
}
if (!array_key_exists($fieldValue['id'], $cvParams[$dao->table_name])) {
$cvParams[$dao->table_name][$fieldValue['id']] = array();
}
if ($fieldValue['id'] > 0) {
$cvParam['id'] = $fieldValue['id'];
}
$cvParams[$dao->table_name][$fieldValue['id']][] = $cvParam;
}
}
if (!empty($cvParams)) {
self::create($cvParams);
return array('is_error' => 0, 'result' => 1);
}
return CRM_Core_Error::createAPIError(ts('Unknown error'));
}
/**
* Take in an array of entityID, custom_ID
* and gets the value from the appropriate table.
*
* To get the values of custom fields with IDs 13 and 43 for contact ID 1327, use:
* $params = array( 'entityID' => 1327, 'custom_13' => 1, 'custom_43' => 1 );
*
* Entity Type will be inferred by the custom fields you request
* Specify $params['entityType'] if you do not supply any custom fields to return
* and entity type is other than Contact
*
* @array $params
*
* @param array $params
*
* @throws Exception
* @return array
*/
public static function &getValues(&$params) {
if (empty($params)) {
return NULL;
}
if (!isset($params['entityID']) ||
CRM_Utils_Type::escape($params['entityID'],
'Integer', FALSE
) === NULL
) {
return CRM_Core_Error::createAPIError(ts('entityID needs to be set and of type Integer'));
}
// first collect all the ids. The format is:
// custom_ID
$fieldIDs = array();
foreach ($params as $n => $v) {
$key = $idx = NULL;
if (substr($n, 0, 7) == 'custom_') {
$idx = substr($n, 7);
if (CRM_Utils_Type::escape($idx, 'Integer', FALSE) === NULL) {
return CRM_Core_Error::createAPIError(ts('field ID needs to be of type Integer for index %1',
array(1 => $idx)
));
}
$fieldIDs[] = (int ) $idx;
}
}
$default = array('Contact', 'Individual', 'Household', 'Organization');
if (!($type = CRM_Utils_Array::value('entityType', $params)) ||
in_array($params['entityType'], $default)
) {
$type = NULL;
}
else {
$entities = CRM_Core_SelectValues::customGroupExtends();
if (!array_key_exists($type, $entities)) {
if (in_array($type, $entities)) {
$type = $entities[$type];
if (in_array($type, $default)) {
$type = NULL;
}
}
else {
return CRM_Core_Error::createAPIError(ts('Invalid entity type') . ': "' . $type . '"');
}
}
}
$values = self::getEntityValues($params['entityID'],
$type,
$fieldIDs
);
if (empty($values)) {
// note that this behaviour is undesirable from an API point of view - it should return an empty array
// since this is also called by the merger code & not sure the consequences of changing
// are just handling undoing this in the api layer. ie. converting the error back into a success
$result = array(
'is_error' => 1,
'error_message' => 'No values found for the specified entity ID and custom field(s).',
);
return $result;
}
else {
$result = array(
'is_error' => 0,
'entityID' => $params['entityID'],
);
foreach ($values as $id => $value) {
$result["custom_{$id}"] = $value;
}
return $result;
}
}
}

View file

@ -0,0 +1,506 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* Class contains Contact dashboard related functions.
*/
class CRM_Core_BAO_Dashboard extends CRM_Core_DAO_Dashboard {
/**
* Add Dashboard.
*
* @param array $params
* Values.
*
*
* @return object
*/
public static function create($params) {
$hook = empty($params['id']) ? 'create' : 'edit';
CRM_Utils_Hook::pre($hook, 'Dashboard', CRM_Utils_Array::value('id', $params), $params);
$dao = self::addDashlet($params);
CRM_Utils_Hook::post($hook, 'Dashboard', $dao->id, $dao);
return $dao;
}
/**
* Get the list of dashlets enabled by admin.
*
* @param bool $all
* All or only active.
* @param bool $checkPermission
* All or only authorized for the current user.
*
* @return array
* array of dashlets
*/
public static function getDashlets($all = TRUE, $checkPermission = TRUE) {
$dashlets = array();
$dao = new CRM_Core_DAO_Dashboard();
if (!$all) {
$dao->is_active = 1;
}
$dao->domain_id = CRM_Core_Config::domainID();
$dao->find();
while ($dao->fetch()) {
if ($checkPermission && !self::checkPermission($dao->permission, $dao->permission_operator)) {
continue;
}
$values = array();
CRM_Core_DAO::storeValues($dao, $values);
$dashlets[$dao->id] = $values;
}
return $dashlets;
}
/**
* Get the list of dashlets for the current user or the specified user.
*
* Additionlly, initializes the dashboard with defaults if this is the
* user's first visit to their dashboard.
*
* @param int $contactID
* Defaults to the current user.
*
* @return array
* array of dashlets
*/
public static function getContactDashlets($contactID = NULL) {
$contactID = $contactID ? $contactID : CRM_Core_Session::getLoggedInContactID();
$dashlets = array();
// Get contact dashboard dashlets.
$results = civicrm_api3('DashboardContact', 'get', array(
'contact_id' => $contactID,
'is_active' => 1,
'dashboard_id.is_active' => 1,
'options' => array('sort' => 'weight', 'limit' => 0),
'return' => array(
'id',
'weight',
'column_no',
'dashboard_id',
'dashboard_id.name',
'dashboard_id.label',
'dashboard_id.url',
'dashboard_id.fullscreen_url',
'dashboard_id.cache_minutes',
'dashboard_id.permission',
'dashboard_id.permission_operator',
),
));
foreach ($results['values'] as $item) {
if (self::checkPermission(CRM_Utils_Array::value('dashboard_id.permission', $item), CRM_Utils_Array::value('dashboard_id.permission_operator', $item))) {
$dashlets[$item['id']] = array(
'dashboard_id' => $item['dashboard_id'],
'weight' => $item['weight'],
'column_no' => $item['column_no'],
'name' => $item['dashboard_id.name'],
'label' => $item['dashboard_id.label'],
'url' => $item['dashboard_id.url'],
'cache_minutes' => $item['dashboard_id.cache_minutes'],
'fullscreen_url' => CRM_Utils_Array::value('dashboard_id.fullscreen_url', $item),
);
}
}
// If empty, then initialize default dashlets for this user.
if (!$results['count']) {
// They may just have disabled all their dashlets. Check if any records exist for this contact.
if (!civicrm_api3('DashboardContact', 'getcount', array('contact_id' => $contactID))) {
$dashlets = self::initializeDashlets();
}
}
return $dashlets;
}
/**
* @return array
*/
public static function getContactDashletsForJS() {
$data = array(array(), array());
foreach (self::getContactDashlets() as $item) {
$data[$item['column_no']][] = array(
'id' => (int) $item['dashboard_id'],
'name' => $item['name'],
'title' => $item['label'],
'url' => self::parseUrl($item['url']),
'cacheMinutes' => $item['cache_minutes'],
'fullscreenUrl' => self::parseUrl($item['fullscreen_url']),
);
}
return $data;
}
/**
* Setup default dashlets for new users.
*
* When a user accesses their dashboard for the first time, set up
* the default dashlets.
*
* @return array
* Array of dashboard_id's
* @throws \CiviCRM_API3_Exception
*/
public static function initializeDashlets() {
$dashlets = array();
$getDashlets = civicrm_api3("Dashboard", "get", array(
'domain_id' => CRM_Core_Config::domainID(),
'option.limit' => 0,
));
$contactID = CRM_Core_Session::getLoggedInContactID();
$allDashlets = CRM_Utils_Array::index(array('name'), $getDashlets['values']);
$defaultDashlets = array();
$defaults = array('blog' => 1, 'getting-started' => '0');
foreach ($defaults as $name => $column) {
if (!empty($allDashlets[$name]) && !empty($allDashlets[$name]['id'])) {
$defaultDashlets[$name] = array(
'dashboard_id' => $allDashlets[$name]['id'],
'is_active' => 1,
'column_no' => $column,
'contact_id' => $contactID,
);
}
}
CRM_Utils_Hook::dashboard_defaults($allDashlets, $defaultDashlets);
if (is_array($defaultDashlets) && !empty($defaultDashlets)) {
foreach ($defaultDashlets as $id => $defaultDashlet) {
$dashboard_id = $defaultDashlet['dashboard_id'];
$dashlet = $getDashlets['values'][$dashboard_id];
if (!self::checkPermission(CRM_Utils_Array::value('permission', $dashlet), CRM_Utils_Array::value('permission_operator', $dashlet))) {
continue;
}
else {
$assignDashlets = civicrm_api3("dashboard_contact", "create", $defaultDashlet);
$values = $assignDashlets['values'][$assignDashlets['id']];
$dashlets[$assignDashlets['id']] = array(
'dashboard_id' => $values['dashboard_id'],
'weight' => $values['weight'],
'column_no' => $values['column_no'],
'name' => $dashlet['name'],
'label' => $dashlet['label'],
'cache_minutes' => $dashlet['cache_minutes'],
'url' => $dashlet['url'],
'fullscreen_url' => CRM_Utils_Array::value('fullscreen_url', $dashlet),
);
}
}
}
return $dashlets;
}
/**
* @param $url
* @return string
*/
public static function parseUrl($url) {
// Check if it is already a fully-formed url
if ($url && substr($url, 0, 4) != 'http' && $url[0] != '/') {
$urlParam = explode('?', $url);
$url = CRM_Utils_System::url($urlParam[0], CRM_Utils_Array::value(1, $urlParam), FALSE, NULL, FALSE);
}
return $url;
}
/**
* Check dashlet permission for current user.
*
* @param string $permission
* Comma separated list.
* @param string $operator
*
* @return bool
* true if use has permission else false
*/
public static function checkPermission($permission, $operator) {
if ($permission) {
$permissions = explode(',', $permission);
$config = CRM_Core_Config::singleton();
static $allComponents;
if (!$allComponents) {
$allComponents = CRM_Core_Component::getNames();
}
$hasPermission = FALSE;
foreach ($permissions as $key) {
$showDashlet = TRUE;
$componentName = NULL;
if (strpos($key, 'access') === 0) {
$componentName = trim(substr($key, 6));
if (!in_array($componentName, $allComponents)) {
$componentName = NULL;
}
}
// hack to handle case permissions
if (!$componentName && in_array($key, array(
'access my cases and activities',
'access all cases and activities',
))
) {
$componentName = 'CiviCase';
}
//hack to determine if it's a component related permission
if ($componentName) {
if (!in_array($componentName, $config->enableComponents) ||
!CRM_Core_Permission::check($key)
) {
$showDashlet = FALSE;
if ($operator == 'AND') {
return $showDashlet;
}
}
else {
$hasPermission = TRUE;
}
}
elseif (!CRM_Core_Permission::check($key)) {
$showDashlet = FALSE;
if ($operator == 'AND') {
return $showDashlet;
}
}
else {
$hasPermission = TRUE;
}
}
if (!$showDashlet && !$hasPermission) {
return FALSE;
}
else {
return TRUE;
}
}
else {
// if permission is not set consider everyone has permission to access it.
return TRUE;
}
}
/**
* Save changes made by user to the Dashlet.
*
* @param array $columns
*
* @param int $contactID
*
* @throws RuntimeException
*/
public static function saveDashletChanges($columns, $contactID = NULL) {
if (!$contactID) {
$contactID = CRM_Core_Session::getLoggedInContactID();
}
if (empty($contactID)) {
throw new RuntimeException("Failed to determine contact ID");
}
$dashletIDs = array();
if (is_array($columns)) {
foreach ($columns as $colNo => $dashlets) {
if (!is_int($colNo)) {
continue;
}
$weight = 1;
foreach ($dashlets as $dashletID => $isMinimized) {
$dashletID = (int) $dashletID;
$query = "INSERT INTO civicrm_dashboard_contact
(weight, column_no, is_active, dashboard_id, contact_id)
VALUES({$weight}, {$colNo}, 1, {$dashletID}, {$contactID})
ON DUPLICATE KEY UPDATE weight = {$weight}, column_no = {$colNo}, is_active = 1";
// fire update query for each column
CRM_Core_DAO::executeQuery($query);
$dashletIDs[] = $dashletID;
$weight++;
}
}
}
// Disable inactive widgets
$dashletClause = $dashletIDs ? "dashboard_id NOT IN (" . implode(',', $dashletIDs) . ")" : '(1)';
$updateQuery = "UPDATE civicrm_dashboard_contact
SET is_active = 0
WHERE $dashletClause AND contact_id = {$contactID}";
CRM_Core_DAO::executeQuery($updateQuery);
}
/**
* Add dashlets.
*
* @param array $params
*
* @return object
* $dashlet returns dashlet object
*/
public static function addDashlet(&$params) {
// special case to handle duplicate entries for report instances
$dashboardID = CRM_Utils_Array::value('id', $params);
if (!empty($params['instanceURL'])) {
$query = "SELECT id
FROM `civicrm_dashboard`
WHERE url LIKE '" . CRM_Utils_Array::value('instanceURL', $params) . "&%'";
$dashboardID = CRM_Core_DAO::singleValueQuery($query);
}
$dashlet = new CRM_Core_DAO_Dashboard();
if (!$dashboardID) {
// check url is same as exiting entries, if yes just update existing
if (!empty($params['name'])) {
$dashlet->name = CRM_Utils_Array::value('name', $params);
$dashlet->find(TRUE);
}
else {
$dashlet->url = CRM_Utils_Array::value('url', $params);
$dashlet->find(TRUE);
}
if (empty($params['domain_id'])) {
$dashlet->domain_id = CRM_Core_Config::domainID();
}
}
else {
$dashlet->id = $dashboardID;
}
if (is_array(CRM_Utils_Array::value('permission', $params))) {
$params['permission'] = implode(',', $params['permission']);
}
$dashlet->copyValues($params);
$dashlet->save();
// now we need to make dashlet entries for each contact
self::addContactDashlet($dashlet);
return $dashlet;
}
/**
* Update contact dashboard with new dashlet.
*
* @param object $dashlet
*/
public static function addContactDashlet($dashlet) {
$admin = CRM_Core_Permission::check('administer CiviCRM');
// if dashlet is created by admin then you need to add it all contacts.
// else just add to contact who is creating this dashlet
$contactIDs = array();
if ($admin) {
$query = "SELECT distinct( contact_id )
FROM civicrm_dashboard_contact";
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
$contactIDs[$dao->contact_id] = NULL;
}
}
else {
//Get the id of Logged in User
$contactID = CRM_Core_Session::getLoggedInContactID();
if (!empty($contactID)) {
$contactIDs[$contactID] = NULL;
}
}
// Remove contact ids that already have this dashlet to avoid DB
// constraint violation.
$query = "SELECT distinct( contact_id )
FROM civicrm_dashboard_contact WHERE dashboard_id = {$dashlet->id}";
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
if (array_key_exists($dao->contact_id, $contactIDs)) {
unset($contactIDs[$dao->contact_id]);
}
}
if (!empty($contactIDs)) {
foreach ($contactIDs as $contactID => $value) {
$valuesArray[] = " ( {$dashlet->id}, {$contactID} )";
}
$valuesString = implode(',', $valuesArray);
$query = "
INSERT INTO civicrm_dashboard_contact ( dashboard_id, contact_id )
VALUES {$valuesString}";
CRM_Core_DAO::executeQuery($query);
}
}
/**
* @param array $params
* Each item is a spec for a dashlet on the contact's dashboard.
* @return bool
*/
public static function addContactDashletToDashboard(&$params) {
$valuesString = NULL;
$columns = array();
foreach ($params as $dashboardIDs) {
$contactID = CRM_Utils_Array::value('contact_id', $dashboardIDs);
$dashboardID = CRM_Utils_Array::value('dashboard_id', $dashboardIDs);
$column = CRM_Utils_Array::value('column_no', $dashboardIDs, 0);
$columns[$column][$dashboardID] = 0;
}
self::saveDashletChanges($columns, $contactID);
return TRUE;
}
/**
* Delete Dashlet.
*
* @param int $dashletID
*
* @return bool
*/
public static function deleteDashlet($dashletID) {
$dashlet = new CRM_Core_DAO_Dashboard();
$dashlet->id = $dashletID;
if (!$dashlet->find(TRUE)) {
return FALSE;
}
$dashlet->delete();
return TRUE;
}
}

View file

@ -0,0 +1,144 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
class CRM_Core_BAO_Discount extends CRM_Core_DAO_Discount {
/**
* Class constructor.
*/
public function __construct() {
parent::__construct();
}
/**
* Delete the discount.
*
* @param int $entityId
* @param string $entityTable
*
* @return bool
*/
public static function del($entityId, $entityTable) {
// delete all discount records with the selected discounted id
$discount = new CRM_Core_DAO_Discount();
$discount->entity_id = $entityId;
$discount->entity_table = $entityTable;
if ($discount->delete()) {
return TRUE;
}
return FALSE;
}
/**
*
* The function extracts all the params it needs to create a
* discount object. the params array contains additional unused name/value
* pairs
*
* @param array $params
* (reference) an assoc array of name/value pairs.
*
* @return object
* CRM_Core_DAO_Discount object on success, otherwise null
*/
public static function add(&$params) {
$discount = new CRM_Core_DAO_Discount();
$discount->copyValues($params);
$discount->save();
return $discount;
}
/**
* Determine whether the given table/id
* has discount associated with it
*
* @param int $entityId
* Entity id to be searched.
* @param string $entityTable
* Entity table to be searched.
*
* @return array
* option group Ids associated with discount
*/
public static function getOptionGroup($entityId, $entityTable) {
$optionGroupIDs = array();
$dao = new CRM_Core_DAO_Discount();
$dao->entity_id = $entityId;
$dao->entity_table = $entityTable;
$dao->find();
while ($dao->fetch()) {
$optionGroupIDs[$dao->id] = $dao->price_set_id;
}
return $optionGroupIDs;
}
/**
* Determine in which discount set the registration date falls.
*
* @param int $entityID
* Entity id to be searched.
* @param string $entityTable
* Entity table to be searched.
*
* @return int
* $dao->id discount id of the set which matches
* the date criteria
*/
public static function findSet($entityID, $entityTable) {
if (empty($entityID) || empty($entityTable)) {
// adding this here, to trap errors if values are not sent
CRM_Core_Error::fatal();
return NULL;
}
$dao = new CRM_Core_DAO_Discount();
$dao->entity_id = $entityID;
$dao->entity_table = $entityTable;
$dao->find();
while ($dao->fetch()) {
$endDate = $dao->end_date;
// if end date is not we consider current date as end date
if (!$endDate) {
$endDate = date('Ymd');
}
$falls = CRM_Utils_Date::getRange($dao->start_date, $endDate);
if ($falls == TRUE) {
return $dao->id;
}
}
return FALSE;
}
}

View file

@ -0,0 +1,312 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
*
*/
class CRM_Core_BAO_Domain extends CRM_Core_DAO_Domain {
/**
* Cache for the current domain object.
*/
static $_domain = NULL;
/**
* Cache for a domain's location array
*/
private $_location = NULL;
/**
* Fetch object based on array of properties.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $defaults
* (reference ) an assoc array to hold the flattened values.
*
* @return CRM_Core_DAO_Domain
*/
public static function retrieve(&$params, &$defaults) {
return CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_Domain', $params, $defaults);
}
/**
* Get the domain BAO.
*
* @param bool $reset
*
* @return \CRM_Core_BAO_Domain
* @throws \CRM_Core_Exception
*/
public static function getDomain($reset = NULL) {
static $domain = NULL;
if (!$domain || $reset) {
$domain = new CRM_Core_BAO_Domain();
$domain->id = CRM_Core_Config::domainID();
if (!$domain->find(TRUE)) {
throw new CRM_Core_Exception('No domain in DB');
}
}
return $domain;
}
/**
* @param bool $skipUsingCache
*
* @return null|string
*/
public static function version($skipUsingCache = FALSE) {
return CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain',
CRM_Core_Config::domainID(),
'version',
'id',
$skipUsingCache
);
}
/**
* Get the location values of a domain.
*
* @return array
* Location::getValues
*/
public function &getLocationValues() {
if ($this->_location == NULL) {
$domain = self::getDomain(NULL);
$params = array(
'contact_id' => $domain->contact_id,
);
$this->_location = CRM_Core_BAO_Location::getValues($params, TRUE);
if (empty($this->_location)) {
$this->_location = NULL;
}
}
return $this->_location;
}
/**
* Save the values of a domain.
*
* @param array $params
* @param int $id
*
* @return array
* domain
*/
public static function edit(&$params, &$id) {
$domain = new CRM_Core_DAO_Domain();
$domain->id = $id;
$domain->copyValues($params);
$domain->save();
return $domain;
}
/**
* Create a new domain.
*
* @param array $params
*
* @return array
* domain
*/
public static function create($params) {
$domain = new CRM_Core_DAO_Domain();
$domain->copyValues($params);
$domain->save();
return $domain;
}
/**
* @return bool
*/
public static function multipleDomains() {
$session = CRM_Core_Session::singleton();
$numberDomains = $session->get('numberDomains');
if (!$numberDomains) {
$query = "SELECT count(*) from civicrm_domain";
$numberDomains = CRM_Core_DAO::singleValueQuery($query);
$session->set('numberDomains', $numberDomains);
}
return $numberDomains > 1 ? TRUE : FALSE;
}
/**
* @param bool $skipFatal
*
* @return array
* name & email for domain
* @throws Exception
*/
public static function getNameAndEmail($skipFatal = FALSE) {
$fromEmailAddress = CRM_Core_OptionGroup::values('from_email_address', NULL, NULL, NULL, ' AND is_default = 1');
if (!empty($fromEmailAddress)) {
foreach ($fromEmailAddress as $key => $value) {
$email = CRM_Utils_Mail::pluckEmailFromHeader($value);
$fromArray = explode('"', $value);
$fromName = CRM_Utils_Array::value(1, $fromArray);
break;
}
return array($fromName, $email);
}
elseif ($skipFatal) {
return array('', '');
}
$url = CRM_Utils_System::url('civicrm/admin/domain',
'action=update&reset=1'
);
$status = ts("There is no valid default from email address configured for the domain. You can configure here <a href='%1'>Configure From Email Address.</a>", array(1 => $url));
CRM_Core_Error::fatal($status);
}
/**
* @param int $contactID
*
* @return bool|null|object|string
*/
public static function addContactToDomainGroup($contactID) {
$groupID = self::getGroupId();
if ($groupID) {
$contactIDs = array($contactID);
CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIDs, $groupID);
return $groupID;
}
return FALSE;
}
/**
* @return bool|null|object|string
*/
public static function getGroupId() {
static $groupID = NULL;
if ($groupID) {
return $groupID;
}
$domainGroupID = Civi::settings()->get('domain_group_id');
$multisite = Civi::settings()->get('is_enabled');
if ($domainGroupID) {
$groupID = $domainGroupID;
}
elseif ($multisite) {
// create a group with that of domain name
$title = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain',
CRM_Core_Config::domainID(), 'name'
);
$groupID = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group',
$title, 'id', 'title', TRUE
);
}
return $groupID ? $groupID : FALSE;
}
/**
* @param int $groupId
*
* @return bool
*/
public static function isDomainGroup($groupId) {
$domainGroupID = self::getGroupId();
return $domainGroupID == $groupId ? TRUE : FALSE;
}
/**
* @return array
*/
public static function getChildGroupIds() {
$domainGroupID = self::getGroupId();
$childGrps = array();
if ($domainGroupID) {
$childGrps = CRM_Contact_BAO_GroupNesting::getChildGroupIds($domainGroupID);
$childGrps[] = $domainGroupID;
}
return $childGrps;
}
/**
* Retrieve a list of contact-ids that belongs to current domain/site.
*
* @return array
*/
public static function getContactList() {
$siteGroups = CRM_Core_BAO_Domain::getChildGroupIds();
$siteContacts = array();
if (!empty($siteGroups)) {
$query = "
SELECT cc.id
FROM civicrm_contact cc
INNER JOIN civicrm_group_contact gc ON
(gc.contact_id = cc.id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $siteGroups) . "))";
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
$siteContacts[] = $dao->id;
}
}
return $siteContacts;
}
/**
* CRM-20308 & CRM-19657
* Return domain information / user information for the useage in receipts
* Try default from adress then fall back to using logged in user details
*/
public static function getDefaultReceiptFrom() {
$domain = civicrm_api3('domain', 'getsingle', array('id' => CRM_Core_Config::domainID()));
if (!empty($domain['from_email'])) {
return array($domain['from_name'], $domain['from_email']);
}
if (!empty($domain['domain_email'])) {
return array($domain['name'], $domain['domain_email']);
}
$userID = CRM_Core_Session::singleton()->getLoggedInContactID();
$userName = '';
$userEmail = '';
if (!empty($userID)) {
list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
}
// If still empty fall back to the logged in user details.
// return empty values no matter what.
return array($userName, $userEmail);
}
}

View file

@ -0,0 +1,336 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class contains functions for email handling.
*/
class CRM_Core_BAO_Email extends CRM_Core_DAO_Email {
/**
* Create email address.
*
* Note that the create function calls 'add' but has more business logic.
*
* @param array $params
* Input parameters.
*
* @return object
*/
public static function create($params) {
// if id is set & is_primary isn't we can assume no change
if (is_numeric(CRM_Utils_Array::value('is_primary', $params)) || empty($params['id'])) {
CRM_Core_BAO_Block::handlePrimary($params, get_class());
}
$email = CRM_Core_BAO_Email::add($params);
return $email;
}
/**
* Takes an associative array and adds email.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
*
* @return object
* CRM_Core_BAO_Email object on success, null otherwise
*/
public static function add(&$params) {
$hook = empty($params['id']) ? 'create' : 'edit';
CRM_Utils_Hook::pre($hook, 'Email', CRM_Utils_Array::value('id', $params), $params);
$email = new CRM_Core_DAO_Email();
$email->copyValues($params);
if (!empty($email->email)) {
// lower case email field to optimize queries
$strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
$email->email = $strtolower($email->email);
}
/*
* since we're setting bulkmail for 1 of this contact's emails, first reset all their other emails to is_bulkmail false
* We shouldn't not set the current email to false even though we
* are about to reset it to avoid contaminating the changelog if logging is enabled
* (only 1 email address can have is_bulkmail = true)
*/
if ($email->is_bulkmail != 'null' && !empty($params['contact_id']) && !self::isMultipleBulkMail()) {
$sql = "
UPDATE civicrm_email
SET is_bulkmail = 0
WHERE contact_id = {$params['contact_id']}
";
if ($hook == 'edit') {
$sql .= " AND id <> {$params['id']}";
}
CRM_Core_DAO::executeQuery($sql);
}
// handle if email is on hold
self::holdEmail($email);
$email->save();
if ($email->is_primary) {
// update the UF user email if that has changed
CRM_Core_BAO_UFMatch::updateUFName($email->contact_id);
}
CRM_Utils_Hook::post($hook, 'Email', $email->id, $email);
return $email;
}
/**
* Given the list of params in the params array, fetch the object
* and store the values in the values array
*
* @param array $entityBlock
* Input parameters to find object.
*
* @return array
*/
public static function getValues($entityBlock) {
return CRM_Core_BAO_Block::getValues('email', $entityBlock);
}
/**
* Get all the emails for a specified contact_id, with the primary email being first
*
* @param int $id
* The contact id.
*
* @param bool $updateBlankLocInfo
*
* @return array
* the array of email id's
*/
public static function allEmails($id, $updateBlankLocInfo = FALSE) {
if (!$id) {
return NULL;
}
$query = "
SELECT email,
civicrm_location_type.name as locationType,
civicrm_email.is_primary as is_primary,
civicrm_email.on_hold as on_hold,
civicrm_email.id as email_id,
civicrm_email.location_type_id as locationTypeId
FROM civicrm_contact
LEFT JOIN civicrm_email ON ( civicrm_email.contact_id = civicrm_contact.id )
LEFT JOIN civicrm_location_type ON ( civicrm_email.location_type_id = civicrm_location_type.id )
WHERE civicrm_contact.id = %1
ORDER BY civicrm_email.is_primary DESC, email_id ASC ";
$params = array(
1 => array(
$id,
'Integer',
),
);
$emails = $values = array();
$dao = CRM_Core_DAO::executeQuery($query, $params);
$count = 1;
while ($dao->fetch()) {
$values = array(
'locationType' => $dao->locationType,
'is_primary' => $dao->is_primary,
'on_hold' => $dao->on_hold,
'id' => $dao->email_id,
'email' => $dao->email,
'locationTypeId' => $dao->locationTypeId,
);
if ($updateBlankLocInfo) {
$emails[$count++] = $values;
}
else {
$emails[$dao->email_id] = $values;
}
}
return $emails;
}
/**
* Get all the emails for a specified location_block id, with the primary email being first
*
* @param array $entityElements
* The array containing entity_id and.
* entity_table name
*
* @return array
* the array of email id's
*/
public static function allEntityEmails(&$entityElements) {
if (empty($entityElements)) {
return NULL;
}
$entityId = $entityElements['entity_id'];
$entityTable = $entityElements['entity_table'];
$sql = " SELECT email, ltype.name as locationType, e.is_primary as is_primary, e.on_hold as on_hold,e.id as email_id, e.location_type_id as locationTypeId
FROM civicrm_loc_block loc, civicrm_email e, civicrm_location_type ltype, {$entityTable} ev
WHERE ev.id = %1
AND loc.id = ev.loc_block_id
AND e.id IN (loc.email_id, loc.email_2_id)
AND ltype.id = e.location_type_id
ORDER BY e.is_primary DESC, email_id ASC ";
$params = array(
1 => array(
$entityId,
'Integer',
),
);
$emails = array();
$dao = CRM_Core_DAO::executeQuery($sql, $params);
while ($dao->fetch()) {
$emails[$dao->email_id] = array(
'locationType' => $dao->locationType,
'is_primary' => $dao->is_primary,
'on_hold' => $dao->on_hold,
'id' => $dao->email_id,
'email' => $dao->email,
'locationTypeId' => $dao->locationTypeId,
);
}
return $emails;
}
/**
* Set / reset hold status for an email
*
* @param object $email
* Email object.
*/
public static function holdEmail(&$email) {
//check for update mode
if ($email->id) {
$params = array(1 => array($email->id, 'Integer'));
if ($email->on_hold && $email->on_hold != 'null') {
$sql = "
SELECT id
FROM civicrm_email
WHERE id = %1
AND hold_date IS NULL
";
if (CRM_Core_DAO::singleValueQuery($sql, $params)) {
$email->hold_date = date('YmdHis');
$email->reset_date = 'null';
}
}
elseif ($email->on_hold == 'null') {
$sql = "
SELECT id
FROM civicrm_email
WHERE id = %1
AND hold_date IS NOT NULL
AND reset_date IS NULL
";
if (CRM_Core_DAO::singleValueQuery($sql, $params)) {
//set reset date only if it is not set and if hold date is set
$email->on_hold = FALSE;
$email->hold_date = 'null';
$email->reset_date = date('YmdHis');
}
}
}
else {
if (($email->on_hold != 'null') && $email->on_hold) {
$email->hold_date = date('YmdHis');
}
}
}
/**
* Build From Email as the combination of all the email ids of the logged in user and
* the domain email id
*
* @return array
* an array of email ids
*/
public static function getFromEmail() {
$contactID = CRM_Core_Session::singleton()->getLoggedInContactID();
$fromEmailValues = array();
// add all configured FROM email addresses
$domainFrom = CRM_Core_OptionGroup::values('from_email_address');
foreach (array_keys($domainFrom) as $k) {
$domainEmail = $domainFrom[$k];
$fromEmailValues[$domainEmail] = htmlspecialchars($domainEmail);
}
// add logged in user's active email ids
if ($contactID) {
$contactEmails = self::allEmails($contactID);
$fromDisplayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'display_name');
foreach ($contactEmails as $emailVal) {
$email = trim($emailVal['email']);
if (!$email || $emailVal['on_hold']) {
continue;
}
$fromEmail = "$fromDisplayName <$email>";
$fromEmailHtml = htmlspecialchars($fromEmail) . ' ' . $emailVal['locationType'];
if (!empty($emailVal['is_primary'])) {
$fromEmailHtml .= ' ' . ts('(preferred)');
}
$fromEmailValues[$fromEmail] = $fromEmailHtml;
}
}
return $fromEmailValues;
}
/**
* @return object
*/
public static function isMultipleBulkMail() {
return Civi::settings()->get('civimail_multiple_bulk_emails');
}
/**
* Call common delete function.
*
* @param int $id
*
* @return bool
*/
public static function del($id) {
return CRM_Contact_BAO_Contact::deleteObjectWithPrimary('Email', $id);
}
}

View file

@ -0,0 +1,502 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This class contains functions for managing Tag(tag) for a contact
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_Core_BAO_EntityTag extends CRM_Core_DAO_EntityTag {
/**
* Given a contact id, it returns an array of tag id's the contact belongs to.
*
* @param int $entityID
* Id of the entity usually the contactID.
* @param string $entityTable
* Name of the entity table usually 'civicrm_contact'.
*
* @return array
* reference $tag array of category id's the contact belongs to.
*/
public static function getTag($entityID, $entityTable = 'civicrm_contact') {
$tags = array();
$entityTag = new CRM_Core_BAO_EntityTag();
$entityTag->entity_id = $entityID;
$entityTag->entity_table = $entityTable;
$entityTag->find();
while ($entityTag->fetch()) {
$tags[$entityTag->tag_id] = $entityTag->tag_id;
}
return $tags;
}
/**
* Takes an associative array and creates a entityTag object.
*
* the function extract all the params it needs to initialize the create a
* group object. the params array could contain additional unused name/value
* pairs
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
*
* @return CRM_Core_BAO_EntityTag
*/
public static function add(&$params) {
$dataExists = self::dataExists($params);
if (!$dataExists) {
return NULL;
}
$entityTag = new CRM_Core_BAO_EntityTag();
$entityTag->copyValues($params);
// dont save the object if it already exists, CRM-1276
if (!$entityTag->find(TRUE)) {
//invoke pre hook
CRM_Utils_Hook::pre('create', 'EntityTag', $params['tag_id'], $params);
$entityTag->save();
//invoke post hook on entityTag
// we are using this format to keep things consistent between the single and bulk operations
// so a bit different from other post hooks
$object = array(0 => array(0 => $params['entity_id']), 1 => $params['entity_table']);
CRM_Utils_Hook::post('create', 'EntityTag', $params['tag_id'], $object);
}
return $entityTag;
}
/**
* Check if there is data to create the object.
*
* @param array $params
* An assoc array of name/value pairs.
*
* @return bool
*/
public static function dataExists($params) {
return !($params['tag_id'] == 0);
}
/**
* Delete the tag for a contact.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
*/
public static function del(&$params) {
//invoke pre hook
if (!empty($params['tag_id'])) {
CRM_Utils_Hook::pre('delete', 'EntityTag', $params['tag_id'], $params);
}
$entityTag = new CRM_Core_BAO_EntityTag();
$entityTag->copyValues($params);
$entityTag->delete();
//invoke post hook on entityTag
if (!empty($params['tag_id'])) {
$object = array(0 => array(0 => $params['entity_id']), 1 => $params['entity_table']);
CRM_Utils_Hook::post('delete', 'EntityTag', $params['tag_id'], $object);
}
}
/**
* Given an array of entity ids and entity table, add all the entity to the tags.
*
* @param array $entityIds
* (reference ) the array of entity ids to be added.
* @param int $tagId
* The id of the tag.
* @param string $entityTable
* Name of entity table default:civicrm_contact.
* @param bool $applyPermissions
* Should permissions be applied in this function.
*
* @return array
* (total, added, notAdded) count of entities added to tag
*/
public static function addEntitiesToTag(&$entityIds, $tagId, $entityTable, $applyPermissions) {
$numEntitiesAdded = 0;
$numEntitiesNotAdded = 0;
$entityIdsAdded = array();
//invoke pre hook for entityTag
$preObject = array($entityIds, $entityTable);
CRM_Utils_Hook::pre('create', 'EntityTag', $tagId, $preObject);
foreach ($entityIds as $entityId) {
// CRM-17350 - check if we have permission to edit the contact
// that this tag belongs to.
if ($applyPermissions && !self::checkPermissionOnEntityTag($entityId, $entityTable)) {
$numEntitiesNotAdded++;
continue;
}
$tag = new CRM_Core_DAO_EntityTag();
$tag->entity_id = $entityId;
$tag->tag_id = $tagId;
$tag->entity_table = $entityTable;
if (!$tag->find()) {
$tag->save();
$entityIdsAdded[] = $entityId;
$numEntitiesAdded++;
}
else {
$numEntitiesNotAdded++;
}
}
//invoke post hook on entityTag
$object = array($entityIdsAdded, $entityTable);
CRM_Utils_Hook::post('create', 'EntityTag', $tagId, $object);
CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
return array(count($entityIds), $numEntitiesAdded, $numEntitiesNotAdded);
}
/**
* Basic check for ACL permission on editing/creating/removing a tag.
*
* In the absence of something better contacts get a proper check and other entities
* default to 'edit all contacts'. This is currently only accessed from the api which previously
* applied edit all contacts to all - so while still too restrictive it represents a loosening.
*
* Current possible entities are attachments, activities, cases & contacts.
*
* @param int $entityID
* @param string $entityTable
*
* @return bool
*/
public static function checkPermissionOnEntityTag($entityID, $entityTable) {
if ($entityTable == 'civicrm_contact') {
return CRM_Contact_BAO_Contact_Permission::allow($entityID, CRM_Core_Permission::EDIT);
}
else {
return CRM_Core_Permission::check('edit all contacts');
}
}
/**
* Given an array of entity ids and entity table, remove entity(s)tags.
*
* @param array $entityIds
* (reference ) the array of entity ids to be removed.
* @param int $tagId
* The id of the tag.
* @param string $entityTable
* Name of entity table default:civicrm_contact.
* @param bool $applyPermissions
* Should permissions be applied in this function.
*
* @return array
* (total, removed, notRemoved) count of entities removed from tags
*/
public static function removeEntitiesFromTag(&$entityIds, $tagId, $entityTable, $applyPermissions) {
$numEntitiesRemoved = 0;
$numEntitiesNotRemoved = 0;
$entityIdsRemoved = array();
//invoke pre hook for entityTag
$preObject = array($entityIds, $entityTable);
CRM_Utils_Hook::pre('delete', 'EntityTag', $tagId, $preObject);
foreach ($entityIds as $entityId) {
// CRM-17350 - check if we have permission to edit the contact
// that this tag belongs to.
if ($applyPermissions && !self::checkPermissionOnEntityTag($entityId, $entityTable)) {
$numEntitiesNotRemoved++;
continue;
}
$tag = new CRM_Core_DAO_EntityTag();
$tag->entity_id = $entityId;
$tag->tag_id = $tagId;
$tag->entity_table = $entityTable;
if ($tag->find()) {
$tag->delete();
$entityIdsRemoved[] = $entityId;
$numEntitiesRemoved++;
}
else {
$numEntitiesNotRemoved++;
}
}
//invoke post hook on entityTag
$object = array($entityIdsRemoved, $entityTable);
CRM_Utils_Hook::post('delete', 'EntityTag', $tagId, $object);
CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
return array(count($entityIds), $numEntitiesRemoved, $numEntitiesNotRemoved);
}
/**
* Takes an associative array and creates tag entity record for all tag entities.
*
* @param array $params
* (reference) an assoc array of name/value pairs.
* @param string $entityTable
* @param int $entityID
*/
public static function create(&$params, $entityTable, $entityID) {
// get categories for the entity id
$entityTag = CRM_Core_BAO_EntityTag::getTag($entityID, $entityTable);
// get the list of all the categories
$allTag = CRM_Core_BAO_Tag::getTags($entityTable);
// this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
if (!is_array($params)) {
$params = array();
}
// this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
if (!is_array($entityTag)) {
$entityTag = array();
}
// check which values has to be inserted/deleted for contact
foreach ($allTag as $key => $varValue) {
$tagParams['entity_table'] = $entityTable;
$tagParams['entity_id'] = $entityID;
$tagParams['tag_id'] = $key;
if (array_key_exists($key, $params) && !array_key_exists($key, $entityTag)) {
// insert a new record
CRM_Core_BAO_EntityTag::add($tagParams);
}
elseif (!array_key_exists($key, $params) && array_key_exists($key, $entityTag)) {
// delete a record for existing contact
CRM_Core_BAO_EntityTag::del($tagParams);
}
}
}
/**
* This function returns all entities assigned to a specific tag.
*
* @param object $tag
* An object of a tag.
*
* @return array
* array of entity ids
*/
public function getEntitiesByTag($tag) {
$entityIds = array();
$entityTagDAO = new CRM_Core_DAO_EntityTag();
$entityTagDAO->tag_id = $tag->id;
$entityTagDAO->find();
while ($entityTagDAO->fetch()) {
$entityIds[] = $entityTagDAO->entity_id;
}
return $entityIds;
}
/**
* Get contact tags.
*
* @param int $contactID
* @param bool $count
*
* @return array
*/
public static function getContactTags($contactID, $count = FALSE) {
$contactTags = array();
if (!$count) {
$select = "SELECT ct.id, ct.name ";
}
else {
$select = "SELECT count(*) as cnt";
}
$query = "{$select}
FROM civicrm_tag ct
INNER JOIN civicrm_entity_tag et ON ( ct.id = et.tag_id AND
et.entity_id = {$contactID} AND
et.entity_table = 'civicrm_contact' AND
ct.is_tagset = 0 )";
$dao = CRM_Core_DAO::executeQuery($query);
if ($count) {
$dao->fetch();
return $dao->cnt;
}
while ($dao->fetch()) {
$contactTags[$dao->id] = $dao->name;
}
return $contactTags;
}
/**
* Get child contact tags given parentId.
*
* @param int $parentId
* @param int $entityId
* @param string $entityTable
*
* @return array
*/
public static function getChildEntityTags($parentId, $entityId, $entityTable = 'civicrm_contact') {
$entityTags = array();
$query = "SELECT ct.id as tag_id, name FROM civicrm_tag ct
INNER JOIN civicrm_entity_tag et ON ( et.entity_id = {$entityId} AND
et.entity_table = '{$entityTable}' AND et.tag_id = ct.id)
WHERE ct.parent_id = {$parentId}";
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
$entityTags[$dao->tag_id] = array(
'id' => $dao->tag_id,
'name' => $dao->name,
);
}
return $entityTags;
}
/**
* Merge two tags
*
* Tag A will inherit all of tag B's properties.
* Tag B will be deleted.
*
* @param int $tagAId
* @param int $tagBId
*
* @return array
*/
public function mergeTags($tagAId, $tagBId) {
$queryParams = array(
1 => array($tagAId, 'Integer'),
2 => array($tagBId, 'Integer'),
);
// re-compute used_for field
$query = "SELECT id, name, used_for FROM civicrm_tag WHERE id IN (%1, %2)";
$dao = CRM_Core_DAO::executeQuery($query, $queryParams);
$tags = array();
while ($dao->fetch()) {
$label = ($dao->id == $tagAId) ? 'tagA' : 'tagB';
$tags[$label] = $dao->name;
$tags["{$label}_used_for"] = $dao->used_for ? explode(",", $dao->used_for) : array();
}
$usedFor = array_merge($tags["tagA_used_for"], $tags["tagB_used_for"]);
$usedFor = implode(',', array_unique($usedFor));
$tags["used_for"] = explode(",", $usedFor);
// get all merge queries together
$sqls = array(
// 1. update entity tag entries
"UPDATE IGNORE civicrm_entity_tag SET tag_id = %1 WHERE tag_id = %2",
// 2. move children
"UPDATE civicrm_tag SET parent_id = %1 WHERE parent_id = %2",
// 3. update used_for info for tag A & children
"UPDATE civicrm_tag SET used_for = '{$usedFor}' WHERE id = %1 OR parent_id = %1",
// 4. delete tag B
"DELETE FROM civicrm_tag WHERE id = %2",
// 5. remove duplicate entity tag records
"DELETE et2.* from civicrm_entity_tag et1 INNER JOIN civicrm_entity_tag et2 ON et1.entity_table = et2.entity_table AND et1.entity_id = et2.entity_id AND et1.tag_id = et2.tag_id WHERE et1.id < et2.id",
// 6. remove orphaned entity_tags
"DELETE FROM civicrm_entity_tag WHERE tag_id = %2",
);
$tables = array('civicrm_entity_tag', 'civicrm_tag');
// Allow hook_civicrm_merge() to add SQL statements for the merge operation AND / OR
// perform any other actions like logging
CRM_Utils_Hook::merge('sqls', $sqls, $tagAId, $tagBId, $tables);
// call the SQL queries in one transaction
$transaction = new CRM_Core_Transaction();
foreach ($sqls as $sql) {
CRM_Core_DAO::executeQuery($sql, $queryParams, TRUE, NULL, TRUE);
}
$transaction->commit();
$tags['status'] = TRUE;
return $tags;
}
/**
* Get options for a given field.
*
* @see CRM_Core_DAO::buildOptions
* @see CRM_Core_DAO::buildOptionsContext
*
* @param string $fieldName
* @param string $context
* As per CRM_Core_DAO::buildOptionsContext.
* @param array $props
* whatever is known about this dao object.
*
* @return array|bool
*/
public static function buildOptions($fieldName, $context = NULL, $props = array()) {
$params = array();
if ($fieldName == 'tag' || $fieldName == 'tag_id') {
if (!empty($props['entity_table'])) {
$entity = CRM_Utils_Type::escape($props['entity_table'], 'String');
$params[] = "used_for LIKE '%$entity%'";
}
// Output tag list as nested hierarchy
// TODO: This will only work when api.entity is "entity_tag". What about others?
if ($context == 'search' || $context == 'create') {
$dummyArray = array();
return CRM_Core_BAO_Tag::getTags(CRM_Utils_Array::value('entity_table', $props, 'civicrm_contact'), $dummyArray, CRM_Utils_Array::value('parent_id', $params), '- ');
}
}
$options = CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
// Special formatting for validate/match context
if ($fieldName == 'entity_table' && in_array($context, array('validate', 'match'))) {
$options = array();
foreach (self::buildOptions($fieldName) as $tableName => $label) {
$bao = CRM_Core_DAO_AllCoreTables::getClassForTable($tableName);
$apiName = CRM_Core_DAO_AllCoreTables::getBriefName($bao);
$options[$tableName] = $apiName;
}
}
return $options;
}
}

View file

@ -0,0 +1,107 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class contains functions for managing extensions
*/
class CRM_Core_BAO_Extension extends CRM_Core_DAO_Extension {
/**
* Fetch object based on array of properties.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $defaults
* (reference ) an assoc array to hold the flattened values.
*
* @return CRM_Core_BAO_LocationType|null
* object on success, null otherwise
*/
public static function retrieve(&$params, &$defaults) {
$extension = new CRM_Core_DAO_Extension();
$extension->copyValues($params);
if ($extension->find(TRUE)) {
CRM_Core_DAO::storeValues($extension, $defaults);
return $extension;
}
return NULL;
}
/**
* Delete an extension.
*
* @param int $id
* Id of the extension to be deleted.
*
* @return mixed
*/
public static function del($id) {
$extension = new CRM_Core_DAO_Extension();
$extension->id = $id;
return $extension->delete();
}
/**
* Change the schema version of an extension.
*
* @param string $fullName
* the fully-qualified name (eg "com.example.myextension").
* @param string $schemaVersion
*
* @return \CRM_Core_DAO|object
*/
public static function setSchemaVersion($fullName, $schemaVersion) {
$sql = 'UPDATE civicrm_extension SET schema_version = %1 WHERE full_name = %2';
$params = array(
1 => array($schemaVersion, 'String'),
2 => array($fullName, 'String'),
);
return CRM_Core_DAO::executeQuery($sql, $params);
}
/**
* Determine the schema version of an extension.
*
* @param string $fullName
* the fully-qualified name (eg "com.example.myextension").
* @return string
*/
public static function getSchemaVersion($fullName) {
$sql = 'SELECT schema_version FROM civicrm_extension WHERE full_name = %1';
$params = array(
1 => array($fullName, 'String'),
);
return CRM_Core_DAO::singleValueQuery($sql, $params);
}
}

View file

@ -0,0 +1,745 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* BAO object for crm_log table
*/
class CRM_Core_BAO_File extends CRM_Core_DAO_File {
static $_signableFields = array('entityTable', 'entityID', 'fileID');
/**
* @param int $fileID
* @param int $entityID
* @param null $entityTable
*
* @return array
*/
public static function path($fileID, $entityID, $entityTable = NULL) {
$entityFileDAO = new CRM_Core_DAO_EntityFile();
if ($entityTable) {
$entityFileDAO->entity_table = $entityTable;
}
$entityFileDAO->entity_id = $entityID;
$entityFileDAO->file_id = $fileID;
if ($entityFileDAO->find(TRUE)) {
$fileDAO = new CRM_Core_DAO_File();
$fileDAO->id = $fileID;
if ($fileDAO->find(TRUE)) {
$config = CRM_Core_Config::singleton();
$path = $config->customFileUploadDir . $fileDAO->uri;
if (file_exists($path) && is_readable($path)) {
return array($path, $fileDAO->mime_type);
}
}
}
return array(NULL, NULL);
}
/**
* @param $data
* @param int $fileTypeID
* @param $entityTable
* @param int $entityID
* @param $entitySubtype
* @param bool $overwrite
* @param null|array $fileParams
* @param string $uploadName
* @param null $mimeType
*
* @throws Exception
*/
public static function filePostProcess(
$data,
$fileTypeID,
$entityTable,
$entityID,
$entitySubtype,
$overwrite = TRUE,
$fileParams = NULL,
$uploadName = 'uploadFile',
$mimeType = NULL
) {
if (!$mimeType) {
CRM_Core_Error::statusBounce(ts('Mime Type is now a required parameter for file upload'));
}
$config = CRM_Core_Config::singleton();
$path = explode('/', $data);
$filename = $path[count($path) - 1];
// rename this file to go into the secure directory
if ($entitySubtype) {
$directoryName = $config->customFileUploadDir . $entitySubtype . DIRECTORY_SEPARATOR . $entityID;
}
else {
$directoryName = $config->customFileUploadDir;
}
CRM_Utils_File::createDir($directoryName);
if (!rename($data, $directoryName . DIRECTORY_SEPARATOR . $filename)) {
CRM_Core_Error::statusBounce(ts('Could not move custom file to custom upload directory'));
}
// to get id's
if ($overwrite && $fileTypeID) {
list($sql, $params) = self::sql($entityTable, $entityID, $fileTypeID);
}
else {
list($sql, $params) = self::sql($entityTable, $entityID, 0);
}
$dao = CRM_Core_DAO::executeQuery($sql, $params);
$dao->fetch();
$fileDAO = new CRM_Core_DAO_File();
$op = 'create';
if (isset($dao->cfID) && $dao->cfID) {
$op = 'edit';
$fileDAO->id = $dao->cfID;
unlink($directoryName . DIRECTORY_SEPARATOR . $dao->uri);
}
if (!empty($fileParams)) {
$fileDAO->copyValues($fileParams);
}
$fileDAO->uri = $filename;
$fileDAO->mime_type = $mimeType;
$fileDAO->file_type_id = $fileTypeID;
$fileDAO->upload_date = date('YmdHis');
$fileDAO->save();
// need to add/update civicrm_entity_file
$entityFileDAO = new CRM_Core_DAO_EntityFile();
if (isset($dao->cefID) && $dao->cefID) {
$entityFileDAO->id = $dao->cefID;
}
$entityFileDAO->entity_table = $entityTable;
$entityFileDAO->entity_id = $entityID;
$entityFileDAO->file_id = $fileDAO->id;
$entityFileDAO->save();
//save static tags
if (!empty($fileParams['tag'])) {
CRM_Core_BAO_EntityTag::create($fileParams['tag'], 'civicrm_file', $entityFileDAO->id);
}
//save free tags
if (isset($fileParams['attachment_taglist']) && !empty($fileParams['attachment_taglist'])) {
CRM_Core_Form_Tag::postProcess($fileParams['attachment_taglist'], $entityFileDAO->id, 'civicrm_file');
}
// lets call the post hook here so attachments code can do the right stuff
CRM_Utils_Hook::post($op, 'File', $fileDAO->id, $fileDAO);
}
/**
* A static function wrapper that deletes the various objects.
*
* Objects are those hat are connected to a file object (i.e. file, entityFile and customValue.
*
* @param int $fileID
* @param int $entityID
* @param int $fieldID
*
* @throws \Exception
*/
public static function deleteFileReferences($fileID, $entityID, $fieldID) {
$fileDAO = new CRM_Core_DAO_File();
$fileDAO->id = $fileID;
if (!$fileDAO->find(TRUE)) {
CRM_Core_Error::fatal();
}
// lets call a pre hook before the delete, so attachments hooks can get the info before things
// disappear
CRM_Utils_Hook::pre('delete', 'File', $fileID, $fileDAO);
// get the table and column name
list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField::getTableColumnGroup($fieldID);
$entityFileDAO = new CRM_Core_DAO_EntityFile();
$entityFileDAO->file_id = $fileID;
$entityFileDAO->entity_id = $entityID;
$entityFileDAO->entity_table = $tableName;
if (!$entityFileDAO->find(TRUE)) {
CRM_Core_Error::fatal(sprintf('No record found for given file ID - %d and entity ID - %d', $fileID, $entityID));
}
$entityFileDAO->delete();
$fileDAO->delete();
// also set the value to null of the table and column
$query = "UPDATE $tableName SET $columnName = null WHERE $columnName = %1";
$params = array(1 => array($fileID, 'Integer'));
CRM_Core_DAO::executeQuery($query, $params);
}
/**
* The $useWhere is used so that the signature matches the parent class
*
* public function delete($useWhere = FALSE) {
* list($fileID, $entityID, $fieldID) = func_get_args();
*
* self::deleteFileReferences($fileID, $entityID, $fieldID);
* } */
/**
* Delete all the files and associated object associated with this combination.
*
* @param string $entityTable
* @param int $entityID
* @param int $fileTypeID
* @param int $fileID
*
* @return bool
* Was file deleted?
*/
public static function deleteEntityFile($entityTable, $entityID, $fileTypeID = NULL, $fileID = NULL) {
$isDeleted = FALSE;
if (empty($entityTable) || empty($entityID)) {
return $isDeleted;
}
$config = CRM_Core_Config::singleton();
list($sql, $params) = self::sql($entityTable, $entityID, $fileTypeID, $fileID);
$dao = CRM_Core_DAO::executeQuery($sql, $params);
$cfIDs = array();
$cefIDs = array();
while ($dao->fetch()) {
$cfIDs[$dao->cfID] = $dao->uri;
$cefIDs[] = $dao->cefID;
}
if (!empty($cefIDs)) {
$cefIDs = implode(',', $cefIDs);
$sql = "DELETE FROM civicrm_entity_file where id IN ( $cefIDs )";
CRM_Core_DAO::executeQuery($sql);
$isDeleted = TRUE;
}
if (!empty($cfIDs)) {
// Delete file only if there no any entity using this file.
$deleteFiles = array();
foreach ($cfIDs as $fId => $fUri) {
//delete tags from entity tag table
$tagParams = array(
'entity_table' => 'civicrm_file',
'entity_id' => $fId,
);
CRM_Core_BAO_EntityTag::del($tagParams);
if (!CRM_Core_DAO::getFieldValue('CRM_Core_DAO_EntityFile', $fId, 'id', 'file_id')) {
unlink($config->customFileUploadDir . DIRECTORY_SEPARATOR . $fUri);
$deleteFiles[$fId] = $fId;
}
}
if (!empty($deleteFiles)) {
$deleteFiles = implode(',', $deleteFiles);
$sql = "DELETE FROM civicrm_file where id IN ( $deleteFiles )";
CRM_Core_DAO::executeQuery($sql);
}
$isDeleted = TRUE;
}
return $isDeleted;
}
/**
* Get all the files and associated object associated with this combination.
*
* @param string $entityTable
* @param int $entityID
* @param bool $addDeleteArgs
*
* @return array|null
*/
public static function getEntityFile($entityTable, $entityID, $addDeleteArgs = FALSE) {
if (empty($entityTable) || !$entityID) {
$results = NULL;
return $results;
}
$config = CRM_Core_Config::singleton();
list($sql, $params) = self::sql($entityTable, $entityID, NULL);
$dao = CRM_Core_DAO::executeQuery($sql, $params);
$results = array();
while ($dao->fetch()) {
$result['fileID'] = $dao->cfID;
$result['entityID'] = $dao->cefID;
$result['mime_type'] = $dao->mime_type;
$result['fileName'] = $dao->uri;
$result['description'] = $dao->description;
$result['cleanName'] = CRM_Utils_File::cleanFileName($dao->uri);
$result['fullPath'] = $config->customFileUploadDir . DIRECTORY_SEPARATOR . $dao->uri;
$result['url'] = CRM_Utils_System::url('civicrm/file', "reset=1&id={$dao->cfID}&eid={$dao->entity_id}");
$result['href'] = "<a href=\"{$result['url']}\">{$result['cleanName']}</a>";
$result['tag'] = CRM_Core_BAO_EntityTag::getTag($dao->cfID, 'civicrm_file');
$result['icon'] = CRM_Utils_File::getIconFromMimeType($dao->mime_type);
if ($addDeleteArgs) {
$result['deleteURLArgs'] = self::deleteURLArgs($dao->entity_table, $dao->entity_id, $dao->cfID);
}
$results[$dao->cfID] = $result;
}
//fix tag names
$tags = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
foreach ($results as &$values) {
if (!empty($values['tag'])) {
$tagNames = array();
foreach ($values['tag'] as $tid) {
$tagNames[] = $tags[$tid];
}
$values['tag'] = implode(', ', $tagNames);
}
else {
$values['tag'] = '';
}
}
$dao->free();
return $results;
}
/**
* @param string $entityTable
* Table-name or "*" (to reference files directly by file-id).
* @param int $entityID
* @param int $fileTypeID
* @param int $fileID
*
* @return array
*/
public static function sql($entityTable, $entityID, $fileTypeID = NULL, $fileID = NULL) {
if ($entityTable == '*') {
// $entityID is the ID of a specific file
$sql = "
SELECT CF.id as cfID,
CF.uri as uri,
CF.mime_type as mime_type,
CF.description as description,
CEF.id as cefID,
CEF.entity_table as entity_table,
CEF.entity_id as entity_id
FROM civicrm_file AS CF
LEFT JOIN civicrm_entity_file AS CEF ON ( CEF.file_id = CF.id )
WHERE CF.id = %2";
}
else {
$sql = "
SELECT CF.id as cfID,
CF.uri as uri,
CF.mime_type as mime_type,
CF.description as description,
CEF.id as cefID,
CEF.entity_table as entity_table,
CEF.entity_id as entity_id
FROM civicrm_file AS CF
LEFT JOIN civicrm_entity_file AS CEF ON ( CEF.file_id = CF.id )
WHERE CEF.entity_table = %1
AND CEF.entity_id = %2";
}
$params = array(
1 => array($entityTable, 'String'),
2 => array($entityID, 'Integer'),
);
if ($fileTypeID !== NULL) {
$sql .= " AND CF.file_type_id = %3";
$params[3] = array($fileTypeID, 'Integer');
}
if ($fileID !== NULL) {
$sql .= " AND CF.id = %4";
$params[4] = array($fileID, 'Integer');
}
return array($sql, $params);
}
/**
* @param CRM_Core_Form $form
* @param string $entityTable
* @param int $entityID
* @param null $numAttachments
* @param bool $ajaxDelete
*/
public static function buildAttachment(&$form, $entityTable, $entityID = NULL, $numAttachments = NULL, $ajaxDelete = FALSE) {
if (!$numAttachments) {
$numAttachments = Civi::settings()->get('max_attachments');
}
// Assign maxAttachments count to template for help message
$form->assign('maxAttachments', $numAttachments);
$config = CRM_Core_Config::singleton();
// set default max file size as 2MB
$maxFileSize = $config->maxFileSize ? $config->maxFileSize : 2;
$currentAttachmentInfo = self::getEntityFile($entityTable, $entityID, TRUE);
$totalAttachments = 0;
if ($currentAttachmentInfo) {
$totalAttachments = count($currentAttachmentInfo);
$form->add('checkbox', 'is_delete_attachment', ts('Delete All Attachment(s)'));
$form->assign('currentAttachmentInfo', $currentAttachmentInfo);
}
else {
$form->assign('currentAttachmentInfo', NULL);
}
if ($totalAttachments) {
if ($totalAttachments >= $numAttachments) {
$numAttachments = 0;
}
else {
$numAttachments -= $totalAttachments;
}
}
$form->assign('numAttachments', $numAttachments);
CRM_Core_BAO_Tag::getTags('civicrm_file', $tags, NULL,
'&nbsp;&nbsp;', TRUE);
// get tagset info
$parentNames = CRM_Core_BAO_Tag::getTagSet('civicrm_file');
// add attachments
for ($i = 1; $i <= $numAttachments; $i++) {
$form->addElement('file', "attachFile_$i", ts('Attach File'), 'size=30 maxlength=221');
$form->addUploadElement("attachFile_$i");
$form->setMaxFileSize($maxFileSize * 1024 * 1024);
$form->addRule("attachFile_$i",
ts('File size should be less than %1 MByte(s)',
array(1 => $maxFileSize)
),
'maxfilesize',
$maxFileSize * 1024 * 1024
);
$form->addElement('text', "attachDesc_$i", NULL, array(
'size' => 40,
'maxlength' => 255,
'placeholder' => ts('Description'),
));
if (!empty($tags)) {
$form->add('select', "tag_$i", ts('Tags'), $tags, FALSE,
array(
'id' => "tags_$i",
'multiple' => 'multiple',
'class' => 'huge crm-select2',
'placeholder' => ts('- none -'),
)
);
}
CRM_Core_Form_Tag::buildQuickForm($form, $parentNames, 'civicrm_file', NULL, FALSE, TRUE, "file_taglist_$i");
}
}
/**
* Return a clean url string and the number of attachment for a
* given entityTable, entityID
*
* @param string $entityTable
* The entityTable to which the file is attached.
* @param int $entityID
* The id of the object in the above entityTable.
* @param string $separator
* The string separator where to implode the urls.
*
* @return array
* An array with 2 elements. The string and the number of attachments
*/
public static function attachmentInfo($entityTable, $entityID, $separator = '<br />') {
if (!$entityID) {
return NULL;
}
$currentAttachments = self::getEntityFile($entityTable, $entityID);
if (!empty($currentAttachments)) {
$currentAttachmentURL = array();
foreach ($currentAttachments as $fileID => $attach) {
$currentAttachmentURL[] = $attach['href'];
}
return implode($separator, $currentAttachmentURL);
}
return NULL;
}
/**
* @param $formValues
* @param array $params
* @param $entityTable
* @param int $entityID
*/
public static function formatAttachment(
&$formValues,
&$params,
$entityTable,
$entityID = NULL
) {
// delete current attachments if applicable
if ($entityID && !empty($formValues['is_delete_attachment'])) {
CRM_Core_BAO_File::deleteEntityFile($entityTable, $entityID);
}
$numAttachments = Civi::settings()->get('max_attachments');
// setup all attachments
for ($i = 1; $i <= $numAttachments; $i++) {
$attachName = "attachFile_$i";
$attachDesc = "attachDesc_$i";
$attachTags = "tag_$i";
$attachFreeTags = "file_taglist_$i";
if (isset($formValues[$attachName]) && !empty($formValues[$attachName])) {
// add static tags if selects
$tagParams = array();
if (!empty($formValues[$attachTags])) {
foreach ($formValues[$attachTags] as $tag) {
$tagParams[$tag] = 1;
}
}
// we dont care if the file is empty or not
// CRM-7448
$extraParams = array(
'description' => $formValues[$attachDesc],
'tag' => $tagParams,
'attachment_taglist' => CRM_Utils_Array::value($attachFreeTags, $formValues, array()),
);
CRM_Utils_File::formatFile($formValues, $attachName, $extraParams);
// set the formatted attachment attributes to $params, later used by
// CRM_Activity_BAO_Activity::sendEmail(...) to send mail with desired attachments
if (!empty($formValues[$attachName])) {
$params[$attachName] = $formValues[$attachName];
}
}
}
}
/**
* @param array $params
* @param $entityTable
* @param int $entityID
*/
public static function processAttachment(&$params, $entityTable, $entityID) {
$numAttachments = Civi::settings()->get('max_attachments');
for ($i = 1; $i <= $numAttachments; $i++) {
if (
isset($params["attachFile_$i"]) &&
is_array($params["attachFile_$i"])
) {
self::filePostProcess(
$params["attachFile_$i"]['location'],
NULL,
$entityTable,
$entityID,
NULL,
TRUE,
$params["attachFile_$i"],
"attachFile_$i",
$params["attachFile_$i"]['type']
);
}
}
}
/**
* @return array
*/
public static function uploadNames() {
$numAttachments = Civi::settings()->get('max_attachments');
$names = array();
for ($i = 1; $i <= $numAttachments; $i++) {
$names[] = "attachFile_{$i}";
}
$names[] = 'uploadFile';
return $names;
}
/**
* copy/attach an existing file to a different entity
* table and id.
*
* @param $oldEntityTable
* @param int $oldEntityId
* @param $newEntityTable
* @param int $newEntityId
*/
public static function copyEntityFile($oldEntityTable, $oldEntityId, $newEntityTable, $newEntityId) {
$oldEntityFile = new CRM_Core_DAO_EntityFile();
$oldEntityFile->entity_id = $oldEntityId;
$oldEntityFile->entity_table = $oldEntityTable;
$oldEntityFile->find();
while ($oldEntityFile->fetch()) {
$newEntityFile = new CRM_Core_DAO_EntityFile();
$newEntityFile->entity_id = $newEntityId;
$newEntityFile->entity_table = $newEntityTable;
$newEntityFile->file_id = $oldEntityFile->file_id;
$newEntityFile->save();
}
}
/**
* @param $entityTable
* @param int $entityID
* @param int $fileID
*
* @return string
*/
public static function deleteURLArgs($entityTable, $entityID, $fileID) {
$params['entityTable'] = $entityTable;
$params['entityID'] = $entityID;
$params['fileID'] = $fileID;
$signer = new CRM_Utils_Signer(CRM_Core_Key::privateKey(), self::$_signableFields);
$params['_sgn'] = $signer->sign($params);
return CRM_Utils_System::makeQueryString($params);
}
/**
* Delete a file attachment from an entity table / entity ID
*
*/
public static function deleteAttachment() {
$params = array();
$params['entityTable'] = CRM_Utils_Request::retrieve('entityTable', 'String', CRM_Core_DAO::$_nullObject, TRUE);
$params['entityID'] = CRM_Utils_Request::retrieve('entityID', 'Positive', CRM_Core_DAO::$_nullObject, TRUE);
$params['fileID'] = CRM_Utils_Request::retrieve('fileID', 'Positive', CRM_Core_DAO::$_nullObject, TRUE);
$signature = CRM_Utils_Request::retrieve('_sgn', 'String', CRM_Core_DAO::$_nullObject, TRUE);
$signer = new CRM_Utils_Signer(CRM_Core_Key::privateKey(), self::$_signableFields);
if (!$signer->validate($signature, $params)) {
CRM_Core_Error::fatal('Request signature is invalid');
}
self::deleteEntityFile($params['entityTable'], $params['entityID'], NULL, $params['fileID']);
}
/**
* Display paper icon for a file attachment -- CRM-13624
*
* @param string $entityTable
* The entityTable to which the file is attached. eg "civicrm_contact", "civicrm_note", "civicrm_activity".
* If you have the ID of a specific row in civicrm_file, use $entityTable='*'
* @param int $entityID
* The id of the object in the above entityTable.
*
* @return array|NULL
* list of HTML snippets; one HTML snippet for each attachment. If none found, then NULL
*
*/
public static function paperIconAttachment($entityTable, $entityID) {
if (empty($entityTable) || !$entityID) {
$results = NULL;
return $results;
}
$currentAttachmentInfo = self::getEntityFile($entityTable, $entityID);
foreach ($currentAttachmentInfo as $fileKey => $fileValue) {
$fileID = $fileValue['fileID'];
if ($fileID) {
$fileType = $fileValue['mime_type'];
$url = $fileValue['url'];
$title = $fileValue['cleanName'];
if ($fileType == 'image/jpeg' ||
$fileType == 'image/pjpeg' ||
$fileType == 'image/gif' ||
$fileType == 'image/x-png' ||
$fileType == 'image/png'
) {
$file_url[$fileID] = "
<a href='$url' class='crm-image-popup' title='$title'>
<i class='crm-i fa-file-image-o'></i>
</a>";
}
// for non image files
else {
$file_url[$fileID] = "
<a href='$url' title='$title'>
<i class='crm-i fa-paperclip'></i>
</a>";
}
}
}
if (empty($file_url)) {
$results = NULL;
}
else {
$results = $file_url;
}
return $results;
}
/**
* Get a reference to the file-search service (if one is available).
*
* @return CRM_Core_FileSearchInterface|NULL
*/
public static function getSearchService() {
$fileSearches = array();
CRM_Utils_Hook::fileSearches($fileSearches);
// use the first available search
foreach ($fileSearches as $fileSearch) {
/** @var $fileSearch CRM_Core_FileSearchInterface */
return $fileSearch;
}
return NULL;
}
}

View file

@ -0,0 +1,775 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_Core_BAO_FinancialTrxn extends CRM_Financial_DAO_FinancialTrxn {
/**
* Class constructor.
*
* @return \CRM_Financial_DAO_FinancialTrxn
*/
/**
*/
public function __construct() {
parent::__construct();
}
/**
* Takes an associative array and creates a financial transaction object.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
*
* @return CRM_Core_BAO_FinancialTrxn
*/
public static function create($params) {
$trxn = new CRM_Financial_DAO_FinancialTrxn();
$trxn->copyValues($params);
if (empty($params['id']) && !CRM_Utils_Rule::currencyCode($trxn->currency)) {
$trxn->currency = CRM_Core_Config::singleton()->defaultCurrency;
}
$trxn->save();
if (!empty($params['id'])) {
// For an update entity financial transaction record will already exist. Return early.
return $trxn;
}
// Save to entity_financial_trxn table.
$entityFinancialTrxnParams = array(
'entity_table' => CRM_Utils_Array::value('entity_table', $params, 'civicrm_contribution'),
'entity_id' => CRM_Utils_Array::value('entity_id', $params, CRM_Utils_Array::value('contribution_id', $params)),
'financial_trxn_id' => $trxn->id,
'amount' => $params['total_amount'],
);
$entityTrxn = new CRM_Financial_DAO_EntityFinancialTrxn();
$entityTrxn->copyValues($entityFinancialTrxnParams);
$entityTrxn->save();
return $trxn;
}
/**
* @param int $contributionId
* @param int $contributionFinancialTypeId
*
* @return array
*/
public static function getBalanceTrxnAmt($contributionId, $contributionFinancialTypeId = NULL) {
if (!$contributionFinancialTypeId) {
$contributionFinancialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'financial_type_id');
}
$toFinancialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($contributionFinancialTypeId, 'Accounts Receivable Account is');
$q = "SELECT ft.id, ft.total_amount FROM civicrm_financial_trxn ft INNER JOIN civicrm_entity_financial_trxn eft ON (eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution') WHERE eft.entity_id = %1 AND ft.to_financial_account_id = %2";
$p[1] = array($contributionId, 'Integer');
$p[2] = array($toFinancialAccount, 'Integer');
$balanceAmtDAO = CRM_Core_DAO::executeQuery($q, $p);
$ret = array();
if ($balanceAmtDAO->N) {
$ret['total_amount'] = 0;
}
while ($balanceAmtDAO->fetch()) {
$ret['trxn_id'] = $balanceAmtDAO->id;
$ret['total_amount'] += $balanceAmtDAO->total_amount;
}
return $ret;
}
/**
* Fetch object based on array of properties.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $defaults
* (reference ) an assoc array to hold the flattened values.
*
* @return CRM_Contribute_BAO_ContributionType
*/
public static function retrieve(&$params, &$defaults) {
$financialItem = new CRM_Financial_DAO_FinancialTrxn();
$financialItem->copyValues($params);
if ($financialItem->find(TRUE)) {
CRM_Core_DAO::storeValues($financialItem, $defaults);
return $financialItem;
}
return NULL;
}
/**
* Given an entity_id and entity_table, check for corresponding entity_financial_trxn and financial_trxn record.
* NOTE: This should be moved to separate BAO for EntityFinancialTrxn when we start adding more code for that object.
*
* @param $entity_id
* Id of the entity usually the contributionID.
* @param string $orderBy
* To get single trxn id for a entity table i.e last or first.
* @param bool $newTrxn
* @param string $whereClause
* Additional where parameters
*
* @return array
* array of category id's the contact belongs to.
*
*/
public static function getFinancialTrxnId($entity_id, $orderBy = 'ASC', $newTrxn = FALSE, $whereClause = '', $fromAccountID = NULL) {
$ids = array('entityFinancialTrxnId' => NULL, 'financialTrxnId' => NULL);
$params = array(1 => array($entity_id, 'Integer'));
$condition = "";
if (!$newTrxn) {
$condition = " AND ((ceft1.entity_table IS NOT NULL) OR (cft.payment_instrument_id IS NOT NULL AND ceft1.entity_table IS NULL)) ";
}
if ($fromAccountID) {
$condition .= " AND (cft.from_financial_account_id <> %2 OR cft.from_financial_account_id IS NULL)";
$params[2] = array($fromAccountID, 'Integer');
}
if ($orderBy) {
$orderBy = CRM_Utils_Type::escape($orderBy, 'String');
}
$query = "SELECT ceft.id, ceft.financial_trxn_id, cft.trxn_id FROM `civicrm_financial_trxn` cft
LEFT JOIN civicrm_entity_financial_trxn ceft
ON ceft.financial_trxn_id = cft.id AND ceft.entity_table = 'civicrm_contribution'
LEFT JOIN civicrm_entity_financial_trxn ceft1
ON ceft1.financial_trxn_id = cft.id AND ceft1.entity_table = 'civicrm_financial_item'
LEFT JOIN civicrm_financial_item cfi ON ceft1.entity_table = 'civicrm_financial_item' and cfi.id = ceft1.entity_id
WHERE ceft.entity_id = %1 AND (cfi.entity_table <> 'civicrm_financial_trxn' or cfi.entity_table is NULL)
{$condition}
{$whereClause}
ORDER BY cft.id {$orderBy}
LIMIT 1;";
$dao = CRM_Core_DAO::executeQuery($query, $params);
if ($dao->fetch()) {
$ids['entityFinancialTrxnId'] = $dao->id;
$ids['financialTrxnId'] = $dao->financial_trxn_id;
$ids['trxn_id'] = $dao->trxn_id;
}
return $ids;
}
/**
* Get the transaction id for the (latest) refund associated with a contribution.
*
* @param int $contributionID
* @return string
*/
public static function getRefundTransactionTrxnID($contributionID) {
$ids = self::getRefundTransactionIDs($contributionID);
return isset($ids['trxn_id']) ? $ids['trxn_id'] : NULL;
}
/**
* Get the transaction id for the (latest) refund associated with a contribution.
*
* @param int $contributionID
* @return string
*/
public static function getRefundTransactionIDs($contributionID) {
$refundStatusID = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Refunded');
return self::getFinancialTrxnId($contributionID, 'DESC', FALSE, " AND cft.status_id = $refundStatusID");
}
/**
* Given an entity_id and entity_table, check for corresponding entity_financial_trxn and financial_trxn record.
* @todo This should be moved to separate BAO for EntityFinancialTrxn when we start adding more code for that object.
*
* @param int $entity_id
* Id of the entity usually the contactID.
*
* @return array
* array of category id's the contact belongs to.
*
*/
public static function getFinancialTrxnTotal($entity_id) {
$query = "
SELECT (ft.amount+SUM(ceft.amount)) AS total FROM civicrm_entity_financial_trxn AS ft
LEFT JOIN civicrm_entity_financial_trxn AS ceft ON ft.financial_trxn_id = ceft.entity_id
WHERE ft.entity_table = 'civicrm_contribution' AND ft.entity_id = %1
";
$sqlParams = array(1 => array($entity_id, 'Integer'));
return CRM_Core_DAO::singleValueQuery($query, $sqlParams);
}
/**
* Given an financial_trxn_id check for previous entity_financial_trxn.
*
* @param $financial_trxn_id
* Id of the latest payment.
*
*
* @return array
* array of previous payments
*
*/
public static function getPayments($financial_trxn_id) {
$query = "
SELECT ef1.financial_trxn_id, sum(ef1.amount) amount
FROM civicrm_entity_financial_trxn ef1
LEFT JOIN civicrm_entity_financial_trxn ef2 ON ef1.financial_trxn_id = ef2.entity_id
WHERE ef2.financial_trxn_id =%1
AND ef2.entity_table = 'civicrm_financial_trxn'
AND ef1.entity_table = 'civicrm_financial_item'
GROUP BY ef1.financial_trxn_id
UNION
SELECT ef1.financial_trxn_id, ef1.amount
FROM civicrm_entity_financial_trxn ef1
LEFT JOIN civicrm_entity_financial_trxn ef2 ON ef1.entity_id = ef2.entity_id
WHERE ef2.financial_trxn_id =%1
AND ef2.entity_table = 'civicrm_financial_trxn'
AND ef1.entity_table = 'civicrm_financial_trxn'";
$sqlParams = array(1 => array($financial_trxn_id, 'Integer'));
$dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
$i = 0;
$result = array();
while ($dao->fetch()) {
$result[$i]['financial_trxn_id'] = $dao->financial_trxn_id;
$result[$i]['amount'] = $dao->amount;
$i++;
}
if (empty($result)) {
$query = "SELECT sum( amount ) amount FROM civicrm_entity_financial_trxn WHERE financial_trxn_id =%1 AND entity_table = 'civicrm_financial_item'";
$sqlParams = array(1 => array($financial_trxn_id, 'Integer'));
$dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
if ($dao->fetch()) {
$result[0]['financial_trxn_id'] = $financial_trxn_id;
$result[0]['amount'] = $dao->amount;
}
}
return $result;
}
/**
* Given an entity_id and entity_table, check for corresponding entity_financial_trxn and financial_trxn record.
* NOTE: This should be moved to separate BAO for EntityFinancialTrxn when we start adding more code for that object.
*
* @param $entity_id
* Id of the entity usually the contactID.
* @param string $entity_table
* Name of the entity table usually 'civicrm_contact'.
*
* @return array
* array of category id's the contact belongs to.
*
*/
public static function getFinancialTrxnLineTotal($entity_id, $entity_table = 'civicrm_contribution') {
$query = "SELECT lt.price_field_value_id AS id, ft.financial_trxn_id,ft.amount AS amount FROM civicrm_entity_financial_trxn AS ft
LEFT JOIN civicrm_financial_item AS fi ON fi.id = ft.entity_id AND fi.entity_table = 'civicrm_line_item' AND ft.entity_table = 'civicrm_financial_item'
LEFT JOIN civicrm_line_item AS lt ON lt.id = fi.entity_id AND lt.entity_table = %2
WHERE lt.entity_id = %1 ";
$sqlParams = array(1 => array($entity_id, 'Integer'), 2 => array($entity_table, 'String'));
$dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
while ($dao->fetch()) {
$result[$dao->financial_trxn_id][$dao->id] = $dao->amount;
}
if (!empty($result)) {
return $result;
}
else {
return NULL;
}
}
/**
* Delete financial transaction.
*
* @param int $entity_id
* @return bool
* TRUE on success, FALSE otherwise.
*/
public static function deleteFinancialTrxn($entity_id) {
$query = "DELETE ceft1, cfi, ceft, cft FROM `civicrm_financial_trxn` cft
LEFT JOIN civicrm_entity_financial_trxn ceft
ON ceft.financial_trxn_id = cft.id AND ceft.entity_table = 'civicrm_contribution'
LEFT JOIN civicrm_entity_financial_trxn ceft1
ON ceft1.financial_trxn_id = cft.id AND ceft1.entity_table = 'civicrm_financial_item'
LEFT JOIN civicrm_financial_item cfi
ON ceft1.entity_table = 'civicrm_financial_item' and cfi.id = ceft1.entity_id
WHERE ceft.entity_id = %1";
CRM_Core_DAO::executeQuery($query, array(1 => array($entity_id, 'Integer')));
return TRUE;
}
/**
* Create financial transaction for premium.
*
* @param array $params
* - oldPremium
* - financial_type_id
* - contributionId
* - isDeleted
* - cost
* - currency
*/
public static function createPremiumTrxn($params) {
if ((empty($params['financial_type_id']) || empty($params['contributionId'])) && empty($params['oldPremium'])) {
return;
}
if (!empty($params['cost'])) {
$contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
$toFinancialAccountType = !empty($params['isDeleted']) ? 'Premiums Inventory Account is' : 'Cost of Sales Account is';
$fromFinancialAccountType = !empty($params['isDeleted']) ? 'Cost of Sales Account is' : 'Premiums Inventory Account is';
$accountRelationship = array_flip($accountRelationship);
$financialtrxn = array(
'to_financial_account_id' => CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($params['financial_type_id'], $toFinancialAccountType),
'from_financial_account_id' => CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($params['financial_type_id'], $fromFinancialAccountType),
'trxn_date' => date('YmdHis'),
'total_amount' => CRM_Utils_Array::value('cost', $params) ? $params['cost'] : 0,
'currency' => CRM_Utils_Array::value('currency', $params),
'status_id' => array_search('Completed', $contributionStatuses),
'entity_table' => 'civicrm_contribution',
'entity_id' => $params['contributionId'],
);
CRM_Core_BAO_FinancialTrxn::create($financialtrxn);
}
if (!empty($params['oldPremium'])) {
$premiumParams = array(
'id' => $params['oldPremium']['product_id'],
);
$productDetails = array();
CRM_Contribute_BAO_ManagePremiums::retrieve($premiumParams, $productDetails);
$params = array(
'cost' => CRM_Utils_Array::value('cost', $productDetails),
'currency' => CRM_Utils_Array::value('currency', $productDetails),
'financial_type_id' => CRM_Utils_Array::value('financial_type_id', $productDetails),
'contributionId' => $params['oldPremium']['contribution_id'],
'isDeleted' => TRUE,
);
CRM_Core_BAO_FinancialTrxn::createPremiumTrxn($params);
}
}
/**
* Create financial trxn and items when fee is charged.
*
* @param array $params
* To create trxn entries.
*
* @return bool
*/
public static function recordFees($params) {
$domainId = CRM_Core_Config::domainID();
$amount = 0;
if (!empty($params['prevContribution'])) {
$amount = $params['prevContribution']->fee_amount;
}
$amount = $params['fee_amount'] - $amount;
if (!$amount) {
return FALSE;
}
$contributionId = isset($params['contribution']->id) ? $params['contribution']->id : $params['contribution_id'];
if (empty($params['financial_type_id'])) {
$financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id', 'id');
}
else {
$financialTypeId = $params['financial_type_id'];
}
$financialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($financialTypeId, 'Expense Account is');
$params['trxnParams']['from_financial_account_id'] = $params['to_financial_account_id'];
$params['trxnParams']['to_financial_account_id'] = $financialAccount;
$params['trxnParams']['total_amount'] = $amount;
$params['trxnParams']['fee_amount'] = $params['trxnParams']['net_amount'] = 0;
$params['trxnParams']['status_id'] = $params['contribution_status_id'];
$params['trxnParams']['contribution_id'] = $contributionId;
$params['trxnParams']['is_payment'] = FALSE;
$trxn = self::create($params['trxnParams']);
if (empty($params['entity_id'])) {
$financialTrxnID = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['trxnParams']['contribution_id'], 'DESC');
$params['entity_id'] = $financialTrxnID['financialTrxnId'];
}
$fItemParams
= array(
'financial_account_id' => $financialAccount,
'contact_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain', $domainId, 'contact_id'),
'created_date' => date('YmdHis'),
'transaction_date' => date('YmdHis'),
'amount' => $amount,
'description' => 'Fee',
'status_id' => CRM_Core_Pseudoconstant::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'),
'entity_table' => 'civicrm_financial_trxn',
'entity_id' => $params['entity_id'],
'currency' => $params['trxnParams']['currency'],
);
$trxnIDS['id'] = $trxn->id;
CRM_Financial_BAO_FinancialItem::create($fItemParams, NULL, $trxnIDS);
}
/**
* get partial payment amount and type of it.
*
* @param int $entityId
* @param string $entityName
* @param bool $returnType
* @param int $lineItemTotal
*
* @return array|int|NULL|string
* [payment type => amount]
* payment type: 'amount_owed' or 'refund_due'
*/
public static function getPartialPaymentWithType($entityId, $entityName = 'participant', $returnType = TRUE, $lineItemTotal = NULL) {
$value = NULL;
if (empty($entityName)) {
return $value;
}
if ($entityName == 'participant') {
$contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $entityId, 'contribution_id', 'participant_id');
}
elseif ($entityName == 'membership') {
$contributionId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $entityId, 'contribution_id', 'membership_id');
}
else {
$contributionId = $entityId;
}
$financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
if ($contributionId && $financialTypeId) {
$statusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
$refundStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Refunded');
if (empty($lineItemTotal)) {
$lineItemTotal = CRM_Price_BAO_LineItem::getLineTotal($contributionId);
}
$sqlFtTotalAmt = "
SELECT SUM(ft.total_amount)
FROM civicrm_financial_trxn ft
INNER JOIN civicrm_entity_financial_trxn eft ON (ft.id = eft.financial_trxn_id AND eft.entity_table = 'civicrm_contribution' AND eft.entity_id = {$contributionId})
WHERE ft.is_payment = 1
AND ft.status_id IN ({$statusId}, {$refundStatusId})
";
$ftTotalAmt = CRM_Core_DAO::singleValueQuery($sqlFtTotalAmt);
$value = 0;
if (!$ftTotalAmt) {
$ftTotalAmt = 0;
}
$value = $paymentVal = $lineItemTotal - $ftTotalAmt;
if ($returnType) {
$value = array();
if ($paymentVal < 0) {
$value['refund_due'] = $paymentVal;
}
elseif ($paymentVal > 0) {
$value['amount_owed'] = $paymentVal;
}
elseif ($lineItemTotal == $ftTotalAmt) {
$value['full_paid'] = $ftTotalAmt;
}
}
}
return $value;
}
/**
* @param int $contributionId
*
* @return array
*/
public static function getTotalPayments($contributionId) {
$statusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
$sql = "SELECT SUM(ft.total_amount) FROM civicrm_financial_trxn ft
INNER JOIN civicrm_entity_financial_trxn eft ON (eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution')
WHERE eft.entity_id = %1 AND ft.is_payment = 1 AND ft.status_id = %2";
$params = array(
1 => array($contributionId, 'Integer'),
2 => array($statusId, 'Integer'),
);
return CRM_Core_DAO::singleValueQuery($sql, $params);
}
/**
* Function records partial payment, complete's contribution if payment is fully paid
* and returns latest payment ie financial trxn
*
* @param array $contribution
* @param array $params
*
* @return CRM_Core_BAO_FinancialTrxn
*/
public static function getPartialPaymentTrxn($contribution, $params) {
$trxn = CRM_Contribute_BAO_Contribution::recordPartialPayment($contribution, $params);
$paid = CRM_Core_BAO_FinancialTrxn::getTotalPayments($params['contribution_id']);
$total = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution_id'], 'total_amount');
$cmp = bccomp($total, $paid, 5);
if ($cmp == 0 || $cmp == -1) {// If paid amount is greater or equal to total amount
civicrm_api3('Contribution', 'completetransaction', array('id' => $contribution['id']));
}
return $trxn;
}
/**
* Get revenue amount for membership.
*
* @param array $lineItem
*
* @return array
*/
public static function getMembershipRevenueAmount($lineItem) {
$revenueAmount = array();
$membershipDetail = civicrm_api3('Membership', 'getsingle', array(
'id' => $lineItem['entity_id'],
));
if (empty($membershipDetail['end_date'])) {
return $revenueAmount;
}
$startDate = strtotime($membershipDetail['start_date']);
$endDate = strtotime($membershipDetail['end_date']);
$startYear = date('Y', $startDate);
$endYear = date('Y', $endDate);
$startMonth = date('m', $startDate);
$endMonth = date('m', $endDate);
$monthOfService = (($endYear - $startYear) * 12) + ($endMonth - $startMonth);
$startDateOfRevenue = $membershipDetail['start_date'];
$typicalPayment = round(($lineItem['line_total'] / $monthOfService), 2);
for ($i = 0; $i <= $monthOfService - 1; $i++) {
$revenueAmount[$i]['amount'] = $typicalPayment;
if ($i == 0) {
$revenueAmount[$i]['amount'] -= (($typicalPayment * $monthOfService) - $lineItem['line_total']);
}
$revenueAmount[$i]['revenue_date'] = $startDateOfRevenue;
$startDateOfRevenue = date('Y-m', strtotime('+1 month', strtotime($startDateOfRevenue))) . '-01';
}
return $revenueAmount;
}
/**
* Create transaction for deferred revenue.
*
* @param array $lineItems
*
* @param CRM_Contribute_BAO_Contribution $contributionDetails
*
* @param bool $update
*
* @param string $context
*
*/
public static function createDeferredTrxn($lineItems, $contributionDetails, $update = FALSE, $context = NULL) {
if (empty($lineItems)) {
return;
}
$revenueRecognitionDate = $contributionDetails->revenue_recognition_date;
if (!CRM_Utils_System::isNull($revenueRecognitionDate)) {
$statuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
if (!$update
&& (CRM_Utils_Array::value($contributionDetails->contribution_status_id, $statuses) != 'Completed'
|| (CRM_Utils_Array::value($contributionDetails->contribution_status_id, $statuses) != 'Pending'
&& $contributionDetails->is_pay_later)
)
) {
return;
}
$trxnParams = array(
'contribution_id' => $contributionDetails->id,
'fee_amount' => '0.00',
'currency' => $contributionDetails->currency,
'trxn_id' => $contributionDetails->trxn_id,
'status_id' => $contributionDetails->contribution_status_id,
'payment_instrument_id' => $contributionDetails->payment_instrument_id,
'check_number' => $contributionDetails->check_number,
);
$deferredRevenues = array();
foreach ($lineItems as $priceSetID => $lineItem) {
if (!$priceSetID) {
continue;
}
foreach ($lineItem as $key => $item) {
$lineTotal = !empty($item['deferred_line_total']) ? $item['deferred_line_total'] : $item['line_total'];
if ($lineTotal <= 0 && !$update) {
continue;
}
$deferredRevenues[$key] = $item;
if ($context == 'changeFinancialType') {
$deferredRevenues[$key]['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_LineItem', $item['id'], 'financial_type_id');
}
if (in_array($item['entity_table'],
array('civicrm_participant', 'civicrm_contribution'))
) {
$deferredRevenues[$key]['revenue'][] = array(
'amount' => $lineTotal,
'revenue_date' => $revenueRecognitionDate,
);
}
else {
// for membership
$item['line_total'] = $lineTotal;
$deferredRevenues[$key]['revenue'] = self::getMembershipRevenueAmount($item);
}
}
}
$accountRel = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
CRM_Utils_Hook::alterDeferredRevenueItems($deferredRevenues, $contributionDetails, $update, $context);
foreach ($deferredRevenues as $key => $deferredRevenue) {
$results = civicrm_api3('EntityFinancialAccount', 'get', array(
'entity_table' => 'civicrm_financial_type',
'entity_id' => $deferredRevenue['financial_type_id'],
'account_relationship' => array('IN' => array('Income Account is', 'Deferred Revenue Account is')),
));
if ($results['count'] != 2) {
continue;
}
foreach ($results['values'] as $result) {
if ($result['account_relationship'] == $accountRel) {
$trxnParams['from_financial_account_id'] = $result['financial_account_id'];
}
else {
$trxnParams['to_financial_account_id'] = $result['financial_account_id'];
}
}
foreach ($deferredRevenue['revenue'] as $revenue) {
$trxnParams['total_amount'] = $trxnParams['net_amount'] = $revenue['amount'];
$trxnParams['trxn_date'] = CRM_Utils_Date::isoToMysql($revenue['revenue_date']);
$financialTxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
$entityParams = array(
'entity_id' => $deferredRevenue['financial_item_id'],
'entity_table' => 'civicrm_financial_item',
'amount' => $revenue['amount'],
'financial_trxn_id' => $financialTxn->id,
);
civicrm_api3('EntityFinancialTrxn', 'create', $entityParams);
}
}
}
}
/**
* Update Credit Card Details in civicrm_financial_trxn table.
*
* @param int $contributionID
* @param int $panTruncation
* @param int $cardType
*
*/
public static function updateCreditCardDetails($contributionID, $panTruncation, $cardType) {
$financialTrxn = civicrm_api3('EntityFinancialTrxn', 'get', array(
'return' => array('financial_trxn_id.payment_processor_id', 'financial_trxn_id'),
'entity_table' => 'civicrm_contribution',
'entity_id' => $contributionID,
'financial_trxn_id.is_payment' => TRUE,
'options' => array('sort' => 'financial_trxn_id DESC', 'limit' => 1),
));
// In case of Contribution status is Pending From Incomplete Transaction or Failed there is no Financial Entries created for Contribution.
// Above api will return 0 count, in such case we won't update card type and pan truncation field.
if (!$financialTrxn['count']) {
return NULL;
}
$financialTrxn = $financialTrxn['values'][$financialTrxn['id']];
$paymentProcessorID = CRM_Utils_Array::value('financial_trxn_id.payment_processor_id', $financialTrxn);
if ($paymentProcessorID) {
return NULL;
}
$financialTrxnId = $financialTrxn['financial_trxn_id'];
$trxnparams = array('id' => $financialTrxnId);
if (isset($cardType)) {
$trxnparams['card_type_id'] = $cardType;
}
if (isset($panTruncation)) {
$trxnparams['pan_truncation'] = $panTruncation;
}
civicrm_api3('FinancialTrxn', 'create', $trxnparams);
}
/**
* The function is responsible for handling financial entries if payment instrument is changed
*
* @param array $inputParams
*
*/
public static function updateFinancialAccountsOnPaymentInstrumentChange($inputParams) {
$prevContribution = $inputParams['prevContribution'];
$currentContribution = $inputParams['contribution'];
// ensure that there are all the information in updated contribution object identified by $currentContribution
$currentContribution->find(TRUE);
$deferredFinancialAccount = CRM_Utils_Array::value('deferred_financial_account_id', $inputParams);
if (empty($deferredFinancialAccount)) {
$deferredFinancialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($prevContribution->financial_type_id, 'Deferred Revenue Account is');
}
$lastFinancialTrxnId = self::getFinancialTrxnId($prevContribution->id, 'DESC', FALSE, NULL, $deferredFinancialAccount);
// there is no point to proceed as we can't find the last payment made
// @todo we should throw an exception here rather than return false.
if (empty($lastFinancialTrxnId['financialTrxnId'])) {
return FALSE;
}
// If payment instrument is changed reverse the last payment
// in terms of reversing financial item and trxn
$lastFinancialTrxn = civicrm_api3('FinancialTrxn', 'getsingle', array('id' => $lastFinancialTrxnId['financialTrxnId']));
unset($lastFinancialTrxn['id']);
$lastFinancialTrxn['trxn_date'] = $inputParams['trxnParams']['trxn_date'];
$lastFinancialTrxn['total_amount'] = -$inputParams['trxnParams']['total_amount'];
$lastFinancialTrxn['net_amount'] = -$inputParams['trxnParams']['net_amount'];
$lastFinancialTrxn['fee_amount'] = -$inputParams['trxnParams']['fee_amount'];
$lastFinancialTrxn['contribution_id'] = $prevContribution->id;
foreach (array($lastFinancialTrxn, $inputParams['trxnParams']) as $financialTrxnParams) {
$trxn = CRM_Core_BAO_FinancialTrxn::create($financialTrxnParams);
$trxnParams = array(
'total_amount' => $trxn->total_amount,
'contribution_id' => $currentContribution->id,
);
CRM_Contribute_BAO_Contribution::assignProportionalLineItems($trxnParams, $trxn->id, $prevContribution->total_amount);
}
self::createDeferredTrxn(CRM_Utils_Array::value('line_item', $inputParams), $currentContribution, TRUE, 'changePaymentInstrument');
return TRUE;
}
}

View file

@ -0,0 +1,177 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class contain function for IM handling
*/
class CRM_Core_BAO_IM extends CRM_Core_DAO_IM {
/**
* Takes an associative array and adds im.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
*
* @return object
* CRM_Core_BAO_IM object on success, null otherwise
*/
public static function add(&$params) {
$hook = empty($params['id']) ? 'create' : 'edit';
CRM_Utils_Hook::pre($hook, 'IM', CRM_Utils_Array::value('id', $params), $params);
$im = new CRM_Core_DAO_IM();
$im->copyValues($params);
$im->save();
CRM_Utils_Hook::post($hook, 'IM', $im->id, $im);
return $im;
}
/**
* Given the list of params in the params array, fetch the object
* and store the values in the values array
*
* @param array $entityBlock input parameters to find object
*
* @return bool
*/
public static function &getValues($entityBlock) {
return CRM_Core_BAO_Block::getValues('im', $entityBlock);
}
/**
* Get all the ims for a specified contact_id, with the primary im being first
*
* @param int $id
* The contact id.
*
* @param bool $updateBlankLocInfo
*
* @return array
* the array of im details
*/
public static function allIMs($id, $updateBlankLocInfo = FALSE) {
if (!$id) {
return NULL;
}
$query = "
SELECT civicrm_im.name as im, civicrm_location_type.name as locationType, civicrm_im.is_primary as is_primary,
civicrm_im.id as im_id, civicrm_im.location_type_id as locationTypeId,
civicrm_im.provider_id as providerId
FROM civicrm_contact
LEFT JOIN civicrm_im ON ( civicrm_im.contact_id = civicrm_contact.id )
LEFT JOIN civicrm_location_type ON ( civicrm_im.location_type_id = civicrm_location_type.id )
WHERE
civicrm_contact.id = %1
ORDER BY
civicrm_im.is_primary DESC, im_id ASC ";
$params = array(1 => array($id, 'Integer'));
$ims = $values = array();
$dao = CRM_Core_DAO::executeQuery($query, $params);
$count = 1;
while ($dao->fetch()) {
$values = array(
'locationType' => $dao->locationType,
'is_primary' => $dao->is_primary,
'id' => $dao->im_id,
'name' => $dao->im,
'locationTypeId' => $dao->locationTypeId,
'providerId' => $dao->providerId,
);
if ($updateBlankLocInfo) {
$ims[$count++] = $values;
}
else {
$ims[$dao->im_id] = $values;
}
}
return $ims;
}
/**
* Get all the ims for a specified location_block id, with the primary im being first
*
* @param array $entityElements
* The array containing entity_id and.
* entity_table name
*
* @return array
* the array of im details
*/
public static function allEntityIMs(&$entityElements) {
if (empty($entityElements)) {
return NULL;
}
$entityId = $entityElements['entity_id'];
$entityTable = $entityElements['entity_table'];
$sql = "SELECT cim.name as im, ltype.name as locationType, cim.is_primary as is_primary, cim.id as im_id, cim.location_type_id as locationTypeId
FROM civicrm_loc_block loc, civicrm_im cim, civicrm_location_type ltype, {$entityTable} ev
WHERE ev.id = %1
AND loc.id = ev.loc_block_id
AND cim.id IN (loc.im_id, loc.im_2_id)
AND ltype.id = cim.location_type_id
ORDER BY cim.is_primary DESC, im_id ASC ";
$params = array(1 => array($entityId, 'Integer'));
$ims = array();
$dao = CRM_Core_DAO::executeQuery($sql, $params);
while ($dao->fetch()) {
$ims[$dao->im_id] = array(
'locationType' => $dao->locationType,
'is_primary' => $dao->is_primary,
'id' => $dao->im_id,
'name' => $dao->im,
'locationTypeId' => $dao->locationTypeId,
);
}
return $ims;
}
/**
* Call common delete function.
*
* @param int $id
*
* @return bool
*/
public static function del($id) {
return CRM_Contact_BAO_Contact::deleteObjectWithPrimary('IM', $id);
}
}

View file

@ -0,0 +1,149 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id: $
*
*/
/**
* This class contains scheduled jobs related functions.
*/
class CRM_Core_BAO_Job extends CRM_Core_DAO_Job {
/**
* Class constructor.
*/
public function __construct() {
parent::__construct();
}
/**
* Add the payment-processor type in the db
*
* @param array $params
* An assoc array of name/value pairs.
*
* @return CRM_Financial_DAO_PaymentProcessorType
*/
public static function create($params) {
$job = new CRM_Core_DAO_Job();
$job->copyValues($params);
return $job->save();
}
/**
* Retrieve DB object based on input parameters.
*
* It also stores all the retrieved values in the default array.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $defaults
* (reference ) an assoc array to hold the flattened values.
*
* @return CRM_Core_DAO_Job|null
* object on success, null otherwise
*/
public static function retrieve(&$params, &$defaults) {
$job = new CRM_Core_DAO_Job();
$job->copyValues($params);
if ($job->find(TRUE)) {
CRM_Core_DAO::storeValues($job, $defaults);
return $job;
}
return NULL;
}
/**
* Update the is_active flag in the db.
*
* @param int $id
* Id of the database record.
* @param bool $is_active
* Value we want to set the is_active field.
*
* @return Object
* DAO object on success, null otherwise
*
*/
public static function setIsActive($id, $is_active) {
return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_Job', $id, 'is_active', $is_active);
}
/**
* Function to delete scheduled job.
*
* @param $jobID
* ID of the job to be deleted.
*
* @return bool|null
*/
public static function del($jobID) {
if (!$jobID) {
CRM_Core_Error::fatal(ts('Invalid value passed to delete function.'));
}
$dao = new CRM_Core_DAO_Job();
$dao->id = $jobID;
if (!$dao->find(TRUE)) {
return NULL;
}
if ($dao->delete()) {
return TRUE;
}
}
/**
* Trim job table on a regular basis to keep it at a good size.
*
* CRM-10513
*
* @param int $maxEntriesToKeep
* @param int $minDaysToKeep
*/
public static function cleanup($maxEntriesToKeep = 1000, $minDaysToKeep = 30) {
// Prevent the job log from getting too big
// For now, keep last minDays days and at least maxEntries records
$query = 'SELECT COUNT(*) FROM civicrm_job_log';
$count = CRM_Core_DAO::singleValueQuery($query);
if ($count <= $maxEntriesToKeep) {
return;
}
$count = $count - $maxEntriesToKeep;
$query = "DELETE FROM civicrm_job_log WHERE run_time < SUBDATE(NOW(), $minDaysToKeep) LIMIT $count";
CRM_Core_DAO::executeQuery($query);
}
}

View file

@ -0,0 +1,550 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright (C) 2011 Marty Wright |
| Licensed to CiviCRM under the Academic Free License version 3.0. |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class contains functions for managing Label Formats.
*/
class CRM_Core_BAO_LabelFormat extends CRM_Core_DAO_OptionValue {
/**
* Static holder for the Label Formats Option Group ID.
*/
private static $_gid = NULL;
/**
* Label Format fields stored in the 'value' field of the Option Value table.
*/
private static $optionValueFields = array(
'paper-size' => array(
// Paper size: names defined in option_value table (option_group = 'paper_size')
'name' => 'paper-size',
'type' => CRM_Utils_Type::T_STRING,
'default' => 'letter',
),
'orientation' => array(
// Paper orientation: 'portrait' or 'landscape'
'name' => 'orientation',
'type' => CRM_Utils_Type::T_STRING,
'default' => 'portrait',
),
'font-name' => array(
// Font name: 'courier', 'helvetica', 'times'
'name' => 'font-name',
'type' => CRM_Utils_Type::T_STRING,
'default' => 'helvetica',
),
'font-size' => array(
// Font size: always in points
'name' => 'font-size',
'type' => CRM_Utils_Type::T_INT,
'default' => 8,
),
'font-style' => array(
// Font style: 'B' bold, 'I' italic, 'BI' bold+italic
'name' => 'font-style',
'type' => CRM_Utils_Type::T_STRING,
'default' => '',
),
'NX' => array(
// Number of labels horizontally
'name' => 'NX',
'type' => CRM_Utils_Type::T_INT,
'default' => 3,
),
'NY' => array(
// Number of labels vertically
'name' => 'NY',
'type' => CRM_Utils_Type::T_INT,
'default' => 10,
),
'metric' => array(
// Unit of measurement for all of the following fields
'name' => 'metric',
'type' => CRM_Utils_Type::T_STRING,
'default' => 'mm',
),
'lMargin' => array(
// Left margin
'name' => 'lMargin',
'type' => CRM_Utils_Type::T_FLOAT,
'metric' => TRUE,
'default' => 4.7625,
),
'tMargin' => array(
// Right margin
'name' => 'tMargin',
'type' => CRM_Utils_Type::T_FLOAT,
'metric' => TRUE,
'default' => 12.7,
),
'SpaceX' => array(
// Horizontal space between two labels
'name' => 'SpaceX',
'type' => CRM_Utils_Type::T_FLOAT,
'metric' => TRUE,
'default' => 3.96875,
),
'SpaceY' => array(
// Vertical space between two labels
'name' => 'SpaceY',
'type' => CRM_Utils_Type::T_FLOAT,
'metric' => TRUE,
'default' => 0,
),
'width' => array(
// Width of label
'name' => 'width',
'type' => CRM_Utils_Type::T_FLOAT,
'metric' => TRUE,
'default' => 65.875,
),
'height' => array(
// Height of label
'name' => 'height',
'type' => CRM_Utils_Type::T_FLOAT,
'metric' => TRUE,
'default' => 25.4,
),
'lPadding' => array(
// Space between text and left edge of label
'name' => 'lPadding',
'type' => CRM_Utils_Type::T_FLOAT,
'metric' => TRUE,
'default' => 5.08,
),
'tPadding' => array(
// Space between text and top edge of label
'name' => 'tPadding',
'type' => CRM_Utils_Type::T_FLOAT,
'metric' => TRUE,
'default' => 5.08,
),
);
/**
* Get page orientations recognized by the DOMPDF package used to create PDF letters.
*
* @return array
* array of page orientations
*/
public static function getPageOrientations() {
return array(
'portrait' => ts('Portrait'),
'landscape' => ts('Landscape'),
);
}
/**
* Get font names supported by the TCPDF package used to create PDF labels.
*
* @param string $name
* Group name.
*
* @return array
* array of font names
*/
public static function getFontNames($name = 'label_format') {
$label = new CRM_Utils_PDF_Label(self::getDefaultValues($name));
return $label->getFontNames();
}
/**
* Get font sizes supported by the TCPDF package used to create PDF labels.
*
* @return array
* array of font sizes
*/
public static function getFontSizes() {
$fontSizes = array();
for ($i = 6; $i <= 60; $i++) {
$fontSizes[$i] = ts('%1 pt', array(1 => $i));
}
return $fontSizes;
}
/**
* Get measurement units recognized by the TCPDF package used to create PDF labels.
*
* @return array
* array of measurement units
*/
public static function getUnits() {
return array(
'in' => ts('Inches'),
'cm' => ts('Centimeters'),
'mm' => ts('Millimeters'),
'pt' => ts('Points'),
);
}
/**
* Get text alignment recognized by the TCPDF package used to create PDF labels.
*
* @return array
* array of alignments
*/
public static function getTextAlignments() {
return array(
'R' => ts('Right'),
'L' => ts('Left'),
'C' => ts('Center'),
);
}
/**
* Get text alignment recognized by the TCPDF package used to create PDF labels.
*
* @return array
* array of alignments
*/
public static function getFontStyles() {
return array(
'' => ts('Normal'),
'B' => ts('Bold'),
'I' => ts('Italic'),
);
}
/**
* Get Option Group ID for Label Formats.
*
* @param string $name
*
* @return int
* Group ID (null if Group ID doesn't exist)
*/
private static function _getGid($name = 'label_format') {
if (!isset(self::$_gid[$name]) || !self::$_gid[$name]) {
self::$_gid[$name] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', $name, 'id', 'name');
if (!self::$_gid[$name]) {
CRM_Core_Error::fatal(ts('Label Format Option Group not found in database.'));
}
}
return self::$_gid[$name];
}
/**
* Add ordering fields to Label Format list.
*
* @param array (reference) $list List of Label Formats
* @param string $returnURL
* URL of page calling this function.
*
* @return array
* (reference) List of Label Formats
*/
public static function addOrder(&$list, $returnURL) {
$filter = "option_group_id = " . self::_getGid();
CRM_Utils_Weight::addOrder($list, 'CRM_Core_DAO_OptionValue', 'id', $returnURL, $filter);
return $list;
}
/**
* Retrieve list of Label Formats.
*
* @param bool $namesOnly
* Return simple list of names.
* @param string $groupName
* Group name of the label format option group.
*
* @return array
* (reference) label format list
*/
public static function &getList($namesOnly = FALSE, $groupName = 'label_format') {
static $list = array();
if (self::_getGid($groupName)) {
// get saved label formats from Option Value table
$dao = new CRM_Core_DAO_OptionValue();
$dao->option_group_id = self::_getGid($groupName);
$dao->is_active = 1;
$dao->orderBy('weight');
$dao->find();
while ($dao->fetch()) {
if ($namesOnly) {
$list[$groupName][$dao->name] = $dao->label;
}
else {
CRM_Core_DAO::storeValues($dao, $list[$groupName][$dao->id]);
}
}
}
return $list[$groupName];
}
/**
* Retrieve the default Label Format values.
*
* @param string $groupName
* Label format group name.
*
* @return array
* Name/value pairs containing the default Label Format values.
*/
public static function &getDefaultValues($groupName = 'label_format') {
$params = array('is_active' => 1, 'is_default' => 1);
$defaults = array();
if (!self::retrieve($params, $defaults, $groupName)) {
foreach (self::$optionValueFields as $name => $field) {
$defaults[$name] = $field['default'];
}
$filter = array('option_group_id' => self::_getGid($groupName));
$defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_OptionValue', $filter);
}
return $defaults;
}
/**
* Get Label Format from the DB.
*
* @param string $field
* Field name to search by.
* @param int $val
* Field value to search for.
*
* @param string $groupName
*
* @return array
* (reference) associative array of name/value pairs
*/
public static function &getLabelFormat($field, $val, $groupName = 'label_format') {
$params = array('is_active' => 1, $field => $val);
$labelFormat = array();
if (self::retrieve($params, $labelFormat, $groupName)) {
return $labelFormat;
}
else {
return self::getDefaultValues($groupName);
}
}
/**
* Get Label Format by Name.
*
* @param int $name
* Label format name. Empty = get default label format.
*
* @return array
* (reference) associative array of name/value pairs
*/
public static function &getByName($name) {
return self::getLabelFormat('name', $name);
}
/**
* Get Label Format by ID.
*
* @param int $id
* Label format id. 0 = get default label format.
* @param string $groupName
* Group name.
*
* @return array
* (reference) associative array of name/value pairs
*/
public static function &getById($id, $groupName = 'label_format') {
return self::getLabelFormat('id', $id, $groupName);
}
/**
* Get Label Format field from associative array.
*
* @param string $field
* Name of a label format field.
* @param array (reference) $values associative array of name/value pairs containing
* label format field selections
*
* @param null $default
*
* @return value
*/
public static function getValue($field, &$values, $default = NULL) {
if (array_key_exists($field, self::$optionValueFields)) {
switch (self::$optionValueFields[$field]['type']) {
case CRM_Utils_Type::T_INT:
return (int) CRM_Utils_Array::value($field, $values, $default);
case CRM_Utils_Type::T_FLOAT:
// Round float values to three decimal places and trim trailing zeros.
// Add a leading zero to values less than 1.
$f = sprintf('%05.3f', $values[$field]);
$f = rtrim($f, '0');
$f = rtrim($f, '.');
return (float) (empty($f) ? '0' : $f);
}
return CRM_Utils_Array::value($field, $values, $default);
}
return $default;
}
/**
* Retrieve DB object based on input parameters.
*
* It also stores all the retrieved values in the default array.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $values
* (reference ) an assoc array to hold the flattened values.
*
* @param string $groupName
*
* @return CRM_Core_DAO_OptionValue
*/
public static function retrieve(&$params, &$values, $groupName = 'label_format') {
$optionValue = new CRM_Core_DAO_OptionValue();
$optionValue->copyValues($params);
$optionValue->option_group_id = self::_getGid($groupName);
if ($optionValue->find(TRUE)) {
// Extract fields that have been serialized in the 'value' column of the Option Value table.
$values = json_decode($optionValue->value, TRUE);
// Add any new fields that don't yet exist in the saved values.
foreach (self::$optionValueFields as $name => $field) {
if (!isset($values[$name])) {
$values[$name] = $field['default'];
if ($field['metric']) {
$values[$name] = CRM_Utils_PDF_Utils::convertMetric($field['default'],
self::$optionValueFields['metric']['default'],
$values['metric'], 3
);
}
}
}
// Add fields from the OptionValue base class
CRM_Core_DAO::storeValues($optionValue, $values);
return $optionValue;
}
return NULL;
}
/**
* Return the name of the group for customized labels.
*/
public static function customGroupName() {
return ts('Custom');
}
/**
* Save the Label Format in the DB.
*
* @param array (reference) $values associative array of name/value pairs
* @param int $id
* Id of the database record (null = new record).
* @param string $groupName
* Group name of the label format.
*/
public function saveLabelFormat(&$values, $id = NULL, $groupName = 'label_format') {
// get the Option Group ID for Label Formats (create one if it doesn't exist)
$group_id = self::_getGid($groupName);
// clear other default if this is the new default label format
if ($values['is_default']) {
$query = "UPDATE civicrm_option_value SET is_default = 0 WHERE option_group_id = $group_id";
CRM_Core_DAO::executeQuery($query);
}
if ($id) {
// fetch existing record
$this->id = $id;
if ($this->find()) {
$this->fetch();
}
}
else {
// new record
$list = self::getList(TRUE, $groupName);
$cnt = 1;
while (array_key_exists("custom_$cnt", $list)) {
$cnt++;
}
$values['name'] = "custom_$cnt";
$values['grouping'] = self::customGroupName();
}
// copy the supplied form values to the corresponding Option Value fields in the base class
foreach ($this->fields() as $name => $field) {
$this->$name = trim(CRM_Utils_Array::value($name, $values, $this->$name));
if (empty($this->$name)) {
$this->$name = 'null';
}
}
$this->id = $id;
$this->option_group_id = $group_id;
$this->is_active = 1;
// serialize label format fields into a single string to store in the 'value' column of the Option Value table
$v = json_decode($this->value, TRUE);
foreach (self::$optionValueFields as $name => $field) {
if (!isset($v[$name])) {
$v[$name] = NULL;
}
$v[$name] = self::getValue($name, $values, $v[$name]);
}
$this->value = json_encode($v);
// make sure serialized array will fit in the 'value' column
$attribute = CRM_Core_DAO::getAttribute('CRM_Core_BAO_LabelFormat', 'value');
if (strlen($this->value) > $attribute['maxlength']) {
CRM_Core_Error::fatal(ts('Label Format does not fit in database.'));
}
$this->save();
// fix duplicate weights
$filter = array('option_group_id' => self::_getGid());
CRM_Utils_Weight::correctDuplicateWeights('CRM_Core_DAO_OptionValue', $filter);
}
/**
* Delete a Label Format.
*
* @param int $id
* ID of the label format to be deleted.
* @param string $groupName
* Group name.
*/
public static function del($id, $groupName) {
if ($id) {
$dao = new CRM_Core_DAO_OptionValue();
$dao->id = $id;
if ($dao->find(TRUE)) {
if ($dao->option_group_id == self::_getGid($groupName)) {
$filter = array('option_group_id' => self::_getGid($groupName));
CRM_Utils_Weight::delWeight('CRM_Core_DAO_OptionValue', $id, $filter);
$dao->delete();
return;
}
}
}
CRM_Core_Error::fatal(ts('Invalid value passed to delete function.'));
}
}

View file

@ -0,0 +1,449 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class handle creation of location block elements.
*/
class CRM_Core_BAO_Location extends CRM_Core_DAO {
/**
* Location block element array.
*/
static $blocks = array('phone', 'email', 'im', 'openid', 'address');
/**
* Create various elements of location block.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param bool $fixAddress
* True if you need to fix (format) address values.
* before inserting in db
*
* @param null $entity
*
* @return array
*/
public static function create(&$params, $fixAddress = TRUE, $entity = NULL) {
$location = array();
if (!self::dataExists($params)) {
return $location;
}
// create location blocks.
foreach (self::$blocks as $block) {
if ($block != 'address') {
$location[$block] = CRM_Core_BAO_Block::create($block, $params, $entity);
}
else {
$location[$block] = CRM_Core_BAO_Address::create($params, $fixAddress, $entity);
}
}
if ($entity) {
// this is a special case for adding values in location block table
$entityElements = array(
'entity_table' => $params['entity_table'],
'entity_id' => $params['entity_id'],
);
$location['id'] = self::createLocBlock($location, $entityElements);
}
else {
// when we come from a form which displays all the location elements (like the edit form or the inline block
// elements, we can skip the below check. The below check adds quite a feq queries to an already overloaded
// form
if (!CRM_Utils_Array::value('updateBlankLocInfo', $params, FALSE)) {
// make sure contact should have only one primary block, CRM-5051
self::checkPrimaryBlocks(CRM_Utils_Array::value('contact_id', $params));
}
}
return $location;
}
/**
* Creates the entry in the civicrm_loc_block.
*
* @param string $location
* @param array $entityElements
*
* @return int
*/
public static function createLocBlock(&$location, &$entityElements) {
$locId = self::findExisting($entityElements);
$locBlock = array();
if ($locId) {
$locBlock['id'] = $locId;
}
foreach (array(
'phone',
'email',
'im',
'address',
) as $loc) {
$locBlock["{$loc}_id"] = !empty($location["$loc"][0]) ? $location["$loc"][0]->id : NULL;
$locBlock["{$loc}_2_id"] = !empty($location["$loc"][1]) ? $location["$loc"][1]->id : NULL;
}
$countNull = 0;
foreach ($locBlock as $key => $block) {
if (empty($locBlock[$key])) {
$locBlock[$key] = 'null';
$countNull++;
}
}
if (count($locBlock) == $countNull) {
// implies nothing is set.
return NULL;
}
$locBlockInfo = self::addLocBlock($locBlock);
return $locBlockInfo->id;
}
/**
* Takes an entity array and finds the existing location block.
*
* @param array $entityElements
*
* @return int
*/
public static function findExisting($entityElements) {
$eid = $entityElements['entity_id'];
$etable = $entityElements['entity_table'];
$query = "
SELECT e.loc_block_id as locId
FROM {$etable} e
WHERE e.id = %1";
$params = array(1 => array($eid, 'Integer'));
$dao = CRM_Core_DAO::executeQuery($query, $params);
while ($dao->fetch()) {
$locBlockId = $dao->locId;
}
return $locBlockId;
}
/**
* Takes an associative array and adds location block.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
*
* @return CRM_Core_BAO_locBlock
* Object on success, null otherwise
*/
public static function addLocBlock(&$params) {
$locBlock = new CRM_Core_DAO_LocBlock();
$locBlock->copyValues($params);
return $locBlock->save();
}
/**
* Delete the Location Block.
*
* @param int $locBlockId
* Id of the Location Block.
*/
public static function deleteLocBlock($locBlockId) {
if (!$locBlockId) {
return;
}
$locBlock = new CRM_Core_DAO_LocBlock();
$locBlock->id = $locBlockId;
$locBlock->find(TRUE);
//resolve conflict of having same ids for multiple blocks
$store = array(
'IM_1' => $locBlock->im_id,
'IM_2' => $locBlock->im_2_id,
'Email_1' => $locBlock->email_id,
'Email_2' => $locBlock->email_2_id,
'Phone_1' => $locBlock->phone_id,
'Phone_2' => $locBlock->phone_2_id,
'Address_1' => $locBlock->address_id,
'Address_2' => $locBlock->address_2_id,
);
$locBlock->delete();
foreach ($store as $daoName => $id) {
if ($id) {
$daoName = 'CRM_Core_DAO_' . substr($daoName, 0, -2);
$dao = new $daoName();
$dao->id = $id;
$dao->find(TRUE);
$dao->delete();
$dao->free();
}
}
}
/**
* Check if there is data to create the object.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
*
* @return bool
*/
public static function dataExists(&$params) {
// return if no data present
$dataExists = FALSE;
foreach (self::$blocks as $block) {
if (array_key_exists($block, $params)) {
$dataExists = TRUE;
break;
}
}
return $dataExists;
}
/**
* Get values.
*
* @param array $entityBlock
* @param bool $microformat
*
* @return array
* array of objects(CRM_Core_BAO_Location)
*/
public static function &getValues($entityBlock, $microformat = FALSE) {
if (empty($entityBlock)) {
return NULL;
}
$blocks = array();
$name_map = array(
'im' => 'IM',
'openid' => 'OpenID',
);
$blocks = array();
//get all the blocks for this contact
foreach (self::$blocks as $block) {
if (array_key_exists($block, $name_map)) {
$name = $name_map[$block];
}
else {
$name = ucfirst($block);
}
$baoString = 'CRM_Core_BAO_' . $name;
$blocks[$block] = $baoString::getValues($entityBlock, $microformat);
}
return $blocks;
}
/**
* Delete all the block associated with the location.
*
* @param int $contactId
* Contact id.
* @param int $locationTypeId
* Id of the location to delete.
*/
public static function deleteLocationBlocks($contactId, $locationTypeId) {
// ensure that contactId has a value
if (empty($contactId) ||
!CRM_Utils_Rule::positiveInteger($contactId)
) {
CRM_Core_Error::fatal();
}
if (empty($locationTypeId) ||
!CRM_Utils_Rule::positiveInteger($locationTypeId)
) {
// so we only delete the blocks which DO NOT have a location type Id
// CRM-3581
$locationTypeId = 'null';
}
static $blocks = array('Address', 'Phone', 'IM', 'OpenID', 'Email');
$params = array('contact_id' => $contactId, 'location_type_id' => $locationTypeId);
foreach ($blocks as $name) {
CRM_Core_BAO_Block::blockDelete($name, $params);
}
}
/**
* Copy or update location block.
*
* @param int $locBlockId
* Location block id.
* @param int $updateLocBlockId
* Update location block id.
*
* @return int
* newly created/updated location block id.
*/
public static function copyLocBlock($locBlockId, $updateLocBlockId = NULL) {
//get the location info.
$defaults = $updateValues = array();
$locBlock = array('id' => $locBlockId);
CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_LocBlock', $locBlock, $defaults);
if ($updateLocBlockId) {
//get the location info for update.
$copyLocationParams = array('id' => $updateLocBlockId);
CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_LocBlock', $copyLocationParams, $updateValues);
foreach ($updateValues as $key => $value) {
if ($key != 'id') {
$copyLocationParams[$key] = 'null';
}
}
}
//copy all location blocks (email, phone, address, etc)
foreach ($defaults as $key => $value) {
if ($key != 'id') {
$tbl = explode("_", $key);
$name = ucfirst($tbl[0]);
$updateParams = NULL;
if ($updateId = CRM_Utils_Array::value($key, $updateValues)) {
$updateParams = array('id' => $updateId);
}
$copy = CRM_Core_DAO::copyGeneric('CRM_Core_DAO_' . $name, array('id' => $value), $updateParams);
$copyLocationParams[$key] = $copy->id;
}
}
$copyLocation = &CRM_Core_DAO::copyGeneric('CRM_Core_DAO_LocBlock',
array('id' => $locBlock['id']),
$copyLocationParams
);
return $copyLocation->id;
}
/**
* Make sure contact should have only one primary block, CRM-5051.
*
* @param int $contactId
* Contact id.
*/
public static function checkPrimaryBlocks($contactId) {
if (!$contactId) {
return;
}
// get the loc block ids.
$primaryLocBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($contactId, array('is_primary' => 1));
$nonPrimaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($contactId, array('is_primary' => 0));
foreach (array(
'Email',
'IM',
'Phone',
'Address',
'OpenID',
) as $block) {
$name = strtolower($block);
if (array_key_exists($name, $primaryLocBlockIds) &&
!CRM_Utils_System::isNull($primaryLocBlockIds[$name])
) {
if (count($primaryLocBlockIds[$name]) > 1) {
// keep only single block as primary.
$primaryId = array_pop($primaryLocBlockIds[$name]);
$resetIds = "(" . implode(',', $primaryLocBlockIds[$name]) . ")";
// reset all primary except one.
CRM_Core_DAO::executeQuery("UPDATE civicrm_$name SET is_primary = 0 WHERE id IN $resetIds");
}
}
elseif (array_key_exists($name, $nonPrimaryBlockIds) &&
!CRM_Utils_System::isNull($nonPrimaryBlockIds[$name])
) {
// data exists and no primary block - make one primary.
CRM_Core_DAO::setFieldValue("CRM_Core_DAO_" . $block,
array_pop($nonPrimaryBlockIds[$name]), 'is_primary', 1
);
}
}
}
/**
* Get chain select values (whatever that means!).
*
* @param mixed $values
* @param string $valueType
* @param bool $flatten
*
* @return array
*/
public static function getChainSelectValues($values, $valueType, $flatten = FALSE) {
if (!$values) {
return array();
}
$values = array_filter((array) $values);
$elements = array();
$list = &$elements;
$method = $valueType == 'country' ? 'stateProvinceForCountry' : 'countyForState';
foreach ($values as $val) {
$result = CRM_Core_PseudoConstant::$method($val);
// Format for quickform
if ($flatten) {
// Option-groups for multiple categories
if ($result && count($values) > 1) {
$elements["crm_optgroup_$val"] = CRM_Core_PseudoConstant::$valueType($val, FALSE);
}
$elements += $result;
}
// Format for js
else {
// Option-groups for multiple categories
if ($result && count($values) > 1) {
$elements[] = array(
'value' => CRM_Core_PseudoConstant::$valueType($val, FALSE),
'children' => array(),
);
$list = &$elements[count($elements) - 1]['children'];
}
foreach ($result as $id => $name) {
$list[] = array(
'value' => $name,
'key' => $id,
);
}
}
}
return $elements;
}
}

View file

@ -0,0 +1,171 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
class CRM_Core_BAO_LocationType extends CRM_Core_DAO_LocationType {
/**
* Static holder for the default LT.
*/
static $_defaultLocationType = NULL;
static $_billingLocationType = NULL;
/**
* Class constructor.
*/
public function __construct() {
parent::__construct();
}
/**
* Fetch object based on array of properties.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $defaults
* (reference ) an assoc array to hold the flattened values.
*
* @return CRM_Core_BAO_LocaationType|null
* object on success, null otherwise
*/
public static function retrieve(&$params, &$defaults) {
$locationType = new CRM_Core_DAO_LocationType();
$locationType->copyValues($params);
if ($locationType->find(TRUE)) {
CRM_Core_DAO::storeValues($locationType, $defaults);
return $locationType;
}
return NULL;
}
/**
* Update the is_active flag in the db.
*
* @param int $id
* Id of the database record.
* @param bool $is_active
* Value we want to set the is_active field.
*
* @return Object
* DAO object on success, null otherwise
*
*/
public static function setIsActive($id, $is_active) {
return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_LocationType', $id, 'is_active', $is_active);
}
/**
* Retrieve the default location_type.
*
* @return object
* The default location type object on success,
* null otherwise
*/
public static function &getDefault() {
if (self::$_defaultLocationType == NULL) {
$params = array('is_default' => 1);
$defaults = array();
self::$_defaultLocationType = self::retrieve($params, $defaults);
}
return self::$_defaultLocationType;
}
/**
* Get ID of billing location type.
*
* @return int
*/
public static function getBilling() {
if (self::$_billingLocationType == NULL) {
$locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
self::$_billingLocationType = array_search('Billing', $locationTypes);
}
return self::$_billingLocationType;
}
/**
* Add a Location Type.
*
* @param array $params
* Reference array contains the values submitted by the form.
*
*
* @return object
*/
public static function create(&$params) {
if (empty($params['id'])) {
$params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
$params['is_default'] = CRM_Utils_Array::value('is_default', $params, FALSE);
$params['is_reserved'] = CRM_Utils_Array::value('is_reserved', $params, FALSE);
}
$locationType = new CRM_Core_DAO_LocationType();
$locationType->copyValues($params);
if (!empty($params['is_default'])) {
$query = "UPDATE civicrm_location_type SET is_default = 0";
CRM_Core_DAO::executeQuery($query);
}
$locationType->save();
return $locationType;
}
/**
* Delete location Types.
*
* @param int $locationTypeId
* ID of the location type to be deleted.
*
*/
public static function del($locationTypeId) {
$entity = array('address', 'phone', 'email', 'im');
//check dependencies
foreach ($entity as $key) {
if ($key == 'im') {
$name = strtoupper($key);
}
else {
$name = ucfirst($key);
}
$baoString = 'CRM_Core_BAO_' . $name;
$object = new $baoString();
$object->location_type_id = $locationTypeId;
$object->delete();
}
$locationType = new CRM_Core_DAO_LocationType();
$locationType->id = $locationTypeId;
$locationType->delete();
}
}

View file

@ -0,0 +1,202 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2016
*/
/**
* BAO object for crm_log table
*/
class CRM_Core_BAO_Log extends CRM_Core_DAO_Log {
static $_processed = NULL;
/**
* @param int $id
* @param string $table
*
* @return array|null
*
*/
public static function &lastModified($id, $table = 'civicrm_contact') {
$log = new CRM_Core_DAO_Log();
$log->entity_table = $table;
$log->entity_id = $id;
$log->orderBy('modified_date desc');
$log->limit(1);
$displayName = $result = $contactImage = NULL;
if ($log->find(TRUE)) {
if ($log->modified_id) {
list($displayName, $contactImage) = CRM_Contact_BAO_Contact::getDisplayAndImage($log->modified_id);
}
$result = array(
'id' => $log->modified_id,
'name' => $displayName,
'image' => $contactImage,
'date' => $log->modified_date,
);
}
return $result;
}
/**
* Add log to civicrm_log table.
*
* @param array $params
* Array of name-value pairs of log table.
*
*/
public static function add(&$params) {
$log = new CRM_Core_DAO_Log();
$log->copyValues($params);
$log->save();
}
/**
* @param int $contactID
* @param string $tableName
* @param int $tableID
* @param int $userID
*/
public static function register(
$contactID,
$tableName,
$tableID,
$userID = NULL
) {
if (!self::$_processed) {
self::$_processed = array();
}
if (!$userID) {
$session = CRM_Core_Session::singleton();
$userID = $session->get('userID');
}
if (!$userID) {
$api_key = CRM_Utils_Request::retrieve('api_key', 'String', $store, FALSE, NULL, 'REQUEST');
if ($api_key && strtolower($api_key) != 'null') {
$userID = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key');
}
}
if (!$userID) {
$userID = $contactID;
}
if (!$userID) {
return;
}
$log = new CRM_Core_DAO_Log();
$log->id = NULL;
if (isset(self::$_processed[$contactID])) {
if (isset(self::$_processed[$contactID][$userID])) {
$log->id = self::$_processed[$contactID][$userID];
}
self::$_processed[$contactID][$userID] = 1;
}
else {
self::$_processed[$contactID] = array($userID => 1);
}
$logData = "$tableName,$tableID";
if (!$log->id) {
$log->entity_table = 'civicrm_contact';
$log->entity_id = $contactID;
$log->modified_id = $userID;
$log->modified_date = date("YmdHis");
$log->data = $logData;
$log->save();
}
else {
$query = "
UPDATE civicrm_log
SET data = concat( data, ':$logData' )
WHERE id = {$log->id}
";
CRM_Core_DAO::executeQuery($query);
}
self::$_processed[$contactID][$userID] = $log->id;
}
/**
* Get log record count for a Contact.
*
* @param int $contactID
*
* @return int
* count of log records
*/
public static function getContactLogCount($contactID) {
$query = "SELECT count(*) FROM civicrm_log
WHERE civicrm_log.entity_table = 'civicrm_contact' AND civicrm_log.entity_id = {$contactID}";
return CRM_Core_DAO::singleValueQuery($query);
}
/**
* Get the id of the report to use to display the change log.
*
* If logging is not enabled a return value of FALSE means to use the
* basic change log view.
*
* @return int|FALSE
* report id of Contact Logging Report (Summary)
*/
public static function useLoggingReport() {
if (!\Civi::settings()->get('logging')) {
return FALSE;
}
$loggingSchema = new CRM_Logging_Schema();
if ($loggingSchema->isEnabled()) {
$params = array('report_id' => 'logging/contact/summary');
$instance = array();
CRM_Report_BAO_ReportInstance::retrieve($params, $instance);
if (!empty($instance) &&
(empty($instance['permission']) ||
(!empty($instance['permission']) && CRM_Core_Permission::check($instance['permission']))
)
) {
return $instance['id'];
}
}
return FALSE;
}
}

View file

@ -0,0 +1,208 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
class CRM_Core_BAO_MailSettings extends CRM_Core_DAO_MailSettings {
/**
* Class constructor.
*/
public function __construct() {
parent::__construct();
}
/**
* Return the DAO object containing to the default row of
* civicrm_mail_settings and cache it for further calls
*
* @param bool $reset
*
* @return CRM_Core_BAO_MailSettings
* DAO with the default mail settings set
*/
public static function defaultDAO($reset = FALSE) {
static $mailSettings = array();
$domainID = CRM_Core_Config::domainID();
if (empty($mailSettings[$domainID]) || $reset) {
$dao = new self();
$dao->is_default = 1;
$dao->domain_id = $domainID;
$dao->find(TRUE);
$mailSettings[$domainID] = $dao;
}
return $mailSettings[$domainID];
}
/**
* Return the domain from the default set of settings.
*
* @return string
* default domain
*/
public static function defaultDomain() {
return self::defaultDAO()->domain;
}
/**
* Return the localpart from the default set of settings.
*
* @return string
* default localpart
*/
public static function defaultLocalpart() {
return self::defaultDAO()->localpart;
}
/**
* Return the return path from the default set of settings.
*
* @return string
* default return path
*/
public static function defaultReturnPath() {
return self::defaultDAO()->return_path;
}
/**
* Return the "include message ID" flag from the default set of settings.
*
* @return bool
* default include message ID
*/
public static function includeMessageId() {
return Civi::settings()->get('include_message_id');
}
/**
* Retrieve DB object based on input parameters.
*
* It also stores all the retrieved values in the default array.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $defaults
* (reference ) an assoc array to hold the flattened values.
*
* @return CRM_Core_BAO_MailSettings
*/
public static function retrieve(&$params, &$defaults) {
$mailSettings = new CRM_Core_DAO_MailSettings();
$mailSettings->copyValues($params);
$result = NULL;
if ($mailSettings->find(TRUE)) {
CRM_Core_DAO::storeValues($mailSettings, $defaults);
$result = $mailSettings;
}
return $result;
}
/**
* Add new mail Settings.
*
* @param array $params
* Reference array contains the values submitted by the form.
*
*
* @return object
*/
public static function add(&$params) {
$result = NULL;
if (empty($params)) {
return $result;
}
if (empty($params['id'])) {
$params['is_ssl'] = CRM_Utils_Array::value('is_ssl', $params, FALSE);
$params['is_default'] = CRM_Utils_Array::value('is_default', $params, FALSE);
}
//handle is_default.
if (!empty($params['is_default'])) {
$query = 'UPDATE civicrm_mail_settings SET is_default = 0 WHERE domain_id = %1';
$queryParams = array(1 => array(CRM_Core_Config::domainID(), 'Integer'));
CRM_Core_DAO::executeQuery($query, $queryParams);
}
$mailSettings = new CRM_Core_DAO_MailSettings();
$mailSettings->copyValues($params);
$result = $mailSettings->save();
return $result;
}
/**
* Takes an associative array and creates a mail settings object.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
*
* @return CRM_Core_BAO_MailSettings
*/
public static function create(&$params) {
$transaction = new CRM_Core_Transaction();
$mailSettings = self::add($params);
if (is_a($mailSettings, 'CRM_Core_Error')) {
$mailSettings->rollback();
return $mailSettings;
}
$transaction->commit();
CRM_Core_BAO_MailSettings::defaultDAO(TRUE);
return $mailSettings;
}
/**
* Delete the mail settings.
*
* @param int $id
* Mail settings id.
*
* @return mixed|null
*/
public static function deleteMailSettings($id) {
$results = NULL;
$transaction = new CRM_Core_Transaction();
$mailSettings = new CRM_Core_DAO_MailSettings();
$mailSettings->id = $id;
$results = $mailSettings->delete();
$transaction->commit();
return $results;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,574 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
require_once 'Mail/mime.php';
/**
* Class CRM_Core_BAO_MessageTemplate.
*/
class CRM_Core_BAO_MessageTemplate extends CRM_Core_DAO_MessageTemplate {
/**
* Fetch object based on array of properties.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $defaults
* (reference ) an assoc array to hold the flattened values.
*
* @return CRM_Core_BAO_MessageTemplate
*/
public static function retrieve(&$params, &$defaults) {
$messageTemplates = new CRM_Core_DAO_MessageTemplate();
$messageTemplates->copyValues($params);
if ($messageTemplates->find(TRUE)) {
CRM_Core_DAO::storeValues($messageTemplates, $defaults);
return $messageTemplates;
}
return NULL;
}
/**
* Update the is_active flag in the db.
*
* @param int $id
* Id of the database record.
* @param bool $is_active
* Value we want to set the is_active field.
*
* @return Object
* DAO object on success, NULL otherwise
*/
public static function setIsActive($id, $is_active) {
return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_MessageTemplate', $id, 'is_active', $is_active);
}
/**
* Add the Message Templates.
*
* @param array $params
* Reference array contains the values submitted by the form.
*
*
* @return object
*/
public static function add(&$params) {
$hook = empty($params['id']) ? 'create' : 'edit';
CRM_Utils_Hook::pre($hook, 'MessageTemplate', CRM_Utils_Array::value('id', $params), $params);
if (!empty($params['file_id']) && is_array($params['file_id']) && count($params['file_id'])) {
$fileParams = $params['file_id'];
unset($params['file_id']);
}
$messageTemplates = new CRM_Core_DAO_MessageTemplate();
$messageTemplates->copyValues($params);
$messageTemplates->save();
if (!empty($fileParams)) {
$params['file_id'] = $fileParams;
CRM_Core_BAO_File::filePostProcess(
$params['file_id']['location'],
NULL,
'civicrm_msg_template',
$messageTemplates->id,
NULL,
TRUE,
$params['file_id'],
'file_id',
$params['file_id']['type']
);
}
CRM_Utils_Hook::post($hook, 'MessageTemplate', $messageTemplates->id, $messageTemplates);
return $messageTemplates;
}
/**
* Delete the Message Templates.
*
* @param int $messageTemplatesID
*/
public static function del($messageTemplatesID) {
// make sure messageTemplatesID is an integer
if (!CRM_Utils_Rule::positiveInteger($messageTemplatesID)) {
CRM_Core_Error::fatal(ts('Invalid Message template'));
}
// Set mailing msg template col to NULL
$query = "UPDATE civicrm_mailing
SET msg_template_id = NULL
WHERE msg_template_id = %1";
$params = array(1 => array($messageTemplatesID, 'Integer'));
CRM_Core_DAO::executeQuery($query, $params);
$messageTemplates = new CRM_Core_DAO_MessageTemplate();
$messageTemplates->id = $messageTemplatesID;
$messageTemplates->delete();
CRM_Core_Session::setStatus(ts('Selected message template has been deleted.'), ts('Deleted'), 'success');
}
/**
* Get the Message Templates.
*
*
* @param bool $all
*
* @param bool $isSMS
*
* @return object
*/
public static function getMessageTemplates($all = TRUE, $isSMS = FALSE) {
$msgTpls = array();
$messageTemplates = new CRM_Core_DAO_MessageTemplate();
$messageTemplates->is_active = 1;
$messageTemplates->is_sms = $isSMS;
if (!$all) {
$messageTemplates->workflow_id = 'NULL';
}
$messageTemplates->find();
while ($messageTemplates->fetch()) {
$msgTpls[$messageTemplates->id] = $messageTemplates->msg_title;
}
asort($msgTpls);
return $msgTpls;
}
/**
* @param int $contactId
* @param $email
* @param int $messageTemplateID
* @param $from
*
* @return bool|NULL
*/
public static function sendReminder($contactId, $email, $messageTemplateID, $from) {
$messageTemplates = new CRM_Core_DAO_MessageTemplate();
$messageTemplates->id = $messageTemplateID;
$domain = CRM_Core_BAO_Domain::getDomain();
$result = NULL;
$hookTokens = array();
if ($messageTemplates->find(TRUE)) {
$body_text = $messageTemplates->msg_text;
$body_html = $messageTemplates->msg_html;
$body_subject = $messageTemplates->msg_subject;
if (!$body_text) {
$body_text = CRM_Utils_String::htmlToText($body_html);
}
$params = array(array('contact_id', '=', $contactId, 0, 0));
list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($params);
//CRM-4524
$contact = reset($contact);
if (!$contact || is_a($contact, 'CRM_Core_Error')) {
return NULL;
}
//CRM-5734
// get tokens to be replaced
$tokens = array_merge(CRM_Utils_Token::getTokens($body_text),
CRM_Utils_Token::getTokens($body_html),
CRM_Utils_Token::getTokens($body_subject));
// get replacement text for these tokens
$returnProperties = array("preferred_mail_format" => 1);
if (isset($tokens['contact'])) {
foreach ($tokens['contact'] as $key => $value) {
$returnProperties[$value] = 1;
}
}
list($details) = CRM_Utils_Token::getTokenDetails(array($contactId),
$returnProperties,
NULL, NULL, FALSE,
$tokens,
'CRM_Core_BAO_MessageTemplate');
$contact = reset($details);
// call token hook
$hookTokens = array();
CRM_Utils_Hook::tokens($hookTokens);
$categories = array_keys($hookTokens);
// do replacements in text and html body
$type = array('html', 'text');
foreach ($type as $key => $value) {
$bodyType = "body_{$value}";
if ($$bodyType) {
CRM_Utils_Token::replaceGreetingTokens($$bodyType, NULL, $contact['contact_id']);
$$bodyType = CRM_Utils_Token::replaceDomainTokens($$bodyType, $domain, TRUE, $tokens, TRUE);
$$bodyType = CRM_Utils_Token::replaceContactTokens($$bodyType, $contact, FALSE, $tokens, FALSE, TRUE);
$$bodyType = CRM_Utils_Token::replaceComponentTokens($$bodyType, $contact, $tokens, TRUE);
$$bodyType = CRM_Utils_Token::replaceHookTokens($$bodyType, $contact, $categories, TRUE);
}
}
$html = $body_html;
$text = $body_text;
$smarty = CRM_Core_Smarty::singleton();
foreach (array(
'text',
'html',
) as $elem) {
$$elem = $smarty->fetch("string:{$$elem}");
}
// do replacements in message subject
$messageSubject = CRM_Utils_Token::replaceContactTokens($body_subject, $contact, FALSE, $tokens);
$messageSubject = CRM_Utils_Token::replaceDomainTokens($messageSubject, $domain, TRUE, $tokens);
$messageSubject = CRM_Utils_Token::replaceComponentTokens($messageSubject, $contact, $tokens, TRUE);
$messageSubject = CRM_Utils_Token::replaceHookTokens($messageSubject, $contact, $categories, TRUE);
$messageSubject = $smarty->fetch("string:{$messageSubject}");
// set up the parameters for CRM_Utils_Mail::send
$mailParams = array(
'groupName' => 'Scheduled Reminder Sender',
'from' => $from,
'toName' => $contact['display_name'],
'toEmail' => $email,
'subject' => $messageSubject,
);
if (!$html || $contact['preferred_mail_format'] == 'Text' ||
$contact['preferred_mail_format'] == 'Both'
) {
// render the &amp; entities in text mode, so that the links work
$mailParams['text'] = str_replace('&amp;', '&', $text);
}
if ($html && ($contact['preferred_mail_format'] == 'HTML' ||
$contact['preferred_mail_format'] == 'Both'
)
) {
$mailParams['html'] = $html;
}
$result = CRM_Utils_Mail::send($mailParams);
}
$messageTemplates->free();
return $result;
}
/**
* Revert a message template to its default subject+text+HTML state.
*
* @param int $id id of the template
*/
public static function revert($id) {
$diverted = new CRM_Core_BAO_MessageTemplate();
$diverted->id = (int) $id;
$diverted->find(1);
if ($diverted->N != 1) {
CRM_Core_Error::fatal(ts('Did not find a message template with id of %1.', array(1 => $id)));
}
$orig = new CRM_Core_BAO_MessageTemplate();
$orig->workflow_id = $diverted->workflow_id;
$orig->is_reserved = 1;
$orig->find(1);
if ($orig->N != 1) {
CRM_Core_Error::fatal(ts('Message template with id of %1 does not have a default to revert to.', array(1 => $id)));
}
$diverted->msg_subject = $orig->msg_subject;
$diverted->msg_text = $orig->msg_text;
$diverted->msg_html = $orig->msg_html;
$diverted->pdf_format_id = is_null($orig->pdf_format_id) ? 'null' : $orig->pdf_format_id;
$diverted->save();
}
/**
* Send an email from the specified template based on an array of params.
*
* @param array $params
* A string-keyed array of function params, see function body for details.
*
* @return array
* Array of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates
*/
public static function sendTemplate($params) {
$defaults = array(
// option group name of the template
'groupName' => NULL,
// option value name of the template
'valueName' => NULL,
// ID of the template
'messageTemplateID' => NULL,
// contact id if contact tokens are to be replaced
'contactId' => NULL,
// additional template params (other than the ones already set in the template singleton)
'tplParams' => array(),
// the From: header
'from' => NULL,
// the recipients name
'toName' => NULL,
// the recipients email - mail is sent only if set
'toEmail' => NULL,
// the Cc: header
'cc' => NULL,
// the Bcc: header
'bcc' => NULL,
// the Reply-To: header
'replyTo' => NULL,
// email attachments
'attachments' => NULL,
// whether this is a test email (and hence should include the test banner)
'isTest' => FALSE,
// filename of optional PDF version to add as attachment (do not include path)
'PDFFilename' => NULL,
);
$params = array_merge($defaults, $params);
CRM_Utils_Hook::alterMailParams($params, 'messageTemplate');
if ((!$params['groupName'] ||
!$params['valueName']
) &&
!$params['messageTemplateID']
) {
CRM_Core_Error::fatal(ts("Message template's option group and/or option value or ID missing."));
}
if ($params['messageTemplateID']) {
// fetch the three elements from the db based on id
$query = 'SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format
FROM civicrm_msg_template mt
WHERE mt.id = %1 AND mt.is_default = 1';
$sqlParams = array(1 => array($params['messageTemplateID'], 'String'));
}
else {
// fetch the three elements from the db based on option_group and option_value names
$query = 'SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format
FROM civicrm_msg_template mt
JOIN civicrm_option_value ov ON workflow_id = ov.id
JOIN civicrm_option_group og ON ov.option_group_id = og.id
WHERE og.name = %1 AND ov.name = %2 AND mt.is_default = 1';
$sqlParams = array(1 => array($params['groupName'], 'String'), 2 => array($params['valueName'], 'String'));
}
$dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
$dao->fetch();
if (!$dao->N) {
if ($params['messageTemplateID']) {
CRM_Core_Error::fatal(ts('No such message template: id=%1.', array(1 => $params['messageTemplateID'])));
}
else {
CRM_Core_Error::fatal(ts('No such message template: option group %1, option value %2.', array(
1 => $params['groupName'],
2 => $params['valueName'],
)));
}
}
$mailContent = array(
'subject' => $dao->subject,
'text' => $dao->text,
'html' => $dao->html,
'format' => $dao->format,
);
$dao->free();
CRM_Utils_Hook::alterMailContent($mailContent);
// add the test banner (if requested)
if ($params['isTest']) {
$query = "SELECT msg_subject subject, msg_text text, msg_html html
FROM civicrm_msg_template mt
JOIN civicrm_option_value ov ON workflow_id = ov.id
JOIN civicrm_option_group og ON ov.option_group_id = og.id
WHERE og.name = 'msg_tpl_workflow_meta' AND ov.name = 'test_preview' AND mt.is_default = 1";
$testDao = CRM_Core_DAO::executeQuery($query);
$testDao->fetch();
$mailContent['subject'] = $testDao->subject . $mailContent['subject'];
$mailContent['text'] = $testDao->text . $mailContent['text'];
$mailContent['html'] = preg_replace('/<body(.*)$/im', "<body\\1\n{$testDao->html}", $mailContent['html']);
$testDao->free();
}
// replace tokens in the three elements (in subject as if it was the text body)
$domain = CRM_Core_BAO_Domain::getDomain();
$hookTokens = array();
$mailing = new CRM_Mailing_BAO_Mailing();
$mailing->subject = $mailContent['subject'];
$mailing->body_text = $mailContent['text'];
$mailing->body_html = $mailContent['html'];
$tokens = $mailing->getTokens();
CRM_Utils_Hook::tokens($hookTokens);
$categories = array_keys($hookTokens);
$contactID = CRM_Utils_Array::value('contactId', $params);
if ($contactID) {
$contactParams = array('contact_id' => $contactID);
$returnProperties = array();
if (isset($tokens['subject']['contact'])) {
foreach ($tokens['subject']['contact'] as $name) {
$returnProperties[$name] = 1;
}
}
if (isset($tokens['text']['contact'])) {
foreach ($tokens['text']['contact'] as $name) {
$returnProperties[$name] = 1;
}
}
if (isset($tokens['html']['contact'])) {
foreach ($tokens['html']['contact'] as $name) {
$returnProperties[$name] = 1;
}
}
// @todo CRM-17253 don't resolve contact details if there are no tokens
// effectively comment out this next (performance-expensive) line
// but unfortunately testing is a bit think on the ground to that needs to
// be added.
list($contact) = CRM_Utils_Token::getTokenDetails($contactParams,
$returnProperties,
FALSE, FALSE, NULL,
CRM_Utils_Token::flattenTokens($tokens),
// we should consider adding groupName and valueName here
'CRM_Core_BAO_MessageTemplate'
);
$contact = $contact[$contactID];
}
$mailContent['subject'] = CRM_Utils_Token::replaceDomainTokens($mailContent['subject'], $domain, FALSE, $tokens['subject'], TRUE);
$mailContent['text'] = CRM_Utils_Token::replaceDomainTokens($mailContent['text'], $domain, FALSE, $tokens['text'], TRUE);
$mailContent['html'] = CRM_Utils_Token::replaceDomainTokens($mailContent['html'], $domain, TRUE, $tokens['html'], TRUE);
if ($contactID) {
$mailContent['subject'] = CRM_Utils_Token::replaceContactTokens($mailContent['subject'], $contact, FALSE, $tokens['subject'], FALSE, TRUE);
$mailContent['text'] = CRM_Utils_Token::replaceContactTokens($mailContent['text'], $contact, FALSE, $tokens['text'], FALSE, TRUE);
$mailContent['html'] = CRM_Utils_Token::replaceContactTokens($mailContent['html'], $contact, FALSE, $tokens['html'], FALSE, TRUE);
$contactArray = array($contactID => $contact);
CRM_Utils_Hook::tokenValues($contactArray,
array($contactID),
NULL,
CRM_Utils_Token::flattenTokens($tokens),
// we should consider adding groupName and valueName here
'CRM_Core_BAO_MessageTemplate'
);
$contact = $contactArray[$contactID];
$mailContent['subject'] = CRM_Utils_Token::replaceHookTokens($mailContent['subject'], $contact, $categories, TRUE);
$mailContent['text'] = CRM_Utils_Token::replaceHookTokens($mailContent['text'], $contact, $categories, TRUE);
$mailContent['html'] = CRM_Utils_Token::replaceHookTokens($mailContent['html'], $contact, $categories, TRUE);
}
// strip whitespace from ends and turn into a single line
$mailContent['subject'] = "{strip}{$mailContent['subject']}{/strip}";
// parse the three elements with Smarty
$smarty = CRM_Core_Smarty::singleton();
foreach ($params['tplParams'] as $name => $value) {
$smarty->assign($name, $value);
}
foreach (array(
'subject',
'text',
'html',
) as $elem) {
$mailContent[$elem] = $smarty->fetch("string:{$mailContent[$elem]}");
}
// send the template, honouring the target users preferences (if any)
$sent = FALSE;
// create the params array
$params['subject'] = $mailContent['subject'];
$params['text'] = $mailContent['text'];
$params['html'] = $mailContent['html'];
if ($params['toEmail']) {
$contactParams = array(array('email', 'LIKE', $params['toEmail'], 0, 1));
list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($contactParams);
$prefs = array_pop($contact);
if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'HTML') {
$params['text'] = NULL;
}
if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'Text') {
$params['html'] = NULL;
}
$config = CRM_Core_Config::singleton();
if (isset($params['isEmailPdf']) && $params['isEmailPdf'] == 1) {
$pdfHtml = CRM_Contribute_BAO_ContributionPage::addInvoicePdfToEmail($params['contributionId'], $params['contactId']);
if (empty($params['attachments'])) {
$params['attachments'] = array();
}
$params['attachments'][] = CRM_Utils_Mail::appendPDF('Invoice.pdf', $pdfHtml, $mailContent['format']);
}
$pdf_filename = '';
if ($config->doNotAttachPDFReceipt &&
$params['PDFFilename'] &&
$params['html']
) {
if (empty($params['attachments'])) {
$params['attachments'] = array();
}
$params['attachments'][] = CRM_Utils_Mail::appendPDF($params['PDFFilename'], $params['html'], $mailContent['format']);
if (isset($params['tplParams']['email_comment'])) {
$params['html'] = $params['tplParams']['email_comment'];
$params['text'] = strip_tags($params['tplParams']['email_comment']);
}
}
$sent = CRM_Utils_Mail::send($params);
if ($pdf_filename) {
unlink($pdf_filename);
}
}
return array($sent, $mailContent['subject'], $mailContent['text'], $mailContent['html']);
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,596 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* BAO object for crm_note table.
*/
class CRM_Core_BAO_Note extends CRM_Core_DAO_Note {
/**
* Const the max number of notes we display at any given time.
* @var int
*/
const MAX_NOTES = 3;
/**
* Given a note id, retrieve the note text.
*
* @param int $id
* Id of the note to retrieve.
*
* @return string
* the note text or NULL if note not found
*
*/
public static function getNoteText($id) {
return CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Note', $id, 'note');
}
/**
* Given a note id, retrieve the note subject
*
* @param int $id
* Id of the note to retrieve.
*
* @return string
* the note subject or NULL if note not found
*
*/
public static function getNoteSubject($id) {
return CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Note', $id, 'subject');
}
/**
* Given a note id, decide if the note should be displayed based on privacy setting
*
* @param object $note
* Either the id of the note to retrieve, or the CRM_Core_DAO_Note object itself.
*
* @return bool
* TRUE if the note should be displayed, otherwise FALSE
*
*/
public static function getNotePrivacyHidden($note) {
if (CRM_Core_Permission::check('view all notes')) {
return FALSE;
}
$noteValues = array();
if (is_object($note) && get_class($note) == 'CRM_Core_DAO_Note') {
CRM_Core_DAO::storeValues($note, $noteValues);
}
else {
$noteDAO = new CRM_Core_DAO_Note();
$noteDAO->id = $note;
$noteDAO->find();
if ($noteDAO->fetch()) {
CRM_Core_DAO::storeValues($noteDAO, $noteValues);
}
}
CRM_Utils_Hook::notePrivacy($noteValues);
if (!$noteValues['privacy']) {
return FALSE;
}
elseif (isset($noteValues['notePrivacy_hidden'])) {
// If the hook has set visibility, use that setting.
return $noteValues['notePrivacy_hidden'];
}
else {
// Default behavior (if hook has not set visibility)
// is to hide privacy notes unless the note creator is the current user.
if ($noteValues['privacy']) {
$session = CRM_Core_Session::singleton();
$userID = $session->get('userID');
return ($noteValues['contact_id'] != $userID);
}
else {
return FALSE;
}
}
}
/**
* Takes an associative array and creates a note object.
*
* the function extract all the params it needs to initialize the create a
* note object. the params array could contain additional unused name/value
* pairs
*
* @param array $params
* (reference) an assoc array of name/value pairs.
* @param array $ids
* (deprecated) associated array with note id - preferably set $params['id'].
*
* @return object|null
* $note CRM_Core_BAO_Note object
*/
public static function add(&$params, $ids = array()) {
$dataExists = self::dataExists($params);
if (!$dataExists) {
return NULL;
}
if (!empty($params['entity_table']) && $params['entity_table'] == 'civicrm_contact' && !empty($params['check_permissions'])) {
if (!CRM_Contact_BAO_Contact_Permission::allow($params['entity_id'], CRM_Core_Permission::EDIT)) {
throw new CRM_Exception('Permission denied to modify contact record');
}
}
$note = new CRM_Core_BAO_Note();
if (!isset($params['modified_date'])) {
$params['modified_date'] = date("Ymd");
}
if (!isset($params['privacy'])) {
$params['privacy'] = 0;
}
$note->copyValues($params);
if (empty($params['contact_id'])) {
if ($params['entity_table'] == 'civicrm_contact') {
$note->contact_id = $params['entity_id'];
}
}
$id = CRM_Utils_Array::value('id', $params, CRM_Utils_Array::value('id', $ids));
if ($id) {
$note->id = $id;
}
$note->save();
// check and attach and files as needed
CRM_Core_BAO_File::processAttachment($params, 'civicrm_note', $note->id);
if ($note->entity_table == 'civicrm_contact') {
CRM_Core_BAO_Log::register($note->entity_id,
'civicrm_note',
$note->id
);
$displayName = CRM_Contact_BAO_Contact::displayName($note->entity_id);
$noteActions = FALSE;
$session = CRM_Core_Session::singleton();
if ($session->get('userID')) {
if ($session->get('userID') == $note->entity_id) {
$noteActions = TRUE;
}
elseif (CRM_Contact_BAO_Contact_Permission::allow($note->entity_id, CRM_Core_Permission::EDIT)) {
$noteActions = TRUE;
}
}
$recentOther = array();
if ($noteActions) {
$recentOther = array(
'editUrl' => CRM_Utils_System::url('civicrm/contact/view/note',
"reset=1&action=update&cid={$note->entity_id}&id={$note->id}&context=home"
),
'deleteUrl' => CRM_Utils_System::url('civicrm/contact/view/note',
"reset=1&action=delete&cid={$note->entity_id}&id={$note->id}&context=home"
),
);
}
// add the recently created Note
CRM_Utils_Recent::add($displayName . ' - ' . $note->subject,
CRM_Utils_System::url('civicrm/contact/view/note',
"reset=1&action=view&cid={$note->entity_id}&id={$note->id}&context=home"
),
$note->id,
'Note',
$note->entity_id,
$displayName,
$recentOther
);
}
return $note;
}
/**
* Check if there is data to create the object.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
*
* @return bool
*/
public static function dataExists(&$params) {
// return if no data present
if (!strlen($params['note'])) {
return FALSE;
}
return TRUE;
}
/**
* Given the list of params in the params array, fetch the object
* and store the values in the values array
*
* @param array $params
* Input parameters to find object.
* @param array $values
* Output values of the object.
* @param int $numNotes
* The maximum number of notes to return (0 if all).
*
* @return object
* $notes Object of CRM_Core_BAO_Note
*/
public static function &getValues(&$params, &$values, $numNotes = self::MAX_NOTES) {
if (empty($params)) {
return NULL;
}
$note = new CRM_Core_BAO_Note();
$note->entity_id = $params['contact_id'];
$note->entity_table = 'civicrm_contact';
// get the total count of notes
$values['noteTotalCount'] = $note->count();
// get only 3 recent notes
$note->orderBy('modified_date desc');
$note->limit($numNotes);
$note->find();
$notes = array();
$count = 0;
while ($note->fetch()) {
$values['note'][$note->id] = array();
CRM_Core_DAO::storeValues($note, $values['note'][$note->id]);
$notes[] = $note;
$count++;
// if we have collected the number of notes, exit loop
if ($numNotes > 0 && $count >= $numNotes) {
break;
}
}
return $notes;
}
/**
* Delete the notes.
*
* @param int $id
* Note id.
* @param bool $showStatus
* Do we need to set status or not.
*
* @return int|NULL
* no of deleted notes on success, null otherwise
*/
public static function del($id, $showStatus = TRUE) {
$return = NULL;
$recent = array($id);
$note = new CRM_Core_DAO_Note();
$note->id = $id;
$note->find();
$note->fetch();
if ($note->entity_table == 'civicrm_note') {
$status = ts('Selected Comment has been deleted successfully.');
}
else {
$status = ts('Selected Note has been deleted successfully.');
}
// Delete all descendents of this Note
foreach (self::getDescendentIds($id) as $childId) {
$childNote = new CRM_Core_DAO_Note();
$childNote->id = $childId;
$childNote->delete();
$childNote->free();
$recent[] = $childId;
}
$return = $note->delete();
$note->free();
if ($showStatus) {
CRM_Core_Session::setStatus($status, ts('Deleted'), 'success');
}
// delete the recently created Note
foreach ($recent as $recentId) {
$noteRecent = array(
'id' => $recentId,
'type' => 'Note',
);
CRM_Utils_Recent::del($noteRecent);
}
return $return;
}
/**
* Delete all records for this contact id.
*
* @param int $id
* ID of the contact for which note needs to be deleted.
*/
public static function deleteContact($id) {
// need to delete for both entity_id
$dao = new CRM_Core_DAO_Note();
$dao->entity_table = 'civicrm_contact';
$dao->entity_id = $id;
$dao->delete();
// and the creator contact id
$dao = new CRM_Core_DAO_Note();
$dao->contact_id = $id;
$dao->delete();
}
/**
* Retrieve all records for this entity-id
*
* @param int $id
* ID of the relationship for which records needs to be retrieved.
*
* @param string $entityTable
*
* @return array
* array of note properties
*
*/
public static function &getNote($id, $entityTable = 'civicrm_relationship') {
$viewNote = array();
$query = "
SELECT id,
note
FROM civicrm_note
WHERE entity_table=\"{$entityTable}\"
AND entity_id = %1
AND note is not null
ORDER BY modified_date desc";
$params = array(1 => array($id, 'Integer'));
$dao = CRM_Core_DAO::executeQuery($query, $params);
while ($dao->fetch()) {
$viewNote[$dao->id] = $dao->note;
}
return $viewNote;
}
/**
* Get log record count for a Contact.
*
* @param int $contactID
*
* @return int
* $count count of log records
*
*/
public static function getContactNoteCount($contactID) {
$note = new CRM_Core_DAO_Note();
$note->entity_id = $contactID;
$note->entity_table = 'civicrm_contact';
$note->find();
$count = 0;
while ($note->fetch()) {
if (!self::getNotePrivacyHidden($note)) {
$count++;
}
}
return $count;
}
/**
* Get all descendent notes of the note with given ID.
*
* @param int $parentId
* ID of the note to start from.
* @param int $maxDepth
* Maximum number of levels to descend into the tree; if not given, will include all descendents.
* @param bool $snippet
* If TRUE, returned values will be pre-formatted for display in a table of notes.
*
* @return array
* Nested associative array beginning with direct children of given note.
*
*/
public static function getNoteTree($parentId, $maxDepth = 0, $snippet = FALSE) {
return self::buildNoteTree($parentId, $maxDepth, $snippet);
}
/**
* Get total count of direct children visible to the current user.
*
* @param int $id
* Note ID.
*
* @return int
* $count Number of notes having the give note as parent
*
*/
public static function getChildCount($id) {
$note = new CRM_Core_DAO_Note();
$note->entity_table = 'civicrm_note';
$note->entity_id = $id;
$note->find();
$count = 0;
while ($note->fetch()) {
if (!self::getNotePrivacyHidden($note)) {
$count++;
}
}
return $count;
}
/**
* Recursive function to get all descendent notes of the note with given ID.
*
* @param int $parentId
* ID of the note to start from.
* @param int $maxDepth
* Maximum number of levels to descend into the tree; if not given, will include all descendents.
* @param bool $snippet
* If TRUE, returned values will be pre-formatted for display in a table of notes.
* @param array $tree
* (Reference) Variable to store all found descendents.
* @param int $depth
* Depth of current iteration within the descendent tree (used for comparison against maxDepth).
*
* @return array
* Nested associative array beginning with direct children of given note.
*/
private static function buildNoteTree($parentId, $maxDepth = 0, $snippet = FALSE, &$tree = array(), $depth = 0) {
if ($maxDepth && $depth > $maxDepth) {
return FALSE;
}
// get direct children of given parentId note
$note = new CRM_Core_DAO_Note();
$note->entity_table = 'civicrm_note';
$note->entity_id = $parentId;
$note->orderBy('modified_date asc');
$note->find();
while ($note->fetch()) {
// foreach child, call this function, unless the child is private/hidden
if (!self::getNotePrivacyHidden($note)) {
CRM_Core_DAO::storeValues($note, $tree[$note->id]);
// get name of user that created this note
$contact = new CRM_Contact_DAO_Contact();
$createdById = $note->contact_id;
$contact->id = $createdById;
$contact->find();
$contact->fetch();
$tree[$note->id]['createdBy'] = $contact->display_name;
$tree[$note->id]['createdById'] = $createdById;
$tree[$note->id]['modified_date'] = CRM_Utils_Date::customFormat($tree[$note->id]['modified_date']);
// paper icon view for attachments part
$paperIconAttachmentInfo = CRM_Core_BAO_File::paperIconAttachment('civicrm_note', $note->id);
$tree[$note->id]['attachment'] = $paperIconAttachmentInfo ? implode('', $paperIconAttachmentInfo) : '';
if ($snippet) {
$tree[$note->id]['note'] = nl2br($tree[$note->id]['note']);
$tree[$note->id]['note'] = smarty_modifier_mb_truncate(
$tree[$note->id]['note'],
80,
'...',
TRUE
);
CRM_Utils_Date::customFormat($tree[$note->id]['modified_date']);
}
self::buildNoteTree(
$note->id,
$maxDepth,
$snippet,
$tree[$note->id]['child'],
$depth + 1
);
}
}
return $tree;
}
/**
* Given a note id, get a list of the ids of all notes that are descendents of that note
*
* @param int $parentId
* Id of the given note.
* @param array $ids
* (reference) one-dimensional array to store found descendent ids.
*
* @return array
* One-dimensional array containing ids of all desendent notes
*/
public static function getDescendentIds($parentId, &$ids = array()) {
// get direct children of given parentId note
$note = new CRM_Core_DAO_Note();
$note->entity_table = 'civicrm_note';
$note->entity_id = $parentId;
$note->find();
while ($note->fetch()) {
// foreach child, add to ids list, and recurse
$ids[] = $note->id;
self::getDescendentIds($note->id, $ids);
}
return $ids;
}
/**
* Delete all note related to contact when contact is deleted.
*
* @param int $contactID
* Contact id whose notes to be deleted.
*/
public static function cleanContactNotes($contactID) {
$params = array(1 => array($contactID, 'Integer'));
// delete all notes related to contribution
$contributeQuery = "DELETE note.*
FROM civicrm_note note LEFT JOIN civicrm_contribution contribute ON note.entity_id = contribute.id
WHERE contribute.contact_id = %1 AND note.entity_table = 'civicrm_contribution'";
CRM_Core_DAO::executeQuery($contributeQuery, $params);
// delete all notes related to participant
$participantQuery = "DELETE note.*
FROM civicrm_note note LEFT JOIN civicrm_participant participant ON note.entity_id = participant.id
WHERE participant.contact_id = %1 AND note.entity_table = 'civicrm_participant'";
CRM_Core_DAO::executeQuery($participantQuery, $params);
// delete all contact notes
$contactQuery = "SELECT id FROM civicrm_note WHERE entity_id = %1 AND entity_table = 'civicrm_contact'";
$contactNoteId = CRM_Core_DAO::executeQuery($contactQuery, $params);
while ($contactNoteId->fetch()) {
self::del($contactNoteId->id, FALSE);
}
}
/**
* Whitelist of possible values for the entity_table field
* @return array
*/
public static function entityTables() {
return array(
'civicrm_relationship' => 'Relationship',
'civicrm_contact' => 'Contact',
'civicrm_participant' => 'Participant',
'civicrm_contribution' => 'Contribution',
);
}
}

View file

@ -0,0 +1,155 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class contains function for Open Id
*/
class CRM_Core_BAO_OpenID extends CRM_Core_DAO_OpenID {
/**
* Takes an associative array and adds OpenID.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
*
* @return object
* CRM_Core_BAO_OpenID object on success, null otherwise
*/
public static function add(&$params) {
$hook = empty($params['id']) ? 'create' : 'edit';
CRM_Utils_Hook::pre($hook, 'OpenID', CRM_Utils_Array::value('id', $params), $params);
$openId = new CRM_Core_DAO_OpenID();
$openId->copyValues($params);
$openId->save();
CRM_Utils_Hook::post($hook, 'OpenID', $openId->id, $openId);
return $openId;
}
/**
* Given the list of params in the params array, fetch the object
* and store the values in the values array
*
* @param array $entityBlock
* Input parameters to find object.
*
* @return mixed
*/
public static function &getValues($entityBlock) {
return CRM_Core_BAO_Block::getValues('openid', $entityBlock);
}
/**
* Returns whether or not this OpenID is allowed to login.
*
* @param string $identity_url
* The OpenID to check.
*
* @return bool
*/
public static function isAllowedToLogin($identity_url) {
$openId = new CRM_Core_DAO_OpenID();
$openId->openid = $identity_url;
if ($openId->find(TRUE)) {
return $openId->allowed_to_login == 1;
}
return FALSE;
}
/**
* Get all the openids for a specified contact_id, with the primary openid being first
*
* @param int $id
* The contact id.
*
* @param bool $updateBlankLocInfo
*
* @return array
* the array of openid's
*/
public static function allOpenIDs($id, $updateBlankLocInfo = FALSE) {
if (!$id) {
return NULL;
}
$query = "
SELECT civicrm_openid.openid, civicrm_location_type.name as locationType, civicrm_openid.is_primary as is_primary,
civicrm_openid.allowed_to_login as allowed_to_login, civicrm_openid.id as openid_id,
civicrm_openid.location_type_id as locationTypeId
FROM civicrm_contact
LEFT JOIN civicrm_openid ON ( civicrm_openid.contact_id = civicrm_contact.id )
LEFT JOIN civicrm_location_type ON ( civicrm_openid.location_type_id = civicrm_location_type.id )
WHERE
civicrm_contact.id = %1
ORDER BY
civicrm_openid.is_primary DESC, openid_id ASC ";
$params = array(1 => array($id, 'Integer'));
$openids = $values = array();
$dao = CRM_Core_DAO::executeQuery($query, $params);
$count = 1;
while ($dao->fetch()) {
$values = array(
'locationType' => $dao->locationType,
'is_primary' => $dao->is_primary,
'id' => $dao->openid_id,
'openid' => $dao->openid,
'locationTypeId' => $dao->locationTypeId,
'allowed_to_login' => $dao->allowed_to_login,
);
if ($updateBlankLocInfo) {
$openids[$count++] = $values;
}
else {
$openids[$dao->openid_id] = $values;
}
}
return $openids;
}
/**
* Call common delete function.
*
* @param int $id
*
* @return bool
*/
public static function del($id) {
return CRM_Contact_BAO_Contact::deleteObjectWithPrimary('OpenID', $id);
}
}

View file

@ -0,0 +1,254 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
class CRM_Core_BAO_OptionGroup extends CRM_Core_DAO_OptionGroup {
/**
* Class constructor.
*/
public function __construct() {
parent::__construct();
}
/**
* Fetch object based on array of properties.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $defaults
* (reference ) an assoc array to hold the flattened values.
*
* @return CRM_Core_BAO_OptionGroup
*/
public static function retrieve(&$params, &$defaults) {
$optionGroup = new CRM_Core_DAO_OptionGroup();
$optionGroup->copyValues($params);
if ($optionGroup->find(TRUE)) {
CRM_Core_DAO::storeValues($optionGroup, $defaults);
return $optionGroup;
}
return NULL;
}
/**
* Update the is_active flag in the db.
*
* @param int $id
* Id of the database record.
* @param bool $is_active
* Value we want to set the is_active field.
*
* @return Object
* DAO object on success, null otherwise
*/
public static function setIsActive($id, $is_active) {
return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_OptionGroup', $id, 'is_active', $is_active);
}
/**
* Add the Option Group.
*
* @param array $params
* Reference array contains the values submitted by the form.
* @param array $ids
* Reference array contains the id.
*
*
* @return object
*/
public static function add(&$params, $ids = array()) {
if (empty($params['id'])) {
$params['id'] = CRM_Utils_Array::value('optionGroup', $ids);
}
$params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
$params['is_default'] = CRM_Utils_Array::value('is_default', $params, FALSE);
// action is taken depending upon the mode
$optionGroup = new CRM_Core_DAO_OptionGroup();
$optionGroup->copyValues($params);;
if ($params['is_default']) {
$query = "UPDATE civicrm_option_group SET is_default = 0";
CRM_Core_DAO::executeQuery($query);
}
$optionGroup->save();
return $optionGroup;
}
/**
* Delete Option Group.
*
* @param int $optionGroupId
* Id of the Option Group to be deleted.
*/
public static function del($optionGroupId) {
// need to delete all option value field before deleting group
$optionValue = new CRM_Core_DAO_OptionValue();
$optionValue->option_group_id = $optionGroupId;
$optionValue->delete();
$optionGroup = new CRM_Core_DAO_OptionGroup();
$optionGroup->id = $optionGroupId;
$optionGroup->delete();
}
/**
* Get title of the option group.
*
* @param int $optionGroupId
* Id of the Option Group.
*
* @return string
* title
*/
public static function getTitle($optionGroupId) {
$optionGroup = new CRM_Core_DAO_OptionGroup();
$optionGroup->id = $optionGroupId;
$optionGroup->find(TRUE);
return $optionGroup->name;
}
/**
* Get DataType for a specified option Group
*
* @param int $optionGroupId
* Id of the Option Group.
*
* @return string|null
* Data Type
*/
public static function getDataType($optionGroupId) {
$optionGroup = new CRM_Core_DAO_OptionGroup();
$optionGroup->id = $optionGroupId;
$optionGroup->find(TRUE);
return $optionGroup->data_type;
}
/**
* Ensure an option group exists.
*
* This function is intended to be called from the upgrade script to ensure
* that an option group exists, without hitting an error if it already exists.
*
* This is sympathetic to sites who might pre-add it.
*
* @param array $params
*
* @return int
* ID of the option group.
*/
public static function ensureOptionGroupExists($params) {
$existingValues = civicrm_api3('OptionGroup', 'get', array(
'name' => $params['name'],
'return' => 'id',
));
if (!$existingValues['count']) {
$result = civicrm_api3('OptionGroup', 'create', $params);
return $result['id'];
}
else {
return $existingValues['id'];
}
}
/**
* Get the title of an option group by name.
*
* @param string $name
* The name value for the option group table.
*
* @return string
* The relevant title.
*/
public static function getTitleByName($name) {
$groups = self::getTitlesByNames();
return $groups[$name];
}
/**
* Get a cached mapping of all group titles indexed by their unique name.
*
* We tend to only have a limited number of option groups so memory caching
* makes more sense than multiple look-ups.
*
* @return array
* Array of all group titles by name.
* e.g
* array('activity_status' => 'Activity Status', 'msg_mode' => 'Message Mode'....)
*/
public static function getTitlesByNames() {
if (!isset(\Civi::$statics[__CLASS__]) || !isset(\Civi::$statics[__CLASS__]['titles_by_name'])) {
$dao = CRM_Core_DAO::executeQuery("SELECT name, title FROM civicrm_option_group");
while ($dao->fetch()) {
\Civi::$statics[__CLASS__]['titles_by_name'][$dao->name] = $dao->title;
}
}
return \Civi::$statics[__CLASS__]['titles_by_name'];
}
/**
* Set the given values to active, and set all other values to inactive.
*
* @param string $optionGroupName
* e.g "languages"
* @param array<string> $activeValues
* e.g. array("en_CA","fr_CA")
*/
public static function setActiveValues($optionGroupName, $activeValues) {
$params = array(
1 => array($optionGroupName, 'String'),
);
// convert activeValues into placeholders / params in the query
$placeholders = array();
$i = count($params) + 1;
foreach ($activeValues as $value) {
$placeholders[] = "%{$i}";
$params[$i] = array($value, 'String');
$i++;
}
$placeholders = implode(', ', $placeholders);
CRM_Core_DAO::executeQuery("
UPDATE civicrm_option_value cov
LEFT JOIN civicrm_option_group cog ON cov.option_group_id = cog.id
SET cov.is_active = CASE WHEN cov.name IN ({$placeholders}) THEN 1 ELSE 0 END
WHERE cog.name = %1",
$params
);
}
}

View file

@ -0,0 +1,554 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_Core_BAO_OptionValue extends CRM_Core_DAO_OptionValue {
/**
* Class constructor.
*/
public function __construct() {
parent::__construct();
}
/**
* Create option value.
*
* Note that the create function calls 'add' but has more business logic.
*
* @param array $params
* Input parameters.
*
* @return object
*/
public static function create($params) {
if (empty($params['id'])) {
self::setDefaults($params);
}
$ids = array();
if (!empty($params['id'])) {
$ids = array('optionValue' => $params['id']);
}
return CRM_Core_BAO_OptionValue::add($params, $ids);
}
/**
* Set default Parameters.
* This functions sets default parameters if not set:
* - name & label are set to each other as required (it might make more sense for one
* to be required but this would mean a change to the api level)
* - weight & value will be set to their respective option groups next values
* if nothing is passed in.
*
* Note this function does not check for presence of $params['id'] so should only be called
* if 'id' is not present
*
* @param array $params
*/
public static function setDefaults(&$params) {
if (CRM_Utils_Array::value('label', $params, NULL) === NULL) {
$params['label'] = $params['name'];
}
if (CRM_Utils_Array::value('name', $params, NULL) === NULL) {
$params['name'] = $params['label'];
}
if (CRM_Utils_Array::value('weight', $params, NULL) === NULL) {
$params['weight'] = self::getDefaultWeight($params);
}
if (CRM_Utils_Array::value('value', $params, NULL) === NULL) {
$params['value'] = self::getDefaultValue($params);
}
}
/**
* Get next available value.
* We will take the highest numeric value (or 0 if no numeric values exist)
* and add one. The calling function is responsible for any
* more complex decision making
*
* @param array $params
*
* @return int
*/
public static function getDefaultWeight($params) {
return (int) CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_OptionValue',
array('option_group_id' => $params['option_group_id']));
}
/**
* Get next available value.
* We will take the highest numeric value (or 0 if no numeric values exist)
* and add one. The calling function is responsible for any
* more complex decision making
* @param array $params
*/
public static function getDefaultValue($params) {
$bao = new CRM_Core_BAO_OptionValue();
$bao->option_group_id = $params['option_group_id'];
if (isset($params['domain_id'])) {
$bao->domain_id = $params['domain_id'];
}
$bao->selectAdd();
$bao->whereAdd("value REGEXP '^[0-9]+$'");
$bao->selectAdd('(ROUND(COALESCE(MAX(CONVERT(value, UNSIGNED)),0)) +1) as nextvalue');
$bao->find(TRUE);
return $bao->nextvalue;
}
/**
* Fetch object based on array of properties.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $defaults
* (reference ) an assoc array to hold the flattened values.
*
* @return CRM_Core_BAO_OptionValue
*/
public static function retrieve(&$params, &$defaults) {
$optionValue = new CRM_Core_DAO_OptionValue();
$optionValue->copyValues($params);
if ($optionValue->find(TRUE)) {
CRM_Core_DAO::storeValues($optionValue, $defaults);
return $optionValue;
}
return NULL;
}
/**
* Update the is_active flag in the db.
*
* @param int $id
* Id of the database record.
* @param bool $is_active
* Value we want to set the is_active field.
*
* @return Object
* DAO object on success, null otherwise
*/
public static function setIsActive($id, $is_active) {
return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_OptionValue', $id, 'is_active', $is_active);
}
/**
* Add an Option Value.
*
* @param array $params
* Reference array contains the values submitted by the form.
* @param array $ids
* Reference array contains the id.
*
*
* @return CRM_Core_DAO_OptionValue
*/
public static function add(&$params, $ids = array()) {
// CRM-10921: do not reset attributes to default if this is an update
//@todo consider if defaults are being set in the right place. 'dumb' defaults like
// these would be usefully set @ the api layer so they are visible to api users
// complex defaults like the domain id below would make sense in the setDefauls function
// but unclear what other ways this function is being used
if (empty($ids['optionValue'])) {
$params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
$params['is_default'] = CRM_Utils_Array::value('is_default', $params, FALSE);
$params['is_optgroup'] = CRM_Utils_Array::value('is_optgroup', $params, FALSE);
$params['filter'] = CRM_Utils_Array::value('filter', $params, FALSE);
}
// Update custom field data to reflect the new value
elseif (isset($params['value'])) {
CRM_Core_BAO_CustomOption::updateValue($ids['optionValue'], $params['value']);
}
// action is taken depending upon the mode
$optionValue = new CRM_Core_DAO_OptionValue();
$optionValue->copyValues($params);
if (!empty($params['is_default'])) {
$query = 'UPDATE civicrm_option_value SET is_default = 0 WHERE option_group_id = %1';
// tweak default reset, and allow multiple default within group.
if ($resetDefaultFor = CRM_Utils_Array::value('reset_default_for', $params)) {
if (is_array($resetDefaultFor)) {
$colName = key($resetDefaultFor);
$colVal = $resetDefaultFor[$colName];
$query .= " AND ( $colName IN ( $colVal ) )";
}
}
$p = array(1 => array($params['option_group_id'], 'Integer'));
CRM_Core_DAO::executeQuery($query, $p);
}
// CRM-13814 : evalute option group id
if (!array_key_exists('option_group_id', $params) && !empty($ids['optionValue'])) {
$groupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue',
$ids['optionValue'], 'option_group_id', 'id'
);
}
else {
$groupId = $params['option_group_id'];
}
$groupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup',
$groupId, 'name', 'id'
);
if (empty($ids['optionValue']) && empty($params['id']) && !empty($params['value'])) {
$domainSpecifc = in_array($groupName, CRM_Core_OptionGroup::$_domainIDGroups) ? TRUE : FALSE;
$dao = new CRM_Core_DAO_OptionValue();
$dao->value = $params['value'];
$dao->option_group_id = $groupId;
if ($dao->find(TRUE)) {
throw new CRM_Core_Exception('Value already exists in the database');
}
}
if (in_array($groupName, CRM_Core_OptionGroup::$_domainIDGroups)) {
$optionValue->domain_id = CRM_Utils_Array::value('domain_id', $params, CRM_Core_Config::domainID());
}
$optionValue->id = CRM_Utils_Array::value('optionValue', $ids);
$optionValue->save();
CRM_Core_PseudoConstant::flush();
return $optionValue;
}
/**
* Delete Option Value.
*
* @param int $optionValueId
*
* @return bool
*
*/
public static function del($optionValueId) {
$optionValue = new CRM_Core_DAO_OptionValue();
$optionValue->id = $optionValueId;
if (!$optionValue->find()) {
return FALSE;
}
if (self::updateRecords($optionValueId, CRM_Core_Action::DELETE)) {
CRM_Core_PseudoConstant::flush();
$optionValue->delete();
return TRUE;
}
return FALSE;
}
/**
* Retrieve activity type label and description.
*
* @param int $activityTypeId
* Activity type id.
*
* @return array
* label and description
*/
public static function getActivityTypeDetails($activityTypeId) {
$query = "SELECT civicrm_option_value.label, civicrm_option_value.description
FROM civicrm_option_value
LEFT JOIN civicrm_option_group ON ( civicrm_option_value.option_group_id = civicrm_option_group.id )
WHERE civicrm_option_group.name = 'activity_type'
AND civicrm_option_value.value = {$activityTypeId} ";
$dao = CRM_Core_DAO::executeQuery($query);
$dao->fetch();
return array($dao->label, $dao->description);
}
/**
* Get the Option Value title.
*
* @param int $id
* Id of Option Value.
*
* @return string
* title
*
*/
public static function getTitle($id) {
return CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $id, 'label');
}
/**
* Updates contacts affected by the option value passed.
*
* @param int $optionValueId
* The option value id.
* @param int $action
* The action describing whether prefix/suffix was UPDATED or DELETED.
*
* @return bool
*/
public static function updateRecords(&$optionValueId, $action) {
//finding group name
$optionValue = new CRM_Core_DAO_OptionValue();
$optionValue->id = $optionValueId;
$optionValue->find(TRUE);
$optionGroup = new CRM_Core_DAO_OptionGroup();
$optionGroup->id = $optionValue->option_group_id;
$optionGroup->find(TRUE);
// group name
$gName = $optionGroup->name;
// value
$value = $optionValue->value;
// get the proper group name & affected field name
// todo: this may no longer be needed for individuals - check inputs
$individuals = array(
'gender' => 'gender_id',
'individual_prefix' => 'prefix_id',
'individual_suffix' => 'suffix_id',
'communication_style' => 'communication_style_id',
// Not only Individuals -- but the code seems to be generic for all contact types, despite the naming...
);
$contributions = array('payment_instrument' => 'payment_instrument_id');
$activities = array('activity_type' => 'activity_type_id');
$participant = array('participant_role' => 'role_id');
$eventType = array('event_type' => 'event_type_id');
$aclRole = array('acl_role' => 'acl_role_id');
$all = array_merge($individuals, $contributions, $activities, $participant, $eventType, $aclRole);
$fieldName = '';
foreach ($all as $name => $id) {
if ($gName == $name) {
$fieldName = $id;
}
}
if ($fieldName == '') {
return TRUE;
}
if (array_key_exists($gName, $individuals)) {
$contactDAO = new CRM_Contact_DAO_Contact();
$contactDAO->$fieldName = $value;
$contactDAO->find();
while ($contactDAO->fetch()) {
if ($action == CRM_Core_Action::DELETE) {
$contact = new CRM_Contact_DAO_Contact();
$contact->id = $contactDAO->id;
$contact->find(TRUE);
// make sure dates doesn't get reset
$contact->birth_date = CRM_Utils_Date::isoToMysql($contact->birth_date);
$contact->deceased_date = CRM_Utils_Date::isoToMysql($contact->deceased_date);
$contact->$fieldName = 'NULL';
$contact->save();
}
}
return TRUE;
}
if (array_key_exists($gName, $contributions)) {
$contribution = new CRM_Contribute_DAO_Contribution();
$contribution->$fieldName = $value;
$contribution->find();
while ($contribution->fetch()) {
if ($action == CRM_Core_Action::DELETE) {
$contribution->$fieldName = 'NULL';
$contribution->save();
}
}
return TRUE;
}
if (array_key_exists($gName, $activities)) {
$activity = new CRM_Activity_DAO_Activity();
$activity->$fieldName = $value;
$activity->find();
while ($activity->fetch()) {
$activity->delete();
}
return TRUE;
}
//delete participant role, type and event type option value
if (array_key_exists($gName, $participant)) {
$participantValue = new CRM_Event_DAO_Participant();
$participantValue->$fieldName = $value;
if ($participantValue->find(TRUE)) {
return FALSE;
}
return TRUE;
}
//delete event type option value
if (array_key_exists($gName, $eventType)) {
$event = new CRM_Event_DAO_Event();
$event->$fieldName = $value;
if ($event->find(TRUE)) {
return FALSE;
}
return TRUE;
}
//delete acl_role option value
if (array_key_exists($gName, $aclRole)) {
$entityRole = new CRM_ACL_DAO_EntityRole();
$entityRole->$fieldName = $value;
$aclDAO = new CRM_ACL_DAO_ACL();
$aclDAO->entity_id = $value;
if ($entityRole->find(TRUE) || $aclDAO->find(TRUE)) {
return FALSE;
}
return TRUE;
}
}
/**
* Updates options values weights.
*
* @param int $opGroupId
* @param array $opWeights
* Options value , weight pair.
*/
public static function updateOptionWeights($opGroupId, $opWeights) {
if (!is_array($opWeights) || empty($opWeights)) {
return;
}
foreach ($opWeights as $opValue => $opWeight) {
$optionValue = new CRM_Core_DAO_OptionValue();
$optionValue->option_group_id = $opGroupId;
$optionValue->value = $opValue;
if ($optionValue->find(TRUE)) {
$optionValue->weight = $opWeight;
$optionValue->save();
}
$optionValue->free();
}
}
/**
* Get the values of all option values given an option group ID. Store in system cache
* Does not take any filtering arguments. The object is to avoid hitting the DB and retrieve
* from memory
*
* @param int $optionGroupID
* The option group for which we want the values from.
*
* @return array
* an array of array of values for this option group
*/
public static function getOptionValuesArray($optionGroupID) {
// check if we can get the field values from the system cache
$cacheKey = "CRM_Core_BAO_OptionValue_OptionGroupID_{$optionGroupID}";
$cache = CRM_Utils_Cache::singleton();
$optionValues = $cache->get($cacheKey);
if (empty($optionValues)) {
$dao = new CRM_Core_DAO_OptionValue();
$dao->option_group_id = $optionGroupID;
$dao->orderBy('weight ASC, label ASC');
$dao->find();
$optionValues = array();
while ($dao->fetch()) {
$optionValues[$dao->id] = array();
CRM_Core_DAO::storeValues($dao, $optionValues[$dao->id]);
}
$cache->set($cacheKey, $optionValues);
}
return $optionValues;
}
/**
* Get the values of all option values given an option group ID as a key => value pair
* Use above cached function to make it super efficient
*
* @param int $optionGroupID
* The option group for which we want the values from.
*
* @return array
* an associative array of label, value pairs
*/
public static function getOptionValuesAssocArray($optionGroupID) {
$optionValues = self::getOptionValuesArray($optionGroupID);
$options = array();
foreach ($optionValues as $id => $value) {
$options[$value['value']] = $value['label'];
}
return $options;
}
/**
* Get the values of all option values given an option group Name as a key => value pair
* Use above cached function to make it super efficient
*
* @param string $optionGroupName
* The option group name for which we want the values from.
*
* @return array
* an associative array of label, value pairs
*/
public static function getOptionValuesAssocArrayFromName($optionGroupName) {
$dao = new CRM_Core_DAO_OptionGroup();
$dao->name = $optionGroupName;
$dao->selectAdd();
$dao->selectAdd('id');
$dao->find(TRUE);
$optionValues = self::getOptionValuesArray($dao->id);
$options = array();
foreach ($optionValues as $id => $value) {
$options[$value['value']] = $value['label'];
}
return $options;
}
/**
* Ensure an option value exists.
*
* This function is intended to be called from the upgrade script to ensure
* that an option value exists, without hitting an error if it already exists.
*
* This is sympathetic to sites who might pre-add it.
*/
public static function ensureOptionValueExists($params) {
$existingValues = civicrm_api3('OptionValue', 'get', array(
'option_group_id' => $params['option_group_id'],
'name' => $params['name'],
'return' => 'id',
));
if (!$existingValues['count']) {
civicrm_api3('OptionValue', 'create', $params);
}
}
}

View file

@ -0,0 +1,344 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright (C) 2011 Marty Wright |
| Licensed to CiviCRM under the Academic Free License version 3.0. |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class contains functions for managing Paper Sizes.
*/
class CRM_Core_BAO_PaperSize extends CRM_Core_DAO_OptionValue {
/**
* Static holder for the Paper Size Option Group ID.
*/
private static $_gid = NULL;
/**
* Paper Size fields stored in the 'value' field of the Option Value table.
*/
private static $optionValueFields = array(
'metric' => array(
'name' => 'metric',
'type' => CRM_Utils_Type::T_STRING,
'default' => 'mm',
),
'width' => array(
'name' => 'width',
'type' => CRM_Utils_Type::T_FLOAT,
'metric' => TRUE,
'default' => 612,
),
'height' => array(
'name' => 'height',
'type' => CRM_Utils_Type::T_FLOAT,
'metric' => TRUE,
'default' => 792,
),
);
/**
* Get Option Group ID for Paper Sizes.
*
* @return int
* Group ID (null if Group ID doesn't exist)
*/
private static function _getGid() {
if (!self::$_gid) {
self::$_gid = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'paper_size', 'id', 'name');
if (!self::$_gid) {
CRM_Core_Error::fatal(ts('Paper Size Option Group not found in database.'));
}
}
return self::$_gid;
}
/**
* Add ordering fields to Paper Size list.
*
* @param array (reference) $list List of Paper Sizes
* @param string $returnURL
* URL of page calling this function.
*
*/
public static function &addOrder(&$list, $returnURL) {
$filter = "option_group_id = " . self::_getGid();
CRM_Utils_Weight::addOrder($list, 'CRM_Core_DAO_OptionValue', 'id', $returnURL, $filter);
}
/**
* Retrieve list of Paper Sizes.
*
* @param bool $namesOnly
* Return simple list of names.
*
* @return array
* (reference) Paper Size list
*/
public static function &getList($namesOnly = FALSE) {
static $list = array();
if (self::_getGid()) {
// get saved Paper Sizes from Option Value table
$dao = new CRM_Core_DAO_OptionValue();
$dao->option_group_id = self::_getGid();
$dao->is_active = 1;
$dao->orderBy('weight');
$dao->find();
while ($dao->fetch()) {
if ($namesOnly) {
$list[$dao->name] = $dao->label;
}
else {
CRM_Core_DAO::storeValues($dao, $list[$dao->id]);
}
}
}
return $list;
}
/**
* Retrieve the default Paper Size values.
*
* @return array
* Name/value pairs containing the default Paper Size values.
*/
public static function &getDefaultValues() {
$params = array('is_active' => 1, 'is_default' => 1);
$defaults = array();
if (!self::retrieve($params, $defaults)) {
foreach (self::$optionValueFields as $name => $field) {
$defaults[$name] = $field['default'];
}
$filter = array('option_group_id' => self::_getGid());
$defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_OptionValue', $filter);
}
return $defaults;
}
/**
* Get Paper Size from the DB.
*
* @param string $field
* Field name to search by.
* @param int $val
* Field value to search for.
*
* @return array
* (reference) associative array of name/value pairs
*/
public static function &getPaperFormat($field, $val) {
$params = array('is_active' => 1, $field => $val);
$paperFormat = array();
if (self::retrieve($params, $paperFormat)) {
return $paperFormat;
}
else {
return self::getDefaultValues();
}
}
/**
* Get Paper Size by Name.
*
* @param int $name
* Paper Size name. Empty = get default Paper Size.
*
* @return array
* (reference) associative array of name/value pairs
*/
public static function &getByName($name) {
return self::getPaperFormat('name', $name);
}
/**
* Get Paper Size by ID.
*
* @param int $id
* Paper Size id. 0 = get default Paper Size.
*
* @return array
* (reference) associative array of name/value pairs
*/
public static function &getById($id) {
return self::getPaperFormat('id', $id);
}
/**
* Get Paper Size field from associative array.
*
* @param string $field
* Name of a Paper Size field.
* @param array (reference) $values associative array of name/value pairs containing
* Paper Size field selections
*
* @param null $default
*
* @return value
*/
public static function getValue($field, &$values, $default = NULL) {
if (array_key_exists($field, self::$optionValueFields)) {
switch (self::$optionValueFields[$field]['type']) {
case CRM_Utils_Type::T_INT:
return (int) CRM_Utils_Array::value($field, $values, $default);
case CRM_Utils_Type::T_FLOAT:
// Round float values to three decimal places and trim trailing zeros.
// Add a leading zero to values less than 1.
$f = sprintf('%05.3f', $values[$field]);
$f = rtrim($f, '0');
$f = rtrim($f, '.');
return (float) (empty($f) ? '0' : $f);
}
return CRM_Utils_Array::value($field, $values, $default);
}
return $default;
}
/**
* Retrieve DB object based on input parameters.
*
* It also stores all the retrieved values in the default array.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $values
* (reference ) an assoc array to hold the flattened values.
*
* @return CRM_Core_DAO_OptionValue
*/
public static function retrieve(&$params, &$values) {
$optionValue = new CRM_Core_DAO_OptionValue();
$optionValue->copyValues($params);
$optionValue->option_group_id = self::_getGid();
if ($optionValue->find(TRUE)) {
// Extract fields that have been serialized in the 'value' column of the Option Value table.
$values = json_decode($optionValue->value, TRUE);
// Add any new fields that don't yet exist in the saved values.
foreach (self::$optionValueFields as $name => $field) {
if (!isset($values[$name])) {
$values[$name] = $field['default'];
if ($field['metric']) {
$values[$name] = CRM_Utils_PDF_Utils::convertMetric($field['default'],
self::$optionValueFields['metric']['default'],
$values['metric'], 3
);
}
}
}
// Add fields from the OptionValue base class
CRM_Core_DAO::storeValues($optionValue, $values);
return $optionValue;
}
return NULL;
}
/**
* Save the Paper Size in the DB.
*
* @param array (reference) $values associative array of name/value pairs
* @param int $id
* Id of the database record (null = new record).
*/
public function savePaperSize(&$values, $id) {
// get the Option Group ID for Paper Sizes (create one if it doesn't exist)
$group_id = self::_getGid(TRUE);
// clear other default if this is the new default Paper Size
if ($values['is_default']) {
$query = "UPDATE civicrm_option_value SET is_default = 0 WHERE option_group_id = $group_id";
CRM_Core_DAO::executeQuery($query);
}
if ($id) {
// fetch existing record
$this->id = $id;
if ($this->find()) {
$this->fetch();
}
}
else {
// new record: set group = custom
$values['grouping'] = self::customGroupName();
}
// copy the supplied form values to the corresponding Option Value fields in the base class
foreach ($this->fields() as $name => $field) {
$this->$name = trim(CRM_Utils_Array::value($name, $values, $this->$name));
if (empty($this->$name)) {
$this->$name = 'null';
}
}
$this->id = $id;
$this->option_group_id = $group_id;
$this->label = $this->name;
$this->is_active = 1;
// serialize Paper Size fields into a single string to store in the 'value' column of the Option Value table
$v = json_decode($this->value, TRUE);
foreach (self::$optionValueFields as $name => $field) {
$v[$name] = self::getValue($name, $values, $v[$name]);
}
$this->value = json_encode($v);
// make sure serialized array will fit in the 'value' column
$attribute = CRM_Core_DAO::getAttribute('CRM_Core_BAO_PaperSize', 'value');
if (strlen($this->value) > $attribute['maxlength']) {
CRM_Core_Error::fatal(ts('Paper Size does not fit in database.'));
}
$this->save();
// fix duplicate weights
$filter = array('option_group_id' => self::_getGid());
CRM_Utils_Weight::correctDuplicateWeights('CRM_Core_DAO_OptionValue', $filter);
}
/**
* Delete a Paper Size.
*
* @param int $id
* ID of the Paper Size to be deleted.
*
*/
public static function del($id) {
if ($id) {
$dao = new CRM_Core_DAO_OptionValue();
$dao->id = $id;
if ($dao->find(TRUE)) {
if ($dao->option_group_id == self::_getGid()) {
$filter = array('option_group_id' => self::_getGid());
CRM_Utils_Weight::delWeight('CRM_Core_DAO_OptionValue', $id, $filter);
$dao->delete();
return;
}
}
}
CRM_Core_Error::fatal(ts('Invalid value passed to delete function.'));
}
}

View file

@ -0,0 +1,397 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright (C) 2011 Marty Wright |
| Licensed to CiviCRM under the Academic Free License version 3.0. |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class contains functions for managing PDF Page Formats.
*/
class CRM_Core_BAO_PdfFormat extends CRM_Core_DAO_OptionValue {
/**
* Static holder for the PDF Page Formats Option Group ID.
*/
private static $_gid = NULL;
/**
* PDF Page Format fields stored in the 'value' field of the Option Value table.
*/
private static $optionValueFields = array(
'paper_size' => array(
'name' => 'paper_size',
'type' => CRM_Utils_Type::T_STRING,
'default' => 'letter',
),
'stationery' => array(
'name' => 'stationery',
'type' => CRM_Utils_Type::T_STRING,
'default' => '',
),
'orientation' => array(
'name' => 'orientation',
'type' => CRM_Utils_Type::T_STRING,
'default' => 'portrait',
),
'metric' => array(
'name' => 'metric',
'type' => CRM_Utils_Type::T_STRING,
'default' => 'in',
),
'margin_top' => array(
'name' => 'margin_top',
'type' => CRM_Utils_Type::T_FLOAT,
'metric' => TRUE,
'default' => 0.75,
),
'margin_bottom' => array(
'name' => 'margin_bottom',
'type' => CRM_Utils_Type::T_FLOAT,
'metric' => TRUE,
'default' => 0.75,
),
'margin_left' => array(
'name' => 'margin_left',
'type' => CRM_Utils_Type::T_FLOAT,
'metric' => TRUE,
'default' => 0.75,
),
'margin_right' => array(
'name' => 'margin_right',
'type' => CRM_Utils_Type::T_FLOAT,
'metric' => TRUE,
'default' => 0.75,
),
);
/**
* Get page orientations recognized by the DOMPDF package used to create PDF letters.
*
* @return array
* array of page orientations
*/
public static function getPageOrientations() {
return array(
'portrait' => ts('Portrait'),
'landscape' => ts('Landscape'),
);
}
/**
* Get measurement units recognized by the DOMPDF package used to create PDF letters.
*
* @return array
* array of measurement units
*/
public static function getUnits() {
return array(
'in' => ts('Inches'),
'cm' => ts('Centimeters'),
'mm' => ts('Millimeters'),
'pt' => ts('Points'),
);
}
/**
* Get Option Group ID for PDF Page Formats.
*
* @return int
* Group ID (null if Group ID doesn't exist)
*/
private static function _getGid() {
if (!self::$_gid) {
self::$_gid = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'pdf_format', 'id', 'name');
if (!self::$_gid) {
CRM_Core_Error::fatal(ts('PDF Format Option Group not found in database.'));
}
}
return self::$_gid;
}
/**
* Add ordering fields to Page Format list.
*
* @param array (reference) $list List of PDF Page Formats
* @param string $returnURL
* URL of page calling this function.
*/
public static function addOrder(&$list, $returnURL) {
$filter = "option_group_id = " . self::_getGid();
CRM_Utils_Weight::addOrder($list, 'CRM_Core_DAO_OptionValue', 'id', $returnURL, $filter);
}
/**
* Get list of PDF Page Formats.
*
* @param bool $namesOnly
* Return simple list of names.
*
* @return array
* (reference) PDF Page Format list
*/
public static function &getList($namesOnly = FALSE) {
static $list = array();
if (self::_getGid()) {
// get saved PDF Page Formats from Option Value table
$dao = new CRM_Core_DAO_OptionValue();
$dao->option_group_id = self::_getGid();
$dao->is_active = 1;
$dao->orderBy('weight');
$dao->find();
while ($dao->fetch()) {
if ($namesOnly) {
$list[$dao->id] = $dao->name;
}
else {
CRM_Core_DAO::storeValues($dao, $list[$dao->id]);
}
}
}
return $list;
}
/**
* Get the default PDF Page Format values.
*
* @return array
* Name/value pairs containing the default PDF Page Format values.
*/
public static function &getDefaultValues() {
$params = array('is_active' => 1, 'is_default' => 1);
$defaults = array();
if (!self::retrieve($params, $defaults)) {
foreach (self::$optionValueFields as $name => $field) {
$defaults[$name] = $field['default'];
}
$filter = array('option_group_id' => self::_getGid());
$defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_OptionValue', $filter);
// also set the id to avoid NOTICES, CRM-8454
$defaults['id'] = NULL;
}
return $defaults;
}
/**
* Get PDF Page Format from the DB.
*
* @param string $field
* Field name to search by.
* @param int $val
* Field value to search for.
*
* @return array
* (reference) associative array of name/value pairs
*/
public static function &getPdfFormat($field, $val) {
$params = array('is_active' => 1, $field => $val);
$pdfFormat = array();
if (self::retrieve($params, $pdfFormat)) {
return $pdfFormat;
}
else {
return self::getDefaultValues();
}
}
/**
* Get PDF Page Format by Name.
*
* @param int $name
* PDF Page Format name. Empty = get default PDF Page Format.
*
* @return array
* (reference) associative array of name/value pairs
*/
public static function &getByName($name) {
return self::getPdfFormat('name', $name);
}
/**
* Get PDF Page Format by ID.
*
* @param int $id
* PDF Page Format id. 0 = get default PDF Page Format.
*
* @return array
* (reference) associative array of name/value pairs
*/
public static function &getById($id) {
return self::getPdfFormat('id', $id);
}
/**
* Get PDF Page Format field from associative array.
*
* @param string $field
* Name of a PDF Page Format field.
* @param array (reference) $values associative array of name/value pairs containing
* PDF Page Format field selections
*
* @param null $default
*
* @return value
*/
public static function getValue($field, &$values, $default = NULL) {
if (array_key_exists($field, self::$optionValueFields)) {
switch (self::$optionValueFields[$field]['type']) {
case CRM_Utils_Type::T_INT:
return (int) CRM_Utils_Array::value($field, $values, $default);
case CRM_Utils_Type::T_FLOAT:
// Round float values to three decimal places and trim trailing zeros.
// Add a leading zero to values less than 1.
$f = sprintf('%05.3f', $values[$field]);
$f = rtrim($f, '0');
$f = rtrim($f, '.');
return (float) (empty($f) ? '0' : $f);
}
return CRM_Utils_Array::value($field, $values, $default);
}
return $default;
}
/**
* Retrieve DB object based on input parameters.
*
* It also stores all the retrieved values in the default array.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $values
* (reference ) an assoc array to hold the flattened values.
*
* @return CRM_Core_DAO_OptionValue
*/
public static function retrieve(&$params, &$values) {
$optionValue = new CRM_Core_DAO_OptionValue();
$optionValue->copyValues($params);
$optionValue->option_group_id = self::_getGid();
if ($optionValue->find(TRUE)) {
// Extract fields that have been serialized in the 'value' column of the Option Value table.
$values = json_decode($optionValue->value, TRUE);
// Add any new fields that don't yet exist in the saved values.
foreach (self::$optionValueFields as $name => $field) {
if (!isset($values[$name])) {
$values[$name] = $field['default'];
if (!empty($field['metric'])) {
$values[$name] = CRM_Utils_PDF_Utils::convertMetric($field['default'],
self::$optionValueFields['metric']['default'],
$values['metric'], 3
);
}
}
}
// Add fields from the OptionValue base class
CRM_Core_DAO::storeValues($optionValue, $values);
return $optionValue;
}
return NULL;
}
/**
* Save the PDF Page Format in the DB.
*
* @param array $values associative array of name/value pairs
* @param int $id
* Id of the database record (null = new record).
*/
public function savePdfFormat(&$values, $id = NULL) {
// get the Option Group ID for PDF Page Formats (create one if it doesn't exist)
$group_id = self::_getGid();
// clear other default if this is the new default PDF Page Format
if ($values['is_default']) {
$query = "UPDATE civicrm_option_value SET is_default = 0 WHERE option_group_id = $group_id";
CRM_Core_DAO::executeQuery($query);
}
if ($id) {
// fetch existing record
$this->id = $id;
if ($this->find()) {
$this->fetch();
}
}
// copy the supplied form values to the corresponding Option Value fields in the base class
foreach ($this->fields() as $name => $field) {
$this->$name = trim(CRM_Utils_Array::value($name, $values, $this->$name));
if (empty($this->$name)) {
$this->$name = 'null';
}
}
$this->id = $id;
$this->option_group_id = $group_id;
$this->label = $this->name;
$this->is_active = 1;
// serialize PDF Page Format fields into a single string to store in the 'value' column of the Option Value table
$v = json_decode($this->value, TRUE);
foreach (self::$optionValueFields as $name => $field) {
$v[$name] = self::getValue($name, $values, CRM_Utils_Array::value($name, $v));
}
$this->value = json_encode($v);
// make sure serialized array will fit in the 'value' column
$attribute = CRM_Core_DAO::getAttribute('CRM_Core_BAO_PdfFormat', 'value');
if (strlen($this->value) > $attribute['maxlength']) {
CRM_Core_Error::fatal(ts('PDF Page Format does not fit in database.'));
}
$this->save();
// fix duplicate weights
$filter = array('option_group_id' => self::_getGid());
CRM_Utils_Weight::correctDuplicateWeights('CRM_Core_DAO_OptionValue', $filter);
}
/**
* Delete a PDF Page Format.
*
* @param int $id
* ID of the PDF Page Format to be deleted.
*
*/
public static function del($id) {
if ($id) {
$dao = new CRM_Core_DAO_OptionValue();
$dao->id = $id;
if ($dao->find(TRUE)) {
if ($dao->option_group_id == self::_getGid()) {
$filter = array('option_group_id' => self::_getGid());
CRM_Utils_Weight::delWeight('CRM_Core_DAO_OptionValue', $id, $filter);
$dao->delete();
return;
}
}
}
CRM_Core_Error::fatal(ts('Invalid value passed to delete function.'));
}
}

View file

@ -0,0 +1,111 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
class CRM_Core_BAO_Persistent extends CRM_Core_DAO_Persistent {
/**
* Fetch object based on array of properties.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $defaults
* (reference ) an assoc array to hold the flattened values.
*
* @return CRM_Core_BAO_Persistent
*/
public static function retrieve(&$params, &$defaults) {
$dao = new CRM_Core_DAO_Persistent();
$dao->copyValues($params);
if ($dao->find(TRUE)) {
CRM_Core_DAO::storeValues($dao, $defaults);
if (CRM_Utils_Array::value('is_config', $defaults) == 1) {
$defaults['data'] = unserialize($defaults['data']);
}
return $dao;
}
return NULL;
}
/**
* Add the Persistent Record.
*
* @param array $params
* Reference array contains the values submitted by the form.
* @param array $ids
* Reference array contains the id.
*
*
* @return object
*/
public static function add(&$params, &$ids) {
if (CRM_Utils_Array::value('is_config', $params) == 1) {
$params['data'] = serialize(explode(',', $params['data']));
}
$persistentDAO = new CRM_Core_DAO_Persistent();
$persistentDAO->copyValues($params);
$persistentDAO->id = CRM_Utils_Array::value('persistent', $ids);
$persistentDAO->save();
return $persistentDAO;
}
/**
* @param $context
* @param null $name
*
* @return mixed
*/
public static function getContext($context, $name = NULL) {
static $contextNameData = array();
if (!array_key_exists($context, $contextNameData)) {
$contextNameData[$context] = array();
$persisntentDAO = new CRM_Core_DAO_Persistent();
$persisntentDAO->context = $context;
$persisntentDAO->find();
while ($persisntentDAO->fetch()) {
$contextNameData[$context][$persisntentDAO->name] = $persisntentDAO->is_config == 1 ? unserialize($persisntentDAO->data) : $persisntentDAO->data;
}
}
if (empty($name)) {
return $contextNameData[$context];
}
else {
return CRM_Utils_Array::value($name, $contextNameData[$context]);
}
}
}

View file

@ -0,0 +1,276 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* Class contains functions for phone.
*/
class CRM_Core_BAO_Phone extends CRM_Core_DAO_Phone {
/**
* Create phone object - note that the create function calls 'add' but
* has more business logic
*
* @param array $params
*
* @return object
* @throws API_Exception
*/
public static function create($params) {
// Ensure mysql phone function exists
CRM_Core_DAO::checkSqlFunctionsExist();
if (is_numeric(CRM_Utils_Array::value('is_primary', $params)) ||
// if id is set & is_primary isn't we can assume no change
empty($params['id'])
) {
CRM_Core_BAO_Block::handlePrimary($params, get_class());
}
$phone = self::add($params);
return $phone;
}
/**
* Takes an associative array and adds phone.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
*
* @return object
* CRM_Core_BAO_Phone object on success, null otherwise
*/
public static function add(&$params) {
// Ensure mysql phone function exists
CRM_Core_DAO::checkSqlFunctionsExist();
$hook = empty($params['id']) ? 'create' : 'edit';
CRM_Utils_Hook::pre($hook, 'Phone', CRM_Utils_Array::value('id', $params), $params);
$phone = new CRM_Core_DAO_Phone();
$phone->copyValues($params);
$phone->save();
CRM_Utils_Hook::post($hook, 'Phone', $phone->id, $phone);
return $phone;
}
/**
* Given the list of params in the params array, fetch the object
* and store the values in the values array
*
* @param array $entityBlock
*
* @return array
* array of phone objects
*/
public static function &getValues($entityBlock) {
$getValues = CRM_Core_BAO_Block::getValues('phone', $entityBlock);
return $getValues;
}
/**
* Get all the phone numbers for a specified contact_id, with the primary being first
*
* @param int $id
* The contact id.
*
* @param bool $updateBlankLocInfo
* @param null $type
* @param array $filters
*
* @return array
* the array of phone ids which are potential numbers
*/
public static function allPhones($id, $updateBlankLocInfo = FALSE, $type = NULL, $filters = array()) {
if (!$id) {
return NULL;
}
$cond = NULL;
if ($type) {
$phoneTypeId = array_search($type, CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'));
if ($phoneTypeId) {
$cond = " AND civicrm_phone.phone_type_id = $phoneTypeId";
}
}
if (!empty($filters) && is_array($filters)) {
foreach ($filters as $key => $value) {
$cond .= " AND " . $key . " = " . $value;
}
}
$query = "
SELECT phone, civicrm_location_type.name as locationType, civicrm_phone.is_primary as is_primary,
civicrm_phone.id as phone_id, civicrm_phone.location_type_id as locationTypeId,
civicrm_phone.phone_type_id as phoneTypeId
FROM civicrm_contact
LEFT JOIN civicrm_phone ON ( civicrm_contact.id = civicrm_phone.contact_id )
LEFT JOIN civicrm_location_type ON ( civicrm_phone.location_type_id = civicrm_location_type.id )
WHERE civicrm_contact.id = %1 $cond
ORDER BY civicrm_phone.is_primary DESC, phone_id ASC ";
$params = array(
1 => array(
$id,
'Integer',
),
);
$numbers = $values = array();
$dao = CRM_Core_DAO::executeQuery($query, $params);
$count = 1;
while ($dao->fetch()) {
$values = array(
'locationType' => $dao->locationType,
'is_primary' => $dao->is_primary,
'id' => $dao->phone_id,
'phone' => $dao->phone,
'locationTypeId' => $dao->locationTypeId,
'phoneTypeId' => $dao->phoneTypeId,
);
if ($updateBlankLocInfo) {
$numbers[$count++] = $values;
}
else {
$numbers[$dao->phone_id] = $values;
}
}
return $numbers;
}
/**
* Get all the phone numbers for a specified location_block id, with the primary phone being first.
*
* This is called from CRM_Core_BAO_Block as a calculated function.
*
* @param array $entityElements
* The array containing entity_id and.
* entity_table name
*
* @param null $type
*
* @return array
* the array of phone ids which are potential numbers
*/
public static function allEntityPhones($entityElements, $type = NULL) {
if (empty($entityElements)) {
return NULL;
}
$cond = NULL;
if ($type) {
$phoneTypeId = array_search($type, CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'));
if ($phoneTypeId) {
$cond = " AND civicrm_phone.phone_type_id = $phoneTypeId";
}
}
$entityId = $entityElements['entity_id'];
$entityTable = $entityElements['entity_table'];
$sql = " SELECT phone, ltype.name as locationType, ph.is_primary as is_primary,
ph.id as phone_id, ph.location_type_id as locationTypeId
FROM civicrm_loc_block loc, civicrm_phone ph, civicrm_location_type ltype, {$entityTable} ev
WHERE ev.id = %1
AND loc.id = ev.loc_block_id
AND ph.id IN (loc.phone_id, loc.phone_2_id)
AND ltype.id = ph.location_type_id
ORDER BY ph.is_primary DESC, phone_id ASC ";
$params = array(
1 => array(
$entityId,
'Integer',
),
);
$numbers = array();
$dao = CRM_Core_DAO::executeQuery($sql, $params);
while ($dao->fetch()) {
$numbers[$dao->phone_id] = array(
'locationType' => $dao->locationType,
'is_primary' => $dao->is_primary,
'id' => $dao->phone_id,
'phone' => $dao->phone,
'locationTypeId' => $dao->locationTypeId,
);
}
return $numbers;
}
/**
* Set NULL to phone, mapping, uffield
*
* @param $optionId
* Value of option to be deleted.
*/
public static function setOptionToNull($optionId) {
if (!$optionId) {
return;
}
// Ensure mysql phone function exists
CRM_Core_DAO::checkSqlFunctionsExist();
$tables = array(
'civicrm_phone',
'civicrm_mapping_field',
'civicrm_uf_field',
);
$params = array(
1 => array(
$optionId,
'Integer',
),
);
foreach ($tables as $tableName) {
$query = "UPDATE `{$tableName}` SET `phone_type_id` = NULL WHERE `phone_type_id` = %1";
CRM_Core_DAO::executeQuery($query, $params);
}
}
/**
* Call common delete function.
*
* @param int $id
*
* @return bool
*/
public static function del($id) {
// Ensure mysql phone function exists
CRM_Core_DAO::checkSqlFunctionsExist();
return CRM_Contact_BAO_Contact::deleteObjectWithPrimary('Phone', $id);
}
}

View file

@ -0,0 +1,115 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_Core_BAO_PreferencesDate extends CRM_Core_DAO_PreferencesDate {
/**
* Static holder for the default LT.
*/
static $_defaultPreferencesDate = NULL;
/**
* Class constructor.
*/
public function __construct() {
parent::__construct();
}
/**
* Fetch object based on array of properties.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $defaults
* (reference ) an assoc array to hold the flattened values.
*
* @return CRM_Core_BAO_PreferencesDate|null
* object on success, null otherwise
*/
public static function retrieve(&$params, &$defaults) {
$dao = new CRM_Core_DAO_PreferencesDate();
$dao->copyValues($params);
if ($dao->find(TRUE)) {
CRM_Core_DAO::storeValues($dao, $defaults);
return $dao;
}
return NULL;
}
/**
* Update the is_active flag in the db.
*
* @param int $id
* Id of the database record.
* @param bool $is_active
* Value we want to set the is_active field.
*/
public static function setIsActive($id, $is_active) {
CRM_Core_Error::fatal();
}
/**
* Delete preference dates.
*
* @param int $id
*/
public static function del($id) {
CRM_Core_Error::fatal();
}
/**
* (Setting Callback - On Change)
* Respond to changes in the "timeInputFormat" setting.
*
* @param array $oldValue
* List of component names.
* @param array $newValue
* List of component names.
* @param array $metadata
* Specification of the setting (per *.settings.php).
*/
public static function onChangeSetting($oldValue, $newValue, $metadata) {
if ($oldValue == $newValue) {
return;
}
$query = "
UPDATE civicrm_preferences_date
SET time_format = %1
WHERE time_format IS NOT NULL
AND time_format <> ''
";
$sqlParams = array(1 => array($newValue, 'String'));
CRM_Core_DAO::executeQuery($query, $sqlParams);
}
}

View file

@ -0,0 +1,623 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* BAO object for civicrm_prevnext_cache table.
*/
class CRM_Core_BAO_PrevNextCache extends CRM_Core_DAO_PrevNextCache {
/**
* Get the previous and next keys.
*
* @param string $cacheKey
* @param int $id1
* @param int $id2
* @param int $mergeId
* @param string $join
* @param string $where
* @param bool $flip
*
* @return array
*/
public static function getPositions($cacheKey, $id1, $id2, &$mergeId = NULL, $join = NULL, $where = NULL, $flip = FALSE) {
if ($flip) {
list($id1, $id2) = array($id2, $id1);
}
if ($mergeId == NULL) {
$query = "
SELECT id
FROM civicrm_prevnext_cache
WHERE cacheKey = %3 AND
entity_id1 = %1 AND
entity_id2 = %2 AND
entity_table = 'civicrm_contact'
";
$params = array(
1 => array($id1, 'Integer'),
2 => array($id2, 'Integer'),
3 => array($cacheKey, 'String'),
);
$mergeId = CRM_Core_DAO::singleValueQuery($query, $params);
}
$pos = array('foundEntry' => 0);
if ($mergeId) {
$pos['foundEntry'] = 1;
if ($where) {
$where = " AND {$where}";
}
$p = array(
1 => array($mergeId, 'Integer'),
2 => array($cacheKey, 'String'),
);
$sql = "SELECT pn.id, pn.entity_id1, pn.entity_id2, pn.data FROM civicrm_prevnext_cache pn {$join} ";
$wherePrev = " WHERE pn.id < %1 AND pn.cacheKey = %2 {$where} ORDER BY ID DESC LIMIT 1";
$sqlPrev = $sql . $wherePrev;
$dao = CRM_Core_DAO::executeQuery($sqlPrev, $p);
if ($dao->fetch()) {
$pos['prev']['id1'] = $dao->entity_id1;
$pos['prev']['id2'] = $dao->entity_id2;
$pos['prev']['mergeId'] = $dao->id;
$pos['prev']['data'] = $dao->data;
}
$whereNext = " WHERE pn.id > %1 AND pn.cacheKey = %2 {$where} ORDER BY ID ASC LIMIT 1";
$sqlNext = $sql . $whereNext;
$dao = CRM_Core_DAO::executeQuery($sqlNext, $p);
if ($dao->fetch()) {
$pos['next']['id1'] = $dao->entity_id1;
$pos['next']['id2'] = $dao->entity_id2;
$pos['next']['mergeId'] = $dao->id;
$pos['next']['data'] = $dao->data;
}
}
return $pos;
}
/**
* Delete an item from the prevnext cache table based on the entity.
*
* @param int $id
* @param string $cacheKey
* @param string $entityTable
*/
public static function deleteItem($id = NULL, $cacheKey = NULL, $entityTable = 'civicrm_contact') {
//clear cache
$sql = "DELETE FROM civicrm_prevnext_cache WHERE entity_table = %1";
$params = array(1 => array($entityTable, 'String'));
if (is_numeric($id)) {
$sql .= " AND ( entity_id1 = %2 OR entity_id2 = %2 )";
$params[2] = array($id, 'Integer');
}
if (isset($cacheKey)) {
$sql .= " AND cacheKey LIKE %3";
$params[3] = array("{$cacheKey}%", 'String');
}
CRM_Core_DAO::executeQuery($sql, $params);
}
/**
* Delete from the previous next cache table for a pair of ids.
*
* @param int $id1
* @param int $id2
* @param string $cacheKey
* @param bool $isViceVersa
* @param string $entityTable
*/
public static function deletePair($id1, $id2, $cacheKey = NULL, $isViceVersa = FALSE, $entityTable = 'civicrm_contact') {
$sql = "DELETE FROM civicrm_prevnext_cache WHERE entity_table = %1";
$params = array(1 => array($entityTable, 'String'));
$pair = !$isViceVersa ? "entity_id1 = %2 AND entity_id2 = %3" : "(entity_id1 = %2 AND entity_id2 = %3) OR (entity_id1 = %3 AND entity_id2 = %2)";
$sql .= " AND ( {$pair} )";
$params[2] = array($id1, 'Integer');
$params[3] = array($id2, 'Integer');
if (isset($cacheKey)) {
$sql .= " AND cacheKey LIKE %4";
$params[4] = array("{$cacheKey}%", 'String'); // used % to address any row with conflict-cacheKey e.g "merge Individual_8_0_conflicts"
}
CRM_Core_DAO::executeQuery($sql, $params);
}
/**
* Mark contacts as being in conflict.
*
* @param int $id1
* @param int $id2
* @param string $cacheKey
* @param array $conflicts
*
* @return bool
*/
public static function markConflict($id1, $id2, $cacheKey, $conflicts) {
if (empty($cacheKey) || empty($conflicts)) {
return FALSE;
}
$sql = "SELECT pn.*
FROM civicrm_prevnext_cache pn
WHERE
((pn.entity_id1 = %1 AND pn.entity_id2 = %2) OR (pn.entity_id1 = %2 AND pn.entity_id2 = %1)) AND
(cacheKey = %3 OR cacheKey = %4)";
$params = array(
1 => array($id1, 'Integer'),
2 => array($id2, 'Integer'),
3 => array("{$cacheKey}", 'String'),
4 => array("{$cacheKey}_conflicts", 'String'),
);
$pncFind = CRM_Core_DAO::executeQuery($sql, $params);
while ($pncFind->fetch()) {
$data = $pncFind->data;
if (!empty($data)) {
$data = unserialize($data);
$data['conflicts'] = implode(",", array_values($conflicts));
$pncUp = new CRM_Core_DAO_PrevNextCache();
$pncUp->id = $pncFind->id;
if ($pncUp->find(TRUE)) {
$pncUp->data = serialize($data);
$pncUp->cacheKey = "{$cacheKey}_conflicts";
$pncUp->save();
}
}
}
return TRUE;
}
/**
* Retrieve from prev-next cache.
*
* This function is used from a variety of merge related functions, although
* it would probably be good to converge on calling CRM_Dedupe_Merger::getDuplicatePairs.
*
* We seem to currently be storing stats in this table too & they might make more sense in
* the main cache table.
*
* @param string $cacheKey
* @param string $join
* @param string $whereClause
* @param int $offset
* @param int $rowCount
* @param array $select
* @param string $orderByClause
* @param bool $includeConflicts
* Should we return rows that have already been idenfified as having a conflict.
* When this is TRUE you should be careful you do not set up a loop.
* @param array $params
*
* @return array
*/
public static function retrieve($cacheKey, $join = NULL, $whereClause = NULL, $offset = 0, $rowCount = 0, $select = array(), $orderByClause = '', $includeConflicts = TRUE, $params = array()) {
$selectString = 'pn.*';
if (!empty($select)) {
$aliasArray = array();
foreach ($select as $column => $alias) {
$aliasArray[] = $column . ' as ' . $alias;
}
$selectString .= " , " . implode(' , ', $aliasArray);
}
$params = array(
1 => array($cacheKey, 'String'),
) + $params;
if (!empty($whereClause)) {
$whereClause = " AND " . $whereClause;
}
if ($includeConflicts) {
$where = ' WHERE (pn.cacheKey = %1 OR pn.cacheKey = %2)' . $whereClause;
$params[2] = array("{$cacheKey}_conflicts", 'String');
}
else {
$where = ' WHERE (pn.cacheKey = %1)' . $whereClause;
}
$query = "
SELECT SQL_CALC_FOUND_ROWS {$selectString}
FROM civicrm_prevnext_cache pn
{$join}
$where
$orderByClause
";
if ($rowCount) {
$offset = CRM_Utils_Type::escape($offset, 'Int');
$rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
$query .= " LIMIT {$offset}, {$rowCount}";
}
$dao = CRM_Core_DAO::executeQuery($query, $params);
$main = array();
$count = 0;
while ($dao->fetch()) {
if (self::is_serialized($dao->data)) {
$main[$count] = unserialize($dao->data);
}
else {
$main[$count] = $dao->data;
}
if (!empty($select)) {
$extraData = array();
foreach ($select as $sfield) {
$extraData[$sfield] = $dao->$sfield;
}
$main[$count] = array(
'prevnext_id' => $dao->id,
'is_selected' => $dao->is_selected,
'entity_id1' => $dao->entity_id1,
'entity_id2' => $dao->entity_id2,
'data' => $main[$count],
);
$main[$count] = array_merge($main[$count], $extraData);
}
$count++;
}
return $main;
}
/**
* @param $string
*
* @return bool
*/
public static function is_serialized($string) {
return (@unserialize($string) !== FALSE);
}
/**
* @param $values
*/
public static function setItem($values) {
$insert = "INSERT INTO civicrm_prevnext_cache ( entity_table, entity_id1, entity_id2, cacheKey, data ) VALUES \n";
$query = $insert . implode(",\n ", $values);
//dump the dedupe matches in the prevnext_cache table
CRM_Core_DAO::executeQuery($query);
}
/**
* Get count of matching rows.
*
* @param string $cacheKey
* @param string $join
* @param string $where
* @param string $op
* @param array $params
* Extra query params to parse into the query.
*
* @return int
*/
public static function getCount($cacheKey, $join = NULL, $where = NULL, $op = "=", $params = array()) {
$query = "
SELECT COUNT(*) FROM civicrm_prevnext_cache pn
{$join}
WHERE (pn.cacheKey $op %1 OR pn.cacheKey $op %2)
";
if ($where) {
$query .= " AND {$where}";
}
$params = array(
1 => array($cacheKey, 'String'),
2 => array("{$cacheKey}_conflicts", 'String'),
) + $params;
return (int) CRM_Core_DAO::singleValueQuery($query, $params, TRUE, FALSE);
}
/**
* Repopulate the cache of merge prospects.
*
* @param int $rgid
* @param int $gid
* @param NULL $cacheKeyString
* @param array $criteria
* Additional criteria to filter by.
*
* @param bool $checkPermissions
* Respect logged in user's permissions.
*
* @param int $searchLimit
* Limit for the number of contacts to be used for comparison.
* The search methodology finds all matches for the searchedContacts so this limits
* the number of searched contacts, not the matches found.
*
* @return bool
* @throws \CRM_Core_Exception
* @throws \CiviCRM_API3_Exception
*/
public static function refillCache($rgid, $gid, $cacheKeyString, $criteria, $checkPermissions, $searchLimit = 0) {
if (!$cacheKeyString && $rgid) {
$cacheKeyString = CRM_Dedupe_Merger::getMergeCacheKeyString($rgid, $gid, $criteria, $checkPermissions);
}
if (!$cacheKeyString) {
return FALSE;
}
// 1. Clear cache if any
$sql = "DELETE FROM civicrm_prevnext_cache WHERE cacheKey LIKE %1";
CRM_Core_DAO::executeQuery($sql, array(1 => array("{$cacheKeyString}%", 'String')));
// FIXME: we need to start using temp tables / queries here instead of arrays.
// And cleanup code in CRM/Contact/Page/DedupeFind.php
// 2. FILL cache
$foundDupes = array();
if ($rgid && $gid) {
$foundDupes = CRM_Dedupe_Finder::dupesInGroup($rgid, $gid, $searchLimit);
}
elseif ($rgid) {
$contactIDs = array();
if (!empty($criteria)) {
$contacts = civicrm_api3('Contact', 'get', array_merge(array('options' => array('limit' => 0), 'return' => 'id'), $criteria['contact']));
$contactIDs = array_keys($contacts['values']);
}
$foundDupes = CRM_Dedupe_Finder::dupes($rgid, $contactIDs, $checkPermissions, $searchLimit);
}
if (!empty($foundDupes)) {
CRM_Dedupe_Finder::parseAndStoreDupePairs($foundDupes, $cacheKeyString);
}
}
public static function cleanupCache() {
// clean up all prev next caches older than $cacheTimeIntervalDays days
$cacheTimeIntervalDays = 2;
// first find all the cacheKeys that match this
$sql = "
DELETE pn, c
FROM civicrm_cache c
INNER JOIN civicrm_prevnext_cache pn ON c.path = pn.cacheKey
WHERE c.group_name = %1
AND c.created_date < date_sub( NOW( ), INTERVAL %2 day )
";
$params = array(
1 => array('CiviCRM Search PrevNextCache', 'String'),
2 => array($cacheTimeIntervalDays, 'Integer'),
);
CRM_Core_DAO::executeQuery($sql, $params);
}
/**
* Save checkbox selections.
*
* @param $cacheKey
* @param string $action
* @param array $cIds
* @param string $entity_table
*/
public static function markSelection($cacheKey, $action = 'unselect', $cIds = NULL, $entity_table = 'civicrm_contact') {
if (!$cacheKey) {
return;
}
$params = array();
$entity_whereClause = " AND entity_table = '{$entity_table}'";
if ($cIds && $cacheKey && $action) {
if (is_array($cIds)) {
$cIdFilter = "(" . implode(',', $cIds) . ")";
$whereClause = "
WHERE cacheKey LIKE %1
AND (entity_id1 IN {$cIdFilter} OR entity_id2 IN {$cIdFilter})
";
}
else {
$whereClause = "
WHERE cacheKey LIKE %1
AND (entity_id1 = %2 OR entity_id2 = %2)
";
$params[2] = array("{$cIds}", 'Integer');
}
if ($action == 'select') {
$whereClause .= "AND is_selected = 0";
$sql = "UPDATE civicrm_prevnext_cache SET is_selected = 1 {$whereClause} {$entity_whereClause}";
$params[1] = array("{$cacheKey}%", 'String');
}
elseif ($action == 'unselect') {
$whereClause .= "AND is_selected = 1";
$sql = "UPDATE civicrm_prevnext_cache SET is_selected = 0 {$whereClause} {$entity_whereClause}";
$params[1] = array("%{$cacheKey}%", 'String');
}
// default action is reseting
}
elseif (!$cIds && $cacheKey && $action == 'unselect') {
$sql = "
UPDATE civicrm_prevnext_cache
SET is_selected = 0
WHERE cacheKey LIKE %1 AND is_selected = 1
{$entity_whereClause}
";
$params[1] = array("{$cacheKey}%", 'String');
}
CRM_Core_DAO::executeQuery($sql, $params);
}
/**
* Get the selections.
*
* @param string $cacheKey
* Cache key.
* @param string $action
* Action.
* $action : get - get only selection records
* getall - get all the records of the specified cache key
* @param string $entity_table
* Entity table.
*
* @return array|NULL
*/
public static function getSelection($cacheKey, $action = 'get', $entity_table = 'civicrm_contact') {
if (!$cacheKey) {
return NULL;
}
$params = array();
$entity_whereClause = " AND entity_table = '{$entity_table}'";
if ($cacheKey && ($action == 'get' || $action == 'getall')) {
$actionGet = ($action == "get") ? " AND is_selected = 1 " : "";
$sql = "
SELECT entity_id1, entity_id2 FROM civicrm_prevnext_cache
WHERE cacheKey LIKE %1
$actionGet
$entity_whereClause
ORDER BY id
";
$params[1] = array("{$cacheKey}%", 'String');
$contactIds = array($cacheKey => array());
$cIdDao = CRM_Core_DAO::executeQuery($sql, $params);
while ($cIdDao->fetch()) {
if ($cIdDao->entity_id1 == $cIdDao->entity_id2) {
$contactIds[$cacheKey][$cIdDao->entity_id1] = 1;
}
}
return $contactIds;
}
}
/**
* @return array
*/
public static function getSelectedContacts() {
$qfKey = CRM_Utils_Request::retrieve('qfKey', 'String');
$cacheKey = "civicrm search {$qfKey}";
$query = "
SELECT *
FROM civicrm_prevnext_cache
WHERE cacheKey LIKE %1
AND is_selected=1
AND cacheKey NOT LIKE %2
";
$params1[1] = array("{$cacheKey}%", 'String');
$params1[2] = array("{$cacheKey}_alphabet%", 'String');
$dao = CRM_Core_DAO::executeQuery($query, $params1);
$val = array();
while ($dao->fetch()) {
$val[] = $dao->data;
}
return $val;
}
/**
* @param CRM_Core_Form $form
* @param array $params
*
* @return mixed
*/
public static function buildSelectedContactPager(&$form, &$params) {
$params['status'] = ts('Contacts %%StatusMessage%%');
$params['csvString'] = NULL;
$params['buttonTop'] = 'PagerTopButton';
$params['buttonBottom'] = 'PagerBottomButton';
$params['rowCount'] = $form->get(CRM_Utils_Pager::PAGE_ROWCOUNT);
if (!$params['rowCount']) {
$params['rowCount'] = CRM_Utils_Pager::ROWCOUNT;
}
$qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $form);
$cacheKey = "civicrm search {$qfKey}";
$query = "
SELECT count(*)
FROM civicrm_prevnext_cache
WHERE cacheKey LIKE %1
AND is_selected = 1
AND cacheKey NOT LIKE %2
";
$params1[1] = array("{$cacheKey}%", 'String');
$params1[2] = array("{$cacheKey}_alphabet%", 'String');
$paramsTotal = CRM_Core_DAO::singleValueQuery($query, $params1);
$params['total'] = $paramsTotal;
$form->_pager = new CRM_Utils_Pager($params);
$form->assign_by_ref('pager', $form->_pager);
list($offset, $rowCount) = $form->_pager->getOffsetAndRowCount();
$params['offset'] = $offset;
$params['rowCount1'] = $rowCount;
return $params;
}
/**
* Flip 2 contacts in the prevNext cache.
*
* @param array $prevNextId
* @param bool $onlySelected
* Only flip those which have been marked as selected.
*/
public static function flipPair(array $prevNextId, $onlySelected) {
$dao = new CRM_Core_DAO_PrevNextCache();
if ($onlySelected) {
$dao->is_selected = 1;
}
foreach ($prevNextId as $id) {
$dao->id = $id;
if ($dao->find(TRUE)) {
$originalData = unserialize($dao->data);
$srcFields = array('ID', 'Name');
$swapFields = array('srcID', 'srcName', 'dstID', 'dstName');
$data = array_diff_assoc($originalData, array_fill_keys($swapFields, 1));
foreach ($srcFields as $key) {
$data['src' . $key] = $originalData['dst' . $key];
$data['dst' . $key] = $originalData['src' . $key];
}
$dao->data = serialize($data);
$dao->entity_id1 = $data['dstID'];
$dao->entity_id2 = $data['srcID'];
$dao->save();
}
}
}
}

View file

@ -0,0 +1,83 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
class CRM_Core_BAO_Query {
/**
* @param CRM_Core_Form $form
* @param array $extends
*/
public static function addCustomFormFields(&$form, $extends) {
$groupDetails = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, TRUE, $extends);
if ($groupDetails) {
$tplName = lcfirst($extends[0]) . 'GroupTree';
$form->assign($tplName, $groupDetails);
foreach ($groupDetails as $group) {
foreach ($group['fields'] as $field) {
$fieldId = $field['id'];
$elementName = 'custom_' . $fieldId;
if ($field['data_type'] == 'Date' && $field['is_search_range']) {
CRM_Core_Form_Date::buildDateRange($form, $elementName, 1, '_from', '_to', ts('From:'), FALSE);
}
else {
CRM_Core_BAO_CustomField::addQuickFormElement($form, $elementName, $fieldId, FALSE, TRUE);
}
}
}
}
}
/**
* Getter for the qill object.
*
* @return string
*/
public function qill() {
return (isset($this->_qill)) ? $this->_qill : "";
}
/**
* Possibly unnecessary function.
*
* @param $row
* @param int $id
*/
public static function searchAction(&$row, $id) {}
/**
* @param $tables
*/
public static function tableNames(&$tables) {}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,785 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This file contains functions for creating and altering CiviCRM-tables structure.
*
* $table = array(
* 'name' => TABLE_NAME,
* 'attributes' => ATTRIBUTES,
* 'fields' => array(
* array(
* 'name' => FIELD_NAME,
* // can be field, index, constraint
* 'type' => FIELD_SQL_TYPE,
* 'class' => FIELD_CLASS_TYPE,
* 'primary' => BOOLEAN,
* 'required' => BOOLEAN,
* 'searchable' => TRUE,
* 'fk_table_name' => FOREIGN_KEY_TABLE_NAME,
* 'fk_field_name' => FOREIGN_KEY_FIELD_NAME,
* 'comment' => COMMENT,
* 'default' => DEFAULT, )
* ...
* ));
*/
class CRM_Core_BAO_SchemaHandler {
/**
* Create a CiviCRM-table
*
* @param array $params
*
* @return bool
* TRUE if successfully created, FALSE otherwise
*
*/
public static function createTable(&$params) {
$sql = self::buildTableSQL($params);
// do not i18n-rewrite
$dao = CRM_Core_DAO::executeQuery($sql, array(), TRUE, NULL, FALSE, FALSE);
$dao->free();
$config = CRM_Core_Config::singleton();
if ($config->logging) {
// logging support
$logging = new CRM_Logging_Schema();
$logging->fixSchemaDifferencesFor($params['name'], NULL, FALSE);
}
// always do a trigger rebuild for this table
CRM_Core_DAO::triggerRebuild($params['name']);
return TRUE;
}
/**
* @param array $params
*
* @return string
*/
public static function buildTableSQL(&$params) {
$sql = "CREATE TABLE {$params['name']} (";
if (isset($params['fields']) &&
is_array($params['fields'])
) {
$separator = "\n";
$prefix = NULL;
foreach ($params['fields'] as $field) {
$sql .= self::buildFieldSQL($field, $separator, $prefix);
$separator = ",\n";
}
foreach ($params['fields'] as $field) {
$sql .= self::buildPrimaryKeySQL($field, $separator, $prefix);
}
foreach ($params['fields'] as $field) {
$sql .= self::buildSearchIndexSQL($field, $separator, $prefix);
}
if (isset($params['indexes'])) {
foreach ($params['indexes'] as $index) {
$sql .= self::buildIndexSQL($index, $separator, $prefix);
}
}
foreach ($params['fields'] as $field) {
$sql .= self::buildForeignKeySQL($field, $separator, $prefix, $params['name']);
}
}
$sql .= "\n) {$params['attributes']};";
return $sql;
}
/**
* @param array $params
* @param $separator
* @param $prefix
*
* @return string
*/
public static function buildFieldSQL(&$params, $separator, $prefix) {
$sql = '';
$sql .= $separator;
$sql .= str_repeat(' ', 8);
$sql .= $prefix;
$sql .= "`{$params['name']}` {$params['type']}";
if (!empty($params['required'])) {
$sql .= " NOT NULL";
}
if (!empty($params['attributes'])) {
$sql .= " {$params['attributes']}";
}
if (!empty($params['default']) &&
$params['type'] != 'text'
) {
$sql .= " DEFAULT {$params['default']}";
}
if (!empty($params['comment'])) {
$sql .= " COMMENT '{$params['comment']}'";
}
return $sql;
}
/**
* @param array $params
* @param $separator
* @param $prefix
*
* @return NULL|string
*/
public static function buildPrimaryKeySQL(&$params, $separator, $prefix) {
$sql = NULL;
if (!empty($params['primary'])) {
$sql .= $separator;
$sql .= str_repeat(' ', 8);
$sql .= $prefix;
$sql .= "PRIMARY KEY ( {$params['name']} )";
}
return $sql;
}
/**
* @param array $params
* @param $separator
* @param $prefix
* @param bool $indexExist
*
* @return NULL|string
*/
public static function buildSearchIndexSQL(&$params, $separator, $prefix, $indexExist = FALSE) {
$sql = NULL;
// dont index blob
if ($params['type'] == 'text') {
return $sql;
}
//create index only for searchable fields during ADD,
//create index only if field is become searchable during MODIFY,
//drop index only if field is no more searchable and index was exist.
if (!empty($params['searchable']) && !$indexExist) {
$sql .= $separator;
$sql .= str_repeat(' ', 8);
$sql .= $prefix;
$sql .= "INDEX_{$params['name']} ( {$params['name']} )";
}
elseif (empty($params['searchable']) && $indexExist) {
$sql .= $separator;
$sql .= str_repeat(' ', 8);
$sql .= "DROP INDEX INDEX_{$params['name']}";
}
return $sql;
}
/**
* @param array $params
* @param $separator
* @param $prefix
*
* @return string
*/
public static function buildIndexSQL(&$params, $separator, $prefix) {
$sql = '';
$sql .= $separator;
$sql .= str_repeat(' ', 8);
if ($params['unique']) {
$sql .= 'UNIQUE INDEX';
$indexName = 'unique';
}
else {
$sql .= 'INDEX';
$indexName = 'index';
}
$indexFields = NULL;
foreach ($params as $name => $value) {
if (substr($name, 0, 11) == 'field_name_') {
$indexName .= "_{$value}";
$indexFields .= " $value,";
}
}
$indexFields = substr($indexFields, 0, -1);
$sql .= " $indexName ( $indexFields )";
return $sql;
}
/**
* @param string $tableName
* @param string $fkTableName
*
* @return bool
*/
public static function changeFKConstraint($tableName, $fkTableName) {
$fkName = "{$tableName}_entity_id";
if (strlen($fkName) >= 48) {
$fkName = substr($fkName, 0, 32) . "_" . substr(md5($fkName), 0, 16);
}
$dropFKSql = "
ALTER TABLE {$tableName}
DROP FOREIGN KEY `FK_{$fkName}`;";
$dao = CRM_Core_DAO::executeQuery($dropFKSql);
$dao->free();
$addFKSql = "
ALTER TABLE {$tableName}
ADD CONSTRAINT `FK_{$fkName}` FOREIGN KEY (`entity_id`) REFERENCES {$fkTableName} (`id`) ON DELETE CASCADE;";
// CRM-7007: do not i18n-rewrite this query
$dao = CRM_Core_DAO::executeQuery($addFKSql, array(), TRUE, NULL, FALSE, FALSE);
$dao->free();
return TRUE;
}
/**
* @param array $params
* @param $separator
* @param $prefix
* @param string $tableName
*
* @return NULL|string
*/
public static function buildForeignKeySQL(&$params, $separator, $prefix, $tableName) {
$sql = NULL;
if (!empty($params['fk_table_name']) && !empty($params['fk_field_name'])) {
$sql .= $separator;
$sql .= str_repeat(' ', 8);
$sql .= $prefix;
$fkName = "{$tableName}_{$params['name']}";
if (strlen($fkName) >= 48) {
$fkName = substr($fkName, 0, 32) . "_" . substr(md5($fkName), 0, 16);
}
$sql .= "CONSTRAINT FK_$fkName FOREIGN KEY ( `{$params['name']}` ) REFERENCES {$params['fk_table_name']} ( {$params['fk_field_name']} ) ";
$sql .= CRM_Utils_Array::value('fk_attributes', $params);
}
return $sql;
}
/**
* @param array $params
* @param bool $indexExist
* @param bool $triggerRebuild
*
* @return bool
*/
public static function alterFieldSQL(&$params, $indexExist = FALSE, $triggerRebuild = TRUE) {
$sql = str_repeat(' ', 8);
$sql .= "ALTER TABLE {$params['table_name']}";
// lets suppress the required flag, since that can cause sql issue
$params['required'] = FALSE;
switch ($params['operation']) {
case 'add':
$separator = "\n";
$prefix = "ADD ";
$sql .= self::buildFieldSQL($params, $separator, "ADD COLUMN ");
$separator = ",\n";
$sql .= self::buildPrimaryKeySQL($params, $separator, "ADD PRIMARY KEY ");
$sql .= self::buildSearchIndexSQL($params, $separator, "ADD INDEX ");
$sql .= self::buildForeignKeySQL($params, $separator, "ADD ", $params['table_name']);
break;
case 'modify':
$separator = "\n";
$prefix = "MODIFY ";
$sql .= self::buildFieldSQL($params, $separator, $prefix);
$separator = ",\n";
$sql .= self::buildSearchIndexSQL($params, $separator, "ADD INDEX ", $indexExist);
break;
case 'delete':
$sql .= " DROP COLUMN `{$params['name']}`";
if (!empty($params['primary'])) {
$sql .= ", DROP PRIMARY KEY";
}
if (!empty($params['fk_table_name'])) {
$sql .= ", DROP FOREIGN KEY FK_{$params['fkName']}";
}
break;
}
// CRM-7007: do not i18n-rewrite this query
$dao = CRM_Core_DAO::executeQuery($sql, array(), TRUE, NULL, FALSE, FALSE);
$dao->free();
$config = CRM_Core_Config::singleton();
if ($config->logging) {
// CRM-16717 not sure why this was originally limited to add.
// For example custom tables can have field length changes - which need to flow through to logging.
// Are there any modifies we DON'T was to call this function for (& shouldn't it be clever enough to cope?)
if ($params['operation'] == 'add' || $params['operation'] == 'modify') {
$logging = new CRM_Logging_Schema();
$logging->fixSchemaDifferencesFor($params['table_name'], array(trim($prefix) => array($params['name'])), FALSE);
}
}
if ($triggerRebuild) {
CRM_Core_DAO::triggerRebuild($params['table_name']);
}
return TRUE;
}
/**
* Delete a CiviCRM-table.
*
* @param string $tableName
* Name of the table to be created.
*/
public static function dropTable($tableName) {
$sql = "DROP TABLE $tableName";
CRM_Core_DAO::executeQuery($sql);
}
/**
* @param string $tableName
* @param string $columnName
* @param bool $l18n
* @param bool $isUpgradeMode
*
*/
public static function dropColumn($tableName, $columnName, $l18n = FALSE, $isUpgradeMode = FALSE) {
if (self::checkIfFieldExists($tableName, $columnName)) {
$sql = "ALTER TABLE $tableName DROP COLUMN $columnName";
if ($l18n) {
CRM_Core_DAO::executeQuery($sql);
}
else {
CRM_Core_DAO::executeQuery($sql, array(), TRUE, NULL, FALSE, FALSE);
}
$domain = new CRM_Core_DAO_Domain();
$domain->find(TRUE);
if ($domain->locales) {
$locales = explode(CRM_Core_DAO::VALUE_SEPARATOR, $domain->locales);
CRM_Core_I18n_Schema::rebuildMultilingualSchema($locales, NULL, $isUpgradeMode);
}
}
}
/**
* @param string $tableName
* @param bool $dropUnique
*/
public static function changeUniqueToIndex($tableName, $dropUnique = TRUE) {
if ($dropUnique) {
$sql = "ALTER TABLE $tableName
DROP INDEX `unique_entity_id` ,
ADD INDEX `FK_{$tableName}_entity_id` ( `entity_id` )";
}
else {
$sql = " ALTER TABLE $tableName
DROP INDEX `FK_{$tableName}_entity_id` ,
ADD UNIQUE INDEX `unique_entity_id` ( `entity_id` )";
}
CRM_Core_DAO::executeQuery($sql);
}
/**
* Create indexes.
*
* @param $tables
* Tables to create index for in the format:
* array('civicrm_entity_table' => 'entity_id')
* OR
* array('civicrm_entity_table' => array('entity_id', 'entity_table'))
* The latter will create a combined index on the 2 keys (in order).
*
* Side note - when creating combined indexes the one with the most variation
* goes first - so entity_table always goes after entity_id.
*
* It probably makes sense to consider more sophisticated options at some point
* but at the moment this is only being as enhanced as fast as the test is.
*
* @todo add support for length & multilingual on combined keys.
*
* @param string $createIndexPrefix
* @param array $substrLengths
*/
public static function createIndexes($tables, $createIndexPrefix = 'index', $substrLengths = array()) {
$queries = array();
$domain = new CRM_Core_DAO_Domain();
$domain->find(TRUE);
$locales = explode(CRM_Core_DAO::VALUE_SEPARATOR, $domain->locales);
// if we're multilingual, cache the information on internationalised fields
static $columns = NULL;
if (!CRM_Utils_System::isNull($locales) and $columns === NULL) {
$columns = CRM_Core_I18n_SchemaStructure::columns();
}
foreach ($tables as $table => $fields) {
$query = "SHOW INDEX FROM $table";
$dao = CRM_Core_DAO::executeQuery($query);
$currentIndexes = array();
while ($dao->fetch()) {
$currentIndexes[] = $dao->Key_name;
}
// now check for all fields if the index exists
foreach ($fields as $field) {
$fieldName = implode('_', (array) $field);
if (is_array($field)) {
// No support for these for combined indexes as yet - add a test when you
// want to add that.
$lengthName = '';
$lengthSize = '';
}
else {
// handle indices over substrings, CRM-6245
// $lengthName is appended to index name, $lengthSize is the field size modifier
$lengthName = isset($substrLengths[$table][$fieldName]) ? "_{$substrLengths[$table][$fieldName]}" : '';
$lengthSize = isset($substrLengths[$table][$fieldName]) ? "({$substrLengths[$table][$fieldName]})" : '';
}
$names = array(
"index_{$fieldName}{$lengthName}",
"FK_{$table}_{$fieldName}{$lengthName}",
"UI_{$fieldName}{$lengthName}",
"{$createIndexPrefix}_{$fieldName}{$lengthName}",
);
// skip to the next $field if one of the above $names exists; handle multilingual for CRM-4126
foreach ($names as $name) {
$regex = '/^' . preg_quote($name) . '(_[a-z][a-z]_[A-Z][A-Z])?$/';
if (preg_grep($regex, $currentIndexes)) {
continue 2;
}
}
// the index doesn't exist, so create it
// if we're multilingual and the field is internationalised, do it for every locale
// @todo remove is_array check & add multilingual support for combined indexes and add a test.
// Note combined indexes currently using this function are on fields like
// entity_id + entity_table which are not multilingual.
if (!is_array($field) && !CRM_Utils_System::isNull($locales) and isset($columns[$table][$fieldName])) {
foreach ($locales as $locale) {
$queries[] = "CREATE INDEX {$createIndexPrefix}_{$fieldName}{$lengthName}_{$locale} ON {$table} ({$fieldName}_{$locale}{$lengthSize})";
}
}
else {
$queries[] = "CREATE INDEX {$createIndexPrefix}_{$fieldName}{$lengthName} ON {$table} (" . implode(',', (array) $field) . "{$lengthSize})";
}
}
}
// run the queries without i18n-rewriting
$dao = new CRM_Core_DAO();
foreach ($queries as $query) {
$dao->query($query, FALSE);
}
}
/**
* Get indexes for tables
* @param array $tables
* array of table names to find indexes for
*
* @return array('tableName' => array('index1', 'index2'))
*/
public static function getIndexes($tables) {
$indexes = array();
foreach ($tables as $table) {
$query = "SHOW INDEX FROM $table";
$dao = CRM_Core_DAO::executeQuery($query);
$tableIndexes = array();
while ($dao->fetch()) {
$tableIndexes[$dao->Key_name]['name'] = $dao->Key_name;
$tableIndexes[$dao->Key_name]['field'][] = $dao->Column_name .
($dao->Sub_part ? '(' . $dao->Sub_part . ')' : '');
$tableIndexes[$dao->Key_name]['unique'] = ($dao->Non_unique == 0 ? 1 : 0);
}
$indexes[$table] = $tableIndexes;
$dao->free();
}
return $indexes;
}
/**
* Drop an index if one by that name exists.
*
* @param string $tableName
* @param string $indexName
*/
public static function dropIndexIfExists($tableName, $indexName) {
if (self::checkIfIndexExists($tableName, $indexName)) {
CRM_Core_DAO::executeQuery("DROP INDEX $indexName ON $tableName");
}
}
/**
* @param int $customFieldID
* @param string $tableName
* @param string $columnName
* @param $length
*
* @throws Exception
*/
public static function alterFieldLength($customFieldID, $tableName, $columnName, $length) {
// first update the custom field tables
$sql = "
UPDATE civicrm_custom_field
SET text_length = %1
WHERE id = %2
";
$params = array(
1 => array($length, 'Integer'),
2 => array($customFieldID, 'Integer'),
);
CRM_Core_DAO::executeQuery($sql, $params);
$sql = "
SELECT is_required, default_value
FROM civicrm_custom_field
WHERE id = %2
";
$dao = CRM_Core_DAO::executeQuery($sql, $params);
if ($dao->fetch()) {
$clause = '';
if ($dao->is_required) {
$clause = " NOT NULL";
}
if (!empty($dao->default_value)) {
$clause .= " DEFAULT '{$dao->default_value}'";
}
// now modify the column
$sql = "
ALTER TABLE {$tableName}
MODIFY {$columnName} varchar( $length )
$clause
";
CRM_Core_DAO::executeQuery($sql);
}
else {
CRM_Core_Error::fatal(ts('Could Not Find Custom Field Details for %1, %2, %3',
array(
1 => $tableName,
2 => $columnName,
3 => $customFieldID,
)
));
}
}
/**
* Check if the table has an index matching the name.
*
* @param string $tableName
* @param array $indexName
*
* @return bool
*/
public static function checkIfIndexExists($tableName, $indexName) {
$result = CRM_Core_DAO::executeQuery(
"SHOW INDEX FROM $tableName WHERE key_name = %1 AND seq_in_index = 1",
array(1 => array($indexName, 'String'))
);
if ($result->fetch()) {
return TRUE;
}
return FALSE;
}
/**
* Check if the table has a specified column.
*
* @param string $tableName
* @param string $columnName
*
* @return bool
*/
public static function checkIfFieldExists($tableName, $columnName) {
$result = CRM_Core_DAO::executeQuery(
"SHOW COLUMNS FROM $tableName LIKE %1",
array(1 => array($columnName, 'String'))
);
if ($result->fetch()) {
return TRUE;
}
return FALSE;
}
/**
* Check if a foreign key Exists
* @param string $table_name
* @param string $constraint_name
* @return bool TRUE if FK is found
*/
public static function checkFKExists($table_name, $constraint_name) {
$config = CRM_Core_Config::singleton();
$dbUf = DB::parseDSN($config->dsn);
$query = "
SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_SCHEMA = %1
AND TABLE_NAME = %2
AND CONSTRAINT_NAME = %3
AND CONSTRAINT_TYPE = 'FOREIGN KEY'
";
$params = array(
1 => array($dbUf['database'], 'String'),
2 => array($table_name, 'String'),
3 => array($constraint_name, 'String'),
);
$dao = CRM_Core_DAO::executeQuery($query, $params);
if ($dao->fetch()) {
return TRUE;
}
return FALSE;
}
/**
* Remove a foreign key from a table if it exists.
*
* @param $table_name
* @param $constraint_name
*
* @return bool
*/
public static function safeRemoveFK($table_name, $constraint_name) {
if (self::checkFKExists($table_name, $constraint_name)) {
CRM_Core_DAO::executeQuery("ALTER TABLE {$table_name} DROP FOREIGN KEY {$constraint_name}", array());
return TRUE;
}
return FALSE;
}
/**
* Add index signature hash to DAO file calculation.
*
* @param string $table table name
* @param array $indices index array spec
*/
public static function addIndexSignature($table, &$indices) {
foreach ($indices as $indexName => $index) {
$indices[$indexName]['sig'] = $table . "::" .
(array_key_exists('unique', $index) ? $index['unique'] : 0) . "::" .
implode("::", $index['field']);
}
}
/**
* Compare the indices specified in the XML files with those in the DB.
*
* @param bool $dropFalseIndices
* If set - this function deletes false indices present in the DB which mismatches the expected
* values of xml file so that civi re-creates them with correct values using createMissingIndices() function.
*
* @return array
* index specifications
*/
public static function getMissingIndices($dropFalseIndices = FALSE) {
$requiredSigs = $existingSigs = array();
// Get the indices defined (originally) in the xml files
$requiredIndices = CRM_Core_DAO_AllCoreTables::indices();
foreach ($requiredIndices as $table => $indices) {
$reqSigs[] = CRM_Utils_Array::collect('sig', $indices);
}
CRM_Utils_Array::flatten($reqSigs, $requiredSigs);
// Get the indices in the database
$existingIndices = CRM_Core_BAO_SchemaHandler::getIndexes(array_keys($requiredIndices));
foreach ($existingIndices as $table => $indices) {
CRM_Core_BAO_SchemaHandler::addIndexSignature($table, $indices);
$extSigs[] = CRM_Utils_Array::collect('sig', $indices);
}
CRM_Utils_Array::flatten($extSigs, $existingSigs);
// Compare
$missingSigs = array_diff($requiredSigs, $existingSigs);
//CRM-20774 - Drop index key which exist in db but the value varies.
$existingKeySigs = array_intersect_key($missingSigs, $existingSigs);
if ($dropFalseIndices && !empty($existingKeySigs)) {
foreach ($existingKeySigs as $sig) {
$sigParts = explode('::', $sig);
foreach ($requiredIndices[$sigParts[0]] as $index) {
if ($index['sig'] == $sig && !empty($index['name'])) {
self::dropIndexIfExists($sigParts[0], $index['name']);
continue;
}
}
}
}
// Get missing indices
$missingIndices = array();
foreach ($missingSigs as $sig) {
$sigParts = explode('::', $sig);
foreach ($requiredIndices[$sigParts[0]] as $index) {
if ($index['sig'] == $sig) {
$missingIndices[$sigParts[0]][] = $index;
continue;
}
}
}
return $missingIndices;
}
/**
* Create missing indices.
*
* @param array $missingIndices as returned by getMissingIndices()
*/
public static function createMissingIndices($missingIndices) {
$queries = array();
foreach ($missingIndices as $table => $indexList) {
foreach ($indexList as $index) {
$queries[] = "CREATE " .
(array_key_exists('unique', $index) && $index['unique'] ? 'UNIQUE ' : '') .
"INDEX {$index['name']} ON {$table} (" .
implode(", ", $index['field']) .
")";
}
}
/* FIXME potential problem if index name already exists, so check before creating */
$dao = new CRM_Core_DAO();
foreach ($queries as $query) {
$dao->query($query, FALSE);
}
$dao->free();
}
}

View file

@ -0,0 +1,555 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* BAO object for civicrm_setting table. This table is used to store civicrm settings that are not used
* very frequently (i.e. not on every page load)
*
* The group column is used for grouping together all settings that logically belong to the same set.
* Thus all settings in the same group are retrieved with one DB call and then cached for future needs.
*/
class CRM_Core_BAO_Setting extends CRM_Core_DAO_Setting {
/**
* Various predefined settings that have been migrated to the setting table.
*/
const
ADDRESS_STANDARDIZATION_PREFERENCES_NAME = 'Address Standardization Preferences',
CAMPAIGN_PREFERENCES_NAME = 'Campaign Preferences',
DEVELOPER_PREFERENCES_NAME = 'Developer Preferences',
DIRECTORY_PREFERENCES_NAME = 'Directory Preferences',
EVENT_PREFERENCES_NAME = 'Event Preferences',
MAILING_PREFERENCES_NAME = 'Mailing Preferences',
MAP_PREFERENCES_NAME = 'Map Preferences',
CONTRIBUTE_PREFERENCES_NAME = 'Contribute Preferences',
MEMBER_PREFERENCES_NAME = 'Member Preferences',
MULTISITE_PREFERENCES_NAME = 'Multi Site Preferences',
PERSONAL_PREFERENCES_NAME = 'Personal Preferences',
SYSTEM_PREFERENCES_NAME = 'CiviCRM Preferences',
URL_PREFERENCES_NAME = 'URL Preferences',
LOCALIZATION_PREFERENCES_NAME = 'Localization Preferences',
SEARCH_PREFERENCES_NAME = 'Search Preferences';
/**
* Retrieve the value of a setting from the DB table.
*
* @param string $group
* The group name of the item (deprecated).
* @param string $name
* (required) The name under which this item is stored.
* @param int $componentID
* The optional component ID (so componenets can share the same name space).
* @param string $defaultValue
* The default value to return for this setting if not present in DB.
* @param int $contactID
* If set, this is a contactID specific setting, else its a global setting.
*
* @param int $domainID
*
* @return mixed
* The data if present in the setting table, else null
*/
public static function getItem(
$group,
$name = NULL,
$componentID = NULL,
$defaultValue = NULL,
$contactID = NULL,
$domainID = NULL
) {
/** @var \Civi\Core\SettingsManager $manager */
$manager = \Civi::service('settings_manager');
$settings = ($contactID === NULL) ? $manager->getBagByDomain($domainID) : $manager->getBagByContact($domainID, $contactID);
if ($name === NULL) {
CRM_Core_Error::debug_log_message("Deprecated: Group='$group'. Name should be provided.\n");
}
if ($componentID !== NULL) {
CRM_Core_Error::debug_log_message("Deprecated: Group='$group'. Name='$name'. Component should be omitted\n");
}
if ($defaultValue !== NULL) {
CRM_Core_Error::debug_log_message("Deprecated: Group='$group'. Name='$name'. Defaults should come from metadata\n");
}
return $name ? $settings->get($name) : $settings->all();
}
/**
* Store multiple items in the setting table.
*
* @param array $params
* (required) An api formatted array of keys and values.
* @param array $domains Array of domains to get settings for. Default is the current domain
* @param $settingsToReturn
*
* @return array
*/
public static function getItems(&$params, $domains = NULL, $settingsToReturn) {
$originalDomain = CRM_Core_Config::domainID();
if (empty($domains)) {
$domains[] = $originalDomain;
}
if (!empty($settingsToReturn) && !is_array($settingsToReturn)) {
$settingsToReturn = array($settingsToReturn);
}
$fields = $result = array();
$fieldsToGet = self::validateSettingsInput(array_flip($settingsToReturn), $fields, FALSE);
foreach ($domains as $domainID) {
$result[$domainID] = array();
foreach ($fieldsToGet as $name => $value) {
$contactID = CRM_Utils_Array::value('contact_id', $params);
$setting = CRM_Core_BAO_Setting::getItem(NULL, $name, NULL, NULL, $contactID, $domainID);
if (!is_null($setting)) {
// we won't return if not set - helps in return all scenario - otherwise we can't indentify the missing ones
// e.g for revert of fill actions
$result[$domainID][$name] = $setting;
}
}
}
return $result;
}
/**
* Store an item in the setting table.
*
* _setItem() is the common logic shared by setItem() and setItems().
*
* @param object $value
* (required) The value that will be serialized and stored.
* @param string $group
* The group name of the item (deprecated).
* @param string $name
* (required) The name of the setting.
* @param int $componentID
* The optional component ID (so componenets can share the same name space).
* @param int $contactID
* @param int $createdID
* An optional ID to assign the creator to. If not set, retrieved from session.
*
* @param int $domainID
*/
public static function setItem(
$value,
$group,
$name,
$componentID = NULL,
$contactID = NULL,
$createdID = NULL,
$domainID = NULL
) {
/** @var \Civi\Core\SettingsManager $manager */
$manager = \Civi::service('settings_manager');
$settings = ($contactID === NULL) ? $manager->getBagByDomain($domainID) : $manager->getBagByContact($domainID, $contactID);
$settings->set($name, $value);
}
/**
* Store multiple items in the setting table. Note that this will also store config keys
* the storage is determined by the metdata and is affected by
* 'name' setting's name
* 'config_key' = the config key is different to the settings key - e.g. debug where there was a conflict
* 'legacy_key' = rename from config or setting with this name
*
* _setItem() is the common logic shared by setItem() and setItems().
*
* @param array $params
* (required) An api formatted array of keys and values.
* @param null $domains
*
* @throws api_Exception
* @domains array an array of domains to get settings for. Default is the current domain
* @return array
*/
public static function setItems(&$params, $domains = NULL) {
$domains = empty($domains) ? array(CRM_Core_Config::domainID()) : $domains;
// FIXME: redundant validation
// FIXME: this whole thing should just be a loop to call $settings->add() on each domain.
$fields = array();
$fieldsToSet = self::validateSettingsInput($params, $fields);
foreach ($fieldsToSet as $settingField => &$settingValue) {
if (empty($fields['values'][$settingField])) {
Civi::log()->warning('Deprecated Path: There is a setting (' . $settingField . ') not correctly defined. You may see unpredictability due to this. CRM_Core_Setting::setItems', array('civi.tag' => 'deprecated'));
$fields['values'][$settingField] = array();
}
self::validateSetting($settingValue, $fields['values'][$settingField]);
}
foreach ($domains as $domainID) {
Civi::settings($domainID)->add($fieldsToSet);
$result[$domainID] = $fieldsToSet;
}
return $result;
}
/**
* Gets metadata about the settings fields (from getfields) based on the fields being passed in
*
* This function filters on the fields like 'version' & 'debug' that are not settings
*
* @param array $params
* Parameters as passed into API.
* @param array $fields
* Empty array to be populated with fields metadata.
* @param bool $createMode
*
* @throws api_Exception
* @return array
* name => value array of the fields to be set (with extraneous removed)
*/
public static function validateSettingsInput($params, &$fields, $createMode = TRUE) {
$ignoredParams = array(
'version',
'id',
'domain_id',
'debug',
'created_id',
'component_id',
'contact_id',
'filters',
'entity_id',
'entity_table',
'sequential',
'api.has_parent',
'IDS_request_uri',
'IDS_user_agent',
'check_permissions',
'options',
'prettyprint',
// CRM-18347: ignore params unintentionally passed by API explorer on WP
'page',
'noheader',
// CRM-18347: ignore params unintentionally passed by wp CLI tool
'',
// CRM-19877: ignore params extraneously passed by Joomla
'option',
'task',
);
$settingParams = array_diff_key($params, array_fill_keys($ignoredParams, TRUE));
$getFieldsParams = array('version' => 3);
if (count($settingParams) == 1) {
// ie we are only setting one field - we'll pass it into getfields for efficiency
list($name) = array_keys($settingParams);
$getFieldsParams['name'] = $name;
}
$fields = civicrm_api3('setting', 'getfields', $getFieldsParams);
$invalidParams = (array_diff_key($settingParams, $fields['values']));
if (!empty($invalidParams)) {
throw new api_Exception(implode(',', array_keys($invalidParams)) . " not valid settings");
}
if (!empty($settingParams)) {
$filteredFields = array_intersect_key($settingParams, $fields['values']);
}
else {
// no filters so we are interested in all for get mode. In create mode this means nothing to set
$filteredFields = $createMode ? array() : $fields['values'];
}
return $filteredFields;
}
/**
* Validate & convert settings input.
*
* @param mixed $value
* value of the setting to be set
* @param array $fieldSpec
* Metadata for given field (drawn from the xml)
*
* @return bool
* @throws \api_Exception
*/
public static function validateSetting(&$value, array $fieldSpec) {
if ($fieldSpec['type'] == 'String' && is_array($value)) {
$value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $value) . CRM_Core_DAO::VALUE_SEPARATOR;
}
if (empty($fieldSpec['validate_callback'])) {
return TRUE;
}
else {
$cb = Civi\Core\Resolver::singleton()->get($fieldSpec['validate_callback']);
if (!call_user_func_array($cb, array(&$value, $fieldSpec))) {
throw new api_Exception("validation failed for {$fieldSpec['name']} = $value based on callback {$fieldSpec['validate_callback']}");
}
}
}
/**
* Validate & convert settings input - translate True False to 0 or 1.
*
* @param mixed $value value of the setting to be set
* @param array $fieldSpec Metadata for given field (drawn from the xml)
*
* @return bool
* @throws \api_Exception
*/
public static function validateBoolSetting(&$value, $fieldSpec) {
if (!CRM_Utils_Rule::boolean($value)) {
throw new api_Exception("Boolean value required for {$fieldSpec['name']}");
}
if (!$value) {
$value = 0;
}
else {
$value = 1;
}
return TRUE;
}
/**
* This provides information about the setting - similar to the fields concept for DAO information.
* As the setting is serialized code creating validation setting input needs to know the data type
* This also helps move information out of the form layer into the data layer where people can interact with
* it via the API or other mechanisms. In order to keep this consistent it is important the form layer
* also leverages it.
*
* Note that this function should never be called when using the runtime getvalue function. Caching works
* around the expectation it will be called during setting administration
*
* Function is intended for configuration rather than runtime access to settings
*
* The following params will filter the result. If none are passed all settings will be returns
*
* @param int $componentID
* Id of relevant component.
* @param array $filters
* @param int $domainID
* @param null $profile
*
* @return array
* the following information as appropriate for each setting
* - name
* - type
* - default
* - add (CiviCRM version added)
* - is_domain
* - is_contact
* - description
* - help_text
*/
public static function getSettingSpecification(
$componentID = NULL,
$filters = array(),
$domainID = NULL,
$profile = NULL
) {
return \Civi\Core\SettingsMetadata::getMetadata($filters, $domainID);
}
/**
* @param $group
* @param string $name
* @param bool $system
* @param int $userID
* @param bool $localize
* @param string $returnField
* @param bool $returnNameANDLabels
* @param null $condition
*
* @return array
*/
public static function valueOptions(
$group,
$name,
$system = TRUE,
$userID = NULL,
$localize = FALSE,
$returnField = 'name',
$returnNameANDLabels = FALSE,
$condition = NULL
) {
$optionValue = self::getItem($group, $name);
$groupValues = CRM_Core_OptionGroup::values($name, FALSE, FALSE, $localize, $condition, $returnField);
//enabled name => label require for new contact edit form, CRM-4605
if ($returnNameANDLabels) {
$names = $labels = $nameAndLabels = array();
if ($returnField == 'name') {
$names = $groupValues;
$labels = CRM_Core_OptionGroup::values($name, FALSE, FALSE, $localize, $condition, 'label');
}
else {
$labels = $groupValues;
$names = CRM_Core_OptionGroup::values($name, FALSE, FALSE, $localize, $condition, 'name');
}
}
$returnValues = array();
foreach ($groupValues as $gn => $gv) {
$returnValues[$gv] = 0;
}
if ($optionValue && !empty($groupValues)) {
$dbValues = explode(CRM_Core_DAO::VALUE_SEPARATOR,
substr($optionValue, 1, -1)
);
if (!empty($dbValues)) {
foreach ($groupValues as $key => $val) {
if (in_array($key, $dbValues)) {
$returnValues[$val] = 1;
if ($returnNameANDLabels) {
$nameAndLabels[$names[$key]] = $labels[$key];
}
}
}
}
}
return ($returnNameANDLabels) ? $nameAndLabels : $returnValues;
}
/**
* @param $group (deprecated)
* @param string $name
* @param $value
* @param bool $system
* @param int $userID
* @param string $keyField
*/
public static function setValueOption(
$group,
$name,
$value,
$system = TRUE,
$userID = NULL,
$keyField = 'name'
) {
if (empty($value)) {
$optionValue = NULL;
}
elseif (is_array($value)) {
$groupValues = CRM_Core_OptionGroup::values($name, FALSE, FALSE, FALSE, NULL, $keyField);
$cbValues = array();
foreach ($groupValues as $key => $val) {
if (!empty($value[$val])) {
$cbValues[$key] = 1;
}
}
if (!empty($cbValues)) {
$optionValue = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
array_keys($cbValues)
) . CRM_Core_DAO::VALUE_SEPARATOR;
}
else {
$optionValue = NULL;
}
}
else {
$optionValue = $value;
}
self::setItem($optionValue, $group, $name);
}
/**
* Civicrm_setting didn't exist before 4.1.alpha1 and this function helps taking decisions during upgrade
*
* @return bool
*/
public static function isUpgradeFromPreFourOneAlpha1() {
if (CRM_Core_Config::isUpgradeMode()) {
$currentVer = CRM_Core_BAO_Domain::version();
if (version_compare($currentVer, '4.1.alpha1') < 0) {
return TRUE;
}
}
return FALSE;
}
/**
* Check if environment is explicitly set.
*
* @return bool
*/
public static function isEnvironmentSet($setting, $value = NULL) {
$environment = CRM_Core_Config::environment();
if ($setting == 'environment' && $environment) {
return TRUE;
}
return FALSE;
}
/**
* Check if job is able to be executed by API.
*
* @throws API_Exception
*/
public static function isAPIJobAllowedToRun($params) {
$environment = CRM_Core_Config::environment(NULL, TRUE);
if ($environment != 'Production') {
if (CRM_Utils_Array::value('runInNonProductionEnvironment', $params)) {
$mailing = Civi::settings()->get('mailing_backend_store');
if ($mailing) {
Civi::settings()->set('mailing_backend', $mailing);
}
}
else {
throw new Exception(ts("Job has not been executed as it is a %1 (non-production) environment.", array(1 => $environment)));
}
}
}
/**
* Setting Callback - On Change.
*
* Respond to changes in the "environment" setting.
*
* @param array $oldValue
* Value of old environment mode.
* @param array $newValue
* Value of new environment mode.
* @param array $metadata
* Specification of the setting (per *.settings.php).
*/
public static function onChangeEnvironmentSetting($oldValue, $newValue, $metadata) {
if ($newValue != 'Production') {
$mailing = Civi::settings()->get('mailing_backend');
if ($mailing['outBound_option'] != 2) {
Civi::settings()->set('mailing_backend_store', $mailing);
}
Civi::settings()->set('mailing_backend', array('outBound_option' => CRM_Mailing_Config::OUTBOUND_OPTION_DISABLED));
CRM_Core_Session::setStatus(ts('Outbound emails have been disabled. Scheduled jobs will not run unless runInNonProductionEnvironment=TRUE is added as a parameter for a specific job'), ts("Non-production environment set"), "success");
}
else {
$mailing = Civi::settings()->get('mailing_backend_store');
if ($mailing) {
Civi::settings()->set('mailing_backend', $mailing);
}
}
}
}

View file

@ -0,0 +1,98 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class contains functions for managing Status Preferences.
*/
class CRM_Core_BAO_StatusPreference extends CRM_Core_DAO_StatusPreference {
/**
* Create or update a Status Preference entry.
*
* @param array $params
*
* @return array
*/
public static function create($params) {
$statusPreference = new CRM_Core_BAO_StatusPreference();
// Default severity level to ignore is 0 (DEBUG).
if (!isset($params['ignore_severity'])) {
$params['ignore_severity'] = 0;
}
// Severity can be either text ('critical') or an integer <= 7.
// It's a magic number, but based on PSR-3 standards.
if (!CRM_Utils_Rule::integer($params['ignore_severity'])) {
$params['ignore_severity'] = CRM_Utils_Check::severityMap($params['ignore_severity']);
}
if ($params['ignore_severity'] > 7) {
CRM_Core_Error::fatal(ts('You can not pass a severity level higher than 7.'));
}
// If severity is now blank, you have an invalid severity string.
if (is_null($params['ignore_severity'])) {
CRM_Core_Error::fatal(ts('Invalid string passed as severity level.'));
}
// Check if this StatusPreference already exists.
if (empty($params['id']) && CRM_Utils_Array::value('name', $params)) {
$statusPreference->domain_id = CRM_Utils_Array::value('domain_id', $params, CRM_Core_Config::domainID());
$statusPreference->name = $params['name'];
$statusPreference->find(TRUE);
}
$statusPreference->copyValues($params);
$edit = ($statusPreference->id) ? TRUE : FALSE;
if ($edit) {
CRM_Utils_Hook::pre('edit', 'StatusPreference', $statusPreference->id, $statusPreference);
}
else {
CRM_Utils_Hook::pre('create', 'StatusPreference', NULL, $statusPreference);
}
$statusPreference->save();
if ($edit) {
CRM_Utils_Hook::post('edit', 'StatusPreference', $statusPreference->id, $statusPreference);
}
else {
CRM_Utils_Hook::post('create', 'StatusPreference', NULL, $statusPreference);
}
return $statusPreference;
}
}

View file

@ -0,0 +1,587 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_Core_BAO_Tag extends CRM_Core_DAO_Tag {
/**
* @var array
*/
protected $tree;
/**
* Class constructor.
*/
public function __construct() {
parent::__construct();
}
/**
* Fetch object based on array of properties.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $defaults
* (reference ) an assoc array to hold the flattened values.
*
* @return object
* CRM_Core_DAO_Tag object on success, otherwise null
*/
public static function retrieve(&$params, &$defaults) {
$tag = new CRM_Core_DAO_Tag();
$tag->copyValues($params);
if ($tag->find(TRUE)) {
CRM_Core_DAO::storeValues($tag, $defaults);
return $tag;
}
return NULL;
}
/**
* Get tag tree.
*
* @param string $usedFor
* @param bool $excludeHidden
*
* @return mixed
*/
public function getTree($usedFor = NULL, $excludeHidden = FALSE) {
if (!isset($this->tree)) {
$this->buildTree($usedFor, $excludeHidden);
}
return $this->tree;
}
/**
* Build a nested array from hierarchical tags.
*
* Supports infinite levels of nesting.
* @param null $usedFor
* @param bool $excludeHidden
*/
public function buildTree($usedFor = NULL, $excludeHidden = FALSE) {
$sql = "SELECT id, parent_id, name, description, is_selectable FROM civicrm_tag";
$whereClause = array();
if ($usedFor) {
$whereClause[] = "used_for like '%{$usedFor}%'";
}
if ($excludeHidden) {
$whereClause[] = "is_tagset = 0";
}
if (!empty($whereClause)) {
$sql .= " WHERE " . implode(' AND ', $whereClause);
}
$sql .= " ORDER BY parent_id,name";
$dao = CRM_Core_DAO::executeQuery($sql, array(), TRUE, NULL, FALSE, FALSE);
$refs = array();
$this->tree = array();
while ($dao->fetch()) {
$thisref = &$refs[$dao->id];
$thisref['parent_id'] = $dao->parent_id;
$thisref['name'] = $dao->name;
$thisref['description'] = $dao->description;
$thisref['is_selectable'] = $dao->is_selectable;
if (!$dao->parent_id) {
$this->tree[$dao->id] = &$thisref;
}
else {
$refs[$dao->parent_id]['children'][$dao->id] = &$thisref;
}
}
}
/**
* Get tags used for the given entity/entities.
*
* @param array $usedFor
* @param bool $buildSelect
* @param bool $all
* @param int $parentId
*
* @return array
*/
public static function getTagsUsedFor(
$usedFor = array('civicrm_contact'),
$buildSelect = TRUE,
$all = FALSE,
$parentId = NULL
) {
$tags = array();
if (empty($usedFor)) {
return $tags;
}
if (!is_array($usedFor)) {
$usedFor = array($usedFor);
}
if ($parentId === NULL) {
$parentClause = " parent_id IS NULL AND ";
}
else {
$parentClause = " parent_id = {$parentId} AND ";
}
foreach ($usedFor as $entityTable) {
$tag = new CRM_Core_DAO_Tag();
$tag->fields();
$tag->orderBy('parent_id');
if ($buildSelect) {
$tag->whereAdd("is_tagset = 0 AND {$parentClause} used_for LIKE '%{$entityTable}%'");
}
else {
$tag->whereAdd("used_for LIKE '%{$entityTable}%'");
}
if (!$all) {
$tag->is_tagset = 0;
}
$tag->find();
while ($tag->fetch()) {
if ($buildSelect) {
$tags[$tag->id] = $tag->name;
}
else {
$tags[$tag->id]['name'] = $tag->name;
$tags[$tag->id]['parent_id'] = $tag->parent_id;
$tags[$tag->id]['is_tagset'] = $tag->is_tagset;
$tags[$tag->id]['used_for'] = $tag->used_for;
$tags[$tag->id]['description'] = $tag->description;
$tags[$tag->id]['color'] = !empty($tag->color) ? $tag->color : NULL;
}
}
$tag->free();
}
return $tags;
}
/**
* Function to retrieve tags.
*
* @param string $usedFor
* Which type of tag entity.
* @param array $tags
* Tags array.
* @param int $parentId
* Parent id if you want need only children.
* @param string $separator
* Separator to indicate children.
* @param bool $formatSelectable
* Add special property for non-selectable.
* tag, so they cannot be selected
*
* @return array
*/
public static function getTags(
$usedFor = 'civicrm_contact',
&$tags = array(),
$parentId = NULL,
$separator = '&nbsp;&nbsp;',
$formatSelectable = FALSE
) {
if (!is_array($tags)) {
$tags = array();
}
// We need to build a list of tags ordered by hierarchy and sorted by
// name. The hierarchy will be communicated by an accumulation of
// separators in front of the name to give it a visual offset.
// Instead of recursively making mysql queries, we'll make one big
// query and build the hierarchy with the algorithm below.
$args = array(1 => array('%' . $usedFor . '%', 'String'));
$query = "SELECT id, name, parent_id, is_tagset, is_selectable
FROM civicrm_tag
WHERE used_for LIKE %1";
if ($parentId) {
$query .= " AND parent_id = %2";
$args[2] = array($parentId, 'Integer');
}
$query .= " ORDER BY name";
$dao = CRM_Core_DAO::executeQuery($query, $args, TRUE, NULL, FALSE, FALSE);
// Sort the tags into the correct storage by the parent_id/is_tagset
// filter the filter was in place previously, we're just reusing it.
// $roots represents the current leaf nodes that need to be checked for
// children. $rows represents the unplaced nodes, not all of much
// are necessarily placed.
$roots = $rows = array();
while ($dao->fetch()) {
// note that we are prepending id with "crm_disabled_opt" which identifies
// them as disabled so that they cannot be selected. We do some magic
// in crm-select2 js function that marks option values to "disabled"
// current QF version in CiviCRM does not support passing this attribute,
// so this is another ugly hack / workaround,
// also know one is too keen to upgrade QF :P
$idPrefix = '';
if ($formatSelectable && !$dao->is_selectable) {
$idPrefix = "crm_disabled_opt";
}
if ($dao->parent_id == $parentId && $dao->is_tagset == 0) {
$roots[] = array(
'id' => $dao->id,
'prefix' => '',
'name' => $dao->name,
'idPrefix' => $idPrefix,
);
}
else {
$rows[] = array(
'id' => $dao->id,
'prefix' => '',
'name' => $dao->name,
'parent_id' => $dao->parent_id,
'idPrefix' => $idPrefix,
);
}
}
$dao->free();
// While we have nodes left to build, shift the first (alphabetically)
// node of the list, place it in our tags list and loop through the
// list of unplaced nodes to find its children. We make a copy to
// iterate through because we must modify the unplaced nodes list
// during the loop.
while (count($roots)) {
$new_roots = array();
$current_rows = $rows;
$root = array_shift($roots);
$tags[$root['id']] = array(
$root['prefix'],
$root['name'],
$root['idPrefix'],
);
// As you find the children, append them to the end of the new set
// of roots (maintain alphabetical ordering). Also remove the node
// from the set of unplaced nodes.
if (is_array($current_rows)) {
foreach ($current_rows as $key => $row) {
if ($row['parent_id'] == $root['id']) {
$new_roots[] = array(
'id' => $row['id'],
'prefix' => $tags[$root['id']][0] . $separator,
'name' => $row['name'],
'idPrefix' => $row['idPrefix'],
);
unset($rows[$key]);
}
}
}
//As a group, insert the new roots into the beginning of the roots
//list. This maintains the hierarchical ordering of the tags.
$roots = array_merge($new_roots, $roots);
}
// Prefix each name with the calcuated spacing to give the visual
// appearance of ordering when transformed into HTML in the form layer.
// here is the actual code that to prepends and set disabled attribute for
// non-selectable tags
$formattedTags = array();
foreach ($tags as $key => $tag) {
if (!empty($tag[2])) {
$key = $tag[2] . "-" . $key;
}
$formattedTags[$key] = $tag[0] . $tag[1];
}
$tags = $formattedTags;
return $tags;
}
/**
* @param string $usedFor
* @param bool $allowSelectingNonSelectable
* @param null $exclude
* @return array
* @throws \CiviCRM_API3_Exception
*/
public static function getColorTags($usedFor = NULL, $allowSelectingNonSelectable = FALSE, $exclude = NULL) {
$params = array(
'options' => array(
'limit' => 0,
'sort' => "name ASC",
),
'is_tagset' => 0,
'return' => array('name', 'description', 'parent_id', 'color', 'is_selectable', 'used_for'),
);
if ($usedFor) {
$params['used_for'] = array('LIKE' => "%$usedFor%");
}
if ($exclude) {
$params['id'] = array('!=' => $exclude);
}
$allTags = array();
foreach (CRM_Utils_Array::value('values', civicrm_api3('Tag', 'get', $params)) as $id => $tag) {
$allTags[$id] = array(
'text' => $tag['name'],
'id' => $id,
'description' => CRM_Utils_Array::value('description', $tag),
'parent_id' => CRM_Utils_Array::value('parent_id', $tag),
'used_for' => CRM_Utils_Array::value('used_for', $tag),
'color' => CRM_Utils_Array::value('color', $tag),
);
if (!$allowSelectingNonSelectable && empty($tag['is_selectable'])) {
$allTags[$id]['disabled'] = TRUE;
}
}
return CRM_Utils_Array::buildTree($allTags);
}
/**
* Delete the tag.
*
* @param int $id
* Tag id.
*
* @return bool
*/
public static function del($id) {
// since this is a destructive operation, lets make sure
// id is a positive number
CRM_Utils_Type::validate($id, 'Positive');
// delete all crm_entity_tag records with the selected tag id
$entityTag = new CRM_Core_DAO_EntityTag();
$entityTag->tag_id = $id;
$entityTag->delete();
// delete from tag table
$tag = new CRM_Core_DAO_Tag();
$tag->id = $id;
CRM_Utils_Hook::pre('delete', 'Tag', $id, $tag);
if ($tag->delete()) {
CRM_Utils_Hook::post('delete', 'Tag', $id, $tag);
return TRUE;
}
return FALSE;
}
/**
* Takes an associative array and creates a tag object.
*
* The function extract all the params it needs to initialize the create a
* contact object. the params array could contain additional unused name/value
* pairs
*
* @param array $params
* (reference) an assoc array of name/value pairs.
* @param array $ids
* (optional) the array that holds all the db ids - we are moving away from this in bao.
* signatures
*
* @return CRM_Core_DAO_Tag|null
* object on success, otherwise null
*/
public static function add(&$params, $ids = array()) {
$id = CRM_Utils_Array::value('id', $params, CRM_Utils_Array::value('tag', $ids));
if (!$id && !self::dataExists($params)) {
return NULL;
}
// Check permission to create or modify reserved tag
if (!empty($params['check_permissions']) && !CRM_Core_Permission::check('administer reserved tags')) {
if (!empty($params['is_reserved']) || ($id && CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Tag', $id, 'is_reserved'))) {
throw new CRM_Core_Exception('Insufficient permission to administer reserved tag.');
}
}
// Check permission to create or modify tagset
if (!empty($params['check_permissions']) && !CRM_Core_Permission::check('administer Tagsets')) {
if (!empty($params['is_tagset']) || ($id && CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Tag', $id, 'is_tagset'))) {
throw new CRM_Core_Exception('Insufficient permission to administer tagset.');
}
}
$tag = new CRM_Core_DAO_Tag();
// if parent id is set then inherit used for and is hidden properties
if (!empty($params['parent_id'])) {
// get parent details
$params['used_for'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Tag', $params['parent_id'], 'used_for');
}
elseif (isset($params['used_for']) && is_array($params['used_for'])) {
$params['used_for'] = implode(',', $params['used_for']);
}
if (isset($params['color']) && strtolower($params['color']) === '#ffffff') {
$params['color'] = '';
}
$tag->copyValues($params);
$tag->id = $id;
$hook = !$id ? 'create' : 'edit';
CRM_Utils_Hook::pre($hook, 'Tag', $tag->id, $params);
// save creator id and time
if (!$tag->id) {
$session = CRM_Core_Session::singleton();
$tag->created_id = $session->get('userID');
$tag->created_date = date('YmdHis');
}
$tag->save();
CRM_Utils_Hook::post($hook, 'Tag', $tag->id, $tag);
// if we modify parent tag, then we need to update all children
$tag->find(TRUE);
if (!$tag->parent_id && $tag->used_for) {
CRM_Core_DAO::executeQuery("UPDATE civicrm_tag SET used_for=%1 WHERE parent_id = %2",
array(
1 => array($tag->used_for, 'String'),
2 => array($tag->id, 'Integer'),
)
);
}
return $tag;
}
/**
* Check if there is data to create the object.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
*
* @return bool
*/
public static function dataExists(&$params) {
// Disallow empty values except for the number zero.
// TODO: create a utility for this since it's needed in many places
if (!empty($params['name']) || (string) $params['name'] === '0') {
return TRUE;
}
return FALSE;
}
/**
* Get the tag sets for a entity object.
*
* @param string $entityTable
* Entity_table.
*
* @return array
* array of tag sets
*/
public static function getTagSet($entityTable) {
$tagSets = array();
$query = "SELECT name, id FROM civicrm_tag
WHERE is_tagset=1 AND parent_id IS NULL and used_for LIKE %1";
$dao = CRM_Core_DAO::executeQuery($query, array(
1 => array(
'%' . $entityTable . '%',
'String',
),
), TRUE, NULL, FALSE, FALSE);
while ($dao->fetch()) {
$tagSets[$dao->id] = $dao->name;
}
$dao->free();
return $tagSets;
}
/**
* Get the tags that are not children of a tagset.
*
* @return array
* associated array of tag name and id
*/
public static function getTagsNotInTagset() {
$tags = $tagSets = array();
// first get all the tag sets
$query = "SELECT id FROM civicrm_tag WHERE is_tagset=1 AND parent_id IS NULL";
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
$tagSets[] = $dao->id;
}
$parentClause = '';
if (!empty($tagSets)) {
$parentClause = ' WHERE ( parent_id IS NULL ) OR ( parent_id NOT IN ( ' . implode(',', $tagSets) . ' ) )';
}
// get that tags that don't have tagset as parent
$query = "SELECT id, name FROM civicrm_tag {$parentClause}";
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
$tags[$dao->id] = $dao->name;
}
return $tags;
}
/**
* Get child tags IDs
*
* @return array $childTagIDs
* associated array of child tags in Array('Parent Tag ID' => Array('Child Tag 1', ...)) format
*/
public static function getChildTags() {
$childTagIDs = array();
// only fetch those tags which has child tags
$getChildGroupSQL = "SELECT parent.id as parent_id, GROUP_CONCAT(child.id) as child_id
FROM civicrm_tag parent,
civicrm_tag child
WHERE parent.is_tagset <> 1 AND child.parent_id = parent.id
GROUP BY parent.id
";
$dao = CRM_Core_DAO::executeQuery($getChildGroupSQL);
while ($dao->fetch()) {
$childTagIDs[$dao->parent_id] = (array) explode(',', $dao->child_id);
}
// check if child tag has any childs, if found then include those child tags inside parent tag
// i.e. format Array('parent_tag' => array('child_tag_1', ...), 'child_tag_1' => array(child_tag_1_1, ..), ..)
// to Array('parent_tag' => array('child_tag_1', 'child_tag_1_1'...), ..)
foreach ($childTagIDs as $parentTagID => $childTags) {
foreach ($childTags as $childTag) {
// if $childTag has any child tag of its own
if (array_key_exists($childTag, $childTagIDs)) {
$childTagIDs[$parentTagID] = array_merge($childTagIDs[$parentTagID], $childTagIDs[$childTag]);
}
}
}
return $childTagIDs;
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,196 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
*
*/
class CRM_Core_BAO_UFJoin extends CRM_Core_DAO_UFJoin {
/**
* Takes an associative array and creates a uf join object.
*
* @param array $params
* (reference) an assoc array of name/value pairs.
*
* @return CRM_Core_DAO_UFJoin
*/
public static function &create($params) {
// see if a record exists with the same weight
$id = self::findJoinEntryId($params);
if ($id) {
$params['id'] = $id;
}
$dao = new CRM_Core_DAO_UFJoin();
$dao->copyValues($params);
if ($params['uf_group_id']) {
$dao->save();
}
else {
$dao->delete();
}
return $dao;
}
/**
* @param array $params
*/
public static function deleteAll(&$params) {
$module = CRM_Utils_Array::value('module', $params);
$entityTable = CRM_Utils_Array::value('entity_table', $params);
$entityID = CRM_Utils_Array::value('entity_id', $params);
if (empty($entityTable) ||
empty($entityID) ||
empty($module)
) {
return;
}
$dao = new CRM_Core_DAO_UFJoin();
$dao->module = $module;
$dao->entity_table = $entityTable;
$dao->entity_id = $entityID;
$dao->delete();
}
/**
* Given an assoc list of params, find if there is a record
* for this set of params
*
* @param array $params
* (reference) an assoc array of name/value pairs.
*
* @return int
* or null
*/
public static function findJoinEntryId(&$params) {
if (!empty($params['id'])) {
return $params['id'];
}
$dao = new CRM_Core_DAO_UFJoin();
// CRM-4377 (ab)uses the module column
if (isset($params['module'])) {
$dao->module = CRM_Utils_Array::value('module', $params);
}
$dao->entity_table = CRM_Utils_Array::value('entity_table', $params);
$dao->entity_id = CRM_Utils_Array::value('entity_id', $params);
// user reg / my account can have multiple entries, so we return if thats
// the case. (since entity_table/id is empty in those cases
if (!$dao->entity_table ||
!$dao->entity_id
) {
return NULL;
}
$dao->weight = CRM_Utils_Array::value('weight', $params);
if ($dao->find(TRUE)) {
return $dao->id;
}
return NULL;
}
/**
* Given an assoc list of params, find if there is a record
* for this set of params and return the group id
*
* @param array $params
* (reference) an assoc array of name/value pairs.
*
* @return int
* or null
*/
public static function findUFGroupId(&$params) {
$dao = new CRM_Core_DAO_UFJoin();
$dao->entity_table = CRM_Utils_Array::value('entity_table', $params);
$dao->entity_id = CRM_Utils_Array::value('entity_id', $params);
$dao->weight = CRM_Utils_Array::value('weight', $params);
$dao->module = CRM_Utils_Array::value('module', $params);
if ($dao->find(TRUE)) {
return $dao->uf_group_id;
}
return NULL;
}
/**
* @param array $params
*
* @return array
*/
public static function getUFGroupIds(&$params) {
$dao = new CRM_Core_DAO_UFJoin();
// CRM-4377 (ab)uses the module column
if (isset($params['module'])) {
$dao->module = CRM_Utils_Array::value('module', $params);
}
$dao->entity_table = CRM_Utils_Array::value('entity_table', $params);
$dao->entity_id = CRM_Utils_Array::value('entity_id', $params);
$dao->orderBy('weight asc');
$dao->find();
$first = $firstActive = NULL;
$second = $secondActive = array();
while ($dao->fetch()) {
if ($dao->weight == 1) {
$first = $dao->uf_group_id;
$firstActive = $dao->is_active;
}
else {
$second[] = $dao->uf_group_id;
$secondActive[] = $dao->is_active;
}
}
return array($first, $second, $firstActive, $secondActive);
}
/**
* Whitelist of possible values for the entity_table field
* @return array
*/
public static function entityTables() {
return array(
'civicrm_event' => 'Event',
'civicrm_contribution_page' => 'ContributionPage',
'civicrm_survey' => 'Survey',
);
}
}

View file

@ -0,0 +1,651 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* The basic class that interfaces with the external user framework.
*/
class CRM_Core_BAO_UFMatch extends CRM_Core_DAO_UFMatch {
/**
* Create UF Match, Note that this function is here in it's simplest form @ the moment
*
* @param $params
*
* @return \CRM_Core_DAO_UFMatch
*/
public static function create($params) {
$hook = empty($params['id']) ? 'create' : 'edit';
CRM_Utils_Hook::pre($hook, 'UFMatch', CRM_Utils_Array::value('id', $params), $params);
if (empty($params['domain_id'])) {
$params['domain_id'] = CRM_Core_Config::domainID();
}
$dao = new CRM_Core_DAO_UFMatch();
$dao->copyValues($params);
if (!$dao->find(TRUE)) {
$dao->save();
}
CRM_Utils_Hook::post($hook, 'UFMatch', $dao->id, $dao);
return $dao;
}
/**
* Given a UF user object, make sure there is a contact
* object for this user. If the user has new values, we need
* to update the CRM DB with the new values
*
* @param Object $user
* The drupal user object.
* @param bool $update
* Has the user object been edited.
* @param $uf
*
* @param $ctype
* @param bool $isLogin
*/
public static function synchronize(&$user, $update, $uf, $ctype, $isLogin = FALSE) {
$userSystem = CRM_Core_Config::singleton()->userSystem;
$session = CRM_Core_Session::singleton();
if (!is_object($session)) {
CRM_Core_Error::fatal('wow, session is not an object?');
return;
}
$userSystemID = $userSystem->getBestUFID($user);
$uniqId = $userSystem->getBestUFUniqueIdentifier($user);
// if the id of the object is zero (true for anon users in drupal)
// have we already processed this user, if so early
// return.
$userID = $session->get('userID');
$ufID = $session->get('ufID');
if (!$update && $ufID == $userSystemID) {
return;
}
//check do we have logged in user.
$isUserLoggedIn = CRM_Utils_System::isUserLoggedIn();
// reset the session if we are a different user
if ($ufID && $ufID != $userSystemID) {
$session->reset();
//get logged in user ids, and set to session.
if ($isUserLoggedIn) {
$userIds = self::getUFValues();
$session->set('ufID', CRM_Utils_Array::value('uf_id', $userIds, ''));
$session->set('userID', CRM_Utils_Array::value('contact_id', $userIds, ''));
$session->set('ufUniqID', CRM_Utils_Array::value('uf_name', $userIds, ''));
}
}
// return early
if ($userSystemID == 0) {
return;
}
$ufmatch = self::synchronizeUFMatch($user, $userSystemID, $uniqId, $uf, NULL, $ctype, $isLogin);
if (!$ufmatch) {
return;
}
//make sure we have session w/ consistent ids.
$ufID = $ufmatch->uf_id;
$userID = $ufmatch->contact_id;
$ufUniqID = '';
if ($isUserLoggedIn) {
$loggedInUserUfID = CRM_Utils_System::getLoggedInUfID();
//are we processing logged in user.
if ($loggedInUserUfID && $loggedInUserUfID != $ufID) {
$userIds = self::getUFValues($loggedInUserUfID);
$ufID = CRM_Utils_Array::value('uf_id', $userIds, '');
$userID = CRM_Utils_Array::value('contact_id', $userIds, '');
$ufUniqID = CRM_Utils_Array::value('uf_name', $userIds, '');
}
}
//set user ids to session.
$session->set('ufID', $ufID);
$session->set('userID', $userID);
$session->set('ufUniqID', $ufUniqID);
// add current contact to recently viewed
if ($ufmatch->contact_id) {
list($displayName, $contactImage, $contactType, $contactSubtype, $contactImageUrl)
= CRM_Contact_BAO_Contact::getDisplayAndImage($ufmatch->contact_id, TRUE, TRUE);
$otherRecent = array(
'imageUrl' => $contactImageUrl,
'subtype' => $contactSubtype,
'editUrl' => CRM_Utils_System::url('civicrm/contact/add', "reset=1&action=update&cid={$ufmatch->contact_id}"),
);
CRM_Utils_Recent::add($displayName,
CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$ufmatch->contact_id}"),
$ufmatch->contact_id,
$contactType,
$ufmatch->contact_id,
$displayName,
$otherRecent
);
}
}
/**
* Synchronize the object with the UF Match entry. Can be called stand-alone from
* the drupalUsers script
*
* @param Object $user
* The drupal user object.
* @param string $userKey
* The id of the user from the uf object.
* @param string $uniqId
* The OpenID of the user.
* @param string $uf
* The name of the user framework.
* @param int $status
* Returns the status if user created or already exits (used for CMS sync).
* @param string $ctype
* contact type
* @param bool $isLogin
*
* @return CRM_Core_DAO_UFMatch|bool
*/
public static function &synchronizeUFMatch(&$user, $userKey, $uniqId, $uf, $status = NULL, $ctype = NULL, $isLogin = FALSE) {
$config = CRM_Core_Config::singleton();
if (!CRM_Utils_Rule::email($uniqId)) {
$retVal = $status ? NULL : FALSE;
return $retVal;
}
$newContact = FALSE;
// make sure that a contact id exists for this user id
$ufmatch = new CRM_Core_DAO_UFMatch();
$ufmatch->domain_id = CRM_Core_Config::domainID();
$ufmatch->uf_id = $userKey;
if (!$ufmatch->find(TRUE)) {
$transaction = new CRM_Core_Transaction();
$dao = NULL;
if (!empty($_POST) && !$isLogin) {
$params = $_POST;
$params['email'] = $uniqId;
$ids = CRM_Contact_BAO_Contact::getDuplicateContacts($params, 'Individual', 'Unsupervised', array(), FALSE);
if (!empty($ids) && Civi::settings()->get('uniq_email_per_site')) {
// restrict dupeIds to ones that belong to current domain/site.
$siteContacts = CRM_Core_BAO_Domain::getContactList();
foreach ($ids as $index => $dupeId) {
if (!in_array($dupeId, $siteContacts)) {
unset($ids[$index]);
}
}
// re-index the array
$ids = array_values($ids);
}
if (!empty($ids)) {
$dao = new CRM_Core_DAO();
$dao->contact_id = $ids[0];
}
}
else {
$dao = CRM_Contact_BAO_Contact::matchContactOnEmail($uniqId, $ctype);
}
$found = FALSE;
if ($dao) {
// ensure there does not exists a contact_id / uf_id pair
// in the DB. This might be due to multiple emails per contact
// CRM-9091
$sql = "
SELECT id
FROM civicrm_uf_match
WHERE contact_id = %1
AND domain_id = %2
";
$params = array(
1 => array($dao->contact_id, 'Integer'),
2 => array(CRM_Core_Config::domainID(), 'Integer'),
);
$conflict = CRM_Core_DAO::singleValueQuery($sql, $params);
if (!$conflict) {
$found = TRUE;
$ufmatch->contact_id = $dao->contact_id;
$ufmatch->uf_name = $uniqId;
}
}
if (!$found) {
// Not sure why we're testing for this. Is there ever a case
// in which $user is not an object?
if (is_object($user)) {
if ($config->userSystem->is_drupal) {
$primary_email = $uniqId;
}
elseif ($uf == 'WordPress') {
$primary_email = $user->user_email;
}
else {
$primary_email = $user->email;
}
$params = array('email-Primary' => $primary_email);
}
if ($ctype == 'Organization') {
$params['organization_name'] = $uniqId;
}
elseif ($ctype == 'Household') {
$params['household_name'] = $uniqId;
}
if (!$ctype) {
$ctype = "Individual";
}
$params['contact_type'] = $ctype;
// extract first / middle / last name
// for joomla
if ($uf == 'Joomla' && $user->name) {
CRM_Utils_String::extractName($user->name, $params);
}
if ($uf == 'WordPress') {
if ($user->first_name) {
$params['first_name'] = $user->first_name;
}
if ($user->last_name) {
$params['last_name'] = $user->last_name;
}
}
$contactId = CRM_Contact_BAO_Contact::createProfileContact($params, CRM_Core_DAO::$_nullArray);
$ufmatch->contact_id = $contactId;
$ufmatch->uf_name = $uniqId;
}
// check that there are not two CMS IDs matching the same CiviCRM contact - this happens when a civicrm
// user has two e-mails and there is a cms match for each of them
// the gets rid of the nasty fata error but still reports the error
$sql = "
SELECT uf_id
FROM civicrm_uf_match
WHERE ( contact_id = %1
OR uf_name = %2
OR uf_id = %3 )
AND domain_id = %4
";
$params = array(
1 => array($ufmatch->contact_id, 'Integer'),
2 => array($ufmatch->uf_name, 'String'),
3 => array($ufmatch->uf_id, 'Integer'),
4 => array($ufmatch->domain_id, 'Integer'),
);
$conflict = CRM_Core_DAO::singleValueQuery($sql, $params);
if (!$conflict) {
$ufmatch = CRM_Core_BAO_UFMatch::create((array) $ufmatch);
$ufmatch->free();
$newContact = TRUE;
$transaction->commit();
}
else {
$msg = ts("Contact ID %1 is a match for %2 user %3 but has already been matched to %4",
array(
1 => $ufmatch->contact_id,
2 => $uf,
3 => $ufmatch->uf_id,
4 => $conflict,
)
);
unset($conflict);
}
}
if ($status) {
return $newContact;
}
else {
return $ufmatch;
}
}
/**
* Update the uf_name in the user object.
*
* @param int $contactId
* Id of the contact to update.
*/
public static function updateUFName($contactId) {
if (!Civi::settings()->get('syncCMSEmail') || !$contactId) {
return;
}
$config = CRM_Core_Config::singleton();
$ufName = CRM_Contact_BAO_Contact::getPrimaryEmail($contactId);
if (!$ufName) {
return;
}
$update = FALSE;
// 1.do check for contact Id.
$ufmatch = new CRM_Core_DAO_UFMatch();
$ufmatch->contact_id = $contactId;
$ufmatch->domain_id = CRM_Core_Config::domainID();
if (!$ufmatch->find(TRUE)) {
return;
}
if ($ufmatch->uf_name != $ufName) {
$update = TRUE;
}
// CRM-6928
// 2.do check for duplicate ufName.
$ufDupeName = new CRM_Core_DAO_UFMatch();
$ufDupeName->uf_name = $ufName;
$ufDupeName->domain_id = CRM_Core_Config::domainID();
if ($ufDupeName->find(TRUE) &&
$ufDupeName->contact_id != $contactId
) {
$update = FALSE;
}
if (!$update) {
return;
}
// save the updated ufmatch object
$ufmatch->uf_name = $ufName;
$ufmatch->save();
$config->userSystem->updateCMSName($ufmatch->uf_id, $ufName);
}
/**
* Update the email value for the contact and user profile.
*
* @param int $contactId
* Contact ID of the user.
* @param string $emailAddress
* Email to be modified for the user.
*/
public static function updateContactEmail($contactId, $emailAddress) {
$strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
$emailAddress = $strtolower($emailAddress);
$ufmatch = new CRM_Core_DAO_UFMatch();
$ufmatch->contact_id = $contactId;
$ufmatch->domain_id = CRM_Core_Config::domainID();
if ($ufmatch->find(TRUE)) {
// Save the email in UF Match table
$ufmatch->uf_name = $emailAddress;
CRM_Core_BAO_UFMatch::create((array) $ufmatch);
// If CMS integration is disabled skip Civi email update if CMS user email is changed
if (Civi::settings()->get('syncCMSEmail') == FALSE) {
return;
}
//check if the primary email for the contact exists
//$contactDetails[1] - email
//$contactDetails[3] - email id
$contactDetails = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactId);
if (trim($contactDetails[1])) {
$emailID = $contactDetails[3];
//update if record is found
$query = "UPDATE civicrm_email
SET email = %1
WHERE id = %2";
$p = array(
1 => array($emailAddress, 'String'),
2 => array($emailID, 'Integer'),
);
$dao = CRM_Core_DAO::executeQuery($query, $p);
}
else {
//else insert a new email record
$email = new CRM_Core_DAO_Email();
$email->contact_id = $contactId;
$email->is_primary = 1;
$email->email = $emailAddress;
$email->save();
$emailID = $email->id;
}
CRM_Core_BAO_Log::register($contactId,
'civicrm_email',
$emailID
);
}
}
/**
* Delete the object records that are associated with this cms user.
*
* @param int $ufID
* Id of the user to delete.
*/
public static function deleteUser($ufID) {
$ufmatch = new CRM_Core_DAO_UFMatch();
$ufmatch->uf_id = $ufID;
$ufmatch->domain_id = CRM_Core_Config::domainID();
$ufmatch->delete();
}
/**
* Get the contact_id given a uf_id.
*
* @param int $ufID
* Id of UF for which related contact_id is required.
*
* @return int
* contact_id on success, null otherwise
*/
public static function getContactId($ufID) {
if (!isset($ufID)) {
return NULL;
}
$ufmatch = new CRM_Core_DAO_UFMatch();
$ufmatch->uf_id = $ufID;
$ufmatch->domain_id = CRM_Core_Config::domainID();
if ($ufmatch->find(TRUE)) {
return (int ) $ufmatch->contact_id;
}
return NULL;
}
/**
* Get the uf_id given a contact_id.
*
* @param int $contactID
* ID of the contact for which related uf_id is required.
*
* @return int
* uf_id of the given contact_id on success, null otherwise
*/
public static function getUFId($contactID) {
if (!isset($contactID)) {
return NULL;
}
$domain = CRM_Core_BAO_Domain::getDomain();
$ufmatch = new CRM_Core_DAO_UFMatch();
$ufmatch->contact_id = $contactID;
$ufmatch->domain_id = $domain->id;
if ($ufmatch->find(TRUE)) {
return $ufmatch->uf_id;
}
return NULL;
}
/**
* @return bool
*/
public static function isEmptyTable() {
$sql = "SELECT count(id) FROM civicrm_uf_match";
return CRM_Core_DAO::singleValueQuery($sql) > 0 ? FALSE : TRUE;
}
/**
* Get the list of contact_id.
*
*
* @return int
* contact_id on success, null otherwise
*/
public static function getContactIDs() {
$id = array();
$dao = new CRM_Core_DAO_UFMatch();
$dao->find();
while ($dao->fetch()) {
$id[] = $dao->contact_id;
}
return $id;
}
/**
* See if this user exists, and if so, if they're allowed to login
*
*
* @param int $openId
*
* @return bool
* true if allowed to login, false otherwise
*/
public static function getAllowedToLogin($openId) {
$ufmatch = new CRM_Core_DAO_UFMatch();
$ufmatch->uf_name = $openId;
$ufmatch->allowed_to_login = 1;
if ($ufmatch->find(TRUE)) {
return TRUE;
}
return FALSE;
}
/**
* Get the next unused uf_id value, since the standalone UF doesn't
* have id's (it uses OpenIDs, which go in a different field)
*
*
* @return int
* next highest unused value for uf_id
*/
public static function getNextUfIdValue() {
$query = "SELECT MAX(uf_id)+1 AS next_uf_id FROM civicrm_uf_match";
$dao = CRM_Core_DAO::executeQuery($query);
if ($dao->fetch()) {
$ufId = $dao->next_uf_id;
}
if (!isset($ufId)) {
$ufId = 1;
}
return $ufId;
}
/**
* @param $email
*
* @return bool
*/
public static function isDuplicateUser($email) {
$session = CRM_Core_Session::singleton();
$contactID = $session->get('userID');
if (!empty($email) && isset($contactID)) {
$dao = new CRM_Core_DAO_UFMatch();
$dao->uf_name = $email;
if ($dao->find(TRUE) && $contactID != $dao->contact_id) {
return TRUE;
}
}
return FALSE;
}
/**
* Get uf match values for given uf id or logged in user.
*
* @param int $ufID
* Uf id.
*
* @return array
* uf values.
*/
public static function getUFValues($ufID = NULL) {
if (!$ufID) {
//get logged in user uf id.
$ufID = CRM_Utils_System::getLoggedInUfID();
}
if (!$ufID) {
return array();
}
static $ufValues;
if ($ufID && !isset($ufValues[$ufID])) {
$ufmatch = new CRM_Core_DAO_UFMatch();
$ufmatch->uf_id = $ufID;
$ufmatch->domain_id = CRM_Core_Config::domainID();
if ($ufmatch->find(TRUE)) {
$ufValues[$ufID] = array(
'uf_id' => $ufmatch->uf_id,
'uf_name' => $ufmatch->uf_name,
'contact_id' => $ufmatch->contact_id,
'domain_id' => $ufmatch->domain_id,
);
}
}
return $ufValues[$ufID];
}
/**
* @inheritDoc
*/
public function addSelectWhereClause() {
// Prevent default behavior of joining ACLs onto the contact_id field
$clauses = array();
CRM_Utils_Hook::selectWhereClause($this, $clauses);
return $clauses;
}
}

View file

@ -0,0 +1,178 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class contain function for Website handling.
*/
class CRM_Core_BAO_Website extends CRM_Core_DAO_Website {
/**
* Takes an associative array and adds im.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
*
* @return object
* CRM_Core_BAO_Website object on success, null otherwise
*/
public static function add(&$params) {
$hook = empty($params['id']) ? 'create' : 'edit';
CRM_Utils_Hook::pre($hook, 'Website', CRM_Utils_Array::value('id', $params), $params);
$website = new CRM_Core_DAO_Website();
$website->copyValues($params);
$website->save();
CRM_Utils_Hook::post($hook, 'Website', $website->id, $website);
return $website;
}
/**
* Process website.
*
* @param array $params
* @param int $contactID
* Contact id.
*
* @param bool $skipDelete
*
* @return bool
*/
public static function create(&$params, $contactID, $skipDelete) {
if (empty($params)) {
return FALSE;
}
$ids = self::allWebsites($contactID);
foreach ($params as $key => $values) {
if (empty($values['id']) && is_array($ids) && !empty($ids)) {
foreach ($ids as $id => $value) {
if (($value['website_type_id'] == $values['website_type_id'])) {
$values['id'] = $id;
}
}
}
if (!empty($values['url'])) {
$values['contact_id'] = $contactID;
self::add($values);
}
elseif ($skipDelete && !empty($values['id'])) {
self::del(array($values['id']));
}
}
}
/**
* Delete website.
*
* @param array $ids
* Website ids.
*
* @return bool
*/
public static function del($ids) {
$query = 'DELETE FROM civicrm_website WHERE id IN ( ' . implode(',', $ids) . ')';
CRM_Core_DAO::executeQuery($query);
// FIXME: we should return false if the del was unsuccessful
return TRUE;
}
/**
* Given the list of params in the params array, fetch the object
* and store the values in the values array
*
* @param array $params
* @param $values
*
* @return bool
*/
public static function &getValues(&$params, &$values) {
$websites = array();
$website = new CRM_Core_DAO_Website();
$website->contact_id = $params['contact_id'];
$website->find();
$count = 1;
while ($website->fetch()) {
$values['website'][$count] = array();
CRM_Core_DAO::storeValues($website, $values['website'][$count]);
$websites[$count] = $values['website'][$count];
$count++;
}
return $websites;
}
/**
* Get all the websites for a specified contact_id.
*
* @param int $id
* The contact id.
*
* @param bool $updateBlankLocInfo
*
* @return array
* the array of website details
*/
public static function allWebsites($id, $updateBlankLocInfo = FALSE) {
if (!$id) {
return NULL;
}
$query = '
SELECT id, website_type_id
FROM civicrm_website
WHERE civicrm_website.contact_id = %1';
$params = array(1 => array($id, 'Integer'));
$websites = $values = array();
$dao = CRM_Core_DAO::executeQuery($query, $params);
$count = 1;
while ($dao->fetch()) {
$values = array(
'id' => $dao->id,
'website_type_id' => $dao->website_type_id,
);
if ($updateBlankLocInfo) {
$websites[$count++] = $values;
}
else {
$websites[$dao->id] = $values;
}
}
return $websites;
}
}

View file

@ -0,0 +1,354 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* Class CRM_Core_BAO_WordReplacement.
*/
class CRM_Core_BAO_WordReplacement extends CRM_Core_DAO_WordReplacement {
/**
* Class constructor.
*/
public function __construct() {
parent::__construct();
}
/**
* Function that must have never worked & should be removed.
*
* Retrieve DB object based on input parameters.
*
* It also stores all the retrieved values in the default array.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $defaults
* (reference ) an assoc array to hold the flattened values.
*
* @return CRM_Core_DAO_WordReplacement
*/
public static function retrieve(&$params, &$defaults) {
return CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_WordRepalcement', $params, $defaults);
}
/**
* Get the domain BAO.
*
* @param null $reset
*
* @return null|CRM_Core_BAO_WordReplacement
*/
public static function getWordReplacement($reset = NULL) {
static $wordReplacement = NULL;
if (!$wordReplacement || $reset) {
$wordReplacement = new CRM_Core_BAO_WordReplacement();
$wordReplacement->id = CRM_Core_Config::wordReplacementID();
if (!$wordReplacement->find(TRUE)) {
CRM_Core_Error::fatal();
}
}
return $wordReplacement;
}
/**
* Save the values of a WordReplacement.
*
* @param array $params
* @param int $id
*
* @return array
*/
public static function edit(&$params, &$id) {
$wordReplacement = new CRM_Core_DAO_WordReplacement();
$wordReplacement->id = $id;
$wordReplacement->copyValues($params);
$wordReplacement->save();
if (!isset($params['options']) || CRM_Utils_Array::value('wp-rebuild', $params['options'], TRUE)) {
self::rebuild();
}
return $wordReplacement;
}
/**
* Create a new WordReplacement.
*
* @param array $params
*
* @return array
*/
public static function create($params) {
if (array_key_exists("domain_id", $params) === FALSE) {
$params["domain_id"] = CRM_Core_Config::domainID();
}
$wordReplacement = new CRM_Core_DAO_WordReplacement();
$wordReplacement->copyValues($params);
$wordReplacement->save();
if (!isset($params['options']) || CRM_Utils_Array::value('wp-rebuild', $params['options'], TRUE)) {
self::rebuild();
}
return $wordReplacement;
}
/**
* Delete website.
*
* @param int $id
* WordReplacement id.
*
* @return object
*/
public static function del($id) {
$dao = new CRM_Core_DAO_WordReplacement();
$dao->id = $id;
$dao->delete();
if (!isset($params['options']) || CRM_Utils_Array::value('wp-rebuild', $params['options'], TRUE)) {
self::rebuild();
}
return $dao;
}
/**
* Get all word-replacements in the form of an array.
*
* @param int $id
* Domain ID.
*
* @return array
* @see civicrm_domain.locale_custom_strings
*/
public static function getAllAsConfigArray($id) {
$query = "
SELECT find_word,replace_word,is_active,match_type
FROM civicrm_word_replacement
WHERE domain_id = %1
";
$params = array(1 => array($id, 'Integer'));
$dao = CRM_Core_DAO::executeQuery($query, $params);
$overrides = array();
while ($dao->fetch()) {
if ($dao->is_active == 1) {
$overrides['enabled'][$dao->match_type][$dao->find_word] = $dao->replace_word;
}
else {
$overrides['disabled'][$dao->match_type][$dao->find_word] = $dao->replace_word;
}
}
$config = CRM_Core_Config::singleton();
$domain = new CRM_Core_DAO_Domain();
$domain->find(TRUE);
// So. Weird. Some bizarre/probably-broken multi-lingual thing where
// data isn't really stored in civicrm_word_replacements. Probably
// shouldn't exist.
$stringOverride = self::_getLocaleCustomStrings($id);
$stringOverride[$config->lcMessages] = $overrides;
return $stringOverride;
}
/**
* Rebuild.
*
* @param bool $clearCaches
*
* @return bool
*/
public static function rebuild($clearCaches = TRUE) {
$id = CRM_Core_Config::domainID();
self::_setLocaleCustomStrings($id, self::getAllAsConfigArray($id));
// Partially mitigate the inefficiency introduced in CRM-13187 by doing this conditionally
if ($clearCaches) {
// Reset navigation
CRM_Core_BAO_Navigation::resetNavigation();
// Clear js localization
CRM_Core_Resources::singleton()->flushStrings()->resetCacheCode();
}
return TRUE;
}
/**
* Get word replacements for the api.
*
* Get all the word-replacements stored in config-arrays for the
* configured language, and convert them to params for the
* WordReplacement.create API.
*
* Note: This function is duplicated in CRM_Core_BAO_WordReplacement and
* CRM_Upgrade_Incremental_php_FourFour to ensure that the incremental upgrade
* step behaves consistently even as the BAO evolves in future versions.
* However, if there's a bug in here prior to 4.4.0, we should apply the
* bug-fix in both places.
*
* @param bool $rebuildEach
* Whether to perform rebuild after each individual API call.
*
* @return array
* Each item is $params for WordReplacement.create
* @see CRM_Core_BAO_WordReplacement::convertConfigArraysToAPIParams
*/
public static function getConfigArraysAsAPIParams($rebuildEach) {
$settingsResult = civicrm_api3('Setting', 'get', array(
'return' => 'lcMessages',
));
$returnValues = CRM_Utils_Array::first($settingsResult['values']);
$lang = $returnValues['lcMessages'];
$wordReplacementCreateParams = array();
// get all domains
$result = civicrm_api3('domain', 'get', array(
'return' => array('locale_custom_strings'),
));
if (!empty($result["values"])) {
foreach ($result["values"] as $value) {
$params = array();
$params["domain_id"] = $value["id"];
$params["options"] = array('wp-rebuild' => $rebuildEach);
// Unserialize word match string.
$localeCustomArray = unserialize($value["locale_custom_strings"]);
if (!empty($localeCustomArray)) {
$wordMatchArray = array();
// Only return the replacement strings of the current language,
// otherwise some replacements will be duplicated, which will
// lead to undesired results, like CRM-19683.
$localCustomData = $localeCustomArray[$lang];
// Traverse status array "enabled" "disabled"
foreach ($localCustomData as $status => $matchTypes) {
$params["is_active"] = ($status == "enabled") ? TRUE : FALSE;
// Traverse Match Type array "wildcardMatch" "exactMatch"
foreach ($matchTypes as $matchType => $words) {
$params["match_type"] = $matchType;
foreach ($words as $word => $replace) {
$params["find_word"] = $word;
$params["replace_word"] = $replace;
$wordReplacementCreateParams[] = $params;
}
}
}
}
}
}
return $wordReplacementCreateParams;
}
/**
* Rebuild word replacements.
*
* Get all the word-replacements stored in config-arrays
* and write them out as records in civicrm_word_replacement.
*
* Note: This function is duplicated in CRM_Core_BAO_WordReplacement and
* CRM_Upgrade_Incremental_php_FourFour to ensure that the incremental upgrade
* step behaves consistently even as the BAO evolves in future versions.
* However, if there's a bug in here prior to 4.4.0, we should apply the
* bug-fix in both places.
*/
public static function rebuildWordReplacementTable() {
civicrm_api3('word_replacement', 'replace', array(
'options' => array('match' => array('domain_id', 'find_word')),
'values' => self::getConfigArraysAsAPIParams(FALSE),
));
CRM_Core_BAO_WordReplacement::rebuild();
}
/**
* Get WordReplacements for a locale.
*
* @param string $locale
* @param int $domainId
*
* @return array
* List of word replacements (enabled/disabled) for the given locale.
*/
public static function getLocaleCustomStrings($locale, $domainId = NULL) {
if ($domainId === NULL) {
$domainId = CRM_Core_Config::domainID();
}
return CRM_Utils_Array::value($locale, self::_getLocaleCustomStrings($domainId));
}
/**
* Get custom locale strings.
*
* @param int $domainId
*
* @return array|mixed
*/
private static function _getLocaleCustomStrings($domainId) {
// TODO: Would it be worthwhile using memcache here?
$domain = CRM_Core_DAO::executeQuery('SELECT locale_custom_strings FROM civicrm_domain WHERE id = %1', array(
1 => array($domainId, 'Integer'),
));
while ($domain->fetch()) {
return empty($domain->locale_custom_strings) ? array() : unserialize($domain->locale_custom_strings);
}
}
/**
* Set locale strings.
*
* @param string $locale
* @param array $values
* @param int $domainId
*/
public static function setLocaleCustomStrings($locale, $values, $domainId = NULL) {
if ($domainId === NULL) {
$domainId = CRM_Core_Config::domainID();
}
$lcs = self::_getLocaleCustomStrings($domainId);
$lcs[$locale] = $values;
self::_setLocaleCustomStrings($domainId, $lcs);
}
/**
* Set locale strings.
*
* @param int $domainId
* @param string $lcs
*/
private static function _setLocaleCustomStrings($domainId, $lcs) {
CRM_Core_DAO::executeQuery("UPDATE civicrm_domain SET locale_custom_strings = %1 WHERE id = %2", array(
1 => array(serialize($lcs), 'String'),
2 => array($domainId, 'Integer'),
));
}
}

View file

@ -0,0 +1,52 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* The Base class of the CRM hierarchy. Currently does not provide
* any useful functionality. As such we dont require anyone to derive
* from this class. However it includes a few common files
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
require_once 'CRM/Core/I18n.php';
/**
* Class CRM_Core_Base
*/
class CRM_Core_Base {
/**
* Constructor.
*/
public function __construct() {
}
}

View file

@ -0,0 +1,660 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* Defines a simple implementation of a drupal block.
*
* Blocks definitions and html are in a smarty template file.
*/
class CRM_Core_Block {
/**
* The following blocks are supported.
*
* @var int
*/
const
CREATE_NEW = 1,
RECENTLY_VIEWED = 2,
DASHBOARD = 3,
ADD = 4,
LANGSWITCH = 5,
EVENT = 6,
FULLTEXT_SEARCH = 7;
/**
* Template file names for the above blocks.
*/
static $_properties = NULL;
/**
* Class constructor.
*/
public function __construct() {
}
/**
* Initialises the $_properties array
*/
public static function initProperties() {
if (!defined('BLOCK_CACHE_GLOBAL')) {
define('BLOCK_CACHE_GLOBAL', 0x0008);
}
if (!defined('BLOCK_CACHE_PER_PAGE')) {
define('BLOCK_CACHE_PER_PAGE', 0x0004);
}
if (!defined('BLOCK_NO_CACHE')) {
define('BLOCK_NO_CACHE', -1);
}
if (!(self::$_properties)) {
$config = CRM_Core_Config::singleton();
self::$_properties = array(
// set status item to 0 to disable block by default (at install)
self::CREATE_NEW => array(
'template' => 'CreateNew.tpl',
'info' => ts('CiviCRM Create New Record'),
'subject' => '',
'active' => TRUE,
'cache' => BLOCK_CACHE_GLOBAL,
'visibility' => 1,
'weight' => -100,
'status' => 1,
'pages' => "civicrm\ncivicrm/*",
'region' => $config->userSystem->getDefaultBlockLocation(),
),
self::RECENTLY_VIEWED => array(
'template' => 'RecentlyViewed.tpl',
'info' => ts('CiviCRM Recent Items'),
'subject' => ts('Recent Items'),
'active' => TRUE,
'cache' => BLOCK_NO_CACHE,
'visibility' => 1,
'weight' => -99,
'status' => 1,
'pages' => "civicrm\ncivicrm/*",
'region' => $config->userSystem->getDefaultBlockLocation(),
),
self::DASHBOARD => array(
'template' => 'Dashboard.tpl',
'info' => ts('CiviCRM Contact Dashboard'),
'subject' => '',
'active' => TRUE,
'cache' => BLOCK_NO_CACHE,
'visibility' => 1,
'weight' => -98,
'status' => 1,
'pages' => "civicrm\ncivicrm/*",
'region' => $config->userSystem->getDefaultBlockLocation(),
),
self::ADD => array(
'template' => 'Add.tpl',
'info' => ts('CiviCRM Quick Add'),
'subject' => ts('New Individual'),
'active' => TRUE,
'cache' => BLOCK_NO_CACHE,
'visibility' => 1,
'weight' => -97,
'status' => 1,
'pages' => "civicrm\ncivicrm/*",
'region' => $config->userSystem->getDefaultBlockLocation(),
),
self::LANGSWITCH => array(
'template' => 'LangSwitch.tpl',
'info' => ts('CiviCRM Language Switcher'),
'subject' => '',
'templateValues' => array(),
'active' => TRUE,
'cache' => BLOCK_NO_CACHE,
'visibility' => 1,
'weight' => -96,
'status' => 1,
'pages' => "civicrm\ncivicrm/*",
'region' => $config->userSystem->getDefaultBlockLocation(),
),
self::EVENT => array(
'template' => 'Event.tpl',
'info' => ts('CiviCRM Upcoming Events'),
'subject' => ts('Upcoming Events'),
'templateValues' => array(),
'active' => TRUE,
'cache' => BLOCK_NO_CACHE,
'visibility' => 1,
'weight' => -95,
'status' => 0,
'pages' => "civicrm\ncivicrm/*",
'region' => $config->userSystem->getDefaultBlockLocation(),
),
self::FULLTEXT_SEARCH => array(
'template' => 'FullTextSearch.tpl',
'info' => ts('CiviCRM Full-text Search'),
'subject' => ts('Full-text Search'),
'active' => TRUE,
'cache' => BLOCK_NO_CACHE,
'visibility' => 1,
'weight' => -94,
'status' => 0,
'pages' => "civicrm\ncivicrm/*",
'region' => $config->userSystem->getDefaultBlockLocation(),
),
);
ksort(self::$_properties);
}
}
/**
* Returns the desired property from the $_properties array
*
* @param int $id
* One of the class constants (ADD, SEARCH, etc.).
* @param string $property
* The desired property.
*
* @return string
* the value of the desired property
*/
public static function getProperty($id, $property) {
if (!(self::$_properties)) {
self::initProperties();
}
return isset(self::$_properties[$id][$property]) ? self::$_properties[$id][$property] : NULL;
}
/**
* Sets the desired property in the $_properties array
*
* @param int $id
* One of the class constants (ADD, SEARCH, etc.).
* @param string $property
* The desired property.
* @param string $value
* The value of the desired property.
*/
public static function setProperty($id, $property, $value) {
if (!(self::$_properties)) {
self::initProperties();
}
self::$_properties[$id][$property] = $value;
}
/**
* Returns the whole $_properties array.
*
* @return array
* the $_properties array
*/
public static function properties() {
if (!(self::$_properties)) {
self::initProperties();
}
return self::$_properties;
}
/**
* Creates the info block for drupal.
*
* @return array
*/
public static function getInfo() {
$block = array();
foreach (self::properties() as $id => $value) {
if ($value['active']) {
if (in_array($id, array(
self::ADD,
self::CREATE_NEW,
))) {
$hasAccess = TRUE;
if (!CRM_Core_Permission::check('add contacts') &&
!CRM_Core_Permission::check('edit groups')
) {
$hasAccess = FALSE;
}
//validate across edit/view - CRM-5666
if ($hasAccess && ($id == self::ADD)) {
$hasAccess = CRM_Core_Permission::giveMeAllACLs();
}
if (!$hasAccess) {
continue;
}
}
if ($id == self::EVENT &&
(!CRM_Core_Permission::access('CiviEvent', FALSE) ||
!CRM_Core_Permission::check('view event info')
)
) {
continue;
}
$block[$id] = array(
'info' => $value['info'],
'cache' => $value['cache'],
'region' => $value['region'],
'visibility' => $value['visibility'],
'pages' => $value['pages'],
'status' => $value['status'],
'weight' => $value['weight'],
);
}
}
return $block;
}
/**
* Set the post action values for the block.
*
* php is lame and u cannot call functions from static initializers
* hence this hack
*
* @param int $id
*/
private static function setTemplateValues($id) {
switch ($id) {
case self::CREATE_NEW:
self::setTemplateShortcutValues();
break;
case self::DASHBOARD:
self::setTemplateDashboardValues();
break;
case self::ADD:
$defaultLocation = CRM_Core_BAO_LocationType::getDefault();
$defaultPrimaryLocationId = $defaultLocation->id;
$values = array(
'postURL' => CRM_Utils_System::url('civicrm/contact/add', 'reset=1&ct=Individual'),
'primaryLocationType' => $defaultPrimaryLocationId,
);
foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
$values[$greeting . '_id'] = CRM_Contact_BAO_Contact_Utils::defaultGreeting('Individual', $greeting);
}
self::setProperty(self::ADD,
'templateValues',
$values
);
break;
case self::LANGSWITCH:
// gives the currentPath without trailing empty lcMessages to be completed
$values = array('queryString' => CRM_Utils_System::getLinksUrl('lcMessages', TRUE, FALSE, FALSE));
self::setProperty(self::LANGSWITCH, 'templateValues', $values);
break;
case self::FULLTEXT_SEARCH:
$urlArray = array(
'fullTextSearchID' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue',
'CRM_Contact_Form_Search_Custom_FullText', 'value', 'name'
),
);
self::setProperty(self::FULLTEXT_SEARCH, 'templateValues', $urlArray);
break;
case self::RECENTLY_VIEWED:
$recent = CRM_Utils_Recent::get();
self::setProperty(self::RECENTLY_VIEWED, 'templateValues', array('recentlyViewed' => $recent));
break;
case self::EVENT:
self::setTemplateEventValues();
break;
}
}
/**
* Create the list of options to create New objects for the application and format is as a block.
*/
private static function setTemplateShortcutValues() {
$config = CRM_Core_Config::singleton();
static $shortCuts = array();
if (!($shortCuts)) {
if (CRM_Core_Permission::check('add contacts')) {
if (CRM_Core_Permission::giveMeAllACLs()) {
$shortCuts = CRM_Contact_BAO_ContactType::getCreateNewList();
}
}
// new activity (select target contact)
$shortCuts = array_merge($shortCuts, array(
array(
'path' => 'civicrm/activity',
'query' => 'action=add&reset=1&context=standalone',
'ref' => 'new-activity',
'title' => ts('Activity'),
),
));
$components = CRM_Core_Component::getEnabledComponents();
if (!empty($config->enableComponents)) {
// check if we can process credit card contribs
$newCredit = CRM_Core_Config::isEnabledBackOfficeCreditCardPayments();
foreach ($components as $componentName => $obj) {
if (in_array($componentName, $config->enableComponents)) {
$obj->creatNewShortcut($shortCuts, $newCredit);
}
}
}
// new email (select recipients)
$shortCuts = array_merge($shortCuts, array(
array(
'path' => 'civicrm/activity/email/add',
'query' => 'atype=3&action=add&reset=1&context=standalone',
'ref' => 'new-email',
'title' => ts('Email'),
),
));
if (CRM_Core_Permission::check('edit groups')) {
$shortCuts = array_merge($shortCuts, array(
array(
'path' => 'civicrm/group/add',
'query' => 'reset=1',
'ref' => 'new-group',
'title' => ts('Group'),
),
));
}
if (CRM_Core_Permission::check('manage tags')) {
$shortCuts = array_merge($shortCuts, array(
array(
'path' => 'civicrm/tag',
'query' => 'reset=1&action=add',
'ref' => 'new-tag',
'title' => ts('Tag'),
),
));
}
if (empty($shortCuts)) {
return NULL;
}
}
$values = array();
foreach ($shortCuts as $key => $short) {
$values[$key] = self::setShortCutValues($short);
}
// call links hook to add user defined links
CRM_Utils_Hook::links('create.new.shorcuts',
NULL,
CRM_Core_DAO::$_nullObject,
$values
);
foreach ($values as $key => $val) {
if (!empty($val['title'])) {
$values[$key]['name'] = CRM_Utils_Array::value('name', $val, $val['title']);
}
}
self::setProperty(self::CREATE_NEW, 'templateValues', array('shortCuts' => $values));
}
/**
* @param $short
*
* @return array
*/
private static function setShortcutValues($short) {
$value = array();
if (isset($short['url'])) {
$value['url'] = $short['url'];
}
elseif (isset($short['path'])) {
$value['url'] = CRM_Utils_System::url($short['path'], $short['query'], FALSE);
}
$value['title'] = $short['title'];
$value['ref'] = isset($short['ref']) ? $short['ref'] : '';
if (!empty($short['shortCuts'])) {
foreach ($short['shortCuts'] as $shortCut) {
$value['shortCuts'][] = self::setShortcutValues($shortCut);
}
}
return $value;
}
/**
* Create the list of dashboard links.
*/
private static function setTemplateDashboardValues() {
static $dashboardLinks = array();
if (CRM_Core_Permission::check('access Contact Dashboard')) {
$dashboardLinks = array(
array(
'path' => 'civicrm/user',
'query' => 'reset=1',
'title' => ts('My Contact Dashboard'),
),
);
}
if (empty($dashboardLinks)) {
return NULL;
}
$values = array();
foreach ($dashboardLinks as $dash) {
$value = array();
if (isset($dash['url'])) {
$value['url'] = $dash['url'];
}
else {
$value['url'] = CRM_Utils_System::url($dash['path'], $dash['query'], FALSE);
}
$value['title'] = $dash['title'];
$value['key'] = CRM_Utils_Array::value('key', $dash);
$values[] = $value;
}
self::setProperty(self::DASHBOARD, 'templateValues', array('dashboardLinks' => $values));
}
/**
* Create the list of mail urls for the application and format is as a block.
*/
private static function setTemplateMailValues() {
static $shortCuts = NULL;
if (!($shortCuts)) {
$shortCuts = array(
array(
'path' => 'civicrm/mailing/send',
'query' => 'reset=1',
'title' => ts('Send Mailing'),
),
array(
'path' => 'civicrm/mailing/browse',
'query' => 'reset=1',
'title' => ts('Browse Sent Mailings'),
),
);
}
$values = array();
foreach ($shortCuts as $short) {
$value = array();
$value['url'] = CRM_Utils_System::url($short['path'], $short['query']);
$value['title'] = $short['title'];
$values[] = $value;
}
self::setProperty(self::MAIL, 'templateValues', array('shortCuts' => $values));
}
/**
* Create the list of shortcuts for the application and format is as a block.
*/
private static function setTemplateMenuValues() {
$config = CRM_Core_Config::singleton();
$path = 'navigation';
$values = CRM_Core_Menu::getNavigation();
if ($values) {
self::setProperty(self::MENU, 'templateValues', array('menu' => $values));
}
}
/**
* Create the event blocks for upcoming events.
*/
private static function setTemplateEventValues() {
$config = CRM_Core_Config::singleton();
$info = CRM_Event_BAO_Event::getCompleteInfo(date("Ymd"));
if ($info) {
$session = CRM_Core_Session::singleton();
// check if registration link should be displayed
foreach ($info as $id => $event) {
//@todo FIXME - validRegistraionRequest takes eventID not contactID as a param
// this is called via an obscure patch from Joomla event block rendering (only)
$info[$id]['onlineRegistration'] = CRM_Event_BAO_Event::validRegistrationRequest($event,
$session->get('userID')
);
}
self::setProperty(self::EVENT, 'templateValues', array('eventBlock' => $info));
}
}
/**
* Given an id creates a subject/content array
*
* @param int $id
* Id of the block.
*
* @return array
*/
public static function getContent($id) {
// return if upgrade mode
$config = CRM_Core_Config::singleton();
if ($config->isUpgradeMode()) {
return NULL;
}
if (!self::getProperty($id, 'active')) {
return NULL;
}
if ($id == self::EVENT &&
CRM_Core_Permission::check('view event info')
) {
// is CiviEvent enabled?
if (!CRM_Core_Permission::access('CiviEvent', FALSE)) {
return NULL;
}
// do nothing
}
// require 'access CiviCRM' permissons, except for the language switch block
elseif (!CRM_Core_Permission::check('access CiviCRM') && $id != self::LANGSWITCH) {
return NULL;
}
elseif ($id == self::ADD) {
$hasAccess = TRUE;
if (!CRM_Core_Permission::check('add contacts') &&
!CRM_Core_Permission::check('edit groups')
) {
$hasAccess = FALSE;
}
//validate across edit/view - CRM-5666
if ($hasAccess) {
$hasAccess = CRM_Core_Permission::giveMeAllACLs();
}
if (!$hasAccess) {
return NULL;
}
}
self::setTemplateValues($id);
// Suppress Recent Items block if it's empty - CRM-5188
if ($id == self::RECENTLY_VIEWED) {
$recent = self::getProperty($id, 'templateValues');
if (CRM_Utils_Array::crmIsEmptyArray($recent)) {
return NULL;
}
}
// Suppress Language switcher if language is inherited from CMS - CRM-9971
$config = CRM_Core_Config::singleton();
if ($id == self::LANGSWITCH && $config->inheritLocale) {
return NULL;
}
$block = array();
$block['name'] = 'block-civicrm';
$block['id'] = $block['name'] . '_' . $id;
$block['subject'] = self::fetch($id, 'Subject.tpl',
array('subject' => self::getProperty($id, 'subject'))
);
$block['content'] = self::fetch($id, self::getProperty($id, 'template'),
self::getProperty($id, 'templateValues')
);
return $block;
}
/**
* Given an id and a template, fetch the contents
*
* @param int $id
* Id of the block.
* @param string $fileName
* Name of the template file.
* @param array $properties
* Template variables.
*
* @return array
*/
public static function fetch($id, $fileName, $properties) {
$template = CRM_Core_Smarty::singleton();
if ($properties) {
$template->assign($properties);
}
return $template->fetch('CRM/Block/' . $fileName);
}
}

View file

@ -0,0 +1,237 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
class CRM_Core_ClassLoader {
/**
* We only need one instance of this object. So we use the singleton
* pattern and cache the instance in this variable
* @var object
*/
private static $_singleton = NULL;
/**
* The classes in CiviTest have ucky, non-standard naming.
*
* @var array
* Array(string $className => string $filePath).
*/
private $civiTestClasses;
/**
* @param bool $force
*
* @return object
*/
public static function &singleton($force = FALSE) {
if ($force || self::$_singleton === NULL) {
self::$_singleton = new CRM_Core_ClassLoader();
}
return self::$_singleton;
}
/**
* @var bool TRUE if previously registered
*/
protected $_registered;
/**
*/
protected function __construct() {
$this->_registered = FALSE;
$this->civiTestClasses = array(
'CiviCaseTestCase',
'CiviDBAssert',
'CiviMailUtils',
'CiviReportTestCase',
'CiviSeleniumTestCase',
'CiviTestSuite',
'CiviUnitTestCase',
'CiviEndToEndTestCase',
'Contact',
'ContributionPage',
'Custom',
'Event',
'Membership',
'Participant',
'PaypalPro',
);
}
/**
* Requires the autoload.php generated by composer
*
* @return void
*/
protected function requireComposerAutoload() {
// We are trying to locate 'vendor/autoload.php'. When installing CiviCRM
// manually from the built tarball, that will be two directories up in the
// civicrm-core directory. However, if civicrm-core was installed via
// composer as a library, that'll be 5 directories up where composer was
// run (ex. the Drupal root on a Drupal 8 site).
$civicrm_base_path = dirname(dirname(__DIR__));
$top_path = dirname(dirname(dirname(dirname(dirname(__DIR__)))));
if (file_exists($civicrm_base_path . '/vendor/autoload.php')) {
require_once $civicrm_base_path . '/vendor/autoload.php';
}
elseif (file_exists($top_path . '/vendor/autoload.php')) {
require_once $top_path . '/vendor/autoload.php';
}
}
/**
* Registers this instance as an autoloader.
*
* @param bool $prepend
* Whether to prepend the autoloader or not.
*
* @api
*/
public function register($prepend = FALSE) {
if ($this->_registered) {
return;
}
$civicrm_base_path = dirname(dirname(__DIR__));
$this->requireComposerAutoload();
// we do this to prevent a autoloader errors with joomla / 3rd party packages
// use absolute path since we dont know the content of include_path as yet
// CRM-11304
// TODO Remove this autoloader. For civicrm-core and civicrm-packages, the composer autoloader works fine.
// Extensions rely on include_path-based autoloading
spl_autoload_register(array($this, 'loadClass'), TRUE, $prepend);
$this->initHtmlPurifier($prepend);
$this->_registered = TRUE;
$packages_path = implode(DIRECTORY_SEPARATOR, array($civicrm_base_path, 'packages'));
$include_paths = array(
'.',
$civicrm_base_path,
$packages_path,
);
$include_paths = implode(PATH_SEPARATOR, $include_paths);
set_include_path($include_paths . PATH_SEPARATOR . get_include_path());
// @todo Why do we need to load this again?
$this->requireComposerAutoload();
}
/**
* Initialize HTML purifier class.
*
* @param string $prepend
*/
public function initHtmlPurifier($prepend) {
if (class_exists('HTMLPurifier_Bootstrap')) {
// HTMLPurifier is already initialized, e.g. by the Drupal module.
return;
}
$htmlPurifierPath = $this->getHtmlPurifierPath();
if (FALSE === $htmlPurifierPath) {
// No HTMLPurifier available, e.g. during installation.
return;
}
require_once $htmlPurifierPath;
spl_autoload_register(array('HTMLPurifier_Bootstrap', 'autoload'), TRUE, $prepend);
}
/**
* @return string|false
* Path to the file where the class HTMLPurifier_Bootstrap is defined, or
* FALSE, if such a file does not exist.
*/
private function getHtmlPurifierPath() {
if (function_exists('libraries_get_path')
&& ($path = libraries_get_path('htmlpurifier'))
&& file_exists($file = $path . '/library/HTMLPurifier/Bootstrap.php')
) {
// We are in Drupal 7, and the HTMLPurifier module is installed.
// Use Drupal's HTMLPurifier path, to avoid conflicts.
// @todo Verify that we are really in Drupal 7, and not in some other
// environment that happens to provide a 'libraries_get_path()' function.
return $file;
}
// we do this to prevent a autoloader errors with joomla / 3rd party packages
// Use absolute path, since we don't know the content of include_path yet.
// CRM-11304
$file = dirname(__FILE__) . '/../../packages/IDS/vendors/htmlpurifier/HTMLPurifier/Bootstrap.php';
if (file_exists($file)) {
return $file;
}
return FALSE;
}
/**
* @param $class
*/
public function loadClass($class) {
if (
// Only load classes that clearly belong to CiviCRM.
// Note: api/v3 does not use classes, but api_v3's test-suite does
(0 === strncmp($class, 'CRM_', 4) || 0 === strncmp($class, 'api_v3_', 7) || 0 === strncmp($class, 'WebTest_', 8) || 0 === strncmp($class, 'E2E_', 4)) &&
// Do not load PHP 5.3 namespaced classes.
// (in a future version, maybe)
FALSE === strpos($class, '\\')
) {
$file = strtr($class, '_', '/') . '.php';
// There is some question about the best way to do this.
// "require_once" is nice because it's simple and throws
// intelligible errors.
if (FALSE != stream_resolve_include_path($file)) {
require_once $file;
}
}
elseif (in_array($class, $this->civiTestClasses)) {
$file = "tests/phpunit/CiviTest/{$class}.php";
if (FALSE != stream_resolve_include_path($file)) {
require_once $file;
}
}
elseif ($class === 'CiviSeleniumSettings') {
if (!empty($GLOBALS['_CV'])) {
require_once 'tests/phpunit/CiviTest/CiviSeleniumSettings.auto.php';
}
elseif (CRM_Utils_File::isIncludable('tests/phpunit/CiviTest/CiviSeleniumSettings.php')) {
require_once 'tests/phpunit/CiviTest/CiviSeleniumSettings.php';
}
}
}
}

View file

@ -0,0 +1,86 @@
<?php
/**
* Class CRM_Core_CodeGen_BaseTask
*/
abstract class CRM_Core_CodeGen_BaseTask implements CRM_Core_CodeGen_ITask {
/**
* @var CRM_Core_CodeGen_Main
*/
protected $config;
protected $tables;
/**
* @param CRM_Core_CodeGen_Main $config
*/
public function __construct($config) {
$this->setConfig($config);
}
/**
* TODO: this is the most rudimentary possible hack. CG config should
* eventually be made into a first-class object.
*
* @param object $config
*/
public function setConfig($config) {
$this->config = $config;
$this->tables = $this->config->tables;
}
/**
* @return bool
* TRUE if an update is needed.
*/
public function needsUpdate() {
return TRUE;
}
/**
* Extract a single regex from a file.
*
* @param string $file
* File name
* @param string $regex
* A pattern to match. Ex: "foo=([a-z]+)".
* @return string|NULL
* The value matched.
*/
protected static function extractRegex($file, $regex) {
$content = file_get_contents($file);
if (preg_match($regex, $content, $matches)) {
return $matches[1];
}
else {
return NULL;
}
}
/**
* Determine if two snippets of PHP code are approximately equivalent.
*
* This includes exceptions to equivalence for (a) whitespace and (b)
* the token "GenCodeChecksum".
*
* This is useful for determining if someone has manually mucked with
* one the files. However, it's not perfect -- because whitespace changes
* are not detected. Hence, it's good to use in combination with another
* heuristic.
*
* @param $actual
* @param $expected
* @return bool
*/
protected function isApproxPhpMatch($actual, $expected) {
$actual = preg_replace(';\(GenCodeChecksum:([a-zA-Z0-9]+)\);', '', $actual);
$actual = preg_replace(';[ \r\n\t];', '', $actual);
$expected = preg_replace(';\(GenCodeChecksum:([a-zA-Z0-9]+)\);', '',
$expected);
$expected = preg_replace(';[ \r\n\t];', '', $expected);
return $actual === $expected;
}
}

View file

@ -0,0 +1,75 @@
<?php
/**
* Generate configuration files
*/
class CRM_Core_CodeGen_Config extends CRM_Core_CodeGen_BaseTask {
public function run() {
$this->setupCms();
}
public function setupCms() {
if (!in_array($this->config->cms, array(
'backdrop',
'drupal',
'drupal8',
'joomla',
'wordpress',
))) {
echo "Config file for '{$this->config->cms}' not known.";
exit();
}
elseif ($this->config->cms !== 'joomla') {
$configTemplate = $this->findConfigTemplate($this->config->cms);
if ($configTemplate) {
echo "Generating civicrm.config.php\n";
copy($configTemplate, '../civicrm.config.php');
}
else {
throw new Exception("Failed to locate template for civicrm.config.php");
}
}
}
/**
* @param string $cms
* "drupal"|"wordpress".
* @return null|string
* path to config template
*/
public function findConfigTemplate($cms) {
$candidates = array();
switch ($cms) {
case 'backdrop':
// FIXME!!!!
$candidates[] = "../backdrop/civicrm.config.php.backdrop";
$candidates[] = "../../backdrop/civicrm.config.php.backdrop";
$candidates[] = "../drupal/civicrm.config.php.backdrop";
$candidates[] = "../../drupal/civicrm.config.php.backdrop";
break;
case 'drupal':
$candidates[] = "../drupal/civicrm.config.php.drupal";
$candidates[] = "../../drupal/civicrm.config.php.drupal";
break;
case 'drupal8':
$candidates[] = "../../modules/civicrm/civicrm.config.php.drupal";
$candidates[] = "../../../modules/civicrm/civicrm.config.php.drupal";
break;
case 'wordpress':
$candidates[] = "../../civicrm.config.php.wordpress";
$candidates[] = "../WordPress/civicrm.config.php.wordpress";
break;
}
foreach ($candidates as $candidate) {
if (file_exists($candidate)) {
return $candidate;
break;
}
}
return NULL;
}
}

View file

@ -0,0 +1,132 @@
<?php
/**
* Create DAO ORM classes.
*/
class CRM_Core_CodeGen_DAO extends CRM_Core_CodeGen_BaseTask {
/**
* @var string
*/
public $name;
/**
* @var string
*/
private $tableChecksum;
/**
* @var string
*/
private $raw;
/**
* CRM_Core_CodeGen_DAO constructor.
*
* @param \CRM_Core_CodeGen_Main $config
* @param string $name
*/
public function __construct($config, $name) {
parent::__construct($config);
$this->name = $name;
}
/**
* @return bool
* TRUE if an update is needed.
*/
public function needsUpdate() {
if (!file_exists($this->getAbsFileName())) {
return TRUE;
}
if ($this->getTableChecksum() !== self::extractRegex($this->getAbsFileName(), ';\(GenCodeChecksum:([a-zA-Z0-9]+)\);')) {
return TRUE;
}
return !$this->isApproxPhpMatch(
file_get_contents($this->getAbsFileName()),
$this->getRaw());
}
/**
* Run generator.
*/
public function run() {
echo "Generating {$this->name} as " . $this->getRelFileName() . "\n";
if (empty($this->tables[$this->name]['base'])) {
echo "No base defined for {$this->name}, skipping output generation\n";
return;
}
$template = new CRM_Core_CodeGen_Util_Template('php');
$template->assign('table', $this->tables[$this->name]);
if (empty($this->tables[$this->name]['index'])) {
$template->assign('indicesPhp', var_export(array(), 1));
}
else {
$template->assign('indicesPhp', var_export($this->tables[$this->name]['index'], 1));
}
$template->assign('genCodeChecksum', $this->getTableChecksum());
$template->run('dao.tpl', $this->getAbsFileName());
}
/**
* Generate the raw PHP code for the DAO.
*
* @return string
*/
public function getRaw() {
if (!$this->raw) {
$template = new CRM_Core_CodeGen_Util_Template('php');
$template->assign('table', $this->tables[$this->name]);
if (empty($this->tables[$this->name]['index'])) {
$template->assign('indicesPhp', var_export(array(), 1));
}
else {
$template->assign('indicesPhp', var_export($this->tables[$this->name]['index'], 1));
}
$template->assign('genCodeChecksum', 'NEW');
$this->raw = $template->fetch('dao.tpl');
}
return $this->raw;
}
/**
* Get relative file name.
*
* @return string
*/
public function getRelFileName() {
return $this->tables[$this->name]['fileName'];
}
/**
* Get the absolute file name.
*
* @return string
*/
public function getAbsFileName() {
$directory = $this->config->phpCodePath . $this->tables[$this->name]['base'];
CRM_Core_CodeGen_Util_File::createDir($directory);
$absFileName = $directory . $this->getRelFileName();
return $absFileName;
}
/**
* Get a unique signature for the table/schema.
*
* @return string
*/
protected function getTableChecksum() {
if (!$this->tableChecksum) {
$flat = array();
CRM_Utils_Array::flatten($this->tables[$this->name], $flat);
ksort($flat);
$this->tableChecksum = md5(json_encode($flat));
}
return $this->tableChecksum;
}
}

View file

@ -0,0 +1,61 @@
<?php
/**
* Generate language files and classes
*/
class CRM_Core_CodeGen_I18n extends CRM_Core_CodeGen_BaseTask {
public function run() {
$this->generateInstallLangs();
$this->generateSchemaStructure();
}
public function generateInstallLangs() {
// CRM-7161: generate install/langs.php from the languages template
// grep it for enabled languages and create a 'xx_YY' => 'Language name' $langs mapping
$matches = array();
preg_match_all('/, 1, \'([a-z][a-z]_[A-Z][A-Z])\', \'..\', \{localize\}\'\{ts escape="sql"\}(.+)\{\/ts\}\'\{\/localize\}, /', file_get_contents('templates/languages.tpl'), $matches);
$langs = array();
for ($i = 0; $i < count($matches[0]); $i++) {
$langs[$matches[1][$i]] = $matches[2][$i];
}
file_put_contents('../install/langs.php', "<?php \$langs = " . var_export($langs, TRUE) . ";");
}
public function generateSchemaStructure() {
echo "Generating CRM_Core_I18n_SchemaStructure...\n";
$columns = array();
$indices = array();
$widgets = array();
foreach ($this->tables as $table) {
if ($table['localizable']) {
$columns[$table['name']] = array();
$widgets[$table['name']] = array();
}
else {
continue;
}
foreach ($table['fields'] as $field) {
if ($field['localizable']) {
$columns[$table['name']][$field['name']] = $field['sqlType'];
$widgets[$table['name']][$field['name']] = $field['widget'];
}
}
if (isset($table['index'])) {
foreach ($table['index'] as $index) {
if ($index['localizable']) {
$indices[$table['name']][$index['name']] = $index;
}
}
}
}
$template = new CRM_Core_CodeGen_Util_Template('php');
$template->assign('columns', $columns);
$template->assign('indices', $indices);
$template->assign('widgets', $widgets);
$template->run('schema_structure.tpl', $this->config->phpCodePath . "/CRM/Core/I18n/SchemaStructure.php");
}
}

View file

@ -0,0 +1,19 @@
<?php
/**
* Implemented by CG tasks
*/
interface CRM_Core_CodeGen_ITask {
/**
* Perform the task.
*/
public function run();
/**
* @return bool
* TRUE if an update is needed.
*/
public function needsUpdate();
}

View file

@ -0,0 +1,152 @@
<?php
/**
* Class CRM_Core_CodeGen_Main
*/
class CRM_Core_CodeGen_Main {
var $buildVersion;
var $db_version;
var $cms; // drupal, joomla, wordpress
var $CoreDAOCodePath;
var $sqlCodePath;
var $phpCodePath;
var $tplCodePath;
var $schemaPath; // ex: schema/Schema.xml
/**
* Definitions of all tables.
*
* @var array
* Ex: $tables['civicrm_address_format']['className'] = 'CRM_Core_DAO_AddressFormat';
*/
var $tables;
/**
* @var array
* Ex: $database['tableAttributes_modern'] = "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci";
*/
var $database;
/**
* @var string|NULL path in which to store a marker that indicates the last execution of
* GenCode. If a matching marker already exists, GenCode doesn't run.
*/
var $digestPath;
/**
* @var string|NULL a digest of the inputs to the code-generator (eg the properties and source files)
*/
var $sourceDigest;
/**
* @param $CoreDAOCodePath
* @param $sqlCodePath
* @param $phpCodePath
* @param $tplCodePath
* @param $IGNORE
* @param $argCms
* @param $argVersion
* @param $schemaPath
* @param $digestPath
*/
public function __construct($CoreDAOCodePath, $sqlCodePath, $phpCodePath, $tplCodePath, $IGNORE, $argCms, $argVersion, $schemaPath, $digestPath) {
$this->CoreDAOCodePath = $CoreDAOCodePath;
$this->sqlCodePath = $sqlCodePath;
$this->phpCodePath = $phpCodePath;
$this->tplCodePath = $tplCodePath;
$this->digestPath = $digestPath;
$this->sourceDigest = NULL;
// default cms is 'drupal', if not specified
$this->cms = isset($argCms) ? strtolower($argCms) : 'drupal';
$versionFile = $this->phpCodePath . "/xml/version.xml";
$versionXML = CRM_Core_CodeGen_Util_Xml::parse($versionFile);
$this->db_version = $versionXML->version_no;
$this->buildVersion = preg_replace('/^(\d{1,2}\.\d{1,2})\.(\d{1,2}|\w{4,7})$/i', '$1', $this->db_version);
if (isset($argVersion)) {
// change the version to that explicitly passed, if any
$this->db_version = $argVersion;
}
$this->schemaPath = $schemaPath;
}
/**
* Automatically generate a variety of files.
*/
public function main() {
echo "\ncivicrm_domain.version := " . $this->db_version . "\n\n";
if ($this->buildVersion < 1.1) {
echo "The Database is not compatible for this version";
exit();
}
if (substr(phpversion(), 0, 1) < 5) {
echo phpversion() . ', ' . substr(phpversion(), 0, 1) . "\n";
echo "
CiviCRM requires a PHP Version >= 5
Please upgrade your php / webserver configuration
Alternatively you can get a version of CiviCRM that matches your PHP version
";
exit();
}
foreach ($this->getTasks() as $task) {
if (getenv('GENCODE_FORCE') || $task->needsUpdate()) {
$task->run();
}
}
}
/**
* @return array
* Array<CRM_Core_CodeGen_ITask>.
* @throws \Exception
*/
public function getTasks() {
$this->init();
$tasks = array();
$tasks[] = new CRM_Core_CodeGen_Config($this);
$tasks[] = new CRM_Core_CodeGen_Version($this);
$tasks[] = new CRM_Core_CodeGen_Reflection($this);
$tasks[] = new CRM_Core_CodeGen_Schema($this);
foreach (array_keys($this->tables) as $name) {
$tasks[] = new CRM_Core_CodeGen_DAO($this, $name);
}
$tasks[] = new CRM_Core_CodeGen_I18n($this);
return $tasks;
}
/**
* Compute a digest based on the GenCode logic (PHP/tpl).
*
* @return string
*/
public function getSourceDigest() {
if ($this->sourceDigest === NULL) {
$srcDir = CRM_Core_CodeGen_Util_File::findCoreSourceDir();
$files = CRM_Core_CodeGen_Util_File::findManyFiles(array(
array("$srcDir/CRM/Core/CodeGen", '*.php'),
array("$srcDir/xml", "*.php"),
array("$srcDir/xml", "*.tpl"),
));
$this->sourceDigest = CRM_Core_CodeGen_Util_File::digestAll($files);
}
return $this->sourceDigest;
}
protected function init() {
if (!$this->database || !$this->tables) {
$specification = new CRM_Core_CodeGen_Specification();
$specification->parse($this->schemaPath, $this->buildVersion);
# cheese:
$this->database = $specification->database;
$this->tables = $specification->tables;
}
}
}

View file

@ -0,0 +1,85 @@
<?php
/**
* Create classes which are used for schema introspection.
*/
class CRM_Core_CodeGen_Reflection extends CRM_Core_CodeGen_BaseTask {
protected $checksum;
/**
* @var string
*/
private $raw;
/**
* @return bool
* TRUE if an update is needed.
*/
public function needsUpdate() {
if (!file_exists($this->getAbsFileName())) {
return TRUE;
}
// Generating this file is fairly cheap, and we don't have robust heuristic
// for the checksum.
// if ($this->getSchemaChecksum() !== self::extractRegex($this->getAbsFileName(), ';\(GenCodeChecksum:([a-zA-Z0-9]+)\);')) {
// return TRUE;
// }
return !$this->isApproxPhpMatch(
file_get_contents($this->getAbsFileName()),
$this->getRaw());
}
/**
* Run generator.
*/
public function run() {
echo "Generating table list\n";
$template = new CRM_Core_CodeGen_Util_Template('php');
$template->assign('tables', $this->tables);
$template->assign('genCodeChecksum', 'IGNORE');
$template->run('listAll.tpl', $this->getAbsFileName());
}
/**
* Generate the raw PHP code for the data file.
*
* @return string
*/
public function getRaw() {
if (!$this->raw) {
$template = new CRM_Core_CodeGen_Util_Template('php');
$template->assign('tables', $this->tables);
$template->assign('genCodeChecksum', 'NEW');
$this->raw = $template->fetch('listAll.tpl');
}
return $this->raw;
}
/**
* Get absolute file name.
*
* @return string
*/
protected function getAbsFileName() {
return $this->config->CoreDAOCodePath . "AllCoreTables.data.php";
}
// /**
// * Get the checksum for the schema.
// *
// * @return string
// */
// protected function getSchemaChecksum() {
// if (!$this->checksum) {
// CRM_Utils_Array::flatten($this->tables, $flat);
// ksort($flat);
// $this->checksum = md5(json_encode($flat));
// }
// return $this->checksum;
// }
}

View file

@ -0,0 +1,133 @@
<?php
/**
* Create SQL files to create and populate a new schema.
*/
class CRM_Core_CodeGen_Schema extends CRM_Core_CodeGen_BaseTask {
/**
* CRM_Core_CodeGen_Schema constructor.
*
* @param \CRM_Core_CodeGen_Main $config
*/
public function __construct($config) {
parent::__construct($config);
$this->locales = $this->findLocales();
}
public function run() {
CRM_Core_CodeGen_Util_File::createDir($this->config->sqlCodePath);
$this->generateCreateSql();
$this->generateDropSql();
$this->generateLocaleDataSql();
// also create the archive tables
// $this->generateCreateSql('civicrm_archive.mysql' );
// $this->generateDropSql('civicrm_archive_drop.mysql');
$this->generateNavigation();
$this->generateSample();
}
/**
* @param string $fileName
*/
public function generateCreateSql($fileName = 'civicrm.mysql') {
echo "Generating sql file\n";
$template = new CRM_Core_CodeGen_Util_Template('sql');
$template->assign('database', $this->config->database);
$template->assign('tables', $this->tables);
$dropOrder = array_reverse(array_keys($this->tables));
$template->assign('dropOrder', $dropOrder);
$template->assign('mysql', 'modern');
$template->run('schema.tpl', $this->config->sqlCodePath . $fileName);
}
/**
* @param string $fileName
*/
public function generateDropSql($fileName = 'civicrm_drop.mysql') {
echo "Generating sql drop tables file\n";
$dropOrder = array_reverse(array_keys($this->tables));
$template = new CRM_Core_CodeGen_Util_Template('sql');
$template->assign('dropOrder', $dropOrder);
$template->run('drop.tpl', $this->config->sqlCodePath . $fileName);
}
public function generateNavigation() {
echo "Generating navigation file\n";
$template = new CRM_Core_CodeGen_Util_Template('sql');
$template->run('civicrm_navigation.tpl', $this->config->sqlCodePath . "civicrm_navigation.mysql");
}
public function generateLocaleDataSql() {
$template = new CRM_Core_CodeGen_Util_Template('sql');
global $tsLocale;
$oldTsLocale = $tsLocale;
foreach ($this->locales as $locale) {
echo "Generating data files for $locale\n";
$tsLocale = $locale;
$template->assign('locale', $locale);
$template->assign('db_version', $this->config->db_version);
$sections = array(
'civicrm_country.tpl',
'civicrm_state_province.tpl',
'civicrm_currency.tpl',
'civicrm_data.tpl',
'civicrm_navigation.tpl',
'civicrm_version_sql.tpl',
);
$ext = ($locale != 'en_US' ? ".$locale" : '');
// write the initialize base-data sql script
$template->runConcat($sections, $this->config->sqlCodePath . "civicrm_data$ext.mysql");
// write the acl sql script
$template->run('civicrm_acl.tpl', $this->config->sqlCodePath . "civicrm_acl$ext.mysql");
}
$tsLocale = $oldTsLocale;
}
public function generateSample() {
$template = new CRM_Core_CodeGen_Util_Template('sql');
$sections = array(
'civicrm_sample.tpl',
'civicrm_acl.tpl',
);
$template->runConcat($sections, $this->config->sqlCodePath . 'civicrm_sample.mysql');
$template->run('case_sample.tpl', $this->config->sqlCodePath . 'case_sample.mysql');
}
/**
* @return array
*/
public function findLocales() {
require_once 'CRM/Core/Config.php';
$config = CRM_Core_Config::singleton(FALSE);
$locales = array();
$localeDir = CRM_Core_I18n::getResourceDir();
if (file_exists($localeDir)) {
$locales = preg_grep('/^[a-z][a-z]_[A-Z][A-Z]$/', scandir($localeDir));
}
$localesMask = getenv('CIVICRM_LOCALES');
if (!empty($localesMask)) {
$mask = explode(',', $localesMask);
$locales = array_intersect($locales, $mask);
}
if (!in_array('en_US', $locales)) {
array_unshift($locales, 'en_US');
}
return $locales;
}
}

View file

@ -0,0 +1,721 @@
<?php
/**
* Read the schema specification and parse into internal data structures
*/
class CRM_Core_CodeGen_Specification {
public $tables;
public $database;
protected $classNames;
/**
* Read and parse.
*
* @param $schemaPath
* @param string $buildVersion
* Which version of the schema to build.
*/
public function parse($schemaPath, $buildVersion) {
$this->buildVersion = $buildVersion;
echo "Parsing schema description " . $schemaPath . "\n";
$dbXML = CRM_Core_CodeGen_Util_Xml::parse($schemaPath);
echo "Extracting database information\n";
$this->database = &$this->getDatabase($dbXML);
$this->classNames = array();
# TODO: peel DAO-specific stuff out of getTables, and spec reading into its own class
echo "Extracting table information\n";
$this->tables = $this->getTables($dbXML, $this->database);
$this->resolveForeignKeys($this->tables, $this->classNames);
$this->tables = $this->orderTables($this->tables);
// add archive tables here
foreach ($this->tables as $name => $table) {
if ($table['archive'] == 'true') {
$name = 'archive_' . $table['name'];
$table['name'] = $name;
$table['archive'] = 'false';
if (isset($table['foreignKey'])) {
foreach ($table['foreignKey'] as $fkName => $fkValue) {
if ($this->tables[$fkValue['table']]['archive'] == 'true') {
$table['foreignKey'][$fkName]['table'] = 'archive_' . $table['foreignKey'][$fkName]['table'];
$table['foreignKey'][$fkName]['uniqName']
= str_replace('FK_', 'FK_archive_', $table['foreignKey'][$fkName]['uniqName']);
}
}
$archiveTables[$name] = $table;
}
}
}
}
/**
* @param $dbXML
*
* @return array
*/
public function &getDatabase(&$dbXML) {
$database = array('name' => trim((string ) $dbXML->name));
$attributes = '';
$this->checkAndAppend($attributes, $dbXML, 'character_set', 'DEFAULT CHARACTER SET ', '');
$this->checkAndAppend($attributes, $dbXML, 'collate', 'COLLATE ', '');
$database['attributes'] = $attributes;
$tableAttributes_modern = $tableAttributes_simple = '';
$this->checkAndAppend($tableAttributes_modern, $dbXML, 'table_type', 'ENGINE=', '');
$this->checkAndAppend($tableAttributes_simple, $dbXML, 'table_type', 'TYPE=', '');
$database['tableAttributes_modern'] = trim($tableAttributes_modern . ' ' . $attributes);
$database['tableAttributes_simple'] = trim($tableAttributes_simple);
$database['comment'] = $this->value('comment', $dbXML, '');
return $database;
}
/**
* @param $dbXML
* @param $database
*
* @return array
*/
public function getTables($dbXML, &$database) {
$tables = array();
foreach ($dbXML->tables as $tablesXML) {
foreach ($tablesXML->table as $tableXML) {
if ($this->value('drop', $tableXML, 0) > 0 and $this->value('drop', $tableXML, 0) <= $this->buildVersion) {
continue;
}
if ($this->value('add', $tableXML, 0) <= $this->buildVersion) {
$this->getTable($tableXML, $database, $tables);
}
}
}
return $tables;
}
/**
* @param $tables
* @param string $classNames
*/
public function resolveForeignKeys(&$tables, &$classNames) {
foreach (array_keys($tables) as $name) {
$this->resolveForeignKey($tables, $classNames, $name);
}
}
/**
* @param $tables
* @param string $classNames
* @param string $name
*/
public function resolveForeignKey(&$tables, &$classNames, $name) {
if (!array_key_exists('foreignKey', $tables[$name])) {
return;
}
foreach (array_keys($tables[$name]['foreignKey']) as $fkey) {
$ftable = $tables[$name]['foreignKey'][$fkey]['table'];
if (!array_key_exists($ftable, $classNames)) {
echo "$ftable is not a valid foreign key table in $name\n";
continue;
}
$tables[$name]['foreignKey'][$fkey]['className'] = $classNames[$ftable];
$tables[$name]['foreignKey'][$fkey]['fileName'] = str_replace('_', '/', $classNames[$ftable]) . '.php';
$tables[$name]['fields'][$fkey]['FKClassName'] = $classNames[$ftable];
}
}
/**
* @param $tables
*
* @return array
*/
public function orderTables(&$tables) {
$ordered = array();
while (!empty($tables)) {
foreach (array_keys($tables) as $name) {
if ($this->validTable($tables, $ordered, $name)) {
$ordered[$name] = $tables[$name];
unset($tables[$name]);
}
}
}
return $ordered;
}
/**
* @param $tables
* @param int $valid
* @param string $name
*
* @return bool
*/
public function validTable(&$tables, &$valid, $name) {
if (!array_key_exists('foreignKey', $tables[$name])) {
return TRUE;
}
foreach (array_keys($tables[$name]['foreignKey']) as $fkey) {
$ftable = $tables[$name]['foreignKey'][$fkey]['table'];
if (!array_key_exists($ftable, $valid) && $ftable !== $name) {
return FALSE;
}
}
return TRUE;
}
/**
* @param $tableXML
* @param $database
* @param $tables
*/
public function getTable($tableXML, &$database, &$tables) {
$name = trim((string ) $tableXML->name);
$klass = trim((string ) $tableXML->class);
$base = $this->value('base', $tableXML);
$sourceFile = "xml/schema/{$base}/{$klass}.xml";
$daoPath = "{$base}/DAO/";
$baoPath = __DIR__ . '/../../../' . str_replace(' ', '', "{$base}/BAO/");
$pre = str_replace('/', '_', $daoPath);
$this->classNames[$name] = $pre . $klass;
$localizable = FALSE;
foreach ($tableXML->field as $fieldXML) {
if ($fieldXML->localizable) {
$localizable = TRUE;
break;
}
}
$table = array(
'name' => $name,
'base' => $daoPath,
'sourceFile' => $sourceFile,
'fileName' => $klass . '.php',
'objectName' => $klass,
'labelName' => substr($name, 8),
'className' => $this->classNames[$name],
'bao' => (file_exists($baoPath . $klass . '.php') ? str_replace('DAO', 'BAO', $this->classNames[$name]) : $this->classNames[$name]),
'entity' => $klass,
'attributes_simple' => trim($database['tableAttributes_simple']),
'attributes_modern' => trim($database['tableAttributes_modern']),
'comment' => $this->value('comment', $tableXML),
'localizable' => $localizable,
'log' => $this->value('log', $tableXML, 'false'),
'archive' => $this->value('archive', $tableXML, 'false'),
);
$fields = array();
foreach ($tableXML->field as $fieldXML) {
if ($this->value('drop', $fieldXML, 0) > 0 and $this->value('drop', $fieldXML, 0) <= $this->buildVersion) {
continue;
}
if ($this->value('add', $fieldXML, 0) <= $this->buildVersion) {
$this->getField($fieldXML, $fields);
}
}
$table['fields'] = &$fields;
if ($this->value('primaryKey', $tableXML)) {
$this->getPrimaryKey($tableXML->primaryKey, $fields, $table);
}
// some kind of refresh?
CRM_Core_Config::singleton(FALSE);
if ($this->value('index', $tableXML)) {
$index = array();
foreach ($tableXML->index as $indexXML) {
if ($this->value('drop', $indexXML, 0) > 0 and $this->value('drop', $indexXML, 0) <= $this->buildVersion) {
continue;
}
$this->getIndex($indexXML, $fields, $index);
}
CRM_Core_BAO_SchemaHandler::addIndexSignature($name, $index);
$table['index'] = &$index;
}
if ($this->value('foreignKey', $tableXML)) {
$foreign = array();
foreach ($tableXML->foreignKey as $foreignXML) {
if ($this->value('drop', $foreignXML, 0) > 0 and $this->value('drop', $foreignXML, 0) <= $this->buildVersion) {
continue;
}
if ($this->value('add', $foreignXML, 0) <= $this->buildVersion) {
$this->getForeignKey($foreignXML, $fields, $foreign, $name);
}
}
$table['foreignKey'] = &$foreign;
}
if ($this->value('dynamicForeignKey', $tableXML)) {
$dynamicForeign = array();
foreach ($tableXML->dynamicForeignKey as $foreignXML) {
if ($this->value('drop', $foreignXML, 0) > 0 and $this->value('drop', $foreignXML, 0) <= $this->buildVersion) {
continue;
}
if ($this->value('add', $foreignXML, 0) <= $this->buildVersion) {
$this->getDynamicForeignKey($foreignXML, $dynamicForeign, $name);
}
}
$table['dynamicForeignKey'] = $dynamicForeign;
}
$tables[$name] = &$table;
}
/**
* @param $fieldXML
* @param $fields
*/
public function getField(&$fieldXML, &$fields) {
$name = trim((string ) $fieldXML->name);
$field = array('name' => $name, 'localizable' => ((bool) $fieldXML->localizable) ? 1 : 0);
$type = (string ) $fieldXML->type;
switch ($type) {
case 'varchar':
case 'char':
$field['length'] = (int) $fieldXML->length;
$field['sqlType'] = "$type({$field['length']})";
$field['phpType'] = 'string';
$field['crmType'] = 'CRM_Utils_Type::T_STRING';
$field['size'] = $this->getSize($fieldXML);
break;
case 'text':
$field['sqlType'] = $field['phpType'] = $type;
$field['crmType'] = 'CRM_Utils_Type::T_' . strtoupper($type);
// CRM-13497 see fixme below
$field['rows'] = isset($fieldXML->html) ? $this->value('rows', $fieldXML->html) : NULL;
$field['cols'] = isset($fieldXML->html) ? $this->value('cols', $fieldXML->html) : NULL;
break;
break;
case 'datetime':
$field['sqlType'] = $field['phpType'] = $type;
$field['crmType'] = 'CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME';
break;
case 'boolean':
// need this case since some versions of mysql do not have boolean as a valid column type and hence it
// is changed to tinyint. hopefully after 2 yrs this case can be removed.
$field['sqlType'] = 'tinyint';
$field['phpType'] = $type;
$field['crmType'] = 'CRM_Utils_Type::T_' . strtoupper($type);
break;
case 'decimal':
$length = $fieldXML->length ? $fieldXML->length : '20,2';
$field['sqlType'] = 'decimal(' . $length . ')';
$field['phpType'] = 'float';
$field['crmType'] = 'CRM_Utils_Type::T_MONEY';
$field['precision'] = $length;
break;
case 'float':
$field['sqlType'] = 'double';
$field['phpType'] = 'float';
$field['crmType'] = 'CRM_Utils_Type::T_FLOAT';
break;
default:
$field['sqlType'] = $field['phpType'] = $type;
if ($type == 'int unsigned') {
$field['crmType'] = 'CRM_Utils_Type::T_INT';
}
else {
$field['crmType'] = 'CRM_Utils_Type::T_' . strtoupper($type);
}
break;
}
$field['required'] = $this->value('required', $fieldXML);
$field['collate'] = $this->value('collate', $fieldXML);
$field['comment'] = $this->value('comment', $fieldXML);
$field['default'] = $this->value('default', $fieldXML);
$field['import'] = $this->value('import', $fieldXML);
if ($this->value('export', $fieldXML)) {
$field['export'] = $this->value('export', $fieldXML);
}
else {
$field['export'] = $this->value('import', $fieldXML);
}
$field['rule'] = $this->value('rule', $fieldXML);
$field['title'] = $this->value('title', $fieldXML);
if (!$field['title']) {
$field['title'] = $this->composeTitle($name);
}
$field['headerPattern'] = $this->value('headerPattern', $fieldXML);
$field['dataPattern'] = $this->value('dataPattern', $fieldXML);
$field['uniqueName'] = $this->value('uniqueName', $fieldXML);
$field['html'] = $this->value('html', $fieldXML);
if (!empty($field['html'])) {
$validOptions = array(
'type',
'formatType',
/* Fixme: prior to CRM-13497 these were in a flat structure
// CRM-13497 moved them to be nested within 'html' but there's no point
// making that change in the DAOs right now since we are in the process of
// moving to docrtine anyway.
// So translating from nested xml back to flat structure for now.
'rows',
'cols',
'size', */
);
$field['html'] = array();
foreach ($validOptions as $htmlOption) {
if (!empty($fieldXML->html->$htmlOption)) {
$field['html'][$htmlOption] = $this->value($htmlOption, $fieldXML->html);
}
}
}
// in multilingual context popup, we need extra information to create appropriate widget
if ($fieldXML->localizable) {
if (isset($fieldXML->html)) {
$field['widget'] = (array) $fieldXML->html;
}
else {
// default
$field['widget'] = array('type' => 'Text');
}
if (isset($fieldXML->required)) {
$field['widget']['required'] = $this->value('required', $fieldXML);
}
}
$field['pseudoconstant'] = $this->value('pseudoconstant', $fieldXML);
if (!empty($field['pseudoconstant'])) {
//ok this is a bit long-winded but it gets there & is consistent with above approach
$field['pseudoconstant'] = array();
$validOptions = array(
// Fields can specify EITHER optionGroupName OR table, not both
// (since declaring optionGroupName means we are using the civicrm_option_value table)
'optionGroupName',
'table',
// If table is specified, keyColumn and labelColumn are also required
'keyColumn',
'labelColumn',
// Non-translated machine name for programmatic lookup. Defaults to 'name' if that column exists
'nameColumn',
// Where clause snippet (will be joined to the rest of the query with AND operator)
'condition',
// callback function incase of static arrays
'callback',
// Path to options edit form
'optionEditPath',
);
foreach ($validOptions as $pseudoOption) {
if (!empty($fieldXML->pseudoconstant->$pseudoOption)) {
$field['pseudoconstant'][$pseudoOption] = $this->value($pseudoOption, $fieldXML->pseudoconstant);
}
}
if (!isset($field['pseudoconstant']['optionEditPath']) && !empty($field['pseudoconstant']['optionGroupName'])) {
$field['pseudoconstant']['optionEditPath'] = 'civicrm/admin/options/' . $field['pseudoconstant']['optionGroupName'];
}
// For now, fields that have option lists that are not in the db can simply
// declare an empty pseudoconstant tag and we'll add this placeholder.
// That field's BAO::buildOptions fn will need to be responsible for generating the option list
if (empty($field['pseudoconstant'])) {
$field['pseudoconstant'] = 'not in database';
}
}
$fields[$name] = &$field;
}
/**
* @param string $name
*
* @return string
*/
public function composeTitle($name) {
$names = explode('_', strtolower($name));
$title = '';
for ($i = 0; $i < count($names); $i++) {
if ($names[$i] === 'id' || $names[$i] === 'is') {
// id's do not get titles
return NULL;
}
if ($names[$i] === 'im') {
$names[$i] = 'IM';
}
else {
$names[$i] = ucfirst(trim($names[$i]));
}
$title = $title . ' ' . $names[$i];
}
return trim($title);
}
/**
* @param object $primaryXML
* @param array $fields
* @param array $table
*/
public function getPrimaryKey(&$primaryXML, &$fields, &$table) {
$name = trim((string ) $primaryXML->name);
// set the autoincrement property of the field
$auto = $this->value('autoincrement', $primaryXML);
if (isset($fields[$name])) {
$fields[$name]['autoincrement'] = $auto;
}
$fields[$name]['autoincrement'] = $auto;
$primaryKey = array(
'name' => $name,
'autoincrement' => $auto,
);
// populate fields
foreach ($primaryXML->fieldName as $v) {
$fieldName = (string) ($v);
$length = (string) ($v['length']);
if (strlen($length) > 0) {
$fieldName = "$fieldName($length)";
}
$primaryKey['field'][] = $fieldName;
}
// when field array is empty set it to the name of the primary key.
if (empty($primaryKey['field'])) {
$primaryKey['field'][] = $name;
}
// all fieldnames have to be defined and should exist in schema.
foreach ($primaryKey['field'] as $fieldName) {
if (!$fieldName) {
echo "Invalid field defination for index $name\n";
return;
}
$parenOffset = strpos($fieldName, '(');
if ($parenOffset > 0) {
$fieldName = substr($fieldName, 0, $parenOffset);
}
if (!array_key_exists($fieldName, $fields)) {
echo "Table does not contain $fieldName\n";
print_r($fields);
exit();
}
}
$table['primaryKey'] = &$primaryKey;
}
/**
* @param $indexXML
* @param $fields
* @param $indices
*/
public function getIndex(&$indexXML, &$fields, &$indices) {
//echo "\n\n*******************************************************\n";
//echo "entering getIndex\n";
$index = array();
// empty index name is fine
$indexName = trim((string) $indexXML->name);
$index['name'] = $indexName;
$index['field'] = array();
// populate fields
foreach ($indexXML->fieldName as $v) {
$fieldName = (string) ($v);
$length = (string) ($v['length']);
if (strlen($length) > 0) {
$fieldName = "$fieldName($length)";
}
$index['field'][] = $fieldName;
}
$index['localizable'] = FALSE;
foreach ($index['field'] as $fieldName) {
if (isset($fields[$fieldName]) and $fields[$fieldName]['localizable']) {
$index['localizable'] = TRUE;
break;
}
}
// check for unique index
if ($this->value('unique', $indexXML)) {
$index['unique'] = TRUE;
}
// field array cannot be empty
if (empty($index['field'])) {
echo "No fields defined for index $indexName\n";
return;
}
// all fieldnames have to be defined and should exist in schema.
foreach ($index['field'] as $fieldName) {
if (!$fieldName) {
echo "Invalid field defination for index $indexName\n";
return;
}
$parenOffset = strpos($fieldName, '(');
if ($parenOffset > 0) {
$fieldName = substr($fieldName, 0, $parenOffset);
}
if (!array_key_exists($fieldName, $fields)) {
echo "Table does not contain $fieldName\n";
print_r($fields);
exit();
}
}
$indices[$indexName] = &$index;
}
/**
* @param $foreignXML
* @param $fields
* @param $foreignKeys
* @param string $currentTableName
*/
public function getForeignKey(&$foreignXML, &$fields, &$foreignKeys, &$currentTableName) {
$name = trim((string ) $foreignXML->name);
/** need to make sure there is a field of type name */
if (!array_key_exists($name, $fields)) {
echo "foreign $name in $currentTableName does not have a field definition, ignoring\n";
return;
}
/** need to check for existence of table and key **/
$table = trim($this->value('table', $foreignXML));
$foreignKey = array(
'name' => $name,
'table' => $table,
'uniqName' => "FK_{$currentTableName}_{$name}",
'key' => trim($this->value('key', $foreignXML)),
'import' => $this->value('import', $foreignXML, FALSE),
'export' => $this->value('import', $foreignXML, FALSE),
// we do this matching in a separate phase (resolveForeignKeys)
'className' => NULL,
'onDelete' => $this->value('onDelete', $foreignXML, FALSE),
);
$foreignKeys[$name] = &$foreignKey;
}
/**
* @param $foreignXML
* @param $dynamicForeignKeys
*/
public function getDynamicForeignKey(&$foreignXML, &$dynamicForeignKeys) {
$foreignKey = array(
'idColumn' => trim($foreignXML->idColumn),
'typeColumn' => trim($foreignXML->typeColumn),
'key' => trim($this->value('key', $foreignXML)),
);
$dynamicForeignKeys[] = $foreignKey;
}
/**
* @param $key
* @param $object
* @param null $default
*
* @return null|string
*/
protected function value($key, &$object, $default = NULL) {
if (isset($object->$key)) {
return (string ) $object->$key;
}
return $default;
}
/**
* @param $attributes
* @param $object
* @param string $name
* @param null $pre
* @param null $post
*/
protected function checkAndAppend(&$attributes, &$object, $name, $pre = NULL, $post = NULL) {
if (!isset($object->$name)) {
return;
}
$value = $pre . trim($object->$name) . $post;
$this->append($attributes, ' ', trim($value));
}
/**
* @param $str
* @param $delim
* @param $name
*/
protected function append(&$str, $delim, $name) {
if (empty($name)) {
return;
}
if (is_array($name)) {
foreach ($name as $n) {
if (empty($n)) {
continue;
}
if (empty($str)) {
$str = $n;
}
else {
$str .= $delim . $n;
}
}
}
else {
if (empty($str)) {
$str = $name;
}
else {
$str .= $delim . $name;
}
}
}
/**
* Sets the size property of a textfield.
*
* @param string $fieldXML
*
* @return null|string
*/
protected function getSize($fieldXML) {
// Extract from <size> tag if supplied
if (!empty($fieldXML->html) && $this->value('size', $fieldXML->html)) {
return $this->value('size', $fieldXML->html);
}
// Infer from <length> tag if <size> was not explicitly set or was invalid
// This map is slightly different from CRM_Core_Form_Renderer::$_sizeMapper
// Because we usually want fields to render as smaller than their maxlength
$sizes = array(
2 => 'TWO',
4 => 'FOUR',
6 => 'SIX',
8 => 'EIGHT',
16 => 'TWELVE',
32 => 'MEDIUM',
64 => 'BIG',
);
foreach ($sizes as $length => $name) {
if ($fieldXML->length <= $length) {
return "CRM_Utils_Type::$name";
}
}
return 'CRM_Utils_Type::HUGE';
}
}

View file

@ -0,0 +1,28 @@
<?php
/**
* Generate files used during testing.
*/
class CRM_Core_CodeGen_Test extends CRM_Core_CodeGen_BaseTask {
public function run() {
$this->generateCiviTestTruncate();
}
public function generateCiviTestTruncate() {
echo "Generating tests truncate file\n";
# TODO template
$truncate = '<?xml version="1.0" encoding="UTF-8" ?>
<!-- Truncate all tables that will be used in the tests -->
<dataset>';
$tbls = array_keys($this->tables);
foreach ($tbls as $d => $t) {
$truncate = $truncate . "\n <$t />\n";
}
$truncate = $truncate . "</dataset>\n";
file_put_contents($this->config->sqlCodePath . "../tests/phpunit/CiviTest/truncate.xml", $truncate);
unset($truncate);
}
}

View file

@ -0,0 +1,97 @@
<?php
/**
* Class CRM_Core_CodeGen_Util_File
*/
class CRM_Core_CodeGen_Util_File {
/**
* @param $dir
* @param int $perm
*/
public static function createDir($dir, $perm = 0755) {
if (!is_dir($dir)) {
mkdir($dir, $perm, TRUE);
}
}
/**
* @param $dir
*/
public static function cleanTempDir($dir) {
foreach (glob("$dir/*") as $tempFile) {
unlink($tempFile);
}
rmdir($dir);
if (preg_match(':^(.*)\.d$:', $dir, $matches)) {
if (file_exists($matches[1])) {
unlink($matches[1]);
}
}
}
/**
* @param $prefix
*
* @return string
*/
public static function createTempDir($prefix) {
$newTempDir = tempnam(sys_get_temp_dir(), $prefix) . '.d';
if (file_exists($newTempDir)) {
self::removeDir($newTempDir);
}
self::createDir($newTempDir);
return $newTempDir;
}
/**
* Calculate a cumulative digest based on a collection of files.
*
* @param array $files
* List of file names (strings).
* @param callable|string $digest a one-way hash function (string => string)
*
* @return string
*/
public static function digestAll($files, $digest = 'md5') {
$buffer = '';
foreach ($files as $file) {
$buffer .= $digest(file_get_contents($file));
}
return $digest($buffer);
}
/**
* Find the path to the main Civi source tree.
*
* @return string
* @throws RuntimeException
*/
public static function findCoreSourceDir() {
$path = str_replace(DIRECTORY_SEPARATOR, '/', __DIR__);
if (!preg_match(':(.*)/CRM/Core/CodeGen/Util:', $path, $matches)) {
throw new RuntimeException("Failed to determine path of code-gen");
}
return $matches[1];
}
/**
* Find files in several directories using several filename patterns.
*
* @param array $pairs
* Each item is an array(0 => $searchBaseDir, 1 => $filePattern).
* @return array
* Array of file paths
*/
public static function findManyFiles($pairs) {
$files = array();
foreach ($pairs as $pair) {
list ($dir, $pattern) = $pair;
$files = array_merge($files, CRM_Utils_File::findFiles($dir, $pattern));
}
sort($files);
return $files;
}
}

View file

@ -0,0 +1,65 @@
<?php
/**
* Class CRM_Core_CodeGen_Util_Smarty
*/
class CRM_Core_CodeGen_Util_Smarty {
/**
* @var CRM_Core_CodeGen_Util_Smarty
*/
private static $singleton;
/**
* @return CRM_Core_CodeGen_Util_Smarty
*/
public static function singleton() {
if (self::$singleton === NULL) {
self::$singleton = new CRM_Core_CodeGen_Util_Smarty();
}
return self::$singleton;
}
private $compileDir;
public function __destruct() {
if ($this->compileDir) {
CRM_Core_CodeGen_Util_File::cleanTempDir($this->compileDir);
}
}
/**
* Get templates_c directory.
*
* @return string
*/
public function getCompileDir() {
if ($this->compileDir === NULL) {
$this->compileDir = CRM_Core_CodeGen_Util_File::createTempDir('templates_c_');
}
return $this->compileDir;
}
/**
* Create a Smarty instance.
*
* @return \Smarty
*/
public function createSmarty() {
$base = dirname(dirname(dirname(dirname(__DIR__))));
require_once 'Smarty/Smarty.class.php';
$smarty = new Smarty();
$smarty->template_dir = "$base/xml/templates";
$smarty->plugins_dir = array("$base/packages/Smarty/plugins", "$base/CRM/Core/Smarty/plugins");
$smarty->compile_dir = $this->getCompileDir();
$smarty->clear_all_cache();
// CRM-5308 / CRM-3507 - we need {localize} to work in the templates
require_once 'CRM/Core/Smarty/plugins/block.localize.php';
$smarty->register_block('localize', 'smarty_block_localize');
return $smarty;
}
}

View file

@ -0,0 +1,92 @@
<?php
/**
* Class CRM_Core_CodeGen_Util_Template
*/
class CRM_Core_CodeGen_Util_Template {
protected $filetype;
protected $smarty;
protected $beautifier;
/**
* @param string $filetype
*/
public function __construct($filetype) {
$this->filetype = $filetype;
$this->smarty = CRM_Core_CodeGen_Util_Smarty::singleton()->createSmarty();
$this->assign('generated', "DO NOT EDIT. Generated by CRM_Core_CodeGen");
if ($this->filetype === 'php') {
require_once 'PHP/Beautifier.php';
// create an instance
$this->beautifier = new PHP_Beautifier();
$this->beautifier->addFilter('ArrayNested');
// add one or more filters
$this->beautifier->addFilter('NewLines', array('after' => 'class, public, require, comment'));
$this->beautifier->setIndentChar(' ');
$this->beautifier->setIndentNumber(2);
$this->beautifier->setNewLine("\n");
}
}
/**
* @param array $inputs
* Template filenames.
* @param string $outpath
* Full path to the desired output file.
*/
public function runConcat($inputs, $outpath) {
if (file_exists($outpath)) {
unlink($outpath);
}
foreach ($inputs as $infile) {
// FIXME: does not beautify. Document.
file_put_contents($outpath, $this->smarty->fetch($infile) . "\n", FILE_APPEND);
}
}
/**
* Run template generator.
*
* @param string $infile
* Filename of the template, without a path.
* @param string $outpath
* Full path to the desired output file.
*/
public function run($infile, $outpath) {
$renderedContents = $this->smarty->fetch($infile);
if ($this->filetype === 'php') {
$this->beautifier->setInputString($renderedContents);
$this->beautifier->setOutputFile($outpath);
$this->beautifier->process();
$this->beautifier->save();
}
else {
file_put_contents($outpath, $renderedContents);
}
}
/**
* Fetch via Smarty.
*
* @param string $infile
*
* @return string
*/
public function fetch($infile) {
return $this->smarty->fetch($infile);
}
/**
* @param $key
* @param $value
*/
public function assign($key, $value) {
$this->smarty->assign_by_ref($key, $value);
}
}

View file

@ -0,0 +1,23 @@
<?php
/**
* Class CRM_Core_CodeGen_Util_Xml
*/
class CRM_Core_CodeGen_Util_Xml {
/**
* @param string $file
* Path to input.
*
* @return SimpleXMLElement|bool
*/
public static function parse($file) {
$dom = new DomDocument();
$xmlString = file_get_contents($file);
$dom->loadXML($xmlString);
$dom->documentURI = $file;
$dom->xinclude();
$xml = simplexml_import_dom($dom);
return $xml;
}
}

View file

@ -0,0 +1,18 @@
<?php
/**
* Generate configuration files
*/
class CRM_Core_CodeGen_Version extends CRM_Core_CodeGen_BaseTask {
public function run() {
echo "Generating civicrm-version file\n";
file_put_contents($this->config->tplCodePath . "/CRM/common/version.tpl", $this->config->db_version);
$template = new CRM_Core_CodeGen_Util_Template('php');
$template->assign('db_version', $this->config->db_version);
$template->assign('cms', ucwords($this->config->cms));
$template->run('civicrm_version.tpl', $this->config->phpCodePath . "civicrm-version.php");
}
}

View file

@ -0,0 +1,240 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* Manage the download, validation, and rendering of community messages
*/
class CRM_Core_CommunityMessages {
const DEFAULT_MESSAGES_URL = 'https://alert.civicrm.org/alert?prot=1&ver={ver}&uf={uf}&sid={sid}&lang={lang}&co={co}';
const DEFAULT_PERMISSION = 'administer CiviCRM';
/**
* Default time to wait before retrying.
*/
const DEFAULT_RETRY = 7200; // 2 hours
/**
* @var CRM_Utils_HttpClient
*/
protected $client;
/**
* @var CRM_Utils_Cache_Interface
*/
protected $cache;
/**
* @var FALSE|string
*/
protected $messagesUrl;
/**
* Create default instance.
*
* @return CRM_Core_CommunityMessages
*/
public static function create() {
return new CRM_Core_CommunityMessages(
Civi::cache('community_messages'),
CRM_Utils_HttpClient::singleton()
);
}
/**
* @param CRM_Utils_Cache_Interface $cache
* @param CRM_Utils_HttpClient $client
* @param null $messagesUrl
*/
public function __construct($cache, $client, $messagesUrl = NULL) {
$this->cache = $cache;
$this->client = $client;
if ($messagesUrl === NULL) {
$this->messagesUrl = Civi::settings()->get('communityMessagesUrl');
}
else {
$this->messagesUrl = $messagesUrl;
}
if ($this->messagesUrl === '*default*') {
$this->messagesUrl = self::DEFAULT_MESSAGES_URL;
}
}
/**
* 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, // ASAP
'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;
}
/**
* Download document from URL and parse as JSON.
*
* @return NULL|array
* parsed JSON
*/
public function fetchDocument() {
list($status, $json) = $this->client->get($this->getRenderedUrl());
if ($status != CRM_Utils_HttpClient::STATUS_OK || empty($json)) {
return NULL;
}
$doc = json_decode($json, TRUE);
if (empty($doc) || json_last_error() != JSON_ERROR_NONE) {
return NULL;
}
return $doc;
}
/**
* Get the final, usable URL string (after interpolating any variables)
*
* @return FALSE|string
*/
public function getRenderedUrl() {
return CRM_Utils_System::evalUrl($this->messagesUrl);
}
/**
* @return bool
*/
public function isEnabled() {
return $this->messagesUrl !== FALSE && $this->messagesUrl !== 'FALSE';
}
/**
* Pick a message to display.
*
* @return NULL|array
*/
public function pick() {
$document = $this->getDocument();
$messages = array();
foreach ($document['messages'] as $message) {
if (!isset($message['perms'])) {
$message['perms'] = array(self::DEFAULT_PERMISSION);
}
if (!CRM_Core_Permission::checkAnyPerm($message['perms'])) {
continue;
}
if (isset($message['components'])) {
$enabled = array_keys(CRM_Core_Component::getEnabledComponents());
if (count(array_intersect($enabled, $message['components'])) == 0) {
continue;
}
}
$messages[] = $message;
}
if (empty($messages)) {
return NULL;
}
$idx = rand(0, count($messages) - 1);
return $messages[$idx];
}
/**
* @param string $markup
* @return string
*/
public static function evalMarkup($markup) {
$config = CRM_Core_Config::singleton();
$vals = array(
'resourceUrl' => rtrim($config->resourceBase, '/'),
'ver' => CRM_Utils_System::version(),
'uf' => $config->userFramework,
'php' => phpversion(),
'sid' => CRM_Utils_System::getSiteID(),
'baseUrl' => $config->userFrameworkBaseURL,
'lang' => $config->lcMessages,
'co' => $config->defaultContactCountry,
);
$vars = array();
foreach ($vals as $k => $v) {
$vars['%%' . $k . '%%'] = $v;
$vars['{{' . $k . '}}'] = urlencode($v);
}
return strtr($markup, $vars);
}
/**
* Ensure that a document is well-formed
*
* @param array $document
* @return bool
*/
public function validateDocument($document) {
if (!isset($document['ttl']) || !is_int($document['ttl'])) {
return FALSE;
}
if (!isset($document['retry']) || !is_int($document['retry'])) {
return FALSE;
}
if (!isset($document['messages']) || !is_array($document['messages'])) {
return FALSE;
}
foreach ($document['messages'] as $message) {
// TODO validate $message['markup']
}
return TRUE;
}
}

View file

@ -0,0 +1,472 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* Component stores all the static and dynamic information of the various
* CiviCRM components
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
class CRM_Core_Component {
/**
* End part (filename) of the component information class'es name
* that needs to be present in components main directory.
*/
const COMPONENT_INFO_CLASS = 'Info';
static $_contactSubTypes = NULL;
/**
* @param bool $force
*
* @return array|null
*/
private static function &_info($force = FALSE) {
if (!isset(Civi::$statics[__CLASS__]['info'])|| $force) {
Civi::$statics[__CLASS__]['info'] = array();
$c = array();
$config = CRM_Core_Config::singleton();
$c = self::getComponents();
foreach ($c as $name => $comp) {
if (in_array($name, $config->enableComponents)) {
Civi::$statics[__CLASS__]['info'][$name] = $comp;
}
}
}
return Civi::$statics[__CLASS__]['info'];
}
/**
* @param string $name
* @param null $attribute
*
* @return mixed
*/
public static function get($name, $attribute = NULL) {
$comp = CRM_Utils_Array::value($name, self::_info());
if ($attribute) {
return CRM_Utils_Array::value($attribute, $comp->info);
}
return $comp;
}
/**
* @param bool $force
*
* @return array
* @throws Exception
*/
public static function &getComponents($force = FALSE) {
if (!isset(Civi::$statics[__CLASS__]['all']) || $force) {
Civi::$statics[__CLASS__]['all'] = array();
$cr = new CRM_Core_DAO_Component();
$cr->find(FALSE);
while ($cr->fetch()) {
$infoClass = $cr->namespace . '_' . self::COMPONENT_INFO_CLASS;
$infoClassFile = str_replace('_', DIRECTORY_SEPARATOR, $infoClass) . '.php';
if (!CRM_Utils_File::isIncludable($infoClassFile)) {
continue;
}
require_once $infoClassFile;
$infoObject = new $infoClass($cr->name, $cr->namespace, $cr->id);
if ($infoObject->info['name'] !== $cr->name) {
CRM_Core_Error::fatal("There is a discrepancy between name in component registry and in info file ({$cr->name}).");
}
Civi::$statics[__CLASS__]['all'][$cr->name] = $infoObject;
unset($infoObject);
}
}
return Civi::$statics[__CLASS__]['all'];
}
/**
* @return array
* Array(string $name => int $id).
*/
public static function &getComponentIDs() {
$componentIDs = array();
$cr = new CRM_Core_DAO_Component();
$cr->find(FALSE);
while ($cr->fetch()) {
$componentIDs[$cr->name] = $cr->id;
}
return $componentIDs;
}
/**
* @param bool $force
*
* @return array|null
*/
static public function &getEnabledComponents($force = FALSE) {
return self::_info($force);
}
static public function flushEnabledComponents() {
self::getEnabledComponents(TRUE);
}
/**
* @param bool $translated
*
* @return array
*/
public static function &getNames($translated = FALSE) {
$allComponents = self::getComponents();
$names = array();
foreach ($allComponents as $name => $comp) {
if ($translated) {
$names[$comp->componentID] = $comp->info['translatedName'];
}
else {
$names[$comp->componentID] = $name;
}
}
return $names;
}
/**
* @param $args
* @param $type
*
* @return bool
*/
public static function invoke(&$args, $type) {
$info = self::_info();
$config = CRM_Core_Config::singleton();
$firstArg = CRM_Utils_Array::value(1, $args, '');
$secondArg = CRM_Utils_Array::value(2, $args, '');
foreach ($info as $name => $comp) {
if (in_array($name, $config->enableComponents) &&
(($comp->info['url'] === $firstArg && $type == 'main') ||
($comp->info['url'] === $secondArg && $type == 'admin')
)
) {
if ($type == 'main') {
// also set the smarty variables to the current component
$template = CRM_Core_Smarty::singleton();
$template->assign('activeComponent', $name);
if (!empty($comp->info[$name]['formTpl'])) {
$template->assign('formTpl', $comp->info[$name]['formTpl']);
}
if (!empty($comp->info[$name]['css'])) {
$styleSheets = '<style type="text/css">@import url(' . "{$config->resourceBase}css/{$comp->info[$name]['css']});</style>";
CRM_Utils_System::addHTMLHead($styleSheet);
}
}
$inv = $comp->getInvokeObject();
$inv->$type($args);
return TRUE;
}
}
return FALSE;
}
/**
* @return array
*/
public static function xmlMenu() {
// lets build the menu for all components
$info = self::getComponents(TRUE);
$files = array();
foreach ($info as $name => $comp) {
$files = array_merge($files,
$comp->menuFiles()
);
}
return $files;
}
/**
* @return array
*/
public static function &menu() {
$info = self::_info();
$items = array();
foreach ($info as $name => $comp) {
$mnu = $comp->getMenuObject();
$ret = $mnu->permissioned();
$items = array_merge($items, $ret);
$ret = $mnu->main($task);
$items = array_merge($items, $ret);
}
return $items;
}
/**
* @param string $componentName
*
* @return mixed
*/
public static function getComponentID($componentName) {
$info = self::_info();
if (!empty($info[$componentName])) {
return $info[$componentName]->componentID;
}
else {
return;
}
}
/**
* @param int $componentID
*
* @return int|null|string
*/
public static function getComponentName($componentID) {
$info = self::_info();
$componentName = NULL;
foreach ($info as $compName => $component) {
if ($component->componentID == $componentID) {
$componentName = $compName;
break;
}
}
return $componentName;
}
/**
* @return array
*/
public static function &getQueryFields($checkPermission = TRUE) {
$info = self::_info();
$fields = array();
foreach ($info as $name => $comp) {
if ($comp->usesSearch()) {
$bqr = $comp->getBAOQueryObject();
$flds = $bqr->getFields($checkPermission);
$fields = array_merge($fields, $flds);
}
}
return $fields;
}
/**
* @param $query
* @param string $fnName
*/
public static function alterQuery(&$query, $fnName) {
$info = self::_info();
foreach ($info as $name => $comp) {
if ($comp->usesSearch()) {
$bqr = $comp->getBAOQueryObject();
$bqr->$fnName($query);
}
}
}
/**
* @param string $fieldName
* @param $mode
* @param $side
*
* @return null
*/
public static function from($fieldName, $mode, $side) {
$info = self::_info();
$from = NULL;
foreach ($info as $name => $comp) {
if ($comp->usesSearch()) {
$bqr = $comp->getBAOQueryObject();
$from = $bqr->from($fieldName, $mode, $side);
if ($from) {
return $from;
}
}
}
return $from;
}
/**
* @param $mode
* @param bool $includeCustomFields
*
* @return null
*/
public static function &defaultReturnProperties(
$mode,
$includeCustomFields = TRUE
) {
$info = self::_info();
$properties = NULL;
foreach ($info as $name => $comp) {
if ($comp->usesSearch()) {
$bqr = $comp->getBAOQueryObject();
$properties = $bqr->defaultReturnProperties($mode, $includeCustomFields);
if ($properties) {
return $properties;
}
}
}
return $properties;
}
/**
* @param CRM_Core_Form $form
*/
public static function &buildSearchForm(&$form) {
$info = self::_info();
foreach ($info as $name => $comp) {
if ($comp->usesSearch()) {
$bqr = $comp->getBAOQueryObject();
$bqr->buildSearchForm($form);
}
}
}
/**
* @param $row
* @param int $id
*/
public static function searchAction(&$row, $id) {
$info = self::_info();
foreach ($info as $name => $comp) {
if ($comp->usesSearch()) {
$bqr = $comp->getBAOQueryObject();
$bqr->searchAction($row, $id);
}
}
}
/**
* @return array|null
*/
public static function &contactSubTypes() {
if (self::$_contactSubTypes == NULL) {
self::$_contactSubTypes = array();
}
return self::$_contactSubTypes;
}
/**
* @param $subType
* @param $op
*
* @return null
*/
public static function &contactSubTypeProperties($subType, $op) {
$properties = self::contactSubTypes();
if (array_key_exists($subType, $properties) &&
array_key_exists($op, $properties[$subType])
) {
return $properties[$subType][$op];
}
return CRM_Core_DAO::$_nullObject;
}
/**
* FIXME: This function does not appear to do anything. The is_array() check runs on a bunch of objects and (always?) returns false
*/
public static function &taskList() {
$info = self::_info();
$tasks = array();
foreach ($info as $name => $value) {
if (is_array($info[$name]) && isset($info[$name]['task'])) {
$tasks += $info[$name]['task'];
}
}
return $tasks;
}
/**
* Handle table dependencies of components.
*
* @param array $tables
* Array of tables.
*
*/
public static function tableNames(&$tables) {
$info = self::_info();
foreach ($info as $name => $comp) {
if ($comp->usesSearch()) {
$bqr = $comp->getBAOQueryObject();
$bqr->tableNames($tables);
}
}
}
/**
* Get components info from info file.
*
* @param string $crmFolderDir
*
* @return array
*/
public static function getComponentsFromFile($crmFolderDir) {
$components = array();
//traverse CRM folder and check for Info file
if (is_dir($crmFolderDir) && $dir = opendir($crmFolderDir)) {
while ($subDir = readdir($dir)) {
// skip the extensions diretory since it has an Info.php file also
if ($subDir == 'Extension') {
continue;
}
$infoFile = $crmFolderDir . "/{$subDir}/" . self::COMPONENT_INFO_CLASS . '.php';
if (file_exists($infoFile)) {
$infoClass = 'CRM_' . $subDir . '_' . self::COMPONENT_INFO_CLASS;
require_once str_replace('_', DIRECTORY_SEPARATOR, $infoClass) . '.php';
$infoObject = new $infoClass(NULL, NULL, NULL);
$components[$infoObject->info['name']] = $infoObject;
unset($infoObject);
}
}
}
return $components;
}
}

View file

@ -0,0 +1,366 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This interface defines methods that need to be implemented
* for a component to introduce itself to the system.
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
abstract class CRM_Core_Component_Info {
/**
* Name of the class (minus component namespace path)
* of the component invocation class'es name.
*/
const COMPONENT_INVOKE_CLASS = 'Invoke';
/**
* Name of the class (minus component namespace path)
* of the component BAO Query class'es name.
*/
const COMPONENT_BAO_QUERY_CLASS = 'BAO_Query';
/**
* Name of the class (minus component namespace path)
* of the component user dashboard plugin.
*/
const COMPONENT_USERDASHBOARD_CLASS = 'Page_UserDashboard';
/**
* Name of the class (minus component namespace path)
* of the component tab offered to contact record view.
*/
const COMPONENT_TAB_CLASS = 'Page_Tab';
/**
* Name of the class (minus component namespace path)
* of the component tab offered to contact record view.
*/
const COMPONENT_ADVSEARCHPANE_CLASS = 'Form_Search_AdvancedSearchPane';
/**
* Name of the directory (assumed in component directory)
* where xml resources used by this component live.
*/
const COMPONENT_XML_RESOURCES = 'xml';
/**
* Name of the directory (assumed in xml resources path)
* containing component menu definition XML file names.
*/
const COMPONENT_MENU_XML = 'Menu';
/**
* Stores component information.
* @var array component settings as key/value pairs
*/
public $info;
/**
* Stores component keyword.
* @var string name of component keyword
*/
protected $keyword;
/**
* @param string $name
* Name of the component.
* @param string $namespace
* Namespace prefix for component's files.
* @param int $componentID
*/
public function __construct($name, $namespace, $componentID) {
$this->name = $name;
$this->namespace = $namespace;
$this->componentID = $componentID;
$this->info = $this->getInfo();
$this->info['url'] = $this->getKeyword();
}
/**
* EXPERIMENTAL: Get a list of AngularJS modules
*
* @return array
* list of modules; same format as CRM_Utils_Hook::angularModules(&$angularModules)
* @see CRM_Utils_Hook::angularModules
*/
public function getAngularModules() {
return array();
}
/**
* Provides base information about the component.
* Needs to be implemented in component's information
* class.
*
* @return array
* collection of required component settings
*/
abstract public function getInfo();
/**
* Get a list of entities to register via API.
*
* @return array
* list of entities; same format as CRM_Utils_Hook::managedEntities(&$entities)
* @see CRM_Utils_Hook::managedEntities
*/
public function getManagedEntities() {
return array();
}
/**
* Provides permissions that are unwise for Anonymous Roles to have.
*
* @return array
* list of permissions
* @see CRM_Component_Info::getPermissions
*/
public function getAnonymousPermissionWarnings() {
return array();
}
/**
* Provides permissions that are used by component.
* Needs to be implemented in component's information
* class.
*
* NOTE: if using conditionally permission return,
* implementation of $getAllUnconditionally is required.
*
* @param bool $getAllUnconditionally
*
* @return array|null
* collection of permissions, null if none
*/
abstract public function getPermissions($getAllUnconditionally = FALSE);
/**
* Determine how many other records refer to a given record.
*
* @param CRM_Core_DAO $dao
* The item for which we want a reference count.
* @return array
* each item in the array is an array with keys:
* - name: string, eg "sql:civicrm_email:contact_id"
* - type: string, eg "sql"
* - count: int, eg "5" if there are 5 email addresses that refer to $dao
*/
public function getReferenceCounts($dao) {
return array();
}
/**
* Provides information about user dashboard element.
* offered by this component.
*
* @return array|null
* collection of required dashboard settings,
* null if no element offered
*/
abstract public function getUserDashboardElement();
/**
* Provides information about user dashboard element.
* offered by this component.
*
* @return array|null
* collection of required dashboard settings,
* null if no element offered
*/
abstract public function registerTab();
/**
* Provides information about advanced search pane
* offered by this component.
*
* @return array|null
* collection of required pane settings,
* null if no element offered
*/
abstract public function registerAdvancedSearchPane();
/**
* Provides potential activity types that this
* component might want to register in activity history.
* Needs to be implemented in component's information
* class.
*
* @return array|null
* collection of activity types
*/
abstract public function getActivityTypes();
/**
* Provides information whether given component is currently
* marked as enabled in configuration.
*
* @return bool
* true if component is enabled, false if not
*/
public function isEnabled() {
$config = CRM_Core_Config::singleton();
if (in_array($this->info['name'], $config->enableComponents)) {
return TRUE;
}
return FALSE;
}
/**
* Provides component's menu definition object.
*
* @return mixed
* component's menu definition object
*/
public function getMenuObject() {
return $this->_instantiate(self::COMPONENT_MENU_CLASS);
}
/**
* Provides component's invocation object.
*
* @return mixed
* component's invocation object
*/
public function getInvokeObject() {
return $this->_instantiate(self::COMPONENT_INVOKE_CLASS);
}
/**
* Provides component's BAO Query object.
*
* @return mixed
* component's BAO Query object
*/
public function getBAOQueryObject() {
return $this->_instantiate(self::COMPONENT_BAO_QUERY_CLASS);
}
/**
* Builds advanced search form's component specific pane.
*
* @param CRM_Core_Form $form
*/
public function buildAdvancedSearchPaneForm(&$form) {
$bao = $this->getBAOQueryObject();
$bao->buildSearchForm($form);
}
/**
* Provides component's user dashboard page object.
*
* @return mixed
* component's User Dashboard applet object
*/
public function getUserDashboardObject() {
return $this->_instantiate(self::COMPONENT_USERDASHBOARD_CLASS);
}
/**
* Provides component's contact record tab object.
*
* @return mixed
* component's contact record tab object
*/
public function getTabObject() {
return $this->_instantiate(self::COMPONENT_TAB_CLASS);
}
/**
* Provides component's advanced search pane's template path.
*
* @return string
* component's advanced search pane's template path
*/
public function getAdvancedSearchPaneTemplatePath() {
$fullpath = $this->namespace . '_' . self::COMPONENT_ADVSEARCHPANE_CLASS;
return str_replace('_', DIRECTORY_SEPARATOR, $fullpath . '.tpl');
}
/**
* Provides information whether given component uses system wide search.
*
* @return bool
* true if component needs search integration
*/
public function usesSearch() {
return $this->info['search'] ? TRUE : FALSE;
}
/**
* Provides the xml menu files.
*
* @return array
* array of menu files
*/
public function menuFiles() {
return CRM_Utils_File::getFilesByExtension($this->_getMenuXMLPath(), 'xml');
}
/**
* Simple "keyword" getter.
* FIXME: It should be protected so the keyword is not
* FIXME: accessed from beyond component infrastructure.
*
* @return string
* component keyword
*/
public function getKeyword() {
return $this->keyword;
}
/**
* Helper for figuring out menu XML file location.
*
* @return mixed
* component's element as class instance
*/
private function _getMenuXMLPath() {
global $civicrm_root;
$fullpath = $this->namespace . '_' . self::COMPONENT_XML_RESOURCES . '_' . self::COMPONENT_MENU_XML;
return CRM_Utils_File::addTrailingSlash($civicrm_root . DIRECTORY_SEPARATOR . str_replace('_', DIRECTORY_SEPARATOR, $fullpath));
}
/**
* Helper for instantiating component's elements.
*
* @param $cl
*
* @return mixed
* component's element as class instance
*/
private function _instantiate($cl) {
$className = $this->namespace . '_' . $cl;
require_once str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
return new $className();
}
}

View file

@ -0,0 +1,591 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* Config handles all the run time configuration changes that the system needs to deal with.
*
* Typically we'll have different values for a user's sandbox, a qa sandbox and a production area.
* The default values in general, should reflect production values (minimizes chances of screwing up)
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
require_once 'Log.php';
require_once 'Mail.php';
require_once 'api/api.php';
/**
* Class CRM_Core_Config
*
* @property CRM_Utils_System_Base $userSystem
* @property CRM_Core_Permission_Base $userPermissionClass
* @property array $enableComponents
* @property array $languageLimit
* @property bool $debug
* @property bool $doNotResetCache
* @property string $maxFileSize
* @property string $defaultCurrency
* @property string $defaultCurrencySymbol
* @property string $lcMessages
* @property string $fieldSeparator
* @property string $userFramework
* @property string $verpSeparator
* @property string $dateFormatFull
* @property string $resourceBase
* @property string $dsn
* @property string $customTemplateDir
* @property string $defaultContactCountry
* @property string $defaultContactStateProvince
* @property string $monetaryDecimalPoint
* @property string $monetaryThousandSeparator
*/
class CRM_Core_Config extends CRM_Core_Config_MagicMerge {
/**
* The handle to the log that we are using
* @var object
*/
private static $_log = NULL;
/**
* We only need one instance of this object. So we use the singleton
* pattern and cache the instance in this variable
*
* @var CRM_Core_Config
*/
private static $_singleton = NULL;
/**
* The constructor. Sets domain id if defined, otherwise assumes
* single instance installation.
*/
public function __construct() {
parent::__construct();
}
/**
* Singleton function used to manage this object.
*
* @param bool $loadFromDB
* whether to load from the database.
* @param bool $force
* whether to force a reconstruction.
*
* @return CRM_Core_Config
*/
public static function &singleton($loadFromDB = TRUE, $force = FALSE) {
if (self::$_singleton === NULL || $force) {
$GLOBALS['civicrm_default_error_scope'] = CRM_Core_TemporaryErrorScope::create(array('CRM_Core_Error', 'handle'));
$errorScope = CRM_Core_TemporaryErrorScope::create(array('CRM_Core_Error', 'simpleHandler'));
if (defined('E_DEPRECATED')) {
error_reporting(error_reporting() & ~E_DEPRECATED);
}
self::$_singleton = new CRM_Core_Config();
\Civi\Core\Container::boot($loadFromDB);
if ($loadFromDB && self::$_singleton->dsn) {
$domain = \CRM_Core_BAO_Domain::getDomain();
\CRM_Core_BAO_ConfigSetting::applyLocale(\Civi::settings($domain->id), $domain->locales);
unset($errorScope);
CRM_Utils_Hook::config(self::$_singleton);
self::$_singleton->authenticate();
// Extreme backward compat: $config binds to active domain at moment of setup.
self::$_singleton->getSettings();
Civi::service('settings_manager')->useDefaults();
self::$_singleton->handleFirstRun();
}
}
return self::$_singleton;
}
/**
* Returns the singleton logger for the application.
*
* @deprecated
* @return object
* @see Civi::log()
*/
static public function &getLog() {
if (!isset(self::$_log)) {
self::$_log = Log::singleton('display');
}
return self::$_log;
}
/**
* Retrieve a mailer to send any mail from the application.
*
* @return Mail
* @deprecated
* @see Civi::service()
*/
public static function getMailer() {
return Civi::service('pear_mail');
}
/**
* Deletes the web server writable directories.
*
* @param int $value
* 1: clean templates_c, 2: clean upload, 3: clean both
* @param bool $rmdir
*/
public function cleanup($value, $rmdir = TRUE) {
$value = (int ) $value;
if ($value & 1) {
// clean templates_c
CRM_Utils_File::cleanDir($this->templateCompileDir, $rmdir);
CRM_Utils_File::createDir($this->templateCompileDir);
}
if ($value & 2) {
// clean upload dir
CRM_Utils_File::cleanDir($this->uploadDir);
CRM_Utils_File::createDir($this->uploadDir);
}
// Whether we delete/create or simply preserve directories, we should
// certainly make sure the restrictions are enforced.
foreach (array(
$this->templateCompileDir,
$this->uploadDir,
$this->configAndLogDir,
$this->customFileUploadDir,
) as $dir) {
if ($dir && is_dir($dir)) {
CRM_Utils_File::restrictAccess($dir);
}
}
}
/**
* Verify that the needed parameters are not null in the config.
*
* @param CRM_Core_Config $config (reference) the system config object
* @param array $required (reference) the parameters that need a value
*
* @return bool
*/
public static function check(&$config, &$required) {
foreach ($required as $name) {
if (CRM_Utils_System::isNull($config->$name)) {
return FALSE;
}
}
return TRUE;
}
/**
* Reset the serialized array and recompute.
* use with care
*/
public function reset() {
$query = "UPDATE civicrm_domain SET config_backend = null";
CRM_Core_DAO::executeQuery($query);
}
/**
* This method should initialize auth sources.
*/
public function authenticate() {
// make sure session is always initialised
$session = CRM_Core_Session::singleton();
// for logging purposes, pass the userID to the db
$userID = $session->get('userID');
if ($userID) {
CRM_Core_DAO::executeQuery('SET @civicrm_user_id = %1',
array(1 => array($userID, 'Integer'))
);
}
if ($session->get('userID') && !$session->get('authSrc')) {
$session->set('authSrc', CRM_Core_Permission::AUTH_SRC_LOGIN);
}
// checksum source
CRM_Contact_BAO_Contact_Permission::initChecksumAuthSrc();
}
/**
* One function to get domain ID.
*
* @param int $domainID
* @param bool $reset
*
* @return int|null
*/
public static function domainID($domainID = NULL, $reset = FALSE) {
static $domain;
if ($domainID) {
$domain = $domainID;
}
if ($reset || empty($domain)) {
$domain = defined('CIVICRM_DOMAIN_ID') ? CIVICRM_DOMAIN_ID : 1;
}
return $domain;
}
/**
* Function to get environment.
*
* @param string $env
* @param bool $reset
*
* @return string
*/
public static function environment($env = NULL, $reset = FALSE) {
static $environment;
if ($env) {
$environment = $env;
}
if ($reset || empty($environment)) {
$environment = Civi::settings()->get('environment');
}
if (!$environment) {
$environment = 'Production';
}
return $environment;
}
/**
* Do general cleanup of caches, temp directories and temp tables
* CRM-8739
*
* @param bool $sessionReset
*/
public function cleanupCaches($sessionReset = TRUE) {
// cleanup templates_c directory
$this->cleanup(1, FALSE);
// clear all caches
self::clearDBCache();
CRM_Utils_System::flushCache();
if ($sessionReset) {
$session = CRM_Core_Session::singleton();
$session->reset(2);
}
}
/**
* Do general cleanup of module permissions.
*/
public function cleanupPermissions() {
$module_files = CRM_Extension_System::singleton()->getMapper()->getActiveModuleFiles();
if ($this->userPermissionClass->isModulePermissionSupported()) {
// Can store permissions -- so do it!
$this->userPermissionClass->upgradePermissions(
CRM_Core_Permission::basicPermissions()
);
}
else {
// Cannot store permissions -- warn if any modules require them
$modules_with_perms = array();
foreach ($module_files as $module_file) {
$perms = $this->userPermissionClass->getModulePermissions($module_file['prefix']);
if (!empty($perms)) {
$modules_with_perms[] = $module_file['prefix'];
}
}
if (!empty($modules_with_perms)) {
CRM_Core_Session::setStatus(
ts('Some modules define permissions, but the CMS cannot store them: %1', array(1 => implode(', ', $modules_with_perms))),
ts('Permission Error'),
'error'
);
}
}
}
/**
* Flush information about loaded modules.
*/
public function clearModuleList() {
CRM_Extension_System::singleton()->getCache()->flush();
CRM_Utils_Hook::singleton(TRUE);
CRM_Core_PseudoConstant::getModuleExtensions(TRUE);
CRM_Core_Module::getAll(TRUE);
}
/**
* Clear db cache.
*/
public static function clearDBCache() {
$queries = array(
'TRUNCATE TABLE civicrm_acl_cache',
'TRUNCATE TABLE civicrm_acl_contact_cache',
'TRUNCATE TABLE civicrm_cache',
'TRUNCATE TABLE civicrm_prevnext_cache',
'UPDATE civicrm_group SET cache_date = NULL',
'TRUNCATE TABLE civicrm_group_contact_cache',
'TRUNCATE TABLE civicrm_menu',
'UPDATE civicrm_setting SET value = NULL WHERE name="navigation" AND contact_id IS NOT NULL',
'DELETE FROM civicrm_setting WHERE name="modulePaths"', // CRM-10543
);
foreach ($queries as $query) {
CRM_Core_DAO::executeQuery($query);
}
// also delete all the import and export temp tables
self::clearTempTables();
}
/**
* Clear leftover temporary tables.
*
* This is called on upgrade, during tests and site move, from the cron and via clear caches in the UI.
*
* Currently the UI clear caches does not pass a time interval - which may need review as it does risk
* ripping the tables out from underneath a current action. This was considered but
* out-of-scope for CRM-16167
*
* @param string|bool $timeInterval
* Optional time interval for mysql date function.g '2 day'. This can be used to prevent
* tables created recently from being deleted.
*/
public static function clearTempTables($timeInterval = FALSE) {
$dao = new CRM_Core_DAO();
$query = "
SELECT TABLE_NAME as tableName
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = %1
AND (
TABLE_NAME LIKE 'civicrm_import_job_%'
OR TABLE_NAME LIKE 'civicrm_export_temp%'
OR TABLE_NAME LIKE 'civicrm_task_action_temp%'
OR TABLE_NAME LIKE 'civicrm_report_temp%'
)
";
if ($timeInterval) {
$query .= " AND CREATE_TIME < DATE_SUB(NOW(), INTERVAL {$timeInterval})";
}
$tableDAO = CRM_Core_DAO::executeQuery($query, array(1 => array($dao->database(), 'String')));
$tables = array();
while ($tableDAO->fetch()) {
$tables[] = $tableDAO->tableName;
}
if (!empty($tables)) {
$table = implode(',', $tables);
// drop leftover temporary tables
CRM_Core_DAO::executeQuery("DROP TABLE $table");
}
}
/**
* Check if running in upgrade mode.
*
* @param string $path
*
* @return bool
*/
public static function isUpgradeMode($path = NULL) {
if (defined('CIVICRM_UPGRADE_ACTIVE')) {
return TRUE;
}
if (!$path) {
// note: do not re-initialize config here, since this function is part of
// config initialization itself
$urlVar = 'q';
if (defined('CIVICRM_UF') && CIVICRM_UF == 'Joomla') {
$urlVar = 'task';
}
$path = CRM_Utils_Array::value($urlVar, $_GET);
}
if ($path && preg_match('/^civicrm\/upgrade(\/.*)?$/', $path)) {
return TRUE;
}
if ($path && preg_match('/^civicrm\/ajax\/l10n-js/', $path)
&& !empty($_SERVER['HTTP_REFERER'])
) {
$ref = parse_url($_SERVER['HTTP_REFERER']);
if (
(!empty($ref['path']) && preg_match('/civicrm\/upgrade/', $ref['path'])) ||
(!empty($ref['query']) && preg_match('/civicrm\/upgrade/', urldecode($ref['query'])))
) {
return TRUE;
}
}
return FALSE;
}
/**
* Is back office credit card processing enabled for this site - ie are there any installed processors that support
* it?
* This function is used for determining whether to show the submit credit card link, not for determining which processors to show, hence
* it is a config var
* @return bool
*/
public static function isEnabledBackOfficeCreditCardPayments() {
return CRM_Financial_BAO_PaymentProcessor::hasPaymentProcessorSupporting(array('BackOffice'));
}
/**
* @deprecated
*/
public function addressSequence() {
return CRM_Utils_Address::sequence(Civi::settings()->get('address_format'));
}
/**
* @deprecated
*/
public function defaultContactCountry() {
return CRM_Core_BAO_Country::defaultContactCountry();
}
/**
* @deprecated
*/
public function defaultContactCountryName() {
return CRM_Core_BAO_Country::defaultContactCountryName();
}
/**
* @deprecated
*
* @param string $defaultCurrency
*
* @return string
*/
public function defaultCurrencySymbol($defaultCurrency = NULL) {
return CRM_Core_BAO_Country::defaultCurrencySymbol($defaultCurrency);
}
/**
* Resets the singleton, so that the next call to CRM_Core_Config::singleton()
* reloads completely.
*
* While normally we could call the singleton function with $force = TRUE,
* this function addresses a very specific use-case in the CiviCRM installer,
* where we cannot yet force a reload, but we want to make sure that the next
* call to this object gets a fresh start (ex: to initialize the DAO).
*/
public function free() {
self::$_singleton = NULL;
}
/**
* Conditionally fire an event during the first page run.
*
* The install system is currently implemented several times, so it's hard to add
* new installation logic. We use a makeshift method to detect the first run.
*
* Situations to test:
* - New installation
* - Upgrade from an old version (predating first-run tracker)
* - Upgrade from an old version (with first-run tracking)
*/
public function handleFirstRun() {
// Ordinarily, we prefetch settings en masse and find that the system is already installed.
// No extra SQL queries required.
if (Civi::settings()->get('installed')) {
return;
}
// Q: How should this behave during testing?
if (defined('CIVICRM_TEST')) {
return;
}
// If schema hasn't been loaded yet, then do nothing. Don't want to interfere
// with the existing installers. NOTE: If we change the installer pageflow,
// then we may want to modify this behavior.
if (!CRM_Core_DAO::checkTableExists('civicrm_domain')) {
return;
}
// If we're handling an upgrade, then the system has already been used, so this
// is not the first run.
if (CRM_Core_Config::isUpgradeMode()) {
return;
}
$dao = CRM_Core_DAO::executeQuery('SELECT version FROM civicrm_domain');
while ($dao->fetch()) {
if ($dao->version && version_compare($dao->version, CRM_Utils_System::version(), '<')) {
return;
}
}
// The installation flag is stored in civicrm_setting, which is domain-aware. The
// flag could have been stored under a different domain.
$dao = CRM_Core_DAO::executeQuery('
SELECT domain_id, value FROM civicrm_setting
WHERE is_domain = 1 AND name = "installed"
');
while ($dao->fetch()) {
$value = unserialize($dao->value);
if (!empty($value)) {
Civi::settings()->set('installed', 1);
return;
}
}
// OK, this looks new.
Civi::service('dispatcher')->dispatch(\Civi\Core\Event\SystemInstallEvent::EVENT_NAME, new \Civi\Core\Event\SystemInstallEvent());
Civi::settings()->set('installed', 1);
}
/**
* Is the system permitted to flush caches at the moment.
*/
static public function isPermitCacheFlushMode() {
return !CRM_Core_Config::singleton()->doNotResetCache;
}
/**
* Set cache clearing to enabled or disabled.
*
* This might be enabled at the start of a long running process
* such as an import in order to delay clearing caches until the end.
*
* @param bool $enabled
* If true then caches can be cleared at this time.
*/
static public function setPermitCacheFlushMode($enabled) {
CRM_Core_Config::singleton()->doNotResetCache = $enabled ? 0 : 1;
}
}

View file

@ -0,0 +1,417 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* Class CRM_Core_Config_MagicMerge
*
* Originally, the $config object was based on a single, serialized
* data object stored in the database. As the needs for settings
* grew (with robust metadata, system overrides, extension support,
* and multi-tenancy), the $config started to store a mix of:
* (a) canonical config options,
* (b) dynamically generated runtime data,
* (c) cached data derived from other sources (esp civicrm_setting)
* (d) instances of service objects
*
* The config object is now deprecated. Settings and service objects
* should generally be accessed via Civi::settings() and Civi::service().
*
* MagicMerge provides backward compatibility. You may still access
* old properties via $config, but they will be loaded from their
* new services.
*/
class CRM_Core_Config_MagicMerge {
/**
* Map old config properties to their contemporary counterparts.
*
* @var array
* Array(string $configAlias => Array(string $realType, string $realName)).
*/
private $map;
private $locals, $settings;
private $cache = array();
/**
* CRM_Core_Config_MagicMerge constructor.
*/
public function __construct() {
$this->map = self::getPropertyMap();
}
/**
* Set the map to the property map.
*/
public function __wakeup() {
$this->map = self::getPropertyMap();
}
/**
* Get a list of $config properties and the entities to which they map.
*
* This is used for two purposes:
*
* 1. Runtime: Provide backward-compatible interface for reading these
* properties.
* 2. Upgrade: Migrate old properties of config_backend into settings.
*
* @return array
*/
public static function getPropertyMap() {
// Each mapping: $propertyName => Array(0 => $type, 1 => $foreignName|NULL, ...).
// If $foreignName is omitted/null, then it's assumed to match the $propertyName.
// Other parameters may be specified, depending on the type.
return array(
// "local" properties are unique to each instance of CRM_Core_Config (each request).
'doNotResetCache' => array('local'),
'inCiviCRM' => array('local'),
'keyDisable' => array('local'),
'userFrameworkFrontend' => array('local'),
'userPermissionTemp' => array('local'),
// "runtime" properties are computed from define()s, $_ENV, etc.
// See also: CRM_Core_Config_Runtime.
'dsn' => array('runtime'),
'initialized' => array('runtime'),
'userFramework' => array('runtime'),
'userFrameworkClass' => array('runtime'),
'userFrameworkDSN' => array('runtime'),
'userFrameworkURLVar' => array('runtime'),
'userHookClass' => array('runtime'),
'cleanURL' => array('runtime'),
'configAndLogDir' => array('runtime'),
'templateCompileDir' => array('runtime'),
'templateDir' => array('runtime'),
// "boot-svc" properties are critical services needed during init.
// See also: Civi\Core\Container::getBootService().
'userSystem' => array('boot-svc'),
'userPermissionClass' => array('boot-svc'),
'userFrameworkBaseURL' => array('user-system', 'getAbsoluteBaseURL'),
'userFrameworkVersion' => array('user-system', 'getVersion'),
'useFrameworkRelativeBase' => array('user-system', 'getRelativeBaseURL'), // ugh typo.
// "setting" properties are loaded through the setting layer, esp
// table "civicrm_setting" and global $civicrm_setting.
// See also: Civi::settings().
'backtrace' => array('setting'),
'contact_default_language' => array('setting'),
'countryLimit' => array('setting'),
'customTranslateFunction' => array('setting'),
'dateInputFormat' => array('setting'),
'dateformatDatetime' => array('setting'),
'dateformatFull' => array('setting'),
'dateformatPartial' => array('setting'),
'dateformatTime' => array('setting'),
'dateformatYear' => array('setting'),
'dateformatFinancialBatch' => array('setting'),
'dateformatshortdate' => array('setting'),
'debug' => array('setting', 'debug_enabled'), // renamed.
'defaultContactCountry' => array('setting'),
'defaultContactStateProvince' => array('setting'),
'defaultCurrency' => array('setting'),
'defaultSearchProfileID' => array('setting'),
'doNotAttachPDFReceipt' => array('setting'),
'empoweredBy' => array('setting'),
'enableComponents' => array('setting', 'enable_components'), // renamed.
'enableSSL' => array('setting'),
'fatalErrorHandler' => array('setting'),
'fieldSeparator' => array('setting'),
'fiscalYearStart' => array('setting'),
'geoAPIKey' => array('setting'),
'geoProvider' => array('setting'),
'includeAlphabeticalPager' => array('setting'),
'includeEmailInName' => array('setting'),
'includeNickNameInName' => array('setting'),
'includeOrderByClause' => array('setting'),
'includeWildCardInName' => array('setting'),
'inheritLocale' => array('setting'),
'languageLimit' => array('setting'),
'lcMessages' => array('setting'),
'legacyEncoding' => array('setting'),
'logging' => array('setting'),
'mailThrottleTime' => array('setting'),
'mailerBatchLimit' => array('setting'),
'mailerJobSize' => array('setting'),
'mailerJobsMax' => array('setting'),
'mapAPIKey' => array('setting'),
'mapProvider' => array('setting'),
'maxFileSize' => array('setting'),
'maxAttachments' => array('setting', 'max_attachments'), // renamed.
'monetaryDecimalPoint' => array('setting'),
'monetaryThousandSeparator' => array('setting'),
'moneyformat' => array('setting'),
'moneyvalueformat' => array('setting'),
'provinceLimit' => array('setting'),
'recaptchaOptions' => array('setting'),
'recaptchaPublicKey' => array('setting'),
'recaptchaPrivateKey' => array('setting'),
'replyTo' => array('setting'),
'secondDegRelPermissions' => array('setting'),
'smartGroupCacheTimeout' => array('setting'),
'timeInputFormat' => array('setting'),
'userFrameworkLogging' => array('setting'),
'userFrameworkUsersTableName' => array('setting'),
'verpSeparator' => array('setting'),
'wkhtmltopdfPath' => array('setting'),
'wpBasePage' => array('setting'),
'wpLoadPhp' => array('setting'),
// "setting-path" properties are settings with special filtering
// to return normalized file paths.
// Option: `mkdir` - auto-create dir
// Option: `restrict` - auto-restrict remote access
'customFileUploadDir' => array('setting-path', NULL, array('mkdir', 'restrict')),
'customPHPPathDir' => array('setting-path'),
'customTemplateDir' => array('setting-path'),
'extensionsDir' => array('setting-path', NULL, array('mkdir')),
'imageUploadDir' => array('setting-path', NULL, array('mkdir')),
'uploadDir' => array('setting-path', NULL, array('mkdir', 'restrict')),
// "setting-url" properties are settings with special filtering
// to return normalized URLs.
// Option: `noslash` - don't append trailing slash
// Option: `rel` - convert to relative URL (if possible)
'customCSSURL' => array('setting-url', NULL, array('noslash')),
'extensionsURL' => array('setting-url'),
'imageUploadURL' => array('setting-url'),
'resourceBase' => array('setting-url', 'userFrameworkResourceURL', array('rel')),
'userFrameworkResourceURL' => array('setting-url'),
// "callback" properties are generated on-demand by calling a function.
'geocodeMethod' => array('callback', 'CRM_Utils_Geocode', 'getProviderClass'),
'defaultCurrencySymbol' => array('callback', 'CRM_Core_BAO_Country', 'getDefaultCurrencySymbol'),
);
}
/**
* Get value.
*
* @param string $k
*
* @return mixed
* @throws \CRM_Core_Exception
*/
public function __get($k) {
if (!isset($this->map[$k])) {
throw new \CRM_Core_Exception("Cannot read unrecognized property CRM_Core_Config::\${$k}.");
}
if (isset($this->cache[$k])) {
return $this->cache[$k];
}
$type = $this->map[$k][0];
$name = isset($this->map[$k][1]) ? $this->map[$k][1] : $k;
switch ($type) {
case 'setting':
return $this->getSettings()->get($name);
case 'setting-path':
// Array(0 => $type, 1 => $setting, 2 => $actions).
$value = $this->getSettings()->get($name);
$value = Civi::paths()->getPath($value);
if ($value) {
$value = CRM_Utils_File::addTrailingSlash($value);
if (isset($this->map[$k][2]) && in_array('mkdir', $this->map[$k][2])) {
if (!is_dir($value) && !CRM_Utils_File::createDir($value, FALSE)) {
CRM_Core_Session::setStatus(ts('Failed to make directory (%1) at "%2". Please update the settings or file permissions.', array(
1 => $k,
2 => $value,
)));
}
}
if (isset($this->map[$k][2]) && in_array('restrict', $this->map[$k][2])) {
CRM_Utils_File::restrictAccess($value);
}
}
$this->cache[$k] = $value;
return $value;
case 'setting-url':
$options = !empty($this->map[$k][2]) ? $this->map[$k][2] : array();
$value = $this->getSettings()->get($name);
if ($value && !(in_array('noslash', $options))) {
$value = CRM_Utils_File::addTrailingSlash($value, '/');
}
$this->cache[$k] = Civi::paths()->getUrl($value,
in_array('rel', $options) ? 'relative' : 'absolute');
return $this->cache[$k];
case 'runtime':
return \Civi\Core\Container::getBootService('runtime')->{$name};
case 'boot-svc':
$this->cache[$k] = \Civi\Core\Container::getBootService($name);
return $this->cache[$k];
case 'local':
$this->initLocals();
return $this->locals[$name];
case 'user-system':
$userSystem = \Civi\Core\Container::getBootService('userSystem');
$this->cache[$k] = call_user_func(array($userSystem, $name));
return $this->cache[$k];
case 'service':
return \Civi::service($name);
case 'callback':
// Array(0 => $type, 1 => $obj, 2 => $getter, 3 => $setter, 4 => $unsetter).
if (!isset($this->map[$k][1], $this->map[$k][2])) {
throw new \CRM_Core_Exception("Cannot find getter for property CRM_Core_Config::\${$k}");
}
return \Civi\Core\Resolver::singleton()->call(array($this->map[$k][1], $this->map[$k][2]), array($k));
default:
throw new \CRM_Core_Exception("Cannot read property CRM_Core_Config::\${$k} ($type)");
}
}
/**
* Set value.
*
* @param string $k
* @param mixed $v
*
* @throws \CRM_Core_Exception
*/
public function __set($k, $v) {
if (!isset($this->map[$k])) {
throw new \CRM_Core_Exception("Cannot set unrecognized property CRM_Core_Config::\${$k}");
}
unset($this->cache[$k]);
$type = $this->map[$k][0];
// If foreign name is set, use that name (except with callback types because
// their second parameter is the object, not the foreign name).
$name = isset($this->map[$k][1]) && $type != 'callback' ? $this->map[$k][1] : $k;
switch ($type) {
case 'setting':
case 'setting-path':
case 'setting-url':
case 'user-system':
case 'runtime':
case 'callback':
case 'boot-svc':
// In the past, changes to $config were not persisted automatically.
$this->cache[$name] = $v;
return;
case 'local':
$this->initLocals();
$this->locals[$name] = $v;
return;
default:
throw new \CRM_Core_Exception("Cannot set property CRM_Core_Config::\${$k} ($type)");
}
}
/**
* Is value set.
*
* @param string $k
*
* @return bool
*/
public function __isset($k) {
return isset($this->map[$k]);
}
/**
* Unset value.
*
* @param string $k
*
* @throws \CRM_Core_Exception
*/
public function __unset($k) {
if (!isset($this->map[$k])) {
throw new \CRM_Core_Exception("Cannot unset unrecognized property CRM_Core_Config::\${$k}");
}
unset($this->cache[$k]);
$type = $this->map[$k][0];
$name = isset($this->map[$k][1]) ? $this->map[$k][1] : $k;
switch ($type) {
case 'setting':
case 'setting-path':
case 'setting-url':
$this->getSettings()->revert($k);
return;
case 'local':
$this->initLocals();
$this->locals[$name] = NULL;
return;
case 'callback':
// Array(0 => $type, 1 => $obj, 2 => $getter, 3 => $setter, 4 => $unsetter).
if (!isset($this->map[$k][1], $this->map[$k][4])) {
throw new \CRM_Core_Exception("Cannot find unsetter for property CRM_Core_Config::\${$k}");
}
\Civi\Core\Resolver::singleton()->call(array($this->map[$k][1], $this->map[$k][4]), array($k));
return;
default:
throw new \CRM_Core_Exception("Cannot unset property CRM_Core_Config::\${$k} ($type)");
}
}
/**
* @return \Civi\Core\SettingsBag
*/
protected function getSettings() {
if ($this->settings === NULL) {
$this->settings = Civi::settings();
}
return $this->settings;
}
/**
* Initialise local settings.
*/
private function initLocals() {
if ($this->locals === NULL) {
$this->locals = array(
'inCiviCRM' => FALSE,
'doNotResetCache' => 0,
'keyDisable' => FALSE,
'initialized' => FALSE,
'userFrameworkFrontend' => FALSE,
'userPermissionTemp' => NULL,
);
}
}
}

View file

@ -0,0 +1,188 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* Class CRM_Core_Config_Runtime
*
* The runtime describes the environment in which CiviCRM executes -- ie
* the DSN, CMS type, CMS URL, etc. Generally, runtime properties must be
* determined externally (before loading CiviCRM).
*/
class CRM_Core_Config_Runtime extends CRM_Core_Config_MagicMerge {
public $dsn;
/**
* The name of user framework
*
* @var string
*/
public $userFramework;
public $userFrameworkBaseURL;
public $userFrameworkClass;
/**
* The dsn of the database connection for user framework
*
* @var string
*/
public $userFrameworkDSN;
/**
* The name of user framework url variable name
*
* @var string
*/
public $userFrameworkURLVar = 'q';
public $userFrameworkVersion;
public $useFrameworkRelativeBase;
public $userHookClass;
/**
* Are we generating clean url's and using mod_rewrite
* @var string
*/
public $cleanURL;
/**
* @var string
*/
public $configAndLogDir;
public $templateCompileDir;
/**
* The root directory of our template tree.
* @var string
*/
public $templateDir;
/**
* @param bool $loadFromDB
*/
public function initialize($loadFromDB = TRUE) {
if (!defined('CIVICRM_DSN') && $loadFromDB) {
$this->fatal('You need to define CIVICRM_DSN in civicrm.settings.php');
}
$this->dsn = defined('CIVICRM_DSN') ? CIVICRM_DSN : NULL;
if (!defined('CIVICRM_TEMPLATE_COMPILEDIR') && $loadFromDB) {
$this->fatal('You need to define CIVICRM_TEMPLATE_COMPILEDIR in civicrm.settings.php');
}
if (defined('CIVICRM_TEMPLATE_COMPILEDIR')) {
$this->configAndLogDir = CRM_Utils_File::baseFilePath() . 'ConfigAndLog' . DIRECTORY_SEPARATOR;
CRM_Utils_File::createDir($this->configAndLogDir);
CRM_Utils_File::restrictAccess($this->configAndLogDir);
$this->templateCompileDir = defined('CIVICRM_TEMPLATE_COMPILEDIR') ? CRM_Utils_File::addTrailingSlash(CIVICRM_TEMPLATE_COMPILEDIR) : NULL;
CRM_Utils_File::createDir($this->templateCompileDir);
CRM_Utils_File::restrictAccess($this->templateCompileDir);
}
if (!defined('CIVICRM_UF')) {
$this->fatal('You need to define CIVICRM_UF in civicrm.settings.php');
}
$this->userFramework = CIVICRM_UF;
$this->userFrameworkClass = 'CRM_Utils_System_' . CIVICRM_UF;
$this->userHookClass = 'CRM_Utils_Hook_' . CIVICRM_UF;
if (CIVICRM_UF == 'Joomla') {
$this->userFrameworkURLVar = 'task';
}
if (defined('CIVICRM_UF_DSN')) {
$this->userFrameworkDSN = CIVICRM_UF_DSN;
}
// this is dynamically figured out in the civicrm.settings.php file
if (defined('CIVICRM_CLEANURL')) {
$this->cleanURL = CIVICRM_CLEANURL;
}
else {
$this->cleanURL = 0;
}
$this->templateDir = array(dirname(dirname(dirname(__DIR__))) . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR);
$this->initialized = 1;
}
/**
* Exit processing after a fatal event, outputting the message.
*
* @param string $message
*/
private function fatal($message) {
echo $message;
exit();
}
/**
* Include custom PHP and template paths
*/
public function includeCustomPath() {
$customProprtyName = array('customPHPPathDir', 'customTemplateDir');
foreach ($customProprtyName as $property) {
$value = $this->getSettings()->get($property);
if (!empty($value)) {
$customPath = Civi::paths()->getPath($value);
set_include_path($customPath . PATH_SEPARATOR . get_include_path());
}
}
}
/**
* Create a unique identification code for this runtime.
*
* If two requests involve a different hostname, different
* port, different DSN, etc., then they should also have a
* different runtime ID.
*
* @return mixed
*/
public static function getId() {
if (!isset(Civi::$statics[__CLASS__]['id'])) {
Civi::$statics[__CLASS__]['id'] = md5(implode(\CRM_Core_DAO::VALUE_SEPARATOR, array(
defined('CIVICRM_DOMAIN_ID') ? CIVICRM_DOMAIN_ID : 1, // e.g. one database, multi URL
parse_url(CIVICRM_DSN, PHP_URL_PATH), // e.g. one codebase, multi database
\CRM_Utils_Array::value('SCRIPT_FILENAME', $_SERVER, ''), // e.g. CMS vs extern vs installer
\CRM_Utils_Array::value('HTTP_HOST', $_SERVER, ''), // e.g. name-based vhosts
\CRM_Utils_Array::value('SERVER_PORT', $_SERVER, ''), // e.g. port-based vhosts
// Depending on deployment arch, these signals *could* be redundant, but who cares?
)));
}
return Civi::$statics[__CLASS__]['id'];
}
}

View file

@ -0,0 +1,856 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This class acts as our base controller class and adds additional
* functionality and smarts to the base QFC. Specifically we create
* our own action classes and handle the transitions ourselves by
* simulating a state machine. We also create direct jump links to any
* page that can be used universally.
*
* This concept has been discussed on the PEAR list and the QFC FAQ
* goes into a few details. Please check
* http://pear.php.net/manual/en/package.html.html-quickform-controller.faq.php
* for other useful tips and suggestions
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
require_once 'HTML/QuickForm/Controller.php';
require_once 'HTML/QuickForm/Action/Direct.php';
/**
* Class CRM_Core_Controller
*/
class CRM_Core_Controller extends HTML_QuickForm_Controller {
/**
* The title associated with this controller.
*
* @var string
*/
protected $_title;
/**
* The key associated with this controller.
*
* @var string
*/
public $_key;
/**
* The name of the session scope where values are stored.
*
* @var object
*/
protected $_scope;
/**
* The state machine associated with this controller.
*
* @var object
*/
protected $_stateMachine;
/**
* Is this object being embedded in another object. If
* so the display routine needs to not do any work. (The
* parent object takes care of the display)
*
* @var boolean
*/
protected $_embedded = FALSE;
/**
* After entire form execution complete,
* do we want to skip control redirection.
* Default - It get redirect to user context.
*
* Useful when we run form in non civicrm context
* and we need to transfer control back.(eg. drupal)
*
* @var boolean
*/
protected $_skipRedirection = FALSE;
/**
* Are we in print mode? if so we need to modify the display
* functionality to do a minimal display :)
*
* @var boolean
*/
public $_print = 0;
/**
* Should we generate a qfKey, true by default
*
* @var boolean
*/
public $_generateQFKey = TRUE;
/**
* QF response type.
*
* @var string
*/
public $_QFResponseType = 'html';
/**
* Cache the smarty template for efficiency reasons.
*
* @var CRM_Core_Smarty
*/
static protected $_template;
/**
* Cache the session for efficiency reasons.
*
* @var CRM_Core_Session
*/
static protected $_session;
/**
* The parent of this form if embedded.
*
* @var object
*/
protected $_parent = NULL;
/**
* The destination if set will override the destination the code wants to send it to.
*
* @var string;
*/
public $_destination = NULL;
/**
* The entry url for a top level form or wizard. Typically the URL with a reset=1
* used to redirect back to when we land into some session wierdness
*
* @var string
*/
public $_entryURL = NULL;
/**
* All CRM single or multi page pages should inherit from this class.
*
* @param string $title
* Descriptive title of the controller.
* @param bool $modal
* Whether controller is modal.
* @param mixed $mode
* @param string $scope
* Name of session if we want unique scope, used only by Controller_Simple.
* @param bool $addSequence
* Should we add a unique sequence number to the end of the key.
* @param bool $ignoreKey
* Should we not set a qfKey for this controller (for standalone forms).
*/
public function __construct(
$title = NULL,
$modal = TRUE,
$mode = NULL,
$scope = NULL,
$addSequence = FALSE,
$ignoreKey = FALSE
) {
// this has to true for multiple tab session fix
$addSequence = TRUE;
// let the constructor initialize this, should happen only once
if (!isset(self::$_template)) {
self::$_template = CRM_Core_Smarty::singleton();
self::$_session = CRM_Core_Session::singleton();
}
// lets try to get it from the session and/or the request vars
// we do this early on in case there is a fatal error in retrieving the
// key and/or session
$this->_entryURL
= CRM_Utils_Request::retrieve('entryURL', 'String', $this);
// add a unique validable key to the name
$name = CRM_Utils_System::getClassName($this);
if ($name == 'CRM_Core_Controller_Simple' && !empty($scope)) {
// use form name if we have, since its a lot better and
// definitely different for different forms
$name = $scope;
}
$name = $name . '_' . $this->key($name, $addSequence, $ignoreKey);
$this->_title = $title;
if ($scope) {
$this->_scope = $scope;
}
else {
$this->_scope = CRM_Utils_System::getClassName($this);
}
$this->_scope = $this->_scope . '_' . $this->_key;
// only use the civicrm cache if we have a valid key
// else we clash with other users CRM-7059
if (!empty($this->_key)) {
CRM_Core_Session::registerAndRetrieveSessionObjects(array(
"_{$name}_container",
array('CiviCRM', $this->_scope),
));
}
parent::__construct($name, $modal);
$snippet = CRM_Utils_Array::value('snippet', $_REQUEST);
if ($snippet) {
if ($snippet == 3) {
$this->_print = CRM_Core_Smarty::PRINT_PDF;
}
elseif ($snippet == 4) {
// this is used to embed fragments of a form
$this->_print = CRM_Core_Smarty::PRINT_NOFORM;
self::$_template->assign('suppressForm', TRUE);
$this->_generateQFKey = FALSE;
}
elseif ($snippet == 5) {
// mode deprecated in favor of json
// still used by dashlets, probably nothing else
$this->_print = CRM_Core_Smarty::PRINT_NOFORM;
}
// Respond with JSON if in AJAX context (also support legacy value '6')
elseif (in_array($snippet, array(CRM_Core_Smarty::PRINT_JSON, 6))) {
$this->_print = CRM_Core_Smarty::PRINT_JSON;
$this->_QFResponseType = 'json';
}
else {
$this->_print = CRM_Core_Smarty::PRINT_SNIPPET;
}
}
// if the request has a reset value, initialize the controller session
if (!empty($_GET['reset'])) {
$this->reset();
// in this case we'll also cache the url as a hidden form variable, this allows us to
// redirect in case the session has disappeared on us
$this->_entryURL = CRM_Utils_System::makeURL(NULL, TRUE, FALSE, NULL, TRUE);
$this->set('entryURL', $this->_entryURL);
}
// set the key in the session
// do this at the end so we have initialized the object
// and created the scope etc
$this->set('qfKey', $this->_key);
// also retrieve and store destination in session
$this->_destination = CRM_Utils_Request::retrieve(
'civicrmDestination',
'String',
$this,
FALSE,
NULL,
$_REQUEST
);
}
public function fini() {
CRM_Core_BAO_Cache::storeSessionToCache(array(
"_{$this->_name}_container",
array('CiviCRM', $this->_scope),
),
TRUE
);
}
/**
* @param string $name
* @param bool $addSequence
* @param bool $ignoreKey
*
* @return mixed|string
*/
public function key($name, $addSequence = FALSE, $ignoreKey = FALSE) {
$config = CRM_Core_Config::singleton();
if (
$ignoreKey ||
(isset($config->keyDisable) && $config->keyDisable)
) {
return NULL;
}
$key = CRM_Utils_Array::value('qfKey', $_REQUEST, NULL);
if (!$key && $_SERVER['REQUEST_METHOD'] === 'GET') {
$key = CRM_Core_Key::get($name, $addSequence);
}
else {
$key = CRM_Core_Key::validate($key, $name, $addSequence);
}
if (!$key) {
$this->invalidKey();
}
$this->_key = $key;
return $key;
}
/**
* Process the request, overrides the default QFC run method
* This routine actually checks if the QFC is modal and if it
* is the first invalid page, if so it call the requested action
* if not, it calls the display action on the first invalid page
* avoids the issue of users hitting the back button and getting
* a broken page
*
* This run is basically a composition of the original run and the
* jump action
*
* @return mixed
*/
public function run() {
// the names of the action and page should be saved
// note that this is split into two, because some versions of
// php 5.x core dump on the triple assignment :)
$this->_actionName = $this->getActionName();
list($pageName, $action) = $this->_actionName;
if ($this->isModal()) {
if (!$this->isValid($pageName)) {
$pageName = $this->findInvalid();
$action = 'display';
}
}
// note that based on action, control might not come back!!
// e.g. if action is a valid JUMP, u basically do a redirect
// to the appropriate place
$this->wizardHeader($pageName);
return $this->_pages[$pageName]->handle($action);
}
/**
* @return bool
*/
public function validate() {
$this->_actionName = $this->getActionName();
list($pageName, $action) = $this->_actionName;
$page = &$this->_pages[$pageName];
$data = &$this->container();
$this->applyDefaults($pageName);
$page->isFormBuilt() or $page->buildForm();
// We use defaults and constants as if they were submitted
$data['values'][$pageName] = $page->exportValues();
$page->loadValues($data['values'][$pageName]);
// Is the page now valid?
if (TRUE === ($data['valid'][$pageName] = $page->validate())) {
return TRUE;
}
return $page->_errors;
}
/**
* Helper function to add all the needed default actions.
*
* Note that the framework redefines all of the default QFC actions.
*
* @param string $uploadDirectory to store all the uploaded files
* @param array $uploadNames for the various upload buttons (note u can have more than 1 upload)
*/
public function addActions($uploadDirectory = NULL, $uploadNames = NULL) {
$names = array(
'display' => 'CRM_Core_QuickForm_Action_Display',
'next' => 'CRM_Core_QuickForm_Action_Next',
'back' => 'CRM_Core_QuickForm_Action_Back',
'process' => 'CRM_Core_QuickForm_Action_Process',
'cancel' => 'CRM_Core_QuickForm_Action_Cancel',
'refresh' => 'CRM_Core_QuickForm_Action_Refresh',
'reload' => 'CRM_Core_QuickForm_Action_Reload',
'done' => 'CRM_Core_QuickForm_Action_Done',
'jump' => 'CRM_Core_QuickForm_Action_Jump',
'submit' => 'CRM_Core_QuickForm_Action_Submit',
);
foreach ($names as $name => $classPath) {
$action = new $classPath($this->_stateMachine);
$this->addAction($name, $action);
}
$this->addUploadAction($uploadDirectory, $uploadNames);
}
/**
* Getter method for stateMachine.
*
* @return CRM_Core_StateMachine
*/
public function getStateMachine() {
return $this->_stateMachine;
}
/**
* Setter method for stateMachine.
*
* @param CRM_Core_StateMachine $stateMachine
*/
public function setStateMachine($stateMachine) {
$this->_stateMachine = $stateMachine;
}
/**
* Add pages to the controller. Note that the controller does not really care
* the order in which the pages are added
*
* @param CRM_Core_StateMachine $stateMachine
* @param \const|int $action the mode in which the state machine is operating
* typically this will be add/view/edit
*/
public function addPages(&$stateMachine, $action = CRM_Core_Action::NONE) {
$pages = $stateMachine->getPages();
foreach ($pages as $name => $value) {
$className = CRM_Utils_Array::value('className', $value, $name);
$title = CRM_Utils_Array::value('title', $value);
$options = CRM_Utils_Array::value('options', $value);
$stateName = CRM_Utils_String::getClassName($className);
if (!empty($value['className'])) {
$formName = $name;
}
else {
$formName = CRM_Utils_String::getClassName($name);
}
$ext = CRM_Extension_System::singleton()->getMapper();
if ($ext->isExtensionClass($className)) {
require_once $ext->classToPath($className);
}
else {
require_once str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
}
$$stateName = new $className($stateMachine->find($className), $action, 'post', $formName);
if ($title) {
$$stateName->setTitle($title);
}
if ($options) {
$$stateName->setOptions($options);
}
if (property_exists($$stateName, 'urlPath')) {
$$stateName->urlPath = explode('/', (string) CRM_Utils_System::getUrlPath());
}
$this->addPage($$stateName);
$this->addAction($stateName, new HTML_QuickForm_Action_Direct());
//CRM-6342 -we need kill the reference here,
//as we have deprecated reference object creation.
unset($$stateName);
}
}
/**
* QFC does not provide native support to have different 'submit' buttons.
* We introduce this notion to QFC by using button specific data. Thus if
* we have two submit buttons, we could have one displayed as a button and
* the other as an image, both are of type 'submit'.
*
* @return string
* the name of the button that has been pressed by the user
*/
public function getButtonName() {
$data = &$this->container();
return CRM_Utils_Array::value('_qf_button_name', $data);
}
/**
* Destroy all the session state of the controller.
*/
public function reset() {
$this->container(TRUE);
self::$_session->resetScope($this->_scope);
}
/**
* Virtual function to do any processing of data.
*
* Sometimes it is useful for the controller to actually process data.
* This is typically used when we need the controller to figure out
* what pages are potentially involved in this wizard. (this is dynamic
* and can change based on the arguments
*/
public function process() {
}
/**
* Store the variable with the value in the form scope.
*
* @param string|array $name name of the variable or an assoc array of name/value pairs
* @param mixed $value
* Value of the variable if string.
*/
public function set($name, $value = NULL) {
self::$_session->set($name, $value, $this->_scope);
}
/**
* Get the variable from the form scope.
*
* @param string $name
* name of the variable.
*
* @return mixed
*/
public function get($name) {
return self::$_session->get($name, $this->_scope);
}
/**
* Create the header for the wizard from the list of pages.
* Store the created header in smarty
*
* @param string $currentPageName
* Name of the page being displayed.
*
* @return array
*/
public function wizardHeader($currentPageName) {
$wizard = array();
$wizard['steps'] = array();
$count = 0;
foreach ($this->_pages as $name => $page) {
$count++;
$wizard['steps'][] = array(
'name' => $name,
'title' => $page->getTitle(),
//'link' => $page->getLink ( ),
'link' => NULL,
'step' => TRUE,
'valid' => TRUE,
'stepNumber' => $count,
'collapsed' => FALSE,
);
if ($name == $currentPageName) {
$wizard['currentStepNumber'] = $count;
$wizard['currentStepName'] = $name;
$wizard['currentStepTitle'] = $page->getTitle();
}
}
$wizard['stepCount'] = $count;
$this->addWizardStyle($wizard);
$this->assign('wizard', $wizard);
return $wizard;
}
/**
* @param array $wizard
*/
public function addWizardStyle(&$wizard) {
$wizard['style'] = array(
'barClass' => '',
'stepPrefixCurrent' => '&raquo;',
'stepPrefixPast' => '&#x2714;',
'stepPrefixFuture' => ' ',
'subStepPrefixCurrent' => '&nbsp;&nbsp;',
'subStepPrefixPast' => '&nbsp;&nbsp;',
'subStepPrefixFuture' => '&nbsp;&nbsp;',
'showTitle' => 1,
);
}
/**
* Assign value to name in template.
*
* @param string $var
* @param mixed $value
* Value of variable.
*/
public function assign($var, $value = NULL) {
self::$_template->assign($var, $value);
}
/**
* Assign value to name in template by reference.
*
* @param string $var
* @param mixed $value
* (reference) value of variable.
*/
public function assign_by_ref($var, &$value) {
self::$_template->assign_by_ref($var, $value);
}
/**
* Appends values to template variables.
*
* @param array|string $tpl_var the template variable name(s)
* @param mixed $value
* The value to append.
* @param bool $merge
*/
public function append($tpl_var, $value = NULL, $merge = FALSE) {
self::$_template->append($tpl_var, $value, $merge);
}
/**
* Returns an array containing template variables.
*
* @param string $name
*
* @return array
*/
public function get_template_vars($name = NULL) {
return self::$_template->get_template_vars($name);
}
/**
* Setter for embedded.
*
* @param bool $embedded
*/
public function setEmbedded($embedded) {
$this->_embedded = $embedded;
}
/**
* Getter for embedded.
*
* @return bool
* return the embedded value
*/
public function getEmbedded() {
return $this->_embedded;
}
/**
* Setter for skipRedirection.
*
* @param bool $skipRedirection
*/
public function setSkipRedirection($skipRedirection) {
$this->_skipRedirection = $skipRedirection;
}
/**
* Getter for skipRedirection.
*
* @return bool
* return the skipRedirection value
*/
public function getSkipRedirection() {
return $this->_skipRedirection;
}
/**
* @param null $fileName
*/
public function setWord($fileName = NULL) {
//Mark as a CSV file.
CRM_Utils_System::setHttpHeader('Content-Type', 'application/vnd.ms-word');
//Force a download and name the file using the current timestamp.
if (!$fileName) {
$fileName = 'Contacts_' . $_SERVER['REQUEST_TIME'] . '.doc';
}
CRM_Utils_System::setHttpHeader("Content-Disposition", "attachment; filename=Contacts_$fileName");
}
/**
* @param null $fileName
*/
public function setExcel($fileName = NULL) {
//Mark as an excel file.
CRM_Utils_System::setHttpHeader('Content-Type', 'application/vnd.ms-excel');
//Force a download and name the file using the current timestamp.
if (!$fileName) {
$fileName = 'Contacts_' . $_SERVER['REQUEST_TIME'] . '.xls';
}
CRM_Utils_System::setHttpHeader("Content-Disposition", "attachment; filename=Contacts_$fileName");
}
/**
* Setter for print.
*
* @param bool $print
*/
public function setPrint($print) {
if ($print == "xls") {
$this->setExcel();
}
elseif ($print == "doc") {
$this->setWord();
}
$this->_print = $print;
}
/**
* Getter for print.
*
* @return bool
* return the print value
*/
public function getPrint() {
return $this->_print;
}
/**
* @return string
*/
public function getTemplateFile() {
if ($this->_print) {
if ($this->_print == CRM_Core_Smarty::PRINT_PAGE) {
return 'CRM/common/print.tpl';
}
elseif ($this->_print == 'xls' || $this->_print == 'doc') {
return 'CRM/Contact/Form/Task/Excel.tpl';
}
else {
return 'CRM/common/snippet.tpl';
}
}
else {
$config = CRM_Core_Config::singleton();
return 'CRM/common/' . strtolower($config->userFramework) . '.tpl';
}
}
/**
* @param $uploadDir
* @param $uploadNames
*/
public function addUploadAction($uploadDir, $uploadNames) {
if (empty($uploadDir)) {
$config = CRM_Core_Config::singleton();
$uploadDir = $config->uploadDir;
}
if (empty($uploadNames)) {
$uploadNames = $this->get('uploadNames');
if (!empty($uploadNames)) {
$uploadNames = array_merge($uploadNames,
CRM_Core_BAO_File::uploadNames()
);
}
else {
$uploadNames = CRM_Core_BAO_File::uploadNames();
}
}
$action = new CRM_Core_QuickForm_Action_Upload($this->_stateMachine,
$uploadDir,
$uploadNames
);
$this->addAction('upload', $action);
}
/**
* @param $parent
*/
public function setParent($parent) {
$this->_parent = $parent;
}
/**
* @return object
*/
public function getParent() {
return $this->_parent;
}
/**
* @return string
*/
public function getDestination() {
return $this->_destination;
}
/**
* @param null $url
* @param bool $setToReferer
*/
public function setDestination($url = NULL, $setToReferer = FALSE) {
if (empty($url)) {
if ($setToReferer) {
$url = $_SERVER['HTTP_REFERER'];
}
else {
$config = CRM_Core_Config::singleton();
$url = $config->userFrameworkBaseURL;
}
}
$this->_destination = $url;
$this->set('civicrmDestination', $this->_destination);
}
/**
* @return mixed
*/
public function cancelAction() {
$actionName = $this->getActionName();
list($pageName, $action) = $actionName;
return $this->_pages[$pageName]->cancelAction();
}
/**
* Write a simple fatal error message.
*
* Other controllers can decide to do something else and present the user a better message
* and/or redirect to the same page with a reset url
*/
public function invalidKey() {
self::invalidKeyCommon();
}
public function invalidKeyCommon() {
$msg = ts("We can't load the requested web page. This page requires cookies to be enabled in your browser settings. Please check this setting and enable cookies (if they are not enabled). Then try again. If this error persists, contact the site administrator for assistance.") . '<br /><br />' . ts('Site Administrators: This error may indicate that users are accessing this page using a domain or URL other than the configured Base URL. EXAMPLE: Base URL is http://example.org, but some users are accessing the page via http://www.example.org or a domain alias like http://myotherexample.org.') . '<br /><br />' . ts('Error type: Could not find a valid session key.');
CRM_Core_Error::fatal($msg);
}
/**
* Instead of outputting a fatal error message, we'll just redirect
* to the entryURL if present
*/
public function invalidKeyRedirect() {
if ($this->_entryURL && $url_parts = parse_url($this->_entryURL)) {
// CRM-16832: Ensure local redirects only.
if (!empty($url_parts['path'])) {
// Prepend a slash, but don't duplicate it.
$redirect_url = '/' . ltrim($url_parts['path'], '/');
if (!empty($url_parts['query'])) {
$redirect_url .= '?' . $url_parts['query'];
}
CRM_Core_Session::setStatus(ts('Your browser session has expired and we are unable to complete your form submission. We have returned you to the initial step so you can complete and resubmit the form. If you experience continued difficulties, please contact us for assistance.'));
return CRM_Utils_System::redirect($redirect_url);
}
}
self::invalidKeyCommon();
}
}

View file

@ -0,0 +1,143 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* We use QFC for both single page and multi page wizards. We want to make
* creation of single page forms as easy and as seamless as possible. This
* class is used to optimize and make single form pages a relatively trivial
* process
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*/
class CRM_Core_Controller_Simple extends CRM_Core_Controller {
/**
* Constructor.
*
* @param null $path
* The class Path of the form being implemented
* @param bool $title
* @param string $mode
* @param bool $imageUpload
* @param bool $addSequence
* Should we add a unique sequence number to the end of the key.
* @param bool $ignoreKey
* Should we not set a qfKey for this controller (for standalone forms).
* @param bool $attachUpload
*
* @return \CRM_Core_Controller_Simple
*/
public function __construct(
$path,
$title,
$mode = NULL,
$imageUpload = FALSE,
$addSequence = FALSE,
$ignoreKey = FALSE,
$attachUpload = FALSE
) {
// by definition a single page is modal :). We use the form name as the scope for this controller
parent::__construct($title, TRUE, $mode, $path, $addSequence, $ignoreKey);
$this->_stateMachine = new CRM_Core_StateMachine($this);
$params = array($path => NULL);
$savedAction = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, NULL);
if (!empty($savedAction) &&
$savedAction != $mode
) {
$mode = $savedAction;
}
$this->_stateMachine->addSequentialPages($params, $mode);
$this->addPages($this->_stateMachine, $mode);
//changes for custom data type File
$uploadNames = $this->get('uploadNames');
$config = CRM_Core_Config::singleton();
if (is_array($uploadNames) && !empty($uploadNames)) {
$uploadArray = $uploadNames;
$this->addActions($config->customFileUploadDir, $uploadArray);
$this->set('uploadNames', NULL);
}
else {
// always allow a single upload file with same name
if ($attachUpload) {
$this->addActions($config->uploadDir,
CRM_Core_BAO_File::uploadNames()
);
}
elseif ($imageUpload) {
$this->addActions($config->imageUploadDir, array('uploadFile'));
}
else {
$this->addActions();
}
}
}
/**
* Set parent.
*
* @param $parent
*/
public function setParent($parent) {
$this->_parent = $parent;
}
/**
* Get template file name.
*
* @return string
*/
public function getTemplateFileName() {
// there is only one form here, so should be quite easy
$actionName = $this->getActionName();
list($pageName, $action) = $actionName;
return $this->_pages[$pageName]->getTemplateFileName();
}
/**
* A wrapper for getTemplateFileName.
*
* This includes calling the hook to prevent us from having to copy & paste
* the logic of calling the hook
*/
public function getHookedTemplateFileName() {
$pageTemplateFile = $this->getTemplateFileName();
CRM_Utils_Hook::alterTemplateFile(get_class($this), $this, 'page', $pageTemplateFile);
return $pageTemplateFile;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,312 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
* Generated from xml/schema/CRM/Core/ActionLog.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:4ef96df03630ecc884c881b79a40818f)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Core_DAO_ActionLog constructor.
*/
class CRM_Core_DAO_ActionLog extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_action_log';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = false;
/**
*
* @var int unsigned
*/
public $id;
/**
* FK to Contact ID
*
* @var int unsigned
*/
public $contact_id;
/**
* FK to id of the entity that the action was performed on. Pseudo - FK.
*
* @var int unsigned
*/
public $entity_id;
/**
* name of the entity table for the above id, e.g. civicrm_activity, civicrm_participant
*
* @var string
*/
public $entity_table;
/**
* FK to the action schedule that this action originated from.
*
* @var int unsigned
*/
public $action_schedule_id;
/**
* date time that the action was performed on.
*
* @var datetime
*/
public $action_date_time;
/**
* Was there any error sending the reminder?
*
* @var boolean
*/
public $is_error;
/**
* Description / text in case there was an error encountered.
*
* @var text
*/
public $message;
/**
* Keeps track of the sequence number of this repetition.
*
* @var int unsigned
*/
public $repetition_number;
/**
* Stores the date from the entity which triggered this reminder action (e.g. membership.end_date for most membership renewal reminders)
*
* @var date
*/
public $reference_date;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_action_log';
parent::__construct();
}
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'action_schedule_id', 'civicrm_action_schedule', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName() , 'entity_id', NULL, 'id', 'entity_table');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
/**
* Returns all the column names of this table
*
* @return array
*/
static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
Civi::$statics[__CLASS__]['fields'] = array(
'id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Action Schedule ID') ,
'required' => true,
'table_name' => 'civicrm_action_log',
'entity' => 'ActionLog',
'bao' => 'CRM_Core_BAO_ActionLog',
'localizable' => 0,
) ,
'contact_id' => array(
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Action Schedule Contact ID') ,
'description' => 'FK to Contact ID',
'table_name' => 'civicrm_action_log',
'entity' => 'ActionLog',
'bao' => 'CRM_Core_BAO_ActionLog',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
) ,
'entity_id' => array(
'name' => 'entity_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Entity ID') ,
'description' => 'FK to id of the entity that the action was performed on. Pseudo - FK.',
'required' => true,
'table_name' => 'civicrm_action_log',
'entity' => 'ActionLog',
'bao' => 'CRM_Core_BAO_ActionLog',
'localizable' => 0,
) ,
'entity_table' => array(
'name' => 'entity_table',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Entity Table') ,
'description' => 'name of the entity table for the above id, e.g. civicrm_activity, civicrm_participant',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_action_log',
'entity' => 'ActionLog',
'bao' => 'CRM_Core_BAO_ActionLog',
'localizable' => 0,
) ,
'action_schedule_id' => array(
'name' => 'action_schedule_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Schedule') ,
'description' => 'FK to the action schedule that this action originated from.',
'required' => true,
'table_name' => 'civicrm_action_log',
'entity' => 'ActionLog',
'bao' => 'CRM_Core_BAO_ActionLog',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_ActionSchedule',
) ,
'action_date_time' => array(
'name' => 'action_date_time',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'title' => ts('Action Date And Time') ,
'description' => 'date time that the action was performed on.',
'table_name' => 'civicrm_action_log',
'entity' => 'ActionLog',
'bao' => 'CRM_Core_BAO_ActionLog',
'localizable' => 0,
) ,
'is_error' => array(
'name' => 'is_error',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Error?') ,
'description' => 'Was there any error sending the reminder?',
'table_name' => 'civicrm_action_log',
'entity' => 'ActionLog',
'bao' => 'CRM_Core_BAO_ActionLog',
'localizable' => 0,
) ,
'message' => array(
'name' => 'message',
'type' => CRM_Utils_Type::T_TEXT,
'title' => ts('Message') ,
'description' => 'Description / text in case there was an error encountered.',
'table_name' => 'civicrm_action_log',
'entity' => 'ActionLog',
'bao' => 'CRM_Core_BAO_ActionLog',
'localizable' => 0,
) ,
'repetition_number' => array(
'name' => 'repetition_number',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Repetition Number') ,
'description' => 'Keeps track of the sequence number of this repetition.',
'table_name' => 'civicrm_action_log',
'entity' => 'ActionLog',
'bao' => 'CRM_Core_BAO_ActionLog',
'localizable' => 0,
) ,
'reference_date' => array(
'name' => 'reference_date',
'type' => CRM_Utils_Type::T_DATE,
'title' => ts('Reference Date') ,
'description' => 'Stores the date from the entity which triggered this reminder action (e.g. membership.end_date for most membership renewal reminders)',
'default' => 'NULL',
'table_name' => 'civicrm_action_log',
'entity' => 'ActionLog',
'bao' => 'CRM_Core_BAO_ActionLog',
'localizable' => 0,
) ,
);
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
static function getTableName() {
return self::$_tableName;
}
/**
* Returns if this table needs to be logged
*
* @return boolean
*/
function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
static function &import($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'action_log', $prefix, array());
return $r;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
static function &export($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'action_log', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array();
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

View file

@ -0,0 +1,289 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
* Generated from xml/schema/CRM/Core/ActionMapping.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:3ae720be63fdf4626db2d1508c2d8f44)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Core_DAO_ActionMapping constructor.
*/
class CRM_Core_DAO_ActionMapping extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_action_mapping';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = false;
/**
*
* @var int unsigned
*/
public $id;
/**
* Entity for which the reminder is created
*
* @var string
*/
public $entity;
/**
* Entity value
*
* @var string
*/
public $entity_value;
/**
* Entity value label
*
* @var string
*/
public $entity_value_label;
/**
* Entity status
*
* @var string
*/
public $entity_status;
/**
* Entity status label
*
* @var string
*/
public $entity_status_label;
/**
* Entity date
*
* @var string
*/
public $entity_date_start;
/**
* Entity date
*
* @var string
*/
public $entity_date_end;
/**
* Entity recipient
*
* @var string
*/
public $entity_recipient;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_action_mapping';
parent::__construct();
}
/**
* Returns all the column names of this table
*
* @return array
*/
static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
Civi::$statics[__CLASS__]['fields'] = array(
'id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Action Mapping ID') ,
'required' => true,
'table_name' => 'civicrm_action_mapping',
'entity' => 'ActionMapping',
'bao' => 'CRM_Core_DAO_ActionMapping',
'localizable' => 0,
) ,
'entity' => array(
'name' => 'entity',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Action Mapping Entity') ,
'description' => 'Entity for which the reminder is created',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_action_mapping',
'entity' => 'ActionMapping',
'bao' => 'CRM_Core_DAO_ActionMapping',
'localizable' => 0,
) ,
'entity_value' => array(
'name' => 'entity_value',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Action Mapping Entity Value') ,
'description' => 'Entity value',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_action_mapping',
'entity' => 'ActionMapping',
'bao' => 'CRM_Core_DAO_ActionMapping',
'localizable' => 0,
) ,
'entity_value_label' => array(
'name' => 'entity_value_label',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Value Label') ,
'description' => 'Entity value label',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_action_mapping',
'entity' => 'ActionMapping',
'bao' => 'CRM_Core_DAO_ActionMapping',
'localizable' => 0,
) ,
'entity_status' => array(
'name' => 'entity_status',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Status') ,
'description' => 'Entity status',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_action_mapping',
'entity' => 'ActionMapping',
'bao' => 'CRM_Core_DAO_ActionMapping',
'localizable' => 0,
) ,
'entity_status_label' => array(
'name' => 'entity_status_label',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Status Label') ,
'description' => 'Entity status label',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_action_mapping',
'entity' => 'ActionMapping',
'bao' => 'CRM_Core_DAO_ActionMapping',
'localizable' => 0,
) ,
'entity_date_start' => array(
'name' => 'entity_date_start',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Entity Start Date') ,
'description' => 'Entity date',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_action_mapping',
'entity' => 'ActionMapping',
'bao' => 'CRM_Core_DAO_ActionMapping',
'localizable' => 0,
) ,
'entity_date_end' => array(
'name' => 'entity_date_end',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Entity End Date') ,
'description' => 'Entity date',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_action_mapping',
'entity' => 'ActionMapping',
'bao' => 'CRM_Core_DAO_ActionMapping',
'localizable' => 0,
) ,
'entity_recipient' => array(
'name' => 'entity_recipient',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Entity Recipient') ,
'description' => 'Entity recipient',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_action_mapping',
'entity' => 'ActionMapping',
'bao' => 'CRM_Core_DAO_ActionMapping',
'localizable' => 0,
) ,
);
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
static function getTableName() {
return self::$_tableName;
}
/**
* Returns if this table needs to be logged
*
* @return boolean
*/
function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
static function &import($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'action_mapping', $prefix, array());
return $r;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
static function &export($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'action_mapping', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array();
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

View file

@ -0,0 +1,837 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
* Generated from xml/schema/CRM/Core/ActionSchedule.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:d158b2da297ca83e4210a3fa0da8d5eb)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Core_DAO_ActionSchedule constructor.
*/
class CRM_Core_DAO_ActionSchedule extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_action_schedule';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = false;
/**
*
* @var int unsigned
*/
public $id;
/**
* Name of the action(reminder)
*
* @var string
*/
public $name;
/**
* Title of the action(reminder)
*
* @var string
*/
public $title;
/**
* Recipient
*
* @var string
*/
public $recipient;
/**
* Is this the recipient criteria limited to OR in addition to?
*
* @var boolean
*/
public $limit_to;
/**
* Entity value
*
* @var string
*/
public $entity_value;
/**
* Entity status
*
* @var string
*/
public $entity_status;
/**
* Reminder Interval.
*
* @var int unsigned
*/
public $start_action_offset;
/**
* Time units for reminder.
*
* @var string
*/
public $start_action_unit;
/**
* Reminder Action
*
* @var string
*/
public $start_action_condition;
/**
* Entity date
*
* @var string
*/
public $start_action_date;
/**
*
* @var boolean
*/
public $is_repeat;
/**
* Time units for repetition of reminder.
*
* @var string
*/
public $repetition_frequency_unit;
/**
* Time interval for repeating the reminder.
*
* @var int unsigned
*/
public $repetition_frequency_interval;
/**
* Time units till repetition of reminder.
*
* @var string
*/
public $end_frequency_unit;
/**
* Time interval till repeating the reminder.
*
* @var int unsigned
*/
public $end_frequency_interval;
/**
* Reminder Action till repeating the reminder.
*
* @var string
*/
public $end_action;
/**
* Entity end date
*
* @var string
*/
public $end_date;
/**
* Is this option active?
*
* @var boolean
*/
public $is_active;
/**
* Contact IDs to which reminder should be sent.
*
* @var string
*/
public $recipient_manual;
/**
* listing based on recipient field.
*
* @var string
*/
public $recipient_listing;
/**
* Body of the mailing in text format.
*
* @var longtext
*/
public $body_text;
/**
* Body of the mailing in html format.
*
* @var longtext
*/
public $body_html;
/**
* Content of the SMS text.
*
* @var longtext
*/
public $sms_body_text;
/**
* Subject of mailing
*
* @var string
*/
public $subject;
/**
* Record Activity for this reminder?
*
* @var boolean
*/
public $record_activity;
/**
* Name/ID of the mapping to use on this table
*
* @var string
*/
public $mapping_id;
/**
* FK to Group
*
* @var int unsigned
*/
public $group_id;
/**
* FK to the message template.
*
* @var int unsigned
*/
public $msg_template_id;
/**
* FK to the message template.
*
* @var int unsigned
*/
public $sms_template_id;
/**
* Date on which the reminder be sent.
*
* @var date
*/
public $absolute_date;
/**
* Name in "from" field
*
* @var string
*/
public $from_name;
/**
* Email address in "from" field
*
* @var string
*/
public $from_email;
/**
* Send the message as email or sms or both.
*
* @var string
*/
public $mode;
/**
*
* @var int unsigned
*/
public $sms_provider_id;
/**
* Used for repeating entity
*
* @var string
*/
public $used_for;
/**
* Used for multilingual installation
*
* @var string
*/
public $filter_contact_language;
/**
* Used for multilingual installation
*
* @var string
*/
public $communication_language;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_action_schedule';
parent::__construct();
}
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'group_id', 'civicrm_group', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'msg_template_id', 'civicrm_msg_template', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'sms_template_id', 'civicrm_msg_template', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'sms_provider_id', 'civicrm_sms_provider', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
/**
* Returns all the column names of this table
*
* @return array
*/
static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
Civi::$statics[__CLASS__]['fields'] = array(
'id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Action Schedule ID') ,
'required' => true,
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
) ,
'name' => array(
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Name') ,
'description' => 'Name of the action(reminder)',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
) ,
'title' => array(
'name' => 'title',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Title') ,
'description' => 'Title of the action(reminder)',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
) ,
'recipient' => array(
'name' => 'recipient',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Recipient') ,
'description' => 'Recipient',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
) ,
'limit_to' => array(
'name' => 'limit_to',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Limit To') ,
'description' => 'Is this the recipient criteria limited to OR in addition to?',
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
) ,
'entity_value' => array(
'name' => 'entity_value',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Entity Value') ,
'description' => 'Entity value',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
) ,
'entity_status' => array(
'name' => 'entity_status',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Entity Status') ,
'description' => 'Entity status',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
) ,
'start_action_offset' => array(
'name' => 'start_action_offset',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Start Action Offset') ,
'description' => 'Reminder Interval.',
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
) ,
'start_action_unit' => array(
'name' => 'start_action_unit',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Start Action Unit') ,
'description' => 'Time units for reminder.',
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'callback' => 'CRM_Core_SelectValues::getRecurringFrequencyUnits',
)
) ,
'start_action_condition' => array(
'name' => 'start_action_condition',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Start Action Condition') ,
'description' => 'Reminder Action',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
) ,
'start_action_date' => array(
'name' => 'start_action_date',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Start Action Date') ,
'description' => 'Entity date',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
) ,
'is_repeat' => array(
'name' => 'is_repeat',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Repeat?') ,
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
) ,
'repetition_frequency_unit' => array(
'name' => 'repetition_frequency_unit',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Repetition Frequency Unit') ,
'description' => 'Time units for repetition of reminder.',
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'callback' => 'CRM_Core_SelectValues::getRecurringFrequencyUnits',
)
) ,
'repetition_frequency_interval' => array(
'name' => 'repetition_frequency_interval',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Repetition Frequency Interval') ,
'description' => 'Time interval for repeating the reminder.',
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
) ,
'end_frequency_unit' => array(
'name' => 'end_frequency_unit',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('End Frequency Unit') ,
'description' => 'Time units till repetition of reminder.',
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'callback' => 'CRM_Core_SelectValues::getRecurringFrequencyUnits',
)
) ,
'end_frequency_interval' => array(
'name' => 'end_frequency_interval',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('End Frequency Interval') ,
'description' => 'Time interval till repeating the reminder.',
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
) ,
'end_action' => array(
'name' => 'end_action',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('End Action') ,
'description' => 'Reminder Action till repeating the reminder.',
'maxlength' => 32,
'size' => CRM_Utils_Type::MEDIUM,
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
) ,
'end_date' => array(
'name' => 'end_date',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('End Date') ,
'description' => 'Entity end date',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
) ,
'is_active' => array(
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Schedule is Active?') ,
'description' => 'Is this option active?',
'default' => '1',
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
) ,
'recipient_manual' => array(
'name' => 'recipient_manual',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Recipient Manual') ,
'description' => 'Contact IDs to which reminder should be sent.',
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
) ,
'recipient_listing' => array(
'name' => 'recipient_listing',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Recipient Listing') ,
'description' => 'listing based on recipient field.',
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
) ,
'body_text' => array(
'name' => 'body_text',
'type' => CRM_Utils_Type::T_LONGTEXT,
'title' => ts('Reminder Text') ,
'description' => 'Body of the mailing in text format.',
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
) ,
'body_html' => array(
'name' => 'body_html',
'type' => CRM_Utils_Type::T_LONGTEXT,
'title' => ts('Reminder HTML') ,
'description' => 'Body of the mailing in html format.',
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
) ,
'sms_body_text' => array(
'name' => 'sms_body_text',
'type' => CRM_Utils_Type::T_LONGTEXT,
'title' => ts('SMS Reminder Text') ,
'description' => 'Content of the SMS text.',
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
) ,
'subject' => array(
'name' => 'subject',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Reminder Subject') ,
'description' => 'Subject of mailing',
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
) ,
'record_activity' => array(
'name' => 'record_activity',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Record Activity for Reminder?') ,
'description' => 'Record Activity for this reminder?',
'default' => 'NULL',
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
) ,
'mapping_id' => array(
'name' => 'mapping_id',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Reminder Mapping') ,
'description' => 'Name/ID of the mapping to use on this table',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
) ,
'group_id' => array(
'name' => 'group_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Reminder Group') ,
'description' => 'FK to Group',
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Group',
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'table' => 'civicrm_group',
'keyColumn' => 'id',
'labelColumn' => 'title',
)
) ,
'msg_template_id' => array(
'name' => 'msg_template_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Reminder Template') ,
'description' => 'FK to the message template.',
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_MessageTemplate',
) ,
'sms_template_id' => array(
'name' => 'sms_template_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('SMS Reminder Template') ,
'description' => 'FK to the message template.',
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_MessageTemplate',
) ,
'absolute_date' => array(
'name' => 'absolute_date',
'type' => CRM_Utils_Type::T_DATE,
'title' => ts('Fixed Date for Reminder') ,
'description' => 'Date on which the reminder be sent.',
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
) ,
'from_name' => array(
'name' => 'from_name',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Reminder from Name') ,
'description' => 'Name in "from" field',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
) ,
'from_email' => array(
'name' => 'from_email',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Reminder From Email') ,
'description' => 'Email address in "from" field',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
) ,
'mode' => array(
'name' => 'mode',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Message Mode') ,
'description' => 'Send the message as email or sms or both.',
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
'default' => 'Email',
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'optionGroupName' => 'msg_mode',
'optionEditPath' => 'civicrm/admin/options/msg_mode',
)
) ,
'sms_provider_id' => array(
'name' => 'sms_provider_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('SMS Provider') ,
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
'FKClassName' => 'CRM_SMS_DAO_Provider',
'html' => array(
'type' => 'Select',
) ,
) ,
'used_for' => array(
'name' => 'used_for',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Used For') ,
'description' => 'Used for repeating entity',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
) ,
'filter_contact_language' => array(
'name' => 'filter_contact_language',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Filter Contact Language') ,
'description' => 'Used for multilingual installation',
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
) ,
'communication_language' => array(
'name' => 'communication_language',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Communication Language') ,
'description' => 'Used for multilingual installation',
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
'table_name' => 'civicrm_action_schedule',
'entity' => 'ActionSchedule',
'bao' => 'CRM_Core_BAO_ActionSchedule',
'localizable' => 0,
) ,
);
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
static function getTableName() {
return self::$_tableName;
}
/**
* Returns if this table needs to be logged
*
* @return boolean
*/
function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
static function &import($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'action_schedule', $prefix, array());
return $r;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
static function &export($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'action_schedule', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array();
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

View file

@ -0,0 +1,870 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
* Generated from xml/schema/CRM/Core/Address.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:472057d193d1e875a14e7719a2d6a2ee)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Core_DAO_Address constructor.
*/
class CRM_Core_DAO_Address extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_address';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = true;
/**
* Unique Address ID
*
* @var int unsigned
*/
public $id;
/**
* FK to Contact ID
*
* @var int unsigned
*/
public $contact_id;
/**
* Which Location does this address belong to.
*
* @var int unsigned
*/
public $location_type_id;
/**
* Is this the primary address.
*
* @var boolean
*/
public $is_primary;
/**
* Is this the billing address.
*
* @var boolean
*/
public $is_billing;
/**
* Concatenation of all routable street address components (prefix, street number, street name, suffix, unit
number OR P.O. Box). Apps should be able to determine physical location with this data (for mapping, mail
delivery, etc.).
*
* @var string
*/
public $street_address;
/**
* Numeric portion of address number on the street, e.g. For 112A Main St, the street_number = 112.
*
* @var int
*/
public $street_number;
/**
* Non-numeric portion of address number on the street, e.g. For 112A Main St, the street_number_suffix = A
*
* @var string
*/
public $street_number_suffix;
/**
* Directional prefix, e.g. SE Main St, SE is the prefix.
*
* @var string
*/
public $street_number_predirectional;
/**
* Actual street name, excluding St, Dr, Rd, Ave, e.g. For 112 Main St, the street_name = Main.
*
* @var string
*/
public $street_name;
/**
* St, Rd, Dr, etc.
*
* @var string
*/
public $street_type;
/**
* Directional prefix, e.g. Main St S, S is the suffix.
*
* @var string
*/
public $street_number_postdirectional;
/**
* Secondary unit designator, e.g. Apt 3 or Unit # 14, or Bldg 1200
*
* @var string
*/
public $street_unit;
/**
* Supplemental Address Information, Line 1
*
* @var string
*/
public $supplemental_address_1;
/**
* Supplemental Address Information, Line 2
*
* @var string
*/
public $supplemental_address_2;
/**
* Supplemental Address Information, Line 3
*
* @var string
*/
public $supplemental_address_3;
/**
* City, Town or Village Name.
*
* @var string
*/
public $city;
/**
* Which County does this address belong to.
*
* @var int unsigned
*/
public $county_id;
/**
* Which State_Province does this address belong to.
*
* @var int unsigned
*/
public $state_province_id;
/**
* Store the suffix, like the +4 part in the USPS system.
*
* @var string
*/
public $postal_code_suffix;
/**
* Store both US (zip5) AND international postal codes. App is responsible for country/region appropriate validation.
*
* @var string
*/
public $postal_code;
/**
* USPS Bulk mailing code.
*
* @var string
*/
public $usps_adc;
/**
* Which Country does this address belong to.
*
* @var int unsigned
*/
public $country_id;
/**
* Latitude
*
* @var float
*/
public $geo_code_1;
/**
* Longitude
*
* @var float
*/
public $geo_code_2;
/**
* Is this a manually entered geo code
*
* @var boolean
*/
public $manual_geo_code;
/**
* Timezone expressed as a UTC offset - e.g. United States CST would be written as "UTC-6".
*
* @var string
*/
public $timezone;
/**
*
* @var string
*/
public $name;
/**
* FK to Address ID
*
* @var int unsigned
*/
public $master_id;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_address';
parent::__construct();
}
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'county_id', 'civicrm_county', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'state_province_id', 'civicrm_state_province', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'country_id', 'civicrm_country', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'master_id', 'civicrm_address', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
/**
* Returns all the column names of this table
*
* @return array
*/
static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
Civi::$statics[__CLASS__]['fields'] = array(
'id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Address ID') ,
'description' => 'Unique Address ID',
'required' => true,
'table_name' => 'civicrm_address',
'entity' => 'Address',
'bao' => 'CRM_Core_BAO_Address',
'localizable' => 0,
) ,
'contact_id' => array(
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Contact ID') ,
'description' => 'FK to Contact ID',
'table_name' => 'civicrm_address',
'entity' => 'Address',
'bao' => 'CRM_Core_BAO_Address',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
) ,
'location_type_id' => array(
'name' => 'location_type_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Address Location Type') ,
'description' => 'Which Location does this address belong to.',
'table_name' => 'civicrm_address',
'entity' => 'Address',
'bao' => 'CRM_Core_BAO_Address',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'table' => 'civicrm_location_type',
'keyColumn' => 'id',
'labelColumn' => 'display_name',
)
) ,
'is_primary' => array(
'name' => 'is_primary',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Is Address Primary?') ,
'description' => 'Is this the primary address.',
'table_name' => 'civicrm_address',
'entity' => 'Address',
'bao' => 'CRM_Core_BAO_Address',
'localizable' => 0,
'html' => array(
'type' => 'CheckBox',
) ,
) ,
'is_billing' => array(
'name' => 'is_billing',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Is Billing Address') ,
'description' => 'Is this the billing address.',
'table_name' => 'civicrm_address',
'entity' => 'Address',
'bao' => 'CRM_Core_BAO_Address',
'localizable' => 0,
'html' => array(
'type' => 'CheckBox',
) ,
) ,
'street_address' => array(
'name' => 'street_address',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Street Address') ,
'description' => 'Concatenation of all routable street address components (prefix, street number, street name, suffix, unit
number OR P.O. Box). Apps should be able to determine physical location with this data (for mapping, mail
delivery, etc.).
',
'maxlength' => 96,
'size' => CRM_Utils_Type::HUGE,
'import' => true,
'where' => 'civicrm_address.street_address',
'headerPattern' => '/(street|address)/i',
'dataPattern' => '/^(\d{1,5}( [0-9A-Za-z]+)+)$|^(P\.?O\.\? Box \d{1,5})$/i',
'export' => true,
'table_name' => 'civicrm_address',
'entity' => 'Address',
'bao' => 'CRM_Core_BAO_Address',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'street_number' => array(
'name' => 'street_number',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Street Number') ,
'description' => 'Numeric portion of address number on the street, e.g. For 112A Main St, the street_number = 112.',
'export' => true,
'where' => 'civicrm_address.street_number',
'headerPattern' => '',
'dataPattern' => '',
'table_name' => 'civicrm_address',
'entity' => 'Address',
'bao' => 'CRM_Core_BAO_Address',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'street_number_suffix' => array(
'name' => 'street_number_suffix',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Street Number Suffix') ,
'description' => 'Non-numeric portion of address number on the street, e.g. For 112A Main St, the street_number_suffix = A
',
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
'export' => true,
'where' => 'civicrm_address.street_number_suffix',
'headerPattern' => '',
'dataPattern' => '',
'table_name' => 'civicrm_address',
'entity' => 'Address',
'bao' => 'CRM_Core_BAO_Address',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'street_number_predirectional' => array(
'name' => 'street_number_predirectional',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Street Direction Prefix') ,
'description' => 'Directional prefix, e.g. SE Main St, SE is the prefix.',
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
'table_name' => 'civicrm_address',
'entity' => 'Address',
'bao' => 'CRM_Core_BAO_Address',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'street_name' => array(
'name' => 'street_name',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Street Name') ,
'description' => 'Actual street name, excluding St, Dr, Rd, Ave, e.g. For 112 Main St, the street_name = Main.',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'export' => true,
'where' => 'civicrm_address.street_name',
'headerPattern' => '',
'dataPattern' => '',
'table_name' => 'civicrm_address',
'entity' => 'Address',
'bao' => 'CRM_Core_BAO_Address',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'street_type' => array(
'name' => 'street_type',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Street Type') ,
'description' => 'St, Rd, Dr, etc.',
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
'table_name' => 'civicrm_address',
'entity' => 'Address',
'bao' => 'CRM_Core_BAO_Address',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'street_number_postdirectional' => array(
'name' => 'street_number_postdirectional',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Street Direction Suffix') ,
'description' => 'Directional prefix, e.g. Main St S, S is the suffix.',
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
'table_name' => 'civicrm_address',
'entity' => 'Address',
'bao' => 'CRM_Core_BAO_Address',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'street_unit' => array(
'name' => 'street_unit',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Street Unit') ,
'description' => 'Secondary unit designator, e.g. Apt 3 or Unit # 14, or Bldg 1200',
'maxlength' => 16,
'size' => CRM_Utils_Type::TWELVE,
'export' => true,
'where' => 'civicrm_address.street_unit',
'headerPattern' => '',
'dataPattern' => '',
'table_name' => 'civicrm_address',
'entity' => 'Address',
'bao' => 'CRM_Core_BAO_Address',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'supplemental_address_1' => array(
'name' => 'supplemental_address_1',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Supplemental Address 1') ,
'description' => 'Supplemental Address Information, Line 1',
'maxlength' => 96,
'size' => CRM_Utils_Type::HUGE,
'import' => true,
'where' => 'civicrm_address.supplemental_address_1',
'headerPattern' => '/(supplemental(\s)?)?address(\s\d+)?/i',
'dataPattern' => '/unit|ap(ar)?t(ment)?\s(\d|\w)+/i',
'export' => true,
'table_name' => 'civicrm_address',
'entity' => 'Address',
'bao' => 'CRM_Core_BAO_Address',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'supplemental_address_2' => array(
'name' => 'supplemental_address_2',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Supplemental Address 2') ,
'description' => 'Supplemental Address Information, Line 2',
'maxlength' => 96,
'size' => CRM_Utils_Type::HUGE,
'import' => true,
'where' => 'civicrm_address.supplemental_address_2',
'headerPattern' => '/(supplemental(\s)?)?address(\s\d+)?/i',
'dataPattern' => '/unit|ap(ar)?t(ment)?\s(\d|\w)+/i',
'export' => true,
'table_name' => 'civicrm_address',
'entity' => 'Address',
'bao' => 'CRM_Core_BAO_Address',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'supplemental_address_3' => array(
'name' => 'supplemental_address_3',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Supplemental Address 3') ,
'description' => 'Supplemental Address Information, Line 3',
'maxlength' => 96,
'size' => CRM_Utils_Type::HUGE,
'import' => true,
'where' => 'civicrm_address.supplemental_address_3',
'headerPattern' => '/(supplemental(\s)?)?address(\s\d+)?/i',
'dataPattern' => '/unit|ap(ar)?t(ment)?\s(\d|\w)+/i',
'export' => true,
'table_name' => 'civicrm_address',
'entity' => 'Address',
'bao' => 'CRM_Core_BAO_Address',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'city' => array(
'name' => 'city',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('City') ,
'description' => 'City, Town or Village Name.',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'import' => true,
'where' => 'civicrm_address.city',
'headerPattern' => '/city/i',
'dataPattern' => '/^[A-Za-z]+(\.?)(\s?[A-Za-z]+){0,2}$/',
'export' => true,
'table_name' => 'civicrm_address',
'entity' => 'Address',
'bao' => 'CRM_Core_BAO_Address',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'county_id' => array(
'name' => 'county_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('County') ,
'description' => 'Which County does this address belong to.',
'table_name' => 'civicrm_address',
'entity' => 'Address',
'bao' => 'CRM_Core_BAO_Address',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_County',
'html' => array(
'type' => 'ChainSelect',
) ,
'pseudoconstant' => array(
'table' => 'civicrm_county',
'keyColumn' => 'id',
'labelColumn' => 'name',
)
) ,
'state_province_id' => array(
'name' => 'state_province_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('State/Province') ,
'description' => 'Which State_Province does this address belong to.',
'table_name' => 'civicrm_address',
'entity' => 'Address',
'bao' => 'CRM_Core_BAO_Address',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_StateProvince',
'html' => array(
'type' => 'ChainSelect',
) ,
'pseudoconstant' => array(
'table' => 'civicrm_state_province',
'keyColumn' => 'id',
'labelColumn' => 'name',
)
) ,
'postal_code_suffix' => array(
'name' => 'postal_code_suffix',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Postal Code Suffix') ,
'description' => 'Store the suffix, like the +4 part in the USPS system.',
'maxlength' => 12,
'size' => 3,
'import' => true,
'where' => 'civicrm_address.postal_code_suffix',
'headerPattern' => '/p(ostal)\sc(ode)\ss(uffix)/i',
'dataPattern' => '/\d?\d{4}(-\d{4})?/',
'export' => true,
'table_name' => 'civicrm_address',
'entity' => 'Address',
'bao' => 'CRM_Core_BAO_Address',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'postal_code' => array(
'name' => 'postal_code',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Postal Code') ,
'description' => 'Store both US (zip5) AND international postal codes. App is responsible for country/region appropriate validation.',
'maxlength' => 64,
'size' => 6,
'import' => true,
'where' => 'civicrm_address.postal_code',
'headerPattern' => '/postal|zip/i',
'dataPattern' => '/\d?\d{4}(-\d{4})?/',
'export' => true,
'table_name' => 'civicrm_address',
'entity' => 'Address',
'bao' => 'CRM_Core_BAO_Address',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'usps_adc' => array(
'name' => 'usps_adc',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('USPS Code') ,
'description' => 'USPS Bulk mailing code.',
'maxlength' => 32,
'size' => CRM_Utils_Type::MEDIUM,
'table_name' => 'civicrm_address',
'entity' => 'Address',
'bao' => 'CRM_Core_BAO_Address',
'localizable' => 0,
) ,
'country_id' => array(
'name' => 'country_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Country') ,
'description' => 'Which Country does this address belong to.',
'table_name' => 'civicrm_address',
'entity' => 'Address',
'bao' => 'CRM_Core_BAO_Address',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_Country',
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'table' => 'civicrm_country',
'keyColumn' => 'id',
'labelColumn' => 'name',
'nameColumn' => 'iso_code',
)
) ,
'geo_code_1' => array(
'name' => 'geo_code_1',
'type' => CRM_Utils_Type::T_FLOAT,
'title' => ts('Latitude') ,
'description' => 'Latitude',
'import' => true,
'where' => 'civicrm_address.geo_code_1',
'headerPattern' => '/geo/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_address',
'entity' => 'Address',
'bao' => 'CRM_Core_BAO_Address',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'geo_code_2' => array(
'name' => 'geo_code_2',
'type' => CRM_Utils_Type::T_FLOAT,
'title' => ts('Longitude') ,
'description' => 'Longitude',
'import' => true,
'where' => 'civicrm_address.geo_code_2',
'headerPattern' => '/geo/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_address',
'entity' => 'Address',
'bao' => 'CRM_Core_BAO_Address',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'manual_geo_code' => array(
'name' => 'manual_geo_code',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Is manually geocoded') ,
'description' => 'Is this a manually entered geo code',
'table_name' => 'civicrm_address',
'entity' => 'Address',
'bao' => 'CRM_Core_BAO_Address',
'localizable' => 0,
'html' => array(
'type' => 'CheckBox',
) ,
) ,
'timezone' => array(
'name' => 'timezone',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Timezone') ,
'description' => 'Timezone expressed as a UTC offset - e.g. United States CST would be written as "UTC-6".',
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
'table_name' => 'civicrm_address',
'entity' => 'Address',
'bao' => 'CRM_Core_BAO_Address',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'address_name' => array(
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Address Name') ,
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'import' => true,
'where' => 'civicrm_address.name',
'headerPattern' => '/^location|(l(ocation\s)?name)$/i',
'dataPattern' => '/^\w+$/',
'export' => true,
'table_name' => 'civicrm_address',
'entity' => 'Address',
'bao' => 'CRM_Core_BAO_Address',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'master_id' => array(
'name' => 'master_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Master Address Belongs To') ,
'description' => 'FK to Address ID',
'import' => true,
'where' => 'civicrm_address.master_id',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_address',
'entity' => 'Address',
'bao' => 'CRM_Core_BAO_Address',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_Address',
) ,
);
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
static function getTableName() {
return self::$_tableName;
}
/**
* Returns if this table needs to be logged
*
* @return boolean
*/
function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
static function &import($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'address', $prefix, array(
'CRM_Core_DAO_County',
'CRM_Core_DAO_StateProvince',
'CRM_Core_DAO_Country',
));
return $r;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
static function &export($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'address', $prefix, array(
'CRM_Core_DAO_County',
'CRM_Core_DAO_StateProvince',
'CRM_Core_DAO_Country',
));
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array(
'index_location_type' => array(
'name' => 'index_location_type',
'field' => array(
0 => 'location_type_id',
) ,
'localizable' => false,
'sig' => 'civicrm_address::0::location_type_id',
) ,
'index_is_primary' => array(
'name' => 'index_is_primary',
'field' => array(
0 => 'is_primary',
) ,
'localizable' => false,
'sig' => 'civicrm_address::0::is_primary',
) ,
'index_is_billing' => array(
'name' => 'index_is_billing',
'field' => array(
0 => 'is_billing',
) ,
'localizable' => false,
'sig' => 'civicrm_address::0::is_billing',
) ,
'index_street_name' => array(
'name' => 'index_street_name',
'field' => array(
0 => 'street_name',
) ,
'localizable' => false,
'sig' => 'civicrm_address::0::street_name',
) ,
'index_city' => array(
'name' => 'index_city',
'field' => array(
0 => 'city',
) ,
'localizable' => false,
'sig' => 'civicrm_address::0::city',
) ,
);
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

View file

@ -0,0 +1,163 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
* Generated from xml/schema/CRM/Core/AddressFormat.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:9f58709f0e50bebe21edf4d50880e5fb)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Core_DAO_AddressFormat constructor.
*/
class CRM_Core_DAO_AddressFormat extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_address_format';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = false;
/**
* Address Format Id
*
* @var int unsigned
*/
public $id;
/**
* The format of an address
*
* @var text
*/
public $format;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_address_format';
parent::__construct();
}
/**
* Returns all the column names of this table
*
* @return array
*/
static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
Civi::$statics[__CLASS__]['fields'] = array(
'id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Address Format ID') ,
'description' => 'Address Format Id',
'required' => true,
'table_name' => 'civicrm_address_format',
'entity' => 'AddressFormat',
'bao' => 'CRM_Core_DAO_AddressFormat',
'localizable' => 0,
) ,
'format' => array(
'name' => 'format',
'type' => CRM_Utils_Type::T_TEXT,
'title' => ts('Address Format') ,
'description' => 'The format of an address',
'table_name' => 'civicrm_address_format',
'entity' => 'AddressFormat',
'bao' => 'CRM_Core_DAO_AddressFormat',
'localizable' => 0,
) ,
);
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
static function getTableName() {
return self::$_tableName;
}
/**
* Returns if this table needs to be logged
*
* @return boolean
*/
function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
static function &import($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'address_format', $prefix, array());
return $r;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
static function &export($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'address_format', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array();
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

View file

@ -0,0 +1,789 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
// (GenCodeChecksum:IGNORE)
return array(
'CRM_Core_DAO_AddressFormat' => array(
'name' => 'AddressFormat',
'class' => 'CRM_Core_DAO_AddressFormat',
'table' => 'civicrm_address_format',
) ,
'CRM_Core_DAO_Extension' => array(
'name' => 'Extension',
'class' => 'CRM_Core_DAO_Extension',
'table' => 'civicrm_extension',
) ,
'CRM_Core_DAO_File' => array(
'name' => 'File',
'class' => 'CRM_Core_DAO_File',
'table' => 'civicrm_file',
) ,
'CRM_Core_DAO_LocationType' => array(
'name' => 'LocationType',
'class' => 'CRM_Core_DAO_LocationType',
'table' => 'civicrm_location_type',
) ,
'CRM_Core_DAO_Managed' => array(
'name' => 'Managed',
'class' => 'CRM_Core_DAO_Managed',
'table' => 'civicrm_managed',
) ,
'CRM_Core_DAO_Mapping' => array(
'name' => 'Mapping',
'class' => 'CRM_Core_DAO_Mapping',
'table' => 'civicrm_mapping',
) ,
'CRM_Core_DAO_MessageTemplate' => array(
'name' => 'MessageTemplate',
'class' => 'CRM_Core_DAO_MessageTemplate',
'table' => 'civicrm_msg_template',
) ,
'CRM_Core_DAO_OptionGroup' => array(
'name' => 'OptionGroup',
'class' => 'CRM_Core_DAO_OptionGroup',
'table' => 'civicrm_option_group',
) ,
'CRM_Core_DAO_PreferencesDate' => array(
'name' => 'PreferencesDate',
'class' => 'CRM_Core_DAO_PreferencesDate',
'table' => 'civicrm_preferences_date',
) ,
'CRM_Core_DAO_SystemLog' => array(
'name' => 'SystemLog',
'class' => 'CRM_Core_DAO_SystemLog',
'table' => 'civicrm_system_log',
) ,
'CRM_Core_DAO_Worldregion' => array(
'name' => 'Worldregion',
'class' => 'CRM_Core_DAO_Worldregion',
'table' => 'civicrm_worldregion',
) ,
'CRM_Core_DAO_Component' => array(
'name' => 'Component',
'class' => 'CRM_Core_DAO_Component',
'table' => 'civicrm_component',
) ,
'CRM_Core_DAO_Persistent' => array(
'name' => 'Persistent',
'class' => 'CRM_Core_DAO_Persistent',
'table' => 'civicrm_persistent',
) ,
'CRM_Core_DAO_PrevNextCache' => array(
'name' => 'PrevNextCache',
'class' => 'CRM_Core_DAO_PrevNextCache',
'table' => 'civicrm_prevnext_cache',
) ,
'CRM_Core_DAO_ActionMapping' => array(
'name' => 'ActionMapping',
'class' => 'CRM_Core_DAO_ActionMapping',
'table' => 'civicrm_action_mapping',
) ,
'CRM_Core_DAO_RecurringEntity' => array(
'name' => 'RecurringEntity',
'class' => 'CRM_Core_DAO_RecurringEntity',
'table' => 'civicrm_recurring_entity',
) ,
'CRM_ACL_DAO_ACL' => array(
'name' => 'ACL',
'class' => 'CRM_ACL_DAO_ACL',
'table' => 'civicrm_acl',
) ,
'CRM_ACL_DAO_EntityRole' => array(
'name' => 'EntityRole',
'class' => 'CRM_ACL_DAO_EntityRole',
'table' => 'civicrm_acl_entity_role',
) ,
'CRM_Contact_DAO_Contact' => array(
'name' => 'Contact',
'class' => 'CRM_Contact_DAO_Contact',
'table' => 'civicrm_contact',
) ,
'CRM_Contact_DAO_ACLContactCache' => array(
'name' => 'ACLContactCache',
'class' => 'CRM_Contact_DAO_ACLContactCache',
'table' => 'civicrm_acl_contact_cache',
) ,
'CRM_Contact_DAO_RelationshipType' => array(
'name' => 'RelationshipType',
'class' => 'CRM_Contact_DAO_RelationshipType',
'table' => 'civicrm_relationship_type',
) ,
'CRM_Contact_DAO_SavedSearch' => array(
'name' => 'SavedSearch',
'class' => 'CRM_Contact_DAO_SavedSearch',
'table' => 'civicrm_saved_search',
) ,
'CRM_Contact_DAO_ContactType' => array(
'name' => 'ContactType',
'class' => 'CRM_Contact_DAO_ContactType',
'table' => 'civicrm_contact_type',
) ,
'CRM_Batch_DAO_Batch' => array(
'name' => 'Batch',
'class' => 'CRM_Batch_DAO_Batch',
'table' => 'civicrm_batch',
) ,
'CRM_Batch_DAO_EntityBatch' => array(
'name' => 'EntityBatch',
'class' => 'CRM_Batch_DAO_EntityBatch',
'table' => 'civicrm_entity_batch',
) ,
'CRM_Mailing_DAO_Component' => array(
'name' => 'Component',
'class' => 'CRM_Mailing_DAO_Component',
'table' => 'civicrm_mailing_component',
) ,
'CRM_Mailing_DAO_MailingAB' => array(
'name' => 'MailingAB',
'class' => 'CRM_Mailing_DAO_MailingAB',
'table' => 'civicrm_mailing_abtest',
) ,
'CRM_Mailing_DAO_BounceType' => array(
'name' => 'BounceType',
'class' => 'CRM_Mailing_DAO_BounceType',
'table' => 'civicrm_mailing_bounce_type',
) ,
'CRM_Mailing_DAO_BouncePattern' => array(
'name' => 'BouncePattern',
'class' => 'CRM_Mailing_DAO_BouncePattern',
'table' => 'civicrm_mailing_bounce_pattern',
) ,
'CRM_Contribute_DAO_Premium' => array(
'name' => 'Premium',
'class' => 'CRM_Contribute_DAO_Premium',
'table' => 'civicrm_premiums',
) ,
'CRM_Financial_DAO_Currency' => array(
'name' => 'Currency',
'class' => 'CRM_Financial_DAO_Currency',
'table' => 'civicrm_currency',
) ,
'CRM_Financial_DAO_FinancialAccount' => array(
'name' => 'FinancialAccount',
'class' => 'CRM_Financial_DAO_FinancialAccount',
'table' => 'civicrm_financial_account',
) ,
'CRM_Financial_DAO_PaymentProcessorType' => array(
'name' => 'PaymentProcessorType',
'class' => 'CRM_Financial_DAO_PaymentProcessorType',
'table' => 'civicrm_payment_processor_type',
) ,
'CRM_Financial_DAO_FinancialType' => array(
'name' => 'FinancialType',
'class' => 'CRM_Financial_DAO_FinancialType',
'table' => 'civicrm_financial_type',
) ,
'CRM_Financial_DAO_EntityFinancialAccount' => array(
'name' => 'EntityFinancialAccount',
'class' => 'CRM_Financial_DAO_EntityFinancialAccount',
'table' => 'civicrm_entity_financial_account',
) ,
'CRM_Financial_DAO_FinancialItem' => array(
'name' => 'FinancialItem',
'class' => 'CRM_Financial_DAO_FinancialItem',
'table' => 'civicrm_financial_item',
) ,
'CRM_Member_DAO_MembershipStatus' => array(
'name' => 'MembershipStatus',
'class' => 'CRM_Member_DAO_MembershipStatus',
'table' => 'civicrm_membership_status',
) ,
'CRM_Campaign_DAO_Campaign' => array(
'name' => 'Campaign',
'class' => 'CRM_Campaign_DAO_Campaign',
'table' => 'civicrm_campaign',
) ,
'CRM_Campaign_DAO_CampaignGroup' => array(
'name' => 'CampaignGroup',
'class' => 'CRM_Campaign_DAO_CampaignGroup',
'table' => 'civicrm_campaign_group',
) ,
'CRM_Campaign_DAO_Survey' => array(
'name' => 'Survey',
'class' => 'CRM_Campaign_DAO_Survey',
'table' => 'civicrm_survey',
) ,
'CRM_Event_DAO_ParticipantStatusType' => array(
'name' => 'ParticipantStatusType',
'class' => 'CRM_Event_DAO_ParticipantStatusType',
'table' => 'civicrm_participant_status_type',
) ,
'CRM_Event_Cart_DAO_Cart' => array(
'name' => 'Cart',
'class' => 'CRM_Event_Cart_DAO_Cart',
'table' => 'civicrm_event_carts',
) ,
'CRM_Dedupe_DAO_RuleGroup' => array(
'name' => 'RuleGroup',
'class' => 'CRM_Dedupe_DAO_RuleGroup',
'table' => 'civicrm_dedupe_rule_group',
) ,
'CRM_Dedupe_DAO_Rule' => array(
'name' => 'Rule',
'class' => 'CRM_Dedupe_DAO_Rule',
'table' => 'civicrm_dedupe_rule',
) ,
'CRM_Dedupe_DAO_Exception' => array(
'name' => 'Exception',
'class' => 'CRM_Dedupe_DAO_Exception',
'table' => 'civicrm_dedupe_exception',
) ,
'CRM_Case_DAO_CaseType' => array(
'name' => 'CaseType',
'class' => 'CRM_Case_DAO_CaseType',
'table' => 'civicrm_case_type',
) ,
'CRM_Grant_DAO_Grant' => array(
'name' => 'Grant',
'class' => 'CRM_Grant_DAO_Grant',
'table' => 'civicrm_grant',
) ,
'CRM_Friend_DAO_Friend' => array(
'name' => 'Friend',
'class' => 'CRM_Friend_DAO_Friend',
'table' => 'civicrm_tell_friend',
) ,
'CRM_Pledge_DAO_PledgeBlock' => array(
'name' => 'PledgeBlock',
'class' => 'CRM_Pledge_DAO_PledgeBlock',
'table' => 'civicrm_pledge_block',
) ,
'CRM_Queue_DAO_QueueItem' => array(
'name' => 'QueueItem',
'class' => 'CRM_Queue_DAO_QueueItem',
'table' => 'civicrm_queue_item',
) ,
'CRM_PCP_DAO_PCP' => array(
'name' => 'PCP',
'class' => 'CRM_PCP_DAO_PCP',
'table' => 'civicrm_pcp',
) ,
'CRM_Cxn_DAO_Cxn' => array(
'name' => 'Cxn',
'class' => 'CRM_Cxn_DAO_Cxn',
'table' => 'civicrm_cxn',
) ,
'CRM_Core_DAO_Cache' => array(
'name' => 'Cache',
'class' => 'CRM_Core_DAO_Cache',
'table' => 'civicrm_cache',
) ,
'CRM_Core_DAO_Country' => array(
'name' => 'Country',
'class' => 'CRM_Core_DAO_Country',
'table' => 'civicrm_country',
) ,
'CRM_Core_DAO_CustomGroup' => array(
'name' => 'CustomGroup',
'class' => 'CRM_Core_DAO_CustomGroup',
'table' => 'civicrm_custom_group',
) ,
'CRM_Core_DAO_CustomField' => array(
'name' => 'CustomField',
'class' => 'CRM_Core_DAO_CustomField',
'table' => 'civicrm_custom_field',
) ,
'CRM_Core_DAO_Domain' => array(
'name' => 'Domain',
'class' => 'CRM_Core_DAO_Domain',
'table' => 'civicrm_domain',
) ,
'CRM_Core_DAO_Email' => array(
'name' => 'Email',
'class' => 'CRM_Core_DAO_Email',
'table' => 'civicrm_email',
) ,
'CRM_Core_DAO_EntityFile' => array(
'name' => 'EntityFile',
'class' => 'CRM_Core_DAO_EntityFile',
'table' => 'civicrm_entity_file',
) ,
'CRM_Core_DAO_IM' => array(
'name' => 'IM',
'class' => 'CRM_Core_DAO_IM',
'table' => 'civicrm_im',
) ,
'CRM_Core_DAO_Job' => array(
'name' => 'Job',
'class' => 'CRM_Core_DAO_Job',
'table' => 'civicrm_job',
) ,
'CRM_Core_DAO_JobLog' => array(
'name' => 'JobLog',
'class' => 'CRM_Core_DAO_JobLog',
'table' => 'civicrm_job_log',
) ,
'CRM_Core_DAO_Log' => array(
'name' => 'Log',
'class' => 'CRM_Core_DAO_Log',
'table' => 'civicrm_log',
) ,
'CRM_Core_DAO_MailSettings' => array(
'name' => 'MailSettings',
'class' => 'CRM_Core_DAO_MailSettings',
'table' => 'civicrm_mail_settings',
) ,
'CRM_Core_DAO_MappingField' => array(
'name' => 'MappingField',
'class' => 'CRM_Core_DAO_MappingField',
'table' => 'civicrm_mapping_field',
) ,
'CRM_Core_DAO_Menu' => array(
'name' => 'Menu',
'class' => 'CRM_Core_DAO_Menu',
'table' => 'civicrm_menu',
) ,
'CRM_Core_DAO_Navigation' => array(
'name' => 'Navigation',
'class' => 'CRM_Core_DAO_Navigation',
'table' => 'civicrm_navigation',
) ,
'CRM_Core_DAO_Note' => array(
'name' => 'Note',
'class' => 'CRM_Core_DAO_Note',
'table' => 'civicrm_note',
) ,
'CRM_Core_DAO_OptionValue' => array(
'name' => 'OptionValue',
'class' => 'CRM_Core_DAO_OptionValue',
'table' => 'civicrm_option_value',
) ,
'CRM_Core_DAO_Phone' => array(
'name' => 'Phone',
'class' => 'CRM_Core_DAO_Phone',
'table' => 'civicrm_phone',
) ,
'CRM_Core_DAO_StateProvince' => array(
'name' => 'StateProvince',
'class' => 'CRM_Core_DAO_StateProvince',
'table' => 'civicrm_state_province',
) ,
'CRM_Core_DAO_Tag' => array(
'name' => 'Tag',
'class' => 'CRM_Core_DAO_Tag',
'table' => 'civicrm_tag',
) ,
'CRM_Core_DAO_UFMatch' => array(
'name' => 'UFMatch',
'class' => 'CRM_Core_DAO_UFMatch',
'table' => 'civicrm_uf_match',
) ,
'CRM_Core_DAO_Timezone' => array(
'name' => 'Timezone',
'class' => 'CRM_Core_DAO_Timezone',
'table' => 'civicrm_timezone',
) ,
'CRM_Core_DAO_OpenID' => array(
'name' => 'OpenID',
'class' => 'CRM_Core_DAO_OpenID',
'table' => 'civicrm_openid',
) ,
'CRM_Core_DAO_Website' => array(
'name' => 'Website',
'class' => 'CRM_Core_DAO_Website',
'table' => 'civicrm_website',
) ,
'CRM_Core_DAO_Setting' => array(
'name' => 'Setting',
'class' => 'CRM_Core_DAO_Setting',
'table' => 'civicrm_setting',
) ,
'CRM_Core_DAO_PrintLabel' => array(
'name' => 'PrintLabel',
'class' => 'CRM_Core_DAO_PrintLabel',
'table' => 'civicrm_print_label',
) ,
'CRM_Core_DAO_WordReplacement' => array(
'name' => 'WordReplacement',
'class' => 'CRM_Core_DAO_WordReplacement',
'table' => 'civicrm_word_replacement',
) ,
'CRM_Core_DAO_StatusPreference' => array(
'name' => 'StatusPreference',
'class' => 'CRM_Core_DAO_StatusPreference',
'table' => 'civicrm_status_pref',
) ,
'CRM_ACL_DAO_Cache' => array(
'name' => 'Cache',
'class' => 'CRM_ACL_DAO_Cache',
'table' => 'civicrm_acl_cache',
) ,
'CRM_Contact_DAO_Group' => array(
'name' => 'Group',
'class' => 'CRM_Contact_DAO_Group',
'table' => 'civicrm_group',
) ,
'CRM_Contact_DAO_SubscriptionHistory' => array(
'name' => 'SubscriptionHistory',
'class' => 'CRM_Contact_DAO_SubscriptionHistory',
'table' => 'civicrm_subscription_history',
) ,
'CRM_Contact_DAO_GroupContactCache' => array(
'name' => 'GroupContactCache',
'class' => 'CRM_Contact_DAO_GroupContactCache',
'table' => 'civicrm_group_contact_cache',
) ,
'CRM_Contact_DAO_GroupNesting' => array(
'name' => 'GroupNesting',
'class' => 'CRM_Contact_DAO_GroupNesting',
'table' => 'civicrm_group_nesting',
) ,
'CRM_Contact_DAO_GroupOrganization' => array(
'name' => 'GroupOrganization',
'class' => 'CRM_Contact_DAO_GroupOrganization',
'table' => 'civicrm_group_organization',
) ,
'CRM_Mailing_Event_DAO_Subscribe' => array(
'name' => 'Subscribe',
'class' => 'CRM_Mailing_Event_DAO_Subscribe',
'table' => 'civicrm_mailing_event_subscribe',
) ,
'CRM_Mailing_Event_DAO_Confirm' => array(
'name' => 'Confirm',
'class' => 'CRM_Mailing_Event_DAO_Confirm',
'table' => 'civicrm_mailing_event_confirm',
) ,
'CRM_Contribute_DAO_ContributionPage' => array(
'name' => 'ContributionPage',
'class' => 'CRM_Contribute_DAO_ContributionPage',
'table' => 'civicrm_contribution_page',
) ,
'CRM_Contribute_DAO_Product' => array(
'name' => 'Product',
'class' => 'CRM_Contribute_DAO_Product',
'table' => 'civicrm_product',
) ,
'CRM_Contribute_DAO_PremiumsProduct' => array(
'name' => 'PremiumsProduct',
'class' => 'CRM_Contribute_DAO_PremiumsProduct',
'table' => 'civicrm_premiums_product',
) ,
'CRM_Contribute_DAO_Widget' => array(
'name' => 'Widget',
'class' => 'CRM_Contribute_DAO_Widget',
'table' => 'civicrm_contribution_widget',
) ,
'CRM_Financial_DAO_PaymentProcessor' => array(
'name' => 'PaymentProcessor',
'class' => 'CRM_Financial_DAO_PaymentProcessor',
'table' => 'civicrm_payment_processor',
) ,
'CRM_Financial_DAO_PaymentToken' => array(
'name' => 'PaymentToken',
'class' => 'CRM_Financial_DAO_PaymentToken',
'table' => 'civicrm_payment_token',
) ,
'CRM_SMS_DAO_Provider' => array(
'name' => 'Provider',
'class' => 'CRM_SMS_DAO_Provider',
'table' => 'civicrm_sms_provider',
) ,
'CRM_Member_DAO_MembershipType' => array(
'name' => 'MembershipType',
'class' => 'CRM_Member_DAO_MembershipType',
'table' => 'civicrm_membership_type',
) ,
'CRM_Member_DAO_MembershipBlock' => array(
'name' => 'MembershipBlock',
'class' => 'CRM_Member_DAO_MembershipBlock',
'table' => 'civicrm_membership_block',
) ,
'CRM_Case_DAO_Case' => array(
'name' => 'Case',
'class' => 'CRM_Case_DAO_Case',
'table' => 'civicrm_case',
) ,
'CRM_Case_DAO_CaseContact' => array(
'name' => 'CaseContact',
'class' => 'CRM_Case_DAO_CaseContact',
'table' => 'civicrm_case_contact',
) ,
'CRM_Pledge_DAO_Pledge' => array(
'name' => 'Pledge',
'class' => 'CRM_Pledge_DAO_Pledge',
'table' => 'civicrm_pledge',
) ,
'CRM_Report_DAO_ReportInstance' => array(
'name' => 'ReportInstance',
'class' => 'CRM_Report_DAO_ReportInstance',
'table' => 'civicrm_report_instance',
) ,
'CRM_Price_DAO_PriceSet' => array(
'name' => 'PriceSet',
'class' => 'CRM_Price_DAO_PriceSet',
'table' => 'civicrm_price_set',
) ,
'CRM_Price_DAO_PriceSetEntity' => array(
'name' => 'PriceSetEntity',
'class' => 'CRM_Price_DAO_PriceSetEntity',
'table' => 'civicrm_price_set_entity',
) ,
'CRM_Core_DAO_County' => array(
'name' => 'County',
'class' => 'CRM_Core_DAO_County',
'table' => 'civicrm_county',
) ,
'CRM_Core_DAO_Dashboard' => array(
'name' => 'Dashboard',
'class' => 'CRM_Core_DAO_Dashboard',
'table' => 'civicrm_dashboard',
) ,
'CRM_Core_DAO_Discount' => array(
'name' => 'Discount',
'class' => 'CRM_Core_DAO_Discount',
'table' => 'civicrm_discount',
) ,
'CRM_Core_DAO_EntityTag' => array(
'name' => 'EntityTag',
'class' => 'CRM_Core_DAO_EntityTag',
'table' => 'civicrm_entity_tag',
) ,
'CRM_Core_DAO_UFGroup' => array(
'name' => 'UFGroup',
'class' => 'CRM_Core_DAO_UFGroup',
'table' => 'civicrm_uf_group',
) ,
'CRM_Core_DAO_UFField' => array(
'name' => 'UFField',
'class' => 'CRM_Core_DAO_UFField',
'table' => 'civicrm_uf_field',
) ,
'CRM_Core_DAO_UFJoin' => array(
'name' => 'UFJoin',
'class' => 'CRM_Core_DAO_UFJoin',
'table' => 'civicrm_uf_join',
) ,
'CRM_Core_DAO_ActionSchedule' => array(
'name' => 'ActionSchedule',
'class' => 'CRM_Core_DAO_ActionSchedule',
'table' => 'civicrm_action_schedule',
) ,
'CRM_Core_DAO_ActionLog' => array(
'name' => 'ActionLog',
'class' => 'CRM_Core_DAO_ActionLog',
'table' => 'civicrm_action_log',
) ,
'CRM_Contact_DAO_DashboardContact' => array(
'name' => 'DashboardContact',
'class' => 'CRM_Contact_DAO_DashboardContact',
'table' => 'civicrm_dashboard_contact',
) ,
'CRM_Contact_DAO_Relationship' => array(
'name' => 'Relationship',
'class' => 'CRM_Contact_DAO_Relationship',
'table' => 'civicrm_relationship',
) ,
'CRM_Mailing_DAO_Mailing' => array(
'name' => 'Mailing',
'class' => 'CRM_Mailing_DAO_Mailing',
'table' => 'civicrm_mailing',
) ,
'CRM_Mailing_DAO_MailingGroup' => array(
'name' => 'MailingGroup',
'class' => 'CRM_Mailing_DAO_MailingGroup',
'table' => 'civicrm_mailing_group',
) ,
'CRM_Mailing_DAO_TrackableURL' => array(
'name' => 'TrackableURL',
'class' => 'CRM_Mailing_DAO_TrackableURL',
'table' => 'civicrm_mailing_trackable_url',
) ,
'CRM_Mailing_DAO_MailingJob' => array(
'name' => 'MailingJob',
'class' => 'CRM_Mailing_DAO_MailingJob',
'table' => 'civicrm_mailing_job',
) ,
'CRM_Mailing_DAO_Recipients' => array(
'name' => 'Recipients',
'class' => 'CRM_Mailing_DAO_Recipients',
'table' => 'civicrm_mailing_recipients',
) ,
'CRM_Mailing_DAO_Spool' => array(
'name' => 'Spool',
'class' => 'CRM_Mailing_DAO_Spool',
'table' => 'civicrm_mailing_spool',
) ,
'CRM_Mailing_Event_DAO_Queue' => array(
'name' => 'Queue',
'class' => 'CRM_Mailing_Event_DAO_Queue',
'table' => 'civicrm_mailing_event_queue',
) ,
'CRM_Mailing_Event_DAO_Bounce' => array(
'name' => 'Bounce',
'class' => 'CRM_Mailing_Event_DAO_Bounce',
'table' => 'civicrm_mailing_event_bounce',
) ,
'CRM_Mailing_Event_DAO_Delivered' => array(
'name' => 'Delivered',
'class' => 'CRM_Mailing_Event_DAO_Delivered',
'table' => 'civicrm_mailing_event_delivered',
) ,
'CRM_Mailing_Event_DAO_Forward' => array(
'name' => 'Forward',
'class' => 'CRM_Mailing_Event_DAO_Forward',
'table' => 'civicrm_mailing_event_forward',
) ,
'CRM_Mailing_Event_DAO_Opened' => array(
'name' => 'Opened',
'class' => 'CRM_Mailing_Event_DAO_Opened',
'table' => 'civicrm_mailing_event_opened',
) ,
'CRM_Mailing_Event_DAO_Reply' => array(
'name' => 'Reply',
'class' => 'CRM_Mailing_Event_DAO_Reply',
'table' => 'civicrm_mailing_event_reply',
) ,
'CRM_Mailing_Event_DAO_TrackableURLOpen' => array(
'name' => 'TrackableURLOpen',
'class' => 'CRM_Mailing_Event_DAO_TrackableURLOpen',
'table' => 'civicrm_mailing_event_trackable_url_open',
) ,
'CRM_Mailing_Event_DAO_Unsubscribe' => array(
'name' => 'Unsubscribe',
'class' => 'CRM_Mailing_Event_DAO_Unsubscribe',
'table' => 'civicrm_mailing_event_unsubscribe',
) ,
'CRM_Contribute_DAO_ContributionRecur' => array(
'name' => 'ContributionRecur',
'class' => 'CRM_Contribute_DAO_ContributionRecur',
'table' => 'civicrm_contribution_recur',
) ,
'CRM_Financial_DAO_FinancialTrxn' => array(
'name' => 'FinancialTrxn',
'class' => 'CRM_Financial_DAO_FinancialTrxn',
'table' => 'civicrm_financial_trxn',
) ,
'CRM_Member_DAO_Membership' => array(
'name' => 'Membership',
'class' => 'CRM_Member_DAO_Membership',
'table' => 'civicrm_membership',
) ,
'CRM_Member_DAO_MembershipLog' => array(
'name' => 'MembershipLog',
'class' => 'CRM_Member_DAO_MembershipLog',
'table' => 'civicrm_membership_log',
) ,
'CRM_Activity_DAO_Activity' => array(
'name' => 'Activity',
'class' => 'CRM_Activity_DAO_Activity',
'table' => 'civicrm_activity',
) ,
'CRM_Activity_DAO_ActivityContact' => array(
'name' => 'ActivityContact',
'class' => 'CRM_Activity_DAO_ActivityContact',
'table' => 'civicrm_activity_contact',
) ,
'CRM_Case_DAO_CaseActivity' => array(
'name' => 'CaseActivity',
'class' => 'CRM_Case_DAO_CaseActivity',
'table' => 'civicrm_case_activity',
) ,
'CRM_Price_DAO_PriceField' => array(
'name' => 'PriceField',
'class' => 'CRM_Price_DAO_PriceField',
'table' => 'civicrm_price_field',
) ,
'CRM_Price_DAO_PriceFieldValue' => array(
'name' => 'PriceFieldValue',
'class' => 'CRM_Price_DAO_PriceFieldValue',
'table' => 'civicrm_price_field_value',
) ,
'CRM_PCP_DAO_PCPBlock' => array(
'name' => 'PCPBlock',
'class' => 'CRM_PCP_DAO_PCPBlock',
'table' => 'civicrm_pcp_block',
) ,
'CRM_Core_DAO_Address' => array(
'name' => 'Address',
'class' => 'CRM_Core_DAO_Address',
'table' => 'civicrm_address',
) ,
'CRM_Core_DAO_LocBlock' => array(
'name' => 'LocBlock',
'class' => 'CRM_Core_DAO_LocBlock',
'table' => 'civicrm_loc_block',
) ,
'CRM_Contact_DAO_GroupContact' => array(
'name' => 'GroupContact',
'class' => 'CRM_Contact_DAO_GroupContact',
'table' => 'civicrm_group_contact',
) ,
'CRM_Contribute_DAO_Contribution' => array(
'name' => 'Contribution',
'class' => 'CRM_Contribute_DAO_Contribution',
'table' => 'civicrm_contribution',
) ,
'CRM_Contribute_DAO_ContributionProduct' => array(
'name' => 'ContributionProduct',
'class' => 'CRM_Contribute_DAO_ContributionProduct',
'table' => 'civicrm_contribution_product',
) ,
'CRM_Contribute_DAO_ContributionSoft' => array(
'name' => 'ContributionSoft',
'class' => 'CRM_Contribute_DAO_ContributionSoft',
'table' => 'civicrm_contribution_soft',
) ,
'CRM_Financial_DAO_EntityFinancialTrxn' => array(
'name' => 'EntityFinancialTrxn',
'class' => 'CRM_Financial_DAO_EntityFinancialTrxn',
'table' => 'civicrm_entity_financial_trxn',
) ,
'CRM_Member_DAO_MembershipPayment' => array(
'name' => 'MembershipPayment',
'class' => 'CRM_Member_DAO_MembershipPayment',
'table' => 'civicrm_membership_payment',
) ,
'CRM_Event_DAO_Event' => array(
'name' => 'Event',
'class' => 'CRM_Event_DAO_Event',
'table' => 'civicrm_event',
) ,
'CRM_Event_DAO_Participant' => array(
'name' => 'Participant',
'class' => 'CRM_Event_DAO_Participant',
'table' => 'civicrm_participant',
) ,
'CRM_Event_DAO_ParticipantPayment' => array(
'name' => 'ParticipantPayment',
'class' => 'CRM_Event_DAO_ParticipantPayment',
'table' => 'civicrm_participant_payment',
) ,
'CRM_Event_Cart_DAO_EventInCart' => array(
'name' => 'EventInCart',
'class' => 'CRM_Event_Cart_DAO_EventInCart',
'table' => 'civicrm_events_in_carts',
) ,
'CRM_Pledge_DAO_PledgePayment' => array(
'name' => 'PledgePayment',
'class' => 'CRM_Pledge_DAO_PledgePayment',
'table' => 'civicrm_pledge_payment',
) ,
'CRM_Price_DAO_LineItem' => array(
'name' => 'LineItem',
'class' => 'CRM_Price_DAO_LineItem',
'table' => 'civicrm_line_item',
) ,
);

View file

@ -0,0 +1,381 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_Core_DAO_AllCoreTables {
private static $tables = NULL;
private static $daoToClass = NULL;
private static $entityTypes = NULL;
/**
* Initialise.
*
* @param bool $fresh
*/
public static function init($fresh = FALSE) {
static $init = FALSE;
if ($init && !$fresh) {
return;
}
Civi::$statics[__CLASS__] = array();
$file = preg_replace('/\.php$/', '.data.php', __FILE__);
$entityTypes = require $file;
CRM_Utils_Hook::entityTypes($entityTypes);
self::$entityTypes = array();
self::$tables = array();
self::$daoToClass = array();
foreach ($entityTypes as $entityType) {
self::registerEntityType(
$entityType['name'],
$entityType['class'],
$entityType['table'],
isset($entityType['fields_callback']) ? $entityType['fields_callback'] : NULL,
isset($entityType['links_callback']) ? $entityType['links_callback'] : NULL
);
}
$init = TRUE;
}
/**
* (Quasi-Private) Do not call externally (except for unit-testing)
*
* @param string $daoName
* @param string $className
* @param string $tableName
* @param string $fields_callback
* @param string $links_callback
*/
public static function registerEntityType($daoName, $className, $tableName, $fields_callback = NULL, $links_callback = NULL) {
self::$daoToClass[$daoName] = $className;
self::$tables[$tableName] = $className;
self::$entityTypes[$className] = array(
'name' => $daoName,
'class' => $className,
'table' => $tableName,
'fields_callback' => $fields_callback,
'links_callback' => $links_callback,
);
}
/**
* @return array
* Ex: $result['CRM_Contact_DAO_Contact']['table'] == 'civicrm_contact';
*/
public static function get() {
self::init();
return self::$entityTypes;
}
/**
* @return array
* List of SQL table names.
*/
public static function tables() {
self::init();
return self::$tables;
}
/**
* @return array
* List of indices.
*/
public static function indices($localize = TRUE) {
$indices = array();
self::init();
foreach (self::$daoToClass as $class) {
if (is_callable(array($class, 'indices'))) {
$indices[$class::getTableName()] = $class::indices($localize);
}
}
return $indices;
}
/**
* Modify indices to account for localization options.
*
* @param CRM_Core_DAO $class DAO class
* @param array $originalIndices index definitions before localization
*
* @return array
* index definitions after localization
*/
public static function multilingualize($class, $originalIndices) {
$domain = new CRM_Core_DAO_Domain();
$domain->find(TRUE);
$locales = explode(CRM_Core_DAO::VALUE_SEPARATOR, $domain->locales);
if (CRM_Utils_System::isNull($locales)) {
return $originalIndices;
}
$classFields = $class::fields();
$finalIndices = array();
foreach ($originalIndices as $index) {
if ($index['localizable']) {
foreach ($locales as $locale) {
$localIndex = $index;
$localIndex['name'] .= "_" . $locale;
$fields = array();
foreach ($localIndex['field'] as $field) {
$baseField = explode('(', $field);
if ($classFields[$baseField[0]]['localizable']) {
// field name may have eg (3) at end for prefix length
// last_name => last_name_fr_FR
// last_name(3) => last_name_fr_FR(3)
$fields[] = preg_replace('/^([^(]+)(\(\d+\)|)$/', '${1}_' . $locale . '${2}', $field);
}
else {
$fields[] = $field;
}
}
$localIndex['field'] = $fields;
$finalIndices[$localIndex['name']] = $localIndex;
}
}
else {
$finalIndices[$index['name']] = $index;
}
}
CRM_Core_BAO_SchemaHandler::addIndexSignature(self::getTableForClass($class), $finalIndices);
return $finalIndices;
}
/**
* @return array
* Mapping from brief-names to class-names.
* Ex: $result['Contact'] == 'CRM_Contact_DAO_Contact'.
*/
public static function daoToClass() {
self::init();
return self::$daoToClass;
}
/**
* @return array
* Mapping from table-names to class-names.
* Ex: $result['civicrm_contact'] == 'CRM_Contact_DAO_Contact'.
*/
public static function getCoreTables() {
return self::tables();
}
/**
* Determine whether $tableName is a core table.
*
* @param string $tableName
* @return bool
*/
public static function isCoreTable($tableName) {
return FALSE !== array_search($tableName, self::tables());
}
/**
* Get the DAO for the class.
*
* @param string $className
*
* @return string
*/
public static function getCanonicalClassName($className) {
return str_replace('_BAO_', '_DAO_', $className);
}
/**
* Get a list of all DAO classes.
*
* @return array
* List of class names.
*/
public static function getClasses() {
return array_values(self::daoToClass());
}
/**
* Get the classname for the table.
*
* @param string $tableName
* @return string
*/
public static function getClassForTable($tableName) {
//CRM-19677: on multilingual setup, trim locale from $tableName to fetch class name
if (CRM_Core_I18n::isMultilingual()) {
global $dbLocale;
$tableName = str_replace($dbLocale, '', $tableName);
}
return CRM_Utils_Array::value($tableName, self::tables());
}
/**
* Given a brief-name, determine the full class-name.
*
* @param string $daoName
* Ex: 'Contact'.
* @return string|NULL
* Ex: 'CRM_Contact_DAO_Contact'.
*/
public static function getFullName($daoName) {
return CRM_Utils_Array::value($daoName, self::daoToClass());
}
/**
* Given a full class-name, determine the brief-name.
*
* @param string $className
* Ex: 'CRM_Contact_DAO_Contact'.
* @return string|NULL
* Ex: 'Contact'.
*/
public static function getBriefName($className) {
return CRM_Utils_Array::value($className, array_flip(self::daoToClass()));
}
/**
* @param string $className DAO or BAO name
* @return string|FALSE SQL table name
*/
public static function getTableForClass($className) {
return array_search(self::getCanonicalClassName($className),
self::tables());
}
/**
* Reinitialise cache.
*
* @param bool $fresh
*/
public static function reinitializeCache($fresh = FALSE) {
self::init($fresh);
}
/**
* (Quasi-Private) Do not call externally. For use by DAOs.
*
* @param string $dao
* Ex: 'CRM_Core_DAO_Address'.
* @param string $labelName
* Ex: 'address'.
* @param bool $prefix
* @param array $foreignDAOs
* @return array
*/
public static function getExports($dao, $labelName, $prefix, $foreignDAOs) {
// Bug-level compatibility -- or sane behavior?
$cacheKey = $dao . ':export';
// $cacheKey = $dao . ':' . ($prefix ? 'export-prefix' : 'export');
if (!isset(Civi::$statics[__CLASS__][$cacheKey])) {
$exports = array();
$fields = $dao::fields();
foreach ($fields as $name => $field) {
if (CRM_Utils_Array::value('export', $field)) {
if ($prefix) {
$exports[$labelName] = & $fields[$name];
}
else {
$exports[$name] = & $fields[$name];
}
}
}
foreach ($foreignDAOs as $foreignDAO) {
$exports = array_merge($exports, $foreignDAO::export(TRUE));
}
Civi::$statics[__CLASS__][$cacheKey] = $exports;
}
return Civi::$statics[__CLASS__][$cacheKey];
}
/**
* (Quasi-Private) Do not call externally. For use by DAOs.
*
* @param string $dao
* Ex: 'CRM_Core_DAO_Address'.
* @param string $labelName
* Ex: 'address'.
* @param bool $prefix
* @param array $foreignDAOs
* @return array
*/
public static function getImports($dao, $labelName, $prefix, $foreignDAOs) {
// Bug-level compatibility -- or sane behavior?
$cacheKey = $dao . ':import';
// $cacheKey = $dao . ':' . ($prefix ? 'import-prefix' : 'import');
if (!isset(Civi::$statics[__CLASS__][$cacheKey])) {
$imports = array();
$fields = $dao::fields();
foreach ($fields as $name => $field) {
if (CRM_Utils_Array::value('import', $field)) {
if ($prefix) {
$imports[$labelName] = & $fields[$name];
}
else {
$imports[$name] = & $fields[$name];
}
}
}
foreach ($foreignDAOs as $foreignDAO) {
$imports = array_merge($imports, $foreignDAO::import(TRUE));
}
Civi::$statics[__CLASS__][$cacheKey] = $imports;
}
return Civi::$statics[__CLASS__][$cacheKey];
}
/**
* (Quasi-Private) Do not call externally. For use by DAOs.
*
* Apply any third-party alterations to the `fields()`.
*
* @param string $className
* @param string $event
* @param mixed $values
*/
public static function invoke($className, $event, &$values) {
self::init();
if (isset(self::$entityTypes[$className][$event])) {
foreach (self::$entityTypes[$className][$event] as $filter) {
$args = array($className, &$values);
\Civi\Core\Resolver::singleton()->call($filter, $args);
}
}
}
}

View file

@ -0,0 +1,282 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
* Generated from xml/schema/CRM/Core/Cache.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:7e57800355db0e3aa11c15d6c73bf9a2)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Core_DAO_Cache constructor.
*/
class CRM_Core_DAO_Cache extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_cache';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = false;
/**
*
* @var int unsigned
*/
public $id;
/**
* group name for cache element, useful in cleaning cache elements
*
* @var string
*/
public $group_name;
/**
* Unique path name for cache element
*
* @var string
*/
public $path;
/**
* data associated with this path
*
* @var longtext
*/
public $data;
/**
* Component that this menu item belongs to
*
* @var int unsigned
*/
public $component_id;
/**
* When was the cache item created
*
* @var timestamp
*/
public $created_date;
/**
* When should the cache item expire
*
* @var timestamp
*/
public $expired_date;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_cache';
parent::__construct();
}
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'component_id', 'civicrm_component', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
/**
* Returns all the column names of this table
*
* @return array
*/
static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
Civi::$statics[__CLASS__]['fields'] = array(
'id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'required' => true,
'table_name' => 'civicrm_cache',
'entity' => 'Cache',
'bao' => 'CRM_Core_BAO_Cache',
'localizable' => 0,
) ,
'group_name' => array(
'name' => 'group_name',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Group Name') ,
'description' => 'group name for cache element, useful in cleaning cache elements',
'required' => true,
'maxlength' => 32,
'size' => CRM_Utils_Type::MEDIUM,
'table_name' => 'civicrm_cache',
'entity' => 'Cache',
'bao' => 'CRM_Core_BAO_Cache',
'localizable' => 0,
) ,
'path' => array(
'name' => 'path',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Path') ,
'description' => 'Unique path name for cache element',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_cache',
'entity' => 'Cache',
'bao' => 'CRM_Core_BAO_Cache',
'localizable' => 0,
) ,
'data' => array(
'name' => 'data',
'type' => CRM_Utils_Type::T_LONGTEXT,
'title' => ts('Data') ,
'description' => 'data associated with this path',
'table_name' => 'civicrm_cache',
'entity' => 'Cache',
'bao' => 'CRM_Core_BAO_Cache',
'localizable' => 0,
) ,
'component_id' => array(
'name' => 'component_id',
'type' => CRM_Utils_Type::T_INT,
'description' => 'Component that this menu item belongs to',
'table_name' => 'civicrm_cache',
'entity' => 'Cache',
'bao' => 'CRM_Core_BAO_Cache',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_Component',
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'table' => 'civicrm_component',
'keyColumn' => 'id',
'labelColumn' => 'name',
)
) ,
'created_date' => array(
'name' => 'created_date',
'type' => CRM_Utils_Type::T_TIMESTAMP,
'title' => ts('Created Date') ,
'description' => 'When was the cache item created',
'default' => 'CURRENT_TIMESTAMP',
'table_name' => 'civicrm_cache',
'entity' => 'Cache',
'bao' => 'CRM_Core_BAO_Cache',
'localizable' => 0,
) ,
'expired_date' => array(
'name' => 'expired_date',
'type' => CRM_Utils_Type::T_TIMESTAMP,
'title' => ts('Expired Date') ,
'description' => 'When should the cache item expire',
'required' => false,
'default' => 'NULL',
'table_name' => 'civicrm_cache',
'entity' => 'Cache',
'bao' => 'CRM_Core_BAO_Cache',
'localizable' => 0,
) ,
);
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
static function getTableName() {
return self::$_tableName;
}
/**
* Returns if this table needs to be logged
*
* @return boolean
*/
function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
static function &import($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'cache', $prefix, array());
return $r;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
static function &export($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'cache', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array(
'UI_group_path_date' => array(
'name' => 'UI_group_path_date',
'field' => array(
0 => 'group_name',
1 => 'path',
2 => 'created_date',
) ,
'localizable' => false,
'unique' => true,
'sig' => 'civicrm_cache::1::group_name::path::created_date',
) ,
);
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

View file

@ -0,0 +1,186 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
* Generated from xml/schema/CRM/Core/Component.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:14ca0040d5a5656fd5dd91ad60a8ac89)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Core_DAO_Component constructor.
*/
class CRM_Core_DAO_Component extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_component';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = false;
/**
* Component ID
*
* @var int unsigned
*/
public $id;
/**
* Name of the component.
*
* @var string
*/
public $name;
/**
* Path to components main directory in a form of a class
namespace.
*
* @var string
*/
public $namespace;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_component';
parent::__construct();
}
/**
* Returns all the column names of this table
*
* @return array
*/
static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
Civi::$statics[__CLASS__]['fields'] = array(
'id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'description' => 'Component ID',
'required' => true,
'table_name' => 'civicrm_component',
'entity' => 'Component',
'bao' => 'CRM_Core_DAO_Component',
'localizable' => 0,
) ,
'name' => array(
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Component name') ,
'description' => 'Name of the component.',
'required' => true,
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_component',
'entity' => 'Component',
'bao' => 'CRM_Core_DAO_Component',
'localizable' => 0,
) ,
'namespace' => array(
'name' => 'namespace',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Namespace reserved for component.') ,
'description' => 'Path to components main directory in a form of a class
namespace.
',
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_component',
'entity' => 'Component',
'bao' => 'CRM_Core_DAO_Component',
'localizable' => 0,
) ,
);
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
static function getTableName() {
return self::$_tableName;
}
/**
* Returns if this table needs to be logged
*
* @return boolean
*/
function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
static function &import($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'component', $prefix, array());
return $r;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
static function &export($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'component', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array();
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

View file

@ -0,0 +1,319 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
* Generated from xml/schema/CRM/Core/Country.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:e01f7b6fdc1c22bcf6fbc125ea2d894a)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Core_DAO_Country constructor.
*/
class CRM_Core_DAO_Country extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_country';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = false;
/**
* Country Id
*
* @var int unsigned
*/
public $id;
/**
* Country Name
*
* @var string
*/
public $name;
/**
* ISO Code
*
* @var string
*/
public $iso_code;
/**
* National prefix to be used when dialing TO this country.
*
* @var string
*/
public $country_code;
/**
* Foreign key to civicrm_address_format.id.
*
* @var int unsigned
*/
public $address_format_id;
/**
* International direct dialing prefix from within the country TO another country
*
* @var string
*/
public $idd_prefix;
/**
* Access prefix to call within a country to a different area
*
* @var string
*/
public $ndd_prefix;
/**
* Foreign key to civicrm_worldregion.id.
*
* @var int unsigned
*/
public $region_id;
/**
* Should state/province be displayed as abbreviation for contacts from this country?
*
* @var boolean
*/
public $is_province_abbreviated;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_country';
parent::__construct();
}
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'address_format_id', 'civicrm_address_format', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'region_id', 'civicrm_worldregion', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
/**
* Returns all the column names of this table
*
* @return array
*/
static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
Civi::$statics[__CLASS__]['fields'] = array(
'id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Country ID') ,
'description' => 'Country Id',
'required' => true,
'table_name' => 'civicrm_country',
'entity' => 'Country',
'bao' => 'CRM_Core_BAO_Country',
'localizable' => 0,
) ,
'name' => array(
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Country') ,
'description' => 'Country Name',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'import' => true,
'where' => 'civicrm_country.name',
'headerPattern' => '/country/i',
'dataPattern' => '/^[A-Z][a-z]+\.?(\s+[A-Z][a-z]+){0,3}$/',
'export' => true,
'table_name' => 'civicrm_country',
'entity' => 'Country',
'bao' => 'CRM_Core_BAO_Country',
'localizable' => 0,
) ,
'iso_code' => array(
'name' => 'iso_code',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Country ISO Code') ,
'description' => 'ISO Code',
'maxlength' => 2,
'size' => CRM_Utils_Type::TWO,
'table_name' => 'civicrm_country',
'entity' => 'Country',
'bao' => 'CRM_Core_BAO_Country',
'localizable' => 0,
) ,
'country_code' => array(
'name' => 'country_code',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Country Phone Prefix') ,
'description' => 'National prefix to be used when dialing TO this country.',
'maxlength' => 4,
'size' => CRM_Utils_Type::FOUR,
'table_name' => 'civicrm_country',
'entity' => 'Country',
'bao' => 'CRM_Core_BAO_Country',
'localizable' => 0,
) ,
'address_format_id' => array(
'name' => 'address_format_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Address Format') ,
'description' => 'Foreign key to civicrm_address_format.id.',
'table_name' => 'civicrm_country',
'entity' => 'Country',
'bao' => 'CRM_Core_BAO_Country',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_AddressFormat',
) ,
'idd_prefix' => array(
'name' => 'idd_prefix',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Outgoing Phone Prefix') ,
'description' => 'International direct dialing prefix from within the country TO another country',
'maxlength' => 4,
'size' => CRM_Utils_Type::FOUR,
'table_name' => 'civicrm_country',
'entity' => 'Country',
'bao' => 'CRM_Core_BAO_Country',
'localizable' => 0,
) ,
'ndd_prefix' => array(
'name' => 'ndd_prefix',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Area Code') ,
'description' => 'Access prefix to call within a country to a different area',
'maxlength' => 4,
'size' => CRM_Utils_Type::FOUR,
'table_name' => 'civicrm_country',
'entity' => 'Country',
'bao' => 'CRM_Core_BAO_Country',
'localizable' => 0,
) ,
'region_id' => array(
'name' => 'region_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Region') ,
'description' => 'Foreign key to civicrm_worldregion.id.',
'required' => true,
'table_name' => 'civicrm_country',
'entity' => 'Country',
'bao' => 'CRM_Core_BAO_Country',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_Worldregion',
) ,
'is_province_abbreviated' => array(
'name' => 'is_province_abbreviated',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Abbreviate Province?') ,
'description' => 'Should state/province be displayed as abbreviation for contacts from this country?',
'table_name' => 'civicrm_country',
'entity' => 'Country',
'bao' => 'CRM_Core_BAO_Country',
'localizable' => 0,
) ,
);
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
static function getTableName() {
return self::$_tableName;
}
/**
* Returns if this table needs to be logged
*
* @return boolean
*/
function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
static function &import($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'country', $prefix, array());
return $r;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
static function &export($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'country', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array(
'UI_name_iso_code' => array(
'name' => 'UI_name_iso_code',
'field' => array(
0 => 'name',
1 => 'iso_code',
) ,
'localizable' => false,
'unique' => true,
'sig' => 'civicrm_country::1::name::iso_code',
) ,
);
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

View file

@ -0,0 +1,231 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
* Generated from xml/schema/CRM/Core/County.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:deaadd903f7cfee93f6b70fb2e9fc012)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Core_DAO_County constructor.
*/
class CRM_Core_DAO_County extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_county';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = false;
/**
* County ID
*
* @var int unsigned
*/
public $id;
/**
* Name of County
*
* @var string
*/
public $name;
/**
* 2-4 Character Abbreviation of County
*
* @var string
*/
public $abbreviation;
/**
* ID of State/Province that County belongs
*
* @var int unsigned
*/
public $state_province_id;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_county';
parent::__construct();
}
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'state_province_id', 'civicrm_state_province', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
/**
* Returns all the column names of this table
*
* @return array
*/
static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
Civi::$statics[__CLASS__]['fields'] = array(
'id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('County ID') ,
'description' => 'County ID',
'required' => true,
'table_name' => 'civicrm_county',
'entity' => 'County',
'bao' => 'CRM_Core_DAO_County',
'localizable' => 0,
) ,
'name' => array(
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('County') ,
'description' => 'Name of County',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'import' => true,
'where' => 'civicrm_county.name',
'headerPattern' => '/county/i',
'dataPattern' => '/[A-Z]{2}/',
'export' => true,
'table_name' => 'civicrm_county',
'entity' => 'County',
'bao' => 'CRM_Core_DAO_County',
'localizable' => 0,
) ,
'abbreviation' => array(
'name' => 'abbreviation',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('County Abbreviation') ,
'description' => '2-4 Character Abbreviation of County',
'maxlength' => 4,
'size' => CRM_Utils_Type::FOUR,
'table_name' => 'civicrm_county',
'entity' => 'County',
'bao' => 'CRM_Core_DAO_County',
'localizable' => 0,
) ,
'state_province_id' => array(
'name' => 'state_province_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('State') ,
'description' => 'ID of State/Province that County belongs',
'required' => true,
'table_name' => 'civicrm_county',
'entity' => 'County',
'bao' => 'CRM_Core_DAO_County',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_StateProvince',
) ,
);
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
static function getTableName() {
return self::$_tableName;
}
/**
* Returns if this table needs to be logged
*
* @return boolean
*/
function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
static function &import($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'county', $prefix, array());
return $r;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
static function &export($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'county', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array(
'UI_name_state_id' => array(
'name' => 'UI_name_state_id',
'field' => array(
0 => 'name',
1 => 'state_province_id',
) ,
'localizable' => false,
'unique' => true,
'sig' => 'civicrm_county::1::name::state_province_id',
) ,
);
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

View file

@ -0,0 +1,692 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
* Generated from xml/schema/CRM/Core/CustomField.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:6c4ced0a0ac204cde5c048d37aee6057)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Core_DAO_CustomField constructor.
*/
class CRM_Core_DAO_CustomField extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_custom_field';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = true;
/**
* Unique Custom Field ID
*
* @var int unsigned
*/
public $id;
/**
* FK to civicrm_custom_group.
*
* @var int unsigned
*/
public $custom_group_id;
/**
* Variable name/programmatic handle for this group.
*
* @var string
*/
public $name;
/**
* Text for form field label (also friendly name for administering this custom property).
*
* @var string
*/
public $label;
/**
* Controls location of data storage in extended_data table.
*
* @var string
*/
public $data_type;
/**
* HTML types plus several built-in extended types.
*
* @var string
*/
public $html_type;
/**
* Use form_options.is_default for field_types which use options.
*
* @var string
*/
public $default_value;
/**
* Is a value required for this property.
*
* @var boolean
*/
public $is_required;
/**
* Is this property searchable.
*
* @var boolean
*/
public $is_searchable;
/**
* Is this property range searchable.
*
* @var boolean
*/
public $is_search_range;
/**
* Controls field display order within an extended property group.
*
* @var int
*/
public $weight;
/**
* Description and/or help text to display before this field.
*
* @var text
*/
public $help_pre;
/**
* Description and/or help text to display after this field.
*
* @var text
*/
public $help_post;
/**
* Optional format instructions for specific field types, like date types.
*
* @var string
*/
public $mask;
/**
* Store collection of type-appropriate attributes, e.g. textarea needs rows/cols attributes
*
* @var string
*/
public $attributes;
/**
* Optional scripting attributes for field.
*
* @var string
*/
public $javascript;
/**
* Is this property active?
*
* @var boolean
*/
public $is_active;
/**
* Is this property set by PHP Code? A code field is viewable but not editable
*
* @var boolean
*/
public $is_view;
/**
* number of options per line for checkbox and radio
*
* @var int unsigned
*/
public $options_per_line;
/**
* field length if alphanumeric
*
* @var int unsigned
*/
public $text_length;
/**
* Date may be up to start_date_years years prior to the current date.
*
* @var int
*/
public $start_date_years;
/**
* Date may be up to end_date_years years after the current date.
*
* @var int
*/
public $end_date_years;
/**
* date format for custom date
*
* @var string
*/
public $date_format;
/**
* time format for custom date
*
* @var int unsigned
*/
public $time_format;
/**
* Number of columns in Note Field
*
* @var int unsigned
*/
public $note_columns;
/**
* Number of rows in Note Field
*
* @var int unsigned
*/
public $note_rows;
/**
* Name of the column that holds the values for this field.
*
* @var string
*/
public $column_name;
/**
* For elements with options, the option group id that is used
*
* @var int unsigned
*/
public $option_group_id;
/**
* Stores Contact Get API params contact reference custom fields. May be used for other filters in the future.
*
* @var string
*/
public $filter;
/**
* Should the multi-record custom field values be displayed in tab table listing
*
* @var boolean
*/
public $in_selector;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_custom_field';
parent::__construct();
}
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'custom_group_id', 'civicrm_custom_group', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
/**
* Returns all the column names of this table
*
* @return array
*/
static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
Civi::$statics[__CLASS__]['fields'] = array(
'id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Custom Field ID') ,
'description' => 'Unique Custom Field ID',
'required' => true,
'table_name' => 'civicrm_custom_field',
'entity' => 'CustomField',
'bao' => 'CRM_Core_BAO_CustomField',
'localizable' => 0,
) ,
'custom_group_id' => array(
'name' => 'custom_group_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Custom Group') ,
'description' => 'FK to civicrm_custom_group.',
'required' => true,
'table_name' => 'civicrm_custom_field',
'entity' => 'CustomField',
'bao' => 'CRM_Core_BAO_CustomField',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_CustomGroup',
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'table' => 'civicrm_custom_group',
'keyColumn' => 'id',
'labelColumn' => 'title',
)
) ,
'name' => array(
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Custom Field Name') ,
'description' => 'Variable name/programmatic handle for this group.',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_custom_field',
'entity' => 'CustomField',
'bao' => 'CRM_Core_BAO_CustomField',
'localizable' => 0,
) ,
'label' => array(
'name' => 'label',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Custom Field Label') ,
'description' => 'Text for form field label (also friendly name for administering this custom property).',
'required' => true,
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_custom_field',
'entity' => 'CustomField',
'bao' => 'CRM_Core_BAO_CustomField',
'localizable' => 1,
) ,
'data_type' => array(
'name' => 'data_type',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Custom Field Data Type') ,
'description' => 'Controls location of data storage in extended_data table.',
'required' => true,
'maxlength' => 16,
'size' => CRM_Utils_Type::TWELVE,
'table_name' => 'civicrm_custom_field',
'entity' => 'CustomField',
'bao' => 'CRM_Core_BAO_CustomField',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'callback' => 'CRM_Core_BAO_CustomField::dataType',
)
) ,
'html_type' => array(
'name' => 'html_type',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Custom Field HTML Type') ,
'description' => 'HTML types plus several built-in extended types.',
'required' => true,
'maxlength' => 32,
'size' => CRM_Utils_Type::MEDIUM,
'table_name' => 'civicrm_custom_field',
'entity' => 'CustomField',
'bao' => 'CRM_Core_BAO_CustomField',
'localizable' => 0,
'pseudoconstant' => array(
'callback' => 'CRM_Core_SelectValues::customHtmlType',
)
) ,
'default_value' => array(
'name' => 'default_value',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Custom Field Default') ,
'description' => 'Use form_options.is_default for field_types which use options.',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_custom_field',
'entity' => 'CustomField',
'bao' => 'CRM_Core_BAO_CustomField',
'localizable' => 0,
) ,
'is_required' => array(
'name' => 'is_required',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Custom Field Is Required?') ,
'description' => 'Is a value required for this property.',
'table_name' => 'civicrm_custom_field',
'entity' => 'CustomField',
'bao' => 'CRM_Core_BAO_CustomField',
'localizable' => 0,
) ,
'is_searchable' => array(
'name' => 'is_searchable',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Allow Searching on Field?') ,
'description' => 'Is this property searchable.',
'table_name' => 'civicrm_custom_field',
'entity' => 'CustomField',
'bao' => 'CRM_Core_BAO_CustomField',
'localizable' => 0,
) ,
'is_search_range' => array(
'name' => 'is_search_range',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Search as a Range') ,
'description' => 'Is this property range searchable.',
'table_name' => 'civicrm_custom_field',
'entity' => 'CustomField',
'bao' => 'CRM_Core_BAO_CustomField',
'localizable' => 0,
) ,
'weight' => array(
'name' => 'weight',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Order') ,
'description' => 'Controls field display order within an extended property group.',
'required' => true,
'default' => '1',
'table_name' => 'civicrm_custom_field',
'entity' => 'CustomField',
'bao' => 'CRM_Core_BAO_CustomField',
'localizable' => 0,
) ,
'help_pre' => array(
'name' => 'help_pre',
'type' => CRM_Utils_Type::T_TEXT,
'title' => ts('Custom Field Pre Text') ,
'description' => 'Description and/or help text to display before this field.',
'table_name' => 'civicrm_custom_field',
'entity' => 'CustomField',
'bao' => 'CRM_Core_BAO_CustomField',
'localizable' => 1,
) ,
'help_post' => array(
'name' => 'help_post',
'type' => CRM_Utils_Type::T_TEXT,
'title' => ts('Custom Field Post Text') ,
'description' => 'Description and/or help text to display after this field.',
'table_name' => 'civicrm_custom_field',
'entity' => 'CustomField',
'bao' => 'CRM_Core_BAO_CustomField',
'localizable' => 1,
) ,
'mask' => array(
'name' => 'mask',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Custom Field Formatting') ,
'description' => 'Optional format instructions for specific field types, like date types.',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_custom_field',
'entity' => 'CustomField',
'bao' => 'CRM_Core_BAO_CustomField',
'localizable' => 0,
) ,
'attributes' => array(
'name' => 'attributes',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Custom Field Attributes') ,
'description' => 'Store collection of type-appropriate attributes, e.g. textarea needs rows/cols attributes',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_custom_field',
'entity' => 'CustomField',
'bao' => 'CRM_Core_BAO_CustomField',
'localizable' => 0,
) ,
'javascript' => array(
'name' => 'javascript',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Custom Field Javascript') ,
'description' => 'Optional scripting attributes for field.',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_custom_field',
'entity' => 'CustomField',
'bao' => 'CRM_Core_BAO_CustomField',
'localizable' => 0,
) ,
'is_active' => array(
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Custom Field Is Active?') ,
'description' => 'Is this property active?',
'table_name' => 'civicrm_custom_field',
'entity' => 'CustomField',
'bao' => 'CRM_Core_BAO_CustomField',
'localizable' => 0,
) ,
'is_view' => array(
'name' => 'is_view',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Field is Viewable') ,
'description' => 'Is this property set by PHP Code? A code field is viewable but not editable',
'table_name' => 'civicrm_custom_field',
'entity' => 'CustomField',
'bao' => 'CRM_Core_BAO_CustomField',
'localizable' => 0,
) ,
'options_per_line' => array(
'name' => 'options_per_line',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Field Options Per Line') ,
'description' => 'number of options per line for checkbox and radio',
'table_name' => 'civicrm_custom_field',
'entity' => 'CustomField',
'bao' => 'CRM_Core_BAO_CustomField',
'localizable' => 0,
) ,
'text_length' => array(
'name' => 'text_length',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Field Length') ,
'description' => 'field length if alphanumeric',
'table_name' => 'civicrm_custom_field',
'entity' => 'CustomField',
'bao' => 'CRM_Core_BAO_CustomField',
'localizable' => 0,
) ,
'start_date_years' => array(
'name' => 'start_date_years',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Field Start Date') ,
'description' => 'Date may be up to start_date_years years prior to the current date.',
'table_name' => 'civicrm_custom_field',
'entity' => 'CustomField',
'bao' => 'CRM_Core_BAO_CustomField',
'localizable' => 0,
) ,
'end_date_years' => array(
'name' => 'end_date_years',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Field End Date') ,
'description' => 'Date may be up to end_date_years years after the current date.',
'table_name' => 'civicrm_custom_field',
'entity' => 'CustomField',
'bao' => 'CRM_Core_BAO_CustomField',
'localizable' => 0,
) ,
'date_format' => array(
'name' => 'date_format',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Field Data Format') ,
'description' => 'date format for custom date',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_custom_field',
'entity' => 'CustomField',
'bao' => 'CRM_Core_BAO_CustomField',
'localizable' => 0,
) ,
'time_format' => array(
'name' => 'time_format',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Field Time Format') ,
'description' => 'time format for custom date',
'table_name' => 'civicrm_custom_field',
'entity' => 'CustomField',
'bao' => 'CRM_Core_BAO_CustomField',
'localizable' => 0,
) ,
'note_columns' => array(
'name' => 'note_columns',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Field Note Columns') ,
'description' => ' Number of columns in Note Field ',
'table_name' => 'civicrm_custom_field',
'entity' => 'CustomField',
'bao' => 'CRM_Core_BAO_CustomField',
'localizable' => 0,
) ,
'note_rows' => array(
'name' => 'note_rows',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Field Note Rows') ,
'description' => ' Number of rows in Note Field ',
'table_name' => 'civicrm_custom_field',
'entity' => 'CustomField',
'bao' => 'CRM_Core_BAO_CustomField',
'localizable' => 0,
) ,
'column_name' => array(
'name' => 'column_name',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Field Column Name') ,
'description' => 'Name of the column that holds the values for this field.',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_custom_field',
'entity' => 'CustomField',
'bao' => 'CRM_Core_BAO_CustomField',
'localizable' => 0,
) ,
'option_group_id' => array(
'name' => 'option_group_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Field Option Group') ,
'description' => 'For elements with options, the option group id that is used',
'table_name' => 'civicrm_custom_field',
'entity' => 'CustomField',
'bao' => 'CRM_Core_BAO_CustomField',
'localizable' => 0,
) ,
'filter' => array(
'name' => 'filter',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Field Filter') ,
'description' => 'Stores Contact Get API params contact reference custom fields. May be used for other filters in the future.',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_custom_field',
'entity' => 'CustomField',
'bao' => 'CRM_Core_BAO_CustomField',
'localizable' => 0,
) ,
'in_selector' => array(
'name' => 'in_selector',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Field Display') ,
'description' => 'Should the multi-record custom field values be displayed in tab table listing',
'table_name' => 'civicrm_custom_field',
'entity' => 'CustomField',
'bao' => 'CRM_Core_BAO_CustomField',
'localizable' => 0,
) ,
);
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
static function getTableName() {
return CRM_Core_DAO::getLocaleTableName(self::$_tableName);
}
/**
* Returns if this table needs to be logged
*
* @return boolean
*/
function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
static function &import($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'custom_field', $prefix, array());
return $r;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
static function &export($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'custom_field', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array(
'UI_label_custom_group_id' => array(
'name' => 'UI_label_custom_group_id',
'field' => array(
0 => 'label',
1 => 'custom_group_id',
) ,
'localizable' => true,
'unique' => true,
'sig' => 'civicrm_custom_field::1::label::custom_group_id',
) ,
'UI_name_custom_group_id' => array(
'name' => 'UI_name_custom_group_id',
'field' => array(
0 => 'name',
1 => 'custom_group_id',
) ,
'localizable' => false,
'unique' => true,
'sig' => 'civicrm_custom_field::1::name::custom_group_id',
) ,
);
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

View file

@ -0,0 +1,537 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
* Generated from xml/schema/CRM/Core/CustomGroup.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:5b2dac3266e0184dc4eaa6de10c9d401)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Core_DAO_CustomGroup constructor.
*/
class CRM_Core_DAO_CustomGroup extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_custom_group';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = true;
/**
* Unique Custom Group ID
*
* @var int unsigned
*/
public $id;
/**
* Variable name/programmatic handle for this group.
*
* @var string
*/
public $name;
/**
* Friendly Name.
*
* @var string
*/
public $title;
/**
* Type of object this group extends (can add other options later e.g. contact_address, etc.).
*
* @var string
*/
public $extends;
/**
* FK to civicrm_option_value.id (for option group custom_data_type.)
*
* @var int unsigned
*/
public $extends_entity_column_id;
/**
* linking custom group for dynamic object
*
* @var string
*/
public $extends_entity_column_value;
/**
* Visual relationship between this form and its parent.
*
* @var string
*/
public $style;
/**
* Will this group be in collapsed or expanded mode on initial display ?
*
* @var int unsigned
*/
public $collapse_display;
/**
* Description and/or help text to display before fields in form.
*
* @var text
*/
public $help_pre;
/**
* Description and/or help text to display after fields in form.
*
* @var text
*/
public $help_post;
/**
* Controls display order when multiple extended property groups are setup for the same class.
*
* @var int
*/
public $weight;
/**
* Is this property active?
*
* @var boolean
*/
public $is_active;
/**
* Name of the table that holds the values for this group.
*
* @var string
*/
public $table_name;
/**
* Does this group hold multiple values?
*
* @var boolean
*/
public $is_multiple;
/**
* minimum number of multiple records (typically 0?)
*
* @var int unsigned
*/
public $min_multiple;
/**
* maximum number of multiple records, if 0 - no max
*
* @var int unsigned
*/
public $max_multiple;
/**
* Will this group be in collapsed or expanded mode on advanced search display ?
*
* @var int unsigned
*/
public $collapse_adv_display;
/**
* FK to civicrm_contact, who created this custom group
*
* @var int unsigned
*/
public $created_id;
/**
* Date and time this custom group was created.
*
* @var datetime
*/
public $created_date;
/**
* Is this a reserved Custom Group?
*
* @var boolean
*/
public $is_reserved;
/**
* Is this property public?
*
* @var boolean
*/
public $is_public;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_custom_group';
parent::__construct();
}
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'created_id', 'civicrm_contact', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
/**
* Returns all the column names of this table
*
* @return array
*/
static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
Civi::$statics[__CLASS__]['fields'] = array(
'id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Custom Group ID') ,
'description' => 'Unique Custom Group ID',
'required' => true,
'table_name' => 'civicrm_custom_group',
'entity' => 'CustomGroup',
'bao' => 'CRM_Core_BAO_CustomGroup',
'localizable' => 0,
) ,
'name' => array(
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Custom Group Name') ,
'description' => 'Variable name/programmatic handle for this group.',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_custom_group',
'entity' => 'CustomGroup',
'bao' => 'CRM_Core_BAO_CustomGroup',
'localizable' => 0,
) ,
'title' => array(
'name' => 'title',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Custom Group Title') ,
'description' => 'Friendly Name.',
'required' => true,
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_custom_group',
'entity' => 'CustomGroup',
'bao' => 'CRM_Core_BAO_CustomGroup',
'localizable' => 1,
) ,
'extends' => array(
'name' => 'extends',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Custom Group Extends') ,
'description' => 'Type of object this group extends (can add other options later e.g. contact_address, etc.).',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'default' => 'Contact',
'table_name' => 'civicrm_custom_group',
'entity' => 'CustomGroup',
'bao' => 'CRM_Core_BAO_CustomGroup',
'localizable' => 0,
) ,
'extends_entity_column_id' => array(
'name' => 'extends_entity_column_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Custom Group Subtype List') ,
'description' => 'FK to civicrm_option_value.id (for option group custom_data_type.)',
'default' => 'NULL',
'table_name' => 'civicrm_custom_group',
'entity' => 'CustomGroup',
'bao' => 'CRM_Core_BAO_CustomGroup',
'localizable' => 0,
) ,
'extends_entity_column_value' => array(
'name' => 'extends_entity_column_value',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Custom Group Subtype') ,
'description' => 'linking custom group for dynamic object',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_custom_group',
'entity' => 'CustomGroup',
'bao' => 'CRM_Core_BAO_CustomGroup',
'localizable' => 0,
) ,
'style' => array(
'name' => 'style',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Custom Group Style') ,
'description' => 'Visual relationship between this form and its parent.',
'maxlength' => 15,
'size' => CRM_Utils_Type::TWELVE,
'table_name' => 'civicrm_custom_group',
'entity' => 'CustomGroup',
'bao' => 'CRM_Core_BAO_CustomGroup',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'callback' => 'CRM_Core_SelectValues::customGroupStyle',
)
) ,
'collapse_display' => array(
'name' => 'collapse_display',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Collapse Custom Group?') ,
'description' => 'Will this group be in collapsed or expanded mode on initial display ?',
'table_name' => 'civicrm_custom_group',
'entity' => 'CustomGroup',
'bao' => 'CRM_Core_BAO_CustomGroup',
'localizable' => 0,
) ,
'help_pre' => array(
'name' => 'help_pre',
'type' => CRM_Utils_Type::T_TEXT,
'title' => ts('Custom Group Pre Text') ,
'description' => 'Description and/or help text to display before fields in form.',
'rows' => 4,
'cols' => 80,
'table_name' => 'civicrm_custom_group',
'entity' => 'CustomGroup',
'bao' => 'CRM_Core_BAO_CustomGroup',
'localizable' => 1,
'html' => array(
'type' => 'TextArea',
) ,
) ,
'help_post' => array(
'name' => 'help_post',
'type' => CRM_Utils_Type::T_TEXT,
'title' => ts('Custom Group Post Text') ,
'description' => 'Description and/or help text to display after fields in form.',
'rows' => 4,
'cols' => 80,
'table_name' => 'civicrm_custom_group',
'entity' => 'CustomGroup',
'bao' => 'CRM_Core_BAO_CustomGroup',
'localizable' => 1,
'html' => array(
'type' => 'TextArea',
) ,
) ,
'weight' => array(
'name' => 'weight',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Order') ,
'description' => 'Controls display order when multiple extended property groups are setup for the same class.',
'required' => true,
'default' => '1',
'table_name' => 'civicrm_custom_group',
'entity' => 'CustomGroup',
'bao' => 'CRM_Core_BAO_CustomGroup',
'localizable' => 0,
) ,
'is_active' => array(
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Custom Group Is Active?') ,
'description' => 'Is this property active?',
'table_name' => 'civicrm_custom_group',
'entity' => 'CustomGroup',
'bao' => 'CRM_Core_BAO_CustomGroup',
'localizable' => 0,
) ,
'table_name' => array(
'name' => 'table_name',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Table Name') ,
'description' => 'Name of the table that holds the values for this group.',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_custom_group',
'entity' => 'CustomGroup',
'bao' => 'CRM_Core_BAO_CustomGroup',
'localizable' => 0,
) ,
'is_multiple' => array(
'name' => 'is_multiple',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Supports Multiple Records') ,
'description' => 'Does this group hold multiple values?',
'table_name' => 'civicrm_custom_group',
'entity' => 'CustomGroup',
'bao' => 'CRM_Core_BAO_CustomGroup',
'localizable' => 0,
) ,
'min_multiple' => array(
'name' => 'min_multiple',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Minimum Multiple Records') ,
'description' => 'minimum number of multiple records (typically 0?)',
'table_name' => 'civicrm_custom_group',
'entity' => 'CustomGroup',
'bao' => 'CRM_Core_BAO_CustomGroup',
'localizable' => 0,
) ,
'max_multiple' => array(
'name' => 'max_multiple',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Maximum Multiple Records') ,
'description' => 'maximum number of multiple records, if 0 - no max',
'table_name' => 'civicrm_custom_group',
'entity' => 'CustomGroup',
'bao' => 'CRM_Core_BAO_CustomGroup',
'localizable' => 0,
) ,
'collapse_adv_display' => array(
'name' => 'collapse_adv_display',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Collapse Group Display') ,
'description' => 'Will this group be in collapsed or expanded mode on advanced search display ?',
'table_name' => 'civicrm_custom_group',
'entity' => 'CustomGroup',
'bao' => 'CRM_Core_BAO_CustomGroup',
'localizable' => 0,
) ,
'created_id' => array(
'name' => 'created_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Custom Group Created By') ,
'description' => 'FK to civicrm_contact, who created this custom group',
'table_name' => 'civicrm_custom_group',
'entity' => 'CustomGroup',
'bao' => 'CRM_Core_BAO_CustomGroup',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
) ,
'created_date' => array(
'name' => 'created_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'title' => ts('Custom Group Created Date') ,
'description' => 'Date and time this custom group was created.',
'table_name' => 'civicrm_custom_group',
'entity' => 'CustomGroup',
'bao' => 'CRM_Core_BAO_CustomGroup',
'localizable' => 0,
) ,
'is_reserved' => array(
'name' => 'is_reserved',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Reserved Group?') ,
'description' => 'Is this a reserved Custom Group?',
'table_name' => 'civicrm_custom_group',
'entity' => 'CustomGroup',
'bao' => 'CRM_Core_BAO_CustomGroup',
'localizable' => 0,
) ,
'is_public' => array(
'name' => 'is_public',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Custom Group Is Public?') ,
'description' => 'Is this property public?',
'default' => '1',
'table_name' => 'civicrm_custom_group',
'entity' => 'CustomGroup',
'bao' => 'CRM_Core_BAO_CustomGroup',
'localizable' => 0,
) ,
);
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
static function getTableName() {
return CRM_Core_DAO::getLocaleTableName(self::$_tableName);
}
/**
* Returns if this table needs to be logged
*
* @return boolean
*/
function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
static function &import($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'custom_group', $prefix, array());
return $r;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
static function &export($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'custom_group', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array(
'UI_title_extends' => array(
'name' => 'UI_title_extends',
'field' => array(
0 => 'title',
1 => 'extends',
) ,
'localizable' => true,
'unique' => true,
'sig' => 'civicrm_custom_group::1::title::extends',
) ,
'UI_name_extends' => array(
'name' => 'UI_name_extends',
'field' => array(
0 => 'name',
1 => 'extends',
) ,
'localizable' => false,
'unique' => true,
'sig' => 'civicrm_custom_group::1::name::extends',
) ,
);
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

View file

@ -0,0 +1,340 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
* Generated from xml/schema/CRM/Core/Dashboard.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:6b7454609bac684a5d32597cdd433f3d)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Core_DAO_Dashboard constructor.
*/
class CRM_Core_DAO_Dashboard extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_dashboard';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = false;
/**
*
* @var int unsigned
*/
public $id;
/**
* Domain for dashboard
*
* @var int unsigned
*/
public $domain_id;
/**
* Internal name of dashlet.
*
* @var string
*/
public $name;
/**
* dashlet title
*
* @var string
*/
public $label;
/**
* url in case of external dashlet
*
* @var string
*/
public $url;
/**
* Permission for the dashlet
*
* @var string
*/
public $permission;
/**
* Permission Operator
*
* @var string
*/
public $permission_operator;
/**
* fullscreen url for dashlet
*
* @var string
*/
public $fullscreen_url;
/**
* Is this dashlet active?
*
* @var boolean
*/
public $is_active;
/**
* Is this dashlet reserved?
*
* @var boolean
*/
public $is_reserved;
/**
* Number of minutes to cache dashlet content in browser localStorage.
*
* @var int unsigned
*/
public $cache_minutes;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_dashboard';
parent::__construct();
}
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'domain_id', 'civicrm_domain', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
/**
* Returns all the column names of this table
*
* @return array
*/
static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
Civi::$statics[__CLASS__]['fields'] = array(
'id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('DashletID') ,
'required' => true,
'table_name' => 'civicrm_dashboard',
'entity' => 'Dashboard',
'bao' => 'CRM_Core_BAO_Dashboard',
'localizable' => 0,
) ,
'domain_id' => array(
'name' => 'domain_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Dashlet Domain') ,
'description' => 'Domain for dashboard',
'required' => true,
'table_name' => 'civicrm_dashboard',
'entity' => 'Dashboard',
'bao' => 'CRM_Core_BAO_Dashboard',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_Domain',
'pseudoconstant' => array(
'table' => 'civicrm_domain',
'keyColumn' => 'id',
'labelColumn' => 'name',
)
) ,
'name' => array(
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Dashlet Name') ,
'description' => 'Internal name of dashlet.',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_dashboard',
'entity' => 'Dashboard',
'bao' => 'CRM_Core_BAO_Dashboard',
'localizable' => 0,
) ,
'label' => array(
'name' => 'label',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Dashlet Title') ,
'description' => 'dashlet title',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_dashboard',
'entity' => 'Dashboard',
'bao' => 'CRM_Core_BAO_Dashboard',
'localizable' => 1,
) ,
'url' => array(
'name' => 'url',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Dashlet URL') ,
'description' => 'url in case of external dashlet',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_dashboard',
'entity' => 'Dashboard',
'bao' => 'CRM_Core_BAO_Dashboard',
'localizable' => 0,
) ,
'permission' => array(
'name' => 'permission',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Dashlet Permission') ,
'description' => 'Permission for the dashlet',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_dashboard',
'entity' => 'Dashboard',
'bao' => 'CRM_Core_BAO_Dashboard',
'localizable' => 0,
) ,
'permission_operator' => array(
'name' => 'permission_operator',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Dashlet Permission Operator') ,
'description' => 'Permission Operator',
'maxlength' => 3,
'size' => CRM_Utils_Type::FOUR,
'table_name' => 'civicrm_dashboard',
'entity' => 'Dashboard',
'bao' => 'CRM_Core_BAO_Dashboard',
'localizable' => 0,
) ,
'fullscreen_url' => array(
'name' => 'fullscreen_url',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Fullscreen URL') ,
'description' => 'fullscreen url for dashlet',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_dashboard',
'entity' => 'Dashboard',
'bao' => 'CRM_Core_BAO_Dashboard',
'localizable' => 0,
) ,
'is_active' => array(
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Is Dashlet Active?') ,
'description' => 'Is this dashlet active?',
'table_name' => 'civicrm_dashboard',
'entity' => 'Dashboard',
'bao' => 'CRM_Core_BAO_Dashboard',
'localizable' => 0,
) ,
'is_reserved' => array(
'name' => 'is_reserved',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Is Dashlet Reserved?') ,
'description' => 'Is this dashlet reserved?',
'table_name' => 'civicrm_dashboard',
'entity' => 'Dashboard',
'bao' => 'CRM_Core_BAO_Dashboard',
'localizable' => 0,
) ,
'cache_minutes' => array(
'name' => 'cache_minutes',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Cache Minutes') ,
'description' => 'Number of minutes to cache dashlet content in browser localStorage.',
'required' => true,
'default' => '60',
'table_name' => 'civicrm_dashboard',
'entity' => 'Dashboard',
'bao' => 'CRM_Core_BAO_Dashboard',
'localizable' => 0,
) ,
);
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
static function getTableName() {
return CRM_Core_DAO::getLocaleTableName(self::$_tableName);
}
/**
* Returns if this table needs to be logged
*
* @return boolean
*/
function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
static function &import($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'dashboard', $prefix, array());
return $r;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
static function &export($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'dashboard', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array();
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

View file

@ -0,0 +1,271 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
* Generated from xml/schema/CRM/Core/Discount.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:1ce69428f948066567e95645cb86254a)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Core_DAO_Discount constructor.
*/
class CRM_Core_DAO_Discount extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_discount';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = true;
/**
* primary key
*
* @var int unsigned
*/
public $id;
/**
* physical tablename for entity being joined to discount, e.g. civicrm_event
*
* @var string
*/
public $entity_table;
/**
* FK to entity table specified in entity_table column.
*
* @var int unsigned
*/
public $entity_id;
/**
* FK to civicrm_price_set
*
* @var int unsigned
*/
public $price_set_id;
/**
* Date when discount starts.
*
* @var date
*/
public $start_date;
/**
* Date when discount ends.
*
* @var date
*/
public $end_date;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_discount';
parent::__construct();
}
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'price_set_id', 'civicrm_price_set', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName() , 'entity_id', NULL, 'id', 'entity_table');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
/**
* Returns all the column names of this table
*
* @return array
*/
static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
Civi::$statics[__CLASS__]['fields'] = array(
'id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Discount ID') ,
'description' => 'primary key',
'required' => true,
'table_name' => 'civicrm_discount',
'entity' => 'Discount',
'bao' => 'CRM_Core_BAO_Discount',
'localizable' => 0,
) ,
'entity_table' => array(
'name' => 'entity_table',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Entity Table') ,
'description' => 'physical tablename for entity being joined to discount, e.g. civicrm_event',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_discount',
'entity' => 'Discount',
'bao' => 'CRM_Core_BAO_Discount',
'localizable' => 0,
) ,
'entity_id' => array(
'name' => 'entity_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Entity ID') ,
'description' => 'FK to entity table specified in entity_table column.',
'required' => true,
'table_name' => 'civicrm_discount',
'entity' => 'Discount',
'bao' => 'CRM_Core_BAO_Discount',
'localizable' => 0,
) ,
'participant_discount_name' => array(
'name' => 'price_set_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Discount Name') ,
'description' => 'FK to civicrm_price_set',
'required' => true,
'export' => true,
'where' => 'civicrm_discount.price_set_id',
'headerPattern' => '',
'dataPattern' => '',
'table_name' => 'civicrm_discount',
'entity' => 'Discount',
'bao' => 'CRM_Core_BAO_Discount',
'localizable' => 0,
'FKClassName' => 'CRM_Price_DAO_PriceSet',
) ,
'start_date' => array(
'name' => 'start_date',
'type' => CRM_Utils_Type::T_DATE,
'title' => ts('Discount Start Date') ,
'description' => 'Date when discount starts.',
'table_name' => 'civicrm_discount',
'entity' => 'Discount',
'bao' => 'CRM_Core_BAO_Discount',
'localizable' => 0,
) ,
'end_date' => array(
'name' => 'end_date',
'type' => CRM_Utils_Type::T_DATE,
'title' => ts('Discount End Date') ,
'description' => 'Date when discount ends.',
'table_name' => 'civicrm_discount',
'entity' => 'Discount',
'bao' => 'CRM_Core_BAO_Discount',
'localizable' => 0,
) ,
);
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
static function getTableName() {
return self::$_tableName;
}
/**
* Returns if this table needs to be logged
*
* @return boolean
*/
function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
static function &import($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'discount', $prefix, array());
return $r;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
static function &export($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'discount', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array(
'index_entity' => array(
'name' => 'index_entity',
'field' => array(
0 => 'entity_table',
1 => 'entity_id',
) ,
'localizable' => false,
'sig' => 'civicrm_discount::0::entity_table::entity_id',
) ,
'index_entity_option_id' => array(
'name' => 'index_entity_option_id',
'field' => array(
0 => 'entity_table',
1 => 'entity_id',
2 => 'price_set_id',
) ,
'localizable' => false,
'sig' => 'civicrm_discount::0::entity_table::entity_id::price_set_id',
) ,
);
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

View file

@ -0,0 +1,306 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
* Generated from xml/schema/CRM/Core/Domain.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:50edefeb24aa64d2125df018985cd701)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Core_DAO_Domain constructor.
*/
class CRM_Core_DAO_Domain extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_domain';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = false;
/**
* Domain ID
*
* @var int unsigned
*/
public $id;
/**
* Name of Domain / Organization
*
* @var string
*/
public $name;
/**
* Description of Domain.
*
* @var string
*/
public $description;
/**
* Backend configuration.
*
* @var text
*/
public $config_backend;
/**
* The civicrm version this instance is running
*
* @var string
*/
public $version;
/**
* FK to Contact ID. This is specifically not an FK to avoid circular constraints
*
* @var int unsigned
*/
public $contact_id;
/**
* list of locales supported by the current db state (NULL for single-lang install)
*
* @var text
*/
public $locales;
/**
* Locale specific string overrides
*
* @var text
*/
public $locale_custom_strings;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_domain';
parent::__construct();
}
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
/**
* Returns all the column names of this table
*
* @return array
*/
static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
Civi::$statics[__CLASS__]['fields'] = array(
'id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Domain ID') ,
'description' => 'Domain ID',
'required' => true,
'table_name' => 'civicrm_domain',
'entity' => 'Domain',
'bao' => 'CRM_Core_BAO_Domain',
'localizable' => 0,
) ,
'name' => array(
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Domain Name') ,
'description' => 'Name of Domain / Organization',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_domain',
'entity' => 'Domain',
'bao' => 'CRM_Core_BAO_Domain',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'description' => array(
'name' => 'description',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Domain Description') ,
'description' => 'Description of Domain.',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_domain',
'entity' => 'Domain',
'bao' => 'CRM_Core_BAO_Domain',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'config_backend' => array(
'name' => 'config_backend',
'type' => CRM_Utils_Type::T_TEXT,
'title' => ts('Domain Configuration') ,
'description' => 'Backend configuration.',
'rows' => 20,
'cols' => 80,
'table_name' => 'civicrm_domain',
'entity' => 'Domain',
'bao' => 'CRM_Core_BAO_Domain',
'localizable' => 0,
'html' => array(
'type' => 'TextArea',
) ,
) ,
'version' => array(
'name' => 'version',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('CiviCRM Version') ,
'description' => 'The civicrm version this instance is running',
'maxlength' => 32,
'size' => CRM_Utils_Type::MEDIUM,
'table_name' => 'civicrm_domain',
'entity' => 'Domain',
'bao' => 'CRM_Core_BAO_Domain',
'localizable' => 0,
) ,
'contact_id' => array(
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Domain Contact') ,
'description' => 'FK to Contact ID. This is specifically not an FK to avoid circular constraints',
'table_name' => 'civicrm_domain',
'entity' => 'Domain',
'bao' => 'CRM_Core_BAO_Domain',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
) ,
'locales' => array(
'name' => 'locales',
'type' => CRM_Utils_Type::T_TEXT,
'title' => ts('Supported Languages') ,
'description' => 'list of locales supported by the current db state (NULL for single-lang install)',
'table_name' => 'civicrm_domain',
'entity' => 'Domain',
'bao' => 'CRM_Core_BAO_Domain',
'localizable' => 0,
) ,
'locale_custom_strings' => array(
'name' => 'locale_custom_strings',
'type' => CRM_Utils_Type::T_TEXT,
'title' => ts('Language Customizations') ,
'description' => 'Locale specific string overrides',
'rows' => 20,
'cols' => 80,
'table_name' => 'civicrm_domain',
'entity' => 'Domain',
'bao' => 'CRM_Core_BAO_Domain',
'localizable' => 0,
'html' => array(
'type' => 'TextArea',
) ,
) ,
);
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
static function getTableName() {
return self::$_tableName;
}
/**
* Returns if this table needs to be logged
*
* @return boolean
*/
function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
static function &import($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'domain', $prefix, array());
return $r;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
static function &export($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'domain', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array(
'UI_name' => array(
'name' => 'UI_name',
'field' => array(
0 => 'name',
) ,
'localizable' => false,
'unique' => true,
'sig' => 'civicrm_domain::1::name',
) ,
);
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

View file

@ -0,0 +1,415 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
* Generated from xml/schema/CRM/Core/Email.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:08f53d44527d7d174b4aa1bd545b028c)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Core_DAO_Email constructor.
*/
class CRM_Core_DAO_Email extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_email';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = true;
/**
* Unique Email ID
*
* @var int unsigned
*/
public $id;
/**
* FK to Contact ID
*
* @var int unsigned
*/
public $contact_id;
/**
* Which Location does this email belong to.
*
* @var int unsigned
*/
public $location_type_id;
/**
* Email address
*
* @var string
*/
public $email;
/**
* Is this the primary?
*
* @var boolean
*/
public $is_primary;
/**
* Is this the billing?
*
* @var boolean
*/
public $is_billing;
/**
* Is this address on bounce hold?
*
* @var boolean
*/
public $on_hold;
/**
* Is this address for bulk mail ?
*
* @var boolean
*/
public $is_bulkmail;
/**
* When the address went on bounce hold
*
* @var datetime
*/
public $hold_date;
/**
* When the address bounce status was last reset
*
* @var datetime
*/
public $reset_date;
/**
* Text formatted signature for the email.
*
* @var text
*/
public $signature_text;
/**
* HTML formatted signature for the email.
*
* @var text
*/
public $signature_html;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_email';
parent::__construct();
}
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
/**
* Returns all the column names of this table
*
* @return array
*/
static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
Civi::$statics[__CLASS__]['fields'] = array(
'id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Email ID') ,
'description' => 'Unique Email ID',
'required' => true,
'table_name' => 'civicrm_email',
'entity' => 'Email',
'bao' => 'CRM_Core_BAO_Email',
'localizable' => 0,
) ,
'contact_id' => array(
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Email Contact') ,
'description' => 'FK to Contact ID',
'table_name' => 'civicrm_email',
'entity' => 'Email',
'bao' => 'CRM_Core_BAO_Email',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
) ,
'location_type_id' => array(
'name' => 'location_type_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Email Location Type') ,
'description' => 'Which Location does this email belong to.',
'table_name' => 'civicrm_email',
'entity' => 'Email',
'bao' => 'CRM_Core_BAO_Email',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'table' => 'civicrm_location_type',
'keyColumn' => 'id',
'labelColumn' => 'display_name',
)
) ,
'email' => array(
'name' => 'email',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Email') ,
'description' => 'Email address',
'maxlength' => 254,
'size' => 30,
'import' => true,
'where' => 'civicrm_email.email',
'headerPattern' => '/e.?mail/i',
'dataPattern' => '/^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/',
'export' => true,
'rule' => 'email',
'table_name' => 'civicrm_email',
'entity' => 'Email',
'bao' => 'CRM_Core_BAO_Email',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'is_primary' => array(
'name' => 'is_primary',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Is Primary email') ,
'description' => 'Is this the primary?',
'table_name' => 'civicrm_email',
'entity' => 'Email',
'bao' => 'CRM_Core_BAO_Email',
'localizable' => 0,
) ,
'is_billing' => array(
'name' => 'is_billing',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Is Billing Email?') ,
'description' => 'Is this the billing?',
'table_name' => 'civicrm_email',
'entity' => 'Email',
'bao' => 'CRM_Core_BAO_Email',
'localizable' => 0,
) ,
'on_hold' => array(
'name' => 'on_hold',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('On Hold') ,
'description' => 'Is this address on bounce hold?',
'required' => true,
'export' => true,
'where' => 'civicrm_email.on_hold',
'headerPattern' => '',
'dataPattern' => '',
'table_name' => 'civicrm_email',
'entity' => 'Email',
'bao' => 'CRM_Core_BAO_Email',
'localizable' => 0,
'html' => array(
'type' => 'CheckBox',
) ,
) ,
'is_bulkmail' => array(
'name' => 'is_bulkmail',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Use for Bulk Mail') ,
'description' => 'Is this address for bulk mail ?',
'required' => true,
'export' => true,
'where' => 'civicrm_email.is_bulkmail',
'headerPattern' => '',
'dataPattern' => '',
'table_name' => 'civicrm_email',
'entity' => 'Email',
'bao' => 'CRM_Core_BAO_Email',
'localizable' => 0,
) ,
'hold_date' => array(
'name' => 'hold_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'title' => ts('Hold Date') ,
'description' => 'When the address went on bounce hold',
'table_name' => 'civicrm_email',
'entity' => 'Email',
'bao' => 'CRM_Core_BAO_Email',
'localizable' => 0,
) ,
'reset_date' => array(
'name' => 'reset_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'title' => ts('Reset Date') ,
'description' => 'When the address bounce status was last reset',
'table_name' => 'civicrm_email',
'entity' => 'Email',
'bao' => 'CRM_Core_BAO_Email',
'localizable' => 0,
) ,
'signature_text' => array(
'name' => 'signature_text',
'type' => CRM_Utils_Type::T_TEXT,
'title' => ts('Signature Text') ,
'description' => 'Text formatted signature for the email.',
'import' => true,
'where' => 'civicrm_email.signature_text',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'default' => 'NULL',
'table_name' => 'civicrm_email',
'entity' => 'Email',
'bao' => 'CRM_Core_BAO_Email',
'localizable' => 0,
) ,
'signature_html' => array(
'name' => 'signature_html',
'type' => CRM_Utils_Type::T_TEXT,
'title' => ts('Signature Html') ,
'description' => 'HTML formatted signature for the email.',
'import' => true,
'where' => 'civicrm_email.signature_html',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'default' => 'NULL',
'table_name' => 'civicrm_email',
'entity' => 'Email',
'bao' => 'CRM_Core_BAO_Email',
'localizable' => 0,
) ,
);
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
static function getTableName() {
return self::$_tableName;
}
/**
* Returns if this table needs to be logged
*
* @return boolean
*/
function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
static function &import($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'email', $prefix, array());
return $r;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
static function &export($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'email', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array(
'index_location_type' => array(
'name' => 'index_location_type',
'field' => array(
0 => 'location_type_id',
) ,
'localizable' => false,
'sig' => 'civicrm_email::0::location_type_id',
) ,
'UI_email' => array(
'name' => 'UI_email',
'field' => array(
0 => 'email',
) ,
'localizable' => false,
'sig' => 'civicrm_email::0::email',
) ,
'index_is_primary' => array(
'name' => 'index_is_primary',
'field' => array(
0 => 'is_primary',
) ,
'localizable' => false,
'sig' => 'civicrm_email::0::is_primary',
) ,
'index_is_billing' => array(
'name' => 'index_is_billing',
'field' => array(
0 => 'is_billing',
) ,
'localizable' => false,
'sig' => 'civicrm_email::0::is_billing',
) ,
);
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

View file

@ -0,0 +1,235 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
* Generated from xml/schema/CRM/Core/EntityFile.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:354c22131251fde259f5b796e102fccf)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Core_DAO_EntityFile constructor.
*/
class CRM_Core_DAO_EntityFile extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_entity_file';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = true;
/**
* primary key
*
* @var int unsigned
*/
public $id;
/**
* physical tablename for entity being joined to file, e.g. civicrm_contact
*
* @var string
*/
public $entity_table;
/**
* FK to entity table specified in entity_table column.
*
* @var int unsigned
*/
public $entity_id;
/**
* FK to civicrm_file
*
* @var int unsigned
*/
public $file_id;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_entity_file';
parent::__construct();
}
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'file_id', 'civicrm_file', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName() , 'entity_id', NULL, 'id', 'entity_table');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
/**
* Returns all the column names of this table
*
* @return array
*/
static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
Civi::$statics[__CLASS__]['fields'] = array(
'id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Entity File ID') ,
'description' => 'primary key',
'required' => true,
'table_name' => 'civicrm_entity_file',
'entity' => 'EntityFile',
'bao' => 'CRM_Core_DAO_EntityFile',
'localizable' => 0,
) ,
'entity_table' => array(
'name' => 'entity_table',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Entity Table') ,
'description' => 'physical tablename for entity being joined to file, e.g. civicrm_contact',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_entity_file',
'entity' => 'EntityFile',
'bao' => 'CRM_Core_DAO_EntityFile',
'localizable' => 0,
) ,
'entity_id' => array(
'name' => 'entity_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Entity ID') ,
'description' => 'FK to entity table specified in entity_table column.',
'required' => true,
'table_name' => 'civicrm_entity_file',
'entity' => 'EntityFile',
'bao' => 'CRM_Core_DAO_EntityFile',
'localizable' => 0,
) ,
'file_id' => array(
'name' => 'file_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('File') ,
'description' => 'FK to civicrm_file',
'required' => true,
'table_name' => 'civicrm_entity_file',
'entity' => 'EntityFile',
'bao' => 'CRM_Core_DAO_EntityFile',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_File',
) ,
);
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
static function getTableName() {
return self::$_tableName;
}
/**
* Returns if this table needs to be logged
*
* @return boolean
*/
function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
static function &import($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'entity_file', $prefix, array());
return $r;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
static function &export($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'entity_file', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array(
'index_entity' => array(
'name' => 'index_entity',
'field' => array(
0 => 'entity_table',
1 => 'entity_id',
) ,
'localizable' => false,
'sig' => 'civicrm_entity_file::0::entity_table::entity_id',
) ,
'index_entity_file_id' => array(
'name' => 'index_entity_file_id',
'field' => array(
0 => 'entity_table',
1 => 'entity_id',
2 => 'file_id',
) ,
'localizable' => false,
'sig' => 'civicrm_entity_file::0::entity_table::entity_id::file_id',
) ,
);
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

Some files were not shown because too many files have changed in this diff Show more