<?php
/**
* Plugin Name: Youtube Mass Videos Importer
* Plugin URI: https://www.wp-script.com/plugins/youtube-mass-videos-importer/
* Description: Tired of adding videos manually? Save time by importing thousands of Adult Videos from Youtube in minutes!
* Author: WP-Script
* Author URI: https://www.wp-script.com
* Version: 2.0.0
* Text Domain: youtube-mass-videos-importer
* Domain Path: /languages
*/


defined( 'ABSPATH' ) or die( 'Cheatin&#8217; uh?' );// Exit if accessed directly

//Singleton Class
final class YMVI {

        /****************/
      /*** INSTANCE ***/
    /****************/

    private static $instance, $config;

    public function __clone()   {_doing_it_wrong( __FUNCTION__, __( 'Cheatin&#8217; huh?', YMVI_LANG ), '1.0' );}
    public function __wakeup()  {_doing_it_wrong( __FUNCTION__, __( 'Cheatin&#8217; huh?', YMVI_LANG ), '1.0' );}

    public static function instance() {
        if ( ! isset( self::$instance ) && ! ( self::$instance instanceof YMVI ) ) {
            include_once( ABSPATH . 'wp-admin/includes/plugin.php' );

            if( !is_plugin_active('wp-script-core/wp-script-core.php') ){

                require( plugin_dir_path( __FILE__ ) . 'admin/vendors/tgm-activation-x/plugin-activation.php' );
                require( plugin_dir_path( __FILE__ ) . 'admin/vendors/tgm-activation-x/class-tgm-plugin-activation.php' );

            }else{

                self::$instance = new YMVI;

                require( plugin_dir_path( __FILE__ ) . 'config.php' );

                if( is_admin() ){

                    //load admin filters
                    self::$instance->load_admin_filters();

                    //load admin hooks
                    self::$instance->load_admin_hooks();

                    //auto-load admin php files
                    self::$instance->auto_load_php_files( 'admin' );

                    //load admin features
                    self::$instance->admin_init();

                    //load text domain
                    self::$instance->load_textdomain();
                }else{

                    //load public filters
                    //self::$instance->load_public_filters();

                    //auto-load admin php files
                    self::$instance->auto_load_php_files( 'public' );

                    //load options file
                    require( plugin_dir_path( __FILE__ ) . 'admin/pages/page-options.php' );

                }
            }
        }
        return self::$instance;
    }


        /*********************/
      /*** ADMIN FILTERS ***/
    /*********************/

    public function load_admin_filters(){
        //add js and css files, tabs, pages, php files
        add_filter( 'WPSCORE-scripts',  array( $this, 'add_admin_scripts' ) );
        add_filter( 'WPSCORE-tabs',     array( $this, 'add_admin_navigation' ) );
        add_filter( 'WPSCORE-pages',    array( $this, 'add_admin_navigation' ) );
    }

    //Add admin js and css scripts Callback
    public function add_admin_scripts( $scripts ){
        if( isset( self::$config['scripts'] ) ){
            eval( WPSCORE()->eval_product_data( 'YMVI', 'add_scripts_js' ) );
            eval( WPSCORE()->eval_product_data( 'YMVI', 'add_scripts_css' ) );
        }
        return $scripts;
    }

    //Add admin Navigation Tab and SubPage Callback
    public function add_admin_navigation( $nav ){
        if( isset( self::$config['nav'] ) )
            $nav += (array) self::$config['nav'];
        return $nav;
    }

