/home/coolpkct/www/websites/cake3.cool.rocks/admin/classes/importer.php
<?php
/**
 * Part of Showkase web site management package
 *
 * @package Showkase
 * @author Jack Hardie {@link http://www.jhardie.com}
 * @copyright Copyright (c) 2014, SimpleViewer Inc.
 */
defined('SK_ACCESS')||die('<h1>403: Forbidden</h1>');
$ds = DIRECTORY_SEPARATOR;
require_once "classes{$ds}pageset.php";
require_once "classes{$ds}pagereader.php";
require_once "classes{$ds}helpers.php";
require_once "classes{$ds}filer.php";
require_once "classes{$ds}urlify.php";
require_once "classes{$ds}themeset.php";
require_once "classes{$ds}theme.php";
require_once "classes{$ds}pagefactory.php";
require_once "classes{$ds}pathparser.php";
 
/**
 * Pages data repair
 *
 * @package Showkase
 */
class Importer
{
    /**
     * @var object instance of SkConfig
     */
    private $config;
    
    /**
     * @var object instance of PathParser
     */
    private $pathParser;
    
    /**
     * @var array data from page.xml files
     */
    private $pagesData = array();
    
    /**
     * @var integer maximum page ref found in page.xml files
     */
    private $maxRef = 0;
    
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->config = SkConfig::getInstance();
        $this->pathParser = new PathParser();
    }
    
    /**
     * Scan directories for web pages
     *
     * @return array
     */
    public function scan($importPath)
    {
        $scanData = array();
        $absContentPath = $this->config->getAbsoluteContentPath();
        $importPath =
            str_replace(
                array('\\', '/'),
                DIRECTORY_SEPARATOR,
		            trim($importPath)
		        );
		    if (strpos($importPath, DIRECTORY_SEPARATOR) === 0) {
		        $importPath =
		            DIRECTORY_SEPARATOR.
		            trim($importPath, '\\/');
		        // calculate doc root from known paths rather than rely on server setup
		        // may not work for paths with symlinks user must use relative path
		        $docRoot = substr(
		            $absContentPath,
		            0,
		            0-strlen(
		                $this->config->getDocRootRelativeContentPath()
		            )
		        );
		        $absImportPath = rtrim($docRoot.$importPath, '\\/').DIRECTORY_SEPARATOR;
		    } else {
		        // PathParser::fix always returns forward slashes
		        $absImportPath = str_replace(
                '/',
                DIRECTORY_SEPARATOR,
                $this->pathParser->fix(
                    $absContentPath.$importPath
                )
            );
		    }
		    if (!is_dir($absImportPath)) {
			      throw new Exception('Cannot find directory '.$absImportPath);
		    }
        $dirs = glob($absImportPath.'*');
        foreach ($dirs as $key=>$dirPath) {
            if (!is_dir($dirPath)) continue;
            if ($dirPath == getcwd()) continue;
            $dir = basename($dirPath);
            if (
                $dir != '_trash'
                && $dir[0] == '_'
            ) continue;
            switch (true) {
                case (file_exists($dirPath.DIRECTORY_SEPARATOR.'page.xml')) :
                    $xmlData = PageReader::readPageVars($dirPath.DIRECTORY_SEPARATOR.'page.xml');
                    if (!isset($xmlData['ss_pageType'])) continue;
                    $scanData[$key]['type'] = $xmlData['ss_pageType'];  
                    break;
                case (is_dir($dirPath.DIRECTORY_SEPARATOR.'jbcore')) :
                    $scanData[$key]['type'] = 'juicebox';
                    break;
                case (is_dir($dirPath.DIRECTORY_SEPARATOR.'svcore')) :
                    $scanData[$key]['type'] = 'simpleviewer';
                    break;
                default:
                    continue(2);
            }
            $scanData[$key]['path'] = $dirPath;
            $scanData[$key]['name'] = $dir;
            $scanData[$key]['valid'] = Helpers::checkUrl($dir);
        }
        return $scanData;
    }
    
    /**
     * import pages and galleries
     *
     * @param array directory scan results
     * @return void
     */
    public function import(array $scanData, PageSet $pageSet, PageFactory $pageFactory, Nav $nav, GalleryIndex $galleryIndex)
    {
        $absContentPath = rtrim($this->config->getAbsoluteContentPath(), '\\/').DIRECTORY_SEPARATOR;
        $relContentPath = $this->config->getRelativeContentPath(getcwd());
        $nextRef = $pageSet->nextPageRef();
        $count = 0;
        foreach ($scanData as $key=>$dir) {
            $folder = preg_replace('/-\d{10}$/', '', $dir['name']); // remove timestamp
            $navName = empty($folder)
                ? 'Page'
                : $folder;
            $folder = URLify::transliterate($folder); //URLify::filter is unreliable
            $folder = Helpers::slugFolder($folder);
            $suffix = '';
            $nameSuffix = '';
            if (strlen($folder) == 0) {
                $folder     = 'page';
                $suffix     = '-1';
                $nameSuffix = ' 1';
            }
            $i = 1;
            while (
                file_exists(
                    $pagePathRelSvm = $relContentPath.$folder.$suffix.DIRECTORY_SEPARATOR)
            ) {
                $i++;
                $suffix     = '-'.$i;
                $nameSuffix = ' '.$i;
            }
            $navName .= $nameSuffix;
            $failures = Filer::rCopy($dir['path'], $pagePathRelSvm, NEW_DIR_MODE, NEW_FILE_MODE);
            if ($failures > 0) {
                Board::addMessage('Failed to copy gallery folder '.$fileName);
                continue;
            }
            if ($navName == '') {
                $navName = $folder;
            }
            $page = $pageFactory->make($dir['type'], $nextRef, $pagePathRelSvm);
            // set nav name to $dir['name']
            $page->setNavName($navName);
            $page->setNavWeight($nextRef);
            $page->setParentPage(0);
            $page->setNavShow(true);
            $page->setIndexShow(true);
            $page->importGallery();
            $page->saveLayer();
            if ($page->isGallery()) {
                $page->gallery->saveGallery();
            }
            $pageSet->addPagesDataRecord($page);
            $page->savePageHtml($nav, $galleryIndex);
            $count++;
            $nextRef++;
        }
        $pageSet->savePagesData();
        if ($count > 0) {
            $pageSet->setPagesPref('publishing', 'unpublished');
        }
        $pageSet->savePagesPrefs();
        Board::addMessage('Pages imported: '.$count, 'notice');
    }
    
}