public static function settingRegionRatesControl($name, $params = array())
 {
     foreach ($params as $field => $param) {
         if (strpos($field, 'wrapper')) {
             unset($params[$field]);
         }
     }
     if (empty($params['value']) || !is_array($params['value'])) {
         $params['value'] = array();
     }
     $control = '';
     waHtmlControl::addNamespace($params, $name);
     $cm = new waCountryModel();
     $countries = $cm->all();
     $rm = new waRegionModel();
     if ($regions = $rm->getByCountry('rus')) {
         $control .= "<table class=\"zebra\"><thead>";
         $control .= "<tr class=\"gridsheader\"><th colspan=\"3\">";
         $control .= htmlentities('Распределите регионы по тарифным поясам Почты России', ENT_QUOTES, 'utf-8');
         $control .= "</th>";
         $control .= "<th>Только авиа</th>";
         $control .= "</th></tr></thead><tbody>";
         $params['control_wrapper'] = '<tr><td>%s</td><td>&rarr;</td><td>%s</td><td>%s</td></tr>';
         $params['title_wrapper'] = '%s';
         $params['description_wrapper'] = '%s';
         $params['options'] = array();
         $params['options'][0] = _wp('*** пояс не выбран ***');
         for ($region = 1; $region <= 5; $region++) {
             $params['options'][$region] = sprintf(_wp('Пояс %d'), $region);
         }
         $avia_params = $params;
         $avia_params['control_wrapper'] = '%2$s';
         $avia_params['description_wrapper'] = false;
         $avia_params['title_wrapper'] = false;
         foreach ($regions as $region) {
             $name = 'zone';
             $id = $region['code'];
             if (empty($params['value'][$id])) {
                 $params['value'][$id] = array();
             }
             $params['value'][$id] = array_merge(array($name => 0, 'avia_only' => false), $params['value'][$id]);
             $region_params = $params;
             waHtmlControl::addNamespace($region_params, $id);
             $avia_params = array('namespace' => $region_params['namespace'], 'control_wrapper' => '%2$s', 'description_wrapper' => false, 'title_wrapper' => false, 'value' => $params['value'][$id]['avia_only']);
             $region_params['value'] = max(0, min(5, $params['value'][$id][$name]));
             $region_params['description'] = waHtmlControl::getControl(waHtmlControl::CHECKBOX, 'avia_only', $avia_params);
             $region_params['title'] = $region['name'];
             if ($region['code']) {
                 $region_params['title'] .= " ({$region['code']})";
             }
             $control .= waHtmlControl::getControl(waHtmlControl::SELECT, 'zone', $region_params);
         }
         $control .= "</tbody>";
         $control .= "</table>";
     } else {
         $control .= 'Не определено ни одной области. Для работы модуля необходимо определить хотя бы одну область в России (см. раздел «Страны и области»).';
     }
     return $control;
 }
 /**
  * @see waShipping::getSettingsHTML()
  * @param array $params
  * @return string HTML
  */
 public function getSettingsHTML($params = array())
 {
     $params += array('translate' => array(&$this, '_w'));
     $values = $this->getSettings();
     if (!empty($params['value'])) {
         $values = array_merge($values, $params['value']);
     }
     if (!$values['rate_zone']['country']) {
         $l = substr(wa()->getUser()->getLocale(), 0, 2);
         if ($l == 'ru') {
             $values['rate_zone']['country'] = 'rus';
             $values['rate_zone']['region'] = '77';
             $values['city'] = '';
         } else {
             $values['rate_zone']['country'] = 'usa';
         }
     }
     $view = wa()->getView();
     $cm = new waCountryModel();
     $view->assign('countries', $cm->all());
     if (!empty($values['rate_zone']['country'])) {
         $rm = new waRegionModel();
         $view->assign('regions', $rm->getByCountry($values['rate_zone']['country']));
     }
     if (!empty($values['rate'])) {
         self::sortRates($values['rate']);
         if ($values['rate_by'] == 'price') {
             $values['rate'] = array_reverse($values['rate']);
         }
     } else {
         $values['rate'] = array();
         $values['rate'][] = array('limit' => 0, 'cost' => 0.0);
     }
     $app_config = wa()->getConfig();
     if (method_exists($app_config, 'getCurrencies')) {
         $view->assign('currencies', $app_config->getCurrencies());
     }
     $namespace = '';
     if (!empty($params['namespace'])) {
         if (is_array($params['namespace'])) {
             $namespace = array_shift($params['namespace']);
             while (($namespace_chunk = array_shift($params['namespace'])) !== null) {
                 $namespace .= "[{$namespace_chunk}]";
             }
         } else {
             $namespace = $params['namespace'];
         }
     }
     $view->assign('namespace', $namespace);
     $view->assign('values', $values);
     $view->assign('p', $this);
     $html = '';
     $view->assign('xhr_url', wa()->getAppUrl('webasyst') . '?module=backend&action=regions');
     $view->assign('map_adapters', wa()->getMapAdapters());
     $html .= $view->fetch($this->path . '/templates/settings.html');
     $html .= parent::getSettingsHTML($params);
     return $html;
 }
 public function execute()
 {
     if (waRequest::post()) {
         $app_settings = new waAppSettingsModel();
         foreach ($this->getData() as $name => $value) {
             $app_settings->set('shop', $name, $value);
         }
         $sms = waRequest::post('sms', array());
         $path = $this->getConfig()->getPath('config', 'sms');
         $save = array();
         foreach ($sms as $s) {
             $from = $s['from'];
             $adapter = $s['adapter'];
             unset($s['from']);
             unset($s['adapter']);
             $empty = true;
             foreach ($s as $v) {
                 if ($v) {
                     $empty = false;
                     break;
                 }
             }
             if (!$empty) {
                 if (!$from) {
                     $from = '*';
                 }
                 foreach (explode("\n", $from) as $from) {
                     $from = trim($from);
                     $save[$from] = $s;
                     $save[$from]['adapter'] = $adapter;
                 }
             }
         }
         waUtils::varExportToFile($save, $path);
     }
     $cm = new waCountryModel();
     $this->view->assign('countries', $cm->all());
     $this->view->assign($this->getConfig()->getGeneralSettings());
     $workhours = wa()->getSetting('workhours', null);
     if ($workhours) {
         $workhours = json_decode($workhours, true);
     }
     $this->view->assign('workhours', $workhours);
     $sms_adapters = $this->getSMSAdapters();
     $this->view->assign('sms_adapters', $sms_adapters);
     $this->view->assign('saved', waRequest::post());
 }
 protected function getParts($data, $format = null)
 {
     $result = array('pic' => '', 'marker' => '', 'parts' => array());
     $countryName = '';
     //        $countryPic = '';
     //        $searchLink = '';
     if (isset($data['data']['country']) && $data['data']['country']) {
         $model = new waCountryModel();
         $countryName = $model->name($data['data']['country']);
         // Do not show pic for unknown country
         if ($countryName) {
             $result['pic'] = '<img src="' . wa_url() . 'wa-content/img/country/' . strtolower($data['data']['country']) . '.gif" class="overhanging" />';
         }
     }
     if (isset($data['data']['street']) || isset($data['data']['city']) || isset($data['data']['region']) || isset($data['data']['country']) || $countryName) {
         $searchURL = '';
         foreach (array('street', 'city', 'region') as $id) {
             if (!isset($data['data'][$id])) {
                 continue;
             }
             $searchURL .= ($searchURL ? ' ' : '') . $data['data'][$id];
         }
         if ($countryName) {
             $searchURL .= ($searchURL ? ' ' : '') . $countryName;
         }
         $searchURL = htmlspecialchars($searchURL);
         $result['marker'] = '<a href="http://mapof.it/' . $searchURL . '" class="small"><i class="icon16 marker"></i><b><i>' . _w('show on map') . '</i></b></a>';
     }
     foreach (waContactFields::get('address')->getFields() as $field) {
         /**
          * @var waContactField $field
          */
         $id = $field->getId();
         if (isset($data['data'][$id]) && trim($data['data'][$id])) {
             if ($id === 'country') {
                 $result['parts'][$id] = $countryName;
             } else {
                 $result['parts'][$id] = $field->format($data['data'][$id], $format, $data['data']);
             }
             $result['parts'][$id] = htmlspecialchars($result['parts'][$id]);
         }
     }
     $result['marker'] = '';
     // marker is disabled, but may be needed in future
     return $result;
 }
