public static function get_classes($location) { $directory = new RecursiveDirectoryIterator($location); $iterator = new RecursiveIteratorIterator($directory); $regex = new RegexIterator($iterator, '/^.+\\.php$/i', RecursiveRegexIterator::GET_MATCH); $classes = array(); foreach ($regex as $path) { $expected = FALSE; $level = $minLevel = 0; $name = ''; $file = $path[0]; if (!joosFile::is_readable($file)) { continue; } $php_file_source = file_get_contents($file); $class_location = str_replace(JPATH_BASE . DS, '', $file); foreach (@token_get_all($php_file_source) as $token) { if (is_array($token)) { switch ($token[0]) { case T_COMMENT: case T_DOC_COMMENT: case T_WHITESPACE: continue 2; case T_NS_SEPARATOR: case T_STRING: if ($expected) { $name .= $token[1]; } continue 2; case T_CLASS: case T_INTERFACE: $expected = $token[0]; $name = ''; continue 2; case T_CURLY_OPEN: case T_DOLLAR_OPEN_CURLY_BRACES: $level++; } } if ($expected) { switch ($expected) { case T_CLASS: case T_INTERFACE: if ($level === $minLevel) { $classes[$name] = $class_location; } break; } $expected = NULL; } if ($token === '{') { $level++; } elseif ($token === '}') { $level--; } } } ksort($classes); return $classes; }
public static function display($name, $content, $hiddenField, $width, $height, $col, $row, $params) { $toolbar = isset($params['toolbar']) ? $params['toolbar'] : 'complete'; $config = joosFile::exists(__DIR__ . '/toolbars/' . $toolbar . '.php') ? require_once __DIR__ . '/toolbars/' . $toolbar . '.php' : ''; $code_on_ready = sprintf("\$().ready(function() { \$('#%s').wysiwyg(%s); })", $name, $config); joosDocument::$data['js_code'][] = $code_on_ready; return '<textarea name="' . $hiddenField . '" id="' . $hiddenField . '" cols="' . $col . '" rows="' . $row . '" style="width:' . $width . ';height:' . $height . ';">' . $content . '</textarea>'; }
public static function load_by_name($module_name) { $module_file = JPATH_APP_BASE . DS . 'modules' . DS . $module_name . DS . $module_name . '.php'; if (joosFile::exists($module_file)) { require_once $module_file; } else { throw new joosException('Файл :file_name для модуля :module_name не найден', array(':module_name' => $module_name, ':file_name' => $module_file)); } }
/** * Исполнение указанного файла шаблона с указанными параметрами */ public function render_file($template_file_name, $params = array()) { extract($params, EXTR_OVERWRITE); if (!joosFile::exists($template_file_name)) { throw new joosModulesException("Не найден файл шаблона {$template_file_name}"); } ob_start(); require $template_file_name; $output = ob_get_contents(); ob_end_clean(); return $output; }
public static function optimize_and_save(array $files) { self::init(); $cache_file = md5(serialize($files)) . '.js'; $cache_file = self::$cache_folder . DS . $cache_file; if (!joosFile::exists($cache_file)) { foreach ($files as $file) { $file = explode('?', $file); $file = $file[0]; $file = str_replace(JPATH_SITE, JPATH_BASE, $file); $file = str_replace('\\', '/', $file); self::$data[] = joosFile::exists($file) ? joosFile::get_content($file) : die($file); } $content = JSMin::minify(implode("\n;", self::$data)); joosFile::create($cache_file, $content); } $cache_file_live = str_replace(JPATH_BASE, JPATH_SITE, $cache_file); $cache_file_live = str_replace('\\', '/', $cache_file_live); return array('live' => $cache_file_live, 'base' => $cache_file); }
public function upload() { // активное правило загрузки для файла $rules_name = joosRequest::post('rules_name'); joosUpload::init($rules_name); $upload_result = array(); $check = joosUpload::check(); if ($check === true) { $upload_result = joosUpload::actions_before() + $upload_result; $upload_result = joosUpload::easy_upload(joosUpload::get_input_name(), joosUpload::get_upload_location()) + $upload_result; $upload_result = joosUpload::actions_after($upload_result) + $upload_result; // удаляем физически файл если проверки не прошли в пользователю выдаём ошибку if ($upload_result['success'] !== true) { joosFile::delete($upload_result['file_base_location']); } } else { $upload_result = $check; } // подчищаем секретные данные unset($upload_result['file_base_location']); return $upload_result; }
/** * Инициализация редактора * * @param string $field_name название поля с текстом, на котором должен быть инициализирован редактоор * @param string $content текст содержимого редактора * @param array $params массив настроек редактора * * @return mixed возвращает код инициализации редактора, либо полный код инициализации и комплекта необходимого HTML кода */ public static function display($field_name, $content, array $params = array()) { $hiddenField = isset($params['hiddenField']) ? $params['hiddenField'] : $field_name; $width = isset($params['width']) ? $params['width'] : '100%'; $height = isset($params['height']) ? $params['height'] : 300; $col = isset($params['col']) ? $params['col'] : 10; $row = isset($params['row']) ? $params['row'] : 5; // попытаемся переопределить редактор если это указано в параметрах self::$editor = isset($params['editor']) ? $params['editor'] : self::$editor; // файл используемого визуального редактора $editor_file = JPATH_BASE . DS . 'app' . DS . 'plugins' . DS . 'editors' . DS . self::$editor . DS . self::$editor . '.php'; if (joosFile::exists($editor_file)) { require_once $editor_file; } else { return sprintf('<!-- %s jooEditor::' . self::$editor . ' -->', 'Не найден редактор:'); } $editor_class = 'pluginEditor' . joosInflector::camelize(self::$editor); // инициализация редактора !isset(self::$init[self::$editor]) ? call_user_func_array("{$editor_class}::init", array($params)) : null; self::$init[self::$editor] = true; // непосредственно область редактора return call_user_func_array("{$editor_class}::display", array($field_name, $content, $hiddenField, $width, $height, $col, $row, $params)); }
public static function show_debug() { // вывод лога отладки // подсчет израсходованной памяти if (defined('JOOS_MEMORY_START')) { $mem_usage = memory_get_usage() - JOOS_MEMORY_START; $mem_usage = joosFile::convert_size($mem_usage); } else { $mem_usage = 'Недоступно'; } // подсчет времени генерации страницы joosDebug::add_top(round(microtime(true) - JOOS_START, 5)); joosDebug::add_top($mem_usage); // вывод итогового лога отлатчика joosDebug::get(); }
public static function get_edit_html_element($element_param, $key, $value, $obj_data, $params) { $class_file = JPATH_BASE . '/app/plugins/autoadmin/edit.' . $element_param['html_edit_element'] . '.php'; $class_name = 'pluginAutoadminEdit' . self::get_plugin_name($element_param['html_edit_element']); if (!joosFile::exists($class_file)) { throw new joosAutoadminFilePluginNotFoundException(sprintf('Файл плагина joosAutoadmin %s для редактирования элемента %s не найден', $class_file, $class_name)); } require_once $class_file; if (!class_exists($class_name)) { throw new joosAutoadminClassPlugionNotFoundException(sprintf('Класс для обработки %s средствами joosAutoadmin в файле %s не найден', $class_file, $class_name)); } return call_user_func_array($class_name . '::render', array($element_param, $key, $value, $obj_data, $params)); }
public function filegenerator() { $codes = self::codegenerator(); $files = $codes['files_body']; $name = $codes['component_name']; if (!joosFile::is_writable(JPATH_APP_BASE . '/components/')) { return array('success' => false, 'message' => 'Не хватает прав для создания каталога компонента'); } $component_root = JPATH_APP_BASE . '/components/' . $name; if (joosFile::exists($component_root)) { return array('success' => false, 'message' => 'Каталог компонента уже существует'); } $dir_structure = array('{app}/components/{name}', '{app}/components/{name}/helpers', '{app}/components/{name}/media', '{app}/components/{name}/media/js', '{app}/components/{name}/media/css', '{app}/components/{name}/models', '{app}/components/{name}/views', '{app}/components/{name}/views_admin'); $oldumask = umask(0); foreach ($dir_structure as $dir) { $create_dir = strtr($dir, array('{app}' => JPATH_APP_BASE, '{name}' => $name)); joosFolder::create($create_dir, 0777); } foreach ($files as $file_name => $file_body) { echo $file_name . "\n"; joosFile::put_content(sprintf('%s/components/%s/%s.php', JPATH_APP_BASE, $name, $file_name), $file_body); } umask($oldumask); //_xdump($files); }
/** * Создание GD-ресурса из файла * * @param string $filename Имя файла. * * @return mixed GD image resource или FALSE при неудаче. * @access public * @static */ public static function imageCreateFromFile($filename) { if (!joosFile::exists($filename) || !joosFile::is_readable($filename)) { throw new joosImageLibrariesException('Unable to open file "' . $filename . '"'); } // determine image format list(, , $type) = getimagesize($filename); switch ($type) { case IMAGETYPE_JPEG: return imagecreatefromjpeg($filename); break; case IMAGETYPE_GIF: return imagecreatefromgif($filename); break; case IMAGETYPE_PNG: return imagecreatefrompng($filename); break; } throw new joosImageLibrariesException('Unsupport image type for file :file', array(':file' => $filename)); }
public static function get_scheme($item) { $group = isset($item->params_group) ? $item->params_group : joosRequest::request('option'); $file = 'app' . DS . 'components' . DS . $group . DS . 'params.' . $group . '.php'; $file = JPATH_BASE . DS . $file; $model = 'params' . ucfirst($group); if (joosFile::exists($file)) { require_once $file; $params = array('notdefault' => array('name' => 'Использовать уникальные параметры', 'editable' => true, 'html_edit_element' => 'checkbox', 'html_edit_element_param' => array('text' => 'Использовать уникальные параметры'))); $add_params = $model::get_params_scheme($item->params['subgroup']); if ($add_params) { $params += $model::get_params_scheme($item->params['subgroup']); return $params; } return false; } else { return false; } }
private function root_xml_create() { $map_count = ceil($this->counters / $this->config['max_elemets_in_map']); $sitemap = array(); for ($index = 1; $index < $map_count + 1; $index++) { $sitemap[] = sprintf('<sitemap><loc>%s/cache/sitemaps/sitemap-%s.xml</loc></sitemap>', JPATH_SITE, $index); } $xml = array(); $xml[] = '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'; $xml[] = implode("\n", $sitemap); $xml[] = "</sitemapindex>"; joosFile::exists(JPATH_BASE . DS . 'sitemap.xml') ? unlink(JPATH_BASE . DS . 'sitemap.xml') : null; joosFile::put_content(JPATH_BASE . DS . 'sitemap.xml', implode("\n", $xml)); }
/** * Предстартовая загрузка необходимого списка * * @tutorial joosAutoloader( array('text','array','acl') ) * * @static * @param array $names * @throws joosAutoloaderOnStartFileNotFoundException */ public static function libraries_load_on_start(array $names = array()) { foreach ($names as $name) { $file = JPATH_BASE . DS . 'core' . DS . 'libraries' . DS . $name . '.php'; if (!joosFile::exists($file)) { throw new joosAutoloaderOnStartFileNotFoundException(sprintf('Автозагрузчки не смог найти файл %s для автозагружаемой библиотеки %', $file, $name)); } require_once $file; } }
/** * Создание безопасного имени для каталога * Работает по принципу joosFile::get_safe_name, но из названия дополнительно удаляются точки * * @param string $location полный путь к каталогу * * @return string безопасное имя для каталога */ public static function get_safe_name($location) { $location = str_replace('.', '-', $location); return joosFile::make_safe_name($location); }
<?php // запрет прямого доступа defined('_JOOS_CORE') or die; //время изменения скомпилированного файла CSS $css_cache = joosFile::get_modified_date(JTEMPLATE_BASE . DS . 'styles' . DS . 'app' . DS . '_app.css'); //текущий роут $page = joosController::instance()->get_router()->get_current_route(); ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <?php echo joosDocument::head(); ?> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <?php if (joosConfig::get('debug_template')) { ?> <link href="<?php echo JTEMPLATE_LIVE; ?> /styles/app/_app.less" rel="stylesheet/less" type="text/css" > <?php } else { ?> <link href="<?php echo JTEMPLATE_LIVE; ?>
private static function get_filefolder($rootdir = false, $filename = false, $fileid = false) { $id = $fileid ? $fileid : joosAttached::add($filename)->id; $rootdir = $rootdir ? $rootdir : joosFile::get_mime_content_type($filename); return array('file_base_location' => JPATH_APP_BASE . DS . 'attachments' . DS . $rootdir . DS . joosFile::make_file_location((int) $id), 'file_live_location' => JPATH_SITE . '/app/attachments/' . $rootdir . '/' . joosFile::make_file_location((int) $id), 'file_id' => $id); }
// стартуем пользователя joosCoreAdmin::init_user(); if (helperAcl::is_allowed('admin_panel::init') !== true) { joosRoute::redirect(JPATH_SITE_ADMIN, 'В доступе отказано'); } ob_start(); joosAutoadmin::dispatch(); joosDocument::set_body(ob_get_clean()); ob_start(); // начало вывода html // загрузка файла шаблона $template_file = JPATH_BASE . DS . 'app' . DS . 'templates' . DS . JTEMPLATE_ADMIN . DS . 'index.php'; if (file_exists($template_file)) { require_once $template_file; } else { throw new joosException('Файл index.php шаблона :template_name не найден', array(':template_name' => JTEMPLATE_ADMIN)); } // подсчет времени генерации страницы if (JDEBUG) { if (defined('_MEM_USAGE_START')) { $mem_usage = joosFile::convert_size(memory_get_usage() - _MEM_USAGE_START); } else { $mem_usage = 'недоступно'; } // подсчет времени генерации страницы joosDebug::add_top(round(microtime(true) - $sysstart, 5)); joosDebug::add_top($mem_usage); // информация отладки, число запросов в БД joosDebug::get(); } ob_end_flush();
<input type="text" class="inputbox search_input" size="30" maxlength="30" name="search" value="<?php echo $search_word; ?> " /> </div> <button class="search_button" type="submit">→</button> </form> </div> <?php if ($search_result) { for ($index = $pager->low; $index < $pager->high + 1; $index++) { if (isset($search_result[$index])) { $row = $search_result[$index]; $section = joosHTML::anchor(joosRoute::href('game_index'), 'Что-то'); $row->anons_image = JPATH_SITE_IMAGES . '/' . joosFile::make_file_location((int) $row->image_id) . '/image.png'; $row->view_href = joosRoute::href('opa_view', array('id' => $row->id, 'alias' => $row->game_slug)); ?> <div class="item"> <h2><?php echo $section . ' → '; echo joosHTML::anchor($row->view_href, $row->title); ?> </h2> <?php if ($row->anons_image) { ?> <a class="thumb" href="<?php echo $row->view_href; ?> ">
/** * Внутренний метод проверки существования файла * В случае ошибки выбрасывает исключение joosFileLibrariesException * * @static * @param $file_name путь к файлу * @throws joosFileLibrariesException */ private static function exception_if_file_not_exists($file_name) { if (!joosFile::exists($file_name)) { throw new joosFileLibrariesException('Файл :file не существует', array(':file' => $file_name)); } }