<?php
/*
  $Id: ultimateseo.php, v2.5 2019/09/20 Devidash Exp $

  Loaded Commerce, Open Source E-Commerce Solutions
  http://www.loadedcommerce.com

  Based on Ultimate SEO URL's 2.1 by Chemo

  Copyright (c) 2019 LoadedCommerce

  Released under the GNU General Public License
*/

  class ultimateseo {
    var $title;

    function __construct() {
      $this->code = 'ultimateseo';
      $this->title = (defined('MODULE_ADDONS_ULTIMATESEO_TITLE')) ? MODULE_ADDONS_ULTIMATESEO_TITLE : '';
      $this->description = (defined('MODULE_ADDONS_ULTIMATESEO_DESCRIPTION')) ? MODULE_ADDONS_ULTIMATESEO_DESCRIPTION : '';
      if (defined('MODULE_ADDONS_ULTIMATESEO_STATUS')) {
        $this->enabled = ((MODULE_ADDONS_ULTIMATESEO_STATUS == 'True') ? true : false);
      } else {
        $this->enabled = false;
      }
      $this->sort_order  = (defined('MODULE_ADDONS_ULTIMATESEO_SORT_ORDER')) ? (int)MODULE_ADDONS_ULTIMATESEO_SORT_ORDER : 0;
    }

    function check() {
      if (!isset($this->_check)) {
        $check_query = tep_db_query("SELECT configuration_value
                                     from " . TABLE_CONFIGURATION . "
                                     WHERE configuration_key = 'MODULE_ADDONS_ULTIMATESEO_STATUS'");
        $this->_check = tep_db_num_rows($check_query);
      }
      return $this->_check;
    }

    function keys() {
      return array('MODULE_ADDONS_ULTIMATESEO_STATUS', 'SEO_VALIDATION_ON');
    }

    function install() {
      // insert module config values
      tep_db_query("INSERT IGNORE INTO configuration VALUES ('', 'Enable Ultimate SEO URL\'s', 'MODULE_ADDONS_ULTIMATESEO_STATUS', 'True', 'Enable the Ultimate SEO URL\'s Module', '6', '5039', now(), now(), NULL, 'tep_cfg_select_option(array(''True'', ''False''),')");
      tep_db_query("INSERT IGNORE INTO configuration VALUES ('', 'Enable Seo URL validation?', 'SEO_VALIDATION_ON', 'true', 'Enable the SEO URL validation?', '6', '5039', now(), now(), NULL, 'tep_cfg_select_option(array(''true'', ''false''),')");
      //tep_db_query("INSERT IGNORE INTO configuration VALUES ('', 'Enable Seo URL performance diagnostic code?', 'MODULE_ADDONS_ULTIMATESEO_PERFORMANCE', 'false', 'Enable the SEO URL performance diagnostic code by setting this option to \'true\' and adding \"?profile=on\" to any store side url. Turn the diagnostic code off by adding \"?profile=off\" to the url then set this option to \'false\'.', '6', '5039', now(), now(), NULL, 'tep_cfg_select_option(array(''true'', ''false''),')");


      $this->sync_permalink();
      // alter the products and categories table
      /*
      $fields = mysql_list_fields(DB_DATABASE, 'categories_description');
      $columns = mysql_num_fields($fields);
      for ($i = 0; $i < $columns; $i++) {$field_array[] = mysql_field_name($fields, $i);}
      if (!in_array('categories_seo_url', $field_array)) {
        tep_db_query("ALTER TABLE categories_description ADD categories_seo_url VARCHAR(255) NOT NULL;");
        tep_db_query("ALTER TABLE products_description ADD products_seo_url VARCHAR(255) NOT NULL;");
      }
      */
    }

    function remove() {
      $seoConfigGroupID = tep_db_fetch_array(tep_db_query("SELECT configuration_group_id FROM configuration_group WHERE configuration_group_title = 'SEO URLs'"));
      tep_db_query("DELETE FROM configuration_group WHERE configuration_group_title = 'SEO URLs'");
      tep_db_query("DELETE FROM configuration WHERE configuration_key = 'MODULE_ADDONS_ULTIMATESEO_STATUS'");
      tep_db_query("DELETE FROM configuration WHERE configuration_key = 'SEO_VALIDATION_ON'");
      tep_db_query("DELETE FROM configuration WHERE configuration_group_id = '" . $seoConfigGroupID['configuration_group_id'] . "'");
      //tep_db_query("DROP TABLE IF EXISTS `cache`");
      //tep_db_query("ALTER TABLE `categories_description` DROP COLUMN `categories_seo_url`;");
      //tep_db_query("ALTER TABLE `products_description` DROP COLUMN `products_seo_url`;");
      tep_db_query("TRUNCATE TABLE permalinks");
    }
   function sync_permalink() {

			$language_id = 1;
			/*******Default permalink first *************/
			$default_query = tep_db_query("SELECT * FROM default_permalink order by page_name asc");
			while($default = tep_db_fetch_array($default_query)){
				$permalink_name = $default['permalink_name'];
				$check_cat = tep_db_query("SELECT * FROM permalinks WHERE permalink_name = '".$permalink_name."' and language_id = '".(int)$language_id."'");
				if(tep_db_num_rows($check_cat) <= 0){

						$slug =  sanitize($permalink_name);
						$permalink_query = tep_db_query("select permalink_id from " . TABLE_PERMALINK . " where permalink_name = '" .$slug . "' and language_id = '" . (int)$language_id . "'");
						$sql_data_array = array(
										  'language_id' => $language_id,
										  'filename' => $default['php_page_name'],
										  'route' => $default['route'],
										  'permalink_name' => $slug,
										  'permalink_type' => 'static');

						//print_r($sql_data_array);
						tep_db_perform(TABLE_PERMALINK, $sql_data_array);
						$count_d++;
				}

			}
			/*******Default permalink first **************/

			$cat_query = tep_db_query("SELECT CD.categories_name, CD.categories_id FROM categories C INNER JOIN categories_description CD ON C.categories_id = CD.categories_id WHERE CD.language_id = '".(int)$language_id."' group by C.categories_id order by CD.categories_id desc");
			while($cat = tep_db_fetch_array($cat_query)){

				$category_name = $cat['categories_name'];
				$check_cat = tep_db_query("SELECT * FROM permalinks WHERE categories_id = '".(int)$cat['categories_id']."' and language_id = '".(int)$language_id."'");
				if(tep_db_num_rows($check_cat) <= 0){
						  $get_cat_name = get_cat_name_lang($cat['categories_id'],$language_id);
						  $category_name = ($get_cat_name != '')? $get_cat_name : $category_name;

						$slug =  sanitize($category_name);
						$permalink_query = tep_db_query("select permalink_id from " . TABLE_PERMALINK . " where permalink_name = '" .$slug . "' and language_id = '" . (int)$language_id . "'");
						if(tep_db_num_rows ($permalink_query) > 0){
							$suffix = 2;
							$slug = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
						}
						$permalink_query = tep_db_query("select permalink_id from " . TABLE_PERMALINK . " where permalink_name = '" .$slug . "' and language_id = '" . (int)$language_id . "'");
						if(tep_db_num_rows ($permalink_query) > 0){
							$suffix = 2;
							$slug = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) .'-'. mt_rand(1,100);

						}

						$sql_data_array = array('categories_id' => $cat['categories_id'],
										  'language_id' => $language_id,
										  'route' => 'core/index',
										  'permalink_name' => $slug,
										  'permalink_type' => 'category');

						//print_r($sql_data_array);
						tep_db_perform(TABLE_PERMALINK, $sql_data_array);
					   $count_c++;

				}
			}

			$language_id = 1;
			$pro_query = tep_db_query("SELECT PD.products_name, PD.products_id FROM products P INNER JOIN products_description PD  ON P.products_id = PD.products_id WHERE PD.language_id = '".(int)$language_id."'  AND P.products_parent_id = 0 group by P.products_id order by PD.products_id desc");
			while($pro = tep_db_fetch_array($pro_query)){
				$products_name = $pro['products_name'];
				$check_pro = tep_db_query("SELECT * FROM permalinks WHERE products_id = '".(int)$pro['products_id']."' and language_id = '".(int)$language_id."'");
				if(tep_db_num_rows($check_pro) <= 0){

						  $get_prod_name = get_prod_name_lang($pro['products_id'],$language_id);
						  $products_name = ($get_prod_name != '')? $get_prod_name : $products_name;

						$slug =  sanitize($products_name);
						$permalink_query = tep_db_query("select permalink_id from " . TABLE_PERMALINK . " where permalink_name = '" .$slug . "' and language_id = '" . (int)$language_id . "'");
						if(tep_db_num_rows ($permalink_query) > 0){
							$suffix = 2;
							$slug = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
						}
						$permalink_query = tep_db_query("select permalink_id from " . TABLE_PERMALINK . " where permalink_name = '" .$slug . "' and language_id = '" . (int)$language_id . "'");
						if(tep_db_num_rows ($permalink_query) > 0){
							$suffix = 2;
							$slug = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) .'-'. mt_rand(1,100);

						}

						$sql_data_array = array('products_id' => $pro['products_id'],
										  'language_id' => $language_id,
										  'route' => 'core/product_info',
										  'permalink_name' => $slug,
										  'permalink_type' => 'product');

						//print_r($sql_data_array);

						tep_db_perform(TABLE_PERMALINK, $sql_data_array);
						$count_p++;
				}

			}//product sync end
			/*******Manufactures sync start **************/
			sync_manufactures();

			/*******pages categoreis data start **************/
			$cat_query = tep_db_query("SELECT CD.categories_name, CD.categories_id FROM pages_categories C INNER JOIN pages_categories_description CD ON C.categories_id = CD.categories_id WHERE CD.language_id = '".(int)$language_id."'  order by CD.categories_id desc");
			while($cat = tep_db_fetch_array($cat_query)) {
				$category_name = $cat['categories_name'];
					$check_cat = tep_db_query("SELECT * FROM permalinks WHERE pages_categories_id = '".(int)$cat['categories_id']."' and language_id = '".(int)$language_id."' ");
					if(tep_db_num_rows($check_cat) <= 0){
						    $slug =  sanitize($category_name);
							$permalink_query = tep_db_query("select permalink_id from " . TABLE_PERMALINK . " where permalink_name = '" .$slug . "' and language_id = '" . (int)$language_id . "'");
							if(tep_db_num_rows ($permalink_query) > 0){
								$suffix = 2;
							    $slug = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
							}
							$permalink_query = tep_db_query("select permalink_id from " . TABLE_PERMALINK . " where permalink_name = '" .$slug . "' and language_id = '" . (int)$language_id . "'");
							if(tep_db_num_rows ($permalink_query) > 0){
								$suffix = 2;
							    $slug = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) .'-'. mt_rand(1,100);

							}
							$sql_data_array = array('pages_categories_id' => $cat['categories_id'],
											  'language_id' => $language_id,
											  'permalink_name' => $slug,
											  'permalink_type' => 'page_category');
							tep_db_perform(TABLE_PERMALINK, $sql_data_array);
						   $count_pc++;

				}
			}
			$page_query = tep_db_query("SELECT PD.pages_title, PD.pages_id FROM pages P INNER JOIN pages_description PD ON P.pages_id = PD.pages_id  order by PD.pages_id desc");
			while($page = tep_db_fetch_array($page_query)) {
				$pages_name = $page['pages_title'];
					$check_page = tep_db_query("SELECT * FROM permalinks WHERE pages_id = '".(int)$page['pages_id']."' and language_id = '".(int)$language_id."' ");
					if(tep_db_num_rows($check_page) <= 0){
						    $slug =  sanitize($pages_name);
							$permalink_query = tep_db_query("select permalink_id from " . TABLE_PERMALINK . " where permalink_name = '" .$slug . "' and language_id = '" . (int)$language_id . "'");
							if(tep_db_num_rows ($permalink_query) > 0){
								$suffix = 2;
							    $slug = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
							}
							$permalink_query = tep_db_query("select permalink_id from " . TABLE_PERMALINK . " where permalink_name = '" .$slug . "' and language_id = '" . (int)$language_id . "'");
							if(tep_db_num_rows ($permalink_query) > 0){
								$suffix = 2;
							    $slug = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) .'-'. mt_rand(1,100);

							}
							$sql_data_array = array('pages_id' => $page['pages_id'],
											  'language_id' => $language_id,
											  'route' => 'core/pages',
											  'permalink_name' => $slug,
											  'permalink_type' => 'page');
							tep_db_perform(TABLE_PERMALINK, $sql_data_array);
						   $count_pc++;
				}
			}
			/*******pages categoreis sync end **************/
			/*******articles category i.e topics sync start **************/
			$count_topics = 0;
			$topics_query = tep_db_query("SELECT T.*, TD.* from ".TABLE_TOPICS." T INNER JOIN ".TABLE_TOPICS_DESCRIPTION." TD ON T.topics_id = TD.topics_id");
			while($topics = tep_db_fetch_array($topics_query)) {
				$topics_name = $topics['topics_name'];
				tep_db_query("DELETE FROM permalinks WHERE topics_id = '".(int)$topics['topics_id']."' and language_id = '".(int)$language_id."'");
				$check_topics = tep_db_query("SELECT * FROM permalinks WHERE topics_id = '".(int)$topics['topics_id']."'");
				if(tep_db_num_rows($check_topics) <= 0){
						$slug =  sanitize($topics_name);
						$permalink_query = tep_db_query("select permalink_id from " . TABLE_PERMALINK . " where permalink_name = '" .$slug . "'");
						if(tep_db_num_rows ($permalink_query) > 0){
							$suffix = 2;
							$slug = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
						}
						$permalink_query = tep_db_query("select permalink_id from " . TABLE_PERMALINK . " where permalink_name = '" .$slug . "'");
						if(tep_db_num_rows ($permalink_query) > 0){
							$suffix = 2;
							$slug = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) .'-'. mt_rand(1,100);

						}

						$sql_data_array = array('topics_id' => $topics['topics_id'],
										  'language_id' => $language_id,
										  'route' => 'core/articles',
										  'permalink_name' => $slug,
										  'permalink_type' => 'topics');


						tep_db_perform(TABLE_PERMALINK, $sql_data_array);
						$count_topics++;
				}
			}//articles category i.e topics sync end
			/*******articles sync start **************/
			$count_articles = 0;
			$articles_query = tep_db_query("SELECT A.*, AD.* from ".TABLE_ARTICLES." A INNER JOIN ".TABLE_ARTICLES_DESCRIPTION." AD ON A.articles_id = AD.articles_id");
			while($articles = tep_db_fetch_array($articles_query)){
				$articles_name = $articles['articles_name'];
				tep_db_query("DELETE FROM permalinks WHERE articles_id = '".(int)$articles['articles_id']."' and language_id = '".(int)$language_id."'");
				$check_articles = tep_db_query("SELECT * FROM permalinks WHERE articles_id = '".(int)$articles['articles_id']."'");
				if(tep_db_num_rows($check_articles) <= 0){
						$slug =  sanitize($articles_name);
						$permalink_query = tep_db_query("select permalink_id from " . TABLE_PERMALINK . " where permalink_name = '" .$slug . "'");
						if(tep_db_num_rows ($permalink_query) > 0){
							$suffix = 2;
							$slug = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
						}
						$permalink_query = tep_db_query("select permalink_id from " . TABLE_PERMALINK . " where permalink_name = '" .$slug . "'");
						if(tep_db_num_rows ($permalink_query) > 0){
							$suffix = 2;
							$slug = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) .'-'. mt_rand(1,100);

						}

						$sql_data_array = array('articles_id' => $articles['articles_id'],
										  'language_id' => $language_id,
										  'route' => 'core/articles_info',
										  'permalink_name' => $slug,
										  'permalink_type' => 'articles');
						tep_db_perform(TABLE_PERMALINK, $sql_data_array);
						$count_articles++;
				}
			}//articles sync end
			/*******Link categories_description sync start **************/
			sync_link_categories();
			/*******Faq sync start **************/
		    sync_faq_categories();
   }

  }
?>