<?php
/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * 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, see <http://www.gnu.org/licenses/>.
 */
/**
 * @category     template
 * @package      template_DefaultTheme
 * @copyright    Manuela v.d.Decken <manuela@isteam.de>
 * @author       Manuela v.d.Decken <manuela@isteam.de>
 * @license      http://www.gnu.org/licenses/gpl.html
 * @revision     $Revision: 2 $
 * @lastmodified $Date: 2017-07-02 17:14:29 +0200 (Sun, 02 Jul 2017) $
 * @since        File available since 25.02.2017
 * @deprecated   no / since 0000/00/00
 * @description
 */
// -----------------------------------------------------------------------------

/**
 * delete directory tree
 * @param string $sBasedir  the absolute path including a trailing slash
 * @param bool   $bRemoveBasedir  (default) true = remove base directory || false = preserve it
 * @throws Exception
 * @descripion deletes a tree recursively from given basedir
 */
    function rebuildAccessFiles_delTree($sBasedir, $bRemoveBasedir = true)
    {
        $aSubDirs = glob($sBasedir.'*', GLOB_MARK|GLOB_ONLYDIR);
        foreach ($aSubDirs as $sSubDir) {
            rebuildAccessFiles_delTree($sSubDir, true);
        }
        array_map(
            function ($sFile) {
                if (!@unlink($sFile)) { throw new Exception('delTree: Unable to delete file'); }
            },
            glob($sBasedir.'*')
        );
        if ($bRemoveBasedir) {
            if (!rmdir($sBasedir)) { throw new Exception('delTree: Unable to remove directory'); }
        }
    }
// -----------------------------------------------------------------------------
/**
 * check if file is an access file
 * @param string $sFileName
 * @return bool
 * @throws Exception
 */
    function rebuildAccessFiles_isAccessFile($sFileName)
    {
        $bRetval = false;
        if (file_exists($sFileName)) {
            if (!is_readable($sFileName)) { throw new Exception('invalid filename ['.basename($sFileName).']'); }
            if (($sFile = file_get_contents($sFileName)) !== false) {
            // test content of this file
                $sPattern = '/^\s*?<\?php.*?\$i?page_?id\s*=\s*[0-9]+;.*?(?:require|include)'
                          . '(?:_once)?\s*\(\s*\'.*?index\.php\'\s?\);/siU';
                $bRetval = (bool) preg_match($sPattern, $sFile);
                unset($sFile);
            }
        }
        return $bRetval;
    }
// -----------------------------------------------------------------------------
// direct access code
// -----------------------------------------------------------------------------
    if (!defined('WB_PATH')) { require (dirname(dirname(dirname(__DIR__)))).'/config.php'; }
    $aJsonRespond = [];
    try {
    // check autentification
        if (!class_exists('admin', false)) { require(WB_PATH.'/framework/class.admin.php'); }
        $admin = new admin('Pages', 'pages_settings',false);
        if (!$admin->is_authenticated() || $admin->get_user_id() != 1) {
            throw new Exception('Access denied');
        }
        $iFilesCreated = 0;
    // Find all active Level 0 pages and delete the files and possible related directories
        $sql = 'SELECT `link` FROM `'.TABLE_PREFIX.'pages` WHERE `level`= 0';
        if (($oPages = $database->query($sql))) {
            while (($aPage = $oPages->fetchRow(MYSQLI_ASSOC))) {
            // santize path
                $sAccessDir = str_replace('\\', '/', WB_PATH.PAGES_DIRECTORY.$aPage['link']);
                $sAccessFile = $sAccessDir.PAGE_EXTENSION;
            // test if file is really an access file
                if (rebuildAccessFiles_isAccessFile($sAccessFile)) {
                // delete the subdir and it's content if exists
                    if (file_exists($sAccessDir.'/')) { rebuildAccessFiles_delTree($sAccessDir.'/'); }
                // delete the current accessfile
                    if (!@unlink($sAccessFile)) { throw new Exception('Unable to delete file'); }
                }
            }
        }
    // get all pages from database
        $sql = 'SELECT `page_id`, `link`, `level` FROM `'.TABLE_PREFIX.'pages` '
             . 'ORDER BY `link`';
        if (!($oPages = $database->query($sql))) { throw new Exception('Database access failed'); }
        while (($aPage = $oPages->fetchRow(MYSQLI_ASSOC))) {
            $sFilePath = WB_PATH.PAGES_DIRECTORY.$aPage['link'].PAGE_EXTENSION;
            $sDirPath = dirname($sFilePath).'/';
            if (!is_dir($sDirPath)) {
                // create missing directory
                if (!mkdir($sDirPath)) { throw new Exception('Unable to create new directory'); }
                if (OPERATING_SYSTEM == 'linux') { chmod($sDirPath, OCTAL_DIR_MODE); }
            }
            $iRepeats = preg_match_all('/\//', PAGES_DIRECTORY) + $aPage['level'];
            $sIndexLocation = str_repeat('../', $iRepeats);
            $sContent =
                '<?php'."\n".
                '// *** This file is generated by WebsiteBaker Ver.'.VERSION."\n".
                '// *** Creation date: '.date('c')."\n".
                '// *** Do not modify this file manually'."\n".
                '// *** WB will rebuild this file from time to time!!'."\n".
                '// *************************************************'."\n".
                "\t".'$page_id    = '.$aPage['page_id'].';'."\n".
                "\t".'require(\''.$sIndexLocation.'index.php\');'."\n".
                '// *************************************************'."\n";
            if (file_put_contents($sFilePath, $sContent) === false) {
                throw new Exception('Unable to write new file');
            }
            if (OPERATING_SYSTEM == 'linux') { chmod($sFilePath, OCTAL_FILE_MODE); }
            $iFilesCreated++;
        }
        $aJsonRespond['message'] = 'Rebuild done:: '.$iFilesCreated.' access files created';
        $aJsonRespond['success'] = true;
    } catch (Exception $e) {
        $aJsonRespond['message'] = 'Rebuild failed:: '.$e->getMessage().'!';
        $aJsonRespond['success'] = false;
    }
    // echo the json_respond to the ajax function
    exit(json_encode($aJsonRespond));
