Storie Plus Plugin 1

<?php
/*
Plugin Name: Storie Plus Plugin
Plugin URI: https://rede.servidortrader.com/
Description: Compartilhe Seus WebStories com sua comunidade e aumente seu tráfego. Juntos somos mais fortes!<br> Autores: <a href="https://www.izalmo.com/">Izalmo Silva</a>, <a href="https://www.ezequielsas.com/">Ezequiel Sas</a>
Version: 6.3
Requires PHP: 7.4
Author: Izalmo Silva
Author URI: https://www.izalmo.com/
*/
  // Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
function is_image_link($link) {
    $image_extensions = ['.jpg', '.png', '.jpeg', '.bmp', '.gif'];
    foreach ($image_extensions as $ext) {
        if (mb_strpos($link, $ext) !== false) {
            return true;
        }
    }
    return false;
}
// Function to curl html from a url and save it as a ws-share-plugin post
function create_wssharestory($id) { 
    global $wpdb;
    $versao = 60; 
    $post = get_post($id); 

    // Gets post content 
    $html = $post->post_content; 
    $htmlfiltered = $post->post_content_filtered; 

    // Gets post meta data
    $postmeta = get_post_meta($id, '', true);  

    // Gets post title 
    $title = $post->post_title; 
    $token = get_option('wssharestory_token'); 
    $publicado = get_option('wssharestory_publicado'); 

    // set url to be called 
    $url = "https://dados.servidortrader.com/guardawebstories.php"; 
    $link = get_permalink($id);
    echo '<body style="background-color: #1C1C1C;">';
    echo '<div style="background-color: black; text-align: center; padding: 22px; position: fixed; top: 22%; left: 22%; bottom: 10%; right: 22%; margin: auto; border-radius: 10px;">';
    echo '<h2 style="color: white;">ENVIANDO WEB STORIES...</h2>';
    $resphtml = ws_send_html($url,$token,$link,$html,$htmlfiltered,$title,$versao);
    
    if ($resphtml[1] != 200) {
        return [$resphtml[0], $resphtml[1]];
    }
    else {
        add_post_meta($id,'web_stories_enviado','S');
        echo '<h2 style="color: white;">WEB STORIES ENVIADO COM SUCESSO!</h2>';
        echo '<h2 style="color: white;">Você acabou de receber créditos por compartilhar! <br> Vá em Baixar Stories para baixar webstories do nosso sistema.</h2>';
        $msg = '<br> <button onclick="location.href=\''. admin_url('edit.php?post_type=ws-share-plugin&page=wssharestory-download') .'\'" style="display: inline-block; padding: 12px 24px; font-size: 16px; font-weight: bold; text-decoration: none; color: #fff; background-color: #1c1c1c; border: none; border-radius: 4px;" aria-label="Voltar para Web Stories">BAIXAR STORIES</button>';
        show_message($msg);  
        echo '</div></body>';
        return [$resphtml[0], $resphtml[1]];
    }
}
// Fucntion to curl html from a url using wordpress functions
function ws_send_html($url,$token,$link,$html,$htmlfiltered,$title,$versao){ 
    $response = wp_remote_post( $url , array(     
        'timeout' => 15, 
        'method'  => 'POST', 
        'body' => array ( 
            'token' => $token, 
            'link' => $link, 
            'html' => $html, 
            'htmlfiltered' => $htmlfiltered,             
            'titulo' => $title, 
            'versao'=>$versao 
            ) 
        ) 
    ); 

    $resposta = wp_remote_retrieve_body($response);
    $resposta = explode('#',$resposta);
    if ($resposta[0] == 'N') {
        return [$resposta[1],406];
    } else {
        return [$resposta[1],200];
    }
}
function ProcurarImagensNoHTML( $html ) {
  //	$html = file_get_contents( $link );
  $stack = array();
  $dom = new DOMDocument();
  $dom->loadHTML($html);
  $tagsimg = $dom->getElementsByTagName('amp-img');
    foreach ($tagsimg as $key=>$value) {
      $link = $value->getAttribute('src');
      if (is_image_link($link)) {     
    	array_push($stack,$link);
      }
      $link2 = $value->getAttribute('srcset');
     // var_dump($link2);
      $linkarray = explode(',',$link2);
      if (count($linkarray) > 0) {
        foreach($linkarray as $iniciallink) {
            //echo 'srcSet: '.$iniciallink.'<br>';
            $linkpartes = explode(' ',$iniciallink);
            if (count($linkpartes) > 0) {
                $link = $linkpartes[0];
            } else {
                $link = $iniciallink;
            }
      if (is_image_link($link)) {     
    	       // echo 'srcSet: '.$link.'<br>';
    	        array_push($stack,$link);
            }
        }
      }
  }
  $tagsimg = $dom->getElementsByTagName('link');
    foreach ($tagsimg as $key=>$value) {
       $link = $value->getAttribute('href');
      if (is_image_link($link)) {     
    	#echo $key.' - '.$link.'<br>';
    	$achou = false;
    	foreach($stack as $lkexiste) {
    	    if ($lkexiste == $link) {
    	        $achou = true;
    	    }
    	}
    	if ($achou == false) {
    	    //$novoar = array($link);
    	    array_push($stack,$link);
    	}
      } 
  }
  $tagsimg = $dom->getElementsByTagName('amp-story');
    foreach ($tagsimg as $key=>$value) {
      $link = $value->getAttribute('publisher-logo-src');
      if (is_image_link($link)) {     
    	#echo $key.' - '.$link.'<br>';
    	$achou = false;
    	foreach($stack as $lkexiste) {
    	    if ($lkexiste == $link) {
    	        $achou = true;
    	    }
    	}
    	if ($achou == false) {
    	   // $novoar = array($link);
    	     array_push($stack,$link);
    	}
      }      
      $link = $value->getAttribute('poster-portrait-src');
      if (is_image_link($link)) {     
    	#echo $key.' - '.$link.'<br>';
    	$achou = false;
    	foreach($stack as $lkexiste) {
    	    if ($lkexiste == $link) {
    	        $achou = true;
    	    }
    	}
    	if ($achou == false) {
    	   // $novoar = array($link);
    	    array_push($stack,$link);
    	}
      }      
  }
  return $stack;
}
function uploadRemoteImageAndAttach($image_url,$linksexistentes){ //, $parent_id){
    $image = $image_url;
  //  echo '<br>uploadRemoteImageAndAttach: '. $image.'<br>';
    $get = wp_remote_get( $image );
    $type = wp_remote_retrieve_header( $get, 'content-type' );
    if (!$type)
        return [false,false];
	$nomebase = basename( $image );
    $achou = false;
    $mirror =  '';
  	$linksexistentes2 = explode('||',$linksexistentes);
      foreach ($linksexistentes2 as $seuslinks) {
      //    echo $seuslinks.'<br>';
      //    echo $nomebase.'<br>';
         if (str_contains($seuslinks, $nomebase)) {
           $achou = true;
           $mirror = $seuslinks;       
         }
      }
        if ($achou == false ) {
      //      echo 'passo 1 Sou eu<br>';
        	$mirror = wp_upload_bits($nomebase , '', wp_remote_retrieve_body( $get ) );
        	return [$mirror['url'],$mirror['url']];
        } else {
       //     echo 'Achei<br>';
            return [$mirror,''];
        }
}
function lerjsoninterno2($value,$linksexistentes) {
  foreach($value as $key2=> $val2) {
      if (is_array($val2)) {
           $value[$key2] = lerjsoninterno2($val2,$linksexistentes);
      } else {
        $link = $val2;
        if (mb_strpos($link, 'wp-content') !== false) {
      if (is_image_link($link)) {     
              		$superlink = uploadRemoteImageAndAttach($link,$linksexistentes);
              		$novolink = $superlink[0];
              		if ($superlink[1] <> '') {
              		    $linksexistentes = $linksexistentes.'||'.$superlink[1];
                  		if ($novolink != false) {
    	          			$value[$key2] = $novolink;
                        }
              		}
			  }   
        }
      }
  }
  return [$value,$linksexistentes];
}
function procuraImagemNoJson($html) {
    $json = json_decode($html,true);
    $linksexistentes = '';
    $json = lerjsoninterno2($json,$linksexistentes);
    //return $json;
    return json_encode($json);
}
// Add "Preview wssharestory to list of action on post list
add_filter( 'post_row_actions', 'wssharestory_preview', 10, 2 ); 
function wssharestory_preview( $actions, $post ) { 
    global $wpdb;
    if ( 'web-story' != $post->post_type ) { 
        return $actions; 
    } 
    // Check if post is published
   /* if ( 'publish' != $post->post_status ) {
        return $actions;
    }*/
    // verifica se esse post foi recebido
    $meuid = get_the_ID();  
    $results = $wpdb->get_results( $wpdb->prepare("SELECT post_id,meta_id,meta_key,meta_value FROM {$wpdb->prefix}postmeta WHERE meta_key in ('web_stories_idcopiado','web_stories_copiado') and post_id = %d order by post_id asc", $meuid), OBJECT ); 

     $metaid = 0;
     $eparaavaliar = false;
     $idvalidar = '-1';
     $str = '';
    foreach($results as $row) {
        //if (($metaid ==  0) and ($row->post_id == $meuid)) {
        if ($row->post_id == $meuid) {
            if ($row->meta_key == 'web_stories_copiado') {
                $metaid = $row->post_id;
            }
            if ($row->meta_key == 'web_stories_idcopiado') {
                $str = $str.$row->meta_key;
                $partes = explode('#',$row->meta_value);
                if (count($partes) < 2 ) {
                    $eparaavaliar = true;               
                    $idvalidar = $row->meta_value;
                }
            }
        }
    }
    if ( $metaid > 0 ) {
        if ($eparaavaliar == true) {
               //$actions['wssharestory_share'] = '<a href="https://dados.servidortrader.com/avaliar.php?id='.$idvalidar.'" target="_blank">Avaliar WS</a>';
               $actions['wssharestory_share'] = 'WS RECEBIDO | <a href="' . admin_url( 'edit.php?post_type=ws-share-plugin&action=wsshareaval&id='.$meuid.'&idavaliacao=' . $idvalidar ) . '">' . __( 'Avaliar WS', 'wssharestory' ) .'</a>';
        } else {
            $actions['wssharestory_share'] = 'WS RECEBIDO';
        }
    } else { // verifica se esse post já foi enviado.
            $results = $wpdb->get_results( "SELECT post_id,meta_id FROM {$wpdb->prefix}postmeta WHERE meta_key = 'web_stories_enviado' and post_id = ".$meuid." order by post_id asc", OBJECT );
            $metaid = 0;
            foreach($results as $row) {
                if (($metaid ==  0) and ($row->post_id == $meuid)) {
                 $metaid = $row->post_id;
                } 
            }
            if ($metaid > 0) {
                $actions['wssharestory_share'] = 'WS COMPARTILHADO';
            } else {// wssharestory generator
            $actions['wssharestory_share'] = '<a href="' . admin_url( 'post-new.php?post_type=ws-share-plugin&id=' . get_the_ID() ) . '" target="_blank">' . __( 'Compartilhar Postagem', 'wssharestory' ) .'</a>';
            }
    }
    return $actions;
}
  // Function to create a new post type called ws-share-plugin
  function create_share_post_type() {
      register_post_type( 'ws-share-plugin',
          array(
              'labels' => array(
                  'name' => __( 'Stories Plus' ),
                  'singular_name' => __( 'wssharestory' )
              ),
              'public' => true,
              'has_archive' => true,
              'rewrite' => array('slug' => 'wssharestory'),
              'menu_icon' => 'dashicons-format-aside',
              'supports' => array('title'),
              'show_in_rest' => true,
              'rest_base' => 'wssharestory',
              'rest_controller_class' => 'WP_REST_Posts_Controller',
              'exclude_from_search' => true
          )
      );
  }
  add_action( 'init', 'create_share_post_type' );// Flush permalink settings on plugin activation
  function wssharestory_flush_rewrite_rules() {
      update_option('rewrite_rules', '');
      flush_rewrite_rules();
  }
  register_activation_hook( __FILE__, 'wssharestory_flush_rewrite_rules' );// Hide add new post to ws-share-plugin post type
  add_action( 'admin_menu', 'share_hide_add_new_post_link' );
  function share_hide_add_new_post_link() {
      global $submenu;
      unset($submenu['edit.php?post_type=ws-share-plugin'][5]);
      unset($submenu['edit.php?post_type=ws-share-plugin'][10]);
  }
  add_action( 'admin_post_wpseaval_23456', 'wpseaval_23456_avalia',10,5 );
  function wpseaval_23456_avalia() {
      $idorigem = $_GET['idorigem'];
      $iddestino = $_GET['iddestino'];
      $avaliacao = $_GET['avaliacao'];
      $melhoria = $_GET['melhoria'];
      $link = get_permalink($idorigem);
      ?><body style="background:#f0f0f1">
        <?php 
            echo '<H2>Conectando ao servidor do Storie Plus... </H2><br>';
            echo '<H2>Enviando avaliação do Web Stories <br>'.$link.'</H2><br>';
            $token = get_option('wssharestory_token');    
            $url = 'https://dados.servidortrader.com/avaliarstories.php';
            $response = wp_remote_post( $url , array(    
                  'timeout' => 15,
                  'method'  => 'POST',
                  'body' => array (
                      'token' => $token,
                      'iddestino' => $iddestino,
                      'avaliacao' => $avaliacao,            
                      'melhoria' => $melhoria
                      )
                  )
              );
              $resposta = wp_remote_retrieve_body($response);
              $partes = explode('#',$resposta);
              if ($partes[0] == 'S') {
                  echo '<H2>Armazenando no servidor do Storie Plus... </H2><br>';
                  update_post_meta( $idorigem, 'web_stories_idcopiado', $iddestino.'#S');
                  echo '<H2>AVALIAÇÃO ENVIADA COM SUCESSO! </H2> <br>';
              }else {
                  echo '<H2>Problema ao Enviar Avaliação! </H2><br>';
                  echo '<H2>Motivo: '.$partes[1].' </H2><br>';
              }
        ?>
        <a href="edit.php?post_type=web-story">Voltar </a>
      </body>
      <?php 
  }

Deixe um comentário