public function payment($data, $order_data, $auto_submit = false) { $data['order_id'] = $order_data['order_id']; if ($order_data['currency_id'] != 'USD') { throw new waPaymentException(_w('Order currency is not USD but payment gateway provide only USD transactions')); } $type_trans = array_flip(self::$type_trans); if (!empty($data['type']) && !empty($type_trans[$data['type']])) { $type = $type_trans[$data['type']]; } else { $type = self::OPERATION_AUTH_ONLY; } if (empty($order_data['description_en'])) { $order_data['description_en'] = 'Order #' . $order_data['order_id'] . ' (' . gmdate('F, d Y') . ')'; } $c = new waContact($order_data['contact_id']); $locale = $c->getLocale(); $form_fields = array('x_login' => $this->login, 'x_amount' => number_format($order_data['amount'], 2, '.', ''), 'x_description' => $order_data['description_en'], 'x_invoice_num' => $order_data['order_id'], 'x_fp_sequence' => rand(1, 1000), 'x_fp_timestamp' => time(), 'x_test_request' => 'false', 'x_show_form' => 'PAYMENT_FORM', 'x_type' => $type, 'x_version' => '3.1', 'x_method' => 'CC', 'x_cust_id' => $order_data['contact_id'], 'x_customer_ip' => wa()->getRequest()->server('REMOTE_ADDR'), 'x_duplicate_window' => '28800', 'x_first_name' => waLocale::transliterate($c->get('firstname'), $locale), 'x_last_name' => waLocale::transliterate($c->get('lastname'), $locale), 'x_company' => waLocale::transliterate($c->get('company'), $locale), 'x_address' => waLocale::transliterate($c->get('address:street', 'default'), $locale), 'x_city' => waLocale::transliterate($c->get('address:city', 'default'), $locale), 'x_state' => waLocale::transliterate($c->get('address:region', 'default'), $locale), 'x_zip' => waLocale::transliterate($c->get('address:zip', 'default'), $locale), 'x_country' => waLocale::transliterate($c->get('address:country', 'default'), $locale), 'x_phone' => $c->get('phone', 'default'), 'x_email' => $c->get('email', 'default'), 'x_relay_response' => isset($data['x_relay_response']) ? $data['x_relay_response'] : 'true', 'x_relay_url' => $this->getRelayUrl(), 'wa_success_url' => $this->getAdapter()->getBackUrl(waAppPayment::URL_SUCCESS, $data), 'wa_decline_url' => $this->getAdapter()->getBackUrl(waAppPayment::URL_DECLINE, $data), 'wa_cancel_url' => $this->getAdapter()->getBackUrl(waAppPayment::URL_FAIL, $data), 'wa_app_id' => $this->app_id, 'wa_merchant_id' => $this->merchant_id); $form_fields['x_fp_hash'] = ''; // @TODO: get from common 'address' field if (phpversion() >= '5.1.2') { $form_fields['x_fp_hash'] = hash_hmac('md5', $this->login . "^" . $form_fields['x_fp_sequence'] . "^" . $form_fields['x_fp_timestamp'] . "^" . $form_fields['x_amount'] . "^", $this->trans_key); } else { $form_fields['x_fp_hash'] = bin2hex(mhash(MHASH_MD5, $this->login . "^" . $form_fields['x_fp_sequence'] . "^" . $form_fields['x_fp_timestamp'] . "^" . $form_fields['x_amount'] . "^", $this->trans_key)); } if ($this->form_header) { $form_fields['x_header_html_payment_form'] = $this->form_header; } $view = wa()->getView(); $view->assign('url', wa()->getRootUrl()); $view->assign('form_fields', $form_fields); $view->assign('form_url', $this->getEndpointUrl()); $view->assign('auto_submit', $auto_submit); return $view->fetch($this->path . '/templates/payment.html'); }
protected function getContact() { // Create new temporary waContact object $contact = new waContact(wa()->getUser()->getId()); // Assign address with the right extension, if no extension is set if ($this->form->fields('address.shipping') && !$contact->get('address.shipping') && ($addresses = $contact->get('address'))) { $contact->set('address.shipping', $addresses[0]); } if ($this->form->fields('address.billing') && !$contact->get('address.billing') && ($addresses = $contact->get('address.shipping'))) { $contact->set('address.billing', $addresses[0]); } return $contact; }
public function execute() { try { $discountcard = waRequest::post('discountcard', array()); $model = new shopDiscountcardsPluginModel(); if (!empty($discountcard['id'])) { $model->updateById($discountcard['id'], $discountcard); $discountcard = $model->getById($discountcard['id']); } elseif (empty($discountcard['discountcard'])) { throw new waException('Ошибка: Не указан номер дисконтной карты'); } else { if ($model->getByField('discountcard', $discountcard['discountcard'])) { throw new waException('Ошибка: Номер дисконтной карты не уникален'); } $id = $model->insert($discountcard); $discountcard = $model->getById($id); } if (!empty($discountcard['contact_id'])) { $contact = new waContact($discountcard['contact_id']); $discountcard['contact_name'] = $contact->get('name'); } $discountcard['amount'] = shop_currency($discountcard['amount']); $this->response = $discountcard; } catch (Exception $ex) { $this->setError($ex->getMessage()); } }
/** * @todo test and complete code */ public function capture($transaction_raw_data) { $result = ''; try { //$order_id, $amount, $phone_number, $description; $soap_client = $this->getQiwiSoapClient(); $parameters = new createBill(); $contact = new waContact($order_data['customer_id']); $mobile_phone = preg_replace('/^\\s*\\+\\s*7/', '', $contact->get('phone.mobile', 'default')); //TODO verify phone $mobile_phone = preg_replace('/[\\D]+/', '', $mobile_phone); $parameters->login = $this->login; $parameters->password = $this->password; $parameters->user = $phone_number; $parameters->amount = $amount; $parameters->comment = $description; $parameters->txn = $this->getInvoiceId($transaction_raw_data['order_id']); $parameters->lifetime = date('d.m.Y H:i:s', time() + 3600 * max(1, (int) $this->lifetime)); $parameters->alarm = $this->alarm; $parameters->create = 1; $response = $soap_client->createBill($parameters); self::log($this->id, $soap_client->getDebug()); if ($response->createBillResult) { $result = $this->getResponseCodeDescription($response->createBillResult); self::log($this->id, array(__METHOD__ . " #{$order_id}\tphone:{$phone_number}\t{$result}")); } } catch (SoapFault $sf) { $result = $sf->getMessage(); self::log($this->id, $sf->getMessage()); self::log($this->id, $soap_client->getDebug()); } return $result; }
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')); } }
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); }
/** * 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 set(waContact $contact, $value, $params = array(), $add = false) { if ($this->isMulti()) { throw new waException('Multi-checkboxes are not implemented.'); } if (!$value) { return ''; } // Only update timestamp if checkbox was not set before the save $old = $contact->get($this->id); return $old ? $old : time(); }
public function getContactField($field, $format = null) { if ($this->getContact()) { $value = $this->contact->get($field, $format); if (is_array($value)) { $res = reset($value); $value = $res['value']; } return $value; } else { return null; } }
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 run() { $app_settings_model = new waAppSettingsModel(); $contact_settings_model = new waContactSettingsModel(); $app_settings_model->set('blog', 'last_reminder_cron_time', time()); // remider settings for all users $reminders = $contact_settings_model->select('contact_id, value')->where("app_id='blog' AND name='reminder'")->fetchAll('contact_id', true); if (!$reminders) { return; } $time = time(); // do job no more one time in 24 hours $last_cron_times = $contact_settings_model->select('contact_id')->where("app_id='blog' AND name='last_reminder_cron_time' AND value <= " . ($time - 86400))->fetchAll('contact_id', true); $reminders_allowed = array_keys($last_cron_times); if (!$reminders_allowed) { return; } $post_model = new blogPostModel(); $backend_url = $app_settings_model->get('blog', 'backend_url', wa()->getRootUrl(true) . wa()->getConfig()->getBackendUrl()); $message_count = 0; foreach ($reminders_allowed as $contact_id) { $days = $reminders[$contact_id]; // get all deadline posts for this contact $posts = $post_model->select("id, title, datetime")->where("status='" . blogPostModel::STATUS_DEADLINE . "' AND contact_id=" . $contact_id . " AND datetime < '" . date('Y-m-d H:i:s', $time + $days * 86400) . "'")->order('datetime')->fetchAll(); if ($posts) { $contact = new waContact($contact_id); $email = $contact->get('email', 'default'); $message = new waMailMessage(_w('Scheduled blog posts'), $this->getMessage($posts, $time, $backend_url)); try { $message->setTo($email); if ($message->send()) { $message_count++; } } catch (Exception $e) { } } $contact_settings_model->set($contact_id, 'blog', 'last_reminder_cron_time', $time); } /** * Notify plugins about sending reminder * @event followup_send * @return void */ wa()->event('reminder_send', $message_count); }
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 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; }
/** Using $this->id get waContact and save it in $this->contact; * Load vars into $this->view specific to waContact. */ protected function getContactInfo() { $system = wa(); if ($this->id == $system->getUser()->getId()) { $this->contact = $system->getUser(); $this->view->assign('own_profile', TRUE); } else { $this->contact = new waContact($this->id); } // // Load vars into view // $this->view->assign('contact', $this->contact); // who created this contact and when $this->view->assign('contact_create_time', waDateTime::format('datetime', $this->contact['create_datetime'], $system->getUser()->getTimezone())); if ($this->contact['create_contact_id']) { try { $author = new waContact($this->contact['create_contact_id']); if ($author['name']) { $this->view->assign('author', $author); } } catch (Exception $e) { // Contact not found. Ignore silently. } } // Info above tabs $fields = array('email', 'phone', 'im'); $top = array(); foreach ($fields as $f) { if ($v = $this->contact->get($f, 'top,html')) { $top[] = array('id' => $f, 'name' => waContactFields::get($f)->getName(), 'value' => is_array($v) ? implode(', ', $v) : $v); } } $this->view->assign('top', $top); // Main contact editor data $fieldValues = $this->contact->load('js', TRUE); $contactFields = waContactFields::getInfo($this->contact['is_company'] ? 'company' : 'person', TRUE); $this->view->assign('contactFields', $contactFields); $this->view->assign('fieldValues', $fieldValues); // Contact categories $cm = new waContactCategoriesModel(); $this->view->assign('contact_categories', array_values($cm->getContactCategories($this->id))); }
public function payment($payment_form_data, $order_data, $auto_submit = false) { $order = waOrder::factory($order_data); $description = preg_replace('/[^\\.\\?,\\[]\\(\\):;"@\\%\\s\\w\\d]+/', ' ', $order->description); $description = preg_replace('/[\\s]{2,}/', ' ', $description); if (!in_array($order->currency, $this->allowedCurrency())) { throw new waPaymentException('Invalid currency'); } list(, $lang) = explode("_", wa()->getLocale()); $contact = new waContact(wa()->getUser()->getId()); list($email) = $contact->get('email', 'value'); $redirectUrl = $this->getRelayUrl() . '?&fondy_id=' . $this->fondy_id . '&app_id=' . $this->app_id . '&merchants_id=' . $this->merchant_id; $formFields = array('order_id' => $order_data['order_id'] . self::ORDER_SEPARATOR . time(), 'merchant_id' => $this->fondy_id, 'order_desc' => $description, 'amount' => $this->getAmount($order), 'currency' => $order->currency, 'server_callback_url' => $redirectUrl, 'response_url' => $redirectUrl . '&show_user_response=1', 'lang' => strtolower($lang), 'sender_email' => $email); $formFields['signature'] = $this->getSignature($formFields); $view = wa()->getView(); $view->assign('form_fields', $formFields); $view->assign('form_url', $this->getEndpointUrl()); $view->assign('auto_submit', $auto_submit); return $view->fetch($this->path . '/templates/payment.html'); }
/** * @description Get HTML with contact info (field name => field html) * @return array */ protected function getFormFieldsHtml() { if (!$this->contact) { $this->contact = $this->getContact(); } if (!$this->form) { $this->form = $this->getForm(); } $user_info = array(); foreach ($this->form->fields as $id => $field) { if (!in_array($id, array('password', 'password_confirm'))) { if ($id === 'photo') { $user_info[$id] = array('name' => _ws('Photo'), 'value' => '<img src="' . $this->contact->getPhoto() . '">'); } else { $user_info[$id] = array('name' => $this->form->fields[$id]->getName(null, true), 'value' => $this->contact->get($id, 'html')); } } } return $user_info; }
public function execute() { $enabled = wa()->getSetting('enabled', 0, array('photos', 'fotorss')); if (!$enabled) { return null; } $url = wa()->getRouting(); $url = $url->getRouteParam('url_type'); $route = ''; if ($url == 0) { $route = 'photo/'; } $author_on = wa()->getSetting('author_tag', 0, array('photos', 'fotorss')); $max_entries = max(1, wa()->getSetting('posts_number', 0, array('photos', 'fotorss'))); $link = wa()->getRouteUrl('photos/frontend', array(), true); $rss_link = wa()->getRouteUrl('photos/frontend/fotorss', array(), true); $title = waRequest::param('title') ? waRequest::param('title') : wa()->accountName(); $collection = new photosCollection(); $fields = "*,"; $thumbs = wa()->getSetting('thumb', 'default', array('photos', 'fotorss')); if ($thumbs == 'big' || $thumbs == 'middle' || $thumbs == 'mobile' || $thumbs == 'crop') { $thumbs = "thumb_" . $thumbs; } elseif ($thumbs == 'default' || empty($thumbs)) { $thumbs = 'thumb'; } $fields .= $thumbs; $posts = $collection->getphotos($fields, 0, $max_entries); foreach ($posts as &$post) { if ($author_on) { $contact = new waContact($post['contact_id']); $post['author'] = $contact->get('name'); } $post['thumb'] = $post[$thumbs]; if ($thumbs == 'vk') { $post['thumb'] = photosPhoto::getThumbInfo($post, '590x0'); } } wa()->getResponse()->addHeader('Content-type', 'application/rss+xml; charset=utf-8', true); $this->view->assign('posts', $posts); $this->view->assign('info', array('title' => $title, 'link' => $link, 'description' => '', 'language' => 'ru', 'pubDate' => date(DATE_RSS), 'lastBuildDate' => date(DATE_RSS), 'photourl' => $route, 'self' => $rss_link)); }
/** * Этот метод вызывается после успешного создания нового контакта * В нём будет отправлено приветственное письмо новому пользователю * @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() { try { $app_settings_model = new waAppSettingsModel(); if (waRequest::post('cancel')) { wa()->getStorage()->set('shop/discountcard', ''); wa()->getStorage()->set('shop/discountcard/customer_id', ''); } else { if ($discountcard_number = waRequest::post('discountcard')) { if (!($customer_id = waRequest::post('customer_id', 0, waRequest::TYPE_INT))) { throw new waException('Укажите покупателя'); } $model = new shopDiscountcardsPluginModel(); if ($app_settings_model->get(shopDiscountcardsPlugin::$plugin_id, 'binding_customer')) { $discountcard = $model->getByField(array('contact_id' => $customer_id, 'discountcard' => $discountcard_number)); if (empty($discountcard)) { $discountcard = $model->getByField(array('contact_id' => 0, 'discountcard' => $discountcard_number)); } } else { $discountcard = $model->getByField('discountcard', $discountcard_number); } if ($discountcard) { wa()->getStorage()->set('shop/discountcard', $discountcard['discountcard']); wa()->getStorage()->set('shop/discountcard/customer_id', $customer_id); $discountcard['amount_format'] = shop_currency($discountcard['amount']); $contact = new waContact($discountcard['contact_id']); $discountcard['contact_name'] = $contact->get('name'); $this->response = $discountcard; } else { throw new waException('Дисконтная карта не найдена'); } } else { throw new waException('Укажите номер дисконтной карты'); } } } catch (Exception $ex) { $this->setError($ex->getMessage()); } }
public function defaultAction() { $city = $this->getSettings('city'); $unit = $this->getUnit(); $nocache = $this->getRequest()->get('nocache'); if (!$city) { $user = wa()->getUser(); if (!$user->getId() && $this->info['dashboard_id']) { $user = new waContact($this->info['contact_id']); } try { $addresses = $user->get('address:city'); foreach ($addresses as $address) { if (!empty($address['value'])) { $city = $address['value']; break; } } } catch (waException $e) { } } $weather = null; if ($city) { // Fetch up-to-date data if asked to bypass cache. if ($nocache) { $weather = $this->getWeather(date('Y-m-d H'), $city, $unit, false); } // Get from cache. if (!$weather) { $weather = $this->getWeatherFromCache($city, $unit); } // Fetch up-to-date data if there's nothing in cache and we didn't try already. if (!$weather && !$nocache) { $weather = $this->getWeather(date('Y-m-d H'), $city, $unit, false); } } $this->display(array('info' => $this->getInfo(), 'city' => $city, 'weather' => $weather, 'unit' => $unit)); }
public function get(waContact $contact, $format = null) { if ($contact['is_company']) { $name = $contact['company']; } else { $name = array(); foreach (array('firstname', 'middlename', 'lastname') as $part) { if (($part = trim($contact[$part])) || $part === '0') { $name[] = $part; } } $name = trim(implode(' ', $name)); } if (!$name) { $email = $contact->get('email', 'default'); if (is_array($email)) { $email = array_shift($email); } $name = strtok($email, '@'); $this->set($contact, $name); } return $this->format($name, $format); }
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')); } }
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; }
/** * Check field value to be unique, if field is set up as unique. * * @param $data * @param int $contactId * @return array|string|null Validation errors (array for multi fields, string for simple fields) or null if everything is ok. */ public function validateUnique($data, $contactId = null) { if (!$this->getParameter('unique')) { return null; } if (!$this->isMulti()) { $data = array($data); } // array of plain string values $values = array(); if (is_array($data)) { foreach ($data as $sort => $value) { $value = $this->format($value, 'value'); if ($value || $value === 0) { // do not check empty values to be unique $values[$sort] = $value; } } } else { if ($data !== null) { return array(_ws('Data must be an array.')); } } // array of duplicates $sort => contact_id $dupl = array(); // Check if there are duplicates among $values $flipped = array_flip($values); if (count($values) != count($flipped)) { // keys that disappeared after array_flip are duplicates, find them foreach (array_diff(array_keys($values), array_values($flipped)) as $key) { $dupl[$key] = $contactId; // there's another key that is not missing, but still is a duplicate since it's a copy of a missing key $dupl[$flipped[$values[$key]]] = $contactId; } } // Check if there are duplicates in database $rows = $this->getStorage()->findDuplicatesFor($this, array_keys($flipped), $contactId ? array($contactId) : array()); foreach ($rows as $value => $cid) { if (isset($flipped[$value])) { $dupl[$flipped[$value]] = $cid; } else { // Must be a duplicate in case-insensitive search foreach ($flipped as $v => $i) { if (mb_strtolower($v) == mb_strtolower($value)) { $dupl[$i] = $cid; break; } } if (!$dupl) { // Sanity check for debugging purposes throw new waException("Unable to find duplicate value {$value} among flipped: " . print_r($flipped, true)); } } } if (!$dupl) { return null; } // Create array of errors $errors = array(); $errStrSelf = _ws('Duplicates are not allowed for this field.'); $errStr = _ws('This field must be unique. The value entered is already set for %NAME_LINK%.'); $errStrNoRights = _ws('This field must be unique. The value entered is already set for another contact.'); $rights_model = null; $userId = null; foreach ($dupl as $sort => $cid) { if ($cid === $contactId) { $errors[$sort] = $errStrSelf; continue; } // Check if current user can view $cid profile. if (!$rights_model && class_exists('ContactsRightsModel')) { $rights_model = new ContactsRightsModel(); $userId = waSystem::getInstance()->getUser()->getId(); } if ($rights_model && $rights_model->getRight($userId, $cid)) { // at least read access $contact = new waContact($cid); $nameLink = '<a href="' . wa_url() . 'webasyst/contacts/#/contact/' . $cid . '">' . $contact->get('name') . '</a>'; $errors[$sort] = str_replace('%NAME_LINK%', $nameLink, $errStr); } else { // no access $errors[$sort] = $errStrNoRights; } } return $errors; }
public function execute() { $this->id = (int) waRequest::post('id'); // Check access if (!$this->id) { if (!$this->getRights('create')) { throw new waRightsException('Access denied.'); } } else { $cr = new contactsRightsModel(); if ($cr->getRight(null, $this->id) != 'write') { throw new waRightsException('Access denied.'); } } $this->type = waRequest::post('type'); $this->contact = new waContact($this->id); if ($this->type == 'company') { $this->contact['is_company'] = 1; } $data = json_decode(waRequest::post('data'), true); if (!$this->id && !isset($data['create_method'])) { $data['create_method'] = 'add'; } $oldLocale = $this->getUser()->getLocale(); // get old data for logging if ($this->id) { $old_data = array(); foreach ($data as $field_id => $field_value) { $old_data[$field_id] = $this->contact->get($field_id); } } $response = array(); if (!($errors = $this->contact->save($data, true))) { if ($this->id) { $new_data = array(); foreach ($data as $field_id => $field_value) { if (!isset($errors[$field_id])) { $response[$field_id] = $this->contact->get($field_id, 'js'); $new_data[$field_id] = $this->contact->get($field_id); } } if (empty($errors)) { $this->logContactEdit($old_data, $new_data); } $response['name'] = $this->contact->get('name', 'js'); $response['top'] = contactsHelper::getTop($this->contact); $response['id'] = $this->contact->getId(); } else { $response = array('id' => $this->contact->getId()); $response['address'] = $this->contact->get('address', 'js'); $this->logAction('contact_add', null, $this->contact->getId()); } // Update recently added menu item $name = waContactNameField::formatName($this->contact); if ($name || $name === '0') { $history = new contactsHistoryModel(); $history->save('/contact/' . $this->contact->getId(), $name, $this->id ? null : 'add'); $history = $history->get(); // to update history in user's browser } } // Reload page with new language if user just changed it in own profile if ($this->contact->getId() == $this->getUser()->getId() && $oldLocale != $this->contact->getLocale()) { $response['reload'] = true; } $this->response = array('errors' => $errors, 'data' => $response); if (isset($history)) { $this->response['history'] = $history; } }
public function execute() { $system = wa(); $datetime = $system->getDateTime(); $user = $this->getUser()->getRights('contacts', 'backend'); $admin = $user >= 2; $cr = new contactsRightsModel(); if (!empty($this->params['limited_own_profile'])) { $this->id = wa()->getUser()->getId(); $this->view->assign('limited_own_profile', true); $this->view->assign('save_url', '?module=profile&action=save'); $this->view->assign('password_save_url', '?module=profile&action=password'); $this->view->assign('save_geocoords_url', '?module=profile&action=saveGeocoords'); $this->view->assign('photo_upload_url', '?module=profile&action=tmpimage'); $this->view->assign('photo_editor_url', '?module=profile&action=photo'); $this->view->assign('photo_editor_uploaded_url', '?module=profile&action=photo&uploaded=1'); } else { $this->id = (int) waRequest::get('id'); if (empty($this->id)) { throw new waException('No id specified.'); } $r = $cr->getRight(null, $this->id); //var_dump($r );exit; if (!$r) { throw new waRightsException(_w('Access denied')); } else { $this->view->assign('readonly', $r === 'read'); } } $exists = $this->getContactInfo(); if ($exists) { $this->getUserInfo(); $this->view->assign('last_view_context', $this->getLastViewContext()); // collect data from other applications to show in tabs if (empty($this->params['limited_own_profile'])) { $links = array(); foreach (wa()->event('profile.tab', $this->id) as $app_id => $one_or_more_links) { if (!isset($one_or_more_links['html'])) { $i = ''; foreach ($one_or_more_links as $link) { $key = isset($link['id']) ? $link['id'] : $app_id . $i; $links[$key] = $link; $i++; } } else { $key = isset($one_or_more_links['id']) ? $one_or_more_links['id'] : $app_id; $links[$key] = $one_or_more_links; } } $this->view->assign('links', $links); } // tab to open by default $this->view->assign('tab', waRequest::get('tab')); $this->view->assign('admin', $admin); $this->view->assign('superadmin', $admin && $this->getUser()->getRights('webasyst', 'backend')); $this->view->assign('current_user_id', wa()->getUser()->getId()); $this->view->assign('can_edit', $cr->getRight(null, $this->id)); // Update history if (empty($this->params['limited_own_profile'])) { $name = $this->contact->get('name'); if ($name || $name === '0') { $history = new contactsHistoryModel(); $history->save('/contact/' . $this->id, $name); } // Update history in user's browser $historyModel = new contactsHistoryModel(); $this->view->assign('history', $historyModel->get()); } $this->view->assign('wa_view', $this->view); $this->view->assign('access_disable_msg', contactsHelper::getAccessDisableMsg($this->contact)); $this->view->assign('my_url', wa()->getRootUrl(true) . 'my/'); $this->view->assign('backend_url', wa()->getRootUrl(true) . wa()->getConfig()->getBackendUrl(false) . '/'); $this->view->assign('static_url', wa()->getAppStaticUrl('contacts')); } $this->view->assign('exists', $exists); if ($this->getRequest()->request('standalone')) { /** * Include plugins js and css * @event backend_assets * @return array[string]string $return[%plugin_id%] */ $this->view->assign('backend_assets', wa()->event('backend_assets')); } $auth = wa()->getAuthConfig(); $this->view->assign('personal_portal_available', !empty($auth['app'])); /* * @event backend_contact_info * @return array[string]array $return[%plugin_id%] array of html output * @return array[string][string]string $return[%plugin_id%]['after_header'] html output * @return array[string][string]string $return[%plugin_id%]['header'] html output * @return array[string][string]string $return[%plugin_id%]['before_header'] html output * @return array[string][string]string $return[%plugin_id%]['before_top'] html output * @return array[string][string]string $return[%plugin_id%]['top'] html output * @return array[string][string]string $return[%plugin_id%]['after_top'] html output * @return array[string][string]string $return[%plugin_id%]['photo'] html output */ $backend_contact_info_params = array('contact_id' => $this->id); $this->view->assign('backend_contact_info', wa()->event('backend_contact_info', $backend_contact_info_params)); }
protected function formalizeData($transaction_raw_data) { $unpack = $this->unpackTransactionCode($transaction_raw_data['VendorTxCode']); list($contact_id, $currency) = array_slice($unpack, 3); $contact = new waContact($contact_id); $view_data = implode(' ', array('Name: ' . $contact->getName(), 'Phone: ' . $contact->get('phone', 'default'), 'Email: ' . $contact->get('email', 'default'))); $status = $transaction_raw_data['Status']; if ($status == 'OK') { $type = waPayment::OPERATION_AUTH_CAPTURE; $state = waPayment::STATE_AUTH; } else { $type = waPayment::OPERATION_CANCEL; $state = waPayment::STATE_CANCELED; } $transaction_data = parent::formalizeData($transaction_raw_data); $transaction_data = array_merge($transaction_data, array('type' => $type, 'native_id' => ifset($transaction_raw_data['VPSTxId']), 'amount' => ifset($transaction_raw_data['Amount']), 'currency_id' => $currency, 'customer_id' => $contact_id, 'result' => 1, 'order_id' => $this->order_id, 'view_data' => $view_data, 'state' => $state)); return $transaction_data; }
public function set(waContact $contact, $value, $params = array(), $add = false) { $subfield = isset($params['subfield']) ? $params['subfield'] : ''; if ($this->isMulti()) { $is_ext = $this->isExt(); $ext = isset($params['ext']) ? $params['ext'] : ''; if ($subfield) { if ($add) { $values = $contact->get($this->getId()); if (($n = count($values)) > 0) { $data = $values[$n - 1]; $data_ext = isset($data['ext']) ? $data['ext'] : null; if (isset($data['fill']) && !isset($data['data'][$subfield]) && $ext == $data_ext) { $values[$n - 1]['data'][$subfield] = $value; return $values; } } $values[] = array('data' => array($subfield => $value), 'fill' => true, 'ext' => $ext); return $values; } else { return array(array('data' => array($subfield => $value), 'ext' => $ext)); } } if (isset($value[0])) { foreach ($value as &$v) { $v = $this->setValue($v); if ($is_ext && $ext) { $v['ext'] = $ext; } } unset($v); } else { $value = $this->setValue($value); if ($is_ext && $ext) { $value['ext'] = $ext; } $value = array($value); } if ($add) { $data = $contact->get($this->id); foreach ($value as $v) { $data[] = $v; } return $data; } else { if ($is_ext && $ext) { $data = $contact->get($this->id); foreach ($data as $sort => $row) { if ($row['ext'] == $ext) { unset($data[$sort]); } } foreach ($value as $v) { $data[] = $v; } return $data; } else { return $value; } } } else { if ($subfield) { $data = $contact->get($this->getId()); $data['data'][$subfield] = $value; return $data; } return $this->setValue($value); } }
/** * Extend items by adding contact info into $rows[i]['user'] * Uses: * - $rows[i]['contact_id'] * - $rows[i]['name'] or $rows[i]['contact_name'] when contact is not found or its name is empty * - $rows[i]['auth_provider'] for default userpic URL * * @param array $rows * @param array $fields * @param bool $get_link pass true to get $rows[i]['user']['posts_link'] */ public static function extendUser(&$rows, $fields = array(), $get_link = false) { $default_fields = array('id', 'name', 'firstname', 'middlename', 'lastname'); $fields = array_unique(array_merge($fields, $default_fields)); // All contact ids $ids = array(); foreach ($rows as $row) { if ($row['contact_id']) { $ids[] = intval($row['contact_id']); } } $ids = array_unique($ids); // Fetch contacts using collection $collection = new waContactsCollection($ids); $contacts = $collection->getContacts(implode(',', $fields), 0, count($ids)); // Prepare data row to use as a placeholder when contact is not found $contact = new waContact(0); $contacts[0] = array('name' => ''); $photo_fields = array(); foreach ($fields as $field) { if (preg_match('@^photo_url_(\\d+)$@', $field, $matches)) { $photo_fields[] = $field; $contacts[0][$field] = $contact->getPhoto($matches[1], $matches[1]); } else { $contacts[0][$field] = $contact->get($field); } } // Format contact names foreach ($contacts as &$c) { $c['name'] = waContactNameField::formatName($c); } unset($c); // Add data as 'user' key to each row in $rows $app_static_url = wa()->getAppStaticUrl(); foreach ($rows as &$row) { $row['user'] = array(); $id = $row['contact_id'] = max(0, intval($row['contact_id'])); if (!isset($contacts[$id])) { $id = 0; } if (isset($contacts[$id])) { if (isset($row['url']) && $get_link && !isset($contacts[$id]['posts_link'])) { $contacts[$id]['posts_link'] = blogPost::getUrl($row, 'author'); } $row['user'] = $contacts[$id]; } if (!$id || !isset($contacts[$id])) { if (isset($row['name'])) { $row['user']['name'] = $row['name']; } elseif (isset($row['contact_name'])) { $row['user']['name'] = $row['contact_name']; } if (isset($row['auth_provider'])) { if ($row['auth_provider'] && $row['auth_provider'] != blogCommentModel::AUTH_GUEST) { $row['user']['photo_url'] = "{$app_static_url}img/{$row['auth_provider']}.png"; foreach ($photo_fields as $field) { $row['user'][$field] =& $row['user']['photo_url']; } } } } unset($row); } }
public function execute() { $order = $this->getOrder(); if (!$order) { $this->view->assign('order', $order); return; } $workflow = new shopWorkflow(); $actions = $workflow->getStateById($order['state_id'])->getActions(); $bottom_buttons = $top_buttons = $buttons = array(); foreach ($actions as $action) { /** * @var shopWorkflowAction $action */ if ($action->getOption('top') || $action->getOption('position') == 'top') { $top_buttons[] = $action->getButton(); } elseif ($action->getOption('position') == 'bottom') { $bottom_buttons[] = $action->getButton(); } else { $buttons[] = $action->getButton(); } } $config = $this->getConfig(); $last_action_datetime = null; $log_model = new shopOrderLogModel(); $log = $log_model->getLog($order['id']); foreach ($log as &$l) { if ($l['action_id']) { $l['action'] = $workflow->getActionById($l['action_id']); } if ($order['state_id'] == $l['after_state_id']) { $last_action_datetime = $l['datetime']; } } $params = $order['params']; $tracking = ''; if (!empty($params['shipping_id'])) { try { $plugin = shopShipping::getPlugin(null, $params['shipping_id']); if (!empty($params['tracking_number'])) { $tracking = $plugin->tracking($params['tracking_number']); } if ($custom_fields = $plugin->customFields(new waOrder())) { foreach ($custom_fields as $k => $v) { if (!empty($params['shipping_params_' . $k])) { $custom_fields[$k]['value'] = $params['shipping_params_' . $k]; } else { unset($custom_fields[$k]); } } $this->view->assign('custom_fields', $custom_fields); } } catch (waException $ex) { $tracking = $ex->getMessage(); } } $this->view->assign('tracking', $tracking); $settings = wa('shop')->getConfig()->getCheckoutSettings(); $form_fields = ifset($settings['contactinfo']['fields'], array()); $formatter = new waContactAddressSeveralLinesFormatter(); $shipping_address = shopHelper::getOrderAddress($params, 'shipping'); $this->view->assign('shipping_address_text', shopHelper::getShippingAddressText($params)); $shipping_address = $formatter->format(array('data' => $shipping_address)); $shipping_address = $shipping_address['value']; if (isset($form_fields['address.billing'])) { $billing_address = shopHelper::getOrderAddress($params, 'billing'); $billing_address = $formatter->format(array('data' => $billing_address)); $billing_address = $billing_address['value']; if ($billing_address === $shipping_address) { $billing_address = null; } } else { $billing_address = null; } $customer_model = new shopCustomerModel(); $customer = $customer_model->getById($order['contact_id']); $customer_contact = new waContact($order['contact_id']); // Customer info $main_contact_info = array(); foreach (array('email', 'phone', 'im') as $f) { if ($v = $customer_contact->get($f, 'top,html')) { $main_contact_info[] = array('id' => $f, 'name' => waContactFields::get($f)->getName(), 'value' => is_array($v) ? implode(', ', $v) : $v); } } $this->view->assign(array('customer' => $customer, 'customer_contact' => $customer_contact, 'main_contact_info' => $main_contact_info, 'currency' => $config->getCurrency(), 'order' => $order, 'params' => $params, 'log' => $log, 'last_action_datetime' => $last_action_datetime, 'bottom_buttons' => $bottom_buttons, 'top_buttons' => $top_buttons, 'buttons' => $buttons, 'filter_params' => $this->getParams(), 'filter_params_str' => $this->getParams(true), 'count_new' => $this->getModel()->getStateCounters('new'), 'timeout' => $config->getOption('orders_update_list'), 'printable_docs' => shopHelper::getPrintForms(array_merge($order, array('params' => $params))), 'billing_address' => $billing_address, 'shipping_address' => $shipping_address, 'shipping_id' => ifset($params['shipping_id'], '') . '.' . ifset($params['shipping_rate_id'], ''), 'offset' => $this->getModel()->getOffset($order['id'], $this->getParams(), true))); /** * Backend order profile page * UI hook allow extends order profile page * @event backend_order * @param array $order * @return array[string][string]string $return[%plugin_id%]['title_suffix'] html output * @return array[string][string]string $return[%plugin_id%]['action_button'] html output * @return array[string][string]string $return[%plugin_id%]['action_link'] html output * @return array[string][string]string $return[%plugin_id%]['info_section'] html output */ $this->view->assign('backend_order', wa()->event('backend_order', $order, array('title_suffix', 'action_button', 'action_link', 'info_section'))); }