Sindbad~EG File Manager

Current Path : /var/www/ispania.gr/plugins/rsdirectory/importsobipro/
Upload File :
Current File : /var/www/ispania.gr/plugins/rsdirectory/importsobipro/importsobipro.php

<?php
/**
 * @package RSDirectory!
 * @copyright (C) 2013-2021 www.rsjoomla.com
 * @license GPL, http://www.gnu.org/licenses/gpl-3.0.html
 */

// No direct access.
defined('_JEXEC') or die('Restricted access');

/**
 * RSDirectory! SobiPro Import Plugin.
 */
class plgRsdirectoryImportSobiPro extends JPlugin
{
    const IMPORT_OPTION = 'sobipro';
    const PLUGIN = 'importsobipro';
    const EXTENSION = 'plg_rsdirectory_importsobipro';
    const OPTION = 'PLG_RSDIRECTORY_IMPORTSOBIPRO_NAME';
	const VERSION = '1.1.0';
	const MINIMUM_SOBIPRO_VERSION = '1.1.0';
		
	/**
	 * Automatically load language files.
	 *
	 * @access protected
	 *
	 * @var boolean
	 */
	protected $autoloadLanguage = true;
		
	/**
	 * An array of sections that need to be processed.
	 *
	 * @access protected
	 *
	 * @static
	 *
	 * @var array
	 */
	protected static $sections = array(
		0 => 'sections',
		1 => 'categories',
		2 => 'fields',
		3 => 'entries',
	);
		
	/**
	 * An array of field types that will imported.
	 *
	 * @access protected
	 *
	 * @static
	 *
	 * @var array
	 */
	protected static $accepted_field_types = array(
		'inbox',
		'email',
		'url',
		'textarea',
		'select',
		'multiselect',
		'chbxgroup',
		'radio',
		'image',
		'geomap',
	);
		
	/**
	 * An array of SobiPro image sizes names.
	 *
	 * @access protected
	 *
	 * @static
	 *
	 * @var array
	 */
	protected static $image_sizes = array(
		'original',
		'image',
		'thumb',
		'ico',
	);
        
    /**
     * Can the plugin run?
     *
     * @access public
     * 
     * @return bool
     */
    public function canRun()
    {
		$app = JFactory::getApplication();
		$db = JFactory::getDbo();
			
		// Get extension data.
		$query = $db->getQuery(true)
		       ->select('*')
			   ->from( $db->qn('#__extensions') )
			   ->where( $db->qn('element') . ' = ' . $db->q('com_sobipro') );
			   
		$db->setQuery($query);
			
        return file_exists(JPATH_ADMINISTRATOR . '/components/com_rsdirectory/helpers/rsdirectory.php') &&
			   $app->isClient('administrator') && $app->input->get('option') == 'com_rsdirectory' &&
			   $db->loadObject();
    }
     
    /**
     * Add the current import option to the import options list.
     *
     * @access public
     * 
     * @return string
     */
    public function onRsdirectoryaddImportOptions()
    {
		if ( $this->canRun() )
			return JHtml::_( 'select.option', self::IMPORT_OPTION, JText::_(self::OPTION) );
    }
		
	/**
	 * Display import fieldset.
	 *
	 * @access public
	 */	
	public function onRsdirectoryDisplayImportFieldset()
	{
		if ( !$this->canRun() )
			return;
			
		JHtml::_('script', 'plg_rsdirectory_importsobipro/script.js', array('relative' => true, 'version' => 'auto'));

		$has_pce = self::hasEntriesStoredInParentCategories();
		$has_mce = self::hasEntriesStoredInMultipleCategories();


		JForm::addFormPath(__DIR__ . '/forms');

		$form = JForm::getInstance( 'plg_rsdirectory_importsobipro.importoptions', 'importoptions', array('control' => 'jform'));

		$pce_fields = array('pce', 'pce_rsdirectory_category', 'pce_sobipro_category');
		$mce_fields = array('mce', 'mce_rsdirectory_category', 'mce_sobipro_category');

		// remove and add conditions to the fields
		foreach ($form->getFieldsets() as $fieldset)
		{
			if ($fields = $form->getFieldset($fieldset->name))
			{
				foreach ($fields as $field)
				{
					// if there is no pce do not render them
					if (in_array($field->fieldname, $pce_fields) && !$has_pce)
					{
						$form->removeField($field->fieldname, 'sobipro');
					}

					// if there is no pce and no mce do not render the mce fields
					if (in_array($field->fieldname, $mce_fields) && !$has_pce && !$has_mce)
					{
						$form->removeField($field->fieldname, 'sobipro');
					}

					// if pce are present but no mce the only case that mce must be displayed is for pce:lowest_subcategories option
					if (in_array($field->fieldname, $mce_fields) && $has_pce && !$has_mce)
					{
						$current_showon = $form->getFieldAttribute($field->fieldname, 'showon', null, 'sobipro');
						$new_showon = 'pce:lowest_subcategories';
						if (!empty($current_showon))
						{
							$new_showon .='[AND]'.$current_showon;
						}

						$form->setFieldAttribute($field->fieldname, 'showon', $new_showon, 'sobipro');
					}
				}
			}
		}
		?>
			
		<fieldset id="sobipro" class="import-fieldset hide">

			<?php
			foreach ($form->getFieldsets() as $fieldset)
			{
				if ($fields = $form->getFieldset($fieldset->name))
				{
					foreach ($fields as $field)
					{
						echo $field->renderField();
					}
				}
			}
			?>
				
		</fieldset>
			
		<?php
			
		JText::script('PLG_RSDIRECTORY_IMPORTSOBIPRO_REQUIRED_FIELDS_ERROR');
	}
		
	/**
	 * Import.
	 *
	 * @access public
	 *
	 * @param object $vars
	 */
	public function onRsdirectoryImport($vars)
	{
		// Do a few checks.
		if ( !$this->canRun() || empty($vars->import_from) || $vars->import_from != self::IMPORT_OPTION || !$vars->import_action )
			return;
			
		switch ($vars->import_action)
		{
			case 'verify':
					
				$this->verify($vars);
				break;
					
			case 'measure':
					
				$this->measure($vars);
				break;
					
			case 'import':
					
				$this->import($vars);
				break;
		}
	}
		
	/**
	 * Method to verify import data.
	 *
	 * @access protected
	 *
	 * @param object $vars
	 */
	protected function verify($vars)
	{
		$messages = $vars->response['messages'];
			
		$db = JFactory::getDbo();
			
		// Get extension data.
		$query = $db->getQuery(true)
		       ->select('*')
			   ->from( $db->qn('#__extensions') )
			   ->where( $db->qn('element') . ' = ' . $db->q('com_sobipro') );
			   
		$db->setQuery($query);
			
		$extension = $db->loadObject();
			
		if ( empty($extension) )
		{
			$messages[] = array(
				'message' => JText::_('PLG_RSDIRECTORY_IMPORTSOBIPRO_COMPONENT_NOT_INSTALLED'),
				'type' => 'error',
				'id' => null,
			);
		}
		else
		{
			$messages[] = array(
				'message' => JText::_('PLG_RSDIRECTORY_IMPORTSOBIPRO_COMPONENT_INSTALLED'),
				'type' => 'success',
				'id' => null,
			);
				
			$xmlPath = JPATH_ADMINISTRATOR.'/components/com_sobipro/com_sobipro.xml';
			
			$version = false;
			if (file_exists($xmlPath) && ($xml = file_get_contents($xmlPath))) {
				if (preg_match('#<version>(.*?)<\/version>#', $xml, $match)) {
					$version = $match[1];
				}
			} elseif (!empty($extension->manifest_cache) && ($manifest_cache = json_decode($extension->manifest_cache)) && isset($manifest_cache->version)) {
				$version = $manifest_cache->version;
			}
				
			if ( empty($version) )
			{
				$messages[] = array(
					'message' => JText::_('PLG_RSDIRECTORY_IMPORTSOBIPRO_UNKNOWN_VERSION'),
					'type' => 'error',
					'id' => null,
				);
			}
			else if ( version_compare(self::MINIMUM_SOBIPRO_VERSION, $version) > 0 )
			{
				$messages[] = array(
					'message' => JText::sprintf('PLG_RSDIRECTORY_IMPORTSOBIPRO_VERSION_INCOMPATIBLE', $version),
					'type' => 'error',
					'id' => null,
				);
			}
			else
			{
				$messages[] = array(
					'message' => JText::sprintf('PLG_RSDIRECTORY_IMPORTSOBIPRO_VERSION_OK', $version),
					'type' => 'success',
					'id' => null,
				);
					
				$vars->response['action'] = 'measure';
			}
		}
			
		$vars->response['messages'] = $messages;
	}
		
