Example #1
0
File: list.php Project: hqd276/bigs
 function draw()
 {
     global $display;
     $type = (int) $_SESSION['type'];
     if ($type < 0) {
         $type = 0;
     }
     $cat_id = intval(Url::get('catid', 0));
     if ($cat_id != 0) {
         $where = ' AND category_id = ' . $cat_id;
     }
     $where .= ' AND type = ' . $type;
     $item_per_page = 5;
     $list_news = News::get_news($where, 0, $item_per_page);
     if (count($list_news > 0)) {
         foreach ($list_news as $key => $value) {
             // $list_news[$key]['title'] = Util::split_char($value['title'],40,-1) . ' ...';
             if ($value['uid'] > 0) {
                 $author = User::getUserById($value['uid']);
                 // var_dump($author);die;
                 if ($author['full_name'] == '') {
                     $list_news[$key]['author'] = $author['user_name'];
                 } else {
                     $list_news[$key]['author'] = $author['full_name'];
                 }
             }
         }
     }
     $display->add('list_news', $list_news);
     $display->add('cid', $cat_id);
     $display->add('uid', User::id());
     $display->output("List");
 }
Example #2
0
 /**
  * Action для главной страницы
  */
 public function actionIndex()
 {
     // Список категорий для левого меню
     $categories = Category::getCategoriesList();
     // Список последних товаров
     $latestProducts = Product::getLatestProducts(6);
     // Список товаров для слайдера
     $sliderProducts = Product::getRecommendedProducts();
     // Показывыем в корзине информацию о добавленных товарах
     $productsInCart = Cart::getProducts();
     if ($productsInCart) {
         // Если в корзине есть товары, получаем полную информацию о товарах для списка
         // Получаем массив только с идентификаторами товаров
         $productsIds = array_keys($productsInCart);
         // Получаем массив с полной информацией о необходимых товарах
         $products = Product::getProdustsByIds($productsIds);
         // Получаем общую стоимость товаров
         $totalPrice = Cart::getTotalPrice($products);
     }
     // Получаем идентификатор пользователя из сессии
     $userId = $_SESSION['user'];
     // Получаем информацию о пользователе из БД
     $user = User::getUserById($userId);
     // Подключаем вид
     require_once ROOT . '/views/site/index.php';
     return true;
 }
Example #3
0
function getProfile()
{
    $arr_submit = array(array('uid', 'int', true, ''));
    $frm_submitted = validate_var($arr_submit);
    global $obj_smarty;
    $arr_user = User::getUser();
    if ($arr_user['user_id'] == $frm_submitted['uid']) {
        $arr_user = User::getUserById($frm_submitted['uid']);
        $arr_birthdate = explode('-', $arr_user['birth_date']);
        $arr_user['birthdate_month'] = $arr_user['birth_date'] !== '0000-00-00' ? $arr_birthdate[1] : '';
        $arr_user['birthdate_day'] = $arr_user['birth_date'] !== '0000-00-00' ? $arr_birthdate[2] : '';
        $arr_user['birthdate_year'] = $arr_user['birth_date'] !== '0000-00-00' ? $arr_birthdate[0] : '';
        unset($arr_user['password']);
        unset($arr_user['birth_date']);
        $obj_smarty->assign('active', 'profile');
        $obj_smarty->assign('profile', $arr_user);
        $obj_smarty->display(FULLCAL_DIR . '/view/user_panel.tpl');
        exit;
    } else {
        $obj_smarty->assign('active', 'profile');
        $obj_smarty->assign('error', 'NO rights to change this user');
        $obj_smarty->display(FULLCAL_DIR . '/view/user_panel.tpl');
        exit;
    }
}
 public function actionView($productId)
 {
     $categories = array();
     $categories = Platform::getPlatformList();
     $product = Products::getProductById($productId);
     $productId = $product['id'];
     $platform = Platform::getPlatformById($product['platform_id']);
     $comments = Comment::getCommentsByProductId($productId);
     //COMMENTS
     if (isset($_POST['submit'])) {
         $userComment = $_POST['message'];
         $errors = false;
         if (!Comment::validateMessage($userComment)) {
             $errors[] = "Введите собщение";
         }
         if (User::isGuest()) {
             $userName = $_POST['name'];
             $userEmail = $_POST['email'];
             if (!User::validateUsername($userName)) {
                 $errors[] = "Неверное имя";
             }
             if (!User::validateEmail($userEmail)) {
                 $errors[] = "Неверный Email";
             }
             $userId = false;
         } else {
             $userId = User::validateLogged();
             $user = User::getUserById($userId);
             $userName = $user['name'];
         }
         Comment::addComment($userComment, $userId, $userName, $productId);
     }
     require_once ROOT . '/views/product/view.php';
     return true;
 }
