<?php

/******************************************************************************
 *
 *	PROJECT: Flynax Classifieds Software
 *	VERSION: 4.X
 *	LICENSE: FL4HLD2A8696 - http://www.flynax.com/license-agreement.html
 *	PRODUCT: Real Estate Agency
 *	DOMAIN: gevimmo.com
 *	FILE: RLBADWORDS.CLASS.PHP
 *
 *	The software is a commercial product delivered under single, non-exclusive,
 *	non-transferable license for one domain or IP address. Therefore distribution,
 *	sale or transfer of the file in whole or in part without permission of Flynax
 *	respective owners is considered to be illegal and breach of Flynax License End
 *	User Agreement.
 *
 *	You are not allowed to remove this information from the file without permission
 *	of Flynax respective owners.
 *
 *	Flynax Classifieds Software 2017 |  All copyrights reserved.
 *
 *	http://www.flynax.com/
 *
 ******************************************************************************/

class rlBadWords extends reefless
{
    /**
     * Checks system languages in the langpack folder
     *
     **/
    public function checkInstalledLanguages()
    {   
        global $rlLang;

        $langugeList = $GLOBALS['languages'] ?: $rlLang -> getLanguagesList(); 
        $delimiter = PHP_EOL;

        foreach ($langugeList as $item) {
            $path = RL_PLUGINS . "badWordsFilter/langpack/" . $item['Code'] . ".txt";

            $fp = @fopen($path, 'r');
            if ($fp) {
                $badwordsArray = explode($delimiter, fread($fp, filesize($path)));
                $badwordsArray = array_diff($badwordsArray, array(''));
                $this->importBadWords($badwordsArray, $item['Code']);
            }
        }
    }

    /**
     * Import bad words
     *
     * @param Bad word string devided by some delimitr
     * @param Language of bad words
     * @param Delimitr between each bad word
     *
     **/
    public function importBadWords($badwordsArray, $lang, $delimiter = PHP_EOL)
    {
        global $rlValid;

        $badwordsArray = array_filter($badwordsArray);

        $sql = "INSERT IGNORE INTO `" . RL_DBPREFIX . "bad_words` (`Code`,`Value`,`Status`) VALUES ";

        foreach ($badwordsArray as $key => $item) {
            $item = $rlValid->xSql($item);
            $sql .= "('{$lang}','{$item}','active'),";
        }
        $sql = substr($sql, 0, -1);
        $sql .= ";";

        $this->query($sql);
    }

    /**
     * Delete bad word from Admin panel's grid
     *
     * @param Bad word id
     *
     * @return javascript code for refreshing badword grid
     **/
    public function ajaxDeleteBadWord($badWord_id = false)
    {
        global $_response;

        $badWord_id = (int) $badWord_id;

        if (!$badWord_id) {
            return $_response;
        }

        //delete bad word
        $this->query("DELETE FROM `" . RL_DBPREFIX . "bad_words` WHERE `ID` = '{$badWord_id}' LIMIT 1");

        $_response->script("badwordsGrid.init();");

        return $_response;
    }

    /**
     * Insert bad word
     *
     * @param Bad word
     *
     * @return status of iserting bad word procces
     **/
    public function ajaxAddBadWord($data)
    {
        global $_response, $lang, $rlActions, $rlValid;

        $bad_word_value = $data[0][1];
        $bad_word_status = $data[1][1];

        $lang_id = $rlValid->xSql($_GET['lang']);
        $lang_code = $this->getOne('Code', "`ID`={$lang_id}", "languages");

        $data = array(
            'Code' => $lang_code,
            'Value' => $bad_word_value,
            'Status' => $bad_word_status,
        );

        $if_exist = $this->getOne("ID", "`Value`='{$bad_word_value}'", "bad_words");

        if (!$if_exist) {
            $rlActions->insertOne($data, 'bad_words');
            $_response->script("printMessage('notice','" . $lang['bw_sucess'] . "');");
            $_response->script("$('#add_badword').val('{$lang['add']}');");
            $_response->script("badwordsGrid.init();");
            $_response->script("$('#badword_value').val('');");
        } else {
            $_response->script("printMessage('error', '$bad_word_value " . $lang['bw_exist'] . "');");
            $_response->script("$('#add_badword').val('{$lang['add']}');");
        }

        return $_response;
    }

