Your IP : 216.73.217.154


Current Path : /home/ereika83/www/wp-content/plugins/pressplay/
Upload File :
Current File : /home/ereika83/www/wp-content/plugins/pressplay/functions.php

<?php

/*
  Plugin Name: PressPlay
  Description: Easily export projects from app.PressPlay.io to your Wordpress website.
  Version: 0.0.6
  Author: <strong>Mark Thompson, Matt Callen</strong> | Dev: Dragoș Mocrii
 */

if ( !class_exists( 'Pressplay' )) {

    define( 'PP_URL', plugins_url( '/', __FILE__ ) );
    define( 'PP_PATH', plugin_dir_path( __FILE__ ) );

    class Pressplay
    {

        static $VERSION = '0.0.6';
        static $INSTANCE = null;
        protected $api_key;
        protected $api_url;
        protected $projects_dir;
        protected $projects_url;

        public function __construct()
        {
            $uploads_dir        = wp_upload_dir();
            $this->projects_dir = $uploads_dir['basedir'] . '/pp_projects/';
            $this->projects_url = $uploads_dir['baseurl'] . '/pp_projects/';

            add_action( 'admin_menu', array( $this, 'register_pp_menu_page' ) );
            add_action( 'init', array( $this, 'on_init' ) );
            add_action( 'admin_init', array( $this, 'on_admin_init' ) );
            add_action( 'template_include', array( $this, 'template_overwrite' ), 99 );
            add_action( 'wp_ajax_pp_delete_page', array( $this, 'delete_page' ) );
            add_action( 'wp_ajax_pp_change_permalink', array( $this, 'change_permalink' ) );
            add_action( 'wp_ajax_pp_change_api_key', array( $this, 'change_api_key' ) );
            add_action( 'wp_ajax_pp_pull_project', array( $this, 'pull_project' ) );
            add_action( 'wp_ajax_pp_refresh_projects_list', array( $this, 'refresh_projects_list' ) );
            add_action( 'wp_ajax_pp_make_homepage', array( $this, 'make_homepage' ) );
            add_action( 'wp_ajax_nopriv_pp_push_page', array( $this, 'push_page' ) );
        }

        static public function set_instance( $instance )
        {
            self::$INSTANCE = $instance;
        }

        /**
         * Get instance of Pressplay Singleton
         *
         * @throws Exception
         * @return Pressplay|false Pressplay object or error
         */
        static public function instance()
        {
            if (self::$INSTANCE === null) {
                throw new Exception( 'PressPlay singleton not instantiated.' );
            }
            return self::$INSTANCE;
        }

        public function on_init()
        {

        }

        public function on_admin_init()
        {
            add_action( 'before_delete_post', array( $this, 'sync_pp_pages' ), 10 );
            wp_register_style( 'pp-style', plugins_url( 'assets/css/pp_style.css', __FILE__ ) );
        }

        public function sync_pp_pages( $page_id )
        {
            $pp_pid = get_post_meta( $page_id, 'pp_pid', true );
            if ($pp_pid) {
                $this->delete_project_files( $pp_pid );
            }
        }

        public function get_api_data()
        {
            if (get_option( 'pp_api_key' )) {
                $api_key = get_option( 'pp_api_key' );
                $api_url = get_option( 'pp_api_url' );

                return array( 'api_key' => $api_key, 'api_url' => $api_url );
            } else {
                //load PP_KEY file
                $pp_key_file = dirname( __FILE__ ) . '/pp_key.php';
                if ( !file_exists( $pp_key_file )) {
                    return null;
                }
                $pp_key_data = include( $pp_key_file );
                $api_key     = $pp_key_data['key'];
                $api_url     = $pp_key_data['api_url'];

                return array( 'api_key' => $api_key, 'api_url' => $api_url );
            }
        }

        public function get_api_key()
        {
            $api_data = $this->get_api_data();
            if ($api_data) {
                return $api_data['api_key'];
            }
            return null; #if api key not set
        }

        public function get_api_url()
        {
            $api_data = $this->get_api_data();
            if ($api_data) {
                return $api_data['api_url'];
            }
            return null; #if api url not set
        }

        public function fetch_projects()
        {
            $response = wp_remote_post(
                $this->get_api_url() . '/wp_site/fetch-projects',
                array(
                    'method'      => 'POST',
                    'timeout'     => 10,
                    'redirection' => 3,
                    'httpversion' => '1.0',
                    'blocking'    => true,
                    'headers'     => array(),
                    'body'        => array( 'api_key' => $this->get_api_key() ),
                    'cookies'     => array()
                )
            );

            if ( !is_wp_error( $response ) && $response['body'] && $return = @json_decode( $response['body'], true )) {
                return $return;
            } else {
                return array();
            }
        }

        public function ping_add_pressplay()
        {
            $api_data = $this->get_api_data();
            if ($api_data) {
                update_option( 'pp_api_key', $api_data['api_key'] );
                update_option( 'pp_api_url', $api_data['api_url'] );
            }

            $response = wp_remote_post(
                $this->get_api_url() . '/wp_site/ping-add',
                array(
                    'method'      => 'POST',
                    'timeout'     => 10,
                    'redirection' => 3,
                    'httpversion' => '1.0',
                    'blocking'    => true,
                    'headers'     => array(),
                    'body'        => array(
                        'api_key'  => $this->get_api_key(),
                        'site_url' => admin_url( 'admin-ajax.php' )
                    ),
                    'cookies'     => array()
                )
            );
        }

        public function ping_remove_pressplay()
        {
            $response = wp_remote_post(
                $this->get_api_url() . '/wp_site/ping-remove',
                array(
                    'method'      => 'POST',
                    'timeout'     => 10,
                    'redirection' => 3,
                    'httpversion' => '1.0',
                    'blocking'    => true,
                    'headers'     => array(),
                    'body'        => array(
                        'api_key'  => $this->get_api_key(),
                        'site_url' => admin_url( 'admin-ajax.php' )
                    ),
                    'cookies'     => array()
                )
            );
        }

        public function pull_project()
        {
            $response = wp_remote_post(
                $this->get_api_url() . '/wp_site/pull-project',
                array(
                    'method'      => 'POST',
                    'timeout'     => 10,
                    'redirection' => 3,
                    'httpversion' => '1.0',
                    'blocking'    => true,
                    'headers'     => array(),
                    'body'        => array(
                        'api_key'    => $this->get_api_key(),
                        'project_id' => $_POST['project_id'],
                        'site_url'   => admin_url( 'admin-ajax.php' )
                    ),
                    'cookies'     => array()
                )
            );

            $response = wp_remote_retrieve_body( $response );

            if ( !empty( $response )) {
                $response = json_decode( $response, true );
            }

            if ($response && isset( $response['status'] ) && $response['status'] == 1) {
                $this->process_zip_download( $response['page_title'], $response['project_id'], $response['zip_id'] );

                die( json_encode(
                    array( 'status' => - 1, 'message' => 'Zip was not processed.' )
                ) );
            } else {
                die( json_encode(
                    array( 'status' => - 1, 'message' => 'Did not receive a well formatted message from Pressplay.' )
                ) );
            }
        }

        public function push_page()
        {
            $api_key = $_POST['api_key'];
            if ($api_key !== $this->get_api_key()) {
                die( json_encode( array( 'status' => - 1, 'message' => 'Bad key.' ) ) );
            }

            $this->process_zip_download( $_POST['page_title'], $_POST['project_id'], $_POST['zip_id'] );

        }

        protected function process_zip_download( $page_title, $project_id, $zip_id )
        {
            $page_title   = strip_tags( $page_title );
            $zip_location = $this->get_api_url() . '/wp_site/api-download/' . $project_id . '/' . $zip_id . '?api_key=' . urlencode(
                    $this->get_api_key()
                );

            $zip_name = md5( basename( $zip_location ) ) . '.zip';
            $zip_path = get_temp_dir() . $zip_name;

            $response = wp_remote_get(
                $zip_location,
                array(
                    'timeout'  => 15,
                    'stream'   => true,
                    'filename' => $zip_path
                )
            );

            if (is_wp_error( $response )) {
                die( json_encode( array( 'status' => - 1, 'message' => 'Could not download zip.' ) ) );
            }

            if (file_exists( $zip_path )) {
                if ($this->unzip_project( $zip_path, $project_id )) {
                    if ( !$page_id = $this->check_page_exists( $project_id )) {
                        $page_id = $this->create_page( $project_id, $page_title );
                    }
                    $out = array( 'status' => 1, 'message' => 'OK', 'link' => get_permalink( $page_id ) );
                } else {
                    $out = array( 'status' => - 1, 'message' => 'Could not unzip file.' );
                }
                unlink( $zip_path );
                die( json_encode( $out ) );
            } else {
                die( json_encode( array( 'status' => - 1, 'message' => 'Could not store zip file to tmp dir.' ) ) );
            }
        }

        public function register_pp_menu_page()
        {
            $page = add_menu_page(
                'PressPlay Settings',
                'PressPlay',
                'manage_options',
                'pressplay/settings',
                array( $this, 'display_settings_page' ),
                PP_URL . 'assets/img/favicon.png',
                '100.789'
            );
            add_action( 'admin_print_styles-' . $page, array( $this, 'pp_add_styles' ) );

            $page = add_submenu_page(
                null,
                'PressPlay Debug',
                'PressPlay',
                'manage_options',
                'pressplay/debug',
                array( $this, 'display_debug_page' ),
                PP_URL . 'assets/img/favicon.png',
                '100.790'
            );
            add_action( 'admin_print_styles-' . $page, array( $this, 'pp_add_styles' ) );
        }

        public function pp_add_styles()
        {
            wp_enqueue_style( 'pp-style' );
        }

        public function page_render( $template, $data = array() )
        {
            ob_start();
            extract( $data );
            include PP_PATH . 'templates/' . ltrim( $template, '/' );
            return ob_get_clean();
        }

        public function display_settings_page()
        {
            echo $this->page_render( 'settings.php' );
        }

        public function display_debug_page()
        {
            echo $this->page_render( 'debug.php' );
        }

        public function delete_page()
        {
            $page_id = $_POST['page_id'];
            $pp_pid  = get_post_meta( $page_id, 'pp_pid', true );
            if ($pp_pid) {
                wp_delete_post( $page_id, true );
                die( json_encode( array( 'status' => 1 ) ) );
            }
            die( json_encode( array( 'status' => - 1 ) ) );
        }

        public function change_api_key()
        {
            $api_key = $_POST['api_key'];
            update_option( 'pp_api_key', $api_key );

            die( json_encode( array( 'status' => 1 ) ) );
        }

        public function refresh_projects_list()
        {
            $projects_list = $this->fetch_projects();
            $html          = Pressplay::instance()->page_render(
                'projects-list.php',
                array( 'projects_list' => $projects_list )
            );

            die( json_encode( array( 'status' => 1, 'html' => $html ) ) );
        }

        public function change_permalink()
        {
            $page_id       = $_POST['page_id'];
            $new_permalink = sanitize_title( $_POST['new_permalink'], '' );
            if (empty( $new_permalink )) {
                die( json_encode( array( 'status' => - 1, 'message' => 'This permalink cannot be used.' ) ) );
            }

            if ( !$this->is_pp_page( $page_id )) {
                die( json_encode( array( 'status' => - 1, 'message' => 'Wrong page id.' ) ) );
            }

            $my_post = array(
                'ID'        => $page_id,
                'post_name' => $new_permalink
            );

            // Update the post into the database
            if (wp_update_post( $my_post )) {
                die( json_encode( array( 'status' => 1 ) ) );
            } else {
                die( json_encode( array( 'status' => - 1, 'message' => 'Could not change permalink.' ) ) );
            }
        }

        public function make_homepage()
        {
            $page_id = $_POST['page_id'];
            if ( !$this->is_pp_page( $page_id )) {
                die( json_encode( array( 'status' => - 1, 'message' => 'Wrong page id.' ) ) );
            }

            if (update_option( 'show_on_front', 'page' ) && update_option( 'page_on_front', $page_id )) {
                die( json_encode( array( 'status' => 1 ) ) );
            } else {
                die( json_encode( array( 'status' => - 1, 'message' => 'Could not set page as homepage' ) ) );
            }
        }

        protected function delete_project_files( $project_id )
        {
            $this->remove_folder_recursively( $this->get_project_folder( $project_id ) );
        }

        /**
         * Checks to see if page already created for current project ID.
         *
         * @param   integer ; Project ID
         *
         * @return  integer;
         */
        public function check_page_exists( $project_id )
        {
            $query = new WP_Query(
                array(
                    'post_type'  => 'page',
                    'meta_query' => array(
                        array(
                            'key'     => 'pp_pid',
                            'value'   => $project_id,
                            'compare' => '=',
                        )
                    )
                )
            );

            if ( !$query->found_posts) {
                return 0;
            } else {
                return $query->posts[0]->ID;
            }
        }

        public function is_pp_page( $page_id )
        {
            $pp_pid = get_post_meta( $page_id, 'pp_pid', true );
            return $pp_pid;
        }

        public function create_page( $project_id, $title )
        {
            $post = array(
                'post_content'   => '',
                //'post_name' => '',
                'post_title'     => $title,
                'post_status'    => 'publish',
                'post_type'      => 'page',
                'post_author'    => '',
                'ping_status'    => 'closed',
                'comment_status' => 'closed',
                'page_template'  => ''
            );

            $post_id = wp_insert_post( $post );

            if ($post_id > 0) {
                add_post_meta( $post_id, 'pp_pid', $project_id, true );
            }

            return $post_id;
        }

        public function template_overwrite( $default )
        {
            global $post;
            if ($post && $pp_pid = get_post_meta( $post->ID, 'pp_pid', true )) {
                $index_file = $this->projects_dir . $pp_pid . '/index.html';
                if ( !file_exists( $index_file )) {
                    trigger_error(
                        'PressPlay index file not found. Please push the page again from app.PressPlay.io',
                        E_USER_ERROR
                    );
                    return false;
                }
                return $index_file;
            } else {
                return $default;
            }
        }

        protected function get_project_folder( $project_id )
        {
            return $this->projects_dir . $project_id;
        }

        public function unzip_project( $source, $project_id )
        {
            require_once( ABSPATH . 'wp-admin/includes/file.php' );
            WP_Filesystem();
            $destination_path = $this->get_project_folder( $project_id );

            if (file_exists( $destination_path )) {
                $this->remove_folder_recursively( $destination_path );
            }

            if ( !wp_mkdir_p( $destination_path )) {
                return false;
            }

            $unzipfile = unzip_file( $source, $destination_path );

            if ($unzipfile) {
                $index_file = $destination_path . '/index.html';
                file_put_contents(
                    $index_file,
                    $this->add_base_meta_tag( file_get_contents( $index_file ), $project_id )
                );
                return true;
            } else {
                return false;
            }
        }

        public function remove_folder_recursively( $path )
        {
            if (is_dir( $path ) === true) {
                $files = new RecursiveIteratorIterator(
                    new RecursiveDirectoryIterator( $path ),
                    RecursiveIteratorIterator::CHILD_FIRST
                );

                foreach ($files as $file) {
                    if (in_array( $file->getBasename(), array( '.', '..' ) ) !== true) {
                        if ($file->isDir() === true) {
                            rmdir( $file->getPathName() );
                        } else if (( $file->isFile() === true ) || ( $file->isLink() === true )) {
                            unlink( $file->getPathname() );
                        }
                    }
                }
                return rmdir( $path );
            } else if (( is_file( $path ) === true ) || ( is_link( $path ) === true )) {
                return unlink( $path );
            }
            return false;
        }

        protected function add_base_meta_tag( $html, $project_id )
        {
            $html = preg_replace(
                "/(<head>)/is",
                "$1<base href=\"" . $this->projects_url . $project_id . "/\" target=\"_self\" />",
                $html
            );
            return $html;
        }

    }

    $pressplay = new Pressplay();
    Pressplay::set_instance( $pressplay );

    register_activation_hook( __FILE__, array( $pressplay, 'ping_add_pressplay' ) );
    register_deactivation_hook( __FILE__, array( $pressplay, 'ping_remove_pressplay' ) );
}

require_once( 'wp-updates-plugin.php' );
new WPUpdatesPluginUpdater_642( 'http://wp-updates.com/api/2/plugin', plugin_basename( __FILE__ ) );