Ejemplo n.º 1
0
 /**
  * Set instance to adm
  */
 public function dispatch()
 {
     View::$instance = 'adm';
     if (!$this->root->getAttribute('title')) {
         $this->root->setAttribute('title', Envi::getHost() . '/adm');
     }
 }
Ejemplo n.º 2
0
 /**
  * @backupGlobals enabled
  */
 public function test_getHost()
 {
     $this->assertEquals(\Difra\Envi::getHost(), trim(`hostname`));
     $this->assertEquals(\Difra\Envi::getHost(true), trim(`hostname`));
     $_SERVER['HTTP_HOST'] = 'www.example.com';
     $this->assertEquals(\Difra\Envi::getHost(), 'www.example.com');
     $_SERVER['VHOST_MAIN'] = 'example.com';
     $this->assertEquals(\Difra\Envi::getHost(true), 'example.com');
     $this->assertEquals(\Difra\Envi::getHost(), 'www.example.com');
 }
Ejemplo n.º 3
0
 /**
  * Get host name
  * @return mixed
  */
 protected static function getHost()
 {
     // TODO: remove next line after tests!
     return 'afisha-dubna.ru';
     static $host = null;
     if (is_null($host)) {
         $host = \Difra\Envi::getHost();
         $host = preg_replace('/^http:\\/\\//', '', $host);
         $host = preg_replace('/^www\\./', '', $host);
     }
     return $host;
 }
Ejemplo n.º 4
0
 public function getSitemap()
 {
     $urls = [];
     $urlPrefix = 'http://' . \Difra\Envi::getHost();
     $categories = Category::getList(true);
     if (!empty($categories)) {
         foreach ($categories as $category) {
             $urls[] = ['loc' => $urlPrefix . $category->getFullLink()];
         }
     }
     $items = Item::getList(null, -1, 1, null, true);
     if (!empty($items)) {
         foreach ($items as $item) {
             $urls[] = ['loc' => $urlPrefix . $item->getFullLink()];
         }
     }
     if (empty($urls)) {
         return false;
     }
     return $urls;
 }
Ejemplo n.º 5
0
 /**
  * Set up environment
  */
 public static function run()
 {
     if (function_exists('mb_internal_encoding')) {
         mb_internal_encoding('UTF-8');
     }
     ini_set('short_open_tag', false);
     ini_set('asp_tags', false);
     ini_set('mysql.trace_mode', false);
     // set session domain
     ini_set('session.use_cookies', true);
     ini_set('session.use_only_cookies', true);
     ini_set('session.cookie_domain', '.' . Envi::getHost(true));
     // set default time zone
     if (self::$timeZone = Config::getInstance()->get('timezone')) {
         date_default_timezone_set(self::$timeZone);
     } elseif (self::$timeZone = ini_get('date.timezone')) {
     } else {
         self::$timeZone = 'Europe/Berlin';
         date_default_timezone_set(self::$timeZone);
     }
     self::setLocale();
 }
