Пример #1
0
 /**
  * Выполнение очистки сайта
  * @param bool $force выполнять клинап вне зависимости от времени
  * @return null
  */
 public function execute($force = false)
 {
     if (!longval(config::o()->v('cleanup_each'))) {
         return;
     }
     $hour = 3600;
     // Секунд в часу
     $time = stats::o()->read('last_cleanup');
     if (!$force && time() < $time + config::o()->v('cleanup_each') * $hour) {
         return;
     }
     stats::o()->write('last_cleanup', time());
     users::o()->admin_mode();
     users::o()->set_tmpvars(array('id' => -1));
     /* @var $mailer mailer */
     $mailer = n("mailer");
     $mailer->change_type('content')->cleanup();
     $mailer->change_type('categories')->cleanup();
     /* @var $attach attachments */
     $attach = n("attachments");
     $attach->clear();
     users::o()->groups_autoupdate();
     foreach ($this->methods as $m) {
         $this->call_method('clear_' . $m);
     }
     users::o()->remove_tmpvars();
     users::o()->admin_mode(false);
     //cache::o()->clear_ocache(config::o()->v('cache_oldtime') * 3600);
 }
Пример #2
0
 /**
  * Получение ID подкатегорий, если необходимо
  * @param array $curcats массив выбранных категорий
  * @return null
  */
 protected function get_children(&$curcats)
 {
     if (!$this->settings['check_children']) {
         return;
     }
     /* @var $cats categories */
     $cats = n("categories");
     foreach ($curcats as $name => $cat) {
         $cat = explode('|', $cat);
         $c = count($cat);
         $ids = array();
         for ($i = 0; $i < $c; $i++) {
             $ic = longval($cat[$i]);
             if (!$ic || !$cats->get($ic)) {
                 continue;
             }
             $ids[] = $ic;
             $cats->get_children_ids($ic, $ids);
         }
         if (!$ids) {
             unset($curcats[$name]);
             continue;
         }
         $ids = array_unique($ids);
         $curcats[$name] = implode('|', $ids);
     }
 }
