Current File : /home/pacjaorg/public_html/km/administrator/components/com_djclassifieds/lib/djfield.php
<?php
/**
 * @package DJ-Classifieds
 * @copyright Copyright (C) DJ-Extensions.com, All rights reserved.
 * @license http://www.gnu.org/licenses GNU/GPL
 * @author url: http://dj-extensions.com
 * @author email contact@dj-extensions.com
 */

defined('_JEXEC') or die('Restricted access');

require_once(JPATH_ROOT.'/administrator/components/com_djclassifieds/lib/djtheme.php');
require_once(JPATH_ROOT.'/administrator/components/com_djclassifieds/lib/djimage.php');
require_once(JPATH_ROOT.'/administrator/components/com_djclassifieds/lib/djseo.php');
require_once(JPATH_ROOT.'/components/com_djclassifieds/model.php');

class DJClassifiedsField
{
	static function getField($id)
	{
		$db = JFactory::getDBO();

		if(!is_numeric($id)){
			$query = "SELECT id FROM #__djcf_fields WHERE name=".$db->q($id);
			$db->setQuery($query);
			$id = $db->loadResult();
		}
		if(!$id){
			return false;
		}

		$query = "SELECT * FROM #__djcf_fields WHERE id=".$id;
		$db->setQuery($query);
		$field = $db->loadObject();
		
		return $field;
	}

	static function getSortFields($cat_id = null)
	{
		$db = JFactory::getDBO();
		$query = "SELECT * FROM #__djcf_fields WHERE published=1 AND source IN (0,1) AND sortable=1 ORDER BY ordering";
		$db->setQuery($query);
		$sort_fields = $db->loadObjectList('name');

		if($cat_id !== null){
			foreach($sort_fields as $key => $f){
				if($f->source == '0' && $f->all_cats == '0'){
					$f_par = new JRegistry();
					$f_par->loadString($f->params);
					if($f_par->get('sortable_all_cats','0') == '0'){
						if(!$cat_id){
							unset($sort_fields[$key]);
						}else{
							$query = "SELECT id FROM #__djcf_fields_xref WHERE field_id=".$f->id." AND cat_id=".$cat_id;
							$db->setQuery($query);
							$cat_assigned = $db->loadResult();
							if(!$cat_assigned){
								unset($sort_fields[$key]);
							}
						}
					}
				}
			}
		}

		return $sort_fields;
	}

	static function getProfileSortFields()
	{
		$db = JFactory::getDBO();
		$query = "SELECT * FROM #__djcf_fields WHERE published=1 AND source=2 AND sortable=1 ORDER BY ordering";
		$db->setQuery($query);
		$sort_fields = $db->loadObjectList('name');

		return $sort_fields;
	}

	static function getFieldGroup($group_id)
	{
		$db = JFactory::getDBO();
		$user = JFactory::getUser();

		$query = "SELECT * FROM #__djcf_fields_groups WHERE published=1 AND id=".$group_id;
		$db->setQuery($query);
		$fieldgroup = $db->loadObject();

		if(!$fieldgroup){
			return null;
		}
		if(!in_array($fieldgroup->access, $user->getAuthorisedViewLevels())){
			return false;
		}
		
		return $fieldgroup;
	}

	static function getProfileFieldGroups()
	{
		$db = JFactory::getDBO();
		$query = "SELECT * FROM #__djcf_fields_groups WHERE source=2 AND published=1 ORDER BY ordering";
		$db->setQuery($query);
		$fieldgroups = $db->loadObjectList('id');

		return $fieldgroups;
	}

	static function renderAdminFormField($f, $item_id = 0)
    {
    	$app = JFactory::getApplication();

		$pluginResults = $app->triggerEvent('onDJClassifiedsAdminRenderFormFieldClass', array($f));
		$f_cl = implode(' ', $pluginResults);

		$cl_arr = array();
		if($f_cl){
			$cl_arr[] = $f_cl;
		}

		$f->class .= ' djtype_'.$f->type.($cl_arr ?' '.implode(' ', $cl_arr) : '');

		if(!$item_id){
			$f->value = $f->default_value;
		}

		if(in_array($f->type, array('inputbox', 'textarea', 'link'))){
			$f->value = $f->value ? htmlspecialchars($f->value) : $f->value;
		}else if(in_array($f->type, array('selectlist', 'radio', 'checkbox'))){
			if(substr($f->values, -1)==';'){
				$f->values = substr($f->values, 0, -1);
			}
			$f->val_arr = explode(';', $f->values);
			if($f->type == 'checkbox'){
				$f->val = $f->value ? explode(';', substr($f->value,1,-1)) : array(); // stripping the beginning & ending ';' chars
			}
		}else if($f->type == 'date'){
			if($f->value == 'current_date'){
				$f->value_date = JFactory::getDate()->format('Y-m-d');
			}else{
				$f->value_date = $f->value_date != '0000-00-00' ? $f->value_date : '';	
			}
		}else if($f->type == 'date_from_to'){
			if($f->value == 'current_date'){
				$f->value_date = JFactory::getDate()->format('Y-m-d');
				$f->value_date_to = JFactory::getDate()->format('Y-m-d');
			}else{
				$f->value_date = $f->value_date != '0000-00-00' ? $f->value_date : '';
				$f->value_date_to = $f->value_date_to != '0000-00-00' ? $f->value_date_to : '';	
			}				
		}else if($f->type == 'image'){
			$db = JFactory::getDBO();
			$sfx = $f->id;
			$dbtype = $f->source == '2' ? 'profile_field_'.$sfx : 'item_field_'.$sfx;
			$img_query = "SELECT * FROM #__djcf_images WHERE item_id=".$item_id." AND type=".$db->q($dbtype)." ORDER BY ordering LIMIT 1";
			$db->setQuery($img_query);
			$img = $db->loadObject();
			$f->img_src = $img ? JURI::root(true).$img->path.$img->name.'_th.'.$img->ext : 'data:,';
			$f->img_id = $img ? $img->id : '';
		}

		$layout = new JLayoutFile('adminformfield');
		$output = $layout->render(array('field' => $f));

		return $output;
    }

