public static function handleTreeRequest($rootNode = null)
 {
     set_time_limit(1800);
     $rootPath = $rootNode ? $rootNode->getFullPath(null, false) : null;
     $collectionConditions = array();
     $fileConditions = array();
     // process excludes
     if (!empty($_REQUEST['exclude']) && method_exists('Emergence_FS', 'getNodesFromPattern')) {
         $excludes = is_array($_REQUEST['exclude']) ? $_REQUEST['exclude'] : array($_REQUEST['exclude']);
         $excludedCollections = array();
         $excludedFiles = array();
         foreach (Emergence_FS::getNodesFromPattern($excludes) as $node) {
             if ($node->Class == 'SiteCollection') {
                 $excludedCollections[] = $node->ID;
             } else {
                 $excludedFiles[] = $node->ID;
             }
         }
         if (count($excludedCollections)) {
             $collectionConditions['excludeTrees'] = $excludedCollections;
         }
         if (count($excludedFiles)) {
             $fileConditions[] = 'ID NOT IN (' . implode(',', $excludedFiles) . ')';
         }
     }
     // get files
     $files = Emergence_FS::getTreeFiles($rootPath, false, $fileConditions, $collectionConditions);
     header('HTTP/1.1 300 Multiple Choices');
     header('Content-Type: application/vnd.emergence.tree+json');
     print json_encode(array('total' => count($files), 'files' => $files));
     exit;
 }
 public static function handleRequest()
 {
     $GLOBALS['Session']->requireAccountLevel('Developer');
     \Emergence_FS::cacheTree('site-root/site-admin');
     return static::respond('siteAdminIndex', array('scripts' => array_filter(\Emergence_FS::getAggregateChildren('site-root/site-admin'), function ($script) {
         return $script->Handle != '_index.php';
     })));
 }
 public static function handleClassesRequest()
 {
     // discover activerecord classes
     $recordClasses = array();
     foreach (Emergence_FS::findFiles('\\.php$', true, 'php-classes') as $classNode) {
         if ($classNode->Type != 'application/php') {
             continue;
         }
         $classPath = $classNode->getFullPath(null, false);
         array_shift($classPath);
         $className = preg_replace('/(\\.class)?\\.php$/i', '', join('\\', $classPath));
         foreach (static::$classFilters as $pattern) {
             if (preg_match($pattern, $className)) {
                 continue 2;
             }
         }
         if (is_subclass_of($className, 'ActiveRecord') && !in_array($className, $recordClasses)) {
             $recordClasses[] = $className;
         }
     }
     natsort($recordClasses);
     return static::respond('classes', array('classes' => $recordClasses));
 }
    die('Parameter framework required');
}
$framework = $_REQUEST['framework'];
Benchmark::mark("configured request: framework={$framework}");
// get temporary directory
$tmpPath = Emergence_FS::getTmpDir();
Benchmark::mark("created tmp: {$tmpPath}");
// write workspace
$workspacePath = 'sencha-workspace';
Benchmark::mark("precaching workspace: {$workspacePath}");
$cachedFiles = Emergence_FS::cacheTree($workspacePath);
Benchmark::mark("precaching finished: {$cachedFiles} files loaded/updated");
Benchmark::mark("exporting workspace: {$workspacePath} to {$tmpPath}");
$exportResult = Emergence_FS::exportTree($workspacePath, $tmpPath);
Benchmark::mark("exported finished: " . http_build_query($exportResult));
// begin cmd
set_time_limit(0);
$cmd = Sencha::buildCmd($framework, 'generate workspace', $tmpPath);
Benchmark::mark("running CMD: {$cmd}");
passthru($cmd, $cmdStatus);
Benchmark::mark("CMD finished: exitCode={$cmdStatus}");
// import app
if ($cmdStatus == 0) {
    $destPath = 'sencha-workspace';
    Benchmark::mark("importing to: {$destPath}");
    $filesImported = Emergence_FS::importTree($tmpPath, $destPath);
    Benchmark::mark("imported {$filesImported} files");
}
// clean up
exec("rm -R {$tmpPath}");
Benchmark::mark("erased {$tmpPath}");
Exemple #5
0
if (empty($_GET['suite'])) {
    ?>
        <h1>Available PHPUnit Test Suites</h1>
        <ul>
        <?php 
    Emergence_FS::cacheTree('phpunit-tests');
    foreach (Emergence_FS::getAggregateChildren('phpunit-tests') as $testsSubNode) {
        if (!is_a($testsSubNode, 'SiteCollection')) {
            continue;
        }
        print "<li><a href='?suite={$testsSubNode->Handle}'>{$testsSubNode->Handle}</a> <form action='/phpunit/run?suite={$testsSubNode->Handle}' method='POST' style='display:inline'><input type='submit' value='Run All Tests'></form></li>";
    }
    ?>
        </ul>
    <?php 
} elseif (count($testNodes = Emergence_FS::getAggregateChildren("phpunit-tests/{$_GET['suite']}"))) {
    ?>
        <h1>Tests in suite <?php 
    echo htmlspecialchars($_GET['suite']);
    ?>
</h1>
        <form action="/phpunit/run?suite=<?php 
    echo urlencode($_GET['suite']);
    ?>
"" method='POST'>
            <input type='submit' value='Run All Tests'>
        </form>
        <ul>
        <?php 
    foreach ($testNodes as $testNode) {
        if (is_a($testNode, 'SiteCollection')) {
function Dwoo_Plugin_sencha_preloader(Dwoo_Core $dwoo, $classes = "app", $App = null)
{
    if (!$App) {
        $App = $dwoo->data['App'];
    }
    $appName = $App->getName();
    $appPath = "sencha-workspace/{$appName}";
    // include classpath files
    $classPaths = explode(',', $App->getBuildCfg('app.classpath'));
    $srcCollections = array();
    foreach ($classPaths as $classPath) {
        if (strpos($classPath, '${workspace.dir}/x/') === 0) {
            $classPath = 'ext-library/' . substr($classPath, 19);
        } elseif (substr($classPath, 0, 11) == '${app.dir}/') {
            $classPath = $appPath . substr($classPath, 10);
        } else {
            continue;
        }
        try {
            $tree = Emergence_FS::getTree($classPath);
            $srcCollections = array_merge($srcCollections, array_keys($tree));
        } catch (Exception $e) {
            continue;
        }
    }
    // include package files
    $requiredPackages = $App->getAppCfg('requires');
    if (!is_array($requiredPackages)) {
        $requiredPackages = array();
    }
    if (($themeName = $App->getBuildCfg('app.theme')) && !in_array($themeName, $requiredPackages)) {
        $requiredPackages[] = $themeName;
    }
    foreach ($requiredPackages as $packageName) {
        $packagePath = "sencha-workspace/packages/{$packageName}";
        foreach (array("{$packagePath}/src", "{$packagePath}/overrides") as $classPath) {
            try {
                $tree = Emergence_FS::getTree($classPath);
                $srcCollections = array_merge($srcCollections, array_keys($tree));
            } catch (Exception $e) {
                continue;
            }
        }
    }
    #	Benchmark::startLive();
    #	Benchmark::mark("sencha_preload");
    #	Benchmark::mark("getting files from ".count($srcCollections)." collections");
    // get files
    if (count($srcCollections)) {
        $sources = DB::allRecords('SELECT' . ' f2.SHA1' . ',CONCAT(' . '(' . 'SELECT GROUP_CONCAT(parent.Handle ORDER BY parent.PosLeft SEPARATOR "/")' . ' FROM `%2$s` AS node, `%2$s` AS parent' . ' WHERE node.PosLeft BETWEEN parent.PosLeft AND parent.PosRight AND node.ID = f2.CollectionID' . ')' . ',"/"' . ',f2.Handle' . ') AS Path' . ' FROM (' . ' SELECT MAX(f1.ID) AS ID' . ' FROM `%1$s` f1' . ' WHERE CollectionID IN (%3$s)' . ' GROUP BY f1.CollectionID, f1.Handle' . ') AS lastestFiles' . ' LEFT JOIN `%1$s` f2 USING (ID)' . ' WHERE f2.Status = "Normal" AND f2.Type = "application/javascript"', array(SiteFile::$tableName, SiteCollection::$tableName, join(',', $srcCollections)));
    } else {
        $sources = array();
    }
    // compile keyed manifest with localized paths
    $manifest = array();
    foreach ($sources as $source) {
        if (strpos($source['Path'], "{$appPath}/") === 0) {
            $manifest[substr($source['Path'], strlen($appPath) + 1)] = $source['SHA1'];
        } elseif (strpos($source['Path'], 'ext-library/') === 0) {
            $manifest["/app/{$appName}/x" . substr($source['Path'], 11)] = $source['SHA1'];
        } elseif (strpos($source['Path'], 'sencha-workspace/packages/') === 0) {
            $manifest['../' . substr($source['Path'], 17)] = $source['SHA1'];
        }
    }
    #	$srcMasterHash = sha1(join(PHP_EOL, $srcHashes));
    #
    #	Benchmark::mark("found ".count($srcHashes)." files");
    #
    #	// try to get src from cache
    #	$cacheKey = "app-cache/$srcMasterHash";
    #
    #	if(!Cache::exists($cacheKey)) {
    #		$src = '';
    #
    #		foreach($srcHashes AS $fileId => $sha1) {
    #			$src .= JSMin::minify(file_get_contents(SiteFile::getRealPathByID($fileId)));
    #		}
    #
    #		Cache::store($cacheKey, $src);
    #	}
    #
    #	Benchmark::mark("compiled: ".strlen($src)." bytes");
    #
    //getRealPathByID
    return '<script type="text/javascript">(function(){' . 'var srcManifest = ' . json_encode($manifest) . ',origLoadScript = Ext.Loader.loadScript' . ',origLoadScriptFile = Ext.Loader.loadScriptFile' . ',dcParam = Ext.Loader.getConfig("disableCachingParam")' . ',now = Ext.Date.now();' . 'function _versionScriptUrl(url) {' . 'if(url in srcManifest) {' . 'url += "?_sha1=" + srcManifest[url];' . '} else {' . 'url += "?" + dcParam + "=" + now;' . '}' . 'return url;' . '}' . 'Ext.Loader.setConfig("disableCaching", false);' . 'Ext.Loader.loadScript = function(options) {' . 'if (typeof options == "string") {' . 'options = _versionScriptUrl(options);' . '} else {' . 'options.url = _versionScriptUrl(options.url);' . '}' . 'origLoadScript.call(Ext.Loader, options);' . '};' . 'Ext.Loader.loadScriptFile = function(url, onLoad, onError, scope, synchronous) {' . 'origLoadScriptFile.call(Ext.Loader, _versionScriptUrl(url), onLoad, onError, scope, synchronous);' . '};' . '})()</script>';
}
Exemple #7
0
 public static function loadConfig($className)
 {
     $cacheKey = 'class-config:' . $className;
     if (!($configFileIds = Cache::fetch($cacheKey))) {
         $configFileIds = array();
         // look for primary config file
         if ($lastNsPos = strrpos($className, '\\')) {
             $namespace = substr($className, 0, $lastNsPos);
             $className = substr($className, $lastNsPos + 1);
             $path = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
         } else {
             $path = '';
         }
         $path .= str_replace('_', DIRECTORY_SEPARATOR, $className);
         $configFileNode = Site::resolvePath("php-config/{$path}.config.php");
         // Fall back on looking for Old_School_Underscore_Namespacing in root
         if (!$configFileNode && empty($namespace) && $path != $className) {
             $configFileNode = Site::resolvePath("php-config/{$className}.config.php");
         }
         if ($configFileNode && $configFileNode->MIMEType == 'application/php') {
             $configFileIds[] = $configFileNode->ID;
         }
         // look for composite config files
         $collectionPath = "php-config/{$path}.config.d";
         Emergence_FS::cacheTree($collectionPath);
         foreach (Emergence_FS::getAggregateChildren($collectionPath) as $filename => $node) {
             if ($node->Type == 'application/php') {
                 $configFileIds[] = $node->ID;
             }
         }
         Cache::store($cacheKey, $configFileIds);
     }
     foreach ($configFileIds as $id) {
         require SiteFile::getRealPathByID($id);
     }
 }
    exec($cmd);
    header('Content-Type: application/x-bzip-compressed-tar');
    header('Content-Disposition: attachment; filename="' . $appName . '.' . date('Y-m-d') . '.tbz"');
    chdir($tmpPath);
    passthru("tar -cjf - ./");
    exec("rm -R {$tmpPath}");
    exit;
} else {
    passthru("{$cmd} 2>&1", $cmdStatus);
}
Benchmark::mark("CMD finished: exitCode={$cmdStatus}");
// import build
if ($cmdStatus == 0) {
    Benchmark::mark("importing {$buildTmpPath}");
    $importResults = Emergence_FS::importTree($buildTmpPath, "sencha-build/{$appName}/{$buildType}", array('exclude' => $defaultExclude));
    Benchmark::mark("imported files: " . http_build_query($importResults));
    if ($framework == 'ext') {
        Emergence_FS::importFile("{$appTmpPath}/bootstrap.js", "{$appPath}/bootstrap.js");
        Benchmark::mark("imported bootstrap.js");
    }
    if (!empty($_GET['archive'])) {
        Benchmark::mark("importing {$archiveTmpPath} to {$archivePath}");
        $importResults = Emergence_FS::importTree($archiveTmpPath, $archivePath);
        Benchmark::mark("imported files: " . http_build_query($importResults));
    }
}
// clean up
if (empty($_GET['leaveWorkspace'])) {
    exec("rm -R {$tmpPath}");
    Benchmark::mark("erased {$tmpPath}");
}
Exemple #9
0
// get requested test suite
$testSuite = empty($_GET['suite']) ? 'emergence.read-only' : $_GET['suite'];
// set paths
$testsPath = "phpunit-tests";
$suitePath = "{$testsPath}/{$testSuite}";
if (!Site::resolvePath($suitePath)) {
    die('Requested test suite not found');
}
// get temporary directory and set paths
$tmpPath = Emergence_FS::getTmpDir();
$suiteTmpPath = "{$tmpPath}/{$testSuite}";
$configTmpPath = "{$tmpPath}/phpunit.xml";
Benchmark::mark("created tmp: {$tmpPath}");
// export tests
Emergence_FS::cacheTree($suitePath);
$exportResult = Emergence_FS::exportTree($suitePath, $suiteTmpPath);
Benchmark::mark("exported {$suitePath} to {$suiteTmpPath}: " . http_build_query($exportResult));
// write phpunit configuration
$timezone = date_default_timezone_get();
// bootstrap path
$bootstrapPath = dirname($_SERVER['SCRIPT_FILENAME']) . '/phpunit.php';
file_put_contents($configTmpPath, <<<EOT
<?xml version="1.0" encoding="UTF-8" ?>
<phpunit bootstrap="{$bootstrapPath}"
         convertErrorsToExceptions="false"
         convertNoticesToExceptions="false"
         convertWarningsToExceptions="false"
         stopOnError="false">
    <php>
        <ini name="date.timezone" value="{$timezone}" />
\t\t<server name="SITE_ROOT" value="{$_SERVER['SITE_ROOT']}" />
Benchmark::mark("precached {$appPath}");
$exportResult = Emergence_FS::exportTree($appPath, $appTmpPath);
Benchmark::mark("exported {$appPath} to {$appTmpPath}: " . http_build_query($exportResult));
// write any libraries from classpath
$classPaths = explode(',', $App->getBuildCfg('app.classpath'));
foreach ($classPaths as $classPath) {
    if (substr($classPath, 0, 2) == 'x/') {
        $classPathSource = 'ext-library' . substr($classPath, 1);
        $cachedFiles = Emergence_FS::cacheTree($classPathSource);
        Benchmark::mark("precached {$cachedFiles} files from {$classPathSource}");
        $exportResult = Emergence_FS::exportTree($classPathSource, "{$appTmpPath}/{$classPath}");
        Benchmark::mark("exported {$classPathSource} to {$appTmpPath}/{$classPath}: " . http_build_query($exportResult));
    }
}
// change into app's directory
chdir($appTmpPath);
Benchmark::mark("chdir to: {$appTmpPath}");
// prepare and run upgrade command
$upgradeCmd = Sencha::buildCmd($cmdVersion, 'app upgrade --noframework');
Benchmark::mark("running upgrade CMD: {$upgradeCmd}");
passthru($upgradeCmd, $upgradeCmdStatus);
Benchmark::mark("Upgrade CMD finished: exitCode={$upgradeCmdStatus}");
// import results
Benchmark::mark("importing {$appTmpPath}");
$importResults = Emergence_FS::importTree($appTmpPath, $appPath, array('exclude' => array("#^/x(/|\$)#", "#/\\.sass-cache(/|\$)#", "#/\\.sencha-backup(/|\$)#", "#/\\.emergence(/|\$)#")));
Benchmark::mark("imported files: " . http_build_query($importResults));
// clean up
if (empty($_GET['leaveWorkspace'])) {
    exec("rm -R {$tmpPath}");
    Benchmark::mark("erased {$tmpPath}");
}
            copy($sourceNode->RealPath, $classPathDest);
            Benchmark::mark("copied file {$classPathSource} to {$classPathDest}");
        } else {
            $exportResult = Emergence_FS::exportTree($classPathSource, $classPathDest);
            Benchmark::mark("exported {$classPathSource} to {$classPathDest}: " . http_build_query($exportResult));
        }
    }
}
// generate docs
$cmd = "jsduck {$srcTmpPath}";
if ($guideJson) {
    $cmd .= " --guides {$appGuidesTmpPath}.json";
}
$cmd .= " --title=\"{$appName} Documentation\"";
$cmd .= " --warnings=-link,-extend,-type_name,+no_doc";
$cmd .= " --output {$docsTmpPath} 2>&1";
Benchmark::mark("running jsduck: {$cmd}");
passthru($cmd, $cmdStatus);
Benchmark::mark("CMD finished: exitCode={$cmdStatus}");
// import build
if ($cmdStatus == 0) {
    $buildTmpPath = "{$tmpPath}/build";
    Benchmark::mark("importing {$docsTmpPath} to {$docsPath}");
    $importResults = Emergence_FS::importTree($docsTmpPath, $docsPath);
    Benchmark::mark("imported files: " . http_build_query($importResults));
}
// clean up
if (empty($_GET['leaveWorkspace'])) {
    exec("rm -R {$tmpPath}");
    Benchmark::mark("erased {$tmpPath}");
}
<?php

