<?php
ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);
//ini_set('max_execution_time', '3');
####################################################################################################
################################## WBots Wordpress Client ##########################################
####################################################################################################
#  /////////  ///////////  /////////--------------                                                   
#  yyyyyyyyy  yyyyyyyyyyy  yyyyyyyyy++++++++++++++++                           -++                   
#  ::syyyy::  :/yyyyyyy::  :yyyyy:::...++++.....+++++                        -++++                   
#     yyyy+    yyyyyyyy.   .yyyy-      ++++     -++++       `::::::::``    ::+++++::    `::::::::::: 
#     -yyyy   .yyyysyyyy   yyyys       ++++```::++++/     `:+++++++++++:   +++++++++   :++++++++++++ 
#      yyyyo  yyyy- yyyy. .yyyy        +++++++++++++`    :++++::..::++++:  ..+++++..   ++++....:++++ 
#      .yyyy-oyyyo  oyyyy yyyy.        ++++:::::+++++.   ++++:      `++++:   +++++     ++++:::::---` 
#       +yyyyyyyy    yyyysyyyy         ++++     `:++++   ++++        +++++   +++++     `:++++++++++/ 
#        yyyyyyy+    .yyyyyyy.         ++++      /++++   ++++/.     /++++`   +++++     //++``:::++++ 
#        +yyyyyy      yyyyyy+       ...++++....//++++-   -+++++/..//++++-    +++++..   ++++/.../++++ 
#         yyyyy`      `yyyyy        +++++++++++++++-       -++++++++++-       ++++++   ++++++++++++- 
#          ////        ////         ------------              ------           -----   ----------    
####################################################################################################
####################################################################################################


#Bağlantı güvenliği için otomatik oluşturulan anahtarlar.
$clientKey = "851241ff2c7f988370697f606f56baf9675e0bc9627d38e8b4850e230b908994";
$wbotsKey  = "346309a67c3592f6d207d2f804742ceac68831bb24f0ee15fc95cd9d7b7bdd97";

#WBots'un gönderdiği içerikler hangi kullanıcı id'sine aktarılacak?
$WPuserID  = 1;

# Wordpress Klasörü farklı bir dizindeyse "/dizin/" şeklinde değiştirin.
$dizin     = "/";

# Zaman Dilimi
$time      = "0"; //"+3" İstanbul İçin


####################################################################################################
########################## WBots Wordpress Client Ayarlar Sonu #####################################
####################################################################################################
require '../bootstrap/autoload.php';
use App\Ayarlar;
use App\HaberKategoriler;
use App\Haberler;
use Illuminate\Http\Request;
use Image;
use Illuminate\Support\Facades\Cache;


$directory = __DIR__ .$dizin;
$bot = new wbotsApi($clientKey,$wbotsKey,$directory);


if(isset($_REQUEST["ckey"])) {
    if($_REQUEST["ckey"]==$clientKey)       $bot->logOn(1);
    
    
    if(isset($_REQUEST["validation"])) {
        $step = (int) $_REQUEST["validation"];
        $bot->validation($step);
    } elseif(isset($_REQUEST["sync"])) {
        $operation = (int) $_REQUEST["sync"];
        $bot->sync($operation);
    } elseif(isset($_REQUEST["clientVersion"])) {
        $bot->clientVersion();
    } elseif(isset($_REQUEST["WPSignal"])){
        $type = (int) $_REQUEST["WPSignal"];
        
        $bot->wbotsGetContents($type);
    }
    
    
    
    
    
} else {
    $bot->errorMSG(0);
}

class wbotsApi {
    private     $clientVersion  = "0.75";
    private     $wbotsURL1      = "https://wbots.net/validation";
    private     $wbotsURL2      = "https://wbots.net/sync";
    private     $clientKey;
    private     $wbotsKey;
    private     $directory;
    public      $login          =0;
    
    
    function __construct($clientKey, $wbotsKey,$directory) {
        if(strlen($clientKey)!=64 or strlen($wbotsKey)!=64) $this->errorMSG(0);
        
        $this->clientKey    = $clientKey;
        $this->wbotsKey     = $wbotsKey;
        
        if(substr($directory, -1)!="/") $this->errorMSG(1);
        $this->directory    = $directory;
    }
    