    static function getFormFieldProps($f)
	{
		$props = array();
		
		if($f->required && !in_array($f->type, array('date', 'date_from_to'))){
			$props['required'] = 'required';
			$props['aria-required'] = $f->value ? 'false' : 'true';
		}

		$prop_str = '';
		foreach($props as $prop_name => $prop_val){
			$prop_str .= ' '.$prop_name.'="'.$prop_val.'"';
		}

		return $prop_str;
	}

	static function getFormFieldClass($f, $cl = '')
	{
		$par = JComponentHelper::getParams('com_djclassifieds');

		if($f->type != 'radio' && $f->type != 'checkbox'){
            $cl .= ' inputbox';
        }
        if($f->required){
			$cl .= ' required';
		}
		if($f->type == 'inputbox'){
			if($f->numbers_only || ($f->name == 'price' && $par->get('price_only_numbers', '0'))){
				$cl .= ' validate-numeric';
			}elseif($f->input_type == 'email'){
				$cl .= ' validate-email';
			}
		}
		if($f->type == 'radio'){
			$cl .= ' validate-radio';
		}
		if($f->type == 'checkbox'){
			$cl .= ' checkboxes';
		}
		if($f->type == 'date' || $f->type == 'date_from_to'){
			$cl .= ' djcalendar';
		}
		
		return $cl;
	}

	static function convertFieldsValues(&$fields, $par = null)
	{
		$par = $par ? $par : JComponentHelper::getParams('com_djclassifieds');
		
		foreach($fields as $key => $f){
			$f_par = new JRegistry();
			$f_par->loadString($f->params);

			$show_empty = $f_par->get('show_empty','-1') != '-1' ? $f_par->get('show_empty','-1') : $par->get('show_empty_cf','1');

			if($show_empty == '0' && !$f->value && (!$f->value_date || $f->value_date=='0000-00-00') && (!$f->value_date_to || $f->value_date_to=='0000-00-00')){
				unset($fields[$key]);
				continue;
			}

			$values_to_labels = $f_par->get('values_to_labels','-1') != '-1' ? $f_par->get('values_to_labels','-1') : $par->get('cf_values_to_labels','0');
			$empty_val = $f_par->get('empty_field_text','') ? JText::_($f_par->get('empty_field_text','')) : (JText::_('COM_DJCLASSIFIEDS_FIELD_EMPTY_VALUE') != 'COM_DJCLASSIFIEDS_FIELD_EMPTY_VALUE' ? JText::_('COM_DJCLASSIFIEDS_FIELD_EMPTY_VALUE') : '---');

			if($f->date_format == 'AGE'){
				$f->label = DJClassifiedsTheme::getFieldValueToLabel($f->name.'_AGE');
			}
			$f->label = JTEXT::_($f->label);

			$f->value_conv = '';

			if($f->type=='textarea'){
				if($f->value == ''){
					$f->value_conv = $empty_val;
				}else{
					$f->value_conv = $f_par->get('textarea_newlines', '0') ? nl2br($f->value) : $f->value;
				}
				if($f_par->get('linked_value','0')){
					$f->value_conv = DJClassifiedsField::getLinkedFieldValue($f, $f->value, $f->value_conv, $f_par->get('linked_value_results_itemid',''));
				}
			}else if($f->type=='checkbox'){
				$ch_values = $f->value ? array_filter(explode(';', $f->value)) : null;
				if(!$ch_values){
					$f->value_conv = $empty_val;
				}else{
					foreach($ch_values as $chi => $chv){
						if($values_to_labels){
							$ch_values[$chi] = DJClassifiedsTheme::getFieldValueToLabel($chv);
						}
						if($f_par->get('linked_value','0')){
							$ch_values[$chi] = DJClassifiedsField::getLinkedFieldValue($f, $chv, $ch_values[$chi], $f_par->get('linked_value_results_itemid',''));
						}
					}
					$f->value_conv = implode($f_par->get('values_separator', ', '), $ch_values);
				}
			}else if($f->type=='date'){
				if($f->value_date == '0000-00-00' || empty($f->value_date)){
					$f->value_conv = $empty_val;
				}else{
					if(!$f->date_format){
						$f->date_format = 'Y-m-d';
					}
					$f->value_conv = DJClassifiedsTheme::formatDate(strtotime($f->value_date),'','',$f->date_format,false);
					if($f_par->get('linked_value','0')){
						$f->value_conv = DJClassifiedsField::getLinkedFieldValue($f, $f->value_conv, $f->value_conv, $f_par->get('linked_value_results_itemid',''));
					}
				}
			}else if($f->type=='date_from_to'){
				if(!$f->date_format){
					$f->date_format = 'Y-m-d';
				}
				$date_from = ($f->value_date != '0000-00-00' && !empty($f->value_date)) ? DJClassifiedsTheme::formatDate(strtotime($f->value_date),'','',$f->date_format,false) : $empty_val;
				$date_to = ($f->value_date_to != '0000-00-00' && !empty($f->value_date_to)) ? DJClassifiedsTheme::formatDate(strtotime($f->value_date_to),'','',$f->date_format,false) : '';
				$f->value_conv = $date_from.($date_to ? '<span class="date_from_to_sep"> - </span>'.$date_to : '');
			}else if($f->type=='link'){
				if($f->value == ''){
					$f->value_conv = $empty_val;
				}else{
					$target = $f_par->get('link_target', '') ? ' target="'.$f_par->get('link_target').'"' : '';
					$rel = $f_par->get('link_rel', '') ? ' rel="'.$f_par->get('link_rel').'"' : '';
					$scheme = $f_par->get('link_scheme', '');
					$href = ($scheme == 'http://' || $scheme == 'https://') ? str_ireplace(array('http://', 'https://'), '', $f->value) : $f->value;
					$href = $scheme.str_replace($scheme, '', $href);
					if($f->hide_on_start){
						$f->value_conv = '<span rel="'.$href.'" data-v="'.base64_encode(htmlentities($f->value)).'">'.DJClassifiedsTheme::renderLayout('svoc', array('value' => ($f_par->get('link_text') ? $f_par->get('link_text') : $f->value), 'par' => $par)).'</span>';
					}else{
						$f->value_conv = '<a'.$target.$rel.' href="'.$href.'">'.($f_par->get('link_text') ? $f_par->get('link_text') : $f->value).'</a>';
					}
				}
			}else if($f->type == 'image'){
				if($f->value == ''){
					$f->value_conv = $empty_val;
				}else{
					$f->value_conv = '<img src="'.JUri::root(true).$f->value.'">';
				}
			}else{
				if($f->value == ''){
					$f->value_conv = $empty_val;
				}else{
					$f->value_conv = $f->value;
					if(in_array($f->type, array('selectlist', 'radio'))){
						if($values_to_labels){
							$f->value_conv = DJClassifiedsTheme::getFieldValueToLabel($f->value_conv);
						}
					}
					if(in_array($f->type, array('selectlist', 'radio', 'inputbox'))){
						if($f_par->get('linked_value','0')){
							$f->value_conv = DJClassifiedsField::getLinkedFieldValue($f, $f->value, $f->value_conv, $f_par->get('linked_value_results_itemid',''));
						}
					}
				}
			}
			if($f->hide_on_start && $f->type != 'link' && $f->value_conv != $empty_val && $f_par->get('linked_value','0') != '1'){
				$f->value_conv = '<span data-v="'.base64_encode(htmlentities($f->value_conv)).'">'.DJClassifiedsTheme::renderLayout('svoc', array('value' => $f->value_conv, 'par' => $par)).'</span>';
			}
		}

		return $fields;
	}

