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');
 }
Example #2
0
function smarty_gettext_translate($matches)
{
    if ($str = waLocale::getString($matches[1])) {
        return $str;
    }
    return _wp(str_replace('\\"', '"', $matches[1]));
}
Example #3
0
 public function getTitle()
 {
     if ($title = $this->getConfig()->getOption('login_form_title')) {
         return waLocale::fromArray($title);
     }
     return wa()->getSetting('name', 'Webasyst', 'webasyst');
 }
 public function loadLocale($set_current = false)
 {
     $locale_path = $this->path . '/locale';
     $domain = ($this->app_id == 'webasyst' ? '' : $this->app_id . '_') . 'widget_' . $this->widget;
     if (file_exists($locale_path)) {
         waLocale::load(wa()->getLocale(), $locale_path, $domain, $set_current);
     }
 }
 public function execute()
 {
     $route_id = waRequest::get('route');
     $routes = wa()->getRouting()->getRoutes(siteHelper::getDomain());
     if (!isset($routes[$route_id])) {
         throw new waException('Route not found', 404);
     }
     $route = $routes[$route_id];
     $app_id = $routes[$route_id]['app'];
     $path = $this->getConfig()->getAppsPath($app_id, 'lib/config/site.php');
     $app = wa()->getAppInfo($app_id);
     if (file_exists($path)) {
         // load locale of the app
         if ($app_id != 'site') {
             waSystem::getInstance($app_id)->setActive($app_id);
         }
         $app['site'] = (include $path);
         // return old locale of the site
         if ($app_id != 'site') {
             waSystem::setActive('site');
         }
     }
     if (isset($app['site']['params'])) {
         $params = $this->getParams($route_id, $app['site']['params'], $route);
     } else {
         $params = array();
     }
     $themes = siteHelper::getThemes($app_id);
     if (!isset($route['theme']) && $themes) {
         $route['theme'] = 'default';
     }
     if (!isset($route['theme_mobile']) && $themes) {
         $route['theme_mobile'] = $route['theme'];
     }
     if (!isset($route['locale'])) {
         $route['locale'] = '';
     }
     if (!isset($route['_name'])) {
         if ($app_id == 'site') {
             if ($title = siteHelper::getDomain('title')) {
                 $route['_name'] = $title;
             } else {
                 $app_settings_model = new waAppSettingsModel();
                 $route['_name'] = $app_settings_model->get('webasyst', 'name', 'Webasyst');
             }
         } else {
             $route['_name'] = $app['name'];
         }
     }
     $this->view->assign('route_id', $route_id);
     $this->view->assign('route', $route);
     $this->view->assign('params', $params);
     $this->view->assign('app_id', $app_id);
     $this->view->assign('app', $app);
     $this->view->assign('domain_id', siteHelper::getDomainId());
     $this->view->assign('domain', siteHelper::getDomain());
     $this->view->assign('locales', array('' => _w('Auto')) + waLocale::getAll('name'));
 }
 /**
  *
  * Correct address (e.g. transliterate)
  *
  * @param string $address
  * @return string
  */
 protected function correctAddress($address)
 {
     if ($address) {
         foreach (waLocale::getAll() as $lang) {
             $address = waLocale::transliterate($address, $lang);
         }
     }
     return $address;
 }
 /**
  * @param string $id id as stored in database
  * @param waWorkflow $workflow
  * @param array $options option => value
  */
 public function __construct($id, waWorkflow $workflow, $options = array())
 {
     parent::__construct($id, $workflow, $options['options']);
     if (isset($options['name'])) {
         $this->name = waLocale::fromArray($options['name']);
     }
     if (isset($options['available_actions'])) {
         $this->available_actions = $options['available_actions'];
     }
 }
 public function __construct($coupon = array())
 {
     waLocale::loadByDomain(array('shop', 'coupon'));
     waSystem::pushActivePlugin('coupon', 'shop');
     $this->data['code'] = ifempty($coupon['code'], '');
     $this->data['expire'] = ifempty($coupon['expire_datetime']);
     $curm = new shopCurrencyModel();
     $currencies = $curm->getAll('code');
     $this->data['discount'] = shopCouponPlugin::formatValue($coupon, $currencies);
     waSystem::popActivePlugin();
 }
 function getOptions($id = null)
 {
     if (!$this->locales) {
         $this->locales = waLocale::getAll('name_region');
     }
     if ($id) {
         if (!isset($this->locales[$id])) {
             throw new Exception('Unknown locale: ' . $id);
         }
         return $this->locales[$id];
     }
     return $this->locales;
 }
 public function execute()
 {
     $this->getResponse()->addHeader('Content-type', 'application/json');
     $t = waRequest::post('t', '', waRequest::TYPE_STRING_TRIM);
     $t = preg_replace('/\\s+/', '-', $t);
     if ($t) {
         foreach (waLocale::getAll() as $lang) {
             $t = waLocale::transliterate($t, $lang);
         }
         $t = preg_replace('/[^a-zA-Z0-9_-]+/', '', $t);
     }
     $this->response = array('t' => strtolower($t), 'placeholder' => date('Ymd'));
 }
 /**
  * @param string $id id as stored in database
  * @param waWorkflow $workflow
  * @param array $options option => value
  */
 public function __construct($id, waWorkflow $workflow, $options = array())
 {
     parent::__construct($id, $workflow, $options['options']);
     if (isset($options['name'])) {
         $this->name = waLocale::fromArray($options['name']);
     }
     if (isset($options['state'])) {
         $this->state_id = $options['state'];
     }
     if (empty($this->options['log_record'])) {
         $this->options['log_record'] = $this->getName();
     }
 }