    private function logOnCtrl(){
        if($this->login!=1) $this->errorMSG(0);
    }
    
    public function logOn($x) {
        if($x==1){
            $app = require_once '../bootstrap/app.php';
            $kernel = $app->make('Illuminate\Contracts\Http\Kernel');
            $kernel->handle(Request::capture());
            $this->login = 1;
        }
    }

    public function clientVersion () {
        if($this->login!=1) $this->errorMSG(0);
        $this->sendJSON(array( "clientVersion"=>$this->clientVersion));
    }
    
    public function validation($step) {
        if($this->login!=1) $this->errorMSG(0);
        switch($step) {
            case 1:
                $this->sendJSON(array("validation"=>1));
                break;
            case 2:
                $this->sendJSON(array(  "validation"=>2,
                                        "systemVer" =>1,
                                        "clientVer" =>$this->clientVersion));
                break;
                
        }
        
    }
    public function sync($operation) {
        if($this->login!=1) $this->errorMSG(0);
        switch($operation) {
            case 1:
                $tmp = array();
                $rows = HaberKategoriler::get();
                foreach( $rows as $row ){
                    $tmp[] = array ("cat_ID"    =>$row->id,
                                    "cat_name"  =>$row->baslik);
                    
                }
                $categories = $tmp;
                $this->sendJSON(array(  "sync"=>1,
                                        "values" =>$categories),2);
                
                break;
            case 2:
                $lastPost = Haberler::orderBy('id', 'desc')->first();
                if(!$lastPost) break;
                
                $lastPost = json_decode(json_encode($lastPost), true);
                
                $ignore     = array("id","kategori","tarih","baslik","baslik2","slug","metadesc","metakey","detay","resim","mansetresim","yatayresim"
                                    ,"ozellink","ozelurl","iliskilihaber","makale","galeri","video","anket","kontrol","hit","durum","editor");
                $tmp        = array();
                foreach($lastPost as $key => $val) {
                    
                    if(is_numeric($key)) continue;
                    if(in_array($key,$ignore)) continue;
                    if(is_null($val)) $val = "";
                    $tmp[$key]  =  array($val);
                }

                $meta       = array("id"    => $lastPost['id'],
                                    "title" => $lastPost['baslik'],
                                    "meta"  => $tmp);
                
                $return = $this->sendJSON(array(  "sync"=>2,
                                        "values" =>$meta),2);
                echo "<pre>"; 
                print_r($return);
                echo "</pre>";
                break;
        }
    }
    
    public function wbotsGetContents($type){
        $json = $this->sendJSON(array( "transfer"=>$type),2);
        $array= json_decode($json,true);
        $completed = array();

        if($array["code"]==1){
            $posts = $array["data"];
            foreach($posts as $post){
                $info = $this->post_insert($post);
                if($info!==false){
                    $completed[$post["id"]] = $info;
                }
            }
        }
        if(count($completed)>0){
            $this->sendJSON(array( "transferCompleted"=>$completed),2);
        }
    }
    