Example #5
0
 function login()
 {
     $accessToken = Url::get('accessToken', '');
     $login_info = json_decode(file_get_contents('http://ids.cpvm.vn/services/api/users/check_open_user.php?o=' . $accessToken . '&t=2'));
     if ($login_info->s) {
         $token = $login_info->v->t;
         //Lay thong tin user theo token
         $info = json_decode(file_get_contents('http://ids.cpvm.vn/services/api/users/userinfo.php?t=' . $token));
         if ($info->s) {
             $u = $info->v->u;
             $user = User::getUserById($u->id);
             if (!$user) {
                 // user chua co trong db => clone
                 $data = array('id' => $u->id, 'user_name' => $u->un, 'full_name' => $u->fn, 'avatar_url' => $u->av);
                 $id = DB::insert('account', $data);
             } else {
                 DB::update('account', array('full_name' => $u->fn), 'id=' . $u->id);
             }
             $u->t = $token;
             //dang nhap
             User::LogIn2((array) $u);
             $_SESSION['token'] = $token;
             echo 1;
         } else {
             echo 0;
         }
     } else {
         echo 0;
     }
     exit;
 }
 /**
  * Action для страницы "Редактирование данных пользователя"
  */
 public function actionEdit()
 {
     // Получаем идентификатор пользователя из сессии
     $userId = User::checkLogged();
     // Получаем ифнормацию о пользователе из БД
     $user = User::getUserById($userId);
     // Заполняем переменные для полей формы
     $name = $user['name'];
     $password = $user['password'];
     // Флаг результата
     $result = false;
     // Обработка формы
     if (isset($_POST['submit'])) {
         // Если форма отправлена
         // Получаем данные из формы редактирования
         $name = $_POST['name'];
         $password = $_POST['password'];
         // Флаг ошибок
         $errors = false;
         // Валидируем значения
         if (!User::checkName($name)) {
             $errors[] = 'Имя д.б. не короче 2-х символов';
         }
         if (!User::checkPassword($password)) {
             $errors[] = 'Пароль короче 6 символов';
         }
         if ($errors === false) {
             // Если ошибок нет, сохраняем изменения профиля
             $result = User::edit($userId, $name, $password);
         }
     }
     // Подключаем вид
     require_once ROOT . '/views/cabinet/edit.php';
     return true;
 }
 public function actionEdit()
 {
     //Получаем идентификатор пользователя из сессиив
     $userId = User::checkLogged();
     //Получаем инфомацию о пользователе из БД
     $user = User::getUserById($userId);
     $name = $user['name'];
     $password = $user['password'];
     $result = false;
     if (isset($_POST['submit'])) {
         $name = $_POST['name'];
         $password = $_POST['password'];
         $errors[] = false;
         if (!User::checkName($name)) {
             $errors[] = 'Имя должно состоять минимум из 2 символов';
         }
         if (!User::checkPassword($password)) {
             $errors[] = 'Пароль должен состоять минимум из 6 символов';
         }
         if ($errors == false) {
             $result = User::edit($userId, $name, $password);
         }
     }
     require_once ROOT . '/views/cabinet/edit.php';
     return true;
 }
