public function execute()
 {
     $form = shopHelper::getCustomerForm();
     if ($form->post()) {
         $customer_validation_disabled = wa()->getSetting('disable_backend_customer_form_validation');
         if ($customer_validation_disabled || $form->isValid()) {
             $c = new waContact();
             if ($customer_validation_disabled) {
                 $errors = array();
                 $c->save($form->post());
             } else {
                 $errors = $c->save($form->post(), true);
             }
             if (!$errors) {
                 $scm = new shopCustomerModel();
                 $scm->createFromContact($c->getId());
                 echo '<script>$.customers.reloadSidebar(); window.location.hash = "#/id/' . $c->getId() . '"</script>';
                 exit;
             }
             // Show errors that waContact returned, e.g. email must be unique.
             foreach ($errors as $fld => $list) {
                 foreach ($list as $err) {
                     $form->errors($fld, $err);
                 }
             }
         }
     }
     $this->view->assign('form', $form);
     $this->view->assign('customer_validation_disabled', wa()->getSetting('disable_backend_customer_form_validation'));
 }
 public function execute()
 {
     // Задаём лайаут для фронтенда
     $this->setLayout(new guestbook2FrontendLayout());
     // Получаем hash из GET параметров
     $hash = waRequest::get('hash');
     // Проверяем хэш
     if (!$hash || strlen($hash) < 33) {
         $this->redirect(wa()->getRouteUrl('/frontend'));
     }
     // Получаем contact_id из хэша
     $contact_id = substr($hash, 16, -16);
     $hash = substr($hash, 0, 16) . substr($hash, -16);
     $contact = new waContact($contact_id);
     // Проверяем валидность хэша
     if ($contact->getSettings($this->getAppId(), 'confirm_hash') === $hash) {
         // Удаляем хэш
         $contact->delSettings($this->getAppId(), 'confirm_hash');
         // Выставляем статус confirmed для email-адреса контакта
         $contact['email'] = array('value' => $contact->get('email', 'default'), 'status' => 'confirmed');
         // Сохраняем контакт
         $contact->save();
     } else {
         // Если хэш неправильный, то просто редирект на главную страницу
         $this->redirect(wa()->getRouteUrl('/frontend'));
     }
 }
 /** 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;
 }
 /**
  * @param array $data
  * @return waContact
  */
 protected function afterAuth($data)
 {
     $app_id = $this->getStorage()->get('auth_app');
     $contact_id = 0;
     // find contact by auth adapter id, i.e. facebook_id
     $contact_data_model = new waContactDataModel();
     $row = $contact_data_model->getByField(array('field' => $data['source'] . '_id', 'value' => $data['source_id'], 'sort' => 0));
     if ($row) {
         $contact_id = $row['contact_id'];
     }
     // try find user by email
     if (!$contact_id && isset($data['email'])) {
         $sql = "SELECT c.id FROM wa_contact_emails e\n            JOIN wa_contact c ON e.contact_id = c.id\n            WHERE e.email = s:email AND e.sort = 0 AND c.password != ''";
         $contact_model = new waContactModel();
         $contact_id = $contact_model->query($sql, array('email' => $data['email']))->fetchField('id');
         // save source_id
         if ($contact_id) {
             $contact_data_model->insert(array('contact_id' => $contact_id, 'field' => $data['source'] . '_id', 'value' => $data['source_id'], 'sort' => 0));
         }
     }
     // create new contact
     if (!$contact_id) {
         $contact = new waContact();
         $data[$data['source'] . '_id'] = $data['source_id'];
         $data['create_method'] = $data['source'];
         $data['create_app_id'] = $app_id;
         // set random password (length = default hash length - 1, to disable ability auth using login and password)
         $contact->setPassword(substr(waContact::getPasswordHash(uniqid(time(), true)), 0, -1), true);
         unset($data['source']);
         unset($data['source_id']);
         if (isset($data['photo_url'])) {
             $photo_url = $data['photo_url'];
             unset($data['photo_url']);
         } else {
             $photo_url = false;
         }
         $contact->save($data);
         $contact_id = $contact->getId();
         if ($contact_id && $photo_url) {
             $photo_url_parts = explode('/', $photo_url);
             // copy photo to tmp dir
             $path = wa()->getTempPath('auth_photo/' . $contact_id . '.' . end($photo_url_parts), $app_id);
             $photo = file_get_contents($photo_url);
             file_put_contents($path, $photo);
             $contact->setPhoto($path);
         }
     } else {
         $contact = new waContact($contact_id);
     }
     // auth user
     if ($contact_id) {
         wa()->getAuth()->auth(array('id' => $contact_id));
         return $contact;
     }
     return false;
 }
 public function execute()
 {
     $this->contact = wa()->getUser();
     $data = json_decode(waRequest::post('data'), true);
     if (!$data || !is_array($data)) {
         $this->response = array('errors' => array(), 'data' => array());
         return;
     }
     // Make sure only allowed fields are saved
     $allowed = array();
     foreach (waContactFields::getAll('person') as $f) {
         if ($f->getParameter('allow_self_edit')) {
             $allowed[$f->getId()] = true;
         }
     }
     $data = array_intersect_key($data, $allowed);
     $oldLocale = $this->getUser()->getLocale();
     // Validate and save contact if no errors found
     $errors = $this->contact->save($data, true);
     if ($errors) {
         $response = array();
     } else {
         // New data formatted for JS
         $response['name'] = $this->contact->get('name', 'js');
         foreach ($data as $field_id => $field_value) {
             if (!isset($errors[$field_id])) {
                 $response[$field_id] = $this->contact->get($field_id, 'js');
             }
         }
         // Top fields
         $response['top'] = array();
         foreach (array('email', 'phone', 'im') as $f) {
             if ($v = $this->contact->get($f, 'top,html')) {
                 $response['top'][] = array('id' => $f, 'name' => waContactFields::get($f)->getName(), 'value' => is_array($v) ? implode(', ', $v) : $v);
             }
         }
     }
     // Reload page with new language if user just changed it in own profile
     if ($oldLocale != $this->contact->getLocale()) {
         $response['reload'] = TRUE;
     }
     $this->response = array('errors' => $errors, 'data' => $response);
 }
 public function execute()
 {
     $id = $this->getRequest()->request('id', null, waRequest::TYPE_INT);
     $sort = $this->getRequest()->request('sort', null, waRequest::TYPE_INT);
     if ($id && $sort !== null) {
         $lat = $this->getRequest()->request('lat', '', waRequest::TYPE_STRING);
         $lng = $this->getRequest()->request('lng', '', waRequest::TYPE_STRING);
         $contact = new waContact($id);
         $address = array();
         foreach ($contact->get('address') as $i => $addr) {
             $address[$i] = array('value' => $addr['data'], 'ext' => $addr['ext']);
         }
         $address[$sort]['value']['lat'] = $lat;
         $address[$sort]['value']['lng'] = $lng;
         $contact->save(array('address' => $address));
     }
 }
 public function execute()
 {
     // There is the same code in webasystProfileSaveGeocoords.controller.php
     $id = $this->getRequest()->request('id', null, waRequest::TYPE_INT);
     $sort = $this->getRequest()->request('sort', null, waRequest::TYPE_INT);
     if ($id && $sort !== null) {
         $lat = $this->getRequest()->request('lat', '', waRequest::TYPE_STRING);
         $lng = $this->getRequest()->request('lng', '', waRequest::TYPE_STRING);
         $contact = new waContact($id);
         $address = array();
         foreach ($contact->get('address') as $i => $addr) {
             $address[$i] = array('value' => $addr['data'], 'ext' => $addr['ext']);
         }
         $address[$sort]['value']['lat'] = $lat;
         $address[$sort]['value']['lng'] = $lng;
         $contact->save(array('address' => $address));
     }
 }
 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()
 {
     if (!$this->getRequest()->request('json', 0)) {
         $action = new contactsContactsInfoAction();
         echo $action->display();
         return;
     }
     $m = new waContactModel();
     $contact_id = $this->getRequest()->request('id', 0, 'int');
     $contact = new waContact($contact_id);
     $values = $contact->load('js', true);
     if (isset($values['company_contact_id'])) {
         if (!$m->getById($values['company_contact_id'])) {
             $values['company_contact_id'] = 0;
             $contact->save(array('company_contact_id' => 0));
         }
     }
     $values['photo_url_96'] = $contact->getPhoto(96);
     $values['photo_url_20'] = $contact->getPhoto(20);
     $fields = waContactFields::getInfo($contact['is_company'] ? 'company' : 'person', true);
     echo json_encode(array('fields' => $fields, 'values' => $values, 'top' => $contact->getTopFields()));
 }
 public function execute()
 {
     // Setting the frontend layout
     // Задаём лайаут для фронтенда
     $this->setLayout(new guestbook2FrontendLayout());
     // Retrieving hash from the GET request
     // Получаем hash из GET параметров
     $hash = waRequest::get('hash');
     // Verifying hash
     // Проверяем хэш
     if (!$hash || strlen($hash) < 33) {
         $this->redirect(wa()->getRouteUrl('/frontend'));
     }
     // Retrieving contact_id from the hash
     // Получаем contact_id из хэша
     $contact_id = substr($hash, 16, -16);
     $hash = substr($hash, 0, 16) . substr($hash, -16);
     $contact = new waContact($contact_id);
     // Validating hash
     // Проверяем валидность хэша
     if ($contact->getSettings($this->getAppId(), 'confirm_hash') === $hash) {
         // Deleting hash
         // Удаляем хэш
         $contact->delSettings($this->getAppId(), 'confirm_hash');
         // Setting "confirmed" status to the contact's email address
         // Выставляем статус confirmed для email-адреса контакта
         $contact['email'] = array('value' => $contact->get('email', 'default'), 'status' => 'confirmed');
         // Saving contact
         // Сохраняем контакт
         $contact->save();
     } else {
         // If the hash is incorrect then simply redirect to the home page
         // Если хэш неправильный, то просто редирект на главную страницу
         $this->redirect(wa()->getRouteUrl('/frontend'));
     }
 }
 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;
     }
 }
 /**
  * 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;
 }
 /**
  * @param array $data
  * @return waContact
  */
 protected function afterAuth($data)
 {
     $app_id = $this->getStorage()->get('auth_app');
     $contact_id = 0;
     // find contact by auth adapter id, i.e. facebook_id
     $contact_data_model = new waContactDataModel();
     $row = $contact_data_model->getByField(array('field' => $data['source'] . '_id', 'value' => $data['source_id'], 'sort' => 0));
     if ($row) {
         $contact_id = $row['contact_id'];
     }
     // try find user by email
     if (!$contact_id && isset($data['email'])) {
         $contact_model = new waContactModel();
         $sql = "SELECT c.id FROM wa_contact_emails e\n            JOIN wa_contact c ON e.contact_id = c.id\n            WHERE e.email LIKE '" . $contact_model->escape($data['email'], 'like') . "' AND e.sort = 0 AND c.password != ''";
         $contact_id = $contact_model->query($sql)->fetchField('id');
         // save source_id
         if ($contact_id) {
             $contact_data_model->insert(array('contact_id' => $contact_id, 'field' => $data['source'] . '_id', 'value' => $data['source_id'], 'sort' => 0));
         }
     }
     // create new contact
     if (!$contact_id) {
         $contact = new waContact();
         $data[$data['source'] . '_id'] = $data['source_id'];
         $data['create_method'] = $data['source'];
         $data['create_app_id'] = $app_id;
         // set random password (length = default hash length - 1, to disable ability auth using login and password)
         $contact->setPassword(substr(waContact::getPasswordHash(uniqid(time(), true)), 0, -1), true);
         unset($data['source']);
         unset($data['source_id']);
         if (isset($data['photo_url'])) {
             $photo_url = $data['photo_url'];
             unset($data['photo_url']);
         } else {
             $photo_url = false;
         }
         $contact->save($data);
         $contact_id = $contact->getId();
         if ($contact_id && $photo_url) {
             $photo_url_parts = explode('/', $photo_url);
             // copy photo to tmp dir
             $path = wa()->getTempPath('auth_photo/' . $contact_id . '.' . md5(end($photo_url_parts)), $app_id);
             $s = parse_url($photo_url, PHP_URL_SCHEME);
             $w = stream_get_wrappers();
             if (in_array($s, $w) && ini_get('allow_url_fopen')) {
                 $photo = file_get_contents($photo_url);
             } elseif (function_exists('curl_init')) {
                 $ch = curl_init($photo_url);
                 curl_setopt($ch, CURLOPT_HEADER, 0);
                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
                 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 25);
                 $photo = curl_exec($ch);
                 curl_close($ch);
             } else {
                 $photo = null;
             }
             if ($photo) {
                 file_put_contents($path, $photo);
                 $contact->setPhoto($path);
             }
         }
     } else {
         $contact = new waContact($contact_id);
     }
     // auth user
     if ($contact_id) {
         wa()->getAuth()->auth(array('id' => $contact_id));
         return $contact;
     }
     return false;
 }
 public function execute()
 {
     // only allowed to global admin
     if (!wa()->getUser()->getRights('webasyst', 'backend')) {
         throw new waRightsException('Access denied.');
     }
     $app_id = waRequest::post('app_id');
     $name = waRequest::post('name');
     $value = (int) waRequest::post('value');
     $contact_id = waRequest::get('id');
     $has_backend_access_old = $this->hasBackendAccess($contact_id);
     if (!$name && !$value) {
         $values = waRequest::post('app');
         if (!is_array($values)) {
             throw new waException('Bad values for access rights.');
         }
     } else {
         $values = array($name => $value);
     }
     $right_model = new waContactRightsModel();
     $is_admin = $right_model->get($contact_id, 'webasyst', 'backend', false);
     if ($is_admin && $app_id != 'webasyst') {
         throw new waException('Cannot change application rights for global admin.');
     }
     // If $contact_id used to have limited access and we're changing global admin privileges,
     // then need to notify all applications to remove their custom access records.
     if (!$is_admin && $app_id == 'webasyst' && $name == 'backend') {
         foreach (wa()->getApps() as $aid => $app) {
             try {
                 if (isset($app['rights']) && $app['rights']) {
                     $app_config = SystemConfig::getAppConfig($aid);
                     $class_name = $app_config->getPrefix() . "RightConfig";
                     $file_path = $app_config->getAppPath('lib/config/' . $class_name . ".class.php");
                     $right_config = null;
                     if (!file_exists($file_path)) {
                         continue;
                     }
                     waSystem::getInstance($aid, $app_config);
                     include_once $file_path;
                     /**
                      * @var waRightConfig
                      */
                     $right_config = new $class_name();
                     $right_config->clearRights($contact_id);
                 }
             } catch (Exception $e) {
                 // silently ignore other applications errors
             }
         }
     }
     // Update $app_id access records
     $app_config = SystemConfig::getAppConfig($app_id);
     $class_name = $app_config->getPrefix() . "RightConfig";
     $file_path = $app_config->getAppPath('lib/config/' . $class_name . ".class.php");
     $right_config = null;
     if (file_exists($file_path)) {
         // Init app
         waSystem::getInstance($app_id, $app_config);
         include_once $file_path;
         /**
          * @var waRightConfig
          */
         $right_config = new $class_name();
     }
     foreach ($values as $name => $value) {
         if ($right_config && $right_config->setRights($contact_id, $name, $value)) {
             // If we've got response from custom rights config, then no need to update main rights table
             continue;
         }
         // Set default limited rights
         if ($right_config && $name == 'backend' && $value == 1) {
             /**
              * @var $right_config waRightConfig
              */
             foreach ($right_config->setDefaultRights($contact_id) as $n => $v) {
                 $right_model->save($contact_id, $app_id, $n, $v);
             }
         }
         $right_model->save($contact_id, $app_id, $name, $value);
     }
     waSystem::setActive('contacts');
     if ($contact_id) {
         // TODO: use waContact method for disabling
         $is_user = waRequest::post('is_user', null, 'int');
         if ($is_user === -1 || $is_user === 0 || $is_user === 1) {
             $contact = new waContact($contact_id);
             $contact->save(array('is_user' => $is_user));
             $this->response['access_disable_msg'] = contactsHelper::getAccessDisableMsg($contact);
         }
     }
     $has_backend_access_new = $this->hasBackendAccess($contact_id);
     if ($has_backend_access_new !== $has_backend_access_old) {
         if ($has_backend_access_new) {
             $this->logAction("grant_backend_access", null, $contact_id);
         } else {
             $this->logAction("revoke_backend_access", null, $contact_id);
         }
     }
 }
 /**
  * @param array $data
  * @param array $errors
  * @return bool|waContact
  */
 public function signup($data, &$errors = array())
 {
     // check exists contacts
     $auth = wa()->getAuth();
     $field_id = $auth->getOption('login');
     if ($field_id == 'login') {
         $field_name = _ws('Login');
     } else {
         $field = waContactFields::get($field_id);
         if ($field) {
             $field_name = $field->getName();
         } else {
             $field_name = ucfirst($field_id);
         }
     }
     $is_error = false;
     // check passwords
     if ($data['password'] !== $data['password_confirm']) {
         $errors['password'] = array();
         $errors['password_confirm'] = array(_ws('Passwords do not match'));
         $is_error = true;
     } elseif (!$data['password']) {
         $errors['password'] = array();
         $errors['password_confirm'][] = _ws('Password can not be empty.');
         $is_error = true;
     }
     if (!$data[$field_id]) {
         $errors[$field_id] = array(sprintf(_ws("%s is required"), $field_name));
         $is_error = true;
     }
     $contact = $auth->getByLogin($data[$field_id]);
     if ($contact) {
         $errors[$field_id] = array(sprintf(_ws('User with the same %s is already registered'), $field_name));
         $is_error = true;
     }
     // set unconfirmed status for email
     if (isset($data['email']) && $data['email']) {
         $data['email'] = array('value' => $data['email'], 'status' => 'unconfirmed');
     }
     // check captcha
     $auth_config = wa()->getAuthConfig();
     if (isset($auth_config['signup_captcha']) && $auth_config['signup_captcha']) {
         if (!wa()->getCaptcha()->isValid()) {
             $errors['captcha'] = _ws('Invalid captcha');
             $is_error = true;
         }
     }
     if ($is_error) {
         return false;
     }
     // remove password_confirm field
     unset($data['password_confirm']);
     // set advansed data
     $data['create_method'] = 'signup';
     $data['create_ip'] = waRequest::getIp();
     $data['create_user_agent'] = waRequest::getUserAgent();
     // try save contact
     $contact = new waContact();
     if (!($errors = $contact->save($data, true))) {
         // after sign up callback
         $this->afterSignup($contact);
         // auth new contact
         wa()->getAuth()->auth($contact);
         return $contact;
     }
     if (isset($errors['name'])) {
         $errors['firstname'] = array();
         $errors['middlename'] = array();
         $errors['lastname'] = $errors['name'];
     }
     return false;
 }
