<?php

/*
 * this class should be used to stores properties and methods shared by the
 * admin and public side of wordpress
 */
class Dahm_Shared
{
    
    //regex
    public $regex_list_of_post_types = '/^(\s*([A-Za-z0-9_-]+\s*,\s*)+[A-Za-z0-9_-]+\s*|\s*[A-Za-z0-9_-]+\s*)$/';
    public $regex_number_ten_digits = '/^\s*\d{1,10}\s*$/';
    public $regex_capability = '/^\s*[A-Za-z0-9_]+\s*$/';
    
    protected static $instance = null;

    private $data = array();

    private function __construct()
    {

		//Add the action associated with the "da_hm_cron_hook". Which is scheduled in Dahm_Admin::schedule_cron_event().
	    add_action( 'da_hm_cron_hook', array( $this, 'da_hm_cron_exec' ) );

        //Set plugin textdomain
        load_plugin_textdomain('dahm', false, 'hreflang-manager/lang/');
        
        $this->data['slug'] = 'da_hm';
        $this->data['ver'] = '1.32';
        $this->data['dir'] = substr(plugin_dir_path(__FILE__), 0, -7);
        $this->data['url'] = substr(plugin_dir_url(__FILE__), 0, -7);

	    //Here are stored the plugin option with the related default values
	    $this->data['options'] = [

            //Database Version -----------------------------------------------------------------------------------------
		    $this->get('slug') . '_database_version' => "0",

		    //General --------------------------------------------------------------------------------------------------
		    $this->get('slug') . '_detect_url_mode' => "wp_request",
		    $this->get('slug') . '_https' => "1",
		    $this->get('slug') . '_auto_trailing_slash' => "1",
		    $this->get('slug') . '_auto_delete' => "1",
		    $this->get('slug') . '_auto_alternate_pages' => "0",
		    $this->get('slug') . '_sanitize_url' => "1",
		    $this->get('slug') . '_sample_future_permalink' => "0",
		    $this->get('slug') . '_show_log' => "0",
		    $this->get('slug') . '_connections_in_menu' => "10",
		    $this->get('slug') . '_meta_box_post_types' => "post, page",
		    $this->get('slug') . '_set_max_execution_time' => "1",
		    $this->get('slug') . '_max_execution_time_value' => "300",
		    $this->get('slug') . '_set_memory_limit' => "1",
		    $this->get('slug') . '_memory_limit_value' => "1024",

		    //Sync
		    $this->get('slug') . '_sync_status' => "0",
		    $this->get('slug') . '_sync_role' => "0",
		    $this->get('slug') . '_sync_frequency' => "2",
		    $this->get('slug') . '_sync_master_rest_endpoint' => "",
		    $this->get('slug') . '_sync_mode' => "0",
		    $this->get('slug') . '_sync_language' => "en",
		    $this->get('slug') . '_sync_script' => "",
		    $this->get('slug') . '_sync_locale' => "",
		    $this->get('slug') . '_sync_delete_target' => "0",

		    //Import
		    $this->get('slug') . '_import_mode' => "exact_copy",
		    $this->get('slug') . '_import_language' => "en",
		    $this->get('slug') . '_import_script' => "",
		    $this->get('slug') . '_import_locale' => "",

		    //Capabilities
		    $this->get('slug') . '_meta_box_capability' => "manage_options",
		    $this->get('slug') . '_editor_sidebar_capability' => "manage_options",
		    $this->get('slug') . '_connections_menu_capability' => "manage_options",
		    $this->get('slug') . '_wizard_menu_capability' => "manage_options",
		    $this->get('slug') . '_import_menu_capability' => "manage_options",
		    $this->get('slug') . '_export_menu_capability' => "manage_options",
		    $this->get('slug') . '_maintenance_menu_capability' => "manage_options",
		    
	    ];

		//Defaults -----------------------------------------------------------------------------------------------------
	    for ($i = 1; $i <= 100; $i++) {
		    $this->data['options'][$this->get('slug') . '_default_language_' . $i] = 'en';
            $this->data['options'][$this->get('slug') . '_default_script_' . $i] = '';
		    $this->data['options'][$this->get('slug') . '_default_locale_' . $i] = '';
	    }

	    //language list (ISO_639-1)
	    $da_hm_language = array(
		    "don't target a specific language or locale" => "x-default",
		    'Abkhaz' => 'ab',
		    'Afar' => 'aa',
		    'Afrikaans' => 'af',
		    'Akan' => 'ak',
		    'Albanian' => 'sq',
		    'Amharic' => 'am',
		    'Arabic' => 'ar',
		    'Aragonese' => 'an',
		    'Armenian' => 'hy',
		    'Assamese' => 'as',
		    'Avaric' => 'av',
		    'Avestan' => 'ae',
		    'Aymara' => 'ay',
		    'Azerbaijani' => 'az',
		    'Bambara' => 'bm',
		    'Bashkir' => 'ba',
		    'Basque' => 'eu',
		    'Belarusian' => 'be',
		    'Bengali/Bangla' => 'bn',
		    'Bihari' => 'bh',
		    'Bislama' => 'bi',
		    'Bosnian' => 'bs',
		    'Breton' => 'br',
		    'Bulgarian' => 'bg',
		    'Burmese' => 'my',
		    'Catalan/Valencian' => 'ca',
		    'Chamorro' => 'ch',
		    'Chechen' => 'ce',
		    'Chichewa/Chewa/Nyanja' => 'ny',
		    'Chinese' => 'zh',
		    'Chuvash' => 'cv',
		    'Cornish' => 'kw',
		    'Corsican' => 'co',
		    'Cree' => 'cr',
		    'Croatian' => 'hr',
		    'Czech' => 'cs',
		    'Danish' => 'da',
		    'Divehi/Dhivehi/Maldivian' => 'dv',
		    'Dutch' => 'nl',
		    'Dzongkha' => 'dz',
		    'English' => 'en',
		    'Esperanto' => 'eo',
		    'Estonian' => 'et',
		    'Ewe' => 'ee',
		    'Faroese' => 'fo',
		    'Fijian' => 'fj',
		    'Finnish' => 'fi',
		    'French' => 'fr',
		    'Fula/Fulah/Pulaar/Pular' => 'ff',
		    'Galician' => 'gl',
		    'Georgian' => 'ka',
		    'German' => 'de',
		    'Greek/Modern' => 'el',
		    'Guaraní' => 'gn',
		    'Gujarati' => 'gu',
		    'Haitian/Haitian Creole' => 'ht',
		    'Hausa' => 'ha',
		    'Hebrew (modern)' => 'he',
		    'Herero' => 'hz',
		    'Hindi' => 'hi',
		    'Hiri Motu' => 'ho',
		    'Hungarian' => 'hu',
		    'Interlingua' => 'ia',
		    'Indonesian' => 'id',
		    'Interlingue' => 'ie',
		    'Irish' => 'ga',
		    'Igbo' => 'ig',
		    'Inupian' => 'ik',
		    'Ido' => 'io',
		    'Icelandic' => 'is',
		    'Italian' => 'it',
		    'Inuktitut' => 'iu',
		    'Japanese' => 'ja',
		    'Javanese' => 'jv',
		    'Kalaallisut/Greenlandic' => 'kl',
		    'Kannada' => 'kn',
		    'Kanuri' => 'kr',
		    'Kashmiri' => 'ks',
		    'Kazakh' => 'kk',
		    'Khmer' => 'km',
		    'Kikuyu/Gikuyu' => 'ki',
		    'Kinyarwanda' => 'rw',
		    'Kyrgyz' => 'ky',
		    'Komi' => 'kv',
		    'Kongo' => 'kg',
		    'Korean' => 'ko',
		    'Kurdish' => 'ku',
		    'Kwanyama/Kuanyama' => 'kj',
		    'Latin' => 'la',
		    'Luxembourgish/Letzeburgesch' => 'lb',
		    'Ganda' => 'lg',
		    'Limburgish/Limburgan/Limburger' => 'li',
		    'Lingala' => 'ln',
		    'Lao' => 'lo',
		    'Lithuanian' => 'lt',
		    'Luba-Katanga' => 'lu',
		    'Latvian' => 'lv',
		    'Manx' => 'gv',
		    'Macedonian' => 'mk',
		    'Malagasy' => 'mg',
		    'Malay' => 'ms',
		    'Malayalam' => 'ml',
		    'Maltese' => 'mt',
		    'Māori' => 'mi',
		    'Marathi/Marāṭhī' => 'mr',
		    'Marshallese' => 'mh',
		    'Mongolian' => 'mn',
		    'Nauru' => 'na',
		    'Navajo/Navaho' => 'nv',
		    'Norwegian Bokmål' => 'nb',
		    'North Ndebele' => 'nd',
		    'Nepali' => 'ne',
		    'Ndonga' => 'ng',
		    'Norwegian Nynorsk' => 'nn',
		    'Norwegian' => 'no',
		    'Nuosu' => 'ii',
		    'South Ndebele' => 'nr',
		    'Occitan' => 'oc',
		    'Ojibwe/Ojibwa' => 'oj',
		    'Old C. Slavonic/C. Slavic/C. Slavonic/Old Bulgarian/Old Slavonic' => 'cu',
		    'Oromo' => 'om',
		    'Orija' => 'or',
		    'Ossetian/Ossetic' => 'os',
		    'Panjabi/Punjabi' => 'pa',
		    'Pāli' => 'pi',
		    'Persian (Farsi)' => 'fa',
		    'Polish' => 'pl',
		    'Pashto/Pushto' => 'ps',
		    'Portuguese' => 'pt',
		    'Quechua' => 'qu',
		    'Romansh' => 'rm',
		    'Kirundi' => 'rn',
		    'Romanian' => 'ro',
		    'Russian' => 'ru',
		    'Sanskrit (Saṁskṛta)' => 'sa',
		    'Sardinian' => 'sc',
		    'Sindhi' => 'sd',
		    'Northern Sami' => 'se',
		    'Samoan' => 'sm',
		    'Sango' => 'sg',
		    'Serbian' => 'sr',
		    'Scottish Gaelic/Gaelic' => 'gd',
		    'Shona' => 'sn',
		    'Sinhala/Sinhalese' => 'si',
		    'Slovak' => 'sk',
		    'Slovene' => 'sl',
		    'Somali' => 'so',
		    'Southern Sotho' => 'st',
		    'South Azebaijani' => 'az',
		    'Spanish/Castilian' => 'es',
		    'Sundanese' => 'su',
		    'Swahili' => 'sw',
		    'Swati' => 'ss',
		    'Swedish' => 'sv',
		    'Tamil' => 'ta',
		    'Telugu' => 'te',
		    'Tajik' => 'tg',
		    'Thai' => 'th',
		    'Tigrinya' => 'ti',
		    'Tibetan Standard/Tibetan/Central' => 'bo',
		    'Turkmen' => 'tk',
		    'Tagalog' => 'tl',
		    'Tswana' => 'tn',
		    'Tonga (Tonga Islands)' => 'to',
		    'Turkish' => 'tr',
		    'Tsonga' => 'ts',
		    'Tatar' => 'tt',
		    'Twi' => 'tw',
		    'Tahitian' => 'ty',
		    'Uyghur/Uighur' => 'ug',
		    'Ukrainian' => 'uk',
		    'Urdu' => 'ur',
		    'Uzbek' => 'uz',
		    'Venda' => 've',
		    'Vietnamese' => 'vi',
		    'Volapük' => 'vo',
		    'Walloon' => 'wa',
		    'Welsh' => 'cy',
		    'Wolof' => 'wo',
		    'Western Frisian' => 'fy',
		    'Xhosa' => 'xh',
		    'Yiddish' => 'yi',
		    'Yoruba' => 'yo',
		    'Zhuang/Chuang' => 'za',
		    'Zulu' => 'zu'
	    );
	    $this->data['options'][$this->get('slug') . '_language'] = $da_hm_language;

        //script list (ISO 15924)
        $da_hm_script = array(
            "Adlam" => "Adlm",
            "Afaka" => "Afak",
            "Caucasian Albanian" => "Aghb",
            "Ahom, Tai Ahom" => "Ahom",
            "Arabic" => "Arab",
            "Arabic (Nastaliq variant)" => "Aran",
            "Imperial Aramaic" => "Armi",
            "Armenian" => "Armn",
            "Avestan" => "Avst",
            "Balinese" => "Bali",
            "Bamum" => "Bamu",
            "Bassa Vah" => "Bass",
            "Batak" => "Batk",
            "Bengali (Bangla)" => "Beng",
            "Bhaiksuki" => "Bhks",
            "Blissymbols" => "Blis",
            "Bopomofo" => "Bopo",
            "Brahmi" => "Brah",
            "Braille" => "Brai",
            "Buginese" => "Bugi",
            "Buhid" => "Buhd",
            "Chakma" => "Cakm",
            "Unified Canadian Aboriginal Syllabics" => "Cans",
            "Carian" => "Cari",
            "Cham" => "Cham",
            "Cherokee" => "Cher",
            "Chorasmian" => "Chrs",
            "Cirth" => "Cirt",
            "Coptic" => "Copt",
            "Cypro-Minoan" => "Cpmn",
            "Cypriot syllabary" => "Cprt",
            "Cyrillic" => "Cyrl",
            "Cyrillic (Old Church Slavonic variant)" => "Cyrs",
            "Devanagari (Nagari)" => "Deva",
            "Dives Akuru" => "Diak",
            "Dogra" => "Dogr",
            "Deseret (Mormon)" => "Dsrt",
            "Duployan shorthand, Duployan stenography" => "Dupl",
            "Egyptian demotic" => "Egyd",
            "Egyptian hieratic" => "Egyh",
            "Egyptian hieroglyphs" => "Egyp",
            "Elbasan" => "Elba",
            "Elymaic" => "Elym",
            "Ethiopic (Geʻez)" => "Ethi",
            "Khutsuri (Asomtavruli and Nuskhuri)" => "Geok",
            "Georgian (Mkhedruli and Mtavruli)" => "Geor",
            "Glagolitic" => "Glag",
            "Gunjala Gondi" => "Gong",
            "Masaram Gondi" => "Gonm",
            "Gothic" => "Goth",
            "Grantha" => "Gran",
            "Greek" => "Grek",
            "Gujarati" => "Gujr",
            "Gurmukhi" => "Guru",
            "Han with Bopomofo (alias for Han + Bopomofo)" => "Hanb",
            "Hangul (Hangŭl, Hangeul)" => "Hang",
            "Han (Hanzi, Kanji, Hanja)" => "Hani",
            "Hanunoo (Hanunóo)" => "Hano",
            "Han (Simplified variant)" => "Hans",
            "Han (Traditional variant)" => "Hant",
            "Hatran" => "Hatr",
            "Hebrew" => "Hebr",
            "Hiragana" => "Hira",
            "Anatolian Hieroglyphs (Luwian Hieroglyphs, Hittite Hieroglyphs)" => "Hluw",
            "Pahawh Hmong" => "Hmng",
            "Nyiakeng Puachue Hmong" => "Hmnp",
            "Japanese syllabaries (alias for Hiragana + Katakana)" => "Hrkt",
            "Old Hungarian (Hungarian Runic)" => "Hung",
            "Indus (Harappan)" => "Inds",
            "Old Italic (Etruscan, Oscan, etc.)" => "Ital",
            "Jamo (alias for Jamo subset of Hangul)" => "Jamo",
            "Javanese" => "Java",
            "Japanese (alias for Han + Hiragana + Katakana)" => "Jpan",
            "Jurchen" => "Jurc",
            "Kayah Li" => "Kali",
            "Katakana" => "Kana",
            "Kharoshthi" => "Khar",
            "Khmer" => "Khmr",
            "Khojki" => "Khoj",
            "Khitan large script" => "Kitl",
            "Khitan small script" => "Kits",
            "Kannada" => "Knda",
            "Korean (alias for Hangul + Han)" => "Kore",
            "Kpelle" => "Kpel",
            "Kaithi" => "Kthi",
            "Tai Tham (Lanna)" => "Lana",
            "Lao" => "Laoo",
            "Latin (Fraktur variant)" => "Latf",
            "Latin (Gaelic variant)" => "Latg",
            "Latin" => "Latn",
            "Leke" => "Leke",
            "Lepcha (Róng)" => "Lepc",
            "Limbu" => "Limb",
            "Linear A" => "Lina",
            "Linear B" => "Linb",
            "Lisu (Fraser)" => "Lisu",
            "Loma" => "Loma",
            "Lycian" => "Lyci",
            "Lydian" => "Lydi",
            "Mahajani" => "Mahj",
            "Makasar" => "Maka",
            "Mandaic, Mandaean" => "Mand",
            "Manichaean" => "Mani",
            "Marchen" => "Marc",
            "Mayan hieroglyphs" => "Maya",
            "Medefaidrin (Oberi Okaime, Oberi Ɔkaimɛ)" => "Medf",
            "Mende Kikakui" => "Mend",
            "Meroitic Cursive" => "Merc",
            "Meroitic Hieroglyphs" => "Mero",
            "Malayalam" => "Mlym",
            "Modi, Moḍī" => "Modi",
            "Mongolian" => "Mong",
            "Moon (Moon code, Moon script, Moon type)" => "Moon",
            "Mro, Mru" => "Mroo",
            "Meitei Mayek (Meithei, Meetei)" => "Mtei",
            "Multani" => "Mult",
            "Myanmar (Burmese)" => "Mymr",
            "Nandinagari" => "Nand",
            "Old North Arabian (Ancient North Arabian)" => "Narb",
            "Nabataean" => "Nbat",
            "Newa, Newar, Newari, Nepāla lipi" => "Newa",
            "Naxi Dongba (na²¹ɕi³³ to³³ba²¹, Nakhi Tomba)" => "Nkdb",
            "Naxi Geba (na²¹ɕi³³ gʌ²¹ba²¹, 'Na-'Khi ²Ggŏ-¹baw, Nakhi Geba)" => "Nkgb",
            "N’Ko" => "Nkoo",
            "Nüshu" => "Nshu",
            "Ogham" => "Ogam",
            "Ol Chiki (Ol Cemet’, Ol, Santali)" => "Olck",
            "Old Turkic, Orkhon Runic" => "Orkh",
            "Oriya (Odia)" => "Orya",
            "Osage" => "Osge",
            "Osmanya" => "Osma",
            "Old Uyghur" => "Ougr",
            "Palmyrene" => "Palm",
            "Pau Cin Hau" => "Pauc",
            "Proto-Cuneiform" => "Pcun",
            "Proto-Elamite" => "Pelm",
            "Old Permic" => "Perm",
            "Phags-pa" => "Phag",
            "Inscriptional Pahlavi" => "Phli",
            "Psalter Pahlavi" => "Phlp",
            "Book Pahlavi" => "Phlv",
            "Phoenician" => "Phnx",
            "Miao (Pollard)" => "Plrd",
            "Klingon (KLI pIqaD)" => "Piqd",
            "Inscriptional Parthian" => "Prti",
            "Proto-Sinaitic" => "Psin",
            "Reserved for private use (start)" => "Qaaa",
            "Reserved for private use (end)" => "Qabx",
            "Ranjana" => "Ranj",
            "Rejang (Redjang, Kaganga)" => "Rjng",
            "Hanifi Rohingya" => "Rohg",
            "Rongorongo" => "Roro",
            "Runic" => "Runr",
            "Samaritan" => "Samr",
            "Sarati" => "Sara",
            "Old South Arabian" => "Sarb",
            "Saurashtra" => "Saur",
            "SignWriting" => "Sgnw",
            "Shavian (Shaw)" => "Shaw",
            "Sharada, Śāradā" => "Shrd",
            "Shuishu" => "Shui",
            "Siddham, Siddhaṃ, Siddhamātṛkā" => "Sidd",
            "Khudawadi, Sindhi" => "Sind",
            "Sinhala" => "Sinh",
            "Sogdian" => "Sogd",
            "Old Sogdian" => "Sogo",
            "Sora Sompeng" => "Sora",
            "Soyombo" => "Soyo",
            "Sundanese" => "Sund",
            "Syloti Nagri" => "Sylo",
            "Syriac" => "Syrc",
            "Syriac (Estrangelo variant)" => "Syre",
            "Syriac (Western variant)" => "Syrj",
            "Syriac (Eastern variant)" => "Syrn",
            "Tagbanwa" => "Tagb",
            "Takri, Ṭākrī, Ṭāṅkrī" => "Takr",
            "Tai Le" => "Tale",
            "New Tai Lue" => "Talu",
            "Tamil" => "Taml",
            "Tangut" => "Tang",
            "Tai Viet" => "Tavt",
            "Telugu" => "Telu",
            "Tengwar" => "Teng",
            "Tifinagh (Berber)" => "Tfng",
            "Tagalog (Baybayin, Alibata)" => "Tglg",
            "Thaana" => "Thaa",
            "Thai" => "Thai",
            "Tibetan" => "Tibt",
            "Tirhuta" => "Tirh",
            "Tangsa" => "Tnsa",
            "Toto" => "Toto",
            "Ugaritic" => "Ugar",
            "Vai" => "Vaii",
            "Visible Speech" => "Visp",
            "Vithkuqi" => "Vith",
            "Warang Citi (Varang Kshiti)" => "Wara",
            "Wancho" => "Wcho",
            "Woleai" => "Wole",
            "Old Persian" => "Xpeo",
            "Cuneiform, Sumero-Akkadian" => "Xsux",
            "Yezidi" => "Yezi",
            "Yi" => "Yiii",
            "Zanabazar Square (Zanabazarin Dörböljin Useg, Xewtee Dörböljin Bicig, Horizontal Square Script)" => "Zanb",
            "Code for inherited script" => "Zinh",
            "Mathematical notation" => "Zmth",
            "Symbols (Emoji variant)" => "Zsye",
            "Symbols" => "Zsym",
            "Code for unwritten documents" => "Zxxx",
            "Code for undetermined script" => "Zyyy",
            "Code for uncoded script" => "Zzzz"
        );
        $this->data['options'][$this->get('slug') . '_script'] = $da_hm_script;

	    //country list (ISO 3166-1 alpha-2)
	    $da_hm_locale = array(
		    'Andorra' => 'ad',
		    'United Arab Emirates' => 'ae',
		    'Afghanistan' => 'af',
		    'Antigua and Barbuda' => 'ag',
		    'Anguilla' => 'ai',
		    'Albania' => 'al',
		    'Armenia' => 'am',
		    'Angola' => 'ao',
		    'Antartica' => 'aq',
		    'Argentina' => 'ar',
		    'American Samoa' => 'as',
		    'Austria' => 'at',
		    'Australia' => 'au',
		    'Aruba' => 'aw',
		    'Åland Islands' => 'ax',
		    'Azerbaijan' => 'az',
		    'Bosnia and Herzegovina' => 'ba',
		    'Barbados' => 'bb',
		    'Bangladesh' => 'bd',
		    'Belgium' => 'be',
		    'Burkina Faso' => 'bf',
		    'Bulgaria' => 'bg',
		    'Bahrain' => 'bh',
		    'Burundi' => 'bi',
		    'Benin' => 'bj',
		    'Saint Barthélemy' => 'bl',
		    'Bermuda' => 'bm',
		    'Brunei Darussalam' => 'bn',
		    'Bolivia' => 'bo',
		    'Bonaire, Sint Eustatius and Saba' => 'bq',
		    'Brazil' => 'br',
		    'Bahamas' => 'bs',
		    'Bhutan' => 'bt',
		    'Bouvet Island' => 'bv',
		    'Botswana' => 'bw',
		    'Belarus' => 'by',
		    'Belize' => 'bz',
		    'Canada' => 'ca',
		    'Cocos (Keeling) Islands' => 'cc',
		    'Congo Democratic Republic' => 'cd',
		    'Central African Republic' => 'cf',
		    'Congo' => 'cg',
		    'Switzerland' => 'ch',
		    'Côte d\'Ivoire' => 'ci',
		    'Cook Islands' => 'ck',
		    'Chile' => 'cl',
		    'Cameroon' => 'cm',
		    'China' => 'cn',
		    'Colombia' => 'co',
		    'Costa Rica' => 'cr',
		    'Cuba' => 'cu',
		    'Cape Verde' => 'cv',
		    'Curaçao' => 'cw',
		    'Christmas Island' => 'cx',
		    'Cyprus' => 'cy',
		    'Czech Republic' => 'cz',
		    'Germany' => 'de',
		    'Djibouti' => 'dj',
		    'Denmark' => 'dk',
		    'Dominica' => 'dm',
		    'Dominican Republic' => 'do',
		    'Algeria' => 'dz',
		    'Ecuador' => 'ec',
		    'Estonia' => 'ee',
		    'Egypt' => 'eg',
		    'Western Sahara' => 'eh',
		    'Eritrea' => 'er',
		    'Spain' => 'es',
		    'Ethiopia' => 'et',
		    'Finland' => 'fi',
		    'Fiji' => 'fj',
		    'Falkland Islands (Malvinas)' => 'fk',
		    'Micronesia Federated States of' => 'fm',
		    'Faroe Islands' => 'fo',
		    'France' => 'fr',
		    'Gabon' => 'ga',
		    'United Kingdom' => 'gb',
		    'Grenada' => 'gd',
		    'Georgia' => 'ge',
		    'French Guiana' => 'gf',
		    'Guernsey' => 'gg',
		    'Ghana' => 'gh',
		    'Gibraltar' => 'gi',
		    'Greenland' => 'gl',
		    'Gambia' => 'gm',
		    'Guinea' => 'gn',
		    'Guadeloupe' => 'gp',
		    'Equatorial Guinea' => 'gq',
		    'Greece' => 'gr',
		    'South Georgia and the South Sandwich Islands' => 'gs',
		    'Guatemala' => 'gt',
		    'Guam' => 'gu',
		    'Guinea-Bissau' => 'gw',
		    'Guyana' => 'gy',
		    'Hong Kong' => 'hk',
		    'Heard Island and McDonald Islands' => 'hm',
		    'Honduras' => 'hn',
		    'Croatia' => 'hr',
		    'Haiti' => 'ht',
		    'Hungary' => 'hu',
		    'Indonesia' => 'id',
		    'Ireland' => 'ie',
		    'Israel' => 'il',
		    'Isle of Man' => 'im',
		    'India' => 'in',
		    'British Indian Ocean Territory' => 'io',
		    'Iraq' => 'iq',
		    'Iran, Islamic Republic of' => 'ir',
		    'Iceland' => 'is',
		    'Italy' => 'it',
		    'Jersey' => 'je',
		    'Jamaica' => 'jm',
		    'Jordan' => 'jo',
		    'Japan' => 'jp',
		    'Kenya' => 'ke',
		    'Kyrgyzstan' => 'kg',
		    'Cambodia' => 'kh',
		    'Kiribati' => 'ki',
		    'Comoros' => 'km',
		    'Saint Kitts and Nevis' => 'kn',
		    'Korea, Democratic People\'s Republic of' => 'kp',
		    'Korea, Republic of' => 'kr',
		    'Kuwait' => 'kw',
		    'Cayman Islands' => 'ky',
		    'Kazakhstan' => 'kz',
		    'Lao People\'s Democratic Republic' => 'la',
		    'Lebanon' => 'lb',
		    'Saint Lucia' => 'lc',
		    'Liechtenstein' => 'li',
		    'Sri Lanka' => 'lk',
		    'Liberia' => 'lr',
		    'Lesotho' => 'ls',
		    'Lithuania' => 'lt',
		    'Luxembourg' => 'lu',
		    'Latvia' => 'lv',
		    'Libya' => 'ly',
		    'Morocco' => 'ma',
		    'Monaco' => 'mc',
		    'Moldova, Republic of' => 'md',
		    'Montenegro' => 'me',
		    'Saint Martin (French part)' => 'mf',
		    'Madagascar' => 'mg',
		    'Marshall Islands' => 'mh',
		    'Macedonia, the former Yugoslav Republic of' => 'mk',
		    'Mali' => 'ml',
		    'Myanmar' => 'mm',
		    'Mongolia' => 'mn',
		    'Macao' => 'mo',
		    'Northern Mariana Islands' => 'mp',
		    'Martinique' => 'mq',
		    'Mauritania' => 'mr',
		    'Montserrat' => 'ms',
		    'Malta' => 'mt',
		    'Mauritius' => 'mu',
		    'Maldives' => 'mv',
		    'Malawi' => 'mw',
		    'Mexico' => 'mx',
		    'Malaysia' => 'my',
		    'Mozambique' => 'mz',
		    'Namibia' => 'na',
		    'New Caledonia' => 'nc',
		    'Niger' => 'ne',
		    'Norfolk Island' => 'nf',
		    'Nigeria' => 'ng',
		    'Nicaragua' => 'ni',
		    'Netherlands' => 'nl',
		    'Norway' => 'no',
		    'Nepal' => 'np',
		    'Nauru' => 'nr',
		    'Niue' => 'nu',
		    'New Zealand' => 'nz',
		    'Oman' => 'om',
		    'Panama' => 'pa',
		    'Peru' => 'pe',
		    'French Polynesia' => 'pf',
		    'Papua New Guinea' => 'pg',
		    'Philippines' => 'ph',
		    'Pakistan' => 'pk',
		    'Poland' => 'pl',
		    'Saint Pierre and Miquelon' => 'pm',
		    'Pitcairn' => 'pn',
		    'Puerto Rico' => 'pr',
		    'Palestine, State of' => 'ps',
		    'Portugal' => 'pt',
		    'Palau' => 'pw',
		    'Paraguay' => 'py',
		    'Qatar' => 'qa',
		    'Réunion' => 're',
		    'Romania' => 'ro',
		    'Serbia' => 'rs',
		    'Russian Federation' => 'ru',
		    'Rwanda' => 'rw',
		    'Saudi Arabia' => 'sa',
		    'Solomon Islands' => 'sb',
		    'Seychelles' => 'sc',
		    'Sudan' => 'sd',
		    'Sweden' => 'se',
		    'Singapore' => 'sg',
		    'Saint Helena, Ascension and Tristan da Cunha' => 'sh',
		    'Slovenia' => 'si',
		    'Svalbard and Jan Mayen' => 'sj',
		    'Slovakia' => 'sk',
		    'Sierra Leone' => 'sl',
		    'San Marino' => 'sm',
		    'Senegal' => 'sn',
		    'Somalia' => 'so',
		    'Suriname' => 'sr',
		    'South Sudan' => 'ss',
		    'Sao Tome and Principe' => 'st',
		    'El Salvador' => 'sv',
		    'Sint Maarten (Dutch part)' => 'sx',
		    'Syrian Arab Republic' => 'sy',
		    'Swaziland' => 'sz',
		    'Turks and Caicos Islands' => 'tc',
		    'Chad' => 'td',
		    'French Southern Territories' => 'tf',
		    'Togo' => 'tg',
		    'Thailand' => 'th',
		    'Tajikistan' => 'tj',
		    'Tokelau' => 'tk',
		    'Timor-Leste' => 'tl',
		    'Turkmenistan' => 'tm',
		    'Tunisia' => 'tn',
		    'Tonga' => 'to',
		    'Turkey' => 'tr',
		    'Trinidad and Tobago' => 'tt',
		    'Tuvalu' => 'tv',
		    'Taiwan, Province of China' => 'tw',
		    'Tanzania, United Republic of' => 'tz',
		    'Ukraine' => 'ua',
		    'Uganda' => 'ug',
		    'United States Minor Outlying Islands' => 'um',
		    'United States' => 'us',
		    'Uruguay' => 'uy',
		    'Uzbekistan' => 'uz',
		    'Holy See (Vatican City State)' => 'va',
		    'Saint Vincent and the Grenadines' => 'vc',
		    'Venezuela, Bolivarian Republic of' => 've',
		    'Virgin Islands, British' => 'vg',
		    'Virgin Islands, U.S.' => 'vi',
		    'Viet Nam' => 'vn',
		    'Vanuatu' => 'vu',
		    'Wallis and Futuna' => 'wf',
		    'Samoa' => 'ws',
		    'Yemen' => 'ye',
		    'Mayotte' => 'yt',
		    'South Africa' => 'za',
		    'Zambia' => 'zm',
		    'Zimbabwe' => 'zw'
	    );
	    $this->data['options'][$this->get('slug') . '_locale'] = $da_hm_locale;

    }