	static function getLinkedFieldValue($field, $value_raw, $value, $itemid = null)
	{
		$results_uri = $itemid ? 'index.php?Itemid='.$itemid : ($field->source == '2' ? DJClassifiedsSEO::getViewUri('profiles') : DJClassifiedsSEO::getCategoryRoute('0:all'));
		$results_uri .= '&se='.($field->source == '2' ? 'p' : '1').'&fid='.$field->id.'&se_'.$field->id.'='.$value_raw;

		return '<a href="'.$results_uri.'" class="linked-value">'.$value.'</a>';
	}

	static function saveFieldsValues($fields, $item_id)
	{
		$app = JFactory::getApplication();
		$db = JFactory::getDBO();
		$lang = JFactory::getLanguage();
		$par = JComponentHelper::getParams('com_djclassifieds');

		if($app->isClient('site')){
			$allowed_tags = $par->get('allow_htmltags_cf','0') ? implode('', array_map(function($v){return '<'.$v.'>';}, explode(';',$par->get('allowed_htmltags_cf','div;p;span;strong;i;b;em;ul;li;ol;br;a')))) : '';
		}

		if(!empty($fields[0]) && $fields[0]->source == '2'){
			$del_query = "DELETE FROM #__djcf_fields_values_profile WHERE user_id=".$item_id;
			$query = "INSERT INTO #__djcf_fields_values_profile(`field_id`,`user_id`,`value`,`value_date`,`value_date_to`) VALUES ";
		}else{
			$del_query = "DELETE FROM #__djcf_fields_values WHERE item_id=".$item_id;
			$query = "INSERT INTO #__djcf_fields_values(`field_id`,`item_id`,`value`,`value_date`,`value_date_to`) VALUES ";
		}

		$db->setQuery($del_query." AND field_id NOT IN (SELECT id FROM #__djcf_fields WHERE edition_blocked=1)");
		$db->execute();

		// checking for form custom fields custom-placed
		if($app->isClient('site')){
			$db->setQuery("SELECT * FROM #__djcf_fields WHERE edition_blocked=1");
			$fields_edit_blocked = $db->loadObjectList();
			foreach($fields_edit_blocked as $f_b){
				if($app->input->post->exists($f_b->name) || $app->input->post->exists($f_b->name.'_djhelper') || $app->input->files->get('imgInp'.$f_b->id)){
					$db->setQuery($del_query." AND field_id=".$f_b->id);
					$db->execute();
					$fields[] = $f_b;
				}
			}
		}
		
		$ins_arr = array();
		foreach($fields as $f){
			if($f->type=='checkbox'){
				if($app->input->post->exists($f->name)){
					$f_value = '';
					$chx_arr = $app->input->post->getVar($f->name);
					if($chx_arr){
						$f_value = ';'.implode(';', $chx_arr).';';
					}
					$ins_arr[] = "(".$f->id.",".$item_id.",'".$db->escape($f_value)."',NULL,NULL)";
				}elseif($app->input->post->exists($f->name.'_djhelper')){ // helper field for submitting empty checkbox values										
					$ins_arr[] = "(".$f->id.",".$item_id.",'',NULL,NULL)";
				}
			}else if($f->type=='date'){
				if($app->input->post->exists($f->name)){							
					$f_var = $app->input->getVar($f->name);							
					if($app->isClient('site') && $f_var && $f_var!='0000-00-00 00:00:00' && $f->date_format){
						$f_var = DJClassifiedsTheme::dateDBConvert($f_var, $f->date_format);
					}
					$f_var = $f_var ? $f_var : '0000-00-00 00:00:00';
					$ins_arr[] = "(".$f->id.",".$item_id.",'','".$db->escape($f_var)."',NULL)";
				}
			}else if($f->type=='date_from_to'){
				if($app->input->post->exists($f->name) || $app->input->post->exists($f->name.'_to')){							
					$f_var = $app->input->getVar($f->name);
					if($app->isClient('site') && $f_var && $f_var!='0000-00-00 00:00:00' && $f->date_format){
						$f_var = DJClassifiedsTheme::dateDBConvert($f_var, $f->date_format);
					}
					$f_var = $f_var ? $f_var : '0000-00-00 00:00:00';
					$f_var_to = $app->input->getVar($f->name.'_to');
					if($app->isClient('site') && $f_var_to && $f_var_to!='0000-00-00 00:00:00' && $f->date_format){
						$f_var_to = DJClassifiedsTheme::dateDBConvert($f_var_to, $f->date_format);
					}
					$f_var_to = $f_var_to ? $f_var_to : '0000-00-00 00:00:00';
					$ins_arr[] = "(".$f->id.",".$item_id.",'','".$db->escape($f_var)."','".$db->escape($f_var_to)."')";
				}
			}else if($f->type=='image'){
				$f_par = new JRegistry();
				$f_par->loadString($f->params);

				$f_var = '';
				$new_icon = $app->input->files->get('imgInp'.$f->id);

				if($app->isClient('site')){
					$img_maxsize = $f_par->get('image_maxsize', 0);
					$img_maxsize = $img_maxsize * 1024 * 1024;
					
					if($img_maxsize && $new_icon['size'] > $img_maxsize){
						$app->enqueueMessage(JText::_('COM_DJCLASSIFIEDS_TO_BIG_IMAGE').': "'.$new_icon['name'].'"', 'error');
						continue;
					}
				}

				if($f->source == '2'){
					$dbtype = 'profile_field_'.$f->id;
				}else{
					$dbtype = 'item_field_'.$f->id;
				}

				if($new_icon){							
					$img_query = "SELECT * FROM #__djcf_images WHERE item_id=".$item_id." AND type=".$db->q($dbtype)." ORDER BY ordering LIMIT 1";
					$db->setQuery($img_query);
					$old_icon = $db->loadObject();

					if($old_icon){
						if($new_icon['size'] || $app->input->get('del_img'.$f->id)){
							if(JFile::exists(JPATH_SITE.$old_icon->path.$old_icon->name.'.'.$old_icon->ext)){
								JFile::delete(JPATH_SITE.$old_icon->path.$old_icon->name.'.'.$old_icon->ext);
							}		
							if(JFile::exists(JPATH_SITE.$old_icon->path.$old_icon->name.'_th.'.$old_icon->ext)){
								JFile::delete(JPATH_SITE.$old_icon->path.$old_icon->name.'_th.'.$old_icon->ext);
							}
							
							$img_query = "DELETE FROM #__djcf_images WHERE id=".$old_icon->id;
							$db->setQuery($img_query);
							$db->execute();
						}else{
							$f_var = $old_icon->path.$old_icon->name.'_th.'.$old_icon->ext;
						}
					}

					if(substr($new_icon['type'], 0, 5) == 'image'){	
						$icon_name = str_ireplace(' ', '_',$new_icon['name']);
						$icon_name = $lang->transliterate($icon_name);
						$icon_name = strtolower($icon_name);
						$icon_name = JFile::makeSafe($icon_name);
						$icon_name = $item_id.'_'.$icon_name;

						if($f->source == '2'){
							$img_path = $par->get('profile_img_path','/components/com_djclassifieds/images/profile/');
						}else{
							$img_path = $par->get('advert_img_path', '/components/com_djclassifieds/images/item/');
						}
						$img_path = '/'.rtrim(ltrim($img_path, '/'), '/').'/';
						$img_path .= 'field/'.$f->id.'/';
						
						$new_img_path_rel = DJClassifiedsImage::generatePath($img_path, $item_id);

						$path = JPATH_SITE.$new_img_path_rel.$icon_name;
						
						move_uploaded_file($new_icon['tmp_name'], $path);

						$nw = (int)$f_par->get('image_th_width', 150);
						$nh = (int)$f_par->get('image_th_height', 0);
					
						$name_parts = pathinfo($path);
						$img_name = $name_parts['filename'];
						$img_ext = $name_parts['extension'];
						$new_path = JPATH_SITE.$new_img_path_rel;
			
						DJClassifiedsImage::makeThumb($path, $new_path.$img_name.'_th.'.$img_ext, $nw, $nh, false, true, 0);
						if($par->get('store_org_img', '1') == '0'){
							JFile::delete($path);
						}

						$img_query = "INSERT INTO #__djcf_images(`item_id`,`type`,`name`,`ext`,`path`,`caption`,`ordering`) VALUES ";
						$img_query .= "(".$item_id.",".$db->q($dbtype).",'".$img_name."','".$img_ext."','".$new_img_path_rel."','','1')";
						$db->setQuery($img_query);
						$db->execute();

						$f_var = $new_img_path_rel.$img_name.'_th.'.$img_ext;
					}

					$ins_arr[] = "(".$f->id.",".$item_id.",'".$f_var."',NULL,NULL)";
				}
			}else{					
				if($app->input->post->exists($f->name)){
					$f_var = $app->input->get($f->name, '', 'RAW');

					if($app->isClient('site')){
						$f_var = strip_tags($f_var, $allowed_tags);
					}
																
					$ins_arr[] = "(".$f->id.",".$item_id.",'".$db->escape($f_var)."',NULL,NULL)";
				}elseif($app->input->post->exists($f->name.'_djhelper')){ // helper field for submitting empty radio values										
					$ins_arr[] = "(".$f->id.",".$item_id.",'',NULL,NULL)";
				}
			}
		}

		if($ins_arr){
			$query .= implode(', ', $ins_arr);
			$db->setQuery($query);
			$db->execute();
		}
	}

