<?php
/*
  Plugin Name: Login Image
  Plugin URI: http://premium.wpmudev.org/project/login-image
  Description: Allows you to change the login image
  Author: Marko Miljus (Incsub), Andrew Billits, Ulrich Sossou (Incsub)
  Version: 2.1
  Author URI: http://premium.wpmudev.org/project/
  Text_domain: login_image
  WDP ID: 169
 */

/*
  Copyright 2007-2013 Incsub (http://incsub.com)

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License (Version 2 - GPLv2) as published by
  the Free Software Foundation.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

class Login_Image {

    var $build = 2.1;

    function __construct() {
        global $wp_version;

        include_once('external/wpmudev-dash-notification.php');

        if (!function_exists('is_plugin_active_for_network')) {
            require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
        }

        //Check for backwards compatibility

        $uploaddir = $this->upload_dir();
        $login_image_old = $this->get_option('ub_login_image_url', false);
        $login_image = $this->get_option('ub_login_image', false);

        // Check for backwards compatibility
        if (!isset($login_image_old) || $login_image_old == '') {
            //there is no any old record
            if (!$login_image) {//add default image if not exists
                $response = wp_remote_head(admin_url() . 'images/wordpress-logo.svg');
                if (!is_wp_error($response) && !empty($response['response']['code']) && $response['response']['code'] == '200') {//support for 3.8+
                    $this->update_option('ub_login_image', admin_url() . 'images/wordpress-logo.svg');
                } else {
                    $this->update_option('ub_login_image', admin_url() . 'images/wordpress-logo.png'); // for older version
                }
            }
        } else {//there IS an OLD RECORD
            $this->update_option('ub_login_image', $login_image_old); //we will assume that file is in place
            $this->update_option('ub_login_image_url', '');
        }

        add_action('admin_enqueue_scripts', array(&$this, 'admin_enqueues'));
        add_action('admin_menu', array(&$this, 'add_admin_page'));
        add_action('network_admin_menu', array(&$this, 'add_network_admin_page'));


        if (defined('WPMU_PLUGIN_DIR') && file_exists(WPMU_PLUGIN_DIR . '/login-image.php')) {
            load_muplugin_textdomain('login_image', 'languages');
        } else {
            load_plugin_textdomain('login_image', false, dirname(plugin_basename(__FILE__)) . '/languages');
        }

        add_action('admin_init', array(&$this, 'process'));

        // Login interface
        add_action('login_head', array(&$this, 'stylesheet'), 99);

        if (!is_multisite()) {
            add_filter('login_headerurl', array(&$this, 'home_url'));
        }
    }

    function Login_Image() {
        $this->__construct();
    }

    function admin_enqueues() {
        global $wp_version;

        wp_enqueue_style('login_image_admin', plugins_url('css/login_image_admin.css', __FILE__), array(), $this->build);
        wp_enqueue_script('li_admin', plugins_url('js/admin.js', __FILE__), array(), $this->build);

        if ($wp_version >= 3.8) {
            wp_register_style('li-38', plugins_url('css/admin-icon.css', __FILE__));
            wp_enqueue_style('li-38');
        }
    }

    /**
     * Add plugin admin page
     * */
    function add_admin_page() {
        global $blog_id;
        if ((is_multisite() && function_exists('is_plugin_active_for_network') && !is_plugin_active_for_network('login-image/login-image.php')) || !is_multisite() || (is_multisite() && is_main_site())) {
            add_menu_page(__('Login Image', 'login_image'), __('Login Image', 'login_image'), 'manage_options', 'login-image', array(&$this, 'manage_output'));
        }
    }

    function add_network_admin_page() {
        add_menu_page(__('Login Image', 'login_image'), __('Login Image', 'login_image'), 'manage_network_options', 'login-image', array(&$this, 'manage_output'));
    }

    /*
     * Add network admin page the old way
     * */

    function pre_3_1_network_admin_page() {
        add_submenu_page('ms-admin.php', __('Login Image', 'login_image'), __('Login Image', 'login_image'), 'manage_network_options', 'login-image', array(&$this, 'manage_output'));	 	   	 	 		  
    }

    function login_headertitle() {
        return esc_attr(bloginfo('name'));
    }

    function home_url() {
        return home_url();
    }

    function stylesheet() {
        global $current_site;

        $login_image_old = $this->get_option('ub_login_image_url', false);
        $login_image_id = $this->get_option('ub_login_image_id', false);
        $login_image_size = $this->get_option('ub_login_image_size', false);
        $login_image = $this->get_option('ub_login_image', false);

        if (isset($login_image_old) && trim($login_image_old) !== '') {
            $login_image = $login_image_old;
        } else {
            if ($login_image_id) {
                if (is_multisite() && function_exists('is_plugin_active_for_network') && is_plugin_active_for_network('login-image/login-image.php')) {
                    switch_to_blog(1);
                    $login_image_src = wp_get_attachment_image_src($login_image_id, $login_image_size, $icon = false);
                    restore_current_blog();
                } else {
                    $login_image_src = wp_get_attachment_image_src($login_image_id, $login_image_size, $icon = false);
                }
                $login_image = $login_image_src[0];
                $width = $login_image_src[1];
                $height = $login_image_src[2];
            } else if ($login_image) {
                list($width, $height) = getimagesize($login_image);
            } else {
                $response = wp_remote_head(admin_url() . 'images/wordpress-logo.svg');
                if (!is_wp_error($response) && !empty($response['response']['code']) && $response['response']['code'] == '200') {//support for 3.8+
                    $login_image = admin_url() . 'images/wordpress-logo.svg';
                } else {
                    $login_image = admin_url() . 'images/wordpress-logo.png';
                }
            }
        }
        ?>
        <style type="text/css">
            .login h1 a {
                background-image: url("<?php echo $login_image; ?>");
                background-size: <?php echo $width; ?>px <?php echo $height; ?>px;
                background-position: center top;
                background-repeat: no-repeat;
                color: rgb(153, 153, 153);
                height: <?php echo $height; ?>px;
                font-size: 20px;
                font-weight: 400;
                line-height: 1.3em;
                margin: 0px auto 25px;
                padding: 0px;
                text-decoration: none;
                width: <?php echo $width; ?>px;
                text-indent: -9999px;
                outline: 0px none;
                overflow: hidden;
                display: block;
            }
        </style>
        <?php
    }

    function process() {
        global $plugin_page;

        if (isset($_GET['reset']) && isset($_GET['page']) && $_GET['page'] == 'login-image') {
            //login_image_save
            //if (check_admin_referer('login_image_save')) {
            $this->delete_option('ub_login_image');
            $this->delete_option('ub_login_image_id');
            $this->delete_option('ub_login_image_size');

            $uploaddir = $this->upload_dir();
            $uploadurl = $this->upload_url();

            $response = wp_remote_head(admin_url() . 'images/wordpress-logo.svg');

            if (!is_wp_error($response) && !empty($response['response']['code']) && $response['response']['code'] == '200') {//support for 3.8+
                $this->update_option('ub_login_image', admin_url() . 'images/wordpress-logo.svg');
            } else {
                $this->update_option('ub_login_image', admin_url() . 'images/wordpress-logo.png');
            }
            //}
            wp_redirect('admin.php?page=login-image');
        } elseif (isset($_POST['wp_login_image'])) {
            //if (check_admin_referer('save_login_image_changes')) {
            $this->update_option('ub_login_image', $_POST['wp_login_image']);
            $this->update_option('ub_login_image_id', $_POST['wp_login_image_id']);
            $this->update_option('ub_login_image_size', $_POST['wp_login_image_size']);

            //}
        }

        return true;
    }

    function manage_output() {
        global $wpdb, $current_site, $page;

        wp_enqueue_style('thickbox');
        wp_enqueue_script('thickbox');
        wp_enqueue_media();
        wp_enqueue_script('media-upload');

        $page = $_GET['page'];

        if (isset($_GET['error']))
            echo '<div id="message" class="error fade"><p>' . __('There was an error uploading the file, please try again.', 'login_image') . '</p></div>';
        elseif (isset($_GET['updated']))
            echo '<div id="message" class="updated fade"><p>' . __('Changes saved.', 'login_image') . '</p></div>';
        ?>
        <div class='wrap nosubsub'>
            <div class="icon32" id="icon-themes"><br /></div>
            <h2><?php _e('Login Image', 'login_image') ?></h2>
            <form name="login_image_form" id="login_image_form" method="post">
                <div class="postbox">
                    <div class="inside">
                        <p class='description'><?php _e('This is the image that is displayed on the login page (wp-login.php) - ', 'login_image'); ?>
                            <a href='<?php echo wp_nonce_url("admin.php?page=" . $page . "&amp;reset=yes&amp;action=process", 'login_image_save') ?>'><?php _e('Reset the image', 'login_image') ?></a>
                        </p>
                        <?php
                        wp_nonce_field('save_login_image_changes');
                        $login_image_old = $this->get_option('ub_login_image_url', false);
                        $login_image_id = $this->get_option('ub_login_image_id', false);
                        $login_image_size = $this->get_option('ub_login_image_size', false);
                        $login_image = $this->get_option('ub_login_image', false);

                        if (isset($login_image_old) && trim($login_image_old) !== '') {
                            $login_image = $login_image_old;
                        } else {
                            if ($login_image_id) {
                                if (is_multisite() && function_exists('is_plugin_active_for_network') && is_plugin_active_for_network('login-image/login-image.php')) {
                                    switch_to_blog(1);
                                    $login_image_src = wp_get_attachment_image_src($login_image_id, $login_image_size, $icon = false);
                                    restore_current_blog();
                                } else {
                                    $login_image_src = wp_get_attachment_image_src($login_image_id, $login_image_size, $icon = false);
                                }
                                $login_image = $login_image_src[0];
                                $width = $login_image_src[1];
                                $height = $login_image_src[2];
                            } else if ($login_image) {
                                list($width, $height) = getimagesize($login_image);
                            } else {
                                $response = wp_remote_head(admin_url() . 'images/wordpress-logo.svg');
                                if (!is_wp_error($response) && !empty($response['response']['code']) && $response['response']['code'] == '200') {//support for 3.8+
                                    $login_image = admin_url() . 'images/wordpress-logo.svg';
                                } else {
                                    $login_image = admin_url() . 'images/wordpress-logo.png';
                                }
                            }
                        }
                        ?>
                        <img src="<?php echo $login_image . '?' . md5(time()); ?>" />
                        </p>

                        <h4><?php _e('Change Image', 'login_image'); ?></h4>

                        <input class="upload-url" id="wp_login_image" type="text" size="36" name="wp_login_image" value="<?php echo esc_attr($login_image); ?>" />
                        <input class="st_upload_button" id="wp_login_image_button" type="button" value="<?php _e('Browse', 'login_image'); ?>" />
                        <input type="hidden" name="wp_login_image_id" id="wp_login_image_id" value="<?php echo esc_attr($login_image_id); ?>" />
                        <input type="hidden" name="wp_login_image_size" id="wp_login_image_size" value="<?php echo esc_attr($login_image_size); ?>" />
                    </div>
                </div>
                <?php submit_button(__('Save Changes'), 'save_login_image_changes', true); ?>
            </form>
        </div>

        <?php
    }

    function upload_dir() {
        global $switched;

        $siteurl = get_option('siteurl');
        $upload_path = get_option('upload_path');
        $upload_path = trim($upload_path);

        $main_override = is_multisite() && defined('MULTISITE') && is_main_site();

        if (empty($upload_path)) {
            $dir = WP_CONTENT_DIR . '/uploads';
        } else {
            $dir = $upload_path;
            if ('wp-content/uploads' == $upload_path) {
                $dir = WP_CONTENT_DIR . '/uploads';
            } elseif (0 !== strpos($dir, ABSPATH)) {
                // $dir is absolute, $upload_path is (maybe) relative to ABSPATH
                $dir = path_join(ABSPATH, $dir);
            }
        }

        if (!$url = get_option('upload_url_path')) {
            if (empty($upload_path) || ( 'wp-content/uploads' == $upload_path ) || ( $upload_path == $dir ))
                $url = WP_CONTENT_URL . '/uploads';
            else
                $url = trailingslashit($siteurl) . $upload_path;
        }

        if (defined('UPLOADS') && !$main_override && (!isset($switched) || $switched === false )) {
            $dir = ABSPATH . UPLOADS;
            $url = trailingslashit($siteurl) . UPLOADS;
        }

        if (is_multisite() && !$main_override && (!isset($switched) || $switched === false )) {
            if (defined('BLOGUPLOADDIR'))
                $dir = untrailingslashit(BLOGUPLOADDIR);
            $url = str_replace(UPLOADS, 'files', $url);
        }

        $bdir = $dir;
        $burl = $url;

        return $bdir;
    }

    /*
      Function based on the function wp_upload_dir, which we can't use here because it insists on creating a directory at the end.
     */

    function upload_url() {
        global $switched;

        $siteurl = get_option('siteurl');
        $upload_path = get_option('upload_path');
        $upload_path = trim($upload_path);

        $main_override = is_multisite() && defined('MULTISITE') && is_main_site();

        if (empty($upload_path)) {
            $dir = WP_CONTENT_DIR . '/uploads';
        } else {
            $dir = $upload_path;
            if ('wp-content/uploads' == $upload_path) {
                $dir = WP_CONTENT_DIR . '/uploads';
            } elseif (0 !== strpos($dir, ABSPATH)) {
                // $dir is absolute, $upload_path is (maybe) relative to ABSPATH
                $dir = path_join(ABSPATH, $dir);
            }
        }

        if (!$url = get_option('upload_url_path')) {
            if (empty($upload_path) || ( 'wp-content/uploads' == $upload_path ) || ( $upload_path == $dir ))
                $url = WP_CONTENT_URL . '/uploads';
            else
                $url = trailingslashit($siteurl) . $upload_path;
        }

        if (defined('UPLOADS') && !$main_override && (!isset($switched) || $switched === false )) {
            $dir = ABSPATH . UPLOADS;
            $url = trailingslashit($siteurl) . UPLOADS;
        }

        if (is_multisite() && !$main_override && (!isset($switched) || $switched === false )) {
            if (defined('BLOGUPLOADDIR'))
                $dir = untrailingslashit(BLOGUPLOADDIR);
            $url = str_replace(UPLOADS, 'files', $url);
        }

        $bdir = $dir;
        $burl = $url;

        return $burl;
    }

    function get_option($option, $default = false) {
        if (is_multisite() && function_exists('is_plugin_active_for_network') && is_plugin_active_for_network('login-image/login-image.php')) {
            return get_site_option($option, $default);
        } else {
            return get_option($option, $default);
        }
    }

    function update_option($option, $value = null) {
        if (is_multisite() && function_exists('is_plugin_active_for_network') && is_plugin_active_for_network('login-image/login-image.php')) {
            return update_site_option($option, $value);
        } else {
            return update_option($option, $value);
        }
    }

    function delete_option($option) {
        if (is_multisite() && function_exists('is_plugin_active_for_network') && is_plugin_active_for_network('login-image/login-image.php')) {
            return delete_site_option($option);
        } else {
            return delete_option($option);
        }
    }

}

$loginimage = new Login_Image();