<?php

/******************************************************************************
 *
 *	PROJECT: Flynax Classifieds Software
 *	VERSION: 4.X
 *	LICENSE: FL4HLD2A8696 - http://www.flynax.com/license-agreement.html
 *	PRODUCT: Real Estate Agency
 *	DOMAIN: savingrack.com
 *	FILE: RLWORDPRESSBRIDGE.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 rlWordpressBridge extends reefless
{
    /**
     * class constructor
     *
     **/
    public $wp_root = "";
    public $wp_functions = "";

    function checkWpUrl($url)
    {
        global $lang;
        if (is_numeric(strpos($url, '[[http'))) {
            $url = preg_replace("#\[\[http(s)?_pref\]\]#", "http$1", $url);
        }

        $wp_url = $url;
        $fl_url = RL_URL_HOME;
        $errors = array();

        if ($wp_url != "http://") {

            //проверка находится ли данные два адреса в одном домене.
            $wp_parsed_url = parse_url($wp_url);
            $wp_host = $wp_parsed_url['host'];
            $fl_parsed_url = parse_url($fl_url);
            $fl_host = $fl_parsed_url['host'];
            $is_same_domain = str_replace($fl_host, '', $wp_host);

            //методы проверки
            $check_in = array("parent", "child");
            if (strlen($is_same_domain) != strlen($wp_host)) {
                //через субдомен или через путь будем искать конфиги вордпресса
                if ($wp_host != $fl_host) {
                    $folders = explode(".", $is_same_domain);
                    $folders = array_filter($folders);
                } else {
                    $wp_path = $wp_parsed_url['path'];
                    $is_file = pathinfo($wp_path, PATHINFO_EXTENSION);
                    $folders = explode('/', $wp_path);
                    $folders = array_filter($folders);
                    if ($is_file) {
                        array_pop($folders);
                    }
                }

                foreach ($check_in as $value) {
                    $folders_count = count($folders);

                    for ($i = 0; $i < $folders_count; $i++) {
                        if ($this->determinateWpConfigs($folders, $value)) {
                            $wp_found = 1;
                            break;
                        } else {
                            array_pop($folders);
                        }
                    }
                    if ($wp_found) {
                        break;
                    }
                }

                if (!$wp_found) {
                    $errors[] = $lang['wpb_wordpress_doesnt_found'];
                }

            } else {
                $errors[] = $lang['wpb_wrong_url'];;
            }

        } else {
            $errors[] = $lang["wpb_enter_url"];
        }

        return $errors;
    }

    public function determinateWpConfigs($folder_array, $which_folder)
    {
        global $rlConfig;

        $this->loadClass('Config');

        $path = RL_ROOT . implode("/", $folder_array) . RL_DS;

        $wp_config_path = $path . "wp-config.php";

        if (file_exists($wp_config_path)) {
            require_once $wp_config_path;

            $this->wp_root = ABSPATH;
            $this->wp_functions = ABSPATH . "wp-load.php";

            $rlConfig->setConfig('fl_wp_root', ABSPATH);
            $rlConfig->setConfig('wp_config_path', ABSPATH . "wp-load.php");

            return true;
        } else {

            return false;
        }
    }
    function determinateWPConfigsFTP($path) {
        global $rlConfig, $lang;
        $tempError = array();
        if($path) {
            $last_url_char = substr($path, -1);
            
            if($last_url_char ==='/' || $last_url_char ==='\\' ) {
            } else {
                $path.= RL_DS;
            }
            
            $this->loadClass('Config');
            $wp_config_path = $path . "wp-config.php";
            
            if (file_exists($wp_config_path)) {

                require_once $wp_config_path;

                $this->wp_root = ABSPATH;
                $this->wp_functions = ABSPATH . "wp-load.php";

                $rlConfig->setConfig('fl_wp_root', ABSPATH);
                $rlConfig->setConfig('wp_config_path', ABSPATH . "wp-load.php");

                return false;
            } else {
                $tempError[] = $lang['wp_path_wrong'];
            }
        } else {

        }
        return $tempError; 
    }
    function connectToWp()
    {
        global $rlConfig;
        
        if(!file_exists($this->wp_functions)) {
            return false;
        }

        require_once $this->wp_functions;
        include_once $this->wp_root . 'wp-admin/includes/plugin.php';

        if (is_plugin_active('flynax-bridge/flynax-bridge.php')) {
            //вывести нотис о том, что все успешно было подключено и связано между собой
            add_option("FL_ROOT_DIR", RL_ROOT);
            add_option("RL_ADMIN_CONTROL", RL_ADMIN_CONTROL);
            add_option("RL_LIBS", RL_LIBS);
            flb_initial();
        } else {
            $errors[] = $lang['wpb_not_configured'];
        }
    }

    function wpDisconnect()
    {
        global $rlConfig;
        $wp_functions = $rlConfig->getConfig('wp_config_path');
        
        if(!file_exists($wp_functions)) {
            return false;
        }

        if ($wp_functions) {
            require_once $wp_functions;
            delete_option("FL_ROOT_DIR");
            delete_option("RL_ADMIN_CONTROL");
            delete_option("RL_LIBS");
        }
    }

    function wpbRegister($username, $email, $account_type, $first_name, $last_name, $password, $personal_address=false)
    {
        global $rlAccount, $rlValid, $rlAction;

        $register_errors = array();
        $username = $rlValid->xSql($username);
        $email = $rlValid->xSql($email);
        $account_type = $rlValid->xSql($account_type);
        $first_name = $rlValid->xSql($first_name);
        $last_name = $rlValid->xSql($last_name);

        $username_exist = $this->getOne("ID", "`Username` ='{$username}'", 'accounts');
        if ($username_exist) {
            $register_errors['fl_user_exist'] = "The <b>" . $username . "</b> username is already use in your Flynax site";
        }
        $email_exist = $this->getOne("ID", "`Mail` ='{$email}'", 'accounts');
        if ($email_exist) {
            $register_errors['fl_email_exist'] = "The <b>" . $email . "</b> email is already use in your Flynax site";
        }

        if (empty($register_errors)) {
            $new_account = array(
                "Username" => $username,
                "Mail" => $email,
                "First_name" => $first_name,
                "Last_name" => $last_name,
                "Type" => $account_type,
                "Password" => md5($password),
                "Date" => date('Y-m-d H:i:s'),
            );

            if($account_type == 'dealer') {
                $new_account['Own_address'] = $personal_address;
            }
            $this->loadClass('Actions');
            $GLOBALS['rlActions']->insertOne($new_account, 'accounts');

        }
        return $register_errors;
    }
    function getUserMeta($username, $meta_name) {

        if(!$username || !$meta_name) {
            return false;
        }

        $sql  = "SELECT `Meta_value` FROM `".RL_DBPREFIX."wb_usermeta` ";
        $sql .="WHERE `Username` = '{$username}' ";
        $sql .="AND `Meta_name`='{$meta_name}'";

        $meta_value = $this->getAll($sql);

        if(empty($meta_value)) {
            return false;
        } else {
            return $meta_value[0]['Meta_value'];
        }

    }

    function addUserMeta($username, $meta_name, $meta_value) {
        if(!$username || !$meta_name || !$meta_value ) {
            return false;
        }
        $this->loadClass('Actions');
        $this->loadClass('Valid');
        $username = $GLOBALS['rlValid']->xSql($username);
        $meta_key = $GLOBALS['rlValid']->xSql($meta_name);
        $meta_value =  $GLOBALS['rlValid']->xSql($meta_value);
        $sql = "SELECT * FROM `".RL_DBPREFIX."wb_usermeta` WHERE `Username`='$username' ";
        $sql .= "AND `Meta_name`='{$meta_name}'";

        $meta_exist = $this->getAll($sql);
        if(!empty($meta_exist)) {

            $updateData = array(
                'fields' => array(
                    'Meta_value' => $meta_value
                ),
                'where' => array(
                    'ID' => $meta_exist[0]['ID']
                )
            );            
           if( $GLOBALS['rlActions']->updateOne( $updateData, 'wb_usermeta') ) {
            $is_insert = true;
           }

        } else {

            $inser_data = array(
                'Username' => $username,
                'Meta_name' => $meta_key,
                'Meta_value' => $meta_value
            );

            $is_insert =$GLOBALS['rlActions']->insertOne($inser_data,'wb_usermeta');
        }
        
        if($is_insert) {
            return true;
        } else {
            return false;
        }
    }

    function removeMeta($username,$meta_name) {

        if(!$username || !$meta_name) {
            return false; 
        }

        $sql ="SELECT `ID` FROM `".RL_DBPREFIX."wb_usermeta` ";
        $sql .="WHERE `Username`='{$username}' AND `Meta_name`='{$meta_name}'";
        $meta_exist = $this->getAll($sql);

        if($meta_exist) {
            $sql ="DELETE FROM `".RL_DBPREFIX."wb_usermeta` ";
            $sql .="WHERE `Username`='{$username}' AND `Meta_name`='{$meta_name}'";
            if($this->query($sql)) {
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }

    }

    function removeAllUserMeta($username) {

        if(!$username) {
            return false;
        } 

        $sql ="DELETE FROM `".RL_DBPREFIX."wb_usermeta` WHERE `Username`='{$username}'";
        if($this->query($sql)) {
            return true;
        } else {
            return false;
        }

    }

    function flbRegister($username, $email, $password, $account_type,$personal_address = false) {
        global $rlConfig, $errors, $lang;
        
        if(!file_exists($rlConfig->getConfig('wp_config_path'))) {
            return false;
        }

        require_once $rlConfig->getConfig('wp_config_path');
        if(username_exists($username) || email_exists($email)) {
            $errors[] = $lang['wpb_user_exist'];
            $error_fields .= 'profile[mail],';
        } else {
            if(!$errors){
                $userdata = array(   
                    'user_login' => $username,
                    'user_email' =>  $email  
                );  
                $user_id = wp_insert_user($userdata);
                wp_set_password($password, $user_id);
                $updateData['ID'] = $user_id;
                $updateData['role'] = $account_type;
                
                if($_POST['account']['First_name']) {
                    $updateData['first_name'] = $_POST['account']['First_name'];
                }
                if($_POST['account']['First_name']) {
                    $updateData['last_name']= $_POST['account']['Last_name'];
                }
                wp_update_user($updateData);

                $own_page_exist = $this->getOne('Page',"`Key`='{$account_type}'",'account_types');
                if($own_page_exist) {
                    if($personal_address) {
                        update_user_meta($user_id,'own_address', $personal_address);
                    }
                }
                $this->addUserMeta($username,false,$user_id,'synch_status','1');
                $this->addUserMeta($username,false,$user_id,'reg_from','fl');
                $this->addUserMeta($username,false,$user_id,'red_data',date('Y-m-d H:i:s'));
            }
        }
    }

    function flbReassignListings($from = null , $to = null) {
    
        if(!$from || !$to) {
            return false;
        }
        
        $this->loadClass('Actions');
        $this->loadClass('Account');
        $this->loadClass('Db');
        $this->loadClass('Mail');
        $config = $GLOBALS['rlConfig']-> allConfig();
        $sql = "SELECT `ID` FROM `".RL_DBPREFIX."accounts` WHERE `Username`='{$from}'";
        $from_exist = $GLOBALS['rlDb']->getAll($sql);
        //deleted user exist
        if(!empty($from_exist)) {
            $from_id = $from_exist[0]['ID'];
            $sql = "SELECT `ID` FROM `".RL_DBPREFIX."listings` WHERE `Account_ID`={$from_id}";
            $from_listings_exist =  $GLOBALS['rlDb']->getAll($sql);

            //and listing exist
            if(!empty($from_listings_exist)){

                $to_exist = $GLOBALS['rlDb']->getOne('ID',"`Username`='{$to}'",'accounts');
                //f user exist
                if($to_exist) {

                    foreach ($from_listings_exist as $key => $listing) {
                        $listing_id = $listing['ID'];
                        $update_data = array(
                            'fields' => array(
                              'Account_ID' => $to_exist
                            ),
                            'where' => array(
                              'ID' => $listing['ID'],
                            )
                        );
                        $GLOBALS['rlActions'] -> updateOne( $update_data, 'listings');
                    }
                } else {
                     
                     $reserve_login = $config['wp_reserve_login'];
                     $reserve_email = $config['wp_reserve_email'];
                     $password = $this -> generateHash(10, 'password', true);
                     $sql = "SELECT `ID` FROM `".RL_DBPREFIX."accounts` WHERE `Username`='{$reserve_login}'";
                     $reserve_exist =  $GLOBALS['rlDb']->getOne('ID',"`Username`='{$reserve_login}'",'accounts');
                     if(empty($reserve_exist)) {
                        // $new_account = $GLOBALS['rlAccount'] ->quickRegistration($reserve_login, $reserve_email);
                        if ( $config['account_quick_account_type'] && $this -> getOne('ID', "`Key` = '{$config['account_quick_account_type']}' AND `Status` = 'active'", 'account_types') )
                        {
                            $type = $config['account_quick_account_type'];
                        }
                        else
                        {
                            $type = $this -> getOne('Key', "`ID` <> 1 ORDER BY `ID` ASC", 'account_types');
                        }
                        /* insert new account */

                        $own_address = $GLOBALS['rlValid'] -> str2path($reserve_login);

                        $new_account = array(
                            'Quick' => 1,
                            'Type' => $type,
                            'Username' => $reserve_login,
                            'Own_address' => $own_address,
                            'Password' => md5('12345'),
                            'Lang' => strtolower(RL_LANG_CODE),
                            'Mail' => $reserve_email,
                            'Date' => 'NOW()',
                            'Status' => 'active'
                        );
                        $GLOBALS['rlActions'] -> insertOne($new_account, 'accounts');
                        $account_id = $this -> insertID();
                        $upd_data = array();
                        foreach ($from_listings_exist as $key => $listing) {
                            $listing_id = $listing['ID'];

                            $upd_data['ID'] = $listing_id;
                            if( $this -> getRow("SHOW FIELDS FROM  `".RL_DBPREFIX."listings` WHERE `Field` = 'cl_direct'") )
                            {
                                $upd_data['cl_direct'] = '1';
                            }
                            $update_data = array(
                                'fields' => array(
                                  'Account_ID' => $account_id
                                ),
                                'where' => $upd_data
                            );
                            $GLOBALS['rlActions'] -> updateOne( $update_data, 'listings');
                        }
                  } else {
                        foreach ($from_listings_exist as $key => $listing) {
                            $listing_id = $listing['ID'];
                            $update_data = array(
                                'fields' => array(
                                  'Account_ID' => $reserve_exist
                                ),
                                'where' => array(
                                  'ID' => $listing['ID'],
                                )
                            );
                            $GLOBALS['rlActions'] -> updateOne( $update_data, 'listings');
                        }
                    }
                }
            }
            $this -> loadClass( 'Admin', 'admin' );
            $GLOBALS['rlAdmin']->ajaxDeleteAccount($from_id, false, true);
        }
    }

    function flbDeleteUser($user_login) {
        $username_exist = $this->getOne("ID", "`Username` ='{$user_login}'", 'accounts');
        if($username_exist) {
            $user_id = (int)$username_exist;
            $this -> loadClass( 'Admin', 'admin' );
            $GLOBALS['rlAdmin']->ajaxDeleteAccount($user_id, false, true);
        }
    }

    function getLastPosts($post_count =  false) 
    {
        global $rlConfig, $errors, $rlSmarty, $config;
        $function_path =$rlConfig->getConfig('wp_config_path');
        if(!file_exists($rlConfig->getConfig('wp_config_path'))) {
            return false;
        }
        if(!$post_count && !$function_path) {
            return false;
        }

        require_once $rlConfig->getConfig('wp_config_path');

        $args = array(
            'numberposts' => $post_count,
            'orderby' => 'post_date',
            'order' => 'DESC',
            'post_type' => 'post',
            'post_status' => 'publish'
            );
        $recent_posts = wp_get_recent_posts( $args, ARRAY_A );
        foreach ($recent_posts as $key => $post) {
            $url = wp_get_attachment_url( get_post_thumbnail_id($post['ID']));
            $userObj = get_userdata($post['post_author']);
            $recent_posts[$key]['img_url'] = $url;
            $recent_posts[$key]['author_username'] = $userObj->user_login;
            $recent_posts[$key]['author_display_name'] = $userObj->display_name;
            $recent_posts[$key]['short_desc'] = wp_trim_words($post['post_content'],$config['wp_box_short_excerpt_size'],null);
            $recent_posts[$key]['medium_desc'] = wp_trim_words($post['post_content'],$config['wp_box_medium_excerpt_size'],null);
        }

        $rlSmarty -> assign("recent_posts", $recent_posts);
        $rlSmarty -> display(RL_PLUGINS."wordpressBridge".RL_DS."recent_posts.tpl");

    }
}
