<?php 

class Diary
{
    /**
     *
     * @param int $num
     * @param string $one
     * @param string $two
     * @param string $more
     * @return string
     */
    static function number($num, $one, $two, $more)
    {
        $num = (int)$num;
        $l2 = substr($num, is_strlen($num) - 2, 2);

        if ($l2 >= 5 && $l2 <= 20)
            return $more;
        $l = substr($num, is_strlen($num) - 1, 1);
        switch ($l) {
            case 1:
                return $one;
                break;
            case 2:
                return $two;
                break;
            case 3:
                return $two;
                break;
            case 4:
                return $two;
                break;
            default:
                return $more;
                break;
        }
    }
    
    /**
     * читабельное представление времени с учетом часового пояса пользователя
     * @global \user $user
     * @param int $time Время в формате timestamp
     * @param boolean $adaptive Адаптивное представлени (вместо полной даты использовать "сегодня", "вчера")
     * @return string
     */
    public static function vremja($time, $adaptive = true) {
        if (!$time) {
            $time = time();
        }
        
        $realTime = time();
        
        if ($time > $realTime) {
            $time -= $realTime;
            $mes = 0;
            $day = 0;
            $hour = 0;
            $min = 0;
            $sec = 0;
            if ($time) {
                $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) {
                $mes = floor($time / 2592000 % 12);
            }

            if ($mes) {
                return $mes . ' месяц' . self::number($mes, '', 'а', 'ев') . ($day ? (', ' . $day . ' ' . self::number($day, 'день', 'дня', 'дней') . ($hour ? ' и ' . $hour . ' час' . self::number($hour, '', 'а', 'ов') : '')) : '');
            }
            if ($day) {
                return $day . ' ' . self::number($day, 'день', 'дня', 'дней') . ($hour ? (', ' . $hour . ' час' . self::number($hour, '', 'а', 'ов') . ($min ? ' и ' . $min . ' минут' . self::number($min, 'а', 'ы', '') : '')) : '');
            }
            if ($hour) {
                return $hour . ' час' . self::number($hour, '', 'а', 'ов') . ($min ? (', ' . $min . ' минут' . self::number($min, 'а', 'ы', '') . ($sec ? ' и ' . $sec . ' секунд' . self::number($sec, 'а', 'ы', '') : '')) : '');
            }
            if ($min) {
                return $min . ' минут' . self::number($min, 'а', 'ы', '') . ($sec ? ' и ' . $sec . ' секунд' . self::number($sec, 'а', 'ы', '') : '');
            }
            return $sec . ' секунд' . self::number($sec, 'а', 'ы', '');
        } else {
            global $user;

            if ($user['set_timesdvig']) {
                $time_shift = $user['set_timesdvig'];
            } else {
                $time_shift = 0;
            }
            $time = $time + $time_shift * 3600;
            $vremja = date('j M', $time);
            $time_p[0] = date('j n Y', $time);
            $time_p[1] = date('H:i', $time);
            
            if ($adaptive && $time_p[0] == date('j n Y', $realTime + $time_shift * 60 * 60)) {
                $vremja = date('H:i', $time);
            }
            
            if ($adaptive && $time_p[0] == date('j n Y', $realTime - 60 * 60 * (24 - $time_shift))) {
                $vremja = __("Вчера");
            }
            
            $vremja = str_replace('Jan', __('Янв'), $vremja);
            $vremja = str_replace('Feb', __('Фев'), $vremja);
            $vremja = str_replace('Mar', __('Мар'), $vremja);
            $vremja = str_replace('May', __('Мая'), $vremja);
            $vremja = str_replace('Apr', __('Апр'), $vremja);
            $vremja = str_replace('Jun', __('Июн'), $vremja);
            $vremja = str_replace('Jul', __('Июл'), $vremja);
            $vremja = str_replace('Aug', __('Авг'), $vremja);
            $vremja = str_replace('Sep', __('Сен'), $vremja);
            $vremja = str_replace('Oct', __('Окт'), $vremja);
            $vremja = str_replace('Nov', __('Ноя'), $vremja);
            $vremja = str_replace('Dec', __('Дек'), $vremja);
            return $vremja;
        }
    }
    
