/**
  * Edit logged user profile
  *
  * @access public
  * @param void
  * @return null
  */
 function edit_profile()
 {
     $user = Users::findById(get_id());
     if (!$user instanceof User) {
         flash_error(lang('user dnx'));
         $this->redirectTo('dashboard');
     }
     // if
     $company = $user->getCompany();
     if (!$company instanceof Company) {
         flash_error(lang('company dnx'));
         $this->redirectToReferer(get_url('administration'));
     }
     // if
     if (!$user->canUpdateProfile(logged_user())) {
         flash_error(lang('no access permissions'));
         $this->redirectTo('dashboard');
     }
     // if
     $redirect_to = array_var($_GET, 'redirect_to');
     if (trim($redirect_to) == '' || !is_valid_url($redirect_to)) {
         $redirect_to = $user->getCardUrl();
     }
     // if
     tpl_assign('redirect_to', $redirect_to);
     $im_types = ImTypes::findAll(array('order' => '`id`'));
     $user_data = array_var($_POST, 'user');
     if (!is_array($user_data)) {
         $user_data = array('username' => $user->getUsername(), 'email' => $user->getEmail(), 'display_name' => $user->getDisplayName(), 'title' => $user->getTitle(), 'homepage' => $user->getHomepage(), 'office_number' => $user->getOfficeNumber(), 'fax_number' => $user->getFaxNumber(), 'mobile_number' => $user->getMobileNumber(), 'home_number' => $user->getHomeNumber(), 'timezone' => $user->getTimezone(), 'is_admin' => $user->getIsAdmin(), 'auto_assign' => $user->getAutoAssign(), 'use_LDAP' => $user->getUseLDAP(), 'use_gravatar' => $user->getUseGravatar(), 'company_id' => $user->getCompanyId(), 'can_manage_projects' => $user->canManageProjects() ? '1' : '0');
         // array
         if (is_array($im_types)) {
             foreach ($im_types as $im_type) {
                 $user_data['im_' . $im_type->getId()] = $user->getImValue($im_type);
             }
             // forech
         }
         // if
         $default_im = $user->getDefaultImType();
         $user_data['default_im'] = $default_im instanceof ImType ? $default_im->getId() : '';
     }
     // if
     tpl_assign('user', $user);
     tpl_assign('company', $company);
     tpl_assign('user_data', $user_data);
     tpl_assign('im_types', $im_types);
     if (is_array(array_var($_POST, 'user'))) {
         try {
             DB::beginWork();
             if (config_option('check_email_unique', '1') == '1') {
                 if (!$user->validateUniquenessOf('email')) {
                     throw new Error(lang('email address is already used'));
                 }
             }
             $user->setFromAttributes($user_data);
             $user->save();
             $granted = trim(array_var($user_data, 'can_manage_projects')) == '1' ? 1 : 0;
             $user->setPermission(PermissionManager::CAN_MANAGE_PROJECTS, $granted);
             $user->clearImValues();
             foreach ($im_types as $im_type) {
                 $value = trim(array_var($user_data, 'im_' . $im_type->getId()));
                 if ($value != '') {
                     $user_im_value = new UserImValue();
                     $user_im_value->setUserId($user->getId());
                     $user_im_value->setImTypeId($im_type->getId());
                     $user_im_value->setValue($value);
                     $user_im_value->setIsDefault(array_var($user_data, 'default_im') == $im_type->getId());
                     $user_im_value->save();
                 }
                 // if
             }
             // foreach
             DB::commit();
             flash_success(lang('success update profile'));
             $this->redirectToUrl($redirect_to);
         } catch (Exception $e) {
             DB::rollback();
             tpl_assign('error', $e);
         }
         // try
     }
     // if
 }
	/**
	 * Edit specific contact
	 *
	 * @access public
	 * @param void
	 * @return null
	 */
	function edit() {
		if (logged_user()->isGuest()) {
			flash_error(lang('no access permissions'));
			ajx_current("empty");
			return;
		}
		$this->setTemplate('edit_contact');		
		
		$contact = Contacts::findById(get_id());
		if(!($contact instanceof Contact)) {
			flash_error(lang('contact dnx'));
			ajx_current("empty");
			return;
		} // if

		if(!$contact->canEdit(logged_user())) {
			flash_error(lang('no access permissions'));
			ajx_current("empty");
			return;
		} // if

		$im_types = ImTypes::findAll(array('order' => '`id`'));
		$personal_emails = $contact->getContactEmails('personal');
		
		$contact_data = array_var($_POST, 'contact');
		// Populate form fields
		if(!is_array($contact_data)) {
			$contact_data = array(
				'first_name' => $contact->getFirstName(),
				'surname' => $contact->getSurname(),
				'username' => $contact->getUsername(),
				'department' => $contact->getDepartment(),
				'job_title' => $contact->getJobTitle(),
				'email' => $contact->getEmailAddress(),
				'email2' => !is_null($personal_emails) && isset($personal_emails[0]) ? $personal_emails[0]->getEmailAddress() : '',
				'email3' => !is_null($personal_emails) && isset($personal_emails[1])? $personal_emails[1]->getEmailAddress() : '',

				'w_web_page'=> $contact->getWebpageUrl('work'),
				'birthday'=> $contact->getBirthday(),
				'w_phone_number'=> $contact->getPhoneNumber('work', true),
				'w_phone_number2'=> $contact->getPhoneNumber('work'),
				'w_fax_number'=> $contact->getPhoneNumber('fax', true),
				'w_assistant_number'=> $contact->getPhoneNumber('assistant'),
				'w_callback_number'=> $contact->getPhoneNumber('callback'),
				
				'h_web_page'=> $contact->getWebpageUrl('personal'),
				'h_phone_number'=> $contact->getPhoneNumber('home', true),
				'h_phone_number2'=> $contact->getPhoneNumber('home'),
				'h_fax_number'=> $contact->getPhoneNumber('fax'),
				'h_mobile_number'=> $contact->getPhoneNumber('mobile'),
				'h_pager_number'=> $contact->getPhoneNumber('pager'),
				
				'o_web_page'=> $contact->getWebpageUrl('other'),
				'o_phone_number'=> $contact->getPhoneNumber('other',true),
				'o_phone_number2'=> $contact->getPhoneNumber('other'),
				
				'comments' => $contact->getCommentsField(),
				'picture_file' => $contact->getPictureFile(),
                'timezone' => $contact->getTimezone(),
                'company_id' => $contact->getCompanyId(),
      	    ); // array
			
      	    $w_address = $contact->getAddress('work');
			if($w_address){
				$contact_data['w_address'] = $w_address->getStreet();
				$contact_data['w_city'] = $w_address->getCity();
				$contact_data['w_state'] = $w_address->getState();
				$contact_data['w_zipcode'] = $w_address->getZipCode();
				$contact_data['w_country'] = $w_address->getCountry();
			}
			
			$h_address = $contact->getAddress('home');
			if($h_address){
				$contact_data['h_address'] = $h_address->getStreet();
				$contact_data['h_city'] = $h_address->getCity();
				$contact_data['h_state'] = $h_address->getState();
				$contact_data['h_zipcode'] = $h_address->getZipCode();
				$contact_data['h_country'] = $h_address->getCountry();
			}
			
			$o_address = $contact->getAddress('other');
			if($o_address){
				$contact_data['o_address'] = $o_address->getStreet();
				$contact_data['o_city'] = $o_address->getCity();
				$contact_data['o_state'] = $o_address->getState();
				$contact_data['o_zipcode'] = $o_address->getZipCode();
				$contact_data['o_country'] = $o_address->getCountry();
			}

      	    if(is_array($im_types)) {
      	    	foreach($im_types as $im_type) {
      	    		$contact_data['im_' . $im_type->getId()] = $contact->getImValue($im_type);
      	    	} // foreach
      	    } // if

      	    $default_im = $contact->getMainImType();
      	    $contact_data['default_im'] = $default_im instanceof ImType ? $default_im->getId() : '';
		} // if
		
		tpl_assign('isEdit', array_var($_GET, 'isEdit',false));
		tpl_assign('contact', $contact);
		tpl_assign('contact_data', $contact_data);
		tpl_assign('im_types', $im_types);
		
		
		//Contact Submit
		if(is_array(array_var($_POST, 'contact'))) {
			
			try {
				DB::beginWork();
				$contact_data['email']= trim ($contact_data['email']);
				Contacts::validate($contact_data, get_id());
				$newCompany = false;
				if (array_var($contact_data, 'isNewCompany') == 'true' && is_array(array_var($_POST, 'company'))){
					$company_data = array_var($_POST, 'company');

					Contacts::validate($company_data);
					
					$company = new Contact();
					$company->setFromAttributes($company_data);
					$company->setIsCompany(true);
					$company->setObjectName();
					$company->save();
					
					if($company_data['address'] != "")
						$company->addAddress($company_data['address'], $company_data['city'], $company_data['state'], $company_data['country'], $company_data['zipcode'], 'work', true);
					if($company_data['phone_number'] != "") $company->addPhone($company_data['phone_number'], 'work', true);
					if($company_data['fax_number'] != "") $company->addPhone($company_data['fax_number'], 'fax', true);
					if($company_data['homepage'] != "") $company->addWebpage($company_data['homepage'], 'work');
					if($company_data['email'] != "") $company->addEmail($company_data['email'], 'work' , true);
					
					ApplicationLogs::createLog($company,ApplicationLogs::ACTION_ADD);
					$newCompany = true;

				}
				
				$contact_data['birthday'] = getDateValue($contact_data["birthday"]);
				if(isset($contact_data['specify_username'])){
					if($contact_data['user']['username'] != ""){
						$contact_data['name'] = $contact_data['user']['username'];
					}else{
						$contact_data['name'] = $contact_data['first_name']." ".$contact_data['surname'];
					}
				}else{
					$contact_data['name'] = $contact_data['first_name']." ".$contact_data['surname'];
				}
				
				$contact->setFromAttributes($contact_data);
				
				if($newCompany) {
					$contact->setCompanyId($company->getId());
				}
						
				//telephones
			
				$mainPone = $contact->getPhone('work', true);
				if($mainPone){
					$mainPone->editNumber($contact_data['w_phone_number']);
				}else{
					if($contact_data['w_phone_number'] != "") $contact->addPhone($contact_data['w_phone_number'], 'work', true);
				}
				
				$pone2 = $contact->getPhone('work');
				if($pone2){
						$pone2->editNumber($contact_data['w_phone_number2']);
				}else{
					if($contact_data['w_phone_number2'] != "") $contact->addPhone($contact_data['w_phone_number2'], 'work');
				}

				$faxPhone =  $contact->getPhone('fax',true);
				if($faxPhone){
						$faxPhone->editNumber($contact_data['w_fax_number']);
				}else{
					if($contact_data['w_fax_number'] != "") $contact->addPhone($contact_data['w_fax_number'], 'fax', true);
				}
				
				$assistantPhone =  $contact->getPhone('assistant');
				if($assistantPhone){
						$assistantPhone->editNumber($contact_data['w_assistant_number']);
				}else{
					if($contact_data['w_assistant_number'] != "") $contact->addPhone($contact_data['w_assistant_number'], 'assistant');
				}
				
				$callbackPhone =  $contact->getPhone('callback');
				if($callbackPhone){
						$callbackPhone->editNumber($contact_data['w_callback_number']);
				}else{
					if($contact_data['w_callback_number'] != "") $contact->addPhone($contact_data['w_callback_number'], 'callback');
				}
				
				$o_phone = $contact->getPhone('other',true);
				if($o_phone){
						$o_phone->editNumber($contact_data['o_phone_number']);
				}else{
					if($contact_data['o_phone_number'] != "") $contact->addPhone($contact_data['o_phone_number'], 'other', true);
				}
				
				$o_pone2 = $contact->getPhone('other');
				if($o_pone2){
						$o_pone2->editNumber($contact_data['o_phone_number2']);
				}else{
					if($contact_data['o_phone_number2'] != "") $contact->addPhone($contact_data['o_phone_number2'], 'other');
				}

				$h_phone = $contact->getPhone('home', true);
				if($h_phone){
						$h_phone->editNumber($contact_data['h_phone_number']);
				}else{
					if($contact_data['h_phone_number'] != "") $contact->addPhone($contact_data['h_phone_number'], 'home', true);
				}
				
				$h_phone2 = $contact->getPhone('home');
				if($h_phone2){
						$h_phone2->editNumber($contact_data['h_phone_number2']);
				}else{
					if($contact_data['h_phone_number2'] != "") $contact->addPhone($contact_data['h_phone_number2'], 'home');
				}

				$h_faxPhone =  $contact->getPhone('fax');
				if($h_faxPhone){
						$h_faxPhone->editNumber($contact_data['h_fax_number']);
				}else{
					if($contact_data['h_fax_number'] != "") $contact->addPhone($contact_data['h_fax_number'], 'fax');
				}
				
				$h_mobilePhone =  $contact->getPhone('mobile');
				if($h_mobilePhone){
						$h_mobilePhone->editNumber($contact_data['h_mobile_number']);
				}else{
					if($contact_data['h_mobile_number'] != "") $contact->addPhone($contact_data['h_mobile_number'], 'mobile');
				}
				
				$h_pagerPhone =  $contact->getPhone('pager');
				if($h_pagerPhone){
						$h_pagerPhone->editNumber($contact_data['h_pager_number']);
				}else{
					if($contact_data['h_pager_number'] != "") $contact->addPhone($contact_data['h_pager_number'], 'pager');
				}
				
				
				//Emails 
				$personal_email_type_id = EmailTypes::getEmailTypeId('personal');
				$main_emails = ContactEmails::getContactMainEmails($contact, $personal_email_type_id);
				$more_main_emails = array();
				$mail = null;
				foreach ($main_emails as $me) {
					if ($mail == null) $mail = $me;
					else $more_main_emails[] = $me;
				}
				
				if($mail){
					$mail->editEmailAddress($contact_data['email']);
				}else{
					if($contact_data['email'] != "") $contact->addEmail($contact_data['email'], 'personal' , true);
				}
				foreach ($more_main_emails as $mme) {
					$mme->setIsMain(false);
					$mme->save();
				}
				
				$mail2 = !is_null($personal_emails) && isset($personal_emails[0])? $personal_emails[0] : null;
				if($mail2){
						$mail2->editEmailAddress($contact_data['email2']);
				}else{ 
						if($contact_data['email2'] != "") $contact->addEmail($contact_data['email2'], 'personal');
				}
				
				$mail3 = !is_null($personal_emails) && isset($personal_emails[1])? $personal_emails[1] : null;
				if($mail3){
						$mail3->editEmailAddress($contact_data['email3']);
				}else{ 
						if($contact_data['email3'] != "") $contact->addEmail($contact_data['email3'], 'personal');
				}
				
				//Addresses
				
				$w_address = $contact->getAddress('work');
				if($w_address){
					$w_address->edit($contact_data['w_address'], $contact_data['w_city'], $contact_data['w_state'], $contact_data['w_country'], $contact_data['w_zipcode'],2,0);
				}else{
					if($contact_data['w_address'] != "" || $contact_data['w_city'] != "" || $contact_data['w_state'] != "" || $contact_data['w_country'] != "" || $contact_data['w_zipcode'] != "")
						$contact->addAddress($contact_data['w_address'], $contact_data['w_city'], $contact_data['w_state'], $contact_data['w_country'], $contact_data['w_zipcode'], 'work');
				}

				$h_address = $contact->getAddress('home');
				if($h_address){
					$h_address->edit($contact_data['h_address'], $contact_data['h_city'], $contact_data['h_state'], $contact_data['h_country'], $contact_data['h_zipcode'],1,0);
				}else{
					if($contact_data['h_address'] != "" || $contact_data['h_city'] != "" || $contact_data['h_state'] != "" || $contact_data['h_country'] != "" || $contact_data['h_zipcode'] != "")
						$contact->addAddress($contact_data['h_address'], $contact_data['h_city'], $contact_data['h_state'], $contact_data['h_country'], $contact_data['h_zipcode'], 'home');
				}
				
				$o_address = $contact->getAddress('other');
				if($o_address){
					$o_address->edit($contact_data['o_address'], $contact_data['o_city'], $contact_data['o_state'], $contact_data['o_country'], $contact_data['o_zipcode'],3,0);
				}else{
					if($contact_data['o_address'] != "" || $contact_data['o_city'] != "" || $contact_data['o_state'] != "" || $contact_data['o_country'] != "" || $contact_data['o_zipcode'] != "")
						$contact->addAddress($contact_data['o_address'], $contact_data['o_city'], $contact_data['o_state'], $contact_data['o_country'], $contact_data['o_zipcode'], 'other');
				}
				
				//Webpages
				
				$w_homepage = $contact->getWebpage('work');
				if($w_homepage){
						$w_homepage->editWebpageURL($contact_data['w_web_page']);
				}else{
						if($contact_data['w_web_page'] != "") $contact->addWebpage($contact_data['w_web_page'], 'work');
				}

				$h_homepage = $contact->getWebpage('personal');
				if($h_homepage){
						$h_homepage->editWebpageURL($contact_data['h_web_page']);
				}else{
						if($contact_data['h_web_page'] != "") $contact->addWebpage($contact_data['h_web_page'], 'personal');
				}
				
				$o_homepage = $contact->getWebpage('other');
				if($o_homepage){
						$o_homepage->editWebpageURL($contact_data['o_web_page']);
				}else{
						if($contact_data['o_web_page'] != "") $contact->addWebpage($contact_data['o_web_page'], 'other');
				}				

				$contact->setObjectName();
				$contact->save();
				$contact->clearImValues();

				foreach($im_types as $im_type) {
					$value = trim(array_var($contact_data, 'im_' . $im_type->getId()));
					if($value <> '') {

						$contact_im_value = new ContactImValue();

						$contact_im_value->setContactId($contact->getId());
						$contact_im_value->setImTypeId($im_type->getId());
						$contact_im_value->setValue($value);
						$contact_im_value->setIsMain(array_var($contact_data, 'default_im') == $im_type->getId());

						$contact_im_value->save();
					} // if
				} // foreach

				$member_ids = json_decode(array_var($_POST, 'members'));
				$object_controller = new ObjectController();
				if (count($member_ids)){
					$object_controller->add_to_members($contact, $member_ids);
				}
				if ($newCompany) $object_controller->add_to_members($company, $member_ids);
				$object_controller->link_to_new_object($contact);
				$object_controller->add_subscribers($contact);
				$object_controller->add_custom_properties($contact);
				
				ApplicationLogs::createLog($contact, ApplicationLogs::ACTION_EDIT );

				// User settings
				$user = array_var(array_var($_POST, 'contact'),'user');
				if($user){
					$user['username'] = str_replace(" ","",strtolower($name));
					$this->createUserFromContactForm($user, $contact->getId(), $contact->getEmailAddress());

					// Reload contact again due to 'createUserFromContactForm' changes
					Hook::fire("after_contact_quick_add", Contacts::instance()->findById($contact->getId()), $ret);
				}
				
				DB::commit();
				
	     		flash_success(lang('success edit contact', $contact->getObjectName()));
				ajx_current("back");

			} catch(Exception $e) {
				DB::rollback();
				flash_error($e->getMessage());
		  		ajx_current("empty");
			} // try
		} // if
	} // edit
