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,326 @@
<?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 is to build the form for Deleting Group
*/
class CRM_Custom_Form_ChangeFieldType extends CRM_Core_Form {
/**
* The field id
*
* @var int
*/
protected $_id;
/**
* Array of custom field values
*/
protected $_values;
/**
* Mapper array of valid field type
*/
protected $_htmlTypeTransitions;
/**
* Set up variables to build the form.
*
* @return void
* @access protected
*/
public function preProcess() {
$this->_id = CRM_Utils_Request::retrieve('id', 'Positive',
$this, TRUE
);
$this->_values = array();
$params = array('id' => $this->_id);
CRM_Core_BAO_CustomField::retrieve($params, $this->_values);
$this->_htmlTypeTransitions = self::fieldTypeTransitions(CRM_Utils_Array::value('data_type', $this->_values),
CRM_Utils_Array::value('html_type', $this->_values)
);
if (empty($this->_values) || empty($this->_htmlTypeTransitions)) {
CRM_Core_Error::fatal(ts("Invalid custom field or can't change input type of this custom field."));
}
$url = CRM_Utils_System::url('civicrm/admin/custom/group/field/update',
"action=update&reset=1&gid={$this->_values['custom_group_id']}&id={$this->_id}"
);
$session = CRM_Core_Session::singleton();
$session->pushUserContext($url);
CRM_Utils_System::setTitle(ts('Change Field Type: %1',
array(1 => $this->_values['label'])
));
}
/**
* Build the form object.
*
* @return void
*/
public function buildQuickForm() {
$srcHtmlType = $this->add('select',
'src_html_type',
ts('Current HTML Type'),
array($this->_values['html_type'] => $this->_values['html_type']),
TRUE
);
$srcHtmlType->setValue($this->_values['html_type']);
$srcHtmlType->freeze();
$this->assign('srcHtmlType', $this->_values['html_type']);
$dstHtmlType = $this->add('select',
'dst_html_type',
ts('New HTML Type'),
array(
'' => ts('- select -'),
) + $this->_htmlTypeTransitions,
TRUE
);
$this->addButtons(array(
array(
'type' => 'next',
'name' => ts('Change Field Type'),
'isDefault' => TRUE,
'js' => array('onclick' => 'return checkCustomDataField();'),
),
array(
'type' => 'cancel',
'name' => ts('Cancel'),
),
)
);
}
/**
* Process the form when submitted.
*
* @return void
*/
public function postProcess() {
$params = $this->controller->exportValues($this->_name);
$tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
$this->_values['custom_group_id'],
'table_name'
);
$singleValueOps = array(
'Text',
'Select',
'Radio',
'Autocomplete-Select',
);
$mutliValueOps = array(
'CheckBox',
'Multi-Select',
'AdvMulti-Select',
);
$srcHtmlType = $this->_values['html_type'];
$dstHtmlType = $params['dst_html_type'];
$customField = new CRM_Core_DAO_CustomField();
$customField->id = $this->_id;
$customField->find(TRUE);
if ($dstHtmlType == 'Text' && in_array($srcHtmlType, array(
'Select',
'Radio',
'Autocomplete-Select',
))
) {
$customField->option_group_id = "NULL";
CRM_Core_BAO_CustomField::checkOptionGroup($this->_values['option_group_id']);
}
if (in_array($srcHtmlType, $mutliValueOps) &&
in_array($dstHtmlType, $singleValueOps)
) {
$this->flattenToFirstValue($tableName, $this->_values['column_name']);
}
elseif (in_array($srcHtmlType, $singleValueOps) &&
in_array($dstHtmlType, $mutliValueOps)
) {
$this->firstValueToFlatten($tableName, $this->_values['column_name']);
}
$customField->html_type = $dstHtmlType;
$customField->save();
// Reset cache for custom fields
CRM_Core_BAO_Cache::deleteGroup('contact fields');
CRM_Core_Session::setStatus(ts('Input type of custom field \'%1\' has been successfully changed to \'%2\'.',
array(1 => $this->_values['label'], 2 => $dstHtmlType)
), ts('Field Type Changed'), 'success');
}
/**
* @param $dataType
* @param $htmlType
*
* @return array|null
*/
public static function fieldTypeTransitions($dataType, $htmlType) {
// Text field is single value field,
// can not be change to other single value option which contains option group
if ($htmlType == 'Text') {
return NULL;
}
$singleValueOps = array(
'Text' => 'Text',
'Select' => 'Select',
'Radio' => 'Radio',
'Autocomplete-Select' => 'Autocomplete-Select',
);
$mutliValueOps = array(
'CheckBox' => 'CheckBox',
'Multi-Select' => 'Multi-Select',
'AdvMulti-Select' => 'AdvMulti-Select',
);
switch ($dataType) {
case 'String':
if (in_array($htmlType, array_keys($singleValueOps))) {
unset($singleValueOps[$htmlType]);
return array_merge($singleValueOps, $mutliValueOps);
}
elseif (in_array($htmlType, array_keys($mutliValueOps))) {
unset($singleValueOps['Text']);
foreach ($singleValueOps as $type => $label) {
$singleValueOps[$type] = "{$label} ( " . ts('Not Safe') . " )";
}
unset($mutliValueOps[$htmlType]);
return array_merge($mutliValueOps, $singleValueOps);
}
break;
case 'Int':
case 'Float':
case 'Int':
case 'Money':
if (in_array($htmlType, array_keys($singleValueOps))) {
unset($singleValueOps[$htmlType]);
return $singleValueOps;
}
break;
case 'Memo':
$ops = array(
'TextArea' => 'TextArea',
'RichTextEditor' => 'RichTextEditor',
);
if (in_array($htmlType, array_keys($ops))) {
unset($ops[$htmlType]);
return $ops;
}
break;
}
return NULL;
}
/**
* Take a single-value column (eg: a Radio or Select etc ) and convert
* value to the multi listed value (eg:"^Foo^")
*
* @param string $table
* @param string $column
*/
public function firstValueToFlatten($table, $column) {
$selectSql = "SELECT id, $column FROM $table WHERE $column IS NOT NULL";
$updateSql = "UPDATE $table SET $column = %1 WHERE id = %2";
$dao = CRM_Core_DAO::executeQuery($selectSql);
while ($dao->fetch()) {
if (!$dao->{$column}) {
continue;
}
$value = CRM_Core_DAO::VALUE_SEPARATOR . $dao->{$column} . CRM_Core_DAO::VALUE_SEPARATOR;
$params = array(
1 => array((string) $value, 'String'),
2 => array($dao->id, 'Integer'),
);
CRM_Core_DAO::executeQuery($updateSql, $params);
}
}
/**
* Take a multi-value column (e.g. a Multi-Select or CheckBox column), and convert
* all values (of the form "^^" or "^Foo^" or "^Foo^Bar^") to the first listed value ("Foo")
*
* @param string $table
* @param string $column
*/
public function flattenToFirstValue($table, $column) {
$selectSql = "SELECT id, $column FROM $table WHERE $column IS NOT NULL";
$updateSql = "UPDATE $table SET $column = %1 WHERE id = %2";
$dao = CRM_Core_DAO::executeQuery($selectSql);
while ($dao->fetch()) {
$values = self::explode($dao->{$column});
$params = array(
1 => array((string) array_shift($values), 'String'),
2 => array($dao->id, 'Integer'),
);
CRM_Core_DAO::executeQuery($updateSql, $params);
}
}
/**
* @param $str
*
* @return array
*/
public static function explode($str) {
if (empty($str) || $str == CRM_Core_DAO::VALUE_SEPARATOR . CRM_Core_DAO::VALUE_SEPARATOR) {
return array();
}
else {
return explode(CRM_Core_DAO::VALUE_SEPARATOR, trim($str, CRM_Core_DAO::VALUE_SEPARATOR));
}
}
}

View file

@ -0,0 +1,197 @@
<?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 builds custom data
*/
class CRM_Custom_Form_CustomData {
/**
* @param CRM_Core_Form $form
* @param null|string $subName
* @param null|string $subType
* @param null|int $groupCount
* @param string $type
* @param null|int $entityID
* @param null $onlySubType
*/
public static function preProcess(
&$form, $subName = NULL, $subType = NULL,
$groupCount = NULL, $type = NULL, $entityID = NULL, $onlySubType = NULL
) {
if ($type) {
$form->_type = $type;
}
else {
$form->_type = CRM_Utils_Request::retrieve('type', 'String', $form);
}
if (isset($subType)) {
$form->_subType = $subType;
}
else {
$form->_subType = CRM_Utils_Request::retrieve('subType', 'String', $form);
}
if ($form->_subType == 'null') {
$form->_subType = NULL;
}
if (isset($subName)) {
$form->_subName = $subName;
}
else {
$form->_subName = CRM_Utils_Request::retrieve('subName', 'String', $form);
}
if ($form->_subName == 'null') {
$form->_subName = NULL;
}
if ($groupCount) {
$form->_groupCount = $groupCount;
}
else {
$form->_groupCount = CRM_Utils_Request::retrieve('cgcount', 'Positive', $form);
}
$form->assign('cgCount', $form->_groupCount);
//carry qf key, since this form is not inhereting core form.
if ($qfKey = CRM_Utils_Request::retrieve('qfKey', 'String')) {
$form->assign('qfKey', $qfKey);
}
if ($entityID) {
$form->_entityId = $entityID;
}
else {
$form->_entityId = CRM_Utils_Request::retrieve('entityID', 'Positive', $form);
}
$typeCheck = CRM_Utils_Request::retrieve('type', 'String');
$urlGroupId = CRM_Utils_Request::retrieve('groupID', 'Positive');
if (isset($typeCheck) && $urlGroupId) {
$form->_groupID = $urlGroupId;
}
else {
$form->_groupID = CRM_Utils_Request::retrieve('groupID', 'Positive', $form);
}
$gid = (isset($form->_groupID)) ? $form->_groupID : NULL;
$getCachedTree = isset($form->_getCachedTree) ? $form->_getCachedTree : TRUE;
$subType = $form->_subType;
if (!is_array($subType) && strstr($subType, CRM_Core_DAO::VALUE_SEPARATOR)) {
$subType = str_replace(CRM_Core_DAO::VALUE_SEPARATOR, ',', trim($subType, CRM_Core_DAO::VALUE_SEPARATOR));
}
self::setGroupTree($form, $subType, $gid, $onlySubType, $getCachedTree);
}
/**
* @param CRM_Core_Form $form
*
* @return array
*/
public static function setDefaultValues(&$form) {
$defaults = array();
CRM_Core_BAO_CustomGroup::setDefaults($form->_groupTree, $defaults, FALSE, FALSE, $form->get('action'));
return $defaults;
}
/**
* @param CRM_Core_Form $form
*/
public static function buildQuickForm(&$form) {
$form->addElement('hidden', 'hidden_custom', 1);
$form->addElement('hidden', "hidden_custom_group_count[{$form->_groupID}]", $form->_groupCount);
CRM_Core_BAO_CustomGroup::buildQuickForm($form, $form->_groupTree);
}
/**
* @param $form
* @param $subType
* @param $gid
* @param $onlySubType
* @param $getCachedTree
*
* @return array
*/
public static function setGroupTree(&$form, $subType, $gid, $onlySubType = NULL, $getCachedTree = FALSE) {
$singleRecord = NULL;
if (!empty($form->_groupCount) && !empty($form->_multiRecordDisplay) && $form->_multiRecordDisplay == 'single') {
$singleRecord = $form->_groupCount;
}
$mode = CRM_Utils_Request::retrieve('mode', 'String', $form);
// when a new record is being added for multivalued custom fields.
if (isset($form->_groupCount) && $form->_groupCount == 0 && $mode == 'add' &&
!empty($form->_multiRecordDisplay) && $form->_multiRecordDisplay == 'single') {
$singleRecord = 'new';
}
$groupTree = CRM_Core_BAO_CustomGroup::getTree($form->_type,
NULL,
$form->_entityId,
$gid,
$subType,
$form->_subName,
$getCachedTree,
$onlySubType,
FALSE,
TRUE,
$singleRecord
);
if (property_exists($form, '_customValueCount') && !empty($groupTree)) {
$form->_customValueCount = CRM_Core_BAO_CustomGroup::buildCustomDataView($form, $groupTree, TRUE, NULL, NULL, NULL, $form->_entityId);
}
// we should use simplified formatted groupTree
$groupTree = CRM_Core_BAO_CustomGroup::formatGroupTree($groupTree, $form->_groupCount, $form);
if (isset($form->_groupTree) && is_array($form->_groupTree)) {
$keys = array_keys($groupTree);
foreach ($keys as $key) {
$form->_groupTree[$key] = $groupTree[$key];
}
return array($form, $groupTree);
}
else {
$form->_groupTree = $groupTree;
return array($form, $groupTree);
}
}
}

View file