Пример #3
0
 /**
  * Подсчёт кол-ва контента в данном месяце и в данном году
  * @param int $month данный месяц
  * @param int $year данный год
  * @return string JS массив кол-ва торрентов по дням
  */
 public function count_content($month = null, $year = null)
 {
     $month = !$month ? date("n") : $month;
     $year = !$year ? date("Y") : $year;
     if (!($r = cache::o()->read('calendar/c' . $month . '-' . $year))) {
         $year_after = $month == 12 ? $year + 1 : $year;
         $month_after = $month < 12 ? $month + 1 : 1;
         $from = mktime(null, null, null, $month, 1, $year);
         $to = mktime(null, null, null, $month_after, 1, $year_after);
         $datas = db::o()->p($from, $to)->query('SELECT posted_time FROM content 
             WHERE posted_time BETWEEN ? AND ?');
         //$count = count($datas);
         $content = array();
         while ($data = db::o()->fetch_assoc($datas)) {
             $day = date("j", $data["posted_time"]);
             $content[$day]++;
         }
         $ncontent = "";
         for ($i = 0; $i <= 31; $i++) {
             $ncontent .= ($ncontent !== "" ? ", " : "") . longval($content[$i]);
         }
         $r = array("new Array(" . $ncontent . ")");
         cache::o()->write($r);
     }
     return $r[0];
 }
Пример #4
0
 /**
  * Функция инициализации Ajax функций для главной страницы
  * @return null
  */
 public function init()
 {
     $act = $_GET['act'];
     switch ($act) {
         case "feedback":
             $this->feedback($_POST);
             ok();
             break;
         case "modsettings":
             modsettings::o()->make_demo($_POST);
             break;
         case "calendar_content":
             $year = (int) $_POST["year"];
             $month = (int) $_POST["month"];
             $this->calendar_content($month, $year);
             break;
         case "search_pre":
             $text = $_POST["text"];
             $this->search_pre($text);
             break;
         case "move_unread":
             $time = (int) $_POST["time"];
             $after = (bool) $_POST['after'];
             $this->move_unread($time, $after);
             break;
         case "get_msgs":
             $this->get_msgs();
             break;
         case "children_cat":
             $id = (int) $_POST["id"];
             $type = $_POST['type'];
             $num = longval($_POST['num']) + 1;
             $this->children_cat($id, $num, $type);
             break;
         case "check_pattern":
             $id = (int) $_GET["id"];
             $this->check_pattern($id);
             break;
         case "build_pattern":
             $id = (int) $_GET["id"];
             $this->build_pattern($id);
             break;
         default:
             break;
     }
 }
Пример #5
0
 /**
  * Функция инициализации Ajax-части ЛС
  * @return null
  */
 public function init()
 {
     users::o()->check_perms('pm');
     lang::o()->get('messages');
     $act = $_GET['act'];
     switch ($act) {
         case "send_ok":
             $to_unames = $_POST['to_usernames'];
             $to_groups = $_POST['to_groups'];
             $title = $_POST['title'];
             $descr = $_POST['body'];
             $this->confirm_send($to_unames, $to_groups, $title, $descr);
             ok();
             break;
         case "send":
             $to = $_GET['to'];
             $id = longval($_GET['id']);
             $this->send($to, $id);
             break;
         case "read":
             $id = (int) $_POST['id'];
             $this->show_simple($id);
             break;
         case "s_read":
             $ids = $_POST['item'];
             $this->read($ids);
             ok();
             break;
         case "delete":
             $ids = $_POST['item'];
             $this->delete($ids);
             ok();
             break;
         default:
             $out = (bool) $_GET['out'];
             $sended = (bool) $_GET['sended'];
             $this->show($out, $sended);
             break;
     }
 }
Пример #6
0
 /**
  * Инициализация управления комментариями
  * @return null
  */
 public function init()
 {
     $act = $_GET['act'];
     $this->comments = n("comments");
     switch ($act) {
         case "edit":
             $id = longval($_POST['id']);
             $this->edit_form($id);
             break;
         case "add":
         case "edit_save":
             $content = $_POST['body'];
             $resid = longval($_POST['resid']);
             $type = $_POST['type'];
             $id = longval($_POST['id']);
             $this->save($content, $resid, $type, $id);
             ok();
             break;
         case "show":
             $resid = longval($_POST['resid']);
             $type = $_POST['type'];
             $this->show($resid, $type);
             break;
         case "del":
             $id = (int) $_POST["id"];
             $this->delete($id);
             ok();
             break;
         case "quote":
             $id = (int) $_POST["id"];
             $this->quote($id);
             die;
         default:
             break;
     }
 }
Пример #7
0
 /**
  * Получение первого и второго IP
  * @param string $firstip первый IP
  * @param string $lastip второй IP
  * @param bool $long преобразовывать в long?
  * @return null
  */
 public function get_ips(&$firstip, &$lastip, $long = false)
 {
     if ($long) {
         $firstip = ip2ulong($firstip);
         $lastip = ip2ulong($lastip);
     } else {
         $ip_f = longval($ip_f);
         $ip_t = longval($ip_t);
     }
     if ($lastip && !$firstip) {
         $firstip = $lastip;
     }
     if ($firstip && !$lastip) {
         $lastip = $firstip;
     }
     if ($firstip > $lastip && $lastip) {
         $t = $firstip;
         $firstip = $lastip;
         $lastip = $t;
     }
 }
Пример #8
0
 /**
  * Отметка проверенным
  * @param int $id ID контента
  * @return null
  */
 public function check($id = "")
 {
     users::o()->check_perms('edit_content', '2');
     $id = longval($id);
     if ($this->tstate) {
         db::o()->p($id)->update(array('status' => 'checked', 'statusby' => users::o()->v('id')), "content_torrents", 'WHERE status="0"' . ($id ? ' AND cid=?' : ''));
     }
     db::o()->p($id)->update(array('on_top' => '1'), "content", $id ? 'WHERE id=?' : '');
 }
Пример #9
0
 /**
  * Обработка значений для preg_replace_callback тега hide
  * @param array $matches входящий массив парсенной строки
  * @param bool $rss RSS?
  * @return string HTML код
  */
 protected function pcre_callback_hide($matches, $rss = false)
 {
     $vars = array();
     if (users::o()->v()) {
         if ($matches[1]) {
             $matches[1] = longval(trim($matches[1]));
             if ($matches[1] <= users::o()->v('content_count')) {
                 return $matches[3];
             }
             if (!$rss) {
                 $vars = array($matches[1], users::o()->v('content_count'));
                 $text = "hidden_need_content_you_have";
             }
         } elseif ($matches[2]) {
             $grps = array_map('longval', explode(",", $matches[2]));
             $c = count($grps);
             for ($i = 0; $i < $c; $i++) {
                 if (!users::o()->get_group($grps[$i])) {
                     continue;
                 }
                 if (!$rss) {
                     $pretext .= ($pretext ? ", " : "") . display::o()->user_group_color($grps[$i]);
                 }
                 if (users::o()->v('group') == $grps[$i]) {
                     return $matches[3];
                 }
             }
             if (!$rss) {
                 $vars = array($pretext, display::o()->user_group_color(users::o()->v('group')));
                 $text = "hidden_group_to_see";
             }
         } else {
             return $matches[3];
         }
     }
     if (!$rss) {
         $text = "hidden_register_to_see";
     }
     //else
     //    return $matches[3];
     if (!$rss) {
         if (!$vars) {
             $vars = furl::o()->construct("registration");
         }
         ob_start();
         /* @var $m message */
         $m = n("message");
         $m->stitle("hidden_text")->sonly_box()->info($text, $vars);
         $cont = ob_get_contents();
         ob_end_clean();
         return $cont;
     }
     return lang::o()->v('hidden_text');
 }
Пример #10
0
 /**
  * Конвертация объёма данных вида %число%(K|M|G|T) в %число%(куда конвертируем), 
  * если конвертируемый объём больше входного значения
  * @param string $v объём данных
  * @param string $to куда конвертируем
  * @return string значение
  */
 protected function convert_filesize($v, $to)
 {
     $l = strlen($v) - 1;
     $pv = $v[$l];
     if (!is_numeric($pv)) {
         $v = longval(substr($v, 0, $l));
     }
     $a = array('K' => 1, 'M' => 2, 'G' => 3, 'T' => 4);
     $pv = (int) $a[strtoupper($pv)];
     $to = (int) $a[strtoupper($to)];
     if ($to >= $pv) {
         return $v;
     }
     return pow(1024, $pv - $to);
 }
Пример #11
0
 /**
  * Функция сохранения комментария
  * @param string $content содержание комментария
  * @param int $resid ID ресурса
  * @param int $id ID комментария
  * @return bool true в случае успешного сохранения комментария
  * @throws EngineException 
  */
 public function save($content, $resid = "", $id = "")
 {
     if (!$this->state) {
         return;
     }
     $type = $this->type;
     lang::o()->get('comments');
     $id = longval($id);
     /* @var $etc etc */
     $etc = n("etc");
     if (!$id) {
         users::o()->check_perms('comment', 2, 2);
         if (!users::o()->v()) {
             $error = array();
             n("captcha")->check($error);
             if ($error) {
                 return implode("\n", $error);
             }
         }
     } else {
         $q = db::o()->p($id)->query('SELECT poster_id FROM comments WHERE id = ? LIMIT 1');
         $poster = db::o()->fetch_assoc($q);
         if (!$poster) {
             throw new EngineException('comment_was_deleted');
         }
         if ($poster['poster_id'] == users::o()->v('id')) {
             users::o()->check_perms('edit_comm');
         } else {
             users::o()->check_perms('edit_comm', 2);
         }
     }
     $content = trim($content);
     $poster = users::o()->v('id') ? users::o()->v('id') : -1;
     if (!longval($resid) && $resid || !longval($id) && $id || !$id && !$resid) {
         throw new EngineException('comment_wrong_data');
     }
     if (!$content || mb_strlen($content) < config::o()->v('min_comm_symb')) {
         throw new EngineException('comment_small_text');
     }
     if (!$id) {
         $etc->anti_flood('comments', 'toid=' . $resid . ' AND type=' . db::o()->esc($type), array('poster_id', 'edited_time'));
     }
     $upd = array();
     if (!$id) {
         $id = $this->check_double_comment($resid, $content);
         if ($id) {
             $upd["edited_time"] = time();
             unset($upd["subject"]);
         }
     }
     $upd["text"] = $content;
     try {
         plugins::o()->pass_data(array('update' => &$upd, "id" => $id), true)->run_hook('comments_save');
     } catch (PReturn $e) {
         return $e->r();
     }
     if (!$id) {
         $upd = array_merge($upd, array("posted_time" => time(), "edited_time" => time(), "poster_id" => $poster, "toid" => $resid, "type" => $type));
         db::o()->insert($upd, "comments");
         $etc->add_res('comm');
         db::o()->no_error();
         $etc->add_res('comm', 1, $type, $resid);
         /* @var $mailer mailer */
         $mailer = n("mailer");
         $mailer->change_type($type)->update($resid);
     } else {
         db::o()->p($id)->update($upd, "comments", 'WHERE id = ? LIMIT 1');
         log_add("edited_comment", "user", array($id));
     }
     return true;
 }
Пример #12
0
 /**
  * Декодирование числа из Bencode
  * @param string $s кодированное число
  * @param string $left ссылка на оставщуюся строку
  * @return int число
  */
 protected function bdec_int($s, &$left = null)
 {
     if (!preg_match('/^i([\\-\\d]+)e(.*)$/s', $s, $m)) {
         return;
     }
     $v = $m[1];
     if ($v === "-0") {
         return;
     }
     if ($v[0] == "0" && strlen($v) != 1) {
         return;
     }
     $left = $m[2];
     return (double) longval($v);
     // сначала "длинное" целое, потом меняем тип
 }
Пример #13
0
 /**
  * Функция выборки категорий
  * Параметры: current, size, null, type
  * @param string $name имя поля
  * @param string $nbsp префикс категорий(необходимо для рекурсии)
  * @param array $carr массив категорий(необходимо для рекурсии)
  * @return string HTML-код выборки
  */
 public function select_categories($name = "categories", $nbsp = null, $carr = null)
 {
     if (!is_array($name)) {
         $this->join_params($name);
     } else {
         $nbsp = null;
         $carr = null;
     }
     $current = $name['current'];
     $size = $name['size'];
     $null = $name["null"];
     $type = $name['type'];
     $name = $name['name'];
     if (!$name) {
         $name = "categories";
     }
     if (!longval($size)) {
         $size = 5;
     }
     /* @var $cats categories */
     $cats = n("categories");
     $cats->change_type($type);
     if (!is_array($carr) || !$carr) {
         $carr = $cats->get(null, 't');
         $select = "<select name='" . $name . "" . ($size == 1 ? "" : "[]'\nmultiple='multiple") . "' \n                " . ($null ? " onclick='clear_select(this)'" : "") . "\n                size='" . longval($size) . "'>";
         $first_run = true;
         $nbsp = "";
         if ($null) {
             $select .= $this->get_null_text();
         }
     }
     $count = count($carr);
     for ($i = 0; $i < $count; $i++) {
         $id = $carr[$i]["id"];
         $select .= "<option value='" . $id . "'\n                " . ($current == $id ? " selected='selected'" : '') . ">" . $nbsp . $carr[$i]["name"] . "</option>";
         $a = $cats->get($id, 'c');
         if ($a) {
             $select .= $this->stype($type)->select_categories($name, $nbsp . "&nbsp;&nbsp;&nbsp;", $a);
         }
     }
     if ($first_run) {
         $select .= "</select>";
     }
     return $select;
 }
Пример #14
0
 /**
  * Обработка значения настроек
  * @param object $object объект модуля
  * @param array $settings массив параметров
  * @param mixed $count кол-во ключей
  * @param string $param параметр
  * @param string $type тип значения
  * @return null
  */
 private function value(&$object, $settings, $count, $param, $type)
 {
     switch ($type) {
         case "text":
         case "string":
             if ($count) {
                 $object->settings[$param] = array_map("strval", $settings[$param]);
             } else {
                 $object->settings[$param] = strval($settings[$param]);
             }
             break;
         case "integer":
             if ($count) {
                 $object->settings[$param] = array_map("intval", $settings[$param]);
             } else {
                 $object->settings[$param] = longval($settings[$param]);
             }
             break;
         default:
             if (!is_array($type)) {
                 unset($object->settings[$param]);
             } else {
                 if ($count) {
                     $ret = array_filter($settings[$param], array($this, "enum"));
                     if ($ret) {
                         $object->settings[$param] = $ret;
                     } else {
                         unset($object->settings[$param]);
                     }
                 } else {
                     if (in_array($settings[$param], $this->enum_vals)) {
                         $object->settings[$param] = $settings[$param];
                     } else {
                         unset($object->settings[$param]);
                     }
                 }
             }
             break;
     }
 }
Пример #15
0
/**
 * ID ли это? (long и больше 0)
 * @param mixed $id проверяемая переменная
 * @return bool true, если таки ID
 */
function validid($id)
{
    return longval($id) == $id && $id > 0;
}
Пример #16
0
 /**
  * Метод обработки параметров для ЧПУ контента
  * @param string $param имя параметра
  * @param mixed $value значение параметра
  * @return string часть ЧПУ
  */
 protected function content_furl_rules($param, $value)
 {
     switch ($param) {
         //case "attr" :
         //    return $value;
         case "year":
         case "month":
         case "day":
             return (preg_match('/^\\$([1-3])$/siu', $value) ? $value : longval($value)) . '/';
         case "act":
             return $value;
         case "id":
             return "-id" . longval($value);
             break;
         case "cid":
             return "-cid" . longval($value);
             break;
         case "title":
             return display::o()->translite($value, 100);
             break;
         case "cat":
             return $value . "/";
         case "comments_page":
         case "page":
             return "page" . $value;
         default:
             return;
             break;
     }
 }
Пример #17
0
 /**
  * Функция для изменения размера изображения
  * @param string|array $filepath путь к файлу
  * если массив, то первый элемент - путь, второй - с типом изображения
  * @param int $maxwidth макс. ширина изображения
  * @param int $maxheight макс. высота изображения
  * @param int $curwidth текущая ширина изображения
  * @param int $curheight текущая высота изображения
  * @param string $new_name путь, куда будет сохраняться уменьшенное изображение
  * @param bool $cut обрезать до размеров превью? 
  * @return bool true, в случае успешного выполения функции
  * @throws EngineException 
  */
 public function resize($filepath, $maxwidth = "", $maxheight = "", $curwidth = "", $curheight = "", $new_name = "", $cut = false)
 {
     lang::o()->get('file');
     if (is_array($filepath)) {
         list($filepath, $type) = $filepath;
         $type = file::o()->get_filetype($type);
     } else {
         $type = file::o()->get_filetype($filepath);
     }
     if ($type == "jpg") {
         $type = "jpeg";
     }
     if (!$type) {
         throw new EngineException("file_false_name");
     }
     if (!$curwidth || !$curheight) {
         $wh = $this->is_image(ROOT . $filepath, true);
         $curwidth = $wh[0];
         $curheight = $wh[1];
     }
     if (!$maxheight && !$maxwidth || !($curwidth >= $maxwidth && $maxwidth || $curheight >= $maxheight && $maxheight)) {
         throw new EngineException('file_unknown_resize', array($maxwidth ? $maxwidth : unended, $maxheight ? $maxheight : unended));
     }
     $imagecftype = 'imagecreatefrom' . $type;
     $imagetype = 'image' . $type;
     if (!function_exists($imagecftype) || !function_exists($imagetype)) {
         throw new EngineException(lang::o()->v('file_unknown_type') . lang::o()->v('file_ft_images'));
     }
     $source = @$imagecftype($filepath);
     if (!$source) {
         throw new EngineException(lang::o()->v('file_unknown_type') . lang::o()->v('file_ft_images'));
     }
     $source_x = $source_y = 0;
     $ratio = $curwidth / $curheight;
     $new_w = $maxwidth;
     $new_h = $maxheight;
     $ratio_n = $new_h ? $new_w / $new_h : 0;
     if (!$maxheight || $ratio > $ratio_n) {
         $new_h = longval($new_w / $ratio);
     } else {
         $new_w = longval($new_h * $ratio);
     }
     if ($cut && $ratio_n && $ratio_n != $ratio) {
         if ($new_w == $maxwidth) {
             $delta = $curheight * $ratio_n;
             $source_x = longval(($curwidth - $delta) / 2);
             $curwidth = longval($delta);
         } else {
             $delta = $curwidth / $ratio_n;
             $source_y = longval(($curheight - $delta) / 2);
             $curheight = longval($delta);
         }
         $new_w = $maxwidth;
         $new_h = $maxheight;
     }
     $target = imagecreatetruecolor($new_w, $new_h);
     @imagecopyresampled($target, $source, 0, 0, $source_x, $source_y, $new_w, $new_h, $curwidth, $curheight);
     $ret = $imagetype($target, ROOT . (!$new_name ? $filepath : $new_name));
     @imagedestroy($target);
     @imagedestroy($source);
     if (!$ret) {
         throw new EngineException("file_unknown_error");
     }
     return true;
 }
Пример #18
0
 /**
  * Голосование в опросе
  * @param int $poll_id ID опроса
  * @param integer|array $answers ответы
  * @return bool true, в случае успешного завершения
  * @throws EngineException 
  */
 public function vote($poll_id, $answers)
 {
     if (!$this->state) {
         return;
     }
     users::o()->check_perms('polls', 1, 2);
     $poll_id = (int) $poll_id;
     if (!$answers) {
         throw new EngineException('polls_so_much_votes');
     }
     $answers = (array) (is_array($answers) ? array_map('intval', $answers) : array(longval($answers)));
     $user_id = (int) users::o()->v('id');
     $user_ip = users::o()->get_ip();
     $day = 60 * 60 * 24;
     $row = db::o()->p($user_id ? $user_id : $user_ip, $poll_id)->query('SELECT p.*,
         pv.question_id, pv.user_ip, pv.user_id FROM polls AS p
         LEFT JOIN poll_votes AS pv ON pv.question_id=p.id AND ' . ($user_id ? 'pv.user_id = ?' : 'pv.user_id=0 AND pv.user_ip = ?') . '
         WHERE p.id = ? LIMIT 1');
     $row = db::o()->fetch_assoc($row);
     if (!$row) {
         throw new EngineException();
     }
     if ((!$row['change_votes'] || !users::o()->v()) && $row['question_id']) {
         throw new EngineException('polls_you_re_voted');
     }
     if ($row['max_votes'] < count($answers) || !$answers) {
         throw new EngineException('polls_so_much_votes');
     }
     if ($row["poll_ends"]) {
         if (time() - $row["posted_time"] > $row["poll_ends"] * $day) {
             throw new EngineException('polls_already_ends');
         }
     }
     $update = array('answers_id' => serialize($answers));
     try {
         plugins::o()->pass_data(array("row" => &$row), true)->run_hook('polls_vote');
     } catch (PReturn $e) {
         return $e->r();
     }
     if (!$row['question_id']) {
         $update['user_id'] = $user_id;
         $update['question_id'] = $poll_id;
         $update['user_ip'] = $user_ip;
         db::o()->insert($update, 'poll_votes');
     } else {
         db::o()->p($row["user_id"], $row["user_ip"], $row['question_id'])->update($update, 'poll_votes', 'WHERE user_id = ?
                 AND user_ip = ? AND question_id=? LIMIT 1');
     }
     $this->uncache($poll_id, true);
     return true;
 }
Пример #19
0
 /**
  * Проверка попыток входа
  * @return int кол-во попыток входа
  * @throws EngineException
  */
 protected function login_tries()
 {
     $max_enter = (int) config::o()->v('max_trylogin') - 1;
     $interval = (int) config::o()->v('logintime_interval');
     $sid = session_id();
     $login_trying = 0;
     if ($max_enter >= 0) {
         $res = db::o()->p($sid, users::o()->get_ip())->query('SELECT trying_time, login_trying 
             FROM sessions WHERE sid=? OR ip=?
             ORDER BY login_trying DESC LIMIT 1');
         $res = db::o()->fetch_assoc($res);
         $login_trying = $res["login_trying"];
         $time = $res["trying_time"];
         if ($login_trying < longval($_COOKIE["login_trying"])) {
             $login_trying = (int) $_COOKIE["login_trying"];
         }
         if ($time < longval($_COOKIE["login_time"])) {
             $time = (int) $_COOKIE["login_time"];
         }
         if ($login_trying >= $max_enter && $time + $interval > time()) {
             throw new EngineException("login_more_than_maybe", array($login_trying + 1, $max_enter + 1));
         }
     }
     return $login_trying;
 }
Пример #20
0
 /**
  * Приближение значения в меньшую сторону
  * @param float $value значение рейтинга
  * @return null
  */
 protected function value_to_part(&$value)
 {
     $type = $this->type;
     $value = (double) $value;
     if (!$value) {
         return;
     }
     $value = number_format($value, 9, '.', '');
     $dec = $this->count_decimals($value);
     if ($dec == 1) {
         $dec = $this->count_decimals($this->part[$type]);
     }
     if (floatval($this->part[$type]) > 0 && floatval($this->part[$type]) <= 1) {
         if (($value - longval($value)) * $dec % ($this->part[$type] * $dec) != 0) {
             $value = $value - ($value - longval($value)) * $dec % ($this->part[$type] * $dec) / $dec;
         }
     }
 }
Пример #21
0
 /**
  * Обрезка выделенного текста
  * @param string $text текст
  * @return null 
  */
 protected function highlight_cut(&$text)
 {
     $cut_symb_max = config::o()->v('max_search_symb');
     $ret = preg_split('/(\\<font class\\=\\"highlighted\\"\\>(?:.+?)\\<\\/font\\>)/siu', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
     $count = count($ret);
     $text = "";
     $max_symb = config::o()->v('max_symb_after_word');
     $smax_symb = longval($max_symb / 2);
     $lastword = 0;
     for ($i = 0; $i < $count; $i++) {
         if ($i % 2 == 0) {
             $strlen = mb_strlen($ret[$i]);
             if ($i == 0) {
                 // режем начало
                 $text .= $strlen > $max_symb ? "..." . display::o()->cut_word($ret[$i], $strlen - $max_symb, $max_symb) : $ret[$i];
             } elseif ($i == $count - 1) {
                 // режем конец
                 $text .= $strlen > $max_symb ? display::o()->cut_word($ret[$i], 0, $max_symb) . "..." : $ret[$i];
             } else {
                 // и серединку
                 $text .= $strlen > $max_symb ? display::o()->cut_word($ret[$i], 0, $smax_symb) . "..." . display::o()->cut_word($ret[$i], $strlen - $smax_symb, $smax_symb) : $ret[$i];
             }
             if (mb_strlen($text) > $cut_symb_max && $cut_symb_max) {
                 // кончаем нарезку, ибо слишком многа букафф
                 $text = display::o()->cut_word($text, 0, $lastword > $cut_symb_max ? $lastword : $cut_symb_max) . "...";
                 break;
             }
         } else {
             $text .= $ret[$i];
             $lastword = mb_strlen($text);
             // на случай, если последнее выделенное слово дальше максимума
         }
     }
 }
Пример #22
0
 /**
  * Переход по степеням в регистрации
  * @param integer|string $step текущая стадия регистрации
  * @param array $data массив данных
  * @return null
  * @throws EngineException
  */
 protected function step_by_step($step, $data)
 {
     $error = array();
     /* @var $uf userfields */
     $uf = n("userfields")->change_type('register');
     // для input_userfields и метода save
     if ($data['to_check'] && is_numeric($step)) {
         $this->check_steps($error, $step, $data);
         if ($step >= 3) {
             try {
                 $uf->save($data);
             } catch (EngineException $e) {
                 $error[] = $e->getEMessage();
             }
         }
         if (!$error) {
             ok();
         } else {
             $error = implode("<br>", $error);
         }
         throw new EngineException($error);
     } elseif ($step == "last") {
         if (!config::o()->v('allowed_register') && !config::o()->v('allowed_invite')) {
             die("ERROR!");
         }
         $refered_by = 0;
         /* @var $etc etc */
         $etc = n("etc");
         $this->check_steps($error, $step, $data, $refered_by);
         if ($error) {
             throw new EngineException(implode("<br>", $error));
         }
         $salt = users::o()->generate_salt();
         display::o()->remove_time_fields("his", "birthday");
         $birthday = display::o()->make_time("birthday", "ymd");
         $cols = array('username', 'password', 'email', 'gender', 'timezone', 'admin_email', 'user_email', 'use_dst', 'invite');
         extract(rex($data, $cols));
         $password = users::o()->generate_pwd_hash($password, $salt);
         $update = array("username" => $username, "username_lower" => mb_strtolower($username), "passkey" => users::o()->generate_salt(), "password" => $password, "salt" => $salt, "registered" => time(), "birthday" => $birthday, "email" => $email, "confirmed" => longval($etc->confirm_user(0, 0)), "group" => users::o()->find_group('default'), "refered_by" => (int) $refered_by, "confirm_key" => config::o()->v('confirm_email') ? $etc->confirm_request($email, "confirm_register") : "");
         if (config::o()->v('bonus_by_default')) {
             $update['bonus_count'] = config::o()->v('bonus_by_default');
         }
         $update["gender"] = $gender == "f" ? "f" : "m";
         $update["admin_email"] = (bool) $admin_email;
         $update["user_email"] = (bool) $user_email;
         $update["dst"] = (bool) $use_dst;
         $update["timezone"] = (int) $timezone;
         $cols = array("name_surname" => 'name');
         $settings = rex($data, $cols);
         $settings["show_age"] = (bool) $data['show_age'];
         $settings = array_merge($settings, $uf->save($data));
         try {
             plugins::o()->pass_data(array('update' => &$update, 'settings' => &$settings), true)->run_hook('register_user');
             $update['settings'] = users::o()->make_settings($settings);
             $id = db::o()->insert($update, "users");
             plugins::o()->pass_data(array('id' => $id))->run_hook('register_user_finish');
         } catch (PReturn $e) {
             return $e->r();
         }
         if ($invite) {
             db::o()->p($invite)->update(array("to_userid" => $id), "invites", 'WHERE invite_id=? LIMIT 1');
         } elseif (!config::o()->v('confirm_email') && !config::o()->v('confirm_admin')) {
             users::o()->write_cookies($username, $password);
         }
         ok();
     }
     tpl::o()->display("register/main_step.tpl");
 }
Пример #23
0
 /**
  * Преобразование получаемого времени в UNIXTIME
  * @param string $name префикс поля
  * @param string $must_be обязательные поля для выборки времени(формат ymdhis)
  * @return int время в формате UNIXTIME
  */
 public function make_time($name = "", $must_be = "")
 {
     $name = $name ? $name . "_" : "";
     $yarr = array("year", "month", "day", "hour", "minute", "second");
     if ($must_be) {
         $must_be = strtolower($must_be);
         foreach ($yarr as $field) {
             if ($field == "minute") {
                 $f = "i";
             } else {
                 $f = $field[0];
             }
             if (strpos($must_be, $f) !== false && !longval($_REQUEST[$name . $field])) {
                 return 0;
             }
         }
     }
     $r = unsigned(@mktime((int) $_REQUEST[$name . "hour"], (int) $_REQUEST[$name . "minute"], (int) $_REQUEST[$name . "second"], (int) $_REQUEST[$name . "month"], (int) $_REQUEST[$name . "day"], (int) $_REQUEST[$name . "year"]));
     return $r;
 }
Пример #24
0
 /**
  * Обработка данных поиска
  * @param array $data данные поиска
  * @return array массив условия, сортировки и значения subupdate
  */
 protected function users_data_prepare($data)
 {
     /* @var $search search */
     $search = n("search");
     $unco = (bool) $_GET['unco'];
     $inadmin = users::o()->check_inadmin("users");
     try {
         $where = array();
         plugins::o()->pass_data(array('where' => &$where, 'orderby' => &$this->orderby, 'data' => &$data), true)->run_hook('search_users_begin');
         $data_params = array("uname" => "user", "email", "ip", "icq", "skype", "name", "country", "group", "reg_type", "lv_type", "subupdate", 'orderby');
         extract(rex($data, $data_params));
         if ($unco) {
             $where[] = "confirmed <> '3'";
         }
         if ($uname && ($cwhere = $search->like_where($uname, 'username'))) {
             $where[] = $cwhere;
         }
         if ($email && ($cwhere = $search->like_where($email, 'email'))) {
             $where[] = $cwhere;
         }
         if ($ip && ($ip = $search->search_ip($ip))) {
             $where[] = $ip;
         }
         /*
          if ($icq)
          $where [] = $search->search_settings('icq', $icq);
          if ($skype)
          $where [] = $search->search_settings('skype', $skype);
          if ($name)
          $where [] = $search->search_settings('name_surname', $name);
          $country = (int) $country;
          if ($country)
          $where [] = $search->search_settings('country', $country);
         */
         $group = (int) $group;
         if ($group) {
             $where[] = '`group`=' . $group;
         }
         $day = 60 * 60 * 24;
         $sign1 = !$reg_type ? "==" : ($reg_type == 1 ? ">=" : "<=");
         $registered = display::o()->make_time("reg", "ymd");
         if ($registered) {
             switch ($sign1) {
                 case "==":
                     $registered2 = $registered + $day;
                     break;
                 case ">=":
                     $registered2 = time();
                     break;
                 case "<=":
                     $registered2 = $last_visited;
                     $last_visited = 0;
                     break;
             }
         }
         if ($registered || $registered2) {
             $where[] = 'registered BETWEEN ' . longval($registered) . ' AND ' . longval($registered2 - ($sign1 != ">=" ? 1 : 0));
         }
         $sign2 = !$lv_type ? "==" : ($lv_type == 1 ? ">=" : "<=");
         $last_visited = display::o()->make_time("lv", "ymd");
         if ($last_visited) {
             switch ($sign2) {
                 case "==":
                     $last_visited2 = $last_visited + $day;
                     break;
                 case ">=":
                     $last_visited2 = time();
                     break;
                 case "<=":
                     $last_visited2 = $last_visited;
                     $last_visited = 0;
                     break;
             }
         }
         if ($last_visited || $last_visited2) {
             $where[] = 'last_visited BETWEEN ' . longval($last_visited) . ' AND ' . longval($last_visited2 - ($sign2 != ">=" ? 1 : 0));
         }
         plugins::o()->run_hook('search_users_end');
         if (!$inadmin && !$where) {
             n("message")->stype("error")->sdie()->info('nothing_selected');
         }
         if ($orderby) {
             $sort = explode(",", $orderby);
             $c = count($sort);
             $orderby = '';
             for ($i = 0; $i < $c; $i += 2) {
                 if (!$this->orderby[$sort[$i]]) {
                     continue;
                 }
                 $orderby .= ($orderby ? ', ' : '') . "`" . $this->orderby[$sort[$i]] . "` " . ($sort[$i + 1] ? "asc" : "desc");
             }
         }
         $where[] = 'id>0';
         $where = $where ? "(" . implode(") AND (", $where) . ")" : null;
     } catch (PReturn $e) {
         return $e->r();
     }
     return array($where, $orderby, $subupdate);
 }