Example #1
0
function get_pages_rows()
{
    $L = Language::instance();
    $Static_pages = Static_pages::instance();
    $categories = array_slice(Config::instance()->route, 2);
    $structure = $Static_pages->get_structure();
    $path = [];
    if (!empty($categories)) {
        foreach ($categories as $category) {
            $category = $Static_pages->get_category($category)['path'];
            if (isset($structure['categories'][$category])) {
                $structure = $structure['categories'][$category];
                $path[] = $structure['path'];
            }
        }
        unset($category);
    }
    Page::instance()->title($structure['id'] == 0 ? $L->root_category : $structure['title']);
    $path = !empty($path) ? implode('/', $path) . '/' : '';
    $content = [];
    if (!empty($structure['pages'])) {
        foreach ($structure['pages'] as &$page) {
            $page = $Static_pages->get($page);
            $content[] = [[h::a($page['title'], ['href' => $path . $page['path']]), ['class' => 'cs-static-pages-padding-left-0']], h::{'a.cs-button-compact'}([h::icon('file-text'), ['href' => "admin/Static_pages/edit_page/{$page['id']}", 'data-title' => $L->edit]], [h::icon('trash-o'), ['href' => "admin/Static_pages/delete_page/{$page['id']}", 'data-title' => $L->delete]])];
        }
    }
    return [$content];
}
Example #2
0
/**
 * Returns server type
 *
 * @return string
 */
function server_api()
{
    $phpinfo = ob_wrapper(function () {
        phpinfo();
    });
    if (preg_match('/apache/i', $_SERVER['SERVER_SOFTWARE'])) {
        return 'Apache' . (preg_match('/mod_php/i', $phpinfo) ? ' + mod_php' : '');
    } elseif (preg_match('/nginx/i', $_SERVER['SERVER_SOFTWARE'])) {
        $return = 'Nginx';
        if (preg_match('/php-fpm/i', $phpinfo)) {
            $return .= ' + PHP-FPM';
        } elseif (defined('HHVM_VERSION')) {
            $return .= ' + HHVM';
        }
        return $return;
    } elseif (defined('HHVM_VERSION')) {
        return 'HipHop Virtual Machine';
    } else {
        return Language::instance()->indefinite;
    }
}
Example #3
0
    /**
     * Get info
     *
     * @return string
     */
    static function get()
    {
        switch (Language::instance()->clang) {
            case 'uk':
                return '
					<p>Принципово вектор розвитку і діяльності нашої організації збігається з інтересами народу України. Ми зобов\'язуємося й надалі відстоювати інтереси громади та лишатися незалежною організацєю. Саме тому ми потребуємо Вашої фінансової підтримки нашого проекту.</p>
					<p>Ми зобов’язуємося вести відкриту звітність щодо використання коштів, оскільки принцип чесності і прозорості лежить у фундаменті нашої організації.</p>
					<p>Рахунок для переказу в UAH/EUR/USD:</p>
					<p>ЄДРПОУ: 39214344</p>
					<p>Р\\р: 26001510692100</p>
					<p>Отримувач: ГО ВГО ОПІГОРГ</p>
					<p>МФО банку: 351005 (АТ "УкрСиббанк")</p>
					<p>Призначення: Добровільна пожертва на здійснення статутної діяльності ГО "ВГО ОПІРОРГ".</p>
				';
            case 'ru':
                return '
					<p>Принципиально вектор развития и деятельности нашей организации совпадает с интересами народа Украины. Мы обязуемся и впредь отстаивать интересы общества и оставаться независимой организаций. Именно поэтому мы нуждаемся Вашей финансовой поддержке нашего проекта.</p>
					<p>Мы обязуемся вести открытую отчетность об использовании средств, поскольку принцип честности и прозрачности лежит в фундаменте нашей организации.</p>
					<p>Счёт для перевода в UAH/EUR/USD:</p>
					<p>ЕГРПОУ: 39214344</p>
					<p>Р\\с: 26001510692100</p>
					<p>Получатель: ГО ВГО ОПІГОРГ</p>
					<p>МФО банка: 351005 (АО "УкрСиббанк")</p>
					<p>Назначение: Добровольное пожертвование на осуществление уставной деятельности ГО "ВГО ОПИРОРГ".</p>
				';
            case 'en':
            default:
                return '
					<p>Fundamentally vector of development and activities of our organization coincides with the interests of the people of Ukraine. We pledge to continue to defend the interests of the community and stay independent organization. That\'s why we need your financial support for our project.</p>
					<p>We pledge to keep an open reporting on the use of funds, as the principle of honesty and transparency lies at the foundation of our organization.</p>
					<p>Account for transfer in UAH/EUR/USD:</p>
					<p>EDRPOU: 39214344</p>
					<p>Correspondent account: 26001510692100</p>
					<p>Recipient: ГО ВГО ОПІГОРГ</p>
					<p>MFO: 351005 (JSC UkrSibbank)</p>
					<p>Purpose: Donation to carry out statutory activities NGO "APA OPIRORG".</p>
				';
        }
    }