/**
 * Smarty plugin
 * @package Smarty
 * @subpackage plugins
 */
function smarty_modifier_wa_format_country($code, $locale = null)
{
    if ($locale === null) {
        /**
         * @var waSmarty3View
         */
        $smarty = waConfig::get('current_smarty');
    }
    if ($locale === null) {
        $locale = $smarty->getVars('locale');
    }
    if ($locale === null) {
        $locale = waSystem::getInstance()->getUser()->getLocale();
    }
    $country_model = new waCountryModel();
    $country = $country_model->get($code, $locale);
    return isset($country['name']) ? $country['name'] : $code;
}
 public static function getTop($contact)
 {
     $top = array();
     static $fields = null;
     if ($fields === null) {
         $fields = array(waContactFields::getAll('person', true), waContactFields::getAll('company', true));
     }
     $country_model = new waCountryModel();
     $iso3letters_map = $country_model->select('DISTINCT iso3letter')->fetchAll('iso3letter', true);
     foreach ($fields[intval($contact['is_company'])] as $f) {
         $info = $f->getInfo();
         if ($f->getParameter('top') && ($value = $contact->get($info['id'], 'top,html'))) {
             if ($info['type'] == 'Address') {
                 $data = $contact->get($info['id']);
                 $data_for_map = $contact->get($info['id'], 'forMap');
                 $value = (array) $value;
                 foreach ($value as $k => &$v) {
                     if (isset($data[$k]['data']['country']) && isset($iso3letters_map[$data[$k]['data']['country']])) {
                         $v = '<img src="' . wa_url() . 'wa-content/img/country/' . strtolower($data[$k]['data']['country']) . '.gif" /> ' . $v;
                     }
                     $map_url = '';
                     if (is_string($data_for_map[$k])) {
                         $map_url = $data_for_map[$k];
                     } else {
                         if (!empty($data_for_map[$k]['coords'])) {
                             $map_url = $data_for_map[$k]['coords'];
                         } else {
                             if (!empty($data_for_map[$k]['with_street'])) {
                                 $map_url = $data_for_map[$k]['with_street'];
                             }
                         }
                     }
                     $v .= ' <a target="_blank" href="//maps.google.com/maps?q=' . urlencode($map_url) . '&z=15" class="small underline map-link">' . _w('map') . '</a>';
                     $v = '<div data-subfield-index=' . $k . '>' . $v . '</div>';
                 }
                 unset($v);
             }
             $delimiter = $info['type'] == 'Composite' || $info['type'] == 'Address' ? "<br>" : ", ";
             $top[] = array('id' => $info['id'], 'name' => $f->getName(), 'value' => is_array($value) ? implode($delimiter, $value) : $value, 'icon' => $info['type'] == 'Email' || $info['type'] == 'Phone' ? strtolower($info['type']) : '', 'pic' => '');
         }
     }
     return $top;
 }
 public function execute()
 {
     $country_iso3 = waRequest::request('country');
     if (!$country_iso3) {
         throw new waException('Country not specified.', 404);
     }
     $regions = array();
     switch ($country_iso3) {
         case '%AL':
             $country = array('name' => _w('All countries'));
             break;
         case '%EU':
             $country = array('name' => _w('All European countries'));
             break;
         case '%RW':
             $country = array('name' => _w('Rest of world'));
             break;
         default:
             // Country
             $cm = new waCountryModel();
             $country = $cm->get($country_iso3);
             if (!$country) {
                 throw new waException('Country not found.', 404);
             }
             // Country regions
             $rm = new waRegionModel();
             foreach ($rm->getByCountry($country_iso3) as $r) {
                 $r['css_class'] = 'highlighted just-added hidden';
                 $r['tax_name'] = '';
                 $r['tax_value'] = '';
                 $r['params'] = array('tax_value_modifier' => '+');
                 $regions[] = $r;
             }
             break;
     }
     $this->view->assign('c', array('css_class' => 'highlighted just-added one_rate', 'name' => $country['name'], 'iso3' => $country_iso3, 'regions' => $regions, 'global_rate' => ''));
 }
 protected function searchPrepare($query, $auto_title = true)
 {
     if ($auto_title || !isset($this->alias_index['data'])) {
         $this->alias_index['data'] = 0;
     }
     //$query = urldecode($query);   // sometime this urldecode broke query, better make urldecode (if needed) outside the searchPrepare
     // `&` can be escaped in search request. Need to split by not escaped ones only.
     $escapedBS = 'ESCAPED_BACKSLASH';
     while (FALSE !== strpos($query, $escapedBS)) {
         $escapedBS .= rand(0, 9);
     }
     $escapedAmp = 'ESCAPED_AMPERSAND';
     while (FALSE !== strpos($query, $escapedAmp)) {
         $escapedAmp .= rand(0, 9);
     }
     $query = str_replace('\\&', $escapedAmp, str_replace('\\\\', $escapedBS, $query));
     $query = explode('&', $query);
     $model = $this->getModel();
     $title = array();
     foreach ($query as $part) {
         if (!($part = trim($part))) {
             continue;
         }
         $part = str_replace(array($escapedBS, $escapedAmp), array('\\', '&'), $part);
         $parts = preg_split("/(\\\$=|\\^=|\\*=|==|!=|>=|<=|=|>|<|@=)/uis", $part, 2, PREG_SPLIT_DELIM_CAPTURE);
         if ($parts) {
             if ($parts[0] === 'name' && $parts[1] === '*=') {
                 $t_a = preg_split("/\\s+/", $parts[2]);
                 $cond = array();
                 foreach ($t_a as $t) {
                     $t = trim($t);
                     if ($t) {
                         $t = $model->escape($t, 'like');
                         $cond[] = "c.name LIKE '%{$t}%'";
                     }
                 }
                 $this->addWhere(implode(" AND ", $cond));
                 $title[] = _ws('Name') . $parts[1] . $parts[2];
             } else {
                 if ($parts[0] == 'email') {
                     if (!isset($this->joins['email'])) {
                         $this->joins['email'] = array('table' => 'wa_contact_emails', 'alias' => 'e');
                     }
                     $title[] = waContactFields::get($parts[0])->getName() . $parts[1] . $parts[2];
                     $this->where[] = 'e.email' . $this->getExpression($parts[1], $parts[2]);
                 } else {
                     if ($model->fieldExists($parts[0])) {
                         if ($f = waContactFields::get($parts[0])) {
                             $title[] = $f->getName() . $parts[1] . $parts[2];
                         } else {
                             $title[] = $parts[0] . $parts[1] . $parts[2];
                         }
                         $this->where[] = 'c.' . $parts[0] . $this->getExpression($parts[1], $parts[2]);
                     } else {
                         if ($parts[0] == 'category') {
                             if (!isset($this->joins['categories'])) {
                                 $this->joins['categories'] = array('table' => 'wa_contact_categories', 'alias' => 'cc');
                             }
                             $title[] = _ws('Category') . $parts[1] . $parts[2];
                             $this->where[] = 'cc.category_id' . $this->getExpression($parts[1], $parts[2]);
                         } else {
                             $field_parts = explode('.', $parts[0]);
                             $f = $field_parts[0];
                             if ($fo = waContactFields::get($f)) {
                                 $title[] = $fo->getName() . $parts[1] . $parts[2];
                             }
                             $ext = isset($field_parts[1]) ? $field_parts[1] : null;
                             $on = ":table.contact_id = c.id AND :table.field = '" . $model->escape($f) . "'";
                             $this->where_fields[] = $f;
                             $op = $parts[1];
                             $term = $parts[2];
                             if ($f === 'address:country') {
                                 $al1 = $this->addJoin('wa_contact_data', $on);
                                 $whr = "{$al1}.value " . $this->getExpression($op, $term);
                                 if ($ext !== null) {
                                     $whr .= " AND {$al1}.ext = '" . $model->escape($ext) . "'";
                                     $whr = "({$whr})";
                                 }
                                 // search by l18n name of countries
                                 if ($op === '*=') {
                                     if (wa()->getLocale() === 'en_US') {
                                         $al2 = $this->addLeftJoin('wa_country', ":table.iso3letter = {$al1}.value");
                                         $whr .= " OR {$al2}.name " . $this->getExpression($parts[1], $parts[2]);
                                     } else {
                                         if (wa()->getLocale() !== 'en_US') {
                                             $iso3letters = array();
                                             $country_model = new waCountryModel();
                                             $countries = $country_model->all();
                                             $term = mb_strtolower($term);
                                             foreach ($countries as &$cntr) {
                                                 if (mb_strpos(mb_strtolower($cntr['name']), $term) === 0) {
                                                     $iso3letters[] = $cntr['iso3letter'];
                                                 }
                                             }
                                             unset($cntr);
                                             if ($iso3letters) {
                                                 $al2 = $this->addLeftJoin('wa_country', ":table.iso3letter = {$al1}.value");
                                                 $whr .= " OR {$al2}.iso3letter IN ('" . implode("','", $iso3letters) . "')";
                                             }
                                         }
                                     }
                                 }
                                 $this->addWhere($whr);
                             } else {
                                 if ($f === 'address:region') {
                                     if (strpos($term, ":") !== false) {
                                         // country_code : region_code - search by country code AND region code AND only in wa_region
                                         $term = explode(":", $term);
                                         $country_iso3 = $model->escape($term[0]);
                                         $code = $model->escape($term[1]);
                                         $al1 = $this->addJoin('wa_contact_data', $on);
                                         $whr = array();
                                         if ($ext !== null) {
                                             $whr[] = "{$al1}.ext = '" . $model->escape($ext) . "'";
                                         }
                                         $al2 = $this->addJoin('wa_contact_data', ":table.contact_id = c.id AND :table.field = 'address:country'");
                                         $al3 = $this->addJoin('wa_region', ":table.code = {$al1}.value AND :table.country_iso3 = {$al2}.value");
                                         $whr[] = "{$al3}.country_iso3 = '{$country_iso3}'";
                                         $whr[] = "{$al3}.code = '{$code}'";
                                         $whr = implode(" AND ", $whr);
                                     } else {
                                         $al1 = $this->addJoin('wa_contact_data', $on);
                                         $whr = "{$al1}.value" . $this->getExpression($op, $term);
                                         if ($ext !== null) {
                                             $whr .= " AND {$al1}.ext = '" . $model->escape($ext) . "'";
                                             $whr = "({$whr})";
                                         }
                                         if ($op === "*=") {
                                             // if search by like, search by wa_region.name but taking into account country
                                             $al2 = $this->addJoin('wa_contact_data', ":table.contact_id = c.id AND :table.field = 'address:country'");
                                             $al3 = $this->addLeftJoin('wa_region', ":table.code = {$al1}.value AND :table.country_iso3 = {$al2}.value");
                                             $whr .= " OR {$al3}.name " . $this->getExpression($op, $term);
                                         }
                                     }
                                     $this->addWhere($whr);
                                 } else {
                                     $on .= ' AND :table.value ' . $this->getExpression($op, $term);
                                     if ($ext !== null) {
                                         $on .= " AND :table.ext = '" . $model->escape($ext) . "'";
                                     }
                                     $this->addJoin('wa_contact_data', $on);
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     if ($title) {
         $title = implode(', ', $title);
         // Strip slashes from search title.
         $bs = '\\\\';
         $title = preg_replace("~{$bs}(_|%|&|{$bs})~", '\\1', $title);
     }
     if ($auto_title && $title) {
         $this->addTitle($title, ' ');
     }
 }
 /** 
  * @return waCountryModel
  */
 public static function getInstance()
 {
     if (!self::$instance) {
         self::$instance = new self();
     }
     return self::$instance;
 }
Example #10
0
 /**
  * Returns customer's shipping address written in one string.
  *
  * @param array $order_params 'params' element of order data array returned by getOrder() method of shopOrderModel class
  * @param bool $for_map Whether full or brief address information must be returned; defaults to true
  * @return string
  */
 public static function getShippingAddressText($order_params, $for_map = true)
 {
     $address = array();
     foreach (waContactFields::get('address')->getFields() as $k => $v) {
         $address[$k] = ifset($order_params['shipping_address.' . $k]);
     }
     if ($for_map) {
         $address_f = array();
         foreach (array('country', 'region', 'zip', 'city', 'street') as $k) {
             if (!isset($address[$k])) {
                 continue;
             } elseif ($k == 'country') {
                 $address_f[$k] = waCountryModel::getInstance()->name(ifempty($address['country']));
             } elseif ($k == 'region') {
                 $address_f['region'] = '';
                 if (!empty($address['country']) && !empty($address['region'])) {
                     $model = new waRegionModel();
                     if ($region = $model->get($address['country'], $address['region'])) {
                         $address_f['region'] = $region['name'];
                     }
                 }
             } else {
                 $address_f[$k] = $address[$k];
             }
         }
         return implode(', ', $address_f);
     }
     return implode(', ', $address);
 }
 protected function getCountryList()
 {
     $cm = new waCountryModel();
     return $cm->all();
 }
 public function execute()
 {
     $this->prepare();
     if ($query = trim(waRequest::post('query'), '/')) {
         if (strpos($query, '/') === false) {
             $h = $hash = 'search/' . $query;
         } else {
             $h = $hash = $query;
             if (substr($hash, 0, 14) == 'import/results') {
                 $h = str_replace('import/results', 'import', $hash);
             }
         }
     } else {
         $h = $hash = '';
     }
     $h_parts = explode('/', $h, 2);
     $add_fields = array();
     if ($h_parts[0] == 'explore') {
         $collection = new contactsCollection();
         $event_params = array('collection' => $collection, 'hash' => $h_parts[1]);
         $result = wa()->event('explore', $event_params);
         if ($result) {
             $result = reset($result);
             $add_fields = ifset($result['fields']);
             $this->response['add_fields'] = $add_fields;
             $this->response['name'] = $result['name'];
         }
     } else {
         $collection = new contactsCollection($h);
     }
     $this->response['fields'] = array();
     $fields = '*,photo_url_32,photo_url_96';
     if ($h_parts[0] === 'users') {
         $fields .= ',_access';
         $this->response['fields']['_access'] = array('id' => '_access', 'name' => _w('Access'), 'type' => 'Access', 'vertical' => true);
     }
     $collection->orderBy($this->sort, $this->order);
     $this->response['count'] = $collection->count();
     $view = waRequest::post('view');
     if ($view == 'list') {
         // Preload info to cache to avoid excess DB access
         $cm = new waCountryModel();
         $cm->preload();
     }
     $this->response['contacts'] = array_values($collection->getContacts($fields, $this->offset, $this->limit));
     $this->workupContacts($this->response['contacts']);
     $this->response['total_count'] = $collection->count();
     foreach ($this->response['contacts'] as $i => &$c) {
         $c['offset'] = $this->offset + $i;
     }
     unset($c);
     if ($view == 'list') {
         // Need to format field values correctly for this view.
         foreach ($this->response['contacts'] as &$cdata) {
             $c = new waContact($cdata['id']);
             $c->setCache($cdata);
             $data = $c->load('list,js') + $cdata;
             contactsHelper::normalzieContactFieldValues($data, waContactFields::getInfo($c['is_company'] ? 'company' : 'person', true));
             if (isset($data['photo'])) {
                 $data['photo'] = $c->getPhoto();
             }
             $c->removeCache(array_keys($cdata));
             $cdata = $data;
         }
         $this->response['fields'] = array_merge($this->response['fields'], contactsHelper::getFieldsDescription(array('title', 'name', 'photo', 'firstname', 'middlename', 'lastname', 'locale', 'timezone', 'jobtitle', 'company', 'sex', 'company_contact_id'), true));
         unset($cdata);
     }
     // for companies set name to company name
     // for contacts with empty name, set it to <no name>
     foreach ($this->response['contacts'] as &$c) {
         if (isset($c['name']) && trim($c['name'])) {
             continue;
         }
         if (isset($c['company']) && trim($c['company'])) {
             $c['name'] = $c['company'];
             unset($c['company']);
             continue;
         }
         $c['name'] = '<' . _w('no name') . '>';
     }
     unset($c);
     $title = $collection->getTitle();
     $hm = new contactsHistoryModel();
     if ($hash) {
         $type = explode('/', $hash);
         $hash = substr($hash, 0, 1) == '/' ? $hash : '/contacts/' . $hash;
         $type = $type[0];
         // if search query looks like a quick search then remove field name from header
         if ($type == 'search' && preg_match('~^/contacts/search/(name\\*=[^/]*|email\\*=[^/]*@[^/]*)/?$~i', $hash)) {
             $title = preg_replace("~^[^=]+=~", '', $title);
         }
         // save history
         if ($type == 'search') {
             $hm->save($hash, $title, $type, $this->response['count']);
             $this->logAction('search');
         }
         // Information about system category in categories view
         if (substr($hash, 0, 19) === '/contacts/category/') {
             $category_id = (int) substr($hash, 19);
             $cm = new waContactCategoryModel();
             $category = $cm->getById($category_id);
             if ($category && $category['system_id']) {
                 $this->response['system_category'] = $category['system_id'];
             }
         }
     }
     // Update history in user's browser
     $this->response['history'] = $hm->get();
     $this->response['title'] = $title;
 }
Example #13
0
 private function init_address(&$address)
 {
     static $model;
     if (empty($address['country_name'])) {
         $address['country_name'] = waCountryModel::getInstance()->name(ifempty($address['country']));
     }
     if (empty($address['region_name'])) {
         $address['region_name'] = '';
         if (!empty($address['country']) && !empty($address['region'])) {
             if (!$model) {
                 $model = new waRegionModel();
             }
             if ($region = $model->get($address['country'], $address['region'])) {
                 $address['region_name'] = $region['name'];
             }
         }
     }
     if (empty($address['address'])) {
         $fields = array('street', 'city', 'region_name', 'zip', 'country_name');
         $address['address'] = '';
         $chunks = array();
         foreach ($fields as $field) {
             if (!empty($address[$field])) {
                 $chunks[] = $address[$field];
             }
         }
         $address['address'] = implode(', ', $chunks);
         if (preg_match('/^(.{1,119}),\\s+(.*)$/', $address['address'], $matches)) {
             $address['address_1'] = $matches[1];
             $address['address_2'] = $matches[2];
         } else {
             $address['address_1'] = $address['address'];
             $address['address_2'] = '';
         }
         $address['name'] = '';
         $fields = array('firstname', 'lasname', 'middlename');
         foreach ($fields as $field) {
             if (!empty($address[$field])) {
                 $address['name'] .= ' ' . $address[$field];
             }
         }
         $address['name'] = trim($address['name']);
     }
 }
 public function execute()
 {
     $this->prepare();
     if ($query = trim(waRequest::post('query'), '/')) {
         if (strpos($query, '/') === false) {
             $h = $hash = 'search/' . $query;
         } else {
             $h = $hash = $query;
             if (substr($hash, 0, 14) == 'import/results') {
                 $h = str_replace('import/results', 'import', $hash);
             }
         }
     } else {
         $h = $hash = '';
     }
     $collection = $this->getCollection($h);
     $collection->orderBy($this->sort, $this->order);
     $this->response['count'] = $collection->count();
     $view = waRequest::post('view');
     switch ($view) {
         case 'list':
             $fields = '*';
             break;
         case 'thumbs':
             $fields = 'id,name,photo';
             break;
         case 'table':
         default:
             $fields = waRequest::post('fields');
     }
     if ($view == 'list') {
         // Preload info to cache to avoid excess DB access
         $cm = new waCountryModel();
         $cm->preload();
     }
     if ($hash && $fields != '*') {
         if ($wf = $collection->getWhereFields()) {
             $fields = $fields . "," . implode(",", $wf);
         }
         $this->response['fields'] = explode(',', $fields);
     }
     $this->response['contacts'] = array_values($collection->getContacts($fields, $this->offset, $this->limit));
     if ($view == 'list') {
         // Need to format field values correctly for this view.
         foreach ($this->response['contacts'] as &$cdata) {
             $c = new waContact($cdata['id']);
             $c->setCache($cdata);
             $data = $c->load('list,js') + $cdata;
             if (isset($data['photo'])) {
                 $data['photo'] = $c->getPhoto();
             }
             $c->removeCache(array_keys($cdata));
             $cdata = $data;
         }
         unset($cdata);
     }
     // for companies set name to company name
     // for contacts with empty name, set it to <no name>
     foreach ($this->response['contacts'] as &$c) {
         if (isset($c['name']) && trim($c['name'])) {
             continue;
         }
         if (isset($c['company']) && trim($c['company'])) {
             $c['name'] = $c['company'];
             unset($c['company']);
             continue;
         }
         $c['name'] = '<' . _w('no name') . '>';
     }
     unset($c);
     $title = $collection->getTitle();
     if ($hash) {
         $type = explode('/', $hash);
         $hash = substr($hash, 0, 1) == '/' ? $hash : '/contacts/' . $hash;
         $type = $type[0];
         // if search query looks like a quick search then remove field name from header
         if ($type == 'search' && preg_match('~^/contacts/search/(name\\*=[^/]*|email\\*=[^/]*@[^/]*)/?$~i', $hash)) {
             $title = preg_replace("~^[^=]+=~", '', $title);
         }
         // save history
         if ($type == 'search' || $type == 'import') {
             $history = new contactsHistoryModel();
             if ($history->save($hash, $title, $type, $this->response['count'])) {
                 // new search performed, save to statistics log
                 $this->log('search', 1);
             }
         }
         // Information about system category in categories view
         if (substr($hash, 0, 19) === '/contacts/category/') {
             $category_id = (int) substr($hash, 19);
             $cm = new waContactCategoryModel();
             $category = $cm->getById($category_id);
             if ($category && $category['system_id']) {
                 $this->response['system_category'] = $category['system_id'];
             }
         }
     }
     // Update history in user's browser
     $historyModel = new contactsHistoryModel();
     $this->response['history'] = $historyModel->get();
     $this->response['title'] = $title;
 }
 public function allowedAddress()
 {
     $cache = new waSerializeCache(__CLASS__ . __FUNCTION__, 86400, 'webasyst');
     if (!($addresses = $cache->get())) {
         $addresses = array();
         /* countries */
         $countries = $this->request('ems.get.locations', array('type' => 'countries'));
         $country_model = new waCountryModel();
         $map = $country_model->getAll('iso2letter');
         $address = array('country' => array());
         foreach ($countries['locations'] as $country) {
             if (ifset($country['type']) == 'countries' && ($value = strtolower(ifset($country['value']))) && isset($map[$value])) {
                 $address['country'][] = $map[$value]['iso3letter'];
             }
         }
         $addresses[] = $address;
         /* regions */
         $region_model = new waRegionModel();
         $address = array('country' => 'rus', 'region' => array());
         $map = $region_model->getByCountry('rus');
         foreach ($map as $region) {
             if ($this->findTo(array('country' => 'rus', 'region_name' => $region['name']))) {
                 $address['region'][] = $region['code'];
             }
         }
         $addresses[] = $address;
         $cache->set($addresses);
     }
     return $addresses;
 }
 /**
  * @param string $iso3
  * @throws waException
  * @return string
  */
 private function getISO2CountryCode($iso3)
 {
     $country_model = new waCountryModel();
     $iso2 = $country_model->select('iso2letter')->where('iso3letter = :iso3', array('iso3' => $iso3))->fetchField('iso2letter');
     if (!$iso2) {
         throw new waException($this->_w("Unknown country"));
     }
     return $iso2;
 }
 /**
  * @param string $code iso3 code
  * @throws waException
  * @return string
  */
 protected function getCountryName($code)
 {
     $country_model = new waCountryModel();
     $country = $country_model->get($code);
     if (!$country) {
         throw new waException($this->plugin->_w("Unknown country: ") . $code);
     }
     $iso2letter = strtoupper($country['iso2letter']);
     $country_list = $this->getCountryList();
     if (!isset($country_list[$iso2letter])) {
         throw new waException($this->plugin->_w("Unknown country: ") . $code);
     }
     return $country_list[$iso2letter];
 }
 /**
  * @param $iso3code
  * @return mixed
  * @throws waException
  */
 protected function getCountryISO2Code($iso3code)
 {
     $country_model = new waCountryModel();
     $country = $country_model->get($iso3code);
     if (!$country) {
         throw new waException($this->_w("Unknown country: ") . $iso3code);
     }
     return strtoupper($country['iso2letter']);
 }
    /**
     *
     * Country/region dependent select boxes [+ city input]
     *
     * @param string $name
     * @param array $params
     * @return string
     * @example
     * Sample of params defined in proper settings.php
     *
     *    'region_zone' => array(
     *           'title' => 'Sender region',
     *           'control_type' => waHtmlControl::CUSTOM . ' waShipping::settingRegionZoneControl',
     *           'items' => array(
     *               'country' => array(
     *                       'value' => 'usa',
     *                       'description' => 'Represents the country from which the shipment will be originating'
     *               ),
     *               'region' => array(
     *                       'value' => 'NY',
     *                       'description' => 'Represents the state/province from which the shipment will be originating.<br>Required for printing labels'
     *               ),
     *               'city' => array(
     *                       'value' => 'New York',
     *                       'description' => Enter city name<br>Required for printing labels'
     *               ),
     *       )
     *    ),
     *
     *    If 'city' is not missing, city input box is presented
     *
     */
    public static function settingRegionZoneControl($name, $params = array())
    {
        $html = "";
        $plugin = $params['instance'];
        /**
         * @var waShipping $plugin
         */
        $params['items']['country']['value'] = !empty($params['value']['country']) ? $params['value']['country'] : '';
        $params['items']['region']['value'] = !empty($params['value']['region']) ? $params['value']['region'] : '';
        if (isset($params['items']['city'])) {
            $params['items']['city']['value'] = !empty($params['value']['city']) ? $params['value']['city'] : '';
        }
        // country section
        $cm = new waCountryModel();
        $html .= "<div class='country'>";
        $html .= "<select name='{$name}[country]'><option value=''></option>";
        foreach ($cm->all() as $country) {
            $html .= "<option value='{$country['iso3letter']}'" . ($params['items']['country']['value'] == $country['iso3letter'] ? " selected='selected'" : "") . ">{$country['name']}</value>";
        }
        $html .= "</select><br>";
        $html .= "<span class='hint'>{$params['items']['country']['description']}</span></div><br>";
        $regions = array();
        if ($params['items']['country']['value']) {
            $rm = new waRegionModel();
            $regions = $rm->getByCountry($params['items']['country']['value']);
        }
        // region section
        $html .= '<div class="region">';
        $html .= '<i class="icon16 loading" style="display:none; margin-left: -23px;"></i>';
        $html .= '<div class="empty"' . (!empty($regions) ? 'style="display:none;"' : '') . '><p class="small">' . $plugin->_w("Shipping will be restricted to the selected country") . "</p>";
        $html .= "<input name='{$name}[region]' value='' type='hidden'" . (!empty($regions) ? 'disabled="disabled"' : '') . '></div>';
        $html .= '<div class="not-empty" ' . (empty($regions) ? 'style="display:none;"' : '') . ">";
        $html .= "<select name='{$name}[region]'" . (empty($regions) ? 'disabled="disabled"' : '') . '><option value=""></option>';
        foreach ($regions as $region) {
            $html .= "<option value='{$region['code']}'" . ($params['items']['region']['value'] == $region['code'] ? ' selected="selected"' : "") . ">{$region['name']}</option>";
        }
        $html .= "</select><br>";
        $html .= "<span class='hint'>{$params['items']['region']['description']}</span></div><br>";
        // city section
        if (isset($params['items']['city'])) {
            $html .= "<div class='city'>";
            $html .= "<input name='{$name}[city]' value='" . (!empty($params['items']['city']['value']) ? $params['items']['city']['value'] : "") . "' type='text'>\n                <br>";
            $html .= "<span class='hint'>{$params['items']['city']['description']}</span></div>";
        }
        $html .= "</div>";
        $url = wa()->getAppUrl('webasyst') . '?module=backend&action=regions';
        // container id for interaction with js purpose
        $id = preg_replace("![\\[\\]]{1,2}!", "-", $name);
        if ($id[strlen($id) - 1] == "-") {
            $id = substr($id, 0, -1);
        }
        // wrap to container
        $html = "<div id='{$id}'>{$html}</div>";
        // javascript here
        $html .= <<<HTML
        <script type='text/javascript'>
        \$(function() {
            'use strict';
            var name = '{$name}[region]';
            var url  = '{$url}';
            var container = \$('#{$id}');

            var target  = container.find("div.region");
            var loader  = container.find(".loading");
            var old_val = target.find("select, input").val();

            container.find('select[name\$="[country]"]').change(function() {
                loader.show();
                \$.post(url, {
                    country: this.value }, function(r) {
                        if (r.data && r.data.options
                                && r.data.oOrder && r.data.oOrder.length)
                        {
                            var select = \$(
                                    "<select name='" + name + "'>" +
                                    "<option value=''></option>" +
                                    "</select>"
                            );
                            var o, selected = false;
                            for (var i = 0; i < r.data.oOrder.length; i++) {
                                o = \$("<option></option>").attr(
                                        "value", r.data.oOrder[i]
                                ).text(
                                        r.data.options[r.data.oOrder[i]]
                                ).attr(
                                        "disabled", r.data.oOrder[i] === ""
                                );
                                if (!selected && old_val === r.data.oOrder[i]) {
                                    o.attr("selected", true);
                                    selected = true;
                                }
                                select.append(o);
                            }
                            target.find(".not-empty select").replaceWith(select);
                            target.find(".not-empty").show();

                            target.find(".empty input").attr("disabled", true);
                            target.find(".empty").hide();

                        } else {
                            target.find(".empty input").attr("disabled", false);
                            target.find(".empty").show();

                            target.find(".not-empty select").attr("disabled", true);
                            target.find(".not-empty").hide();

                        }
                        loader.hide();
                    }, "json");
            });

            container.on("change", 'select[name="' + name + '"]', function() {
                old_val = this.value;
            });

        });
        </script>
HTML;
        return $html;
    }
 public function format($data)
 {
     return waCountryModel::getInstance()->name($data);
 }
 private function overview()
 {
     $this->setLayout(new shopWelcomeLayout());
     #countries
     $cm = new waCountryModel();
     $cm->preload();
     $countries = array();
     if (!empty($this->countries)) {
         foreach ($this->countries as $iso3) {
             $countries[$iso3] = $cm->get($iso3);
         }
     }
     $locale = waLocale::getInfo(wa()->getUser()->getLocale());
     if (!isset($locale['iso3']) || !isset($countries[$locale['iso3']])) {
         if (isset($countries['usa'])) {
             $country_iso3 = 'usa';
         } else {
             reset($countries);
             $country_iso3 = key($countries);
         }
     } else {
         $country_iso3 = $locale['iso3'];
     }
     $this->view->assign('countries', $countries);
     $this->view->assign('country_iso', $country_iso3);
     $this->view->assign('translate', $this->translate);
     #product types
     $types = array();
     if (!empty($this->types)) {
         foreach ($this->types as $id => $type) {
             if ($id != 'default') {
                 $name = ifempty($type['name'], $id);
                 $types[$id] = array('name' => ifempty($this->translate[$name], $name), 'icon' => ifempty($type['icon'], ''), 'description' => '');
             }
         }
     }
     $this->view->assign('types', $types);
 }