Example #8
0
 public function actionEdit()
 {
     //primim identificatorul utilizatorului din sesiune
     $userId = User::checkLogged();
     //primim informatii despre utilizator din baza de date
     $user = User::getUserById($userId);
     $name = $user['name'];
     $password = $user['password'];
     $result = false;
     $errors = false;
     if (isset($_POST['submit'])) {
         $name = $_POST['name'];
         $password = $_POST['password'];
         if (!User::checkName($name)) {
             $errors[] = 'Numele nu trebue sa fie mai scurt de doua simboluri';
         }
         if (!User::checkPassword($password)) {
             $errors[] = 'parola nu trebue sa fie mai scurta de 6 simboluri';
         }
         if ($errors == false) {
             $result = User::edit($userId, $name, $password);
         }
     }
     require_once ROOT . '/views/cabinet/edit.php';
     return true;
 }
Example #9
0
 /**
  * Action для стартовой страницы "Панель администратора"
  */
 public function actionIndex()
 {
     $userId = User::checkLogged();
     $user = User::getUserById($userId);
     require_once ROOT . '/views/admin/index.php';
     return true;
 }
Example #10
0
 public function getComment()
 {
     $id = Auth::id();
     $postList = Post::where("author_id", $id)->get(array('_id'));
     $postIdList = array();
     foreach ($postList as $post) {
         //                echo $post->_id;
         //              echo "<br>";
         array_push($postIdList, $post->_id);
     }
     $comment_data = Comment::whereIn('post_id', $postIdList)->get();
     //echo count($comment_data);
     foreach ($comment_data as $comment) {
         $user_id = $comment['user_id'];
         $user = User::getUserById($user_id);
         $post = Post::where('_id', $comment->post_id)->first();
         $comment['title'] = $post['title'];
         $comment['username'] = $user['username'];
         $comment['email'] = $user['email'];
         $format = "F j, Y, g:i a";
         $date = new DateTime($comment['updated_at']);
         $formatDate = $date->format($format);
         $comment['update_time'] = $formatDate;
         if (isset($user['fb_img'])) {
             $comment['fb_img'] = $user['fb_img'];
         }
     }
     return View::make('backend.comment', array('comment_data' => $comment_data));
 }
Example #11
0
 /**
  * Action для страницы "Оформление покупки"
  */
 public function actionCheckout()
 {
     $productsInCart = Cart::getProducts();
     if ($productsInCart == false) {
         header("Location: /");
     }
     $categories = Category::getCategoriesList();
     // Находим общую стоимость
     $productsIds = array_keys($productsInCart);
     $products = Product::getProdustsByIds($productsIds);
     $totalPrice = Cart::getTotalPrice($products);
     // Количество товаров
     $totalQuantity = Cart::countItems();
     $userName = false;
     $userPhone = false;
     $userComment = false;
     $result = false;
     if (!User::isGuest()) {
         // Если пользователь не гость
         // Получаем информацию о пользователе из БД
         $userId = User::checkLogged();
         $user = User::getUserById($userId);
         $userName = $user['name'];
     } else {
         // Если гость, поля формы останутся пустыми
         $userId = false;
     }
     if (isset($_POST['submit'])) {
         $userName = $_POST['userName'];
         $userPhone = $_POST['userPhone'];
         $userComment = $_POST['userComment'];
         // Флаг ошибок
         $errors = false;
         if (!User::checkName($userName)) {
             $errors[] = 'Неправильное имя';
         }
         if (!User::checkPhone($userPhone)) {
             $errors[] = 'Неправильный телефон';
         }
         if ($errors == false) {
             // Если ошибок нет
             // Сохраняем заказ в базе данных
             $result = Order::save($userName, $userPhone, $userComment, $userId, $productsInCart);
             if ($result) {
                 // Если заказ успешно сохранен
                 // Оповещаем администратора о новом заказе по почте
                 $adminEmail = '*****@*****.**';
                 $message = '<a href="localhost/admin/orders">Список заказов</a>';
                 $subject = 'Новый заказ!';
                 mail($adminEmail, $subject, $message);
                 // Очищаем корзину
                 Cart::clear();
             }
         }
     }
     // Подключаем вид
     require_once ROOT . '/views/cart/checkout.php';
     return true;
 }
 protected function update()
 {
     $user = User::getUserById($this->id);
     if ($user->pass != $this->pass) {
         $this->encodePassword();
     }
     parent::update();
 }
 public function actionIndex()
 {
     $userId = User::checkLogged();
     $user = new User('', '', '');
     $userData = $user->getUserById($userId);
     require_once ROOT . '/views/cabinet/index.php';
     return true;
 }