Example #4
0
 /**
  * Get precinct
  *
  * @param int|int[] $id
  *
  * @return array|array[]|bool
  */
 function get($id)
 {
     if (is_array($id)) {
         foreach ($id as &$i) {
             $i = $this->get($i);
         }
         return $id;
     }
     $clang = Language::instance()->clang;
     return $this->cache->get("{$id}/{$clang}", function () use($id, $clang) {
         $data = $this->read_simple($id);
         if (!$data) {
             return false;
         }
         $data['id'] = (int) $data['id'];
         $data['lat'] = (double) $data['lat'];
         $data['lng'] = (double) $data['lng'];
         $data['address'] = $data["address_{$clang}"] ?: $data['address_uk'];
         unset($data['address_uk'], $data['address_en'], $data['address_ru']);
         $data['district'] = (int) $data['district'];
         $data['violations'] = (int) $data['violations'];
         return $data;
     });
 }
Example #5
0
 /**
  * Pseudo tag for labels with tooltips, specified <i>input</i> is translation item of <b>$L</b> object,
  * <i>input</i>_into item of <b>$L</b> is content of tooltip
  *
  * @static
  *
  * @param array|string	$in
  * @param array			$data
  *
  * @return mixed
  */
 static function info($in = '', $data = [])
 {
     if (isset($in['insert']) || isset($data['insert'])) {
         return static::__callStatic(__FUNCTION__, func_get_args());
     }
     if ($in === false) {
         return '';
     } elseif (is_array($in)) {
         return static::__callStatic(__FUNCTION__, [$in, $data]);
     }
     $L = Language::instance();
     if (Config::instance(true)->core['show_tooltips']) {
         return static::span($L->{$in}, array_merge(['data-title' => $L->{$in . '_info'}], $data));
     } else {
         return static::span($L->{$in}, $data);
     }
 }
Example #6
0
 * @copyright	Copyright (c) 2013-2014, Nazar Mokrynskyi
 * @license		MIT License, see license.txt
 */
namespace cs;

use h;
/**
 * Multilingual functionality: redirects and necessary meta-tags
 */
