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

class pjLoad extends pjFront
{
	private $isoDatePattern = '/\d{4}-\d{2}-\d{2}/';
	
	private $imageFiles = array('small_path', 'medium_path', 'large_path', 'source_path');
		
	private $imageFillColor = array(255, 255, 255);
	
	private $imageCrop = true;
	
	public function pjActionCheckEmail()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (!isset($_GET['email']) || empty($_GET['email']))
			{
				echo 'false';
				exit;
			}
			$pjMemberModel = pjMemberModel::factory()->where('t1.email', $_GET['email']);
			if (isset($_GET['id']) && (int) $_GET['id'] > 0)
			{
				$pjMemberModel->where('t1.id !=', $_GET['id']);
			}
			echo $pjMemberModel->findCount()->getData() == 0 ? 'true' : 'false';
		}
		exit;
	}
	public function pjActionIndex()
	{	
		$pjMemberModel = pjMemberModel::factory()
			->join('pjMultiLang', "t2.model='pjMember' AND t2.foreign_id=t1.id AND t2.field='biography' AND t2.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t3.model='pjCountry' AND t3.foreign_id=t1.country_id AND t3.field='name' AND t3.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t4.foreign_id = t1.id AND t4.model = 'pjMember' AND t4.locale = '".$this->getLocaleId()."' AND t4.field = 'name'", 'left')
			->join('pjMultiLang', "t5.foreign_id = t1.id AND t5.model = 'pjMember' AND t5.locale = '".$this->getLocaleId()."' AND t5.field = 'address'", 'left')
			->join('pjMultiLang', "t6.foreign_id = t1.id AND t6.model = 'pjMember' AND t6.locale = '".$this->getLocaleId()."' AND t6.field = 'city'", 'left')
			->join('pjMultiLang', "t7.foreign_id = t1.id AND t7.model = 'pjMember' AND t7.locale = '".$this->getLocaleId()."' AND t7.field = 'state'", 'left');

		$pjMemberModel->where('t1.status', 'T');
		
		if(isset($_GET['members_search']))
		{
			if(isset($_GET['name']) && $_GET['name'] != '')
			{
				$name = pjObject::escapeString($_GET['name']);
				$pjMemberModel->where("(t4.content LIKE '%$name%')");
			}
			if(isset($_GET['email']) && $_GET['email'] != '')
			{
				$email = pjObject::escapeString($_GET['email']);
				$pjMemberModel->where('t1.email', $email);
			}
			if(isset($_GET['city']) && $_GET['city'] != '')
			{
				$city = pjObject::escapeString($_GET['city']);
				$pjMemberModel->where("(t6.content LIKE '%$city%')");
			}
			if(isset($_GET['age']) && (int) $_GET['age'] > 0)
			{
				$age = $_GET['age'];
				switch ($age) {
					case 1:
						$pjMemberModel->where("(t1.age >= 0 AND t1.age < 15)");
					break;
					case 15:
						$pjMemberModel->where("(t1.age >= 15 AND t1.age < 30)");
						break;
					case 30:
						$pjMemberModel->where("(t1.age >= 30 AND t1.age < 45)");
						break;
					case 45:
						$pjMemberModel->where("(t1.age >= 45 AND t1.age < 60)");
						break;
					case 60:
						$pjMemberModel->where("(t1.age >= 60 AND t1.age < 75)");
						break;
					case 75:
						$pjMemberModel->where("(t1.age >= 75)");
						break;
				}
			}
			if(isset($_GET['skills']) && !empty($_GET['skills']))
			{
				$pjMemberModel->where("t1.id IN(SELECT TMS.member_id FROM `".pjMemberSkillModel::factory()->getTable()."` AS `TMS` WHERE `TMS`.skill_id IN(".join(",", $_GET['skills'])."))");
			}
		}
		
		$column = 'name';
		$direction = 'ASC';
		$total = $pjMemberModel->findCount()->getData();
		$items_per_page = (int) $this->option_arr['o_items_per_page'] > 0 ? $this->option_arr['o_items_per_page'] : 10;
		$rowCount = isset($_GET['rowCount']) && (int) $_GET['rowCount'] > 0 ? (int) $_GET['rowCount'] : $items_per_page;
		$pages = ceil($total / $rowCount);
		$page = isset($_GET['pjPage']) && (int) $_GET['pjPage'] > 0 ? intval($_GET['pjPage']) : 1;
		$offset = ((int) $page - 1) * $rowCount;
		if ($page > $pages)
		{
			$page = $pages;
		}
		
		$arr = $pjMemberModel
			->select("
						t1.id, t1.email, t1.phone, t1.age, t1.zip, t1.country_id, t1.avatar_path, t1.mime_type, t1.avatar_hash, 
						t1.ip, t1.facebook, t1.google, t1.linkedin, t1.twitter, t1.modified, t1.created, t1.last_login, t1.status,
						AES_DECRYPT(t1.password, '".PJ_SALT."') AS `password`,						
						t4.content as name, 
						t5.content as address, 
						t6. content as city, 
						t7.content as state,
					  (IF(CHAR_LENGTH(t2.content) >= 100, CONCAT(SUBSTRING(t2.content, 1, 100), '...'), t2.content)) AS biography,
					  t3.content AS country,	
					  (SELECT GROUP_CONCAT(TML.content SEPARATOR '~:~') FROM `".pjMemberSkillModel::factory()->getTable()."` AS TMS LEFT OUTER JOIN `".pjMultiLangModel::factory()->getTable()."` AS TML ON (TML.model='pjSkill' AND TML.foreign_id=TMS.skill_id AND TML.field='name' AND TML.locale='".$this->getLocaleId()."') WHERE TMS.member_id=t1.id) AS skills")
			->orderBy("$column $direction")
			->limit($rowCount, $offset)
			->findAll()
			->toArray('skills', "~:~")
			->getData();
		
		$this->set('arr', $arr);
		$this->set('paginator', array('pages' => $pages, 'total' => $total));
	}
	
	public function pjActionView()
	{
		$pjMemberModel = pjMemberModel::factory()
			->join('pjMultiLang', "t2.model='pjMember' AND t2.foreign_id=t1.id AND t2.field='biography' AND t2.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t3.model='pjCountry' AND t3.foreign_id=t1.country_id AND t3.field='name' AND t3.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t4.foreign_id = t1.id AND t4.model = 'pjMember' AND t4.locale = '".$this->getLocaleId()."' AND t4.field = 'name'", 'left')
			->join('pjMultiLang', "t5.foreign_id = t1.id AND t5.model = 'pjMember' AND t5.locale = '".$this->getLocaleId()."' AND t5.field = 'address'", 'left')
			->join('pjMultiLang', "t6.foreign_id = t1.id AND t6.model = 'pjMember' AND t6.locale = '".$this->getLocaleId()."' AND t6.field = 'city'", 'left')
			->join('pjMultiLang', "t7.foreign_id = t1.id AND t7.model = 'pjMember' AND t7.locale = '".$this->getLocaleId()."' AND t7.field = 'state'", 'left');
	
		$arr = $pjMemberModel
			->select("
					t1.id, t1.email, t1.phone, t1.age, t1.zip, t1.country_id, t1.avatar_path, t1.mime_type, t1.avatar_hash, 
					t1.ip, t1.facebook, t1.google, t1.linkedin, t1.twitter, t1.modified, t1.created, t1.last_login, t1.status,
					AES_DECRYPT(t1.password, '".PJ_SALT."') AS `password`,						
					t4.content as name, 
					t5.content as address, 
					t6. content as city, 
					t7.content as state,
					t2.content as biography, t3.content as country,
					(SELECT GROUP_CONCAT(TML.content SEPARATOR '~:~') FROM `".pjMemberSkillModel::factory()->getTable()."` AS TMS LEFT OUTER JOIN `".pjMultiLangModel::factory()->getTable()."` AS TML ON (TML.model='pjSkill' AND TML.foreign_id=TMS.skill_id AND TML.field='name' AND TML.locale='".$this->getLocaleId()."') WHERE TMS.member_id=t1.id) AS skills")
			->find($_GET['id'])
			->toArray('skills', "~:~")
			->getData();
		
		$this->set('arr', $arr);
		$this->set('gallery_arr', pjGalleryModel::factory()->where('t1.foreign_id', $_GET['id'])->orderBy('t1.sort ASC')->findAll()->getData());
	}
	
	public function pjActionSearch()
	{
		$skill_arr = pjSkillModel::factory()
			->select("t1.*, t2.content as skill_title")
			->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjSkill' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'name'", 'left')
			->where('status', 'T')
			->orderBy('skill_title ASC')
			->findAll()
			->getData();
		
		$this->set('skill_arr', $skill_arr);
	}
	
	public function pjActionLogin()
	{
		if(isset($_POST['login']))
		{
			$err = null;
			if (!isset($_POST['email']))
			{
				$err = 'LOG01';
			}
			if (isset($_POST['email']) && !pjValidation::pjActionNotEmpty($_POST['email']))
			{
				$err = 'LOG02';
			}
			if (isset($_POST['email']) && pjValidation::pjActionNotEmpty($_POST['email']) && !pjValidation::pjActionEmail($_POST['email']))
			{
				$err = 'LOG03';
			}
			if (!isset($_POST['password']))
			{
				$err = 'LOG04';
			}
			if (isset($_POST['password']) && !pjValidation::pjActionNotEmpty($_POST['password']))
			{
				$err = 'LOG05';
			}
			if($err == null)
			{
				$pjMemberModel = pjMemberModel::factory();
				$member = $pjMemberModel
					->select("t1.*, AES_DECRYPT(t1.password, '".PJ_SALT."') AS `password`")
					->where('t1.email', $_POST['email'])
					->where(sprintf("t1.password = AES_ENCRYPT('%s', '%s')", pjObject::escapeString($_POST['password']), PJ_SALT))
					->limit(1)
					->findAll()
					->getData();
				if (count($member) != 1)
				{
					$_SESSION[$this->defaultError] = 'LOG06';
					pjUtil::redirect($_SERVER['PHP_SELF'] . '?controller=pjLoad&action=pjActionRegister&tab=1' . (isset($_POST['iframe']) ? '&iframe' : NULL));
				}else{
					$member = $member[0];
					if ($member['status'] == 'F')
					{
						$_SESSION[$this->defaultError] = 'LOG07';
						pjUtil::redirect($_SERVER['PHP_SELF'] . '?controller=pjLoad&action=pjActionRegister&tab=1' . (isset($_POST['iframe']) ? '&iframe' : NULL));
					}
					$_SESSION[$this->defaultMember] = $member;
	
					$data = array();
					$data['last_login'] = date("Y-m-d H:i:s");
					$pjMemberModel->reset()->setAttributes(array('id' => $client['id']))->modify($data);
						
					pjUtil::redirect($_SERVER['PHP_SELF'] . '?controller=pjLoad&action=pjActionProfile' . (isset($_POST['iframe']) ? '&iframe' : NULL));
				}
			}else{
				$_SESSION[$this->defaultError] = $err;
				pjUtil::redirect($_SERVER['PHP_SELF'] . '?controller=pjLoad&action=pjActionRegister&tab=1' . (isset($_POST['iframe']) ? '&iframe' : NULL));
			}
		}else{
			if(isset($_SESSION[$this->defaultError]))
			{
				$this->set('err', $_SESSION[$this->defaultError]);
				unset($_SESSION[$this->defaultError]);
			}
		}
	}
	
	public function pjActionRegister()
	{
		if(isset($_POST['register']))
		{
			$err = null;
			if (!isset($_POST['i18n'][$this->getLocaleId()]['name']))
			{
				$err = 'REG01';
			}
			if (isset($_POST['i18n'][$this->getLocaleId()]['name']) && !pjValidation::pjActionNotEmpty($_POST['i18n'][$this->getLocaleId()]['name']))
			{
				$err = 'REG02';
			}
			if (!isset($_POST['email']))
			{
				$err = 'REG03';
			}
			if (isset($_POST['email']) && !pjValidation::pjActionNotEmpty($_POST['email']))
			{
				$err = 'REG04';
			}
			if (isset($_POST['email']) && pjValidation::pjActionNotEmpty($_POST['email']) && !pjValidation::pjActionEmail($_POST['email']))
			{
				$err = 'REG05';
			}
			if (!isset($_POST['password']))
			{
				$err = 'REG06';
			}
			if (isset($_POST['password']) && !pjValidation::pjActionNotEmpty($_POST['password']))
			{
				$err = 'REG07';
			}
			if (!isset($_POST['reenter_password']))
			{
				$err = 'REG08';
			}
			if (isset($_POST['reenter_password']) && !pjValidation::pjActionNotEmpty($_POST['reenter_password']))
			{
				$err = 'REG09';
			}
			if (isset($_POST['password']) && !pjValidation::pjActionNotEmpty($_POST['password']) && isset($_POST['reenter_password']) && !pjValidation::pjActionNotEmpty($_POST['reenter_password']) && $_POST['password'] != $_POST['reenter_password'])
			{
				$err = 'REG10';
			}
			if (!isset($_POST['captcha']))
			{
				$err = 'REG11';
			}
			if (isset($_POST['captcha']) && !pjValidation::pjActionNotEmpty($_POST['captcha']))
			{
				$err = 'REG12';
			}
			if ($_SESSION[$this->defaultCaptcha]=="" || $_POST['captcha']=="" || strtoupper($_POST['captcha']) != $_SESSION[$this->defaultCaptcha])
			{
				$err = 'REG13';
			}
			
			if($err == null)
			{
				$data = array();
				$data['ip'] = pjUtil::getClientIp();
				$id = pjMemberModel::factory(array_merge($_POST, $data))->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					if (isset($_POST['i18n']))
					{
						pjMultiLangModel::factory()->saveMultiLang($_POST['i18n'], $id, 'pjMember', 'data');
					}
					$this->pjActionRegistrationEmail($id);
					$_SESSION[$this->defaultMessage] = 'REG01';
					pjUtil::redirect($_SERVER['PHP_SELF'] . '?controller=pjLoad&action=pjActionRegister&tab=2' . (isset($_POST['iframe']) ? '&iframe' : NULL));
				}else{
					$_SESSION[$this->defaultError] = 'REG14';
					pjUtil::redirect($_SERVER['PHP_SELF'] . '?controller=pjLoad&action=pjActionRegister&tab=2' . (isset($_POST['iframe']) ? '&iframe' : NULL));
				}
			}else{
				$_SESSION[$this->defaultError] = $err;
				pjUtil::redirect($_SERVER['PHP_SELF'] . '?controller=pjLoad&action=pjActionRegister&tab=2' . (isset($_POST['iframe']) ? '&iframe' : NULL));
			}
		}else{
			if(isset($_SESSION[$this->defaultError]))
			{
				$this->set('err', $_SESSION[$this->defaultError]);
				unset($_SESSION[$this->defaultError]);
			}
			if(isset($_SESSION[$this->defaultMessage]))
			{
				$this->set('msg', $_SESSION[$this->defaultMessage]);
				unset($_SESSION[$this->defaultMessage]);
			}
		}
	}
	
	public function pjActionForgot()
	{
		if(isset($_POST['forgot_password']))
		{
			$err = null;
			if (!isset($_POST['email']))
			{
				$err = 'FOR01';
			}
			if (isset($_POST['email']) && !pjValidation::pjActionNotEmpty($_POST['email']))
			{
				$err = 'FOR02';
			}
			if (isset($_POST['email']) && pjValidation::pjActionNotEmpty($_POST['email']) && !pjValidation::pjActionEmail($_POST['email']))
			{
				$err = 'FOR03';
			}
			if($err == null)
			{
				$pjMemberModel = pjMemberModel::factory();
				
				$member = $pjMemberModel
					->select("
								t1.id, t1.email, t1.phone, t1.age, t1.zip, t1.country_id, t1.avatar_path, t1.mime_type, t1.avatar_hash, 
								t1.ip, t1.facebook, t1.google, t1.linkedin, t1.twitter, t1.modified, t1.created, t1.last_login, t1.status,
								AES_DECRYPT(t1.password, '".PJ_SALT."') AS `password`,						
								t4.content as name, 
								t5.content as address, 
								t6. content as city, 
								t7.content as state,
							 	t3.content AS country
							")
					->join('pjMultiLang', "t2.model='pjMember' AND t2.foreign_id=t1.id AND t2.field='biography' AND t2.locale='".$this->getLocaleId()."'", 'left')
					->join('pjMultiLang', "t3.model='pjCountry' AND t3.foreign_id=t1.country_id AND t3.field='name' AND t3.locale='".$this->getLocaleId()."'", 'left')
					->join('pjMultiLang', "t4.foreign_id = t1.id AND t4.model = 'pjMember' AND t4.locale = '".$this->getLocaleId()."' AND t4.field = 'name'", 'left')
					->join('pjMultiLang', "t5.foreign_id = t1.id AND t5.model = 'pjMember' AND t5.locale = '".$this->getLocaleId()."' AND t5.field = 'address'", 'left')
					->join('pjMultiLang', "t6.foreign_id = t1.id AND t6.model = 'pjMember' AND t6.locale = '".$this->getLocaleId()."' AND t6.field = 'city'", 'left')
					->join('pjMultiLang', "t7.foreign_id = t1.id AND t7.model = 'pjMember' AND t7.locale = '".$this->getLocaleId()."' AND t7.field = 'state'", 'left')
					->where('t1.email', $_POST['email'])
					->limit(1)
					->findAll()
					->getData();
				
				$member = $member[0];
				if(empty($member))
				{
					$_SESSION[$this->defaultError] = 'FOR05';
					pjUtil::redirect($_SERVER['PHP_SELF'] . '?controller=pjLoad&action=pjActionForgot' . (isset($_POST['iframe']) ? '&iframe' : NULL));
				}
				if($member['status'] == 'F')
				{
					$_SESSION[$this->defaultError] = 'FOR04';
					pjUtil::redirect($_SERVER['PHP_SELF'] . '?controller=pjLoad&action=pjActionForgot' . (isset($_POST['iframe']) ? '&iframe' : NULL));
				}else{
					
					$pjMultiLangModel = pjMultiLangModel::factory();
					$lang_subject = $pjMultiLangModel
						->reset()
						->select('t1.*')
						->where('foreign_id', 1)
						->where('t1.model','pjOption')
						->where('t1.locale', $this->getLocaleId())
						->where('t1.field', 'o_email_forgot_subject')
						->limit(0, 1)
						->findAll()->getData();
					$lang_message = $pjMultiLangModel
						->reset()
						->select('t1.*')
						->where('foreign_id', 1)
						->where('t1.model','pjOption')
						->where('t1.locale', $this->getLocaleId())
						->where('t1.field', 'o_email_forgot_message')
						->limit(0, 1)
						->findAll()
						->getData();
						
					if (count($lang_message) === 1 && count($lang_subject) === 1)
					{
					
						$pjEmail = new pjEmail();
	
						if ($this->option_arr['o_send_email'] == 'smtp')
						{
							$pjEmail
								->setTransport('smtp')
								->setSmtpHost($this->option_arr['o_smtp_host'])
								->setSmtpPort($this->option_arr['o_smtp_port'])
								->setSmtpUser($this->option_arr['o_smtp_user'])
								->setSmtpPass($this->option_arr['o_smtp_pass']);
						}
	
						$to = $_POST['email'];
						$from = $this->getAdminEmail();
	
						$search = array("{Name}", "{Email}", "{Password}", "{Phone}", "{Country}", "{City}", "{State}", "{Zip}", "{Address}");
						$replace = array($member['name'], $member['email'], $member['password'], $member['phone'], @$member['country'], @$member['city'],@$member['state'], @$member['zip'], @$member['address']);
	
						$subject = str_replace($search, $replace, $lang_subject[0]['content']);
						$message = str_replace($search, $replace, $lang_message[0]['content']);
						
						$pjEmail->setContentType('text/html');
						$pjEmail->setTo($member['email']);
						$pjEmail->setFrom($this->getAdminEmail());
						$pjEmail->setSubject($subject);
						$pjEmail->send($message);
						
						$_SESSION[$this->defaultMessage] = 'FOR01';
						pjUtil::redirect($_SERVER['PHP_SELF'] . '?controller=pjLoad&action=pjActionForgot' . (isset($_POST['iframe']) ? '&iframe' : NULL));
					}
				}
			}else{
				$_SESSION[$this->defaultError] = $err;
				pjUtil::redirect($_SERVER['PHP_SELF'] . '?controller=pjLoad&action=pjActionForgot' . (isset($_POST['iframe']) ? '&iframe' : NULL));
			}
		}else{
			if(isset($_SESSION[$this->defaultError]))
			{
				$this->set('err', $_SESSION[$this->defaultError]);
				unset($_SESSION[$this->defaultError]);
			}
			if(isset($_SESSION[$this->defaultMessage]))
			{
				$this->set('msg', $_SESSION[$this->defaultMessage]);
				unset($_SESSION[$this->defaultMessage]);
			}
		}
	}
	
	public function pjActionProfile()
	{
		$post_max_size = pjUtil::getPostMaxSize();
		if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_SERVER['CONTENT_LENGTH']) && (int) $_SERVER['CONTENT_LENGTH'] > $post_max_size)
		{
			$_SESSION[$this->defaultError] = 'PRO01';
			pjUtil::redirect($_SERVER['PHP_SELF'] . '?controller=pjLoad&action=pjActionProfile' . (isset($_POST['iframe']) ? '&iframe' : NULL));
		}
		if(isset($_POST['profile']))
		{
			$err = null;
			
			if (!isset($_POST['i18n'][$this->getLocaleId()]['name']))
			{
				$err = 'REG01';
			}
			if (isset($_POST['i18n'][$this->getLocaleId()]['name']) && !pjValidation::pjActionNotEmpty($_POST['i18n'][$this->getLocaleId()]['name']))
			{
				$err = 'REG02';
			}
			if (!isset($_POST['email']))
			{
				$err = 'REG03';
			}
			if (isset($_POST['email']) && !pjValidation::pjActionNotEmpty($_POST['email']))
			{
				$err = 'REG04';
			}
			if (isset($_POST['email']) && pjValidation::pjActionNotEmpty($_POST['email']) && !pjValidation::pjActionEmail($_POST['email']))
			{
				$err = 'REG05';
			}
			if (!isset($_POST['password']))
			{
				$err = 'REG06';
			}
			if (isset($_POST['password']) && !pjValidation::pjActionNotEmpty($_POST['password']))
			{
				$err = 'REG07';
			}
			
			if($err == null)
			{
				$data = array();
				$data['ip'] = pjUtil::getClientIp();
				$data['modified'] = date('Y-m-d H:i:s');
				
				$pjMemberModel = pjMemberModel::factory();
				$arr = $pjMemberModel->find($_POST['id'])->getData();
				$pjMemberModel->reset()->where('id', $_POST['id'])->limit(1)->modifyAll(array_merge($_POST, $data));
				if (isset($_POST['i18n']))
				{
					pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $_POST['id'], 'pjMember', 'data');
				}
				
				$pjMemberSkillModel = pjMemberSkillModel::factory();
				$pjMemberSkillModel->where('member_id', $_POST['id'])->eraseAll();
				if(isset($_POST['skill_id']))
				{
					$pjMemberSkillModel->reset()->begin();
					foreach ($_POST['skill_id'] as $skill_id){
						$data = array();
						$data['member_id'] = $_POST['id'];
						$data['skill_id'] = $skill_id;
						$pjMemberSkillModel->reset()->setAttributes($data)->insert();
					}
					$pjMemberSkillModel->commit();
				}
				
				if (isset($_FILES['avatar']) && !empty($_FILES['avatar']['tmp_name']))
				{
					$Image = new pjImage();
					if ($Image->getErrorCode() !== 200)
					{
						$Image->setAllowedTypes(array('image/png', 'image/gif', 'image/jpg', 'image/jpeg', 'image/pjpeg'));
						if ($Image->load($_FILES['avatar']))
						{
							$resp = $Image->isConvertPossible();
							if ($resp['status'] === true)
							{
								if (!empty($arr['avatar_path']) && is_file(PJ_INSTALL_PATH . $arr['avatar_path']))
								{
									@unlink(PJ_INSTALL_PATH . $arr['avatar_path']);
								}
								$hash = md5(uniqid(rand(), true));
								$image_path = PJ_UPLOAD_PATH . 'avatars/' . $_POST['id'] . '_' . $hash . '.' . $Image->getExtension();
				
								$Image->loadImage();
								$Image->setFillColor($this->imageFillColor);
								$Image->resizeSmart(96, 96);
								$Image->saveImage(PJ_INSTALL_PATH . $image_path);
									
								$data = array();
								$data['avatar_path'] = $image_path;
								$data['mime_type'] = $_FILES['avatar']['type'];
								$data['avatar_hash'] = $hash;
				
								$pjMemberModel->reset()->where('id', $_POST['id'])->limit(1)->modifyAll($data);
							}
						}else{
							$_SESSION[$this->defaultError] = 'PRO02';
							pjUtil::redirect($_SERVER['PHP_SELF'] . '?controller=pjLoad&action=pjActionProfile' . (isset($_POST['iframe']) ? '&iframe' : NULL));
						}
					}
				}
				$_SESSION[$this->defaultMessage] = 'PRO01';
				pjUtil::redirect($_SERVER['PHP_SELF'] . '?controller=pjLoad&action=pjActionProfile' . (isset($_POST['iframe']) ? '&iframe' : NULL));
			}else{
				$_SESSION[$this->defaultError] = $err;
				pjUtil::redirect($_SERVER['PHP_SELF'] . '?controller=pjLoad&action=pjActionProfile' . (isset($_POST['iframe']) ? '&iframe' : NULL));
			}
		}else{
			$member = $_SESSION[$this->defaultMember];
			
			$arr = pjMemberModel::factory()->find($member['id'])->getData();
			$arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($arr['id'], 'pjMember');
			
			$country_arr = pjCountryModel::factory()
				->select('t1.id, t2.content AS country_title')
				->join('pjMultiLang', "t2.model='pjCountry' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->orderBy('`country_title` ASC')
				->findAll()
				->getData();
			$this->set('country_arr', $country_arr);
			
			$skill_arr = pjSkillModel::factory()
				->select('t1.id, t2.content AS name')
				->join('pjMultiLang', "t2.model='pjSkill' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->orderBy('`name` ASC')
				->findAll()
				->getData();
			
			$this->set('arr', $arr);
			$this->set('skill_arr', $skill_arr);
			$this->set('skill_id_arr', pjMemberSkillModel::factory()->where('t1.member_id', $member['id'])->findAll()->getDataPair(null, 'skill_id'));
			$this->set('gallery_arr', pjGalleryModel::factory()->where('t1.foreign_id', $member['id'])->orderBy('t1.sort ASC')->findAll()->getData());
			
			if(isset($_SESSION[$this->defaultError]))
			{
				$this->set('err', $_SESSION[$this->defaultError]);
				unset($_SESSION[$this->defaultError]);
			}
			if(isset($_SESSION[$this->defaultMessage]))
			{
				$this->set('msg', $_SESSION[$this->defaultMessage]);
				unset($_SESSION[$this->defaultMessage]);
			}
		}
	}
	
	public function pjActionLogout()
	{
		if ($this->checkLogin())
		{
			unset($_SESSION[$this->defaultMember]);
		}
		pjUtil::redirect($_SERVER['PHP_SELF'] . '?controller=pjLoad&action=pjActionIndex' . (isset($_POST['iframe']) ? '&iframe' : NULL));
	}
	
	public function pjActionDeleteAvatar()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			if (isset($_GET['id']))
			{
				$pjMemberModel = pjMemberModel::factory();
				$arr = $pjMemberModel->find($_GET['id'])->getData();
				@clearstatcache();
				if (!empty($arr['avatar_path']) && is_file(PJ_INSTALL_PATH . $arr['avatar_path']))
				{
					@unlink(PJ_INSTALL_PATH . $arr['avatar_path']);
				}
				$pjMemberModel->reset()->where('id', $_GET['id'])->limit(1)->modifyAll(array('avatar_path' => ':NULL', 'mime_type' => ':NULL', 'avatar_hash' => ':NULL'));
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionGallery()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$this->set('gallery_arr', pjGalleryModel::factory()->where('t1.foreign_id', $_GET['id'])->orderBy('t1.sort ASC')->findAll()->getData());
		}
		
	}
	
	public function pjActionDeleteGallery()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			if (isset($_GET['id']))
			{
				$pjGalleryModel = pjGalleryModel::factory();
				$arr = $pjGalleryModel->find($_GET['id'])->getData();
				if($pjGalleryModel->reset()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
				{
					foreach ($this->imageFiles as $file)
					{
						@clearstatcache();
						if (!empty($arr[$file]) && is_file($arr[$file]))
						{
							@unlink($arr[$file]);
						}
					}
				}
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionUpload()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$front_upload_err = __('front_upload_err', true);
			
			$post_max_size = pjUtil::getPostMaxSize();
			if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_SERVER['CONTENT_LENGTH']) && (int) $_SERVER['CONTENT_LENGTH'] > $post_max_size)
			{
				$response = array();
				$response['code'] = '100';
				$response['text'] = str_replace("{MAXSIZE}", ini_get('post_max_size'), $front_upload_err[100]);
				pjAppController::jsonResponse($response);
			}else{
				$response = array();
				if (isset($_FILES['image']))
				{
					$Image = new pjImage();
					if ($Image->getErrorCode() !== 200)
					{
						$Image->setAllowedTypes(array('image/png', 'image/gif', 'image/jpg', 'image/jpeg', 'image/pjpeg'));
				
						if ($Image->load($_FILES['image']))
						{
							$resp = $Image->isConvertPossible();
							if ($resp['status'] === true)
							{
								$hash = md5(uniqid(rand(), true));
								$source_path = PJ_UPLOAD_PATH . 'source/' . @$_POST['id'] . '_' . $hash . '.' . $Image->getExtension();
								$upload_path = PJ_INSTALL_PATH . $source_path;
								if ($Image->save($upload_path))
								{
									$GalleryModel = pjGalleryModel::factory();
				
									$data = array();
									if (isset($_POST['id']) && (int) $_POST['id'] > 0)
									{
										$GalleryModel->where('t1.foreign_id', $_POST['id']);
										$data['foreign_id'] = $_POST['id'];
									} elseif (isset($_GET['hash']) && !empty($_GET['hash'])) {
										$GalleryModel->where('t1.hash', $_GET['hash']);
										$data['hash'] = $_GET['hash'];
									}
				
									$arr = $GalleryModel->orderBy('t1.sort DESC')->limit(1)->findAll()->getData();
									$sort = 1;
									if (count($arr) === 1)
									{
										$sort = (int) $arr[0]['sort'] + 1;
									}
				
									$data['mime_type'] = $_FILES['image']['type'];
									$data['source_path'] = $source_path;
									$data['source_size'] = $_FILES['image']['size'];
									$data['name'] = $_FILES['image']['name'];
									$data['sort'] = $sort;
				
									$data = array_merge($data, $this->pjActionBuildFromSource($Image, $data));
										
									$size = $Image->getImageSize();
									$data['source_width'] = $size[0];
									$data['source_height'] = $size[1];
				
									$GalleryModel->reset()->setAttributes($data)->insert();
									
									$response['code'] = '200';
									$response['id'] = $_POST['id'];
									$response['text'] = $front_upload_err[200];
								} else {
									$response['code'] = '104';
									$response['text'] = $front_upload_err[104];
								}
							} else {
								$response['code'] = '103';
								$response['text'] = sprintf($front_upload_err[103], $resp['memory_limit'], $resp['memory_needed']);
							}
						} else {
							$response['code'] = '102';
							$response['text'] = $front_upload_err[102];
						}
					} else {
						$response['code'] = '101';
						$response['text'] = $front_upload_err[101];
					}
				}
				pjAppController::jsonResponse($response);
			}
		}
		
		exit;
	}
	
	public function pjActionRegistrationEmail($id)
	{
		$arr = pjMemberModel::factory()
			->select("
						t1.id, t1.email, t1.phone, t1.age, t1.zip, t1.country_id, t1.avatar_path, t1.mime_type, t1.avatar_hash, 
						t1.ip, t1.facebook, t1.google, t1.linkedin, t1.twitter, t1.modified, t1.created, t1.last_login, t1.status,
						AES_DECRYPT(t1.password, '".PJ_SALT."') AS `password`,						
						t4.content as name, 
						t5.content as address, 
						t6. content as city, 
						t7.content as state,
					 	t3.content AS country
					")
			->join('pjMultiLang', "t2.model='pjMember' AND t2.foreign_id=t1.id AND t2.field='biography' AND t2.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t3.model='pjCountry' AND t3.foreign_id=t1.country_id AND t3.field='name' AND t3.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t4.foreign_id = t1.id AND t4.model = 'pjMember' AND t4.locale = '".$this->getLocaleId()."' AND t4.field = 'name'", 'left')
			->join('pjMultiLang', "t5.foreign_id = t1.id AND t5.model = 'pjMember' AND t5.locale = '".$this->getLocaleId()."' AND t5.field = 'address'", 'left')
			->join('pjMultiLang', "t6.foreign_id = t1.id AND t6.model = 'pjMember' AND t6.locale = '".$this->getLocaleId()."' AND t6.field = 'city'", 'left')
			->join('pjMultiLang', "t7.foreign_id = t1.id AND t7.model = 'pjMember' AND t7.locale = '".$this->getLocaleId()."' AND t7.field = 'state'", 'left')
			->find($id)
			->getData();
		
		if(!empty($arr))
		{
			$pjEmail = new pjEmail();
			if ($this->option_arr['o_send_email'] == 'smtp')
			{
				$pjEmail
					->setTransport('smtp')
					->setSmtpHost($this->option_arr['o_smtp_host'])
					->setSmtpPort($this->option_arr['o_smtp_port'])
					->setSmtpUser($this->option_arr['o_smtp_user'])
					->setSmtpPass($this->option_arr['o_smtp_pass']);
			}
			$pjEmail->setContentType('text/html');
			$from = $this->getAdminEmail();
			$search = array("{Name}", "{Email}", "{Password}", "{Phone}", "{Country}", "{City}", "{State}", "{Zip}", "{Address}");
			$replace = array($arr['name'], $arr['email'], $arr['password'], $arr['phone'], @$arr['country'], @$arr['city'],@$arr['state'], @$arr['zip'], @$arr['address']);
	
			$pjMultiLangModel = pjMultiLangModel::factory();
			if ($arr['email'] != '')
			{
				$lang_subject = $pjMultiLangModel
					->reset()
					->select('t1.*')
					->where('foreign_id', 1)
					->where('t1.model','pjOption')
					->where('t1.locale', $this->getLocaleId())
					->where('t1.field', 'o_email_register_subject')
					->limit(0, 1)
					->findAll()->getData();
				$lang_message = $pjMultiLangModel
					->reset()
					->select('t1.*')
					->where('foreign_id', 1)
					->where('t1.model','pjOption')
					->where('t1.locale', $this->getLocaleId())
					->where('t1.field', 'o_email_register_message')
					->limit(0, 1)
					->findAll()
					->getData();
					
				if (count($lang_message) === 1 && count($lang_subject) === 1)
				{
					$subject = str_replace($search, $replace, $lang_subject[0]['content']);
					$message = str_replace($search, $replace, $lang_message[0]['content']);
	
					$pjEmail
						->setTo($arr['email'])
						->setFrom($from)
						->setSubject($subject)
						->send($message);
				}
			}
			if ($from != "")
			{
				$lang_subject = $pjMultiLangModel
					->reset()
					->select('t1.*')
					->where('foreign_id', 1)
					->where('t1.model','pjOption')
					->where('t1.locale', $this->getLocaleId())
					->where('t1.field', 'o_admin_email_register_subject')
					->limit(0, 1)
					->findAll()
					->getData();
				$lang_message = $pjMultiLangModel
					->reset()
					->select('t1.*')
					->where('foreign_id', 1)
					->where('t1.model','pjOption')
					->where('t1.locale', $this->getLocaleId())
					->where('t1.field', 'o_admin_email_register_message')
					->limit(0, 1)
					->findAll()
					->getData();
					
				if (count($lang_message) === 1 && count($lang_subject) === 1)
				{
					$subject = str_replace($search, $replace, $lang_subject[0]['content']);
					$message = str_replace($search, $replace, $lang_message[0]['content']);
					$pjEmail
						->setTo($from)
						->setFrom($from)
						->setSubject($subject)
						->send($message);
				}
			}
			if(!empty($arr['phone']))
			{
				$lang_message = $pjMultiLangModel
					->reset()
					->select('t1.*')
					->where('foreign_id', 1)
					->where('t1.model','pjOption')
					->where('t1.locale', $this->getLocaleId())
					->where('t1.field', 'o_sms_register_message')
					->limit(0, 1)
					->findAll()
					->getData();
				if (count($lang_message) === 1)
				{
					$message = str_replace($search, $replace, $lang_message[0]['content']);
					$params = array(
							'text' => $message,
							'type' => 'unicode',
							'key' => md5($this->option_arr['private_key'] . PJ_SALT)
					);
					$params['number'] = $arr['phone'];
					$this->requestAction(array('controller' => 'pjSms', 'action' => 'pjActionSend', 'params' => $params), array('return'));
				}
			}
			$admin_phone = $this->getAdminPhone();
			if(!empty($admin_phone))
			{
				$lang_message = $pjMultiLangModel
					->reset()
					->select('t1.*')
					->where('foreign_id', 1)
					->where('t1.model','pjOption')
					->where('t1.locale', $this->getLocaleId())
					->where('t1.field', 'o_admin_sms_register_message')
					->limit(0, 1)
					->findAll()
					->getData();
				if (count($lang_message) === 1)
				{
					$message = str_replace($search, $replace, $lang_message[0]['content']);
					$params = array(
							'text' => $message,
							'type' => 'unicode',
							'key' => md5($this->option_arr['private_key'] . PJ_SALT)
					);
					$params['number'] = $admin_phone;
					$this->requestAction(array('controller' => 'pjSms', 'action' => 'pjActionSend', 'params' => $params), array('return'));
				}
			}
		}
	}
	
	private function pjActionBuildFromSource(&$Image, $item, $watermark=NULL, $watermarkPosition="cc")
	{
		$data = array();
		if (defined("PJ_GALLERY_SMALL") && strpos(PJ_GALLERY_SMALL, ",") !== FALSE)
		{
			$this->imageSizes['small'] = explode(",", preg_replace('/\s+/', '', PJ_GALLERY_SMALL));
		}
		if (defined("PJ_GALLERY_MEDIUM") && strpos(PJ_GALLERY_MEDIUM, ",") !== FALSE)
		{
			$this->imageSizes['medium'] = explode(",", preg_replace('/\s+/', '', PJ_GALLERY_MEDIUM));
		}
		foreach ($this->imageSizes as $key => $d)
		{
			if (isset($item[$key . '_path']) && !empty($item[$key . '_path']))
			{
				$dst = $item[$key . '_path'];
			} else {
				$dst = str_replace(PJ_UPLOAD_PATH . 'source/', PJ_UPLOAD_PATH . $key . '/', $item['source_path']);
			}
			$Image->loadImage(PJ_INSTALL_PATH . $item['source_path']);
			if ($this->imageCrop)
			{
				$Image->setFillColor($this->imageFillColor)->resizeSmart($d[0], $d[1]);
			} else {
				$Image->resizeToWidth($d[0]);
			}
			if (!empty($watermark) && $key != 'small')
			{
				$Image->setWatermark($watermark, $watermarkPosition);
			}
			$Image->saveImage(PJ_INSTALL_PATH . $dst);
			$data[$key . '_path'] = $dst;
			$data[$key . '_size'] = filesize($dst);
			$size = getimagesize($dst);
			$data[$key . '_width'] = $size[0];
			$data[$key . '_height'] = $size[1];
		}
		# Large image
		$dst = str_replace(PJ_UPLOAD_PATH . 'source/', PJ_UPLOAD_PATH . 'large/', $item['source_path']);
		$Image->loadImage(PJ_INSTALL_PATH . $item['source_path']);
		if (!empty($watermark))
		{
		$Image->setWatermark($watermark, $watermarkPosition);
		}
		$Image->saveImage(PJ_INSTALL_PATH . $dst);
		$data['large_path'] = $dst;
		$data['large_size'] = filesize($dst);
		$size = getimagesize($dst);
		$data['large_width'] = $size[0];
		$data['large_height'] = $size[1];
		return $data;
	}
}
?>