	/**
	 * Method to measure import data.
	 *
	 * @access protected
	 *
	 * @param object $vars
	 */
	public function measure($vars)
	{
		// Get DBO.
		$db = JFactory::getDbo();
			
		$messages = $vars->response['messages'];
			
		$totals = array();
			
		$total = 0;
			
		foreach (self::$sections as $section)
		{
			if ($section == 'sections')
			{
				$query = $db->getQuery(true)
					   ->select('COUNT(*)')
					   ->from( $db->qn('#__sobipro_object') )
					   ->where( $db->qn('oType') . ' = ' . $db->q('section') );
			}
			else if ($section == 'categories')
			{
				$query = $db->getQuery(true)
					   ->select('COUNT(*)')
					   ->from( $db->qn('#__sobipro_object') )
					   ->where( $db->qn('oType') . ' = ' . $db->q('category') );
			}
			else if ($section == 'fields')
			{
				$query = $db->getQuery(true)
					   ->select('COUNT(*)')
					   ->from( $db->qn('#__sobipro_field') )
					   ->where( $db->qn('fieldType') . ' IN (' . RSDirectoryHelper::quoteImplode(self::$accepted_field_types) . ')' );
			}
			else if ($section == 'entries')
			{
				$query = $db->getQuery(true)
					   ->select('COUNT(*)')
					   ->from( $db->qn('#__sobipro_object') )
					   ->where( $db->qn('oType') . ' = ' . $db->q('entry') );
			}
				
			$db->setQuery($query);
			$count = $db->loadResult();
				
			$totals[$section] = $count;
			$total += $count;
		}
			
		$totals['total'] = $total;
			
		JFactory::getApplication()->setUserState('com_rsdirectory.measure.import.totals', $totals);
			
		$messages[] = array(
			'message' => JText::_('COM_RSDIRECTORY_IMPORT_MEASURING_DATA_DONE'),
			'type' => 'success',
			'id' => 'import-msg-data-measuring',
		);
			
		$messages[] = array(
			'message' => JText::_('COM_RSDIRECTORY_IMPORTING_DATA'),
			'type' => 'info',
			'id' => null,
		);
			
		$section = self::$sections[0];
			
		$messages[] = array(
			'message' => JText::sprintf('COM_RSDIRECTORY_IMPORT_SECTION_PROGRESS', $section, 0.0),
			'type' => 'success',
			'id' => self::sectionNameToId($section),
		);
			
		$vars->response['action'] = 'import';
		$vars->response['section'] = $section;
		$vars->response['messages'] = $messages;
	}
		