示例#16
0
 /**
  * @param array $data
  * @return waContact
  * @throws waException
  */
 protected function createContact($data)
 {
     $app_id = $this->getStorage()->get('auth_app');
     $contact = new waContact();
     $data[$data['source'] . '_id'] = $data['source_id'];
     $data['create_method'] = $data['source'];
     $data['create_app_id'] = $app_id;
     // set random password (length = default hash length - 1, to disable ability auth using login and password)
     $contact->setPassword(substr(waContact::getPasswordHash(uniqid(time(), true)), 0, -1), true);
     unset($data['source']);
     unset($data['source_id']);
     if (isset($data['photo_url'])) {
         $photo_url = $data['photo_url'];
         unset($data['photo_url']);
     } else {
         $photo_url = false;
     }
     $contact->save($data);
     $contact_id = $contact->getId();
     if ($contact_id && $photo_url) {
         $photo_url_parts = explode('/', $photo_url);
         // copy photo to tmp dir
         $path = wa()->getTempPath('auth_photo/' . $contact_id . '.' . md5(end($photo_url_parts)), $app_id);
         $s = parse_url($photo_url, PHP_URL_SCHEME);
         $w = stream_get_wrappers();
         if (in_array($s, $w) && ini_get('allow_url_fopen')) {
             $photo = file_get_contents($photo_url);
         } elseif (function_exists('curl_init')) {
             $ch = curl_init($photo_url);
             curl_setopt($ch, CURLOPT_HEADER, 0);
             curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
             curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
             curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
             curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
             curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 25);
             $photo = curl_exec($ch);
             curl_close($ch);
         } else {
             $photo = null;
         }
         if ($photo) {
             file_put_contents($path, $photo);
             $contact->setPhoto($path);
         }
     }
     /**
      * @event signup
      * @param waContact $contact
      */
     wa()->event('signup', $contact);
     return $contact;
 }
 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()
 {
     if ($shipping_id = waRequest::post('shipping_id')) {
         if ($data = waRequest::post('customer_' . $shipping_id)) {
             $settings = wa('shop')->getConfig()->getCheckoutSettings();
             if (!isset($settings['contactinfo']) || !isset($settings['contactinfo']['fields']['address.shipping']) && !isset($settings['contactinfo']['fields']['address'])) {
                 $settings = wa('shop')->getConfig()->getCheckoutSettings(true);
             }
             $plugin = shopShipping::getPlugin(null, $shipping_id);
             $form = $this->getAddressForm($shipping_id, $plugin, $settings, array(), true);
             if (!$form->isValid()) {
                 return false;
             }
             $contact = $this->getContact();
             if (!$contact) {
                 $contact = new waContact();
             }
             if ($data && is_array($data)) {
                 foreach ($data as $field => $value) {
                     if (is_array($value) && ($old = $contact->get($field))) {
                         if (isset($old[0]['data'])) {
                             foreach ($old[0]['data'] as $k => $v) {
                                 if (!isset($value[$k])) {
                                     $value[$k] = $v;
                                 }
                             }
                         }
                     }
                     $contact->set($field, $value);
                 }
                 if (wa()->getUser()->isAuth()) {
                     $contact->save();
                 } else {
                     $this->setSessionData('contact', $contact);
                 }
             }
         }
         $rates = waRequest::post('rate_id');
         $rate_id = isset($rates[$shipping_id]) ? $rates[$shipping_id] : null;
         $rate = $this->getRate($shipping_id, $rate_id);
         if (is_string($rate)) {
             $rate = false;
         }
         $this->setSessionData('shipping', array('id' => $shipping_id, 'rate_id' => $rate_id, 'name' => $rate ? $rate['name'] : '', 'plugin' => $rate ? $rate['plugin'] : ''));
         if (!$rate) {
             return false;
         }
         if ($comment = waRequest::post('comment')) {
             $this->setSessionData('comment', $comment);
         }
         if ($shipping_params = waRequest::post('shipping_' . $shipping_id)) {
             $params = $this->getSessionData('params', array());
             $params['shipping'] = $shipping_params;
             $this->setSessionData('params', $params);
         }
         return true;
     } else {
         return false;
     }
 }
 public static function revokeUser($id)
 {
     // wa_contact
     $user = new waContact($id);
     $user['is_user'] = 0;
     $user['login'] = null;
     $user['password'] = '';
     $user->save();
     // user groups
     $ugm = new waUserGroupsModel();
     $ugm->delete($id);
     // Access rigths
     $right_model = new waContactRightsModel();
     $right_model->deleteByField('group_id', -$id);
     // Custom application access rigths
     foreach (wa()->getApps() as $aid => $app) {
         if (isset($app['rights']) && $app['rights']) {
             $app_config = SystemConfig::getAppConfig($aid);
             $class_name = $app_config->getPrefix() . "RightConfig";
             $file_path = $app_config->getAppPath('lib/config/' . $class_name . ".class.php");
             $right_config = null;
             if (!file_exists($file_path)) {
                 continue;
             }
             waSystem::getInstance($aid, $app_config);
             include_once $file_path;
             /**
              * @var waRightConfig $right_config
              */
             $right_config = new $class_name();
             $right_config->clearRights($id);
         }
     }
 }
