<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Joomla extends MY_Controller
{
	private $data = array();

	public function __construct()
	{
		parent::__construct();

		$this->admin_login_required();
		$this->data["show_menu"] = true;
		$this->data["sites"] = $this->site->get();

		require_once(APPLICATION_PATH . '/third_party/htmlpurifier/HTMLPurifier.auto.php');
		require_once(APPLICATION_PATH . '/third_party/htmlpurifier/htmlpurifier_html5.php');

		$config = HTMLPurifier_Config::createDefault();
		// $config->set('HTML.ForbiddenAttributes', array("style"));
		$config->set('Attr.AllowedFrameTargets', array("_blank", "_self", "_parent", "_top"));
		$config->set('Attr.EnableID', true);
		// $config->set('AutoFormat.RemoveEmpty', true);
		// $config->set('AutoFormat.RemoveEmpty.RemoveNbsp', true);
		$config->set('AutoFormat.RemoveSpansWithoutAttributes', true);
		$config->set('HTML.SafeObject', true);
		$config->set('HTML.SafeEmbed', true);
		$config->set('HTML.SafeIframe', true);
		$config->set('HTML.FlashAllowFullScreen', true);
		$config->set('HTML.TargetBlank', true);
		$config->set('HTML.Trusted', true);
		$config->set('Output.FixInnerHTML', false);
		$config->set('Output.FlashCompat', true);

		$allowed = array(
			'img[src|alt|title|width|height|style|align|vspace|hspace|data-mce-src|data-mce-json|class|id]',
			'figure', 'figcaption',
			'video[src|type|width|height|poster|preload|controls|autoplay]', 'source[src|type]',
			'a[href|target|style|class|id|title]',
			'iframe[width|height|src|frameborder|allowfullscreen|class|id]',
			'strong', 'b', 'i[class|id]', 'u', 'em[class|id]', 'br',
			'h1[style|class|id]', 'h2[style|class|id]', 'h3[style|class|id]', 'h4[style|class|id]', 'h5[style|class|id]', 'h6[style|class|id]',
			'p[style|class|id]', 'div[style|class|id]', 'center', 'address[style|class|id]',
			'span[style|class|id]', 'pre[style|class|id]',
			'ul[style|class|id]', 'ol[style|class|id]', 'li[style|class|id]',
			'table[width|height|border|style|class|id|cellspacing|cellpadding]', 'th[width|height|border|style|class|id]',
			'tr[width|height|border|style|class|id]', 'td[width|height|border|style|class|id|align|valign]',
			'hr[style|class|id]','script[src|type]'
		);

		$this->purifier = load_htmlpurifier($config, $allowed);
		$this->current_user = get_user();
		$this->data["user"] = $this->current_user;
	}

	public function index()
	{
		$query = $this->db->query("SHOW TABLES LIKE 'jos_menu_types'");

		if($query->num_rows() > 0)
		{
			$query = $this->db->query("SELECT id FROM jos_menu_types");
			$this->data["menus"] = $query->result();
		}
		else
		{
			$this->data["menus"] = -1;
		}

		$query = $this->db->query("SHOW TABLES LIKE 'jos_menu'");

		if($query->num_rows() > 0)
		{
			$query = $this->db->query("SELECT id FROM jos_menu");
			$this->data["menu_items"] = $query->result();
		}
		else
		{
			$this->data["menu_items"] = -1;
		}

		$query = $this->db->query("SHOW TABLES LIKE 'jos_categories'");

		if($query->num_rows() > 0)
		{
			$query = $this->db->query("SELECT id FROM jos_categories");
			$this->data["categories"] = $query->result();
		}
		else
		{
			$this->data["categories"] = -1;
		}

		$query = $this->db->query("SHOW TABLES LIKE 'jos_content'");

		if($query->num_rows() > 0)
		{
			$query = $this->db->query("SELECT id FROM jos_content");
			$this->data["content"] = $query->result();
		}
		else
		{
			$this->data["content"] = -1;
		}

		$query = $this->db->query("SHOW TABLES LIKE 'jos_modules'");

		if($query->num_rows() > 0)
		{
			$query = $this->db->query("SELECT id FROM jos_modules WHERE `module`='mod_custom'");
			$this->data["modules"] = $query->result();
		}
		else
		{
			$this->data["modules"] = -1;
		}

		$query = $this->db->query("SHOW TABLES LIKE 'jos_users'");

		if($query->num_rows() > 0)
		{
			$query = $this->db->query("SELECT id FROM jos_users WHERE username != 'admin'");
			$this->data["users"] = $query->result();
		}
		else
		{
			$this->data["users"] = -1;
		}

		$query = $this->db->query("SHOW TABLES LIKE 'jos_docman_categories'");

		if($query->num_rows() > 0)
		{
			$query = $this->db->query("SELECT docman_category_id FROM jos_docman_categories");
			$this->data["docman_categories"] = $query->result();
		}
		else
		{
			$this->data["docman_categories"] = -1;
		}

		$query = $this->db->query("SHOW TABLES LIKE 'jos_docman_documents'");

		if($query->num_rows() > 0)
		{
			$query = $this->db->query("SELECT docman_document_id FROM jos_docman_documents");
			$this->data["docman"] = $query->result();
		}
		else
		{
			$this->data["docman"] = -1;
		}

		$this->load->view("common/header", $this->data);
		$this->load->view("common/message", array("messages" => $this->messages, "errors" => $this->errors));
		$this->load->view("admin/joomla/step1", $this->data);
		$this->load->view("common/footer", $this->data);
	}

	public function step2()
	{
		$this->load->helper("password");
		$site_id = Mainframe::active_site_id();

		$this->db->query("SET FOREIGN_KEY_CHECKS=0");
		$this->db->query("UPDATE `menu_items` SET `page_id`=null, `parent_id`=null");
		$this->db->query("DELETE FROM `menu_items`");
		$this->db->query("DELETE FROM `menus`");
		$this->db->query("DELETE FROM `pages`");
		$this->db->query("DELETE FROM `categories`");
		$this->db->query("DELETE FROM `users` WHERE user_id > 1");
		$this->db->query("DELETE FROM `module_instances`");
		$this->db->query("DELETE FROM `module_settings`");
		$this->db->query("DELETE FROM `document`");
		$this->db->query("DELETE FROM `content_values`");

		$this->db->query("ALTER TABLE `menu_items` AUTO_INCREMENT = 1");
		$this->db->query("ALTER TABLE `menus` AUTO_INCREMENT = 1");
		$this->db->query("ALTER TABLE `pages` AUTO_INCREMENT = 1");
		$this->db->query("ALTER TABLE `content_values` AUTO_INCREMENT = 1");
		$this->db->query("ALTER TABLE `categories` AUTO_INCREMENT = 1");
		$this->db->query("ALTER TABLE `users` AUTO_INCREMENT = 1");
		$this->db->query("ALTER TABLE `document` AUTO_INCREMENT = 1");
		$this->db->query("ALTER TABLE `module_instances` AUTO_INCREMENT = 1");
		$this->db->query("ALTER TABLE `module_settings` AUTO_INCREMENT = 1");

		$query = $this->db->query("ALTER TABLE `menus` ADD IF NOT EXISTS `joomla_id` VARCHAR(255)");
		$query = $this->db->query("ALTER TABLE `menu_items` ADD IF NOT EXISTS `joomla_id` VARCHAR(255)");
		$query = $this->db->query("ALTER TABLE `categories` ADD IF NOT EXISTS `joomla_id` VARCHAR(255)");
		$query = $this->db->query("ALTER TABLE `pages` ADD IF NOT EXISTS `joomla_id` VARCHAR(255)");
		$query = $this->db->query("ALTER TABLE `module_instances` ADD IF NOT EXISTS `joomla_id` VARCHAR(255)");
		$query = $this->db->query("ALTER TABLE `users` ADD IF NOT EXISTS `joomla_id` VARCHAR(255)");
		$query = $this->db->query("ALTER TABLE `document` ADD IF NOT EXISTS `joomla_id` VARCHAR(255)");

		$menus_success 				= 0;
		$menus_failed 				= 0;
		$menu_items_success 		= 0;
		$menu_items_failed 			= 0;
		$categories_success 		= 0;
		$categories_failed 			= 0;
		$pages_success 				= 0;
		$pages_failed 				= 0;
		$modules_success 			= 0;
		$modules_failed 			= 0;
		$users_success 				= 0;
		$users_failed 				= 0;
		$docman_success 			= 0;
		$docman_failed 				= 0;
		$docman_categories_success 	= 0;
		$docman_categories_failed 	= 0;
		$links_updated 				= 0;

		$query = $this->db->query("SELECT * FROM jos_users WHERE username != 'admin'");

		foreach($query->result() as $user)
		{
			if($user->id == "")
			{
				continue;
			}

			$admin 			= ($user->usertype == "Administrator" || $user->usertype == "Super Administrator");
			$active 		= !$user->block;
			$password 		= generatePassword(8);
			$password_hash 	= password_hash($password, PASSWORD_BCRYPT);
			$name_parts 	= explode(" ", $user->name);
			$fname 			= (isset($name_parts[0]) ? $name_parts[0] : "");
			$lname 			= (isset($name_parts[1]) ? $name_parts[1] : "");

			$this->db->query("INSERT INTO `users` SET
			                 `username`='" . addslashes($user->username) . "',
			                 `password`='" . $password_hash . "',
			                 `fname`='" . addslashes($fname) . "',
			                 `lname`='" . addslashes($lname) . "',
			                 `email`='" . $user->email . "',
			                 `joined`='" . $user->registerDate . "',
			                 `last_login`='" . $user->lastvisitDate . "',
			                 `admin`='" . ($admin ? 1 : 0) . "',
			                 `active`='" . ($active ? 1 : 0) . "',
				             `joomla_id`='" . $user->id . "'");

			$this->messages[] = "User `" . $user->username . "` Imported. New password: " . $password;
			$users_success++;
		}
		$this->messages[] = $users_success . " users imported";
		if($users_failed > 0) { $this->errors[] = number_format($users_failed, 0) . " users failed"; }

		$query = $this->db->query("SELECT * FROM jos_categories");

		foreach($query->result() as $category)
		{
			if($category->id == "")
			{
				continue;
			}

			if($category->extension == "com_content" && $category->path != "")
			{
				$this->db->query("INSERT INTO `categories` SET
				                 `site_id`='" . $site_id . "',
				                 `name`='" . addslashes($category->title) . "',
				                 `joomla_id`='" . $category->id . "'");
				// $this->messages[] = "Category `" . $category->title . "` Imported";
				$categories_success++;
			}
		}

		$query = $this->db->query("SELECT * FROM jos_docman_categories");

		foreach($query->result() as $category)
		{
			if($category->docman_category_id == "")
			{
				continue;
			}

			$this->db->query("INSERT INTO `categories` SET
			                 `site_id`='" . $site_id . "',
			                 `name`='" . addslashes($category->title) . "',
			                 `joomla_id`='DOCMAN:" . $category->docman_category_id . "'");
			// $this->messages[] = "Category `" . $category->title . "` Imported";
			$docman_categories_success++;
		}

		$query = $this->db->query("SELECT * FROM jos_content");

		foreach($query->result() as $content)
		{
			set_time_limit(30);

			if($content->id == "")
			{
				continue;
			}

			$query2 		= $this->db->query("SELECT `category_id` FROM `categories` WHERE `joomla_id`='" . $content->catid . "'");
			$category_id 	= (isset($query2->row()->category_id) ? $query2->row()->category_id : null);
			$page_content 	= $content->introtext . $content->fulltext;
			$page_content 	= $this->content_cleanup($page_content);
			$has_h1 		= preg_match('/<h1/i', $page_content);
			$meta 			= json_decode($content->metadata);

			if($category_id == "")
			{
				$category_id = "NULL";
				// $this->errors[] = "Category ID For `" . $content->title . "` Not Found";
				// continue;
			}

			$this->db->query("INSERT INTO `pages` SET
			                 `site_id`='" . $site_id . "',
			                 `category_id`=" . $category_id . ",
			                 `content_type_id`=1,
			                 `created`='" . $content->created . "',
			                 `modified`='" . $content->modified . "',
			                 `title`='" . addslashes($content->title) . "',
			                 `title_heading_level`=" . ($has_h1 ? 0 : 1) . ",
			                 `url`='" . $content->alias . "',
			                 `description`='" . addslashes((isset($meta->description) ? $meta->description : null)) . "',
			                 `content`=null,
			                 `searchable`=1,
			                 `published`='" . ($content->state == 1 ? 1 : 0) . "',
				             `joomla_id`='" . $content->id . "'");
			$page_id = $this->db->insert_id();
			$this->db->query("INSERT INTO `acl` SET `page_id`=?, acl_role_id=1, `read`=" . ($content->access > 1 ? 1 : 0) . ", `write`=0", array($page_id));
			$this->db->query("INSERT INTO `acl` SET `page_id`=?, acl_role_id=2, `read`=" . ($content->access > 1 ? 1 : 0) . ", `write`=0", array($page_id));
			$this->db->query("INSERT INTO `acl` SET `page_id`=?, acl_role_id=3, `read`=1, `write`=1", array($page_id));
			$this->db->query("INSERT INTO `content_values` SET `page_id`='" . $page_id . "', `key`='content1', `value`='" . addslashes($page_content) . "'");

			// $this->messages[] = "Page `" . $content->title . "` Imported";
			$pages_success++;
		}

		$query = $this->db->query("SELECT * FROM jos_docman_documents");

		foreach($query->result() as $docman)
		{
			set_time_limit(30);

			if($docman->docman_document_id == "")
			{
				continue;
			}

			$query2 		= $this->db->query("SELECT `category_id` FROM `categories` WHERE `joomla_id`='DOCMAN:" . $docman->docman_category_id . "'");
			$category_id 	= (isset($query2->row()->category_id) ? $query2->row()->category_id : null);

			if($category_id == "")
			{
				$category_id = "NULL";
			}

			$query2 		= $this->db->query("SELECT `user_id` FROM `users` WHERE `joomla_id`='" . $docman->created_by . "'");
			$created_user_id = (isset($query2->row()->user_id) ? $query2->row()->user_id : null);

			if(!$created_user_id)
			{
				$created_user_id = "NULL";
			}

			$query2 		= $this->db->query("SELECT `user_id` FROM `users` WHERE `joomla_id`='" . $docman->modified_by . "'");
			$modified_user_id = (isset($query2->row()->user_id) ? $query2->row()->user_id : null);

			if(!$modified_user_id)
			{
				$modified_user_id = "NULL";
			}

			$url = preg_replace('/[^a-z0-9\-_]/', '-', strtolower($docman->dmname));
			$url = preg_replace('/-{2,10}/', '-', $url);
			$url = preg_replace('/(^-|-$)/', '', $url);

			$this->db->query("INSERT INTO `document` SET
			                 `site_id`='" . $site_id . "',
			                 `category_id`=" . $category_id . ",
			                 `title`='" . addslashes($docman->title) . "',
			                 `description`='" . addslashes($docman->description) . "',
			                 `filename`='" . addslashes($docman->storage_path) . "',
			                 `created`='" . $docman->created_on . "',
			                 `created_user_id`=" . $created_user_id . ",
			                 `modified`='" . $docman->modified_on . "',
			                 `modified_user_id`=" . $modified_user_id . ",
			                 `url`='" . $url . "',
			                 `published`=" . ($docman->published == 1 ? 1 : 0) . ",
				             `joomla_id`='" . $docman->docman_document_id . "'");

			$document_id = $this->db->insert_id();
			$this->db->query("INSERT INTO `acl` SET `document_id`=?, acl_role_id=1, `read`=" . ($docman->access == 1 ? 1 : 0) . ", `write`=0", array($document_id));
			$this->db->query("INSERT INTO `acl` SET `document_id`=?, acl_role_id=2, `read`=" . ($docman->access == 1 ? 1 : 0) . ", `write`=0", array($document_id));
			$this->db->query("INSERT INTO `acl` SET `document_id`=?, acl_role_id=3, `read`=1, `write`=1", array($document_id));

			// if($category_id)
			// {
			// 	$this->db->query("INSERT INTO `document_category` SET `document_id`='" . $document_id . "', `category_id`='" . $category_id . "'");
			// }

			$docman_success++;
		}

		$query = $this->db->query("SELECT * FROM jos_menu_types");

		foreach($query->result() as $menu)
		{
			if($menu->id == "")
			{
				continue;
			}

			$this->db->query("INSERT INTO `menus` SET
			                 `site_id`='" . $site_id . "',
			                 `name`='" . addslashes($menu->title) . "',
				             `joomla_id`='" . $menu->menutype . "'");
			// $this->messages[] = "Menu `" . $menu->title . "` Imported";
			$menus_success++;
			$menu_id = $this->db->insert_id();

			$this->db->query('INSERT INTO `module_instances` SET `module_id`=(SELECT `module_id` FROM `modules` WHERE `file_name`="menu"), `site_id`=1, `tag`="' . addslashes($menu->title) . '", `position`="menu", `sort`=1, `published`=1, `always_on`=1');
			$query2 = $this->db->query('SELECT MAX(module_instance_id) AS module_instance_id FROM `module_instances`');
			$module_instance_id = $query2->row()->module_instance_id;
			$this->db->query('INSERT INTO `module_settings` SET `module_instance_id`=' . $module_instance_id . ', `key`="menu_id", `value`=' . $menu_id);
			$this->db->query('INSERT INTO `module_settings` SET `module_instance_id`=' . $module_instance_id . ', `key`="show_icons", `value`="submenu"');
			$this->db->query('INSERT INTO `module_settings` SET `module_instance_id`=' . $module_instance_id . ', `key`="more_text", `value`="<em class=\"fas fa-bars\" aria-hidden="true"></em> More"');
			$this->db->query('INSERT INTO `module_settings` SET `module_instance_id`=' . $module_instance_id . ', `key`="menu_text", `value`="<em class=\"fas fa-bars\" aria-hidden="true"></em> Menu"');
			$this->db->query('INSERT INTO `module_settings` SET `module_instance_id`=' . $module_instance_id . ', `key`="duplicate_parent_links", `value`=1');
			$this->db->query('INSERT INTO `module_settings` SET `module_instance_id`=' . $module_instance_id . ', `key`="search", `value`=1');
			$this->db->query('INSERT INTO `module_settings` SET `module_instance_id`=' . $module_instance_id . ', `key`="search_action", `value`="/search"');
			$this->db->query('INSERT INTO `module_settings` SET `module_instance_id`=' . $module_instance_id . ', `key`="search_legend", `value`="What are you looking for?"');

			$query2 = $this->db->query("SELECT `page_id` FROM `pages`");
			if($query2 && $query2->num_rows())
			{
				foreach($query2->result() as $row)
				{
					$this->db->query("INSERT INTO `modules_pages` SET `module_instance_id`=" . $module_instance_id . ", `page_id`=" . $row->page_id);
				}
			}
		}

		$query = $this->db->query("SELECT * FROM jos_menu");

		foreach($query->result() as $item)
		{
			if($item->id == "" || $item->menutype == "menu")	// "menu" is the admin menu
			{
				continue;
			}

			if($item->path != "")
			{
				$params 	= json_decode($item->params);
				if($item->type == "alias")
				{
					$url 		= "";
					$query4 	= $this->db->query("SELECT * FROM `jos_menu` WHERE `id`='" . $params->aliasoptions . "'");
					// $this->messages[] = "`" . $item->title . "` aliased to `" . $query4->row()->title . "`";
					// Change item to the alias before further processing.
					$item 		= $query4->row();
				}

				$query2 	= $this->db->query("SELECT `menu_id` FROM `menus` WHERE `joomla_id`='" . $item->menutype . "'");
				$menu_id 	= (isset($query2->row()->menu_id) ? $query2->row()->menu_id : null);

				if($item->component_id == 22) // com_content
				{
					preg_match_all('/&id=(.*)$/', $item->link, $matches);
					$page_id 	= (isset($matches[1][0]) ? $matches[1][0] : null);
					$query3 	= $this->db->query("SELECT `page_id` FROM `pages` WHERE `joomla_id`='" . $page_id . "'");
					$page_id 	= (isset($query3->row()->page_id) ? $query3->row()->page_id : null);
				}
				else
				{
					$query3 	= $this->db->query("SELECT `page_id` FROM `pages` WHERE `url`='" . $item->alias . "'");
					$page_id 	= (isset($query3->row()->page_id) ? $query3->row()->page_id : null);
				}

				if($menu_id == "")
				{
					$this->errors[] = "Menu ID For `" . $item->title . "` Not Found";
					$menu_items_failed++;
					continue;
				}

				if($page_id == "")
				{
					$page_id = "NULL";
					// $this->errors[] = "Page ID For `" . $item->title . "` Not Found (`" . $item->path . "`)";
					// $menu_items_failed++;
					// continue;
				}

				if($item->type == "component")
				{
					$url = "";
				}
				else if($item->type == "url")
				{
					$url = $item->link;
				}
				else if($item->type == "separator")
				{
					$url = "#";
					$page_id = "NULL";
				}

				$this->db->query("INSERT INTO `menu_items` SET
				                 `menu_id`='" . $menu_id . "',
				                 `title`='" . addslashes($item->title) . "',
				                 `page_id`=" . $page_id . ",
				                 `url`='" . $url . "',
				                 `sort`='" . $item->ordering . "',
				                 `published`='" . ($item->published == 1 ? 1 : 0) . "',
				             	 `joomla_id`='" . $item->id . "'");
				// $this->messages[] = "Menu Item `" . $item->title . "` Imported";
				$menu_item_id = $this->db->insert_id();
				$this->db->query("INSERT INTO `acl` SET `menu_item_id`=?, acl_role_id=1, `read`=1, `write`=0", array($menu_item_id));
				$this->db->query("INSERT INTO `acl` SET `menu_item_id`=?, acl_role_id=2, `read`=1, `write`=0", array($menu_item_id));
				$this->db->query("INSERT INTO `acl` SET `menu_item_id`=?, acl_role_id=3, `read`=1, `write`=1", array($menu_item_id));

				$menu_items_success++;
			}
		}

		// Go through all the menu items again and update their parent IDs.
		foreach($query->result() as $item)
		{
			if($item->id == "")
			{
				continue;
			}

			if($item->path != "")
			{
				$query2 		= $this->db->query("SELECT `menu_item_id` FROM `menu_items` WHERE `joomla_id`='" . $item->parent_id . "'");
				$menu_item_id 	= (isset($query2->row()->menu_item_id) ? $query2->row()->menu_item_id : null);

				if($menu_item_id)
				{
					$this->db->query("UPDATE `menu_items` SET
				    	             `parent_id`='" . $menu_item_id . "'
				        	         WHERE `joomla_id`='" . $item->id . "'");
				}
				else
				{
					$this->errors[] = "Could not find parent menu ID for `" . $item->title . "`";
				}
			}
		}

		// Rebuild page URLs based on menu tree
		$sql = "SELECT IF(p5.page_id IS NOT NULL, p5.page_id,
						IF(p4.page_id IS NOT NULL, p4.page_id,
						IF(p3.page_id IS NOT NULL, p3.page_id,
						IF(p2.page_id IS NOT NULL, p2.page_id,
						IF(p.page_id IS NOT NULL, p.page_id, ''))))) AS page_id,
				CONCAT(p.url,
				IF(p2.url='', '', CONCAT('/', p2.url)),
				IF(p3.url='', '', CONCAT('/', p3.url)),
				IF(p4.url='', '', CONCAT('/', p4.url)),
				IF(p5.url='', '', CONCAT('/', p5.url))) AS url
				FROM menu_items AS i
				LEFT JOIN menu_items AS i2 ON i2.parent_id=i.menu_item_id
				LEFT JOIN menu_items AS i3 ON i3.parent_id=i2.menu_item_id
				LEFT JOIN menu_items AS i4 ON i4.parent_id=i3.menu_item_id
				LEFT JOIN menu_items AS i5 ON i4.parent_id=i4.menu_item_id
				INNER JOIN pages AS p ON i.page_id=p.page_id
				LEFT JOIN pages AS p2 ON i2.page_id=p2.page_id
				LEFT JOIN pages AS p3 ON i3.page_id=p3.page_id
				LEFT JOIN pages AS p4 ON i4.page_id=p4.page_id
				LEFT JOIN pages AS p5 ON i5.page_id=p5.page_id
				";

		$query = $this->db->query($sql);

		foreach($query->result() as $row)
		{
			if($row->url) {
				$this->db->query("UPDATE `pages` SET `url`='" . $row->url . "' WHERE `page_id`='" . $row->page_id . "'");
			}
		}

		$query = $this->db->query("SELECT * FROM jos_modules WHERE `module`='mod_custom'");

		foreach($query->result() as $module)
		{
			set_time_limit(30);

			if($module->id == "")
			{
				continue;
			}

			$this->db->query("INSERT INTO `module_instances` SET `site_id`='" . $site_id . "', `module_id`=12, `tag`='" . addslashes($module->title) . "', `position`='" . $module->position . "', `always_on`=1, `published`=1, `joomla_id`='" . $module->id . "'"); // Custom HTML
			$module_instance_id = $this->db->insert_id();
			$module->content = $this->content_cleanup($module->content);

			$this->db->query("INSERT INTO `module_settings` SET `module_instance_id`='" . $module_instance_id . "', `key`='number_of_columns', `value`='1'");
			$this->db->query("INSERT INTO `module_settings` SET `module_instance_id`='" . $module_instance_id . "', `key`='title', `value`='" . ($module->showtitle ? addslashes($module->title) : '') . "'");
			$this->db->query("INSERT INTO `module_settings` SET `module_instance_id`='" . $module_instance_id . "', `key`='title_heading_level', `value`='" . ($module->showtitle ? 'h3' : '') . "'");
			$this->db->query("INSERT INTO `module_settings` SET `module_instance_id`='" . $module_instance_id . "', `key`='module_class', `value`=''");
			$this->db->query("INSERT INTO `module_settings` SET `module_instance_id`='" . $module_instance_id . "', `key`='size_sm1', `value`='12'");
			$this->db->query("INSERT INTO `module_settings` SET `module_instance_id`='" . $module_instance_id . "', `key`='size_md1', `value`='12'");
			$this->db->query("INSERT INTO `module_settings` SET `module_instance_id`='" . $module_instance_id . "', `key`='size_lg1', `value`='12'");
			$this->db->query("INSERT INTO `module_settings` SET `module_instance_id`='" . $module_instance_id . "', `key`='size_xl1', `value`='12'");
			$this->db->query("INSERT INTO `module_settings` SET `module_instance_id`='" . $module_instance_id . "', `key`='html1', `value`='" . addslashes($module->content) . "'");

			// $this->messages[] = "Module `" . $module->title . "` Imported";
			$modules_success++;
		}

		// Look for links to content items and replace them with updated URLs.
		$query = $this->db->query("SELECT * FROM `content_values` WHERE `key`='content1' AND
		                          (`value` LIKE '%com_content%' OR `value` LIKE '%com_docman%' OR `value` LIKE '%doc_download%')");

		foreach($query->result() as $content)
		{
			preg_match_all('/href="((.*?)com_content(.*?)&(amp;)?id=(.*?)(&(.*?))?)"/', $content->value, $links);

			for($i=0; $i<count($links[0]); $i++)
			{
				// Fifth index is the content's old ID, which is saved in `pages`.`joomla_id`
				if(isset($links[5][$i]))
				{
					$query2 = $this->db->query("SELECT * FROM `pages` WHERE `joomla_id`='" . $links[5][$i] . "'");

					if($query2 && isset($query2->row()->url))
					{
						$new_link = "/" . $query2->row()->url;
						$content->value = str_replace($links[1][$i], $new_link, $content->value);
						$links_updated++;
					}
				}
			}

			//http://dev.rmh.org/index.php?option=com_docman&task=doc_download&gid=265&Itemid=656
			preg_match_all('/href="((.*?)com_docman(.*?)&(amp;)?gid=([0-9]+)(&(.*?))?)"/', $content->value, $links);

			for($i=0; $i<count($links[0]); $i++)
			{
				// Fifth index is the content's old ID, which is saved in `documents`.`joomla_id`
				if(isset($links[5][$i]))
				{
					$query2 = $this->db->query("SELECT * FROM `document` WHERE `joomla_id`='" . $links[5][$i] . "'");

					if($query2 && isset($query2->row()->url))
					{
						$new_link = "/document/" . $query2->row()->url;
						$content->value = str_replace($links[1][$i], $new_link, $content->value);
						$links_updated++;
					}
					else
					{
						$this->errors[] = "Failed to find document with Joomla ID " . $links[5][$i];
					}
				}
			}

			//http://rmh.org/archives/doc_download/621-download-the-patient-visitor-handbook
			preg_match_all('/href="((.*?)\/doc_download\/(.*?)-(.*?))"/', $content->value, $links);

			for($i=0; $i<count($links[0]); $i++)
			{
				// Third index is the content's old ID, which is saved in `documents`.`joomla_id`
				if(isset($links[3][$i]))
				{
					$query2 = $this->db->query("SELECT * FROM `document` WHERE `joomla_id`='" . $links[3][$i] . "'");

					if($query2 && isset($query2->row()->url))
					{
						$new_link = "/document/" . $query2->row()->url;
						$content->value = str_replace($links[1][$i], $new_link, $content->value);
						$links_updated++;
					}
					else
					{
						$this->errors[] = "Failed to find document with Joomla ID " . $links[3][$i];
					}
				}
			}

			$this->db->query("UPDATE `content_values` SET `value`='" . addslashes($content->value) . "' WHERE `content_value_id`='" . $content->content_value_id . "'");
		}

		// Look for links to content items and replace them with updated URLs.
		$query = $this->db->query("SELECT * FROM `module_settings` WHERE `key`='html1' AND
		                          (`value` LIKE '%com_content%' OR `value` LIKE '%com_docman%' OR `value` LIKE '%doc_download%')");

		foreach($query->result() as $content)
		{
			preg_match_all('/href="((.*?)com_content(.*?)&(amp;)?id=(.*?)(&(.*?))?)"/', $content->value, $links);

			for($i=0; $i<count($links[0]); $i++)
			{
				// Fifth index is the content's old ID, which is saved in `pages`.`joomla_id`
				if(isset($links[5][$i]))
				{
					$query2 = $this->db->query("SELECT * FROM `pages` WHERE `joomla_id`='" . $links[5][$i] . "'");

					if($query2 && isset($query2->row()->url))
					{
						$new_link = "/" . $query2->row()->url;
						$content->value = str_replace($links[1][$i], $new_link, $content->value);
						$links_updated++;
					}
				}
			}

			//http://dev.rmh.org/index.php?option=com_docman&task=doc_download&gid=265&Itemid=656
			preg_match_all('/href="((.*?)com_docman(.*?)&(amp;)?gid=([0-9]+)(&(.*?))?)"/', $content->value, $links);

			for($i=0; $i<count($links[0]); $i++)
			{
				// Fifth index is the content's old ID, which is saved in `documents`.`joomla_id`
				if(isset($links[5][$i]))
				{
					$query2 = $this->db->query("SELECT * FROM `document` WHERE `joomla_id`='" . $links[5][$i] . "'");

					if($query2 && isset($query2->row()->url))
					{
						$new_link = "/document/" . $query2->row()->url;
						$content->value = str_replace($links[1][$i], $new_link, $content->value);
						$links_updated++;
					}
					else
					{
						$this->errors[] = "Failed to find document with Joomla ID " . $links[5][$i];
					}
				}
			}

			//http://rmh.org/archives/doc_download/621-download-the-patient-visitor-handbook
			preg_match_all('/href="((.*?)\/doc_download\/(.*?)-(.*?))"/', $content->value, $links);

			for($i=0; $i<count($links[0]); $i++)
			{
				// Third index is the content's old ID, which is saved in `documents`.`joomla_id`
				if(isset($links[3][$i]))
				{
					$query2 = $this->db->query("SELECT * FROM `document` WHERE `joomla_id`='" . $links[3][$i] . "'");

					if($query2 && isset($query2->row()->url))
					{
						$new_link = "/document/" . $query2->row()->url;
						$content->value = str_replace($links[1][$i], $new_link, $content->value);
						$links_updated++;
					}
					else
					{
						$this->errors[] = "Failed to find document with Joomla ID " . $links[3][$i];
					}
				}
			}
			$this->db->query("UPDATE `module_settings` SET `value`='" . addslashes($content->value) . "' WHERE `module_setting_id`='" . $content->module_setting_id . "'");
		}

		$this->messages[] = number_format($menus_success, 0) . " menus imported";
		if($menus_failed > 0) { $this->errors[] = number_format($menus_failed, 0) . " menus failed"; }
		$this->messages[] = number_format($menu_items_success, 0) . " menu items imported";
		if($menu_items_failed > 0) { $this->errors[] = number_format($menu_items_failed, 0) . " menu items failed"; }
		$this->messages[] = number_format($categories_success, 0) . " categories imported";
		if($categories_failed > 0) { $this->errors[] = number_format($categories_failed, 0) . " categories failed"; }
		$this->messages[] = number_format($pages_success, 0) . " pages imported";
		if($pages_failed > 0) { $this->errors[] = number_format($pages_failed, 0) . " pages failed"; }
		$this->messages[] = number_format($modules_success, 0) . " HTML modules imported";
		if($modules_failed > 0) { $this->errors[] = number_format($modules_failed, 0) . " HTML modules failed"; }
		$this->messages[] = number_format($docman_success, 0) . " DocMan documents imported";
		if($docman_failed > 0) { $this->errors[] = number_format($docman_failed, 0) . " DocMan documents failed"; }
		$this->messages[] = number_format($docman_categories_success, 0) . " DocMan categories imported";
		if($docman_categories_failed > 0) { $this->errors[] = number_format($docman_categories_failed, 0) . " DocMan categories failed"; }
		$this->messages[] = number_format($links_updated, 0) . " links were updated";

		$query = $this->db->query("ALTER TABLE `menus` DROP COLUMN IF EXISTS `joomla_id`");
		$query = $this->db->query("ALTER TABLE `menu_items` DROP COLUMN IF EXISTS `joomla_id`");
		$query = $this->db->query("ALTER TABLE `categories` DROP COLUMN IF EXISTS `joomla_id`");
		$query = $this->db->query("ALTER TABLE `pages` DROP COLUMN IF EXISTS `joomla_id`");
		$query = $this->db->query("ALTER TABLE `module_instances` DROP COLUMN IF EXISTS `joomla_id`");
		$query = $this->db->query("ALTER TABLE `users` DROP COLUMN IF EXISTS `joomla_id`");
		$query = $this->db->query("ALTER TABLE `document` DROP COLUMN IF EXISTS `joomla_id`");
		$this->db->query("SET FOREIGN_KEY_CHECKS=1");

		$this->load->view("common/header", $this->data);
		$this->load->view("common/message", array("messages" => $this->messages, "errors" => $this->errors));
		$this->load->view("admin/joomla/step2", $this->data);
		$this->load->view("common/footer", $this->data);
	}

	private function content_cleanup($content)
	{
		// Run HTML Purifier on our content.
		$content = $this->purifier->purify($content);
		// HTML Purifier CDATA's our script contents, and this is easier than figuring out why.
		$content = str_replace(array("<!--//--><![CDATA[//><!--", "//--><!]]>"), "", $content);
		// <div> tags which are only used for setting a width will be removed.
		$content = preg_replace('/<div style="width:(.*?);?">((.|\s)*?)<\/div>/', '$2', $content);

		return $content;
	}
}
