public function validate($data, $contact_id = null) { $errors = parent::validate($data, $contact_id); $email_model = new waContactEmailsModel(); $contact_model = new waContactModel(); if ($this->isMulti()) { if (!empty($data[0]) && $contact_id) { $c = $contact_model->getById($contact_id); if (!$c['password']) { return $errors; } $value = $this->format($data[0], 'value'); $id = $email_model->getContactWithPassword($value); if ($id && $id != $contact_id) { $errors[0] = sprintf(_ws('User with the same %s is already registered'), 'email'); } } } else { $value = $this->format($data, 'value'); if ($value) { if ($contact_id) { $c = $contact_model->getById($contact_id); if (!$c['password']) { return $errors; } } $id = $email_model->getContactWithPassword($value); if ($id && $id != $contact_id) { $errors = sprintf(_ws('User with the same %s is already registered'), 'email'); } } } return $errors; }
/** * @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; }
/** * @param array $data * @return waContact */ protected function afterAuth($data) { $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']; } if (wa()->getUser()->isAuth()) { $contact = wa()->getUser(); if ($contact_id && $contact_id != $contact->getId()) { // delete old link $contact_data_model->deleteByField(array('contact_id' => $contact_id, 'field' => $data['source'] . '_id')); // save new link $contact->save(array($data['source'] . '_id' => $data['source_id'])); } $contact_id = $contact->getId(); } // 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) { $tmp = array('contact_id' => $contact_id, 'field' => $data['source'] . '_id', 'sort' => 0); // contact already has this source $row = $contact_data_model->getByField($tmp); if ($row) { $contact_data_model->updateByField($tmp, array('value' => $data['source_id'])); } else { $tmp['value'] = $data['source_id']; $contact_data_model->insert($tmp); } } } // create new contact if (!$contact_id) { $contact = $this->createContact($data); if ($contact) { $contact_id = $contact->getId(); } } elseif (empty($contact)) { $contact = new waContact($contact_id); } // auth user if ($contact_id) { if (!wa()->getUser()->isAuth()) { wa()->getAuth()->auth(array('id' => $contact_id)); } return $contact; } return false; }
public function execute() { $superadmin = $this->getUser()->getRights('webasyst', 'backend'); $contacts = waRequest::post('id', array(), 'array_int'); // do not try to delete self if (in_array($this->getUser()->getId(), $contacts)) { throw new waRightsException('Access denied: attempt to delete own account.'); } $this->getRights(); $crm = new contactsRightsModel(); $contacts = $crm->getAllowedContactsIds($contacts); if (!$contacts) { throw new waRightsException('Access denied: no access to contacts '); } // Deletion of contacts with links to other applications is only allowed to superadmins if (!$superadmin && ($links = wa()->event('links', $contacts))) { foreach ($links as $app_id => $l) { foreach ($l as $contact_id => $contact_links) { if ($contact_links) { throw new waRightsException('Access denied: only superadmin is allowed to delete contacts with links to other applications.'); } } } } // Are there users among $contacts? $um = new waUserModel(); $users = array_keys($um->getByField(array('id' => $contacts, 'is_user' => 1), 'id')); // deletion of users is only allowed to superadmins if (!$superadmin && $users) { throw new waRightsException('Access denied: only superadmin is allowed to delete users.'); } // Revoke user access before deletion foreach ($users as $user_id) { waUser::revokeUser($user_id); } $contact_model = new waContactModel(); $cnt = count($contacts); if ($cnt > 30) { $log_params = $cnt; } else { // contact names $log_params = $contact_model->getName($contacts); } $history_model = new contactsHistoryModel(); foreach ($contacts as $contact_id) { $history_model->deleteByField(array('type' => 'add', 'hash' => '/contact/' . $contact_id)); } // Bye bye... $contact_model->delete($contacts); // also throws a contacts.delete event $this->response['deleted'] = $cnt; $this->response['message'] = sprintf(_w("%d contact has been deleted", "%d contacts have been deleted", $this->response['deleted']), $this->response['deleted']); $this->logAction('contact_delete', $log_params); }
/** * @param array $params deleted contact_id * @see waEventHandler::execute() * @return void */ public function execute($params) { // Получаем все удаляемые контакты $contact_model = new waContactModel(); $contacts = $contact_model->getByField('id', $params, true); $guestbook_model = new guestbook2Model(); foreach ($contacts as $contact) { // Обновляем записи гостевой книги, чтобы не было "битых" contact_id $guestbook_model->updateByField('contact_id', $contact['id'], array('contact_id' => 0, 'name' => $contact['name'])); } }
public function execute() { $ids = waRequest::post('id', array(), 'array_int'); if (!$ids) { $ids = (int) waRequest::get('id'); if (!$ids) { throw new Exception('No ids specified.'); } $ids = array($ids); } // do not try to delete self if (in_array($this->getUser()->getId(), $ids)) { die('<p>' . _w('You can not delete yourself.') . '</p><p>' . _w('Please eliminate yourself from deletion list.') . '</p>'); } // Only allow actions with contacts available for current user if (!$this->getRights('category.all')) { $crm = new contactsRightsModel(); $ccm = new waContactCategoriesModel(); $allowed = array_keys($crm->getAllowedCategories()); foreach ($ccm->getContactsCategories($ids) as $id => $cats) { if (!array_intersect($allowed, $cats)) { throw new waRightsException('Access denied'); } } } $superadmin = wa()->getUser()->getRights('webasyst', 'backend'); $result = wa()->event('links', $ids); $this->view->assign('apps', wa()->getApps()); $links = array(); foreach ($result as $app_id => $app_links) { foreach ($app_links as $contact_id => $contact_links) { if ($contact_links) { $links[$contact_id][$app_id] = $contact_links; } } } // Do not allow non-superadmin to remove users if (!$superadmin) { $um = new waUserModel(); $users = array_keys($um->getByField(array('id' => $ids, 'is_user' => 1), 'id')); foreach ($users as $user_id) { if (!isset($links[$user_id]['contacts'])) { $links[$user_id]['contacts'] = array(); } $links[$user_id]['contacts'][] = array('user', 1); } } $contact_model = new waContactModel(); $this->view->assign('ids', $superadmin ? $ids : array_diff($ids, array_keys($links))); $this->view->assign('contacts', $contact_model->getName(array_keys($links))); $this->view->assign('superadmin', $superadmin); $this->view->assign('all', count($ids)); $this->view->assign('links', $links); }
/** * @param array $params deleted contact_id * @see waEventHandler::execute() * @return void */ public function execute($params) { // Getting all contacts to be deleted // Получаем все удаляемые контакты $contact_model = new waContactModel(); $contacts = $contact_model->getByField('id', $params, true); $guestbook_model = new guestbook2Model(); foreach ($contacts as $contact) { // Updating guestbook records to avoid appearance of non-existent contact_id values // Обновляем записи гостевой книги, чтобы не было "битых" contact_id $guestbook_model->updateByField('contact_id', $contact['id'], array('contact_id' => 0, 'name' => $contact['name'])); } }
/** * Get list of contacts (IDs) and remove not allowed contacts * @param type $contact_ids */ public function getAllowedContactsIds(array $contact_ids) { $contact_ids = array_map('intval', $contact_ids); if (wa()->getUser()->getRights('contacts', 'edit', true)) { return $contact_ids; } if (!$contact_ids) { return array(); } $m = new waContactModel(); $user_id = wa()->getUser()->getId(); return array_keys($m->select('id')->where("create_contact_id = {$user_id} \n AND id IN(" . implode(',', $contact_ids) . ")")->fetchAll('id')); }
/** * @param int[] $params Deleted contact_id * @see waEventHandler::execute() * @return void */ public function execute($params) { $contact_model = new waContactModel(); $contacts = $contact_model->getByField('id', $params, true); $post_model = new blogPostModel(); $comment_model = new blogCommentModel(); foreach ($contacts as $contact) { $data = array('contact_id' => 0, 'contact_name' => $contact['name']); $post_model->updateByField('contact_id', $contact['id'], $data); $data = array('contact_id' => 0, 'name' => $contact['name'], 'auth_provider' => null); $comment_model->updateByField('contact_id', $contact['id'], $data); } }
public function execute() { $superadmin = $this->getUser()->getRights('webasyst', 'backend'); $contacts = waRequest::post('id', array(), 'array_int'); // do not try to delete self if (in_array($this->getUser()->getId(), $contacts)) { throw new waRightsException('Access denied: attempt to delete own account.'); } // Only allow actions with contacts available for current user if (!$this->getRights('category.all')) { $crm = new contactsRightsModel(); $ccm = new waContactCategoriesModel(); $allowed = array_keys($crm->getAllowedCategories()); foreach ($ccm->getContactsCategories($contacts) as $id => $cats) { if (!array_intersect($allowed, $cats)) { throw new waRightsException('Access denied: no access to contact ' . $id); } } } // Deletion of contacts with links to other applications is only allowed to superadmins if (!$superadmin && ($links = wa()->event('links', $contacts))) { foreach ($links as $app_id => $l) { foreach ($l as $contact_id => $contact_links) { if ($contact_links) { throw new waRightsException('Access denied: only superadmin is allowed to delete contacts with links to other applications.'); } } } } // Are there users among $contacts? $um = new waUserModel(); $users = array_keys($um->getByField(array('id' => $contacts, 'is_user' => 1), 'id')); // deletion of users is only allowed to superadmins if (!$superadmin && $users) { throw new waRightsException('Access denied: only superadmin is allowed to delete users.'); } // Revoke user access before deletion foreach ($users as $user_id) { waUser::revokeUser($user_id); } // Bye bye... $contact_model = new waContactModel(); $contact_model->delete($contacts); // also throws a contacts.delete event $this->response['deleted'] = count($contacts); $this->response['message'] = sprintf(_w("%d contact has been deleted", "%d contacts have been deleted", $this->response['deleted']), $this->response['deleted']); $this->log('contact_delete', count($contacts)); }
/** * @param int[] $params Deleted contact_id * @see waEventHandler::execute() * @return void */ public function execute(&$params) { $contact_model = new waContactModel(); $contacts = $contact_model->getByField('id', $params, true); $post_model = new blogPostModel(); $comment_model = new blogCommentModel(); foreach ($contacts as $contact) { $data = array('contact_id' => 0, 'contact_name' => $contact['name']); $post_model->updateByField('contact_id', $contact['id'], $data); $data = array('contact_id' => 0, 'name' => $contact['name'], 'auth_provider' => null); $comment_model->updateByField('contact_id', $contact['id'], $data); } /** * @event contacts_delete * @param array[] int $contact_ids array of contact's ID * @return void */ wa()->event(array('blog', 'contacts_delete'), $params); }
public function execute() { try { $contact_model = new waContactModel(); if ($contact_model->countAll()) { $this->setLayout(new webasystLoginLayout()); if (waRequest::get('forgotpassword') !== null) { $this->executeAction(new webasystForgotPasswordAction()); } else { $this->executeAction(new webasystLoginAction()); } } else { $this->executeAction(new webasystLoginFirstAction()); } } catch (waException $e) { // db.php not found if ($e->getCode() == 600) { $this->executeAction(new webasystLoginConfigAction()); } } }
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 findDuplicatesFor($field, $values, $excludeIds = array()) { if (!$values) { return array(); } // Check if field exists, is active and is kept in this storage if (!$field instanceof waContactField) { $field = waContactFields::get($field); if (!$field) { return array(); } } if ($field->getParameter('storage') != 'info') { return array(); } $field = $field->getId(); $sql = "SELECT `{$field}` AS f, id\n FROM wa_contact\n WHERE `{$field}` IN (:values)" . ($excludeIds ? " AND id NOT IN (:excludeIds) " : ' ') . "GROUP BY f"; $this->getModel(); $r = $this->model->query($sql, array('values' => $values, 'excludeIds' => $excludeIds)); return $r->fetchAll('f', true); }
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; }
/** 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; }
/** * 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 string $hash * @return bool|waContact */ protected function checkHash($hash) { $contact_id = substr($hash, 16, -16); $contact_model = new waContactModel(); $contact = $contact_model->getById($contact_id); if ($contact && $hash === $this->getHash($contact_id)) { return new waContact($contact_id); } return false; }
public function getContacts($ids) { if (!$ids) { return array(); } $contact_model = new waContactModel(); $contacts = $contact_model->getByField('id', $ids, 'id'); $config = wa('shop')->getConfig(); $use_gravatar = $config->getGeneralSettings('use_gravatar'); $gravatar_default = $config->getGeneralSettings('gravatar_default'); // Put everything into one array foreach ($contacts as &$c) { $contact = new waContact($c['id']); if (!$contact->get('photo') && $use_gravatar) { $c['photo_50x50'] = shopHelper::getGravatar($contact->get('email', 'default'), 50, $gravatar_default); } else { $c['photo_50x50'] = $contact->getPhoto(50); } //$c += ifset($additional_fields[$c['id']], array()); } return $contacts; }
/** * Execute step * * @return bool */ public function execute() { $contact = $this->getContact(); if (!$contact) { $contact = new waContact(); } $data = waRequest::post('customer'); if ($data && is_array($data)) { foreach ($data as $field => $value) { $contact->set($field, $value); } } $this->form = shopHelper::getCustomerForm(); if ($shipping = $this->getSessionData('shipping') && !waRequest::post('ignore_shipping_error')) { $shipping_step = new shopOnestepCheckoutShipping(); $rate = $shipping_step->getRate($shipping['id'], isset($shipping['rate_id']) ? $shipping['rate_id'] : null, $contact); if (!$rate || is_string($rate)) { // remove selected shipping method $this->setSessionData('shipping', null); /* $errors = array(); $errors['all'] = sprintf(_w('We cannot ship to the specified address via %s.'), $shipping['name']); if ($rate) { $errors['all'] .= '<br> <strong>'.$rate.'</strong><br>'; } $errors['all'] .= '<br> '._w('Please double-check the address above, or return to the shipping step and select another shipping option.'); $errors['all'] .= '<input type="hidden" name="ignore_shipping_error" value="1">'; wa()->getView()->assign('errors', $errors); return false; */ } } if (wa()->getUser()->isAuth()) { $contact->save(); } else { $errors = array(); if (waRequest::post('create_user')) { $login = waRequest::post('login'); if (!$login) { $errors['email'][] = _ws('Required'); } if (!waRequest::post('password')) { $errors['password'] = _ws('Required'); } $email_validator = new waEmailValidator(); if (!$email_validator->isValid($login)) { $errors['email'] = $email_validator->getErrors(); } if (!$errors) { $contact_model = new waContactModel(); if ($contact_model->getByEmail($login, true)) { $errors['email'][] = _w('Email already registered'); } } if (!$errors) { $contact->set('email', $login); $contact->set('password', waRequest::post('password')); } else { if (isset($errors['email'])) { $errors['email'] = implode(', ', $errors['email']); } wa()->getView()->assign('errors', $errors); return false; } } $this->setSessionData('contact', $contact); } if ($comment = waRequest::post('comment')) { $this->setSessionData('comment', $comment); } if (!$this->form->isValid($contact)) { return false; } return true; }
/** * @return array|bool * @throws waException */ protected function _authByCookie() { if ($this->getOption('remember_enabled') && ($token = waRequest::cookie('auth_token'))) { $model = new waContactModel(); $response = waSystem::getInstance()->getResponse(); $id = substr($token, 15, -15); $user_info = $model->getById($id); $this->checkBan($user_info); $cookie_domain = ifset($this->options['cookie_domain'], ''); if ($user_info && ($user_info['is_user'] > 0 || !$this->options['is_user']) && $token === $this->getToken($user_info)) { $response->setCookie('auth_token', $token, time() + 2592000, null, $cookie_domain, false, true); return $this->getAuthData($user_info); } else { $response->setCookie('auth_token', null, -1, null, $cookie_domain); } } return false; }
/** * * Get contact extra info * @param int $id * @param int|int[] $size * @return array|bool */ public static function getContactInfo($id, $size = 50) { $ids = is_array($id) ? $id : array($id); static $cache = array(); $cached = array_keys($cache); if ($search = array_unique(array_diff($ids, $cached))) { $user_model = new waContactModel(); $cache += $user_model->getByField('id', $search, 'id'); } if (is_array($id)) { $result = array(); foreach ($ids as $id) { $result[$id] = isset($cache[$id]) ? $cache[$id] : false; } return $result; } elseif (isset($cache[$id])) { if (!isset($cache[$id]['photo_url'])) { $waContact = new waContact($id); $max_size = 0; foreach ((array) $size as $s) { $cache[$id]['photo_url_' . $s] = $waContact->getPhoto($s); if ($max_size < $s) { $max_size = $s; $cache[$id]['photo_url'] = $cache[$id]['photo_url_' . $s]; } } unset($waContact); } return $cache[$id]; } else { return false; } }
<?php $category_model = new waContactCategoryModel(); $category = $category_model->getBySystemId('blog'); $contact_model = new waContactModel(); $sql = "SELECT id FROM wa_contact WHERE create_app_id='blog'"; $contact_ids = $contact_model->query($sql)->fetchAll(null, true); if ($contact_ids) { $contact_categories_model = new waContactCategoriesModel(); $contact_categories_model->add($contact_ids, $category['id']); }
/** * Returns contact's locale id. * * @return string */ public function getLocale() { if (!$this->id) { $locale = isset($this->data['locale']) ? $this->data['locale'] : null; if (!$locale) { $locale = waRequest::get('lang'); } } else { if (isset(self::$cache[$this->id]['locale'])) { $locale = self::$cache[$this->id]['locale']; } else { $contact_model = new waContactModel(); $contact_info = $contact_model->getById($this->id); $this->setCache($contact_info); $locale = isset($contact_info['locale']) ? $contact_info['locale'] : ''; } } if (wa()->getEnv() == 'frontend' && waRequest::param('locale')) { return waRequest::param('locale'); } // try get locale by header Accept-Language (only for current user) if (!$locale && $this instanceof waAuthUser) { $locale = waRequest::getLocale(); } if (!$locale) { $locale = self::$options['default']['locale']; } return $locale; }
/** * Returns list of the users * * @param string $app_id - if specified returns only users whish has access to the application * @return array */ public static function getUsers($app_id = null) { $contact_model = new waContactModel(); if ($app_id) { $sql = "SELECT c.id, c.name\n FROM " . $contact_model->getTableName() . " c JOIN\n wa_contact_rights r ON c.id = -r.group_id AND c.is_user = 1\n WHERE (r.app_id = s:app_id OR (r.app_id = 'webasyst' AND r.name = 'backend')) AND r.value > 0\n UNION\n (SELECT c.id, c.name\n FROM " . $contact_model->getTableName() . " c JOIN\n wa_user_groups g ON c.id = g.contact_id AND c.is_user = 1 JOIN\n wa_contact_rights r ON g.group_id = r.group_id\n WHERE (r.app_id = s:app_id OR (r.app_id = 'webasyst' AND r.name = 'backend')) AND r.value > 0\n ) ORDER BY name"; } else { $sql = "SELECT c.id, c.name FROM " . $contact_model->getTableName() . " c\n WHERE c.is_user = 1\n ORDER BY c.name"; } return $contact_model->query($sql, array('app_id' => $app_id))->fetchAll('id', 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; }
public function execute() { $contact_model = new waContactModel(); if ($contact_model->countAll()) { $this->redirect($this->getConfig()->getBackendUrl(true)); } if (($locale = waRequest::get('lang')) && waLocale::getInfo($locale)) { // set locale wa()->setLocale($locale); // save to database default locale $app_settings_model = new waAppSettingsModel(); $app_settings_model->set('webasyst', 'locale', $locale); } if (file_exists($this->getConfig()->getRootPath() . '/install.php')) { @unlink($this->getConfig()->getRootPath() . '/install.php'); } if (waRequest::getMethod() == 'post') { $errors = array(); $login = waRequest::post('login'); $validator = new waLoginValidator(); if (!$validator->isValid($login)) { $errors['login'] = implode("<br />", $validator->getErrors()); } $password = waRequest::post('password'); $password_confirm = waRequest::post('password_confirm'); if ($password !== $password_confirm) { $errors['password'] = _w('Passwords do not match'); } $email = waRequest::post('email'); $validator = new waEmailValidator(); if (!$validator->isValid($email)) { $errors['email'] = implode("<br />", $validator->getErrors()); } if ($errors) { $this->view->assign('errors', $errors); } else { // save account name $app_settings_model = new waAppSettingsModel(); $app_settings_model->set('webasyst', 'name', waRequest::post('account_name')); if ($email) { $app_settings_model->set('webasyst', 'email', $email); $app_settings_model->set('webasyst', 'sender', $email); } // create user $user = new waUser(); $firstname = waRequest::post('firstname'); $user['firstname'] = $firstname ? $firstname : $login; $user['lastname'] = waRequest::post('lastname'); $user['is_user'] = 1; $user['login'] = $login; $user['password'] = $password; $user['email'] = $email; $user['locale'] = wa()->getLocale(); $user['create_method'] = 'install'; if ($errors = $user->save()) { $result = array(); foreach ($errors as $k => $v) { $result['all'][] = $k . ": " . (is_array($v) ? implode(', ', $v) : $v); } $result['all'] = implode("\r\n", $result['all']); $this->view->assign('errors', $result); } else { $user->setRight('webasyst', 'backend', 1); waSystem::getInstance()->getAuth()->auth(array('login' => $login, 'password' => $password)); $path = $this->getConfig()->getPath('config'); // check routing.php if (!file_exists($path . '/routing.php')) { $apps = wa()->getApps(); $data = array(); $domain = $this->getConfig()->getDomain(); $site = false; foreach ($apps as $app_id => $app) { if ($app_id == 'site') { $site = true; } elseif (!empty($app['frontend'])) { $routing = array('url' => $app_id . '/*', 'app' => $app_id); if (!empty($app['routing_params']) && is_array($app['routing_params'])) { $routing = array_merge($routing, $app['routing_params']); } $data[$domain][] = $routing; } } if ($site) { $data[$domain][] = array('url' => '*', 'app' => 'site'); } waUtils::varExportToFile($data, $path . '/routing.php'); } // redirect to backend $this->redirect($this->getConfig()->getBackendUrl(true)); } } } }
public function updateLastTime($force = false) { $time = $this->storage->read('user_last_datetime'); if (!$time || $force || $time == '0000-00-00 00:00:00' || time() - strtotime($time) > 120) { try { $login_log_model = new waLoginLogModel(); $last_activity = $login_log_model->getCurrent($this->id); } catch (waDbException $e) { if ($e->getCode() == 1146) { waSystem::getInstance()->getAuth()->clearAuth(); header("Location: " . wa()->getConfig()->getBackendUrl(true)); exit; } } $contact_model = new waContactModel(); $contact_info = $contact_model->getById($this->id); $auth = waSystem::getInstance()->getAuth(); if (!$auth->checkAuth($contact_info)) { header("Location: " . wa()->getConfig()->getRequestUrl(false)); exit; } if (!$contact_info || waSystem::getInstance()->getEnv() == 'backend' && !$contact_info['is_user']) { waSystem::getInstance()->getAuth()->clearAuth(); header("Location: " . wa()->getConfig()->getBackendUrl(true)); exit; } else { $this->setCache($contact_info); } if (!$last_activity) { $login_log_model->insert(array('contact_id' => $this->id, 'datetime_in' => date("Y-m-d H:i:s"), 'datetime_out' => null)); } elseif ($last_datetime = strtotime($time)) { if (time() - $last_datetime > self::$options['activity_timeout']) { $login_log_model->updateById($last_activity['id'], array('datetime_out' => $time)); $login_log_model->insert(array('contact_id' => $this->id, 'datetime_in' => date("Y-m-d H:i:s"), 'datetime_out' => null)); } } $t = date("Y-m-d H:i:s"); $contact_model->updateById($this->id, array('last_datetime' => $t)); $this->storage->write('user_last_datetime', $t); } }
/** * Returns array of orders included in collection. * * @param string $fields List of order properties, comma-separated, to be included in returned array: * '*' — values from shop_order table * '*,params,items,contact' (different combinations are acceptable) — values from tables shop_order, shop_order_items, shop_order_params, wa_contact * @param int $offset Initial position in returned order array, 0 means first order in collection * @param int|bool $limit Maximum order limit. * If a Boolean value is specified, then $escape = $limit and $limit = null * If no value is specified, then $limit = 0. * If no value is specified and $offset is non-zero, then $limit = $offset and $offset = 50 * @param bool $escape Whether order parameters and contact names must be escaped using htmlspecialchars() function, defaults to true * * @return array Array of collection orders' sub-arrays */ public function getOrders($fields = "*", $offset = 0, $limit = null, $escape = true) { if (is_bool($limit)) { $escape = $limit; $limit = null; } if ($limit === null) { if ($offset) { $limit = $offset; $offset = 0; } else { $limit = 50; } } $sql = $this->getSQL(); $sql = "SELECT " . $this->getFields($fields) . " " . $sql; $sql .= " LIMIT " . ($offset ? $offset . ',' : '') . (int) $limit; $data = $this->getModel()->query($sql)->fetchAll('id'); if (!$data) { return array(); } $ids = array_keys($data); // add other fields foreach ($this->other_fields as $field) { switch ($field) { case 'items': case 'params': $rows = $this->getModel($field)->getByField('order_id', $ids, true); foreach ($rows as $row) { if ($field == 'params') { $data[$row['order_id']][$field][$row['name']] = $row['value']; } else { if ($escape) { $row['name'] = htmlspecialchars($row['name']); } $data[$row['order_id']][$field][] = $row; } } break; case 'contact': $contact_ids = array(); foreach ($data as $o) { $contact_ids[] = $o['contact_id']; } $contact_model = new waContactModel(); $contacts = $contact_model->getById(array_unique($contact_ids)); foreach ($data as &$o) { if (isset($contacts[$o['contact_id']])) { $c = $contacts[$o['contact_id']]; $o['contact'] = array('id' => $c['id'], 'name' => waContactNameField::formatName($c), 'photo' => $c['photo']); if ($escape) { $o['contact']['name'] = htmlspecialchars($o['contact']['name']); } } } unset($o); break; } } unset($t); return $data; }