@ -0,0 +1,87 @@
<?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 form is intended to replace the overloading of many forms to generate a snippet for custom data.
*/
class CRM_Custom_Form_CustomDataByType extends CRM_Core_Form {
/**
* Preprocess function.
*/
public function preProcess() {
$this->_type = $this->_cdType = CRM_Utils_Request::retrieve('type', 'String', CRM_Core_DAO::$_nullObject, TRUE);
$this->_subType = CRM_Utils_Request::retrieve('subType', 'String');
$this->_subName = CRM_Utils_Request::retrieve('subName', 'String');
$this->_groupCount = CRM_Utils_Request::retrieve('cgcount', 'Positive');
$this->_entityId = CRM_Utils_Request::retrieve('entityID', 'Positive');
$this->_groupID = CRM_Utils_Request::retrieve('groupID', 'Positive');
$this->_onlySubtype = CRM_Utils_Request::retrieve('onlySubtype', 'Boolean');
$this->assign('cdType', FALSE);
$this->assign('cgCount', $this->_groupCount);
$contactTypes = CRM_Contact_BAO_ContactType::contactTypeInfo();
if (array_key_exists($this->_type, $contactTypes)) {
$this->assign('contactId', $this->_entityId);
}
if (!is_array($this->_subType) && strstr($this->_subType, CRM_Core_DAO::VALUE_SEPARATOR)) {
$this->_subType = str_replace(CRM_Core_DAO::VALUE_SEPARATOR, ',', trim($this->_subType, CRM_Core_DAO::VALUE_SEPARATOR));
}
CRM_Custom_Form_CustomData::setGroupTree($this, $this->_subType, $this->_groupID, $this->_onlySubtype);
$this->assign('suppressForm', TRUE);
$this->controller->_generateQFKey = FALSE;
}
/**
* Set defaults.
*
* @return array
*/
public function setDefaultValues() {
$defaults = array();
CRM_Core_BAO_CustomGroup::setDefaults($this->_groupTree, $defaults, FALSE, FALSE, $this->get('action'));
return $defaults;
}
/**
* Build quick form.
*/
public function buildQuickForm() {
$this->addElement('hidden', 'hidden_custom', 1);
$this->addElement('hidden', "hidden_custom_group_count[{$this->_groupID}]", $this->_groupCount);
CRM_Core_BAO_CustomGroup::buildQuickForm($this, $this->_groupTree);
}
}

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$
*
*/
/**
* This class is to build the form for deleting a field
*/
class CRM_Custom_Form_DeleteField extends CRM_Core_Form {
/**
* The group id.
*
* @var int
*/
protected $_id;
/**
* The title of the group being deleted.
*
* @var string
*/
protected $_title;
/**
* Set up variables to build the form.
*
* @return void
* @access protected
*/
public function preProcess() {
$this->_id = $this->get('id');
$defaults = array();
$params = array('id' => $this->_id);
CRM_Core_BAO_CustomField::retrieve($params, $defaults);
$this->_title = CRM_Utils_Array::value('label', $defaults);
CRM_Utils_System::setTitle(ts('Delete %1', array(1 => $this->_title)));
}
/**
* Build the form object.
*
* @return void
*/
public function buildQuickForm() {
$this->addButtons(array(
array(
'type' => 'next',
'name' => ts('Delete Custom Field'),
'isDefault' => TRUE,
),
array(
'type' => 'cancel',
'name' => ts('Cancel'),
),
)
);
}
/**
* Process the form when submitted.
*
* @return void
*/
public function postProcess() {
$field = new CRM_Core_DAO_CustomField();
$field->id = $this->_id;
$field->find(TRUE);
CRM_Core_BAO_CustomField::deleteField($field);
// also delete any profiles associted with this custom field
CRM_Core_Session::setStatus(ts('The custom field \'%1\' has been deleted.', array(1 => $field->label)), '', 'success');
}
}

View file

@ -0,0 +1,120 @@
<?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 is to build the form for Deleting Group
*/
class CRM_Custom_Form_DeleteGroup extends CRM_Core_Form {
/**
* The group id.
*
* @var int
*/
protected $_id;
/**
* The title of the group being deleted.
*
* @var string
*/
protected $_title;
/**
* Set up variables to build the form.
*
* @return void
* @access protected
*/
public function preProcess() {
$this->_id = $this->get('id');
$defaults = array();
$params = array('id' => $this->_id);
CRM_Core_BAO_CustomGroup::retrieve($params, $defaults);
$this->_title = $defaults['title'];
//check wheter this contain any custom fields
$customField = new CRM_Core_DAO_CustomField();
$customField->custom_group_id = $this->_id;
if ($customField->find(TRUE)) {
CRM_Core_Session::setStatus(ts("The Group '%1' cannot be deleted! You must Delete all custom fields in this group prior to deleting the group.", array(1 => $this->_title)), ts('Deletion Error'), 'error');
$url = CRM_Utils_System::url('civicrm/admin/custom/group', "reset=1");
CRM_Utils_System::redirect($url);
return TRUE;
}
$this->assign('title', $this->_title);
CRM_Utils_System::setTitle(ts('Confirm Custom Group Delete'));
}
/**
* Build the form object.
*
* @return void
*/
public function buildQuickForm() {
$this->addButtons(array(
array(
'type' => 'next',
'name' => ts('Delete Custom Group'),
'isDefault' => TRUE,
),
array(
'type' => 'cancel',
'name' => ts('Cancel'),
),
)
);
}
/**
* Process the form when submitted.
*
* @return void
*/
public function postProcess() {
$group = new CRM_Core_DAO_CustomGroup();
$group->id = $this->_id;
$group->find(TRUE);
$wt = CRM_Utils_Weight::delWeight('CRM_Core_DAO_CustomGroup', $this->_id);
CRM_Core_BAO_CustomGroup::deleteGroup($group);
CRM_Core_Session::setStatus(ts("The Group '%1' has been deleted.", array(1 => $group->title)), '', 'success');
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,526 @@
<?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$
*
*/
/**
* form to process actions on the set aspect of Custom Data
*/
class CRM_Custom_Form_Group extends CRM_Core_Form {
/**
* The set id saved to the session for an update.
*
* @var int
*/
protected $_id;
/**
* set is empty or not.
*
* @var bool
*/
protected $_isGroupEmpty = TRUE;
/**
* Array of existing subtypes set for a custom set.
*
* @var array
*/
protected $_subtypes = array();
/**
* Set variables up before form is built.
*
*
* @return void
*/
public function preProcess() {
// current set id
$this->_id = $this->get('id');
if ($this->_id && $isReserved = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_id, 'is_reserved', 'id')) {
CRM_Core_Error::fatal("You cannot edit the settings of a reserved custom field-set.");
}
// setting title for html page
if ($this->_action == CRM_Core_Action::UPDATE) {
$title = CRM_Core_BAO_CustomGroup::getTitle($this->_id);
CRM_Utils_System::setTitle(ts('Edit %1', array(1 => $title)));
}
elseif ($this->_action == CRM_Core_Action::VIEW) {
$title = CRM_Core_BAO_CustomGroup::getTitle($this->_id);
CRM_Utils_System::setTitle(ts('Preview %1', array(1 => $title)));
}
else {
CRM_Utils_System::setTitle(ts('New Custom Field Set'));
}
if (isset($this->_id)) {
$params = array('id' => $this->_id);
CRM_Core_BAO_CustomGroup::retrieve($params, $this->_defaults);
$subExtends = CRM_Utils_Array::value('extends_entity_column_value', $this->_defaults);
if (!empty($subExtends)) {
$this->_subtypes = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($subExtends, 1, -1));
}
}
}
/**
* Global form rule.
*
* @param array $fields
* The input form values.
* @param array $files
* The uploaded files if any.
* @param $self
*
*
* @return bool|array
* true if no errors, else array of errors
*/
public static function formRule($fields, $files, $self) {
$errors = array();
//validate group title as well as name.
$title = $fields['title'];
$name = CRM_Utils_String::munge($title, '_', 64);
$query = 'select count(*) from civicrm_custom_group where ( name like %1 OR title like %2 ) and id != %3';
$grpCnt = CRM_Core_DAO::singleValueQuery($query, array(
1 => array($name, 'String'),
2 => array($title, 'String'),
3 => array((int) $self->_id, 'Integer'),
));
if ($grpCnt) {
$errors['title'] = ts('Custom group \'%1\' already exists in Database.', array(1 => $title));
}
if (!empty($fields['extends'][1])) {
if (in_array('', $fields['extends'][1]) && count($fields['extends'][1]) > 1) {
$errors['extends'] = ts("Cannot combine other option with 'Any'.");
}
}
if (empty($fields['extends'][0])) {
$errors['extends'] = ts("You need to select the type of record that this set of custom fields is applicable for.");
}
$extends = array('Activity', 'Relationship', 'Group', 'Contribution', 'Membership', 'Event', 'Participant');
if (in_array($fields['extends'][0], $extends) && $fields['style'] == 'Tab') {
$errors['style'] = ts("Display Style should be Inline for this Class");
$self->assign('showStyle', TRUE);
}
if (!empty($fields['is_multiple'])) {
$self->assign('showMultiple', TRUE);
}
if (empty($fields['is_multiple']) && $fields['style'] == 'Tab with table') {
$errors['style'] = ts("Display Style 'Tab with table' is only supported for multiple-record custom field sets.");
}
//checks the given custom set doesnot start with digit
$title = $fields['title'];
if (!empty($title)) {
// gives the ascii value
$asciiValue = ord($title{0});
if ($asciiValue >= 48 && $asciiValue <= 57) {
$errors['title'] = ts("Name cannot not start with a digit");
}
}
return empty($errors) ? TRUE : $errors;
}
/**
* add the rules (mainly global rules) for form.
* All local rules are added near the element
*
*
* @return void
* @see valid_date
*/
public function addRules() {
$this->addFormRule(array('CRM_Custom_Form_Group', 'formRule'), $this);
}
/**
* Build the form object.
*
*
* @return void
*/
public function buildQuickForm() {
$this->applyFilter('__ALL__', 'trim');
$attributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_CustomGroup');
//title
$this->add('text', 'title', ts('Set Name'), $attributes['title'], TRUE);
//Fix for code alignment, CRM-3058
$contactTypes = array('Contact', 'Individual', 'Household', 'Organization');
$this->assign('contactTypes', json_encode($contactTypes));
$sel1 = array("" => ts("- select -")) + CRM_Core_SelectValues::customGroupExtends();
$sel2 = array();
$activityType = CRM_Core_PseudoConstant::activityType(FALSE, TRUE, FALSE, 'label', TRUE);
$eventType = CRM_Core_OptionGroup::values('event_type');
$grantType = CRM_Core_OptionGroup::values('grant_type');
$campaignTypes = CRM_Campaign_PseudoConstant::campaignType();
$membershipType = CRM_Member_BAO_MembershipType::getMembershipTypes(FALSE);
$participantRole = CRM_Core_OptionGroup::values('participant_role');
ksort($sel1);
asort($activityType);
asort($eventType);
asort($grantType);
asort($membershipType);
asort($participantRole);
$sel2['Event'] = $eventType;
$sel2['Grant'] = $grantType;
$sel2['Activity'] = $activityType;
$sel2['Campaign'] = $campaignTypes;
$sel2['Membership'] = $membershipType;
$sel2['ParticipantRole'] = $participantRole;
$sel2['ParticipantEventName'] = CRM_Event_PseudoConstant::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
$sel2['ParticipantEventType'] = $eventType;
$sel2['Contribution'] = CRM_Contribute_PseudoConstant::financialType();
$sel2['Relationship'] = self::getRelationshipTypes();
$sel2['Individual'] = CRM_Contact_BAO_ContactType::subTypePairs('Individual', FALSE, NULL);
$sel2['Household'] = CRM_Contact_BAO_ContactType::subTypePairs('Household', FALSE, NULL);
$sel2['Organization'] = CRM_Contact_BAO_ContactType::subTypePairs('Organization', FALSE, NULL);
CRM_Core_BAO_CustomGroup::getExtendedObjectTypes($sel2);
foreach ($sel2 as $main => $sub) {
if (!empty($sel2[$main])) {
$sel2[$main] = array(
'' => ts("- Any -"),
) + $sel2[$main];
}
}
$cSubTypes = CRM_Core_Component::contactSubTypes();
if (!empty($cSubTypes)) {
$contactSubTypes = array();
foreach ($cSubTypes as $key => $value) {
$contactSubTypes[$key] = $key;
}
$sel2['Contact'] = array(
"" => ("- Any -"),
) + $contactSubTypes;
}
else {
if (!isset($this->_id)) {
$formName = 'document.forms.' . $this->_name;
$js = "<script type='text/javascript'>\n";
$js .= "{$formName}['extends_1'].style.display = 'none';\n";
$js .= "</script>";
$this->assign('initHideBlocks', $js);
}
}
$sel = &$this->add('hierselect',
'extends',
ts('Used For'),
array(
'name' => 'extends[0]',
'style' => 'vertical-align: top;',
),
TRUE
);
$sel->setOptions(array($sel1, $sel2));
if (is_a($sel->_elements[1], 'HTML_QuickForm_select')) {
// make second selector a multi-select -
$sel->_elements[1]->setMultiple(TRUE);
$sel->_elements[1]->setSize(5);
}
if ($this->_action == CRM_Core_Action::UPDATE) {
$subName = CRM_Utils_Array::value('extends_entity_column_id', $this->_defaults);
if ($this->_defaults['extends'] == 'Participant') {
if ($subName == 1) {
$this->_defaults['extends'] = 'ParticipantRole';
}
elseif ($subName == 2) {
$this->_defaults['extends'] = 'ParticipantEventName';
}
elseif ($subName == 3) {
$this->_defaults['extends'] = 'ParticipantEventType';
}
}
//allow to edit settings if custom set is empty CRM-5258
$this->_isGroupEmpty = CRM_Core_BAO_CustomGroup::isGroupEmpty($this->_id);
if (!$this->_isGroupEmpty) {
if (!empty($this->_subtypes)) {
// we want to allow adding / updating subtypes for this case,
// and therefore freeze the first selector only.
$sel->_elements[0]->freeze();
}
else {
// freeze both the selectors
$sel->freeze();
}
}
$this->assign('isCustomGroupEmpty', $this->_isGroupEmpty);
$this->assign('gid', $this->_id);
}
$this->assign('defaultSubtypes', json_encode($this->_subtypes));
// help text
$this->add('wysiwyg', 'help_pre', ts('Pre-form Help'), $attributes['help_pre']);
$this->add('wysiwyg', 'help_post', ts('Post-form Help'), $attributes['help_post']);
// weight
$this->add('text', 'weight', ts('Order'), $attributes['weight'], TRUE);
$this->addRule('weight', ts('is a numeric field'), 'numeric');
// display style
$this->add('select', 'style', ts('Display Style'), CRM_Core_SelectValues::customGroupStyle());
// is this set collapsed or expanded ?
$this->addElement('advcheckbox', 'collapse_display', ts('Collapse this set on initial display'));
// is this set collapsed or expanded ? in advanced search
$this->addElement('advcheckbox', 'collapse_adv_display', ts('Collapse this set in Advanced Search'));
// is this set active ?
$this->addElement('advcheckbox', 'is_active', ts('Is this Custom Data Set active?'));
//Is this set visible on public pages?
$this->addElement('advcheckbox', 'is_public', ts('Is this Custom Data Set public?'));
// does this set have multiple record?
$multiple = $this->addElement('advcheckbox', 'is_multiple',
ts('Does this Custom Field Set allow multiple records?'), NULL);
// $min_multiple = $this->add('text', 'min_multiple', ts('Minimum number of multiple records'), $attributes['min_multiple'] );
// $this->addRule('min_multiple', ts('is a numeric field') , 'numeric');
$max_multiple = $this->add('text', 'max_multiple', ts('Maximum number of multiple records'), $attributes['max_multiple']);
$this->addRule('max_multiple', ts('is a numeric field'), 'numeric');
//allow to edit settings if custom set is empty CRM-5258
$this->assign('isGroupEmpty', $this->_isGroupEmpty);
if (!$this->_isGroupEmpty) {
$multiple->freeze();
//$min_multiple->freeze();
$max_multiple->freeze();
}
$this->assign('showStyle', FALSE);
$this->assign('showMultiple', FALSE);
$buttons = array(
array(
'type' => 'next',
'name' => ts('Save'),
'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
'isDefault' => TRUE,
),
array(
'type' => 'cancel',
'name' => ts('Cancel'),
),
);
if (!$this->_isGroupEmpty && !empty($this->_subtypes)) {
$buttons[0]['class'] = 'crm-warnDataLoss';
}
$this->addButtons($buttons);
// TODO: Is this condition ever true? Can this code be removed?
if ($this->_action & CRM_Core_Action::VIEW) {
$this->freeze();
$this->addElement('button', 'done', ts('Done'), array('onclick' => "location.href='civicrm/admin/custom/group?reset=1&action=browse'"));
}
}
/**
* Set default values for the form. Note that in edit/view mode
* the default values are retrieved from the database
*
*
* @return array
* array of default values
*/
public function setDefaultValues() {
$defaults = &$this->_defaults;
$this->assign('showMaxMultiple', TRUE);
if ($this->_action == CRM_Core_Action::ADD) {
$defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_CustomGroup');
$defaults['is_multiple'] = $defaults['min_multiple'] = 0;
$defaults['is_active'] = $defaults['is_public'] = $defaults['collapse_display'] = 1;
$defaults['style'] = 'Inline';
}
elseif (empty($defaults['max_multiple']) && !$this->_isGroupEmpty) {
$this->assign('showMaxMultiple', FALSE);
}
if (($this->_action & CRM_Core_Action::UPDATE) && !empty($defaults['is_multiple'])) {
$defaults['collapse_display'] = 0;
}
if (isset($defaults['extends'])) {
$extends = $defaults['extends'];
unset($defaults['extends']);
$defaults['extends'][0] = $extends;
if (!empty($this->_subtypes)) {
$defaults['extends'][1] = $this->_subtypes;
}
else {
$defaults['extends'][1] = array(0 => '');
}
if ($extends == 'Relationship' && !empty($this->_subtypes)) {
$relationshipDefaults = array();
foreach ($defaults['extends'][1] as $donCare => $rel_type_id) {
$relationshipDefaults[] = $rel_type_id;
}
$defaults['extends'][1] = $relationshipDefaults;
}
}
return $defaults;
}
/**
* Process the form.
*
*
* @return void
*/
public function postProcess() {
// get the submitted form values.
$params = $this->controller->exportValues('Group');
$params['overrideFKConstraint'] = 0;
if ($this->_action & CRM_Core_Action::UPDATE) {
$params['id'] = $this->_id;
if ($this->_defaults['extends'][0] != $params['extends'][0]) {
$params['overrideFKConstraint'] = 1;
}
if (!empty($this->_subtypes)) {
$subtypesToBeRemoved = array();
$subtypesToPreserve = $params['extends'][1];
// Don't remove any value if group is extended to -any- subtype
if (!empty($subtypesToPreserve[0])) {
$subtypesToBeRemoved = array_diff($this->_subtypes, array_intersect($this->_subtypes, $subtypesToPreserve));
}
CRM_Contact_BAO_ContactType::deleteCustomRowsOfSubtype($this->_id, $subtypesToBeRemoved, $subtypesToPreserve);
}
}
elseif ($this->_action & CRM_Core_Action::ADD) {
//new custom set , so lets set the created_id
$session = CRM_Core_Session::singleton();
$params['created_id'] = $session->get('userID');
$params['created_date'] = date('YmdHis');
}
$group = CRM_Core_BAO_CustomGroup::create($params);
// reset the cache
CRM_Core_BAO_Cache::deleteGroup('contact fields');
if ($this->_action & CRM_Core_Action::UPDATE) {
CRM_Core_Session::setStatus(ts('Your custom field set \'%1 \' has been saved.', array(1 => $group->title)), ts('Saved'), 'success');
}
else {
// Jump directly to adding a field if popups are disabled
$action = CRM_Core_Resources::singleton()->ajaxPopupsEnabled ? '' : '/add';
$url = CRM_Utils_System::url("civicrm/admin/custom/group/field$action", 'reset=1&new=1&gid=' . $group->id . '&action=' . ($action ? 'add' : 'browse'));
CRM_Core_Session::setStatus(ts("Your custom field set '%1' has been added. You can add custom fields now.",
array(1 => $group->title)
), ts('Saved'), 'success');
$session = CRM_Core_Session::singleton();
$session->replaceUserContext($url);
}
// prompt Drupal Views users to update $db_prefix in settings.php, if necessary
global $db_prefix;
$config = CRM_Core_Config::singleton();
if (is_array($db_prefix) && $config->userSystem->is_drupal && module_exists('views')) {
// get table_name for each custom group
$tables = array();
$sql = "SELECT table_name FROM civicrm_custom_group WHERE is_active = 1";
$result = CRM_Core_DAO::executeQuery($sql);
while ($result->fetch()) {
$tables[$result->table_name] = $result->table_name;
}
// find out which tables are missing from the $db_prefix array
$missingTableNames = array_diff_key($tables, $db_prefix);
if (!empty($missingTableNames)) {
CRM_Core_Session::setStatus(ts("To ensure that all of your custom data groups are available to Views, you may need to add the following key(s) to the db_prefix array in your settings.php file: '%1'.",
array(1 => implode(', ', $missingTableNames))
), ts('Note'), 'info');
}
}
}
/**
* Return a formatted list of relationship labels.
*
* @return array
* Array (int $id => string $label).
*/
public static function getRelationshipTypes() {
// Note: We include inactive reltypes because we don't want to break custom-data
// UI when a reltype is disabled.
return CRM_Core_DAO::executeQuery('
SELECT
id,
(CASE 1
WHEN label_a_b is not null AND label_b_a is not null AND label_a_b != label_b_a
THEN concat(label_a_b, \' / \', label_b_a)
WHEN label_a_b is not null
THEN label_a_b
WHEN label_b_a is not null
THEN label_b_a
ELSE concat("RelType #", id)
END) as label
FROM civicrm_relationship_type
'
)->fetchMap('id', 'label');
}
}

View file

@ -0,0 +1,182 @@
<?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 is to build the form for Deleting Group
*/
class CRM_Custom_Form_MoveField extends CRM_Core_Form {
/**
* The src group id.
*
* @var int
*/
protected $_srcGID;
/**
* The src field id.
*
* @var int
*/
protected $_srcFID;
/**
* The dst group id.
*
* @var int
*/
protected $_dstGID;
/**
* The dst field id.
*
* @var int
*/
protected $_dstFID;
/**
* The title of the field being moved.
*
* @var string
*/
protected $_srcFieldLabel;
/**
* Set up variables to build the form.
*
* @return void
* @access protected
*/
public function preProcess() {
$this->_srcFID = CRM_Utils_Request::retrieve('fid', 'Positive',
$this, TRUE
);
$this->_srcGID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
$this->_srcFID,
'custom_group_id'
);
$this->_srcFieldLabel = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
$this->_srcFID,
'label'
);
CRM_Utils_System::setTitle(ts('Custom Field Move: %1',
array(1 => $this->_srcFieldLabel)
));
$session = CRM_Core_Session::singleton();
$session->pushUserContext(CRM_Utils_System::url('civicrm/admin/custom/group/field', "reset=1&action=browse&gid={$this->_srcGID}"));
}
/**
* Build the form object.
*
* @return void
*/
public function buildQuickForm() {
$customGroup = CRM_Core_PseudoConstant::get('CRM_Core_DAO_CustomField', 'custom_group_id');
unset($customGroup[$this->_srcGID]);
if (empty($customGroup)) {
CRM_Core_Error::statusBounce(ts('You need more than one custom group to move fields'));
}
$customGroup = array(
'' => ts('- select -'),
) + $customGroup;
$this->add('select',
'dst_group_id',
ts('Destination'),
$customGroup,
TRUE
);
$this->addButtons(array(
array(
'type' => 'next',
'name' => ts('Move Custom Field'),
'isDefault' => TRUE,
),
array(
'type' => 'cancel',
'name' => ts('Cancel'),
),
)
);
$this->addFormRule(array('CRM_Custom_Form_MoveField', 'formRule'), $this);
}
/**
* @param $fields
* @param $files
* @param $self
*
* @return array|bool
*/
public static function formRule($fields, $files, $self) {
$self->_dstGID = $fields['dst_group_id'];
$tmp = CRM_Core_BAO_CustomField::_moveFieldValidate($self->_srcFID, $self->_dstGID);
$errors = array();
if ($tmp['newGroupID']) {
$errors['dst_group_id'] = $tmp['newGroupID'];
}
return empty($errors) ? TRUE : $errors;
}
/**
* Process the form when submitted.
*
* @return void
*/
public function postProcess() {
CRM_Core_BAO_CustomField::moveField($this->_srcFID, $this->_dstGID);
$dstGroup = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
$this->_dstGID,
'title'
);
$srcUrl = CRM_Utils_System::url('civicrm/admin/custom/group/field', "reset=1&action=browse&gid={$this->_dstGID}");
CRM_Core_Session::setStatus(ts("%1 has been moved to the custom set <a href='%3'>%2</a>.",
array(
1 => $this->_srcFieldLabel,
2 => $dstGroup,
3 => $srcUrl,
)), '', 'success');
}
}