    public static function get_instance()
    {

        if (null == self::$instance) {
            self::$instance = new self;
        }

        return self::$instance;

    }

    //retrieve data
    public function get($index)
    {
        return $this->data[$index];
    }

    /*
     * Generate an array with the connections associated with the current url
     *
     * @return An array with the connections associated with the current url or False if there are not connections
     * associated with the current url
     */
    public function generate_hreflang_output(){

        //get the current url
        $current_url = $this->get_current_url();

        global $wpdb;
        $table_name=$wpdb->prefix . "da_hm_connect";

        /**
         * If the 'Auto Trailing Slash' option is enabled compare the 'url_to_connect' value in the database not only
         * with $current_url, but also with the URL present in $current_url with the trailing slash manually added or
         * removed.
         */
        if(intval(get_option("da_hm_auto_trailing_slash"), 10) == 1){

            if(substr($current_url, strlen($current_url) - 1) == '/'){

                /**
                 * In this case there is a trailing slash, so remove it and compare the 'url_to_connect' value in the
                 * database not only with $current_url, but also with $current_url_without_trailing_slash, which is
                 * $current_url with the trailing slash removed.
                 */
                $current_url_without_trailing_slash = substr($current_url, 0, -1);
                $safe_sql = $wpdb->prepare( "SELECT * FROM $table_name WHERE url_to_connect = %s or url_to_connect = %s", $current_url, $current_url_without_trailing_slash);

            }else{

                /**
                 * In this case there is no trailing slash, so add it and compare the 'url_to_connect' value in the
                 * database not only with $current_url, but also with $current_url_with_trailing_slash, which is
                 * $current_url with the trailing slash added.
                 */
                $current_url_with_trailing_slash = $current_url . '/';
                $safe_sql = $wpdb->prepare( "SELECT * FROM $table_name WHERE url_to_connect = %s or url_to_connect = %s", $current_url, $current_url_with_trailing_slash);

            }

        }else{
            $safe_sql = $wpdb->prepare( "SELECT * FROM $table_name WHERE url_to_connect = %s", $current_url);
        }

        $results = $wpdb->get_row($safe_sql);

        if($results === NULL){

            return false;

        }else{

            //init $hreflang_output
            $hreflang_output = array();

            //Convert the json strings to objects
            $results->url = json_decode($results->url);
            $results->language = json_decode($results->language);
            $results->script = json_decode($results->script);
            $results->locale = json_decode($results->locale);

            //generate an array with all the connections
            for ( $i=1; $i<=100; $i++ ){

                //check if this is a valid hreflang
                if( strlen( $results->url->{$i} ) > 0 and strlen( $results->language->{$i} ) > 0 ){

                    $language = $results->language->{$i};

                    if( strlen( $results->script->{$i} ) > 0){
                        $script = '-' . $results->script->{$i};
                    }else{
                        $script = '';
                    }

                    if( strlen( $results->locale->{$i} ) > 0){
                        $locale = '-' . $results->locale->{$i};
                    }else{
                        $locale = '';
                    }

                    /**
                     * Add the link element to the output and sanitize the URL in the href attribute of the link element
                     * if the 'Sanitize URL' option is enabled.
                     */
                    if(intval(get_option("da_hm_sanitize_url"), 10) == 1){
                        $hreflang_output[$i] = '<link rel="alternate" href="' . esc_url($results->url->{$i}) . '" hreflang="' . esc_attr($language . $script . $locale) . '" />';
                    }else{
                        $hreflang_output[$i] = '<link rel="alternate" href="' . $results->url->{$i} . '" hreflang="' . esc_attr($language . $script . $locale) . '" />';
                    }

                }

            }

            if( is_array($hreflang_output) )
                return $hreflang_output;
            else{
                return false;
            }

        }

    }