    public function auto_load_php_files( $dir ) {

        $dirs = (array) ( plugin_dir_path( __FILE__ ) . $dir . '/' );

        foreach( (array) $dirs as $dir ){
            $files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $dir ) );
            if( ! empty( $files ) ) {
                foreach ( $files as $file ) {
                    //exlude dir
                    if ( $file->isDir() ) { continue; }
                    //exlude index.php
                    if ( $file->getPathname() == 'index.php' ) { continue; }
                    //exlude files != .php
                    if (substr($file->getPathname(), -4 ) != '.php' ) { continue; }
                    //exlude files from -x suffixed directories
                    if (substr($file->getPath(), -2 ) == '-x' ) { continue; }
                    //exlude -x suffixed files
                    if (substr($file->getPathname(), -6 ) == '-x.php' ) { continue; }
                    //else require file
                    require $file->getPathname();
                }
            }
        }
    }


        /*******************/
      /*** ADMIN HOOKS ***/
    /*******************/

    public function load_admin_hooks() {
        //plugin activation / deactivation / uninstall
        register_activation_hook(   __FILE__, array( 'YMVI', 'activation' ) );
        register_deactivation_hook( __FILE__, array( 'YMVI', 'deactivation' ) );
        register_uninstall_hook(    __FILE__, array( 'YMVI', 'uninstall' ) );
    }

    static function activation(){
        //update site signature
        WPSCORE()->update_client_signature();

        //call init
        WPSCORE()->init( true );
    }

    static function deactivation(){
        //update site signature
        WPSCORE()->update_client_signature();

        //call init
        WPSCORE()->init( true );
    }

    static function uninstall(){
        //update site signature
        WPSCORE()->update_client_signature();

        //call init
        WPSCORE()->init( true );
    }

        /*******************/
      /*** TEXT DOMAIN ***/
    /*******************/

    private function load_textdomain() {
        // Set filter for plugin's languages directory
        $lang_dir = dirname( plugin_basename( YMVI_FILE ) ) . '/languages/';

        // Traditional WordPress plugin locale filter
        $mofile = sprintf( '%1$s-%2$s.mo', YMVI_LANG, get_locale() );

        // Setup paths to current locale file
        $mofile_local  = $lang_dir . $mofile;
        $mofile_global = WP_LANG_DIR . '/' . YMVI_LANG . '/' . $mofile;

        if ( file_exists( $mofile_global ) ) {
            // Look in global /wp-content/languages/WPSCORE/ folder
            load_textdomain( YMVI_LANG, $mofile_global );
        } elseif ( file_exists( $mofile_local ) ) {
            // Look in local /wp-content/plugins/WPSCORE/languages/ folder
            load_textdomain( YMVI_LANG, $mofile_local );
        } else {
            // Load the default language files
            load_plugin_textdomain( YMVI_LANG, false, $lang_dir );
        }
        return false;
    }


        /**********************/
      /*** PUBLIC FILTERS ***/
    /**********************/

    //add public filters
    public function load_public_filters(){
        add_filter( 'WPSCORE-public_dirs', array( $this, 'add_public_dirs' ) );
    }

    //Add public php files to require
    public function add_public_dirs( $public_dirs ){
        $public_dirs[] = plugin_dir_path( __FILE__ ) . 'public/';
        return $public_dirs;
    }



        /*************/
      /***  INIT ***/
    /*************/
    //admin init
    private function admin_init(){

    }

    //public init
    private function public_init(){

    }

        /****************/
      /***  METHODS ***/
    /****************/
    public function duration_iso8601_to_seconds($iso_duration, $allow_negative = true){
        // Parse duration parts
        $matches = array();
        preg_match('/^(-|)?P([0-9]+Y|)?([0-9]+M|)?([0-9]+D|)?T?([0-9]+H|)?([0-9]+M|)?([0-9]+S|)?$/', $iso_duration, $matches);
        if(!empty($matches)){
            // Strip all but digits and -
            foreach($matches as &$match){
                $match = preg_replace('/((?!([0-9]|-)).)*/', '', $match);
            }
            // Fetch min/plus symbol
            $result['symbol'] = ($matches[1] == '-') ? $matches[1] : '+'; // May be needed for actions outside this function.
            // Fetch duration parts
            $m = ($allow_negative) ? $matches[1] : '';
            $result['year']   = intval($m.$matches[2]);
            $result['month']  = intval($m.$matches[3]);
            $result['day']    = intval($m.$matches[4]);
            $result['hour']   = intval($m.$matches[5]);
            $result['minute'] = intval($m.$matches[6]);
            $result['second'] = intval($m.$matches[7]);

            return $result['hour'] * 3600 + $result['minute'] * 60 + $result['second'];

        }
        else{
            return false;
        }
    }

    public function get_youtube_existing_ids(){
        global $wpdb;

        $custom_post_type = xbox_get_field_value( 'ymvi-options', 'custom-video-post-type' );
        $custom_post_type = $custom_post_type != '' ? $custom_post_type : 'post';

        $query_str = "
            SELECT wposts.ID, wpostmetaVideoId.meta_value videoId
            FROM $wpdb->posts wposts, $wpdb->postmeta wpostmetasponsor, $wpdb->postmeta wpostmetaVideoId
            WHERE wposts.ID = wpostmetasponsor.post_id
            AND ( wpostmetasponsor.meta_key = 'partner' AND wpostmetasponsor.meta_value = %s )
            AND (wposts.ID =  wpostmetaVideoId.post_id AND wpostmetaVideoId.meta_key = 'video_id')
            AND wposts.post_type = %s
        ";

        $bdd_videos = $wpdb->get_results( $wpdb->prepare( $query_str, 'youtube', $custom_post_type), OBJECT );

        $partner_videos_ids = array();

        foreach( (array)$bdd_videos as $bdd_video ){
            $partner_videos_ids[$bdd_video->ID] = $bdd_video->videoId;
        }
        unset( $bdd_videos );
        return $partner_videos_ids;
    }

    public function get_wp_cats(){
        return (array) get_terms( 'category', array( 'hide_empty' => 0 ) );
    }

    public function get_objectL10n(){
        return array(
            'error_suppression'         => __( 'An error occured during the suppression:', YMVI_LANG ),
            'select_wp_cat'             => __( 'Select a WordPress category', YMVI_LANG ),
            'select_cat_from'           => __( 'Select a category from', YMVI_LANG ),
            'and'                       => __( 'AND', YMVI_LANG ),
            'check_least'               => __( 'Check at least 1 video', YMVI_LANG ),
            'enable_button'             => __( 'to enable this button', YMVI_LANG ),
            'import'                    => __( 'Import', YMVI_LANG ),
            'search_feed'               => __( 'videos and save this search as a Feed. All your Feeds are displayed at the bottom of this page.', YMVI_LANG )
        );
    }

    public function call_by_ref(&$var){
		return $var;
	}

    public function media_sideload_image( $file, $post_id, $desc = null, $source ) {
        require_once(ABSPATH . 'wp-admin/includes/media.php');
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        require_once(ABSPATH . 'wp-admin/includes/image.php');

        if ( ! empty( $file ) ) {

            // Set variables for storage, fix file filename for query strings.
            preg_match( '/[^\?]+\.(jpe?g|jpe|gif|png)\b/i', $file, $matches );
            $tmp = explode( '.', basename( $matches[0] ) );
            $file_ext = end( $tmp );
            $file_array = array();
            $file_array['name'] = sanitize_title(get_the_title( $post_id )) . '.' . $file_ext;
            unset( $tmp, $file_ext );

            // Download file to temp location.
            $file_array['tmp_name'] = download_url( $file );

            // If error storing temporarily, return the error.
            if ( is_wp_error( $file_array['tmp_name'] ) ) {
                return $file_array['tmp_name'];
            }

            // Do the validation and storage stuff.
            $id = media_handle_sideload( $file_array, $post_id, $desc );

            // If error storing permanently, unlink.
            if ( is_wp_error( $id ) ) {
                @unlink( $file_array['tmp_name'] );
                return $id;
            }
            $src = wp_get_attachment_url( $id );
        }

        // Finally check to make sure the file has been saved, then return the HTML.
        if ( ! empty( $src ) ) {
            $alt = isset( $desc ) ? esc_attr( $desc ) : '';
            $html = "<img src='$src' alt='$alt' />";
            return $html;
        }
    }

}

function YMVI() {
    return YMVI::instance();
}
YMVI();