	static function getFieldValue($field_id, $item_id = null, $obj = false)
	{
		$db = JFactory::getDBO();

		if(is_numeric($field_id)){
			$query = "SELECT * FROM #__djcf_fields WHERE id=".$field_id;
		}else{
			$query = "SELECT * FROM #__djcf_fields WHERE name=".$db->q($field_id);
		}
		$db->setQuery($query);
		$field = $db->loadObject();

		if(!$field){
			return false;
		}

		if($field->source == '2'){
			$fv_table = '#__djcf_fields_values_profile';
			$fv_item_id = 'user_id';
		}else{
			$fv_table = '#__djcf_fields_values';
			$fv_item_id = 'item_id';
		}

		$query = "SELECT fv.*, f.* "
		."FROM #__djcf_fields f "
		."LEFT JOIN ".$fv_table." fv ON f.id=fv.field_id AND fv.".$fv_item_id."=".(is_numeric($item_id) ? $item_id : 0)." "
		."WHERE f.id=".$field->id;
		$db->setQuery($query);
		$fv = $db->loadObject();

		if($fv){
			if($obj){
				return $fv;
			}else{
				if(in_array($fv->type, array('checkbox', 'radio')) && $fv->value !== null){
					$val_arr = array_filter(explode(';', $fv->value));
					return implode(', ', $val_arr);
				}elseif($fv->type == 'date' && $fv->value_date !== null){
					return $fv->value_date;
				}elseif($fv->type == 'date_from_to' && $fv->value_date_ !== null){
					return $fv->value_date.' - '.$fv->value_date_to;
				}else{
					return $fv->value;
				}
			}
		}
	}