$GLOBALS['Session']->requireAccountLevel('Developer');
set_time_limit(0);
Benchmark::startLive();
foreach (Sencha::$frameworks as $framework => $frameworkConfig) {
    $cachedFiles = Emergence_FS::cacheTree("sencha-workspace/{$framework}-{$frameworkConfig['defaultVersion']}");
    Benchmark::mark("precached sencha-workspace/{$framework}-{$frameworkConfig['defaultVersion']}");
}
// precache workspace config
$cachedFiles = Emergence_FS::cacheTree('sencha-workspace/.sencha');
Benchmark::mark("precached sencha-workspace/.sencha");
<?php

$GLOBALS['Session']->requireAccountLevel('Developer');
set_time_limit(0);
Benchmark::startLive();
// precache workspace config
$cachedFiles = Emergence_FS::cacheTree('sencha-workspace/.sencha');
Benchmark::mark("precached sencha-workspace/.sencha");
// precache workspace packages
$cachedFiles = Emergence_FS::cacheTree('sencha-workspace/packages');
Benchmark::mark("precached sencha-workspace/packages");
// precache workspace microloaders
$cachedFiles = Emergence_FS::cacheTree('sencha-workspace/microloaders');
Benchmark::mark("precached sencha-workspace/microloaders");
 public static function handleExportRequest()
 {
     // get repo
     if (empty($_REQUEST['repo'])) {
         die('Parameter "repo" required');
     }
     $repoName = $_REQUEST['repo'];
     if (!array_key_exists($repoName, Git::$repositories)) {
         die("Repo '{$repoName}' is not defined in Git::\$repositories");
     }
     $repoCfg = Git::$repositories[$repoName];
     $exportOptions = array('localOnly' => false);
     if (!empty($repoCfg['localOnly'])) {
         $exportOptions['localOnly'] = true;
     }
     // start the process
     set_time_limit(0);
     Benchmark::startLive();
     Benchmark::mark("configured request: repoName={$repoName}");
     // get paths
     $repoPath = "{$_SERVER['SITE_ROOT']}/site-data/git/{$repoName}";
     // check if there is an existing repo
     if (!is_dir("{$repoPath}/.git")) {
         die("{$repoPath} does not contain .git");
     }
     // get repo
     chdir($repoPath);
     // sync trees
     foreach ($repoCfg['trees'] as $srcPath => $treeOptions) {
         if (is_string($treeOptions)) {
             $treeOptions = array('path' => $treeOptions);
         }
         $treeOptions = array_merge($exportOptions, $treeOptions, ['dataPath' => false]);
         if (!is_string($srcPath)) {
             $srcPath = $treeOptions['path'];
         } elseif (!$treeOptions['path']) {
             $treeOptions['path'] = $srcPath;
         }
         $srcFileNode = Site::resolvePath($srcPath);
         if (is_a($srcFileNode, 'SiteFile')) {
             $destDir = dirname($treeOptions['path']);
             if ($destDir && !is_dir($destDir)) {
                 mkdir($destDir, 0777, true);
             }
             copy($srcFileNode->RealPath, $treeOptions['path']);
             Benchmark::mark("exported file {$srcPath} to {$treeOptions['path']}");
         } else {
             $exportResult = Emergence_FS::exportTree($srcPath, $treeOptions['path'], $treeOptions);
             Benchmark::mark("exported directory {$srcPath} to {$treeOptions['path']}: " . http_build_query($exportResult));
         }
     }
     Benchmark::mark("wrote all changes");
 }
