<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}

class pjAppController extends pjController
{
	public $models = array();

	/**
	 * Generate (or return existing) CSRF token for the current session.
	 */
	public static function getCsrfToken()
	{
		if (empty($_SESSION['csrf_token']))
		{
			$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
		}
		return $_SESSION['csrf_token'];
	}

	/**
	 * Validate CSRF token (admin requests).
	 */
	public static function validateCsrfToken()
	{
		$token = '';
		if (!empty($_POST['csrf_token'])) {
			$token = $_POST['csrf_token'];
		} elseif (!empty($_GET['csrf_token'])) {
			$token = $_GET['csrf_token'];
		} elseif (!empty($_SERVER['HTTP_X_CSRF_TOKEN'])) {
			$token = $_SERVER['HTTP_X_CSRF_TOKEN'];
		}
		if (empty($_SESSION['csrf_token']) || !hash_equals($_SESSION['csrf_token'], (string) $token))
		{
			header('HTTP/1.1 403 Forbidden');
			exit('Invalid CSRF token.');
		}
	}
	
	public $option_arr = array();

	public $defaultUser = 'admin_user';
	
	public $defaultLocale = 'admin_locale_id';
	
	public $defaultFields = 'fields';
	
	public $defaultFieldsIndex = 'fields_index';
	
	protected function loadSetFields($force=FALSE)
	{
		$registry = pjRegistry::getInstance();
		if ($force
				|| !isset($_SESSION[$this->defaultFieldsIndex])
				|| $_SESSION[$this->defaultFieldsIndex] != $this->option_arr['o_fields_index']
				|| !isset($_SESSION[$this->defaultFields])
				|| empty($_SESSION[$this->defaultFields]))
		{
			pjAppController::setFields($this->getLocaleId());
	
			if ($registry->is('fields'))
			{
				$_SESSION[$this->defaultFields] = $registry->get('fields');
			}
			$_SESSION[$this->defaultFieldsIndex] = $this->option_arr['o_fields_index'];
		}
	
		if (isset($_SESSION[$this->defaultFields]) && !empty($_SESSION[$this->defaultFields]))
		{
			$registry->set('fields', $_SESSION[$this->defaultFields]);
		}
			
		return TRUE;
	}
		
	public function isOneAdminReady()
	{
		return $this->isAdmin();
	}
	public function isCountryReady()
    {
    	return $this->isAdmin();
    }
    
	public static function setTimezone($timezone="UTC")
    {
    	if (in_array(version_compare(phpversion(), '5.1.0'), array(0,1)))
		{
			date_default_timezone_set($timezone);
		} else {
			$safe_mode = ini_get('safe_mode');
			if ($safe_mode)
			{
				putenv("TZ=".$timezone);
			}
		}
    }

	public static function setMySQLServerTime($offset="-0:00")
    {
		pjAppModel::factory()->prepare("SET SESSION time_zone = :offset;")->exec(compact('offset'));
    }
    
    public function isEmployer()
    {
    	if(isset($_SESSION[$this->defaultUser]))
    	{
    		$employer = $_SESSION[$this->defaultUser];
    		if(isset($employer['is_employer']))
    		{
    			return true;
    		}else{
    			return false;
    		}
    	}else{
    		return false;
    	}
    }
    
	public function setTime()
	{
		if (isset($this->option_arr['o_timezone']))
		{
			$offset = $this->option_arr['o_timezone'] / 3600;
			if ($offset > 0)
			{
				$offset = "-".$offset;
			} elseif ($offset < 0) {
				$offset = "+".abs($offset);
			} elseif ($offset === 0) {
				$offset = "+0";
			}
	
			pjAppController::setTimezone('Etc/GMT' . $offset);
			if (strpos($offset, '-') !== false)
			{
				$offset = str_replace('-', '+', $offset);
			} elseif (strpos($offset, '+') !== false) {
				$offset = str_replace('+', '-', $offset);
			}
			pjAppController::setMySQLServerTime($offset . ":00");
		}
	}
    
	public function afterFilter()
	{
		if ($_GET['controller'] != 'pjInstaller')
		{
			$this->set('menu_locale_arr', pjLocaleModel::factory()->select('t1.*, t2.file, t2.title')
				->join('pjLocaleLanguage', 't2.iso=t1.language_iso', 'left outer')
				->where('t2.file IS NOT NULL')
				->orderBy('t1.sort ASC')
				->findAll()
				->getDataPair('id')
			);
		}
	}
	