	static function getProfileFieldValue($field_id, $user_id = null, $obj = false) // backward compatibility
	{
		return self::getFieldValue($field_id, $user_id, $obj);
	}

	static function getAskFormFieldsForEmail()
	{
		$app = JFactory::getApplication();
		$db = JFactory::getDBO();

		$query = "SELECT * FROM #__djcf_fields WHERE published=1 AND source=3 AND edition_blocked=0 ORDER BY ordering";
		$db->setQuery($query);
		$fields = $db->loadObjectList();
		
		$custom_fields_msg = '';
		foreach($fields as $f){
			$f_val = $app->input->getStr($f->name);
			if(is_array($f_val)){
				$custom_fields_msg .= $f->label.": ".implode(', ', $f_val)."<br />"; 
			}else if($f_val){
				$custom_fields_msg .= $f->label.": ".$f_val."<br />";
			}
		}

		return $custom_fields_msg;
	}

	static function getAskFormFieldsEmailCopy($item_id = null, $par = null)
	{
		$app = JFactory::getApplication();
		$db = JFactory::getDBO();
		$user = JFactory::getUser();
		$djmodel = new DJClassifiedsModel();
		$par = $par ? $par : JComponentHelper::getParams('com_djclassifieds');

		$main_query = $db->getQuery(true);
		$main_query->select('f.*')
			->from('#__djcf_fields f')
			->where('f.published = 1')
			->where('f.askform_cc > 0')
			->order('f.ordering');

		if($item_id){
			$item = $djmodel->getItemById($item_id);
			$app->triggerEvent('onDJClassifiedsPrepareItem', array(&$item, &$par, 'askform'));
		}else{
			$main_query->where('f.source IN (2,3)');
		}

		$db->setQuery($main_query);
		$cc_fields = $db->loadObjectList();
		
		$fields = array();
		$cc = array();
		$bcc = array();
		foreach($cc_fields as $f){
			$query = clone $main_query;

			if($f->source == '0'){
				$catid_arr = array($item->cat_id);
				if(!empty($item->extra_cats)){
					foreach($item->extra_cats as $extra_cat){
						$catid_arr[] = $extra_cat->id;
					}
				}
				
				$query->select('fv.*')
					->join('LEFT', '#__djcf_fields_values fv ON fv.field_id = f.id AND fv.item_id = '.$item_id)
					->join('INNER', '#__djcf_fields_xref fx ON f.id = fx.field_id AND fx.cat_id IN ('.implode(', ', $catid_arr).')')
					->where('f.source = 0');
				if(!empty($item->extra_cats)){
					$query->group('fx.field_id');
				}
			}elseif($f->source == '1'){
				$query->select('fv.*')
					->join('LEFT', '#__djcf_fields_values fv ON fv.field_id = f.id AND fv.item_id = '.$item_id)
					->where('f.source = 1');
			}elseif($f->source == '2'){
				$query->select('fv.*')
					->join('LEFT', '#__djcf_fields_values_profile fv ON fv.field_id = f.id AND fv.user_id = '.$user->id)
					->where('f.source = 2');
			}elseif($f->source == '3'){
				$query->where('f.source = 3');
			}

			$db->setQuery($query);
			$fields = array_merge($fields, $db->loadObjectList());
		}

		foreach($fields as $f){
			if(!DJClassifiedsAccess::hasAccessToFormField($f, ($f->source == '2' ? $djmodel->getProfileRow($user->id)->group_id : null))){
				continue;
			}
			if($f->source == '0' || $f->source == '1'){
				$load_default = $f->item_id === null;
			}elseif($f->source == '2'){
				$load_default = $f->user_id === null;
			}else{
				$load_default = true;
			}
			if($load_default){
				DJClassifiedsField::setFieldDefaultValue($f, $user->id);
			}
			if($f->source == '3'){
				$f_val = $app->input->getStr($f->name);
				if($f_val){
					$f->value = $f_val;
				}
			}
			if(!filter_var($f->value, FILTER_VALIDATE_EMAIL)){
				continue;
			}

			if($f->askform_cc == '1'){
				$cc[] = $f->value;
			}else{
				$bcc[] = $f->value;
			}
		}

		return array(
			'cc' => $cc,
			'bcc' => $bcc
		);
	}