Example #14
0
 function on_submit()
 {
     $uid = Url::get('id');
     $coin = Url::get('coin');
     $point = Url::get('point');
     $coin_note = trim(Url::get('coin_note'));
     $user = User::getUserById($uid);
 }
Example #15
0
 /**
  * Method for check admin
  * @return boolean
  */
 function __construct()
 {
     $userId = User::checkLogged();
     $user = User::getUserById($userId);
     if ($user['role'] == 'admin') {
         return true;
     }
     die('Access denied');
 }
Example #16
0
 public static function checkAdmin()
 {
     $userId = User::checkLogged();
     $user = User::getUserById($userId);
     if ($user['role'] == 'admin') {
         return true;
     }
     return false;
 }
 public static function validateAdmin()
 {
     $userId = User::validateLogged();
     $user = User::getUserById($userId);
     if ($user['role'] == 'admin') {
         return true;
     }
     die("ACCESS DINIED");
 }
 private function __construct()
 {
     include 'settings.php';
     date_default_timezone_set($settings->timezone);
     $this->request = Request::getInstance();
     $this->session = Session::getInstance();
     $this->response = Response::getInstance();
     $this->user = User::getUserById($this->session->userID);
 }
Example #19
0
 public function actionIndex()
 {
     $uri = trim($_SERVER['REQUEST_URI'], '/');
     if (User::checkIfAuth()) {
         $userId = User::checkLogged()['id'];
         $userInfo = User::getUserById($userId);
     }
     require_once ROOT . '/views/index.php';
 }
 public function actionProfile()
 {
     $name = '';
     $sname = '';
     $phone = '';
     $country = '';
     $region = '';
     $city = '';
     $address = '';
     $index = '';
     $userId = '';
     $user = new User();
     $result = false;
     if (isset($_POST['add_profile'])) {
         $name = $_POST['u_name'];
         $sname = $_POST['u_sname'];
         $phone = $_POST['u_phone'];
         $country = $_POST['u_country'];
         $region = $_POST['u_region'];
         $city = $_POST['u_city'];
         $address = $_POST['u_address'];
         $index = $_POST['u_index'];
         $userId = $user->getUserById($user->isUser());
         $errors = false;
         if (!User::checkName($name)) {
             $errors[] = 'Имя должно быть более 2-х символов';
         }
         if (!User::checkSname($sname)) {
             $errors[] = 'Фамилия должна быть более 2-х символов';
         }
         if (!User::checkPhone($phone)) {
             $errors[] = 'Телефон должен быть более 7-ми символов';
         }
         if (!User::checkCountry($country)) {
             $errors[] = 'Страна должна быть более 2-х символов';
         }
         if (!User::checkRegion($region)) {
             $errors[] = 'Область должна быть более 2-х символов';
         }
         if (!User::checkCity($city)) {
             $errors[] = 'Город должен быть более 2-х символов';
         }
         if (!User::checkAddress($address)) {
             $errors[] = 'Адрес должен быть более 5-ти символов';
         }
         if (!User::checkIndex($index)) {
             $errors[] = 'Индекс должен быть более 4-х символов';
         }
         if ($errors == false) {
             $result = $user->addProfile($name, $sname, $phone, $country, $region, $city, $address, $index, $userId['id']);
             header("Location: /");
         }
     }
     require_once ROOT . '/views/user/profile.php';
     return true;
 }