Trigger::instance()->register('System/User/construct/after', function () {
    $Config = Config::instance();
    if (!$Config->core['multilingual']) {
        return;
    }
    $relative_address = $Config->server['relative_address'];
    $Cache = Cache::instance();
    if (!FIXED_LANGUAGE && $_SERVER['REQUEST_METHOD'] == 'GET' && $Cache->cache_state() && Core::instance()->cache_engine != 'BlackHole') {
        $clang = Language::instance()->clang;
        if (!HOME) {
            header("Location: /{$clang}/{$relative_address}", true, 301);
        } else {
            header("Location: /{$clang}", true, 301);
        }
    }
    $base_url = substr($Config->base_url(), 0, -3);
    Page::instance()->Head .= h::{'link[rel=alternate]'}(['hreflang' => 'x-default', 'href' => !HOME ? "{$base_url}/{$relative_address}" : "{$base_url}"]) . h::{'link[rel=alternate]|'}(array_map(function ($lang) use($base_url, $relative_address) {
        return ['hreflang' => $lang, 'href' => "{$base_url}/{$lang}/{$relative_address}"];
    }, array_values($Cache->get('languages/clangs', function () use($Config) {
        return $Config->update_clangs();
    })) ?: []));
});
Example #7
0
    /**
     * Get info
     *
     * @return string
     */
    static function get()
    {
        switch (Language::instance()->clang) {
            case 'uk':
                return '
					<p><strong>Всеукраїнське Громадське Об’єднання OPIR.ORG</strong> — політично й фінансово незалежна громадська організація, що почала свою діяльність в найтрагічніші дні Української Революції 2013-2014 років за ініціативою групи молодих громадських активістів.</p>
					<p>Діяльність нашої організації направлена на створення <strong>інноваційних інструментів</strong> для вирішення суспільно-важливих проблем</p>
					<p>Ми розраховуємо на набуту Україною <strong>громадянську свідомість, відповідальність та ініціативність</strong> для використання таких інструментів з метою вирішення поставлених задач та <strong>проблем</strong></p>
					<h2 class="cs-center">Очі України</h2>
					<p>Проект в пілотному режимі працював на Президентських виборах 25.05.2014 і був успішно реалізовний під час Парламентських виборів 25.10.2014. Розрахований на циклічну реалізацію під час кожних наступних парламентських та президентських виборів.</p>
					<p><strong>Мета:</strong> забезпечення освітлення виборчого процесу, в разі виявлення значних фальсифікацій — використання доказів для анулювання результатів та за можливості перешкоджання порушенням через оперативне втручання.</p>
					<p><strong>Суть:</strong> можливість оперативного фіксування порушень та введення он-лайн відео-стрім спостереження з виборчих дільниць за допомогою мобільних додатків. Моніторинг таких порушень на геолокаційному веб-сервісі з відповідним організованим реагуванням громади в складі мобільних груп.</p>
					<p><strong>Наразі:</strong> ми готуємося до місцевих виборів і плануємо висвітлити виборчий процес у Києві. Наша ціль - забезпечити кожне з ~1100 відділень для голосування нашими спостерігачами-стрімерами, котрі зможуть фіксувати порушення, що значно впливають на підсумок голосування. Результатом стане альтернативний до ЦВК підрахунок результатів і відстоювання чесних результатів у суді. Подібну практику ми закликаємо проводити в кожному іншому місті, де місцева громада зорганізується для такого спостереження.</p>
					<h2 class="cs-center">Контакти</h2>
					<p>Центральний офіс ВГО OPIR.ORG:</p>
					<p>м. Київ, вул. Костянтинівська, 25</p>
					<p><a href="mailto:info@opir.org">info@opir.org</a></p>
					<p>+380 93 01 222 11</p>
					<h2 class="cs-center">Партнери</h2>
					<p style="display:flex;display:-webkit-flex;justify-content:space-around;text-align:center;">
						<a href="http://www.hromadske.tv/">
							<img src="/components/modules/Info/includes/img/1.png" alt=""/>
						</a>
						<a href="http://www.cvu.org.ua/">
							<img src="/components/modules/Info/includes/img/2.png" alt=""/>
						</a>
						<a href="http://chesno.org/">
							<img src="/components/modules/Info/includes/img/3.png" alt=""/>
						</a>
					</p>
				';
            case 'ru':
                return '
					<p><strong>Общественная Организация OPIR.ORG</strong> — политически и финансово независимая общественная организация, начавшая свою деятельность в самые трагические дни Украинской Революции 2013-2014 годов по инициативе группы молодых общественных активистов.</p>
					<p>Деятельность нашей организации направлена на создание <strong>инновационных инструментов</strong> для решения общественно важных проблем</p>
					<p>Мы полагаемся на возросшую в Украине <strong>ггражданскую сознательность, ответственность и инициативность</strong> для использования таких инструментов с целью решения поставленных задач и <strong>проблем</strong></p>
					<h2 class="cs-center">Глаза Украины</h2>
					<p>Проект в пилотном режиме прошел во время президентских выборов 25.05.2014 и был успешно реализован во время Парламентских выборов 25.10.2014. Рассчитан на циклическую реализацию во время каждых следующих парламентских и президентских выборов.</p>
					<p><strong>Цель:</strong> обеспечение освещения избирательного процесса, в случае выявления значительных фальсификаций - использование доказательств для аннулирования результатов и по возможности препятствования нарушением через оперативное вмешательство.</p>
					<p><strong>Суть:</strong> возможность оперативного фиксирования нарушений и введение онлайн видео-стрим наблюдения с избирательных участков с помощью мобильных приложений. Мониторинг таких нарушений на геолокационном веб-сервисе с соответствующим организованным реагированием общества в составе мобильных групп.</p>
					<p><strong>Сейчас:</strong> мы готовимся к местным выборам и планируем осветить избирательный процесс в Киеве. Наша цель - обеспечить каждое из ~ 1100 отделений для голосования нашими наблюдателями-стримерами, которые смогут фиксировать нарушения, которые значительно влияют на итог голосования. Результатом станет альтернативный к ЦИК подсчет результатов и отстаивания честных результатов в суде. Подобную практику мы призываем проводить в любом другом городе, где местная община организуется для такого наблюдения.</p>
					<h2 class="cs-center">Контакты</h2>
					<p>Центральный офис ОО OPIR.ORG:</p>
					<p>г. Киев, ул . Константиновская, 25</p>
					<p><a href="mailto:info@opir.org">info@opir.org</a></p>
					<p>+380 93 01 222 11</p>
					<h2 class="cs-center">Партнеры</h2>
					<p style="display:flex;display:-webkit-flex;justify-content:space-around;text-align:center;">
						<a href="http://www.hromadske.tv/">
							<img src="/components/modules/Info/includes/img/1.png" alt=""/>
						</a>
						<a href="http://www.cvu.org.ua/">
							<img src="/components/modules/Info/includes/img/2.png" alt=""/>
						</a>
						<a href="http://chesno.org/">
							<img src="/components/modules/Info/includes/img/3.png" alt=""/>
						</a>
					</p>
				';
            case 'en':
            default:
                return '
					<p><strong>NGO OPIR.ORG</strong> — politically and financially independent NGO that started its activities in the most tragic days of Ukrainian Revolution 2013-2014 on the initiative of a group of young activists.</p>
					<p>The activities of our organization aimed to create <strong>innovative tools</strong> addressing socially important problems</p>
					<p>We believe Ukraine acquired <strong>civil consciousness, responsibility and initiative</strong> to use such tools for solving social tasks and <strong>problems</strong></p>
					<h2 class="cs-center">Eyes of Ukraine</h2>
					<p>The project tested during the presidential election held on 25 May 2014 and is designed for cyclical implementation during each of the next parliamentary and presidential elections. Successfully launched on parliamentary elections held on 25 October 2014.</p>
					<p><strong>Objective:</strong> to ensure transparency of electoral process in case of significant falsifications. Use of evidence for the annulment of results and if possible prevent violations.</p>
					<p><strong>Core:</strong> the possibility to quickly capture violations and the introduction of online video stream observation at polling stations through mobile applications. Monitoring of such violations on geolocation web service with an appropriate organized response of the community as part of mobile crews.</p>
					<p><strong>Now:</strong> we are preparing for local elections and we plan to highlight the election process in Kyev. Our goal - to provide each of the approximately 1100 precints by our streaming observers, which can capture the violations, which greatly affect the outcome of the vote. The result will be an alternative to CEC calculation of the results of votes and upholding fair outcomes in court. Such a practice we call on hold in every other city where the local community will organize for such an observation.</p>
					<h2 class="cs-center">Contacts</h2>
					<p>The central office of NGO OPIR.ORG:</p>
					<p>25, Kostyantynivska str, Kyiv, Ukraine</p>
					<p><a href="mailto:info@opir.org">info@opir.org</a></p>
					<p>+380 93 01 222 11</p>
					<h2 class="cs-center">Partners</h2>
					<p style="display:flex;display:-webkit-flex;justify-content:space-around;text-align:center;">
						<a href="http://www.hromadske.tv/">
							<img src="/components/modules/Info/includes/img/1.png" alt=""/>
						</a>
						<a href="http://www.cvu.org.ua/">
							<img src="/components/modules/Info/includes/img/2.png" alt=""/>
						</a>
						<a href="http://chesno.org/">
							<img src="/components/modules/Info/includes/img/3.png" alt=""/>
						</a>
					</p>
				';
        }
    }