	/**
	 * Method to import data.
	 *
	 * @access protected
	 *
	 * @param object $vars
	 */
	protected function import($vars)
	{
		// Get application.
		$app = JFactory::getApplication();
			
		// Get form data.
		$jform_data = $app->input->get( 'jform', array(), 'array' );
			
		// Get plugin form data.
		$data = empty($jform_data[self::IMPORT_OPTION]) ? array() : $jform_data[self::IMPORT_OPTION];
			
		$section = empty($data['section']) ? '' : $data['section'];
		$section_offset = empty($data['section_offset']) ? 0 : $data['section_offset'];
		$offset = empty($data['offset']) ? 0 : $data['offset'];
		
		if ( !$section || !in_array($section, self::$sections) )
		{
			$vars->response['messages'][] = array(
				'message' => JText::_('COM_RSDIRECTORY_INVALID_DATA_PROVIDED'),
				'type' => 'error',
				'id' => null,
			);
				
			return;
		}
			
		// Get DBO.
		$db = JFactory::getDbo();
			
		// Get import language.
		$language = empty($data['language']) ? '' : $data['language'];
			
		$messages = $vars->response['messages'];
		$tmp_values = array();
			
		// Empty the import temporary table.
		if (!$offset)
		{
			$db->setQuery( 'TRUNCATE TABLE ' . $db->qn('#__rsdirectory_import_tmp') );
			$db->execute();
		}
			
		$limit = 100;
			
		if ($section == 'sections')
		{
			$query = $db->getQuery(true)
				   ->select('*')
				   ->from( $db->qn('#__sobipro_object') )
				   ->where( $db->qn('oType') . ' = ' . $db->q('section') );
					
			$db->setQuery($query, $section_offset, $limit);
			$objects = $db->loadObjectList();
				
			if ($objects)
			{
				$form_model = RSDirectoryModel::getInstance( 'Form', 'RSDirectoryModel', array('ignore_request' => true) );
					
				// Translate sections data.
				self::translate($objects, $language, 'section', 'id');
					
				foreach ($objects as $object)
				{
					$data = array();
						
					if ( $form = $form_model->getForm() )
					{
						$fieldsets = $form->getFieldsets();
							
						foreach ($fieldsets as $name => $fieldset)
						{
							$fields = $form->getFieldset($name);
								
							// Set properties with their default values.
							foreach ($fields as $field)
							{
								$data[$field->fieldname] = $form->getFieldAttribute($field->fieldname, 'default');
							}
						}
					}
						
					$data['title'] = stripslashes($object->name);
						
					$form_model->save($data);
					
					$section_tmp_id = (int) $form_model->getState( $form_model->getName() . '.id');
					
					$tmp = array(
						$db->q($object->id),
						$db->q($section_tmp_id),
						$db->q($section),
					);
						
					$tmp_values[] = implode(',', $tmp);
				}
			}
		}
		else if ($section == 'categories')
		{
			$limit = 30;
				
			$query = $db->getQuery(true)
				   ->select( $db->qn('o') . '.*, ' . $db->qn('c') . '.*' )
				   ->from( $db->qn('#__sobipro_object', 'o') )
				   ->leftJoin( $db->qn('#__sobipro_category', 'c') . ' ON ' . $db->qn('o.id') . ' = ' . $db->qn('c.id') )
				   ->where( $db->qn('o.oType') . ' = ' . $db->q('category') );
				   
			$db->setQuery($query, $section_offset, $limit);
			$objects = $db->loadObjectList();
				
			if ($objects)
			{
				$category_model = RSDirectoryModel::getInstance( 'Category', 'RSDirectoryModel', array('ignore_request' => true) );
					
				$parents = $this->getTmp('categories');
				$sections = $this->getTmp('sections');
					
				// Translate categories data.
				self::translate($objects, $language, 'category', 'id');
					
				foreach ($objects as $object)
				{
					$file_id = 0;
						
					// Process thumbnail.
					if ($object->icon)
					{
						// Set the source file.
						$src = realpath(JPATH_ROOT . "/media/sobipro/images/$object->icon");
							
						// Get the extension.
						$ext = strtolower( JFile::getExt($object->icon) );
							
						// Get the hash.
						$hash = RSDirectoryHelper::getHash();
							
						// Generate a file name.
						$file_name = $hash . ($ext ? ".$ext" : '');
							
						// Set the destination file.
						$dest = JPATH_ROOT . "/components/com_rsdirectory/files/images/categories/$file_name";
							
						if ( JFile::copy($src, $dest) )
						{
							$thumb = (object)array(
								'user_id' => $object->owner,
								'hash' => $hash,
								'file_name' => $file_name,
								'original_file_name' => basename($object->icon),
							);
								
							$db->insertObject('#__rsdirectory_uploaded_files', $thumb, 'id');
								
							// Get the file id.
							$file_id = $thumb->id;
						}
					}
						
					$parent_id = isset($sections[$object->parent]) || !isset($parents[$object->parent]) ? 1 : $parents[$object->parent];
					list($title, $alias) = self::getTitleAndAlias($object->name, $parent_id);
						
					$params = array(
						'form_id' => isset($sections[$object->parent]) ? $sections[$object->parent] : 0,
					);
						
					$data = array(
						'parent_id' => $parent_id,
						'title' => $title,
						'alias' => $alias,
						'description' => stripcslashes($object->description),
						'metadesc' => $object->metaDesc,
						'metadata' => array(
							'author' => $object->metaAuthor,
							'robots' => $object->metaRobots,
						),
						'params' => $params,
						'published' => $object->state == 1 ? 1 : 0,
						'created_time' => $object->createdTime,
						'created_user_id' => $object->owner,
						'modified_time' => $object->updatedTime,
						'modified_user_id' => $object->updater,
						'hits' => $object->counter,
						'language' => '*',
					);
					
					// Save the category.
					if (!$category_model->save($data)) {
						$vars->response['messages'][] = array(
							'message' => JText::sprintf('PLG_RSDIRECTORY_IMPORTSOBIPRO_CATEGORY_SAVE_ERROR', $title, $category_model->getError()),
							'type' => 'error',
							'id' => null,
						);
						
						return;
					}
						
					// Get the id of the newly inserted category.
					$category_id = (int) $category_model->getState( $category_model->getName() . '.id' );
						
					// Reset the category id.
					$category_model->setState( $category_model->getName() . '.id', null );
						
					// Insert the file - category relation.
					if ($file_id)
					{
						$relation = (object)array(
							'file_id' => $file_id,
							'category_id' => $category_id,
						);
							
						$db->insertObject('#__rsdirectory_uploaded_files_categories_relations', $relation);
							
						// Load params.
						$query = $db->getQuery(true)
							   ->select( $db->qn('params') )
							   ->from( $db->qn('#__categories') )
							   ->where( $db->qn('id') . ' = ' . $db->q($category_id) );
							   
						$db->setQuery($query);
						$params = (array)json_decode( $db->loadResult() );
						$params['thumbnail'] = $file_id;
							
						$category = (object)array(
							'id' => $category_id,
							'params' => json_encode($params),
						);
							
						$db->updateObject('#__categories', $category, 'id');
					}
						
					$parents[$object->id] = $category_id;
						
					// Process children categories.
					$query = $db->getQuery(true)
						   ->select( $db->qn('id') )
						   ->from( $db->qn('#__sobipro_object') )
						   ->where( $db->qn('oType') . ' = ' . $db->q('category') )
						   ->where( $db->qn('parent') . ' = ' . $db->q($object->id) );
						   
					$db->setQuery($query);
						
					if ( $children_old_ids = $db->loadColumn() )
					{
						$children_new_ids = self::getNewIds($parents, $children_old_ids);
							
						foreach ($children_new_ids as $child_new_id)
						{
							$category_update = (object)array(
								'id' => $child_new_id,
								'parent_id' => $category_id,
							);
								
							$db->updateObject('#__categories', $category_update, 'id');
						}
							
						// Rebuild.
						$category_model->rebuild();
					}
						
					$tmp = array(
						$db->q($object->id),
						$db->q($category_id),
						$db->q($section),
					);
						
					$tmp_values[] = implode(',', $tmp);	
				}
			}
		}
		else if ($section == 'fields')
		{
			$query = $db->getQuery(true)
					->select( '*' )
					->from( $db->qn('#__sobipro_field') )
					->where( $db->qn('fieldType') . ' IN (' . RSDirectoryHelper::quoteImplode(self::$accepted_field_types) . ')' );
					
			$db->setQuery($query, $section_offset, $limit);
			$objects = $db->loadObjectList();
				
			if ($objects)
			{
				$field_model = RSDirectoryModel::getInstance( 'Field', 'RSDirectoryModel', array('ignore_request' => true) );
					
				$sections = $this->getTmp('sections');
					
				// Translate categories data.
				self::translate($objects, $language, 'field', 'fid');
					
				$field_types_map = array(
					'inbox' => 'textbox',
					'email' => 'textbox',
					'url' => 'textbox',
					'textarea' => 'textarea',
					'select' => 'dropdown',
					'multiselect' => 'dropdown',
					'chbxgroup' => 'checkboxgroup',
					'radio' => 'radiogroup',
					'image' => 'image_upload',
					'geomap' => 'map',
				);
					
				$query = $db->getQuery(true)
					   ->select( $db->qn('id') . ', ' . $db->qn('type') )
					   ->from( $db->qn('#__rsdirectory_field_types') );
					   
				$db->setQuery($query);
				$field_types = $db->loadObjectList();
					
				$field_types_ids = array();
					
				foreach ($field_types_map as $sobipro_field_type => $rsdirectory_field_type)
				{
					if ( $field_type = RSDirectoryHelper::findElements( array('type' => $rsdirectory_field_type), $field_types ) )
					{
						$field_types_ids[$sobipro_field_type] = $field_type->id;
					}
				}
					
				// Get the 1st image fields from each section.
				$query = $db->getQuery(true)
							->select( $db->qn('fid') . ', ' . $db->qn('section') )
							->from( $db->qn('#__sobipro_field') )
							->where( $db->qn('fieldType') . ' = ' . $db->q('image') )
							->order( $db->qn('position') );
							
				$db->setQuery($query);
					
				// Initialize the 1st image fields array.
				$image_fields = array();
					
				if ( $items = $db->loadObjectList() )
				{
					foreach ($items as $item)
					{
						if ( !isset($image_fields[$item->section]) )
						{
							$image_fields[$item->section] = $item->fid;
						}
					}
				}
					
				// Initialize the custom fields values array.
				$custom_fields = array();
					
				foreach ($objects as $object)
				{
					// Skip the 1st image field from each section, because we'll just copy the files from it into the images core field in RSDirectory!.
					if ( $object->fieldType == 'image' && in_array($object->fid, $image_fields) )
						continue;
						
					// Initialize the data array.
					$data = array();
						
					if ( isset($field_types_ids[$object->fieldType]) )
					{
						$app->input->set('field_type_id', $field_types_ids[$object->fieldType]);
							
						if ( $form = $field_model->getForm() )
						{
							$fieldsets = $form->getFieldsets();
								
							foreach ($fieldsets as $name => $fieldset)
							{
								$fields = $form->getFieldset($name);
									
								// Set properties with their default values.
								foreach ($fields as $field)
								{
									$data[$field->fieldname] = $form->getFieldAttribute($field->fieldname, 'default');
								}
							}
						}
					}
						
					$name = str_replace('_', '-', $object->nid);
					$name_tmp = $name;
						
					$i = 2;
						
					do
					{
						$query = $db->getQuery(true)
							   ->select( $db->qn('id') )
							   ->from( $db->qn('#__rsdirectory_fields') )
							   ->where( $db->qn('name') . ' = ' . $db->q($name_tmp) );
								
						$db->setQuery($query);
							
						// Check if the name property value is unique.
						if ( $result = $db->loadResult() )
						{
							$name_tmp = $name . $i;
								
							$i++;
						}
					}
					while ($result);
						
					$data['name'] = $name_tmp;
					$data['field_type_id'] = $field_types_ids[$object->fieldType];
					$data['forms'] = array($sections[$object->section]);
					
					$data['published'] = $object->enabled;
					$data['required'] = $object->required;
						
					if ( isset($object->name) )
					{
						$object->name = stripslashes($object->name);
						self::updateFieldProperty('form_caption', $object->name, $data);
						self::updateFieldProperty('listing_caption', $object->name, $data);
						self::updateFieldProperty('searchable_advanced_caption', $object->name, $data);
					}
						
					if ( isset($object->suffix) )
					{
						self::updateFieldProperty('field_append', $object->suffix, $data);
					}
						
					if ( !empty($object->cssClass) )
					{
						self::updateFieldProperty('additional_html_attributes', ' class="' . $object->cssClass . '"', $data);
					}
						
					if ( isset($object->description) )
					{
						self::updateFieldProperty('help_tip', stripslashes($object->description), $data);
					}
						
					$filter = 'none';
					$regex_syntax = '';
						
					switch ($object->filter)
					{
						case 'alpha':
								
							$filter = 'alpha';
							break;
								
						case 'alphanum':
								
							$filter = 'alphanumeric';
							break;
								
						case 'integer':
								
							$filter = 'numeric';
							break;
								
						case 'email':
								
							$filter = 'email';
							break;
								
						case 'float':
								
							$filter = 'regex';
							$regex_syntax = '/^\d+(\.\d*)?$/';
							break;
								
						case 'single_letter':
								
							$filter = 'regex';
							$regex_syntax = '/^[a-zA-Z]$/';
							break;
								
						case 'phone':
								
							$filter = 'regex';
							$regex_syntax = '/^(\+\d{1,3}\s?)?(\s?\([\d]\)\s?)?[\d\-\s\.]+$/';
							break;
								
						case 'title':
								
							$filter = 'regex';
							$regex_syntax = '/^[\w\d]+[\w\d\s!@\$\%\&\*\"\'\-\+_]*$/';
							break;
								
						case 'website':
								
							$filter = 'regex';
							$regex_syntax = '/^[\w\.-]+\.{1}[a-zA-Z]{2,5}(\/[^\s]*)?$/';
							break;
								
						case 'website_full':
								
							$filter = 'validurl';
							break;
					}
						
					self::updateFieldProperty('default_validation_rule', $filter, $data);
					self::updateFieldProperty('regex_syntax', $regex_syntax, $data);
						
					if ( !empty($object->isFree) || empty($object->fee) )
					{
						self::updateFieldProperty('credits', 0, $data);
					}
					else
					{
						self::updateFieldProperty('credits', $object->fee, $data);
					}
						
					$params = self::unserialize($object->params);
						
					$searchable_simple = 0;
					$searchable_advanced = '';
					$searchable_advanced_condition_type = 'strict';
					$use_field_items = 1;
						
					if ( !empty($object->inSearch) )
					{
						$searchable_simple = 1;
							
						if ( !empty($params['searchMethod']) )
						{
							if ($params['searchMethod'] == 'general')
							{
								$searchable_advanced = 'textbox';
							}
							else if ( in_array( $params['searchMethod'], array('chbx', 'mselect') ) )
							{
								$searchable_advanced = 'checkboxgroup';
							}
							else if ($params['searchMethod'] == 'radio')
							{
								$searchable_advanced = 'radiogroup';
							}
							else if ($params['searchMethod'] == 'select')
							{
								$searchable_advanced = 'dropdown';
							}
							else if ($params['searchMethod'] == 'select')
							{
								$searchable_advanced = 'dropdown';
							}
							else if ($params['searchMethod'] == 'range')
							{
								$searchable_advanced = 'range';
								$use_field_items = 0;
								$ranges = array();
									
								if ( !empty($params['searchRangeValues']) )
								{
									$searchRangeValues = explode(',', $params['searchRangeValues']);
										
									foreach ($searchRangeValues as $value)
									{
										if ( isset($last_value) )
										{
											$ranges[] = trim($last_value) . ' - ' . trim($value);
										}
											
										$last_value = $value;
									}	
								}
									
								if ( !empty($params['freeRange']) )
								{
									$ranges[] = '{range}';
								}
									
								if ( !empty($ranges) )
								{
									self::updateFieldProperty( 'searchable_advanced_items', implode("\n", $ranges), $data );
								}
							}
						}
					}
						
					if ( isset($params['size']) )
					{
						self::updateFieldProperty('size', $params['size'], $data);	
					}
						
					if ( isset($params['defSel']) )
					{
						if ( in_array( $object->fieldType, array('chbxgroup', 'multiselect') ) )
						{
							self::updateFieldProperty('default_values', $params['defSel'], $data);
						}
						else
						{
							self::updateFieldProperty('default_value', $params['defSel'], $data);	
						}
					}
						
					// Convert the maximum file size from bytes to kilobytes and update field property.
					if ( isset($params['maxSize']) )
					{
						self::updateFieldProperty('maximum_file_size', $params['maxSize'] / 1024, $data);
					}
						
					self::updateFieldProperty('max_files_number', 1, $data);
						
					if ( $object->fieldType == 'textarea' )
					{
						if ( !empty($object->inSearch) )
						{
							$searchable_advanced = 'textbox';
							$searchable_advanced_condition_type = 'containing';
						}
					}
					
					// map field
					if ( $object->fieldType == 'geomap') {
						if (isset($params['determineLocation']) && !empty($params['determineLocation'])) {
							self::updateFieldProperty('use_geolocation', 1, $data);
						}
						if (isset($params['zoomLevel']) && !empty($params['zoomLevel'])) {
							self::updateFieldProperty('default_zoom', $params['zoomLevel'], $data);
						}
						
						if (isset($params['width']) && !empty($params['width'])) {
							self::updateFieldProperty('width', $params['width'], $data);
						}
						
						if (isset($params['height']) && !empty($params['height'])) {
							self::updateFieldProperty('height', $params['height'], $data);
						}
						
						if (isset($params['startPoint']) && !empty($params['startPoint'])) {
							list($def_lat, $def_lng) = explode(',',$params['startPoint'], 2);
							self::updateFieldProperty('default_lat', $def_lat, $data);
							self::updateFieldProperty('default_lng', $def_lng, $data);
						}						
					}
						
					self::updateFieldProperty('searchable_simple', $searchable_simple, $data);
					self::updateFieldProperty('searchable_advanced', $searchable_advanced, $data);
					self::updateFieldProperty('use_dependency', 0, $data);
					self::updateFieldProperty('use_field_items', $use_field_items, $data);
					self::updateFieldProperty('searchable_advanced_condition_type', $searchable_advanced_condition_type, $data);
						
					self::updateFieldProperty('allow_html', $object->editor ? 1 : 0, $data);
						
					// Get field options (if any).
					$query = $db->getQuery(true)
					       ->select('*')
						   ->from( $db->qn('#__sobipro_field_option') )
						   ->where( $db->qn('fid') . ' = ' . $db->q($object->fid) )
						   ->order( $db->qn('optPos') );
						   
					$db->setQuery($query);
						
					// Add field options to the data array.
					if ( $field_options = $db->loadObjectList() )
					{
						// Translate options data.
						self::translate($field_options, $language, 'field_option', 'fid');
							
						$options = array();
						$has_parent = false;
							
						foreach ($field_options as $field_option)
						{
							$value = $field_option->optValue;
							$text = isset($field_option->optText) ? $field_option->optText : $value;
							$text = stripslashes($text);
								
							if ( RSDirectoryHelper::findElements( array('optParent' => $field_option->optValue), $field_options ) )
							{
								if ($has_parent)
								{
									$options[] = '[/g]';
								}
									
								$options[] = $text . '[g]';
									
								$has_parent = true;
							}
							else
							{
								if ( empty($field_option->optParent) && $has_parent )
								{
									$options[] = '[/g]';
									$has_parent = false;
								}
									
								$options[] = $value == $text ? $value : "$value|$text";
							}
						}
							
						if ($has_parent)
						{
							$options[] = '[/g]';
						}
							
						self::updateFieldProperty( 'items', implode("\n", $options), $data );
					}
						
					if ($object->fieldType == 'multiselect')
					{
						self::updateFieldProperty('multiple', 1, $data);
					}
						
					if ($object->fieldType == 'email')
					{
						self::updateFieldProperty( 'default_validation_rule', empty($params['validateUrl']) ? 'email' : 'emaildns', $data );
					}
						
					if ( $field_model->save($data) )
					{
						$field_id = (int) $field_model->getState( $field_model->getName() . '.id' );
							
						// Build custom fields array.
						if ( $object->fieldType != 'image' && in_array( $object->showIn, array('both', 'details') ) )
						{
							$custom_fields[] = array(
								$db->q($sections[$object->section]),
								$db->q($field_id),
							);
						}
							
						// Update title templates.
						$query = $db->getQuery(true)
						       ->select( $db->qn('section') )
						       ->from( $db->qn('#__sobipro_config') )
							   ->where( $db->qn('sKey') . ' = ' . $db->q('name_field') )
							   ->where( $db->qn('cSection') . ' = ' . $db->q('entry') )
							   ->where( $db->qn('sValue') . ' = ' . $db->q($object->fid) );
							   
						$db->setQuery($query);
							
						if ( $section_ids = $db->loadColumn() )
						{
							foreach ($section_ids as $section_id)
							{
								$form = (object)array(
									'id' => $sections[$section_id],
									'title_template' => '{' . $name_tmp . '}',
									'use_title_template' => 1,
								);
									
								$db->updateObject('#__rsdirectory_forms', $form, 'id');;
							}
						}
							
						$tmp = array(
							$db->q($object->fid),
							$db->q($field_id),
							$db->q($section),
						);
							
						$tmp_values[] = implode(',', $tmp);	
					}
				}
					
				if ($custom_fields)
				{
					// Insert columns.
					$columns = array('form_id', 'field_id');
						
					// Insert the custom form fields in the database.
					$query = $db->getQuery(true)
						   ->insert( $db->qn('#__rsdirectory_forms_custom_fields') )
						   ->columns( $db->qn($columns) );
							
					foreach ($custom_fields as $field)
					{
						$query->values( implode(',', $field) );
					}
						
					$db->setQuery($query);
					$db->execute();
				}
			}
		}
		else if ($section == 'entries')
		{
			$query = $db->getQuery(true)
				   ->select('*')
				   ->from( $db->qn('#__sobipro_object') )
				   ->where( $db->qn('oType') . ' = ' . $db->q('entry') );
				   
			$db->setQuery($query, $section_offset, $limit);
			$objects = $db->loadObjectList();
				
			if ($objects)
			{
				$has_pce = self::hasEntriesStoredInParentCategories();
					
				$pce = empty($data['pce']) ? '' : $data['pce'];
				$pce_rsdirectory_category = empty($data['pce_rsdirectory_category']) ? '' : $data['pce_rsdirectory_category'];
				$pce_sobipro_category = empty($data['pce_sobipro_category']) ? '' : $data['pce_sobipro_category'];
				$mce = empty($data['mce']) ? '' : $data['mce'];
				$mce_rsdirectory_category = empty($data['mce_rsdirectory_category']) ? '' : $data['mce_rsdirectory_category'];
				$mce_sobipro_category = empty($data['mce_sobipro_category']) ? '' : $data['mce_sobipro_category'];

				$entry_model = RSDirectoryModel::getInstance( 'Entry', 'RSDirectoryModel', array('ignore_request' => true) );
					
				$parents = $this->getTmp('categories');
				$fields_tmp = $this->getTmp('fields');
					
				// Get all the form fields.
				$form_fields = RSDirectoryHelper::getFormFields();
					
				// Get title fields.
				$query = $db->getQuery(true)
					   ->select('*')
					   ->from( $db->qn('#__sobipro_config') )
					   ->where( $db->qn('sKey') . ' = ' . $db->q('name_field') );
					   
				$db->setQuery($query);
					
				$title_fields = array();
					
				if ( $items = $db->loadObjectList() )
				{
					foreach ($items as $item)
					{
						$title_fields[$item->section] = $item->sValue;
					}
				}
					
				// Get entry - categories relations.
				$query = $db->getQuery(true)
				       ->select( $db->qn( array('id', 'pid') ) )
					   ->from( $db->qn('#__sobipro_relations') )
					   ->where( $db->qn('oType') . ' = ' . $db->q('entry') );
					   
				$db->setQuery($query);
				$results = $db->loadObjectList();
					
				$relations = array();
					
				if ($results)
				{
					foreach ($results as $result)
					{
						if ( !isset($relations[$result->id]) )
						{
							$relations[$result->id] = array();
						}
							
						$relations[$result->id][] = $result->pid;
					}
				}
					
				// Initialize files array.
				$files = array();
					
				// Process each entry.
				foreach ($objects as $object)
				{
					$categories = array();
						
					// Check if the entry is in a parent category.
					if ( isset($relations[$object->id]) )
					{
						foreach ($relations[$object->id] as $category_id)
						{
							if ( $has_pce && self::hasChildren($category_id) )
							{
								if ($pce == 'lowest_subcategories')
								{
									if ( $lowest_subcategories = self::getLowestSubcategories($category_id) )
									{
										$lowest_subcategories = self::getTmpIds($lowest_subcategories, $parents);
										$categories = array_merge($categories, $lowest_subcategories);
									}
								}
								else if ($pce == 'rsdirectory_category')
								{
									$categories[] = $pce_rsdirectory_category;
								}
								else if ($pce == 'sobipro_category')
								{
									$categories[] = self::getTmpIds($pce_sobipro_category, $parents);
								}
								else if ($mce == 'ignore_entry')
								{
									// Ignore entry.
									continue 2;
								}
							}
							else
							{
								$categories[] = self::getTmpIds($category_id, $parents);
							}
						}
					}
						
					// Remove duplicates.
					$categories = array_unique($categories);
						
					// Check if the entry is in multiple categories.
					if ( count($categories) > 1 )
					{
						if ($mce == 'first_category')
						{
							$categories = array($categories[0]);
						}
						else if ($mce == 'rsdirectory_category')
						{
							$categories = array($mce_rsdirectory_category);
						}
						else if ($mce == 'sobipro_category')
						{
							$categories = array( self::getTmpIds($mce_sobipro_category, $parents) );
						}
						else if ($mce == 'ignore_entry')
						{
							// Ignore entry.
							continue;
						}
					}
						
					if ($categories)
					{
						// Initialize entry data array.
						$data = array(
							'user_id' => $object->owner,
							'created_time' => $object->createdTime,
							'published_time' => $object->validSince,
							'modified_user_id' => $object->updater,
							'modified_time' => $object->updatedTime,
							'expiry_time' => $object->validUntil,
							'published' => $object->state,
							'charge' => 0,
							'import' => 1,
						);
							
						// Get SobiPro form data.
						$select = array(
							$db->qn('fd') . '.*',
							$db->qn('f.fieldType'),
						);
							
						$query = $db->getQuery(true)
							   ->select($select)
							   ->from( $db->qn('#__sobipro_field_data', 'fd') )
							   ->innerJoin( $db->qn('#__sobipro_field', 'f') . ' ON ' . $db->qn('fd.fid') . ' = ' . $db->qn('f.fid') )
							   ->where( $db->qn('f.fieldType') . ' IN (' . RSDirectoryHelper::quoteImplode(self::$accepted_field_types) . ')' )
							   ->where( $db->qn('fd.sid') . ' = ' . $db->q($object->id) )
							   ->where( $db->qn('fd.copy') . ' = ' . $db->q(0) )
							   ->order( $db->qn('fd.lang') . ' = ' . $db->q($language) );
								
						$db->setQuery($query);
							
						// Add SobiPro data to entry data array.
						if ( $items = $db->loadObjectList() )
						{
							foreach ($items as $item)
							{
								// Skip the form field if it wasn't imported into RSDirectory!
								if ( empty($fields_tmp[$item->fid]) )
									continue;
									
								// Get the RSDirectory! form field id.
								$field_id = $fields_tmp[$item->fid];
									
								// Find the form field.
								$form_field = RSDirectoryHelper::findElements( array('id' => $field_id), $form_fields );
									
								// Skip the form field if it wasn't found in the RSDirectory! fields list.
								if ( empty($form_field) )
									continue;
									
								if ( $form_field->create_column && !isset($data[$form_field->form_field_name]) )
								{
									$field_value = '';
										
									if ($item->fieldType == 'url')
									{
										$arr = self::unserialize($item->baseData);
											
										if ( isset($arr['url']) )
										{
											$juri = new JUri($arr['url']);
											$juri->setScheme( empty($arr['protocol']) ? 'http' : $arr['protocol'] );
												
											$field_value = (string)$juri;
										}
									}
									else if ($item->fieldType == 'email')
									{
										$arr = self::unserialize($item->baseData);
											
										$field_value = isset($arr['url']) ? $arr['url'] : '';
									}
									else if ($item->fieldType == 'geomap') {
										$arr = self::unserialize($item->baseData);
										$field_value = array();
										if (isset($arr['latitude']) && !empty($arr['latitude'])) {
											$field_value['lat'] = $arr['latitude'];
										}
										if (isset($arr['longitude']) && !empty($arr['longitude'])) {
											$field_value['lng'] = $arr['longitude'];
										}
									}									
									else
									{
										$field_value = stripslashes($item->baseData);
									}
										
									$data[$form_field->form_field_name] = $field_value;
								}
							}
						}
							
						// Get selected values for selects, checkboxes, radio.
						$query = $db->getQuery(true)
							   ->select('*')
							   ->from( $db->qn('#__sobipro_field_option_selected') )
							   ->where( $db->qn('sid') . ' = ' . $db->q($object->id) )
							   ->where( $db->qn('copy') . ' = ' . $db->q(0) );
							   
						$db->setQuery($query);
							
						// Add selected values to entry data array.
						if ( $items = $db->loadObjectList() )
						{
							// Initialize the selected values array.
							$selected_values = array();
								
							foreach ($items as $item)
							{
								if ( !isset($selected_values[$item->fid]) )
								{
									$selected_values[$item->fid] = array();
								}
									
								$selected_values[$item->fid][] = stripslashes($item->optValue);
							}
								
							foreach ($selected_values as $field_id => $arr)
							{
								if (!isset($fields_tmp[$field_id]))
								{
									continue;
								}

								// Get the RSDirectory! form field id.
								$field_id = $fields_tmp[$field_id];
									
								// Find the form field.
								$form_field = RSDirectoryHelper::findElements( array('id' => $field_id), $form_fields );
									
								// Skip the form field if it wasn't found in the RSDirectory! fields list.
								if ( empty($form_field) )
									continue;
									
								if ( $form_field->field_type == 'radiogroup' || ( $form_field->field_type == 'dropdown' && !$form_field->properties->get('multiple') ) )
								{
									$data[$form_field->form_field_name] = implode(',', $arr);
								}
								else
								{
									$data[$form_field->form_field_name] = $arr;
								}
							}
						}
							
						// Get SobiPro images data.
						$query = $db->getQuery(true)
							   ->select( $db->qn('fd') . '.*' )
							   ->from( $db->qn('#__sobipro_field_data', 'fd') )
							   ->innerJoin( $db->qn('#__sobipro_field', 'f') . ' ON ' . $db->qn('fd.fid') . ' = ' . $db->qn('f.fid') )
							   ->where( $db->qn('f.fieldType') . ' = ' . $db->q('image') )
							   ->where( $db->qn('fd.sid') . ' = ' . $db->q($object->id) )
							   ->where( $db->qn('fd.copy') . ' = ' . $db->q(0) )
							   ->order( $db->qn('f.position') . ', ' . $db->qn('fd.lang') . ' = ' . $db->q($language) );
								
						$db->setQuery($query);
						$sobipro_image_fields = $db->loadObjectList();
							
						// Insert the entry in each category.
						foreach ($categories as $category_id)
						{
							// Get the form associated with the category.
							$form = RSDirectoryHelper::getCategoryInheritedForm($category_id);
								
							if ( empty($form) )
								return;
								
							$data['category_id'] = $category_id;
							$data['form_id'] = $form->id;
								
							// Save entry.
							if ( $entry_model->save($data) )
							{
								// Get the id of the newly inserted entry.
								$entry_id = $entry_model->getState( $entry_model->getName() . '.id' );
									
								$first = array();
								
								static $processed_core_images = array();
								
								// Process image fields.
								foreach ($sobipro_image_fields as $sobipro_image_field)
								{
									$arr = self::unserialize($sobipro_image_field->baseData);
										
									if ( empty($arr) )
										continue;
										
									// Process 1st image field in the section.
									if ( empty($first[$sobipro_image_field->section]) )
									{
										// Find the core image field.
										$image_field = RSDirectoryHelper::findFormField('images', $form_fields);
										
										// If we're using a core Images field, assign it.
										if ($image_field && empty($processed_core_images[$form->id])) {
											$field_model = RSDirectoryModel::getInstance( 'Field', 'RSDirectoryModel', array('ignore_request' => true) );
											$field_model->assign2Form($image_field->id, $form->id);
											$processed_core_images[$form->id] = true;
										}
										
										// Remember that we processed the 1st image field in the section.
										$first[$sobipro_image_field->section] = true;
									}
									// Process the other image fields in the section.
									else
									{
										if ( empty($fields_tmp[$sobipro_image_field->fid]) )
											continue;
											
										// Get the RSDirectory! form field id.
										$field_id = $fields_tmp[$sobipro_image_field->fid];
											
										$image_field = RSDirectoryHelper::findElements( array('id' => $field_id), $form_fields );
									}
										
									// Skip the form field if it wasn't found in the RSDirectory! fields list.
									if ( empty($image_field) )
										continue;
										
									$properties = $image_field->properties;
										
									$last_width = 0;
									$last_height = 0;
									$last_file_path = '';
										
									foreach (self::$image_sizes as $image_size)
									{
										if ( empty($arr[$image_size]) )
											continue;
											
										$file_path = JPATH_ROOT . '/' . $arr[$image_size];
											
										// Skip if the file is not an image
										if ( !RSDirectoryHelper::isImage($file_path) )
											continue;
											
										if ( $properties->get('maximum_file_size') )
										{
											// Skip the file because it's too big.
											if ( $properties->get('maximum_file_size') * 1024 < filesize($file_path) )
												continue;
										}
											
										// Get the extension.
										$ext = strtolower( JFile::getExt($file_path) );
											
										// Get the accepted file extensions.
										$accepted_files = $properties->get('accepted_files') ? explode( "\r\n", $properties->get('accepted_files') ) : array();
											
										if ($accepted_files)
										{
											// Convert all the accepted files extensions to lowercase.
											foreach ($accepted_files as &$value)
											{
												$value = strtolower($value);
											}
												
											// Skip this file if it's unallowed.
											if ( !in_array($ext, $accepted_files) )
												continue;
										}
											
										list($width, $height) = getimagesize($file_path);
											
										if ($width * $height > $last_width * $last_height)
										{
											$last_width = $width;
											$last_height = $height;
											$last_file_path = $file_path;
										}
									}
										
									if ($last_file_path)
									{
										$dst_dir = JPATH_ROOT . "/components/com_rsdirectory/files/entries/$entry_id/";
											
										// Get the extension.
										$ext = strtolower( JFile::getExt($last_file_path) );
											
										// Get a hash.
										$hash = RSDirectoryHelper::getHash();
											
										// Generate a file name.
										$file_name = $hash . ($ext ? ".$ext" : '');
										
										if ( JFile::copy($last_file_path, "$dst_dir/$file_name") )
										{
											// Insert the file.
											$new_file = (object)array(
												'user_id' => $object->owner,
												'hash' => $hash,
												'file_name' => $file_name,
												'original_file_name' => basename($last_file_path),
											);
												
											$db->insertObject('#__rsdirectory_uploaded_files', $new_file, 'id');
												
											$files[] = array(
												$db->q($new_file->id),
												$db->q($entry_id),
												$db->q($image_field->id),
												$db->q(1),
											);
										}
									}
								}
							}
						}
					}
				}
					
				if ( !empty($files) )
				{
					$columns = array(
						'file_id',
						'entry_id',
						'field_id',
						'ordering',
					);
						
					$query = $db->getQuery(true)
						   ->insert( $db->qn('#__rsdirectory_uploaded_files_fields_relations') )
						   ->columns( $db->qn($columns) );
							
					foreach ($files as $file)
					{
						$query->values( implode(',', $file) );
					}
						
					$db->setQuery($query);
					$db->execute();
				}
			}
		}
			
		if ($tmp_values)
		{
			$query = $db->getQuery(true)
			       ->insert( $db->qn('#__rsdirectory_import_tmp') )
			       ->columns( $db->qn( array('id_old', 'id_new', 'section') ) )
			       ->values($tmp_values);
					
			$db->setQuery($query);
			$db->execute();
		}
			
		$count = count($objects);
		$totals = $app->getUserState('com_rsdirectory.measure.import.totals');
			
		$vars->response['total'] = $totals['total'];
			
		$progress = $offset + $count;
		$progress = $progress > $totals['total'] ? $totals['total'] : $progress;
			
		$vars->response['progress'] = $progress;
		$vars->response['completition'] = $totals['total'] ? number_format( ($progress * 100) / $totals['total'], 1 ) : 100.0;
			
		$section_progress = $section_offset + $count;
		$section_progress = $section_progress > $totals[$section] ? $totals[$section] : $section_progress;
			
		$vars->response['section_progress'] = $section_progress;
		$vars->response['section_completition'] = $totals[$section] ? number_format( ($section_progress * 100) / $totals[$section], 1 ) : 100.0;
			
		$messages[] = array(
			'message' => JText::sprintf('COM_RSDIRECTORY_IMPORT_SECTION_PROGRESS', $section, $vars->response['section_completition']),
			'type' => 'success',
			'id' => self::sectionNameToId($section),
		);
			
		if ($vars->response['section_completition'] == 100)
		{
			$key = array_search($section, self::$sections);
				
			if ( isset(self::$sections[$key + 1]) )
			{
				// Get the next section.
				$section = self::$sections[$key + 1];
					
				// Reset section completition.
				$vars->response['section_completition'] = 0.0;
					
				// Reset section progress.
				$vars->response['section_progress'] = 0.0;
					
				$messages[] = array(
					'message' => JText::sprintf('COM_RSDIRECTORY_IMPORT_SECTION_PROGRESS', $section, 0.0),
					'type' => 'success',
					'id' => self::sectionNameToId($section),
				);
			}
		}
			
		$vars->response['section'] = $section;
		$vars->response['action'] = $vars->response['completition'] < 100 ? 'import' : 'done';
		$vars->response['messages'] = $messages;
	}
		