Ejemplo n.º 6
0
 /**
  * Save images
  * Saves images found in $html to $path and replaces paths in img src="..." to $urlPrefix/{$id}.png.
  * Warning: if $path contains files not found in $html's as img src="..." links, those files will be deleted.
  * 1. Use $path exclusively for one object.
  * 2. Call saveImages() before saving $html
  * @param $html
  * @param $path
  * @param $urlPrefix
  */
 public static function saveImages(&$html, $path, $urlPrefix)
 {
     // when using AjaxSafeHTML, characters inside src= are encoded using ESAPI
     $html = str_replace('src="http://' . Envi::getHost() . '/up/tmp/', 'src="/up/tmp/', $html);
     $html = str_replace('src="/up/tmp/', 'src="/up/tmp/', $html);
     $html = str_replace('src="http://' . Envi::getHost() . str_replace('/', '/', "{$urlPrefix}/"), 'src="' . $urlPrefix . '/', $html);
     $html = str_replace('src="' . str_replace('/', '/', $urlPrefix . '/'), 'src="' . $urlPrefix . '/', $html);
     preg_match_all('/src=\\"\\/up\\/tmp\\/([0-9]+)\\"/', $html, $newImages);
     preg_match_all('/src=\\"' . preg_quote($urlPrefix, '/') . '\\/([0-9]+)\\.png\\"/', $html, $oldImages);
     if (!empty($oldImages[1])) {
         $usedImages = $oldImages[1];
     } else {
         $usedImages = [];
     }
     if (!empty($newImages[1])) {
         @mkdir($path, 0777, true);
         $urlPrefix = trim($urlPrefix, '/');
         foreach ($newImages[1] as $v) {
             $img = Vault::get($v);
             file_put_contents("{$path}/{$v}.png", $img);
             $html = str_replace("src=\"/up/tmp/{$v}\"", "src=\"/{$urlPrefix}/{$v}.png\"", $html);
             Vault::delete($v);
             $usedImages[] = $v;
         }
     }
     if (is_dir($path)) {
         $dir = opendir($path);
         while (false !== ($file = readdir($dir))) {
             if ($file[0] == '.') {
                 continue;
             }
             if (substr($file, -4) != '.png' or !in_array(substr($file, 0, strlen($file) - 4), $usedImages)) {
                 @unlink("{$path}/{$file}");
             }
         }
     }
 }
Ejemplo n.º 7
0
 public function getUrl()
 {
     if (!$this->groupDomain) {
         return 'http://' . \Difra\Envi::getHost(true) . '/blogs/' . rawurlencode($this->nickname) . '/' . $this->id . '/' . $this->getLink();
     } elseif ($this->blog != 1) {
         return 'http://' . $this->groupDomain . '.' . \Difra\Envi::getHost(true) . '/' . $this->id . '/' . $this->getLink();
     } else {
         return 'http://' . \Difra\Envi::getHost(true) . '/' . $this->id . '/' . $this->getLink();
     }
 }
Ejemplo n.º 8
0
 /**
  * Fill output XML with some common data
  * @param \DOMDocument|null $xml
  * @param null $instance
  */
 public static function fillXML(&$xml = null, $instance = null)
 {
     $controller = Controller::getInstance();
     if (is_null($xml)) {
         $xml = $controller->xml;
         $node = $controller->realRoot;
     } else {
         $node = $xml->documentElement;
     }
     Debugger::addLine('Filling XML data for render: Started');
     // TODO: sync this with Envi::getState()
     $node->setAttribute('lang', Envi\Setup::getLocale());
     $node->setAttribute('site', Envi::getSubsite());
     $node->setAttribute('host', $host = Envi::getHost());
     $node->setAttribute('mainhost', $mainhost = Envi::getHost(true));
     $node->setAttribute('protocol', Envi::getProtocol());
     $node->setAttribute('fullhost', Envi::getURLPrefix());
     $node->setAttribute('instance', $instance ? $instance : View::$instance);
     $node->setAttribute('uri', Envi::getUri());
     $node->setAttribute('controllerUri', Action::getControllerUri());
     if ($host != $mainhost) {
         $node->setAttribute('urlprefix', Envi::getURLPrefix(true));
     }
     // get user agent
     Envi\UserAgent::getUserAgentXML($node);
     // ajax flag
     $node->setAttribute('ajax', (Request::isAjax() or isset($_SERVER['HTTP_X_REQUESTED_WITH']) and $_SERVER['HTTP_X_REQUESTED_WITH'] == 'SwitchPage') ? '1' : '0');
     $node->setAttribute('switcher', (!$controller->cache and isset($_SERVER['HTTP_X_REQUESTED_WITH']) and $_SERVER['HTTP_X_REQUESTED_WITH'] == 'SwitchPage') ? '1' : '0');
     // build and version number
     $node->setAttribute('build', Version::getBuild());
     $node->setAttribute('framework', Version::getFrameworkVersion(false));
     $node->setAttribute('frameworkLong', Version::getFrameworkVersion(true));
     // date
     /** @var $dateNode \DOMElement */
     $dateNode = $node->appendChild($xml->createElement('date'));
     $dateKeys = ['d', 'e', 'A', 'a', 'm', 'B', 'b', 'Y', 'y', 'c', 'x', 'H', 'M', 'S'];
     $dateValues = explode('|', strftime('%' . implode('|%', $dateKeys)));
     $dateCombined = array_combine($dateKeys, $dateValues);
     $dateNode->setAttribute('ts', time());
     foreach ($dateCombined as $k => $v) {
         $dateNode->setAttribute($k, $v);
     }
     // debug flag
     $node->setAttribute('debug', Debugger::isEnabled() ? '1' : '0');
     // config values (for js variable)
     $configNode = $node->appendChild($xml->createElement('config'));
     Envi::getStateXML($configNode);
     // menu
     if ($menuResource = Resourcer::getInstance('menu')->compile(View::$instance)) {
         $menuXML = new \DOMDocument();
         $menuXML->loadXML($menuResource);
         $node->appendChild($xml->importNode($menuXML->documentElement, true));
     }
     // auth
     Auth::getInstance()->getAuthXML($node);
     // locale
     Locales::getInstance()->getLocaleXML($node);
     // Add config js object
     $config = Envi::getState();
     $confJS = '';
     foreach ($config as $k => $v) {
         $confJS .= "config.{$k}='" . addslashes($v) . "';";
     }
     $node->setAttribute('jsConfig', $confJS);
     Debugger::addLine('Filling XML data for render: Done');
     Debugger::debugXML($node);
 }