Example #8
0
 /**
  * Page generation
  */
 function __finish()
 {
     static $executed = false;
     if ($executed) {
         return;
     }
     $executed = true;
     /**
      * Cleaning of output
      */
     if (OUT_CLEAN) {
         ob_end_clean();
     }
     /**
      * Detection of compression
      */
     $ob = false;
     $Config = Config::instance(true);
     if (API || $Config && !zlib_compression() && $Config->core['gzip_compression']) {
         ob_start('ob_gzhandler');
         $ob = true;
     }
     /**
      * For AJAX and API requests only content without page template
      */
     if (!$this->interface) {
         /**
          * Processing of replacing in content
          */
         echo $this->process_replacing($this->Content ?: (API ? 'null' : ''));
     } else {
         Trigger::instance()->run('System/Page/pre_display');
         class_exists('\\cs\\Error', false) && Error::instance(true)->display();
         /**
          * Processing of template, substituting of content, preparing for the output
          */
         $this->prepare();
         /**
          * Processing of replacing in content
          */
         $this->Html = $this->process_replacing($this->Html);
         /**
          * Getting of debug information
          */
         if (DEBUG && (User::instance(true)->admin() || $Config->can_be_admin && $Config->core['ip_admin_list_only'])) {
             $this->get_debug_info();
         }
         Trigger::instance()->run('System/Page/display');
         echo str_replace(['<!--debug_info-->', '<!--generate time-->', '<!--peak memory usage-->'], [$this->debug_info ? h::level(h::{'div#cs-debug.uk-modal div.uk-modal-dialog-large'}(h::level($this->debug_info), ['title' => Language::instance()->debug, 'style' => 'margin-left: -45%; width: 90%;']), $this->level['debug_info']) : '', format_time(round(microtime(true) - MICROTIME, 5)), format_filesize(memory_get_usage(), 5) . h::{'sup[level=0]'}(format_filesize(memory_get_peak_usage(), 5))], rtrim($this->Html));
     }
     if ($ob) {
         ob_end_flush();
     }
 }