    public function beforeFilter()
    {
		if (strtoupper(@$_SERVER['REQUEST_METHOD']) === 'POST')
		{
			$_csrf_ctrl = isset($_GET['controller']) ? $_GET['controller'] : '';
			$_csrf_act = isset($_GET['action']) ? $_GET['action'] : '';
			if (strpos($_csrf_ctrl, 'pjAdmin') === 0
				&& !in_array($_csrf_act, array('pjActionLogin', 'pjActionEmployerLogin', 'pjActionForgot', 'pjActionEmployerForgot', 'pjActionLogout', 'pjActionPreview', 'pjActionExportFeed'), true)) {
				pjAppController::validateCsrfToken();
			}
		}

    	$this->appendJs('jquery.min.js', PJ_THIRD_PARTY_PATH . 'jquery/');
    	$baseDir = defined("PJ_INSTALL_PATH") ? PJ_INSTALL_PATH : null;
		$dm = new pjDependencyManager($baseDir, PJ_THIRD_PARTY_PATH);
    	$dm->load(PJ_CONFIG_PATH . 'dependencies.php')->resolve();
    	$this->appendJs('jquery-migrate.min.js', $dm->getPath('jquery_migrate'), FALSE, FALSE);
    	$this->appendJs('pjAdminCore.js');
    	$this->appendCss('reset.css');
    	
    	$this->appendJs('js/jquery-ui.custom.min.js', PJ_THIRD_PARTY_PATH . 'jquery_ui/');
		$this->appendCss('css/smoothness/jquery-ui.min.css', PJ_THIRD_PARTY_PATH . 'jquery_ui/');
				
		$this->appendCss('pj-all.css', PJ_FRAMEWORK_LIBS_PATH . 'pj/css/');
		$this->appendCss('admin.css');
		
    	if ($_GET['controller'] != 'pjInstaller')
		{
			$this->models['Option'] = pjOptionModel::factory();
			$this->option_arr = $this->models['Option']->getPairs($this->getForeignId());
			$this->set('option_arr', $this->option_arr);
			$this->setTime();
			
			if (!isset($_SESSION[$this->defaultLocale]))
			{
				$locale_arr = pjLocaleModel::factory()->where('is_default', 1)->limit(1)->findAll()->getData();
				if (count($locale_arr) === 1)
				{
					$this->setLocaleId($locale_arr[0]['id']);
				}
			}
			
			if (!in_array($_GET['action'], array()))
			{
				$this->loadSetFields(true);
			}
		}
    }
    
	public function pjActionCheckInstall()
	{
		$this->setLayout('pjActionEmpty');
		
		$result = array('status' => 'OK', 'code' => 200, 'text' => 'Operation succeeded', 'info' => array());
		$folders = array(
							'app/web/upload',
							'app/web/upload/files/applications',
							'app/web/upload/files/employees',
							'app/web/upload/logos', 
							'app/web/upload/logos/thumbs'
						);
		foreach ($folders as $dir)
		{
			if (!is_writable($dir))
			{
				$result['status'] = 'ERR';
				$result['code'] = 101;
				$result['text'] = 'Permission requirement';
				$result['info'][] = sprintf('Folder \'<span class="bold">%1$s</span>\' is not writable. You need to set write permissions (chmod 777) to directory located at \'<span class="bold">%1$s</span>\'', $dir);
			}
		}
		
		return $result;
	}
    
    public function getForeignId()
    {
    	return 1;
    }
    