Ejemplo n.º 9
0
 /**
  * Links filter
  * @param string $link
  * @return string
  */
 private function cleanLink($link)
 {
     if (ESAPI::validateURL($link)) {
         return ESAPI::encoder()->encodeForHTMLAttribute($link);
     }
     if (mb_substr($link, 0, 1) == '/') {
         $newLink = 'http://' . Envi::getHost() . $link;
         if (ESAPI::validateURL($newLink)) {
             return ESAPI::encoder()->encodeForHTMLAttribute($newLink);
         }
     }
     return '#';
 }
Ejemplo n.º 10
0
 /**
  * Render message body from template
  * @param string $template
  * @param array $data
  */
 public function render($template, $data)
 {
     $xml = new \DOMDocument();
     /** @var \DOMelement $root */
     $root = $xml->appendChild($xml->createElement('mail'));
     $root->setAttribute('host', Envi::getHost(true));
     Locales::getInstance()->getLocaleXML($root);
     if (!empty($data)) {
         foreach ($data as $k => $v) {
             $root->setAttribute($k, $v);
         }
     }
     $this->body = View::render($xml, $template, true);
 }
Ejemplo n.º 11
0
 private function rssImage()
 {
     if ($this->settings['image'] == 0) {
         return;
     }
     $imagePath = DIR_DATA . 'rss/';
     if (file_exists($imagePath . 'rsslogo.png')) {
         $Locales = \Difra\Locales::getInstance();
         $mainHost = Envi::getHost();
         $sizes = getimagesize($imagePath . 'rssLogo.png');
         $imageNode = $this->channel->appendChild($this->rssDoc->createElement('image'));
         $imageNode->appendChild($this->rssDoc->createElement('title', $Locales->getXPath('rss/imageTitle')));
         $imageNode->appendChild($this->rssDoc->createElement('link', 'http://' . $mainHost));
         $imageNode->appendChild($this->rssDoc->createElement('url', 'http://' . $mainHost . '/rss/rsslogo.png'));
         $imageNode->appendChild($this->rssDoc->createElement('width', $sizes[0]));
         $imageNode->appendChild($this->rssDoc->createElement('height', $sizes[1]));
     }
 }
Ejemplo n.º 12
0
 /**
  * Send mail
  * @return mixed
  */
 public function send()
 {
     $this->connect(true);
     // todo: move EHLO to connect()
     $this->command('EHLO ' . Envi::getHost(true));
     //        $this->command('EHLO ' . Envi::getHost(true));
     $this->command('MAIL FROM:' . $this->formatFrom(true));
     foreach ($this->formatTo(true) as $to) {
         $this->command('RCPT TO:' . $to);
     }
     //        $this->command('RCPT TO:' . implode('+', $this->formatTo(true)));
     $message = $this->getHeaders(true, true) . self::EOL . $this->formatBody();
     //        $this->command('CHUNKING ' . mb_strlen($message, '8bit'));
     //        $this->write($message, false);
     $this->command('DATA');
     $this->write($message);
     $this->command('.');
     // todo: move to __destruct()
     $this->command('QUIT');
 }