Example #9
0
<?php

/**
 * @package        Moderation
 * @category       modules
 * @author         Nazar Mokrynskyi <*****@*****.**>
 * @copyright      Copyright (c) 2014, Nazar Mokrynskyi
 * @license        MIT License, see license.txt
 */
namespace cs;

use h;
$module_properties = Config::instance()->module('Moderation');
$Index = Index::instance();
if (isset($_POST['moderators_group'])) {
    $module_properties->moderators_group = (int) $_POST['moderators_group'];
    $Index->save();
}
$groups = Group::instance()->get_all();
$Index->apply_button = false;
$Index->content(h::{'p.uk-text-center'}(Language::instance()->moderators_group, h::{'select[name=moderators_group]'}(['in' => array_column($groups, 'title'), 'value' => array_column($groups, 'id'), 'selected' => $module_properties->moderators_group ?: User::ADMIN_GROUP_ID])));
Example #10
0
 /**
  * Create the session for the user with specified id
  *
  * @param bool|int	$user
  * @param bool		$delete_current_session
  *
  * @return bool
  */
 function add_session($user = false, $delete_current_session = true)
 {
     $user = (int) $user ?: self::GUEST_ID;
     if ($delete_current_session && is_md5($this->current['session'])) {
         $this->del_session_internal(null, false);
     }
     /**
      * Load user data
      * Return point, runs if user is blocked, inactive, or disabled
      */
     getting_user_data:
     $data = $this->get(['login', 'username', 'language', 'timezone', 'status', 'block_until', 'avatar'], $user);
     if (is_array($data)) {
         $L = Language::instance();
         $Page = Page::instance();
         if ($data['status'] != self::STATUS_ACTIVE) {
             /**
              * If user is disabled
              */
             if ($data['status'] == self::STATUS_INACTIVE) {
                 $Page->warning($L->your_account_disabled);
                 /**
                  * Mark user as guest, load data again
                  */
                 $user = self::GUEST_ID;
                 goto getting_user_data;
                 /**
                  * If user is not active
                  */
             } else {
                 $Page->warning($L->your_account_is_not_active);
                 /**
                  * Mark user as guest, load data again
                  */
                 $user = self::GUEST_ID;
                 goto getting_user_data;
             }
             /**
              * If user if blocked
              */
         } elseif ($data['block_until'] > TIME) {
             $Page->warning($L->your_account_blocked_until . ' ' . date($L->_datetime, $data['block_until']));
             /**
              * Mark user as guest, load data again
              */
             $user = self::GUEST_ID;
             goto getting_user_data;
         }
     } elseif ($this->id != self::GUEST_ID) {
         /**
          * If data was not loaded - mark user as guest, load data again
          */
         $user = self::GUEST_ID;
         goto getting_user_data;
     }
     unset($data);
     $Config = Config::instance();
     /**
      * Generate hash in cycle, to obtain unique value
      */
     for ($i = 0; $hash = md5(MICROTIME . uniqid($i, true)); ++$i) {
         if ($this->db_prime()->qf("SELECT `id`\n\t\t\t\tFROM `[prefix]sessions`\n\t\t\t\tWHERE `id` = '{$hash}'\n\t\t\t\tLIMIT 1")) {
             continue;
         }
         $this->db_prime()->q("INSERT INTO `[prefix]sessions`\n\t\t\t\t\t(\n\t\t\t\t\t\t`id`,\n\t\t\t\t\t\t`user`,\n\t\t\t\t\t\t`created`,\n\t\t\t\t\t\t`expire`,\n\t\t\t\t\t\t`user_agent`,\n\t\t\t\t\t\t`ip`,\n\t\t\t\t\t\t`forwarded_for`,\n\t\t\t\t\t\t`client_ip`\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'%s',\n\t\t\t\t\t\t'%s',\n\t\t\t\t\t\t'%s',\n\t\t\t\t\t\t'%s',\n\t\t\t\t\t\t'%s',\n\t\t\t\t\t\t'%s',\n\t\t\t\t\t\t'%s',\n\t\t\t\t\t\t'%s'\n\t\t\t\t\t)", $hash, $user, TIME, TIME + ($user != self::GUEST_ID || $Config->core['session_expire'] < 300 ? $Config->core['session_expire'] : 300), $this->user_agent, $ip = ip2hex($this->ip), $forwarded_for = ip2hex($this->forwarded_for), $client_ip = ip2hex($this->client_ip));
         $time = TIME;
         if ($user != self::GUEST_ID) {
             $this->db_prime()->q("UPDATE `[prefix]users` SET `last_sign_in` = {$time}, `last_online` = {$time}, `last_ip` = '{$ip}.' WHERE `id` ='{$user}'");
         }
         $this->current['session'] = $hash;
         $this->cache->{"sessions/{$hash}"} = ['user' => $user, 'expire' => TIME + $Config->core['session_expire'], 'user_agent' => $this->user_agent, 'ip' => $ip, 'forwarded_for' => $forwarded_for, 'client_ip' => $client_ip];
         _setcookie('session', $hash, TIME + $Config->core['session_expire']);
         $this->id = $this->get_session_user();
         $this->update_user_is();
         if ($this->db()->qfs("SELECT COUNT(`id`)\n\t\t\t\t\t FROM `[prefix]sessions`") % $Config->core['inserts_limit'] == 0) {
             $this->db_prime()->aq("DELETE FROM `[prefix]sessions`\n\t\t\t\t\tWHERE `expire` < {$time}");
         }
         return true;
     }
     return false;
 }
