<?php
/*
Plugin Name: WP Spin
Plugin URI: http://WPSpin.com
Description: Spin Post on Auto or Manually using the Advanced API from The Best Spinner. Schedule Post Updates for enhanced SEO and enhanced Content Management.
Version: 1.0.2.2
Author: Mike Johnson
Author URI: http://WPSpin.com
*/

set_time_limit(0);
error_reporting(0);

class WPSpin
{
    public $wpspin_options = array(
        'wpspin_login',
        'wpspin_pass',
        'wpspin_autospin',
        'wpspin_spin_quality',
        'wpspin_auto_options',
        'wpspin_time_count',
        'wpspin_time_type',
        'wpspin_spin_count',
        'wpspin_publish',
        'wpspin_spin_title',
        'wpspin_excluded_words',
        'my_alarm'
        ), 
        $table, 
        $wpdb,
        $option = array(),
        $hideKeys = array(),
        $mySpin,
        $postTitle = array(),
        $mySession = 0; 
        
    function __construct() 
    {
        register_activation_hook(__FILE__,   array (&$this, 'wpspinInstall') );   // correct install
        register_deactivation_hook(__FILE__, array (&$this, 'wpspinUninstall') ); // correct uninstall
        
        remove_filter('the_content' , 'wptexturize');
        remove_filter('comment_text', 'wptexturize');
        remove_filter('the_excerpt' , 'wptexturize');

        //add_action('init'               , array (&$this, 'myInit') );
        add_action('admin_menu'         , array (&$this, 'adminPageCreate') );
        add_action('admin_menu'         , array (&$this, 'calendarPageCreate') );
        //add_action('admin_menu'         , array (&$this, 'synonymsPageCreate') );
        add_action('admin_head'         , array (&$this, 'headHook') ); 
        add_action('publish_post'       , array (&$this, 'getID') ); 
        add_action('publish_page'       , array (&$this, 'getID') );
        add_action('delete_post'        , array (&$this, 'deletePost') );
        add_action('my_hourly_event'    , array (&$this, 'spinSchedule') );
        

        add_filter( 'mce_buttons_3'       , array (&$this, 'mce_buttons') );
        add_filter( 'mce_external_plugins', array (&$this, 'mce_external_plugins') );
        add_filter( 'the_title'           , array (&$this, 'spinViewedTitle') );
        add_filter( 'single_post_title'   , array (&$this, 'spinViewedTitle') );
        add_filter( 'the_content'         , array (&$this, 'spinViewed') );
    }
    
    function myInit() {
        $path = pathinfo( $_SERVER['SCRIPT_NAME'] );

        if( $path['basename'] == 'post.php' OR $path['basename'] == 'post-new.php' ) {
            /*wp_deregister_script( 'jquery' );
            wp_deregister_script( 'jquery-ui-core' );
            wp_deregister_script( 'jquery-ui-draggable' );
            wp_deregister_script( 'jquery-ui-resizable' );
            wp_deregister_script( 'jquery-ui-dialog' );
            wp_deregister_script( 'jquery-ui-widget' );
            wp_deregister_script( 'jquery-ui-position' );
            wp_deregister_script( 'jquery-ui-mouse' );
            wp_deregister_script( 'jquery-ui-button' );
            
            wp_register_script( 'jquery', WP_PLUGIN_URL.'/wpspin/js/jquery-1.4.4.js');
            wp_register_script( 'jquery-ui-core', WP_PLUGIN_URL.'/wpspin/js/ui/jquery.ui.core.js');
            wp_register_script( 'jquery-ui-mouse', WP_PLUGIN_URL.'/wpspin/js/ui/jquery.ui.mouse.js');
            wp_register_script( 'jquery-ui-button', WP_PLUGIN_URL.'/wpspin/js/ui/jquery.ui.button.js');
            wp_register_script( 'jquery-ui-draggable', WP_PLUGIN_URL.'/wpspin/js/ui/jquery.ui.draggable.js');
            wp_register_script( 'jquery-ui-resizable', WP_PLUGIN_URL.'/wpspin/js/ui/jquery.ui.resizable.js');
            wp_register_script( 'jquery-ui-dialog', WP_PLUGIN_URL.'/wpspin/js/ui/jquery.ui.dialog.js');*/
        }
    }
    
    function wpDB() {
        global $wpdb;
        $this->table       = $wpdb->prefix . "wpspin_base";
        $this->table_syn   = $wpdb->prefix . "wpspin_synonyms";
        $this->table_posts = $wpdb->prefix . "posts";
        $this->prefix      = $wpdb->prefix;
        $this->wpdb        = $wpdb;
    }
    
