public function afterCompress(&$obj = null, array &$code = null) { // Iterate through generated php code $files = array(); foreach (\samson\core\File::dir($this->cache_path, 'php', '', $files, 1) as $file) { // No namespace for global function file $ns = strpos($file, 'func') === false ? __NAMESPACE__ : ''; // Compress generated php code $obj->compress_php($file, $this, $code, $ns); } }
/** * Получить путь к ресурсу веб-приложения/модуля по унифицированному URL * * @param string $path Относительный путь к ресурсу модуля/приложения * @param string $destination Имя маршрута из таблицы маршрутизации * * @return string Физическое относительное расположение ресурса в системе */ public static function parse($path, $destination = 'local') { // Найдем в рабочей папке приложения файл с маршрутами $result = array(); foreach (File::dir(__SAMSON_CWD__ . __SAMSON_CACHE_PATH, 'map', '', $result) as $file) { // Прочитаем файл с маршрутами и загрузим маршруты self::$routes = unserialize(file_get_contents($file)); // Остановим цикл break; } // Если передан слеш в пути - отрежим его т.к. пути к модулям его обязательно включают if ($path[0] == '/') { $path = substr($path, 1); } // Сформируем путь к модулю/предложению, если он задан // и добавим относительный путь к самому ресурсу $path = (isset(self::$routes[$destination]) ? self::$routes[$destination] : '') . $path; // Вернем полученный путь return $path; }
/** * Create static HTML site version */ public function compress() { // If no output path specified if (!isset($this->output[0])) { $this->output = __SAMSON_PUBLIC_PATH . '/out/'; } // Create output directory and clear old HTML data if (\samson\core\File::mkdir($this->output)) { \samson\core\File::clear($this->output); } // Save original output path $o_output = $this->output; elapsed('Creating static HTML web-application from: ' . $this->input . ' to ' . $this->output); // Collection of existing generated views $views = '<h1>#<i>' . $_SERVER['HTTP_HOST'] . '</i> .html pages:</h1>'; $views .= 'Generated on ' . date('d M Y h:i'); // Path to new resources $cssPath = ''; $jsPath = ''; // Copy generated css & js resources to root folder if (class_exists('\\samson\\resourcer\\ResourceRouter')) { $rr = m('resourcer'); // Get resourcer CSS generated files $cssPath = $this->input . $rr->cached['css']; if (isset($cssPath)) { elapsed('Creating CSS resource file from:' . $cssPath); // Read CSS file $css = file_get_contents($cssPath); // Perform URL rewriting $css = preg_replace_callback('/url\\s*\\(\\s*(\'|\\")?([^\\)\\s\'\\"]+)(\'|\\")?\\s*\\)/i', array($this, 'srcReplaceCallback'), $css); //$css = preg_replace('url((.*?)=si', '\\www', $css); $css = str_replace('url("fonts/', 'url("www/fonts/', $css); $css = str_replace('url("img/', 'url("www/img/', $css); // Write new CSS file file_put_contents($this->output . 'style.css', $css); } // Get resourcer JS generated files $jsPath = $rr->cached['js']; if (isset($jsPath)) { elapsed('Creating JavaScript resource file from:' . $jsPath); $this->copy_resource($this->input . $jsPath, $this->output . 'index.js'); } } // Iterate all site supported locales foreach (\samson\core\SamsonLocale::$locales as $locale) { // Generate localized path to cached html pages $pages_path = $this->cache_path . locale_path($locale); // Set views locale description $views .= '<h2>Locale <i>' . ($locale == \samson\core\SamsonLocale::DEF ? 'default' : $locale) . '</i>:<h2>'; // Get original output path $this->output = $o_output; //создаем набор дескрипторов cURL $mh = curl_multi_init(); //$__modules = array('local', 'account', 'clients', 'dashboard', 'login', 'main', 'notification', 'project', 'sidebar', 'translators'); $system_methods = array('__construct', '__sleep', '__destruct', '__get', '__set', '__call', '__wakeup'); //handler // TODO: this is not should be rewritten to support new router // Perform generation of every controller foreach (s()->module_stack as $id => $ctrl) { $rmController = sizeof($ctrl->resourceMap->controllers) ? $ctrl->resourceMap->controllers : $ctrl->resourceMap->module; //trace($rmController, 1); $controller = array(); //trace($controller, true); if (isset($rmController[0]) && class_exists($rmController[0])) { if (!substr_count($rmController[1], 'vendor')) { $methods = get_class_methods($rmController[0]); foreach ($methods as $method) { if (!in_array($method, $system_methods)) { if ($method == '__handler') { $controller[] = '/' . $id; } elseif (substr_count($method, '__') && !substr_count($method, '__async')) { $new_method = str_replace('__', '', $method); $controller[] = '/' . $id . '/' . $new_method; } } } } } else { $controller = $rmController; } foreach ($controller as $cntrl) { if (strpos($cntrl, '.php')) { // generate controller URL $cntrl = '/' . locale_path('ru') . strtolower(basename($cntrl, '.php')); } elapsed('Generating HTML snapshot for: ' . $cntrl); // Create curl instance $ch = \curl_init('127.0.0.1' . $cntrl); // Set base request options \curl_setopt_array($ch, array(CURLOPT_VERBOSE => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => array('Host: ' . $_SERVER['HTTP_HOST']))); // Add curl too multi request curl_multi_add_handle($mh, $ch); } } // TODO: Create function\module for this // Curl multi-request $active = null; do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM); while ($active && $mrc == CURLM_OK) { if (curl_multi_select($mh) != -1) { do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM); } } curl_multi_close($mh); // Files array $files = array(); // Iterate generated pages foreach (\samson\core\File::dir($pages_path, 'html', null, $files, 0) as $f) { // Ignore default controller index page as it will be included in this controller if (strpos($f, '/index.html') != false) { continue; } // Read HTML file $html = file_get_contents($f); // If we have resourcer CSS resource if (isset($cssPath[0])) { //$html = str_replace(basename($cssPath, '.css'), 'style', $html); //$html = str_replace('/cache/resourcer/style.css', 'style.css', $html); $html = preg_replace("'<link type=\"text/css\"[^>]*?>'si", '<link type="text/css" rel="stylesheet" href="style.css">', $html); } // If we have resourcer JS resource if (isset($jsPath[0])) { $html = preg_replace("'<script[^>]*?></script>'si", '<script type="text/javascript" src="index.js"></script>', $html); } // Change path in all img SRC attributes if (preg_match_all('/< *img[^>]*src *= *["\']?([^"\']*)/i', $html, $matches)) { if (isset($matches['url'])) { foreach ($matches['url'] as $match) { trace($match . '-' . (__SAMSON_PUBLIC_PATH . ltrim($match, '/'))); $html = str_ireplace($match, __SAMSON_PUBLIC_PATH . ltrim($match, '/'), $html); } } } // Fix images inside modules $html = str_replace('<img src="img', '<img src="www/img', $html); // Remove relative links $html = str_ireplace('<base href="/">', '', $html); // Get just file name $view_path = ($locale != \samson\core\SamsonLocale::DEF ? $locale . '_' : '') . basename($f); // Save HTML file file_put_contents($this->output . $view_path, $html); // Create index.html record $views .= '<a href="' . $view_path . '">' . basename($f) . '</a><br>'; } } // Write index file file_put_contents($this->output . 'index.html', $views); // TODO: Add support to external-internal modules // Iterate other resources foreach (\samson\core\ResourceMap::get($this->input, false, array(__SAMSON_PUBLIC_PATH . 'out/'))->resources as $type => $files) { if (!in_array($type, $this->restricted)) { foreach ($files as $f) { $this->copy_resource($f, str_replace($this->input, $this->output, $f)); } } } $imagesArray = array('png', 'jpg', 'jpeg', 'gif'); foreach (s()->module_stack as $module) { if (isset($module->resourceMap->module[1]) && !substr_count($module->resourceMap->module[1], 'vendor')) { foreach ($imagesArray as $format) { if (isset($module->resourceMap->resources[$format]) && sizeof($module->resourceMap->resources[$format])) { foreach ($module->resourceMap->resources[$format] as $file) { $this->copy_resource($file, $this->output . 'www/img/' . basename($file)); } } } } } // Generate zip file name $zip_file = $o_output . 'www.zip'; elapsed('Creating ZIP file: ' . $zip_file); // Create zip archieve $zip = new \ZipArchive(); if ($zip->open($zip_file, \ZipArchive::CREATE) === true) { foreach (\samson\core\File::dir($this->output) as $file) { $zip->addFile($file, str_replace($this->output, '', $file)); } $zip->close(); } else { elapsed('Cannot create zip file'); } }
/** * Perform resource gathering starting from $path entry point * @param string $path Entry point to start scanning resources * @return bool True if we had no errors on building path resource map */ public function build($path = null) { // If no other path is passed use current entry point and convert it to *nix path format $path = isset($path) ? realpath(normalizepath($path)) . '/' : $this->entryPoint; // Store new entry point $this->entryPoint = $path; // Check for correct path and then try to get files if (file_exists($path)) { // Collect all resources from entry point $files = array(); foreach (File::dir($this->entryPoint, null, '', $files, null, 0, $this->ignoreFolders) as $file) { // Get real path to file $file = realpath($file); // Check if this file does not has to be ignored if (!in_array(basename($file), $this->ignoreFiles)) { // Class name $class = ''; // Parent class $extends = ''; // We can determine SamsonPHP view files by 100% if ($this->isView($file)) { $this->views[] = $file; } elseif ($this->isGlobal($file)) { $this->globals[] = $file; } elseif ($this->isModel($file)) { $this->models[] = $file; } elseif ($this->isController($file)) { $this->controllers[] = $file; } elseif ($this->isModule($file, $class, $extends)) { $this->module = array($class, $file, $extends); $this->modules[] = array($class, $file, $extends); } elseif ($this->isPHP($file)) { $this->php[] = $file; } else { // Save resource by file extension // Get extension as resource type $rt = pathinfo($file, PATHINFO_EXTENSION); // Check if resource type array cell created if (!isset($this->resources[$rt])) { $this->resources[$rt] = array(); } // Add resource to collection $this->resources[$rt][] = $file; } } } // Iterate all defined object variables foreach (array_keys(get_object_vars($this)) as $var) { // If we have matched resources with that type if (isset($this->resources[$var])) { // Bind object variable to resources collection $this->{$var} =& $this->resources[$var]; } } return true; } else { // Signal error return e('Cannot build ResourceMap from ## - path does not exists', E_SAMSON_CORE_ERROR, $path); } }