    /*
     * Get the current URL
     */
    public function get_current_url(){

        if(get_option("da_hm_detect_url_mode") === 'server_variable'){

            //Detect the URL using the "Server Variable" method
            if( intval(get_option("da_hm_https"), 10) == 0 ){
                $protocol = 'http';
            }else{
                $protocol = 'https';
            }
            return esc_url_raw($protocol . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);

        }else{

            //Detect the URL using the "WP Request" method
            global $wp;
            return trailingslashit(home_url(add_query_arg(array(),$wp->request)));

        }

    }

    /*
     * Returns the number of records available in the '[prefix]_da_hm_connect' db table
     *
     * @return int The number of records available in the '[prefix]_da_hm_connect' db table
     */
    public function number_of_connections(){

        global $wpdb;
        $table_name  = $wpdb->prefix . $this->get( 'slug' ) . "_connect";
        $total_items = $wpdb->get_var( "SELECT COUNT(*) FROM $table_name" );

        return $total_items;

    }

    /**
     * Generates the 'url_to_connect' value based on the connection data and on the provided language, script, and
     * locale.
     *
     * @param $connection Array with all the information of a connection (all the fields of the 'connect' db table
     * except 'id')
     * @return String
     */
    public function generate_url_to_connect($connection, $language, $script, $locale){

        //Get the objects from the serialized data
        $connection['url'] = json_decode($connection['url']);
        $connection['language'] = json_decode($connection['language']);
        $connection['script'] = json_decode($connection['script']);
        $connection['locale'] = json_decode($connection['locale']);

        /**
         * Search the 'url' where the related 'language', 'script' and 'locale' are the same of the ones specified with
         * the 'Import Language', 'Import Script' and 'Import Locale' options. In case this 'url' is found use it as the
         * 'url_to_connect' value.
         */
        for($i=1;$i<=100;$i++){

            if((string)$connection['language']->{$i} === (string)$language
                and (string)$connection['script']->{$i} === (string)$script
                and (string)$connection['locale']->{$i} === (string)$locale){
                $url_to_connect = $connection['url']->{$i};
                break;
            }

        }

        /**
         * If a specific 'url_to_connect' is found return it, otherwise use the 'url_to_connect' value available in the
         * imported XML file.
         */
        if(isset($url_to_connect)){
            return $url_to_connect;
        }else{
            return $connection['url_to_connect'];
        }

    }

