<?php
/*
Plugin Name: AIT Languages
Plugin URI: http://ait-themes.club
Version: 1.2.8
Author: AitThemes.Club
Author URI: http://ait-themes.club
Description: Adds multilingual capability to WordPress
Text Domain: ait-languages
Domain Path: /languages
*/

/* stable@r223 */

/*
 * Copyright 2011-2013 Frédéric Demarle
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 *
 */

define('AIT_LANGUAGES_ENABLED', true);

define('POLYLANG_VERSION', '1.2.8');
define('PLL_MIN_WP_VERSION', '3.7');

define('POLYLANG_BASENAME', plugin_basename(__FILE__)); // plugin name as known by WP

define('POLYLANG_DIR', dirname(__FILE__)); // our directory
define('PLL_INC', POLYLANG_DIR . '/include');
define('PLL_FRONT_INC',  POLYLANG_DIR . '/frontend');
define('PLL_ADMIN_INC',  POLYLANG_DIR . '/admin');

// default directory to store user data such as custom flags
if (!defined('PLL_LOCAL_DIR'))
	define('PLL_LOCAL_DIR', WP_CONTENT_DIR . '/polylang');

// includes local config file if exists
if (file_exists(PLL_LOCAL_DIR . '/pll-config.php'))
	include_once(PLL_LOCAL_DIR . '/pll-config.php');

// our url. Don't use WP_PLUGIN_URL http://wordpress.org/support/topic/ssl-doesnt-work-properly
define('POLYLANG_URL', plugins_url('/' . basename(POLYLANG_DIR)));

// default url to access user data such as custom flags
if (!defined('PLL_LOCAL_URL'))
	define('PLL_LOCAL_URL', content_url('/polylang'));

// cookie name. no cookie will be used if set to false
if (!defined('PLL_COOKIE'))
	define('PLL_COOKIE', 'pll_language');

// backward compatibility WP < 3.6
// the search form js is no more needed in WP 3.6+ except if the search form is hardcoded elsewhere than in searchform.php
if (!defined('PLL_SEARCH_FORM_JS') && !version_compare($GLOBALS['wp_version'], '3.6', '<'))
	define('PLL_SEARCH_FORM_JS', false);

/*
 * controls the plugin, as well as activation, and deactivation
 *
 * @since 0.1
 */
class Polylang {

	/*
	 * constructor
	 *
	 * @since 0.1
	 */
	public function __construct() {
		// manages plugin activation and deactivation
		register_activation_hook( __FILE__, array(&$this, 'activate'));
		register_deactivation_hook( __FILE__, array(&$this, 'deactivate'));

		// stopping here if we are going to deactivate the plugin (avoids breaking rewrite rules)
		if (isset($_GET['action'], $_GET['plugin']) && 'deactivate' == $_GET['action'] && plugin_basename(__FILE__) == $_GET['plugin'])
			return;

		// avoid loading polylang admin for frontend ajax requests
		if (!defined('PLL_AJAX_ON_FRONT'))
			define('PLL_AJAX_ON_FRONT', defined('DOING_AJAX') && DOING_AJAX && !isset($_REQUEST['pll_ajax_backend']));

		if (!defined('PLL_ADMIN'))
			define('PLL_ADMIN', defined('DOING_CRON') || (is_admin() && !PLL_AJAX_ON_FRONT));

		if (!defined('PLL_SETTINGS'))
			define('PLL_SETTINGS', is_admin() && isset($_GET['page']) && $_GET['page'] == 'ait-languages');

		// blog creation on multisite
		add_action('wpmu_new_blog', array(&$this, 'wpmu_new_blog'));

		// FIXME maybe not available on every installations but widely used by WP plugins
		spl_autoload_register(array(&$this, 'autoload')); // autoload classes

		// override load text domain waiting for the language to be defined
		// here for plugins which load text domain as soon as loaded :(
		if (!defined('PLL_OLT') || PLL_OLT)
			new PLL_OLT_Manager();

		// plugin initialization
		// take no action before all plugins are loaded
		add_action('plugins_loaded', array(&$this, 'init'), 1);

		require_once(PLL_INC . '/functions.php');

		// extra code for compatibility with some plugins
		if (!defined('PLL_PLUGINS_COMPAT') || PLL_PLUGINS_COMPAT)
			new PLL_Plugins_Compat();

		if(is_admin()){
			add_action('ait-after-import', array($this, 'reactivateAfterDemoContentImport'), 1, 2);
			add_action('ait-before-import', array($this, 'clearLanguagesList'), 1);
			add_action('ait-after-import', array($this, 'clearLanguagesList'), 1, 2);
		}
	}