    private function post_insert($post) {
        global $wpdb;
        global $WPuserID;
        global $time;
        
        
        
        $ayarlar        = Ayarlar::select("siteadresi","mansety","buyukmansety","yataymansety")->first();

        $siteURL        = $ayarlar->siteadresi;
        
        $title          = $post["title"];
        $image          = $post["photo"];
        $excerpt        = $post["excerpt"];
        $content        = $post["content"];
        $categories     = $post["category"];
        $postType       = "post";  
        $postStatus     = ($post["post_status"]=="draft")? 0 : 1;
        $sfields        = $post["sfields"];
        
        $cc1 = strip_tags($content);
        
        $findPosts = Haberler::where('baslik',$title)->get();
        $findPosts = json_decode(json_encode($findPosts), true);
        
        foreach($findPosts as $findPost) { 
            $cc2 = strip_tags($findPost['detay']);
            
            if($cc1==$cc2){
               $permalink = trim($siteURL,"/")."/haber/".$findPost['slug']."-".$findPost['id'];
               return $permalink;
            }
        }
        
        $timeStamp = date("Y-m-d H:i:s", strtotime($time." hours"));
        
        $category = intval($categories[0]);
        if($category==0) $category = 1;
        $slug               = $this->generateSeoURL($title);
        
        
        $anamanset          = isset($sfields['anamanset']) ? $sfields['anamanset'] : 1;
        $buyukmanset        = isset($sfields['buyukmanset']) ? $sfields['buyukmanset'] : 0;
        $spot               = isset($sfields['spot']) ? $sfields['spot'] : 1;
        $yataymanset        = isset($sfields['yataymanset']) ? $sfields['yataymanset'] : 1;
        $embed              = isset($sfields['embed']) ? $sfields['embed'] : "";
        $renk               = isset($sfields['renk']) ? $sfields['renk'] : 0;
        $sehir              = isset($sfields['sehir']) ? $sfields['sehir'] : 0;
        $kaynak             = isset($sfields['kaynak']) ? $sfields['kaynak'] : 0;
        $mansetbaslik       = isset($sfields['mansetbaslik']) ? $sfields['mansetbaslik'] : 1;
        $sondakika          = isset($sfields['sondakika']) ? $sfields['sondakika'] : 1;
        $flashaber          = isset($sfields['flashaber']) ? $sfields['flashaber'] : 1;
        $durum              = 0;
        $yorum              = isset($sfields['yorum']) ? $sfields['yorum'] : 1;
        $sitemap            = isset($sfields['sitemap']) ? $sfields['sitemap'] : 0;
        $normal_boyutlandirma       = isset($sfields['normal_boyutlandirma']) ? $sfields['normal_boyutlandirma'] : 1;
        $buyukmanset_boyutlandirma  = isset($sfields['buyukmanset_boyutlandirma']) ? $sfields['buyukmanset_boyutlandirma'] : 1;
        $yataymanset_boyutlandirma  = isset($sfields['yataymanset_boyutlandirma']) ? $sfields['yataymanset_boyutlandirma'] : 1;
        
        $insert = Haberler::create([
            'kategori'  => $category,
            'tarih'     => $timeStamp,
            'baslik'    => $title,
            'slug'      => $slug,
            'anamanset'	    => $anamanset,
            'buyukmanset'	=> $buyukmanset,
            'spot'	        => $spot,
            'yataymanset'	=> $yataymanset,
            'metadesc'      => $excerpt,
            'metakey'       => $post["tags"],
            'detay'         => $content,
            'embed'         => $embed,
            'renk'          => $renk,
            'sehir'         => $sehir,
            'kaynak'        => $kaynak,
            'editor'        => $WPuserID,
            'mansetbaslik'  => $mansetbaslik,
            'sondakika'     => $sondakika,
            'flashaber'     => $flashaber,
            'durum'         => $durum,
            'yorum'         => $yorum,
            'sitemap'       => $sitemap,
            'normal_boyutlandirma'      => $normal_boyutlandirma,
            'buyukmanset_boyutlandirma' => $buyukmanset_boyutlandirma,
            'yataymanset_boyutlandirma' => $yataymanset_boyutlandirma
            
        ]);
        
        
        
        if ( $insert ){
            $post_id = $insert->id;
        }
         
         if($post_id){
            $resimx =  $this->Generate_Featured_Image( $image, $post_id, $title, 1);
            
            //manşet boyutlandırma
            $img = Image::make("images/haberler/".$resimx['url']);
            $img->resize(640, $ayarlar->mansety);
            $img->save("images/haberler/".$resimx['url'],100);
            $dir = 'images/tn/'.date('Y/m');
            if(!is_dir($dir)) mkdir($dir, 0755, true);
            $img->fit(320, 180)->save('images/tn/'.$resimx['url']);
            
            
            if($post["in_upload"]==1){
                if(isset($post["in_images"])){
                    $in_images = $post["in_images"];
                    for($i=0;$i<count($in_images);$i++){
                        $attach_img = trim($siteURL,"/")."/images/haberler/".$this->Generate_Featured_Image( $in_images[$i], $post_id, $title." ".$i, 0);
                        if(!$attach_img) continue;
                        $content    = str_replace($in_images[$i].'"',$attach_img.'"',$content);   
                    }
                }
                
                if(isset($post["in_files"])){
                    $in_files = $post["in_files"];
                    for($i=0;$i<count($in_files);$i++){
                        $attach_file = trim($siteURL,"/")."/images/haberler/".$this->wbotsAddFileToPost($in_files[$i]['url'],$in_files[$i]['ext'],$post_id,$title." ".$i);
                        if(!$attach_file) continue;
                        $content    = str_replace($in_files[$i]['url'].'"',$attach_file.'"',$content);   
                    }
                }
                $content = preg_replace("#<img[^>]+wbots\.net/api[^>]+>#si","",$content);
                $postx = array('detay'=> $content, 'resim'=>$resimx['url'], 'durum' => $postStatus );
                Haberler::where('id',$post_id)->update($postx);
            
            } else {
                $postx = array('resim'=>$resimx['url'], 'durum' => $postStatus );
                Haberler::where('id',$post_id)->update($postx);
            }
            //Cache::flush('cokOkunanlar');
            //Cache::flush('sondakika');
            $permalink = trim($siteURL,"/")."/haber/".$slug."-".$post_id;
            return $permalink;
         } else{
            return false;
         }
       
    }
    private function wbotsAddFileToPost($url,$extension,$post_id,$title){
        $blackList  = array("exe","scr","vb","script","hta","bat","jar","js","com","class","ocx","php","asp","aspx","py","rb","inc");
        if($extension==""){
            $filename   = basename($url);
            $extension  = pathinfo($filename);
            $extension  = $extension["extension"];
        }
        
        if (in_array($extension, $blackList)) return false;
        
        $datax      = $this->wbotsDownloadFile($url);
        $data       = $datax['data'];
        $code       = $datax['code'];
        if($code!=200) return false;
        
        $filename   = $this->generateSeoURL($title,32)."-".$this->RandomString(7).".".$extension;
        $return = $this->wbotsInsertAttachment($filename,$data,$post_id);
        if($post_id!=0) {
            return $return['url'];
        } else {
            return $return;
        }
        
    }
    private function Generate_Featured_Image($image_url, $post_id, $title, $setThumb){
        $datax      = $this->wbotsDownloadFile($image_url);
        $image_data = $datax['data'];
        $code       = $datax['code'];
        
        if($code!=200) return false;
        
        $filename   = basename($image_url);
        $extension  = pathinfo($filename);
        $extension  = $extension["extension"];
        $whitelist = array("webp","jpg","jpeg","gif","png"); 
        if (!(in_array($extension, $whitelist))) {
            $extension = "jpg";
        }
        
        $filename   = $this->generateSeoURL($title,32)."-".$this->RandomString(7).".".$extension;
        $return = $this->wbotsInsertAttachment($filename,$image_data,$post_id);
        if($post_id!=0) {
            if($setThumb==1) {
                //$res2= set_post_thumbnail( $post_id, $return['attach_id'] );
                return $return;
            }
            
            return $return['url'];
        } else {
            return $return;
        }
        
        
    }
    