Example #12
0
 public static function getAvailableLanguages()
 {
     static $options;
     if ($options !== null) {
         return $options;
     }
     $langs = waLocale::getAll('info');
     $options = array();
     foreach ($langs as $code => $lang) {
         $code = substr($code, 0, 2);
         $options[$code] = ifempty($lang['name'], '') . ' (' . $code . ')';
     }
     return $options;
 }
/**
 * Smarty plugin
 * @package Smarty
 * @subpackage plugins
 */
function smarty_modifier_wa_format_number($n, $decimals = 0, $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();
    }
    return waLocale::format($n, $decimals, $locale);
}
 public static function getFilesFromPost()
 {
     if (waRequest::server('HTTP_X_FILE_NAME')) {
         $name = waRequest::server('HTTP_X_FILE_NAME');
         $size = waRequest::server('HTTP_X_FILE_SIZE');
         $safe_name = trim(preg_replace('~[^a-z\\.]~', '', waLocale::transliterate($name)), ". \n\t\r");
         $safe_name || ($safe_name = uniqid('p'));
         $file_path = wa()->getTempPath('photos/upload/') . $safe_name;
         $append_file = is_file($file_path) && $size > filesize($file_path);
         clearstatcache();
         file_put_contents($file_path, fopen('php://input', 'r'), $append_file ? FILE_APPEND : 0);
         $file = new waRequestFile(array('name' => $name, 'type' => waRequest::server('HTTP_X_FILE_TYPE'), 'size' => $size, 'tmp_name' => $file_path, 'error' => 0));
         return array($file);
     } else {
         return waRequest::file('files');
     }
 }
 /**
  * @param array $params deleted contact_id
  * @return array|void
  */
 public function execute(&$params)
 {
     waLocale::loadByDomain('blog');
     $post_model = new blogPostModel();
     $comment_model = new blogCommentModel();
     $links = array();
     foreach ($params as $contact_id) {
         $links[$contact_id] = array();
         if ($count = $post_model->countByField('contact_id', $contact_id)) {
             $links[$contact_id][] = array('role' => _wd('blog', 'Posts author'), 'links_number' => $count);
         }
         if ($count = $comment_model->countByField('contact_id', $contact_id)) {
             $links[$contact_id][] = array('role' => _wd('blog', 'Comments author'), 'links_number' => $count);
         }
     }
     return $links;
 }
 /**
  * @param array $params deleted contact_id
  * @return array|void
  */
 public function execute(&$params)
 {
     waLocale::loadByDomain('shop');
     // TODO: take a look to other models related with contacts
     $links = array();
     $product_reviews_model = new shopProductReviewsModel();
     $order_model = new shopOrderModel();
     foreach ($params as $contact_id) {
         $links[$contact_id] = array();
         if ($count = $product_reviews_model->countByField('contact_id', $contact_id)) {
             $links[$contact_id][] = array('role' => _wd('shop', 'Reviews author'), 'links_number' => $count);
         }
         if ($count = $order_model->countByField('contact_id', $contact_id)) {
             $links[$contact_id][] = array('role' => _wd('shop', 'Order customer'), 'links_number' => $count);
         }
     }
     return $links;
 }