Ejemplo n.º 13
0
 /**
  * Constructor
  */
 private function __construct()
 {
     $this->domain = '.' . Envi::getHost(true);
     $this->path = '/';
 }
Ejemplo n.º 14
0
 /**
  * Возвращает полную ссылку на анонс
  * @return string
  */
 public function getLink()
 {
     $server = Envi::getHost();
     return 'http://' . $server . '/events/' . $this->id . '-' . $this->link;
 }
Ejemplo n.º 15
0
 /**
  * Возвращает заголовки и ссылки на анонсы для экспорта в сторонние социалочки
  */
 public function getForExport()
 {
     $returnArray = [];
     $eventsArray = Announcements\Announcement::getForExport();
     if (!is_null($eventsArray)) {
         foreach ($eventsArray as $event) {
             $title = $event->getTitle();
             $link = 'http://' . Envi::getHost() . '/events/' . $event->getId();
             if (mb_strlen($title) >= 130) {
                 $title = mb_substr($title, 0, 130) . '...';
             }
             $returnArray[$event->getId()] = $title . ' ' . $link;
         }
     }
     return $returnArray;
 }
Ejemplo n.º 16
0
 /**
  * Возвращает массив ссылок на работы портфолио для карты сайта
  * @return array|null
  */
 public static function getSiteMap()
 {
     $currentHost = \Difra\Envi::getHost();
     $db = \Difra\MySQL::getInstance();
     $query = "SELECT `uri` FROM `portfolio_entry`";
     $res = $db->fetch($query);
     $returnArray = [];
     if (!empty($res)) {
         foreach ($res as $k => $data) {
             $returnArray[] = ['loc' => 'http://' . $currentHost . '/portfolio/' . $data['uri']];
         }
     }
     return !empty($returnArray) ? $returnArray : null;
 }
Ejemplo n.º 17
0
    /**
     * Construct
     * @param string $message
     * @param int $code
     * @param \Exception $previous
     */
    public function __construct($message, $code = 0, \Exception $previous = null)
    {
        //parent::__construct( $message, $code, $previous );
        if (isset(self::$errors[$message])) {
            $err = $message;
            $error = self::$errors[$err];
            $msg = '';
        } elseif (isset(self::$errors[$code])) {
            $err = $code;
            $error = self::$errors[$err];
            $msg = $message;
        } else {
            $err = self::E_INTERNAL_SERVER_ERROR;
            $error = self::$errors[$err];
            $msg = $message;
        }
        self::$error = $err;
        header("HTTP/1.1 {$err} {$error}");
        /*
        if( $ttl and is_numeric( $ttl ) and $ttl >= 0 ) {
            self::addExpires( $ttl );
        }
        */
        try {
            $xml = new \DOMDocument();
            /** @var $root \DOMElement */
            $root = $xml->appendChild($xml->createElement('error' . $err));
            $root->setAttribute('host', Envi::getSubsite());
            $root->setAttribute('hostname', $host = Envi::getHost());
            $root->setAttribute('mainhost', $mainHost = Envi::getHost(true));
            if ($host != $mainHost) {
                $root->setAttribute('urlprefix', 'http://' . $mainHost);
            }
            $root->setAttribute('build', Version::getBuild());
            $configNode = $root->appendChild($xml->createElement('config'));
            Envi::getStateXML($configNode);
            View::render($xml, 'error_' . $err);
        } catch (\Difra\Exception $ex) {
            echo <<<ErrorPage
<html>
\t<head>
\t\t<title>{$error}</title>
\t</head>
\t<body>
\t\t<center>
\t\t\t<h1 style="padding:350px 0 0 0">Error {$err}: {$error}</h1>
\t\t\t{$msg}
\t\t</center>
\t</body>
</html>
ErrorPage;
        }
        View::$rendered = true;
        die;
    }
