public function getRight($user_id, $contact_id)
 {
     if ($user_id) {
         $user = new waUser($user_id);
     } else {
         $user = wa()->getUser();
     }
     $user_id = $user->getId();
     if ($user->getRights('contacts', 'edit')) {
         $data = array();
         foreach ((array) $contact_id as $c_id) {
             $u = new waUser($c_id);
             $data[$c_id] = $user->isAdmin() || !$u->isAdmin() ? 'write' : 'read';
         }
     } else {
         $data = array_fill_keys((array) $contact_id, 'read');
         $m = new waContactModel();
         $allowed = array_keys($m->select('id')->where("create_contact_id = {$user_id}\n                    AND id IN(" . implode(',', (array) $contact_id) . ")")->fetchAll('id'));
         foreach ($allowed as $c) {
             if (isset($data[$c])) {
                 $data[$c] = 'write';
             } else {
                 $data[$c] = false;
             }
         }
     }
     if (is_array($contact_id)) {
         return $data;
     } else {
         return isset($data[$contact_id]) ? $data[$contact_id] : false;
     }
 }
 protected function createUser($id)
 {
     $user = new waUser($id);
     if ($user['is_user']) {
         throw new waException('Already a user.');
     }
     if (waRequest::post('invite')) {
         $user['password'] = uniqid(time(), true);
     } else {
         $login = trim(waRequest::post('login'));
         if (strlen($login) <= 0) {
             $this->errors[] = _w('Login is required.');
         } else {
             if ($u = waUser::getByLogin($login)) {
                 $nameLink = '<a href="' . wa_url() . 'webasyst/contacts/#/contact/' . $u->getId() . '">' . $u->get('name') . '</a>';
                 $this->errors[] = str_replace('%NAME_LINK%', $nameLink, _w('This login is already set for user %NAME_LINK%'));
             }
         }
         $user['login'] = $login;
         if (waRequest::post('password') === waRequest::post('confirm_password')) {
             $user['password'] = waRequest::post('password');
         } else {
             $this->errors[] = _w('Passwords do not match.');
         }
     }
     if (!$this->errors) {
         $user['is_user'] = 1;
         $this->response = $user->save();
         $this->log('create_user_account', 1);
     }
 }
 public function getUser()
 {
     if (!wa()->getUser()->getId()) {
         try {
             $c = new waUser($this->info['contact_id']);
             $c->getName();
             return $c;
         } catch (waException $e) {
         }
     }
     return wa()->getUser();
 }
 public function init()
 {
     parent::init();
     $this->storage = waSystem::getInstance()->getStorage();
     if (!isset(self::$options['session_timeout'])) {
         self::$options['session_timeout'] = 1800;
     }
     if (ini_get('session.gc_maxlifetime') < self::$options['session_timeout']) {
         ini_set('session.gc_maxlifetime', self::$options['session_timeout']);
     }
     $auth = waSystem::getInstance()->getAuth();
     $info = $auth->isAuth();
     if ($info && isset($info['id']) && $info['id']) {
         $this->auth = true;
         $this->id = $info['id'];
         // update last_datetime for contact
         if (!waRequest::request('background_process')) {
             $this->updateLastTime();
         }
         // check CSRF cookie
         if (!waRequest::cookie('_csrf')) {
             waSystem::getInstance()->getResponse()->setCookie('_csrf', uniqid('', true));
         }
     }
 }
 /** Using $this->id get waContact and save it in $this->contact;
  * Load vars into $this->view specific to waContact. */
 protected function getContactInfo()
 {
     $system = wa();
     if ($this->id == $system->getUser()->getId()) {
         $this->contact = $system->getUser();
         $this->view->assign('own_profile', true);
     } else {
         $this->contact = new waContact($this->id);
         $this->view->assign('own_profile', false);
     }
     $exists = $this->contact->exists();
     if ($exists) {
         $this->view->assign('contact', $this->contact);
         // who created this contact and when
         $this->view->assign('contact_create_time', waDateTime::format('datetime', $this->contact['create_datetime'], $system->getUser()->getTimezone()));
         if ($this->contact['create_contact_id']) {
             try {
                 $author = new waContact($this->contact['create_contact_id']);
                 if ($author['name']) {
                     $this->view->assign('author', $author);
                 }
             } catch (Exception $e) {
                 // Contact not found. Ignore silently.
             }
         }
         $this->view->assign('top', $this->contact->getTopFields());
         // Main contact editor data
         $fieldValues = $this->contact->load('js', true);
         $m = new waContactModel();
         if (isset($fieldValues['company_contact_id'])) {
             if (!$m->getById($fieldValues['company_contact_id'])) {
                 $fieldValues['company_contact_id'] = 0;
                 $this->contact->save(array('company_contact_id' => 0));
             }
         }
         $contactFields = waContactFields::getInfo($this->contact['is_company'] ? 'company' : 'person', true);
         // Only show fields that are allowed in own profile
         if (!empty($this->params['limited_own_profile'])) {
             $allowed = array();
             foreach (waContactFields::getAll('person') as $f) {
                 if ($f->getParameter('allow_self_edit')) {
                     $allowed[$f->getId()] = true;
                 }
             }
             $fieldValues = array_intersect_key($fieldValues, $allowed);
             $contactFields = array_intersect_key($contactFields, $allowed);
         }
         contactsHelper::normalzieContactFieldValues($fieldValues, $contactFields);
         $this->view->assign('contactFields', $contactFields);
         $this->view->assign('contactFieldsOrder', array_keys($contactFields));
         $this->view->assign('fieldValues', $fieldValues);
         // Contact categories
         $cm = new waContactCategoriesModel();
         $this->view->assign('contact_categories', array_values($cm->getContactCategories($this->id)));
     } else {
         $this->view->assign('contact', array('id' => $this->id));
     }
     return $exists;
 }
 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()
 {
     $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.');
     }
     // Only allow actions with contacts available for current user
     if (!$this->getRights('category.all')) {
         $crm = new contactsRightsModel();
         $ccm = new waContactCategoriesModel();
         $allowed = array_keys($crm->getAllowedCategories());
         foreach ($ccm->getContactsCategories($contacts) as $id => $cats) {
             if (!array_intersect($allowed, $cats)) {
                 throw new waRightsException('Access denied: no access to contact ' . $id);
             }
         }
     }
     // 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);
     }
     // Bye bye...
     $contact_model = new waContactModel();
     $contact_model->delete($contacts);
     // also throws a contacts.delete event
     $this->response['deleted'] = count($contacts);
     $this->response['message'] = sprintf(_w("%d contact has been deleted", "%d contacts have been deleted", $this->response['deleted']), $this->response['deleted']);
     $this->log('contact_delete', count($contacts));
 }
 public function execute()
 {
     $id = waRequest::request('id');
     $class = 'photosImport' . ucfirst($id) . 'Transport';
     if ($id && class_exists($class)) {
         /**
          * @var photosImportTransport $transport
          */
         $transport = new $class();
     } else {
         throw new waException('Transport not found', 404);
     }
     $this->view->assign('controls', $transport->getControls());
     $this->view->assign('contacts', waUser::getUsers('photos'));
     $this->view->assign('user_id', $this->getUser()->getId());
 }
 /** Using $this->id get waContact and save it in $this->contact;
  * Load vars into $this->view specific to waContact. */
 protected function getContactInfo()
 {
     $system = wa();
     if ($this->id == $system->getUser()->getId()) {
         $this->contact = $system->getUser();
         $this->view->assign('own_profile', TRUE);
     } else {
         $this->contact = new waContact($this->id);
     }
     //
     // Load vars into view
     //
     $this->view->assign('contact', $this->contact);
     // who created this contact and when
     $this->view->assign('contact_create_time', waDateTime::format('datetime', $this->contact['create_datetime'], $system->getUser()->getTimezone()));
     if ($this->contact['create_contact_id']) {
         try {
             $author = new waContact($this->contact['create_contact_id']);
             if ($author['name']) {
                 $this->view->assign('author', $author);
             }
         } catch (Exception $e) {
             // Contact not found. Ignore silently.
         }
     }
     // Info above tabs
     $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);
         }
     }
     $this->view->assign('top', $top);
     // Main contact editor data
     $fieldValues = $this->contact->load('js', TRUE);
     $contactFields = waContactFields::getInfo($this->contact['is_company'] ? 'company' : 'person', TRUE);
     $this->view->assign('contactFields', $contactFields);
     $this->view->assign('fieldValues', $fieldValues);
     // Contact categories
     $cm = new waContactCategoriesModel();
     $this->view->assign('contact_categories', array_values($cm->getContactCategories($this->id)));
 }
 /**
  * Get data for contacts in this collection.
  * @param string|array $fields
  * @param int $offset
  * @param int $limit
  * @return array [contact_id][field] = field value in appropriate field format
  * @throws waException
  */
 public function getContacts($fields = "id", $offset = 0, $limit = 50)
 {
     $sql = "SELECT " . $this->getFields($fields) . " " . $this->getSQL();
     $sql .= $this->getGroupBy();
     $sql .= $this->getHaving();
     $sql .= $this->getOrderBy();
     $sql .= " LIMIT " . ($offset ? $offset . ',' : '') . (int) $limit;
     //header("X-SQL-". mt_rand() . ": ". str_replace("\n", " ", $sql));
     $data = $this->getModel()->query($sql)->fetchAll('id');
     $ids = array_keys($data);
     //
     // Load fields from other storages
     //
     if ($ids && $this->post_fields) {
         // $fill[table][field] = null
         // needed for all rows to always contain all apropriate keys
         // in case when we're asked to load all fields from that table
         $fill = array_fill_keys(array_keys($this->post_fields), array());
         foreach (waContactFields::getAll('enabled') as $fid => $field) {
             /**
              * @var waContactField $field
              */
             $fill[$field->getStorage(true)][$fid] = false;
         }
         foreach ($this->post_fields as $table => $fields) {
             if ($table == '_internal') {
                 foreach ($fields as $f) {
                     /**
                      * @var $f string
                      */
                     if ($f == 'photo_url' || substr($f, 0, 10) == 'photo_url_') {
                         if ($f == 'photo_url') {
                             $size = null;
                         } else {
                             $size = substr($f, 10);
                         }
                         $retina = isset($this->options['photo_url_2x']) ? $this->options['photo_url_2x'] : null;
                         foreach ($data as $id => &$v) {
                             $v[$f] = waContact::getPhotoUrl($id, $v['photo'], $size, $size, $v['is_company'] ? 'company' : 'person', $retina);
                         }
                         unset($v);
                     } else {
                         switch ($f) {
                             case '_online_status':
                                 $llm = new waLoginLogModel();
                                 $contact_ids_map = $llm->select('DISTINCT contact_id')->where('datetime_out IS NULL')->fetchAll('contact_id');
                                 $timeout = waUser::getOption('online_timeout');
                                 foreach ($data as &$v) {
                                     if (isset($v['last_datetime']) && $v['last_datetime'] && $v['last_datetime'] != '0000-00-00 00:00:00') {
                                         if (time() - strtotime($v['last_datetime']) < $timeout) {
                                             if (isset($contact_ids_map[$v['id']])) {
                                                 $v['_online_status'] = 'online';
                                             } else {
                                                 $v['_online_status'] = 'offline';
                                             }
                                         }
                                     }
                                     $v['_online_status'] = 'offline';
                                 }
                                 unset($v);
                                 break;
                             case '_access':
                                 $rm = new waContactRightsModel();
                                 $accessStatus = $rm->getAccessStatus($ids);
                                 foreach ($data as $id => &$v) {
                                     if (!isset($accessStatus[$id])) {
                                         $v['_access'] = '';
                                         continue;
                                     }
                                     $v['_access'] = $accessStatus[$id];
                                 }
                                 unset($v);
                                 break;
                             default:
                                 throw new waException('Unknown internal field: ' . $f);
                         }
                     }
                 }
                 continue;
             }
             $data_fields = $fields;
             foreach ($data_fields as $k => $field_id) {
                 $f = waContactFields::get($field_id);
                 if ($f && $f instanceof waContactCompositeField) {
                     unset($data_fields[$k]);
                     $data_fields = array_merge($data_fields, $f->getField());
                 }
             }
             $model = $this->getModel($table);
             $post_data = $model->getData($ids, $data_fields);
             foreach ($post_data as $contact_id => $contact_data) {
                 foreach ($contact_data as $field_id => $value) {
                     if (!($f = waContactFields::get($field_id))) {
                         continue;
                     }
                     if (!$f->isMulti()) {
                         $post_data[$contact_id][$field_id] = isset($value[0]['data']) ? $value[0]['data'] : (is_array($value[0]) ? $value[0]['value'] : $value[0]);
                     }
                 }
             }
             if ($fields) {
                 $fill[$table] = array_fill_keys($fields, '');
             } else {
                 if (!isset($fill[$table])) {
                     $fill[$table] = array();
                 }
             }
             foreach ($data as $contact_id => $v) {
                 if (isset($post_data[$contact_id])) {
                     $data[$contact_id] += $post_data[$contact_id];
                 }
                 $data[$contact_id] += $fill[$table];
             }
         }
     }
     return $data;
 }
 private function checkAuthorRightsToBlog($author_id, $post)
 {
     $user = new waUser($author_id);
     if ($user->getId()) {
         $rights = $user->getRights($this->getApp(), "blog.{$post['blog_id']}");
         return $rights >= blogRightConfig::RIGHT_READ_WRITE;
     }
     return false;
 }
 public function execute()
 {
     $contact_model = new waContactModel();
     if ($contact_model->countAll()) {
         $this->redirect($this->getConfig()->getBackendUrl(true));
     }
     if (($locale = waRequest::get('lang')) && waLocale::getInfo($locale)) {
         // set locale
         wa()->setLocale($locale);
         // save to database default locale
         $app_settings_model = new waAppSettingsModel();
         $app_settings_model->set('webasyst', 'locale', $locale);
     }
     if (file_exists($this->getConfig()->getRootPath() . '/install.php')) {
         @unlink($this->getConfig()->getRootPath() . '/install.php');
     }
     if (waRequest::getMethod() == 'post') {
         $errors = array();
         $login = waRequest::post('login');
         $validator = new waLoginValidator();
         if (!$validator->isValid($login)) {
             $errors['login'] = implode("<br />", $validator->getErrors());
         }
         $password = waRequest::post('password');
         $password_confirm = waRequest::post('password_confirm');
         if ($password !== $password_confirm) {
             $errors['password'] = _w('Passwords do not match');
         }
         $email = waRequest::post('email');
         $validator = new waEmailValidator();
         if (!$validator->isValid($email)) {
             $errors['email'] = implode("<br />", $validator->getErrors());
         }
         if ($errors) {
             $this->view->assign('errors', $errors);
         } else {
             // save account name
             $app_settings_model = new waAppSettingsModel();
             $app_settings_model->set('webasyst', 'name', waRequest::post('account_name'));
             if ($email) {
                 $app_settings_model->set('webasyst', 'email', $email);
                 $app_settings_model->set('webasyst', 'sender', $email);
             }
             // create user
             $user = new waUser();
             $firstname = waRequest::post('firstname');
             $user['firstname'] = $firstname ? $firstname : $login;
             $user['lastname'] = waRequest::post('lastname');
             $user['is_user'] = 1;
             $user['login'] = $login;
             $user['password'] = $password;
             $user['email'] = $email;
             $user['locale'] = wa()->getLocale();
             $user['create_method'] = 'install';
             if ($errors = $user->save()) {
                 $result = array();
                 foreach ($errors as $k => $v) {
                     $result['all'][] = $k . ": " . (is_array($v) ? implode(', ', $v) : $v);
                 }
                 $result['all'] = implode("\r\n", $result['all']);
                 $this->view->assign('errors', $result);
             } else {
                 $user->setRight('webasyst', 'backend', 1);
                 waSystem::getInstance()->getAuth()->auth(array('login' => $login, 'password' => $password));
                 $path = $this->getConfig()->getPath('config');
                 // check routing.php
                 if (!file_exists($path . '/routing.php')) {
                     $apps = wa()->getApps();
                     $data = array();
                     $domain = $this->getConfig()->getDomain();
                     $site = false;
                     foreach ($apps as $app_id => $app) {
                         if ($app_id == 'site') {
                             $site = true;
                         } elseif (!empty($app['frontend'])) {
                             $routing = array('url' => $app_id . '/*', 'app' => $app_id);
                             if (!empty($app['routing_params']) && is_array($app['routing_params'])) {
                                 $routing = array_merge($routing, $app['routing_params']);
                             }
                             $data[$domain][] = $routing;
                         }
                     }
                     if ($site) {
                         $data[$domain][] = array('url' => '*', 'app' => 'site');
                     }
                     waUtils::varExportToFile($data, $path . '/routing.php');
                 }
                 // redirect to backend
                 $this->redirect($this->getConfig()->getBackendUrl(true));
             }
         }
     }
 }
 protected function createLogin($id, $just_check = false)
 {
     $user = new waUser($id);
     $login = trim(waRequest::post('login'));
     if (strlen($login) <= 0) {
         $this->errors[] = _w('Login is required.');
     } else {
         if ($u = $this->loginExists($login, $id)) {
             $nameLink = '<a href="' . wa_url() . 'webasyst/contacts/#/contact/' . $u['id'] . '">' . $u['name'] . '</a>';
             $this->errors[] = str_replace('%NAME_LINK%', $nameLink, _w('This login is already set for user %NAME_LINK%'));
         }
     }
     if (!$this->errors) {
         if ($just_check) {
             return true;
         }
         $user['login'] = $login;
         $r = $user->save();
         if ($r === 0) {
             return array('login' => $login);
         } else {
             $this->errors = $r;
             return false;
         }
     } else {
         return false;
     }
 }
 protected function addRightsCondition(waUser $user)
 {
     if ($user->isAdmin('photos')) {
         $on = "(pr.group_id >= 0 OR pr.group_id = -" . $user->getId() . ")";
     } else {
         $group_ids = $user->getGroupIds();
         $on = 'pr.group_id IN (' . implode(",", $group_ids) . ')';
     }
     $this->joins[] = array('table' => 'photos_photo_rights', 'alias' => 'pr', 'on' => 'p.id = pr.photo_id AND ' . $on);
 }