<?php
/*
 * ----------------------------------------------------------------------
 *
 *                          Borlabs Cookie
 *                      developed by Borlabs
 *
 * ----------------------------------------------------------------------
 *
 * Copyright 2018 Borlabs - Benjamin A. Bornschein. All rights reserved.
 * This file may not be redistributed in whole or significant part.
 * Content of this file is protected by international copyright laws.
 *
 * ----------------- Borlabs Cookie IS NOT FREE SOFTWARE -----------------
 *
 * @copyright Borlabs - Benjamin A. Bornschein, https://borlabs.io
 * @author Benjamin A. Bornschein, Borlabs ben@borlabs.io
 *
 */

namespace BorlabsCookie\Cookie\Frontend\BlockedContentTypes;

use BorlabsCookie\Cookie\Frontend\ContentBlocker;
use BorlabsCookie\Cookie\Frontend\JavaScript;

class YouTube
{
    private static $instance;

    public static function getInstance()
    {
        if (null === self::$instance) {
            self::$instance = new self;
        }

        return self::$instance;
    }

    private function __clone()
    {
    }

    private function __wakeup()
    {
    }

    /**
     * __construct function.
     *
     * Register the action hook for additional settings.
     *
     * @access protected
     * @return void
     */
    protected function __construct()
    {
        add_action('borlabsCookie/bct/edit_template/youtube', [$this, 'additionalSettingsTemplate']);
    }

    /**
     * getDefault function.
     *
     * @access public
     * @return void
     */
    public function getDefault()
    {
        $data = [
            'typeId'=>'youtube',
            'name'=>'YouTube',
            'description'=>'',
            'hosts'=>[
                'youtube.com',
                'youtu.be',
                'youtube-nocookie.com',
                'youtube.',
            ],
            'previewHTML'=>'<div class="borlabs-cookie-bct bc-bct-video bc-bct-youtube">
    <p class="bc-thumbnail"><img src="%%thumbnail%%" alt="%%name%%"></p>
    <div class="bc-text">
        <p>'._x('To protect your personal data, your connection to YouTube has been blocked.<br>Click on <strong>Load video</strong> to unblock YouTube.<br>By loading the video you accept the privacy policy of YouTube.<br>More information about YouTube\'s privacy policy can be found here <a href="https://policies.google.com/privacy?hl=en&amp;gl=en" target="_blank" rel="nofollow">Google - Privacy &amp; Terms</a>.', 'Blocked Content Types - YouTube', 'borlabs-cookie').'</p>
        <p><label><input type="checkbox" name="unblockAll" value="1" checked> '._x('Do not block YouTube videos in the future anymore.', 'Blocked Content Types - YouTube', 'borlabs-cookie').'</label>
        <a role="button" data-borlabs-cookie-unblock>'._x('Load video', 'Blocked Content Types', 'borlabs-cookie').'</a></p>
    </div>
</div>',
            'globalJS'=>'',
            'initJS'=>'',
            'settings'=>[
                'changeURLToNoCookie'=>true,
                'responsiveIframe'=>true,
                'thumbnailQuality'=>'sddefault',
            ],
            'status'=>true,
            'undeleteable'=>true,
        ];