View file

@ -0,0 +1,516 @@
<?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$
*
*/
/**
* form to process actions on the field aspect of Custom
*/
class CRM_Custom_Form_Option extends CRM_Core_Form {
/**
* The custom field id saved to the session for an update
*
* @var int
*/
protected $_fid;
/**
* The custom group id saved to the session for an update
*
* @var int
*/
protected $_gid;
/**
* The option group ID
*/
protected $_optionGroupID = NULL;
/**
* The Option id, used when editing the Option
*
* @var int
*/
protected $_id;
/**
* Set variables up before form is built.
*
* @return void
*/
public function preProcess() {
$this->_fid = CRM_Utils_Request::retrieve('fid', 'Positive', $this);
$this->_gid = CRM_Utils_Request::retrieve('gid', 'Positive', $this);
if (!isset($this->_gid) && $this->_fid) {
$this->_gid = CRM_Core_DAO::getFieldValue(
'CRM_Core_DAO_CustomField',
$this->_fid,
'custom_group_id'
);
}
if ($this->_fid) {
$this->_optionGroupID = CRM_Core_DAO::getFieldValue(
'CRM_Core_DAO_CustomField',
$this->_fid,
'option_group_id'
);
}
if ($isReserved = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_gid, 'is_reserved', 'id')) {
CRM_Core_Error::fatal("You cannot add or edit muliple choice options in a reserved custom field-set.");
}
$this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
}
/**
* Set default values for the form. Note that in edit/view mode
* the default values are retrieved from the database
*
* @return array
* array of default values
*/
public function setDefaultValues() {
$defaults = $fieldDefaults = array();
if (isset($this->_id)) {
$params = array('id' => $this->_id);
CRM_Core_BAO_CustomOption::retrieve($params, $defaults);
$paramsField = array('id' => $this->_fid);
CRM_Core_BAO_CustomField::retrieve($paramsField, $fieldDefaults);
if ($fieldDefaults['html_type'] == 'CheckBox'
|| $fieldDefaults['html_type'] == 'Multi-Select'
|| $fieldDefaults['html_type'] == 'AdvMulti-Select'
) {
if (!empty($fieldDefaults['default_value'])) {
$defaultCheckValues = explode(CRM_Core_DAO::VALUE_SEPARATOR,
substr($fieldDefaults['default_value'], 1, -1)
);
if (in_array($defaults['value'], $defaultCheckValues)) {
$defaults['default_value'] = 1;
}
}
}
else {
if (CRM_Utils_Array::value('default_value', $fieldDefaults) == CRM_Utils_Array::value('value', $defaults)) {
$defaults['default_value'] = 1;
}
}
}
else {
$defaults['is_active'] = 1;
}
if ($this->_action & CRM_Core_Action::ADD) {
$fieldValues = array('option_group_id' => $this->_optionGroupID);
$defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_OptionValue', $fieldValues);
}
return $defaults;
}
/**
* Build the form object.
*
* @return void
*/
public function buildQuickForm() {
if ($this->_action == CRM_Core_Action::DELETE) {
$option = civicrm_api3('option_value', 'getsingle', array('id' => $this->_id));
$this->assign('label', $option['label']);
$this->addButtons(array(
array(
'type' => 'next',
'name' => ts('Delete'),
'isDefault' => TRUE,
),
array(
'type' => 'cancel',
'name' => ts('Cancel'),
),
)
);
}
else {
// lets trim all the whitespace
$this->applyFilter('__ALL__', 'trim');
// hidden Option Id for validation use
$this->add('hidden', 'optionId', $this->_id);
//hidden field ID for validation use
$this->add('hidden', 'fieldId', $this->_fid);
// label
$this->add('text', 'label', ts('Option Label'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'label'), TRUE);
$this->add('text', 'value', ts('Option Value'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'value'), TRUE);
// weight
$this->add('text', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'weight'), TRUE);
$this->addRule('weight', ts('is a numeric field'), 'numeric');
// is active ?
$this->add('checkbox', 'is_active', ts('Active?'));
// Set the default value for Custom Field
$this->add('checkbox', 'default_value', ts('Default'));
// add a custom form rule
$this->addFormRule(array('CRM_Custom_Form_Option', 'formRule'), $this);
// add buttons
$this->addButtons(array(
array(
'type' => 'next',
'name' => ts('Save'),
'isDefault' => TRUE,
),
array(
'type' => 'next',
'name' => ts('Save and New'),
'subName' => 'new',
),
array(
'type' => 'cancel',
'name' => ts('Cancel'),
),
)
);
// if view mode pls freeze it with the done button.
if ($this->_action & CRM_Core_Action::VIEW) {
$this->freeze();
$url = CRM_Utils_System::url('civicrm/admin/custom/group/field/option',
'reset=1&action=browse&fid=' . $this->_fid . '&gid=' . $this->_gid,
TRUE, NULL, FALSE
);
$this->addElement('button',
'done',
ts('Done'),
array('onclick' => "location.href='$url'", 'class' => 'crm-form-submit cancel', 'crm-icon' => 'fa-times')
);
}
}
$this->assign('id', $this->_id);
}
/**
* Global validation rules for the form.
*
* @param array $fields
* Posted values of the form.
*
* @param $files
* @param CRM_Core_Form $form
*
* @return array
* list of errors to be posted back to the form
*/
public static function formRule($fields, $files, $form) {
$optionLabel = $fields['label'];
$optionValue = $fields['value'];
$fieldId = $form->_fid;
$optionGroupId = $form->_optionGroupID;
$temp = array();
if (empty($form->_id)) {
$query = "
SELECT count(*)
FROM civicrm_option_value
WHERE option_group_id = %1
AND label = %2";
$params = array(
1 => array($optionGroupId, 'Integer'),
2 => array($optionLabel, 'String'),
);
if (CRM_Core_DAO::singleValueQuery($query, $params) > 0) {
$errors['label'] = ts('There is an entry with the same label.');
}
$query = "
SELECT count(*)
FROM civicrm_option_value
WHERE option_group_id = %1
AND value = %2";
$params = array(
1 => array($optionGroupId, 'Integer'),
2 => array($optionValue, 'String'),
);
if (CRM_Core_DAO::singleValueQuery($query, $params) > 0) {
$errors['value'] = ts('There is an entry with the same value.');
}
}
else {
//capture duplicate entries while updating Custom Options
$optionId = CRM_Utils_Type::escape($fields['optionId'], 'Integer');
//check label duplicates within a custom field
$query = "
SELECT count(*)
FROM civicrm_option_value
WHERE option_group_id = %1
AND id != %2
AND label = %3";
$params = array(
1 => array($optionGroupId, 'Integer'),
2 => array($optionId, 'Integer'),
3 => array($optionLabel, 'String'),
);
if (CRM_Core_DAO::singleValueQuery($query, $params) > 0) {
$errors['label'] = ts('There is an entry with the same label.');
}
//check value duplicates within a custom field
$query = "
SELECT count(*)
FROM civicrm_option_value
WHERE option_group_id = %1
AND id != %2
AND value = %3";
$params = array(
1 => array($optionGroupId, 'Integer'),
2 => array($optionId, 'Integer'),
3 => array($optionValue, 'String'),
);
if (CRM_Core_DAO::singleValueQuery($query, $params) > 0) {
$errors['value'] = ts('There is an entry with the same value.');
}
}
$query = "
SELECT data_type
FROM civicrm_custom_field
WHERE id = %1";
$params = array(1 => array($fieldId, 'Integer'));
$dao = CRM_Core_DAO::executeQuery($query, $params);
if ($dao->fetch()) {
switch ($dao->data_type) {
case 'Int':
if (!CRM_Utils_Rule::integer($fields["value"])) {
$errors['value'] = ts('Please enter a valid integer value.');
}
break;
case 'Float':
// case 'Money':
if (!CRM_Utils_Rule::numeric($fields["value"])) {
$errors['value'] = ts('Please enter a valid number.');
}
break;
case 'Money':
if (!CRM_Utils_Rule::money($fields["value"])) {
$errors['value'] = ts('Please enter a valid value.');
}
break;
case 'Date':
if (!CRM_Utils_Rule::date($fields["value"])) {
$errors['value'] = ts('Please enter a valid date using YYYY-MM-DD format. Example: 2004-12-31.');
}
break;
case 'Boolean':
if (!CRM_Utils_Rule::integer($fields["value"]) &&
($fields["value"] != '1' || $fields["value"] != '0')
) {
$errors['value'] = ts('Please enter 1 or 0 as value.');
}
break;
case 'Country':
if (!empty($fields["value"])) {
$params = array(1 => array($fields['value'], 'String'));
$query = "SELECT count(*) FROM civicrm_country WHERE name = %1 OR iso_code = %1";
if (CRM_Core_DAO::singleValueQuery($query, $params) <= 0) {
$errors['value'] = ts('Invalid default value for country.');
}
}
break;
case 'StateProvince':
if (!empty($fields["value"])) {
$params = array(1 => array($fields['value'], 'String'));
$query = "
SELECT count(*)
FROM civicrm_state_province
WHERE name = %1
OR abbreviation = %1";
if (CRM_Core_DAO::singleValueQuery($query, $params) <= 0) {
$errors['value'] = ts('The invalid value for State/Province data type');
}
}
break;
}
}
return empty($errors) ? TRUE : $errors;
}
/**
* Process the form.
*
* @return void
*/
public function postProcess() {
// store the submitted values in an array
$params = $this->controller->exportValues('Option');
if ($this->_action == CRM_Core_Action::DELETE) {
$option = civicrm_api3('option_value', 'getsingle', array('id' => $this->_id));
$fieldValues = array('option_group_id' => $this->_optionGroupID);
CRM_Utils_Weight::delWeight('CRM_Core_DAO_OptionValue', $this->_id, $fieldValues);
CRM_Core_BAO_CustomOption::del($this->_id);
CRM_Core_Session::setStatus(ts('Option "%1" has been deleted.', array(1 => $option['label'])), ts('Deleted'), 'success');
return;
}
// set values for custom field properties and save
$customOption = new CRM_Core_DAO_OptionValue();
$customOption->label = $params['label'];
$customOption->name = CRM_Utils_String::titleToVar($params['label']);
$customOption->weight = $params['weight'];
$customOption->value = $params['value'];
$customOption->is_active = CRM_Utils_Array::value('is_active', $params, FALSE);
$oldWeight = NULL;
if ($this->_id) {
$customOption->id = $this->_id;
CRM_Core_BAO_CustomOption::updateCustomValues($params);
$oldWeight = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $this->_id, 'weight', 'id');
}
$fieldValues = array('option_group_id' => $this->_optionGroupID);
$customOption->weight
= CRM_Utils_Weight::updateOtherWeights(
'CRM_Core_DAO_OptionValue',
$oldWeight,
$params['weight'],
$fieldValues);
$customOption->option_group_id = $this->_optionGroupID;
$customField = new CRM_Core_DAO_CustomField();
$customField->id = $this->_fid;
if (
$customField->find(TRUE) &&
(
$customField->html_type == 'CheckBox' ||
$customField->html_type == 'AdvMulti-Select' ||
$customField->html_type == 'Multi-Select'
)
) {
$defVal = explode(
CRM_Core_DAO::VALUE_SEPARATOR,
substr($customField->default_value, 1, -1)
);
if (!empty($params['default_value'])) {
if (!in_array($customOption->value, $defVal)) {
if (empty($defVal[0])) {
$defVal = array($customOption->value);
}
else {
$defVal[] = $customOption->value;
}
$customField->default_value
= CRM_Core_DAO::VALUE_SEPARATOR .
implode(CRM_Core_DAO::VALUE_SEPARATOR, $defVal) .
CRM_Core_DAO::VALUE_SEPARATOR;
$customField->save();
}
}
elseif (in_array($customOption->value, $defVal)) {
$tempVal = array();
foreach ($defVal as $v) {
if ($v != $customOption->value) {
$tempVal[] = $v;
}
}
$customField->default_value
= CRM_Core_DAO::VALUE_SEPARATOR .
implode(CRM_Core_DAO::VALUE_SEPARATOR, $tempVal) .
CRM_Core_DAO::VALUE_SEPARATOR;
$customField->save();
}
}
else {
switch ($customField->data_type) {
case 'Money':
$customOption->value = CRM_Utils_Rule::cleanMoney($customOption->value);
break;
case 'Int':
$customOption->value = intval($customOption->value);
break;
case 'Float':
$customOption->value = floatval($customOption->value);
break;
}
if (!empty($params['default_value'])) {
$customField->default_value = $customOption->value;
$customField->save();
}
elseif ($customField->find(TRUE) && $customField->default_value == $customOption->value) {
// this is the case where this option is the current default value and we have been reset
$customField->default_value = 'null';
$customField->save();
}
}
$customOption->save();
$msg = ts('Your multiple choice option \'%1\' has been saved', array(1 => $customOption->label));
CRM_Core_Session::setStatus($msg, '', 'success');
$buttonName = $this->controller->getButtonName();
$session = CRM_Core_Session::singleton();
if ($buttonName == $this->getButtonName('next', 'new')) {
CRM_Core_Session::setStatus(ts('You can add another option.'), '', 'info');
$session->replaceUserContext(
CRM_Utils_System::url(
'civicrm/admin/custom/group/field/option',
'reset=1&action=add&fid=' . $this->_fid . '&gid=' . $this->_gid
)
);
}
}
}