Example #11
0
 /**
  * Executes plugins processing, blocks and module page generation
  */
 function __finish()
 {
     static $finished = false;
     if ($finished) {
         return;
     }
     $finished = true;
     $Config = Config::instance();
     $Page = Page::instance();
     /**
      * If site is closed, user is not admin, and it is not request for sign in
      */
     if (!$Config->core['site_mode'] && !(User::instance()->admin() || API && $Config->route === ['user', 'sign_in'])) {
         code_header(503);
         return;
     }
     if (defined('ERROR_CODE')) {
         $Page->error();
     }
     Trigger::instance()->run('System/Index/preload');
     if (!IN_ADMIN && !$this->api && file_exists(MODULES . '/' . MODULE . '/index.html')) {
         ob_start();
         _include(MODULES . '/' . MODULE . '/index.html', false, false);
         $Page->content(ob_get_clean());
         if ($this->title_auto) {
             $Page->title(Language::instance()->{HOME ? 'home' : MODULE});
         }
     } elseif (!defined('ERROR_CODE') && !$this->stop) {
         $this->init_auto && $this->init();
     }
     if ($this->generate_auto) {
         $this->generate();
     }
     if ($this->stop) {
         if (_getcookie('sign_out') && !(API && MODULE == 'System' && $Config->route == ['user', 'sign_out'])) {
             _setcookie('sign_out', '');
         }
         return;
     }
     if (defined('ERROR_CODE')) {
         $Page->error();
     } elseif (_getcookie('sign_out') && !(API && MODULE == 'System' && $Config->route == ['user', 'sign_out'])) {
         _setcookie('sign_out', '');
     }
     Trigger::instance()->run('System/Index/postload');
 }
Example #12
0
 /**
  * Get array of pages structure
  *
  * @return array|bool
  */
 function get_structure()
 {
     $L = Language::instance();
     return $this->cache->get("structure/{$L->clang}", function () {
         return $this->get_structure_internal();
     });
 }
Example #13
0
/**
 * Formatting of data size in bytes to human-readable form
 *
 * @param int		$size
 * @param bool|int	$round
 *
 * @return float|string
 */