	static function renderSearchFormField($f, $mod_id)
	{
		$app = JFactory::getApplication();
		$par = clone JComponentHelper::getParams('com_djclassifieds'); // clone to avoid param conflicts due to 'cf_values_to_labels' set
	
		$f_par = new JRegistry();
		$f_par->loadString($f->params);
        $f->par = $f_par;

		$app->triggerEvent('onDJClassifiedsRenderSearchFormField', array(&$f, $mod_id, &$par));
	
		$f_cl = implode(' ', $app->triggerEvent('onDJClassifiedsRenderFormFieldClass', array($f)));
		$cl_arr = array();
		if($f_cl){
			$cl_arr[] = $f_cl;
		}
		if($f->search_type=='checkbox_accordion_o'){
			$cl_arr[] = 'djfields_accordion_o';
		}else if($f->search_type=='checkbox_accordion_c'){
			$cl_arr[] = $app->getUserState('se_'.$f->id,'') ? 'djfields_accordion_o' : 'djfields_accordion_c';
		}
		if($f->group_id){
			$cl_arr[] = 'group_'.implode(' group_', explode(',', $f->group_id));
		}
		if($f->search_type=='checkbox' && $f->par->get('search_show_in_modal','0')){
			$cl_arr[] = 'djshow_in_modal';
		}
		if($f->class){
			$cl_arr[] = $f->class;
		}
		$f->cl = 'djse_type_'.$f->search_type.' djse_field_'.$f->id.' djse_'.$f->name.($cl_arr ? ' '.implode(' ', $cl_arr) : '');
	
		if($f->type=='date' || $f->type=='date_from_to'){
			if($f->search_type=='inputbox'){
				$f->val = $app->getUserState('se_'.$f->id,'')!='' ? $app->getUserState('se_'.$f->id,'') : '';
			}else if($f->search_type=='inputbox_min_max'){
				$f->val = $app->getUserState('se_'.$f->id.'_min','');
				$f->val2 = $app->getUserState('se_'.$f->id.'_max','');
			}
			if($f->date_format == 'AGE'){
				$f->type = 'inputbox';
				$f->label = DJClassifiedsTheme::getFieldValueToLabel($f->name.'_AGE');
			}
		}else{
			if(!empty($f->par->get('search_values_assigned')) && in_array($f->search_type, array('select', 'radio', 'checkbox', 'checkbox_accordion_o', 'checkbox_accordion_c'))){
				self::filterAssignedSearchValues($f);
				if(empty($f->search_value1)){
					return null;
				}
			}
			if($f->search_type=='inputbox'){	
				$f->val = $app->getUserState('se_'.$f->id,'');
			}else if($f->search_type=='select' || $f->search_type=='radio'){														
				if(substr($f->search_value1, -1)==';'){
					$f->search_value1 = substr($f->search_value1, 0,-1);
				}
				$f->val_arr = explode(';', $f->search_value1);
				$f->val = $app->getUserState('se_'.$f->id,'');
			}else if($f->search_type=='checkbox' || $f->search_type=='checkbox_accordion_o' || $f->search_type=='checkbox_accordion_c'){
				if(substr($f->search_value1, -1)==';'){
					$f->search_value1 = substr($f->search_value1, 0,-1);
				}
				$f->val_arr = explode(';', $f->search_value1);
				$f->val = explode(';', str_ireplace(',', ';', substr($app->getUserState('se_'.$f->id,''),1,-1)));
				$f->val_arr2 = $f->val; // backward compatibility
			}else if($f->search_type=='inputbox_min_max'){
				$f->val = $app->getUserState('se_'.$f->id.'_min','');
				$f->val2 = $app->getUserState('se_'.$f->id.'_max','');
			}else if($f->search_type=='select_min_max'){
				if(substr($f->search_value1, -1)==';'){
					$f->search_value1 = substr($f->search_value1, 0,-1);
				}
				$f->val_arr = explode(';', $f->search_value1);
				$f->val = $app->getUserState('se_'.$f->id.'_min','');
	
				if(substr($f->search_value2, -1)==';'){
					$f->search_value2 = substr($f->search_value2, 0,-1);
				}
				$f->val_arr2 = explode(';', $f->search_value2);
				$f->val2 = $app->getUserState('se_'.$f->id.'_max','');
				if(!$f->val2){
					$f->val2 = $f->val_arr2 && reset($f->val_arr2) != '' ? end($f->val_arr2) : ''; // if first value not empty
				}
			}else if($f->search_type=='date_min_max'){
				$f->val = $app->getUserState('se_'.$f->id.'_min','');
				$f->val2 = $app->getUserState('se_'.$f->id.'_max','');
			}
		}

		if($f->par->get('values_to_labels','-1') != '-1'){
			$par->set('cf_values_to_labels',$f->par->get('values_to_labels','-1'));
		}
	
		return DJClassifiedsTheme::renderLayout('searchformfield', array(
			'f' => $f,
			'mod_id' => $mod_id,
			'par' => $par
		));
	}

	static $_search_values_count = array();
	static $_search_values_count_profile = array();

	static function filterAssignedSearchValues(&$f)
	{
		if($f->source == '2'){
			self::_loadSearchValuesCount($f, self::$_search_values_count_profile, true);
			$check_arr = self::$_search_values_count_profile;
		}else{
			self::_loadSearchValuesCount($f, self::$_search_values_count);
			$check_arr = self::$_search_values_count;
		}

		$val_arr = explode(';', $f->search_value1);
		foreach($val_arr as $key => $val){
			if($val && !isset($check_arr[$f->id][$val])){
				unset($val_arr[$key]);
			}
		}

		$f->search_value1 = implode(';', $val_arr);
	}