	/**
	 * Get the permalink of the post.
	 *
	 * Note that if the:
	 *
	 * - "Sample Permalink" option is enabled
	 * - And if the post status is 'future'
	 *
	 * The value of the permalink field is generated with the get_sample_permalink() function.
	 *
	 * @param $post_id The post id.
	 * @param $require True if the wp-admin/includes/post.php file should be required.
	 *
	 * @return String The permalink of the post associated with the provided post id.
	 */
    public function get_permalink($post_id, $require = false){

	    $post_status = get_post_status($post_id);

	    /**
	     * If the post status is 'future' the value of the url_to_connect field is generated
	     * with the get_future_permalink() function. Otherwise it's generated with the get_permalink() function.
	     */
	    if(intval(get_option('da_hm_sample_future_permalink'), 10) === 1 and $post_status === 'future'){

		    if($require){
			    require_once(ABSPATH . 'wp-admin/includes/post.php');
		    }

		    $permalink_a = get_sample_permalink($post_id);
		    $permalink = preg_replace('/\%[^\%]+name\%/', $permalink_a[1], $permalink_a[0]);

	    }else{

	    	$permalink = get_permalink($post_id);

	    }

		return $permalink;

	}

	/**
	 * Verifies if the provided ISO_639-1 language code is valid.
	 * Returns True if it's valid, otherwise returns False.
	 *
	 * @param $code The ISO_639-1 language code.
	 * @return bool
	 */
	public function is_valid_language($code){

		$found = False;

		$language = get_option('da_hm_language');
		foreach($language as $value){
			if($code === $value){
				$found = True;
			}
		}

		return $found;

	}