View file

@ -0,0 +1,130 @@
<?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 generates form components for previewing custom data
*
* It delegates the work to lower level subclasses and integrates the changes
* back in. It also uses a lot of functionality with the CRM API's, so any change
* made here could potentially affect the API etc. Be careful, be aware, use unit tests.
*
*/
class CRM_Custom_Form_Preview extends CRM_Core_Form {
/**
* The group tree data.
*
* @var array
*/
protected $_groupTree;
/**
* Pre processing work done here.
*
* gets session variables for group or field id
*
* @return void
*/
public function preProcess() {
// get the controller vars
$this->_groupId = $this->get('groupId');
$this->_fieldId = $this->get('fieldId');
if ($this->_fieldId) {
// field preview
$defaults = array();
$params = array('id' => $this->_fieldId);
$fieldDAO = new CRM_Core_DAO_CustomField();
CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
if (!empty($defaults['is_view'])) {
CRM_Core_Error::statusBounce(ts('This field is view only so it will not display on edit form.'));
}
elseif (CRM_Utils_Array::value('is_active', $defaults) == 0) {
CRM_Core_Error::statusBounce(ts('This field is inactive so it will not display on edit form.'));
}
$groupTree = array();
$groupTree[$this->_groupId]['id'] = 0;
$groupTree[$this->_groupId]['fields'] = array();
$groupTree[$this->_groupId]['fields'][$this->_fieldId] = $defaults;
$this->_groupTree = CRM_Core_BAO_CustomGroup::formatGroupTree($groupTree, 1, $this);
$this->assign('preview_type', 'field');
}
else {
$groupTree = CRM_Core_BAO_CustomGroup::getGroupDetail($this->_groupId);
$this->_groupTree = CRM_Core_BAO_CustomGroup::formatGroupTree($groupTree, TRUE, $this);
$this->assign('preview_type', 'group');
}
}
/**
* Set the default form values.
*
* @return array
* the default array reference
*/
public function setDefaultValues() {
$defaults = array();
CRM_Core_BAO_CustomGroup::setDefaults($this->_groupTree, $defaults, FALSE, FALSE);
return $defaults;
}
/**
* Build the form object.
*
* @return void
*/
public function buildQuickForm() {
if (is_array($this->_groupTree[$this->_groupId])) {
foreach ($this->_groupTree[$this->_groupId]['fields'] as & $field) {
//add the form elements
CRM_Core_BAO_CustomField::addQuickFormElement($this, $field['element_name'], $field['id'], CRM_Utils_Array::value('is_required', $field));
}
$this->assign('groupTree', $this->_groupTree);
}
$this->addButtons(array(
array(
'type' => 'cancel',
'name' => ts('Done with Preview'),
'isDefault' => TRUE,
),
)
);
}
}

View file

@ -0,0 +1,32 @@
<?php
/**
* Class CRM_Custom_Import_Controller
*/
class CRM_Custom_Import_Controller extends CRM_Core_Controller {
/**
* Class constructor.
*
* @param string $title
* @param bool|int $action
* @param bool $modal
*/
public function __construct($title = NULL, $action = CRM_Core_Action::NONE, $modal = TRUE) {
parent::__construct($title, $modal);
// lets get around the time limit issue if possible, CRM-2113
if (!ini_get('safe_mode')) {
set_time_limit(0);
}
$this->_stateMachine = new CRM_Import_StateMachine($this, $action);
// create and instantiate the pages
$this->addPages($this->_stateMachine, $action);
// add all the actions
$config = CRM_Core_Config::singleton();
$this->addActions($config->uploadDir, array('uploadFile'));
}
}

View file

@ -0,0 +1,32 @@
<?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_Custom_Import_Field
*/
class CRM_Custom_Import_Field extends CRM_Contact_Import_Field {
}

View file

@ -0,0 +1,94 @@
<?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 gets the name of the file to upload
*/
class CRM_Custom_Import_Form_DataSource extends CRM_Import_Form_DataSource {
const PATH = 'civicrm/import/custom';
const IMPORT_ENTITY = 'Multi value custom data';
/**
* @return array
*/
public function setDefaultValues() {
$config = CRM_Core_Config::singleton();
$defaults = array(
'contactType' => CRM_Import_Parser::CONTACT_INDIVIDUAL,
'fieldSeparator' => $config->fieldSeparator,
'multipleCustomData' => $this->_id,
);
if ($loadeMapping = $this->get('loadedMapping')) {
$this->assign('loadedMapping', $loadeMapping);
$defaults['savedMapping'] = $loadeMapping;
}
return $defaults;
}
/**
* Build the form object.
*
* @return void
*/
public function buildQuickForm() {
parent::buildQuickForm();
$multipleCustomData = CRM_Core_BAO_CustomGroup::getMultipleFieldGroup();
$this->add('select', 'multipleCustomData', ts('Multi-value Custom Data'), array('' => ts('- select -')) + $multipleCustomData, TRUE);
$this->addContactTypeSelector();
}
/**
* Process the uploaded file.
*
* @return void
*/
public function postProcess() {
$this->storeFormValues(array(
'contactType',
'dateFormats',
'savedMapping',
'multipleCustomData',
));
$this->submitFileForMapping('CRM_Custom_Import_Parser_Api', 'multipleCustomData');
}
}

View file