Exemple #15
0
$fontsTmpPath = "{$tmpPath}/fonts";
$cssTmpPath = "{$tmpPath}/css";
Benchmark::mark("created tmp: {$tmpPath}");
// grab resources to work with
Emergence_FS::cacheTree($sassPath);
$exportResult = Emergence_FS::exportTree($sassPath, $sassTmpPath);
Benchmark::mark("exported {$sassPath} to {$sassTmpPath}: " . http_build_query($exportResult));
Emergence_FS::cacheTree($imgPath);
$exportResult = Emergence_FS::exportTree($imgPath, $imgTmpPath);
Benchmark::mark("exported {$imgPath} to {$imgTmpPath}: " . http_build_query($exportResult));
Emergence_FS::cacheTree($fontsPath);
$exportResult = Emergence_FS::exportTree($fontsPath, $fontsTmpPath);
Benchmark::mark("exported {$fontsPath} to {$fontsTmpPath}: " . http_build_query($exportResult));
// begin cmd
chdir($sassTmpPath);
Benchmark::mark("chdir to: {$sassTmpPath}");
$cmd = 'compass compile 2>&1';
Benchmark::mark("running CMD: {$cmd}");
passthru($cmd, $cmdStatus);
Benchmark::mark("CMD finished: exitCode={$cmdStatus}");
// import build
if ($cmdStatus == 0) {
    Benchmark::mark("importing {$cssTmpPath}");
    $importResults = Emergence_FS::importTree($cssTmpPath, "site-root/css", array('transferDelete' => false));
    Benchmark::mark("imported files: " . http_build_query($importResults));
}
// clean up
if (empty($_GET['leaveWorkspace'])) {
    exec("rm -R {$tmpPath}");
    Benchmark::mark("erased {$tmpPath}");
}
 public static function getSourceNodes($paths, $root, $contentType = null)
 {
     $paths = static::splitMultipath($paths);
     if (is_string($root)) {
         $root = Site::splitPath($root);
     }
     $sourceFiles = array();
     foreach ($paths as $path) {
         $path = array_merge($root, $path);
         list($filename) = array_slice($path, -1);
         if ($filename == '*') {
             array_pop($path);
             Emergence_FS::cacheTree($path);
             foreach (Emergence_FS::getTreeFiles($path, false, $contentType ? array('Type' => $contentType) : null) as $path => $fileData) {
                 $sourceFiles[$path] = $fileData;
             }
         } else {
             $node = Site::resolvePath($path);
             if (!$node || !is_a($node, 'SiteFile')) {
                 throw new Exception('Source file "' . implode('/', $path) . '" does not exist', self::ERROR_NOT_FOUND);
             }
             if ($node->Type != $contentType) {
                 throw new Exception('Source file "' . implode('/', $path) . '" does not match requested content type "' . $contentType . '"', self::ERROR_TYPE_MISMATCH);
             }
             $sourceFiles[join('/', $path)] = array('ID' => $node->ID, 'SHA1' => $node->SHA1);
         }
     }
     return $sourceFiles;
 }