    /**
     * Verifies if the provided ISO 15924 script code is valid.
     * Returns True if it's valid, otherwise returns False.
     *
     * @param $code The ISO 15924 script code.
     * @return bool
     */
    public function is_valid_script($code){

        $found = False;

        $script = get_option('da_hm_script');
        foreach($script as $value){
            if($code === $value){
                $found = True;
            }
        }

        return $found;

    }
	
	/**
	 * Verifies if the provided ISO 3166-1 alpha-2 locale code is valid.
	 * Returns True if it's valid, otherwise returns False.
	 *
	 * @param $code The ISO_639-1 language code.
	 * @return bool
	 */
	public function is_valid_locale($code){

		$found = False;

		$locale = get_option('da_hm_locale');
		foreach($locale as $value){
			if($code === $value){
				$found = True;
			}
		}

		return $found;

	}

	/*
	 * Set the PHP "Max Execution Time" and "Memory Limit" based on the values defined in the options.
	 */
	public function set_met_and_ml(){

		/*
		 * Set the custom "Max Execution Time Value" defined in the options if the 'Set Max Execution Time' option is
		 * set to "Yes".
		 */
		if (intval(get_option($this->get('slug') . '_set_max_execution_time'), 10) === 1) {
			ini_set('max_execution_time',
				intval(get_option($this->get('slug') . '_max_execution_time_value'), 10));
		}

		/*
		 * Set the custom "Memory Limit Value" (in megabytes) defined in the options if the 'Set Memory Limit' option is
		 * set to "Yes".
		 */
		if (intval(get_option($this->get('slug') . '_set_memory_limit'), 10) === 1) {
			ini_set('memory_limit', intval(get_option($this->get('slug') . "_memory_limit_value"), 10) . 'M');
		}

	}

