/**
  * 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
 }
 /**
  *
  * @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');
     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
 }