Exemple #17
0
    } elseif (!$treeOptions['path']) {
        $treeOptions['path'] = $srcPath;
    }
    $treeOptions['exclude'][] = '#(^|/)\\.git(/|$)#';
    if (is_file($treeOptions['path'])) {
        $sha1 = sha1_file($treeOptions['path']);
        $existingNode = Site::resolvePath($srcPath);
        if (!$existingNode || $existingNode->SHA1 != $sha1) {
            $fileRecord = SiteFile::createFromPath($srcPath, null, $existingNode ? $existingNode->ID : null);
            SiteFile::saveRecordData($fileRecord, fopen($treeOptions['path'], 'r'), $sha1);
            Benchmark::mark("importing file {$srcPath} from {$treeOptions['path']}");
        } else {
            Benchmark::mark("skipped unchanged file {$srcPath} from {$treeOptions['path']}");
        }
    } else {
        $cachedFiles = Emergence_FS::cacheTree($srcPath);
        Benchmark::mark("precached {$srcPath}: " . $cachedFiles);
        $exportResult = Emergence_FS::importTree($treeOptions['path'], $srcPath, $treeOptions);
        Benchmark::mark("importing directory {$srcPath} from {$treeOptions['path']}: " . http_build_query($exportResult));
    }
}
// commit changes
#$repo->git('add --all');
#
#$repo->git(sprintf(
#	'commit -n -m "%s" --author="%s <%s>"'
#	,addslashes($_POST['message'])
#	,$GLOBALS['Session']->Person->FullName
#	,$GLOBALS['Session']->Person->Email
#));
#Benchmark::mark("committed all changes");
    }
}
// write archive
if (!empty($_GET['archive'])) {
    try {
        $exportResult = Emergence_FS::exportTree($archivePath, $archiveTmpPath);
        Benchmark::mark("exported {$archivePath} to {$archiveTmpPath}: " . http_build_query($exportResult));
    } catch (Exception $e) {
        Benchmark::mark("failed to export {$archivePath}, continueing");
    }
}
// change into app's directory
chdir($appTmpPath);
Benchmark::mark("chdir to: {$appTmpPath}");
// prepare cmd
$cmd = Sencha::buildCmd($cmdVersion, 'ant', "-Dbuild.dir={$buildTmpPath}", 'sass');
Benchmark::mark("running CMD: {$cmd}");
// execute CMD
passthru("{$cmd} 2>&1", $cmdStatus);
Benchmark::mark("CMD finished: exitCode={$cmdStatus}");
// import resources directory
if ($cmdStatus == 0) {
    Benchmark::mark("importing {$buildTmpPath}/resources to {$buildPath}/resources");
    $importResults = Emergence_FS::importTree("{$buildTmpPath}/resources", "{$buildPath}/resources", array('exclude' => $defaultExclude));
    Benchmark::mark("imported files: " . http_build_query($importResults));
}
// clean up
if (empty($_GET['leaveWorkspace'])) {
    exec("rm -R {$tmpPath}");
    Benchmark::mark("erased {$tmpPath}");
}
Exemple #19
0
$patternTemplate = '/(_|gettext)\\(\\s*(\'|")(.*?)\\2\\s*\\)/si';
$patternTemplateShort = '/\\{(_|gettext)\\s+("|\'|)(.*?)\\2\\s*\\}/si';
$patternPHP = '/(_|gettext)\\s*\\(\\s*(\'|")(.*?)\\2\\s*\\)/si';
$patternPHPValidators = '/(\'|")errorMessage\\1\\s*=>\\s*(\'|")(.*?)\\2/s';
// create a memory handle to write pot file to
$pot = fopen('php://memory', 'w+');
$strings = array();
// extract strings from templates
$files = Emergence_FS::getTreeFiles('html-templates', false, array('Type' => 'text/x-html-template'));
foreach ($files as $path => $fileData) {
    $contents = file_get_contents(SiteFile::getByID($fileData['ID'])->RealPath);
    _extractStrings($patternTemplate, $contents, $path, $strings);
    _extractStrings($patternTemplateShort, $contents, $path, $strings);
}
// extract strings from PHP files
$files = Emergence_FS::getTreeFiles(null, false, array('Type' => 'application/php'));
foreach ($files as $path => $fileData) {
    $contents = file_get_contents(SiteFile::getByID($fileData['ID'])->RealPath);
    _extractStrings($patternPHP, $contents, $path, $strings);
    _extractStrings($patternPHPValidators, $contents, $path, $strings);
}
// write pot file
foreach ($strings as $string => $sources) {
    fwrite($pot, '#: ' . implode(' ', $sources) . PHP_EOL);
    // switch output format if embedded newlines found (see https://www.gnu.org/software/gettext/manual/html_node/Normalizing.html)
    if (preg_match('/[^\\n]\\n+[^\\n]/', $string)) {
        // multiline output format
        fwrite($pot, 'msgid ""' . PHP_EOL);
        fwrite($pot, str_replace('\\n', '\\n"' . PHP_EOL . '"', _encodeString($string)) . PHP_EOL);
    } else {
        fwrite($pot, 'msgid ' . _encodeString($string) . PHP_EOL);
<?php

$GLOBALS['Session']->requireAccountLevel('Developer');
set_time_limit(0);
Benchmark::startLive();
if (!($framework = $_GET['framework'])) {
    die('parameter "framework" missing');
}
if (!($frameworkVersion = $_GET['version'])) {
    die('parameter "version" missing');
}
$cachedFiles = Emergence_FS::cacheTree("sencha-workspace/{$framework}-{$frameworkVersion}");
Benchmark::mark("precached {$cachedFiles} files in sencha-workspace/{$framework}-{$frameworkVersion}");
function Dwoo_Plugin_sencha_bootstrap(Dwoo_Core $dwoo, $App = null, $classPaths = array(), $packages = array(), $patchLoader = true, $framework = 'ext', $frameworkVersion = null, $packageRequirers = null)
{
    // retrieve app if available
    if (!$App) {
        $App = $dwoo->data['App'];
    }
    // load workspace classpaths
    $classPaths = array_merge($classPaths, explode(',', Sencha::getWorkspaceCfg('workspace.classpath')));
    // if app provided, load classpaths and packages
    if ($App) {
        $framework = $App->getFramework();
        $frameworkVersion = $App->getFrameworkVersion();
        $appPath = 'sencha-workspace/' . $App->getName();
        // recursively merge app's required packages and their required packages into packages list
        $packages = array_merge($packages, $App->getRequiredPackages(false));
        // false to skip crawling decendents, we'll do it here later
        // add theme to packages list
        if ($themeName = $App->getBuildCfg('app.theme')) {
            $packages[] = $themeName;
        }
        // include classpath files
        $classPaths = array_merge($classPaths, explode(',', $App->getBuildCfg('app.classpath')));
        // include override files
        if ($overridesPath = $App->getBuildCfg('app.overrides')) {
            $classPaths = array_merge($classPaths, explode(',', $overridesPath));
        }
    }
    // pull package requirements from source files
    if (!empty($packageRequirers)) {
        if (is_string($packageRequirers)) {
            $packageRequirers = array($packageRequirers);
        }
        foreach ($packageRequirers as $packageRequirer) {
            if ($sourceNode = Site::resolvePath($packageRequirer)) {
                $packages = array_merge($packages, Sencha::getRequiredPackagesForSourceFile($sourceNode->RealPath));
            }
        }
    }
    // apply default framework version and normalize
    if (!$frameworkVersion) {
        $frameworkVersion = Sencha::$frameworks[$framework]['defaultVersion'];
    }
    $frameworkVersion = Sencha::normalizeFrameworkVersion($framework, $frameworkVersion);
    $frameworkPath = "sencha-workspace/{$framework}-{$frameworkVersion}";
    // initialize output state
    $manifest = array();
    $autoLoadPaths = array();
    // set framework path if patching loader
    if ($patchLoader) {
        $manifest['Ext'] = "/app/{$framework}-{$frameworkVersion}/src";
    }
    // add paths for packages
    $packages = array_unique(Sencha::crawlRequiredPackages(array_unique($packages), $framework, $frameworkVersion));
    foreach ($packages as $packageName) {
        // check workspace and framework package dirs
        $packagePath = "sencha-workspace/packages/{$packageName}";
        if (!Site::resolvePath($packagePath)) {
            $packagePath = "{$frameworkPath}/packages/{$packageName}";
            if (!Site::resolvePath($packagePath)) {
                throw new Exception("Source for package {$packageName} not found in workspace or framework");
            }
        }
        array_push($classPaths, "{$packagePath}/src", "{$packagePath}/overrides");
    }
    // include classpaths from packages
    $classPaths = array_merge($classPaths, Sencha::aggregateClassPathsForPackages($packages));
    // filter classpaths
    $classPaths = array_unique(array_filter($classPaths));
    // build list of all source trees, resolving CMD variables and children
    $sources = array();
    foreach ($classPaths as $classPath) {
        if (strpos($classPath, '${workspace.dir}/x/') === 0) {
            $classPath = substr($classPath, 19);
            $manifest[str_replace('/', '.', $classPath)] = '/app/x/' . $classPath;
            $classPath = 'ext-library/' . $classPath;
        } elseif (strpos($classPath, 'ext-library/') === 0) {
            $classPath = substr($classPath, 12);
            $manifest[str_replace('/', '.', $classPath)] = '/app/x/' . $classPath;
            $classPath = 'ext-library/' . $classPath;
        } elseif (strpos($classPath, '${app.dir}/') === 0) {
            $classPath = $appPath . substr($classPath, 10);
        } elseif (strpos($classPath, '${ext.dir}/') === 0) {
            $classPath = $frameworkPath . substr($classPath, 10);
        } elseif (strpos($classPath, '${touch.dir}/') === 0) {
            $classPath = $frameworkPath . substr($classPath, 12);
        }
        Emergence_FS::cacheTree($classPath);
        $sources = array_merge($sources, Emergence_FS::getTreeFiles($classPath, false, array('Type' => 'application/javascript')));
    }
    // skip patching loader if manifest will be empty
    if (empty($sources)) {
        return '';
    }
    // process all source files and build manifest and list of classes to automatically load
    foreach ($sources as $path => &$source) {
        $autoLoad = false;
        $addToManifest = true;
        // rewrite path to canonican external URL
        if ($appPath && strpos($path, "{$appPath}/") === 0) {
            $webPath = '/app/' . substr($path, 17);
            // app overrides should automatically be loaded
            if (substr($path, strlen($appPath), 11) == '/overrides/') {
                $autoLoad = true;
                $addToManifest = false;
            }
        } elseif (strpos($path, 'ext-library/') === 0) {
            $webPath = '/app/x' . substr($path, 11);
        } elseif (strpos($path, 'sencha-workspace/packages/') === 0) {
            $webPath = '/app/' . substr($path, 17);
            // package overrides should automatically be loaded
            if (substr($path, strpos($path, '/', 26), 11) == '/overrides/') {
                $autoLoad = true;
                $addToManifest = false;
            }
        } elseif (strpos($path, $frameworkPath) === 0) {
            $webPath = "/app/{$framework}-{$frameworkVersion}/" . substr($path, strlen($frameworkPath) + 1);
            // package overrides should automatically be loaded
            if (substr($path, strpos($path, '/', strlen($frameworkPath) + 10), 11) == '/overrides/') {
                $autoLoad = true;
                $addToManifest = false;
            }
        } elseif (strpos($path, 'sencha-workspace/pages/') === 0) {
            $webPath = '/app/' . substr($path, 17);
        } elseif (strpos($path, $frameworkPath) === 0) {
            $webPath = '/app/' . substr($path, 17);
        } else {
            // this class was not in a recognized externally loadable collection
            continue;
        }
        // discover class name
        $sourceCacheKey = "sencha-class-name/{$source['SHA1']}";
        if (!($source['Class'] = Cache::fetch($sourceCacheKey))) {
            $sourceNode = Site::resolvePath($path);
            $sourceReadHandle = $sourceNode->get();
            while (($line = fgets($sourceReadHandle, 4096)) !== false) {
                if (preg_match('/^\\s*(Ext\\.define\\(\\s*([\'"])([^\\2]+)\\2|\\/\\/\\s*@define[ \\t]+(\\S+))/i', $line, $matches)) {
                    $source['Class'] = empty($matches[4]) ? $matches[3] : $matches[4];
                    break;
                }
            }
            fclose($sourceReadHandle);
            // cache class name
            Cache::store($sourceCacheKey, $source['Class']);
        }
        // skip if class name could not be determined
        if (!$source['Class']) {
            continue;
        }
        // apply fingerprint signature to path
        $webPath = "{$webPath}?_sha1={$source['SHA1']}";
        // map class name to path
        if ($addToManifest) {
            $manifest[$source['Class']] = $webPath;
        }
        // add path to autoLoad list
        if ($autoLoad) {
            $autoLoadPaths[] = $webPath;
        }
    }
    // build loader overrides
    $loaderPatch = '';
    if ($patchLoader) {
        $loaderPatch .= 'Ext.Loader.setConfig("disableCaching", false);';
        $loaderPatch .= 'function _versionScriptUrl(url) {' . 'if (url[0] != "/") {' . 'url = window.location.pathname + url;' . 'while (url.match(/\\/\\.\\.\\//)) url = url.replace(/\\/[^\\/]+\\/\\.\\./g, "");' . '}' . 'if(!url.match(/\\?_sha1=/)) {' . 'console.warn("Fingerprinted URL not found for %o, it will be loaded with a cache-buster", url);' . 'url += "?" + dcParam + "=" + now;' . '}' . 'return url;' . '}';
        $loaderPatch .= 'function _overrideMethod(cls, method, override) {' . 'var parent = cls[method] || Ext.emptyFn;' . 'cls[method] = function() {' . 'var me = this;' . 'callArgs = Array.prototype.slice.call(arguments, 0);' . 'callArgs.unshift(function() {' . 'parent.apply(me, arguments);' . '});' . 'return override.apply(this, callArgs);' . '};' . '}';
        #        if (Sencha::isVersionNewer('5', $frameworkVersion)) {
        if ($framework == 'ext') {
            $loaderPatch .= '_overrideMethod(Ext.Loader, "loadScript", function(parent, options) {' . 'if (typeof options == "string") {' . 'options = _versionScriptUrl(options);' . '} else {' . 'options.url = _versionScriptUrl(options.url);' . '}' . 'return parent(options);' . '});';
        } else {
            $loaderPatch .= '_overrideMethod(Ext.Loader, "loadScriptFile", function(parent, url, onLoad, onError, scope, synchronous) {' . 'return parent(_versionScriptUrl(url), onLoad, onError, scope, synchronous);' . '});';
        }
    }
    // output loader patch and manifest
    return '<script type="text/javascript">(function(){' . 'var dcParam = Ext.Loader.getConfig("disableCachingParam")' . ',now = Ext.Date.now();' . $loaderPatch . 'Ext.Loader.addClassPathMappings(' . json_encode($manifest) . ');' . '})()</script>' . (count($autoLoadPaths) ? implode('', array_map(function ($url) {
        return '<script type="text/javascript" src="' . $url . '"></script>';
    }, $autoLoadPaths)) : '');
}
Exemple #22
0
<?php

$GLOBALS['Session']->requireAccountLevel('Developer');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    Site::$autoPull = true;
    Site::$debug = true;
    set_time_limit(0);
    $trees = array('dwoo-plugins', 'event-handlers', 'ext-library', 'html-templates', 'js-library', 'php-classes', 'php-config', 'phpunit-tests', 'php-migrations', 'site-root', 'sencha-workspace/.sencha', 'sencha-workspace/microloaders', 'sencha-workspace/pages', 'sencha-workspace/packages', 'sencha-workspace/EmergenceEditor', 'sencha-workspace/EmergencePullTool', 'sencha-workspace/ContentEditor');
    $message = "";
    foreach ($_POST['collections'] as $collection) {
        $filesCached = Emergence_FS::cacheTree($collection, true);
        $message .= sprintf('Precached %03u files in %s' . PHP_EOL, $filesCached, $collection);
    }
}
RequestHandler::respond('precache', array('message' => $message));
$workspaceConfigPath = "{$workspacePath}/.sencha";
$workspaceFrameworkPath = "{$workspacePath}/{$framework}-{$frameworkVersion}";
// precache framework and workspace config
$cachedFiles = Emergence_FS::cacheTree($workspaceConfigPath);
Benchmark::mark("precached {$workspaceConfigPath}");
$cachedFiles = Emergence_FS::cacheTree($workspaceFrameworkPath);
Benchmark::mark("precached {$workspaceFrameworkPath}");
// write workspace to tmp
$exportResult = Emergence_FS::exportTree($workspaceConfigPath, $tmpConfigPath);
Benchmark::mark("exported {$workspaceConfigPath} to {$tmpConfigPath}: " . http_build_query($exportResult));
$exportResult = Emergence_FS::exportTree($workspaceFrameworkPath, $tmpFrameworkPath);
Benchmark::mark("exported {$workspaceFrameworkPath} to {$tmpFrameworkPath}: " . http_build_query($exportResult));
// begin cmd
$appPath = "{$workspacePath}/{$appName}";
$appTmpPath = "{$tmpPath}/{$appName}";
$cmd = Sencha::buildCmd(null, "-sdk {$tmpFrameworkPath}", 'generate app', $appName, $appTmpPath);
//config -prop templates.dir=/root/templates then
Benchmark::mark("running CMD: {$cmd}");
passthru("{$cmd} 2>&1", $cmdStatus);
Benchmark::mark("CMD finished: exitCode={$cmdStatus}");
// import app
if ($cmdStatus == 0) {
    Benchmark::mark("importing {$appTmpPath} to {$appPath}");
    $importResults = Emergence_FS::importTree($appTmpPath, $appPath, array('exclude' => array("#^/{$framework}/#")));
    Benchmark::mark("imported files: " . http_build_query($importResults));
}
// clean up
if (empty($_GET['leaveWorkspace'])) {
    exec("rm -R {$tmpPath}");
    Benchmark::mark("erased {$tmpPath}");
}