示例#20
0
 /**
  * @param array $data
  * @param array $errors
  * @return bool|waContact
  */
 public function signup($data, &$errors = array())
 {
     // check exists contacts
     $auth = wa()->getAuth();
     $field_id = $auth->getOption('login');
     if ($field_id == 'login') {
         $field_name = _ws('Login');
     } else {
         $field = waContactFields::get($field_id);
         if ($field) {
             $field_name = $field->getName();
         } else {
             $field_name = ucfirst($field_id);
         }
     }
     $is_error = false;
     // check passwords
     if ($data['password'] !== $data['password_confirm']) {
         $errors['password'] = array();
         $errors['password_confirm'] = array(_ws('Passwords do not match'));
         $is_error = true;
     } elseif (!$data['password']) {
         $errors['password'] = array();
         $errors['password_confirm'][] = _ws('Password can not be empty.');
         $is_error = true;
     }
     if (!$data[$field_id]) {
         $errors[$field_id] = array(sprintf(_ws("%s is required"), $field_name));
         $is_error = true;
     }
     if (!$is_error) {
         $contact = $auth->getByLogin($data[$field_id]);
         if ($contact) {
             $errors[$field_id] = array(sprintf(_ws('User with the same %s is already registered'), $field_name));
             $is_error = true;
         }
     }
     $auth_config = wa()->getAuthConfig();
     // set unknown or unconfirmed status for email
     if (isset($data['email']) && $data['email']) {
         if (!empty($auth_config['params']['confirm_email'])) {
             $email_status = 'unconfirmed';
         } else {
             $email_status = 'unknown';
         }
         $data['email'] = array('value' => $data['email'], 'status' => $email_status);
     }
     // check captcha
     if (isset($auth_config['signup_captcha']) && $auth_config['signup_captcha']) {
         if (!wa()->getCaptcha()->isValid()) {
             $errors['captcha'] = _ws('Invalid captcha');
             $is_error = true;
         }
     }
     if (is_array($auth_config['fields'])) {
         foreach ($auth_config['fields'] as $fld_id => $fld) {
             if (array_key_exists('required', $fld) && !$data[$fld_id] && $fld_id !== 'password') {
                 $field = waContactFields::get($fld_id);
                 if (!empty($fld['caption'])) {
                     $field_name = $fld['caption'];
                 } else {
                     if ($field) {
                         $field_name = $field->getName();
                     } else {
                         $field_name = ucfirst($fld_id);
                     }
                 }
                 $errors[$fld_id] = array(sprintf(_ws("%s is required"), $field_name));
                 $is_error = true;
             }
         }
     }
     if ($is_error) {
         return false;
     }
     if (isset($data['birthday']) && is_array($data['birthday']['value'])) {
         foreach ($data['birthday']['value'] as $bd_id => $bd_val) {
             if (strlen($bd_val) === 0) {
                 $data['birthday']['value'][$bd_id] = null;
             }
         }
     }
     // remove password_confirm field
     unset($data['password_confirm']);
     // set advanced data
     $data['create_method'] = 'signup';
     $data['create_ip'] = waRequest::getIp();
     $data['create_user_agent'] = waRequest::getUserAgent();
     // try save contact
     $contact = new waContact();
     if (!($errors = $contact->save($data, true))) {
         if (!empty($data['email'])) {
             $this->send($contact);
         }
         /**
          * @event signup
          * @param waContact $contact
          */
         wa()->event('signup', $contact);
         // after sign up callback
         $this->afterSignup($contact);
         // try auth new contact
         try {
             if (empty($data['email']) || empty($auth_config['params']['confirm_email'])) {
                 if (wa()->getAuth()->auth($contact)) {
                     $this->logAction('signup', wa()->getEnv());
                 }
             }
         } catch (waException $e) {
             $errors = array('auth' => $e->getMessage());
         }
         return $contact;
     }
     if (isset($errors['name'])) {
         $errors['firstname'] = array();
         $errors['middlename'] = array();
         $errors['lastname'] = $errors['name'];
     }
     return false;
 }
 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());
 }