    public static function setFields($locale)
    {
    	if(isset($_SESSION['lang_show_id']) && (int) $_SESSION['lang_show_id'] == 1)
		{
			$fields = pjMultiLangModel::factory()
				->select('CONCAT(t1.content, CONCAT(":", t2.id, ":")) AS content, t2.key')
				->join('pjField', "t2.id=t1.foreign_id", 'inner')
				->where('t1.locale', $locale)
				->where('t1.model', 'pjField')
				->where('t1.field', 'title')
				->findAll()
				->getDataPair('key', 'content');
		}else{
			$fields = pjMultiLangModel::factory()
				->select('t1.content, t2.key')
				->join('pjField', "t2.id=t1.foreign_id", 'inner')
				->where('t1.locale', $locale)
				->where('t1.model', 'pjField')
				->where('t1.field', 'title')
				->findAll()
				->getDataPair('key', 'content');
		}
		$registry = pjRegistry::getInstance();
		$tmp = array();
		if ($registry->is('fields'))
		{
			$tmp = $registry->get('fields');
		}
		$arrays = array();
		foreach ($fields as $key => $value)
		{
			if (strpos($key, '_ARRAY_') !== false)
			{
				list($prefix, $suffix) = explode("_ARRAY_", $key);
				if (!isset($arrays[$prefix]))
				{
					$arrays[$prefix] = array();
				}
				$arrays[$prefix][$suffix] = $value;
			}
		}
		require PJ_CONFIG_PATH . 'settings.inc.php';
		$fields = array_merge($tmp, $fields, $settings, $arrays);
		$registry->set('fields', $fields);
    }

    public static function jsonDecode($str)
	{
		$Services_JSON = new pjServices_JSON();
		return $Services_JSON->decode($str);
	}
	
	public static function jsonEncode($arr)
	{
		$Services_JSON = new pjServices_JSON();
		return $Services_JSON->encode($arr);
	}
	
	public static function jsonResponse($arr)
	{
		header("Content-Type: application/json; charset=utf-8");
		echo pjAppController::jsonEncode($arr);
		exit;
	}

	public function getLocaleId()
	{
		return isset($_SESSION[$this->defaultLocale]) && (int) $_SESSION[$this->defaultLocale] > 0 ? (int) $_SESSION[$this->defaultLocale] : false;
	}
	
	public function setLocaleId($locale_id)
	{
		$_SESSION[$this->defaultLocale] = (int) $locale_id;
	}
	public function getDirection()
	{
	    $dir = 'ltr';
	    if($this->getLocaleId() != false)
	    {
	        $locale_arr = pjLocaleModel::factory()->find($this->getLocaleId())->getData();
	        $dir = $locale_arr['dir'];
	    }
	    return $dir;
	}
	public static function friendlyURL($str, $divider='-')
	{
	    $str = mb_strtolower($str, mb_detect_encoding($str));
	    $str = trim($str);
	    $str = preg_replace('/[_|\s]+/', $divider, $str);
	    $str = preg_replace('/\x{00C5}/u', 'AA', $str);
	    $str = preg_replace('/\x{00C6}/u', 'AE', $str);
	    $str = preg_replace('/\x{00D8}/u', 'OE', $str);
	    $str = preg_replace('/\x{00E5}/u', 'aa', $str);
	    $str = preg_replace('/\x{00E6}/u', 'ae', $str);
	    $str = preg_replace('/\x{00F8}/u', 'oe', $str);
	    $str = preg_replace('/[^a-z\x{0400}-\x{04FF}0-9-]+/u', '', $str);
	    $str = preg_replace('/[-]+/', $divider, $str);
	    $str = preg_replace('/^-+|-+$/', '', $str);
	    return $str;
	}
	
	public function getFromEmail($option_arr)
	{
		$email = $option_arr['o_email_address'];
		if($email == '')
		{
			$arr = pjUserModel::factory()->find(1)->getData();
			$email = $arr['email'];
		}
		return $email;
	}
	public function getAdminEmail()
	{
		$arr = pjUserModel::factory()->where('role_id', 1)->findAll()->getDataPair(null, 'email');
		return $arr;
	}
	
	protected function updateEmployee($id)
	{
		$data = array();
		$arr = pjEmployeeModel::factory()->find($id)->getData();
		$data['email'] = $arr['email'];
		$data['fname'] = $arr['fname'];
		$data['lname'] = $arr['lname'];
		
		pjApplicationModel::factory()->where('employee_id', $id)->modifyAll($data);
	}
	
	protected function getJobId($employer_id)
	{
		$arr = pjJobModel::factory()->where('employer_id', $employer_id)->findAll()->getDataPair('id', 'id');
		return $arr;
	}
	
	protected function getApplicationId($employer_id)
	{
		$job_id_arr = pjJobModel::factory()->where('employer_id', $employer_id)->findAll()->getDataPair('id', 'id');
		$arr = pjApplicationModel::factory()->whereIn('job_id', $job_id_arr)->findAll()->getDataPair('id', 'id');
		return $arr;
	}
	
