public function connect(Application $app) { global $beforeTokenCheker; $controllers = $app['controllers_factory']; $self = $this; // ToDo: Add token check $controllers->get('/filedownloader', function (Request $request) use($app, $self) { $fileID = $request->get('file'); $filePath = __DIR__ . '/../../../' . FileController::$fileDirName . "/" . basename($fileID); $app['logger']->addDebug($filePath); if (file_exists($filePath)) { $response = new Response(); $lastModified = new \DateTime(); $file = new \SplFileInfo($filePath); $lastModified = new \DateTime(); $lastModified->setTimestamp($file->getMTime()); $response->setLastModified($lastModified); if ($response->isNotModified($request)) { $response->prepare($request)->send(); return $response; } $response = $app->sendFile($filePath); $currentDate = new \DateTime(null, new \DateTimeZone('UTC')); $response->setDate($currentDate)->prepare($request)->send(); return $response; } else { return $self->returnErrorResponse("file doesn't exists."); } }); //})->before($app['beforeTokenChecker']); // ToDo: Add token check $controllers->post('/fileuploader', function (Request $request) use($app, $self) { $file = $request->files->get(FileController::$paramName); $fineName = \Spika\Utils::randString(20, 20) . time(); if (!is_writable(__DIR__ . '/../../../' . FileController::$fileDirName)) { return $self->returnErrorResponse(FileController::$fileDirName . " dir is not writable."); } $file->move(__DIR__ . '/../../../' . FileController::$fileDirName, $fineName); return $fineName; })->before($app['beforeApiGeneral']); //})->before($app['beforeTokenChecker']); return $controllers; }
public function saveThumb($file) { $uploadDirPath = __DIR__ . '/../../../../' . FileController::$fileDirName . '/'; $fileName = \Spika\Utils::randString(20, 20) . time(); // resize and save file $imagine = new Imagine(); $image = $imagine->open($file->getPathname()); $size = $image->getSize(); $targetSize = $size->getWidth(); if ($size->getHeight() < $size->getWidth()) { $targetSize = $size->getHeight(); } $originX = ($size->getWidth() - $targetSize) / 2; $originY = ($size->getHeight() - $targetSize) / 2; $image->crop(new Point($originX, $originY), new Box($targetSize, $targetSize))->resize(new Box(120, 120))->save($uploadDirPath . $fileName, array('format' => 'jpg')); return $fileName; }
public function doSpikaAuth($email, $password) { $emailQuery = urlencode('"' . $email . '"'); list($header, $result) = $this->sendRequest("GET", $this->couchDBURL . "/_design/app/_view/find_user_by_email?key=" . $emailQuery); $json = json_decode($result, true); if (empty($json['rows'][0]['value']['email'])) { $arr = array('message' => 'User not found!', 'error' => 'logout'); return json_encode($arr); } if ($json['rows'][0]['value']['password'] != $password) { $arr = array('message' => 'Wrong password!', 'error' => 'logout'); return json_encode($arr); } $token = \Spika\Utils::randString(40, 40); $json['rows'][0]['value']['token'] = $token; $json['rows'][0]['value']['token_timestamp'] = time(); $json['rows'][0]['value']['last_login'] = time(); $userJson = $json['rows'][0]['value']; $result = $this->saveUserToken(json_encode($userJson), $json['rows'][0]['value']['_id']); $filteredUserData = $this->filterUser($result); return json_encode($filteredUserData); }
public function addPassworResetRequest($toUserId) { $token = \Spika\Utils::randString(40, 40); $data = array('user_id' => $toUserId, 'created' => time(), 'token' => $token, 'valid' => 1); $this->logger->addDebug(print_r($data, true)); if ($this->DB->insert('password_change_request', $data)) { return $token; } else { return null; } }
public function connect(Application $app) { ExceptionHandler::register(false); $controllers = $app['controllers_factory']; $self = $this; // first screen $controllers->get('/installer', function (Request $request) use($app, $self) { $app['monolog']->addDebug("top"); $rootUrl = str_replace("/installer", "", $self->curPageURL()); return $app['twig']->render('installer/installerTop.twig', array('ROOT_URL' => $rootUrl)); }); // connect to DB $controllers->post('/installer/step1', function (Request $request) use($app, $self) { $app['monolog']->addDebug("step1"); $rootUrl = str_replace("/installer/step1", "", $self->curPageURL()); $host = $request->get('host'); $database = $request->get('database'); $userName = $request->get('username'); $password = $request->get('password'); $config = new \Doctrine\DBAL\Configuration(); $connectionParams = array('dbname' => $database, 'user' => $userName, 'password' => $password, 'host' => $host, 'driver' => 'pdo_mysql'); $app['session']->set('databaseConfiguration', $connectionParams); $conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config); try { $connectionResult = $conn->connect(); } catch (\PDOException $e) { $connectionResult = false; $app['monolog']->addDebug("Failed to connect DB"); } if ($connectionResult) { return $app['twig']->render('installer/installerStep1.twig', array('ROOT_URL' => $rootUrl, 'ConnectionSucceed' => $connectionResult)); } else { return $app['twig']->render('installer/installerTop.twig', array('ROOT_URL' => $rootUrl, 'ConnectionSucceed' => $connectionResult)); } }); // create database schema $controllers->post('/installer/step2', function (Request $request) use($app, $self) { $app['monolog']->addDebug("step2"); $rootUrl = str_replace("/installer/step2", "", $self->curPageURL()); $config = new \Doctrine\DBAL\Configuration(); $connectionParams = $app['session']->get('databaseConfiguration'); $conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config); try { $connectionResult = $conn->connect(); } catch (\PDOException $e) { $app->redirect('/installer'); } // read sql file $pathToSchemaFile = "../install/databaseschema.sql"; if (!file_exists("../install/databaseschema.sql")) { return $app['twig']->render('installer/installerError.twig', array('ROOT_URL' => $rootUrl)); } $schemacontent = file_get_contents($pathToSchemaFile); $queries = explode(";", $schemacontent); $conn->beginTransaction(); try { foreach ($queries as $query) { $query = trim($query); if (!empty($query)) { $conn->executeQuery($query); } } $conn->commit(); } catch (\Exception $e) { $app['monolog']->addDebug($e->getMessage()); $conn->rollback(); return $app['twig']->render('installer/installerError.twig', array('ROOT_URL' => $rootUrl)); } return $app['twig']->render('installer/installerStep2.twig', array('ROOT_URL' => $rootUrl, 'ConnectionSucceed' => $connectionResult)); }); // generate initial data $controllers->post('/installer/step3', function (Request $request) use($app, $self) { $app['monolog']->addDebug("step3"); $rootUrl = str_replace("/installer/step3", "", $self->curPageURL()); $localRootUrl = str_replace("/installer/step3", "", $self->curPageURLLocal()); $config = new \Doctrine\DBAL\Configuration(); $connectionParams = $app['session']->get('databaseConfiguration'); $conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config); try { $connectionResult = $conn->connect(); } catch (\PDOException $e) { $app['monolog']->addDebug("failed to connect DB" . var_dump($connectionParams)); $app['monolog']->addDebug($e->getMessage()); $app->redirect('/installer'); } $fileDir = __DIR__ . '/../../../../../' . FileController::$fileDirName; if (!is_writable($fileDir)) { $app['monolog']->addDebug("{$fileDir} is not writable."); return $app['twig']->render('installer/installerError.twig', array('ROOT_URL' => $rootUrl)); } $conn->beginTransaction(); // generate group categories $files = array(); $filesPath = __DIR__ . '/../../../../../install/resouces/categoryimages'; if ($handle = opendir($filesPath)) { while ($entry = readdir($handle)) { if (is_file($filesPath . "/" . $entry)) { if (preg_match("/png/", $entry)) { $files[] = $filesPath . "/" . $entry; } } } closedir($handle); } foreach ($files as $path) { // copy to file dir $pathinfo = pathinfo($path); $categoryName = $pathinfo['filename']; $imgbinary = @file_get_contents($path); $fileName = \Spika\Utils::randString(20, 20) . time(); $newFilePath = $fileDir . "/" . $fileName; copy($path, $newFilePath); // create data $data = array('title' => $categoryName, 'avatar_file_id' => $fileName, 'created' => time()); try { $conn->insert('group_category', $data); } catch (\Exception $e) { $app['monolog']->addDebug($e->getMessage()); $conn->rollback(); return $app['twig']->render('installer/installerError.twig', array('ROOT_URL' => $rootUrl)); } } // generate emoticons $files = array(); $filesPath = __DIR__ . '/../../../../../install/resouces/emoticons'; if ($handle = opendir($filesPath)) { while ($entry = readdir($handle)) { if (is_file($filesPath . "/" . $entry)) { if (preg_match("/png/", $entry)) { $files[] = $filesPath . "/" . $entry; } } } closedir($handle); } foreach ($files as $path) { // copy to file dir $pathinfo = pathinfo($path); $emoticonname = $pathinfo['filename']; $imgbinary = @file_get_contents($path); $fileName = \Spika\Utils::randString(20, 20) . time(); $newFilePath = $fileDir . "/" . $fileName; copy($path, $newFilePath); // create data $data = array('identifier' => $emoticonname, 'file_id' => $fileName, 'created' => time()); try { $conn->insert('emoticon', $data); } catch (\Exception $e) { $app['monolog']->addDebug($e->getMessage()); $conn->rollback(); return $app['twig']->render('installer/installerError.twig', array('ROOT_URL' => $rootUrl)); } } // create support user $password = '******'; $userData = array(); $userData['name'] = "Administrator"; $userData['email'] = "*****@*****.**"; $userData['password'] = md5($password); $userData['online_status'] = "online"; $userData['max_contact_count'] = 100; $userData['max_favorite_count'] = 100; $userData['birthday'] = 0; $userData['created'] = time(); $conn->insert('user', $userData); $conn->commit(); return $app['twig']->render('installer/installerStep3.twig', array('ROOT_URL' => $rootUrl, 'LOCAL_ROOT_URL' => $localRootUrl, 'ConnectionSucceed' => $connectionResult, 'DbParams' => $connectionParams, 'SupportUserId' => $conn->lastInsertId("_id"))); }); 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; }