	/**
	 * Get data from the import tmp table.
	 *
	 * @access public
	 *
	 * @param string $section
	 *
	 * @return array
	 */
	public function getTmp($section)
	{
		$db = JFactory::getDbo();
			
		$query = $db->getQuery(true)
		       ->select('*')
			   ->from( $db->qn('#__rsdirectory_import_tmp') )
			   ->where( $db->qn('section') . ' = ' . $db->q($section) );
				
		$db->setQuery($query);
			
		$parents = array();
			
		if ( $results = $db->loadObjectList() )
		{
			foreach ($results as $result)
			{
				$parents[$result->id_old] = $result->id_new;
			}
		}
			
		return $parents;
	}
		
	/**
	 * Get the new ids of the specified objects.
	 *
	 * @acces public
	 *
	 * @static
	 *
	 * @param array $parents
	 *
	 * @return array
	 */
	public static function getNewIds($parents, $old_ids)
	{
		$old_ids = (array)$old_ids;
			
		$new_ids = array();
			
		if ($parents && $old_ids)
		{
			foreach ($old_ids as $old_id)
			{
				if ( isset($parents[$old_id]) )
				{
					$new_ids[] = $parents[$old_id];
				}
			}
		}
			
		return $new_ids;
	}
		
	/**
	 * Convert the section name into a valid id attribute string.
	 *
	 * @access public
	 *
	 * @param string $section
	 *
	 * @return string
	 */
	public static function sectionNameToId($section)
	{
		return "import-msg-$section";
	}
		