示例#22
0
 public function oauth($provider, $config, $token, $code = null)
 {
     /**
      * @var waOAuth2Adapter $auth
      */
     $auth = wa()->getAuth($provider, $config);
     if (!$token && $code) {
         $token = $auth->getAccessToken($code);
     }
     $data = $auth->getUserData($token);
     if (wa()->getUser()->getId()) {
         wa()->getUser()->save(array($data['source'] . '_id' => $data['source_id']));
         return wa()->getUser();
     }
     $app_id = wa()->getApp();
     $contact_id = 0;
     // find contact by auth adapter id, i.e. facebook_id
     $contact_data_model = new waContactDataModel();
     $row = $contact_data_model->getByField(array('field' => $data['source'] . '_id', 'value' => $data['source_id'], 'sort' => 0));
     if ($row) {
         $contact_id = $row['contact_id'];
     }
     // try find user by email
     if (!$contact_id && isset($data['email'])) {
         $sql = "SELECT c.id FROM wa_contact_emails e\n            JOIN wa_contact c ON e.contact_id = c.id\n            WHERE e.email = s:email AND e.sort = 0 AND c.password != ''";
         $contact_model = new waContactModel();
         $contact_id = $contact_model->query($sql, array('email' => $data['email']))->fetchField('id');
         // save source_id
         if ($contact_id) {
             $contact_data_model->insert(array('contact_id' => $contact_id, 'field' => $data['source'] . '_id', 'value' => $data['source_id'], 'sort' => 0));
         }
     }
     // create new contact
     if (!$contact_id) {
         $contact = new waContact();
         $data[$data['source'] . '_id'] = $data['source_id'];
         $data['create_method'] = $data['source'];
         $data['create_app_id'] = $app_id;
         // set random password (length = default hash length - 1, to disable ability auth using login and password)
         $contact->setPassword(substr(waContact::getPasswordHash(uniqid(time(), true)), 0, -1), true);
         unset($data['source']);
         unset($data['source_id']);
         if (isset($data['photo_url'])) {
             $photo_url = $data['photo_url'];
             unset($data['photo_url']);
         } else {
             $photo_url = false;
         }
         $contact->save($data);
         $contact_id = $contact->getId();
         if ($contact_id && $photo_url) {
             $photo_url_parts = explode('/', $photo_url);
             // copy photo to tmp dir
             $path = wa()->getTempPath('auth_photo/' . $contact_id . '.' . md5(end($photo_url_parts)), $app_id);
             if (function_exists('curl_init')) {
                 $ch = curl_init($photo_url);
                 curl_setopt($ch, CURLOPT_HEADER, 0);
                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 25);
                 $photo = curl_exec($ch);
                 curl_close($ch);
             } else {
                 $photo = file_get_contents($photo_url);
             }
             if ($photo) {
                 file_put_contents($path, $photo);
                 $contact->setPhoto($path);
             }
         }
     } else {
         $contact = new waContact($contact_id);
     }
     // auth user
     if ($contact_id) {
         wa()->getAuth()->auth(array('id' => $contact_id));
         return $contact;
     }
     return false;
 }