#0 | Hybrid_Endpoint->authInit()
/var/www/html/app/library/Hybrid/Endpoint.php (117) <?php
/**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/**
* Hybrid_Endpoint class
*
* Provides a simple way to handle the OpenID and OAuth endpoint
*/
class Hybrid_Endpoint {
protected $request = null;
protected $initDone = false;
/**
* Process the current request
*
* @param array $request The current request parameters. Leave as null to default to use $_REQUEST.
*/
public function __construct($request = null) {
if (is_null($request)) {
// Fix a strange behavior when some provider call back ha endpoint
// with /index.php?hauth.done={provider}?{args}...
// >here we need to parse $_SERVER[QUERY_STRING]
$request = $_REQUEST;
if (isset($_SERVER["QUERY_STRING"]) && strrpos($_SERVER["QUERY_STRING"], '?')) {
$_SERVER["QUERY_STRING"] = str_replace("?", "&", $_SERVER["QUERY_STRING"]);
parse_str($_SERVER["QUERY_STRING"], $request);
}
}
// Setup request variable
$this->request = $request;
// If openid_policy requested, we return our policy document
if (isset($this->request["get"]) && $this->request["get"] == "openid_policy") {
$this->processOpenidPolicy();
}
// If openid_xrds requested, we return our XRDS document
if (isset($this->request["get"]) && $this->request["get"] == "openid_xrds") {
$this->processOpenidXRDS();
}
// If we get a hauth.start
if (isset($this->request["hauth_start"]) && $this->request["hauth_start"]) {
$this->processAuthStart();
}
// Else if hauth.done
elseif (isset($this->request["hauth_done"]) && $this->request["hauth_done"]) {
$this->processAuthDone();
}
// Else we advertise our XRDS document, something supposed to be done from the Realm URL page
else {
$this->processOpenidRealm();
}
}
/**
* Process the current request
*
* @param array $request The current request parameters. Leave as null to default to use $_REQUEST.
* @return Hybrid_Endpoint
*/
public static function process($request = null) {
// Trick for PHP 5.2, because it doesn't support late static binding
$class = function_exists('get_called_class') ? get_called_class() : __CLASS__;
new $class($request);
}
/**
* Process OpenID policy request
* @return void
*/
protected function processOpenidPolicy() {
$output = file_get_contents(dirname(__FILE__) . "/resources/openid_policy.html");
print $output;
die();
}
/**
* Process OpenID XRDS request
* @return void
*/
protected function processOpenidXRDS() {
header("Content-Type: application/xrds+xml");
$output = str_replace("{RETURN_TO_URL}", str_replace(
array("<", ">", "\"", "'", "&"), array("<", ">", """, "'", "&"), Hybrid_Auth::getCurrentUrl(false)
), file_get_contents(dirname(__FILE__) . "/resources/openid_xrds.xml"));
print $output;
die();
}
/**
* Process OpenID realm request
* @return void
*/
protected function processOpenidRealm() {
$output = str_replace("{X_XRDS_LOCATION}", htmlentities(Hybrid_Auth::getCurrentUrl(false), ENT_QUOTES, 'UTF-8')
. "?get=openid_xrds&v="
. Hybrid_Auth::$version, file_get_contents(dirname(__FILE__) . "/resources/openid_realm.html"));
print $output;
die();
}
/**
* Define: endpoint step 3
* @return void
* @throws Hybrid_Exception
*/
protected function processAuthStart() {
$this->authInit();
$provider_id = trim(strip_tags($this->request["hauth_start"]));
// check if page accessed directly
if (!Hybrid_Auth::storage()->get("hauth_session.$provider_id.hauth_endpoint")) {
Hybrid_Logger::error("Endpoint: hauth_endpoint parameter is not defined on hauth_start, halt login process!");
throw new Hybrid_Exception("You cannot access this page directly.");
}
// define:hybrid.endpoint.php step 2.
$hauth = Hybrid_Auth::setup($provider_id);
// if REQUESTed hauth_idprovider is wrong, session not created, etc.
if (!$hauth) {
Hybrid_Logger::error("Endpoint: Invalid parameter on hauth_start!");
throw new Hybrid_Exception("Invalid parameter! Please return to the login page and try again.");
}
try {
Hybrid_Logger::info("Endpoint: call adapter [{$provider_id}] loginBegin()");
$hauth->adapter->loginBegin();
} catch (Exception $e) {
Hybrid_Logger::error("Exception:" . $e->getMessage(), $e);
Hybrid_Error::setError($e->getMessage(), $e->getCode(), $e->getTraceAsString(), $e->getPrevious());
$hauth->returnToCallbackUrl();
}
die();
}
/**
* Define: endpoint step 3.1 and 3.2
* @return void
* @throws Hybrid_Exception
*/
protected function processAuthDone() {
$this->authInit();
$provider_id = trim(strip_tags($this->request["hauth_done"]));
$hauth = Hybrid_Auth::setup($provider_id);
if (!$hauth) {
Hybrid_Logger::error("Endpoint: Invalid parameter on hauth_done!");
$hauth->adapter->setUserUnconnected();
throw new Hybrid_Exception("Invalid parameter! Please return to the login page and try again.");
}
try {
Hybrid_Logger::info("Endpoint: call adapter [{$provider_id}] loginFinish() ");
$hauth->adapter->loginFinish();
} catch (Exception $e) {
Hybrid_Logger::error("Exception:" . $e->getMessage(), $e);
Hybrid_Error::setError($e->getMessage(), $e->getCode(), $e->getTraceAsString(), $e->getPrevious());
$hauth->adapter->setUserUnconnected();
}
Hybrid_Logger::info("Endpoint: job done. return to callback url.");
$hauth->returnToCallbackUrl();
die();
}
/**
* Initializes authentication
* @throws Hybrid_Exception
*/
protected function authInit() {
if (!$this->initDone) {
$this->initDone = true;
// Init Hybrid_Auth
try {
if (!class_exists("Hybrid_Storage", false)) {
require_once realpath(dirname(__FILE__)) . "/Storage.php";
}
if (!class_exists("Hybrid_Exception", false)) {
require_once realpath(dirname(__FILE__)) . "/Exception.php";
}
if (!class_exists("Hybrid_Logger", false)) {
require_once realpath(dirname(__FILE__)) . "/Logger.php";
}
$storage = new Hybrid_Storage();
// Check if Hybrid_Auth session already exist
if (!$storage->config("CONFIG")) {
throw new Hybrid_Exception("You cannot access this page directly.");
}
Hybrid_Auth::initialize($storage->config("CONFIG"));
} catch (Exception $e) {
Hybrid_Logger::error("Endpoint: Error while trying to init Hybrid_Auth: " . $e->getMessage());
throw new Hybrid_Exception( "Endpoint: Error while trying to init Hybrid_Auth: " . $e->getMessage(), $e->getCode(), $e );
}
}
}
}
|
#1 | Hybrid_Endpoint->processAuthStart()
/var/www/html/app/library/Hybrid/Endpoint.php (51) <?php
/**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/**
* Hybrid_Endpoint class
*
* Provides a simple way to handle the OpenID and OAuth endpoint
*/
class Hybrid_Endpoint {
protected $request = null;
protected $initDone = false;
/**
* Process the current request
*
* @param array $request The current request parameters. Leave as null to default to use $_REQUEST.
*/
public function __construct($request = null) {
if (is_null($request)) {
// Fix a strange behavior when some provider call back ha endpoint
// with /index.php?hauth.done={provider}?{args}...
// >here we need to parse $_SERVER[QUERY_STRING]
$request = $_REQUEST;
if (isset($_SERVER["QUERY_STRING"]) && strrpos($_SERVER["QUERY_STRING"], '?')) {
$_SERVER["QUERY_STRING"] = str_replace("?", "&", $_SERVER["QUERY_STRING"]);
parse_str($_SERVER["QUERY_STRING"], $request);
}
}
// Setup request variable
$this->request = $request;
// If openid_policy requested, we return our policy document
if (isset($this->request["get"]) && $this->request["get"] == "openid_policy") {
$this->processOpenidPolicy();
}
// If openid_xrds requested, we return our XRDS document
if (isset($this->request["get"]) && $this->request["get"] == "openid_xrds") {
$this->processOpenidXRDS();
}
// If we get a hauth.start
if (isset($this->request["hauth_start"]) && $this->request["hauth_start"]) {
$this->processAuthStart();
}
// Else if hauth.done
elseif (isset($this->request["hauth_done"]) && $this->request["hauth_done"]) {
$this->processAuthDone();
}
// Else we advertise our XRDS document, something supposed to be done from the Realm URL page
else {
$this->processOpenidRealm();
}
}
/**
* Process the current request
*
* @param array $request The current request parameters. Leave as null to default to use $_REQUEST.
* @return Hybrid_Endpoint
*/
public static function process($request = null) {
// Trick for PHP 5.2, because it doesn't support late static binding
$class = function_exists('get_called_class') ? get_called_class() : __CLASS__;
new $class($request);
}
/**
* Process OpenID policy request
* @return void
*/
protected function processOpenidPolicy() {
$output = file_get_contents(dirname(__FILE__) . "/resources/openid_policy.html");
print $output;
die();
}
/**
* Process OpenID XRDS request
* @return void
*/
protected function processOpenidXRDS() {
header("Content-Type: application/xrds+xml");
$output = str_replace("{RETURN_TO_URL}", str_replace(
array("<", ">", "\"", "'", "&"), array("<", ">", """, "'", "&"), Hybrid_Auth::getCurrentUrl(false)
), file_get_contents(dirname(__FILE__) . "/resources/openid_xrds.xml"));
print $output;
die();
}
/**
* Process OpenID realm request
* @return void
*/
protected function processOpenidRealm() {
$output = str_replace("{X_XRDS_LOCATION}", htmlentities(Hybrid_Auth::getCurrentUrl(false), ENT_QUOTES, 'UTF-8')
. "?get=openid_xrds&v="
. Hybrid_Auth::$version, file_get_contents(dirname(__FILE__) . "/resources/openid_realm.html"));
print $output;
die();
}
/**
* Define: endpoint step 3
* @return void
* @throws Hybrid_Exception
*/
protected function processAuthStart() {
$this->authInit();
$provider_id = trim(strip_tags($this->request["hauth_start"]));
// check if page accessed directly
if (!Hybrid_Auth::storage()->get("hauth_session.$provider_id.hauth_endpoint")) {
Hybrid_Logger::error("Endpoint: hauth_endpoint parameter is not defined on hauth_start, halt login process!");
throw new Hybrid_Exception("You cannot access this page directly.");
}
// define:hybrid.endpoint.php step 2.
$hauth = Hybrid_Auth::setup($provider_id);
// if REQUESTed hauth_idprovider is wrong, session not created, etc.
if (!$hauth) {
Hybrid_Logger::error("Endpoint: Invalid parameter on hauth_start!");
throw new Hybrid_Exception("Invalid parameter! Please return to the login page and try again.");
}
try {
Hybrid_Logger::info("Endpoint: call adapter [{$provider_id}] loginBegin()");
$hauth->adapter->loginBegin();
} catch (Exception $e) {
Hybrid_Logger::error("Exception:" . $e->getMessage(), $e);
Hybrid_Error::setError($e->getMessage(), $e->getCode(), $e->getTraceAsString(), $e->getPrevious());
$hauth->returnToCallbackUrl();
}
die();
}
/**
* Define: endpoint step 3.1 and 3.2
* @return void
* @throws Hybrid_Exception
*/
protected function processAuthDone() {
$this->authInit();
$provider_id = trim(strip_tags($this->request["hauth_done"]));
$hauth = Hybrid_Auth::setup($provider_id);
if (!$hauth) {
Hybrid_Logger::error("Endpoint: Invalid parameter on hauth_done!");
$hauth->adapter->setUserUnconnected();
throw new Hybrid_Exception("Invalid parameter! Please return to the login page and try again.");
}
try {
Hybrid_Logger::info("Endpoint: call adapter [{$provider_id}] loginFinish() ");
$hauth->adapter->loginFinish();
} catch (Exception $e) {
Hybrid_Logger::error("Exception:" . $e->getMessage(), $e);
Hybrid_Error::setError($e->getMessage(), $e->getCode(), $e->getTraceAsString(), $e->getPrevious());
$hauth->adapter->setUserUnconnected();
}
Hybrid_Logger::info("Endpoint: job done. return to callback url.");
$hauth->returnToCallbackUrl();
die();
}
/**
* Initializes authentication
* @throws Hybrid_Exception
*/
protected function authInit() {
if (!$this->initDone) {
$this->initDone = true;
// Init Hybrid_Auth
try {
if (!class_exists("Hybrid_Storage", false)) {
require_once realpath(dirname(__FILE__)) . "/Storage.php";
}
if (!class_exists("Hybrid_Exception", false)) {
require_once realpath(dirname(__FILE__)) . "/Exception.php";
}
if (!class_exists("Hybrid_Logger", false)) {
require_once realpath(dirname(__FILE__)) . "/Logger.php";
}
$storage = new Hybrid_Storage();
// Check if Hybrid_Auth session already exist
if (!$storage->config("CONFIG")) {
throw new Hybrid_Exception("You cannot access this page directly.");
}
Hybrid_Auth::initialize($storage->config("CONFIG"));
} catch (Exception $e) {
Hybrid_Logger::error("Endpoint: Error while trying to init Hybrid_Auth: " . $e->getMessage());
throw new Hybrid_Exception( "Endpoint: Error while trying to init Hybrid_Auth: " . $e->getMessage(), $e->getCode(), $e );
}
}
}
}
|
#2 | Hybrid_Endpoint->__construct()
/var/www/html/app/frontend/controllers/UsersController.php (523) <?php
namespace Med\Frontend\Controllers;
error_reporting(E_ALL);
ini_set('display_errors', 1);
use \Phalcon\Validation\Validator\PresenceOf,
\Phalcon\Validation\Validator\Email;
use Med\Frontend\Models\Users;
use Med\Frontend\Models\Invoices;
use Med\Frontend\Models\ServiceTypes;
class UsersController extends ControllerBase {
private $Hybrid;
private $paymaster;
private $log;
public function initialize() {
$this->view->disableLevel(\Phalcon\Mvc\View::LEVEL_MAIN_LAYOUT);
//$this->view->no_script = 1;
$this->Hybrid = $this->getDi()->getShared('Hybrid');
$this->paymaster = $this->getDi()->getShared('paymaster');
$this->logger = new \Phalcon\Logger\Adapter\File(dirname(dirname(__DIR__)).'/logs/payments.log');
#$this->flash->notice(__DIR__);
if(in_array($this->request->getClientAddress(), ['77.122.220.193'])) {
$this->view->show_btn = true;
} else {
$this->view->show_btn = false;
}
}
/**
* Check user email
*/
public function ajaxCheckEmailAction() {
$res = 'true';
$this->setJsonResponse();
$email = $this->request->get('email', 'email', '');
$validation = new \Phalcon\Validation();
$validation->add('email', new PresenceOf())
->add('email', new Email());
$errors = $validation->validate(array('email' => $email));
if (!count($errors)) {
try {
$ui = Users::findFirst(array('conditions' => 'LOWER(email) = ?1'/* . ($this->identity ? ' AND id <> ' . $this->identity->id : '') */,
'bind' => array(1 => mb_strtolower($email, 'UTF-8'))));
if (!empty($ui)) {
$res = 'false';
}
} catch (\Phalcon\Exception $exc) {
}
}
echo $res;
exit();
}
public function ajaxLoginAction() {
$this->setJsonResponse();
if ($this->identity) {
return array('q' => 'ok');
exit();
}
$res = array('q' => 'err', 'errs' => array());
$credentials = array(
'email' => $this->request->getPost('email', 'string', ''),
'password' => $this->request->getPost('password', 'string', ''),
'remember' => $this->request->getPost('remember', 'int', 0),
'role' => false
);
try {
$this->auth->checkUser($credentials);
$user = $this->auth->getUser();
$res['q'] = 'ok';
} catch (\Phalcon\Exception $exception) {
$res['errs'][] = $exception->getMessage();
}
return $res;
}
/**
* Ajax signup submit
* @return array
*/
public function ajaxSignupAction() {
$this->setJsonResponse();
$res = array('q' => 'err', 'errs' => array());
$birthday_day = $this->request->getPost('birthday_day', 'int', 0);
$birthday_month = $this->request->getPost('birthday_month', 'int', 0);
$birthday_year = $this->request->getPost('birthday_year', 'int', 0);
$password = $this->request->getPost('password', 'string', '');
try {
$user = new Users();
$user->first_name = $this->request->getPost('first_name', 'string', '');
$user->last_name = $this->request->getPost('last_name', 'string', '');
$user->middle_name = $this->request->getPost('middle_name', 'string', '');
$user->name = $user->first_name . ' ' . $user->last_name;
$user->sex = $this->request->getPost('sex', 'int', 0);
$user->email = $this->request->getPost('email', 'string', '');
$user->role = 1;
$user->created_at = date('Y-m-d H:i:s');
$user->birth = $birthday_year . '-' . $birthday_month . '-' . $birthday_day;
$user->password = $this->security->hash($password);
//save
if (!$user->save()) {
foreach ($user->getMessages() as $message) {
throw new \Phalcon\Exception($message->getMessage());
}
}
$res['q'] = 'ok';
} catch (\Phalcon\Exception $exception) {
if ($exception->getMessage()) {
$res['errs'][] = $exception->getMessage();
}
}
return $res;
}
/**
* Ajax восстановление пароля
* @return array
*/
public function ajaxForgotAction() {
$this->setJsonResponse();
$res = array('q' => 'err', 'errs' => array());
$email = $this->request->getPost('email', 'string', '');
try {
$user = Users::findFirst(array(
"conditions" => "email = :email:",
"bind" => array('email' => $email)
));
if (empty($user)) {
throw new \Phalcon\Exception('Пользователя с данным email не существует');
}
$password = substr(md5(time() . rand(1000, 9999)), 2, 8);
$user->password = $this->security->hash($password);
$user->updated_at = date('Y-m-d H:i:s');
//save
if (!$user->save()) {
foreach ($user->getMessages() as $message) {
throw new \Phalcon\Exception($message->getMessage());
}
}
//send email to user
$email_text = "
<p>Уважаемый(ая) пользователь.</p>
<p>Вы запросили восстановление на сайте Medintercom.ru</p>
<p>Ваш новый пароль для входа на сайт: <b>[password]</b></p>
<p>Это письмо отправлено роботом, не отвечайте на него.</p>
";
$vars = array('[password]' => $password);
if ($this->email->send($user->email, $user->name, 'Восстановление пароля на сайте Medintercom.ru', $email_text, $vars)) {
$res['email'] = 'ok';
}
$res['q'] = 'ok';
} catch (\Phalcon\Exception $exception) {
if ($exception->getMessage()) {
$res['errs'][] = $exception->getMessage();
}
}
return $res;
}
public function loginAction() {
if ($this->userId) {
return $this->response->redirect()->send();
}
}
public function logoutAction() {
if ($this->acl->isAuth()) {
$this->auth->remove();
}
return $this->response->redirect()->send();
}
public function registrationAction() {
if ($this->userId) {
return $this->response->redirect()->send();
}
$this->view->list_day = range(1, 31);
$this->view->list_month = getMontsList();
$this->view->list_years = range(1940, 2010);
}
public function restoreAction() {
if ($this->userId) {
return $this->response->redirect()->send();
}
}
public function profileAction() {
if (!$this->userId) {
return $this->response->redirect()->send();
}
$this->view->statuses = Invoices::getStatuses();
$this->view->invoices_list = Invoices::getListByUserId($this->userId, 'date DESC')->toArray();
#$ServiceTypesList = ServiceTypes::find(array('order' => 'name ASC'))->toArray();
#$this->view->service_types = make_assoc_array($ServiceTypesList, 'id');
$this->view->forum_themes = \Med\Frontend\Models\ForumThemes::query()
->columns('id, name')
->where('active = "Y"')
->orderBy('sort DESC')
->execute();
$user_data = $this->auth->getUser();
$topic_array = [];
$topic_db_array = \Med\Frontend\Models\ForumTopics::query()
->columns('id')
->where('user_relation = :idsx:', ['idsx' => $user_data->id])
->execute();
foreach($topic_db_array as $tp) {
$topic_array[] = $tp->id;
}
$this->view->responses_from_doctors = $this->modelsManager->createBuilder()
->columns("Med\Frontend\Models\ForumMessages.id,
Med\Frontend\Models\ForumMessages.text,
Med\Frontend\Models\ForumMessages.date_create,
Med\Frontend\Models\ForumMessages.user_relation,
Med\Frontend\Models\ForumMessages.topic_relation,
Med\Frontend\Models\ForumTopics.name AS user_treatment,
Med\Frontend\Models\ForumTopics.translit AS user_treatment_tranlit,
Med\Frontend\Models\ForumTopics.id AS user_treatment_id,
Med\Frontend\Models\Users.id AS user_id,
Med\Frontend\Models\Users.name AS user_name,
Med\Frontend\Models\Users.photo AS user_photo,
Med\Frontend\Models\Users.email AS user_email,
Med\Frontend\Models\Users.is_doctor,
Med\Frontend\Models\Users.doctor_spec")
->from("Med\Frontend\Models\ForumMessages")
->inWhere('Med\Frontend\Models\ForumMessages.topic_relation', $topic_array)
->andWhere("Med\Frontend\Models\Users.is_doctor = 1")
->andWhere('Med\Frontend\Models\ForumMessages.active = "Y"')
->andWhere('Med\Frontend\Models\Users.id != :idm:', ['idm' => $user_data->id])
->leftJoin('Med\Frontend\Models\Users', 'Med\Frontend\Models\Users.id = Med\Frontend\Models\ForumMessages.user_relation')
->leftJoin('Med\Frontend\Models\ForumTopics', 'Med\Frontend\Models\ForumMessages.topic_relation = Med\Frontend\Models\ForumTopics.id')
->orderBy('Med\Frontend\Models\ForumMessages.date_create ASC')
#->groupBy('Med\Frontend\Models\ForumMessages.text')
->getQuery()
->execute();
$this->view->responses_from_users = $this->modelsManager->createBuilder()
->columns("Med\Frontend\Models\ForumMessages.id,
Med\Frontend\Models\ForumMessages.text,
Med\Frontend\Models\ForumMessages.date_create,
Med\Frontend\Models\ForumMessages.user_relation,
Med\Frontend\Models\ForumMessages.topic_relation,
Med\Frontend\Models\ForumTopics.name AS user_treatment,
Med\Frontend\Models\ForumTopics.translit AS user_treatment_tranlit,
Med\Frontend\Models\ForumTopics.id AS user_treatment_id,
Med\Frontend\Models\Users.id AS user_id,
Med\Frontend\Models\Users.name AS user_name,
Med\Frontend\Models\Users.photo AS user_photo,
Med\Frontend\Models\Users.email AS user_email,
Med\Frontend\Models\Users.is_doctor,
Med\Frontend\Models\Users.doctor_spec")
->from("Med\Frontend\Models\ForumMessages")
->inWhere('Med\Frontend\Models\ForumMessages.topic_relation', $topic_array)
->andWhere("Med\Frontend\Models\Users.is_doctor = 0")
->andWhere('Med\Frontend\Models\ForumMessages.active = "Y"')
->andWhere('Med\Frontend\Models\Users.id != :idm:', ['idm' => $user_data->id])
->leftJoin('Med\Frontend\Models\Users', 'Med\Frontend\Models\Users.id = Med\Frontend\Models\ForumMessages.user_relation')
->leftJoin('Med\Frontend\Models\ForumTopics', 'Med\Frontend\Models\ForumMessages.topic_relation = Med\Frontend\Models\ForumTopics.id')
->orderBy('Med\Frontend\Models\ForumMessages.date_create ASC')
#->groupBy('Med\Frontend\Models\ForumMessages.text')
->getQuery()
->execute();
}
public function servicesAction() {
if (!$this->userId) {
return $this->response->redirect()->send();
}
$this->view->statuses = Invoices::getStatuses();
$this->view->invoices_list = Invoices::getListByUserId($this->userId, 'date DESC')->toArray();
}
public function lkAction() {
if (!$this->userId) {
return $this->response->redirect()->send();
}
}
public function editAction() {
if (!$this->userId) {
return $this->response->redirect()->send();
}
$this->view->list_day = range(1, 31);
$this->view->list_month = getMontsList();
$this->view->list_years = range(1940, 2010);
}
public function passwordAction() {
if (!$this->userId) {
return $this->response->redirect()->send();
}
}
/**
* Ajax редактирование кабинета пользователя
*/
public function ajaxEditCabinetSettingsAction() {
$this->setJsonResponse();
$res = array('q' => 'err', 'errs' => array());
if (!$this->userId) {
return $res;
}
$act = $this->request->get('act', 'string', '');
try {
switch ($act) {
case 'contact_information':
$birthday = $this->request->getPost('birthday', 'string', '');
//$birthday_month = $this->request->getPost('birthday_month', 'int', 0);
//$birthday_year = $this->request->getPost('birthday_year', 'int', 0);
$this->identity->first_name = $this->request->getPost('first_name', 'string', '');
$this->identity->last_name = $this->request->getPost('last_name', 'string', '');
$this->identity->middle_name = $this->request->getPost('middle_name', 'string', '');
$this->identity->name = $this->identity->first_name . ' ' . $this->identity->last_name;
$this->identity->sex = $this->request->getPost('sex', 'int', 0);
$this->identity->email = $this->request->getPost('email', 'string', '');
$this->identity->address = $this->request->getPost('address', 'string', '');
$this->identity->profession = $this->request->getPost('profession', 'string', '');
$this->identity->phone = $this->request->getPost('phone', 'string', '');
$this->identity->phone2 = $this->request->getPost('phone2', 'string', '');
$this->identity->birth = date('Y-m-d', strtotime($birthday));
break;
case 'change_password':
$current_password = $this->request->get('current_password', 'string', '');
$new_password = $this->request->get('new_password', 'string', '');
$new_confirm = $this->request->get('new_confirm', 'string', '');
if (!$this->security->checkHash($current_password, $this->identity->password)) {
throw new \Phalcon\Exception('Введен не верный текущий пароль');
}
if (empty($new_password) || mb_strlen($new_password) < 5) {
throw new \Phalcon\Exception('Введите новый пароль');
}
if ($new_password != $new_confirm) {
throw new \Phalcon\Exception('Введенные пароли не совпадают');
}
$this->identity->password = $this->security->hash($new_password);
break;
}
if (!$this->identity->save()) {
foreach ($this->identity->getMessages() as $message) {
throw new \Phalcon\Exception($message->getMessage());
}
}
/*
//авторизуем пользователя
$credentials = array(
'email' => $ui->email,
'password' => $password2,
//'remember' => 1
);
try
{
$this->auth->check($credentials);
$res['q'] = 'ok';
}
catch (\Phalcon\Exception $exception)
{
throw new \Phalcon\Exception($exception->getMessage());
} */
$res['q'] = 'ok';
} catch (\Phalcon\Exception $exc) {
if ($exc->getMessage()) {
$res['errors'][] = $exc->getMessage();
}
}
return $res;
}
public function uploadAction() {
$this->setJsonResponse();
if (empty($_FILES) || $_FILES['file']['error']) {
$res = array("OK" => 0, 'info' => 'Failed to move uploaded file.');
return $res;
}
$chunk = $this->request->get('chunk', 'int', 0);
$chunks = $this->request->get('chunks', 'int', 0);
$fileName = $this->request->get('name', 'string', '');
$fileName = $fileName ? $fileName : $_FILES["file"]["name"];
//create tmp dir
$user_dir = 'files/users/' . $this->userId;
$dir = PUB_PATH . $user_dir;
if (!file_exists($dir)) {
@mkdir($dir);
}
$pathinfo = pathinfo($fileName);
$filename = $pathinfo['filename'];
$ext = isset($pathinfo['extension']) ? $pathinfo['extension'] : '';
$allowedExtensions = array('jpg', 'jpeg', 'gif', 'png');
if ($allowedExtensions && !in_array(strtolower($ext), $allowedExtensions)) {
$res = array("OK" => 0, 'info' => 'Failed extension');
return $res;
}
$filePath = $dir . '/' . $fileName;
$filename = $fileName;
$k = 1;
while (file_exists($dir . '/' . $filename)) {
$filename = $k . $fileName;
$k ++;
}
$fileName = $filename;
$filePath = $dir . '/' . $fileName;
// Open temp file
$out = @fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
if ($out) {
// Read binary input stream and append it to temp file
$in = @fopen($_FILES['file']['tmp_name'], "rb");
if ($in) {
while ($buff = fread($in, 4096)) {
fwrite($out, $buff);
}
} else {
$res = array("OK" => 0, 'info' => 'Failed to open input stream.');
return $res;
}
@fclose($in);
@fclose($out);
@unlink($_FILES['file']['tmp_name']);
} else {
$res = array("OK" => 0, 'info' => 'Failed to open output stream.');
return $res;
}
// Check if file has been uploaded
if (!$chunks || $chunk == $chunks - 1) {
// Strip the temp .part suffix off
rename("{$filePath}.part", $filePath);
}
$this->identity->photo = $user_dir . '/' . $fileName;
$this->identity->save();
$res = array("OK" => 1, 'info' => 'Upload successful.', 'filename' => $fileName, 'filepath' => $user_dir);
return $res;
}
/**
* authorize or register user if it doesn't exist
* @return type
*/
public function hybridauthAction() {
$provider = $this->dispatcher->getParam('provider');
if (empty($provider)) {
return $this->response->redirect('/');
}
if ($provider == 'socialauth') {
require_once dirname($_SERVER['DOCUMENT_ROOT']) . "/app/library/Hybrid/Endpoint.php";
require_once dirname($_SERVER['DOCUMENT_ROOT']) . '/app/library/Hybrid/Auth.php';
$endpoint = new \Hybrid_Endpoint();
$endpoint->process();
}
try {
switch ($provider) {
case 'facebook':
$adapter = $this->Hybrid->authenticate("Facebook");
break;
case 'google':
$adapter = $this->Hybrid->authenticate("Google");
break;
case 'vkontakte':
$adapter = $this->Hybrid->authenticate("Vkontakte");
break;
}
#print_r($adapter);
#return;
if (!empty($adapter)) {
$user_profile = $adapter->getUserProfile();
// Проверяем пользователя по базе
$user = Users::findFirst([
'conditions' => 'email = :email:',
'bind' => [
'email' => $user_profile->email
]
]);
$date = new \Phalcon\Db\RawValue('now()');
// если юзер есть
if ($user) {
// конектим его и редирект, если нужно
$info_arr = json_decode($user->info, true);
$info_arr = array_merge(['status' => "Пользователь зарегистрированный через социальную сеть $provider"]);
$this->session->set('auth-identity', array(
'id' => $user->id,
'name' => $user_profile->firstName . " " . $user_profile->lastName,
'email' => $user_profile->email,
'role' => false
));
$this->flash->success('Вы успешно авторизованы');
return $this->response->redirect('/profile');
} else {
// регистрация пользователя
$random_password = $this->randomString(8);
$user = new Users();
$user->email = $user_profile->email;
$user->password = $this->security->hash($random_password);
$user->first_name = $user_profile->firstName;
$user->last_name = $user_profile->lastName;
$user->created_at = $date;
$user->role = 1;
$user->birth = date('Y-m-d');
if ($user_profile->photoURL) {
$user->photo = $user_profile->photoURL;
}
if ($user_profile->phone) {
$user->phone = $user_profile->phone;
}
if ($user->create()) {
// отправка письма о сгенерированном пароле
$this->email->send($user_profile->email, $user->name, 'Registration on dts-auto.com', '<h3>Спасибо за регистрацию на нашём сервисе объявлений.</h3> Сгенерированный пароль = <b>' . $random_password . "</b>");
$this->flash->notice('На вашу почту ' . $user_profile->email . ' отправлен сгенерированный пароль, в случае если Вы захотить авторизоваться без социальных сетей.');
$this->session->set('auth-identity', array(
'id' => $user->id,
'name' => $user_profile->firstName . " " . $user_profile->lastName,
'email' => $user_profile->email,
'role' => false
));
return $this->response->redirect('/profile', true, 301);
} else {
foreach ($user->getMessages() as $message)
$this->flash->error($message);
return;
}
}
} else {
$this->flash->error($e->getMessage());
#$this->Hybrid->logoutAllProviders();
return $this->response->redirect('/users/login');
}
} catch (\Exception $e) {
// Display the recived error,
// to know more please refer to Exceptions handling section on the userguide
switch ($e->getCode()) {
case 0 : $this->flash->error("Unspecified error.");
break;
case 1 : $this->flash->error("Hybriauth configuration error.");
break;
case 2 : $this->flash->error("Provider not properly configured.");
break;
case 3 : $this->flash->error("Unknown or disabled provider.");
break;
case 4 : $this->flash->error("Missing provider application credentials.");
break;
case 5 : $this->flash->error("Authentification failed. "
. "The user has canceled the authentication or the provider refused the connection.");
break;
case 6 : $this->flash->error("User profile request failed. Most likely the user is not connected "
. "to the provider and he should authenticate again.");
$this->Hybrid->logoutAllProviders();
break;
case 7 : $this->flash->error("User not connected to the provider.");
$this->Hybrid->logout();
break;
case 8 : $this->flash->error("Provider does not support this feature.");
break;
}
$this->flash->error($e->getMessage());
#$this->Hybrid->logoutAllProviders();
#return $this->response->redirect('/users/login');
}
#$this->Hybrid->logoutAllProviders();
return $this->response->redirect('/users/login');
}
/**
* Редирект на страницу оплаты
* @return type
*/
public function startPaymentAction() {
$id = $this->dispatcher->getParam('id', 'int');
if(empty($id)) {
$this->flash->error('Некорректный идентификатор услуги');
return $this->response->redirect('/profile');
}
$user = $this->session->get('auth-identity');
// check service
$check_service = \Med\Frontend\Models\Invoices::findFirst(['id = :mid: AND user_id = :muser_id:',
'bind' => ['mid' => $id, 'muser_id' => $user['id']]]);
if($check_service == null) {
$this->flash->error('Не удалось найти услугу пользователя в БД');
return $this->response->redirect('/profile');
}
if($check_service->status == 2) {
$this->flash->error('Платёж уже оплачен');
return $this->response->redirect('/profile');
}
$check_payment_stats = \Med\Frontend\Models\Payments::findFirstByService_id($id);
$fields = array(
'LMI_MERCHANT_ID' => $this->paymaster->merchantId,
'LMI_PAYMENT_NO' => $id,
'LMI_PAYMENT_AMOUNT' => $check_service->cost,
'LMI_CURRENCY' => 'RUB',
'LMI_PAYMENT_DESC' => 'Оплата услуги - '.$check_service->name,
#'LMI_SUCCESS_URL' => 'https://medintercom.ru/payment/success',
#'LMI_FAILURE_URL' => 'https://medintercom.ru/payment/failure',
'SIGN' => $this->paymaster->getSign($id),
);
$payment_stats = new \Med\Frontend\Models\Payments();
$payment_stats->description = 'Старт начала оплаты услуги';
$payment_stats->service = $id;
$payment_stats->service_id = $check_payment_stats->serviceType_id;
$payment_stats->status = 'В процессе оплаты';
$payment_stats->sum = $check_service->cost;
$payment_stats->user_id = $user['id'];
$payment_stats->user_email = $user['email'];
$payment_stats->user_name = $user['name'];
if($payment_stats->create()) {
// redirect to paymaster
return $this->response->redirect('https://paymaster.ru/Payment/Init?'.http_build_query($fields));
} else {
$this->flash->error('Не удалось создать запись о начале оплаты в БД');
foreach($payment_stats->getMessages() as $message) {
$this->flash->error($message);
}
return $this->response->redirect('/profile');
}
}
/**
* Обработчик оплаты
* @return type
*/
public function paymasterNotificationAction() {
$order_id = $this->paymaster->getOrderId();
$amount = $this->paymaster->getAmount();
$this->logger->notice('Старт верификации оплаты. $order = '.$order_id.' $amount = '.$amount);
if ($order_id == null) {
$this->logger->error('Пустой идентификатор номера оплаты');
return $this->response->setJsonContent(['code' => 102, 'status' => 'Пустой идентификатор номера оплаты']);
}
$service_payment = \Med\Frontend\Models\Invoices::findFirst([
'conditions' => 'id = :id:',
'bind' => ['id' => $order_id]]);
if($service_payment == false) {
$this->logger->error('Не удалось найти услугу пользователя в БД. '.$order_id);
return $this->response->setJsonContent(['code' => 103, 'status' => 'Не удалось найти услугу пользователя в БД']);
}
$verify = $this->paymaster->verify();
if ($verify) {
if ($amount != $service_payment->cost || $amount <= 0) {
$this->logger->error('Сумма оплаты не равна сумме выставленного счёта. $amount '.$amount.' $service_payment->cost = '.$service_payment->cost);
return $this->response->setJsonContent(['code' => 104, 'status' => 'Оплаченная услуга '.$amount.' не равна стоимости услуги в БД '.$service_payment->cost]);
}
// update payment status
$service_payment->status = 2;
if($service_payment->update()) {
// create log
$payment_stats = new \Med\Frontend\Models\Payments();
$payment_stats->status = "Оплачено";
$payment_stats->service = $order_id;
$payment_stats->service_id = $service_payment->serviceType_id;
$payment_stats->description = 'Оплата услуги';
$payment_stats->sum = $service_payment->cost;
if(!$payment_stats->create()) {
foreach($payment_stats->getMessages() as $message) {
$this->log->error($message);
}
}
return $this->response->setJsonContent(['code' => 200, 'status' => 'Состояние оплаты успешно обновлено']);
} else {
$this->logger->error('Не удалось обновить запись о платеже в БД');
foreach($service_payment->getMessages() as $message) {
$this->logger->error($message);
}
}
} else {
$this->logger->error('Верификация завершилась не удачей');
return $this->response->setJsonContent(['code' => 366, 'status' => 'Ошибка верификации. ']);
}
return $this->response->setJsonContent(['code' => 335, 'status' => 'Возникла непредвиденная ошибка']);
}
/**
* Уведомление об успешной оплате
* @return type
*/
public function successPaymentAction() {
$this->flash->success('Платёж успешно оплачен');
return $this->response->redirect('/profile');
}
/**
* Уведомление об ошибке оплаты
* @return type
*/
public function unsuccessPaymentAction() {
$this->flash->error('Оплата платежа завершилась ошибкой');
return $this->response->redirect('/profile');
}
/**
*
* @return type
*/
public function createMessageAction() {
if(!$this->userId) {
return $this->response->setJsonContent(['code' => 401, 'status' => 'Сессия пользователя истекла. Требуется авторизация.']);
}
$theme_id = $this->request->getPost('theme_id', 'int');
$title = $this->request->getPost('title', 'string');
$message = $this->request->getPost('message', 'string');
if(!$theme_id) {
return $this->response->setJsonContent(['code' => 455, 'status' => 'Идентификатор раздела отсутствует.']);
}
if(strlen($title) < 2) {
return $this->response->setJsonContent(['code' => 460, 'status' => 'Заголовок отсутствует.']);
}
if(strlen($message) < 2) {
return $this->response->setJsonContent(['code' => 465, 'status' => 'Сообщение отсутствует.']);
}
$this->db->begin();
//$this->db->rollback();
//$this->db->commit();
$new_theme_conversation = new \Med\Frontend\Models\ForumTopics();
$new_theme_conversation->name = $title;
$new_theme_conversation->browser = $this->request->getUserAgent();
$new_theme_conversation->ip = $this->request->getClientAddress();
$new_theme_conversation->category = $theme_id;
$new_theme_conversation->date_create = new \Phalcon\Db\RawValue('now()');
$new_theme_conversation->description = "";
$new_theme_conversation->translit = ruslink($title);
$new_theme_conversation->user_relation = $this->userId;
if($new_theme_conversation->create() == false) {
$string = "";
foreach($new_theme_conversation->getMessages() as $message) {
$string .= $message."<br/>";
}
$this->db->rollback();
return $this->response->setJsonContent(['code' => 321, 'status' => $string]);
}
$new_message_conversation = new \Med\Frontend\Models\ForumMessages();
$new_message_conversation->browser = $this->request->getUserAgent();
$new_message_conversation->ip = $this->request->getClientAddress();
$new_message_conversation->date_create = new \Phalcon\Db\RawValue('now()');
$new_message_conversation->rating = 0;
$new_message_conversation->text = $message;
$new_message_conversation->topic_relation = $new_theme_conversation->id;
$new_message_conversation->user_relation = $this->userId;
if($new_message_conversation->create() == false) {
$string = "";
foreach($new_message_conversation->getMessages() as $message) {
$string .= $message."<br/>";
}
$this->db->rollback();
return $this->response->setJsonContent(['code' => 323, 'status' => $string]);
}
$this->db->commit();
return $this->response->setJsonContent(['code' => 200, 'status' => 'Запись успешно создана']);
}
}
|