	static function _loadSearchValuesCount($field, &$load_arr, $profile = false)
	{
		if(empty($load_arr)){
			$app = JFactory::getApplication();
			$db = JFactory::getDBO();

			$f_par = new JRegistry();
			$f_par->loadString($field->params);
			$cat_id = 0;
			if(!$profile && $f_par->get('search_values_assigned_include_cat','0')){
				if($field->cat_id){
					$cat_id = $field->cat_id;
				}elseif($cid = $app->input->getInt('cid')){
					$cat_id = $cid;
				}elseif($se_cats = DJClassifiedsTheme::getIdFromTree($app->input->getVar('se_cats'))){
					$cat_id = $se_cats;
				}
				if($cat_id){
					$cat_ids_arr = array_map(function ($v){
						return $v->id;
					}, DJClassifiedsCategory::getSubCat($cat_id));
					$cat_ids = implode(',',$cat_ids_arr);
				}
			}

			$query = "SELECT fv.field_id, REPLACE(REPLACE(GROUP_CONCAT(fv.value SEPARATOR ';'),';;',';'),';;',';') vals "
					.($profile ? "FROM #__djcf_fields_values_profile fv " : "FROM #__djcf_fields_values fv ")
					."INNER JOIN #__djcf_fields f ON fv.field_id=f.id "
					.($profile ? "" : "INNER JOIN #__djcf_items i ON fv.item_id=i.id AND i.published=1 AND i.blocked=0 AND i.date_exp>".$db->q(JFactory::getDate()->toSQL())." ")
					.(JPluginHelper::isEnabled('djclassifieds', 'multicategories') ? "LEFT JOIN #__djcf_items_categories ic ON i.id=ic.item_id " : "")
					."WHERE fv.value != '' AND f.in_search=1 AND f.search_type IN ('select','radio','checkbox','checkbox_accordion_o','checkbox_accordion_c') ".($cat_id ? "AND (i.cat_id IN (".$cat_ids.")".(JPluginHelper::isEnabled('djclassifieds', 'multicategories') ? " OR ic.cat_id IN (".$cat_ids.")" : "").") " : "")
					."GROUP BY fv.field_id";
			$db->setQuery($query);
			$vals_assoc = $db->loadAssocList('field_id', 'vals');
	
			foreach($vals_assoc as $field_id => $vals){
				$vals_arr = array_filter(explode(';',$vals));
				$count_arr = array();
				foreach($vals_arr as $val){
					if(!isset($count_arr[$val])){
						$count_arr[$val] = 0;
					}
					$count_arr[$val] += 1;
				}
				//arsort($count_arr);
				$load_arr[$field_id] = $count_arr;
			}
		}
	}

    public static function renderFormField($f, $id = 0, $post_data = null, $show_field_only = false)
    {
		if(!$f){
			return;
		}

    	$app = JFactory::getApplication();
		$par = clone JComponentHelper::getParams('com_djclassifieds'); // clone to avoid param conflicts due to 'cf_values_to_labels' set
		$db = JFactory::getDBO();
		
		$f_par = new JRegistry();
		$f_par->loadString($f->params);
        $f->par = $f_par;

		$f->value = isset($f->value) ? $f->value : null;
		$f->value = in_array($f->type, array('inputbox', 'textarea', 'link')) && $f->value ? htmlspecialchars($f->value) : $f->value;

		$app->triggerEvent('onDJClassifiedsRenderFormField', array(&$f, $id, &$par));

		$f_cl = implode(' ', $app->triggerEvent('onDJClassifiedsRenderFormFieldClass', array($f)));
		$cl_arr = array();
		if($f_cl){
			$cl_arr[] = $f_cl;
		}
		if($f->group_id){
			$cl_arr[] = 'group_'.implode(' group_', explode(',', $f->group_id));
		}
		if($f->type=='checkbox' && $f->par->get('show_in_modal','0')){
			$cl_arr[] = 'djshow_in_modal';
		}
		if($f->class){
			$cl_arr[] = $f->class;
		}

		$f->wrapper_cl = 'djtype_'.$f->type.' djrow_'.$f->name.($cl_arr ? ' '.implode(' ', $cl_arr) : '');
		$f->cl = DJClassifiedsField::getFormFieldClass($f);
		$f->props = DJClassifiedsField::getFormFieldProps($f);

		if($f->attribs){ // getting class from attributes
			$attr_arr = array_filter(explode(' ', $f->attribs));
			foreach($attr_arr as $key => $attr){
				if(strpos($attr, 'class=') !== false){
					$f->cl .= ' '.str_replace(array('class=','"','\''), '', $attr);
					unset($attr_arr[$key]);
				}
			}
			$f->attribs = implode(' ', $attr_arr);
		}

		$f->val = $f->value;
		if($f->type=='inputbox' && $f->source == 0 && $f->name=='price' && $id){
			$djmodel = new DJClassifiedsModel();
			$item = $djmodel->getItemById($id);
		}else if(in_array($f->type, array('selectlist', 'radio', 'checkbox'))){
			if(substr($f->values, -1)==';'){
				$f->values = substr($f->values, 0, -1);
			}
			$f->val_arr = explode(';', $f->values);
			if($f->type == 'checkbox'){
				$f->val = $f->value ? explode(';', substr($f->value,1,-1)) : array(); // stripping the beginning & ending ';' chars
			}
		}else if($f->type=='date'){
			if($f->value == 'current_date'){
				$f->val = JFactory::getDate()->format('Y-m-d');
			}else{
				$f->val = isset($f->value_date) ? $f->value_date : '';
			}
			$f->val = $f->val == '0000-00-00' ? '' : $f->val;
		}else if($f->type=='date_from_to'){
			if($f->value == 'current_date'){
				$f->val = JFactory::getDate()->format('Y-m-d');
				$f->val2 = JFactory::getDate()->format('Y-m-d');
			}else{
				$f->val = isset($f->value_date) ? $f->value_date : '';
				$f->val2 = isset($f->value_date_to) ? $f->value_date_to : '';
			}
			$f->val = $f->val == '0000-00-00' ? '' : $f->val;
			$f->val2 = $f->val2 == '0000-00-00' ? '' : $f->val2;
		}else if($f->type=='image'){
			$dbtype = $f->source == '2' ? 'profile_field_'.$f->id : 'item_field_'.$f->id;
			$img_query = "SELECT * FROM #__djcf_images WHERE item_id=".$id." AND type=".$db->q($dbtype)." ORDER BY ordering LIMIT 1";
			$db->setQuery($img_query);
			$img = $db->loadObject();

			$f->img_src = $img ? JURI::root(true).$img->path.$img->name.'_th.'.$img->ext : 'data:,';
			$f->img_id = $img ? $img->id : '';
		}

		if($post_data){
			if(!empty($post_data[$f->name])){
				$f->val = $post_data[$f->name];
			}
			if(!empty($post_data[$f->name.'_to'])){
				$f->val = $post_data[$f->name.'_to'];
			}
		}

		if($f->par->get('values_to_labels','-1') != '-1'){
			$par->set('cf_values_to_labels',$f->par->get('values_to_labels','-1'));
		}

		return DJClassifiedsTheme::renderLayout('formfield', array(
			'f' => $f,
			'item' => !empty($item) ? $item : null,
			'show_field_only' => $show_field_only,
			'par' => $par
		));
    }