function format_filesize($size, $round = false)
{
    if (!is_numeric($size)) {
        return $size;
    }
    $L = Language::instance();
    $unit = '';
    if ($size >= 1099511627776.0) {
        $size = $size / 1099511627776.0;
        $unit = " {$L->TB}";
    } elseif ($size >= 1073741824) {
        $size = $size / 1073741824;
        $unit = " {$L->GB}";
    } elseif ($size >= 1048576) {
        $size = $size / 1048576;
        $unit = " {$L->MB}";
    } elseif ($size >= 1024) {
        $size = $size / 1024;
        $unit = " {$L->KB}";
    } else {
        $size = "{$size} {$L->Bytes}";
    }
    return $round ? round($size, $round) . $unit : $size . $unit;
}
Example #14
0
/**
 * Check backward dependencies (during uninstalling/disabling)
 *
 * @param string	$name	Component name
 * @param string	$type	Component type module|plugin
 * @param string	$mode	Mode of checking for modules uninstall|disable
 *
 * @return bool
 */
function check_backward_dependencies($name, $type = 'module', $mode = 'disable')
{
    switch ($type) {
        case 'module':
            $dir = MODULES . "/{$name}";
            break;
        case 'plugin':
            $dir = PLUGINS . "/{$name}";
            break;
        default:
            return false;
    }
    if (!file_exists("{$dir}/meta.json")) {
        return true;
    }
    $meta = file_get_json("{$dir}/meta.json");
    $return = true;
    $Config = Config::instance();
    $L = Language::instance();
    $Page = Page::instance();
    /**
     * Checking for backward dependencies of modules
     */
    $return_m = true;
    foreach ($Config->components['modules'] as $module => $module_data) {
        /**
         * If module uninstalled, disabled (in disable check mode), module name is the same as checking or meta.json file does not exists
         * Then skip this module
         */
        if ($module_data['active'] == -1 || $mode == 'disable' && $module_data['active'] == 0 || $module == $name && $type == 'module' || !file_exists(MODULES . "/{$module}/meta.json")) {
            continue;
        }
        $module_require = file_get_json(MODULES . "/{$module}/meta.json");
        if (!isset($module_require['require'])) {
            continue;
        }
        $module_require = dep_normal($module_require['require']);
        if (isset($module_require[$meta['package']]) || isset($meta['provide']) && array_intersect(array_keys($module_require), (array) $meta['provide'])) {
            if ($return_m) {
                $Page->warning($L->dependencies_not_satisfied);
            }
            $return_m = false;
            $Page->warning($L->this_package_is_used_by_module($module));
        }
    }
    $return = $return && $return_m;
    unset($return_m, $module, $module_data, $module_require);
    /**
     * Checking for backward dependencies of plugins
     */
    $return_p = true;
    foreach ($Config->components['plugins'] as $plugin) {
        if ($plugin == $name && $type == 'plugin' || !file_exists(PLUGINS . "/{$plugin}/meta.json")) {
            continue;
        }
        $plugin_require = file_get_json(PLUGINS . "/{$plugin}/meta.json");
        if (!isset($plugin_require['require'])) {
            continue;
        }
        $plugin_require = dep_normal($plugin_require['require']);
        if (isset($plugin_require[$meta['package']]) || isset($meta['provide']) && array_intersect(array_keys($plugin_require), (array) $meta['provide'])) {
            if ($return_p) {
                $Page->warning($L->dependencies_not_satisfied);
            }
            $return_p = false;
            $Page->warning($L->this_package_is_used_by_plugin($plugin));
        }
    }
    return $return && $return_p;
}
Example #15
0
 /**
  * Formatting data according to language locale (translating months names, days of week, etc.)
  *
  * @param string|string[]	$data
  * @param bool				$short_may	When in date() or similar functions "M" format option is used, third month "May"
  * 										have the same short textual representation as full, so, this option allows to
  * 										specify, which exactly form of representation do you want
  *
  * @return string|string[]
  */
 function to_locale($data, $short_may = false)
 {
     return Language::instance()->to_locale($data, $short_may);
 }
Example #16
0
 * @copyright      Copyright (c) 2014, Nazar Mokrynskyi
 * @license        MIT License, see license.txt
 */
namespace cs\modules\Precincts;