Example #17
0
 /**
  * Trigger event with given $name from current active application.
  * @param string $name
  * @param mixed $params passed to event handlers
  * @return array app_id or plugin_id => data returned from handler (unless null is returned)
  */
 public function event($name, &$params = null)
 {
     $result = array();
     if (is_array($name)) {
         $event_app_id = $name[0];
         $system = self::getInstance($event_app_id);
         $name = $name[1];
     } else {
         $event_app_id = $this->getConfig()->getApplication();
         $system = $this;
     }
     $prefix = wa($event_app_id)->getConfig()->getPrefix();
     //
     // Call handlers defined by applications
     //
     $apps = $this->getApps();
     $path = $this->getConfig()->getPath('apps');
     foreach ($apps as $app_id => $info) {
         $file_path = $path . "/" . $app_id . "/lib/handlers/" . $prefix . "." . $name . ".handler.php";
         if (file_exists($file_path)) {
             waSystem::getInstance($app_id);
             include_once $file_path;
             $class_name = $name;
             if (strpos($name, '.') !== false) {
                 $class_name = strtok($class_name, '.') . ucfirst(strtok(''));
             }
             $class_name = $app_id . ucfirst($prefix) . ucfirst($class_name) . "Handler";
             /**
              * @var $handler waEventHandler
              */
             $handler = new $class_name();
             try {
                 $r = $handler->execute($params);
                 if ($r !== null) {
                     $result[$app_id] = $r;
                 }
             } catch (Exception $e) {
                 waLog::log('Event handling error in ' . $file_path . ': ' . $e->getMessage());
             }
         }
     }
     //self::setActive($event_app_id);
     //
     // Call handlers defined by current application's plugins
     //
     $plugins = $system->getConfig()->getPlugins();
     foreach ($plugins as $plugin_id => $plugin) {
         foreach ($plugin['handlers'] as $handler_event => $handler_method) {
             if ($name == $handler_event) {
                 // Remember active plugin locale name for _wp() to work
                 self::pushActivePlugin($plugin_id, wa($event_app_id)->getConfig()->getPrefix());
                 $class_name = $event_app_id . ucfirst($plugin_id) . 'Plugin';
                 try {
                     $class = new $class_name($plugin);
                     // Load plugin locale if it exists
                     $locale_path = $this->getAppPath('plugins/' . $plugin_id . '/locale', $event_app_id);
                     if (is_dir($locale_path)) {
                         waLocale::load($this->getLocale(), $locale_path, self::getActiveLocaleDomain(), false);
                     }
                     if (method_exists($class, $handler_method) && null !== ($r = $class->{$handler_method}($params))) {
                         $result[$plugin_id . '-plugin'] = $r;
                     }
                 } catch (Exception $e) {
                     waLog::log('Event handling error in ' . $class_name . '->' . $handler_method . '(): ' . $e->getMessage());
                 }
                 self::popActivePlugin();
             }
         }
     }
     return $result;
 }
 /**
  * Returns information about all app's installed plugins as an associative array.
  *
  * @return array
  */
 public function getPlugins()
 {
     if ($this->plugins === null) {
         $locale = wa()->getLocale();
         $file = waConfig::get('wa_path_cache') . "/apps/" . $this->application . '/config/plugins.' . $locale . '.php';
         if (!file_exists($file) || SystemConfig::isDebug()) {
             waFiles::create(waConfig::get('wa_path_cache') . "/apps/" . $this->application . '/config');
             // read plugins from file wa-config/[APP_ID]/plugins.php
             $path = $this->getConfigPath('plugins.php', true);
             if (!file_exists($path)) {
                 $this->plugins = array();
                 return $this->plugins;
             }
             $all_plugins = (include $path);
             $this->plugins = array();
             foreach ($all_plugins as $plugin_id => $enabled) {
                 if ($enabled) {
                     $plugin_config = $this->getPluginPath($plugin_id) . "/lib/config/plugin.php";
                     if (!file_exists($plugin_config)) {
                         continue;
                     }
                     $plugin_info = (include $plugin_config);
                     waSystem::pushActivePlugin($plugin_id, $this->application);
                     // Load plugin locale if it exists
                     $locale_path = wa()->getAppPath('plugins/' . $plugin_id . '/locale', $this->application);
                     if (is_dir($locale_path)) {
                         waLocale::load($locale, $locale_path, wa()->getActiveLocaleDomain(), false);
                     }
                     $plugin_info['name'] = _wp($plugin_info['name']);
                     if (isset($plugin_info['title'])) {
                         $plugin_info['title'] = _wp($plugin_info['title']);
                     }
                     if (isset($plugin_info['description'])) {
                         $plugin_info['description'] = _wp($plugin_info['description']);
                     }
                     waSystem::popActivePlugin();
                     $plugin_info['id'] = $plugin_id;
                     $plugin_info['app_id'] = $this->application;
                     if (isset($plugin_info['img'])) {
                         $plugin_info['img'] = 'wa-apps/' . $this->application . '/plugins/' . $plugin_id . '/' . $plugin_info['img'];
                     }
                     if (isset($plugin_info['rights']) && $plugin_info['rights']) {
                         $plugin_info['handlers']['rights.config'] = 'rightsConfig';
                     }
                     if (isset($plugin_info['frontend']) && $plugin_info['frontend']) {
                         $plugin_info['handlers']['routing'] = 'routing';
                     }
                     if (!empty($plugin_info[$this->application . '_settings'])) {
                         $plugin_info['custom_settings'] = $plugin_info[$this->application . '_settings'];
                     }
                     $this->plugins[$plugin_id] = $plugin_info;
                 }
             }
             if (!SystemConfig::isDebug()) {
                 waUtils::varExportToFile($this->plugins, $file);
             } else {
                 waFiles::delete($file);
             }
         } else {
             $this->plugins = (include $file);
         }
     }
     return $this->plugins;
 }
 /**
  * Returns name of the field
  *
  * @param string $locale - locale
  * @return string
  */
 public function getName($locale = null, $escape = false)
 {
     if (!$locale) {
         $locale = waSystem::getInstance()->getLocale();
     }
     $name = '';
     if (isset($this->name[$locale])) {
         $name = $this->name[$locale];
     } else {
         if (isset($this->name['en_US'])) {
             if ($locale == waSystem::getInstance()->getLocale() && wa()->getEnv() == 'backend') {
                 $name = _ws($this->name['en_US']);
             } else {
                 $name = waLocale::translate('webasyst', $locale, $this->name['en_US']);
             }
         } else {
             $name = reset($this->name);
             // reset() returns the first value
         }
     }
     return $escape ? htmlspecialchars($name, ENT_QUOTES) : $name;
 }
 private function stepImportImage()
 {
     /**
      * @var shopProductImagesModel $model
      */
     static $model;
     if (!is_array($this->data['map'][self::STAGE_IMAGE]) && $this->data['map'][self::STAGE_IMAGE]) {
         $this->data['map'][self::STAGE_IMAGE] = array($this->data['map'][self::STAGE_IMAGE]);
     }
     if ($file = reset($this->data['map'][self::STAGE_IMAGE])) {
         if (!$model) {
             $model = new shopProductImagesModel();
         }
         //TODO store image id & if repeated - skip it
         $target = 'new';
         $u = @parse_url($file);
         $_is_url = false;
         if (!$u || !(isset($u['scheme']) && isset($u['host']) && isset($u['path']))) {
         } elseif (in_array($u['scheme'], array('http', 'https', 'ftp', 'ftps'))) {
             $_is_url = true;
         } else {
             $target = 'skip';
             $file = null;
             $this->error(sprintf('Unsupported file source protocol', $u['scheme']));
         }
         $search = array('product_id' => $this->data['map'][self::STAGE_PRODUCT], 'ext' => pathinfo($file, PATHINFO_EXTENSION));
         try {
             $name = preg_replace('@[^a-zA-Zа-яА-Я0-9\\._\\-]+@', '', basename(urldecode($file)));
             if ($_is_url) {
                 $pattern = sprintf('@/(%d)/images/(\\d+)/\\2\\.(\\d+(x\\d+)?)\\.([^\\.]+)$@', $search['product_id']);
                 if (preg_match($pattern, $file, $matches)) {
                     $image = array('product_id' => $matches[1], 'id' => $matches[2], 'ext' => $matches[5]);
                     if (strpos($file, shopImage::getUrl($image, $matches[3])) !== false && $model->getByField($image)) {
                         #skip local file
                         $target = 'skip';
                         $file = null;
                     }
                 }
                 if ($file) {
                     waFiles::upload($file, $file = wa()->getTempPath('csv/upload/images/' . waLocale::transliterate($name, 'en_US')));
                 }
             } elseif ($file) {
                 $file = $this->data['upload_path'] . $file;
             }
             if ($file && file_exists($file)) {
                 if ($image = waImage::factory($file)) {
                     $search['original_filename'] = $name;
                     $data = array('product_id' => $this->data['map'][self::STAGE_PRODUCT], 'upload_datetime' => date('Y-m-d H:i:s'), 'width' => $image->width, 'height' => $image->height, 'size' => filesize($file), 'original_filename' => $name, 'ext' => pathinfo($file, PATHINFO_EXTENSION));
                     if ($exists = $model->getByField($search)) {
                         $data = array_merge($exists, $data);
                         $thumb_dir = shopImage::getThumbsPath($data);
                         $back_thumb_dir = preg_replace('@(/$|$)@', '.back$1', $thumb_dir, 1);
                         $paths[] = $back_thumb_dir;
                         waFiles::delete($back_thumb_dir);
                         // old backups
                         if (file_exists($thumb_dir)) {
                             if (!(waFiles::move($thumb_dir, $back_thumb_dir) || waFiles::delete($back_thumb_dir)) && !waFiles::delete($thumb_dir)) {
                                 throw new waException(_w("Error while rebuild thumbnails"));
                             }
                         }
                     }
                     $image_changed = false;
                     /**
                      * TODO move it code into product core method
                      */
                     /**
                      * Extend add/update product images
                      * Make extra workup
                      * @event image_upload
                      */
                     $event = wa()->event('image_upload', $image);
                     if ($event) {
                         foreach ($event as $result) {
                             if ($result) {
                                 $image_changed = true;
                                 break;
                             }
                         }
                     }
                     if (empty($data['id'])) {
                         $image_id = $data['id'] = $model->add($data);
                     } else {
                         $image_id = $data['id'];
                         $target = 'update';
                         $model->updateById($image_id, $data);
                     }
                     if (!$image_id) {
                         throw new waException("Database error");
                     }
                     $image_path = shopImage::getPath($data);
                     if (file_exists($image_path) && !is_writable($image_path) || !file_exists($image_path) && !waFiles::create($image_path)) {
                         $model->deleteById($image_id);
                         throw new waException(sprintf("The insufficient file write permissions for the %s folder.", substr($image_path, strlen($this->getConfig()->getRootPath()))));
                     }
                     if ($image_changed) {
                         $image->save($image_path);
                         /**
                          * @var shopConfig $config
                          */
                         $config = $this->getConfig();
                         if ($config->getOption('image_save_original') && ($original_file = shopImage::getOriginalPath($data))) {
                             waFiles::copy($file, $original_file);
                         }
                     } else {
                         waFiles::copy($file, $image_path);
                     }
                     $this->data['processed_count'][self::STAGE_IMAGE][$target]++;
                 } else {
                     $this->error(sprintf('Invalid image file', $file));
                 }
             } elseif ($file) {
                 $this->error(sprintf('File %s not found', $file));
                 $target = 'skip';
                 $this->data['processed_count'][self::STAGE_IMAGE][$target]++;
             } else {
                 $this->data['processed_count'][self::STAGE_IMAGE][$target]++;
             }
         } catch (Exception $e) {
             $this->error($e->getMessage());
             //TODO skip on repeated error
         }
         array_shift($this->data['map'][self::STAGE_IMAGE]);
         ++$this->data['current'][self::STAGE_IMAGE];
         if ($_is_url) {
             waFiles::delete($file);
         }
     }
     return true;
 }
 protected function forgotPassword()
 {
     $error = '';
     $auth = wa()->getAuth();
     if (waRequest::method() == 'post' && !waRequest::post('ignore')) {
         if ($contact = $this->findContact(waRequest::post('login'), $auth)) {
             if ($contact->get('is_banned')) {
                 $error = _ws('Password recovery for this email has been banned.');
             } elseif ($email = $contact->get('email', 'default')) {
                 if ($contact['locale']) {
                     wa()->setLocale($contact['locale']);
                     waLocale::loadByDomain('webasyst', wa()->getLocale());
                 }
                 $hash = $this->getHash($contact['id'], true);
                 if ($this->send($email, $this->getResetPasswordUrl($hash))) {
                     $this->view->assign('sent', 1);
                 } else {
                     $error = _ws('Sorry, we can not recover password for this login name or email. Please refer to your system administrator.');
                 }
             }
         } else {
             if ($auth->getOption('login') == 'email') {
                 $error = _ws('No user with this email has been found.');
             } else {
                 $error = _ws('No user with this login name or email has been found.');
             }
         }
     }
     $this->view->assign('options', $auth->getOptions());
     $this->view->assign('error', $error);
     if ($this->layout) {
         $this->layout->assign('error', $error);
     }
     wa()->getResponse()->setTitle(_ws('Password recovery'));
 }