Example #21
0
 public static function startBattle($battleId, $attackerId, $defenderId)
 {
     $db = mysqli_connect("localhost", "root", "1234", "ant_rpg");
     $attackerRequest = mysqli_query($db, "SELECT tfb.quantity,a.ant_id,a.attack FROM troops_for_battle tfb\n      \tJOIN ant a\n\t    \tON tfb.ant_id=a.ant_id\n        WHERE tfb.battleid = " . $battleId);
     $defenderRequest = mysqli_query($db, "SELECT ua.quantity,a.attack,a.ant_id FROM user_ants ua JOIN ant a ON ua.ant_id=a.ant_id\n        WHERE user_id = " . $defenderId);
     $attackerATT = 0;
     while ($row = $attackerRequest->fetch_assoc()) {
         $attackerATT = $attackerATT + $row['quantity'] * $row['attack'];
     }
     $defendATT = 0;
     $attacker = User::getUserById($attackerId)['username'];
     $defender = User::getUserById($defenderId)['username'];
     while ($row = $defenderRequest->fetch_assoc()) {
         $defendATT = $defendATT + $row['quantity'] * $row['attack'];
     }
     if ($attackerATT > $defendATT) {
         $diff = $defendATT;
         $attackerAnts = Ants::getAntsByUserId($attackerId);
         for ($i = 0; $i < 2; $i++) {
             if ($i == count($attackerAnts) - 1) {
                 $attackerAnts[$i] = $attackerAnts[$i] - $diff;
             } else {
                 if ($diff > $attackerAnts[$i]) {
                     $diff = $diff - $attackerAnts[$i];
                     $attackerAnts[$i] = 0;
                 }
             }
             Ants::updateTroops($i + 1, $attackerAnts[$i], $battleId);
         }
         BattleReport::sendReport($attackerId, "You have won the attack versus player " . $defender . " and lost " . $defendATT . " troops", $defendATT);
         BattleReport::sendReport($defenderId, "You lost defence versus " . $attacker . " and lost " . $defendATT . " troops", $defendATT);
         Action::returnArmy($battleId);
         Ants::UpdateAntsToZero($defenderId);
     } elseif ($attackerATT == $defendATT) {
         BattleReport::sendReport($attackerId, "Draw you lost all your troops versus " . $defender, $defendATT);
         BattleReport::sendReport($attackerId, "Draw you lost all your troops versus " . $attacker, $defendATT);
         Ants::UpdateAntsToZero($defenderId);
     } else {
         $diff = $attackerATT;
         $defenderAnts = Ants::getAntsByUserId($defenderId);
         for ($i = 0; $i < 2; $i++) {
             if ($i == count($defenderAnts) - 1) {
                 $defenderAnts[$i] = $defenderAnts[$i] - $diff;
             } else {
                 if ($diff > $defenderAnts[$i]) {
                     $diff = $diff - $defenderAnts[$i];
                     $defenderAnts[$i] = 0;
                 }
             }
             Ants::updateAntsTo($i + 1, $defenderAnts[$i], $defenderId);
         }
         BattleReport::sendReport($defenderId, "You have won the defence versus player " . $attacker . " and lost " . $attackerATT . " troops", $attackerATT);
         BattleReport::sendReport($attackerId, "You lost the attack versus " . $defender . " and lost " . $attackerATT . " troops", $attackerATT);
     }
     mysqli_query($db, "UPDATE attack SET battled=1 WHERE idattack=" . $battleId);
 }
