Beispiel #1
0
 /**
  * Сохранение сессионных данных.
  *
  * Перед сохранением из БД удаляются ранее существовавшие данные этой сессии.
  * @todo менять sid надо при _каждом_ сохранении, см. Session Fixation
  * Vulnerability.
  *
  * Если сессия не была загружена — возникает RuntimeException().
  *
  * @see http://en.wikipedia.org/wiki/Session_fixation
  *
  * @return Session $this
  */
 public function save($force = false)
 {
     static $sent = false;
     if ($force) {
         $sent = false;
     }
     // При запуске из консоли сессии никуда не сохраняем.
     if (empty($_SERVER['REMOTE_ADDR'])) {
         return;
     }
     if (null === $this->data) {
         throw new RuntimExeption(t('Session is being saved ' . 'without having been loaded.'));
     }
     if ($this->hash() != $this->_hash) {
         if (null === $this->id) {
             $this->id = $this->getsessionId();
         }
         switch ($this->getStorageType()) {
             case 'file':
                 os::mkdir(dirname($path = $this->getStoragePath($this->id)), t('Не удалось создать временный каталог для хранения сессий.'));
                 if (!empty($this->data)) {
                     os::write($path, serialize($this->data));
                 } elseif (file_exists($path)) {
                     unlink($path);
                 }
                 break;
             default:
                 $db = Context::last()->db;
                 $db->exec("DELETE FROM node__session WHERE `sid` = ?", array($this->id));
                 $ckey = 'session:' . $this->id;
                 $cache = cache::getInstance();
                 if (!empty($this->data)) {
                     $db->exec("INSERT INTO node__session (`created`, `sid`, `data`) " . "VALUES (UTC_TIMESTAMP(), ?, ?)", array($this->id, serialize($this->data)));
                     $cache->{$ckey} = serialize($this->data);
                 } else {
                     unset($cache->{$ckey});
                 }
         }
         if (!$sent) {
             $sent = true;
             // $path = '/';
             $time = time() + 60 * 60 * 24 * 30;
             $name = self::cookie;
             if (!headers_sent()) {
                 setcookie($name, empty($this->data) ? null : $this->id, $time);
                 Logger::log("cookie set: {$name}={$this->id}", 'auth');
             }
         }
     }
     return $this;
 }
Beispiel #2
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;
     }
 }
Beispiel #3
0
 /**
  * Импорт нескольких файлов из архива.
  *
  * Вытаскивает из архива все файлы, добавляет их в файловый архив.
  *
  * @return Node последний добавленный в архив файл
  * @param string $zipfile путь к ZIP-архиву.
  */
 public static function unzip($zipfile, $folder = null, $parent_id = null)
 {
     $node = null;
     $tmpdir = os::mkdir(os::path(Context::last()->config->getPath('main/tmpdir'), 'upload'));
     if (function_exists('zip_open')) {
         if (file_exists($zipfile)) {
             $zip = zip_open($zipfile);
             while ($zip_entry = zip_read($zip)) {
                 zip_entry_open($zip, $zip_entry);
                 if (substr(zip_entry_name($zip_entry), -1) == '/') {
                     /*
                     mcms::debug(zip_entry_name($zip_entry));
                     
                     $zdir = substr(zip_entry_name($zip_entry), 0, -1);
                     if (file_exists($zdir))
                       throw new Exception('Directory "<b>' . $zdir . '</b>" exists');
                     
                     os::mkdir($zdir);
                     */
                 } else {
                     $name = basename(zip_entry_name($zip_entry));
                     $tmpname = tempnam($tmpdir, 'unzip');
                     file_put_contents($tmpname, zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)));
                     $node = Node::create('file');
                     $node->import($a = array('parent_id' => $parent_id, 'tmp_name' => $tmpname, 'name' => $name, 'filename' => $name, 'type' => os::getFileType($name)), false);
                     $node->save();
                     unlink($tmpname);
                 }
                 zip_entry_close($zip_entry);
             }
             zip_close($zip);
         } else {
             throw new RuntimeException("No such file {$zipfile}");
         }
     } else {
         throw new RuntimeException('zlib extension is not available');
     }
     return $node;
 }
 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);
 }
Beispiel #5
0
 public function run()
 {
     $tmpdir = os::mkdir(os::path('tmp', 'modules'));
     $existing = $this->getExistingModules();
     foreach (glob(os::path('lib', 'modules', '*', 'module.ini')) as $inifile) {
         $module = basename(dirname($inifile));
         $ini = array_merge(array('priority' => 'optional', 'section' => 'service'), ini::read($inifile));
         foreach (array('section', 'version', 'name') as $k) {
             if (!array_key_exists($k, $ini)) {
                 printf("warning: %s has no '%s' key, module ignored.\n", $module, $k);
                 continue 2;
             }
         }
         if (!in_array($zipname = $module . '-' . $ini['version'] . '.zip', $existing)) {
             zip::fromFolder($fullzipname = os::path($tmpdir, $zipname), dirname($inifile));
             printf("new file: %s\n", basename($fullzipname));
         }
         foreach ($ini as $k => $v) {
             if (is_array($v)) {
                 unset($ini[$k]);
             }
         }
         $ini['filename'] = $zipname;
         $this->modules[$module] = $ini;
     }
     ksort($this->modules);
     ini::write($this->inifile, $this->modules);
 }