    private function wbotsDownloadFile($url){
        $ch = curl_init();  
        curl_setopt($ch, CURLOPT_URL, $url);  
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
        curl_setopt($ch, CURLOPT_REFERER, $url);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);  
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);  
        curl_setopt($ch, CURLOPT_TIMEOUT, 180);  
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);  
        curl_setopt($ch, CURLOPT_ENCODING, "");  
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);  
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);  # required for https urls  
        curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
        $data = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return array('code'=>$code,'data'=>$data);
    }
    private function wbotsInsertAttachment($filename,$data,$post_id){
        $dir = $this->directory;
        $dir .= "images/";
        if(!is_dir($dir)) mkdir($dir);
        $dir .= "haberler/";
        if(!is_dir($dir)) mkdir($dir);
        
        
        if(!is_dir($dir)) mkdir($dir);
        $dir .= date("Y")."/";
        if(!is_dir($dir)) mkdir($dir);
        $dir .=  date("m")."/";
        if(!is_dir($dir)) mkdir($dir);
        if (!file_exists($dir.'/index.html')) touch($dir.'/index.html');
        
        $file = $dir.$filename;
        //$url  = trim($this->siteURL,"/")."/".str_replace($this->directory,"",$file);
        $url  = date("Y/m")."/".$filename;
        
        if(file_put_contents($file, $data) === FALSE) $this->errorMSG(3);
        
        
        if($post_id!=0){
            return array('attach_id' => 0, 'url' => $url, 'dir' => $file);
        }
        
        return $url;
        
    }

    private function generateSeoURL($string, $wordLimit = 0){
        $separator = "-";
        if($wordLimit != 0){
            $wordArr = explode(" ", $string);
            $string = implode(" ", array_slice($wordArr, 0, $wordLimit));
        }
        $quoteSeparator = preg_quote($separator, "#");
        $trans = array(
            "&.+?;"                    => "",
            "[^\w\d _-]"            => "",
            "\s+"                    => $separator,
            "(".$quoteSeparator.")+"=> $separator
        );
        $string = strip_tags($string);
        foreach ($trans as $key => $val){
            $string = preg_replace("#".$key."#i".("UTF8_ENABLED" ? "u" : ""), $val, $string);
        }
        
        $tr     = array("ş","Ş","ı","I","İ","ğ","Ğ","ü","Ü","ö","Ö","Ç","ç");
        $eng    = array("s","s","i","i","i","g","g","u","u","o","o","c","c");
        $string = str_replace($tr,$eng,$string);

        $string = strtolower($string);
        $string = preg_replace("/[^A-Za-z0-9]/"," ",$string); 
        $string = preg_replace("/\s+/"," ",$string);
        $string = str_replace(" ","-",$string);
        return trim(trim($string, $separator));
    }
    private function RandomString($length = 32) {
        $randstr = "";
        srand((double) microtime(TRUE) * 1000000);
        //our array add all letters and numbers if you wish
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "p",
            "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", 
            "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
    
        for ($rand = 0; $rand <= $length; $rand++) {
            $random = rand(0, count($chars) - 1);
            $randstr .= $chars[$random];
        }
        return $randstr;
    }
    
    public function errorMSG($x) {
        
        switch($x){
            case 0:
                http_response_code(501);
                $msg = json_encode(array(
                                    "code" => 0,
                                    "msg"  => "Hatalı Key"
                                  ),JSON_UNESCAPED_UNICODE);
                die($msg);
                break;
            case 1:
                http_response_code(502);
                $msg = json_encode(array(
                                    "code" => 1,
                                    "msg"  => "Dizin hatalı olarak yazılmış."
                                  ),JSON_UNESCAPED_UNICODE);
                die($msg);
                break;
            case 2:
                http_response_code(503);
                $msg = json_encode(array(
                                    "code" => 2,
                                    "msg"  => "WordPress fonksiyonu çalışmıyor."
                                  ),JSON_UNESCAPED_UNICODE);
                die($msg);
                break;
            case 3:
                http_response_code(507);
                $msg = json_encode(array(
                                    "code" => 3,
                                    "msg"  => "Yetersiz depolama alanı."
                                  ),JSON_UNESCAPED_UNICODE);
                die($msg);
                break;
        }
        
    }
    
    public function sendJSON($data,$url=1) {
        switch($url) {
            case 1: $urlx = $this->wbotsURL1; break;
            case 2: $urlx = $this->wbotsURL2; break;
        }
        
        
        $ch         = curl_init( $urlx );
        $postFields = array( "wbotsKey"=> $this->wbotsKey ,"data"=> json_encode($data,JSON_UNESCAPED_UNICODE ));
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt( $ch, CURLOPT_POSTFIELDS, $postFields );
        curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true);  
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $ch, CURLOPT_MAXREDIRS, 5);
        curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false);
        
        $result = curl_exec($ch);
        curl_close($ch);
        
        
        return $result;
    }
}





?>