Example #22
0
 function draw()
 {
     global $display;
     $id = intval(Url::get('id', 0));
     if (!empty($id)) {
         $item = News::get_item($id);
     }
     if (empty($item)) {
         Url::redirect_url('/tin-tuc.html');
         exit;
     }
     if (!empty($item)) {
         if (!empty($item['category_id'])) {
             $categories = NewsCategory::get_by_ids($item['category_id']);
         }
         if ($item['is_active'] == 0) {
             Url::redirect_url('/tin-tuc.html');
             exit;
         }
         if ($item['uid'] > 0) {
             $author = User::getUserById($item['uid']);
             // var_dump($author);die;
             if ($author['full_name'] == '') {
                 $item['author'] = $author['user_name'];
             } else {
                 $item['author'] = $author['full_name'];
             }
         }
         $item['view'] += 1;
         News::update_view(array('view' => $item['view']), 'id=' . $id);
     }
     $tags = News::render_tags($item['keywords']);
     $related_items = NewsCategory::get_top_news($item['category_id'], 4);
     if (count($related_items > 0)) {
         foreach ($related_items as $key => $value) {
             // $list_news[$key]['title'] = Util::split_char($value['title'],40,-1) . ' ...';
             if ($value['uid'] > 0) {
                 $author = User::getUserById($value['uid']);
                 // var_dump($author);die;
                 if ($author['full_name'] == '') {
                     $related_items[$key]['author'] = $author['user_name'];
                 } else {
                     $related_items[$key]['author'] = $author['full_name'];
                 }
             }
         }
     }
     $display->add('roots', NewsCategory::get_categories());
     $display->add('item', $item);
     $display->add('tags', $tags);
     $display->add('related_items', $related_items);
     $display->add("categories", $categories);
     $display->output("Detail");
 }
Example #23
0
 function on_submit()
 {
     $us = trim(Url::get('user_name_this', ''));
     $pa = Url::get('password_this', '');
     $err = false;
     if ($us == '') {
         $err = true;
         $this->setErrorMessage('dangnhap', 'Bạn chưa nhập Tên tài khoản!');
     }
     if ($pa == '') {
         $err = true;
         $this->setErrorMessage('dangnhap', 'Bạn chưa nhập Mật khẩu!');
     }
     if (!$err) {
         $data = "u=" . $us . "&p=" . $pa;
         $loginInfo = json_decode(EClassApi::execPostRequest(CGlobal::$login_url, $data), true);
         // var_dump($loginInfo);die;
         if ($loginInfo['s']) {
             $user = $loginInfo['v']['u'];
             $user['t'] = $loginInfo['v']['t'];
             $u = User::getUserById($user['id']);
             if (!$user['fn']) {
                 $user['fn'] = $user['un'];
             }
             if (!$u) {
                 // user chua co trong db => clone
                 $data = array('id' => $user['id'], 'user_name' => $user['un'], 'full_name' => $user['fn'], 'avatar_url' => $user['av']);
                 $id = DB::insert('account', $data);
             } else {
                 DB::update('account', array('full_name' => $user['fn']), 'id=' . $user['id']);
             }
             $_SESSION['token'] = $loginInfo['t'];
             User::LogIn2($user);
             header('Location:' . STATIC_URL);
         } else {
             switch ($regInfo['m']) {
                 case 2:
                     $this->setErrorMessage('dangnhap', 'Hệ thống lỗi, xin vui lòng quay lại sau');
                     break;
                 case 4:
                     $this->setErrorMessage('dangnhap', 'Tài khoản chưa kích hoạt');
                     break;
                 case 5:
                     $this->setErrorMessage('dangnhap', 'Tên tài khoản không được để trống');
                     break;
                 case 6:
                     $this->setErrorMessage('dangnhap', 'Tên tài khoản không được chứa kí tự đặc biệt');
                     break;
                 default:
                     $this->setErrorMessage('dangnhap', 'Hệ thống lỗi, xin vui lòng quay lại sau');
             }
         }
     }
 }
 public static function checkAdmin()
 {
     $users = new User();
     //Проверка на авторизацию
     $userId = $users->checkLogged();
     //Получаем информацию о текущем пользователе
     $user = $users->getUserById($userId);
     if ($user['role'] == 'admin') {
         return true;
     }
     die('Access denied');
 }
 protected function checkAdmin()
 {
     $userId = User::isLogged();
     // Проверяем авторизирован ли пользователь
     $user = User::getUserById($userId);
     //Получаем инфу о текущем пользователе по id
     if ($user['is_admin'] == 'admin') {
         //если пользователь админ,у его есть доступ к админ панели
         return true;
     }
     die('У Вас нет прав Администратора');
 }