        return $data;
    }

    /**
     * modify function.
     *
     * @access public
     * @param mixed $id
     * @param mixed $content
     * @return void
     */
    public function modify($id, $content)
    {
        // Get settings of the Blocked Content Type
        $bctData = ContentBlocker::getInstance()->getDataOfBlockedContentType('youtube');

        // Check if the iframe should be made responsive
        if (!empty($bctData['settings']['responsiveIframe'])) {

            // Add wrapper around the iframe, size is handled via CSS
            $content = '<div class="borlabs-cookie-responsive-iframe-wrapper">'.$content.'</div>';

            // Add the modified content to the Blocked Content list, overwrite the old content
            JavaScript::getInstance()->addBlockedContent('youtube', $id, $content);
        }

        // Check if the URL should be changed to youtube-nocookie.com
        if (!empty($bctData['settings']['changeURLToNoCookie'])) {

            // Replace the host with the www.youtube-nocookie.com host
            // The host is not the oEmbed host like youtu.be - it is always www.youtube.com
            $content = str_replace('www.youtube.com', 'www.youtube-nocookie.com', $content);

            // Add the modified content to the Blocked Content list, overwrite the old content
            JavaScript::getInstance()->addBlockedContent('youtube', $id, $content);
        }

        // Default thumbnail
        $thumbnail = BORLABS_COOKIE_PLUGIN_URL.'images/bct-no-thumbnail.png';

        // Check if the thumbnail should be saved locally
        if (!empty($bctData['settings']['saveThumbnails'])) {

            // Get the video id out of the YouTube URL
            $videoId = [];
            preg_match('/(\.[a-z]{2,}\/)(embed\/|watch\?v=)?([a-zA-z0-9\-_]{1,})/', ContentBlocker::getInstance()->getCurrentURL(), $videoId);

            // Try to get the thumbnail from YouTube
            if (!empty($videoId[3])) {
                $thumbnail = $this->getThumbnail($videoId[3]);
            }
        }

        // Get the title which was maybe set via title-attribute in a shortcode
        $title = ContentBlocker::getInstance()->getCurrentTitle();

        // If no title was set use the Blocked Content Type name as title
        if (empty($title)) {
            $title = $bctData['name'];
        }

        // Replace text variables
        $bctData['previewHTML'] = str_replace(
            [
                '%%name%%',
                '%%thumbnail%%',
            ],
            [
                $title,
                $thumbnail
            ],
            $bctData['previewHTML']
        );

        return $bctData['previewHTML'];
    }

    /**
     * getThumbnail function.
     *
     * @access public
     * @param mixed $videoId
     * @return void
     */
    public function getThumbnail($videoId)
    {
        /*
            Plan B: https://www.googleapis.com/youtube/v3/videos?id={VIDEO_ID}&key={API_KEY}&part=snippet&fields=items/snippet/thumbnails
            Plan C: https://www.youtube.com/oembed?url=http%3A//youtube.com/watch%3Fv%3DM3r2XDceM6A&format=json
        */

        // Get settings of the Blocked Content Type
        $bctData = ContentBlocker::getInstance()->getDataOfBlockedContentType('youtube');

        // Default thumbnail in case a thumbnail can not be retrieved
        $thumbnailURL = BORLABS_COOKIE_PLUGIN_URL.'images/bct-no-thumbnail.png';;

        // Set a default thumbnail quality if no quality was defined (which should not happen...)
        $thumbnailQuality = 'hqdefault';

        // Overwrite the default thumbnail quality with the configured one
        if (!empty($bctData['settings']['thumbnailQuality'])) {
            $thumbnailQuality = $bctData['settings']['thumbnailQuality'];
        }

        // Path and filename of the requested thumbnail on the HDD
        $filename = ContentBlocker::getInstance()->getCacheFolder().'/'.$videoId.'_'.$thumbnailQuality.'.jpg';

        // URL of the requested thumbnail
        $webFilename = content_url().'/cache/borlabs_cookie/'.$videoId.'_'.$thumbnailQuality.'.jpg';

        // Check if thumbnail does not exist
        if (!file_exists($filename)) {

            // Only try to retrieve a thumbnail when the cache folder is writable
            if (is_writable(ContentBlocker::getInstance()->getCacheFolder())) {

                // Get image from YouTube in the requested quality
                $response = wp_remote_get('https://img.youtube.com/vi/'.$videoId.'/'.$thumbnailQuality.'.jpg');

                // Check if YouTube has the requested quality, if not it returns 404
                $httpStatus = wp_remote_retrieve_response_code($response);

                // If YouTube does not have the requested quality and the configured quality is not hqdefault try to get hqdefault
                if ($httpStatus === 404 && $thumbnailQuality !== 'hqdefault') {

                    // Get image from YouTube in hqdefault quality
                    $response = wp_remote_get('https://img.youtube.com/vi/'.$videoId.'/hqdefault.jpg');

                    // Update the http status code - if again 404 the default thumbnail will be used
                    $httpStatus = wp_remote_retrieve_response_code($response);
                }

                // Get the content-type, only jpeg is accepted
                $contentType = wp_remote_retrieve_header($response, 'content-type');

                if (!empty($response) && is_array($response) && $httpStatus === 200 && $contentType == 'image/jpeg') {

                    // Save thumbnail locally, in the case of the use of the fallback quality we do not change the filename
                    file_put_contents($filename, wp_remote_retrieve_body($response));

                    // Update the thumbnail URL
                    $thumbnailURL = $webFilename;
                }
            }
        } else {
            // Thumbnail is already saved locally
            $thumbnailURL = $webFilename;
        }

        return $thumbnailURL;
    }

    /**
     * additionalSettingsTemplate function.
     *
     * @access public
     * @param mixed $data
     * @return void
     */
    public function additionalSettingsTemplate($data)
    {
        $checkboxResponsiveIframe           = !empty($data->settings['responsiveIframe']) ? ' checked' : '';
        $checkboxSaveThumbnails             = !empty($data->settings['saveThumbnails']) ? ' checked' : '';

        $optionThumbnailQualityHQDefault    = !empty($data->settings['thumbnailQuality']) && $data->settings['thumbnailQuality'] === 'hqdefault' ? ' selected' : '';
        $optionThumbnailQualityMQDefault    = !empty($data->settings['thumbnailQuality']) && $data->settings['thumbnailQuality'] === 'mqdefault' ? ' selected' : '';
        $optionThumbnailQualitySDDefault    = !empty($data->settings['thumbnailQuality']) && $data->settings['thumbnailQuality'] === 'sddefault' ? ' selected' : '';
        $optionThumbnailQualityMaxResDefault= !empty($data->settings['thumbnailQuality']) && $data->settings['thumbnailQuality'] === 'maxresdefault' ? ' selected' : '';

        $checkboxChangeURLToNoCookie        = !empty($data->settings['changeURLToNoCookie']) ? ' checked' : '';
        ?>
        <div class="form-group">
            <div class="form-title"><?php _ex('Responsive Iframe', 'Setting title', 'borlabs-cookie'); ?></div>
            <div class="form-field">
                <label for="responsiveIframe">
                    <input<?php echo $checkboxResponsiveIframe; ?> type="checkbox" name="settings[responsiveIframe]" id="responsiveIframe" value="1"> <span class="option-title"><?php _ex('Activate', 'Setting checkbox', 'borlabs-cookie'); ?></span>
                </label>
                <span class="description"><?php _ex('The width and height will be replaced to get the iframe responsive.', 'Setting description', 'borlabs-cookie'); ?></span>
            </div>
        </div>

        <div class="form-group">
            <div class="form-title"><?php _ex('Save thumbnails locally', 'Setting title', 'borlabs-cookie'); ?></div>
            <div class="form-field">
                <label for="saveThumbnails">
                    <input<?php echo $checkboxSaveThumbnails; ?> type="checkbox" name="settings[saveThumbnails]" id="saveThumbnails" value="1"> <span class="option-title"><?php _ex('Activate', 'Setting checkbox', 'borlabs-cookie'); ?></span>
                </label>
                <span class="description"><?php _ex('Attempts to get the thumbnail of the YouTube video to save it locally. Your visitor\'s IP-address will not be transferred to YouTube during this process.', 'Setting description', 'borlabs-cookie'); ?></span>
            </div>
        </div>

        <div class="form-group">
            <div class="form-title"><?php _ex('Thumbnail size &amp; quality', 'Setting title', 'borlabs-cookie'); ?></div>
            <div class="form-field">
                <select name="settings[thumbnailQuality]" id="thumbnailQuality">
                    <option<?php echo $optionThumbnailQualityHQDefault; ?> value="hqdefault"><?php _ex('High Quality', 'Select option', 'borlabs-cookie'); ?></option>
                    <option<?php echo $optionThumbnailQualityMQDefault; ?> value="mqdefault"><?php _ex('Medium Quality', 'Select option', 'borlabs-cookie'); ?></option>
                    <option<?php echo $optionThumbnailQualitySDDefault; ?> value="sddefault"><?php _ex('Standard Quality', 'Select option', 'borlabs-cookie'); ?></option>
                    <option<?php echo $optionThumbnailQualityMaxResDefault; ?> value="maxresdefault"><?php _ex('Maximum Resolution', 'Select option', 'borlabs-cookie'); ?></option>
                </select>
                <span class="description"><?php _ex('<strong>High Quality</strong>: 480 x 360 px. This size is available in most cases.', 'Setting description', 'borlabs-cookie'); ?></span>
                <span class="description"><?php _ex('<strong>Medium Quality</strong>: 320 x 180 px.', 'Setting description', 'borlabs-cookie'); ?></span>
                <span class="description"><?php _ex('<strong>Standard Quality</strong>: 640 x 480 px.', 'Setting description', 'borlabs-cookie'); ?></span>
                <span class="description"><?php _ex('<strong>Maximum Resolution</strong>: 1280 x 720 px.', 'Setting description', 'borlabs-cookie'); ?></span>
                <span class="description"><?php _ex('If the thumbnail in the requested quality is not available the <strong>High Quality</strong> quality is used.', 'Setting description', 'borlabs-cookie'); ?></span>
            </div>
        </div>

        <div class="form-group">
            <div class="form-title"><?php _ex('Change URL to youtube-nocookie.com', 'Setting title', 'borlabs-cookie'); ?></div>
            <div class="form-field">
                <label for="changeURLToNoCookie">
                    <input<?php echo $checkboxChangeURLToNoCookie; ?> type="checkbox" name="settings[changeURLToNoCookie]" id="changeURLToNoCookie" value="1"> <span class="option-title"><?php _ex('Activate', 'Setting checkbox', 'borlabs-cookie'); ?></span>
                </label>
                <span class="description"><?php _ex('The YouTube URL of the iframe will be changed to www.youtube-nocookie.com.', 'Setting description', 'borlabs-cookie'); ?></span>
            </div>
        </div>
        <?php
    }
}