Example #22
0
    public function getUniqueCode($code, $id = null)
    {
        if ($code = preg_replace('/[^a-zA-Z0-9_]+/', '_', trim(waLocale::transliterate($code)))) {
            if ($code == '_') {
                $code = 'f_';
            }
            $sql = <<<SQL
            SELECT `id`, LOWER(`code`) AS `code`
            FROM `{$this->table}`
            WHERE (`id` != i:id) AND (`code` LIKE s:c)
SQL;
            $params = array('c' => $this->escape($code, 'like') . '%', 'id' => $id);
            $codes = $this->query($sql, $params)->fetchAll('id', true);
            if ($codes) {
                $count = 0;
                $unique_code = $code;
                while (in_array(strtolower($unique_code), $codes)) {
                    $unique_code = $code . ++$count;
                }
            } else {
                $unique_code = $code;
            }
        } else {
            $unique_code = time();
        }
        return $unique_code;
    }
Example #23
0
/**
 * Smarty plugin
 * @package Smarty
 * @subpackage plugins
 */
function smarty_modifier_wa_format($n, $decimals = null)
{
    return waLocale::format($n, $decimals);
}
 /**
  * Returns name of the field
  *
  * @param string $locale - locale
  * @return string
  */
 public function getName($locale = null)
 {
     if (!$locale) {
         $locale = waSystem::getInstance()->getLocale();
     }
     if (isset($this->name[$locale])) {
         return $this->name[$locale];
     } else {
         if (isset($this->name['en_US'])) {
             if ($locale = waSystem::getInstance()->getLocale()) {
                 return _ws($this->name['en_US']);
             } else {
                 return waLocale::translate('webasyst', $locale, $this->name['en_US']);
             }
         } else {
             return reset($this->name);
             // reset() returns the first value
         }
     }
 }
 public function format($data)
 {
     $info = waLocale::getInfo($data);
     return ifset($info['name'], $data);
 }
 public function execute()
 {
     $contact_model = new waContactModel();
     if ($contact_model->countAll()) {
         $this->redirect($this->getConfig()->getBackendUrl(true));
     }
     if (($locale = waRequest::get('lang')) && waLocale::getInfo($locale)) {
         // set locale
         wa()->setLocale($locale);
         // save to database default locale
         $app_settings_model = new waAppSettingsModel();
         $app_settings_model->set('webasyst', 'locale', $locale);
     }
     if (file_exists($this->getConfig()->getRootPath() . '/install.php')) {
         @unlink($this->getConfig()->getRootPath() . '/install.php');
     }
     if (waRequest::getMethod() == 'post') {
         $errors = array();
         $login = waRequest::post('login');
         $validator = new waLoginValidator();
         if (!$validator->isValid($login)) {
             $errors['login'] = implode("<br />", $validator->getErrors());
         }
         $password = waRequest::post('password');
         $password_confirm = waRequest::post('password_confirm');
         if ($password !== $password_confirm) {
             $errors['password'] = _w('Passwords do not match');
         }
         $email = waRequest::post('email');
         $validator = new waEmailValidator();
         if (!$validator->isValid($email)) {
             $errors['email'] = implode("<br />", $validator->getErrors());
         }
         if ($errors) {
             $this->view->assign('errors', $errors);
         } else {
             // save account name
             $app_settings_model = new waAppSettingsModel();
             $app_settings_model->set('webasyst', 'name', waRequest::post('account_name'));
             if ($email) {
                 $app_settings_model->set('webasyst', 'email', $email);
                 $app_settings_model->set('webasyst', 'sender', $email);
             }
             // create user
             $user = new waUser();
             $firstname = waRequest::post('firstname');
             $user['firstname'] = $firstname ? $firstname : $login;
             $user['lastname'] = waRequest::post('lastname');
             $user['is_user'] = 1;
             $user['login'] = $login;
             $user['password'] = $password;
             $user['email'] = $email;
             $user['locale'] = wa()->getLocale();
             $user['create_method'] = 'install';
             if ($errors = $user->save()) {
                 $result = array();
                 foreach ($errors as $k => $v) {
                     $result['all'][] = $k . ": " . (is_array($v) ? implode(', ', $v) : $v);
                 }
                 $result['all'] = implode("\r\n", $result['all']);
                 $this->view->assign('errors', $result);
             } else {
                 $user->setRight('webasyst', 'backend', 1);
                 waSystem::getInstance()->getAuth()->auth(array('login' => $login, 'password' => $password));
                 $path = $this->getConfig()->getPath('config');
                 // check routing.php
                 if (!file_exists($path . '/routing.php')) {
                     $apps = wa()->getApps();
                     $data = array();
                     $domain = $this->getConfig()->getDomain();
                     $site = false;
                     foreach ($apps as $app_id => $app) {
                         if ($app_id == 'site') {
                             $site = true;
                         } elseif (!empty($app['frontend'])) {
                             $routing = array('url' => $app_id . '/*', 'app' => $app_id);
                             if (!empty($app['routing_params']) && is_array($app['routing_params'])) {
                                 $routing = array_merge($routing, $app['routing_params']);
                             }
                             $data[$domain][] = $routing;
                         }
                     }
                     if ($site) {
                         $data[$domain][] = array('url' => '*', 'app' => 'site');
                     }
                     waUtils::varExportToFile($data, $path . '/routing.php');
                 }
                 // redirect to backend
                 $this->redirect($this->getConfig()->getBackendUrl(true));
             }
         }
     }
 }
 /**
  * Trigger event with given $name from current active application.
  *
  * @param  string    $name        Event name.
  * @param  mixed     $params      Parameters passed to event handlers.
  * @param  string[]  $array_keys  Array of expected template items for UI events.
  * @return  array  app_id or plugin_id => data returned from handler (unless null is returned)
  */
 public function event($name, &$params = null, $array_keys = null)
 {
     $result = array();
     if (is_array($name)) {
         $event_app_id = $name[0];
         $event_system = self::getInstance($event_app_id);
         $name = $name[1];
     } else {
         $event_app_id = $this->getConfig()->getApplication();
         $event_system = $this;
     }
     $event_prefix = wa($event_app_id)->getConfig()->getPrefix();
     if (!isset(self::$handlers['apps'])) {
         self::$handlers['apps'] = array();
         $cache_file = $this->config->getPath('cache', 'config/handlers');
         if (!waSystemConfig::isDebug() && file_exists($cache_file)) {
             self::$handlers['apps'] = (include $cache_file);
         }
         if (!self::$handlers['apps'] || !is_array(self::$handlers['apps'])) {
             $apps = $this->getApps();
             $path = $this->getConfig()->getPath('apps');
             foreach ($apps as $app_id => $app_info) {
                 $files = waFiles::listdir($path . '/' . $app_id . '/lib/handlers/');
                 foreach ($files as $file) {
                     if (substr($file, -12) == '.handler.php') {
                         $file = explode('.', substr($file, 0, -12), 2);
                         self::$handlers['apps'][$file[0]][$file[1]][] = $app_id;
                     }
                 }
             }
             if (!waSystemConfig::isDebug()) {
                 waUtils::varExportToFile(self::$handlers['apps'], $cache_file);
             }
         }
     }
     if (!isset(self::$handlers['plugins'][$event_app_id])) {
         self::$handlers['plugins'][$event_app_id] = array();
         $plugins = $event_system->getConfig()->getPlugins();
         foreach ($plugins as $plugin_id => $plugin) {
             if (!empty($plugin['handlers'])) {
                 foreach ($plugin['handlers'] as $handler_event => $handler_method) {
                     self::$handlers['plugins'][$event_app_id][$handler_event][$plugin_id] = $handler_method;
                 }
             }
         }
     }
     if (isset(self::$handlers['apps'][$event_app_id][$name])) {
         $path = $this->getConfig()->getPath('apps');
         foreach (self::$handlers['apps'][$event_app_id][$name] as $app_id) {
             $file_path = $path . '/' . $app_id . '/lib/handlers/' . $event_prefix . "." . $name . ".handler.php";
             if (!file_exists($file_path)) {
                 continue;
             }
             wa($app_id);
             include_once $file_path;
             $class_name = $name;
             if (strpos($name, '.') !== false) {
                 $class_name = strtok($class_name, '.') . ucfirst(strtok(''));
             }
             $class_name = $app_id . ucfirst($event_prefix) . ucfirst($class_name) . "Handler";
             /**
              * @var $handler waEventHandler
              */
             $handler = new $class_name();
             try {
                 $r = $handler->execute($params);
                 if ($r !== null) {
                     $result[$app_id] = $r;
                 }
             } catch (Exception $e) {
                 waLog::log('Event handling error in ' . $file_path . ': ' . $e->getMessage());
             }
         }
     }
     if (isset(self::$handlers['plugins'][$event_app_id][$name])) {
         $plugins = $event_system->getConfig()->getPlugins();
         foreach (self::$handlers['plugins'][$event_app_id][$name] as $plugin_id => $method) {
             if (!isset($plugins[$plugin_id])) {
                 continue;
             }
             $plugin = $plugins[$plugin_id];
             self::pushActivePlugin($plugin_id, $event_prefix);
             $class_name = $event_app_id . ucfirst($plugin_id) . 'Plugin';
             try {
                 $class = new $class_name($plugin);
                 // Load plugin locale if it exists
                 $locale_path = $this->getAppPath('plugins/' . $plugin_id . '/locale', $event_app_id);
                 if (is_dir($locale_path)) {
                     waLocale::load($this->getLocale(), $locale_path, self::getActiveLocaleDomain(), false);
                 }
                 if (method_exists($class, $method) && null !== ($r = $class->{$method}($params))) {
                     if ($array_keys && is_array($r)) {
                         foreach ($array_keys as $k) {
                             if (!isset($r[$k])) {
                                 $r[$k] = '';
                             }
                         }
                     }
                     $result[$plugin_id . '-plugin'] = $r;
                 }
             } catch (Exception $e) {
                 waLog::log('Event handling error in ' . $class_name . '->' . $name . '(): ' . $e->getMessage());
             }
             self::popActivePlugin();
         }
     }
     return $result;
 }
 public static function load($locale, $locale_path, $domain, $textdomain = true)
 {
     if (!self::$locale || $textdomain) {
         self::$locale = $locale;
     }
     self::$loaded[$locale][$domain] = true;
     self::getAdapter()->load($locale, $locale_path, $domain, $textdomain);
     if ($textdomain) {
         self::$domain = $domain;
     }
 }