    function getOptions() {
        foreach ($this->wpspin_options as $wpspin_opt) {
            $this->option[$wpspin_opt] = get_option($wpspin_opt);
        }
    }
    
    function wpspinInstall() {
        $this->wpDB();
    
        $charset_collate = '';
        if ( version_compare(mysql_get_server_info(), '4.1.0', '>=') )
            $charset_collate = "DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci";
            
        $sql = "CREATE TABLE IF NOT EXISTS `".$this->table."` (
            `id` INT NOT NULL,
            `mode` VARCHAR(12) NOT NULL,
            `auto_options` VARCHAR(2) NOT NULL,
            `quality` VARCHAR(2) NOT NULL,
            `time_count` VARCHAR(2) NOT NULL,
            `time_type` VARCHAR(2) NOT NULL,
            `spin_count` VARCHAR(2) NOT NULL,
            `spin_publish` VARCHAR(2) NOT NULL,
            `spin_title` VARCHAR(2) NOT NULL,
            `excluded` TEXT NOT NULL,
            `alarm` TEXT NULL,
            `content` TEXT NULL,
            `status` INT(2) NOT NULL,
            UNIQUE KEY id (id)
        )$charset_collate";
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    
        add_option('wpspin_login', '');
        add_option('wpspin_pass', '');
        add_option('wpspin_autospin', '2');
        add_option('wpspin_spin_quality', '1');
        add_option('wpspin_auto_options', '1');
        add_option('wpspin_time_count', '1');
        add_option('wpspin_time_type', '1');
        add_option('wpspin_spin_count', '1');
        add_option('wpspin_publish', '1');
        add_option('wpspin_spin_title', '0');
        add_option('wpspin_excluded_words', '&');
        add_option('my_alarm', '0');
    