	/**
	 * This method runs all the cron tasks associated with the "da_hm_cron_hook" action hook.
	 */
	public function da_hm_cron_exec(){

		//Sync the connections
		$this->sync_connections();

	}

	/**
	 * This method syncs the connections of a slave website with the connections available in the master.
	 *
	 * Specifically, it does what follows:
	 *
	 * 1 - Verifies that the sync feature is enabled and that this website is set to slave.
	 * 2 - Retrieves the connections present in the master by using the REST API endpoint defined in the options.
	 * 3 - Finds the indexes of the connections present in master that already exists in the database table of the
	 * current website (slave).
	 * 4 - Delete from the database of this website (slave) the connections present in master that already exists in the
	 * database table of the current website (slave).
	 * 5 - Adds in the database table of this website (slave) all the connections present in master that don't already
	 * exists in the database table of the current website
	 * of the $shared_record_a array.
	 *
	 * Note that the connections are not simply copied from the master to the slave to avoid deleting and creating each
	 * time records that are already in sync.
	 */
	public function sync_connections() {

		//Run this task only if Sync Status is equal to "Enabled" and the Sync Role is equal to "Slave"
		$sync_status = intval( get_option( $this->get( 'slug' ) . "_sync_status" ), 10 );
		$sync_role   = intval( get_option( $this->get( 'slug' ) . "_sync_role" ), 10 );
		$sync_delete_target = intval(get_option($this->get('slug') . '_sync_delete_target'), 10);
		if ( ( $sync_status === 1 and $sync_role === 1 ) === false ) {
			return;
		}

		//Set the PHP "Max Execution Time" and "Memory Limit" based on the values defined in the options
		$this->set_met_and_ml();

		/**
		 * The $shared_record_a variable includes indexes of the records shared between the master and the slave.
		 *
		 * Each item of the array includes an array with the index of the $master_connection_a array ('master_id') and
		 * the value of the 'id' field in the slave database.
		 *
		 * Example of an array element:
		 *
		 *    [
		 *     'master_id' => 0, // The index of the master in the $master_connection_a.
		 *     'slave_id' => 345 // The 'id' field of the record in the slave database.
		 * ];
		 */
		$shared_record_a = [];

		//Read the REST API endpoint of the master website
		$master_rest_endpoint = get_option( $this->get( 'slug' ) . "_sync_master_rest_endpoint" );
		$response             = wp_remote_get( $master_rest_endpoint );

		//If the response is not a WP Error instance decode the json
		if(!is_wp_error($response)){
			$master_connection_a  = json_decode( $response['body'] );
		}else{
			return;
		}

		//Do not proceed if there are no connection in the master website
		if($master_connection_a === false){
			return;
		}

		/**
		 * Do not proceed if the items in the generated array don't include the proper indexes.
		 *
		 * This check is useful to avoid errors (and avoid adding to the plugin empty connections) when the
		 * "Master Endpoint" includes a URL to a json source which doesn't include the expecting data.
		 */
		foreach ( $master_connection_a as $master_connection ) {

			if ( ! isset( $master_connection->url_to_connect ) or
			     ! isset( $master_connection->url ) or
			     ! isset( $master_connection->language ) or
			     ! isset( $master_connection->script ) or
			     ! isset( $master_connection->locale ) ) {
				return;
			}

		}

		/**
		 * Find the indexes of the connections present in $master_connection_a that already exists in the "_connect" db
		 * table and save them in the $shared_record_a array.
		 *
		 * Note that the "Url to Connect" of the destination is calculated to properly compare the connection resulting
		 * from the master data. (The connection resulting from the master data has the url_to_connect field adapted
		 * based on the "Sync Language", "Sync Script", and "Sync Locale" options)
		 */
		foreach ( $master_connection_a as $key => $master_connection ) {

			/**
			 * If the "Sync Mode" option is set to "Based on Sync Options" generate the "url_to_connect" value based on the
			 * "Sync Language", "Sync Script", and "Sync Locale" options.
			 */
			if(intval(get_option($this->get('slug') . '_sync_mode', 10)) === 1){

				//Retrieve the 'Sync Language' and the "Sync Locale' from the options
				$sync_language = get_option($this->get('slug') . '_sync_language');
				$sync_script = get_option($this->get('slug') . '_sync_script');
				$sync_locale = get_option($this->get('slug') . '_sync_locale');

				//Get the URL to connect
				$adapted_url_to_connect = $this->generate_url_to_connect(
					[
						'url_to_connect' => $master_connection->url_to_connect,
						'url'            => $master_connection->url,
						'language'       => $master_connection->language,
						'script'         => $master_connection->script,
						'locale'         => $master_connection->locale
					],
					$sync_language,
					$sync_script,
					$sync_locale
				);

			}else{

				//Use the original url to connect of the connection
				$adapted_url_to_connect = $master_connection->url_to_connect;

			}
			
			/**
			 * Verify if the iterated master connection is available in the slave database.
			 * 
			 *
			 */
			global $wpdb;
			$table_name = $wpdb->prefix . "da_hm_connect";
			$safe_sql   = $wpdb->prepare( "SELECT * FROM $table_name WHERE
                 url_to_connect = %s AND
                 url = %s AND
                 language = %s AND
                 script = %s AND
                 locale = %s",
				$adapted_url_to_connect,
				$master_connection->url,
				$master_connection->language,
				$master_connection->script,
				$master_connection->locale
			);

			$connection_obj = $wpdb->get_row( $safe_sql );

			/**
			 * If the iterated master connection is available in the slave database add the corresponding two indexes
			 * in the $shared_record_a array.
			 */
			if ( $connection_obj !== false and $connection_obj !== null ) {
				$shared_record_a[] = [
					'master_id' => $key,
					'slave_id'  => $connection_obj->id
				];
			}

		}

		/**
		 * Delete from the "_connect" db table the connections that are not shared between master and slave (in other
		 * words with indexes not included in the $shared_record_a array).
		 *
		 * Note that if the "Delete Target" option is equal to "All" any connection that is not included in the
		 * $shared_record_a array is deleted. If instead the "Delete Target" option is equal to "Inherited", only the
		 * connections not included in the $shared_record_a array with the "inherit" field equal to "1" are deleted.
		 * This behavior is used to preserve existing connections of the slave site that should not be deleted and
		 * delete only the connections that have been previously inherited from the master site.
		 */
		if($sync_delete_target === 0){
			$sql = "SELECT * FROM $table_name ORDER BY ID ASC";
		}else{
			$sql = "SELECT * FROM $table_name WHERE inherited = 1 ORDER BY ID ASC";
		}

		$slave_connection_a = $wpdb->get_results( $sql, ARRAY_A );

		foreach ( $slave_connection_a as $slave_connection ) {

			//if this record is not included in the db_id field of $shared_record_a delete it
			$found = false;
			foreach ( $shared_record_a as $already_updated_single ) {

				if ( intval( $already_updated_single['slave_id'], 10 ) === intval( $slave_connection['id'], 10 ) ) {
					$found = true;
				}

			}

			//delete this record
			if ( $found === false ) {

				$safe_sql     = $wpdb->prepare( "DELETE FROM $table_name WHERE id = %d ", $slave_connection['id'] );
				$query_result = $wpdb->query( $safe_sql );

			}

		}

		/**
		 * Add in the "_connect" db table all the connections in $master_connection_a that don't have an index in the
		 * 'master_id' index of the $shared_record_a array.
		 */
		foreach ( $master_connection_a as $key => $connection ) {

			//if the index of $master_connection_a is present in the key field $already_update return
			$found = false;
			foreach ( $shared_record_a as $shared_record ) {

				if ( intval( $key, 10 ) === intval( $shared_record['master_id'], 10 ) ) {
					$found = true;
				}

			}
			if ( $found ) {
				continue;
			}

			$this->add_synced_connection( $connection );

		}

	}