	static function setFieldDefaultValue(&$f, $user_id = null)
	{
		if($f->profile_source && $user_id){
			if($f->profile_source > 0){
				$db = JFactory::getDBO();		
				$query = "SELECT * FROM #__djcf_fields_values_profile WHERE field_id=".$f->profile_source." AND user_id=".$user_id;
				$db->setQuery($query);
				$fv = $db->loadObject();
				if($fv){
					$f->value = $fv->value;
					$f->value_date = $fv->value_date;
					$f->value_date_to = $fv->value_date_to;
				}
			}else{
				$user = JFactory::getUser($user_id);
				if($f->profile_source == '-1'){
					$f->value = $user->email;
				}elseif($f->profile_source == '-2'){
					$f->value = $user->name;
				}elseif($f->profile_source == '-3'){
					$f->value = $user->username;
				}
			}
		}

		if(empty($f->value) && $f->default_value){
			$f->value = $f->type == 'checkbox' ? ';'.$f->default_value.';' : $f->default_value;
		}
	}

	static $_overwritable_fields = array(
		'show_price' => 'price',
		'show_contact' => 'contact',
		'show_address' => 'address',
		'show_postcode' => 'postcode',
		'show_website' => 'website',
		'show_video' => 'video',
		'show_introdesc' => 'intro_desc',
		'show_description' => 'description',
		'seo_keywords_user_edit' => 'metakey',
		'seo_metadesc_user_edit' => 'metadesc',
		'email_for_guest' => 'email',
		'show_regions' => 'region_id',
		'show_types' => 'type_id'
	);

	static function getOverwritableFieldNames($db_quoted = false)
	{
		$fields = self::$_overwritable_fields;
		if($db_quoted){
			$fields = array_map(function($v){return JFactory::getDBO()->q($v);}, $fields);
		}
		return $fields;
	}

	static function clearOverwritableFields(&$row)
	{
		$db = JFactory::getDBO();
		$query = $db->getQuery(true);
		$query->select('f.*')
			->from('#__djcf_fields f')
			->where('f.source IN (0,1)')
			->where('f.published = 1')
			->where('f.name IN ('.implode(',', DJClassifiedsField::getOverwritableFieldNames(true)).')');
		$db->setQuery($query);
		$fields = $db->loadObjectList();

		foreach($fields as $f){
			$row->{$f->name} = strpos($f->name, '_id') !== false ? '0' : '';
		}
	}

	static function convertOverwritableFieldsValues(&$item, $par)
	{
		$db = JFactory::getDBO();
		$query = $db->getQuery(true);
		$query->select(array('fv.*', 'f.*'))
			->from('#__djcf_fields f')
			->join('INNER', '#__djcf_fields_values fv ON f.id = fv.field_id AND fv.item_id = '.$item->id)
			->where('f.source IN (0,1)')
			->where('f.published = 1')
			->where('f.name IN ('.implode(',', DJClassifiedsField::getOverwritableFieldNames(true)).')')
			->where('f.name NOT IN ("type_id","region_id")');
		$db->setQuery($query);
		$fields = $db->loadObjectList();

		DJClassifiedsAccess::filterFieldsByGroupAccess($fields);
		DJClassifiedsField::convertFieldsValues($fields, $par);

		foreach($fields as $f){
			$item->{$f->name} = ($f->value || $f->value_date != '0000-00-00' || $f->value_date_to != '0000-00-00') ? $f->value_conv : '';
		}
	}

	static function setParamsForOverwritableFields(&$par)
	{
		$db = JFactory::getDBO();
		foreach(self::$_overwritable_fields as $paramname => $fieldname){
			$query = "SELECT count(*) FROM #__djcf_fields WHERE published=1 AND source IN (0,1) AND name=".$db->q($fieldname);
			$db->setQuery($query);
			$field_exists = $db->loadResult();
			if($field_exists){
				$par->set($paramname, '0');
			}
		}
	}

	static function getFieldOptionValue($val)
	{
		$val_arr = explode('|', $val);
		return count($val_arr) == 2 ? $val_arr : array($val, $val);
	}
}
Site is undergoing maintenance

PACJA Events

Maintenance mode is on

Site will be available soon. Thank you for your patience!