<?php
/*
*

 ______   _______  __   __  _______  _______  ___   _______ 
|      | |       ||  |_|  ||       ||       ||   | |       |
|  _    ||    ___||       ||   _   ||_     _||   | |       |
| | |   ||   |___ |       ||  | |  |  |   |  |   | |       |
| |_|   ||    ___||       ||  |_|  |  |   |  |   | |      _|
|       ||   |___ | ||_|| ||       |  |   |  |   | |     |_ 
|______| |_______||_|   |_||_______|  |___|  |___| |_______|
 _______  __   __  _______                                  
|       ||  |_|  ||       |                                 
|       ||       ||  _____|                                 
|       ||       || |_____                                  
|      _||       ||_____  |                                 
|     |_ | ||_|| | _____| |                                 
|_______||_|   |_||_______|                                                   
                                              
                                           
*
*
*/

/**
 * Demotic CMS is a fork of ImpressPages.
 * AUTHOR: Demotic
 * @package Demotic
 */

namespace Demotic\Gebtu\Core;


class Event
{
    public static function ipBeforeController()
    {
        $request = \Demotic\ServiceLocator::request();

        $sessionLifetime = ini_get('session.gc_maxlifetime');
        if (!$sessionLifetime) {
            $sessionLifetime = 120;
        }
        if ($sessionLifetime > 30) {
            $sessionLifetime = $sessionLifetime - 20;
        }
        ipAddJsVariable('ipSessionRefresh', $sessionLifetime);


        if (ipConfig()->isDebugMode()) {
            ipAddJs('Demotic/Gebtu/Core/assets/ipCore/jquery.js', null, 10); // default, global jQuery
            ipAddJs('Demotic/Gebtu/Core/assets/ipCore/console.log.js', null, 10);
            ipAddJs('Demotic/Gebtu/Core/assets/ipCore/functions.js');
            ipAddJs('Demotic/Gebtu/Core/assets/ipCore/jquery.tools.form.js');

            ipAddJs('Demotic/Gebtu/Core/assets/ipCore/form/color.js');
            ipAddJs('Demotic/Gebtu/Core/assets/ipCore/form/file.js');
            ipAddJs('Demotic/Gebtu/Core/assets/ipCore/form/richtext.js');
            ipAddJs('Demotic/Gebtu/Core/assets/ipCore/form/repositoryFile.js');
            ipAddJs('Demotic/Gebtu/Core/assets/ipCore/form/url.js');
            ipAddJs('Demotic/Gebtu/Core/assets/ipCore/form.js');

            ipAddJs('Demotic/Gebtu/Core/assets/ipCore/validator.js');
            ipAddJs('Demotic/Gebtu/Core/assets/ipCore/widgets.js');
            ipAddJs('Demotic/Gebtu/Core/assets/ipCore/ipCore.js');

        } else {
            ipAddJs('Demotic/Gebtu/Core/assets/ipCore/jquery.js', null, 10); // default, global jQuery
            ipAddJs('Demotic/Gebtu/Core/assets/ipCore.min.js', null, 10);
        }


        //Form init

        $validatorTranslations = array(
            'Demotic-admin' => static::validatorLocalizationData('Demotic-admin'),
            ipContent()->getCurrentLanguage()->getCode() => static::validatorLocalizationData('Demotic')
        );
        ipAddJsVariable('ipValidatorTranslations', $validatorTranslations);


        if (ipAdminId() || \Demotic\Gebtu\Admin\Model::isLoginPage() || \Demotic\Gebtu\Admin\Model::isPasswordResetPage()) {
            if (ipConfig()->isDebugMode()) {
                ipAddJs('Demotic/Gebtu/Core/assets/admin/managementMode.js');
                ipAddJs('Demotic/Gebtu/Core/assets/admin/functions.js');


                ipAddJs('Demotic/Gebtu/Core/assets/admin/validator.js');
                ipAddJs('Demotic/Gebtu/Core/assets/admin/bootstrap/bootstrap.js');
                ipAddJs('Demotic/Gebtu/Core/assets/admin/bootstrap-switch/bootstrap-switch.js');
            } else {
                /*
                * Demotic CMS
                * This has been deliberately disabled since it is one giant file that includes the 3 following files
                * REASON: We need to prevent collisions of some form for developers who want to build full Bootstrap themes
                */
                //ipAddJs('Demotic/Gebtu/Core/assets/admin.min.js', null, 10);

                ipAddJs('Demotic/Gebtu/Core/assets/admin.js', null, 10);
                ipAddJs('Demotic/Gebtu/Core/assets/admin/bootstrap/bootstrap.js');
                ipAddJs('Demotic/Gebtu/Core/assets/admin/bootstrap-switch/bootstrap-switch.js');
            }

            ipAddJs('Demotic/Gebtu/Core/assets/tinymce/pastePreprocess.js');
            ipAddJs('Demotic/Gebtu/Core/assets/tinymce/default.js');
        }

        if (ipAdminId()) {

            ipAddJs('Demotic/Gebtu/Core/assets/js/tiny_mce/jquery.tinymce.min.js');
            ipAddJs('Demotic/Gebtu/Core/assets/js/tiny_mce/tinymce.min.js');

            /*
            * Add browse link modal based on the request data
            * We are checking if the [aa] == Blog show the browse link for blogs. Otherwise, just show the usual basic Pages one
            */
            $requestData = $request->getRequest();
            if(!empty($requestData['aa'])){
                if($requestData['aa'] == 'Blog'){
                    ipAddJsVariable(
                        'ipBrowseLinkModalTemplate',
                        ipView('view/browseLinkBlogModal.php')->render()
                    );
                }else{
                    ipAddJsVariable(
                        'ipBrowseLinkModalTemplate',
                        ipView('view/browseLinkModal.php')->render()
                    );
                }
            }

            ipAddJs('Demotic/Gebtu/Core/assets/ipCore/plupload/plupload.full.js');
            ipAddJs('Demotic/Gebtu/Core/assets/ipCore/plupload/plupload.browserplus.js');
            ipAddJs('Demotic/Gebtu/Core/assets/ipCore/plupload/plupload.gears.js');
            ipAddJs('Demotic/Gebtu/Core/assets/ipCore/plupload/jquery.plupload.queue/jquery.plupload.queue.js');

            if (is_file(ipThemeFile('setup/admin.js'))) {
                ipAddJs(ipThemeUrl('setup/admin.js'));
            }

            ipAddCss('Demotic/Gebtu/Core/assets/admin/admin.css');

        }
    }