Ejemplo n.º 18
0
    /**
     * If page rendered too long, report to developers
     * @throws Exception
     */
    public static function checkSlow()
    {
        // TODO: merge this method with Exception::sendNotification()
        $time = self::getTimer();
        if (!$time <= 1) {
            return;
        }
        // don't send notifications on development environment
        if (!Envi::isProduction()) {
            return;
        }
        $notificationMail = self::getNotificationMail();
        // no notification mail is set
        if (!$notificationMail) {
            return;
        }
        $output = '<pre>';
        foreach (self::$output as $line) {
            if (!isset($line['type'])) {
                $line['type'] = null;
            }
            $output .= "{$line['timer']}\t{$line['class']}\t{$line['type']}\t{$line['message']}\n";
        }
        $date = date('r');
        $server = print_r($_SERVER, true);
        $post = print_r($_POST, true);
        $cookie = print_r($_COOKIE, true);
        $host = Envi::getHost();
        $uri = Envi::getUri();
        $user = Auth::getInstance()->getEmail();
        $output .= <<<MSG

Page:\t{$uri}
Time:\t{$date}
Host:\t{$host}
User:\t{$user}

\$_SERVER:
{$server}

\$_POST:
{$post}

\$_COOKIE:
{$cookie}
MSG;
        $output .= '</pre>';
        Mailer::getInstance()->sendMail(self::getNotificationMail(), 'Slow script', print_r($output, true));
    }
Ejemplo n.º 19
0
 /**
  * Добавляет видео в базу
  * @param $file
  * @param $name
  * @param null $poster
  * @return bool|string
  */
 public function addVideo($file, $name, $poster = null)
 {
     $hasPoster = 0;
     $db = \Difra\MySQL::getInstance();
     $videoHash = sha1(uniqid());
     if (!is_null($poster)) {
         $hasPoster = 1;
         if (!is_dir($this->postersDir)) {
             return 'badPosterDir';
         }
         foreach ($this->videoSizes as $size) {
             $res = @file_put_contents($this->postersDir . '/' . $videoHash . '_' . $size . '_0' . '.png', Images::createThumbnail($poster, $size, $size, 'png'));
             if ($res === false) {
                 return 'badPosterSave';
             }
         }
         // отдельно сохраняем маленькую превьюшку для админки
         $res = @file_put_contents($this->postersDir . '/' . $videoHash . '_thumb.png', Images::createThumbnail($poster, 78, 78, 'png'));
         if ($res === false) {
             return 'badPosterSave';
         }
     }
     $query = "INSERT INTO `videos` (`video`, `site`, `name`, `original_file`, `date`, `status`, `hasPoster`)\n\t\t\t\tVALUES ('" . $videoHash . "', '" . Difra\Envi::getHost(true) . "', '" . $db->escape($name) . "', '" . $db->escape($file) . "', NOW(), 0, '" . intval($hasPoster) . "')";
     $db->query($query);
     return true;
 }
Ejemplo n.º 20
0
 /**
  * Check referer to prevent cross-site calls
  * Should be called manually
  * @throws Exception
  */
 public function checkReferer()
 {
     if (empty($_SERVER['HTTP_REFERER'])) {
         throw new Exception('Bad referer');
     }
     if (substr($_SERVER['HTTP_REFERER'], 0, 7) != 'http://' and substr($_SERVER['HTTP_REFERER'], 0, 8) != 'https://') {
         throw new Exception('Bad referer');
     }
     $domain = explode('://', $_SERVER['HTTP_REFERER'], 2);
     $domain = explode('/', $domain[1]);
     $domain = $domain[0] . '/';
     if (false === strpos($domain, Envi::getHost(true))) {
         throw new Exception('Bad referer');
     }
 }
Ejemplo n.º 21
0
 /**
  * Save session
  */
 private static function save()
 {
     if (!empty($_SESSION) and empty($_SESSION['dhost'])) {
         $_SESSION['dhost'] = Envi::getHost(true);
     }
 }