'=', //equal
'ne' => '<>', //not equal
'lt' => '<', //less than
'le' => '<=', //less than or equal
'gt' => '>', //greater than
'ge' => '>=', //greater than or equal
'bw' => 'LIKE', //begins with
'bn' => 'NOT LIKE', //doesn't begin with
'in' => 'LIKE', //is in
'ni' => 'NOT LIKE', //is not in
'ew' => 'LIKE', //ends with
'en' => 'NOT LIKE', //doesn't end with
'cn' => 'LIKE', //contains
'nc' => 'NOT LIKE', //doesn't contain
];
public $type = 'user';
public $pageName;
public $pageUrl;
public $extraFieldType = 0;
public $table_field_options;
public $table_field_values;
public $table_field_tag;
public $table_field_rel_tag;
public $handler_id;
public $primaryKey;
/**
* @param string $type
*/
public function __construct($type)
{
parent::__construct();
$this->type = $type;
$this->table = Database::get_main_table(TABLE_EXTRA_FIELD);
$this->table_field_options = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
$this->table_field_values = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
$this->table_field_tag = Database::get_main_table(TABLE_MAIN_TAG);
$this->table_field_rel_tag = Database::get_main_table(TABLE_MAIN_EXTRA_FIELD_REL_TAG);
$this->handler_id = 'item_id';
switch ($this->type) {
case 'calendar_event':
$this->extraFieldType = EntityExtraField::CALENDAR_FIELD_TYPE;
break;
case 'course':
$this->extraFieldType = EntityExtraField::COURSE_FIELD_TYPE;
$this->primaryKey = 'id';
break;
case 'user':
$this->extraFieldType = EntityExtraField::USER_FIELD_TYPE;
$this->primaryKey = 'id';
break;
case 'session':
$this->extraFieldType = EntityExtraField::SESSION_FIELD_TYPE;
$this->primaryKey = 'id';
break;
case 'exercise':
$this->extraFieldType = EntityExtraField::EXERCISE_FIELD_TYPE;
break;
case 'question':
$this->extraFieldType = EntityExtraField::QUESTION_FIELD_TYPE;
break;
case 'lp':
$this->extraFieldType = EntityExtraField::LP_FIELD_TYPE;
break;
case 'lp_item':
$this->extraFieldType = EntityExtraField::LP_ITEM_FIELD_TYPE;
break;
case 'skill':
$this->extraFieldType = EntityExtraField::SKILL_FIELD_TYPE;
break;
case 'work':
$this->extraFieldType = EntityExtraField::WORK_FIELD_TYPE;
break;
case 'career':
$this->extraFieldType = EntityExtraField::CAREER_FIELD_TYPE;
break;
case 'user_certificate':
$this->extraFieldType = EntityExtraField::USER_CERTIFICATE;
break;
case 'survey':
$this->extraFieldType = EntityExtraField::SURVEY_FIELD_TYPE;
break;
case 'scheduled_announcement':
$this->extraFieldType = EntityExtraField::SCHEDULED_ANNOUNCEMENT;
break;
case 'terms_and_condition':
$this->extraFieldType = EntityExtraField::TERMS_AND_CONDITION_TYPE;
break;
case 'forum_category':
$this->extraFieldType = EntityExtraField::FORUM_CATEGORY_TYPE;
break;
case 'forum_post':
$this->extraFieldType = EntityExtraField::FORUM_POST_TYPE;
break;
}
$this->pageUrl = 'extra_fields.php?type='.$this->type;
// Example QuestionFields
$this->pageName = get_lang(ucwords($this->type).'Fields');
}
/**
* @return int
*/
public function getExtraFieldType()
{
return (int) $this->extraFieldType;
}
/**
* @return array
*/
public static function getValidExtraFieldTypes()
{
$result = [
'user',
'course',
'session',
'question',
'lp',
'calendar_event',
'lp_item',
'skill',
'work',
'career',
'user_certificate',
'survey',
'terms_and_condition',
'forum_category',
'forum_post',
'exercise',
];
if (api_get_configuration_value('allow_scheduled_announcements')) {
$result[] = 'scheduled_announcement';
}
return $result;
}
/**
* @return int
*/
public function get_count()
{
$em = Database::getManager();
$query = $em->getRepository('ChamiloCoreBundle:ExtraField')->createQueryBuilder('e');
$query->select('count(e.id)');
$query->where('e.extraFieldType = :type');
$query->setParameter('type', $this->getExtraFieldType());
return $query->getQuery()->getSingleScalarResult();
}
/**
* @param string $sidx
* @param string $sord
* @param int $start
* @param int $limit
*
* @return array
*/
public function getAllGrid($sidx, $sord, $start, $limit)
{
switch ($sidx) {
case 'field_order':
$sidx = 'e.fieldOrder';
break;
case 'variable':
$sidx = 'e.variable';
break;
case 'display_text':
$sidx = 'e.displayText';
break;
case 'changeable':
$sidx = 'e.changeable';
break;
case 'visible_to_self':
$sidx = 'e.visibleToSelf';
break;
case 'visible_to_others':
$sidx = 'e.visibleToOthers';
break;
case 'filter':
$sidx = 'e.filter';
break;
}
$em = Database::getManager();
$query = $em->getRepository('ChamiloCoreBundle:ExtraField')->createQueryBuilder('e');
$query->select('e')
->where('e.extraFieldType = :type')
->setParameter('type', $this->getExtraFieldType())
->orderBy($sidx, $sord)
->setFirstResult($start)
->setMaxResults($limit);
return $query->getQuery()->getArrayResult();
}
/**
* Get an array of all the values from the extra_field and extra_field_options tables
* based on the current object's type.
*
* @param array $conditions
* @param null $order_field_options_by
*
* @return array
*/
public function get_all($conditions = [], $order_field_options_by = null)
{
$conditions = Database::parse_conditions(['where' => $conditions]);
if (empty($conditions)) {
$conditions .= ' WHERE extra_field_type = '.$this->extraFieldType;
} else {
$conditions .= ' AND extra_field_type = '.$this->extraFieldType;
}
$sql = "SELECT * FROM $this->table
$conditions
ORDER BY field_order ASC
";
$result = Database::query($sql);
$extraFields = Database::store_result($result, 'ASSOC');
$option = new ExtraFieldOption($this->type);
if (!empty($extraFields)) {
foreach ($extraFields as &$extraField) {
$extraField['display_text'] = $this->translateDisplayName(
$extraField['variable'],
$extraField['display_text']
);
$extraField['options'] = $option->get_field_options_by_field(
$extraField['id'],
false,
$order_field_options_by
);
}
}
return $extraFields;
}
/**
* @param string $variable
*
* @return array|bool
*/
public function get_handler_field_info_by_field_variable($variable)
{
$variable = Database::escape_string($variable);
$sql = "SELECT * FROM {$this->table}
WHERE
variable = '$variable' AND
extra_field_type = $this->extraFieldType";
$result = Database::query($sql);
if (Database::num_rows($result)) {
$row = Database::fetch_array($result, 'ASSOC');
if ($row) {
$row['display_text'] = $this->translateDisplayName(
$row['variable'],
$row['display_text']
);
// All the options of the field
$sql = "SELECT * FROM $this->table_field_options
WHERE field_id='".intval($row['id'])."'
ORDER BY option_order ASC";
$result = Database::query($sql);
while ($option = Database::fetch_array($result)) {
$row['options'][$option['id']] = $option;
}
return $row;
}
}
return false;
}
/**
* Get all the field info for tags.
*
* @param string $variable
*
* @return array|bool
*/
public function get_handler_field_info_by_tags($variable)
{
$variable = Database::escape_string($variable);
$sql = "SELECT * FROM {$this->table}
WHERE
variable = '$variable' AND
extra_field_type = $this->extraFieldType";
$result = Database::query($sql);
if (Database::num_rows($result)) {
$row = Database::fetch_array($result, 'ASSOC');
$row['display_text'] = $this->translateDisplayName(
$row['variable'],
$row['display_text']
);
// All the tags of the field
$sql = "SELECT * FROM $this->table_field_tag
WHERE field_id='".intval($row['id'])."'
ORDER BY id ASC";
$result = Database::query($sql);
while ($option = Database::fetch_array($result, 'ASSOC')) {
$row['options'][$option['id']] = $option;
}
return $row;
} else {
return false;
}
}
/**
* @param int $fieldId
*
* @return array|bool
*/
public function getFieldInfoByFieldId($fieldId)
{
$fieldId = (int) $fieldId;
$sql = "SELECT * FROM {$this->table}
WHERE
id = '$fieldId' AND
extra_field_type = $this->extraFieldType";
$result = Database::query($sql);
if (Database::num_rows($result)) {
$row = Database::fetch_array($result, 'ASSOC');
// All the options of the field
$sql = "SELECT * FROM $this->table_field_options
WHERE field_id='".$fieldId."'
ORDER BY option_order ASC";
$result = Database::query($sql);
while ($option = Database::fetch_array($result)) {
$row['options'][$option['id']] = $option;
}
return $row;
} else {
return false;
}
}
/**
* @return int
*/
public function get_max_field_order()
{
$sql = "SELECT MAX(field_order)
FROM {$this->table}
WHERE
extra_field_type = '.$this->extraFieldType.'";
$res = Database::query($sql);
$order = 0;
if (Database::num_rows($res) > 0) {
$row = Database::fetch_row($res);
$order = $row[0] + 1;
}
return $order;
}
/**
* @param string $handler
*
* @return array
*/
public static function get_extra_fields_by_handler($handler)
{
$types = [];
$types[self::FIELD_TYPE_TEXT] = get_lang('FieldTypeText');
$types[self::FIELD_TYPE_TEXTAREA] = get_lang('FieldTypeTextarea');
$types[self::FIELD_TYPE_RADIO] = get_lang('FieldTypeRadio');
$types[self::FIELD_TYPE_SELECT] = get_lang('FieldTypeSelect');
$types[self::FIELD_TYPE_SELECT_MULTIPLE] = get_lang('FieldTypeSelectMultiple');
$types[self::FIELD_TYPE_DATE] = get_lang('FieldTypeDate');
$types[self::FIELD_TYPE_DATETIME] = get_lang('FieldTypeDatetime');
$types[self::FIELD_TYPE_DOUBLE_SELECT] = get_lang('FieldTypeDoubleSelect');
$types[self::FIELD_TYPE_DIVIDER] = get_lang('FieldTypeDivider');
$types[self::FIELD_TYPE_TAG] = get_lang('FieldTypeTag');
$types[self::FIELD_TYPE_TIMEZONE] = get_lang('FieldTypeTimezone');
$types[self::FIELD_TYPE_SOCIAL_PROFILE] = get_lang('FieldTypeSocialProfile');
$types[self::FIELD_TYPE_MOBILE_PHONE_NUMBER] = get_lang('FieldTypeMobilePhoneNumber');
$types[self::FIELD_TYPE_CHECKBOX] = get_lang('FieldTypeCheckbox');
$types[self::FIELD_TYPE_INTEGER] = get_lang('FieldTypeInteger');
$types[self::FIELD_TYPE_FILE_IMAGE] = get_lang('FieldTypeFileImage');
$types[self::FIELD_TYPE_FLOAT] = get_lang('FieldTypeFloat');
$types[self::FIELD_TYPE_FILE] = get_lang('FieldTypeFile');
$types[self::FIELD_TYPE_VIDEO_URL] = get_lang('FieldTypeVideoUrl');
$types[self::FIELD_TYPE_LETTERS_ONLY] = get_lang('FieldTypeOnlyLetters');
$types[self::FIELD_TYPE_ALPHANUMERIC] = get_lang('FieldTypeAlphanumeric');
$types[self::FIELD_TYPE_LETTERS_SPACE] = get_lang('FieldTypeLettersSpaces');
$types[self::FIELD_TYPE_ALPHANUMERIC_SPACE] = get_lang('FieldTypeAlphanumericSpaces');
$types[self::FIELD_TYPE_GEOLOCALIZATION] = get_lang('Geolocalization');
$types[self::FIELD_TYPE_GEOLOCALIZATION_COORDINATES] = get_lang('GeolocalizationCoordinates');
$types[self::FIELD_TYPE_SELECT_WITH_TEXT_FIELD] = get_lang('FieldTypeSelectWithTextField');
$types[self::FIELD_TYPE_TRIPLE_SELECT] = get_lang('FieldTypeTripleSelect');
switch ($handler) {
case 'course':
case 'session':
case 'user':
case 'skill':
break;
}
return $types;
}
/**
* Add elements to a form.
*
* @param FormValidator $form The form object to which to attach this element
* @param int $itemId The item (course, user, session, etc) this extra_field is linked to
* @param array $exclude Variables of extra field to exclude
* @param bool $filter Whether to get only the fields with the "filter" flag set to 1 (true) or not (false)
* @param bool $useTagAsSelect Whether to show tag fields as select drop-down or not
* @param array $showOnlyTheseFields Limit the extra fields shown to just the list given here
* @param array $orderFields An array containing the names of the fields shown, in the right order
* @param array $extraData
* @param bool $orderDependingDefaults
* @param bool $adminPermissions
* @param array $separateExtraMultipleSelect
* @param array $customLabelsExtraMultipleSelect
* @param bool $addEmptyOptionSelects
* @param array $introductionTextList
* @param array $requiredFields
* @param bool $hideGeoLocalizationDetails
*
* @throws Exception
*
* @return array|bool If relevant, returns a one-element array with JS code to be added to the page HTML headers.
* Returns false if the form object was not given
*/
public function addElements(
$form,
$itemId = 0,
$exclude = [],
$filter = false,
$useTagAsSelect = false,
$showOnlyTheseFields = [],
$orderFields = [],
$extraData = [],
$orderDependingDefaults = false,
$adminPermissions = false,
$separateExtraMultipleSelect = [],
$customLabelsExtraMultipleSelect = [],
$addEmptyOptionSelects = false,
$introductionTextList = [],
$requiredFields = [],
$hideGeoLocalizationDetails = false,
$help = false
) {
if (empty($form)) {
return false;
}
$itemId = (int) $itemId;
$form->addHidden('item_id', $itemId);
if (empty($extraData)) {
if (!empty($itemId)) {
$extraData = self::get_handler_extra_data($itemId);
if ($form) {
if (!empty($showOnlyTheseFields)) {
$setData = [];
foreach ($showOnlyTheseFields as $variable) {
$extraName = 'extra_'.$variable;
if (in_array($extraName, array_keys($extraData))) {
$setData[$extraName] = $extraData[$extraName];
}
}
$form->setDefaults($setData);
} else {
$form->setDefaults($extraData);
}
}
}
}
$conditions = [];
if ($filter) {
$conditions = ['filter = ?' => 1];
}
$extraFields = $this->get_all($conditions, 'option_order');
$extra = $this->set_extra_fields_in_form(
$form,
$extraData,
$adminPermissions,
$extraFields,
$itemId,
$exclude,
$useTagAsSelect,
$showOnlyTheseFields,
$orderFields,
$orderDependingDefaults,
$separateExtraMultipleSelect,
$customLabelsExtraMultipleSelect,
$addEmptyOptionSelects,
$introductionTextList,
$hideGeoLocalizationDetails,
$help
);
if (!empty($requiredFields)) {
/** @var HTML_QuickForm_input $element */
foreach ($form->getElements() as $element) {
$name = str_replace('extra_', '', $element->getName());
if (in_array($name, $requiredFields)) {
$form->setRequired($element);
}
}
}
return $extra;
}
/**
* Return an array of all the extra fields available for this item.
*
* @param int $itemId (session_id, question_id, course id)
*
* @return array
*/
public function get_handler_extra_data($itemId)
{
if (empty($itemId)) {
return [];
}
$extra_data = [];
$fields = $this->get_all();
$field_values = new ExtraFieldValue($this->type);
if (!empty($fields) > 0) {
foreach ($fields as $field) {
$field_value = $field_values->get_values_by_handler_and_field_id(
$itemId,
$field['id']
);
if ($field['field_type'] == self::FIELD_TYPE_TAG) {
$tags = UserManager::get_user_tags_to_string(
$itemId,
$field['id'],
false
);
$extra_data['extra_'.$field['variable']] = $tags;
continue;
}
if ($field_value) {
$variable = $field['variable'];
$field_value = $field_value['value'];
switch ($field['field_type']) {
case self::FIELD_TYPE_TAG:
$tags = UserManager::get_user_tags_to_string(
$itemId,
$field['id'],
false
);
$extra_data['extra_'.$field['variable']] = $tags;
break;
case self::FIELD_TYPE_DOUBLE_SELECT:
case self::FIELD_TYPE_SELECT_WITH_TEXT_FIELD:
$selected_options = explode('::', $field_value);
$firstOption = isset($selected_options[0]) ? $selected_options[0] : '';
$secondOption = isset($selected_options[1]) ? $selected_options[1] : '';
$extra_data['extra_'.$field['variable']]['extra_'.$field['variable']] = $firstOption;
$extra_data['extra_'.$field['variable']]['extra_'.$field['variable'].'_second'] = $secondOption;
break;
case self::FIELD_TYPE_SELECT_MULTIPLE:
$field_value = explode(';', $field_value);
$extra_data['extra_'.$field['variable']] = $field_value;
break;
case self::FIELD_TYPE_RADIO:
$extra_data['extra_'.$field['variable']]['extra_'.$field['variable']] = $field_value;
break;
case self::FIELD_TYPE_TRIPLE_SELECT:
list($level1, $level2, $level3) = explode(';', $field_value);
$extra_data["extra_$variable"]["extra_$variable"] = $level1;
$extra_data["extra_$variable"]["extra_{$variable}_second"] = $level2;
$extra_data["extra_$variable"]["extra_{$variable}_third"] = $level3;
break;
default:
$extra_data['extra_'.$field['variable']] = $field_value;
break;
}
} else {
// Set default values
if (isset($field['field_default_value']) &&
!empty($field['field_default_value'])
) {
$extra_data['extra_'.$field['variable']] = $field['field_default_value'];
}
}
}
}
return $extra_data;
}
/**
* @param string $field_type
*
* @return array
*/
public function get_all_extra_field_by_type($field_type)
{
// all the information of the field
$sql = "SELECT * FROM {$this->table}
WHERE
field_type = '".Database::escape_string($field_type)."' AND
extra_field_type = $this->extraFieldType
";
$result = Database::query($sql);
$return = [];
while ($row = Database::fetch_array($result)) {
$return[] = $row['id'];
}
return $return;
}
/**
* @return array
*/
public function get_field_types()
{
return $this->get_extra_fields_by_handler($this->type);
}
/**
* @param int $id
*/
public function get_field_type_by_id($id)
{
$types = $this->get_field_types();
if (isset($types[$id])) {
return $types[$id];
}
return null;
}
/**
* Converts a string like this:
* France:Paris;Bretagne;Marseille;Lyon|Belgique:Bruxelles;Namur;Liège;Bruges|Peru:Lima;Piura;
* into
* array(
* 'France' =>
* array('Paris', 'Bretagne', 'Marseille'),
* 'Belgique' =>
* array('Namur', 'Liège')
* ), etc.
*
* @param string $string
*
* @return array
*/
public static function extra_field_double_select_convert_string_to_array($string)
{
$options = explode('|', $string);
$options_parsed = [];
$id = 0;
if (!empty($options)) {
foreach ($options as $sub_options) {
$options = explode(':', $sub_options);
$sub_sub_options = isset($options[1]) ? explode(';', $options[1]) : [];
$options_parsed[$id] = [
'label' => $options[0],
'options' => $sub_sub_options,
];
$id++;
}
}
return $options_parsed;
}
/**
* @param $string
*
* @return array
*/
public static function tripleSelectConvertStringToArray($string)
{
$options = [];
foreach (explode('|', $string) as $i => $item0) {
$level1 = explode('\\', $item0);
foreach ($level1 as $j => $item1) {
if (0 === $j) {
$options[] = ['label' => $item1, 'options' => []];
continue;
}
foreach (explode(':', $item1) as $k => $item2) {
if (0 === $k) {
$options[$i]['options'][] = ['label' => $item2, 'options' => []];
continue;
}
$options[$i]['options'][$j - 1]['options'][] = explode(';', $item2);
}
}
}
array_walk_recursive($options, function (&$item) {
$item = trim($item);
});
return $options;
}
/**
* @param array $options
*
* @return array
*/
public static function extra_field_double_select_convert_array_to_ordered_array($options)
{
$options_parsed = [];
if (!empty($options)) {
foreach ($options as $option) {
if ($option['option_value'] == 0) {
$options_parsed[$option['id']][] = $option;
} else {
$options_parsed[$option['option_value']][] = $option;
}
}
}
return $options_parsed;
}
/**
* @param array $options
*
* @return array
*/
public static function tripleSelectConvertArrayToOrderedArray(array $options)
{
$level1 = self::getOptionsFromTripleSelect($options, 0);
$level2 = [];
$level3 = [];
foreach ($level1 as $item1) {
$level2 += self::getOptionsFromTripleSelect($options, $item1['id']);
}
foreach ($level2 as $item2) {
$level3 += self::getOptionsFromTripleSelect($options, $item2['id']);
}
return ['level1' => $level1, 'level2' => $level2, 'level3' => $level3];
}
/**
* @param array $options the result of the get_field_options_by_field() array
*
* @return string
*/
public static function extra_field_double_select_convert_array_to_string($options)
{
$string = null;
$options_parsed = self::extra_field_double_select_convert_array_to_ordered_array($options);
if (!empty($options_parsed)) {
foreach ($options_parsed as $option) {
foreach ($option as $key => $item) {
$string .= $item['display_text'];
if ($key == 0) {
$string .= ':';
} else {
if (isset($option[$key + 1])) {
$string .= ';';
}
}
}
$string .= '|';
}
}
if (!empty($string)) {
$string = substr($string, 0, strlen($string) - 1);
}
return $string;
}
/**
* @param array $options The result of the get_field_options_by_field() array
*
* @return string
*/
public static function extraFieldSelectWithTextConvertArrayToString(array $options)
{
$string = '';
$parsedOptions = self::extra_field_double_select_convert_array_to_ordered_array($options);
if (empty($parsedOptions)) {
return '';
}
foreach ($parsedOptions as $options) {
$option = current($options);
$string .= $option['display_text'];
$string .= '|';
}
return rtrim($string, '|');
}
/**
* @param array $options
*
* @return string
*/
public static function tripleSelectConvertArrayToString(array $options)
{
$string = '';
$parsedOptions = self::tripleSelectConvertArrayToOrderedArray($options);
foreach ($parsedOptions['level1'] as $item1) {
$string .= $item1['display_text'];
$level2 = self::getOptionsFromTripleSelect($parsedOptions['level2'], $item1['id']);
foreach ($level2 as $item2) {
$string .= '\\'.$item2['display_text'].':';
$level3 = self::getOptionsFromTripleSelect($parsedOptions['level3'], $item2['id']);
$string .= implode(';', array_column($level3, 'display_text'));
}
$string .= '|';
}
return trim($string, '\\|;');
}
/**
* @param array $params
*
* @return array
*/
public function clean_parameters($params)
{
if (!isset($params['variable']) || empty($params['variable'])) {
$params['variable'] = $params['display_text'];
}
$params['variable'] = trim(strtolower(str_replace(" ", "_", $params['variable'])));
if (!isset($params['field_order'])) {
$max_order = self::get_max_field_order();
$params['field_order'] = $max_order;
} else {
$params['field_order'] = (int) $params['field_order'];
}
return $params;
}
/**
* @param array $params
* @param bool $show_query
*
* @return int|bool
*/
public function save($params, $show_query = false)
{
$fieldInfo = self::get_handler_field_info_by_field_variable($params['variable']);
$params = $this->clean_parameters($params);
$params['extra_field_type'] = $this->extraFieldType;
if ($fieldInfo) {
return $fieldInfo['id'];
} else {
$id = parent::save($params, $show_query);
if ($id) {
$fieldOption = new ExtraFieldOption($this->type);
$params['field_id'] = $id;
$fieldOption->save($params);
}
return $id;
}
}
/**
* {@inheritdoc}
*/
public function update($params, $showQuery = false)
{
$params = $this->clean_parameters($params);
if (isset($params['id'])) {
$fieldOption = new ExtraFieldOption($this->type);
$params['field_id'] = $params['id'];
if (empty($params['field_type'])) {
$params['field_type'] = $this->type;
}
$fieldOption->save($params, $showQuery);
}
return parent::update($params, $showQuery);
}
/**
* @param $id
*
* @return bool
*/
public function delete($id)
{
$em = Database::getManager();
$items = $em->getRepository('ChamiloCoreBundle:ExtraFieldSavedSearch')->findBy(['field' => $id]);
if ($items) {
foreach ($items as $item) {
$em->remove($item);
}
$em->flush();
}
$field_option = new ExtraFieldOption($this->type);
$field_option->delete_all_options_by_field_id($id);
$session_field_values = new ExtraFieldValue($this->type);
$session_field_values->delete_all_values_by_field_id($id);
return parent::delete($id);
}
/**
* Add an element that matches the given extra field to the given $form object.
*
* @param FormValidator $form The form these fields are to be attached to
* @param array $extraData
* @param bool $adminPermissions Whether the display is considered without edition limits (true) or not (false)
* @param array $extra
* @param int $itemId The item (course, user, session, etc) this extra_field is attached to
* @param array $exclude Extra fields to be skipped, by textual ID
* @param bool $useTagAsSelect Whether to show tag fields as select drop-down or not
* @param array $showOnlyTheseFields Limit the extra fields shown to just the list given here
* @param array $orderFields An array containing the names of the fields shown, in the right order
*
* @throws Exception
*
* @return array If relevant, returns a one-element array with JS code to be added to the page HTML headers
*/
public function set_extra_fields_in_form(
$form,
$extraData,
$admin_permissions = false,
$extra = [],
$itemId = null,
$exclude = [],
$useTagAsSelect = false,
$showOnlyTheseFields = [],
$orderFields = [],
$orderDependingDefaults = false,
$separateExtraMultipleSelect = [],
$customLabelsExtraMultipleSelect = [],
$addEmptyOptionSelects = false,
$introductionTextList = [],
$hideGeoLocalizationDetails = false,
$help = false
) {
$type = $this->type;
$jquery_ready_content = '';
if (!empty($extra)) {
$newOrder = [];
if (!empty($orderFields)) {
foreach ($orderFields as $order) {
foreach ($extra as $field_details) {
if ($order === $field_details['variable']) {
$newOrder[] = $field_details;
}
}
}
$extra = $newOrder;
}
foreach ($extra as $field_details) {
if (!empty($showOnlyTheseFields)) {
if (!in_array($field_details['variable'], $showOnlyTheseFields)) {
continue;
}
}
// Getting default value id if is set
$defaultValueId = null;
if (isset($field_details['options']) && !empty($field_details['options'])) {
$valueToFind = null;
if (isset($field_details['field_default_value'])) {
$valueToFind = $field_details['field_default_value'];
}
// If a value is found we override the default value
if (isset($extraData['extra_'.$field_details['variable']])) {
$valueToFind = $extraData['extra_'.$field_details['variable']];
}
foreach ($field_details['options'] as $option) {
if ($option['option_value'] == $valueToFind) {
$defaultValueId = $option['id'];
}
}
}
if (!$admin_permissions) {
if ($field_details['visible_to_self'] == 0) {
continue;
}
if (in_array($field_details['variable'], $exclude)) {
continue;
}
}
if (!empty($introductionTextList) &&
in_array($field_details['variable'], array_keys($introductionTextList))
) {
$form->addHtml($introductionTextList[$field_details['variable']]);
}
$freezeElement = false;
if (!$admin_permissions) {
$freezeElement = $field_details['visible_to_self'] == 0 || $field_details['changeable'] == 0;
}
$translatedDisplayText = get_lang($field_details['display_text'], true);
$translatedDisplayHelpText = '';
if ($help) {
$translatedDisplayHelpText .= get_lang($field_details['display_text'].'Help');
}
$label = [$translatedDisplayText, $translatedDisplayHelpText];
// Ofaj
if (!empty($translatedDisplayText)) {
//$field_details['display_text'] = $label;
}
switch ($field_details['field_type']) {
case self::FIELD_TYPE_TEXT:
$form->addElement(
'text',
'extra_'.$field_details['variable'],
$field_details['display_text'],
[
'id' => 'extra_'.$field_details['variable'],
]
);
$form->applyFilter(
'extra_'.$field_details['variable'],
'stripslashes'
);
$form->applyFilter(
'extra_'.$field_details['variable'],
'trim'
);
if ($freezeElement) {
$form->freeze('extra_'.$field_details['variable']);
}
break;
case self::FIELD_TYPE_TEXTAREA:
$form->addHtmlEditor(
'extra_'.$field_details['variable'],
$field_details['display_text'],
false,
false,
[
'ToolbarSet' => 'Profile',
'Width' => '100%',
'Height' => '130',
'id' => 'extra_'.$field_details['variable'],
]
);
$form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
$form->applyFilter('extra_'.$field_details['variable'], 'trim');
if ($freezeElement) {
$form->freeze('extra_'.$field_details['variable']);
}
break;
case self::FIELD_TYPE_RADIO:
$group = [];
if (isset($field_details['options']) &&
!empty($field_details['options'])
) {
foreach ($field_details['options'] as $option_details) {
$options[$option_details['option_value']] = $option_details['display_text'];
$group[] = $form->createElement(
'radio',
'extra_'.$field_details['variable'],
$option_details['option_value'],
$option_details['display_text'].'
',
$option_details['option_value']
);
}
}
$form->addGroup(
$group,
'extra_'.$field_details['variable'],
$field_details['display_text']
);
if ($freezeElement) {
$form->freeze('extra_'.$field_details['variable']);
}
break;
case self::FIELD_TYPE_CHECKBOX:
$group = [];
if (isset($field_details['options']) &&
!empty($field_details['options'])
) {
foreach ($field_details['options'] as $option_details) {
$options[$option_details['option_value']] = $option_details['display_text'];
$group[] = $form->createElement(
'checkbox',
'extra_'.$field_details['variable'],
$option_details['option_value'],
$option_details['display_text'].'
',
$option_details['option_value']
);
}
} else {
$fieldVariable = "extra_{$field_details['variable']}";
$checkboxAttributes = [];
if (is_array($extraData) &&
array_key_exists($fieldVariable, $extraData)
) {
if (!empty($extraData[$fieldVariable])) {
$checkboxAttributes['checked'] = 1;
}
}
if (empty($checkboxAttributes) &&
isset($field_details['default_value']) && empty($extraData)) {
if ($field_details['default_value'] == 1) {
$checkboxAttributes['checked'] = 1;
}
}
// We assume that is a switch on/off with 1 and 0 as values
$group[] = $form->createElement(
'checkbox',
'extra_'.$field_details['variable'],
null,
//$field_details['display_text'].'
',
get_lang('Yes'),
$checkboxAttributes
);
}
$form->addGroup(
$group,
'extra_'.$field_details['variable'],
$field_details['display_text']
);
if ($freezeElement) {
$form->freeze('extra_'.$field_details['variable']);
}
break;
case self::FIELD_TYPE_SELECT:
$get_lang_variables = false;
if (in_array(
$field_details['variable'],
['mail_notify_message', 'mail_notify_invitation', 'mail_notify_group_message']
)
) {
$get_lang_variables = true;
}
// Get extra field workflow
$userInfo = api_get_user_info();
$addOptions = [];
$optionsExists = false;
global $app;
// Check if exist $app['orm.em'] object
if (isset($app['orm.em']) && is_object($app['orm.em'])) {
$optionsExists = $app['orm.em']
->getRepository('ChamiloLMS\Entity\ExtraFieldOptionRelFieldOption')
->findOneBy(['fieldId' => $field_details['id']]);
}
if ($optionsExists) {
if (isset($userInfo['status']) && !empty($userInfo['status'])) {
$fieldWorkFlow = $app['orm.em']->getRepository('ChamiloLMS\Entity\ExtraFieldOptionRelFieldOption')
->findBy(
[
'fieldId' => $field_details['id'],
'relatedFieldOptionId' => $defaultValueId,
'roleId' => $userInfo['status'],
]
);
foreach ($fieldWorkFlow as $item) {
$addOptions[] = $item->getFieldOptionId();
}
}
}
$options = [];
if (empty($defaultValueId)) {
$options[''] = get_lang('SelectAnOption');
}
$optionList = [];
if (!empty($field_details['options'])) {
foreach ($field_details['options'] as $option_details) {
$optionList[$option_details['id']] = $option_details;
if ($get_lang_variables) {
$options[$option_details['option_value']] = $option_details['display_text'];
} else {
if ($optionsExists) {
// Adding always the default value
if ($option_details['id'] == $defaultValueId) {
$options[$option_details['option_value']] = $option_details['display_text'];
} else {
if (isset($addOptions) && !empty($addOptions)) {
// Parsing filters
if (in_array($option_details['id'], $addOptions)) {
$options[$option_details['option_value']] = $option_details['display_text'];
}
}
}
} else {
// Normal behaviour
$options[$option_details['option_value']] = $option_details['display_text'];
}
}
}
// Setting priority message
if (isset($optionList[$defaultValueId]) &&
isset($optionList[$defaultValueId]['priority'])
) {
if (!empty($optionList[$defaultValueId]['priority'])) {
$priorityId = $optionList[$defaultValueId]['priority'];
$option = new ExtraFieldOption($this->type);
$messageType = $option->getPriorityMessageType($priorityId);
$form->addElement(
'label',
null,
Display::return_message(
$optionList[$defaultValueId]['priority_message'],
$messageType
)
);
}
}
}
// chzn-select doesn't work for sessions??
$form->addElement(
'select',
'extra_'.$field_details['variable'],
$field_details['display_text'],
$options,
['id' => 'extra_'.$field_details['variable']]
);
if (!$admin_permissions) {
if ($field_details['visible_to_self'] == 0) {
$form->freeze('extra_'.$field_details['variable']);
}
}
break;
case self::FIELD_TYPE_SELECT_MULTIPLE:
$options = [];
if (empty($defaultValueId)) {
$options[''] = get_lang('SelectAnOption');
}
foreach ($field_details['options'] as $option_id => $option_details) {
$options[$option_details['option_value']] = $option_details['display_text'];
}
if ($orderDependingDefaults) {
$defaultOptions = $extraData['extra_'.$field_details['variable']];
if (!empty($defaultOptions)) {
$firstList = [];
if ($addEmptyOptionSelects) {
$firstList[] = '';
}
foreach ($defaultOptions as $key) {
if (isset($options[$key])) {
$firstList[$key] = $options[$key];
}
}
if (!empty($firstList)) {
$options = array_merge($firstList, $options);
}
} else {
$firstList = [];
if ($addEmptyOptionSelects) {
$firstList[] = ' ';
$options = array_merge($firstList, $options);
}
}
}
// OFAJ
$separateValue = 0;
if (isset($separateExtraMultipleSelect[$field_details['variable']])) {
$separateValue = $separateExtraMultipleSelect[$field_details['variable']];
}
if ($separateValue > 0) {
for ($i = 0; $i < $separateValue; $i++) {
$form->addElement(
'select',
'extra_'.$field_details['variable'].'['.$i.']',
$customLabelsExtraMultipleSelect[$field_details['variable']][$i], //$field_details['display_text'],
$options,
['id' => 'extra_'.$field_details['variable'].'_'.$i]
);
}
} else {
// Ofaj
$attributes = ['multiple' => 'multiple', 'id' => 'extra_'.$field_details['variable']];
$chosenSelect = [
'ecouter',
'lire',
'participer_a_une_conversation',
's_exprimer_oralement_en_continu',
'ecrire',
];
if (in_array($field_details['variable'], $chosenSelect)) {
$attributes['select_chosen'] = true;
}
// default behaviour
$form->addElement(
'select',
'extra_'.$field_details['variable'],
$field_details['display_text'],
$options,
$attributes
);
}
if (!$admin_permissions) {
if ($field_details['visible_to_self'] == 0) {
$form->freeze('extra_'.$field_details['variable']);
}
}
break;
case self::FIELD_TYPE_DATE:
$form->addDatePicker('extra_'.$field_details['variable'], $field_details['display_text']);
if ($freezeElement) {
$form->freeze('extra_'.$field_details['variable']);
}
break;
case self::FIELD_TYPE_DATETIME:
$form->addDateTimePicker(
'extra_'.$field_details['variable'],
$field_details['display_text']
);
$defaults['extra_'.$field_details['variable']] = api_get_local_time();
if (!isset($form->_defaultValues['extra_'.$field_details['variable']])) {
$form->setDefaults($defaults);
}
if ($freezeElement) {
$form->freeze('extra_'.$field_details['variable']);
}
break;
case self::FIELD_TYPE_DOUBLE_SELECT:
$first_select_id = 'first_extra_'.$field_details['variable'];
$url = api_get_path(WEB_AJAX_PATH).'extra_field.ajax.php?1=1';
$jquery_ready_content .= '
$("#'.$first_select_id.'").on("change", function() {
var id = $(this).val();
if (id) {
$.ajax({
url: "'.$url.'&a=get_second_select_options",
dataType: "json",
data: "type='.$type.'&field_id='.$field_details['id'].'&option_value_id="+id,
success: function(data) {
$("#second_extra_'.$field_details['variable'].'").empty();
$.each(data, function(index, value) {
$("#second_extra_'.$field_details['variable'].'").append($("", {
value: index,
text: value
}));
});
$("#second_extra_'.$field_details['variable'].'").selectpicker("refresh");
},
});
} else {
$("#second_extra_'.$field_details['variable'].'").empty();
}
});';
$first_id = null;
if (!empty($extraData)) {
if (isset($extraData['extra_'.$field_details['variable']])) {
$first_id = $extraData['extra_'.$field_details['variable']]['extra_'.$field_details['variable']];
}
}
$options = self::extra_field_double_select_convert_array_to_ordered_array(
$field_details['options']
);
$values = ['' => get_lang('Select')];
$second_values = [];
if (!empty($options)) {
foreach ($options as $option) {
foreach ($option as $sub_option) {
if ($sub_option['option_value'] == '0') {
$values[$sub_option['id']] = $sub_option['display_text'];
} else {
if ($first_id === $sub_option['option_value']) {
$second_values[$sub_option['id']] = $sub_option['display_text'];
}
}
}
}
}
$group = [];
$group[] = $form->createElement(
'select',
'extra_'.$field_details['variable'],
null,
$values,
['id' => $first_select_id]
);
$group[] = $form->createElement(
'select',
'extra_'.$field_details['variable'].'_second',
null,
$second_values,
['id' => 'second_extra_'.$field_details['variable']]
);
$form->addGroup(
$group,
'extra_'.$field_details['variable'],
$field_details['display_text']
);
if (!$admin_permissions) {
if ($field_details['visible_to_self'] == 0) {
$form->freeze('extra_'.$field_details['variable']);
}
}
break;
case self::FIELD_TYPE_DIVIDER:
$form->addHtml('