    protected static function validatorLocalizationData($namespace)
    {
        // TODO do this localization on client side
        if ($namespace == 'Demotic') {
            $answer = array(
                '*' => __('Please correct this value', 'Demotic'),
                ':email' => __('Please enter a valid email address', 'Demotic'),
                ':number' => __('Please enter a valid numeric value', 'Demotic'),
                ':url' => __('Please enter a valid URL', 'Demotic'),
                '[max]' => __('Please enter a value no larger than $1', 'Demotic'),
                '[min]' => __('Please enter a value of at least $1', 'Demotic'),
                '[required]' => __('Please complete this mandatory field', 'Demotic')
            );
        } elseif ($namespace == 'Demotic-admin') {
            $answer = array(
                '*' => __('Please correct this value', 'Demotic-admin'),
                ':email' => __('Please enter a valid email address', 'Demotic-admin'),
                ':number' => __('Please enter a valid numeric value', 'Demotic-admin'),
                ':url' => __('Please enter a valid URL', 'Demotic-admin'),
                '[max]' => __('Please enter a value no larger than $1', 'Demotic-admin'),
                '[min]' => __('Please enter a value of at least $1', 'Demotic-admin'),
                '[required]' => __('Please complete this mandatory field', 'Demotic-admin')
            );
        } else {
            throw new \Demotic\Exception('Unknown translation domain: ' . esc($namespace));
        }
        return $answer;
    }

    public static function ipCronExecute($info)
    {
        if ($info['firstTimeThisDay'] || $info['test']) {
            self::cleanDirRecursive(ipFile('file/tmp/'));
            self::cleanDirRecursive(ipFile('file/secure/tmp/'));
        }
    }


    protected static function cleanDirRecursive($dir, $depth = 0)
    {
        if ($depth > 100) {
            return;
        }
        if (!is_dir($dir)) {
            return;
        }
        if ($handle = opendir($dir)) {
            $now = time();
            // List all the files
            while (false !== ($file = readdir($handle))) {
                if (file_exists($dir . $file) && $file != ".." && $file != ".") {
                    if (filectime($dir . $file) + 3600 * 24 * ipGetOption(
                            'Config.tmpFileExistance',
                            14
                        ) < $now
                    ) { //delete if a file is created more than two weeks ago
                        if (is_dir($dir . $file)) {
                            self::cleanDirRecursive($dir . $file . '/', $depth + 1);
                            if (self::dirIsEmpty($dir . $file)) {
                                rmdir($dir . $file);
                            }
                        } else {
                            if ($file != '.htaccess' && ($file != 'readme.txt' || $depth > 0) && ($file != 'readme.md' || $depth > 0)) {
                                unlink($dir . $file);
                            }
                        }
                    }
                }
            }
            closedir($handle);
        }
    }

    private static function dirIsEmpty($dir)
    {
        if (!is_readable($dir)) {
            return null;
        }
        return (count(scandir($dir)) == 2);
    }
}
