/var/www/vhosts/ihelp.ro/httpdocs/src/Controller/Component
Edit: /var/www/vhosts/ihelp.ro/httpdocs/src/Controller/Component/UserAuthComponent.php (15541B)
registry = $registry;
parent::__construct($registry, $config);
}
public function beforeFilter(EventInterface $event)
{
$this->controller = $this->getController();
$this->request = $this->controller->getRequest();
$this->response = $this->controller->getResponse();
$this->session = $this->request->getSession();
//$this->controller->loadComponent('Auth');
$this->init();
}
/**
* Used to init user management plugin
*
* @access public
* @return void
*/
public function init()
{
$this->setCustomSettings();
$this->checkForCookieLogin();
}
/**
* Used to set custom settings
*
* @access public
* @return void
*/
public function setCustomSettings()
{
if (!defined("SITE_URL")) {
if (!defined('CRON_DISPATCHER')) {
define("SITE_URL", Router::url('/', true));
}
}
if (!defined("SITE_NAME") && defined("SITE_NAME_FULL")) {
//use SITE_NAME_FULL everywhere
define("SITE_NAME", SITE_NAME_FULL);
}
if (!defined("DEFAULT_IMAGE_PATH")) {
define("DEFAULT_IMAGE_PATH", APP . DS . "webroot" . DS . "img" . DS . "default.png");/* setting path for default image */
}
if (!defined("DEFAULT_IMAGE_URL")) {
define("DEFAULT_IMAGE_URL", Router::url('/', true) . "img/default.png");
}
// define your more constants or write configure elements
}
/**
* Used to check if user is guest and can we auto login via cookie
*
* @access public
* @return void
*/
public function checkForCookieLogin()
{
if (!$this->isLogged()) {
$cookieValue = $this->request->getCookie(LOGIN_COOKIE_NAME);
if (!empty($cookieValue)) {
$this->response = $this->response->withExpiredCookie(new Cookie(LOGIN_COOKIE_NAME));
$this->controller->setResponse($this->response);
$tokenParts = explode(':', strval($cookieValue));
if (count($tokenParts) == 3) {
$token = $tokenParts[0];
$user_id = $tokenParts[1];
$duration = $tokenParts[2];
$userTable = TableRegistry::getTableLocator()->get('Users');
$user = $userTable->getUserByCookieToken(compact('token', 'user_id', 'duration'));
$this->login($user);
if (!empty($user)) {
$this->persist($duration);
}
}
}
}
}
/**
* Used to force use of HTTP/HTTPS based on setting
*
* @access public
* @return void
*/
public function checkForHttpsRedirect()
{
$skipForHttps = ['login/fb', 'login/twt', 'login/gmail', 'login/ldn', 'login/fs', 'login/yahoo'];
if (!$this->request->is('ajax')) {
if (defined('USE_HTTPS') && USE_HTTPS) {
$this->Ssl->force();
} else {
if (defined('HTTPS_URLS')) {
$httpsUrls = HTTPS_URLS;
if (!empty($httpsUrls)) {
$httpsUrls = array_map('trim', explode(',', strtolower($httpsUrls)));
$httpsUrls = array_map(function ($v) {
return rtrim(ltrim($v, '/'), '/');
}, $httpsUrls);
$actionUrl1 = strtolower($this->request->getParam('controller') . '/' . $this->request->getParam('action'));
$actionUrl2 = strtolower($this->request->getParam('controller') . '/*');
if (!empty($this->request->getParam('plugin'))) {
$actionUrl1 = strtolower($this->request->getParam('plugin')) . '/' . $actionUrl1;
$actionUrl2 = strtolower($this->request->getParam('plugin')) . '/' . $actionUrl2;
}
if (in_array($actionUrl1, $httpsUrls) || in_array($actionUrl2, $httpsUrls)) {
if (!in_array($this->request->getPath(), $skipForHttps)) {
$this->Ssl->force();
}
} else {
$this->Ssl->unforce();
}
}
}
}
}
}
/**
* Used to set $var variable with user details, which is available in view templates
*
* @access public
* @return void
*/
public function setVarVariableForView()
{
$userId = $this->getUserId();
$user = [];
if ($userId) {
$userTable = TableRegistry::getTableLocator()->get('Usermgmt.Users');
$user = $userTable->getUserById($userId);
if (empty($user['id'])) {
$this->controller->redirect(['plugin' => 'Usermgmt', 'controller' => 'Users', 'action' => 'logout']);
}
}
$this->controller->set('var', $user);
}
/**
* Used to maintain login session of user
*
* @access public
* @param array $user user information for session
* @return void
*/
public function login($user)
{
$this->updateLastLoginTime($user);
$this->Authentication->setIdentity($user);
}
public function updateLastLoginTime($user)
{
if (!empty($user->id)) {
$userTable = TableRegistry::getTableLocator()->get('Users');
$userEntity = $userTable->newEmptyEntity();
$userEntity['id'] = $user->id;
$userEntity['last_login'] = date('Y-m-d H:i:s');
$userTable->save($userEntity, ['validate' => false]);
}
}
/**
* Used to maintain login cookie on remember me option, it is used to auto login user
*
* @access public
* @param string $duration duration time
* @return void
*/
public function persist($duration = '2 weeks')
{
$userId = $this->getUserId();
if (!empty($userId)) {
$loginTokenTable = TableRegistry::getTableLocator()->get('LoginTokens');
$token = $loginTokenTable->saveCookieToken($userId, $duration);
// Add a cookie
$cookie = new Cookie(
LOGIN_COOKIE_NAME,
$token,
new DateTime('+' . $duration),
'/',
'',
false,
true
);
$this->response = $this->response->withCookie($cookie);
$this->controller->setResponse($this->response);
}
}
/**
* Used to delete user session and cookie
*
* @access public
* @return void
*/
public function logout()
{
$this->clearSessionAndCookie();
$this->Authentication->logout();
}
public function clearSessionAndCookie()
{
$this->response = $this->response->withExpiredCookie(new Cookie(LOGIN_COOKIE_NAME));
$this->controller->setResponse($this->response);
if (defined('FB_APP_ID')) {
$this->session->delete("fb_" . FB_APP_ID . "_code");
$this->session->delete("fb_" . FB_APP_ID . "_access_token");
$this->session->delete("fb_" . FB_APP_ID . "_user_id");
}
$this->session->delete("G_token");
}
/********************************************** USEFUL FUNCTIONS ****************************************/
/**
* Used to check whether user is logged in or not
*
* @access public
* @return boolean
*/
public function isLogged()
{
if ($this->getUserId()) {
return true;
}
return false;
}
/**
* Used to get user from session
*
* @access public
* @return array
*/
public function getUser()
{
return $this->session->read('Auth');
}
/**
* Used to get user id from session
*
* @access public
* @return integer
*/
public function getUserId()
{
return $this->session->read('Auth.id');
}
/**
* Used to get group id from session
*
* @access public
* @return integer
*/
public function getGroupId()
{
return $this->session->read('Auth.role_id');
}
/**
* Used to check is admin logged in
*
* @access public
* @return string
*/
public function isAdmin()
{
$roleId = $this->session->read('Auth.role_id');
if (isset($roleId) && $roleId == ADMIN) {
return true;
}
return false;
}
/**
* Used to check is guest logged in
*
* @access public
* @return string
*/
public function isGuest()
{
$roleId = $this->session->read('Auth.role_id');
if (empty($roleId)) {
return true;
}
return false;
}
/**
* Used to make password in hash format
*
* @access public
* @param string $password password of user
* @return hash
*/
public function makeHashedPassword($password)
{
return (new DefaultPasswordHasher)->hash($password);
}
/**
* Used to check user password with database password
*
* @access public
* @param string $password password of user
* @param string $dbpassword database password of user
* @param array $options options array
* @return boolean
*/
public function checkPassword($password, $dbpassword, $options = [])
{
if (!isset($options['passwordHasher'])) {
$options['passwordHasher'] = 'Default';
}
$passwordHasher = [];
if (!empty($options)) {
if (strtolower($options['passwordHasher']) == 'ump2' && !empty($options['salt'])) {
//cakephp 2.x old password compatibility
if (strlen($options['salt']) == 32) {
//cakephp 2.x user management plugin version upto 2.2.1 version
return $dbpassword === md5(md5($password) . md5($options['salt']));
} else {
//cakephp 2.x user management plugin version greater than 2.2.1 version
$options['salt'] = base64_decode($options['salt']) . Security::getSalt();
return $dbpassword === Security::hash($password, 'sha256', $options['salt']);
}
} else {
//cakephp 2.x old password compatibility (which are not using our cakephp 2.x user management plugin)
$passwordHasher['passwordHasher']['className'] = $options['passwordHasher'];
}
if (isset($options['hashType'])) {
$passwordHasher['passwordHasher']['hashType'] = $options['hashType'];
}
}
//cakephp 3.x & 4.x
$hasher = (new BasicAuthenticate($this->registry, $passwordHasher))->passwordHasher();
return $hasher->check($password, $dbpassword);
}
/**
* Used to generate random password
*
* @access public
* @return string
*/
public function generatePassword()
{
return substr(md5(mt_rand(0, 32) . time()), 0, 7);
}
/**
* It is used to update profile pic from given url
*
* @access public
* @param url $file_location url of pic
* @return string
*/
public function updateProfilePic($file_location)
{
$fullpath = WWW_ROOT . "uploads" . DS . "images" . DS . "Profiles";
if (!is_dir($fullpath)) {
mkdir($fullpath, 0777, true);
}
$imgContent = file_get_contents($file_location);
$photo = time() . mt_rand() . ".jpg";
$fp = fopen($fullpath . DS . $photo, "w");
fwrite($fp, $imgContent);
fclose($fp);
return $photo;
}
/**
* It is used to delete tmp cache
* $congig = ['type'=>'all', 'increase_qrdn'=>true, 'truncate_user_activities_table'=>true]
* type = 'all', 'models', 'persistent', 'views', 'user_settings', 'permissions'
* increase_qrdn = true|false
* truncate_user_activities_table = true|false
*
* @access public
* @param array $congig array of features
* @return string
*/
public function deleteCache($congig)
{
$default = ['type' => 'all'];
$congig = $default + $congig;
$success = true;
$iterator = new \RecursiveDirectoryIterator(CACHE);
foreach (new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::CHILD_FIRST) as $file) {
if (!in_array($file->getBasename(), ['.svn', '.', '..'])) {
$filepath = $file->getPath();
$filepathname = $file->getPathname();
$basename = $file->getBasename();
if ($congig['type'] == 'all' || $congig['type'] == 'models') {
if ($filepath == CACHE . 'models') {
if (!@unlink($filepathname)) {
$success = false;
}
}
}
if ($congig['type'] == 'all' || $congig['type'] == 'persistent') {
if ($filepath == CACHE . 'persistent') {
if (!@unlink($filepathname)) {
$success = false;
}
}
}
if ($congig['type'] == 'all' || $congig['type'] == 'views') {
if ($filepath == CACHE . 'views') {
if (!@unlink($filepathname)) {
$success = false;
}
}
}
if ($filepath == TMP . 'cache') {
if ($congig['type'] == 'all') {
if (!is_dir($filepathname) && strpos($basename, 'iHelp_') !== false) {
if (!@unlink($filepathname)) {
$success = false;
}
}
}
}
}
}
return $success;
}
/**
* Used to get last login time
*
* @access public
* @return string
*/
public function getLastLoginTime()
{
$last_login = $this->session->read('Auth.User.last_login');
if (!empty($last_login)) {
return $this->getFormatDatetime($last_login);
}
return '';
}
/**
* Used to format date
*
* @access public
* @param mixed $dateObj string or date object
* @return string
*/
public function getFormatDate($dateObj)
{
if (is_object($dateObj)) {
return $dateObj->i18nFormat('dd-MMM-yyyy', date_default_timezone_get());
} else if (!empty($dateObj)) {
return date('d-M-Y', strtotime($dateObj));
}
return null;
}
/**
* Used to format datetime
*
* @access public
* @param mixed $dateObj string or date object
* @return string
*/
public function getFormatDatetime($dateObj)
{
if (is_object($dateObj)) {
return $dateObj->i18nFormat('dd-MMM-yyyy hh:mm a', date_default_timezone_get());
} else if (!empty($dateObj)) {
return date('d-M-Y h:i A', strtotime($dateObj));
}
return null;
}
/**
* Used to format time
*
* @access public
* @param mixed $dateObj string or date object
* @return string
*/
public function getFormatTime($dateObj)
{
if (is_object($dateObj)) {
return $dateObj->i18nFormat('hh:mm a', date_default_timezone_get());
} else if (!empty($dateObj)) {
return date('h:i A', strtotime($dateObj));
}
return null;
}
/**
* Used to generate activation key
*
* @access public
* @param string $string string
* @return hash
*/
public function getActivationKey($string)
{
return md5(md5($string) . Security::getSalt());
}
/**
* Used to encrypt field
*
* @access public
* @param string $string string
* @return hash
*/
public function encryptField($field)
{
return base64_encode($field . '.' . Security::getSalt());
}
/**
* Used to decrypt field
*
* @access public
* @param hash $hash hash string
* @return string
*/
public function decryptField($hash)
{
$fieldDecrypt = base64_decode($hash);
if (strpos($fieldDecrypt, '.') !== false) {
$fieldDecrypt = explode('.', $fieldDecrypt);
$field = array_shift($fieldDecrypt);
$salt = implode('.', $fieldDecrypt);
if (Security::getSalt() === $salt) {
return $field;
}
}
return 'unknown';
}
/**
* Used to get pagination page number
*
* @access public
* @return integer
*/
public function getPageNumber()
{
$page = 1;
$pagingAttributes = $this->request->getAttribute('paging');
$pageQuery = $this->request->getQuery('page');
if (!empty($pagingAttributes)) {
foreach ($pagingAttributes as $attr) {
$page = $attr['page'];
}
} else if (!empty($pageQuery)) {
$page = $pageQuery;
}
return $page;
}
}