	/**
	 * Add the provided connection to the database. Note that the Url to Connect value is adapted based on the following
	 * options:
	 *
	 * - Sync -> Mode
	 * - Sync -> Language
	 * - Sync -> Script
	 * - Sync -> Locale
	 *
	 * @param $connection
	 */
	public function add_synced_connection($connection){

		/**
		 * If the "Sync Mode" option is set to "Based on Sync Options" generate the "url_to_connect" value based on the
		 * "Sync Language", "Sync Script", and "Sync Locale" options.
		 */
		if(intval(get_option($this->get('slug') . '_sync_mode', 10)) === 1){

			//Retrieve the 'Sync Language' and the "Sync Locale' from the options
			$sync_language = get_option($this->get('slug') . '_sync_language');
			$sync_script = get_option($this->get('slug') . '_sync_script');
			$sync_locale = get_option($this->get('slug') . '_sync_locale');

			//Get the URL to connect
			$adapted_url_to_connect = $this->generate_url_to_connect(
				[
					'url_to_connect' => $connection->url_to_connect,
					'url'            => $connection->url,
					'language'       => $connection->language,
					'script'         => $connection->script,
					'locale'         => $connection->locale
				],
				$sync_language,
				$sync_script,
				$sync_locale
			);

		}else{

			//Use the original url to connect of the connection
			$adapted_url_to_connect = $connection->url_to_connect;

		}

		//Add a new connection into the database
		global $wpdb;
		$table_name = $wpdb->prefix . "da_hm_connect";
		$safe_sql = $wpdb->prepare("INSERT INTO $table_name SET url_to_connect = %s ,
                 url = %s,
                 language = %s,
                 script = %s,
                 locale = %s,
                 inherited = %d",
			$adapted_url_to_connect,
			$connection->url,
			$connection->language,
			$connection->script,
			$connection->locale,
			1
		);

		$query_result = $wpdb->query($safe_sql);

	}

}