<?php

// telephone types
$all_telephone_types = TelephoneTypes::getAllTelephoneTypesInfo();
// address types
$all_address_types = AddressTypes::getAllAddressTypesInfo();
// webpage types
$all_webpage_types = WebpageTypes::getAllWebpageTypesInfo();
// email types
$all_email_types = EmailTypes::getAllEmailTypesInfo();
// instant messenger types
$im_types = ImTypes::findAll(array('order' => '`id`'));
if (!isset($id_prefix)) {
    $id_prefix = '';
}
?>
<div id="<?php 
echo $genid;
?>
_additional_data" class="additional-data">
	<div class="information-block no-border-bottom">
		
		<div class="input-container">
			<?php 
echo label_tag(lang('birthday'), $genid . 'profileFormBirthday');
?>
			<span style="float:left;"><?php 
echo pick_date_widget2('contact[birthday]', array_var($contact_data, 'birthday'), $genid, 265);
?>
</span>
		</div>
 /**
  *
  * @access public
  * @param void
  * @return null
  */
 function edit()
 {
     $this->setTemplate('add_contact');
     $contact = Contacts::findById(get_id());
     if (!$contact instanceof Contact) {
         flash_error(lang('contact dnx'));
         $this->redirectTo('dashboard', 'contacts');
     }
     // if
     if (!$contact->canEdit(logged_user())) {
         flash_error(lang('no access permissions'));
         $this->redirectTo('dashboard', 'contacts');
     }
     // if
     $im_types = ImTypes::findAll(array('order' => '`id`'));
     $contact_data = array_var($_POST, 'contact');
     $company = $contact->getCompany();
     if (!is_array($contact_data)) {
         $tag_names = null;
         if (plugin_active('tags')) {
             $tag_names = $contact->getTagNames();
         }
         $contact_data = array('display_name' => $contact->getDisplayName(), 'first_name' => $contact->getFirstName(), 'middle_name' => $contact->getMiddleName(), 'last_name' => $contact->getLastName(), 'company_id' => $contact->getCompanyId(), 'title' => $contact->getTitle(), 'email' => $contact->getEmail(), 'timezone' => $contact->getTimezone(), 'office_number' => $contact->getOfficeNumber(), 'fax_number' => $contact->getFaxNumber(), 'mobile_number' => $contact->getMobileNumber(), 'home_number' => $contact->getHomeNumber(), 'food_preferences' => $contact->getFoodPreferences(), 'license_plate' => $contact->getLicensePlate(), 'location_details' => $contact->getLocationDetails(), 'department_details' => $contact->getDepartmentDetails(), 'use_gravatar' => $contact->getUseGravatar(), 'tags' => is_array($tag_names) ? implode(', ', $tag_names) : '');
         // array
         if (is_array($im_types)) {
             foreach ($im_types as $im_type) {
                 $contact_data['im_' . $im_type->getId()] = $contact->getImValue($im_type);
             }
             // forech
         }
         // if
         $default_im = $contact->getDefaultImType();
         $contact_data['default_im'] = $default_im instanceof ImType ? $default_im->getId() : '';
     }
     // if
     tpl_assign('contact', $contact);
     tpl_assign('company', $company);
     tpl_assign('contact_data', $contact_data);
     tpl_assign('im_types', $im_types);
     $avatar = array_var($_FILES, 'new_avatar');
     if (is_array($avatar) && isset($avatar['size']) && $avatar['size'] != 0) {
         try {
             $old_file = $contact->getAvatarPath();
             if (!isset($avatar['name']) || !isset($avatar['type']) || !isset($avatar['size']) || !isset($avatar['tmp_name']) || !is_readable($avatar['tmp_name'])) {
                 throw new InvalidUploadError($avatar, lang('error upload file'));
             }
             // if
             $valid_types = array('image/jpg', 'image/jpeg', 'image/pjpeg', 'image/gif', 'image/png');
             $max_width = config_option('max_avatar_width', 50);
             $max_height = config_option('max_avatar_height', 50);
             if ($avatar['size']) {
                 if (!in_array($avatar['type'], $valid_types) || !($image = getimagesize($avatar['tmp_name']))) {
                     throw new InvalidUploadError($avatar, lang('invalid upload type', 'JPG, GIF, PNG'));
                 } elseif (!$contact->setAvatar($avatar['tmp_name'], $max_width, $max_height, false)) {
                     throw new Error($avatar, lang('error edit avatar'));
                     $contact->setAvatarFile('');
                 }
                 // if
                 if (is_file($old_file)) {
                     @unlink($old_file);
                 }
                 // if
             }
             // if
         } catch (Exception $e) {
             flash_error($e->getMessage());
         }
         // try
     } else {
         if (array_var($contact_data, 'delete_avatar') == "checked") {
             $old_file = $contact->getAvatarPath();
             if (is_file($old_file)) {
                 @unlink($old_file);
             }
             // if
             $contact->setAvatarFile('');
         }
     }
     // if
     if (is_array(array_var($_POST, 'contact'))) {
         try {
             DB::beginWork();
             $contact->setFromAttributes($contact_data);
             $contact->save();
             if (plugin_active('tags')) {
                 $contact->setTagsFromCSV(array_var($contact_data, 'tags'));
             }
             $contact->clearImValues();
             foreach ($im_types as $im_type) {
                 $value = trim(array_var($contact_data, 'im_' . $im_type->getId()));
                 if ($value != '') {
                     $contact_im_value = new ContactImValue();
                     $contact_im_value->setContactId($contact->getId());
                     $contact_im_value->setImTypeId($im_type->getId());
                     $contact_im_value->setValue($value);
                     $contact_im_value->setIsDefault(array_var($contact_data, 'default_im') == $im_type->getId());
                     $contact_im_value->save();
                 }
                 // if
             }
             // foreach
             ApplicationLogs::createLog($contact, null, ApplicationLogs::ACTION_ADD);
             DB::commit();
             flash_success(lang('success edit contact', $contact->getDisplayName()));
             if (!logged_user()->isMemberOfOwnerCompany()) {
                 $this->redirectToUrl(logged_user()->getAccountUrl());
             } else {
                 $this->redirectToUrl($contact->getCompany()->getViewUrl());
                 // Translate to profile page
             }
             // if
         } catch (Exception $e) {
             DB::rollback();
             tpl_assign('error', $e);
         }
         // try
     }
     // if
 }
 /**
  * Edit specific contact
  *
  * @access public
  * @param void
  * @return null
  */
 function edit()
 {
     if (logged_user()->isGuest()) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     $this->setTemplate('edit_contact');
     $contact = Contacts::findById(get_id());
     if (!$contact instanceof Contact) {
         flash_error(lang('contact dnx'));
         ajx_current("empty");
         return;
     }
     // if
     if (!$contact->canEdit(logged_user())) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     // if
     $im_types = ImTypes::findAll(array('order' => '`id`'));
     // telephone types
     $all_telephone_types = TelephoneTypes::getAllTelephoneTypesInfo();
     tpl_assign('all_telephone_types', $all_telephone_types);
     // address types
     $all_address_types = AddressTypes::getAllAddressTypesInfo();
     tpl_assign('all_address_types', $all_address_types);
     // webpage types
     $all_webpage_types = WebpageTypes::getAllWebpageTypesInfo();
     tpl_assign('all_webpage_types', $all_webpage_types);
     // email types
     $all_email_types = EmailTypes::getAllEmailTypesInfo();
     tpl_assign('all_email_types', $all_email_types);
     $contact_data = array_var($_POST, 'contact');
     // Populate form fields
     if (!is_array($contact_data)) {
         // set layout for modal form
         if (array_var($_REQUEST, 'modal')) {
             $this->setLayout("json");
             tpl_assign('modal', true);
         }
         $contact_data = $this->get_contact_data_from_contact($contact);
         if ($contact->isUser()) {
             $_REQUEST['is_user'] = 1;
             tpl_assign('user_type', $contact->getUserType());
         }
         if (is_array($im_types)) {
             foreach ($im_types as $im_type) {
                 $contact_data['im_' . $im_type->getId()] = $contact->getImValue($im_type);
             }
             // foreach
         }
         // if
         $null = null;
         Hook::fire('before_edit_contact_form', array('object' => $contact), $null);
     }
     // if
     tpl_assign('isEdit', array_var($_GET, 'isEdit', false));
     tpl_assign('contact', $contact);
     tpl_assign('contact_data', $contact_data);
     tpl_assign('im_types', $im_types);
     tpl_assign('active_tab', array_var($_REQUEST, 'active_tab'));
     //Contact Submit
     if (is_array(array_var($_POST, 'contact'))) {
         foreach ($contact_data as $k => &$v) {
             $v = remove_scripts($v);
         }
         try {
             DB::beginWork();
             $contact_data['email'] = trim($contact_data['email']);
             $contact_data['contact_type'] = 'contact';
             Contacts::validate($contact_data, get_id());
             $newCompany = false;
             if (array_var($contact_data, 'isNewCompany') == 'true' && is_array(array_var($_POST, 'company'))) {
                 $company_data = array_var($_POST, 'company');
                 $company_data['contact_type'] = 'company';
                 Contacts::validate($company_data);
                 $company = new Contact();
                 $company->setFromAttributes($company_data);
                 $company->setIsCompany(true);
                 $company->setObjectName();
                 $company->save();
                 // save phones, addresses and webpages
                 $this->save_phones_addresses_webpages($company_data, $company);
                 if ($company_data['email'] != "") {
                     $company->addEmail($company_data['email'], 'work', true);
                 }
                 $newCompany = true;
             }
             $contact_data['birthday'] = getDateValue($contact_data["birthday"]);
             if (isset($contact_data['specify_username'])) {
                 if ($contact_data['user']['username'] != "") {
                     $contact_data['name'] = $contact_data['user']['username'];
                 } else {
                     $contact_data['name'] = $contact_data['first_name'] . " " . $contact_data['surname'];
                 }
             } else {
                 $contact_data['name'] = $contact_data['first_name'] . " " . $contact_data['surname'];
             }
             $user_data = array_var($_POST, 'user');
             if (is_array($user_data) && trim(array_var($user_data, 'username', '')) != "") {
                 $contact_data['username'] = trim(array_var($user_data, 'username', ''));
             }
             $contact->setFromAttributes($contact_data);
             if ($newCompany) {
                 $contact->setCompanyId($company->getId());
             }
             $contact->setObjectName();
             $contact->save();
             // save phones, addresses and webpages
             $this->save_phones_addresses_webpages($contact_data, $contact);
             //Emails
             $personal_email_type_id = EmailTypes::getEmailTypeId('personal');
             $main_emails = $contact->getMainEmails();
             $more_main_emails = array();
             $main_mail = null;
             foreach ($main_emails as $me) {
                 if ($main_mail == null) {
                     $main_mail = $me;
                 } else {
                     $more_main_emails[] = $me;
                 }
             }
             if ($main_mail) {
                 $main_mail->editEmailAddress($contact_data['email']);
             } else {
                 if ($contact_data['email'] != "") {
                     $contact->addEmail($contact_data['email'], 'personal', true);
                 }
             }
             foreach ($more_main_emails as $mme) {
                 $mme->setIsMain(false);
                 $mme->save();
             }
             // save additional emails
             $this->save_non_main_emails($contact_data, $contact);
             // autodetect timezone
             $autotimezone = array_var($contact_data, 'autodetect_time_zone', null);
             if ($autotimezone !== null) {
                 set_user_config_option('autodetect_time_zone', $autotimezone, $contact->getId());
             }
             // IM values
             $contact->clearImValues();
             foreach ($im_types as $im_type) {
                 $value = trim(array_var($contact_data, 'im_' . $im_type->getId()));
                 if ($value != '') {
                     $contact_im_value = new ContactImValue();
                     $contact_im_value->setContactId($contact->getId());
                     $contact_im_value->setImTypeId($im_type->getId());
                     $contact_im_value->setValue($value);
                     $contact_im_value->setIsMain(array_var($contact_data, 'default_im') == $im_type->getId());
                     $contact_im_value->save();
                 }
                 // if
             }
             // foreach
             $member_ids = json_decode(array_var($_POST, 'members'));
             $object_controller = new ObjectController();
             if (!is_null($member_ids)) {
                 $object_controller->add_to_members($contact, $member_ids);
             }
             $no_perm_members_ids = json_decode(array_var($_POST, 'no_perm_members'));
             if (count($no_perm_members_ids)) {
                 $object_controller->add_to_members($contact, $no_perm_members_ids);
             }
             if ($newCompany) {
                 $object_controller->add_to_members($company, $member_ids);
             }
             $object_controller->link_to_new_object($contact);
             $object_controller->add_subscribers($contact);
             $object_controller->add_custom_properties($contact);
             // User settings
             $user = array_var(array_var($_POST, 'contact'), 'user');
             if ($user && $contact->canUpdatePermissions(logged_user())) {
                 $user_type_changed = false;
                 if (array_var($user, 'type')) {
                     $user_type_changed = $contact->getUserType() != array_var($user, 'type');
                     $contact->setUserType(array_var($user, 'type'));
                     $contact->save();
                 }
                 if ($user_type_changed) {
                     $this->cut_max_user_permissions($contact);
                 }
                 // update user groups
                 if (isset($_REQUEST['user_groups'])) {
                     $insert_values = "";
                     $group_ids = explode(',', $_REQUEST['user_groups']);
                     foreach ($group_ids as $gid) {
                         if (trim($gid) == "" || !is_numeric($gid)) {
                             continue;
                         }
                         $insert_values .= ($insert_values == "" ? "" : ",") . "(" . $contact->getId() . ", {$gid})";
                     }
                     ContactPermissionGroups::instance()->delete("contact_id=" . $contact->getId() . " AND permission_group_id <> " . $contact->getPermissionGroupId());
                     if ($insert_values != "") {
                         DB::execute("INSERT INTO " . TABLE_PREFIX . "contact_permission_groups VALUES {$insert_values} ON DUPLICATE KEY UPDATE contact_id=contact_id;");
                     }
                     ContactMemberCaches::updateContactMemberCacheAllMembers($contact);
                 }
             }
             $null = null;
             Hook::fire('after_edit_contact', $contact, $null);
             DB::commit();
             // save user permissions
             if ($user && $contact->canUpdatePermissions(logged_user())) {
                 save_user_permissions_background(logged_user(), $contact->getPermissionGroupId(), $contact->isGuest());
             }
             if (array_var($contact_data, 'isNewCompany') == 'true' && is_array(array_var($_POST, 'company'))) {
                 ApplicationLogs::createLog($company, ApplicationLogs::ACTION_ADD);
             }
             ApplicationLogs::createLog($contact, ApplicationLogs::ACTION_EDIT);
             flash_success(lang('success edit contact', $contact->getObjectName()));
             ajx_current("back");
             if (array_var($_REQUEST, 'modal')) {
                 evt_add("reload current panel");
             }
         } catch (Exception $e) {
             DB::rollback();
             flash_error($e->getMessage());
             ajx_current("empty");
         }
         // try
     }
     // if
 }
 /**
  * Adds contact to project (as a PageAttachment)
  *
  * @param void
  * @return null
  */
 function add_contact()
 {
     if (!active_project()->canChangePermissions(logged_user())) {
         flash_error(lang('no access permissions'));
         $this->redirectToReferer(active_project()->getOverviewUrl());
     }
     // if
     $already_attached_contacts = PageAttachments::getAttachmentsByTypeAndProject(array('Contacts'), active_project());
     $already_attached_contacts_ids = null;
     if (is_array($already_attached_contacts)) {
         $already_attached_contacts_ids = array();
         foreach ($already_attached_contacts as $already_attached_contact) {
             $already_attached_contacts_ids[] = $already_attached_contact->getRelObjectId();
         }
         // foreach
     }
     // if
     $this->setTemplate('add_contact');
     $contact = new Contact();
     $im_types = ImTypes::findAll(array('order' => '`id`'));
     $contact_data = array_var($_POST, 'contact');
     if (!is_array($contact_data)) {
         $contact_data = array();
         // array
     }
     // if
     $existing_contact_data = array_var($contact_data, 'existing');
     if (!is_array($existing_contact_data)) {
         $existing_contact_data = array();
         // array
     }
     // if
     $new_contact_data = array_var($contact_data, 'new');
     if (!is_array($new_contact_data)) {
         $new_contact_data = array();
         // array
     }
     // if
     $company_data = array_var($new_contact_data, 'company');
     if (!is_array($company_data)) {
         $company_data = array();
         // array
     }
     // if
     $user_data = array_var($new_contact_data, 'user');
     if (!is_array($user_data)) {
         $user_data = array();
         // array
     }
     // if
     $project_init = array_var($_GET, 'project_init');
     tpl_assign('already_attached_contacts_ids', $already_attached_contacts_ids);
     tpl_assign('contact', $contact);
     tpl_assign('contact_data', $contact_data);
     tpl_assign('existing_contact_data', $existing_contact_data);
     tpl_assign('new_contact_data', $new_contact_data);
     tpl_assign('company_data', $company_data);
     tpl_assign('user_data', $user_data);
     tpl_assign('project_init', $project_init);
     tpl_assign('im_types', $im_types);
     tpl_assign('project', active_project());
     if (is_array(array_var($_POST, 'contact'))) {
         if (array_var($contact_data, 'what') == 'existing') {
             if (!Contacts::findById(array_var($existing_contact_data, 'rel_object_id')) instanceof Contact) {
                 tpl_assign('error', new FormSubmissionErrors(array(lang('existing contact required'))));
             } else {
                 $page_attachment = new PageAttachment();
                 $page_attachment->setFromAttributes($existing_contact_data);
                 $page_attachment->setRelObjectManager('Contacts');
                 $page_attachment->setProjectId(active_project()->getId());
                 $page_attachment->setPageName('people');
                 $page_attachment->save();
                 PageAttachments::reorder('people', active_project());
                 flash_success(lang('success add contact', $page_attachment->getObject()->getDisplayName()));
                 if ($project_init) {
                     $this->redirectToUrl(active_project()->getAddContactUrl(array('project_init' => '1')));
                 } else {
                     $this->redirectToUrl(get_url('project', 'people'));
                 }
                 // if
             }
             // if
         } else {
             // New contact
             // Save avatar
             $avatar = array_var($_FILES, 'new_avatar');
             if (is_array($avatar) && isset($avatar['size']) && $avatar['size'] != 0) {
                 try {
                     if (!isset($avatar['name']) || !isset($avatar['type']) || !isset($avatar['size']) || !isset($avatar['tmp_name']) || !is_readable($avatar['tmp_name'])) {
                         throw new InvalidUploadError($avatar, lang('error upload file'));
                     }
                     // if
                     $valid_types = array('image/jpg', 'image/jpeg', 'image/pjpeg', 'image/gif', 'image/png');
                     $max_width = config_option('max_avatar_width', 50);
                     $max_height = config_option('max_avatar_height', 50);
                     if ($avatar['size']) {
                         if (!in_array($avatar['type'], $valid_types) || !($image = getimagesize($avatar['tmp_name']))) {
                             throw new InvalidUploadError($avatar, lang('invalid upload type', 'JPG, GIF, PNG'));
                         } elseif (!$contact->setAvatar($avatar['tmp_name'], $max_width, $max_height, false)) {
                             throw new Error($avatar, lang('error edit avatar'));
                             $contact->setAvatarFile('');
                         }
                         // if
                     }
                     // if
                 } catch (Exception $e) {
                     flash_error($e->getMessage());
                 }
             } else {
                 $contact->setAvatarFile('');
             }
             // if
             try {
                 DB::beginWork();
                 $contact->setFromAttributes($new_contact_data);
                 if (array_var($company_data, 'what') == 'existing') {
                     $company_id = $new_contact_data['company_id'];
                 } else {
                     $company = new Company();
                     $company->setName(array_var($company_data, 'name'));
                     $company->setTimezone(array_var($company_data, 'timezone'));
                     $company->setClientOfId(owner_company()->getId());
                     $company->save();
                     $company_id = $company->getId();
                 }
                 // if
                 $contact->setCompanyId($company_id);
                 // User account info
                 if (array_var($user_data, 'add_account') == "yes") {
                     $user = new User();
                     $user->setFromAttributes($user_data);
                     if (array_var($user_data, 'password_generator') == 'random') {
                         // Generate random password
                         $password = substr(sha1(uniqid(rand(), true)), rand(0, 25), 13);
                     } else {
                         // Validate user input
                         $password = array_var($user_data, 'password');
                         if (trim($password) == '') {
                             throw new Error(lang('password value required'));
                         }
                         // if
                         if ($password != array_var($user_data, 'password_a')) {
                             throw new Error(lang('passwords dont match'));
                         }
                         // if
                     }
                     // if
                     $user->setPassword($password);
                     $user->save();
                     $contact->setUserId($user->getId());
                 } else {
                     $contact->setUserId(0);
                 }
                 // if
                 $contact->save();
                 if (plugin_active('tags')) {
                     $contact->setTagsFromCSV(array_var($new_contact_data, 'tags'));
                 }
                 $contact->clearImValues();
                 foreach ($im_types as $im_type) {
                     $value = trim(array_var($new_contact_data, 'im_' . $im_type->getId()));
                     if ($value != '') {
                         $contact_im_value = new ContactImValue();
                         $contact_im_value->setContactId($contact->getId());
                         $contact_im_value->setImTypeId($im_type->getId());
                         $contact_im_value->setValue($value);
                         $contact_im_value->setIsDefault(array_var($new_contact_data, 'default_im') == $im_type->getId());
                         $contact_im_value->save();
                     }
                     // if
                 }
                 // foreach
                 ApplicationLogs::createLog($contact, null, ApplicationLogs::ACTION_ADD);
                 $page_attachment = new PageAttachment();
                 $page_attachment->setFromAttributes($new_contact_data);
                 $page_attachment->setRelObjectId($contact->getId());
                 $page_attachment->setRelObjectManager('Contacts');
                 $page_attachment->setProjectId(active_project()->getId());
                 $page_attachment->setPageName('people');
                 $page_attachment->save();
                 PageAttachments::reorder('people', active_project());
                 DB::commit();
                 // Send notification...
                 try {
                     if (array_var($user_data, 'add_account') == "yes" && array_var($user_data, 'send_email_notification')) {
                         Notifier::newUserAccount($user, $password);
                     }
                     // if
                 } catch (Exception $e) {
                 }
                 // try
                 flash_success(lang('success add contact', $contact->getDisplayName()));
                 if ($project_init) {
                     $this->redirectToUrl(active_project()->getAddContactUrl(array('project_init' => '1')));
                 } else {
                     $this->redirectToUrl(get_url('project', 'people'));
                 }
                 // if
             } catch (Exception $e) {
                 DB::rollback();
                 tpl_assign('error', $e);
             }
             // try
         }
         // if
     }
     // if
 }
 /**
  * Edit specific contact
  *
  * @access public
  * @param void
  * @return null
  */
 function edit()
 {
     if (logged_user()->isGuest()) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     $this->setTemplate('edit_contact');
     if (active_project() instanceof Project) {
         tpl_assign('isAddProject', true);
     }
     $contact = Contacts::findById(get_id());
     if (!$contact instanceof Contact) {
         flash_error(lang('contact dnx'));
         ajx_current("empty");
         return;
     }
     // if
     if (!$contact->canEdit(logged_user())) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     // if
     $im_types = ImTypes::findAll(array('order' => '`id`'));
     $active_project = active_project();
     $role = "";
     if ($active_project) {
         $pc = $contact->getRole(active_project());
         if ($pc instanceof ProjectContact) {
             $role = $pc->getRole();
         }
     }
     $contact_data = array_var($_POST, 'contact');
     if (!is_array($contact_data)) {
         $tag_names = $contact->getTagNames();
         $contact_data = array('firstname' => $contact->getFirstName(), 'lastname' => $contact->getLastName(), 'middlename' => $contact->getMiddleName(), 'department' => $contact->getDepartment(), 'job_title' => $contact->getJobTitle(), 'email' => $contact->getEmail(), 'email2' => $contact->getEmail2(), 'email3' => $contact->getEmail3(), 'w_web_page' => $contact->getWWebPage(), 'w_address' => $contact->getWAddress(), 'w_city' => $contact->getWCity(), 'w_state' => $contact->getWState(), 'w_zipcode' => $contact->getWZipcode(), 'w_country' => $contact->getWCountry(), 'w_phone_number' => $contact->getWPhoneNumber(), 'w_phone_number2' => $contact->getWPhoneNumber2(), 'w_fax_number' => $contact->getWFaxNumber(), 'w_assistant_number' => $contact->getWAssistantNumber(), 'w_callback_number' => $contact->getWCallbackNumber(), 'h_web_page' => $contact->getHWebPage(), 'h_address' => $contact->getHAddress(), 'h_city' => $contact->getHCity(), 'h_state' => $contact->getHState(), 'h_zipcode' => $contact->getHZipcode(), 'h_country' => $contact->getHCountry(), 'h_phone_number' => $contact->getHPhoneNumber(), 'h_phone_number2' => $contact->getHPhoneNumber2(), 'h_fax_number' => $contact->getHFaxNumber(), 'h_mobile_number' => $contact->getHMobileNumber(), 'h_pager_number' => $contact->getHPagerNumber(), 'o_web_page' => $contact->getOWebPage(), 'o_address' => $contact->getOAddress(), 'o_city' => $contact->getOCity(), 'o_state' => $contact->getOState(), 'o_zipcode' => $contact->getOZipcode(), 'o_country' => $contact->getOCountry(), 'o_phone_number' => $contact->getOPhoneNumber(), 'o_phone_number2' => $contact->getOPhoneNumber2(), 'o_fax_number' => $contact->getOFaxNumber(), 'o_birthday' => $contact->getOBirthday(), 'picture_file' => $contact->getPictureFile(), 'timezone' => $contact->getTimezone(), 'notes' => $contact->getNotes(), 'is_private' => $contact->getIsPrivate(), 'company_id' => $contact->getCompanyId(), 'role' => $role, 'tags' => is_array($tag_names) ? implode(', ', $tag_names) : '');
         // array
         if (is_array($im_types)) {
             foreach ($im_types as $im_type) {
                 $contact_data['im_' . $im_type->getId()] = $contact->getImValue($im_type);
             }
             // forech
         }
         // if
         $default_im = $contact->getDefaultImType();
         $contact_data['default_im'] = $default_im instanceof ImType ? $default_im->getId() : '';
     }
     // if
     tpl_assign('contact', $contact);
     tpl_assign('contact_data', $contact_data);
     tpl_assign('im_types', $im_types);
     if (is_array(array_var($_POST, 'contact'))) {
         //	MANAGE CONCURRENCE WHILE EDITING
         $upd = array_var($_POST, 'updatedon');
         if ($upd && $contact->getUpdatedOn()->getTimestamp() > $upd && !array_var($_POST, 'merge-changes') == 'true') {
             ajx_current('empty');
             evt_add("handle edit concurrence", array("updatedon" => $contact->getUpdatedOn()->getTimestamp(), "genid" => array_var($_POST, 'genid')));
             return;
         }
         if (array_var($_POST, 'merge-changes') == 'true') {
             $this->setTemplate('card');
             $new_contact = Contacts::findById($contact->getId());
             ajx_set_panel(lang('tab name', array('name' => $new_contact->getDisplayName())));
             ajx_extra_data(array("title" => $new_contact->getDisplayName(), 'icon' => 'ico-contact'));
             ajx_set_no_toolbar(true);
             //ajx_set_panel(lang ('tab name',array('name'=>$new_contact->getDisplayName())));
             return;
         }
         try {
             DB::beginWork();
             $newCompany = false;
             if (array_var($contact_data, 'isNewCompany') == 'true' && is_array(array_var($_POST, 'company'))) {
                 $company_data = array_var($_POST, 'company');
                 $company = new Company();
                 $company->setFromAttributes($company_data);
                 $company->setClientOfId(1);
                 $company->save();
                 ApplicationLogs::createLog($company, null, ApplicationLogs::ACTION_ADD);
                 $newCompany = true;
                 if (active_project() instanceof Project && $company->canAdd(logged_user(), active_project())) {
                     $company->addToWorkspace(active_project());
                 } else {
                     $company->addToWorkspace(logged_user()->getPersonalProject());
                 }
             }
             $contact_data['o_birthday'] = getDateValue(array_var($contact_data, "o_birthday_value", ''));
             $contact->setFromAttributes($contact_data);
             /*if (!is_null($contact->getOBirthday()) && $contact_data["o_birthday_year"] == 0){
             			$contact->setOBirthday(null);
             		} else if ($contact_data["o_birthday_year"] != 0) {
             			$bday = new DateTimeValue(0);
             			$bday->setYear($contact_data["o_birthday_year"]);
             			$bday->setMonth($contact_data["o_birthday_month"]);
             			$bday->setDay($contact_data["o_birthday_day"]);
             			$contact->setOBirthday($bday);
             		}*/
             if ($newCompany) {
                 $contact->setCompanyId($company->getId());
             }
             $contact->save();
             $contact->setTagsFromCSV(array_var($contact_data, 'tags'));
             $contact->clearImValues();
             foreach ($im_types as $im_type) {
                 $value = trim(array_var($contact_data, 'im_' . $im_type->getId()));
                 if ($value != '') {
                     $contact_im_value = new ContactImValue();
                     $contact_im_value->setContactId($contact->getId());
                     $contact_im_value->setImTypeId($im_type->getId());
                     $contact_im_value->setValue($value);
                     $contact_im_value->setIsDefault(array_var($contact_data, 'default_im') == $im_type->getId());
                     $contact_im_value->save();
                 }
                 // if
             }
             // foreach
             $object_controller = new ObjectController();
             $object_controller->add_to_workspaces($contact, !can_manage_contacts(logged_user()));
             $object_controller->link_to_new_object($contact);
             $object_controller->add_subscribers($contact);
             $object_controller->add_custom_properties($contact);
             ApplicationLogs::createLog($contact, null, ApplicationLogs::ACTION_EDIT);
             DB::commit();
             if (trim(array_var($contact_data, 'role', '')) != '' && active_project() instanceof Project) {
                 if (!ProjectContact::canAdd(logged_user(), active_project())) {
                     flash_error(lang('error contact added but not assigned', $contact->getDisplayName(), active_project()->getName()));
                     ajx_current("back");
                     return;
                 }
                 // if
                 $pc = $contact->getRole(active_project());
                 if (!$pc instanceof ProjectContact) {
                     $pc = new ProjectContact();
                     $pc->setContactId($contact->getId());
                     $pc->setProjectId(active_project()->getId());
                 }
                 $pc->setRole(array_var($contact_data, 'role'));
                 $pc->save();
                 //ApplicationLogs::createLog($contact, $contact->getWorkspaces(), ApplicationLogs::ACTION_ADD);
             }
             flash_success(lang('success edit contact', $contact->getDisplayName()));
             ajx_current("back");
         } catch (Exception $e) {
             DB::rollback();
             flash_error($e->getMessage());
             ajx_current("empty");
         }
         // try
     }
     // if
 }