	/**
	 * A method to generate alias and title.
	 *
	 * @access public
	 *
	 * @static
	 *
	 * @param string $title
	 * @param int $parent_id
	 *
	 * @return array An array consisting of the title and alias
	 */
	public static function getTitleAndAlias($title, $parent_id)
	{
		$db = JFactory::getDbo();
		$title = stripslashes($title);
		$alias = JFilterOutput::stringURLSafe(trim($title));
			
		if ( trim( str_replace('-', '', $alias) ) == '' )
		{
			$alias = JFactory::getDate()->format('Y-m-d-H-i-s');
		}
			
		do
		{
			$query = $db->getQuery(true)
			       ->select('COUNT(*)')
				   ->from( $db->qn('#__categories') )
				   ->where( $db->qn('parent_id') . ' = ' . $db->q($parent_id) )
				   ->where( $db->qn('alias') . ' = ' . $db->q($alias) );
					
			$db->setQuery($query);
				
			if ( $result = $db->loadResult() )
			{
				$title = Joomla\String\StringHelper::increment($title);
				$alias = Joomla\String\StringHelper::increment($alias, 'dash');
			}
		}
		while ($result);
			
		return array($title, $alias);
	}
		
	/**
	 * Update a field property if it already exists in the data array.
	 *
	 * @access public
	 *
	 * @static
	 *
	 * @param string $prop
	 * @param mixed $value
	 * @param array &$data
	 */
	public static function updateFieldProperty($prop, $value, &$data)
	{
		if ( array_key_exists($prop, $data) )
		{
			$data[$prop] = $value;
		}
	}
		