    /**
    * 
    * @param undefined $data
    * @param undefined $type
    * 
    * @return
    */
    protected function get_data_type($data, $type = 'return') {
        if (isset($_GET['type']) && $_GET['type'] == 'json') {
            die(json_encode($data));
        } else {
            return $data;
        }
    }
    
    /**
    * Like & Dislike
    * @param undefined $like
    * @param undefined $diary_id
    * @param undefined $user_id
    * 
    * @return array()
    */
    public function get_like($diary_id, $user_id, $like) {
        $user_id = (int) $user_id;
        $diary_id = (int) $diary_id;
        $like = ($like == 0 ? 0 : 1);
        $like_count = ($like == 0 ? -1 : 1);
        
        $diary = mysql_fetch_assoc(mysql_query("SELECT n.*, 
                                                  (SELECT COUNT(*) FROM notes_like AS l WHERE l.id_notes = n.id AND l.id_user = '$user_id') AS 'like'
                                                FROM notes AS n
                                                WHERE n.id = '$diary_id' 
                                                LIMIT 1"));
        
        $err = array();
        
        if ($diary['id']) {
            if ($diary['like'] == 0) {
                mysql_query("INSERT INTO `notes_like` (`id_notes`, `id_user`, `like`) VALUES ('$diary[id]', '$user_id', '$like')");
			          mysql_query("UPDATE `notes` SET `count` = '" . ($diary['count'] + $like_count) . "' WHERE `id` = '$diary[id]' LIMIT 1");
            } else {
                $err[] = 'Вы уже голосовали';
            }
        } else {
            $err[] = 'Дневник не существует';
        }
        
        if ($err) {
            return $this->get_data_type(array(
                'error' => $err,
            ));
        }
        
        return $this->get_data_type(array(
            'success' => ($like == '1' ? 'like' : 'dislike'),
            'like' => $like,
        ));
    } 
    
    /**
    * Отправка комментария
    */
    public function get_comment($diary_id, $user_id, $msg, $reply) {
        $user_id = (int) $user_id;
        $diary_id = (int) $diary_id;
        $reply = (int) $reply;
        $user = user::get_user($user_id);
        $time = time();
        
        $diary = mysql_fetch_assoc(mysql_query("SELECT n.*
                                                FROM notes AS n
                                                WHERE n.id = '$diary_id' 
                                                LIMIT 1"));
        
        $is_err = $this->is_strlen($msg, 2, 2048);
        
        if ($is_err !== true) {
            $err[] = 'Текст сообщения слишком ' . ($is_err == 'to' ? 'длинный' : 'короткий');
        }
        
        if ($this->is_access($diary, $user_id, 'private_komm') == false) {
            $err[] = 'Автор ограничил комментирование этой записи.';
        }
        
        $msg = my_esc($msg);
        
        if (!$diary['id']) {
            $err[] = 'Дневник не найден';
        }
        
        if (!isset($err)) {
            mysql_query("INSERT INTO `notes_komm` (`id_user`, `time`, `msg`, `id_notes`) values('$user_id', '$time', '$msg', '$diary_id')");
            
            // Обсуждения
            $this->get_disc($user_id, $diary['id_user'], $diary_id);
            
            // Ответы
            if ($reply != 0) {
                $set = mysql_fetch_assoc(mysql_query("SELECT * FROM `notification_set` WHERE `id_user` = '$reply' LIMIT 1"));
                
                if ($set['komm'] == 1 && $reply != $user_id) {
                    mysql_query("INSERT INTO `notification` (`avtor`, `id_user`, `id_object`, `type`, `time`) VALUES ('$user_id', '$reply', '$diary_id', 'notes_komm', '$time')");
                }
            }
            
            return $this->get_data_type(array(
                'success' => array(
                    'msg' => output_text($msg),
                    'user_id' => $user['id'],
                    'link' => $user['link'],
                    'avatar' => $user['avatar'],
                    'icon' => $user['icon'],
                    'online' => $user['online'],
                    'time' => vremja($time),
                ),
                'msg' => 'Сообщение успешно отправлено',
            ));
        }
        
        return $this->get_data_type(array(
            'error' => $err,
        ));
    }
    
    /**
    * Проверка доступа приватности
    */
    public function is_access($diary, $user_id, $type = 'private') 
    {
        $token = true;

        if ($diary[$type] == 2) {
            $token = false;
        } 

        else {
            if ($diary[$type] == 1) {
                if ($user_id) {
                    $is_friends = mysql_fetch_assoc(mysql_query("SELECT *
                                                         FROM frends AS f
                                                         WHERE (f.user = '$user_id' AND f.frend = '$diary[id_user]') 
                                                         OR (f.frend = '$user_id' AND f.user = '$diary[id_user]')"));
                    if (!$is_friends) {
                        $token = false;
                    }
                } else {
                    $token = false;
                }
            }
        }

        if ($user_id && ( $user_id == $diary['id_user'] || user_access('notes_delete') )) {
            $token = true;
        }
        
        return $token;
    }
    
    /**
    * Редактирование прав доступа
    */
    public function get_edit_access($diary_id, $type, $select) {
        global $user;
        $diary_id = (int) $diary_id;
        $type_sess = ($type == 'private' ? 'diary_access' : 'diary_comment');
        
        if ($diary_id != 0) {
            $diary = mysql_fetch_assoc(mysql_query("SELECT n.*
                                                    FROM notes AS n
                                                    WHERE n.id = '$diary_id' 
                                                    LIMIT 1"));
            
            if (isset($diary['id']) && (user_access('notes_edit') || $user['id'] == $diary['id_user'])) {
                mysql_query("UPDATE notes SET $type = '$select' WHERE id = " . $diary_id);
            } else {
                $err = true;
            }
        } else {
            $_SESSION[$type_sess] = (int) $select;
        }

        if (!isset($err)) {
            return $this->get_data_type(array(
                'success' => array($type => $select),
                'msg' => 'Настроки доступа сохранены',
            ));            
        }

        return $this->get_data_type(array(
            'error' => 'Не удалось изменить права доступа',
        ));
    }
    
    /**
    * Редактирование и создание дневника
    */
    
    public function get_edit($diary_id, $user_id, $data) {
        $user_id = (int) $user_id;
        $diary_id = (int) $diary_id;
        $edit = false;
        $time = time();
        
        if ($diary_id != 0) {
            $diary = mysql_fetch_assoc(mysql_query("SELECT n.*
                                                    FROM notes AS n
                                                    WHERE n.id = '$diary_id' 
                                                    LIMIT 1"));
            
            if ($diary['id_user'] != $user_id && !user_access('notes_edit')) {
                $err[] = 'У вас не прав доступа';
            }
            
            $edit = true;
        }
        
        $is_err = $this->is_strlen($data['msg'], 2, 4096);
        
        if ($is_err !== true) {
            $err[] = 'Текст слишком ' . ($is_err == 'to' ? 'длинный' : 'короткий');
            $_SESSION['diary_message'] = $data['msg'];
        }
        
        $is_err = $this->is_strlen($data['name'], 3, 128);
        
        if ($is_err === 'to') {
            $err[] = 'Название слишком ' . ($is_err === 'to' ? 'длинное' : 'короткое');
            $_SESSION['diary_name'] = $data['name'];
        }
        
        $attach = array();
        
        if (isset($diary) && $diary['attachments']) {
            $attach = unserialize($diary['attachments']);
        }
        
        if (isset($_SESSION['diary']['attachments'])) {
            $attach = array_merge($attach, $_SESSION['diary']['attachments']);
        }
        
        if (isset($attach['photo']) && count($attach['photo']) > 10) {
            $err[] = 'Допускается не более 10 вложений';
        }
       
        if (!isset($err)) {
            if ($edit == false) {
                mysql_query("INSERT INTO `notes` (`time`, `msg`, `name`, `id_user`, `private`, `attachments`) 
                              VALUES('$time', '" . my_esc($data['msg']) . "', '" . my_esc($data['name']) . "', '$user_id', '" . (int) $data['private'] . "', '" . serialize($attach) . "')");
                $diary = $data;
                $diary['id'] = mysql_insert_id();
                $diary['time'] = $time;
                
                if ($diary['private'] != 2) {
                  $this->get_tape($user_id, $diary['id']);
                }
                
            } else {
                mysql_query("UPDATE `notes` 
                             SET `name` = '" . my_esc($data['name']) . "', `msg` = '" . my_esc($data['msg']) . "', `attachments` = '" . serialize($attach) . "'
                             WHERE `id` = '$diary_id' LIMIT 1");
            }    
            
            unset($_SESSION['diary_message'], $_SESSION['diary_name'], $_SESSION['diary_access'], $_SESSION['diary_comment'], $_SESSION['diary']);
            
            return $this->get_data_type(array(
                'success' => array(
                    'id' => $diary['id'],
                    'name' => $diary['name'],
                    'msg' => output_text($diary['msg']),
                    'id_user' => $user_id,
                    'time' => $this->vremja($diary['time']),
                ),
                'msg' => 'Запись успешно ' . ($edit ? 'отредактирована' : 'создана'),
                'maps' => array(
                    'diary_id' => $diary['id'],
                    'r' => 'diary',
                ),
            ));  
        }
        
        return $this->get_data_type(array(
            'error' => $err,
        ));
    }
    
    /**
    * Рассылка обсуждений друзьям и автору
    * @param undefined $user_id
    * @param undefined $author_id
    * @param undefined $diary_id
    */
    protected function get_disc($user_id, $author_id, $diary_id) {
        
        $time = time();
        
        // Друзьям
        $q = mysql_query("SELECT f.frend AS id, f.disc_notes AS set_user, d.disc_notes AS 'set'
                          FROM frends AS f
                          LEFT JOIN discussions_set AS d ON d.id_user = f.frend
                          WHERE (f.user = '$user_id' OR f.user = '$author_id') AND f.i = '1' AND f.user != '$user_id' AND f.user != '$author_id'");
        
        while ($ank = mysql_fetch_assoc($q))
        {
            if ($ank['set'] == 1 && $ank['set_user'] == 1)
            {
                $count = mysql_result(mysql_query("SELECT COUNT(*) 
                                                   FROM `discussions` 
                                                   WHERE `id_user` = '$ank[id]' AND `type` = 'notes' AND `id_sim` = '$diary_id'"), 0);
                
                if ($count == 0)
                {
                    mysql_query("INSERT INTO `discussions` (`id_user`, `avtor`, `type`, `time`, `id_sim`, `count`) 
                                 VALUES('$ank[id]', '$author_id', 'notes', '$time', '$diary_id', '1')"); 
                } else {
                    mysql_query("UPDATE discussions 
                                 SET `count` = `count` + '1', `time` = '$time' 
                                 WHERE `id_user` = '$ank[id]' AND `type` = 'notes' AND `id_sim` = '$diary_id' LIMIT 1");
                }
            }
        }
        
        // Автору
        $author = mysql_fetch_assoc(mysql_query("
                          SELECT d.count, d.id
                          FROM discussions AS d
                          WHERE d.id_user = '$author_id' AND d.type = 'notes' AND d.id_sim = '$diary_id'"));
        
        if (!$author['id'])
        {
            mysql_query("INSERT INTO `discussions` (`id_user`, `avtor`, `type`, `time`, `id_sim`, `count`) 
                         VALUES('$author_id', '$author_id', 'notes', '$time', '$diary_id', '1')"); 
        } else {
            mysql_query("UPDATE `discussions` 
                         SET `count` = `count` + '1', `time` = '$time' 
                         WHERE `id_user` = '$author_id' AND `type` = 'notes' AND `id_sim` = '$diary_id' 
                         LIMIT 1");
        }
    }
    
    /**
    * Рассылка в ленту друзьям
    * @param undefined $user_id
    * @param undefined $diary_id
    */
    protected function get_tape($user_id, $diary_id) {

        $time = time();
        
        $q = mysql_query("SELECT f.frend AS id, f.lenta_notes AS set_user, t.lenta_notes AS 'set'
                          FROM frends AS f
                          LEFT JOIN tape_set AS t ON t.id_user = f.frend
                          WHERE f.user = '$user_id' AND f.i = '1'");
        
        while ($ank = mysql_fetch_assoc($q))
        {
            if ($ank['set'] == 1 && $ank['set_user'] == 1)
            {
                mysql_query("INSERT INTO `tape` (`id_user`,`avtor`, `type`, `time`, `id_file`) 
                                 VALUES('$ank[id]', '$user_id', 'notes', '$time', '$diary_id')");
            }
        }
    }
    
    /**
    * Удаление комментариев
    * @param undefined $id
    * @param undefined $type
    * 
    * @return
    */
    public function get_delete($type, $id) {
        global $user;
        
        if ($id == 0) {
            $err[] = 'Ошибка данных';
        } 
        
        if ($type == 'comment') {
            $comment = mysql_fetch_assoc(mysql_query("
                            SELECT k.*
                            FROM notes_komm AS k WHERE k.id = '" . (int) $id . "' LIMIT 1"));
        }
        
        $diary = mysql_fetch_assoc(mysql_query("
                            SELECT n.*
                            FROM notes AS n WHERE n.id = '" . ($type == 'diary' ? $id : $comment['id_notes']) . "' LIMIT 1"));

        if (!isset($diary['id'])) {
            $err[] = 'Дневник не найден';
        }
        
        if ($user['id'] != $diary['id_user'] && !user_access('notes_delete')) {
            $err[] = 'У вас не прав доступа';
        }
        
        if (!isset($err)) {
            if ($type == 'comment') {
                mysql_query("DELETE FROM notes_komm WHERE id = " . (int) $id);
            } elseif ($type == 'diary') {
                mysql_query("DELETE FROM notes WHERE id = " . (int) $id);
                mysql_query("DELETE FROM notes_komm WHERE id_notes = " . (int) $id);
                mysql_query("DELETE FROM notes_count WHERE id_notes = " . (int) $id);
                mysql_query("DELETE FROM notes_like WHERE id_notes = " . (int) $id);
                
                mysql_query("DELETE FROM tape WHERE type = 'notes' AND id_file = '$diary[id]'");
                mysql_query("DELETE FROM notification WHERE type = 'notes' AND id_object = '$diary[id]'");
                mysql_query("DELETE FROM discussions WHERE type = 'notes' AND id_sim = '$diary[id]'");
            }  
            
            return $this->get_data_type(array(
                'success' => array('id' => (int) $id),
                'msg' => $type == 'comment' ? 'Комментарий успешно удален' : 'Запись успешно удалена',
            ));       
        }
        
        return $this->get_data_type(array(
            'error' => $err,
        ));
    }
    
    /**
    * Cоздание заголовка при отсутствии его
    * @param undefined $name
    * @param undefined $msg
    * 
    * @return $name 
    */
    public static function get_name($name, $msg, $size = 32) {
        if ($name) {
            return text($name);
        } else {
            $text = explode(" ", $msg);
            $str = '';
            
            foreach($text AS $key => $value) {
                if (strlen2($str) < $size && strlen2($value) < $size) {
                    $str .= $value . ' ';
                } elseif (strlen2($value) >= $size) {
                    $str .= substr($value, 0, $size);
                    break;
                } else {
                    break;
                }
            }
            
            return text($str);
        }
    }
    
    /**
    * Проверка длинны символов
    */
    protected function is_strlen($msg, $from = 2, $to = 1024) {
        if (strlen2($msg) > $to) {
            return 'to';
        } elseif (strlen2($msg) < $from) {
            return 'from';
        } else {
            return true;
        }
    }
}