public function execute()
 {
     $system = wa();
     $datetime = $system->getDateTime();
     if (!($this->id = (int) waRequest::get('id'))) {
         throw new waException('No id specified.');
     }
     $user = $this->getUser()->getRights('contacts', 'backend');
     $admin = $user >= 2;
     $ownProfile = $this->id == wa()->getUser()->getId();
     $cr = new contactsRightsModel();
     if (!$cr->getRight(null, $this->id)) {
         if ($user && $ownProfile) {
             $this->view->assign('readonly', true);
         } else {
             throw new waRightsException('Access denied.');
         }
     }
     $this->getContactInfo();
     $this->getUserInfo();
     // free or premium app?
     $this->view->assign('versionFull', $this->getConfig()->getInfo('edition') === 'full');
     // collect data from other applications to show in tabs (for premium app only)
     if ($this->getConfig()->getInfo('edition') === 'full') {
         $links = array();
         foreach (wa()->event('profile.tab', $this->id) as $app_id => $one_or_more_links) {
             if (!isset($one_or_more_links['html'])) {
                 $i = '';
                 foreach ($one_or_more_links as $link) {
                     $key = isset($link['id']) ? $link['id'] : $app_id . $i;
                     $links[$key] = $link;
                     $i++;
                 }
             } else {
                 $key = isset($one_or_more_links['id']) ? $one_or_more_links['id'] : $app_id;
                 $links[$key] = $one_or_more_links;
             }
         }
         $this->view->assign('links', $links);
     }
     // tab to open by default
     $this->view->assign('tab', waRequest::get('tab'));
     $this->view->assign('admin', $admin);
     $this->view->assign('superadmin', $admin && $this->getUser()->getRights('webasyst', 'backend'));
     $this->view->assign('current_user_id', wa()->getUser()->getId());
     $this->view->assign('limitedCategories', $admin || $this->getRights('category.all') ? 0 : 1);
     // Update history
     if (($name = $this->contact->get('name')) || $name === '0') {
         $name = trim($this->contact->get('title') . ' ' . $name);
         $history = new contactsHistoryModel();
         $history->save('/contact/' . $this->id, $name);
     }
     // Update history in user's browser
     $historyModel = new contactsHistoryModel();
     $this->view->assign('history', $historyModel->get());
     $this->view->assign('wa_view', $this->view);
 }
 public function execute()
 {
     $superadmin = $this->getUser()->getRights('webasyst', 'backend');
     $contacts = waRequest::post('id', array(), 'array_int');
     // do not try to delete self
     if (in_array($this->getUser()->getId(), $contacts)) {
         throw new waRightsException('Access denied: attempt to delete own account.');
     }
     $this->getRights();
     $crm = new contactsRightsModel();
     $contacts = $crm->getAllowedContactsIds($contacts);
     if (!$contacts) {
         throw new waRightsException('Access denied: no access to contacts ');
     }
     // Deletion of contacts with links to other applications is only allowed to superadmins
     if (!$superadmin && ($links = wa()->event('links', $contacts))) {
         foreach ($links as $app_id => $l) {
             foreach ($l as $contact_id => $contact_links) {
                 if ($contact_links) {
                     throw new waRightsException('Access denied: only superadmin is allowed to delete contacts with links to other applications.');
                 }
             }
         }
     }
     // Are there users among $contacts?
     $um = new waUserModel();
     $users = array_keys($um->getByField(array('id' => $contacts, 'is_user' => 1), 'id'));
     // deletion of users is only allowed to superadmins
     if (!$superadmin && $users) {
         throw new waRightsException('Access denied: only superadmin is allowed to delete users.');
     }
     // Revoke user access before deletion
     foreach ($users as $user_id) {
         waUser::revokeUser($user_id);
     }
     $contact_model = new waContactModel();
     $cnt = count($contacts);
     if ($cnt > 30) {
         $log_params = $cnt;
     } else {
         // contact names
         $log_params = $contact_model->getName($contacts);
     }
     $history_model = new contactsHistoryModel();
     foreach ($contacts as $contact_id) {
         $history_model->deleteByField(array('type' => 'add', 'hash' => '/contact/' . $contact_id));
     }
     // Bye bye...
     $contact_model->delete($contacts);
     // also throws a contacts.delete event
     $this->response['deleted'] = $cnt;
     $this->response['message'] = sprintf(_w("%d contact has been deleted", "%d contacts have been deleted", $this->response['deleted']), $this->response['deleted']);
     $this->logAction('contact_delete', $log_params);
 }
 public function execute()
 {
     $this->view->assign('views', null);
     $this->view->assign('settings', $this->getUser()->getSettings('contacts'));
     $historyModel = new contactsHistoryModel();
     $this->view->assign('history', $historyModel->get());
     $cc = new contactsCollection();
     $this->view->assign('totalContacts', $cc->count());
     // only show categories available to current user
     //        $crm = new contactsRightsModel();
     $wcrm = new waContactRightsModel();
     $ccm = new waContactCategoryModel();
     //        $allowed = $crm->getAllowedCategories();
     //        $categories = array();
     //        if($allowed === true) {
     //            $categories = $ccm->getAll();
     //        } else if ($allowed) {
     //            foreach($ccm->getAll() as $cat) {
     //                if (isset($allowed[$cat['id']])) {
     //                    $categories[] = $cat;
     //                }
     //            }
     //        }
     $categories = $ccm->getAll();
     $this->view->assign('categories', $categories);
     // User views are only available to global admin
     $r = new waContactRightsModel();
     $this->view->assign('superadmin', FALSE);
     $this->view->assign('admin', FALSE);
     if (wa()->getUser()->getRights('webasyst', 'backend')) {
         $this->view->assign('superadmin', TRUE);
         $this->view->assign('admin', TRUE);
         //            $group_model = new waGroupModel();
         //            $this->view->assign('groups', $group_model->getAll());
         $cc = new contactsCollection('/users/all/');
         $this->view->assign('totalUsers', $cc->count());
     } else {
         if (wa()->getUser()->getRights('contacts', 'backend') >= 2) {
             $this->view->assign('admin', TRUE);
         }
     }
     // is user allowed to add contacts?
     $this->view->assign('show_create', $wcrm->get(null, null, 'create'));
     $event_params = array();
     $this->view->assign('backend_sidebar', wa()->event('backend_sidebar', $event_params, array('top_li')));
 }
 public function execute()
 {
     $historyModel = new contactsHistoryModel();
     if ($fix = (int) waRequest::get('fix')) {
         $position = (int) waRequest::get('position');
         $historyModel->fix($fix, $position);
         $this->response['fixed'] = $fix;
     }
     if ($unfix = (int) waRequest::get('unfix')) {
         $historyModel->fix($unfix, 0);
         $this->response['unfixed'] = $unfix;
     }
     if (waRequest::get('clear')) {
         $type = waRequest::get('ctype');
         $historyModel->prune(0, $type);
         $this->response['cleared'] = 1;
     }
 }
 public function execute()
 {
     $id = $this->getId();
     // Delete the old photos if they exist
     $oldDir = wa()->getDataPath(waContact::getPhotoDir($id), TRUE);
     if (file_exists($oldDir)) {
         waFiles::delete($oldDir);
     }
     // Update record in DB for this user
     $contact = new waContact($id);
     $contact['photo'] = 0;
     $contact->save();
     // Update recent history to reload thumbnail correctly (if not called from personal account)
     if (wa()->getUser()->get('is_user')) {
         $history = new contactsHistoryModel();
         $history->save('/contact/' . $id, null, null, '--');
     }
     $this->response = array('done' => 1, 'url' => $contact->getPhoto());
 }
 public function execute()
 {
     $this->response = array();
     // Initialize all needed post vars as $vars in current namespace
     foreach (array('x1', 'y1', 'x2', 'y2', 'w', 'h', 'ww', 'orig') as $var) {
         if (null === (${$var} = (int) waRequest::post($var))) {
             // $$ black magic...
             $this->response['error'] = 'wrong parameters';
             return;
         }
     }
     $id = $this->getId();
     $contact = new waContact($id);
     // Path to file we need to crop
     $rand = mt_rand();
     $dir = waContact::getPhotoDir($id, true);
     $filename = wa()->getDataPath("{$dir}{$rand}.original.jpg", true, 'contacts');
     $oldDir = wa()->getDataPath("{$dir}", true, 'contacts');
     $no_old_photo = false;
     if (!$orig) {
         // Delete the old photos if they exist
         if (file_exists($oldDir)) {
             waFiles::delete($oldDir);
             $no_old_photo = true;
         }
         waFiles::create($oldDir);
         // Is there an uploaded file in session?
         $photoEditors = $this->getStorage()->read('photoEditors');
         if (!isset($photoEditors[$id]) || !file_exists($photoEditors[$id])) {
             $this->response['error'] = 'Photo editor session is not found or already expired.';
             return;
         }
         $newFile = $photoEditors[$id];
         // Save the original image in jpeg for future use
         try {
             $img = waImage::factory($newFile)->save($filename);
         } catch (Exception $e) {
             $this->response['error'] = 'Unable to save new file ' . $filename . ' (' . pathinfo($filename, PATHINFO_EXTENSION) . ') as jpeg: ' . $e->getMessage();
             return;
         }
         // Remove uploaded file
         unset($photoEditors[$id]);
         $this->getStorage()->write('photoEditors', $photoEditors);
         unlink($newFile);
     } else {
         // cropping an old file. Move it temporarily to temp dir to delete all cached thumbnails
         $oldFile = wa()->getDataPath("{$dir}{$contact['photo']}.original.jpg", TRUE, 'contacts');
         $tempOldFile = wa()->getTempPath("{$id}/{$rand}.original.jpg", 'contacts');
         waFiles::move($oldFile, $tempOldFile);
         // Delete thumbnails
         if (file_exists($oldDir)) {
             waFiles::delete($oldDir);
         }
         waFiles::create($oldDir);
         // return original image to its proper place
         waFiles::move($tempOldFile, $filename);
     }
     if (!file_exists($filename)) {
         $this->response['error'] = 'Image to crop not found (check directory access rights).';
         return;
     }
     // Crop and save selected area
     $croppedFilename = wa()->getDataPath("{$dir}{$rand}.jpg", TRUE, 'contacts');
     try {
         $img = waImage::factory($filename);
         $scale = $img->width / $ww;
         $img->crop(floor($w * $scale), floor($h * $scale), floor($x1 * $scale), floor($y1 * $scale))->save($croppedFilename);
     } catch (Exception $e) {
         $this->response['error'] = 'Unable to crop an image: ' . $e->getMessage();
         return;
     }
     // Update record in DB for this user
     $contact['photo'] = $rand;
     $contact->save();
     if ($no_old_photo) {
         $old_app = null;
         if (wa()->getApp() !== 'contacts') {
             $old_app = wa()->getApp();
             waSystem::setActive('contacts');
         }
         $this->logAction('photo_add', null, $contact->getId());
         if ($old_app) {
             waSystem::setActive($old_app);
         }
     }
     // Update recent history to reload thumbnail correctly (if not called from personal account)
     if (wa()->getUser()->get('is_user')) {
         $history = new contactsHistoryModel();
         $history->save('/contact/' . $id, null, null, '--');
     }
     $this->response = array('url' => $contact->getPhoto());
 }
 public function execute()
 {
     $system = wa();
     $datetime = $system->getDateTime();
     $user = $this->getUser()->getRights('contacts', 'backend');
     $admin = $user >= 2;
     $cr = new contactsRightsModel();
     if (!empty($this->params['limited_own_profile'])) {
         $this->id = wa()->getUser()->getId();
         $this->view->assign('limited_own_profile', true);
         $this->view->assign('save_url', '?module=profile&action=save');
         $this->view->assign('password_save_url', '?module=profile&action=password');
         $this->view->assign('save_geocoords_url', '?module=profile&action=saveGeocoords');
         $this->view->assign('photo_upload_url', '?module=profile&action=tmpimage');
         $this->view->assign('photo_editor_url', '?module=profile&action=photo');
         $this->view->assign('photo_editor_uploaded_url', '?module=profile&action=photo&uploaded=1');
     } else {
         $this->id = (int) waRequest::get('id');
         if (empty($this->id)) {
             throw new waException('No id specified.');
         }
         $r = $cr->getRight(null, $this->id);
         //var_dump($r );exit;
         if (!$r) {
             throw new waRightsException(_w('Access denied'));
         } else {
             $this->view->assign('readonly', $r === 'read');
         }
     }
     $exists = $this->getContactInfo();
     if ($exists) {
         $this->getUserInfo();
         $this->view->assign('last_view_context', $this->getLastViewContext());
         // collect data from other applications to show in tabs
         if (empty($this->params['limited_own_profile'])) {
             $links = array();
             foreach (wa()->event('profile.tab', $this->id) as $app_id => $one_or_more_links) {
                 if (!isset($one_or_more_links['html'])) {
                     $i = '';
                     foreach ($one_or_more_links as $link) {
                         $key = isset($link['id']) ? $link['id'] : $app_id . $i;
                         $links[$key] = $link;
                         $i++;
                     }
                 } else {
                     $key = isset($one_or_more_links['id']) ? $one_or_more_links['id'] : $app_id;
                     $links[$key] = $one_or_more_links;
                 }
             }
             $this->view->assign('links', $links);
         }
         // tab to open by default
         $this->view->assign('tab', waRequest::get('tab'));
         $this->view->assign('admin', $admin);
         $this->view->assign('superadmin', $admin && $this->getUser()->getRights('webasyst', 'backend'));
         $this->view->assign('current_user_id', wa()->getUser()->getId());
         $this->view->assign('can_edit', $cr->getRight(null, $this->id));
         // Update history
         if (empty($this->params['limited_own_profile'])) {
             $name = $this->contact->get('name');
             if ($name || $name === '0') {
                 $history = new contactsHistoryModel();
                 $history->save('/contact/' . $this->id, $name);
             }
             // Update history in user's browser
             $historyModel = new contactsHistoryModel();
             $this->view->assign('history', $historyModel->get());
         }
         $this->view->assign('wa_view', $this->view);
         $this->view->assign('access_disable_msg', contactsHelper::getAccessDisableMsg($this->contact));
         $this->view->assign('my_url', wa()->getRootUrl(true) . 'my/');
         $this->view->assign('backend_url', wa()->getRootUrl(true) . wa()->getConfig()->getBackendUrl(false) . '/');
         $this->view->assign('static_url', wa()->getAppStaticUrl('contacts'));
     }
     $this->view->assign('exists', $exists);
     if ($this->getRequest()->request('standalone')) {
         /**
          * Include plugins js and css
          * @event backend_assets
          * @return array[string]string $return[%plugin_id%]
          */
         $this->view->assign('backend_assets', wa()->event('backend_assets'));
     }
     $auth = wa()->getAuthConfig();
     $this->view->assign('personal_portal_available', !empty($auth['app']));
     /*
      * @event backend_contact_info
      * @return array[string]array $return[%plugin_id%] array of html output
      * @return array[string][string]string $return[%plugin_id%]['after_header'] html output
      * @return array[string][string]string $return[%plugin_id%]['header'] html output
      * @return array[string][string]string $return[%plugin_id%]['before_header'] html output
      * @return array[string][string]string $return[%plugin_id%]['before_top'] html output
      * @return array[string][string]string $return[%plugin_id%]['top'] html output
      * @return array[string][string]string $return[%plugin_id%]['after_top'] html output
      * @return array[string][string]string $return[%plugin_id%]['photo'] html output
      */
     $backend_contact_info_params = array('contact_id' => $this->id);
     $this->view->assign('backend_contact_info', wa()->event('backend_contact_info', $backend_contact_info_params));
 }
 /**
  * Merge given contacts into master contact, save, send merge event, then delete slaves.
  *
  * !!! Probably should move it into something like contactsHelper
  *
  * @param array $merge_ids list of contact ids
  * @param int $master_id contact id to merge others into
  * @return array
  */
 public static function merge($merge_ids, $master_id)
 {
     $merge_ids[] = $master_id;
     // List of contacts to merge
     $collection = new contactsCollection('id/' . implode(',', $merge_ids));
     $contacts_data = $collection->getContacts('*');
     // Master contact data
     if (!$master_id || !isset($contacts_data[$master_id])) {
         throw new waException('No contact to merge into.');
     }
     $master_data = $contacts_data[$master_id];
     unset($contacts_data[$master_id]);
     $master = new waContact($master_id);
     $result = array('total_requested' => count($contacts_data) + 1, 'total_merged' => 0, 'error' => '', 'users' => 0);
     if ($master_data['photo']) {
         $filename = wa()->getDataPath(waContact::getPhotoDir($master_data['id']) . "{$master_data['photo']}.original.jpg", true, 'contacts');
         if (!file_exists($filename)) {
             $master_data['photo'] = null;
         }
     }
     $data_fields = waContactFields::getAll('enabled');
     $check_duplicates = array();
     // field_id => true
     $update_photo = null;
     // if need to update photo here it is file paths
     // merge loop
     foreach ($contacts_data as $id => $info) {
         if ($info['is_user'] > 0) {
             $result['users']++;
             unset($contacts_data[$id]);
             continue;
         }
         foreach ($data_fields as $f => $field) {
             if (!empty($info[$f])) {
                 if ($field->isMulti()) {
                     $master->add($f, $info[$f]);
                     $check_duplicates[$f] = true;
                 } else {
                     // Field does not allow multiple values.
                     // Set value if no value yet.
                     if (empty($master_data[$f])) {
                         $master[$f] = $master_data[$f] = $info[$f];
                     }
                 }
             }
         }
         // photo
         if (!$master_data['photo'] && $info['photo'] && !$update_photo) {
             $filename_original = wa()->getDataPath(waContact::getPhotoDir($info['id']) . "{$info['photo']}.original.jpg", true, 'contacts');
             if (file_exists($filename_original)) {
                 $update_photo = array('original' => $filename_original);
                 $filename_crop = wa()->getDataPath(waContact::getPhotoDir($info['id']) . "{$info['photo']}.jpg", true, 'contacts');
                 if (file_exists($filename_crop)) {
                     $update_photo['crop'] = $filename_crop;
                 }
             }
         }
         // birthday parts
         if (!empty($data_fields['birthday'])) {
             foreach (array('birth_day', 'birth_month', 'birth_year') as $f) {
                 if (empty($master_data[$f]) && !empty($info[$f])) {
                     $master[$f] = $master_data[$f] = $info[$f];
                 }
             }
         }
     }
     // Remove duplicates
     foreach (array_keys($check_duplicates) as $f) {
         $values = $master[$f];
         if (!is_array($values) || count($values) <= 1) {
             continue;
         }
         $unique_values = array();
         // md5 => true
         foreach ($values as $k => $v) {
             if (is_array($v)) {
                 if (isset($v['value']) && is_string($v['value'])) {
                     $v = $v['value'];
                 } else {
                     unset($v['ext'], $v['status']);
                     ksort($v);
                     $v = serialize($v);
                 }
             }
             $hash = md5(mb_strtolower($v));
             if (!empty($unique_values[$hash])) {
                 unset($values[$k]);
                 continue;
             }
             $unique_values[$hash] = true;
         }
         $master[$f] = array_values($values);
     }
     // Save master contact
     $errors = $master->save(array(), 42);
     // 42 == do not validate anything at all
     if ($errors) {
         $errormsg = array();
         foreach ($errors as $field => $err) {
             if (!is_array($err)) {
                 $err = array($err);
             }
             foreach ($err as $str) {
                 $errormsg[] = $field . ': ' . $str;
             }
         }
         $result['error'] = implode("\n<br>", $errormsg);
         return $result;
     }
     // Merge categories
     $category_ids = array();
     $ccm = new waContactCategoriesModel();
     foreach ($ccm->getContactsCategories($merge_ids) as $cid => $cats) {
         $category_ids += array_flip($cats);
     }
     $category_ids = array_keys($category_ids);
     $ccm->add($master_id, $category_ids);
     // update photo
     if ($update_photo) {
         $rand = mt_rand();
         $path = wa()->getDataPath(waContact::getPhotoDir($master['id']), true, 'contacts', false);
         // delete old image
         if (file_exists($path)) {
             waFiles::delete($path);
         }
         waFiles::create($path);
         $filename = $path . "/" . $rand . ".original.jpg";
         waFiles::create($filename);
         waImage::factory($update_photo['original'])->save($filename, 90);
         if (!empty($update_photo['crop'])) {
             $filename = $path . "/" . $rand . ".jpg";
             waFiles::create($filename);
             waImage::factory($update_photo['crop'])->save($filename, 90);
         } else {
             waFiles::copy($filename, $path . "/" . $rand . ".jpg");
         }
         $master->save(array('photo' => $rand));
     }
     $result['total_merged'] = count($contacts_data) + 1;
     $contact_ids = array_keys($contacts_data);
     // wa_log
     $log_model = new waLogModel();
     $log_model->updateByField('contact_id', $contact_ids, array('contact_id' => $master_id));
     // wa_login_log
     $login_log_model = new waLoginLogModel();
     $login_log_model->updateByField('contact_id', $contact_ids, array('contact_id' => $master_id));
     // Merge event
     $params = array('contacts' => $contact_ids, 'id' => $master_data['id']);
     wa()->event(array('contacts', 'merge'), $params);
     // Delete all merged contacts
     $contact_model = new waContactModel();
     $contact_model->delete($contact_ids, false);
     // false == do not trigger event
     $history_model = new contactsHistoryModel();
     foreach ($contact_ids as $contact_id) {
         $history_model->deleteByField(array('type' => 'add', 'hash' => '/contact/' . $contact_id));
     }
     return $result;
 }
 public function execute()
 {
     $this->id = (int) waRequest::post('id');
     // Check access
     if (!$this->id) {
         if (!$this->getRights('create')) {
             throw new waRightsException('Access denied.');
         }
     } else {
         $cr = new contactsRightsModel();
         if ($cr->getRight(null, $this->id) != 'write') {
             throw new waRightsException('Access denied.');
         }
     }
     $this->type = waRequest::post('type');
     $this->contact = new waContact($this->id);
     if ($this->type == 'company') {
         $this->contact['is_company'] = 1;
     }
     $data = json_decode(waRequest::post('data'), true);
     if (!$this->id && !isset($data['create_method'])) {
         $data['create_method'] = 'add';
     }
     $oldLocale = $this->getUser()->getLocale();
     // get old data for logging
     if ($this->id) {
         $old_data = array();
         foreach ($data as $field_id => $field_value) {
             $old_data[$field_id] = $this->contact->get($field_id);
         }
     }
     $response = array();
     if (!($errors = $this->contact->save($data, true))) {
         if ($this->id) {
             $new_data = array();
             foreach ($data as $field_id => $field_value) {
                 if (!isset($errors[$field_id])) {
                     $response[$field_id] = $this->contact->get($field_id, 'js');
                     $new_data[$field_id] = $this->contact->get($field_id);
                 }
             }
             if (empty($errors)) {
                 $this->logContactEdit($old_data, $new_data);
             }
             $response['name'] = $this->contact->get('name', 'js');
             $response['top'] = contactsHelper::getTop($this->contact);
             $response['id'] = $this->contact->getId();
         } else {
             $response = array('id' => $this->contact->getId());
             $response['address'] = $this->contact->get('address', 'js');
             $this->logAction('contact_add', null, $this->contact->getId());
         }
         // Update recently added menu item
         $name = waContactNameField::formatName($this->contact);
         if ($name || $name === '0') {
             $history = new contactsHistoryModel();
             $history->save('/contact/' . $this->contact->getId(), $name, $this->id ? null : 'add');
             $history = $history->get();
             // to update history in user's browser
         }
     }
     // Reload page with new language if user just changed it in own profile
     if ($this->contact->getId() == $this->getUser()->getId() && $oldLocale != $this->contact->getLocale()) {
         $response['reload'] = true;
     }
     $this->response = array('errors' => $errors, 'data' => $response);
     if (isset($history)) {
         $this->response['history'] = $history;
     }
 }
 public function execute()
 {
     $this->id = (int) waRequest::post('id');
     // Check access
     if (!$this->id) {
         if (!$this->getRights('create')) {
             throw new waRightsException('Access denied.');
         }
     } else {
         $cr = new contactsRightsModel();
         if ($cr->getRight(null, $this->id) != 'write') {
             throw new waRightsException('Access denied.');
         }
     }
     $this->type = waRequest::post('type');
     $this->contact = new waContact($this->id);
     if ($this->type == 'company') {
         $this->contact['is_company'] = 1;
     }
     $data = json_decode(waRequest::post('data'), true);
     if (!$this->id && !isset($data['create_method'])) {
         $data['create_method'] = 'add';
     }
     $oldLocale = $this->getUser()->getLocale();
     $response = array();
     if (!($errors = $this->contact->save($data, true))) {
         if ($this->id) {
             foreach ($data as $field_id => $field_value) {
                 if (!isset($errors[$field_id])) {
                     $response[$field_id] = $this->contact->get($field_id, 'js');
                 }
             }
             $response['name'] = $this->contact->get('name', 'js');
             $fields = array('email', 'phone', 'im');
             $top = array();
             foreach ($fields as $f) {
                 if ($v = $this->contact->get($f, 'top,html')) {
                     $top[] = array('id' => $f, 'name' => waContactFields::get($f)->getName(), 'value' => is_array($v) ? implode(', ', $v) : $v);
                 }
             }
             $response['top'] = $top;
         } else {
             $response = array('id' => $this->contact->getId());
             $this->log('contact_add', 1);
         }
         // Update recently added menu item
         if (($name = $this->contact->get('name')) || $name === '0') {
             $name = trim($this->contact->get('title') . ' ' . $name);
             $history = new contactsHistoryModel();
             $history->save('/contact/' . $this->contact->getId(), $name, $this->id ? null : 'add');
             $history = $history->get();
             // to update history in user's browser
         }
     }
     // Reload page with new language if user just changed it in own profile
     if ($this->contact->getId() == $this->getUser()->getId() && $oldLocale != $this->contact->getLocale()) {
         $response['reload'] = TRUE;
     }
     $this->response = array('errors' => $errors, 'data' => $response);
     if (isset($history)) {
         $this->response['history'] = $history;
     }
 }
 public function execute()
 {
     $this->prepare();
     if ($query = trim(waRequest::post('query'), '/')) {
         if (strpos($query, '/') === false) {
             $h = $hash = 'search/' . $query;
         } else {
             $h = $hash = $query;
             if (substr($hash, 0, 14) == 'import/results') {
                 $h = str_replace('import/results', 'import', $hash);
             }
         }
     } else {
         $h = $hash = '';
     }
     $h_parts = explode('/', $h, 2);
     $add_fields = array();
     if ($h_parts[0] == 'explore') {
         $collection = new contactsCollection();
         $event_params = array('collection' => $collection, 'hash' => $h_parts[1]);
         $result = wa()->event('explore', $event_params);
         if ($result) {
             $result = reset($result);
             $add_fields = ifset($result['fields']);
             $this->response['add_fields'] = $add_fields;
             $this->response['name'] = $result['name'];
         }
     } else {
         $collection = new contactsCollection($h);
     }
     $this->response['fields'] = array();
     $fields = '*,photo_url_32,photo_url_96';
     if ($h_parts[0] === 'users') {
         $fields .= ',_access';
         $this->response['fields']['_access'] = array('id' => '_access', 'name' => _w('Access'), 'type' => 'Access', 'vertical' => true);
     }
     $collection->orderBy($this->sort, $this->order);
     $this->response['count'] = $collection->count();
     $view = waRequest::post('view');
     if ($view == 'list') {
         // Preload info to cache to avoid excess DB access
         $cm = new waCountryModel();
         $cm->preload();
     }
     $this->response['contacts'] = array_values($collection->getContacts($fields, $this->offset, $this->limit));
     $this->workupContacts($this->response['contacts']);
     $this->response['total_count'] = $collection->count();
     foreach ($this->response['contacts'] as $i => &$c) {
         $c['offset'] = $this->offset + $i;
     }
     unset($c);
     if ($view == 'list') {
         // Need to format field values correctly for this view.
         foreach ($this->response['contacts'] as &$cdata) {
             $c = new waContact($cdata['id']);
             $c->setCache($cdata);
             $data = $c->load('list,js') + $cdata;
             contactsHelper::normalzieContactFieldValues($data, waContactFields::getInfo($c['is_company'] ? 'company' : 'person', true));
             if (isset($data['photo'])) {
                 $data['photo'] = $c->getPhoto();
             }
             $c->removeCache(array_keys($cdata));
             $cdata = $data;
         }
         $this->response['fields'] = array_merge($this->response['fields'], contactsHelper::getFieldsDescription(array('title', 'name', 'photo', 'firstname', 'middlename', 'lastname', 'locale', 'timezone', 'jobtitle', 'company', 'sex', 'company_contact_id'), true));
         unset($cdata);
     }
     // for companies set name to company name
     // for contacts with empty name, set it to <no name>
     foreach ($this->response['contacts'] as &$c) {
         if (isset($c['name']) && trim($c['name'])) {
             continue;
         }
         if (isset($c['company']) && trim($c['company'])) {
             $c['name'] = $c['company'];
             unset($c['company']);
             continue;
         }
         $c['name'] = '<' . _w('no name') . '>';
     }
     unset($c);
     $title = $collection->getTitle();
     $hm = new contactsHistoryModel();
     if ($hash) {
         $type = explode('/', $hash);
         $hash = substr($hash, 0, 1) == '/' ? $hash : '/contacts/' . $hash;
         $type = $type[0];
         // if search query looks like a quick search then remove field name from header
         if ($type == 'search' && preg_match('~^/contacts/search/(name\\*=[^/]*|email\\*=[^/]*@[^/]*)/?$~i', $hash)) {
             $title = preg_replace("~^[^=]+=~", '', $title);
         }
         // save history
         if ($type == 'search') {
             $hm->save($hash, $title, $type, $this->response['count']);
             $this->logAction('search');
         }
         // Information about system category in categories view
         if (substr($hash, 0, 19) === '/contacts/category/') {
             $category_id = (int) substr($hash, 19);
             $cm = new waContactCategoryModel();
             $category = $cm->getById($category_id);
             if ($category && $category['system_id']) {
                 $this->response['system_category'] = $category['system_id'];
             }
         }
     }
     // Update history in user's browser
     $this->response['history'] = $hm->get();
     $this->response['title'] = $title;
 }
 public function execute()
 {
     $this->prepare();
     if ($query = trim(waRequest::post('query'), '/')) {
         if (strpos($query, '/') === false) {
             $h = $hash = 'search/' . $query;
         } else {
             $h = $hash = $query;
             if (substr($hash, 0, 14) == 'import/results') {
                 $h = str_replace('import/results', 'import', $hash);
             }
         }
     } else {
         $h = $hash = '';
     }
     $collection = $this->getCollection($h);
     $collection->orderBy($this->sort, $this->order);
     $this->response['count'] = $collection->count();
     $view = waRequest::post('view');
     switch ($view) {
         case 'list':
             $fields = '*';
             break;
         case 'thumbs':
             $fields = 'id,name,photo';
             break;
         case 'table':
         default:
             $fields = waRequest::post('fields');
     }
     if ($view == 'list') {
         // Preload info to cache to avoid excess DB access
         $cm = new waCountryModel();
         $cm->preload();
     }
     if ($hash && $fields != '*') {
         if ($wf = $collection->getWhereFields()) {
             $fields = $fields . "," . implode(",", $wf);
         }
         $this->response['fields'] = explode(',', $fields);
     }
     $this->response['contacts'] = array_values($collection->getContacts($fields, $this->offset, $this->limit));
     if ($view == 'list') {
         // Need to format field values correctly for this view.
         foreach ($this->response['contacts'] as &$cdata) {
             $c = new waContact($cdata['id']);
             $c->setCache($cdata);
             $data = $c->load('list,js') + $cdata;
             if (isset($data['photo'])) {
                 $data['photo'] = $c->getPhoto();
             }
             $c->removeCache(array_keys($cdata));
             $cdata = $data;
         }
         unset($cdata);
     }
     // for companies set name to company name
     // for contacts with empty name, set it to <no name>
     foreach ($this->response['contacts'] as &$c) {
         if (isset($c['name']) && trim($c['name'])) {
             continue;
         }
         if (isset($c['company']) && trim($c['company'])) {
             $c['name'] = $c['company'];
             unset($c['company']);
             continue;
         }
         $c['name'] = '<' . _w('no name') . '>';
     }
     unset($c);
     $title = $collection->getTitle();
     if ($hash) {
         $type = explode('/', $hash);
         $hash = substr($hash, 0, 1) == '/' ? $hash : '/contacts/' . $hash;
         $type = $type[0];
         // if search query looks like a quick search then remove field name from header
         if ($type == 'search' && preg_match('~^/contacts/search/(name\\*=[^/]*|email\\*=[^/]*@[^/]*)/?$~i', $hash)) {
             $title = preg_replace("~^[^=]+=~", '', $title);
         }
         // save history
         if ($type == 'search' || $type == 'import') {
             $history = new contactsHistoryModel();
             if ($history->save($hash, $title, $type, $this->response['count'])) {
                 // new search performed, save to statistics log
                 $this->log('search', 1);
             }
         }
         // Information about system category in categories view
         if (substr($hash, 0, 19) === '/contacts/category/') {
             $category_id = (int) substr($hash, 19);
             $cm = new waContactCategoryModel();
             $category = $cm->getById($category_id);
             if ($category && $category['system_id']) {
                 $this->response['system_category'] = $category['system_id'];
             }
         }
     }
     // Update history in user's browser
     $historyModel = new contactsHistoryModel();
     $this->response['history'] = $historyModel->get();
     $this->response['title'] = $title;
 }