/** * @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')); } }
/** * @param $id * @param array $params * @return shopCouponPluginCoupon */ public static function gen($id, $params = array()) { $m = new shopCouponModel(); $tm = new shopCouponPluginTemplateModel(); if (!($gen = $tm->getById($id))) { return new shopCouponPluginCoupon(); } if (!($candidates = self::_candidates($gen))) { return new shopCouponPluginCoupon(); } // Кто-то читает код? :) // Стоит проверять в цикле, чтоб наверняка? //do{ $exists = $m->select('code')->where('code IN(?)', $candidates)->fetchAll(null, true); $candidates = array_diff($candidates, $exists); $code = reset($candidates); //} while(empty($code)); $comment = $gen['comment']; if (!empty($params['contact_id'])) { $contact = new waContact($params['contact_id']); if ($contact->exists()) { $comment .= "\n" . _wp('for') . ' ' . $contact->getName(); } $comment = trim($comment); } try { $code = mb_substr($code, 0, 32); $coupon = array('code' => $code, 'type' => $gen['type'], 'limit' => $gen['limit'], 'value' => $gen['value'], 'comment' => $comment, 'expire_datetime' => $gen['expire_hours'] ? date('Y-m-d H:i:s', time() + $gen['expire_hours'] * 3600) : null, 'create_datetime' => date('Y-m-d H:i:s'), 'create_contact_id' => $gen['create_contact_id']); $m->insert($coupon); } catch (waDbException $e) { $coupon = array(); } return new shopCouponPluginCoupon($coupon); }
public function execute() { $form = shopHelper::getCustomerForm(); if ($form->post()) { $customer_validation_disabled = wa()->getSetting('disable_backend_customer_form_validation'); if ($customer_validation_disabled || $form->isValid()) { $c = new waContact(); if ($customer_validation_disabled) { $errors = array(); $c->save($form->post()); } else { $errors = $c->save($form->post(), true); } if (!$errors) { $scm = new shopCustomerModel(); $scm->createFromContact($c->getId()); echo '<script>$.customers.reloadSidebar(); window.location.hash = "#/id/' . $c->getId() . '"</script>'; exit; } // Show errors that waContact returned, e.g. email must be unique. foreach ($errors as $fld => $list) { foreach ($list as $err) { $form->errors($fld, $err); } } } } $this->view->assign('form', $form); $this->view->assign('customer_validation_disabled', wa()->getSetting('disable_backend_customer_form_validation')); }
public function execute() { 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()); } }
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; }
/** * @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; } }
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() . '/'); }
/** * @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 (!$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) { if (!isset($fields['categories'])) { return TRUE; } if (empty($fields['categories'][0])) { $fields['categories'] = array(); } $this->getModel()->setContactCategories($contact->getId(), $fields['categories']); return TRUE; }
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 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); } }
/** Add `when` and `who` fields (used in templated) to given item db row. */ public static function prepareItem($item) { $item['name'] = htmlspecialchars($item['name']); $item['when'] = $item['done'] ? waDateTime::format('humandatetime', $item['done']) : ''; $item['who'] = ''; if ($item['contact_id'] && wa()->getUser()->getId() != $item['contact_id']) { $c = new waContact($item['contact_id']); try { $item['who'] = htmlspecialchars($c->getName()); } catch (Exception $e) { } } return $item; }
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() . '/'); } }
public function settingsAction($params) { $blog_id = $params['id']; $html = '<div class="fields-group"> <div class="field"> <div class="name">' . _wp('Subscribed via email') . '</div> <div class="value">'; $model = new blogEmailsubscriptionModel(); $contacts = $model->getSubscribers($blog_id); $rights = wa()->getUser()->getRights('contacts'); $html .= '<ul class="menu-v">'; if (!$contacts) { $html .= '<li>' . _wp('none') . '</li>'; } foreach ($contacts as $c) { $html .= '<li>'; if ($rights) { $html .= '<a href="' . wa()->getConfig()->getBackendUrl(true) . 'contacts/#/contact/' . $c['id'] . '">'; } $html .= '<i class="icon16 userpic20" style="background-image: url(' . waContact::getPhotoUrl($c['id'], $c['photo'], 20) . ')"></i>'; $html .= '<span>' . htmlspecialchars($c['name']) . '</span>'; if ($rights) { $html .= '</a>'; } $html .= '</li>'; } $html .= '</ul></div></div></div>'; return array('settings' => $html); }
public function execute() { $this->setLayout(new guestbook2BackendLayout()); // Создаем экземпляр модели для получения данных из БД $model = new guestbook2Model(); // Получаем все записи гостевой книги из БД $records = $model->getRecords(0, 0); foreach ($records as &$r) { if ($r['contact_id']) { $r['name'] = $r['contact_name']; // получаем URL на фотографию контакта $r['photo_url'] = waContact::getPhotoUrl($r['contact_id'], $r['photo'], 20); } } unset($r); // Передаем записи в шаблон $this->view->assign('records', $records); // Передаём в шаблон УРЛ фронтенда $this->view->assign('url', wa()->getRouteUrl($this->getAppId(), true)); // Передаём в шаблон права пользователя на удаление записей из гостевой книги // Права описаны в конфиге lib/config/guestbookRightConfig.class.php $this->view->assign('rights_delete', $this->getRights('delete')); // Если пользователь админ приложения контакты, то показывать ссылки на контакты $this->view->assign('rights_contacts', $this->getUser()->isAdmin('contacts')); }
public function execute() { $this->setLayout(new guestbook2BackendLayout()); // Creating a model instance for retrieving data from the database // Создаем экземпляр модели для получения данных из БД $model = new guestbook2Model(); // Retrieving all guestbook records from the database // Получаем все записи гостевой книги из БД $records = $model->getRecords(0, 0); foreach ($records as &$r) { if ($r['contact_id']) { $r['name'] = $r['contact_name']; // getting the contact photo URL // получаем URL на фотографию контакта $r['photo_url'] = waContact::getPhotoUrl($r['contact_id'], $r['photo'], 20); } } unset($r); // Passing records to the template // Передаем записи в шаблон $this->view->assign('records', $records); // Passing the frontend URL to the template // Передаём в шаблон УРЛ фронтенда $this->view->assign('url', wa()->getRouteUrl($this->getAppId(), true)); // Passing user's record deletion access rights value to the template // Access rights are defined in config file lib/config/guestbookRightConfig.class.php // Передаём в шаблон права пользователя на удаление записей из гостевой книги // Права описаны в конфиге lib/config/guestbookRightConfig.class.php $this->view->assign('rights_delete', $this->getRights('delete')); // If user is an admin of the Contacts app then show links to Contacts // Если пользователь админ приложения контакты, то показывать ссылки на контакты $this->view->assign('rights_contacts', $this->getUser()->isAdmin('contacts')); }
/** Using $this->id get waContact and save it in $this->contact; * Load vars into $this->view specific to waContact. */ protected function getContactInfo() { $system = wa(); if ($this->id == $system->getUser()->getId()) { $this->contact = $system->getUser(); $this->view->assign('own_profile', true); } else { $this->contact = new waContact($this->id); $this->view->assign('own_profile', false); } $exists = $this->contact->exists(); if ($exists) { $this->view->assign('contact', $this->contact); // who created this contact and when $this->view->assign('contact_create_time', waDateTime::format('datetime', $this->contact['create_datetime'], $system->getUser()->getTimezone())); if ($this->contact['create_contact_id']) { try { $author = new waContact($this->contact['create_contact_id']); if ($author['name']) { $this->view->assign('author', $author); } } catch (Exception $e) { // Contact not found. Ignore silently. } } $this->view->assign('top', $this->contact->getTopFields()); // Main contact editor data $fieldValues = $this->contact->load('js', true); $m = new waContactModel(); if (isset($fieldValues['company_contact_id'])) { if (!$m->getById($fieldValues['company_contact_id'])) { $fieldValues['company_contact_id'] = 0; $this->contact->save(array('company_contact_id' => 0)); } } $contactFields = waContactFields::getInfo($this->contact['is_company'] ? 'company' : 'person', true); // Only show fields that are allowed in own profile if (!empty($this->params['limited_own_profile'])) { $allowed = array(); foreach (waContactFields::getAll('person') as $f) { if ($f->getParameter('allow_self_edit')) { $allowed[$f->getId()] = true; } } $fieldValues = array_intersect_key($fieldValues, $allowed); $contactFields = array_intersect_key($contactFields, $allowed); } contactsHelper::normalzieContactFieldValues($fieldValues, $contactFields); $this->view->assign('contactFields', $contactFields); $this->view->assign('contactFieldsOrder', array_keys($contactFields)); $this->view->assign('fieldValues', $fieldValues); // Contact categories $cm = new waContactCategoriesModel(); $this->view->assign('contact_categories', array_values($cm->getContactCategories($this->id))); } else { $this->view->assign('contact', array('id' => $this->id)); } return $exists; }
public function execute() { $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)); } }
/** * @param string $login * @param waAuth $auth * @return waContact|bool */ protected function findContact($login, $auth) { $contact_model = new waContactModel(); $is_user = $auth->getOption('is_user'); if (strpos($login, '@')) { $sql = "SELECT c.* FROM wa_contact c\n JOIN wa_contact_emails e ON c.id = e.contact_id\n WHERE " . ($is_user ? "c.is_user = 1 AND " : "") . "e.email LIKE s:email AND e.sort = 0\n ORDER BY c.id LIMIT 1"; $contact_info = $contact_model->query($sql, array('email' => $login))->fetch(); } else { $contact_info = $contact_model->getByField('login', $login); } if ($contact_info && (!$is_user || $contact_info['is_user'])) { $contact = new waContact($contact_info['id']); $contact->setCache($contact_info); return $contact; } return false; }
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 execute() { // Setting the frontend layout // Задаём лайаут для фронтенда $this->setLayout(new guestbook2FrontendLayout()); // Setting the theme template // Задаём шаблон темы $this->setThemeTemplate('guestbook.html'); // if a POST request has been received then write a new record to the database // Если пришёл POST-запрос, то нужно записать в БД новую запись if (waRequest::method() == 'post') { $this->add(); } // Creating a model instance for retrieving data from the database // Создаем экземпляр модели для получения данных из БД $model = new guestbook2Model(); // Retrieving the record count per page from the app's settings // Получаем количество записей на одной странице из настроек приложения $limit = $this->getConfig()->getOption('records_per_page'); // Current page // Текущая страница $page = waRequest::param('page'); if (!$page) { $page = 1; } $this->view->assign('page', $page); // Calculating offset // Вычисляем смещение $offset = ($page - 1) * $limit; // Retrieving all records from the database // Получаем записи гостевой книги из БД $records = $model->getRecords($offset, $limit); // Total record count // Всего записей $records_count = $model->countAll(); $pages_count = ceil($records_count / $limit); $this->view->assign('pages_count', $pages_count); // Preparing records for being passed to the theme template // Подготавливаем записи для передачи в шаблон темы foreach ($records as &$r) { if ($r['contact_id']) { $r['name'] = htmlspecialchars($r['contact_name']); // getting contact photo URL // получаем URL на фотографию контакта $r['photo_url'] = waContact::getPhotoUrl($r['contact_id'], $r['photo'], 20); } else { $r['name'] = htmlspecialchars($r['name']); } $r['text'] = nl2br(htmlspecialchars($r['text'])); } unset($r); // Passing records to the template // Передаем записи в шаблон $this->view->assign('records', $records); // URL portion for links to pages // Часть урла для ссылок на страницы $this->view->assign('url', wa()->getRouteUrl('/frontend')); }
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; }
public function execute() { $id = waRequest::request('id', null, waRequest::TYPE_INT); $contact = new waContact($id); $contact->getName(); // Customer orders $im = new shopOrderItemsModel(); $orders_collection = new shopOrdersCollection('search/contact_id=' . $id); $orders = $orders_collection->getOrders('*,items,params', 0, 500); shopHelper::workupOrders($orders); foreach ($orders as &$o) { $o['total_formatted'] = waCurrency::format('%{s}', $o['total'], $o['currency']); $o['shipping_name'] = ifset($o['params']['shipping_name'], ''); $o['payment_name'] = ifset($o['params']['payment_name'], ''); } $this->view->assign('orders', $orders); $this->view->assign('contact', $contact); $this->view->assign('def_cur_tmpl', str_replace('0', '%s', waCurrency::format('%{s}', 0, wa()->getConfig()->getCurrency()))); }
public function execute() { $id = $this->getId(); // Delete the old photos if they exist $oldDir = wa()->getDataPath(waContact::getPhotoDir($id), TRUE); if (file_exists($oldDir)) { waFiles::delete($oldDir); } // Update record in DB for this user $contact = new waContact($id); $contact['photo'] = 0; $contact->save(); // Update recent history to reload thumbnail correctly (if not called from personal account) if (wa()->getUser()->get('is_user')) { $history = new contactsHistoryModel(); $history->save('/contact/' . $id, null, null, '--'); } $this->response = array('done' => 1, 'url' => $contact->getPhoto()); }
public function 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'); }