	/**
	 * A method to translate data retrieved from the SobiPro tables.
	 *
	 * @access public
	 *
	 * @static
	 *
	 * @param array &$list
	 * @param string $language
	 * @param string $type The object type to translate
	 * @param string $pk The name of the primary key
	 */
	public static function translate(&$list, $language, $type, $pk)
	{
		if ( empty($list) || !is_array($list) )
			return;
			
		$pks = RSDirectoryHelper::getColumn($list, $pk);
			
		if ( empty($pks) )
			return;
			
		$db = JFactory::getDbo();
			
		$query = $db->getQuery(true)
			   ->select('*')
			   ->from( $db->qn('#__sobipro_language') )
			   ->where( $db->qn('oType') . ' = ' . $db->q($type) )
			   ->where( $db->qn($pk) . ' IN (' . implode(',', $pks) . ')' );
				
		if ($language)
		{
			$query->order( $db->qn('language') . ' = ' . $db->q($language) );
		}
			
		$db->setQuery($query);
		$results = $db->loadObjectList();
			
		if (!$results)
			return;
			
		// The provided language will be at the end so reverse the array.
		$results = array_reverse($results);
			
		$translations = array();
			
		foreach ($results as $result)
		{
			if ( !isset($translations[$result->$pk]) )
			{
				$translations[$result->$pk] = array();
			}
				
			if ( !isset($translations[$result->$pk][$result->sKey]) )
			{
				$translations[$result->$pk][$result->sKey] = $result->sValue;
			}
		}
			
		if ($type == 'field_option')
		{
			foreach ($list as $object)
			{
				if ( isset($translations[$object->$pk]) )
				{
					foreach ($translations[$object->$pk] as $key => $value)
					{
						if ($object->optValue == $key)
						{
							$object->optText = $value;
						}
					}
				}
			}
		}
		else
		{
			foreach ($list as $object)
			{
				if ( isset($translations[$object->$pk]) )
				{
					foreach ($translations[$object->$pk] as $key => $value)
					{
						$object->$key = $value;
					}
				}
			}
		}
	}
		
