Файл: silawar.ru/protected/components/FuncHelper.php
Строк: 557
<?php
class FuncHelper extends CWidget {
/**
* Массив фильтров для аукциона
* @return array $filter массив фильтро
*/
public static function auctionFilters($value = null) {
$filter['levels'] = Array(1 => '1-5', 6 => '6-10', 11 => '11-15', 16 => '16-20', 21 => '21-25');
$filter['types'] = Array(1 => 'Голова', 'Амулет', 'Наплечник', 'Щит', 'Броня', 'Серьга', 'Штаны', 'Браслет', 'Перчатки', 'Кольцо', 'Оружие', 'Обувь');
$filter['qualities'] = Array(1 => 'Хлам', 'Обычный', 'Добротный', 'Замечательный', 'Редкий', 'Легендарный');
$filter['show'] = Array(1 => 'Лучше (+)', 'Не мои лоты', 'Мои лоты', 'Мои ставки');
$filter['sort'] = Array('time' => 'По времени', 'price' => 'По ставке', 'price_out' => 'По выкупу', 'strength' => 'По силе', 'health' => 'По здоровью', 'energy' => 'По энергии', 'regeneration' => 'По регенерации', 'armor' => 'По броне', 'all' => 'По сумме');
if ($value) {
return $filter[$value];
}
return $filter;
}
/**
* Вовращает массив параметров
* @return type
*/
public static function mainParams() {
return array(
'strength' => 'сила',
'health' => 'здоровье',
'energy' => 'энергия',
'regeneration' => 'регенерация',
'armor' => 'броня'
);
}
/**
* Конвертирует опыт в строку
* @param type $number
* @return string
*/
public static function convertXP($number) {
if ($number < 1000)
$result = number_format($number);
elseif ($number < 1000000)
$result = number_format($number / 1000, 2) . 'K';
elseif ($number < 1000000000)
$result = number_format($number / 1000000, 2) . 'M';
else
$result = number_format($number / 1000000000, 2) . 'G';
return $result;
}
/**
* Возвращает массив времени для премиума или значение по ключу
* @param string $key ключ
* @return массив или значение
*/
public static function premiumTimes($key = null) {
$array = array(1 => 60 * 60, 60 * 60 * 24, 60 * 60 * 24 * 3, 60 * 60 * 24 * 7, 60 * 60 * 24 * 30);
if ($key) {
return $array[$key];
}
return $array;
}
public static function abilityShopInfo($data) {
if ($data->id_ability == 1) {
return $data->value.'%';
}
elseif ($data->id_ability == 2) {
return $data->time_cooldown.' сек.';
}
elseif ($data->id_ability == 3) {
return $data->time_active.' сек.';
}
}
/**
* Возвращает массив цен для премиума или значение по ключу
* @param string $key ключ
* @return массив или значение
*/
public static function premiumPrices($key = null) {
$array = array(1 => 300, 2000, 5500, 10000, 20000);
if ($key) {
return $array[$key];
}
return $array;
}
public static function pagination($pagination = true) {
if ($pagination) {
return array(
'pageSize' => (int) Yii::app()->session['pageCount'] ? Yii::app()->session['pageCount'] : 50,
);
} else {
return array(
'pageSize' => 1000000, /* мильён! я не жадный! */
);
}
}
/**
* Текстовый фильтр для нового интерфейса
* @param array $model модель
* @param string $value название поля
* @return string $return возвращаем фильтр
*/
public static function getSearchFilter($model, $value) {
$name = get_class($model);
$return = CHtml::openTag('div', array('class' => 'input-group input-search'));
$return .= CHtml::textField($name . '[' . $value . ']', $model->$value, array('class' => 'form-control', 'placeholder' => Yii::t('layout', 'Поиск...')));
$return .= CHtml::openTag('span', array('class' => 'input-group-btn'));
$return .= '<button class="btn btn-default" type="submit"><i class="fa fa-search"></i></button>';
$return .= CHtml::closeTag('span');
$return .= CHtml::closeTag('div');
return $return;
}
/**
* Массив товаров для аукциона
* @return array $list
*/
public static function auctionTrade() {
return array('iron' => 'Железо', 'bottles' => 'Элексиры');
}
public static function sendCurl($url) {
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, $url);
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
$result = simplexml_load_string($output);
return $result;
}
/**
*
* @param array $model модель вещи с аукциона
* @param boolean $onlyNumber определяет возвращать число или отображение
* @return array параметр
*/
public static function auctionNextStep($model, $onlyNumber = false) {
$return = array();
if ($model->last) {
$return['step'] = (round($model->price * 1.1) > $model->price_out ? $model->price_out : round($model->price * 1.1));
} else {
$return['step'] = ($model->price > $model->price_out ? $model->price_out : $model->price);
}
if ($onlyNumber) {
return $return['step'];
} else {
//Делим число на золото и серебро
$step_value = self::moneyForForm($return['step']);
if ($step_value['gold'] > 0)
$return['gold'] = $step_value['gold'];
else
$return['gold'] = 0;
if ($step_value['silver'] > 0)
$return['silver'] = $step_value['silver'];
else
$return['silver'] = 0;
return $return;
}
}
/**
* Вычисляет оставшееся врамя на аукционе
* @param type $time указываем время
* @return string вывод оставшееся время
*/
public static function auctionTimeLeft($time) {
if ($time >= 3600 * 3) {
$hour = floor($time / 3600 % 24);
$text = 'более ' . $hour . ' ч.';
} elseif ($time > 3600) {
$hour = floor($time / 3600 % 24);
$text = 'менее ' . $hour . ' ч.';
} else
$text = 'менее 1 ч.';
return $text;
}
/**
* Отображает время, подходит для привата и прочего
* @param string $time
* @return string отображает время
*/
public static function time($time) {
if (date('z', $time) == date('z', time())) {
$text = date('H:i:s', $time);
} elseif (date('z', $time) == (date('z', time()) - 1)) {
$text = 'Вчера в ' . date('H:i', $time);
} else {
$text = date('j M в H:i', $time);
$monthes_en = array('Jan', 'Feb', 'Mar', 'May', 'Apr', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
$monthes_ru = array('Янв', 'Фев', 'Марта', 'Мая', 'Апр', 'Июня', 'Июля', 'Авг', 'Сент', 'Окт', 'Ноября', 'Дек');
$text = str_replace($monthes_en, $monthes_ru, $text);
}
return $text;
}
/**
* Отображает обратный отсчет времени
* @param string $time
* @return string отображает время
*/
public static function timeLeft($time, $hide = array()) {
if ($time > time())
$time -= time();
$month = $day = $hour = $min = $sec = 0;
$sec = $time % 60;
if ($time >= 60) {
$min = floor($time / 60 % 60);
}
if ($time >= 3600) {
$hour = floor($time / 3600 % 24);
}
if ($time >= 86400) {
$day = floor($time / 86400 % 30);
}
if ($time >= 2592000) {
$month = floor($time / 2592000 % 12);
}
$text = '';
if ($month) {
$text .= $month . ' месяц' . self::number($month, '', 'а', 'ев') . ' ';
}
if ($day) {
$text .= $day . ' ' . self::number($day, 'день', 'дня', 'дней') . ' ';
}
if ($hour) {
$text .= $hour . ' час' . self::number($hour, '', 'а', 'ов') . ' ';
}
if (!in_array('min', $hide)) {
if ($min && !$month) {
$text .= $min . ' минут' . self::number($min, 'а', 'ы', '') . ' ';
}
}
if (!in_array('sec', $hide)) {
if ($min && !$day) {
$text .= $sec . ' секунд' . self::number($sec, 'а', 'ы', '');
}
}
return $text;
}
/**
* Возвращает таймер в виде часы:минуты:секунды
* @param type $number
* @return type
*/
public static function timeToCount($number, $hide_hours = false) {
$hour = $min = $sec = 0;
$sec = $number % 60;
if ($number >= 60) {
$min = floor($number / 60 % 60);
}
if ($number >= 3600) {
$hour = floor($number / 3600 % 24);
}
$hour = str_pad($hour, 2, '0', STR_PAD_LEFT);
$min = str_pad($min, 2, '0', STR_PAD_LEFT);
$sec = str_pad($sec, 2, '0', STR_PAD_LEFT);
if ($hide_hours)
$text = $min . ':' . $sec;
else
$text = $hour . ':' . $min . ':' . $sec;
return $text;
}
/**
* Выводит текст типа (N дней назад) или (через N дней)
* @param type $time
* @return type
*/
function time_ago($time) {
$lengths = array("60", "60", "24", "7", "4.35", "12", "10");
if (time() > $time) {
$difference = time() - $time;
$old = true;
} else {
$difference = $time - time();
$old = false;
}
for ($j = 0; $difference >= $lengths[$j] && $j < count($lengths) - 1; $j++) {
$difference /= $lengths[$j];
}
$difference = round($difference);
$periods = array('секунд' . self::number($difference, 'а', 'ы', ''), 'минут' . self::number($difference, 'а', 'ы', ''), ' час' . self::number($difference, '', 'а', 'ов'), self::number($difference, 'день', 'дня', 'дней'), self::number($difference, 'неделя', 'недели', 'недель'), self::number($difference, 'месяц', 'месяца', 'месяцев'), self::number($difference, 'год', 'года', 'лет'));
if ($old)
return $difference . ' ' . $periods[$j] . ' назад';
else
return 'через ' . $difference . ' ' . $periods[$j];
}
/**
* Возвращает окончание строки по указанному числу
* @param integer $num число
* @param string $one окончание
* @param string $two окончание
* @param string $more окончание
* @return string возвращает окончание
*/
public static function number($num, $one, $two, $more) {
$num = (int) $num;
$checkFirst = substr($num, strlen($num) - 2, 2);
if ($checkFirst >= 5 && $checkFirst <= 20) {
return $more;
}
$checkLast = substr($num, strlen($num) - 1, 1);
switch ($checkLast) {
case 1:
return $one;
break;
case 2:
return $two;
break;
case 3:
return $two;
break;
case 4:
return $two;
break;
default:
return $more;
break;
}
}
/**
* Функция для вывода текста, пока такая, но должна быть лучше на Yii
* @param string $str строка с текстом взята с бд
* @param boolean $br переносы строк, вырезаем все нечитаемые символы, которые могут нам подпортить разметку :)
* @param boolean $html преобразуем все к нормальному перевариванию браузером
* @param boolean $antimat антимат
* @param boolean $antilink ссылки
* @param boolean $bbcode обработка bbcode
* @return string возвращаем обработанную строку
*/
public static function outputText($str, $br = true, $html = true, $antimat = true, $antilink = false, $bbcode = true) {
if ($html == true) {
$str = htmlentities($str, ENT_QUOTES, 'UTF-8');
}
if ($bbcode == true) {
$str = self::bbcodeForOutput($str);
}
if ($antimat == true) {
$str = strtr($str, array("блядь" => "[cenzor]", "cyкa" => "[cenzor]", "пидap" => "[cenzor]", "xyй" => "[cenzor]", "пиздa" => "[cenzor]", "зaлyпa" => "[cenzor]", "мyдaк" => "[cenzor]", "гнидa" => "[cenzor]", "лox" => "[cenzor]", "гaндoн" => "[cenzor]", "loh" => "[cenzor]"));
}
if ($antilink == true) {
$str = preg_replace("~^(?:(?:https?|ftp|telnet)://(?:[а-яёa-z0-9_-]{1,32}(?::[а-яёa-z0-9_-]{1,32})?@)?)?(?:(?:[а-яёa-z0-9-]{1,128}.)+(?:рф|ru|su|com|net|org|mil|edu|arpa|gov|biz|info|aero|inc|name|[a-z]{2})|(?!0)(?:(?!0[^.]|255)[0-9]{1,3}.){3}(?!0|255)[0-9]{1,3})(?:/[а-яёa-z0-9.,_@%&?+=~/-]*)?(?:#[^ '"&]*)?$~i", '[Реклама]', $str);
}
if ($br == true) {
$str = preg_replace("#((<br( ?/?)>)|n|r)+#i", '<br />', $str);
$str = self::escForOutput($str);
} else {
$str = preg_replace("#((<br( ?/?)>)|n|r)+#i", ' ', $str);
$str = self::escForOutput($str);
}
return $str;
}
/**
*
* @param string $text строка
* @param boolean $br хз даже если честно
* @return string строка
*/
public static function escForOutput($text, $br = NULL) {
$text = str_replace("'", """, $text);
if ($br != NULL) {
for ($i = 0; $i < 30; $i++)
$text = str_replace(chr($i), NULL, $text);
} else {
for ($i = 0; $i < 10; $i++) {
$text = str_replace(chr($i), NULL, $text);
}
for ($i = 11; $i < 20; $i++) {
$text = str_replace(chr($i), NULL, $text);
}
for ($i = 21; $i < 30; $i++) {
$text = str_replace(chr($i), NULL, $text);
}
}
return $text;
}
/**
* Подставляем ББ-тэги в строку
* @param string $str строка на входе
* @return string строка с тэгами
*/
public static function bbcodeForOutput($str) {
$str = preg_replace("#[img](.*?)[/img]#si", "<img src="\1"alt="*">", $str);
$str = preg_replace("#[span=(.*?)](.*?)[/span]#si", "<span style="\1">\2</span>", $str);
$str = preg_replace("#[b](.*?)[/b]#si", "<b>\1</b>", $str);
$str = preg_replace("#[i](.*?)[/i]#si", "<i>\1</i>", $str);
$str = preg_replace("#[del](.*?)[/del]#si", "<del>\1</del>", $str);
$str = preg_replace("#[ins](.*?)[/ins]#si", "<ins>\1</ins>", $str);
$str = preg_replace("#[a=(.*?)](.*?)[/a]#si", "<a href="\1">\2</a>", $str);
$str = preg_replace("#[color=(.*?)](.*?)[/color]#si", "<span style="color: \1">\2</span>", $str);
$str = preg_replace("#[left](.*?)[/left]#si", "<div align="left">\1</div>", $str);
$str = preg_replace("#[right](.*?)[/right]#si", "<div align="right">\1</div>", $str);
$str = preg_replace("#[center](.*?)[/center]#si", "<div align="center">\1</div>", $str);
$str = preg_replace("#[justify](.*?)[/justify]#si", "<div align="justify">\1</div>", $str);
$str = str_replace('rn', '<br/>', $str);
return $str;
}
/**
* Возвращает список тэгов для админов
* @param type $role_cat роль пользователя
* @return string список тэгов
*/
public static function textAreaTagsForAdmin($role_cat) {
$return = array();
if (RoleCategories::checkRoleForAdmins($role_cat)) {
$return[] = '<a href="#" onclick="return AddTagToMsg('[b]', '[/b]')">[b]</a> ';
$return[] = '<a href="#" onclick="return AddTagToMsg('[i]', '[/i]')">[i]</a> ';
$return[] = '<a href="#" onclick="return AddTagToMsg('[del]', '[/del]')">[del]</a> ';
$return[] = '<a href="#" onclick="return AddTagToMsg('[ins]', '[/ins]')">[ins]</a> ';
$return[] = '<a href="#" onclick="return AddTagToMsg('[left]', '[/left]')">[left]</a> ';
$return[] = '<a href="#" onclick="return AddTagToMsg('[right]', '[/right]')">[right]</a> ';
$return[] = '<a href="#" onclick="return AddTagToMsg('[center]', '[/center]')">[center]</a> ';
$return[] = '<a href="#" onclick="return AddTagToMsg('[justify]', '[/justify]')">[justify]</a> ';
$return[] = '<a href="#" onclick="return AddTagToMsg('[a=]', '[/a]')">[a]</a> ';
$return[] = '<a href="#" onclick="return AddTagToMsg('[img]', '[/img]')">[img]</a> ';
$return[] = '<a href="#" onclick="return AddTagToMsg('[color=]', '[/color]')">[color]</a> ';
}
$return = implode('', $return);
return $return;
}
public static function filterLevels($type) {
$types = Array(1 => '1-5', 6 => '6-10', 11 => '11-15', 16 => '16-20', 21 => '21-25');
return $levels[$value];
}
public static function getType($type) {
$types = Array(1 => 'Голова', 'Амулет', 'Наплечник', 'Щит', 'Броня', 'Серьга', 'Штаны', 'Браслет', 'Перчатки', 'Кольцо', 'Оружие', 'Обувь');
return $types[$type];
}
public static function getQuality($quality) {
$qualities = Array('без бонуса', 'хлам', 'обычный', 'добротный', 'замечательный', 'редкий', 'легендарный');
return $qualities[$quality];
}
/**
* Сравнивает параметры на вещах
* @param obj $item Вещь для просмотра
* @param obj $user_item Вещь того кто смотрит
* @return mixed
*/
public static function compareStats($item, $user_item) {
$result = array();
foreach (self::mainParams() as $param => $name) {
if ($item->$param > $user_item->$param)
$result[$param] = '<span class="green">' . $item->$param . '</span>';
elseif ($item->$param < $user_item->$param) {
$result[$param] = '<span class="red">' . $item->$param . '</span>';
} else {
$result[$param] = $item->$param;
}
}
return $result;
}
/**
* Сравнивает параметры на вещах
* @param obj $item Вещь для просмотра
* @param string $type тип, если 1 значит вещь юзера
* @return type
*/
public static function compareItemsView($item, $type = 1) {
if ($type == 1) {
$second_item = UserItems::findUserItem($item);
}
$compare = array();
foreach (self::mainParams() as $param => $name) {
if ($second_item) {
if ($item->$param > $second_item->$param)
$compare[$param] = '<span class="green">' . $item->$param . '</span>';
elseif ($item->$param < $second_item->$param) {
$compare[$param] = '<span class="red">' . $item->$param . '</span>';
} else {
$compare[$param] = $item->$param;
}
} else {
if ($item->id_user == Yii::app()->user->id && $item->status == ITEM_ON_BODY) {
$compare[$param] = $item->$param;
} else {
$compare[$param] = '<span class="green">' . $item->$param . '</span>';
}
}
}
$item->sum = $item->health + $item->armor + $item->strength + $item->regeneration + $item->energy;
if ($second_item) {
$better = ($item->sum > $second_item->sum ? $item->sum - $second_item->sum : false);
} else {
if ($item->id_user == Yii::app()->user->id && $item->status == ITEM_ON_BODY) {
$better = 0;
} else {
$better = $item->sum;
}
}
$result = '
<div class="item-view">
<div class="item-view_img">
<img src="/images/items/' . $item->img . '.jpg">
</div>
<div class="item-view_info">
<img src="/images/icons/quality/' . $item->quality . '.png"> ' . FuncHelper::getQuality($item->quality) . '
' . (!isset($item->personal) && $item->personal > 0 ? ', личный' : '') . ' <br />
' . $item->name . '<br />
' . FuncHelper::getType($item->type) . ', <b>' . $item->level . '</b> уровень<br />
</div>
</div>
<hr>
<div class="item-stats">';
foreach (FuncHelper::mainParams() as $param => $name) {
if ($item->$param) {
$percent = $param . '_percent';
$result .= '<img src="/images/icons/' . $param . '.png"> ' . $name . ': ' . $compare[$param] . ' <span class="percent">(' . $item->$percent . '%)</span><br />';
}
}
if (!isset($item->enchant_type) && $item->enchant_type > 0) {
$result .= '<hr><img src="/images/icons/star_green.png"> <span class="green">Чары: <img src="/images/icons/quality/' . $item->enchant_type . '.png" alt="*"/> ' . UserItems::enchantInfo($item->id_item) . '</span>';
}
if ($better) {
$result .= '<hr><img src="/images/icons/star_green.png"> <span class="green">Лучше (+' . $better . ')</span><br />';
}
$result .= '</div>';
return $result;
}
public static function betterItem($id_item) {
$criteria = new CDbCriteria;
$criteria->select = array('type');
$criteria->compare('id_item', $id_item);
$item = UserItems::model()->find($criteria);
$item->all = UserItems::calcAllParams($id_item);
/*
* Выбираем аналогичную надетую шмотку у пользователя
*/
$criteria = new CDbCriteria;
$criteria->select = array('id_item');
$criteria->compare('id_user', Yii::app()->user->id);
$criteria->compare('type', $item->type);
$criteria->compare('status', ITEM_ON_BODY);
$user_item = UserItems::model()->find($criteria);
if ($user_item) {
$all = UserItems::calcAllParams($user_item->id_item);
} else
$all = 0;
return $item->all - $all;
}
/*
* Выыводит кол-во монет с бд в нормальное представление
*/
public static function money($value) {
$gold = floor($value / 100);
$silver = $value % 100;
$result = null;
if ($gold > 0)
$result .= '<img src="/images/icons/money_gold.png" alt="*"/>' . $gold;
if ($silver > 0)
$result .= '<img src="/images/icons/money_silver.png" alt="*"/>' . $silver;
if ($gold < 1 && $silver < 1)
$result .= '<img src="/images/icons/money_silver.png" alt="*"/>0';
return $result;
}
/*
* Делит число монет отдельно на золото и серебро
* Для всяких форм и прочих проверок
*/
public static function moneyForForm($value) {
$result = array();
$result['gold'] = floor($value / 100);
$result['silver'] = $value % 100;
return $result;
}
public static function guildActionsAccess($user, $member, $guild) {
$result[0] = '';
if ($guild->level < 2) {
if ($user->guild_rank >= 3 AND $member->guild_rank < 3) {
$result[] = CHtml::link('[повысить]', array('/guild/upper/', 'id' => $member->id_user));
}
if ($user->guild_rank >= 3 AND $member->guild_rank > 1 AND $member->guild_rank < $user->guild_rank) {
$result[] = CHtml::link('[понизить]', array('/guild/lower/', 'id' => $member->id_user));
}
if ($user->guild_rank >= $guild->rank_kick) {
$result[] = CHtml::link('[исключить]', array('/guild/kick/', 'id' => $member->id_user));
}
if ($user->guild_rank == 5 AND $member->guild_rank > 2) {
$result[] = CHtml::link('[передать лидера]', array('/guild/swap/', 'id' => $member->id_user));
}
} elseif ($guild->level < 4) {
if ($user->guild_rank >= 3 AND $member->guild_rank < 3) {
$result[] = CHtml::link('[повысить]', array('/guild/upper/', 'id' => $member->id_user));
}
if ($user->guild_rank >= 3 AND $member->guild_rank > 0 AND $member->guild_rank < $user->guild_rank) {
$result[] = CHtml::link('[понизить]', array('/guild/lower/', 'id' => $member->id_user));
}
if ($user->guild_rank >= $guild->rank_kick) {
$result[] = CHtml::link('[исключить]', array('/guild/kick/', 'id' => $member->id_user));
}
if ($user->guild_rank == 5 AND $member->guild_rank > 2) {
$result[] = CHtml::link('[передать лидера]', array('/guild/swap/', 'id' => $member->id_user));
}
} else {
if ($user->guild_rank >= 3 AND $member->guild_rank < $user->guild_rank AND $member->guild_rank < 4) {
$result[] = CHtml::link('[повысить]', array('/guild/upper/', 'id' => $member->id_user));
}
if ($user->guild_rank >= 3 AND $member->guild_rank > 0 AND $member->guild_rank < $user->guild_rank) {
$result[] = CHtml::link('[понизить]', array('/guild/lower/', 'id' => $member->id_user));
}
if ($user->guild_rank >= $guild->rank_kick) {
$result[] = CHtml::link('[исключить]', array('/guild/kick/', 'id' => $member->id_user));
}
if ($user->guild_rank == 5 AND $member->guild_rank > 3) {
$result[] = CHtml::link('[передать лидера]', array('/guild/swap/', 'id' => $member->id_user));
}
}
if (!empty($result))
$result[0] = '<br />';
return implode(' ', $result);
}
}
?>