	public function reactivateAfterDemoContentImport($whatToImport, $results = '')
	{
		if($whatToImport == 'demo-content'){

			delete_transient('pll_languages_list');
			wp_cache_delete('alloptions', 'options'); // will force to load new options from DB in next get_option call

			$options = get_option('polylang');
			$adminModel = new PLL_Admin_Model($options);
			$lang = $adminModel->get_language($options['default_lang']);

			$locale = 'en_US';
			if($lang){
				$locale = $lang->locale;
			}

			update_user_meta(get_current_user_id(), 'user_lang', $locale);

			if($locale === 'en_US'){
				update_option('WPLANG', ''); // for default en_US, value is empty string
			}else{
				update_option('WPLANG', $locale);
			}

			$adminModel->fillExistingPostsTermsWithDefaultLanguage();
		}
	}



	public function clearLanguagesList($whatToImport, $results = '')
	{
		delete_transient('pll_languages_list');
	}


	/*
	 * activation or deactivation for all blogs
	 *
	 * @since 1.2
	 *
	 * @param string $what either 'activate' or 'deactivate'
	 */
	protected function do_for_all_blogs($what) {
		// network
		if (is_multisite() && isset($_GET['networkwide']) && ($_GET['networkwide'] == 1)) {
			global $wpdb;

			foreach ($wpdb->get_col("SELECT blog_id FROM $wpdb->blogs") as $blog_id) {
				switch_to_blog($blog_id);
				$what == 'activate' ? $this->_activate() : $this->_deactivate();
			}
			restore_current_blog();
		}

		// single blog
		else
			$what == 'activate' ? $this->_activate() : $this->_deactivate();
	}

	/*
	 * plugin activation for multisite
	 *
	 * @since 0.1
	 */
	public function activate() {
		global $wp_version;
		load_plugin_textdomain('ait-languages', false, basename(POLYLANG_DIR).'/languages'); // plugin i18n

		if (version_compare($wp_version, PLL_MIN_WP_VERSION , '<'))
			die (sprintf('<p style = "font-family: sans-serif; font-size: 12px; color: #333; margin: -5px">%s</p>',
				sprintf(__('You are using WordPress %s. AIT Languages requires at least WordPress %s.', 'ait-languages'),
					esc_html($wp_version),
					PLL_MIN_WP_VERSION
				)
			));

		$this->do_for_all_blogs('activate');
	}

	/*
	 * plugin activation
	 *
	 * @since 0.5
	 */
	protected function _activate()
	{
		$currentSuportedSlug = $this->getSlugFromCurrentSuportedLocale();

		if ($options = get_option('polylang')) {
			// plugin upgrade
			if (version_compare($options['version'], POLYLANG_VERSION, '<')) {
				$upgrade = new PLL_Upgrade($options);
				$upgrade->upgrade_at_activation();
			}
		}
		// defines default values for options in case this is the first installation
		else {

			$options = $this->getDefaultOptions();

			update_option('polylang', $options);
		}

		$adminModel = new PLL_Admin_Model($options);
		$adminModel->clean_languages_cache();

		$this->addFirstLangOnActivate($currentSuportedSlug, $adminModel);
		$adminModel->fillExistingPostsTermsWithDefaultLanguage();

		// add our rewrite rules
		$this->get_links_model($adminModel, $options);
		flush_rewrite_rules();
	}



	public function getDefaultOptions()
	{
		$currentSuportedSlug = $this->getSlugFromCurrentSuportedLocale();

		$aitCpts = array_values(get_post_types(array('ait-translatable-cpt' => true)));
		$aitTaxs = array_values(get_taxonomies(array('ait-translatable-tax' => true)));

		$wcCpts = array('product', 'product_variation', 'shop_order', 'shop_coupon', 'shop_order_refund', 'shop_webhook'); // exclude woocommerce CPTs
		$wcTaxs = array('product_type', 'product_cat', 'product_tag', 'product_shipping_class', 'shop_order_status'); // exclude woocommerce taxonomies

		global $wc_product_attributes;

		if(isset($wc_product_attributes) and !empty($wc_product_attributes)){
			$wcTaxs = array_merge($wcTaxs, array_keys($wc_product_attributes));
		}

		return array(
			'browser'       => 0, // default language for the front page is set by browser preference
			'rewrite'       => 1, // remove /language/ in permalinks (was the opposite before 0.7.2)
			'hide_default'  => 1, // do not remove URL language information for default language
			'force_lang'    => 0, // do not add URL language information when useless
			'redirect_lang' => 1, // do not redirect the language page to the homepage
			'media_support' => 0, // support languages and translation for media by default
			'sync'          => array(), // synchronisation is disabled by default (was the opposite before 1.2)
			'post_types'    => array_merge($aitCpts, array_values(array_diff(
				get_post_types(array('_builtin' => false, 'show_ui' => false)),
				get_post_types(array('_pll' => true)),
				$aitCpts,
				$wcCpts
			))),
			'taxonomies'    => array_merge($aitTaxs, array_values(array_diff(
				get_taxonomies(array('_builtin' => false, 'show_ui' => false)),
				get_taxonomies(array('_pll' => true)),
				$aitTaxs,
				$wcTaxs
			))),
			'domains'       => array(),
			'version'       => POLYLANG_VERSION,
			'default_lang'  => $currentSuportedSlug,
		);
	}



