protected function assignUrls()
 {
     $this->view->assign('tmpimage_url', '?module=photo&action=tmpimage');
     $this->view->assign('delete_url', '?module=photo&action=delete&id=' . $this->contact->getId());
     $this->view->assign('crop_url', '?module=photo&action=crop');
     $this->view->assign('back_url', '#/contact/' . $this->contact->getId() . '/');
 }
 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 save(waContact $contact, $fields)
 {
     if (!isset($fields['categories'])) {
         return TRUE;
     }
     if (empty($fields['categories'][0])) {
         $fields['categories'] = array();
     }
     if (wa()->getApp() == 'contacts' && !wa()->getUser()->getRights('contacts', 'category.all')) {
         // only save categories available for current user to see, and do not change others
         $crm = new contactsRightsModel();
         $cats = $this->getModel()->getContactCategories($contact->getId());
         $allowed = $crm->getAllowedCategories();
         $set = $fields['categories'] ? array_flip($fields['categories']) : array();
         foreach ($allowed as $id => $cat) {
             if (isset($set[$id])) {
                 $cats[$id] = true;
             } else {
                 unset($cats[$id]);
             }
         }
         $fields['categories'] = array_keys($cats);
     }
     $this->getModel()->setContactCategories($contact->getId(), $fields['categories']);
     return TRUE;
 }
 public function save(waContact $contact, $fields)
 {
     if (!isset($fields['email'])) {
         return true;
     }
     $data = array();
     $delete_flag = false;
     $sort = 0;
     foreach ($fields['email'] as $sort => $field) {
         if ($field === null) {
             $sql = "DELETE FROM " . $this->getModel()->getTableName() . " \n                        WHERE contact_id = i:id AND sort >= i:sort";
             $this->getModel()->exec($sql, array('id' => $contact->getId(), 'sort' => $sort));
             continue;
         }
         $status = false;
         if (is_array($field)) {
             $value = $field['value'];
             if (isset($field['status'])) {
                 $status = $field['status'];
             }
         } else {
             $value = $field;
         }
         if (!$status) {
             $status = wa()->getEnv() == 'frontend' ? 'unconfirmed' : 'unknown';
         }
         $ext = is_array($field) && isset($field['ext']) ? $field['ext'] : '';
         if ($value) {
             $data[$sort] = array('email' => $value, 'ext' => $ext, 'status' => $status);
         } else {
             $sql = "DELETE FROM " . $this->getModel()->getTableName() . " \n                        WHERE contact_id = i:id AND sort = i:sort";
             $this->getModel()->exec($sql, array('id' => $contact->getId(), 'sort' => $sort));
             $delete_flag = true;
             continue;
         }
     }
     if ($delete_flag) {
         $sql = "DELETE FROM " . $this->getModel()->getTableName() . " \n                        WHERE contact_id = i:id AND sort >= i:sort";
         $this->getModel()->exec($sql, array('id' => $contact->getId(), 'sort' => $sort));
     }
     if ($data) {
         // find records to update
         $rows = $this->getModel()->getByField(array('contact_id' => $contact->getId(), 'sort' => array_keys($data)), true);
         foreach ($rows as $row) {
             $this->getModel()->updateById($row['id'], $data[$row['sort']]);
             unset($data[$row['sort']]);
         }
         foreach ($data as $k => $row) {
             $data[$k] = $contact->getId() . ", '" . $this->getModel()->escape($row['email']) . "', '" . $this->getModel()->escape($row['ext']) . "', " . (int) $k . ", '" . $this->getModel()->escape($row['status']) . "'";
         }
         if ($data) {
             // insert new records
             $sql = "INSERT INTO " . $this->getModel()->getTableName() . " (contact_id, email, ext, sort, status)\n                        VALUES (" . implode("), (", $data) . ")";
             return $this->getModel()->exec($sql);
         }
     }
     return true;
 }
 public function save(waContact $contact, $fields)
 {
     if (!$this->model) {
         $this->model = new waContactModel();
     }
     if ($contact->getId()) {
         return $this->model->updateById($contact->getId(), $fields);
     } else {
         return $this->model->insert($fields);
     }
 }
 public function save(waContact $contact, $fields)
 {
     $this->getModel();
     if (isset($fields['birthday']) && isset($fields['birthday']['value'])) {
         $fields = array_merge($fields, $fields['birthday']['value']);
         unset($fields['birthday']);
     }
     if ($contact->getId()) {
         return $this->model->updateById($contact->getId(), $fields);
     } else {
         return $this->model->insert($fields);
     }
 }
 /**
  * Обработчик хука signup
  *
  * @param waContact $contact
  */
 public function handlerSignup($contact)
 {
     $category_id = $this->getSettings('category_id');
     $ContactCategory = new waContactCategoryModel();
     // проверим на всякий случай есть-ли еще такая категория
     // а то вдруг ее какой-нибудь дурак удалил, а в настройке плагина она осталась
     // ресурсов на проверку нужно мало, а дураков на свете много
     $category_id = $ContactCategory->select('id')->where('id=:id', array('id' => $category_id))->fetchField();
     if ($contact instanceof waContact && $contact->getId() && $category_id) {
         $ContactCategories = new waContactCategoriesModel();
         $ContactCategories->add($contact->getId(), $category_id);
     }
 }
 protected function assignUrls()
 {
     if (!empty($this->params['limited_own_profile'])) {
         $this->view->assign('tmpimage_url', '?module=profile&action=tmpimage');
         $this->view->assign('delete_url', '?module=profile&action=deletePhoto');
         $this->view->assign('crop_url', '?module=profile&action=savePhoto');
         $this->view->assign('back_url', '?module=profile');
     } else {
         $this->view->assign('tmpimage_url', '?module=photo&action=tmpimage');
         $this->view->assign('delete_url', '?module=photo&action=delete&id=' . $this->contact->getId());
         $this->view->assign('crop_url', '?module=photo&action=crop');
         $this->view->assign('back_url', '#/contact/' . $this->contact->getId() . '/');
     }
 }
 /**
  * @param waContact $contact
  * @param array|string $fields
  * @param bool $old_value
  * @return array|void
  */
 public function get(waContact $contact, $fields = array(), $old_value = false)
 {
     if (!is_array($fields)) {
         $all_fields = array($fields);
     } else {
         $all_fields = $fields;
     }
     $result = array();
     $load_fields = array();
     foreach ($all_fields as $field_id) {
         if ($contact->issetCache($field_id, $old_value)) {
             $result[$field_id] = $contact->getCache($field_id, $old_value);
         } else {
             if (strpos($field_id, ':') === false) {
                 $result[$field_id] = null;
             }
             $load_fields[] = $field_id;
         }
     }
     if ((!$fields || $load_fields) && $contact->getId()) {
         if ($load_result = $this->load($contact, $load_fields)) {
             $result = $load_result + $result;
         }
         $contact->setCache($result);
     }
     if (!is_array($fields)) {
         return $result[$fields];
     } else {
         return $result;
     }
 }
 public function logProfileEdit($old_data, $new_data)
 {
     $diff = array();
     wa_array_diff_r($old_data, $new_data, $diff);
     if (!empty($diff)) {
         $this->logAction('my_profile_edit', $diff, null, $this->contact->getId());
     }
 }
 public function logContactEdit($old_data, $new_data)
 {
     $diff = array();
     wa_array_diff_r($old_data, $new_data, $diff);
     if (!empty($diff)) {
         $this->logAction('contact_edit', $diff, $this->contact->getId());
     }
 }
 public function prepareSave($value, waContact $contact = null)
 {
     if (!$contact) {
         return $value;
     }
     if ($contact['is_company']) {
         $name = $contact['company'];
     } else {
         $fst = trim($contact['firstname']);
         $mdl = trim($contact['middlename']);
         $lst = trim($contact['lastname']);
         $cmp = trim($contact['company']);
         $eml = trim($contact->get('email', 'default'));
         $name = array();
         if ($fst || $fst === '0' || $mdl || $mdl === '0' || $lst || $lst === '0') {
             $name[] = $lst;
             $name[] = $fst;
             $name[] = $mdl;
         } else {
             if ($cmp || $cmp === '0') {
                 $name[] = $cmp;
             } else {
                 if ($eml) {
                     $pos = strpos($eml, '@');
                     if ($pos == false) {
                         $name[] = $eml;
                     } else {
                         $name[] = substr($eml, 0, $pos);
                     }
                 }
             }
         }
         foreach ($name as $i => $n) {
             if (!$n && $n !== '0') {
                 unset($name[$i]);
             }
         }
         $name = trim(implode(' ', $name));
     }
     if (!$name && $name !== '0') {
         $name = $contact->getId() ? $contact->getId() : '';
     }
     return $name;
 }
 /**
  * @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 save(waContact $contact, $fields)
 {
     if (!isset($fields['categories'])) {
         return TRUE;
     }
     if (empty($fields['categories'][0])) {
         $fields['categories'] = array();
     }
     $this->getModel()->setContactCategories($contact->getId(), $fields['categories']);
     return TRUE;
 }
    /**
     * This method is called upon successful creation of a new contact
     * It sends a welcome message to the new user
     *
     * Этот метод вызывается после успешного создания нового контакта
     * В нём будет отправлено приветственное письмо новому пользователю
     *
     * @param waContact $contact
     */
    public function afterSignup(waContact $contact)
    {
        // Adding contact to system category guestbook2 (named by the app ID)
        // to be able to easily view all contacts registered in the guestbook
        // or who have left a comment, in the Contacts app
        // Добавляем контакт в системную категорию guestbook2 (по ID приложения)
        // Чтобы в приложении Контакты можно было легко посмотреть все контакты,
        // которые были зарегистрированы в гостевой книге, либо что-то написали в ней
        $contact->addToCategory($this->getAppId());
        // Getting contact's main email address
        // Получаем главный email контакта
        $email = $contact->get('email', 'default');
        // If not specified, do nothing
        // Если он не задан, ничего не делаем
        if (!$email) {
            return;
        }
        // Generating random hash
        // Генерируем случайный хэш
        $hash = md5(uniqid(time(), true));
        // Saving the hash in contact info table with the app id
        // Сохраняем этот хэш в таблице свойств контакта, указывая приложение
        $contact->setSettings($this->getAppId(), 'confirm_hash', $hash);
        // Adding contact id to the hash for easier search and verification by hash (see guestbook2FrontendConfirmAction)
        // Добавляем в хэш номер контакта, чтобы было проще искать и проверять по хэшу (см. guestbook2FrontendConfirmAction)
        $hash = substr($hash, 0, 16) . $contact->getId() . substr($hash, 16);
        // Creating confirmation link with an absolute URL
        // Формируем абсолютную ссылку подтверждения
        $confirmation_url = wa()->getRouteUrl('/frontend/confirm', true) . "?hash=" . $hash;
        // Creating a link to the app's home page with an absolute URL
        // Формируем абсолютную ссылку на главную страницу приложения
        $root_url = wa()->getRouteUrl('/frontend', true);
        // Getting account name
        // Получаем название аккаунта
        $app_settings_model = new waAppSettingsModel();
        $account_name = htmlspecialchars($app_settings_model->get('webasyst', 'name', 'Webasyst'));
        // Generating message body
        // Формируем тело письма
        $body = _w('Hi') . ' ' . htmlspecialchars($contact->getName()) . ',<br>
<br>
' . sprintf(_w('Please confirm your account at %s by clicking this link:'), $account_name) . '<br>
<a href="' . $confirmation_url . '"><strong>' . $confirmation_url . '</strong></a><br>
<br>
--<br>
' . $account_name . '<br>
<a href="' . $root_url . '">' . $root_url . '</a>';
        $subject = _w('Confirm your account');
        // Sending email message
        // Отправляем письмо
        $message = new waMailMessage($subject, $body);
        $message->setTo($email, $contact->getName());
        $message->send();
    }
 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');
             }
         }
         $response['top'] = $this->contact->getTopFields();
     }
     // Reload page with new language if user just changed it in own profile
     if ($oldLocale != $this->contact->getLocale()) {
         $response['reload'] = TRUE;
     }
     $response['id'] = $this->contact->getId();
     $this->response = array('errors' => $errors, 'data' => $response);
 }
    /**
     * Этот метод вызывается после успешного создания нового контакта
     * В нём будет отправлено приветственное письмо новому пользователю
     * @param waContact $contact
     */
    public function afterSignup(waContact $contact)
    {
        // Добавляем контакт в системную категорию guestbook2 (по ID приложения)
        // Чтобы в приложении контакты можно было легко посмотреть все контакты,
        // которые были зарегистрированы в гостевой книге, либо что-то написали в ней
        $contact->addToCategory($this->getAppId());
        // Получаем главный email контакта
        $email = $contact->get('email', 'default');
        // Если он не задан, ничего не делаем
        if (!$email) {
            return;
        }
        // Генерируем случайный хэш
        $hash = md5(uniqid(time(), true));
        // Сохраняем этот хэш в таблице свойств контакта, указывая приложение
        $contact->setSettings($this->getAppId(), 'confirm_hash', $hash);
        // Добавляем в хэш номер контакта, чтобы было проще искать и проверять по хэшу (см. guestbook2FrontendConfirmAction)
        $hash = substr($hash, 0, 16) . $contact->getId() . substr($hash, 16);
        // Формируем абсолютную ссылку подтверждения
        $confirmation_url = wa()->getRouteUrl('/frontend/confirm', true) . "?hash=" . $hash;
        // Формируем абсолютную ссылку на главную страницу приложения
        $root_url = wa()->getRouteUrl('/frontend', true);
        // Получаем название аккаунта
        $app_settings_model = new waAppSettingsModel();
        $account_name = htmlspecialchars($app_settings_model->get('webasyst', 'name', 'Webasyst'));
        // Формируем тело письма
        $body = _w('Hi') . ' ' . htmlspecialchars($contact->getName()) . ',<br>
<br>
' . sprintf(_w('Please confirm your account at %s by clicking this link:'), $account_name) . '<br>
<a href="' . $confirmation_url . '"><strong>' . $confirmation_url . '</strong></a><br>
<br>
--<br>
' . $account_name . '<br>
<a href="' . $root_url . '">' . $root_url . '</a>';
        $subject = _w('Confirm your account');
        // Отправляем письмо
        $message = new waMailMessage($subject, $body);
        $message->setTo($email, $contact->getName());
        $message->send();
    }
 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 save(waContact $contact, $fields)
 {
     $contact_id = $contact->getId();
     $data = array();
     foreach ($fields as $field => $value) {
         $f = waContactFields::get($field);
         if (!$f || !$f->isMulti()) {
             if ($f instanceof waContactCompositeField) {
                 /**
                  * @var $f waContactCompositeField
                  */
                 $delete = array();
                 if (isset($value['data'])) {
                     $value = $value['data'];
                 } elseif (isset($value['value']) && is_array($value['value'])) {
                     $value = $value['value'];
                 }
                 foreach ($f->getField(false) as $subfield) {
                     if (isset($value[$subfield]) && $value[$subfield]) {
                         $data[$field . ":" . $subfield][0] = array('value' => $value[$subfield], 'ext' => '');
                     } else {
                         $delete[] = $field . ":" . $subfield;
                     }
                 }
                 if ($delete) {
                     $sql = "DELETE FROM " . $this->getModel()->getTableName() . " \n                                WHERE contact_id = " . (int) $contact_id . " AND field IN ('" . implode("', '", $this->getModel()->escape($delete)) . "')";
                     $this->getModel()->exec($sql);
                 }
             } else {
                 if ($value === null) {
                     $sql = "DELETE FROM " . $this->getModel()->getTableName() . "\n                                WHERE contact_id = " . (int) $contact_id . " AND field = '" . $this->getModel()->escape($field) . "'";
                     $this->getModel()->exec($sql);
                 } else {
                     $data[$field][0] = array('value' => $value, 'ext' => '');
                 }
             }
         } elseif ($f->isMulti()) {
             $sort = 0;
             if (!is_array($value) || isset($value['value'])) {
                 $value = array($value);
             }
             $delete_flag = false;
             foreach ($value as $value_info) {
                 if ($value_info === null) {
                     $sql = "DELETE FROM " . $this->getModel()->getTableName() . " \n                                WHERE contact_id = i:id AND " . ($f instanceof waContactCompositeField ? "field LIKE s:field" : "field = s:field") . " \n                                AND sort >= i:sort";
                     $this->getModel()->exec($sql, array('id' => $contact_id, 'field' => $field . ($f instanceof waContactCompositeField ? ':%' : ''), 'sort' => $sort));
                     continue;
                 } elseif (!is_array($value_info) && !strlen($value_info)) {
                     $sql = "DELETE FROM " . $this->getModel()->getTableName() . " \n                                WHERE contact_id = i:id AND field = s:field AND sort = i:sort";
                     $this->getModel()->exec($sql, array('id' => $contact_id, 'field' => $field, 'sort' => $sort));
                     continue;
                 }
                 if (is_array($value_info) && (isset($value_info['data']) || $f instanceof waContactCompositeField)) {
                     $v = isset($value_info['data']) ? $value_info['data'] : $value_info['value'];
                     $ext = isset($value_info['ext']) ? $value_info['ext'] : '';
                     foreach ($v as $subfield => $subvalue) {
                         if (!strlen($subvalue)) {
                             $sql = "DELETE FROM " . $this->getModel()->getTableName() . " \n                                            WHERE contact_id = i:id AND field = s:field AND sort = i:sort";
                             $this->getModel()->exec($sql, array('id' => $contact_id, 'field' => $field . ":" . $subfield, 'sort' => $sort));
                         } else {
                             $data[$field . ":" . $subfield][$sort] = array('value' => $subvalue, 'ext' => $ext);
                         }
                     }
                 } else {
                     if (is_array($value_info)) {
                         $v = $value_info['value'];
                         $ext = isset($value_info['ext']) ? $value_info['ext'] : '';
                     } else {
                         $v = $value_info;
                         $ext = '';
                     }
                     if (!strlen($v)) {
                         $sql = "DELETE FROM " . $this->getModel()->getTableName() . " \n                                    WHERE contact_id = i:id AND field = s:field AND sort = i:sort";
                         $this->getModel()->exec($sql, array('id' => $contact_id, 'field' => $field, 'sort' => $sort));
                         $delete_flag = true;
                         continue;
                     }
                     $data[$field][$sort] = array('value' => $v, 'ext' => $ext);
                 }
                 $sort++;
             }
             if ($delete_flag) {
                 $sql = "DELETE FROM " . $this->getModel()->getTableName() . " \n                            WHERE contact_id = i:id AND field = s:field AND sort >= i:sort";
                 $this->getModel()->exec($sql, array('id' => $contact_id, 'field' => $field, 'sort' => $sort));
             }
         }
     }
     if ($data) {
         // find records to update
         $rows = $this->getModel()->getByField(array('contact_id' => $contact->getId(), 'field' => array_keys($data)), true);
         foreach ($rows as $row) {
             if (isset($data[$row['field']][$row['sort']])) {
                 $this->getModel()->updateById($row['id'], $data[$row['field']][$row['sort']]);
                 unset($data[$row['field']][$row['sort']]);
             }
         }
         $insert = array();
         foreach ($data as $f => $f_rows) {
             foreach ($f_rows as $s => $row) {
                 $insert[] = $contact->getId() . ", '" . $this->getModel()->escape($f) . "', '" . $this->getModel()->escape($row['ext']) . "', '" . $this->getModel()->escape($row['value']) . "', " . (int) $s;
             }
         }
         // insert new records
         if ($insert) {
             $sql = "INSERT INTO " . $this->getModel()->getTableName() . " (contact_id, field, ext, value, sort)\n                        VALUES (" . implode("), (", $insert) . ")";
             return $this->getModel()->exec($sql);
         }
     }
     return true;
 }
 /**
  * @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;
 }
Beispiel #21
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;
 }
 private function sendConfirmationLink(waContact $contact)
 {
     $config = wa()->getAuthConfig();
     if (!empty($config['params']['confirm_email'])) {
         $confirmation_hash = md5(time() . 'rfb2:zfbdbawrsddswr4$h5t3/.`w' . mt_rand() . mt_rand() . mt_rand());
         $contact->setSettings(wa()->getApp(), "email_confirmation_hash", $confirmation_hash);
         $ce = new waContactEmailsModel();
         $unconfirmed_email = $ce->getByField(array('contact_id' => $contact->getId(), 'email' => $contact->get('email', 'default'), 'status' => 'unconfirmed'));
         $hash = substr($confirmation_hash, 0, 16) . $unconfirmed_email['id'] . substr($confirmation_hash, -16);
         $this->view->assign('email_confirmation_hash', $hash);
         return true;
     }
     return false;
 }
 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;
     }
 }
 /**
  * @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;
 }