@ -0,0 +1,223 @@
<?php
/**
* Class CRM_Custom_Import_Form_MapField
*/
class CRM_Custom_Import_Form_MapField extends CRM_Contact_Import_Form_MapField {
protected $_parser = 'CRM_Custom_Import_Parser_Api';
protected $_mappingType = 'Import Multi value custom data';
/**
* Entity being imported to.
* @var string
*/
protected $_entity;
/**
* Set variables up before form is built.
*
* @return void
*/
public function preProcess() {
$this->_mapperFields = $this->get('fields');
asort($this->_mapperFields);
$this->_columnCount = $this->get('columnCount');
$this->assign('columnCount', $this->_columnCount);
$this->_dataValues = $this->get('dataValues');
$highlightedFields = array('contact_id', 'external_identifier');
//Separate column names from actual values.
$columnNames = $this->_dataValues[0];
//actual values need to be in 2d array ($array[$i][$j]) format to be parsed by the template.
$dataValues[] = $this->_dataValues[1];
$this->assign('dataValues', $dataValues);
$this->_entity = $this->_multipleCustomData = $this->get('multipleCustomData');
$skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
$this->_onDuplicate = $this->get('onDuplicate');
if ($skipColumnHeader) {
//showColNames needs to be true to show "Column Names" column
$this->assign('showColNames', $skipColumnHeader);
$this->assign('columnNames', $columnNames);
/* if we had a column header to skip, stash it for later */
$this->_columnHeaders = $this->_dataValues[0];
}
$this->assign('rowDisplayCount', 2);
$this->assign('highlightedFields', $highlightedFields);
}
/**
* Build the form object.
*
* @return void
*/
public function buildQuickForm() {
parent::buildQuickForm();
$this->addFormRule(array('CRM_Custom_Import_Form_MapField', 'formRule'));
}
/**
* Global validation rules for the form.
*
* @param array $fields
* Posted values of the form.
*
* @return array
* list of errors to be posted back to the form
*/
public static function formRule($fields) {
$errors = array();
$fieldMessage = NULL;
if (!array_key_exists('savedMapping', $fields)) {
$importKeys = array();
foreach ($fields['mapper'] as $mapperPart) {
$importKeys[] = $mapperPart[0];
}
// check either contact id or external identifier
if (!in_array('contact_id', $importKeys) && !in_array('external_identifier', $importKeys)) {
if (!isset($errors['_qf_default'])) {
$errors['_qf_default'] = '';
}
$errors['_qf_default'] .= ts('Missing required field: %1', array(1 => ts('Contact ID or External Identifier')));
}
}
if (!empty($fields['saveMapping'])) {
$nameField = CRM_Utils_Array::value('saveMappingName', $fields);
if (empty($nameField)) {
$errors['saveMappingName'] = ts('Name is required to save Import Mapping');
}
else {
$mappingTypeId = CRM_Core_OptionGroup::getValue('mapping_type', 'Import Multi value custom data', 'name');
if (CRM_Core_BAO_Mapping::checkMapping($nameField, $mappingTypeId)) {
$errors['saveMappingName'] = ts('Duplicate ' . $self->_mappingType . 'Mapping Name');
}
}
}
//display Error if loaded mapping is not selected
if (array_key_exists('loadMapping', $fields)) {
$getMapName = CRM_Utils_Array::value('savedMapping', $fields);
if (empty($getMapName)) {
$errors['savedMapping'] = ts('Select saved mapping');
}
}
if (!empty($errors)) {
if (!empty($errors['saveMappingName'])) {
$_flag = 1;
$assignError = new CRM_Core_Page();
$assignError->assign('mappingDetailsError', $_flag);
}
return $errors;
}
return TRUE;
}
/**
* Process the mapped fields and map it into the uploaded file.
* preview the file and extract some summary statistics
*
* @return void
*/
public function postProcess() {
$params = $this->controller->exportValues('MapField');
$this->set('multipleCustomData', $this->_multipleCustomData);
//reload the mapfield if load mapping is pressed
if (!empty($params['savedMapping'])) {
$this->set('savedMapping', $params['savedMapping']);
$this->controller->resetPage($this->_name);
return;
}
$fileName = $this->controller->exportValue('DataSource', 'uploadFile');
$separator = $this->controller->exportValue('DataSource', 'fieldSeparator');
$skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
$this->_entity = $this->controller->exportValue('DataSource', 'entity');
$mapperKeys = array();
$mapper = array();
$mapperKeys = $this->controller->exportValue($this->_name, 'mapper');
$mapperKeysMain = array();
for ($i = 0; $i < $this->_columnCount; $i++) {
$mapper[$i] = $this->_mapperFields[$mapperKeys[$i][0]];
$mapperKeysMain[$i] = $mapperKeys[$i][0];
}
$this->set('mapper', $mapper);
// store mapping Id to display it in the preview page
$this->set('loadMappingId', CRM_Utils_Array::value('mappingId', $params));
//Updating Mapping Records
if (!empty($params['updateMapping'])) {
$mappingFields = new CRM_Core_DAO_MappingField();
$mappingFields->mapping_id = $params['mappingId'];
$mappingFields->find();
$mappingFieldsId = array();
while ($mappingFields->fetch()) {
if ($mappingFields->id) {
$mappingFieldsId[$mappingFields->column_number] = $mappingFields->id;
}
}
for ($i = 0; $i < $this->_columnCount; $i++) {
$updateMappingFields = new CRM_Core_DAO_MappingField();
$updateMappingFields->id = $mappingFieldsId[$i];
$updateMappingFields->mapping_id = $params['mappingId'];
$updateMappingFields->column_number = $i;
$explodedValues = explode('_', $mapperKeys[$i][0]);
$id = CRM_Utils_Array::value(0, $explodedValues);
$first = CRM_Utils_Array::value(1, $explodedValues);
$second = CRM_Utils_Array::value(2, $explodedValues);
$updateMappingFields->name = $mapper[$i];
$updateMappingFields->save();
}
}
//Saving Mapping Details and Records
if (!empty($params['saveMapping'])) {
$mappingParams = array(
'name' => $params['saveMappingName'],
'description' => $params['saveMappingDesc'],
'mapping_type_id' => CRM_Core_OptionGroup::getValue('mapping_type',
$this->_mappingType,
'name'
),
);
$saveMapping = CRM_Core_BAO_Mapping::add($mappingParams);
for ($i = 0; $i < $this->_columnCount; $i++) {
$saveMappingFields = new CRM_Core_DAO_MappingField();
$saveMappingFields->mapping_id = $saveMapping->id;
$saveMappingFields->column_number = $i;
$explodedValues = explode('_', $mapperKeys[$i][0]);
$id = CRM_Utils_Array::value(0, $explodedValues);
$first = CRM_Utils_Array::value(1, $explodedValues);
$second = CRM_Utils_Array::value(2, $explodedValues);
$saveMappingFields->name = $mapper[$i];
$saveMappingFields->save();
}
$this->set('savedMapping', $saveMappingFields->mapping_id);
}
$this->set('_entity', $this->_entity);
$parser = new $this->_parser($mapperKeysMain);
$parser->setEntity($this->_multipleCustomData);
$parser->run($fileName, $separator, $mapper, $skipColumnHeader,
CRM_Import_Parser::MODE_PREVIEW, $this->get('contactType')
);
// add all the necessary variables to the form
$parser->set($this);
}
}

View file

