Skip to content

Commit

Permalink
v0.6
Browse files Browse the repository at this point in the history
  • Loading branch information
dragomano committed Jan 18, 2020
1 parent 2bda7f7 commit 1875c27
Show file tree
Hide file tree
Showing 53 changed files with 1,418 additions and 346 deletions.
64 changes: 59 additions & 5 deletions Sources/LightPortal/Block.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
* @copyright 2019-2020 Bugo
* @license https://opensource.org/licenses/BSD-3-Clause BSD
*
* @version 0.5
* @version 0.6
*/

if (!defined('SMF'))
Expand All @@ -21,14 +21,15 @@ class Block
{
/**
* Display blocks in their designated areas
*
* Отображаем блоки в предназначенных им областях
*
* @param string $area
* @return void
*/
public static function display($area = 'portal')
{
global $context;
global $context, $modSettings;

if (empty($context['template_layers']))
return;
Expand All @@ -38,7 +39,7 @@ public static function display($area = 'portal')
return isset($block['areas']['all']) || isset($block['areas'][$area]) || isset($block['areas']['page=' . filter_input(INPUT_GET, 'page', FILTER_SANITIZE_STRING)]);
});

if (empty($blocks))
if (empty($blocks) || (!empty($modSettings['lp_hide_blocks_in_admin_section']) && $context['current_action'] == 'admin'))
return;