	protected function addFirstLangOnActivate($currentSuportedSlug, $adminModel)
	{
		if($currentSuportedSlug != 'en'){

			include PLL_ADMIN_INC . '/languages.php';

			$defaultLang = array('en', 'en_US', 'English');

			foreach($languages as $langData){
				if($langData[0] == $currentSuportedSlug){
					$defaultLang = $langData;
					break;
				}
			}

			$adminModel->add_language(array(
				'slug' => $defaultLang[0],
				'locale' => $defaultLang[1],
				'name' => $defaultLang[2],
				'rtl' => isset($defaultLang[3]) ? 1 : 0,
				'term_group' => '',
			));

			PLL_Admin::download_mo($defaultLang[1]);

			$userId = get_current_user_id();
			update_user_meta(get_current_user_id(), 'user_lang', $defaultLang[1]);
			do_action('pll_after_language_switch', array('lang' => $defaultLang[1], 'user' => $userId));

		}else{

			$r = $adminModel->add_language(array(
				'slug' => 'en',
				'locale' => 'en_US',
				'name' => 'English',
				'rtl' => 0,
				'term_group' => '',
			));
		}
	}



	protected function getSlugFromCurrentSuportedLocale()
	{
		$currentLocale = get_locale();

		if($currentLocale != 'en_US'){

			include PLL_ADMIN_INC . '/languages.php';

			foreach($languages as $langData){
				if($langData[1] == $currentLocale){
					return $langData[0];
				}
			}
			return 'en'; // currentLocale is not supported
		}else{
			return 'en';
		}
	}



	/*
	 * plugin deactivation for multisite
	 *
	 * @since 0.1
	 */
	public function deactivate() {
		$this->do_for_all_blogs('deactivate');
	}

	/*
	 * plugin deactivation
	 *
	 * @since 0.5
	 */
	protected function _deactivate() {
		flush_rewrite_rules();
	}

	/*
	 * blog creation on multisite (to set default options)
	 *
	 * @since 0.9.4
	 *
	 * @param int $blog_id
	 */
	public function wpmu_new_blog($blog_id) {
		switch_to_blog($blog_id);
		$this->_activate();
		restore_current_blog();
	}

	/*
	 * autoload classes
	 *
	 * @since 1.2
	 *
	 * @param string $class
	 */
	public function autoload($class) {
		$class = str_replace('_', '-', strtolower(substr($class, 4)));
		foreach (array(PLL_INC, PLL_FRONT_INC, PLL_ADMIN_INC) as $path)
			if (file_exists($file = "$path/$class.php"))
				require_once($file);
	}

	/*
	 * Polylang initialization
	 * setups models and separate admin and frontend
	 *
	 * @since 1.2
	 */
	public function init() {
		global $polylang;

		$options = get_option('polylang', $this->getDefaultOptions());

		// plugin upgrade
		if ($options && version_compare($options['version'], POLYLANG_VERSION, '<')) {
			$upgrade = new PLL_Upgrade($options);
			if (!$upgrade->upgrade()) // if the version is too old
				return;
		}

		$model = PLL_SETTINGS ? new PLL_Admin_Model($options) : new PLL_Model($options);
		$links_model = $this->get_links_model($model);

		if (PLL_ADMIN) {
			$polylang = new PLL_Admin($links_model);
			$polylang->init();
		}
		// do nothing on frontend if no language is defined
		elseif (!is_admin() and $model->get_languages_list()) {
			$polylang = new PLL_Frontend($links_model);
			$polylang->init();
		}
		else{
			do_action('pll_no_language_defined'); // to load overriden textdomains
		}
	}

	/*
	 * setup the links model based on options
	 *
	 * @since 1.2
	 *
	 * @param object $model instance of PLL_Model
	 * @return object implementing "links_model interface"
	 */
	protected function get_links_model(&$model) {
		if (get_option('permalink_structure')) {
			if (2 == $model->options['force_lang'])
				return new PLL_Links_Subdomain($model);
			elseif (3 == $model->options['force_lang'])
				return new PLL_Links_Domain($model);
			else
				return new PLL_Links_Directory($model);
		}
		return new PLL_Links_Default($model);
	}
}

new Polylang();