use cs\Cache\Prefix, cs\Index, cs\Language, cs\Page;
$Index = Index::instance();
$Page = Page::instance();
$Precincts = Precincts::instance();
if (isset($Index->route_ids[0])) {
    $Page->json($Precincts->get($Index->route_ids[0]));
    header('Cache-Control: max-age=60, public');
    header('Expires: access plus 1 minute');
} else {
    $Cache = new Prefix('precincts');
    $precincts = $Cache->get('all/ids_api/' . Language::instance()->clang, function () use($Precincts) {
        return $Precincts->get($Precincts->get_all());
    });
    if (isset($_GET['id'])) {
        $id = array_unique(_int(explode(',', $_GET['id'])));
        if ($id) {
            $precincts = array_filter($precincts, function ($precinct) use($id) {
                return in_array($precinct['id'], $id);
            });
            $precincts = array_values($precincts);
        }
    }
    if (isset($_GET['number'])) {
        if (isset($_GET['page'])) {
            $page = max((int) $_GET['page'], 1);
        } else {
Example #17
0
<?php

/**
 * @package		CleverStyle CMS
 * @subpackage	System module
 * @category	modules
 * @author		Nazar Mokrynskyi <*****@*****.**>
 * @copyright	Copyright (c) 2011-2014, Nazar Mokrynskyi
 * @license		MIT License, see license.txt
 */
namespace cs\modules\System;

use h, cs\Config, cs\Core, cs\Index, cs\Language;
$Config = Config::instance();
$L = Language::instance();
$Config->reload_languages();
$translate_engines = _mb_substr(get_files_list(ENGINES . '/Text', '/^[^_].*?\\.php$/i', 'f'), 0, -4);
$translate_engines_settings = [];
$current_engine_settings = '';
foreach ($translate_engines as $engine) {
    $parameters = file_get_json(ENGINES . '/Text/' . $engine . '.json');
    if (is_array($parameters) && !empty($parameters)) {
        $table = '';
        foreach ($parameters as $paremeter => $description) {
            $table .= h::{'tr td'}([$description, h::input(['name' => 'core[auto_translation_engine][' . $paremeter . ']', 'value' => isset($Config->core['auto_translation_engine'][$paremeter]) ? $Config->core['auto_translation_engine'][$paremeter] : ''])]);
        }
        $translate_engines_settings[] = base64_encode(h::table($table));
    } else {
        $translate_engines_settings[] = base64_encode($parameters ?: $L->no_settings_found);
    }
    if ($engine == $Config->core['auto_translation_engine']['name']) {
Example #18
0
 /**
  * Put or change data of cache item
  *
  * @param string	$item	May contain "/" symbols for cache structure, for example users/<i>user_id</i>
  * @param mixed		$data
  *
  * @return bool
  */
 function set($item, $data)
 {
     $data = @_json_encode($data);
     if (mb_strpos($item, '/') !== false) {
         $path = mb_substr($item, 0, mb_strrpos($item, '/'));
         if (!is_dir(CACHE . "/{$path}")) {
             @mkdir(CACHE . "/{$path}", 0700, true);
         }
         unset($path);
     }
     if (!file_exists(CACHE . "/{$item}") || is_writable(CACHE . "/{$item}")) {
         if ($this->cache_size > 0) {
             $dsize = strlen($data);
             if ($dsize > $this->cache_size) {
                 return false;
             }
             if (file_exists(CACHE . "/{$item}")) {
                 $dsize -= filesize(CACHE . "/{$item}");
             }
             $cache_size_file = fopen(CACHE . '/size', 'c+b');
             $time = microtime(true);
             while (!flock($cache_size_file, LOCK_EX | LOCK_NB)) {
                 if ($time < microtime(true) - 0.5) {
                     fclose($cache_size_file);
                     return false;
                 }
                 usleep(1000);
             }
             unset($time);
             $cache_size = (int) stream_get_contents($cache_size_file);
             $cache_size += $dsize;
             if ($cache_size > $this->cache_size) {
                 $cache_list = get_files_list(CACHE, false, 'f', true, true, 'date|desc');
                 foreach ($cache_list as $file) {
                     $cache_size -= filesize($file);
                     unlink($file);
                     $disk_size = $this->cache_size * 2 / 3;
                     if ($cache_size <= $disk_size * Config::instance()->core['update_ratio'] / 100) {
                         break;
                     }
                 }
                 unset($cache_list, $file);
             }
             if (($return = file_put_contents(CACHE . "/{$item}", $data, LOCK_EX | FILE_BINARY)) !== false) {
                 ftruncate($cache_size_file, 0);
                 fseek($cache_size_file, 0);
                 fwrite($cache_size_file, $cache_size > 0 ? $cache_size : 0);
             }
             flock($cache_size_file, LOCK_UN);
             fclose($cache_size_file);
             return $return;
         } else {
             return file_put_contents(CACHE . "/{$item}", $data, LOCK_EX | FILE_BINARY);
         }
     } else {
         $L = Language::instance();
         trigger_error($L->file . ' ' . CACHE . "/{$item} {$L->not_writable}", E_USER_WARNING);
         return false;
     }
 }