	/**
	 * Method to check if a SobiPro category has children.
	 *
	 * @access public
	 *
	 * @static
	 *
	 * @param int $category_id
	 *
	 * @return bool
	 */
	public static function hasChildren($category_id)
	{
		static $parents = array();
			
		if (!$parents)
		{
			$db = JFactory::getDbo();
				
			$query = $db->getQuery(true)
				   ->select( $db->qn( array('id', 'parent') ) )
				   ->from( $db->qn('#__sobipro_object') )
				   ->where( $db->qn('oType') . ' = ' . $db->q('category') );
					
			$db->setQuery($query);
				
			if ( $items = $db->loadObjectList() )
			{
				foreach ($items as $item)
				{
					$parents[$item->parent] = true;
				}
			}
		}
			
		return !empty($parents[$category_id]);
	}
		
	/**
	 * Method to get the lowest subcategories for a specified category.
	 *
	 * @access public
	 *
	 * @static
	 *
	 * @param int $category_id
	 *
	 * @return array
	 */
	public static function getLowestSubcategories($category_id, $results = array() )
	{
		static $parents = array();
			
		if (!$parents)
		{
			$db = JFactory::getDbo();
				
			$query = $db->getQuery(true)
				   ->select( $db->qn( array('id', 'parent') ) )
				   ->from( $db->qn('#__sobipro_object') )
				   ->where( $db->qn('oType') . ' = ' . $db->q('category') );
					
			$db->setQuery($query);
				
			if ( $items = $db->loadObjectList() )
			{
				foreach ($items as $item)
				{
					if ( !isset($parents[$item->parent]) )
					{
						$parents[$item->parent] = array();
					}
						
					$parents[$item->parent][] = $item->id;
				}
			}
		}
			
		if ( empty($parents[$category_id]) )
		{
			$results[] = $category_id;
		}
		else
		{
			foreach ($parents[$category_id] as $subcategory_id)
			{
				if ( $results_aux = self::getLowestSubcategories($subcategory_id, $results) )
				{
					$results = array_merge($results, $results_aux);
				}
			}
		}
			
		return array_unique($results);
	}
		