Example #29
0
 public static function transliterate($slug)
 {
     $slug = preg_replace('/\\s+/', '-', $slug);
     if ($slug) {
         foreach (waLocale::getAll() as $lang) {
             $slug = waLocale::transliterate($slug, $lang);
         }
     }
     $slug = preg_replace('/[^a-zA-Z0-9_-]+/', '', $slug);
     if (!$slug) {
         $slug = date('Ymd');
     }
     return strtolower($slug);
 }
Example #30
0
 public function execute()
 {
     $wa_vars = array('$wa_url' => _w('URL of this Webasyst installation (relative)'), '$wa_app_url' => _w('URL of the current app settlement (relative)'), '$wa_backend_url' => _w('URL to access Webasyst backend (relative)'), '$wa_theme_url' => _w('URL of the current app design theme folder (relative)'), '$wa->title()' => _w('Title'), '$wa->title("<em>title</em>")' => _w('Assigns a new title'), '$wa->accountName()' => _w('Returns name of this Webasyst installation (name is specified in “Installer” app settings)'), '$wa->apps()' => _w('Returns this site’s core navigation menu which is either set automatically or manually in the “Site settings” screen'), '$wa->currentUrl(bool <em>$absolute</em>)' => _w('Returns current page URL (either absolute or relative)'), '$wa->domainUrl()' => _w('Returns this domain’s root URL (absolute)'), '$wa->globals("<em>key</em>")' => _w('Returns value of the global var by <em>key</em>. Global var array is initially empty, and can be used arbitrarily.'), '$wa->globals("<em>key</em>", "<em>value</em>")' => _w('Assigns global var a new value'), '$wa->get("<em>key</em>")' => _w('Returns GET parameter value (same as PHP $_GET["<em>key</em>"])'), '$wa->isMobile()' => _w('Based on current session data returns <em>true</em> or <em>false</em> if user is using a multi-touch mobile device; if no session var reflecting current website version (mobile or desktop) is available, User Agent information is used'), '$wa->locale()' => _w('Returns user locale, e.g. "en_US", "ru_RU". In case user is authorized, locale is retrieved from “Contacts” app user record, or detected automatically otherwise'), '$wa->post("<em>key</em>")' => _w('Returns POST parameter value (same as PHP $_POST["<em>key</em>"])'), '$wa->server("<em>key</em>")' => _w('Returns SERVER parameter value (same as PHP $_SERVER["KEY"])'), '$wa->session("<em>key</em>")' => _w('Returns SESSION var value (same as PHP $_SESSION["<em>key</em>"])'), '$wa->block("<em>id</em>")' => _w('Embeds HTML block by ID'), '$wa->user("<em>field</em>")' => _w('Returns authorized user data from associated record in “Contacts” app. "<em>field</em>" (string) is optional and indicates the field id to be returned. If not  Returns <em>false</em> if user is not authorized'), '$wa->userAgent("<em>key</em>")' => _w('Returns User Agent info by specified “<em>key</em>” parameter:') . '<br />' . _w('— <em>"platform"</em>: current visitor device platform name, e.g. <em>windows, mac, linux, ios, android, blackberry</em>;') . '<br />' . _w('— <em>"isMobile"</em>: returns <em>true</em> or <em>false</em> if user is using a multi-touch mobile device (iOS, Android and similar), based solely on User Agent string;'), '$wa-><em>APP_ID</em>->themePath("<em>theme_id</em>")' => _w('Returns path to theme folder by <em>theme_id</em> and <em>APP_ID</em>'));
     $app_id = waRequest::get('app');
     $file = waRequest::get('file');
     $vars = array();
     if ($app_id) {
         $app = wa()->getAppInfo($app_id);
         $path = $this->getConfig()->getAppsPath($app_id, 'lib/config/site.php');
         if (file_exists($path)) {
             $site = (include $path);
             if (isset($site['vars'])) {
                 if (isset($site['vars'][$file])) {
                     $vars += $site['vars'][$file];
                 }
                 if (isset($site['vars']['$wa'])) {
                     $vars += $site['vars']['$wa'];
                 }
                 if (isset($site['vars']['all'])) {
                     $vars += $site['vars']['all'];
                 }
             }
         }
         if ($app_id == 'site' && ($id = waRequest::get('id'))) {
             $page_model = new sitePageModel();
             $page = $page_model->getById($id);
             $file = $page['name'];
             $vars += $site['vars']['page.html'];
         }
     } else {
         $app = null;
     }
     $this->view->assign('vars', $vars);
     $this->view->assign('file', $file);
     $this->view->assign('app', $app);
     $this->view->assign('wa_vars', $wa_vars);
     $this->view->assign('smarty_vars', array('{$foo}' => _w('Displays a simple variable (non array/object)'), '{$foo[4]}' => _w('Displays the 5th element of a zero-indexed array'), '{$foo.bar}' => _w('Displays the "<em>bar</em>" key value of an array. Similar to PHP $foo["bar"]'), '{$foo.$bar}' => _w('Displays variable key value of an array. Similar to PHP $foo[$bar]'), '{$foo->bar}' => _w('Displays the object property named <em>bar</em>'), '{$foo->bar()}' => _w('Displays the return value of object method named <em>bar()</em>'), '{$foo|print_r}' => _w('Displays structured information about variable. Arrays and objects are explored recursively with values indented to show structure. Similar to PHP var_dump($foo)'), '{$foo|escape}' => _w('Escapes a variable for safe display in HTML'), '{$foo|wa_datetime:$format}' => _w('Outputs <em>$var</em> datetime in a user-friendly form. Supported <em>$format</em> values: <em>monthdate, date, dtime, datetime, fulldatetime, time, fulltime, humandate, humandatetime</em>'), '{$x+$y}' => _w('Outputs the sum of <em>$x</em> and <em>$y</em>'), '{$foo=3*4}' => _w('Assigns variable a value'), '{time()}' => _w('Direct PHP function access. E.g. <em>{time()}</em> displays the current timestamp'), '{literal}...{/literal}' => _w('Content between {literal} tags will not be parsed by Smarty'), '{include file="..."}' => _w('Embeds a Smarty template into the current content. <em>file</em> attribute specifies a template filename within the current design theme folder'), '{if}...{else}...{/if}' => _w('Similar to PHP if statements'), '{foreach from=$a key=k item=v}...{foreachelse}...{/foreach}' => _w('{foreach} is for looping over arrays of data')));
     $model = new siteBlockModel();
     $blocks = $model->order('sort')->fetchAll('id');
     $active_app = wa()->getApp();
     $apps = wa()->getApps();
     foreach ($apps as $app_id => $app) {
         $path = $this->getConfig()->getAppsPath($app_id, 'lib/config/site.php');
         if (file_exists($path)) {
             waLocale::load(wa()->getLocale(), $this->getConfig()->getAppsPath($app_id, 'locale'), $app_id, true);
             $site_config = (include $path);
             if (!empty($site_config['blocks'])) {
                 foreach ($site_config['blocks'] as $block_id => $block) {
                     if (!is_array($block)) {
                         $block = array('content' => $block, 'description' => '');
                     }
                     $block_id = $app_id . '.' . $block_id;
                     if (!isset($blocks[$block_id])) {
                         $block['id'] = $block_id;
                         $block['app'] = $app;
                         $blocks[$block_id] = $block;
                     }
                 }
             }
         }
     }
     wa()->setActive($active_app);
     $this->view->assign('blocks', $blocks);
 }