@ -0,0 +1,150 @@
<?php
/**
* Class CRM_Custom_Import_Form_Preview
*/
class CRM_Custom_Import_Form_Preview extends CRM_Import_Form_Preview {
public $_parser = 'CRM_Custom_Import_Parser_Api';
protected $_importParserUrl = '&parser=CRM_Custom_Import_Parser';
/**
* Set variables up before form is built.
*
* @return void
*/
public function preProcess() {
$skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
//get the data from the session
$dataValues = $this->get('dataValues');
$mapper = $this->get('mapper');
$invalidRowCount = $this->get('invalidRowCount');
$conflictRowCount = $this->get('conflictRowCount');
$mismatchCount = $this->get('unMatchCount');
$entity = $this->get('_entity');
//get the mapping name displayed if the mappingId is set
$mappingId = $this->get('loadMappingId');
if ($mappingId) {
$mapDAO = new CRM_Core_DAO_Mapping();
$mapDAO->id = $mappingId;
$mapDAO->find(TRUE);
$this->assign('loadedMapping', $mappingId);
$this->assign('savedName', $mapDAO->name);
}
if ($skipColumnHeader) {
$this->assign('skipColumnHeader', $skipColumnHeader);
$this->assign('rowDisplayCount', 3);
}
else {
$this->assign('rowDisplayCount', 2);
}
if ($invalidRowCount) {
$urlParams = 'type=' . CRM_Import_Parser::ERROR . $this->_importParserUrl;
$this->set('downloadErrorRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
if ($conflictRowCount) {
$urlParams = 'type=' . CRM_Import_Parser::CONFLICT . $this->_importParserUrl;
$this->set('downloadConflictRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
if ($mismatchCount) {
$urlParams = 'type=' . CRM_Import_Parser::NO_MATCH . $this->_importParserUrl;
$this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
$properties = array(
'mapper',
'dataValues',
'columnCount',
'totalRowCount',
'validRowCount',
'invalidRowCount',
'conflictRowCount',
'downloadErrorRecordsUrl',
'downloadConflictRecordsUrl',
'downloadMismatchRecordsUrl',
);
foreach ($properties as $property) {
$this->assign($property, $this->get($property));
}
}
/**
* Process the mapped fields and map it into the uploaded file.
* preview the file and extract some summary statistics
*
* @return void
*/
public function postProcess() {
$fileName = $this->controller->exportValue('DataSource', 'uploadFile');
$separator = $this->controller->exportValue('DataSource', 'fieldSeparator');
$skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
$invalidRowCount = $this->get('invalidRowCount');
$conflictRowCount = $this->get('conflictRowCount');
$onDuplicate = $this->get('onDuplicate');
$entity = $this->get('_entity');
$mapper = $this->controller->exportValue('MapField', 'mapper');
$mapperKeys = array();
foreach ($mapper as $key => $value) {
$mapperKeys[$key] = $mapper[$key][0];
}
$parser = new $this->_parser($mapperKeys);
$parser->setEntity($entity);
$mapFields = $this->get('fields');
foreach ($mapper as $key => $value) {
$header = array();
if (isset($mapFields[$mapper[$key][0]])) {
$header[] = $mapFields[$mapper[$key][0]];
}
$mapperFields[] = implode(' - ', $header);
}
$parser->run($fileName, $separator,
$mapperFields,
$skipColumnHeader,
CRM_Import_Parser::MODE_IMPORT,
$this->get('contactType'),
$onDuplicate
);
// add all the necessary variables to the form
$parser->set($this, CRM_Import_Parser::MODE_IMPORT);
// check if there is any error occurred
$errorStack = CRM_Core_Error::singleton();
$errors = $errorStack->getErrors();
$errorMessage = array();
if (is_array($errors)) {
foreach ($errors as $key => $value) {
$errorMessage[] = $value['message'];
}
$errorFile = $fileName['name'] . '.error.log';
if ($fd = fopen($errorFile, 'w')) {
fwrite($fd, implode('\n', $errorMessage));
}
fclose($fd);
$this->set('errorFile', $errorFile);
$urlParams = 'type=' . CRM_Import_Parser::ERROR . $this->_importParserUrl;
$this->set('downloadErrorRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
$urlParams = 'type=' . CRM_Import_Parser::CONFLICT . $this->_importParserUrl;
$this->set('downloadConflictRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
$urlParams = 'type=' . CRM_Import_Parser::NO_MATCH . $this->_importParserUrl;
$this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
}
}

View file

@ -0,0 +1,18 @@
<?php
/**
* Class CRM_Custom_Import_Form_Summary
*/
class CRM_Custom_Import_Form_Summary extends CRM_Contact_Import_Form_Summary {
/**
* Set variables up before form is built.
*
* @return void
*/
public function preProcess() {
parent::preProcess();
$session = CRM_Core_Session::singleton();
$session->pushUserContext(CRM_Utils_System::url('civicrm/import/custom', 'reset=1'));
}
}

View file

@ -0,0 +1,385 @@
<?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$
*
*/
abstract class CRM_Custom_Import_Parser extends CRM_Contact_Import_Parser {
protected $_fileName;
/**#@+
* @var integer
*/
/**
* Imported file size
*/
protected $_fileSize;
/**
* Separator being used
*/
protected $_separator;
/**
* Total number of lines in file
*/
protected $_lineCount;
/**
* Whether the file has a column header or not
*
* @var boolean
*/
protected $_haveColumnHeader;
/**
* @param string $fileName
* @param string $separator
* @param int $mapper
* @param bool $skipColumnHeader
* @param int|string $mode
* @param int|string $contactType
* @param int $onDuplicate
*
* @return mixed
* @throws Exception
*/
public function run(
$fileName,
$separator = ',',
&$mapper,
$skipColumnHeader = FALSE,
$mode = self::MODE_PREVIEW,
$contactType = self::CONTACT_INDIVIDUAL,
$onDuplicate = self::DUPLICATE_SKIP
) {
if (!is_array($fileName)) {
CRM_Core_Error::fatal();
}
$fileName = $fileName['name'];
switch ($contactType) {
case CRM_Import_Parser::CONTACT_INDIVIDUAL:
$this->_contactType = 'Individual';
break;
case CRM_Import_Parser::CONTACT_HOUSEHOLD:
$this->_contactType = 'Household';
break;
case CRM_Import_Parser::CONTACT_ORGANIZATION:
$this->_contactType = 'Organization';
}
$this->init();
$this->_haveColumnHeader = $skipColumnHeader;
$this->_separator = $separator;
$fd = fopen($fileName, "r");
if (!$fd) {
return FALSE;
}
$this->_lineCount = $this->_warningCount = 0;
$this->_invalidRowCount = $this->_validCount = 0;
$this->_totalCount = $this->_conflictCount = 0;
$this->_errors = array();
$this->_warnings = array();
$this->_conflicts = array();
$this->_fileSize = number_format(filesize($fileName) / 1024.0, 2);
if ($mode == self::MODE_MAPFIELD) {
$this->_rows = array();
}
else {
$this->_activeFieldCount = count($this->_activeFields);
}
while (!feof($fd)) {
$this->_lineCount++;
$values = fgetcsv($fd, 8192, $separator);
if (!$values) {
continue;
}
self::encloseScrub($values);
// skip column header if we're not in mapfield mode
if ($mode != self::MODE_MAPFIELD && $skipColumnHeader) {
$skipColumnHeader = FALSE;
continue;
}
/* trim whitespace around the values */
$empty = TRUE;
foreach ($values as $k => $v) {
$values[$k] = trim($v, " \t\r\n");
}
if (CRM_Utils_System::isNull($values)) {
continue;
}
$this->_totalCount++;
if ($mode == self::MODE_MAPFIELD) {
$returnCode = $this->mapField($values);
}
elseif ($mode == self::MODE_PREVIEW) {
$returnCode = $this->preview($values);
}
elseif ($mode == self::MODE_SUMMARY) {
$returnCode = $this->summary($values);
}
elseif ($mode == self::MODE_IMPORT) {
$returnCode = $this->import($onDuplicate, $values);
}
else {
$returnCode = self::ERROR;
}
// note that a line could be valid but still produce a warning
if ($returnCode & self::VALID) {
$this->_validCount++;
if ($mode == self::MODE_MAPFIELD) {
$this->_rows[] = $values;
$this->_activeFieldCount = max($this->_activeFieldCount, count($values));
}
}
if ($returnCode & self::WARNING) {
$this->_warningCount++;
if ($this->_warningCount < $this->_maxWarningCount) {
$this->_warningCount[] = $line;
}
}
if ($returnCode & self::ERROR) {
$this->_invalidRowCount++;
if ($this->_invalidRowCount < $this->_maxErrorCount) {
$recordNumber = $this->_lineCount;
if ($this->_haveColumnHeader) {
$recordNumber--;
}
array_unshift($values, $recordNumber);
$this->_errors[] = $values;
}
}
if ($returnCode & self::CONFLICT) {
$this->_conflictCount++;
$recordNumber = $this->_lineCount;
if ($this->_haveColumnHeader) {
$recordNumber--;
}
array_unshift($values, $recordNumber);
$this->_conflicts[] = $values;
}
if ($returnCode & self::DUPLICATE) {
if ($returnCode & self::MULTIPLE_DUPE) {
/* TODO: multi-dupes should be counted apart from singles
* on non-skip action */
}
$this->_duplicateCount++;
$recordNumber = $this->_lineCount;
if ($this->_haveColumnHeader) {
$recordNumber--;
}
array_unshift($values, $recordNumber);
$this->_duplicates[] = $values;
if ($onDuplicate != self::DUPLICATE_SKIP) {
$this->_validCount++;
}
}
// we give the derived class a way of aborting the process
// note that the return code could be multiple code or'ed together
if ($returnCode & self::STOP) {
break;
}
// if we are done processing the maxNumber of lines, break
if ($this->_maxLinesToProcess > 0 && $this->_validCount >= $this->_maxLinesToProcess) {
break;
}
}
fclose($fd);
if ($mode == self::MODE_PREVIEW || $mode == self::MODE_IMPORT) {
$customHeaders = $mapper;
$customfields = CRM_Core_BAO_CustomField::getFields('Activity');
foreach ($customHeaders as $key => $value) {
if ($id = CRM_Core_BAO_CustomField::getKeyID($value)) {
$customHeaders[$key] = $customfields[$id][0];
}
}
if ($this->_invalidRowCount) {
// removed view url for invlaid contacts
$headers = array_merge(array(
ts('Line Number'),
ts('Reason'),
),
$customHeaders
);
$this->_errorFileName = self::errorFileName(self::ERROR);
self::exportCSV($this->_errorFileName, $headers, $this->_errors);
}
if ($this->_conflictCount) {
$headers = array_merge(array(
ts('Line Number'),
ts('Reason'),
),
$customHeaders
);
$this->_conflictFileName = self::errorFileName(self::CONFLICT);
self::exportCSV($this->_conflictFileName, $headers, $this->_conflicts);
}
if ($this->_duplicateCount) {
$headers = array_merge(array(
ts('Line Number'),
ts('View Activity History URL'),
),
$customHeaders
);
$this->_duplicateFileName = self::errorFileName(self::DUPLICATE);
self::exportCSV($this->_duplicateFileName, $headers, $this->_duplicates);
}
}
return $this->fini();
}
/**
* Given a list of the importable field keys that the user has selected
* set the active fields array to this list
*
* @param array $fieldKeys mapped array of values
*
* @return void
*/
public function setActiveFields($fieldKeys) {
$this->_activeFieldCount = count($fieldKeys);
foreach ($fieldKeys as $key) {
if (empty($this->_fields[$key])) {
$this->_activeFields[] = new CRM_Custom_Import_Field('', ts('- do not import -'));
}
else {
$this->_activeFields[] = clone($this->_fields[$key]);
}
}
}
/**
* Format the field values for input to the api.
*
* @return array
* (reference ) associative array of name/value pairs
*/
public function &getActiveFieldParams() {
$params = array();
for ($i = 0; $i < $this->_activeFieldCount; $i++) {
if (isset($this->_activeFields[$i]->_value)
&& !isset($params[$this->_activeFields[$i]->_name])
&& !isset($this->_activeFields[$i]->_related)
) {
$params[$this->_activeFields[$i]->_name] = $this->_activeFields[$i]->_value;
}
}
return $params;
}
/**
* Store parser values.
*
* @param CRM_Core_Session $store
*
* @param int $mode
*
* @return void
*/
public function set($store, $mode = self::MODE_SUMMARY) {
$store->set('fileSize', $this->_fileSize);
$store->set('lineCount', $this->_lineCount);
$store->set('seperator', $this->_separator);
$store->set('fields', $this->getSelectValues());
$store->set('fieldTypes', $this->getSelectTypes());
$store->set('headerPatterns', $this->getHeaderPatterns());
$store->set('dataPatterns', $this->getDataPatterns());
$store->set('columnCount', $this->_activeFieldCount);
$store->set('_entity', $this->_entity);
$store->set('totalRowCount', $this->_totalCount);
$store->set('validRowCount', $this->_validCount);
$store->set('invalidRowCount', $this->_invalidRowCount);
$store->set('conflictRowCount', $this->_conflictCount);
switch ($this->_contactType) {
case 'Individual':
$store->set('contactType', CRM_Import_Parser::CONTACT_INDIVIDUAL);
break;
case 'Household':
$store->set('contactType', CRM_Import_Parser::CONTACT_HOUSEHOLD);
break;
case 'Organization':
$store->set('contactType', CRM_Import_Parser::CONTACT_ORGANIZATION);
}
if ($this->_invalidRowCount) {
$store->set('errorsFileName', $this->_errorFileName);
}
if ($this->_conflictCount) {
$store->set('conflictsFileName', $this->_conflictFileName);
}
if (isset($this->_rows) && !empty($this->_rows)) {
$store->set('dataValues', $this->_rows);
}
if ($mode == self::MODE_IMPORT) {
$store->set('duplicateRowCount', $this->_duplicateCount);
if ($this->_duplicateCount) {
$store->set('duplicatesFileName', $this->_duplicateFileName);
}
}
}
}

View file

@ -0,0 +1,272 @@
<?php
/**
* Class CRM_Custom_Import_Parser_Api
*/
class CRM_Custom_Import_Parser_Api extends CRM_Custom_Import_Parser {
protected $_entity = '';
protected $_fields = array();
protected $_requiredFields = array();
protected $_dateFields = array();
protected $_multipleCustomData = '';
/**
* Params for the current entity being prepared for the api.
* @var array
*/
protected $_params = array();
/**
* Class constructor.
*
* @param array $mapperKeys
* @param null $mapperLocType
* @param null $mapperPhoneType
*/
public function __construct(&$mapperKeys, $mapperLocType = NULL, $mapperPhoneType = NULL) {
parent::__construct();
$this->_mapperKeys = &$mapperKeys;
}
public function setFields() {
$customGroupID = $this->_multipleCustomData;
$importableFields = $this->getGroupFieldsForImport($customGroupID, $this);
$this->_fields = array_merge(array(
'do_not_import' => array('title' => ts('- do not import -')),
'contact_id' => array('title' => ts('Contact ID')),
'external_identifier' => array('title' => ts('External Identifier')),
), $importableFields);
}
/**
* The initializer code, called before the processing
*
* @return void
*/
public function init() {
$this->setFields();
$fields = $this->_fields;
$hasLocationType = FALSE;
foreach ($fields as $name => $field) {
$field['type'] = CRM_Utils_Array::value('type', $field, CRM_Utils_Type::T_INT);
$field['dataPattern'] = CRM_Utils_Array::value('dataPattern', $field, '//');
$field['headerPattern'] = CRM_Utils_Array::value('headerPattern', $field, '//');
$this->addField($name, $field['title'], $field['type'], $field['headerPattern'], $field['dataPattern'], $hasLocationType);
}
$this->setActiveFields($this->_mapperKeys);
}
/**
* Handle the values in mapField mode.
*
* @param array $values
* The array of values belonging to this line.
*
* @return bool
*/
public function mapField(&$values) {
return CRM_Import_Parser::VALID;
}
/**
* Handle the values in preview mode.
*
* @param array $values
* The array of values belonging to this line.
*
* @return bool
* the result of this processing
*/
public function preview(&$values) {
return $this->summary($values);
}
/**
* @param array $values
* The array of values belonging to this line.
*
* @return bool
* the result of this processing
* It is called from both the preview & the import actions
*
* @see CRM_Custom_Import_Parser_BaseClass::summary()
*/
public function summary(&$values) {
$erroneousField = NULL;
$response = $this->setActiveFieldValues($values, $erroneousField);
$errorRequired = FALSE;
$missingField = '';
$this->_params = &$this->getActiveFieldParams();
$formatted = $this->_params;
$this->_updateWithId = FALSE;
$this->_parseStreetAddress = CRM_Utils_Array::value('street_address_parsing', CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'address_options'), FALSE);
$this->_params = $this->getActiveFieldParams();
foreach ($this->_requiredFields as $requiredField) {
if (empty($this->_params[$requiredField])) {
$errorRequired = TRUE;
$missingField .= ' ' . $requiredField;
CRM_Contact_Import_Parser_Contact::addToErrorMsg($this->_entity, $requiredField);
}
}
if ($errorRequired) {
array_unshift($values, ts('Missing required field(s) :') . $missingField);
return CRM_Import_Parser::ERROR;
}
$errorMessage = NULL;
$contactType = $this->_contactType ? $this->_contactType : 'Organization';
CRM_Contact_Import_Parser_Contact::isErrorInCustomData($this->_params + array('contact_type' => $contactType), $errorMessage, $this->_contactSubType, NULL);
// pseudoconstants
if ($errorMessage) {
$tempMsg = "Invalid value for field(s) : $errorMessage";
array_unshift($values, $tempMsg);
$errorMessage = NULL;
return CRM_Import_Parser::ERROR;
}
return CRM_Import_Parser::VALID;
}
/**
* Handle the values in import mode.
*
* @param int $onDuplicate
* The code for what action to take on duplicates.
* @param array $values
* The array of values belonging to this line.
*
* @return bool
* the result of this processing
*/
public function import($onDuplicate, &$values) {
$response = $this->summary($values);
if ($response != CRM_Import_Parser::VALID) {
$importRecordParams = array(
$statusFieldName => 'INVALID',
"${statusFieldName}Msg" => "Invalid (Error Code: $response)",
);
return $response;
}
$this->_updateWithId = FALSE;
$this->_parseStreetAddress = CRM_Utils_Array::value('street_address_parsing', CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'address_options'), FALSE);
$params = $this->getActiveFieldParams();
$contactType = $this->_contactType ? $this->_contactType : 'Organization';
$formatted = array(
'contact_type' => $contactType,
);
$session = CRM_Core_Session::singleton();
$dateType = $session->get('dateTypes');
if (isset($this->_params['external_identifier']) && !isset($this->_params['contact_id'])) {
$checkCid = new CRM_Contact_DAO_Contact();
$checkCid->external_identifier = $this->_params['external_identifier'];
$checkCid->find(TRUE);
$formatted['id'] = $checkCid->id;
}
else {
$formatted['id'] = $this->_params['contact_id'];
}
$setDateFields = array_intersect_key($this->_params, array_flip($this->_dateFields));
$this->formatCommonData($this->_params, $formatted, $formatted);
foreach ($formatted['custom'] as $key => $val) {
$this->_params['custom_' . $key] = $val[-1]['value'];
}
$this->_params['skipRecentView'] = TRUE;
$this->_params['check_permissions'] = TRUE;
$this->_params['entity_id'] = $formatted['id'];
try {
civicrm_api3('custom_value', 'create', $this->_params);
}
catch (CiviCRM_API3_Exception $e) {
$error = $e->getMessage();
array_unshift($values, $error);
return CRM_Import_Parser::ERROR;
}
}
/**
* Format Date params.
*
* Although the api will accept any strtotime valid string CiviCRM accepts at least one date format
* not supported by strtotime so we should run this through a conversion
*/
public function formatDateParams() {
$session = CRM_Core_Session::singleton();
$dateType = $session->get('dateTypes');
$setDateFields = array_intersect_key($this->_params, array_flip($this->_dateFields));
foreach ($setDateFields as $key => $value) {
CRM_Utils_Date::convertToDefaultDate($this->_params, $dateType, $key);
$this->_params[$key] = CRM_Utils_Date::processDate($this->_params[$key]);
}
}
/**
* Set import entity.
* @param string $entity
*/
public function setEntity($entity) {
$this->_entity = $entity;
$this->_multipleCustomData = $entity;
}
/**
* The initializer code, called before the processing
*
* @return void
*/
public function fini() {
}
/**
* Return the field ids and names (with groups) for import purpose.
*
* @param int $id
* Custom group ID.
*
* @return array
*
*/
public function getGroupFieldsForImport($id) {
$importableFields = array();
$params = array('custom_group_id' => $id);
$allFields = civicrm_api3('custom_field', 'get', $params);
$fields = $allFields['values'];
foreach ($fields as $id => $values) {
$datatype = CRM_Utils_Array::value('data_type', $values);
if ($datatype == 'File') {
continue;
}
/* generate the key for the fields array */
$key = "custom_$id";
$regexp = preg_replace('/[.,;:!?]/', '', CRM_Utils_Array::value(0, $values));
$importableFields[$key] = array(
'name' => $key,
'title' => CRM_Utils_Array::value('label', $values),
'headerPattern' => '/' . preg_quote($regexp, '/') . '/',
'import' => 1,
'custom_field_id' => $id,
'options_per_line' => CRM_Utils_Array::value('options_per_line', $values),
'data_type' => CRM_Utils_Array::value('data_type', $values),
'html_type' => CRM_Utils_Array::value('html_type', $values),
'is_search_range' => CRM_Utils_Array::value('is_search_range', $values),
);
if (CRM_Utils_Array::value('html_type', $values) == 'Select Date') {
$importableFields[$key]['date_format'] = CRM_Utils_Array::value('date_format', $values);
$importableFields[$key]['time_format'] = CRM_Utils_Array::value('time_format', $values);
$this->_dateFields[] = $key;
}
}
return $importableFields;
}
}

View file

@ -0,0 +1,164 @@
<?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 the functions that are called using AJAX (jQuery)
*/
class CRM_Custom_Page_AJAX {
/**
* This function uses the deprecated v1 datatable api and needs updating. See CRM-16353.
* @deprecated
*/
public static function getOptionList() {
$params = $_REQUEST;
$sEcho = CRM_Utils_Type::escape($_REQUEST['sEcho'], 'Integer');
$offset = isset($_REQUEST['iDisplayStart']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayStart'], 'Integer') : 0;
$rowCount = isset($_REQUEST['iDisplayLength']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayLength'], 'Integer') : 25;
$params['page'] = ($offset / $rowCount) + 1;
$params['rp'] = $rowCount;
$options = CRM_Core_BAO_CustomOption::getOptionListSelector($params);
$iFilteredTotal = $iTotal = $params['total'];
$selectorElements = array(
'label',
'value',
'is_default',
'is_active',
'links',
'class',
);
CRM_Utils_System::setHttpHeader('Content-Type', 'application/json');
echo CRM_Utils_JSON::encodeDataTableSelector($options, $sEcho, $iTotal, $iFilteredTotal, $selectorElements);
CRM_Utils_System::civiExit();
}
/**
* Fix Ordering of options
*
*/
public static function fixOrdering() {
$params = $_REQUEST;
$queryParams = array(
1 => array($params['start'], 'Integer'),
2 => array($params['end'], 'Integer'),
3 => array($params['gid'], 'Integer'),
);
$dao = "SELECT id FROM civicrm_option_value WHERE weight = %1 AND option_group_id = %3";
$startid = CRM_Core_DAO::singleValueQuery($dao, $queryParams);
$dao2 = "SELECT id FROM civicrm_option_value WHERE weight = %2 AND option_group_id = %3";
$endid = CRM_Core_DAO::singleValueQuery($dao2, $queryParams);
$query = "UPDATE civicrm_option_value SET weight = %2 WHERE id = $startid";
CRM_Core_DAO::executeQuery($query, $queryParams);
// increment or decrement the rest by one
if ($params['start'] < $params['end']) {
$updateRows = "UPDATE civicrm_option_value
SET weight = weight - 1
WHERE weight > %1 AND weight < %2 AND option_group_id = %3
OR id = $endid";
}
else {
$updateRows = "UPDATE civicrm_option_value
SET weight = weight + 1
WHERE weight < %1 AND weight > %2 AND option_group_id = %3
OR id = $endid";
}
CRM_Core_DAO::executeQuery($updateRows, $queryParams);
CRM_Utils_JSON::output(TRUE);
}
/**
* Get list of Multi Record Fields.
*
*/
public static function getMultiRecordFieldList() {
$params = CRM_Core_Page_AJAX::defaultSortAndPagerParams(0, 10);
$params['cid'] = CRM_Utils_Type::escape($_GET['cid'], 'Integer');
$params['cgid'] = CRM_Utils_Type::escape($_GET['cgid'], 'Integer');
$contactType = CRM_Contact_BAO_Contact::getContactType($params['cid']);
$obj = new CRM_Profile_Page_MultipleRecordFieldsListing();
$obj->_pageViewType = 'customDataView';
$obj->_contactId = $params['cid'];
$obj->_customGroupId = $params['cgid'];
$obj->_contactType = $contactType;
$obj->_DTparams['offset'] = ($params['page'] - 1) * $params['rp'];
$obj->_DTparams['rowCount'] = $params['rp'];
if (!empty($params['sortBy'])) {
$obj->_DTparams['sort'] = $params['sortBy'];
}
list($fields, $attributes) = $obj->browse();
// format params and add class attributes
$fieldList = array();
foreach ($fields as $id => $value) {
$field = array();
foreach ($value as $fieldId => &$fieldName) {
if (!empty($attributes[$fieldId][$id]['class'])) {
$fieldName = array('data' => $fieldName, 'cellClass' => $attributes[$fieldId][$id]['class']);
}
if (is_numeric($fieldId)) {
$fName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $fieldId, 'column_name');
CRM_Utils_Array::crmReplaceKey($value, $fieldId, $fName);
}
}
$field = $value;
array_push($fieldList, $field);
}
$totalRecords = !empty($obj->_total) ? $obj->_total : 0;
$multiRecordFields = array();
$multiRecordFields['data'] = $fieldList;
$multiRecordFields['recordsTotal'] = $totalRecords;
$multiRecordFields['recordsFiltered'] = $totalRecords;
if (!empty($_GET['is_unit_test'])) {
return $multiRecordFields;
}
CRM_Utils_JSON::output($multiRecordFields);
}
}

View file

@ -0,0 +1,316 @@
<?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$
*
*/
/**
* Create a page for displaying Custom Fields.
*
* Heart of this class is the run method which checks
* for action type and then displays the appropriate
* page.
*
*/
class CRM_Custom_Page_Field extends CRM_Core_Page {
public $useLivePageJS = TRUE;
/**
* The group id of the field.
*
* @var int
*/
protected $_gid;
/**
* The action links that we need to display for the browse screen.
*
* @var array
*/
private static $_actionLinks;
/**
* Get the action links for this page.
*
* @return array
* array of action links that we need to display for the browse screen
*/
public static function &actionLinks() {
if (!isset(self::$_actionLinks)) {
self::$_actionLinks = array(
CRM_Core_Action::UPDATE => array(
'name' => ts('Edit Field'),
'url' => 'civicrm/admin/custom/group/field/update',
'qs' => 'action=update&reset=1&gid=%%gid%%&id=%%id%%',
'title' => ts('Edit Custom Field'),
),
CRM_Core_Action::BROWSE => array(
'name' => ts('Edit Multiple Choice Options'),
'url' => 'civicrm/admin/custom/group/field/option',
'qs' => 'reset=1&action=browse&gid=%%gid%%&fid=%%id%%',
'title' => ts('List Custom Options'),
),
CRM_Core_Action::PREVIEW => array(
'name' => ts('Preview Field Display'),
'url' => 'civicrm/admin/custom/group/field',
'qs' => 'action=preview&reset=1&gid=%%gid%%&id=%%id%%',
'title' => ts('Preview Custom Field'),
),
CRM_Core_Action::DISABLE => array(
'name' => ts('Disable'),
'ref' => 'crm-enable-disable',
'title' => ts('Disable Custom Field'),
),
CRM_Core_Action::ENABLE => array(
'name' => ts('Enable'),
'ref' => 'crm-enable-disable',
'title' => ts('Enable Custom Field'),
),
CRM_Core_Action::EXPORT => array(
'name' => ts('Move'),
'url' => 'civicrm/admin/custom/group/field/move',
'class' => 'small-popup',
'qs' => 'reset=1&fid=%%id%%',
'title' => ts('Move Custom Field'),
),
CRM_Core_Action::DELETE => array(
'name' => ts('Delete'),
'url' => 'civicrm/admin/custom/group/field',
'qs' => 'action=delete&reset=1&gid=%%gid%%&id=%%id%%',
'title' => ts('Delete Custom Field'),
),
);
}
return self::$_actionLinks;
}
/**
* Browse all custom group fields.
*
* @return void
*/
public function browse() {
$resourceManager = CRM_Core_Resources::singleton();
if (!empty($_GET['new']) && $resourceManager->ajaxPopupsEnabled) {
$resourceManager->addScriptFile('civicrm', 'js/crm.addNew.js', 999, 'html-header');
}
$customField = array();
$customFieldBAO = new CRM_Core_BAO_CustomField();
// fkey is gid
$customFieldBAO->custom_group_id = $this->_gid;
$customFieldBAO->orderBy('weight, label');
$customFieldBAO->find();
while ($customFieldBAO->fetch()) {
$customField[$customFieldBAO->id] = array();
CRM_Core_DAO::storeValues($customFieldBAO, $customField[$customFieldBAO->id]);
$action = array_sum(array_keys(self::actionLinks()));
if ($customFieldBAO->is_active) {
$action -= CRM_Core_Action::ENABLE;
}
else {
$action -= CRM_Core_Action::DISABLE;
}
switch ($customFieldBAO->data_type) {
case "String":
case "Int":
case "Float":
case "Money":
// if Multi Select field is selected in custom field
if ($customFieldBAO->html_type == 'Text') {
$action -= CRM_Core_Action::BROWSE;
}
break;
case "ContactReference":
case "Memo":
case "Date":
case "Boolean":
case "StateProvince":
case "Country":
case "File":
case "Link":
$action -= CRM_Core_Action::BROWSE;
break;
}
$customFieldDataType = CRM_Core_BAO_CustomField::dataType();
$customField[$customFieldBAO->id]['data_type'] = $customFieldDataType[$customField[$customFieldBAO->id]['data_type']];
$customField[$customFieldBAO->id]['order'] = $customField[$customFieldBAO->id]['weight'];
$customField[$customFieldBAO->id]['action'] = CRM_Core_Action::formLink(self::actionLinks(), $action,
array(
'id' => $customFieldBAO->id,
'gid' => $this->_gid,
),
ts('more'),
FALSE,
'customField.row.actions',
'CustomField',
$customFieldBAO->id
);
}
$returnURL = CRM_Utils_System::url('civicrm/admin/custom/group/field', "reset=1&action=browse&gid={$this->_gid}");
$filter = "custom_group_id = {$this->_gid}";
CRM_Utils_Weight::addOrder($customField, 'CRM_Core_DAO_CustomField',
'id', $returnURL, $filter
);
$this->assign('customField', $customField);
}
/**
* Edit custom data.
*
* editing would involved modifying existing fields + adding data to new fields.
*
* @param string $action
* The action to be invoked.
*
* @return void
*/
public function edit($action) {
// create a simple controller for editing custom dataCRM/Custom/Page/Field.php
$controller = new CRM_Core_Controller_Simple('CRM_Custom_Form_Field', ts('Custom Field'), $action);
// set the userContext stack
$session = CRM_Core_Session::singleton();
$session->pushUserContext(CRM_Utils_System::url('civicrm/admin/custom/group/field', 'reset=1&action=browse&gid=' . $this->_gid));
$controller->set('gid', $this->_gid);
$controller->setEmbedded(TRUE);
$controller->process();
$controller->run();
}
/**
* Run the page.
*
* This method is called after the page is created. It checks for the
* type of action and executes that action.
*
* @return void
*/
public function run() {
$id = CRM_Utils_Request::retrieve('id', 'Positive',
$this, FALSE, 0
);
if ($id) {
$values = civicrm_api3('custom_field', 'getsingle', array('id' => $id));
$this->_gid = $values['custom_group_id'];
}
// get the group id
else {
$this->_gid = CRM_Utils_Request::retrieve('gid', 'Positive',
$this
);
}
if ($isReserved = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_gid, 'is_reserved', 'id')) {
CRM_Core_Error::fatal("You cannot add or edit fields in a reserved custom field-set.");
}
$action = CRM_Utils_Request::retrieve('action', 'String',
// default to 'browse'
$this, FALSE, 'browse'
);
if ($action & CRM_Core_Action::DELETE) {
$session = CRM_Core_Session::singleton();
$session->pushUserContext(CRM_Utils_System::url('civicrm/admin/custom/group/field', 'reset=1&action=browse&gid=' . $this->_gid));
$controller = new CRM_Core_Controller_Simple('CRM_Custom_Form_DeleteField', "Delete Custom Field", '');
$id = CRM_Utils_Request::retrieve('id', 'Positive',
$this, FALSE, 0
);
$controller->set('id', $id);
$controller->setEmbedded(TRUE);
$controller->process();
$controller->run();
$fieldValues = array('custom_group_id' => $this->_gid);
$wt = CRM_Utils_Weight::delWeight('CRM_Core_DAO_CustomField', $id, $fieldValues);
}
if ($this->_gid) {
$groupTitle = CRM_Core_BAO_CustomGroup::getTitle($this->_gid);
$this->assign('gid', $this->_gid);
$this->assign('groupTitle', $groupTitle);
if ($action & CRM_Core_Action::BROWSE) {
CRM_Utils_System::setTitle(ts('%1 - Custom Fields', array(1 => $groupTitle)));
}
}
// assign vars to templates
$this->assign('action', $action);
// what action to take ?
if ($action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD)) {
// no browse for edit/update/view
$this->edit($action);
}
elseif ($action & CRM_Core_Action::PREVIEW) {
$this->preview($id);
}
else {
$this->browse();
}
// Call the parents run method
return parent::run();
}
/**
* Preview custom field.
*
* @param int $id
* Custom field id.
*
* @return void
*/
public function preview($id) {
$controller = new CRM_Core_Controller_Simple('CRM_Custom_Form_Preview', ts('Preview Custom Data'), CRM_Core_Action::PREVIEW);
$session = CRM_Core_Session::singleton();
$session->pushUserContext(CRM_Utils_System::url('civicrm/admin/custom/group/field', 'reset=1&action=browse&gid=' . $this->_gid));
$controller->set('fieldId', $id);
$controller->set('groupId', $this->_gid);
$controller->setEmbedded(TRUE);
$controller->process();
$controller->run();
}
}

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
* $Id$
*
*/
/**
* Create a page for displaying Custom Sets.
*
* Heart of this class is the run method which checks
* for action type and then displays the appropriate
* page.
*
*/
class CRM_Custom_Page_Group extends CRM_Core_Page {
/**
* The action links that we need to display for the browse screen
*
* @var array
*/
private static $_actionLinks;
/**
* Get the action links for this page.
*
*
* @return array
* array of action links that we need to display for the browse screen
*/
public static function &actionLinks() {
// check if variable _actionsLinks is populated
if (!isset(self::$_actionLinks)) {
self::$_actionLinks = array(
CRM_Core_Action::BROWSE => array(
'name' => ts('View and Edit Custom Fields'),
'url' => 'civicrm/admin/custom/group/field',
'qs' => 'reset=1&action=browse&gid=%%id%%',
'title' => ts('View and Edit Custom Fields'),
),
CRM_Core_Action::PREVIEW => array(
'name' => ts('Preview'),
'url' => 'civicrm/admin/custom/group',
'qs' => 'action=preview&reset=1&id=%%id%%',
'title' => ts('Preview Custom Data Set'),
),
CRM_Core_Action::UPDATE => array(
'name' => ts('Settings'),
'url' => 'civicrm/admin/custom/group',
'qs' => 'action=update&reset=1&id=%%id%%',
'title' => ts('Edit Custom Set'),
),
CRM_Core_Action::DISABLE => array(
'name' => ts('Disable'),
'ref' => 'crm-enable-disable',
'title' => ts('Disable Custom Set'),
),
CRM_Core_Action::ENABLE => array(
'name' => ts('Enable'),
'ref' => 'crm-enable-disable',
'title' => ts('Enable Custom Set'),
),
CRM_Core_Action::DELETE => array(
'name' => ts('Delete'),
'url' => 'civicrm/admin/custom/group',
'qs' => 'action=delete&reset=1&id=%%id%%',
'title' => ts('Delete Custom Set'),
),
);
}
return self::$_actionLinks;
}
/**
* Run the page.
*
* This method is called after the page is created. It checks for the
* type of action and executes that action.
* Finally it calls the parent's run method.
*
* @return void
*/
public function run() {
// get the requested action
$action = CRM_Utils_Request::retrieve('action', 'String',
// default to 'browse'
$this, FALSE, 'browse'
);
if ($action & CRM_Core_Action::DELETE) {
$session = CRM_Core_Session::singleton();
$session->pushUserContext(CRM_Utils_System::url('civicrm/admin/custom/group/', 'action=browse'));
$controller = new CRM_Core_Controller_Simple('CRM_Custom_Form_DeleteGroup', "Delete Cutom Set", NULL);
$id = CRM_Utils_Request::retrieve('id', 'Positive',
$this, FALSE, 0
);
$controller->set('id', $id);
$controller->setEmbedded(TRUE);
$controller->process();
$controller->run();
}
// assign vars to templates
$this->assign('action', $action);
$id = CRM_Utils_Request::retrieve('id', 'Positive',
$this, FALSE, 0
);
// what action to take ?
if ($action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD)) {
$this->edit($id, $action);
}
elseif ($action & CRM_Core_Action::PREVIEW) {
$this->preview($id);
}
else {
// finally browse the custom groups
$this->browse();
}
// parent run
return parent::run();
}
/**
* Edit custom group.
*
* @param int $id
* Custom group id.
* @param string $action
* The action to be invoked.
*
* @return void
*/
public function edit($id, $action) {
// create a simple controller for editing custom data
$controller = new CRM_Core_Controller_Simple('CRM_Custom_Form_Group', ts('Custom Set'), $action);
// set the userContext stack
$session = CRM_Core_Session::singleton();
$session->pushUserContext(CRM_Utils_System::url('civicrm/admin/custom/group/', 'action=browse'));
$controller->set('id', $id);
$controller->setEmbedded(TRUE);
$controller->process();
$controller->run();
}
/**
* Preview custom group.
*
* @param int $id
* Custom group id.
*
* @return void
*/
public function preview($id) {
$controller = new CRM_Core_Controller_Simple('CRM_Custom_Form_Preview', ts('Preview Custom Data'), NULL);
$session = CRM_Core_Session::singleton();
$session->pushUserContext(CRM_Utils_System::url('civicrm/admin/custom/group', 'action=browse'));
$controller->set('groupId', $id);
$controller->setEmbedded(TRUE);
$controller->process();
$controller->run();
}
/**
* Browse all custom data groups.
*
* @param string $action
* The action to be invoked.
*
* @return void
*/
public function browse($action = NULL) {
// get all custom groups sorted by weight
$customGroup = array();
$dao = new CRM_Core_DAO_CustomGroup();
$dao->is_reserved = FALSE;
$dao->orderBy('weight, title');
$dao->find();
$customGroupExtends = CRM_Core_SelectValues::customGroupExtends();
$customGroupStyle = CRM_Core_SelectValues::customGroupStyle();
while ($dao->fetch()) {
$id = $dao->id;
$customGroup[$id] = array();
CRM_Core_DAO::storeValues($dao, $customGroup[$id]);
// form all action links
$action = array_sum(array_keys(self::actionLinks()));
// update enable/disable links depending on custom_group properties.
if ($dao->is_active) {
$action -= CRM_Core_Action::ENABLE;
}
else {
$action -= CRM_Core_Action::DISABLE;
}
$customGroup[$id]['order'] = $customGroup[$id]['weight'];
$customGroup[$id]['action'] = CRM_Core_Action::formLink(self::actionLinks(), $action,
array('id' => $id),
ts('more'),
FALSE,
'customGroup.row.actions',
'CustomGroup',
$id
);
if (!empty($customGroup[$id]['style'])) {
$customGroup[$id]['style_display'] = $customGroupStyle[$customGroup[$id]['style']];
}
$customGroup[$id]['extends_display'] = $customGroupExtends[$customGroup[$id]['extends']];
}
//fix for Displaying subTypes
$subTypes = array();
$subTypes['Activity'] = CRM_Core_PseudoConstant::activityType(FALSE, TRUE, FALSE, 'label', TRUE);
$subTypes['Contribution'] = CRM_Contribute_PseudoConstant::financialType();
$subTypes['Membership'] = CRM_Member_BAO_MembershipType::getMembershipTypes(FALSE);
$subTypes['Event'] = CRM_Core_OptionGroup::values('event_type');
$subTypes['Grant'] = CRM_Core_OptionGroup::values('grant_type');
$subTypes['Campaign'] = CRM_Campaign_PseudoConstant::campaignType();
$subTypes['Participant'] = array();
$subTypes['ParticipantRole'] = CRM_Core_OptionGroup::values('participant_role');;
$subTypes['ParticipantEventName'] = CRM_Event_PseudoConstant::event();
$subTypes['ParticipantEventType'] = CRM_Core_OptionGroup::values('event_type');
$subTypes['Individual'] = CRM_Contact_BAO_ContactType::subTypePairs('Individual', FALSE, NULL);
$subTypes['Household'] = CRM_Contact_BAO_ContactType::subTypePairs('Household', FALSE, NULL);
$subTypes['Organization'] = CRM_Contact_BAO_ContactType::subTypePairs('Organization', FALSE, NULL);
$relTypeInd = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Individual');
$relTypeOrg = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Organization');
$relTypeHou = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Household');
$allRelationshipType = array();
$allRelationshipType = array_merge($relTypeInd, $relTypeOrg);
$allRelationshipType = array_merge($allRelationshipType, $relTypeHou);
//adding subtype specific relationships CRM-5256
$relSubType = CRM_Contact_BAO_ContactType::subTypeInfo();
foreach ($relSubType as $subType => $val) {
$subTypeRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $val['parent'],
FALSE, 'label', TRUE, $subType
);
$allRelationshipType = array_merge($allRelationshipType, $subTypeRelationshipTypes);
}
$subTypes['Relationship'] = $allRelationshipType;
$cSubTypes = CRM_Core_Component::contactSubTypes();
$contactSubTypes = array();
foreach ($cSubTypes as $key => $value) {
$contactSubTypes[$key] = $key;
}
$subTypes['Contact'] = $contactSubTypes;
CRM_Core_BAO_CustomGroup::getExtendedObjectTypes($subTypes);
foreach ($customGroup as $key => $values) {
$subValue = CRM_Utils_Array::value('extends_entity_column_value', $customGroup[$key]);
$subName = CRM_Utils_Array::value('extends_entity_column_id', $customGroup[$key]);
$type = CRM_Utils_Array::value('extends', $customGroup[$key]);
if ($subValue) {
$subValue = explode(CRM_Core_DAO::VALUE_SEPARATOR,
substr($subValue, 1, -1)
);
$colValue = NULL;
foreach ($subValue as $sub) {
if ($sub) {
if ($type == 'Participant') {
if ($subName == 1) {
$colValue = $colValue ? $colValue . ', ' . $subTypes['ParticipantRole'][$sub] : $subTypes['ParticipantRole'][$sub];
}
elseif ($subName == 2) {
$colValue = $colValue ? $colValue . ', ' . $subTypes['ParticipantEventName'][$sub] : $subTypes['ParticipantEventName'][$sub];
}
elseif ($subName == 3) {
$colValue = $colValue ? $colValue . ', ' . $subTypes['ParticipantEventType'][$sub] : $subTypes['ParticipantEventType'][$sub];
}
}
elseif ($type == 'Relationship') {
$colValue = $colValue ? $colValue . ', ' . $subTypes[$type][$sub . '_a_b'] : $subTypes[$type][$sub . '_a_b'];
if (isset($subTypes[$type][$sub . '_b_a'])) {
$colValue = $colValue ? $colValue . ', ' . $subTypes[$type][$sub . '_b_a'] : $subTypes[$type][$sub . '_b_a'];
}
}
else {
$colValue = $colValue ? ($colValue . (isset($subTypes[$type][$sub]) ? ', ' . $subTypes[$type][$sub] : '')) : (isset($subTypes[$type][$sub]) ? $subTypes[$type][$sub] : '');
}
}
}
$customGroup[$key]["extends_entity_column_value"] = $colValue;
}
else {
if (is_array(CRM_Utils_Array::value($type, $subTypes))) {
$customGroup[$key]["extends_entity_column_value"] = ts("Any");
}
}
}
$returnURL = CRM_Utils_System::url('civicrm/admin/custom/group', "reset=1&action=browse");
CRM_Utils_Weight::addOrder($customGroup, 'CRM_Core_DAO_CustomGroup',
'id', $returnURL
);
$this->assign('rows', $customGroup);
}
}

View file

@ -0,0 +1,284 @@
<?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$
*
*/
/**
* Create a page for displaying Custom Options.
*
* Heart of this class is the run method which checks
* for action type and then displays the appropriate
* page.
*
*/
class CRM_Custom_Page_Option extends CRM_Core_Page {
public $useLivePageJS = TRUE;
/**
* The Group id of the option
*
* @var int
*/
protected $_gid;
/**
* The field id of the option
*
* @var int
*/
protected $_fid;
/**
* The action links that we need to display for the browse screen
*
* @var array
*/
private static $_actionLinks;
/**
* Get the action links for this page.
*
* @return array
* array of action links that we need to display for the browse screen
*/
public static function &actionLinks() {
if (!isset(self::$_actionLinks)) {
self::$_actionLinks = array(
CRM_Core_Action::UPDATE => array(
'name' => ts('Edit Option'),
'url' => 'civicrm/admin/custom/group/field/option',
'qs' => 'reset=1&action=update&id=%%id%%&fid=%%fid%%&gid=%%gid%%',
'title' => ts('Edit Multiple Choice Option'),
),
CRM_Core_Action::VIEW => array(
'name' => ts('View'),
'url' => 'civicrm/admin/custom/group/field/option',
'qs' => 'action=view&id=%%id%%&fid=%%fid%%',
'title' => ts('View Multiple Choice Option'),
),
CRM_Core_Action::DISABLE => array(
'name' => ts('Disable'),
'ref' => 'crm-enable-disable',
'title' => ts('Disable Mutliple Choice Option'),
),
CRM_Core_Action::ENABLE => array(
'name' => ts('Enable'),
'ref' => 'crm-enable-disable',
'title' => ts('Enable Mutliple Choice Option'),
),
CRM_Core_Action::DELETE => array(
'name' => ts('Delete'),
'url' => 'civicrm/admin/custom/group/field/option',
'qs' => 'action=delete&id=%%id%%&fid=%%fid%%',
'title' => ts('Disable Multiple Choice Option'),
),
);
}
return self::$_actionLinks;
}
/**
* Alphabetize multiple option values
*
* @return void
*/
public function alphabetize() {
$optionGroupID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
$this->_fid,
'option_group_id'
);
$query = "
SELECT id, label
FROM civicrm_option_value
WHERE option_group_id = %1";
$params = array(
1 => array($optionGroupID, 'Integer'),
);
$dao = CRM_Core_DAO::executeQuery($query, $params);
$optionValue = array();
while ($dao->fetch()) {
$optionValue[$dao->id] = $dao->label;
}
asort($optionValue, SORT_STRING | SORT_FLAG_CASE | SORT_NATURAL);
$i = 1;
foreach ($optionValue as $key => $_) {
$clause[] = "WHEN $key THEN $i";
$i++;
}
$when = implode(' ', $clause);
$sql = "
UPDATE civicrm_option_value
SET weight = CASE id
$when
END
WHERE option_group_id = %1";
$dao = CRM_Core_DAO::executeQuery($sql, $params);
}
/**
* Browse all custom group fields.
*
* @return void
*/
public function browse() {
// get the option group id
$optionGroupID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
$this->_fid,
'option_group_id'
);
$query = "
SELECT id, label
FROM civicrm_custom_field
WHERE option_group_id = %1";
$params = array(
1 => array($optionGroupID, 'Integer'),
2 => array($this->_fid, 'Integer'),
);
$dao = CRM_Core_DAO::executeQuery($query, $params);
$reusedNames = array();
if ($dao->N > 1) {
while ($dao->fetch()) {
$reusedNames[] = $dao->label;
}
$reusedNames = implode(', ', $reusedNames);
$newTitle = ts('%1 - Multiple Choice Options',
array(1 => $reusedNames)
);
CRM_Utils_System::setTitle($newTitle);
$this->assign('reusedNames', $reusedNames);
}
$this->assign('optionGroupID', $optionGroupID);
}
/**
* Edit custom Option.
*
* editing would involved modifying existing fields + adding data to new fields.
*
* @param string $action
* The action to be invoked.
*
* @return void
*/
public function edit($action) {
// create a simple controller for editing custom data
$controller = new CRM_Core_Controller_Simple('CRM_Custom_Form_Option', ts('Custom Option'), $action);
// set the userContext stack
$session = CRM_Core_Session::singleton();
$session->pushUserContext(CRM_Utils_System::url('civicrm/admin/custom/group/field/option',
"reset=1&action=browse&fid={$this->_fid}&gid={$this->_gid}"
));
$controller->setEmbedded(TRUE);
$controller->process();
$controller->run();
}
/**
* Run the page.
*
* This method is called after the page is created. It checks for the
* type of action and executes that action.
*
* @return void
*/
public function run() {
// get the field id
$this->_fid = CRM_Utils_Request::retrieve('fid', 'Positive',
$this, FALSE, 0
);
$this->_gid = CRM_Utils_Request::retrieve('gid', 'Positive',
$this, FALSE, 0
);
if ($isReserved = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_gid, 'is_reserved', 'id')) {
CRM_Core_Error::fatal("You cannot add or edit muliple choice options in a reserved custom field-set.");
}
//as url contain $gid so append breadcrumb dynamically.
$breadcrumb = array(
array(
'title' => ts('Custom Data Fields'),
'url' => CRM_Utils_System::url('civicrm/admin/custom/group/field', 'reset=1&gid=' . $this->_gid),
),
);
CRM_Utils_System::appendBreadCrumb($breadcrumb);
if ($this->_fid) {
$fieldTitle = CRM_Core_BAO_CustomField::getTitle($this->_fid);
$this->assign('fid', $this->_fid);
$this->assign('gid', $this->_gid);
$this->assign('fieldTitle', $fieldTitle);
CRM_Utils_System::setTitle(ts('%1 - Multiple Choice Options', array(1 => $fieldTitle)));
}
// get the requested action
$action = CRM_Utils_Request::retrieve('action', 'String',
// default to 'browse'
$this, FALSE, 'browse'
);
// assign vars to templates
$this->assign('action', $action);
$id = CRM_Utils_Request::retrieve('id', 'Positive',
$this, FALSE, 0
);
// take action in addition to default browse ?
if (($action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD |
CRM_Core_Action::VIEW | CRM_Core_Action::DELETE
)
) ||
!empty($_POST)
) {
// no browse for edit/update/view
$this->edit($action);
}
elseif ($action & CRM_Core_Action::MAP) {
$this->alphabetize();
}
$this->browse();
// Call the parents run method
return parent::run();
}
}