	public static function pjActionEmployeeConfirmSend($option_arr, $id, $locale_id)
	{
		$employee = pjEmployeeModel::factory()->find($id)->getData();
		
		$notify_arr = pjNotificationModel::factory()->find(5)->getData();
		$notify_arr['i18n'] = pjMultiLangModel::factory()->getMultiLang(5, 'pjNotification');
		
		$subject = $notify_arr['i18n'][$locale_id]['subject5'];
		$message = $notify_arr['i18n'][$locale_id]['message5'];
		
		if(!empty($employee['email']) && !empty($message) && !empty($subject))
		{
			$confirmURL = '';
			if($option_arr['o_employee_confirmed'] == 'manual')
			{
				$confirmURL = PJ_INSTALL_URL . 'index.php?controller=pjLoad&action=pjActionEmployeeConfirm&id='.$id.'&hash='.sha1($id.$employee['created'].PJ_SALT);
				$confirmURL = '<a href="'.$confirmURL.'">'.$confirmURL.'</a>';
			}
			$message = str_replace(array('{fname}', '{lname}', '{email}', '{password}', '{confirmURL}'), array(@$employee['fname'], @$employee['lname'], @$employee['email'], @$employee['password'], $confirmURL), $message);

			$to = $employee['email'];
			$from = pjAppController::getFromEmail($option_arr);
			
			$pjEmail = new pjEmail();
			if ($option_arr['o_send_email'] == 'smtp')
			{
				$pjEmail
					->setTransport('smtp')
					->setSmtpHost($option_arr['o_smtp_host'])
					->setSmtpPort($option_arr['o_smtp_port'])
					->setSmtpUser($option_arr['o_smtp_user'])
					->setSmtpPass($option_arr['o_smtp_pass'])
					->setSender($option_arr['o_smtp_user'])
				;
			}
			$pjEmail->setContentType('text/html');
			$pjEmail->setFrom($from);
			$pjEmail->setTo($to);
			$pjEmail->setSubject($subject);
			$pjEmail->send($message);
		}
	}
	
	public static function pjActionEmployerConfirmSend($option_arr, $id, $locale_id)
	{
		$employer = pjEmployerModel::factory()->find($id)->getData();
	
		$notify_arr = pjNotificationModel::factory()->find(6)->getData();
		$notify_arr['i18n'] = pjMultiLangModel::factory()->getMultiLang(6, 'pjNotification');
	
		$subject = $notify_arr['i18n'][$locale_id]['subject6'];
		$message = $notify_arr['i18n'][$locale_id]['message6'];
	
		if(!empty($employer['email']) && !empty($message) && !empty($subject))
		{
			$confirmURL = '';
			if($option_arr['o_employer_confirmed'] == 'manual')
			{
				$confirmURL = PJ_INSTALL_URL . 'index.php?controller=pjLoad&action=pjActionEmployerConfirm&id='.$id.'&hash='.sha1($id.$employer['created'].PJ_SALT);
				$confirmURL = '<a href="'.$confirmURL.'">'.$confirmURL.'</a>';
			}
			$message = str_replace(array('{companyname}', '{contactname}', '{email}', '{password}', '{confirmURL}'), array(@$employer['company_name'], @$employer['contact_name'], @$employer['email'], @$employer['password'], $confirmURL), $message);
	
			$to = $employer['email'];
			$from = pjAppController::getFromEmail($option_arr);
				
			$pjEmail = new pjEmail();
			if ($option_arr['o_send_email'] == 'smtp')
			{
				$pjEmail
					->setTransport('smtp')
					->setSmtpHost($option_arr['o_smtp_host'])
					->setSmtpPort($option_arr['o_smtp_port'])
					->setSmtpUser($option_arr['o_smtp_user'])
					->setSmtpPass($option_arr['o_smtp_pass'])
					->setSender($option_arr['o_smtp_user'])
				;
			}
			$pjEmail->setContentType('text/html');
			$pjEmail->setFrom($from);
			$pjEmail->setTo($to);
			$pjEmail->setSubject($subject);
			$pjEmail->send($message);
		}
	}
}
?>