Example #26
0
 /**
  * Метод, который проверяет пользователя на то, является ли он администратором
  * @return boolean
  */
 public static function checkAdmin()
 {
     // Проверяем авторизирован ли пользователь. Если нет, он будет переадресован
     $userId = User::checkLogged();
     // Получаем информацию о текущем пользователе
     $user = User::getUserById($userId);
     // Если роль текущего пользователя "admin", пускаем его в админпанель
     if ($user['role'] == 'admin') {
         return true;
     }
     // Иначе завершаем работу с сообщением об закрытом доступе
     die('Access denied');
 }
Example #27
0
 public static function trainAnts($ants)
 {
     while (!empty($ants)) {
         $name = key($ants);
         $shift = array_shift($ants);
         if (empty($shift)) {
             continue;
         }
         $ant = Ants::getAntByName($name)->fetch_all()[0];
         Ants::tryTrain($ant, $shift);
         $userID = User::getUserById($_SESSION['id'])['iduser'];
         $db = mysqli_connect("localhost", "root", "1234", "ant_rpg");
         $result = mysqli_query($db, "INSERT INTO train_ants (ant_id,user_id,quantity,trained) VALUES ('" . $ant[0] . "','" . $userID . "','" . $shift . "',0)");
     }
 }
Example #28
0
 function draw()
 {
     global $display;
     $this->beginForm(false, 'post', false, "?" . htmlentities($_SERVER['QUERY_STRING']));
     $item_id = intval(Url::get('id', 0));
     $item = array();
     // Get Data
     if ($item_id) {
         $item = User::getUserById($item_id);
     }
     $display->add('item', $item);
     $display->add('error_message', $this->getErrorMessage('user/item/error'));
     $display->add('success_message', $this->getSuccessMessage('user/item/success'));
     $display->output('addUser');
     $this->endForm();
 }
Example #29
0
 public static function getCommentsOfPost($post_id)
 {
     $comments = Comment::where('post_id', $post_id)->get();
     foreach ($comments as $comment) {
         $user_id = $comment['user_id'];
         $user = User::getUserById($user_id);
         $comment['username'] = $user['username'];
         $comment['avatar_link'] = $user['avatar_link'];
         $comment['email'] = $user['email'];
         $post = Post::getPostById($comment["post_id"]);
         $comment['title'] = $post['title'];
         $format = "F j, Y, g:i a";
         $date = new DateTime($post['updated_at']);
         $formatDate = $date->format($format);
         $comment['update_time'] = $formatDate;
     }
     return $comments;
 }
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store($post_id)
 {
     //
     try {
         if (Auth::check()) {
         }
     } catch (Exception $ex) {
         return Response::json(array("message" => "Đăng nhập để comment", "isHide" => true), 404);
     }
     $content = Input::get('content');
     $id = Auth::id();
     if ($id == null) {
         return Response::json(array("message" => "Đăng nhập để comment", "isHide" => true), 404);
     }
     if ($content != null) {
         $comment = new Comment();
         $comment->content = $content;
         $comment->user_id = Auth::id();
         $comment->post_id = $post_id;
         $comment->avatar_link = Auth::user()->avatar_link;
         $comment->save();
         $user_id = $comment['user_id'];
         $user = User::getUserById($user_id);
         $comment['username'] = $user['username'];
         $comment['email'] = $user['email'];
         $post = Post::getPostById($comment["post_id"]);
         $comment['title'] = $post['title'];
         $format = "F j, Y, g:i a";
         $date = new DateTime($post['updated_at']);
         $formatDate = $date->format($format);
         $comment['update_time'] = $formatDate;
         if (isset($user['fb_img'])) {
             $comment['fb_img'] = $user['fb_img'];
         }
         if ($comment["user_id"] == $id) {
             $comment["owner"] = true;
         } else {
             $comment["owner"] = false;
         }
         return Response::json($comment);
     } else {
         return Response::json(array('success' => false));
     }
 }