        wp_schedule_event(time(), 'hourly', 'my_hourly_event');
    }
    
    function wpspinUninstall() {
    
        $this->wpDB();
        $sql  = "DROP TABLE `".$this->table."`";
        $this->wpdb->query( $sql );
	
        delete_option('wpspin_login');
        delete_option('wpspin_pass');
        delete_option('wpspin_autospin');
        delete_option('wpspin_spin_quality');
        delete_option('wpspin_auto_options');
        delete_option('wpspin_time_count');
        delete_option('wpspin_time_type');
        delete_option('wpspin_spin_count');
        delete_option('wpspin_publish');
        delete_option('wpspin_spin_title');
        delete_option('wpspin_excluded_words');
        delete_option('my_alarm');
	
        wp_clear_scheduled_hook('my_hourly_event');
    }
    
    function mce_buttons( $buttons ) {
        array_push($buttons, "wpspin1", "wpspin2");
        return $buttons;
    }

    function mce_external_plugins( $plugin_array ) {  
        if (function_exists (plugins_url) )
            $plugin_array['wpspin'] = plugins_url ('/wpspin/js/wpspin.js');
        else
            $plugin_array['wpspin'] = get_option('siteurl') . '/wp-content/plugins/wpspin/js/wpspin.js';
        return $plugin_array;
    }
    
    function adminPageCreate() {
        add_options_page('WP Spin Options', 'WP Spin Options', 8, __FILE__, array (&$this, 'adminPage') );
    }
    
    function adminPage() {
        include_once( dirname(__FILE__) . '/includes/adminpage.php' );
    }
    
    function calendarPageCreate() {
        add_options_page('WP Spin Scheduler', 'WP Spin Scheduler', 8, dirname(__FILE__) . '/includes/datepage.php', array (&$this, 'datesPage') );
    }
    
    function datesPage() {
        include_once( dirname(__FILE__) . '/includes/datepage.php' );
    }
    
    function synonymsPageCreate() {
        add_options_page('WP Spin - My Synonyms', 'WP Spin - My Synonyms', 8, dirname(__FILE__) . '/includes/synonympage.php', array (&$this, 'synonymsPage') );
    }
    
    function synonymsPage() {
        include_once( dirname(__FILE__) . '/includes/synonympage.php' );
    }
    
    function getID( $postID ) {
        include_once( dirname(__FILE__) . '/class.getter.php' );
        $myGet = new Getter( $postID );
        return $postID;
    }
    
    function spinAll() {
        $allPosts = $this->myGetPosts();
        $allPages = $this->myGetPages();

        $debug = 0;
    
        if( !count($allPosts) AND !count($allPages) ) {
            echo "<script>alert(\"Posts and pages not found on this blog.\");</script>";
            return 0;
        }
        //echo "<script>alert(\"Found ".count($allPosts)." posts and ".count($allPages)." pages.\\n\\nSpin it?\");</script>";
    
        $this->getOptions();
        $this->wpDB();
    
        if( $debug ) { $fp = fopen( 'logs_spin_all.txt', 'a' ); }
        $goodPostSpin = 0; $failedPostSpin = 0; $goodPageSpin = 0; $failedPageSpin = 0;
    
        foreach( $allPosts as $post ) {
            //echo "[-] ".$post->ID."<br>"; continue;
            if( $this->wpdb->get_var( "SELECT COUNT(*) FROM `".$this->table."` WHERE `id`='".$post->ID."'" ) ) continue;
            if( $this->option['wpspin_spin_title'] == 1 ) $title = $post->post_title; else $title = FALSE;

            //echo "Spin ".$post->ID." (".$post->post_content.")<br> ".$this->option['wpspin_spin_quality'].";".$this->option['wpspin_excluded_words'].";".$this->mySession."<br>";
        
            if( $wtf = $this->spinPost( $post->ID, $post->post_content, $this->option['wpspin_spin_quality'], $this->option['wpspin_excluded_words'], $title ) ) {
                if( $debug ) fwrite( $fp, "[".date('Y-m-d H:i:s')."] spin post #".$post->ID." - DONE\n" );
                $goodPostSpin++;
            } else {
                if( $debug ) fwrite( $fp, "[".date('Y-m-d H:i:s')."] spin post #".$post->ID." - FAILED\n" );
                $failedPostSpin++;
            }
        }
        foreach( $allPages as $page ) {
            if( $this->wpdb->get_var( "SELECT COUNT(*) FROM `".$this->table."` WHERE `id`='".$page->ID."'" ) ) continue;
            if( $this->option['wpspin_spin_title'] == 1 ) $title = $page->post_title; else $title = FALSE;
        
            if( $this->spinPost( $page->ID, $page->post_content, $this->option['wpspin_spin_quality'], $this->option['wpspin_excluded_words'], $title ) ) {
                if( $debug ) { fwrite( $fp, "[".date('Y-m-d H:i:s')."] spin page #".$page->ID." - DONE\n" ); }
                $goodPageSpin++;
            } else {
                if( $debug ) { fwrite( $fp, "[".date('Y-m-d H:i:s')."] spin page #".$page->ID." - FAILED\n" ); }
                $failedPageSpin++;
            }
        }
        if( $debug ) { fclose( $fp ); }
    
        echo "<script>alert(\"Successful spin $goodPostSpin posts and $goodPageSpin pages.\\n\\nFailed $failedPostSpin posts and $failedPageSpin pages\");</script>";
    }
    
    function spinViewedTitle( $title ) {
        $md5 = md5($title);
        if( !$this->postTitle[$md5] ) {
            preg_match_all("|{(.*)}|U",$title,$out);
            foreach( $out[1] as $synonyms ) {
                $synonym = explode( "|", $synonyms );
                $randSynonym = $synonym[rand(0,(count($synonym)-1))];
                $title = str_replace( '{'.$synonyms.'}', $randSynonym, $title );
            }
            if( is_single() OR is_page() ) $this->postTitle[$md5] = $title;
        } else {
            $title = $this->postTitle[$md5];
        }
        return $title;
    }
    
    function spinViewed( $content ) {
        $postInfo = wp_get_single_post( 0,ARRAY_A );
        
        if( !is_single() AND !is_page() ) {
            preg_match_all("|{(.*)}|U",$content,$out);
            foreach( $out[1] as $synonyms ) {
                $synonym = explode( "|", $synonyms );
                $randSynonym = $synonym[0];
                $content = str_replace( '{'.$synonyms.'}', $randSynonym, $content );
            }
        } else {
            $this->wpDB();
            $row = $this->wpdb->get_row("SELECT * FROM `".$this->table."` WHERE `id`='".$postInfo['ID']."' AND `status`='1'", ARRAY_A);
            $this->getOptions();
            
            if( $row['auto_options'] == 2 ) {
                preg_match_all("|{(.*)}|U",$content,$out);
                foreach( $out[1] as $synonyms ) {
                    $synonym = explode( "|", $synonyms );
                    $randSynonym = $synonym[rand(0,(count($synonym)-1))];
                    $content = str_replace( '{'.$synonyms.'}', $randSynonym, $content );
                }
            } else if( $row ) {
                preg_match_all("|{(.*)}|U",$content,$out);
                foreach( $out[1] as $synonyms ) {
                    $synonym = explode( "|", $synonyms );
                    $randSynonym = $synonym[0];
                    $content = str_replace( '{'.$synonyms.'}', $randSynonym, $content );
                }
            } else if( $this->option['wpspin_auto_options'] == 2 AND !$this->wpdb->get_var( "SELECT COUNT(*) FROM `".$this->table."` WHERE `id`='".$postInfo['ID']."'" ) ) {
                $title = ( $this->option['wpspin_spin_title'] == 1 ) ? $postInfo['post_title'] : FALSE;
                if( $result = $this->spinPost($postInfo['ID'], $content, $this->option['wpspin_spin_quality'], $this->option['wpspin_excluded_words'], $title) ) {
                    $content = $result;
                }
            } else {
                preg_match_all("|{(.*)}|U",$content,$out);
                foreach( $out[1] as $synonyms ) {
                    $synonym = explode( "|", $synonyms );
                    $randSynonym = $synonym[0];
                    $content = str_replace( '{'.$synonyms.'}', $randSynonym, $content );
                }
            }
        }
        
        return $content;
    }
    
    function spinSchedule() {
        $debug = 0;
        
        if( !$session = $this->checkAuth() ) return 0;
        $this->mySession = $session;
        
        $nowTimestamp = time();
        
        
        $this->getOptions();
        $this->wpDB();
        
        if( $this->option['wpspin_autospin'] == 1 AND $this->option['wpspin_auto_options'] == 3 ) {
        /*
        $wpspin_time_count - кол-во единиц времени
        $wpspin_time_type  - тип времени (1-час,2-день,3-неделя,4-месяц)
        $wpspin_spin_count - кол-во раз запуска
        $wpspin_publish    - действие (1-переписать статью,2-создать черновик статьи)
        */	
            
            if( $this->option['wpspin_spin_count'] ) {
                $countHours = $this->countHours( $this->option['wpspin_time_type'], $this->option['wpspin_time_count'] );
                //$myAlarm = $this->option['my_alarm'];
                update_option('my_alarm', $countHours );
                $myAlarm = $countHours;
                
                if( !$myAlarm ) {
                    update_option('my_alarm', $countHours );
                    $myAlarm = $countHours;
                    
                }
                if( $myAlarm > 1 ) {
                    $myAlarm--;
                    echo $this->option['wpspin_time_count'];
                    update_option('my_alarm', $myAlarm );
                } else if( $myAlarm == 1 ) {
                    $this->option['wpspin_spin_count']--;
                    if( $this->option['wpspin_spin_count'] ) {
                        update_option('my_alarm', $countHours );
                        update_option('wpspin_spin_count', $this->option['wpspin_spin_count'] );
                    } else {
                        update_option('my_alarm', 0 );
                        update_option('wpspin_spin_count', 0 );
                    }
                    
                    $allPosts = $this->myGetPosts();
                    $allPages = $this->myGetPages();
                    //print_r( $allPosts ); exit;
                    
                    if( $debug ) { 
                        $fp = fopen( 'logs_spin_schedule.txt', 'a' ); 
                        fwrite( $fp, "\n\n[~] Schedule spin: ".count($allPosts)." and ".count($allPages)." pages\n" );
                    }
                    
                    foreach( $allPosts as $post ) $this->workPost( $post );
                    
                    foreach( $allPages as $page ) $this->workPost( $page );
                    
                    if( $debug ) fclose( $fp );
                }
            }
        }
        
        if($rows = $this->wpdb->get_results("SELECT * FROM `".$this->table."` WHERE `auto_options`='3' AND `spin_count`<>'0' AND `status`='1'", ARRAY_A)) {
            if( $debug ) { 
                $fp = fopen( 'logs_spin_schedule.txt', 'a' ); 
                fwrite( $fp, "\n\n[~] Schedule spin: ".count($rows)." (individual)\n" );
            }
            
            foreach( $rows as $row ) {
                $wpspin_time_count = $row['time_count'];
                $wpspin_time_type  = $row['time_type'];
                $wpspin_spin_count = $row['spin_count'];
                $wpspin_publish    = $row['spin_publish'];
                $myAlarm           = $row['alarm'];
                $myID              = $row['id'];
                $goNow             = FALSE;
                
                if( $wpspin_spin_count ) {
                    if( $wpspin_time_type == 5 ) {
                        $now = date("d/m/Y");
                        $dates = explode(",", $myAlarm);
                        $wpspin_spin_count = count( $dates );
                        foreach( $dates as $date ) {
                            if( $date == $now ) {
                                $goNow = TRUE;
                                break;
                            }
                        }
                        if( !$goNow ) continue;
                    } else $countHours = $this->countHours( $wpspin_time_type, $wpspin_time_count );
                    
                    if( !$myAlarm ) {
                        $this->wpdb->query("UPDATE `".$this->table."` SET `alarm`='$countHours' WHERE `id`='$myID'");
                        $myAlarm = $countHours;
                    }
                    if( $myAlarm > 1 AND $wpspin_time_type != 5 ) {
                        $myAlarm--;
                        $this->wpdb->query("UPDATE `".$this->table."` SET `alarm`='$myAlarm' WHERE `id`='$myID'");
                    } else if( $myAlarm == 1 OR $wpspin_time_type == 5 ) {
                        $wpspin_spin_count--;
                        if( $wpspin_spin_count ) {
                            if( $wpspin_time_type == 5 ) {
                                $myAlarm = str_replace( "$now,", "", $myAlarm );
                                $myAlarm = str_replace( "$now", "", $myAlarm );
                                $this->wpdb->query("UPDATE `".$this->table."` SET `alarm`='$myAlarm',`spin_count`='$wpspin_spin_count' WHERE `id`='$myID'");
                            }
                            else $this->wpdb->query("UPDATE `".$this->table."` SET `alarm`='$countHours',`spin_count`='$wpspin_spin_count' WHERE `id`='$myID'");
                        } else {
                            $this->wpdb->query("UPDATE `".$this->table."` SET `alarm`='0',`spin_count`='0' WHERE `id`='$myID'");
                        }
                        
                        $postInfo = $this->wpdb->get_row("SELECT `post_content`,`post_title` FROM `".$this->table_posts."` WHERE `ID`='$myID'", ARRAY_A);
                        $title = ( $row['spin_title'] == 1 ) ? $postInfo['post_title'] : FALSE;
                        $identify = ( $row['mode'] == 'identify' OR $row['mode'] == 'manual' ) ? $row['content'] : FALSE;
                        
                        $postContent = $postInfo['post_content'];
                        if( $row['mode'] == 'identify' ) {
                            preg_match_all("|{(.*)}|U",$postContent,$out);
                            foreach( $out[1] as $synonyms ) {
                                $wordsNew = $synonyms;
                                $synonym = explode( "|", $synonyms );
                                $randSynonym  = $synonym[rand(0,(count($synonym)-1))];
                                $firstSynonym = $synonym[0];
                                foreach( $synonym as $s ) {
                                    if( $s == $firstSynonym )     $wordsNew = str_replace( $firstSynonym, "%rand%", $wordsNew );
                                    else if( $s == $randSynonym ) $wordsNew = str_replace( $randSynonym, $firstSynonym, $wordsNew );
                                }
                                $wordsNew = str_replace( "%rand%", $randSynonym, $wordsNew );
                                $identify = str_replace( $synonyms, $wordsNew, $identify );
                                $postContent = str_replace( $synonyms, $wordsNew, $postContent );
                            }
                            if(count($out[1])) {
                                $this->wpdb->query("UPDATE `".$this->table."` SET `content`='$identify' WHERE `id`='$myID'");
                                //$this->wpdb->query("UPDATE `".$this->table_posts."` SET `post_content`='!".trim($postContent)."' WHERE `ID`='$myID'");
                                wp_update_post( array('ID'=>$myID, 'post_content'=>addslashes(trim($postContent)) ) );
                            }
                        } else if( $row['mode'] == 'replace' ) {
                            preg_match_all("|{(.*)}|U",$postContent,$out);
                            foreach( $out[1] as $synonyms ) {
                                $wordsNew = $synonyms;
                                $synonym = explode( "|", $synonyms );
                                $randSynonym  = $synonym[rand(0,(count($synonym)-1))];
                                $firstSynonym = $synonym[0];
                                foreach( $synonym as $s ) {
                                    if( $s == $firstSynonym )     $wordsNew = str_replace( $firstSynonym, "%rand%", $wordsNew );
                                    else if( $s == $randSynonym ) $wordsNew = str_replace( $randSynonym, $firstSynonym, $wordsNew );
                                }
                                $wordsNew = str_replace( "%rand%", $randSynonym, $wordsNew );
                                $postContent = str_replace( $synonyms, $wordsNew, $postContent );
                            }
                            if(count($out[1])) {
                                $this->wpdb->query("UPDATE `".$this->table."` SET `content`='$identify' WHERE `id`='$myID'");
                                wp_update_post( array('ID'=>$myID, 'post_content'=>addslashes(trim($postContent)) ) );
                            }
                        }
                        
                        /*if( $wpspin_publish == 1 ) {
                            if( $this->spinPost( $myID, $postInfo['post_content'], $row['quality'], $row['excluded'], $title, $identify ) ) {
                                if( $debug ) fwrite( $fp, "[".date('Y-m-d H:i:s')."] spin post #$myID - DONE\n" );
                            } else {
                                if( $debug ) fwrite( $fp, "[".date('Y-m-d H:i:s')."] spin post #$myID - FAILED\n" );
                            }
                        } else if( $wpspin_publish == 2 ) {
                            if( $this->spinAndDraft( $myID, $postInfo['post_content'], $row['quality'], $row['excluded'], $title, $identify ) ) {
                                if( $debug ) fwrite( $fp, "[".date('Y-m-d H:i:s')."] spin draft post #$myID - DONE\n" );
                            } else {
                                if( $debug ) fwrite( $fp, "[".date('Y-m-d H:i:s')."] spin draft post #$myID - FAILED\n" );
                            }
                        }*/
                    }
                }
            }
            if( $debug ) { fclose($fp); }
        }
    }
    
    function workPost( $post ) {
        $debug = 0;
        if( $this->wpdb->get_var( "SELECT COUNT(*) FROM `".$this->table."` WHERE `id`='".$post->ID."'" ) ) return 0;
        $title = ( $this->option['wpspin_spin_title'] == 1 ) ? $post->post_title : FALSE;
        
        if( $this->option['wpspin_publish'] == 1 ) {
            if( $this->spinPost( $post->ID, $post->post_content, $this->option['wpspin_spin_quality'], $this->option['wpspin_excluded_words'], $title ) ) {
                if( $debug ) fwrite( $fp, "[".date('Y-m-d H:i:s')."] spin post #".$post->ID." - DONE\n" );
            } else {
                if( $debug ) fwrite( $fp, "[".date('Y-m-d H:i:s')."] spin post #".$post->ID." - FAILED\n" );
                return 0;
            }
        } else {
            if( $this->spinAndDraft( $post->ID, $post->post_content, $this->option['wpspin_spin_quality'], $this->option['wpspin_excluded_words'], $title ) ) {
                if( $debug ) fwrite( $fp, "[".date('Y-m-d H:i:s')."] spin post #".$post->ID." - DONE\n" );
            } else {
                if( $debug ) fwrite( $fp, "[".date('Y-m-d H:i:s')."] spin post #".$post->ID." - FAILED\n" );
                return 0;
            }
        }
        
        return 1;
    }
    
    function myGetPosts() {
        $this->wpDB();
        $sql = "SELECT `ID`, `post_content`, `post_title` FROM `".$this->table_posts."` WHERE `post_status`='publish' AND `post_type`='post'"; 
        if( $objects = $this->wpdb->get_results( $sql, OBJECT_K ) ) return $objects;
        else return 0;
    }
    
    function myGetPages() {
        $this->wpDB();
        $sql = "SELECT `ID`, `post_content`, `post_title` FROM `".$this->table_posts."` WHERE `post_status`='publish' AND `post_type`='page'"; 
        if( $objects = $this->wpdb->get_results( $sql, OBJECT_K ) ) return $objects;
        else return 0;
    }
    
    function spinPost( $postID, $content, $quality, $excluded, $spin_title, $identify = FALSE ) {
    
        $debug = 0;
        //$content = stripslashes($content); $identify = stripslashes($identify);
        //$content = addslashes($content); $identify = addslashes($identify);
        //echo "[~] Spin $postID <br> $quality;$excluded;".$this->mySession."<br>";

        if( !$this->mySession ) {
            if( $session = $this->checkAuth() ) {
                $this->mySession = $session;
            } else {
                if( $debug ) echo "<br>Information is incorrect [1]<br>";
                return 0;
            }
        }
        
        if( $identify ) {
            $success = $this->mySpin->spinText( $identify, 'replaceEveryonesFavorites', '1', $quality, $excluded, $this->mySession );
            //echo "Text: ".stripslashes(trim($content))."<br>Old: ".stripslashes(trim($identify))."<br>New: ".stripslashes(trim($success))."<br><br>";
            $content = str_replace( stripslashes(trim($identify)), stripslashes(trim($success)), stripslashes(trim($content)) );
            
            $sql = "UPDATE `".$this->table."` SET `content`='".addslashes($success)."' WHERE `mode`='identify' AND `id`='$postID'";
            $this->wpdb->query($sql);
        } else {
            $success = $this->mySpin->spinText( $content, 'replaceEveryonesFavorites', '1', $quality, $excluded, $this->mySession );
            if( $debug ) echo "Old: $content<br>New: $success<br><br>";
            $content = stripslashes(trim($success));
        }
        
        if( !$success ) {
            if( $debug ) echo "<br>Information is incorrect [2][".$this->mySession."]<br>";
            return 0;
        } else {
            if( $debug ) echo "<br>success spin<br>";
            
            if( $spin_title ) {
                if( $title = $this->mySpin->spinText( strip_tags(trim($spin_title)), 'replaceEveryonesFavorites', '1', $quality, $excluded, $this->mySession) ) {
                    wp_update_post( array('ID'=>$postID, 'post_content'=>addslashes($content), 'post_title'=>$title ) );
                } else {
                    wp_update_post( array('ID'=>$postID, 'post_content'=>addslashes($content) ) );
                }
            } else {
                wp_update_post( array('ID'=>$postID, 'post_content'=>addslashes($content) ) );
            }
        }
        
        return $content;
    }
    
    function spinAndDraft( $postID, $content, $quality, $excluded, $spin_title, $identify = FALSE ) {
    
        $debug = 0;
        //if( $debug ) echo "[~] Spin $postID <br> $quality;$excluded;$identify;".$this->mySession."<br>";

        if( !$this->mySession ) {
            if( $debug ) echo "<br>Information is incorrect [1]<br>";
            return 0;
        }
        
        if( $identify ) {
            $success = $this->mySpin->spinText( trim($identify), 'replaceEveryonesFavorites', '1', $quality, $excluded, $this->mySession );
            $content = str_replace( stripslashes(trim($identify)), stripslashes(trim($success)), stripslashes(trim($content)) );
            $sql = "UPDATE `".$this->table."` SET `content`='".addslashes($success)."' WHERE `mode`='identify' AND `id`='$postID'";
            $this->wpdb->query($sql);
        } else {
            $success = $this->mySpin->spinText( trim($content), 'replaceEveryonesFavorites', '1', $quality, $excluded, $this->mySession );
            $content = $success;
        }
        
        if( !$success ) {
            if( $debug ) echo "<br>Information is incorrect [2][".$this->mySession."]<br>";
            return 0;
        } else {
            if( $debug ) echo "<br>success spin<br>";
            
            if( $spin_title ) {
                if( $title = $this->mySpin->spinText( strip_tags(trim($spin_title)), 'replaceEveryonesFavorites', '1', $quality, $excluded, $this->mySession) ) {
                    //wp_update_post( array('ID'=>$postID, 'post_content'=>$content, 'post_title'=>$title ) );
                    if( $draftID = $this->wpdb->get_var("SELECT `ID` FROM `".$this->table_posts."` WHERE `ID`='$postID' AND `post_status`='draft' LIMIT 1") ) {
                        $sql = "UPDATE `".$this->table_posts."` SET `post_content`='".addslashes($content)."', `post_title`='[spin] $title', `post_modified`='".date("Y-m-d H:i:s")."' WHERE `ID`='$postID' AND `post_status`='draft'";
                        $newPostID = $draftID;
                    } else {
                        $sql = "INSERT INTO `".$this->table_posts."` 
                        (`post_author`, `post_date`, `post_date_gmt`, `post_content`, `post_title`, `post_excerpt`, `post_status`, `comment_status`, `ping_status`, `post_password`, `post_name`, `to_ping`, `pinged`, `post_modified`, `post_modified_gmt`, `post_content_filtered`, `post_parent`, `guid`, `menu_order`, `post_type`, `post_mime_type`, `comment_count`) 
                        SELECT 
                        `post_author`, `post_date`, `post_date_gmt`, '".addslashes($content)."', '[spin] $title', `post_excerpt`, 'draft', `comment_status`, `ping_status`, `post_password`, `post_name`, `to_ping`, `pinged`, `post_modified`, `post_modified_gmt`, `post_content_filtered`, '$postID', `guid`, `menu_order`, `post_type`, `post_mime_type`, `comment_count`
                        FROM `".$this->table_posts."` WHERE `ID`='$postID'";
                    }
                    
                } else {
                    //wp_update_post( array('ID'=>$postID, 'post_content'=>$content ) );
                    if( $draftID = $this->wpdb->get_var("SELECT `ID` FROM `".$this->table_posts."` WHERE `ID`='$postID' AND `post_status`='draft' LIMIT 1") ) {
                        $sql = "UPDATE `".$this->table_posts."` SET `post_content`='".addslashes($content)."', `post_title`='[spin] $title', `post_modified`='".date("Y-m-d H:i:s")."' WHERE `ID`='$postID' AND `post_status`='draft'";
                        $newPostID = $draftID;
                    } else {
                        $sql = "INSERT INTO `".$this->table_posts."` 
                        (`post_author`, `post_date`, `post_date_gmt`, `post_content`, `post_title`, `post_excerpt`, `post_status`, `comment_status`, `ping_status`, `post_password`, `post_name`, `to_ping`, `pinged`, `post_modified`, `post_modified_gmt`, `post_content_filtered`, `post_parent`, `guid`, `menu_order`, `post_type`, `post_mime_type`, `comment_count`) 
                        SELECT 
                        `post_author`, `post_date`, `post_date_gmt`, '".addslashes($content)."', CONCAT('[spin] ',`post_title`), `post_excerpt`, 'draft', `comment_status`, `ping_status`, `post_password`, `post_name`, `to_ping`, `pinged`, `post_modified`, `post_modified_gmt`, `post_content_filtered`, '$postID', `guid`, `menu_order`, `post_type`, `post_mime_type`, `comment_count`
                        FROM `".$this->table_posts."` WHERE `ID`='$postID'";
                    }
                }
            } else {
                //wp_update_post( array('ID'=>$postID, 'post_content'=>$content ) );
                if( $draftID = $this->wpdb->get_var("SELECT `ID` FROM `".$this->table_posts."` WHERE `ID`='$postID' AND `post_status`='draft' LIMIT 1") ) {
                    $sql = "UPDATE `".$this->table_posts."` SET `post_content`='".addslashes($content)."', `post_title`='[spin] $title', `post_modified`='".date("Y-m-d H:i:s")."' WHERE `ID`='$postID' AND `post_status`='draft'";
                    $newPostID = $draftID;
                } else {
                    $sql = "INSERT INTO `".$this->table_posts."` 
                    (`post_author`, `post_date`, `post_date_gmt`, `post_content`, `post_title`, `post_excerpt`, `post_status`, `comment_status`, `ping_status`, `post_password`, `post_name`, `to_ping`, `pinged`, `post_modified`, `post_modified_gmt`, `post_content_filtered`, `post_parent`, `guid`, `menu_order`, `post_type`, `post_mime_type`, `comment_count`) 
                    SELECT 
                    `post_author`, `post_date`, `post_date_gmt`, '".addslashes($content)."', CONCAT('[spin] ',`post_title`), `post_excerpt`, 'draft', `comment_status`, `ping_status`, `post_password`, `post_name`, `to_ping`, `pinged`, `post_modified`, `post_modified_gmt`, `post_content_filtered`, '$postID', `guid`, `menu_order`, `post_type`, `post_mime_type`, `comment_count`
                    FROM `".$this->table_posts."` WHERE `ID`='$postID'";
                }
            }
            //echo "$sql";
            $this->wpdb->query($sql);
            if( !$newPostID ) {
                $newPostID = $this->wpdb->get_var("SELECT `ID` FROM `".$this->table_posts."` WHERE `post_parent`='$postID' ORDER BY `ID` DESC LIMIT 1");
                $sql = "UPDATE `".$this->table."` SET `id`='$newPostID' WHERE `id`='$postID'";
                //echo "<br>New ID: $newPostID";
                $this->wpdb->query($sql);
            }
        }
        
        return $content;
    }
    
    function deletePost( $postID ) {
        $this->wpDB();
        $this->wpdb->query("DELETE FROM `".$this->table."` WHERE `id`='$postID'");
        return 1;
    }
    
    function headHook() {
        $path = pathinfo( $_SERVER['SCRIPT_NAME'] );
        if( $path['basename'] != 'post-new.php' AND $path['basename'] != 'post.php' ) return 0;
        include_once( dirname(__FILE__) . '/includes/headhook.php' );
    }
    
    function checkAuth( $login = FALSE, $pass = FALSE ) {
        if( !$login ) $login = get_option('wpspin_login');
        if( !$pass )  $pass  = get_option('wpspin_pass');

        include_once( dirname(__FILE__) . '/class.bestspin.php' );
        $this->mySpin = new Spin( 'http://thebestspinner.com/api.php', $login, $pass );
        if( $session = $this->mySpin->auth() ) return $session;
        else {
            //echo $this->mySpin->getError();
            return 0;
        }
    }
    
    function countHours($type, $count ) {

        switch( $type ) {
            case '1':
                $return = $count;
                break;
            case '2':
                $return = 24*$count;
                break;
            case '3':
                $return = 7*24*$count;
                break;
            case '4':
                $return = 30*24*$count;
                break;
            default:
                $return = 0;
        }
    
        return $return;
    }
}

$WPSpin = new WPspin();

?>