foreach ($blocks as $item => $data) {
Expand All @@ -59,7 +60,6 @@ public static function display($area = 'portal')

loadTemplate('LightPortal/ViewBlock');

// Zen for layers | Дзен для слоев
$counter = 0;
foreach ($context['template_layers'] as $position => $name) {
$counter++;
Expand All @@ -76,6 +76,7 @@ public static function display($area = 'portal')

/**
* Manage blocks
*
* Управление блоками
*
* @return void
Expand All @@ -102,6 +103,7 @@ public static function manage()

/**
* Get a list of all blocks sorted by placement
*
* Получаем список всех блоков с разбивкой по размещению
*
* @return void
Expand Down Expand Up @@ -131,13 +133,15 @@ public static function getAll()
);

$context['lp_current_blocks'][$row['placement']][$row['block_id']]['title'][$row['lang']] = $row['title'];
Helpers::findMissingBlockTypes($row['type']);
}

$smcFunc['db_free_result']($request);
}

/**
* Possible actions with blocks
*
* Возможные действия с блоками
*
* @return void
Expand All @@ -163,6 +167,7 @@ private static function postActions()

/**
* Deleting a block
*
* Удаление блока
*
* @return void
Expand Down Expand Up @@ -214,6 +219,7 @@ private static function remove()

/**
* Changing the block status
*
* Смена статуса блока
*
* @param int $item
Expand All @@ -240,6 +246,7 @@ public static function toggleStatus($item, $status)

/**
* Update priority
*
* Обновление приоритета
*
* @return void
Expand Down Expand Up @@ -290,6 +297,7 @@ private static function updatePriority()

/**
* Adding a block
*
* Добавление блока
*
* @return void
Expand Down Expand Up @@ -330,6 +338,7 @@ public static function add()

/**
* Editing a block
*
* Редактирование блока
*
* @return void
Expand Down Expand Up @@ -375,6 +384,7 @@ public static function edit()

/**
* Get the parameters of all blocks
*
* Получаем параметры всех блоков
*
* @return array
Expand All @@ -400,6 +410,7 @@ private static function getOptions()

/**
* Validating the sent data
*
* Валидируем отправляемые данные
*
* @return void
Expand Down Expand Up @@ -438,6 +449,10 @@ private static function validateData()
}

$options = self::getOptions();

if (empty($options[$context['current_block']['type']]))
$options[$context['current_block']['type']] = [];

$block_options = $context['current_block']['options'] ?? $options;

$context['lp_block'] = array(
Expand Down Expand Up @@ -474,6 +489,7 @@ private static function validateData()

/**
* Check that the fields are filled in correctly
*
* Проверям правильность заполнения полей
*
* @param array $data
Expand All @@ -499,6 +515,7 @@ private static function findErrors($data)

/**
* Adding special fields to the form
*
* Добавляем свои поля для формы
*
* @return void
Expand Down Expand Up @@ -652,6 +669,7 @@ private static function prepareFormFields()

/**
* Run the desired editor
*
* Подключаем нужный редактор
*
* @return void
Expand All @@ -666,6 +684,7 @@ private static function prepareEditor()

/**
* Preview
*
* Предварительный просмотр
*
* @return void
Expand Down Expand Up @@ -695,8 +714,39 @@ private static function showPreview()
$context['preview_title'] = self::getIcon() . Helpers::getPreviewTitle();
}

/**
* Get correct priority for a new block
*
* Получаем правильный приоритет для нового блока
*
* @param string $placement
* @return int
*/
private static function calculatePriority($placement)
{
global $smcFunc;

if (empty($placement))
return 0;

$request = $smcFunc['db_query']('', '
SELECT MAX(priority) + 1
FROM {db_prefix}lp_blocks
WHERE placement = {string:placement}',
array(
'placement' => $placement
)
);

list ($priority) = $smcFunc['db_fetch_row']($request);
$smcFunc['db_free_result']($request);

return $priority;
}

/**
* Creating or updating a block
*
* Создаем или обновляем блок
*
* @param int $item
Expand All @@ -714,6 +764,8 @@ public static function setData($item = null)
if (empty($item)) {
$max_length = Helpers::getMaxMessageLength();

$priority = self::calculatePriority($context['lp_block']['placement']);

$item = $smcFunc['db_insert']('',
'{db_prefix}lp_blocks',
array(
Expand All @@ -734,7 +786,7 @@ public static function setData($item = null)
$context['lp_block']['type'],
$context['lp_block']['content'],
$context['lp_block']['placement'],
$context['lp_block']['priority'],
$context['lp_block']['priority'] ?: $priority,
$context['lp_block']['permissions'],
$context['lp_block']['areas'],
$context['lp_block']['title_class'],
Expand Down Expand Up @@ -860,6 +912,7 @@ public static function setData($item = null)

/**
* Get the block fields
*
* Получаем поля блока
*
* @param mixed $item
Expand Down Expand Up @@ -924,6 +977,7 @@ public static function getData($item)

/**
* Get the block icon
*
* Получаем иконку блока
*
* @param string $icon
Expand Down
60 changes: 58 additions & 2 deletions Sources/LightPortal/Helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
* @copyright 2019-2020 Bugo
* @license https://opensource.org/licenses/BSD-3-Clause BSD
*
* @version 0.5
* @version 0.6
*/

if (!defined('SMF'))
Expand All @@ -21,6 +21,7 @@ class Helpers
{
/**
* Get language of the current user
*
* Получаем язык текущего пользователя
*
* @return string
Expand All @@ -34,6 +35,7 @@ public static function getUserLanguage()

/**
* Get the maximum possible length of the message, in accordance with the settings of the forum
*
* Получаем максимально возможную длину сообщения, в соответствии с настройками форума
*
* @return int
Expand All @@ -47,6 +49,7 @@ public static function getMaxMessageLength()

/**
* Remove BBCode from transmitted data
*
* Убираем ББ-код из переданных данных
*
* @param array|string $data
Expand All @@ -62,6 +65,7 @@ public static function cleanBbcode($data)

/**
* Get a title for preview block
*
* Получаем заголовок блока превью
*
* @return string
Expand All @@ -75,6 +79,7 @@ public static function getPreviewTitle()

/**
* Get text within span that is floating by defined direction
*
* Получаем текст внутри тега span, с float = $direction (left|right)
*
* @param string $text
Expand All @@ -88,7 +93,9 @@ private static function getFloatSpan($text, $direction = 'left')

/**
* The correct declination of words
*
* Правильное склонение слов
*
* https://developer.mozilla.org/en-US/docs/Mozilla/Localization/Localization_and_Plurals
* http://docs.translatehouse.org/projects/localization-guide/en/latest/l10n/pluralforms.html
*
Expand Down Expand Up @@ -162,6 +169,7 @@ public static function correctDeclension(int $num, $str)

/**
* Get the time in the format "Yesterday", "Today", "X minutes ago", etc.
*
* Получаем время в формате «Вчера», «Сегодня», «X минут назад» и т. д.
*
* @param integer $a — Unix time
Expand All @@ -179,7 +187,8 @@ public static function getFriendlyTime(int $a)
$sec = $time - $a;
$last = round(($sec) / 60);

// Future time? | Будущее время?
// Future time?
// Будущее время?
if ($a > $time) {
$days = ($a - $time) / 60 / 60 / 24;

Expand Down Expand Up @@ -211,4 +220,51 @@ public static function getFriendlyTime(int $a)
else
return timeformat($a);
}

/**
* Using cache
*
* Используем кэш
*
* @param string $data
* @param string $getData
* @param string $class
* @param int $time (in seconds)
* @param array $vars
* @return mixed
*/
public static function useCache($data, $getData, $class = 'self', $time = 3600, $vars = [])
{
if (($$data = cache_get_data('light_portal_' . $data, $time)) == null) {
$$data = null;

if (method_exists($class, $getData)) {
if ($class == 'self')
$$data = self::$getData($vars);
else
$$data = $class::$getData($vars);
} elseif (function_exists($getData)) {
$$data = $getData($vars);}

cache_put_data('light_portal_' . $data, $$data, $time);
}

return $$data;
}

/**
* Form a list of addons that not installed
*
* Формируем список неустановленных плагинов
*
* @param string $type
* @return void
*/
public static function findMissingBlockTypes($type)
{
global $txt, $context;

if (empty($txt['lp_block_types'][$type]))
$context['lp_missing_block_types'][$type] = sprintf($txt['lp_addon_not_installed'], str_replace('_', '', ucwords($type, '_')));
}
}
Loading

0 comments on commit 1875c27

Please sign in to comment.