	/**
	 * Get tmp ids.
	 *
	 * @access public
	 *
	 * @static
	 *
	 * @param mixed $ids
	 * @param array $tmp_ids
	 *
	 * @return mixed
	 */
	public static function getTmpIds( $ids, $tmp_ids = array() )
	{
		if ( is_array($ids) )
		{
			$results = array();
				
			if ($ids)
			{
				foreach ($ids as $id)
				{
					if ( isset($tmp_ids[$id]) )
					{
						$results[] = $tmp_ids[$id];
					}
				}
			}
				
			return $results;
		}
			
		return isset($tmp_ids[$ids]) ? $tmp_ids[$ids] : null;
	}
		
	/**
	 * Method to check if there are entries stored in parent categories.
	 *
	 * @access public
	 *
	 * @static
	 *
	 * @return bool
	 */
	public static function hasEntriesStoredInParentCategories()
	{
		$db = JFactory::getDbo();
			
		$select = array(
			$db->qn('id'),
			$db->qn('pid'),
			$db->qn('oType'),
		);
			
		$query = $db->getQuery(true)
		       ->select($select)
			   ->from( $db->qn('#__sobipro_relations') )
			   ->where( $db->qn('oType') . ' = ' . $db->q('entry') . ' OR ' . $db->qn('oType') . ' = ' . $db->q('category') );
			   
		$db->setQuery($query);
			
		if ( $items = $db->loadObjectList() )
		{
			$parents = array();
			$entries_categories_ids = array();
				
			foreach ($items as $item)
			{
				if ($item->oType == 'entry')
				{
					// Remember the categories in which the entries are stored.
					$entries_categories_ids[] = $item->pid;
				}
				else
				{
					// Remember the categories that are selected as parents by other categories.
					$parents[$item->pid] = true;
				}
			}
				
			if ($entries_categories_ids)
			{
				foreach ($entries_categories_ids as $category_id)
				{
					if ( isset($parents[$category_id]) )
						return true;
				}
			}
		}
			
		return false;
	}
		
	/**
	 * Method to check if there are entries stored in multiple categories.
	 *
	 * @access public
	 *
	 * @static
	 *
	 * @return bool
	 */
	public static function hasEntriesStoredInMultipleCategories()
	{
		$db = JFactory::getDbo();
			
		$query = $db->getQuery(true)
		       ->select( 'COUNT(*) AS ' . $db->qn('count') )
			   ->from( $db->qn('#__sobipro_relations') )
			   ->where( $db->qn('oType') . ' = ' . $db->q('entry') )
			   ->group( $db->qn('id') )
			   ->having( $db->qn('count') . ' > ' . $db->q(1) );
				
		$db->setQuery($query);
			
		return (bool)$db->loadResult();
	}
	
	public static function unserialize( $var, $name = null ) {
		$r = null;
		if ( is_string( $var ) && strlen( $var ) > 2 ) {
			if ( ( $var2 = base64_decode( $var, true ) ) ) {
				if ( function_exists( 'gzinflate' ) ) {
					if ( ( $r = @gzinflate( $var2 ) ) ) {
						if ( !$r = @unserialize( $r ) ) {
							return array();
						}
					}
					else {
						if ( !( $r = @unserialize( $var2 ) ) ) {
							return array();
						}
					}
				}
				else {
					if ( !( $r = @unserialize( $var2 ) ) ) {
						return array();
					}
				}
			}
			else {
				if ( !( $r = @unserialize( $var ) ) ) {
					return array();
				}
			}
		}
		return $r;
	}
}

Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists