public static function rpc_post_subscribe(Context $ctx)
 {
     $data = $ctx->post;
     if (empty($data['sections'])) {
         throw new InvalidArgumentException("Не выбраны разделы для подписки.");
     }
     if (false === strpos($data['email'], '@')) {
         throw new InvalidArgumentException(t('Введённый email не похож на email.'));
     }
     // В массиве могут быть и другие данные, поэтому мы
     // выбираем только то, что нам нужно завернуть.
     $bulk = array('email' => $data['email'], 'sections' => $data['sections']);
     $link = new url(array('args' => array('q' => 'subscription.rpc', 'action' => 'confirm', 'code' => base64_encode(serialize($bulk)))));
     $sections = Node::findXML(array('class' => 'tag', 'deleted' => 0, 'published' => 1, 'id' => $data['sections'], '#sort' => 'name'), $ctx->db, 'section');
     if (empty($sections)) {
         throw new InvalidArgumentException("Выбраны несуществующие разделы для подписки.");
     }
     $xml = html::em('message', array('mode' => 'confirm', 'host' => MCMS_HOST_NAME, 'email' => $data['email'], 'base' => $ctx->url()->getBase($ctx), 'confirmLink' => $link->string()), html::em('sections', $sections));
     $xsl = $ctx->config->get('modules/subscription/stylesheet', os::path('lib', 'modules', 'subscription', 'message.xsl'));
     if (false === ($body = xslt::transform($xml, $xsl, null))) {
         throw new RuntimeException(t('Возникла ошибка при форматировании почтового сообщения.'));
     }
     $subject = t('Подписка на новости сайта %host', array('%host' => MCMS_HOST_NAME));
     // mcms::debug($data['email'], $subject, $body);
     BebopMimeMail::send(null, $data['email'], $subject, $body);
 }
 /**
  * Возвращает список скриптов и стилей для использования на сайте.
  *
  * @mcms_message ru.molinos.cms.compressor.enumXXX
  */
 public static function on_compressor_enum(Context $ctx, $mode = 'website')
 {
     $result = array();
     $conf = $ctx->config->get('modules/tinymce');
     $conf['gzip'] = false;
     if (empty($conf['gzip'])) {
         $result[] = array('script', 'lib/modules/tinymce/editor/tiny_mce.js');
     } else {
         $result[] = array('script', 'lib/modules/tinymce/editor/tiny_mce_gzip.js');
     }
     $initializer = empty($conf['initializer']) ? '' : $conf['initializer'] . ', ';
     $initializer .= 'document_base_url: "http://' . MCMS_HOST_NAME . $ctx->folder() . '/", ';
     $initializer .= 'tiny_mce_path: "lib/modules/tinymce/editor"';
     $text = 'tinyMCE_initializer = {' . $initializer . '};';
     os::write($path = os::path($ctx->config->getPath('main/tmpdir'), 'tinymce_initializer.js'), $text);
     $result[] = array('script', os::localpath($path));
     $theme = empty($conf['theme']) ? 'simple' : $conf['theme'];
     if (!empty($conf['gzip'])) {
         if (file_exists($path = os::path('lib', 'modules', 'tinymce', 'editor', 'template_' . $theme . '_gzip.js'))) {
             $result[] = array('script', os::webpath($path));
         }
     }
     if (file_exists($path = os::path('lib', 'modules', 'tinymce', 'editor', 'template_' . $theme . '.js'))) {
         $result[] = array('script', os::webpath($path));
     }
     return $result;
 }
Esempio n. 3
0
 public function render(Context $ctx, array $options = array())
 {
     $options = array_merge(array('name' => 'custom', 'title' => MCMS_HOST_NAME, 'xsl' => os::path('lib', 'modules', 'rss', 'default.xsl'), 'base' => $ctx->url()->getBase($ctx), 'description' => 'News from ' . MCMS_HOST_NAME, 'language' => 'ru', 'url' => 'http://' . MCMS_HOST_NAME . $ctx->url()->string()), $options);
     $content = html::wrap('nodes', Node::findXML($this->filter, $ctx->db));
     $content = html::em('rss', $options, $content);
     return xslt::transform($content, $options['xsl'], 'text/xml');
 }
 public function __construct(array $conf)
 {
     $this->dbfile = $this->dbname = MCMS_SITE_FOLDER . DIRECTORY_SEPARATOR . $conf['name'];
     if (':memory:' != $this->dbfile and !file_exists($this->dbfile)) {
         os::copy(os::path('lib', 'modules', 'pdo', 'default.sqlite'), $this->dbfile);
     }
     $dsn = 'sqlite:' . $this->dbfile;
     if (':memory:' != $this->dbfile) {
         if (!file_exists(realpath($this->dbfile))) {
             throw new NotInstalledException('db');
         }
     }
     try {
         parent::__construct($dsn, '', '');
     } catch (PDOException $e) {
         if (!in_array('sqlite', PDO::getAvailableDrivers())) {
             throw new NotInstalledException('driver');
         } elseif (file_exists($conf['name'])) {
             throw new RuntimeException(t('Не удалось открыть базу данных.'));
         } else {
             throw new NotInstalledException('connection');
         }
     }
     $this->dbtype = 'SQLite';
 }
 /**
  * @mcms_message ru.molinos.cms.cron
  */
 public static function taskRun(Context $ctx)
 {
     $types = $ctx->config->get('modules/subscription/types', array());
     $xsl = $ctx->config->get('modules/subscription/stylesheet', os::path('lib', 'modules', 'subscription', 'message.xsl'));
     $sub = $ctx->config->get('modules/subscription/subject', 'Новости сайта %host');
     if (empty($types)) {
         return;
     }
     $ctx->db->beginTransaction();
     $users = Node::find(array('class' => 'subscription', 'deleted' => 0, 'published' => 1, '#sort' => 'name'), $ctx->db);
     // Обрабатываем активных пользователей.
     foreach ($users as $user) {
         $olast = $last = intval($user->last);
         if ($sections = (array) $user->tags) {
             list($sql, $params) = Query::build(array('class' => $types, 'tags' => $sections, 'published' => 1, 'deleted' => 0, 'id' => array('>' . ($olast + 1))))->getSelect(array('id', 'xml'));
             $nodes = $ctx->db->getResultsKV('id', 'xml', $sql, $params);
             // Отправляем документы.
             foreach ($nodes as $nid => $node) {
                 $xml = html::em('message', array('mode' => 'regular', 'unsubscribe' => 'subscription.rpc?action=remove&name=' . urlencode($user->name) . '&id=' . $user->id, 'base' => $ctx->url()->getBase($ctx), 'host' => MCMS_HOST_NAME), $node);
                 $body = xslt::transform($xml, $xsl, null);
                 $subject = t($sub, array('%host' => $ctx->url()->host()));
                 BebopMimeMail::send(null, $user->name, $subject, $body);
                 $last = max($last, $nid);
             }
             // Запоминаем последнее отправленное сообщение.
             $user->last = $last;
             $user->save();
         }
     }
     $ctx->db->commit();
 }
Esempio n. 6
0
 /**
  * Вывод формы авторизации.
  * @route GET//login
  */
 public static function on_get_login_form(Context $ctx)
 {
     if ($ctx->user->id and !$ctx->get('stay')) {
         return $ctx->getRedirect();
     }
     if (class_exists('APIStream')) {
         APIStream::init($ctx);
     }
     $handler = array('theme' => $ctx->config->get('modules/auth/login_theme'));
     $content = '';
     foreach ((array) $ctx->registry->poll('ru.molinos.cms.page.head', array($ctx, $handler, null), true) as $block) {
         if (!empty($block['result'])) {
             $content .= $block['result'];
         }
     }
     $content .= self::getXML($ctx);
     $xml = html::em('page', array('status' => 401, 'base' => $ctx->url()->getBase($ctx), 'host' => MCMS_HOST_NAME, 'prefix' => os::webpath(MCMS_SITE_FOLDER, 'themes'), 'back' => urlencode(MCMS_REQUEST_URI), 'next' => $ctx->get('destination'), 'api' => APIStream::getPrefix(), 'query' => $ctx->query()), $content);
     if (file_exists($xsl = os::path(MCMS_SITE_FOLDER, 'themes', $handler['theme'], 'templates', 'login.xsl'))) {
         try {
             return xslt::transform($xml, $xsl);
         } catch (Exception $e) {
         }
     }
     return xslt::transform($xml, 'lib/modules/auth/xsl/login.xsl');
 }
 /**
  * Возвращает экземпляр типографа. Кэширует его, для быстрого применения к нескольким полям.
  * 
  * @static
  * @access private
  * @return Pride_Typograph
  */
 private static function getTypo()
 {
     if (self::$typo === null) {
         $options = array('array_regex_array' => require os::path('lib', 'modules', 'pridetypograph', 'resources', 'RulesRegex.php'), 'array_replace_array' => require os::path('lib', 'modules', 'pridetypograph', 'resources', 'RulesReplace.php'), 'array_clean_array' => require os::path('lib', 'modules', 'pridetypograph', 'resources', 'CleanHtml.php'));
         self::$typo = Pride_Typograph::factory('array', $options);
     }
     return self::$typo;
 }
 public static function rpc_get_default(Context $ctx)
 {
     if ($ctx->config->isOk()) {
         $ctx->redirect('admin');
     }
     $xml = self::listDriversXML();
     $xsl = os::path('lib', 'modules', 'install', 'template.xsl');
     return xslt::transform(html::em('installer', array('base' => $ctx->url()->getBase($ctx), 'dirname' => $ctx->config->getDirName()), $xml), $xsl);
 }
Esempio n. 9
0
 /**
  * Возвращает RSS комментариев.
  * @route GET//comments.rss
  */
 public static function on_get_rss(Context $ctx)
 {
     if (!class_exists('RSSFeed')) {
         throw new PageNotFoundException(t('Модуль rss не установлен.'));
     }
     $filter = array('class' => 'comment', 'deleted' => 0, 'published' => 1, '#limit' => 20, '#sort' => '-id');
     $title = t('Комментарии на %host', array('%host' => MCMS_HOST_NAME));
     $feed = new RSSFeed($filter);
     return $feed->render($ctx, array('title' => $title, 'description' => $title . '.', 'xsl' => os::path('lib', 'modules', 'comment', 'rss.xsl')));
 }
Esempio n. 10
0
 public static function on_download(Context $ctx)
 {
     zip::fromFolder($zipFile = os::path($ctx->config->getPath('main/tmpdir'), 'backup.zip'), MCMS_ROOT, realpath($ctx->config->getPath('main/tmpdir')));
     $filename = $ctx->host() . '-' . date('YmdHi', time() - date('Z', time())) . '.zip';
     header('Content-Type: application/zip');
     header('Content-Length: ' . filesize($zipFile));
     header('Content-Disposition: attachment; filename="' . $filename . '"');
     readfile($zipFile);
     unlink($zipFile);
     die;
 }
Esempio n. 11
0
 /**
  * @mcms_message ru.molinos.cms.compressor.enum
  */
 public static function on_compressor_enum(Context $ctx)
 {
     $libs = array();
     if ($version = $ctx->config->get('modules/jquery/jsversion', '1.2.6')) {
         $libs[] = array('script', os::path('lib', 'modules', 'jquery', 'jquery-' . $version . '.min.js'));
     }
     if ($ctx->config->get('modules/jquery/ui')) {
         $libs[] = array('script', os::path('lib', 'modules', 'jquery', 'jquery-ui-1.5.3.min.js'));
     }
     return $libs;
 }
Esempio n. 12
0
 /**
  * @mcms_message ru.molinos.cms.admin.form.modman
  */
 public static function getAdminFormXML(Context $ctx)
 {
     $ctx->theme = os::path('lib', 'modules', 'modman', 'template.xsl');
     switch ($ctx->get('mode')) {
         case 'addremove':
             return self::getInstallForm($ctx);
         case 'config':
             return self::getConfigForm($ctx);
         case 'upgrade':
             return self::getUpgradeForm($ctx);
         default:
             return self::getSettingsForm($ctx);
     }
 }
Esempio n. 13
0
 public function __construct($keyStr)
 {
     $iniParams = ini::read(os::path('lib', 'modules', 'captcha', 'config.ini'));
     foreach ($iniParams as $k => $v) {
         $this->{$k} = $v;
     }
     // CAPTCHA image colors (RGB, 0-255)
     // $this->foreground_color = array(0, 0, 0);
     // $this->background_color = array(220, 230, 255);
     $this->foreground_color = array(mt_rand(0, 100), mt_rand(0, 100), mt_rand(0, 100));
     $this->background_color = array(mt_rand(200, 255), mt_rand(200, 255), mt_rand(200, 255));
     // Что надо нарисовать
     $this->keyString = $keyStr;
 }
Esempio n. 14
0
 public function format(Node $node, $em)
 {
     $value = $node->{$this->value};
     include_once os::path(dirname(__FILE__), 'markdown.php');
     $output = Markdown($value);
     $ctx = Context::last();
     $ctx->registry->broadcast('ru.molinos.cms.format.text', array($ctx, $this->value, &$output));
     $attrs = array();
     if (!($sniplen = $this->sniplen)) {
         $sniplen = 50;
     }
     $attrs['snippet'] = mb_strimwidth(strip_tags($output), 0, $sniplen, '…');
     return html::wrap($em, html::cdata(trim($output)), $attrs);
 }
 /**
  * Добавление скриптов к странице.
  * @mcms_message ru.molinos.cms.page.head
  */
 public static function on_get_head(Context $ctx, array $pathinfo)
 {
     if ($query = $ctx->get('query') and $key = $ctx->config->get('modules/search/gas_key')) {
         $query = str_replace('"', "'", $query);
         $paths = array(os::path(MCMS_SITE_FOLDER, 'gas.js'), os::path('lib', 'modules', 'search', 'gas.js'));
         $output = '';
         foreach ($paths as $path) {
             if (file_exists($path)) {
                 $js = str_replace('QUERY', $query, file_get_contents($path));
                 $js = str_replace('HOSTNAME', url::host($_SERVER['HTTP_HOST']), $js);
                 $output = '<script type="text/javascript" src="http://www.google.com/jsapi?key=' . $key . '"></script>' . '<script type="text/javascript">' . $js . '</script>';
                 return html::wrap('head', html::cdata($output), array('module' => 'search'));
             }
         }
     }
 }
Esempio n. 16
0
 /**
  * Вывод административной страницы. Вызывает обработчик, указанный в next,
  * предварительно проверив права пользователя.
  */
 public static function serve(Context $ctx, $path, array $pathinfo)
 {
     if (class_exists('APIStream')) {
         APIStream::init($ctx);
     }
     try {
         self::checkperm($ctx, $pathinfo);
         if (!$ctx->user->id and empty($pathinfo['anonymous'])) {
             throw new UnauthorizedException();
         }
         if (empty($pathinfo['next'])) {
             if (!empty($pathinfo['xsl'])) {
                 $pathinfo['next'] = 'AdminPage::xsltonly';
             } else {
                 throw new RuntimeException(t('Не указан обработчик для страницы %path (параметр <tt>next</tt>).', array('%path' => $path)));
             }
         }
         if (!is_callable($pathinfo['next'])) {
             throw new RuntimeException(t('Неверный обработчик для страницы %path (<tt>%next()</tt>).', array('%path' => $path, '%next' => $pathinfo['next'])));
         }
         $args = func_get_args();
         $output = call_user_func_array($pathinfo['next'], $args);
         if (!$output instanceof Response) {
             $xsl = empty($pathinfo['xsl']) ? null : implode(DIRECTORY_SEPARATOR, explode('/', $pathinfo['xsl']));
             $tmp = new AdminPage($output, $xsl);
             $output = $tmp->getResponse($ctx);
         }
         return $output;
     } catch (NotConnectedException $e) {
         Logger::trace($e);
         if (is_dir(os::path('lib', 'modules', 'install'))) {
             $ctx->redirect('install?destination=' . urlencode(MCMS_REQUEST_URI));
         } else {
             throw new RuntimeException('Система не проинсталлирована и модуля install нет.');
         }
     } catch (Exception $e) {
         Logger::trace($e);
         $data = array('status' => 500, 'error' => get_class($e), 'message' => $e->getMessage(), 'version' => MCMS_VERSION, 'release' => MCMS_RELEASE, 'base' => $ctx->url()->getBase($ctx), 'prefix' => MCMS_SITE_FOLDER . '/themes', 'back' => urlencode(MCMS_REQUEST_URI), 'next' => urlencode($ctx->get('destination')), 'clean' => !empty($_GET['__cleanurls']));
         if ($e instanceof UserErrorException) {
             $data['status'] = $e->getCode();
         }
         $xsl = os::path('lib', 'modules', 'admin', 'template.xsl');
         xslt::transform(html::em('page', $data), $xsl)->send();
     }
 }
Esempio n. 17
0
 /**
  * Возвращает содержимое файла для текущего домена.
  * @route GET//robots.txt
  */
 public static function on_get_robots(Context $ctx)
 {
     $content = "";
     foreach ($ctx->registry->poll('ru.molinos.cms.robots.txt', array($ctx)) as $tmp) {
         if (!empty($tmp['result'])) {
             $content .= trim($tmp['result']) . "\n";
         }
     }
     if (!empty($content)) {
         $content .= "\n";
     }
     $content .= "User-agent: *\n" . "Disallow: /admin\n" . "Disallow: /api/\n" . "Disallow: /doc/\n" . "Disallow: /lib/\n" . "Disallow: /sites/\n" . "Disallow: /download/\n";
     if (file_exists($path = os::path(MCMS_SITE_FOLDER, 'robots.txt'))) {
         $content .= trim(file_get_contents($path)) . "\n";
     }
     header('Content-Type: text/plain; charset=utf-8');
     header('Content-Length: ' . strlen($content));
     die($content);
 }
 /**
  * @mcms_message ru.molinos.cms.reload
  */
 public static function on_reload(Context $ctx, $path = null)
 {
     list($scripts, $styles) = self::getGlobal($ctx);
     foreach (os::find('sites', '*', 'themes', '*') as $theme) {
         if (null === $path or $theme == $path) {
             if (is_dir($theme)) {
                 $lscripts = array_merge($scripts, os::find($theme, 'scripts', '*.js'));
                 $lstyles = array_merge($styles, os::find($theme, 'styles', '*.css'));
                 os::write(os::path($theme, 'compressed.js'), self::join($lscripts, ';'));
                 os::write(os::path($theme, 'compressed.css'), self::join($lstyles));
             }
         }
     }
     foreach (os::find(os::path($ctx->config->getPath('main/tmpdir'), 'admin.*')) as $fileName) {
         if (file_exists($fileName)) {
             unlink($fileName);
         }
     }
     self::getAdminFiles($ctx);
 }
Esempio n. 19
0
 /**
  * Восстановление пароля.
  * 
  * @param Context $ctx 
  * @param array $params 
  * @return void
  * @mcms_message ru.molinos.cms.auth.process.basicpw
  */
 public static function on_register(Context $ctx, array $params)
 {
     if (false === strpos($params['email'], '@')) {
         throw new BadRequestException(t('Неверно введён почтовый адрес.'));
     }
     $node = Node::load(array('class' => 'user', 'name' => $params['email']));
     if ($node->deleted) {
         throw new ForbiddenException(t('Этот пользователь был удалён.'));
     } elseif (!$node->published) {
         throw new ForbiddenException(t('Этот пользователь заблокирован.'));
     }
     $salt = md5($_SERVER['REMOTE_ADDR'] . microtime(true) . $node->name . rand());
     $node->otp = $salt;
     $ctx->db->beginTransaction();
     $node->save();
     $ctx->db->commit();
     $xml = html::em('request', array('email' => $node->name, 'host' => MCMS_HOST_NAME, 'base' => $ctx->url()->getBase($ctx), 'link' => 'authbasic/restore.rpc?email=' . urlencode($node->name) . '&otp=' . urlencode($salt)));
     $xsl = $ctx->config->get('modules/authbasic/restoretpl', os::path('lib', 'modules', 'authbasic', 'restore.xsl'));
     $html = xslt::transform($xml, $xsl, null);
     BebopMimeMail::send(null, $node->name, t('Восстановление пароля'), $html);
 }
Esempio n. 20
0
 private static function get_file_path(Context $ctx)
 {
     return os::path($ctx->config->getPath('main/tmpdir'), 'sitemap-' . MCMS_HOST_NAME . '.xml');
 }
Esempio n. 21
0
 public static function on_get_upgrade(Context $ctx)
 {
     $ctx->theme = os::path('lib', 'modules', 'modman', 'template.xsl');
     $modules = modman::getUpdatedModules();
     if (empty($modules)) {
         // FIXME: когда перестанут сбрасывать кэш при каждом вздохе, всем станет лучше.
         modman::updateDB();
         $modules = modman::getUpdatedModules();
     }
     // Удаляем из списка обязательные модули: их нельзя отключать.
     // Это, за одно, позволит дробить модули без захламления интерфейса
     // и смущения пользователя.
     foreach ($modules as $k => $v) {
         if (empty($v['installed'])) {
             unset($modules[$k]);
         }
     }
     return self::getXML2($ctx, $modules, array('mode' => 'upgrade', 'title' => t('Обновление модулей')));
 }
Esempio n. 22
0
 /**
  * Сканирует классы, обновляет файлы module.ini
  */
 public function rebuildMeta()
 {
     foreach (os::find('lib', 'modules', '*', 'module.ini') as $iniFileName) {
         $moduleName = basename(dirname($iniFileName));
         if (!empty($argv[1]) and $argv[1] != $moduleName) {
             continue;
         }
         $ini = ini::read($iniFileName);
         $path = dirname($iniFileName);
         if (file_exists($routeFileName = os::path($path, 'route.ini'))) {
             $routes = ini::read($routeFileName);
         } else {
             $routes = array();
         }
         // Удаляем временные маршруты, считанные из комментариев в прошлый раз.
         foreach ($routes as $k => $v) {
             if (is_array($v) and !empty($v['volatile'])) {
                 unset($routes[$k]);
             }
         }
         foreach ($ini as $k => $v) {
             if (is_array($v)) {
                 unset($ini[$k]);
             }
         }
         foreach (os::find($path, '*.php') as $fileName) {
             $baseName = basename($fileName);
             if (0 === strpos($baseName, 'test')) {
                 continue;
             } elseif ('.test.php' == substr($baseName, -9)) {
                 continue;
             }
             $source = strtolower(file_get_contents($fileName));
             if (preg_match('@^\\s*(?:abstract\\s+)?class\\s+([a-z0-9_]+)(\\s+extends\\s+([^\\s]+))*(\\s+implements\\s+([^\\n\\r]+))*@m', $source, $m)) {
                 $className = $m[1];
                 $ini['classes'][$m[1]] = $baseName;
                 if (preg_match_all('#(?:@mcms_message\\s+)([a-z0-9.]+)(?:[^{]*public\\s+static\\s+function\\s+)([^(]+)#s', $source, $m)) {
                     foreach ($m[1] as $idx => $message) {
                         $method = $m[2][$idx];
                         $ini['messages'][$message][] = $className . '::' . $method;
                     }
                 }
                 if (preg_match_all('#(?:@route\\s+)([a-z0-9./-]+)(?:[^{]*public\\s+static\\s+function\\s+)([^(]+)#s', $source, $m)) {
                     foreach ($m[1] as $idx => $route) {
                         $parts = explode('//', $route);
                         $parts[0] = strtoupper($parts[0]);
                         $routes[implode('//', $parts)] = array('call' => $className . '::' . $m[2][$idx], 'volatile' => true);
                     }
                 }
             } elseif (preg_match('@^\\s*interface\\s+([a-z0-9_]+)@m', $source, $m)) {
                 $ini['classes'][$m[1]] = $baseName;
             }
         }
         $ini['changelog'] = 'http://molinos-cms.googlecode.com/svn/dist/' . MCMS_RELEASE . '/changelogs/' . $moduleName . '.txt';
         if (!empty($ini['classes'])) {
             ksort($ini['classes']);
         }
         if (!empty($routes)) {
             ksort($routes);
             ini::write($routeFileName, $routes);
         } elseif (file_exists($routeFileName)) {
             unlink($routeFileName);
         }
         ini::write($iniFileName, $ini);
     }
 }
Esempio n. 23
0
 private static function getStore()
 {
     /**
      * This is where the example will store its OpenID information.
      * You should change this path if you want the example store to be
      * created elsewhere.  After you're done playing with the example
      * script, you'll have to remove this directory manually.
      */
     $store_path = os::mkdir($path = os::path(Context::last()->config->getPath('main/tmpdir'), 'openid'), 'Could not create the FileStore directory (%path), please check the effective permissions.', array('%path' => $path));
     return new Auth_OpenID_FileStore($store_path);
 }
Esempio n. 24
0
 public function getImage()
 {
     switch ($this->filetype) {
         case 'image/jpeg':
         case 'image/pjpeg':
             $func = 'imagecreatefromjpeg';
             break;
         case 'image/png':
         case 'image/x-png':
             $func = 'imagecreatefrompng';
             break;
         case 'image/gif':
             $func = 'imagecreatefromgif';
             break;
         default:
             throw new RuntimeException(t('Файл %name не является картинкой.', array('%name' => $this->filename)));
     }
     if (!function_exists($func)) {
         throw new RuntimeException(t('Текущая конфигурация PHP не поддерживает работу с файлами типа %type.', array('%type' => $this->filetype)));
     }
     $img = call_user_func($func, os::path(Context::last()->config->getPath('files'), $this->filepath));
     if (null === $img) {
         throw new RuntimeException(t('Не удалось открыть файл %name (возможно, он повреждён).', array('%name' => $this->filename)));
     }
     return $img;
 }
Esempio n. 25
0
 public static function fetch($url, $options = null)
 {
     // FIXME: придумать нормальное решение!
     try {
         $tmpdir = Context::last()->config->getPath('main/tmpdir');
     } catch (Exception $e) {
         $tmpdir = null;
     }
     if (!$tmpdir) {
         $tmpdir = 'tmp';
     }
     $outfile = os::path(os::mkdir($tmpdir), 'mcms-fetch.' . md5($url));
     $ttl = mcms::config('file.cache.ttl', 3600);
     if (file_exists($outfile) and ($options & self::NO_CACHE or time() - $ttl > @filectime($outfile))) {
         if (is_writable(dirname($outfile))) {
             Logger::log('removing cached copy of ' . $url, 'fetch');
             unlink($outfile);
         }
     }
     // Скачиваем файл только если его нет на диске во временной директории
     if (file_exists($outfile)) {
         Logger::log('found in cache: ' . $url, 'fetch');
     } else {
         if (function_exists('curl_init')) {
             $ch = curl_init($url);
             $fp = fopen($outfile, "w+");
             curl_setopt($ch, CURLOPT_FILE, $fp);
             curl_setopt($ch, CURLOPT_HEADER, 0);
             if (null !== ($time = ini_get('max_execution_time'))) {
                 curl_setopt($ch, CURLOPT_TIMEOUT, $time);
             }
             curl_setopt($ch, CURLOPT_USERAGENT, 'Molinos.CMS/' . mcms::version() . '; http://' . MCMS_HOST_NAME);
             if (!ini_get('safe_mode')) {
                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
             }
             curl_exec($ch);
             $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
             curl_close($ch);
             fclose($fp);
             if (200 != $code) {
                 Logger::log($url . ': error ' . $code, 'fetch');
                 unlink($outfile);
                 return null;
             }
         } elseif ($f = @fopen($url, 'rb')) {
             if (!($out = fopen($outfile, 'w'))) {
                 throw new RuntimeException(t('Не удалось сохранить временный файл %name', array('%name' => $outfile)));
             }
             while (!feof($f)) {
                 fwrite($out, fread($f, 1024));
             }
             fclose($f);
             fclose($out);
         } else {
             Logger::log($url . ': failed.', 'fetch');
             throw new RuntimeException(t('Не удалось загрузить файл: ' . 'модуль CURL отсутствует, ' . 'открыть поток HTTP тоже не удалось.'));
         }
         if (function_exists('get_headers')) {
             $headers = get_headers($url, true);
             if (!empty($headers['Content-Length']) and ($real = $headers['Content-Length']) != ($got = filesize($outfile))) {
                 unlink($outfile);
                 throw new RuntimeException(t('Не удалось скачать файл: вместо %real байтов было получено %got.', array('%got' => $got, '%real' => $real)));
             }
         }
     }
     if ($options & self::CONTENT) {
         $content = file_get_contents($outfile);
         return $content;
     } else {
         return $outfile;
     }
 }
Esempio n. 26
0
 private function getStoragePath($id)
 {
     $config = Context::last()->config;
     $default = os::path($config->get('main/tmpdir'), 'sessions');
     $path = $config->getPath('modules/session/path', $default);
     return os::path($path, $id . '.session');
 }
Esempio n. 27
0
 /**
  * Возвращает схему для редактирования маршрута.
  */
 private static function getSchema(Context $ctx)
 {
     $widgets = array();
     if (class_exists('Widget')) {
         foreach (Widget::loadWidgets($ctx) as $k => $v) {
             $widgets[$k] = sprintf("%s (%s)", $v['title'], $v['classname']);
         }
         asort($widgets);
     }
     $themes = array();
     foreach (glob(os::path(MCMS_SITE_FOLDER, 'themes', '*'), GLOB_ONLYDIR) as $dir) {
         $themes[] = basename($dir);
     }
     return new Schema(array('host' => array('type' => 'TextLineControl', 'label' => t('Домен'), 'weight' => 1, 'required' => true, 'description' => t('Имя «localhost» используется как домен по умолчанию.'), 'group' => t('Адрес'), 'default' => 'localhost'), 'path' => array('type' => 'TextLineControl', 'label' => t('Путь'), 'weight' => 2, 'description' => t('Звёздочка используется для передачи произвольного параметра. Она может быть только одна. Пустой путь означает главную страницу домена.'), 'group' => t('Адрес')), 'title' => array('type' => 'TextLineControl', 'label' => t('Заголовок'), 'weight' => 3, 'group' => t('Внешний вид')), 'language' => array('type' => 'TextLineControl', 'label' => t('Язык по умолчанию'), 'weight' => 4, 'required' => true, 'default' => 'ru', 'group' => t('Внешний вид')), 'content_type' => array('type' => 'TextLineControl', 'label' => t('Тип содержимого'), 'required' => true, 'default' => 'text/html', 'group' => t('Внешний вид'), 'weight' => 5, 'description' => t('Обычно используют text/html, реже — text/xml.')), 'theme' => array('type' => 'TextLineControl', 'label' => t('Шкура'), 'group' => t('Внешний вид'), 'weight' => 6, 'description' => t('Доступные шкуры: %list.', array('%list' => join(', ', $themes))), 'default' => empty($themes) ? null : $themes[0]), 'optional' => array('type' => 'BoolControl', 'label' => t('Параметры не обязательны'), 'group' => t('Параметризация'), 'weight' => 7), 'defaultsection' => array('type' => 'EnumControl', 'label' => t('Раздел по умолчанию'), 'options' => Node::getSortedList('tag'), 'group' => t('Параметризация'), 'weight' => 8), 'widgets' => array('type' => 'SetControl', 'options' => $widgets, 'group' => t('Виджеты'), 'label' => t('Виджеты'), 'weight' => 9), 'cache' => array('type' => 'NumberControl', 'group' => t('Производительность'), 'weight' => 10, 'label' => t('Время жизни страницы в кэше'), 'description' => t('Указывается в секундах, по умолчанию кэш отключен.'))));
 }
 public function __construct(Context $ctx)
 {
     $ctx->theme = os::path('lib', 'modules', 'subscription', 'template.xsl');
     parent::__construct($ctx);
 }
Esempio n. 29
0
 /**
  * Проверяет, установлен ли модуль.
  */
 public static function isInstalled($moduleName)
 {
     return is_dir(os::path('lib', 'modules', $moduleName));
 }
Esempio n. 30
0
 private function writeConfig()
 {
     $ini = array();
     $ini['db']['dsn'] = $this->conf['db.default'];
     $ini['mail']['from'] = $this->conf['mail.from'];
     $ini['mail']['server'] = $this->conf['mail.server'];
     $ini['debug']['backtrace'] = join(',', $this->conf['backtracerecipients']);
     $ini['debug']['allow'] = join(',', $this->conf['debuggers']);
     $ini['attachment']['storage'] = $this->conf['filestorage'];
     $ini['attachment']['ftp'] = $this->conf['ftp'];
     $ini['core']['tmpdir'] = $this->conf['tmpdir'];
     ini::write($fileName = os::path($this->site, 'config.ini'), $ini);
     $this->log('wrote ' . $fileName);
 }