public function connect(Application $app)
 {
     parent::connect($app);
     $controllers = $app['controllers_factory'];
     $self = $this;
     $controllers->get('/main', function (Request $request) use($app, $self) {
         if (!$self->checkLogin()) {
             return $app->redirect(ROOT_URL . '/client/login');
         }
         $self->setVariables();
         return $self->render('client/main.twig', array('ROOT_URL' => ROOT_URL));
     });
     $controllers->get('/user/{userId}', function (Request $request, $userId) use($app, $self) {
         if (!$self->checkLogin()) {
             return $app->redirect(ROOT_URL . '/client/login');
         }
         $self->setVariables();
         return $self->render('client/main.twig', array('ROOT_URL' => ROOT_URL, 'targetUserId' => $userId));
     });
     $controllers->get('/group/{groupId}', function (Request $request, $groupId) use($app, $self) {
         if (!$self->checkLogin()) {
             return $app->redirect(ROOT_URL . '/client/login');
         }
         $self->setVariables();
         return $self->render('client/main.twig', array('ROOT_URL' => ROOT_URL, 'targetGroupId' => $groupId));
     });
     return $controllers;
 }
 public function connect(Application $app)
 {
     parent::connect($app);
     $controllers = $app['controllers_factory'];
     $self = $this;
     $controllers->get('/', function (Request $request) use($app, $self) {
         return $app->redirect(ROOT_URL . '/admin/login');
     });
     $controllers->get('/login', function (Request $request) use($app, $self) {
         $cookies = $request->cookies;
         $username = "";
         $password = "";
         if ($cookies->has('username')) {
             $username = $cookies->get('username');
         }
         if ($cookies->has('password')) {
             $password = $cookies->get('password');
         }
         return $self->render('admin/login.twig', array('ROOT_URL' => ROOT_URL, 'formValues' => array('username' => $username, 'password' => $password, 'rememberChecked' => '')));
     });
     $controllers->post('/login', function (Request $request) use($app, $self) {
         $self->setVariables();
         $username = $request->get('username');
         $password = $request->get('password');
         $remember = $request->get('remember');
         $rememberChecked = "";
         if (!empty($remember)) {
             $rememberChecked = "checked=\"checked\"";
         }
         $authData = $self->app['spikadb']->doSpikaAuth($username, md5($password));
         $authData = json_decode($authData, true);
         if (isset($authData['token'])) {
             $html = $self->render('admin/login.twig', array('ROOT_URL' => ROOT_URL, 'formValues' => array('username' => $username, 'password' => $password, 'rememberChecked' => $rememberChecked)));
             $response = new RedirectResponse(ROOT_URL . "/admin/dashboard");
             if (!empty($remember)) {
                 $response->headers->setCookie(new Cookie("username", $username));
                 $response->headers->setCookie(new Cookie("password", $password));
             }
             $app['session']->set('user', $authData);
             return $response;
         } else {
             $self->setErrorAlert($self->language['messageLoginFailed']);
             return $self->render('admin/login.twig', array('ROOT_URL' => ROOT_URL, 'formValues' => array('username' => $username, 'password' => $password, 'rememberChecked' => $rememberChecked)));
         }
     });
     $controllers->get('/dashboard', function (Request $request) use($app, $self) {
         $self->setVariables();
         $countUsers = $self->app['spikadb']->findUserCount();
         $countMessages = $self->app['spikadb']->getMessageCount();
         $countLastLoginedUsers = $self->app['spikadb']->getLastLoginedUsersCount();
         return $self->render('admin/dashboard.twig', array('countUsers' => $countUsers, 'countMessages' => $countMessages, 'countLastLoginedUsers' => $countLastLoginedUsers));
     })->before($app['adminBeforeTokenChecker']);
     $controllers->get('/logout', function (Request $request) use($app, $self) {
         $app['session']->remove('user');
         $response = new RedirectResponse("login");
         return $response;
     });
     return $controllers;
 }
 public function connect(Application $app)
 {
     parent::connect($app);
     $controllers = $app['controllers_factory'];
     $self = $this;
     //
     // List/paging logics
     //
     $controllers->get('group/list', function (Request $request) use($app, $self) {
         $self->setVariables();
         // search criteria
         $searchCriteriaGroupName = $app['session']->get('groupnameCriteria');
         $criteria = "";
         $searchGroupNameCriteriaValues = array();
         if (!empty($searchCriteriaGroupName)) {
             $criteria .= " and LOWER(name) like LOWER(?)";
             $searchGroupNameCriteriaValues[] = "%{$searchCriteriaGroupName}%";
         }
         $count = $self->app['spikadb']->findGroupCountWithCriteria($criteria, $searchGroupNameCriteriaValues);
         $page = $request->get('page');
         if (empty($page)) {
             $page = 1;
         }
         $msg = $request->get('msg');
         if (!empty($msg)) {
             $self->setInfoAlert($self->language[$msg]);
         }
         $groups = $self->app['spikadb']->findAllGroupsWithPagingWithCriteria(($page - 1) * ADMIN_LISTCOUNT, ADMIN_LISTCOUNT, $criteria, $searchGroupNameCriteriaValues);
         // convert timestamp to date
         for ($i = 0; $i < count($groups); $i++) {
             $groups[$i]['created'] = date("Y.m.d", $groups[$i]['created']);
             $groups[$i]['modified'] = date("Y.m.d", $groups[$i]['modified']);
         }
         return $self->render('admin/groupList.twig', array('categoryList' => $self->getGroupCategoryList(), 'groups' => $groups, 'pager' => array('baseURL' => ROOT_URL . "/admin/group/list?page=", 'pageCount' => ceil($count / ADMIN_LISTCOUNT) - 1, 'page' => $page), 'searchCriteria' => array('groupName' => $searchCriteriaGroupName)));
     })->before($app['adminBeforeTokenChecker']);
     $controllers->post('group/list', function (Request $request) use($app, $self) {
         $groupnameCriteria = trim($request->get('search-groupname'));
         $clearButton = $request->get('clear');
         if (!empty($clearButton)) {
             $app['session']->set('groupnameCriteria', '');
         } else {
             $app['session']->set('groupnameCriteria', $groupnameCriteria);
         }
         return $app->redirect(ROOT_URL . '/admin/group/list');
     })->before($app['adminBeforeTokenChecker']);
     $controllers->get('group/add', function (Request $request) use($app, $self) {
         $self->setVariables();
         return $self->render('admin/groupAdd.twig', array('mode' => 'new', 'categoryList' => $self->getGroupCategoryList(), 'formValues' => $self->getEmptyFormData()));
     })->before($app['adminBeforeTokenChecker']);
     //
     // create new logics
     //
     $controllers->post('group/add', function (Request $request) use($app, $self) {
         $self->setVariables();
         $validationError = false;
         $fileName = "";
         $thumbFileName = "";
         if ($request->files->has("file")) {
             $file = $request->files->get("file");
             if ($file && $file->isValid()) {
                 $mimeType = $file->getClientMimeType();
                 if (!preg_match("/jpeg/", $mimeType)) {
                     $self->setErrorAlert($self->language['messageValidationErrorFormat']);
                     $validationError = true;
                 } else {
                     $fileName = $self->savePicture($file);
                     $thumbFileName = $self->saveThumb($file);
                 }
             }
         }
         $formValues = $request->request->all();
         //validation
         if (empty($formValues['name']) || empty($formValues['category_id']) || empty($formValues['description'])) {
             $self->setErrorAlert($self->language['messageValidationErrorRequired']);
             $validationError = true;
         }
         // check name is unique
         $check = $self->app['spikadb']->findGroupByName($formValues['name']);
         if (isset($check['_id'])) {
             $self->setErrorAlert($self->language['messageValidationErrorGroupNotUnique']);
             $validationError = true;
         }
         if (!$validationError) {
             $password = '';
             if (!empty($formValues['group_password'])) {
                 $password = md5($formValues['group_password']);
             }
             $result = $self->app['spikadb']->createGroup($formValues['name'], $self->loginedUser['_id'], $formValues['category_id'], $formValues['description'], $password, $fileName, $thumbFileName);
             $self->app['spikadb']->subscribeGroup($result['id'], $self->loginedUser['_id']);
             return $app->redirect(ROOT_URL . '/admin/group/list?msg=messageGroupAdded');
         }
         return $self->render('admin/groupAdd.twig', array('mode' => 'new', 'categoryList' => $self->getGroupCategoryList(), 'formValues' => $formValues));
     })->before($app['adminBeforeTokenChecker']);
     //
     // Detail logics
     //
     $controllers->get('group/view/{id}', function (Request $request, $id) use($app, $self) {
         $self->setVariables();
         $group = $self->app['spikadb']->findGroupById($id);
         $tab = 'profile';
         $action = $request->get('action');
         if ($action == 'subscribe') {
             $self->app['spikadb']->subscribeGroup($group['_id'], $self->loginedUser['_id']);
             $self->setInfoAlert($self->language['messageSubscribed']);
             $self->updateLoginUserData();
         }
         if ($action == 'unsubscribe') {
             $self->app['spikadb']->unSubscribeGroup($group['_id'], $self->loginedUser['_id']);
             $self->setInfoAlert($self->language['messageUnsubscribed']);
             $self->updateLoginUserData();
         }
         $categoryList = $self->getGroupCategoryList();
         $categoryName = $categoryList[$group['category_id']]['title'];
         $group['categoryName'] = $categoryName;
         $pageSubscribedUsers = $request->get('page');
         if (empty($pageSubscribedUsers)) {
             $pageSubscribedUsers = 1;
         } else {
             $tab = 'users';
         }
         $criteria = "";
         $searchUsernameCriteria = $app['session']->get('subscribedUsersCriteria');
         $searchUsernameCriteriaValues = array();
         if (!empty($searchUsernameCriteria)) {
             $criteria .= " and LOWER(name) like LOWER(?)";
             $searchUsernameCriteriaValues[] = "%{$searchUsernameCriteria}%";
             $tab = 'users';
         }
         $userList = $self->app['spikadb']->getAllUsersByGroupIdWithCriteria($group['_id'], ($pageSubscribedUsers - 1) * ADMIN_LISTCOUNT, ADMIN_LISTCOUNT, $criteria, $searchUsernameCriteriaValues);
         $userCount = $self->app['spikadb']->getAllUsersCountByGroupIdWithCriteria($group['_id'], $criteria, $searchUsernameCriteriaValues);
         $isSubscribed = $self->checkUserIsSubscribedGroup($group['_id']);
         return $self->render('admin/groupProfile.twig', array('mode' => 'view', 'categoryList' => $self->getGroupCategoryList(), 'formValues' => $group, 'groupId' => $id, 'isSubscribed' => $isSubscribed, 'subscribedUsers' => $userList, 'tab' => $tab, 'pager' => array('baseURL' => ROOT_URL . "/admin/group/view/{$group['_id']}?page=", 'pageCount' => ceil($userCount / ADMIN_LISTCOUNT) - 1, 'page' => $pageSubscribedUsers), 'searchCriteria' => array('userName' => $searchUsernameCriteria)));
     })->before($app['adminBeforeTokenChecker']);
     $controllers->post('group/view/{id}', function (Request $request, $id) use($app, $self) {
         $usernameCriteria = trim($request->get('search-subscribedusers'));
         $clearButton = $request->get('clear');
         if (!empty($clearButton)) {
             $app['session']->set('subscribedUsersCriteria', '');
         } else {
             $app['session']->set('subscribedUsersCriteria', $usernameCriteria);
         }
         return $app->redirect(ROOT_URL . "/admin/group/view/{$id}");
     })->before($app['adminBeforeTokenChecker']);
     //
     // Edit logics
     //
     $controllers->get('group/edit/{id}', function (Request $request, $id) use($app, $self) {
         $self->setVariables();
         $tab = 'profile';
         $group = $self->app['spikadb']->findGroupById($id);
         if ($group['user_id'] != $self->loginedUser['_id'] && $self->loginedUser['_id'] != SUPPORT_USER_ID) {
             return $app->redirect(ROOT_URL . '/admin/group/list?msg=messageNoPermission');
         }
         $action = $request->get('action');
         if ($action == 'unsubscribeUser') {
             $userId = $request->get('value');
             $self->app['spikadb']->unSubscribeGroup($group['_id'], $userId);
             $self->setInfoAlert($self->language['messageKicked']);
             $self->updateLoginUserData();
             $tab = 'users';
         }
         $pageSubscribedUsers = $request->get('page');
         if (empty($pageSubscribedUsers)) {
             $pageSubscribedUsers = 1;
         } else {
             $tab = 'users';
         }
         $criteria = "";
         $searchUsernameCriteria = $app['session']->get('subscribedUsersCriteria');
         $searchUsernameCriteriaValues = array();
         if (!empty($searchUsernameCriteria)) {
             $criteria .= " and LOWER(name) like LOWER(?)";
             $searchUsernameCriteriaValues[] = "%{$searchUsernameCriteria}%";
             $tab = 'users';
         }
         $userList = $self->app['spikadb']->getAllUsersByGroupIdWithCriteria($group['_id'], ($pageSubscribedUsers - 1) * ADMIN_LISTCOUNT, ADMIN_LISTCOUNT, $criteria, $searchUsernameCriteriaValues);
         $userCount = $self->app['spikadb']->getAllUsersCountByGroupIdWithCriteria($group['_id'], $criteria, $searchUsernameCriteriaValues);
         $categoryList = $self->getGroupCategoryList();
         if (isset($categoryList[$group['category_id']]['title'])) {
             $categoryName = $categoryList[$group['category_id']]['title'];
         } else {
             $categoryName = '';
         }
         $group['categoryName'] = $categoryName;
         return $self->render('admin/groupEdit.twig', array('id' => $id, 'mode' => 'edit', 'categoryList' => $self->getGroupCategoryList(), 'formValues' => $group, 'tab' => $tab, 'subscribedUsers' => $userList, 'pager' => array('baseURL' => ROOT_URL . "/admin/group/edit/{$group['_id']}?page=", 'pageCount' => ceil($userCount / ADMIN_LISTCOUNT) - 1, 'page' => $pageSubscribedUsers), 'searchCriteria' => array('userName' => $searchUsernameCriteria)));
     })->before($app['adminBeforeTokenChecker']);
     $controllers->post('group/edit/{id}', function (Request $request, $id) use($app, $self) {
         // search
         $usernameCriteria = trim($request->get('search-subscribedusers'));
         $clearButton = $request->get('clear');
         $searchButton = $request->get('search');
         if (!empty($clearButton)) {
             $app['session']->set('subscribedUsersCriteria', '');
             return $app->redirect(ROOT_URL . "/admin/group/edit/{$id}");
         }
         if (!empty($searchButton)) {
             $app['session']->set('subscribedUsersCriteria', $usernameCriteria);
             return $app->redirect(ROOT_URL . "/admin/group/edit/{$id}");
         }
         // update
         $self->setVariables();
         $tab = 'profile';
         $group = $self->app['spikadb']->findGroupById($id);
         if ($group['user_id'] != $self->loginedUser['_id'] && $self->loginedUser['_id'] != SUPPORT_USER_ID) {
             return $app->redirect(ROOT_URL . '/admin/group/list?msg=messageNoPermission');
         }
         $validationError = false;
         $fileName = "";
         $thumbFileName = "";
         $formValues = $request->request->all();
         $fileName = $group['avatar_file_id'];
         $thumbFileName = $group['avatar_thumb_file_id'];
         if ($request->files->has("file")) {
             $file = $request->files->get("file");
             if ($file && $file->isValid()) {
                 $mimeType = $file->getClientMimeType();
                 if (!preg_match("/jpeg/", $mimeType)) {
                     $self->setErrorAlert($self->language['messageValidationErrorFormat']);
                     $validationResult = true;
                 } else {
                     $fileName = $self->savePicture($file);
                     $thumbFileName = $self->saveThumb($file);
                 }
             }
         } else {
         }
         if (isset($formValues['chkbox_delete_picture'])) {
             $fileName = '';
             $thumbFileName = '';
         }
         //validation
         if (empty($formValues['name']) || empty($formValues['category_id']) || empty($formValues['description'])) {
             $self->setErrorAlert($self->language['messageValidationErrorRequired']);
             $validationError = true;
         }
         // check name is unique
         $check = $self->app['spikadb']->findGroupByName($formValues['name']);
         if (isset($check['_id']) && $check['_id'] != $group['_id']) {
             $self->setErrorAlert($self->language['messageValidationErrorGroupNotUnique']);
             $validationError = true;
         }
         if (!$validationError) {
             $password = '';
             if (isset($formValues['chkbox_change_password'])) {
                 if (!empty($formValues['group_password'])) {
                     $password = md5($formValues['group_password']);
                 }
             } else {
                 $password = $group['group_password'];
             }
             $self->app['spikadb']->updateGroup($id, $formValues['name'], SUPPORT_USER_ID, $formValues['category_id'], $formValues['description'], $password, $fileName, $thumbFileName);
             $group = $self->app['spikadb']->findGroupById($id);
         }
         $criteria = "";
         $searchUsernameCriteria = $app['session']->get('subscribedUsersCriteria');
         $searchUsernameCriteriaValues = array();
         if (!empty($searchUsernameCriteria)) {
             $criteria .= " and LOWER(name) like LOWER(?)";
             $searchUsernameCriteriaValues[] = "%{$searchUsernameCriteria}%";
             $tab = 'users';
         }
         $userList = $self->app['spikadb']->getAllUsersByGroupIdWithCriteria($group['_id'], 0, ADMIN_LISTCOUNT, $criteria, $searchUsernameCriteriaValues);
         $userCount = $self->app['spikadb']->getAllUsersCountByGroupIdWithCriteria($group['_id'], $criteria, $searchUsernameCriteriaValues);
         return $self->render('admin/groupEdit.twig', array('id' => $id, 'mode' => 'edit', 'categoryList' => $self->getGroupCategoryList(), 'formValues' => $group, 'tab' => $tab, 'subscribedUsers' => $userList, 'pager' => array('baseURL' => ROOT_URL . "/admin/group/edit/{$group['_id']}?page=", 'pageCount' => ceil($userCount / ADMIN_LISTCOUNT) - 1, 'page' => 1), 'searchCriteria' => array('userName' => $searchUsernameCriteria)));
     })->before($app['adminBeforeTokenChecker']);
     //
     // Delete logics
     //
     $controllers->get('group/delete/{id}', function (Request $request, $id) use($app, $self) {
         $self->setVariables();
         $group = $self->app['spikadb']->findGroupById($id);
         if ($group['user_id'] != $self->loginedUser['_id'] && $self->loginedUser['_id'] != SUPPORT_USER_ID) {
             return $app->redirect(ROOT_URL . '/admin/group/list?msg=messageNoPermission');
         }
         $categoryList = $self->getGroupCategoryList();
         $categoryName = $categoryList[$group['category_id']]['title'];
         $group['categoryName'] = $categoryName;
         return $self->render('admin/groupDelete.twig', array('id' => $id, 'mode' => 'delete', 'categoryList' => $self->getGroupCategoryList(), 'formValues' => $group));
     })->before($app['adminBeforeTokenChecker']);
     $controllers->post('group/delete/{id}', function (Request $request, $id) use($app, $self) {
         $self->setVariables();
         $group = $self->app['spikadb']->findGroupById($id);
         if ($group['user_id'] != $self->loginedUser['_id'] && $self->loginedUser['_id'] != SUPPORT_USER_ID) {
             return $app->redirect(ROOT_URL . '/admin/group/list?msg=messageNoPermission');
         }
         $formValues = $request->request->all();
         if (isset($formValues['submit_delete'])) {
             $self->app['spikadb']->deleteGroup($id);
             return $app->redirect(ROOT_URL . '/admin/group/list?msg=messageGroupDeleted');
         } else {
             return $app->redirect(ROOT_URL . '/admin/group/list');
         }
     })->before($app['adminBeforeTokenChecker']);
     $controllers->get('group/users/{groupId}', function (Request $request, $groupId) use($app, $self) {
         $page = $request->get('page');
         if (empty($page)) {
             $page = 1;
         }
         $msg = $request->get('msg');
         if (!empty($msg)) {
             $self->setInfoAlert($self->language[$msg]);
         }
         $users = $self->app['spikadb']->getAllUsersByGroupId($groupId, ($page - 1) * ADMIN_LISTCOUNT, ADMIN_LISTCOUNT);
         $count = $self->app['spikadb']->getAllUsersCountByGroupId($groupId);
         return $self->render('admin/groupUserList.twig', array('groupId' => $groupId, 'users' => $users, 'pager' => array('baseURL' => ROOT_URL . "/admin/group/users/{$groupId}?page=", 'pageCount' => ceil($count / ADMIN_LISTCOUNT) - 1, 'page' => $page)));
     })->before($app['adminBeforeTokenChecker']);
     $controllers->get('group/unsubscribeUser/{groupId}/{userId}', function (Request $request, $groupId, $userId) use($app, $self) {
         $group = $self->app['spikadb']->findGroupById($id);
         if ($group['user_id'] != $self->loginedUser['_id'] && $self->loginedUser['_id'] != SUPPORT_USER_ID) {
             return $app->redirect(ROOT_URL . '/admin/group/list?msg=messageNoPermission');
         }
         $self->app['spikadb']->unSubscribeGroup($groupId, $userId);
         return $app->redirect(ROOT_URL . "/admin/group/users/{$groupId}?msg=messageRemoveUser");
     })->before($app['adminBeforeTokenChecker']);
     return $controllers;
 }
 public function connect(Application $app)
 {
     parent::connect($app);
     $controllers = $app['controllers_factory'];
     $self = $this;
     //
     // List/paging logics
     //
     $controllers->get('servers/list', function (Request $request) use($app, $self) {
         $self->setVariables();
         $count = $self->app['spikadb']->findServersCount();
         $page = $request->get('page');
         if (empty($page)) {
             $page = 1;
         }
         $msg = $request->get('msg');
         if (!empty($msg)) {
             $self->setInfoAlert($self->language[$msg]);
         }
         $servers = $self->app['spikadb']->findAllServers(($page - 1) * ADMIN_LISTCOUNT, ADMIN_LISTCOUNT);
         // convert timestamp to date
         for ($i = 0; $i < count($servers); $i++) {
             $servers[$i]['created'] = date("Y.m.d", $servers[$i]['created']);
             $servers[$i]['modified'] = date("Y.m.d", $servers[$i]['modified']);
         }
         return $self->render('admin/serversList.twig', array('servers' => $servers, 'pager' => array('baseURL' => ROOT_URL . "/admin/servers/list?page=", 'pageCount' => ceil($count / ADMIN_LISTCOUNT) - 1, 'page' => $page)));
     })->before($app['adminBeforeTokenChecker']);
     ///**************************************************
     //***************************************************
     $controllers->get('servers/add', function (Request $request) use($app, $self) {
         $self->setVariables();
         if (!$self->checkPermission()) {
             return $app->redirect(ROOT_URL . '/admin/servers/list?msg=messageNoPermission');
         }
         return $self->render('admin/serversForm.twig', array('mode' => 'new', 'formValues' => $self->getEmptyFormData()));
     })->before($app['adminBeforeTokenChecker']);
     //
     // create new logics
     //
     $controllers->post('servers/add', function (Request $request) use($app, $self) {
         $self->setVariables();
         if (!$self->checkPermission()) {
             return $app->redirect(ROOT_URL . '/admin/servers/list?msg=messageNoPermission');
         }
         $validationError = false;
         $formValues = $request->request->all();
         //validation
         if (empty($formValues['name']) || empty($formValues['url'])) {
             $self->setErrorAlert($self->language['messageValidationErrorRequired']);
             $validationError = true;
         }
         //checking url
         $pattern = "/^https?:\\/\\/(.*)[^\\/]\$/";
         if (preg_match($pattern, $formValues['url'], $match) == 0) {
             $self->setErrorAlert($self->language['messageUrlIsNotValid']);
             $validationError = true;
         }
         if (!$validationError) {
             $result = $self->app['spikadb']->createServer($formValues['name'], $formValues['url']);
             return $app->redirect(ROOT_URL . '/admin/servers/list?msg=messageServerAdded');
         }
         return $self->render('admin/serversForm.twig', array('mode' => 'new', 'formValues' => $formValues));
     })->before($app['adminBeforeTokenChecker']);
     //
     // Detail logics
     //
     $controllers->get('servers/view/{id}', function (Request $request, $id) use($app, $self) {
         $self->setVariables();
         $server = $self->app['spikadb']->findServerById($id);
         return $self->render('admin/serversForm.twig', array('mode' => 'view', 'formValues' => $server));
     })->before($app['adminBeforeTokenChecker']);
     //
     // Edit logics
     //
     $controllers->get('servers/edit/{id}', function (Request $request, $id) use($app, $self) {
         $self->setVariables();
         if (!$self->checkPermission()) {
             return $app->redirect(ROOT_URL . '/admin/servers/list?msg=messageNoPermission');
         }
         $server = $self->app['spikadb']->findServerById($id);
         return $self->render('admin/serversForm.twig', array('id' => $id, 'mode' => 'edit', 'formValues' => $server));
     })->before($app['adminBeforeTokenChecker']);
     $controllers->post('servers/edit/{id}', function (Request $request, $id) use($app, $self) {
         $self->setVariables();
         $server = $self->app['spikadb']->findServerById($id);
         $formValues = $request->request->all();
         $validationError = false;
         //validation
         if (empty($formValues['name']) || empty($formValues['url'])) {
             $self->setErrorAlert($self->language['messageValidationErrorRequired']);
             $validationError = true;
         }
         //checking url
         $pattern = "/^https?:\\/\\/(.*)[^\\/]\$/";
         if (preg_match($pattern, $formValues['url'], $match) == 0) {
             $self->setErrorAlert($self->language['messageUrlIsNotValid']);
             $validationError = true;
         }
         if (!$validationError) {
             $self->app['spikadb']->updateServer($id, $formValues['name'], $formValues['url']);
             return $app->redirect(ROOT_URL . '/admin/servers/list?msg=messageServerChanged');
         }
         return $self->render('admin/serversForm.twig', array('id' => $id, 'mode' => 'edit', 'formValues' => $server));
     })->before($app['adminBeforeTokenChecker']);
     //
     // Delete logics
     //
     $controllers->get('servers/delete/{id}', function (Request $request, $id) use($app, $self) {
         $self->setVariables();
         if (!$self->checkPermission()) {
             return $app->redirect(ROOT_URL . '/admin/servers/list?msg=messageNoPermission');
         }
         $server = $self->app['spikadb']->findServerById($id);
         return $self->render('admin/serversDelete.twig', array('id' => $id, 'mode' => 'delete', 'formValues' => $server));
     })->before($app['adminBeforeTokenChecker']);
     $controllers->post('servers/delete/{id}', function (Request $request, $id) use($app, $self) {
         $self->setVariables();
         if (!$self->checkPermission()) {
             return $app->redirect(ROOT_URL . '/admin/servers/list?msg=messageNoPermission');
         }
         $formValues = $request->request->all();
         if (isset($formValues['submit_delete'])) {
             $self->app['spikadb']->deleteServer($id);
             return $app->redirect(ROOT_URL . '/admin/servers/list?msg=messageServerDeleted');
         } else {
             return $app->redirect(ROOT_URL . '/admin/servers/list');
         }
     })->before($app['adminBeforeTokenChecker']);
     return $controllers;
 }
 public function connect(Application $app)
 {
     parent::connect($app);
     $controllers = $app['controllers_factory'];
     $self = $this;
     //
     // List/paging logics
     //
     $controllers->get('emoticon/list', function (Request $request) use($app, $self) {
         $self->setVariables();
         if (!$self->checkPermission()) {
             return $app->redirect(ROOT_URL . '/admin/user/list?msg=messageNoPermission');
         }
         $count = $self->app['spikadb']->findEmoticonCount();
         $page = $request->get('page');
         if (empty($page)) {
             $page = 1;
         }
         $msg = $request->get('msg');
         if (!empty($msg)) {
             $self->setInfoAlert($self->language[$msg]);
         }
         $emoticons = $self->app['spikadb']->findAllEmoticonsWithPaging(($page - 1) * ADMIN_LISTCOUNT, ADMIN_LISTCOUNT);
         // convert timestamp to date
         for ($i = 0; $i < count($emoticons['rows']); $i++) {
             $emoticons['rows'][$i]['value']['created'] = date("Y.m.d", $emoticons['rows'][$i]['value']['created']);
             $emoticons['rows'][$i]['value']['modified'] = date("Y.m.d", $emoticons['rows'][$i]['value']['modified']);
         }
         return $self->render('admin/emoticonList.twig', array('emoticons' => $emoticons['rows'], 'pager' => array('baseURL' => ROOT_URL . "/admin/emoticon/list?page=", 'pageCount' => ceil($count / ADMIN_LISTCOUNT) - 1, 'page' => $page)));
     })->before($app['adminBeforeTokenChecker']);
     $controllers->get('emoticon/add', function (Request $request) use($app, $self) {
         $self->setVariables();
         if (!$self->checkPermission()) {
             return $app->redirect(ROOT_URL . '/admin/user/list?msg=messageNoPermission');
         }
         return $self->render('admin/emoticonForm.twig', array('mode' => 'new', 'formValues' => $self->getEmptyFormData()));
     })->before($app['adminBeforeTokenChecker']);
     //
     // create new logics
     //
     $controllers->post('emoticon/add', function (Request $request) use($app, $self) {
         $self->setVariables();
         if (!$self->checkPermission()) {
             return $app->redirect(ROOT_URL . '/admin/user/list?msg=messageNoPermission');
         }
         $formValues = $request->request->all();
         $validationError = false;
         $fileName = "";
         $thumbFileName = "";
         $validationResult = $self->validate($request);
         if ($validationResult) {
             if ($request->files->has("file")) {
                 $file = $request->files->get("file");
                 if ($file && $file->isValid()) {
                     $fileName = $self->savePicture($file);
                 }
             }
             $self->app['spikadb']->createEmoticon($formValues['identifier'], $fileName);
             return $app->redirect(ROOT_URL . '/admin/emoticon/list?msg=messageEmoticonAdded');
         }
         return $self->render('admin/emoticonForm.twig', array('mode' => 'new', 'formValues' => $formValues));
     })->before($app['adminBeforeTokenChecker']);
     //
     // Detail logics
     //
     $controllers->get('emoticon/view/{id}', function (Request $request, $id) use($app, $self) {
         $self->setVariables();
         if (!$self->checkPermission()) {
             return $app->redirect(ROOT_URL . '/admin/user/list?msg=messageNoPermission');
         }
         $emoticon = $self->app['spikadb']->findEmoticonById($id);
         return $self->render('admin/emoticonForm.twig', array('mode' => 'view', 'formValues' => $emoticon));
     })->before($app['adminBeforeTokenChecker']);
     //
     // Edit logics
     //
     $controllers->get('emoticon/edit/{id}', function (Request $request, $id) use($app, $self) {
         $self->setVariables();
         if (!$self->checkPermission()) {
             return $app->redirect(ROOT_URL . '/admin/user/list?msg=messageNoPermission');
         }
         $emoticon = $self->app['spikadb']->findEmoticonById($id);
         return $self->render('admin/emoticonForm.twig', array('id' => $id, 'mode' => 'edit', 'formValues' => $emoticon));
     })->before($app['adminBeforeTokenChecker']);
     $controllers->post('emoticon/edit/{id}', function (Request $request, $id) use($app, $self) {
         $self->setVariables();
         if (!$self->checkPermission()) {
             return $app->redirect(ROOT_URL . '/admin/user/list?msg=messageNoPermission');
         }
         $validationError = false;
         $fileName = "";
         $emoticon = $self->app['spikadb']->findEmoticonById($id);
         $formValues = $request->request->all();
         $fileName = $emoticon['file_id'];
         $validationResult = $self->validate($request, true, $id);
         if ($validationResult) {
             if ($request->files->has("file")) {
                 $file = $request->files->get("file");
                 if ($file && $file->isValid()) {
                     $fileName = $self->savePicture($file);
                 }
             }
             $self->app['spikadb']->updateEmoticon($id, $formValues['identifier'], $fileName);
             return $app->redirect(ROOT_URL . '/admin/emoticon/list?msg=messageEmoticonChanged');
         }
         return $self->render('admin/emoticonForm.twig', array('id' => $id, 'mode' => 'edit', 'formValues' => $emoticon));
     })->before($app['adminBeforeTokenChecker']);
     //
     // Delete logics
     //
     $controllers->get('emoticon/delete/{id}', function (Request $request, $id) use($app, $self) {
         $self->setVariables();
         if (!$self->checkPermission()) {
             return $app->redirect(ROOT_URL . '/admin/user/list?msg=messageNoPermission');
         }
         $emoticon = $self->app['spikadb']->findEmoticonById($id);
         return $self->render('admin/emoticonDelete.twig', array('id' => $id, 'mode' => 'delete', 'formValues' => $emoticon));
     })->before($app['adminBeforeTokenChecker']);
     $controllers->post('emoticon/delete/{id}', function (Request $request, $id) use($app, $self) {
         $self->setVariables();
         if (!$self->checkPermission()) {
             return $app->redirect(ROOT_URL . '/admin/user/list?msg=messageNoPermission');
         }
         $formValues = $request->request->all();
         if (isset($formValues['submit_delete'])) {
             $self->app['spikadb']->deleteEmoticon($id);
             return $app->redirect(ROOT_URL . '/admin/emoticon/list?msg=messageEmoticonDeleted');
         } else {
             return $app->redirect(ROOT_URL . '/admin/emoticon/list');
         }
     })->before($app['adminBeforeTokenChecker']);
     return $controllers;
 }
 public function connect(Application $app)
 {
     parent::connect($app);
     $controllers = $app['controllers_factory'];
     $self = $this;
     $controllers->get('/', function (Request $request) use($app, $self) {
         return $app->redirect(ROOT_URL . '/client/login');
     });
     $controllers->get('/login', function (Request $request) use($app, $self) {
         $cookies = $request->cookies;
         $username = "";
         $password = "";
         if ($cookies->has('username')) {
             $username = $cookies->get('username');
         }
         if ($cookies->has('password')) {
             $password = $cookies->get('password');
         }
         return $self->render('client/login.twig', array('ROOT_URL' => ROOT_URL, 'formValues' => array('username' => $username, 'password' => $password, 'rememberChecked' => '')));
     });
     $controllers->post('/login', function (Request $request) use($app, $self) {
         $self->setVariables();
         $registBtn = $request->get('regist');
         if (!empty($registBtn)) {
             return new RedirectResponse("regist");
         }
         $username = $request->get('username');
         $password = $request->get('password');
         $remember = $request->get('remember');
         $rememberChecked = "";
         if (!empty($remember)) {
             $rememberChecked = "checked=\"checked\"";
         }
         $authData = $self->app['spikadb']->doSpikaAuth($username, md5($password));
         $authData = json_decode($authData, true);
         if (isset($authData['token'])) {
             $html = $self->render('client/login.twig', array('ROOT_URL' => ROOT_URL, 'formValues' => array('username' => $username, 'password' => $password, 'rememberChecked' => $rememberChecked)));
             $response = new RedirectResponse(ROOT_URL . "/client/main");
             $app['session']->set('user', $authData);
             return $response;
         } else {
             $self->setErrorAlert($self->language['messageLoginFailed']);
             return $self->render('client/login.twig', array('ROOT_URL' => ROOT_URL, 'formValues' => array('username' => $username, 'password' => $password, 'rememberChecked' => $rememberChecked)));
         }
     });
     $controllers->get('/logout', function (Request $request) use($app, $self) {
         $app['session']->remove('user');
         $response = new RedirectResponse("login");
         return $response;
     });
     $controllers->get('/regist', function (Request $request) use($app, $self) {
         $cookies = $request->cookies;
         $email = "";
         $username = "";
         $password = "";
         return $self->render('client/regist.twig', array('ROOT_URL' => ROOT_URL, 'formValues' => array('username' => $username, 'password' => $password, 'email' => $email)));
     });
     $controllers->post('/regist', function (Request $request) use($app, $self) {
         $self->setVariables();
         $username = $request->get('username');
         $password = $request->get('password');
         $email = $request->get('email');
         $loginBtn = $request->get('login');
         if (!empty($loginBtn)) {
             return new RedirectResponse("login");
         }
         // validation
         $errorMessage = "";
         if (empty($username)) {
             $errorMessage = $self->language['messageValidationErrorEmptyUserName'];
         } else {
             if (empty($email)) {
                 $errorMessage = $self->language['messageValidationErrorEmptyEmail'];
             } else {
                 if (empty($password)) {
                     $errorMessage = $self->language['messageValidationErrorEmptyPassword'];
                 }
             }
         }
         if (empty($errorMessage)) {
             if (!Utils::checkEmailIsValid($email)) {
                 $errorMessage = $self->language['messageValidationErrorInvalidEmail'];
             }
         }
         if (empty($errorMessage)) {
             if (!Utils::checkPasswordIsValid($password)) {
                 $errorMessage = $self->language['messageValidationErrorInvalidPassword'];
             }
         }
         if (empty($errorMessage)) {
             $check = $app['spikadb']->findUserByName($username);
             if (!empty($check['_id'])) {
                 $errorMessage = $self->language['messageValidationErrorUserNameNotUnique'];
             }
         }
         if (empty($errorMessage)) {
             $check = $app['spikadb']->findUserByEmail($email);
             if (!empty($check['_id'])) {
                 $errorMessage = $self->language['messageValidationErrorUserEmailNotUnique'];
             }
         }
         if (!empty($errorMessage)) {
             $self->setErrorAlert($errorMessage);
         } else {
             $newUserId = $app['spikadb']->createUser($username, $email, md5($password));
             $authData = $self->app['spikadb']->doSpikaAuth($email, md5($password));
             $authData = json_decode($authData, true);
             $response = new RedirectResponse("main");
             $app['session']->set('user', $authData);
             return $response;
         }
         return $self->render('client/regist.twig', array('ROOT_URL' => ROOT_URL, 'formValues' => array('username' => $username, 'password' => $password, 'email' => $email)));
     });
     $controllers->get('/resetPassword', function (Request $request) use($app, $self) {
         $self->setVariables();
         return $self->render('client/resetpassword.twig', array('ROOT_URL' => ROOT_URL, 'formValues' => array('email' => '')));
     });
     $controllers->post('/resetPassword', function (Request $request) use($app, $self) {
         $self->setVariables();
         $email = $request->get('email');
         $loginBtn = $request->get('login');
         if (!empty($loginBtn)) {
             return new RedirectResponse("login");
         }
         // validation
         $errorMessage = "";
         if (empty($email)) {
             $errorMessage = $self->language['messageValidationErrorEmptyEmail'];
         }
         if (empty($errorMessage)) {
             $check = $app['spikadb']->findUserByEmail($email);
             if (empty($check['_id'])) {
                 $errorMessage = $self->language['messageValidationEmailIsNotExist'];
             }
         }
         if (!empty($errorMessage)) {
             $self->setErrorAlert($errorMessage);
         } else {
             // call api
             $client = new Client();
             $request = $client->get(LOCAL_ROOT_URL . "/api/resetPassword?email=" . $email);
             $response = $request->send();
             $self->setInfoAlert($self->language['messageResetPasswordEmailSent']);
         }
         return $self->render('client/resetpassword.twig', array('ROOT_URL' => ROOT_URL, 'formValues' => array('email' => $email)));
     });
     return $controllers;
 }
 public function connect(Application $app)
 {
     parent::connect($app);
     $controllers = $app['controllers_factory'];
     $self = $this;
     //
     // List/paging logics
     //
     $controllers->get('user/list', function (Request $request) use($app, $self) {
         $self->setVariables();
         // search criteria
         $searchCriteriaUserName = $app['session']->get('usernameCriteria');
         $criteria = "";
         $criteriaValues = array();
         if (!empty($searchCriteriaUserName)) {
             $criteria .= " and LOWER(name) like LOWER(?)";
             $criteriaValues[] = "%{$searchCriteriaUserName}%";
         }
         $count = $self->app['spikadb']->findUserCountWithCriteria($criteria, $criteriaValues);
         $page = $request->get('page');
         if (empty($page)) {
             $page = 1;
         }
         $msg = $request->get('msg');
         if (!empty($msg)) {
             $self->setInfoAlert($self->language[$msg]);
         }
         $users = $self->app['spikadb']->findAllUsersWithPagingWithCriteria(($page - 1) * ADMIN_LISTCOUNT, ADMIN_LISTCOUNT, $criteria, $criteriaValues);
         // convert timestamp to date
         for ($i = 0; $i < count($users['rows']); $i++) {
             $users['rows'][$i]['value']['created'] = date("Y.m.d", $users['rows'][$i]['value']['created']);
             $users['rows'][$i]['value']['modified'] = date("Y.m.d", $users['rows'][$i]['value']['modified']);
         }
         return $self->render('admin/userList.twig', array('categoryList' => $self->getGroupCategoryList(), 'users' => $users['rows'], 'pager' => array('baseURL' => ROOT_URL . "/admin/user/list?page=", 'pageCount' => ceil($count / ADMIN_LISTCOUNT) - 1, 'page' => $page), 'searchCriteria' => array('username' => $searchCriteriaUserName)));
     })->before($app['adminBeforeTokenChecker']);
     $controllers->post('user/list', function (Request $request) use($app, $self) {
         $usernameCriteria = trim($request->get('search-username'));
         $clearButton = $request->get('clear');
         if (!empty($clearButton)) {
             $app['session']->set('usernameCriteria', '');
         } else {
             $app['session']->set('usernameCriteria', $usernameCriteria);
         }
         return $app->redirect(ROOT_URL . '/admin/user/list');
     })->before($app['adminBeforeTokenChecker']);
     $controllers->get('user/add', function (Request $request) use($app, $self) {
         $self->setVariables();
         if (!$self->checkPermission()) {
             return $app->redirect(ROOT_URL . '/admin/user/list?msg=messageNoPermission');
         }
         return $self->render('admin/userAdd.twig', array('mode' => 'new', 'statusList' => $self->userStatusList, 'genderList' => $self->userGenderList, 'formValues' => $self->getEmptyFormData()));
     })->before($app['adminBeforeTokenChecker']);
     //
     // create new logics
     //
     $controllers->post('user/add', function (Request $request) use($app, $self) {
         $self->setVariables();
         if (!$self->checkPermission()) {
             return $app->redirect(ROOT_URL . '/admin/user/list?msg=messageNoPermission');
         }
         $formValues = $request->request->all();
         $validationError = false;
         $fileName = "";
         $thumbFileName = "";
         $validationResult = $self->validate($request);
         if ($validationResult) {
             if ($request->files->has("file")) {
                 $file = $request->files->get("file");
                 if ($file && $file->isValid()) {
                     $fileName = $self->savePicture($file);
                     $thumbFileName = $self->saveThumb($file);
                 }
             }
             $self->app['spikadb']->createUserDetail($formValues['name'], md5($formValues['password']), $formValues['email'], $formValues['about'], $formValues['online_status'], $formValues['max_contact_count'], $formValues['max_favorite_count'], strtotime($formValues['birthday']), $formValues['gender'], $fileName, $thumbFileName);
             return $app->redirect(ROOT_URL . '/admin/user/list?msg=messageUserAdded');
         }
         return $self->render('admin/userAdd.twig', array('mode' => 'new', 'statusList' => $self->userStatusList, 'genderList' => $self->userGenderList, 'formValues' => $formValues));
     })->before($app['adminBeforeTokenChecker']);
     //
     // Detail logics
     //
     $controllers->get('user/view/{id}', function (Request $request, $id) use($app, $self) {
         $self->setVariables();
         $user = $self->app['spikadb']->findUserById($id, false);
         $action = $request->get('action');
         if ($action == 'addToContact') {
             $self->app['spikadb']->addContact($self->loginedUser['_id'], $user['_id']);
             $self->setInfoAlert($self->language['labelAddToContact']);
             $self->updateLoginUserData();
         }
         if ($action == 'removeFromContact') {
             $self->app['spikadb']->removeContact($self->loginedUser['_id'], $user['_id']);
             $self->setInfoAlert($self->language['messageRemoveContact']);
             $self->updateLoginUserData();
         }
         $isInMyContact = $self->checkUserIsInLoginUserContact($user['_id']);
         $contact = $self->app['spikadb']->getContactsByUserId($id);
         $contacted = $self->app['spikadb']->getContactedByUserId($id);
         $group = $self->app['spikadb']->getGroupsByUserId($id);
         return $self->render('admin/userProfile.twig', array('mode' => 'view', 'statusList' => $self->userStatusList, 'genderList' => $self->userGenderList, 'userId' => $id, 'formValues' => $user, 'contacts' => $contact, 'contacted' => $contacted, 'groups' => $group, 'categoryList' => $self->getGroupCategoryList(), 'isInMyContact' => $isInMyContact));
     })->before($app['adminBeforeTokenChecker']);
     //
     // Edit logics
     //
     $controllers->get('user/edit/{id}', function (Request $request, $id) use($app, $self) {
         $tab = 'profile';
         $self->setVariables();
         if (!$self->checkPermission() && $self->loginedUser['_id'] != $id) {
             return $app->redirect(ROOT_URL . '/admin/user/list?msg=messageNoPermission');
         }
         $action = $request->get('action');
         if ($action == 'removeContact') {
             $removeUserId = $request->get('value');
             if (!empty($removeUserId)) {
                 $self->app['spikadb']->removeContact($id, $removeUserId);
                 $self->setInfoAlert($self->language['messageRemoveContact']);
             }
             $self->updateLoginUserData();
             $tab = 'contacts';
         }
         if ($action == 'removeGroup') {
             $groupId = $request->get('value');
             if (!empty($groupId)) {
                 $self->app['spikadb']->unSubscribeGroup($groupId, $id);
                 $self->setInfoAlert($self->language['messagUnsubscribed']);
             }
             $self->updateLoginUserData();
             $tab = 'groups';
         }
         $user = $self->app['spikadb']->findUserById($id, false);
         $user['birthday'] = date('Y-m-d', $user['birthday']);
         $contact = $self->app['spikadb']->getContactsByUserId($id);
         $group = $self->app['spikadb']->getGroupsByUserId($id);
         return $self->render('admin/userEdit.twig', array('id' => $id, 'mode' => 'edit', 'statusList' => $self->userStatusList, 'genderList' => $self->userGenderList, 'contacts' => $contact, 'groups' => $group, 'formValues' => $user, 'userId' => $id, 'contacts' => $contact, 'groups' => $group, 'tab' => $tab));
     })->before($app['adminBeforeTokenChecker']);
     $controllers->post('user/edit/{id}', function (Request $request, $id) use($app, $self) {
         $self->setVariables();
         if (!$self->checkPermission() && $self->loginedUser['_id'] != $id) {
             return $app->redirect(ROOT_URL . '/admin/user/list?msg=messageNoPermission');
         }
         $validationError = false;
         $fileName = "";
         $thumbFileName = "";
         $user = $self->app['spikadb']->findUserById($id, false);
         $formValues = $request->request->all();
         $fileName = $user['avatar_file_id'];
         $thumbFileName = $user['avatar_thumb_file_id'];
         $validationResult = $self->validate($request, true, $id);
         if ($validationResult) {
             if ($request->files->has("file")) {
                 $file = $request->files->get("file");
                 if ($file && $file->isValid()) {
                     $fileName = $self->savePicture($file);
                     $thumbFileName = $self->saveThumb($file);
                 }
             }
             if (isset($formValues['chkbox_delete_picture'])) {
                 $fileName = '';
                 $thumbFileName = '';
             }
             $password = $user['password'];
             if (isset($formValues['chkbox_change_password'])) {
                 if (!empty($formValues['password'])) {
                     $password = md5($formValues['password']);
                 }
             }
             $self->app['spikadb']->updateUser($id, array('name' => $formValues['name'], 'email' => $formValues['email'], 'password' => $password, 'about' => $formValues['about'], 'online_status' => $formValues['online_status'], 'birthday' => strtotime($formValues['birthday']), 'gender' => $formValues['gender'], 'avatar_file_id' => $fileName, 'avatar_thumb_file_id' => $thumbFileName, 'max_contact_count' => $formValues['max_contact_count'], 'max_favorite_count' => $formValues['max_favorite_count']), false);
             $user = $self->app['spikadb']->findUserById($id, false);
             $self->setInfoAlert($self->language['messageUserChanged']);
         }
         $contact = $self->app['spikadb']->getContactsByUserId($id);
         $group = $self->app['spikadb']->getGroupsByUserId($id);
         $user['birthday'] = date('Y-m-d', $user['birthday']);
         return $self->render('admin/userEdit.twig', array('id' => $id, 'mode' => 'edit', 'statusList' => $self->userStatusList, 'genderList' => $self->userGenderList, 'userId' => $id, 'contacts' => $contact, 'groups' => $group, 'formValues' => $user, 'tab' => 'profile'));
     })->before($app['adminBeforeTokenChecker']);
     //
     // Delete logics
     //
     $controllers->get('user/delete/{id}', function (Request $request, $id) use($app, $self) {
         $self->setVariables();
         if (!$self->checkPermission()) {
             return $app->redirect(ROOT_URL . '/admin/user/list?msg=messageNoPermission');
         }
         $user = $self->app['spikadb']->findUserById($id, false);
         return $self->render('admin/userDelete.twig', array('id' => $id, 'mode' => 'delete', 'formValues' => $user));
     })->before($app['adminBeforeTokenChecker']);
     $controllers->post('user/delete/{id}', function (Request $request, $id) use($app, $self) {
         $self->setVariables();
         if (!$self->checkPermission()) {
             return $app->redirect(ROOT_URL . '/admin/user/list?msg=messageNoPermission');
         }
         $formValues = $request->request->all();
         if (isset($formValues['submit_delete'])) {
             $self->app['spikadb']->deleteUser($id);
             return $app->redirect(ROOT_URL . '/admin/user/list?msg=messageUserDeleted');
         } else {
             return $app->redirect(ROOT_URL . '/admin/user/list');
         }
     })->before($app['adminBeforeTokenChecker']);
     $controllers->get('user/conversation/{userId}', function (Request $request, $userId) use($app, $self) {
         $self->setVariables();
         if (!$self->checkPermission()) {
             return $app->redirect(ROOT_URL . '/admin/user/list?msg=messageNoPermission');
         }
         $count = $self->app['spikadb']->getConversationHistoryCount($userId);
         $page = $request->get('page');
         if (empty($page)) {
             $page = 1;
         }
         $msg = $request->get('msg');
         if (!empty($msg)) {
             $self->setInfoAlert($self->language[$msg]);
         }
         $conversationHistory = $self->app['spikadb']->getConversationHistory($userId, ($page - 1) * ADMIN_LISTCOUNT, ADMIN_LISTCOUNT);
         // convert timestamp to date
         for ($i = 0; $i < count($conversationHistory); $i++) {
             $conversationHistory[$i]['created'] = date("Y.m.d H:i:s", $conversationHistory[$i]['created']);
         }
         $user = $self->app['spikadb']->findUserById($userId);
         return $self->render('admin/userConversationHistory.twig', array('conversations' => $conversationHistory, 'pager' => array('baseURL' => ROOT_URL . "/admin/user/conversateion/{$userId}?page=", 'pageCount' => ceil($count / ADMIN_LISTCOUNT) - 1, 'page' => $page), 'user' => $self->app['spikadb']->findUserById($userId, false)));
     })->before($app['adminBeforeTokenChecker']);
     return $controllers;
 }
 public function connect(Application $app)
 {
     parent::connect($app);
     $controllers = $app['controllers_factory'];
     $self = $this;
     //
     // List/paging logics
     //
     $controllers->get('news/list', function (Request $request) use($app, $self) {
         $self->setVariables();
         $count = $self->app['spikadb']->findStoriesCount();
         $page = $request->get('page');
         if (empty($page)) {
             $page = 1;
         }
         $msg = $request->get('msg');
         if (!empty($msg)) {
             $self->setInfoAlert($self->language[$msg]);
         }
         $news = $self->app['spikadb']->findAllNews(($page - 1) * ADMIN_LISTCOUNT, ADMIN_LISTCOUNT);
         // convert timestamp to date
         for ($i = 0; $i < count($news); $i++) {
             $news[$i]['created'] = date("Y.m.d", $news[$i]['created']);
             $news[$i]['modified'] = date("Y.m.d", $news[$i]['modified']);
         }
         return $self->render('admin/newsList.twig', array('news' => $news, 'pager' => array('baseURL' => ROOT_URL . "/admin/news/list?page=", 'pageCount' => ceil($count / ADMIN_LISTCOUNT) - 1, 'page' => $page)));
     })->before($app['adminBeforeTokenChecker']);
     ///**************************************************
     //***************************************************
     $controllers->get('news/add', function (Request $request) use($app, $self) {
         $self->setVariables();
         if (!$self->checkPermission()) {
             return $app->redirect(ROOT_URL . '/admin/news/list?msg=messageNoPermission');
         }
         return $self->render('admin/newsForm.twig', array('mode' => 'new', 'formValues' => $self->getEmptyFormData()));
     })->before($app['adminBeforeTokenChecker']);
     //
     // create new logics
     //
     $controllers->post('news/add', function (Request $request) use($app, $self) {
         $self->setVariables();
         if (!$self->checkPermission()) {
             return $app->redirect(ROOT_URL . '/admin/news/list?msg=messageNoPermission');
         }
         $validationError = false;
         $formValues = $request->request->all();
         //validation
         if (empty($formValues['title']) || empty($formValues['content'])) {
             $self->setErrorAlert($self->language['messageValidationErrorRequired']);
             $validationError = true;
         }
         if (!$validationError) {
             $result = $self->app['spikadb']->createStory($formValues['title'], $formValues['content'], $self->loginedUser['_id'], $formValues['story_url']);
             return $app->redirect(ROOT_URL . '/admin/news/list?msg=messageNewsAdded');
         }
         return $self->render('admin/newsForm.twig', array('mode' => 'new', 'formValues' => $formValues));
     })->before($app['adminBeforeTokenChecker']);
     //
     // Detail logics
     //
     $controllers->get('news/view/{id}', function (Request $request, $id) use($app, $self) {
         $self->setVariables();
         $story = $self->app['spikadb']->findStoryById($id);
         return $self->render('admin/newsForm.twig', array('mode' => 'view', 'formValues' => $story));
     })->before($app['adminBeforeTokenChecker']);
     //
     // Edit logics
     //
     $controllers->get('news/edit/{id}', function (Request $request, $id) use($app, $self) {
         $self->setVariables();
         if (!$self->checkPermission()) {
             return $app->redirect(ROOT_URL . '/admin/news/list?msg=messageNoPermission');
         }
         $story = $self->app['spikadb']->findStoryById($id);
         if ($story['user_id'] != $self->loginedUser['_id'] && $self->loginedUser['_id'] != SUPPORT_USER_ID) {
             return $app->redirect(ROOT_URL . '/admin/news/list?msg=messageNoPermission');
         }
         return $self->render('admin/newsForm.twig', array('id' => $id, 'mode' => 'edit', 'formValues' => $story));
     })->before($app['adminBeforeTokenChecker']);
     $controllers->post('news/edit/{id}', function (Request $request, $id) use($app, $self) {
         $self->setVariables();
         $story = $self->app['spikadb']->findStoryById($id);
         if ($story['user_id'] != $self->loginedUser['_id'] && $self->loginedUser['_id'] != SUPPORT_USER_ID) {
             return $app->redirect(ROOT_URL . '/admin/news/list?msg=messageNoPermission');
         }
         $formValues = $request->request->all();
         $validationError = false;
         //validation
         if (empty($formValues['title']) || empty($formValues['content'])) {
             $self->setErrorAlert($self->language['messageValidationErrorRequired']);
             $validationError = true;
         }
         if (!$validationError) {
             $self->app['spikadb']->updateStory($id, $formValues['title'], $formValues['content'], $formValues['story_url']);
             return $app->redirect(ROOT_URL . '/admin/news/list?msg=messageNewsChanged');
         }
         return $self->render('admin/newsForm.twig', array('id' => $id, 'mode' => 'edit', 'formValues' => $story));
     })->before($app['adminBeforeTokenChecker']);
     //
     // Delete logics
     //
     $controllers->get('news/delete/{id}', function (Request $request, $id) use($app, $self) {
         $self->setVariables();
         if (!$self->checkPermission()) {
             return $app->redirect(ROOT_URL . '/admin/news/list?msg=messageNoPermission');
         }
         $story = $self->app['spikadb']->findStoryById($id);
         if ($story['user_id'] != $self->loginedUser['_id'] && $self->loginedUser['_id'] != SUPPORT_USER_ID) {
             return $app->redirect(ROOT_URL . '/admin/news/list?msg=messageNoPermission');
         }
         $story = $self->app['spikadb']->findStoryById($id);
         return $self->render('admin/newsDelete.twig', array('id' => $id, 'mode' => 'delete', 'formValues' => $story));
     })->before($app['adminBeforeTokenChecker']);
     $controllers->post('news/delete/{id}', function (Request $request, $id) use($app, $self) {
         $self->setVariables();
         if (!$self->checkPermission()) {
             return $app->redirect(ROOT_URL . '/admin/news/list?msg=messageNoPermission');
         }
         $story = $self->app['spikadb']->findStoryById($id);
         if ($story['user_id'] != $self->loginedUser['_id'] && $self->loginedUser['_id'] != SUPPORT_USER_ID) {
             return $app->redirect(ROOT_URL . '/admin/news/list?msg=messageNoPermission');
         }
         $formValues = $request->request->all();
         if (isset($formValues['submit_delete'])) {
             $self->app['spikadb']->deleteStory($id);
             return $app->redirect(ROOT_URL . '/admin/news/list?msg=messageStoryDeleted');
         } else {
             return $app->redirect(ROOT_URL . '/admin/news/list');
         }
     })->before($app['adminBeforeTokenChecker']);
     return $controllers;
 }