    /**
     * Check form fields for bad words.
     *
     * @param Form fields and values array
     * @param Error array
     *
     * @return Erros
     **/
    public function checkForm($data, $errors, $type)
    {
        global $rlSmarty, $lang;

        // $sql = "SELECT `Value` FROM `" . RL_DBPREFIX . "bad_words` WHERE `Code`='" . RL_LANG_CODE . "'";
        $sql = "SELECT `Value` FROM `" . RL_DBPREFIX . "bad_words` WHERE `Status`='active'";
        $badword_list = $this->getAll($sql, array(false, 'Value'));

        if($badword_list) {
            $regex = "(^|\s)" . implode("[\?\,\;\-\:\!\.]*($|\s)|(^|\s)", $badword_list) . "($|\s)";
            foreach ($data as $field_key => $value) {

                if (is_array($value) && isset($value['value'])) {
                    $value_to_check = $value['value'];
                } elseif (is_array($value) && isset($value[0])) {
                    $value_to_check = $value['value'][0];
                } else {
                    $value_to_check = $value;
                }

                if ($type == "comment") {
                    $field_title = $field_key == 'message' ? $lang['message'] : $lang['comment_' . $field_key];
                } elseif ($type == "contacts") {
                    $field_title = $lang[$field_key];
                } else {
                    $field_title = $lang[$type . "_fields+name+" . $field_key]
                    ? $lang[$type . "_fields+name+" . $field_key]
                    : $field_key;
                }

                $result = preg_match("/" . $regex . "/iu", $value_to_check, $matches);

                if ($result) {
                    $bw_errors[] = $lang['bw_error'] . " <b>" . $field_title . "</b>";

                    if ($GLOBALS['page_info']['Controller'] == 'registration') {
                        $bw_error_fields .= "account[" . $field_key . "],";
                    } else {
                        $bw_error_fields .= "f[" . $field_key . "],";
                    }

                }

            }

            /*applying to the existing errors array*/
            foreach ($bw_errors as $key => $value) {
                $errors[] = $value;
            }

            $GLOBALS['error_fields'] .= $bw_error_fields;
        }
        
        return $errors;
    }

    /**
     * Adding Bad word icon in Language grid
     *
     **/
    public function hookAddBadWordIcon()
    {
        global $rlSmarty, $lang;

        $bw_count = $lang['bw_manage'];
        $bw_column_header = $lang['bw_manage_header'];

        echo <<<JS
        var exjs_bw_column = {
                  header: '$bw_column_header',
                  width: 150,
                  fixed: true,
                renderer: function(val, ext, row) {
                   var lang_array = row.data.Data.split('|');
                   var lang_id = lang_array[0];
                   var out = "<b class='x-grid3-cell-inner x-grid3-col-rlExt_item_bold'>" + row.data.bw_count;
                   out += "</b><a class='green_11_bg' href='"+rlUrlHome;
                   out += "index.php?controller=bad_words_filter&amp;lang="+lang_id+"'>$bw_count</a>";
                   return out;
              }
         };
        languagesGrid.getInstance().columns.splice(2, 0, exjs_bw_column);
        languagesGrid.getInstance().fields.push({name: 'bw_count', mapping: 'bw_count'});
JS;
    }

    /**
     * Bad Words plugin installation function
     * @since v 1.0.2
     *
     **/
    public function bwInstall()
    {
        $sql = "CREATE TABLE `".RL_DBPREFIX."bad_words` (
              `ID` int(11) NOT NULL auto_increment,
              `Code` char(2) character set utf8 NOT NULL,
              `Value` varchar(255) character set utf8 NOT NULL,
              `Status` enum('active','approval','trash') NOT NULL default 'active',
              PRIMARY KEY  (`ID`),
              UNIQUE `bw_uniq` (`Code`,`Value`)
        ) DEFAULT CHARSET=utf8;";
        $this->query($sql);
        
        $this->checkInstalledLanguages();
        $GLOBALS['rlPlugin'] -> controller = '';
    }
}
