コード例 #1
0
 public function execute()
 {
     $path = rtrim(waRequest::post('path'), ' /');
     $path = wa()->getDataPath($path, true);
     if (!file_exists($path)) {
         throw new waException("File not found", 404);
     }
     $dh = opendir($path);
     $names = array();
     while (($f = readdir($dh)) !== false) {
         if ($f !== '.' && $f !== '..' && is_file($path . '/' . $f)) {
             $names[] = $f;
         }
     }
     natcasesort($names);
     $n = count($names);
     $limit = 100;
     $page = waRequest::get('page', 1);
     $names = array_slice($names, ($page - 1) * $limit, 100);
     $files = array();
     foreach ($names as $name) {
         $f = $name;
         $t = filemtime($path . '/' . $f);
         $files[] = array('file' => htmlspecialchars($name), 'type' => $this->getType($f), 'size' => filesize($path . '/' . $f), 'timestamp' => $t, 'datetime' => waDateTime::format('humandatetime', $t));
     }
     closedir($dh);
     $this->response['pages'] = ceil((double) $n / $limit);
     $this->response['files'] = $files;
 }
コード例 #2
0
 public function execute()
 {
     $path = rtrim(waRequest::post('path'), ' /');
     $path = wa()->getDataPath($path, true);
     if (!file_exists($path)) {
         throw new waException("File not found", 404);
     }
     $files = array();
     $dh = opendir($path);
     $names = array();
     while (($f = readdir($dh)) !== false) {
         if ($f !== '.' && $f !== '..' && is_file($path . '/' . $f)) {
             $t = filemtime($path . '/' . $f);
             $name = htmlspecialchars($f);
             $files[$name] = array('file' => $name, 'type' => $this->getType($f), 'size' => filesize($path . '/' . $f), 'timestamp' => $t, 'datetime' => waDateTime::format('humandatetime', $t));
             $names[] = $name;
         }
     }
     natcasesort($names);
     $sorted_files = array();
     foreach ($names as $name) {
         $sorted_files[] =& $files[$name];
     }
     closedir($dh);
     $this->response = $sorted_files;
 }
コード例 #3
0
 public function calculate()
 {
     $params = array();
     $params['weight'] = max(0.1, $this->getTotalWeight());
     if ($params['weight'] > 31.5) {
         /* hardcoded */
         return 'Вес отправления превышает максимально допустимый (31,5 кг).';
     } elseif (empty($params['weight'])) {
         return 'Вес отправления не задан.';
     }
     $incomplete = false;
     switch ($country_iso3 = $this->getAddress('country')) {
         case 'rus':
             $address = array_merge(array('country' => 'rus'), $this->getSettings());
             $params['from'] = $this->findTo($address);
             $params['to'] = $this->findTo($this->getAddress());
             if (empty($params['to'])) {
                 $incomplete = empty($address['city']) && empty($address['region']);
             }
             break;
         default:
             /* International shipping*/
             $country_model = new waCountryModel();
             if ($country = $country_model->get($country_iso3)) {
                 $params['to'] = mb_strtoupper($country['iso2letter']);
             } else {
                 $params['to'] = false;
             }
             $params['type'] = 'att';
             $incomplete = empty($params['to']);
             break;
     }
     $services = array();
     if (!empty($params['to'])) {
         if (!empty($params['from']) || !empty($params['type'])) {
             if ($result = $this->request('ems.calculate', $params)) {
                 $est_delivery = '';
                 $time = array('min' => sprintf('+%d day', ifset($result['term']['min'], 7)), 'max' => sprintf('+%d day', ifset($result['term']['max'], 14)));
                 $est_delivery .= waDateTime::format('humandate', strtotime($time['min']));
                 $est_delivery .= ' — ';
                 $est_delivery .= waDateTime::format('humandate', strtotime($time['max']));
                 $rate = doubleval(ifset($result['price'], 0));
                 if (doubleval($this->surcharge) > 0) {
                     $rate += $this->getTotalPrice() * doubleval($this->surcharge) / 100.0;
                 }
                 $services['main'] = array('rate' => $rate, 'currency' => 'RUB', 'est_delivery' => $est_delivery);
             } else {
                 $services = 'Ошибка расчета стоимости доставки в указанные город и регион.';
             }
         } else {
             $services = 'Адрес отправителя не указан в настройках способа доставки «EMS Почта России».';
         }
     } elseif ($incomplete) {
         $services = array();
     } else {
         $services = 'Ошибка расчета стоимости доставки в указанные город и регион.';
     }
     return $services;
 }
コード例 #4
0
 /**
  * Main shipping rate calculation method.
  * Returns array of estimated shipping rates and transit times.
  * or error message to be displayed to customer,
  * or false, if this shipping option must not be available under certain conditions.
  * 
  * @example <pre>
  * //return array of shipping options
  * return array(
  *     'option_id_1' => array(
  *          'name'         => $this->_w('...'),
  *          'description'  => $this->_w('...'),
  *          'est_delivery' => '...',
  *          'currency'     => $this->currency,
  *          'rate'         => $this->cost,
  *      ),
  *      ...
  * );
  * 
  * //return error message
  * return 'Для расчета стоимости доставки укажите регион доставки';
  * 
  * //shipping option is unavailable
  * return false;</pre>
  *
  * Useful parent class (waShipping) methods to be used in calculate() method:
  * 
  *     <pre>
  *     // total package price
  *     $price = $this->getTotalPrice();
  *     
  *     // total package weight
  *     $weight = $this->getTotalWeight();
  *     
  *     // order items array
  *     $items = $this->getItems();
  *     
  *     // obtain either full address info array or specified address field value
  *     $address = $this->getAddress($field = null);</pre>
  *     
  * @return mixed
  */
 public function calculate()
 {
     if ($this->delivery === '') {
         $est_delivery = null;
     } else {
         $est_delivery = waDateTime::format('humandate', strtotime($this->delivery));
     }
     return array('ground' => array('name' => $this->_w('Ground shipping'), 'description' => '', 'est_delivery' => $est_delivery, 'currency' => $this->currency, 'rate' => $this->cost));
 }
コード例 #5
0
 /**
  * Main shipping rate calculation method.
  * Returns array of estimated shipping rates and transit times.
  * or error message to be displayed to customer,
  * or false, if this shipping option must not be available under certain conditions.
  *
  * @example <pre>
  * //return array of shipping options
  * return array(
  *     'option_id_1' => array(
  *          'name'         => $this->_w('...'),
  *          'description'  => $this->_w('...'),
  *          'est_delivery' => '...',
  *          'currency'     => $this->currency,
  *          'rate'         => $this->cost,
  *      ),
  *      ...
  * );
  *
  * //return error message
  * return 'Для расчета стоимости доставки укажите регион доставки';
  *
  * //shipping option is unavailable
  * return false;</pre>
  *
  * Useful parent class (waShipping) methods to be used in calculate() method:
  *
  *     <pre>
  *     // total package price
  *     $price = $this->getTotalPrice();
  *
  *     // total package weight
  *     $weight = $this->getTotalWeight();
  *
  *     // order items array
  *     $items = $this->getItems();
  *
  *     // obtain either full address info array or specified address field value
  *     $address = $this->getAddress($field = null);</pre>
  *
  * @return mixed
  */
 protected function calculate()
 {
     if ($this->delivery === '') {
         $est_delivery = null;
     } else {
         $est_delivery = waDateTime::format('humandate', strtotime($this->delivery));
     }
     return array('ground' => array('description' => '', 'est_delivery' => $est_delivery, 'currency' => $this->currency, 'rate' => $this->parseCost($this->cost)));
 }
コード例 #6
0
 /** Add `when` and `who` fields (used in templated) to given item db row. */
 public static function prepareItem($item)
 {
     $item['name'] = htmlspecialchars($item['name']);
     $item['when'] = $item['done'] ? waDateTime::format('humandatetime', $item['done']) : '';
     $item['who'] = '';
     if ($item['contact_id'] && wa()->getUser()->getId() != $item['contact_id']) {
         $c = new waContact($item['contact_id']);
         try {
             $item['who'] = htmlspecialchars($c->getName());
         } catch (Exception $e) {
         }
     }
     return $item;
 }
コード例 #7
0
 /**
  * Core shipping rate calculation method.
  * Returns the list (array) of estimated shipping rates and transit times
  *
  * Useful parent class (waShipping) methods to be used in calculate():
  * $price = $this->getTotalPrice();
  * $weight = $this->getTotalWeight();
  */
 public function calculate()
 {
     /*
     Use following methods to obtain package information:
     
     — $this->getTotalWeight(); // returns overall package weight
     — $this->getTotalPrice(); // returns declared shipment value
     — $this->getRecipientName(); // returns full name of the package recipient
     — $this->getAddress($field = null); // returns either entire address (array) or exact address field, e.g. 'country', 'region', 'city', 'zip', 'street' or any custom defined field
     
     Use $this->VAR_ID to access module settings as defined in the config/settings.php
     */
     return array('ground' => array('name' => $this->_w('Ground shipping'), 'description' => '', 'est_delivery' => waDateTime::format('humandate', strtotime($this->delivery)), 'currency' => $this->currency, 'rate' => $this->cost));
 }
コード例 #8
0
 public function format($data)
 {
     if (is_array($data)) {
         $value =& $data['value'];
     } else {
         $value =& $data;
     }
     if ($value) {
         $value = waDateTime::format('date', $value);
     }
     unset($value);
     // being paranoid
     return $data;
 }
コード例 #9
0
 public function format($data)
 {
     if (is_array($data)) {
         $value =& $data['value'];
     } else {
         $value =& $data;
     }
     if ($value) {
         $format = isset($this->options['format']) ? $this->options['format'] : 'date';
         $value = waDateTime::format($format, $value);
     }
     unset($value);
     // being paranoid
     return $data;
 }
コード例 #10
0
ファイル: logsHelper.class.php プロジェクト: Lazary/webasyst
 public static function getFilesByUpdatetime()
 {
     $root_log_dir = self::getRootLogsDirPath();
     $files = self::listDir($root_log_dir, true);
     $paths = array();
     foreach ($files as $file) {
         $update_time = filemtime($root_log_dir . DIRECTORY_SEPARATOR . $file);
         $paths[] = array('is_file' => true, 'file' => basename($file), 'folder' => strpos($file, '/') === false ? '' : dirname($file) . '/', 'path' => self::normalizePath($file), 'update_time' => $update_time, 'data' => waDateTime::format('humandatetime', $update_time));
     }
     usort($paths, create_function('$a, $b', 'if ($a["update_time"] != $b["update_time"]) {
             return $a["update_time"] < $b["update_time"] ? 1 : -1;
         } else {
             return strcmp($a["path"], $b["path"]);
         }'));
     return $paths;
 }
コード例 #11
0
 /** Using $this->id get waContact and save it in $this->contact;
  * Load vars into $this->view specific to waContact. */
 protected function getContactInfo()
 {
     $system = wa();
     if ($this->id == $system->getUser()->getId()) {
         $this->contact = $system->getUser();
         $this->view->assign('own_profile', TRUE);
     } else {
         $this->contact = new waContact($this->id);
     }
     //
     // Load vars into view
     //
     $this->view->assign('contact', $this->contact);
     // who created this contact and when
     $this->view->assign('contact_create_time', waDateTime::format('datetime', $this->contact['create_datetime'], $system->getUser()->getTimezone()));
     if ($this->contact['create_contact_id']) {
         try {
             $author = new waContact($this->contact['create_contact_id']);
             if ($author['name']) {
                 $this->view->assign('author', $author);
             }
         } catch (Exception $e) {
             // Contact not found. Ignore silently.
         }
     }
     // Info above tabs
     $fields = array('email', 'phone', 'im');
     $top = array();
     foreach ($fields as $f) {
         if ($v = $this->contact->get($f, 'top,html')) {
             $top[] = array('id' => $f, 'name' => waContactFields::get($f)->getName(), 'value' => is_array($v) ? implode(', ', $v) : $v);
         }
     }
     $this->view->assign('top', $top);
     // Main contact editor data
     $fieldValues = $this->contact->load('js', TRUE);
     $contactFields = waContactFields::getInfo($this->contact['is_company'] ? 'company' : 'person', TRUE);
     $this->view->assign('contactFields', $contactFields);
     $this->view->assign('fieldValues', $fieldValues);
     // Contact categories
     $cm = new waContactCategoriesModel();
     $this->view->assign('contact_categories', array_values($cm->getContactCategories($this->id)));
 }
コード例 #12
0
 public function execute()
 {
     $post_id = waRequest::get('id', null, waRequest::TYPE_INT);
     $blog_model = new blogBlogModel();
     $blogs = $blog_model->getAvailable();
     if (!$blogs) {
         $this->setTemplate('BlogNotFound');
         return;
     }
     $blogs = $blog_model->prepareView($blogs);
     if ($post_id) {
         // edit post
         $post_model = new blogPostModel();
         $post = $post_model->getById($post_id);
         if (!$post) {
             throw new waException(_w('Post not found'), 404);
         }
         //check rights
         if (blogHelper::checkRights($post['blog_id']) < blogRightConfig::RIGHT_FULL && $post['contact_id'] != $this->getUser()->getId()) {
             throw new waRightsException(_w('Access denied'));
         }
         $post['datetime'] = $post['datetime'] >= 1971 ? $post['datetime'] : '';
         $blog_id = $post['blog_id'];
         $blog = $blogs[$blog_id];
         $title = trim(sprintf(_w('Editing post %s'), $post['title']));
     } else {
         // add post
         $date = waRequest::get('date', '');
         $blog = $this->getAllowedBlog($blogs, wa()->getStorage()->read('blog_last_id'));
         if (!$blog) {
             throw new waRightsException(_w('Access denied'));
         }
         $blog_id = $blog['id'];
         $post = array('title' => $this->getRequest()->post('title', '', waRequest::TYPE_STRING_TRIM), 'text' => $this->getRequest()->post('text', '', waRequest::TYPE_STRING_TRIM), 'continued_text' => null, 'categories' => array(), 'contact_id' => wa()->getUser()->getId(), 'url' => '', 'blog_id' => $blog_id, 'comments_allowed' => true);
         $post['id'] = '';
         $post['status'] = $date ? blogPostModel::STATUS_DEADLINE : blogPostModel::STATUS_DRAFT;
         $post['datetime'] = $date ? waDateTime::format('date', $date) : '';
         $title = _w('Adding new post');
     }
     $all_links = blogPostModel::getPureUrls($post);
     $post['other_links'] = $all_links;
     $post['link'] = array_shift($post['other_links']);
     $post['remaining_time'] = null;
     if ($post['status'] == blogPostModel::STATUS_SCHEDULED && $post['datetime']) {
         $post['remaining_time'] = $this->calculateRemainingTime($post['datetime']);
     }
     if ($blog['rights'] >= blogRightConfig::RIGHT_FULL) {
         $users = blogHelper::getAuthors($post['blog_id']);
     } else {
         $user = $this->getUser();
         $users = array($user->getId() => $user->getName());
     }
     // preview hash for all type of drafts
     if ($post['status'] != blogPostModel::STATUS_PUBLISHED) {
         $options = array('contact_id' => $post['contact_id'], 'blog_id' => $blog_id, 'post_id' => $post['id'], 'user_id' => wa()->getUser()->getId());
         $preview_hash = blogPostModel::getPreviewHash($options);
         $this->view->assign('preview_hash', base64_encode($preview_hash . $options['user_id']));
     }
     $this->view->assign('no_settlements', empty($all_links) ? true : false);
     $this->view->assign('params', $this->getPostParams($post['id']));
     $this->view->assign('blog', $blog);
     $this->view->assign('users', $users);
     $this->view->assign('blogs', $blogs);
     $allow_change_blog = 0;
     foreach ($blogs as $blog_item) {
         if ($blog_item['rights'] >= blogRightConfig::RIGHT_READ_WRITE) {
             ++$allow_change_blog;
         }
     }
     $this->view->assign('allow_change_blog', $allow_change_blog);
     $this->view->assign('post_id', $post_id);
     $this->view->assign('datetime_timezone', waDateTime::date("T", null, wa()->getUser()->getTimezone()));
     /**
      * Backend post edit page
      * UI hook allow extends post edit page
      * @event backend_post_edit
      * @param array[string]mixed $post
      * @param array[string]int $post['id']
      * @param  array[string]int $post['blog_id']
      * @return array[string][string]string $return[%plugin_id%] Array plugin's html output
      * @return array[string][string]string $return[%plugin_id%]['sidebar'] Plugin sidebar html output
      * @return array[string][string]string $return[%plugin_id%]['toolbar'] Plugin toolbar html output
      */
     $this->view->assign('backend_post_edit', wa()->event('backend_post_edit', $post));
     $app_settings = new waAppSettingsModel();
     $show_comments = $app_settings->get($this->getApp(), 'show_comments', true);
     $this->view->assign('show_comments', $show_comments);
     $this->view->assign('post', $post);
     $locale = $this->getUser()->getLocale();
     $this->setLayout(new blogDefaultLayout());
     $this->getResponse()->setTitle($title);
 }
コード例 #13
0
 /** Using $this->id get waContact and save it in $this->contact;
  * Load vars into $this->view specific to waContact. */
 protected function getContactInfo()
 {
     $system = wa();
     if ($this->id == $system->getUser()->getId()) {
         $this->contact = $system->getUser();
         $this->view->assign('own_profile', true);
     } else {
         $this->contact = new waContact($this->id);
         $this->view->assign('own_profile', false);
     }
     $exists = $this->contact->exists();
     if ($exists) {
         $this->view->assign('contact', $this->contact);
         // who created this contact and when
         $this->view->assign('contact_create_time', waDateTime::format('datetime', $this->contact['create_datetime'], $system->getUser()->getTimezone()));
         if ($this->contact['create_contact_id']) {
             try {
                 $author = new waContact($this->contact['create_contact_id']);
                 if ($author['name']) {
                     $this->view->assign('author', $author);
                 }
             } catch (Exception $e) {
                 // Contact not found. Ignore silently.
             }
         }
         $this->view->assign('top', $this->contact->getTopFields());
         // Main contact editor data
         $fieldValues = $this->contact->load('js', true);
         $m = new waContactModel();
         if (isset($fieldValues['company_contact_id'])) {
             if (!$m->getById($fieldValues['company_contact_id'])) {
                 $fieldValues['company_contact_id'] = 0;
                 $this->contact->save(array('company_contact_id' => 0));
             }
         }
         $contactFields = waContactFields::getInfo($this->contact['is_company'] ? 'company' : 'person', true);
         // Only show fields that are allowed in own profile
         if (!empty($this->params['limited_own_profile'])) {
             $allowed = array();
             foreach (waContactFields::getAll('person') as $f) {
                 if ($f->getParameter('allow_self_edit')) {
                     $allowed[$f->getId()] = true;
                 }
             }
             $fieldValues = array_intersect_key($fieldValues, $allowed);
             $contactFields = array_intersect_key($contactFields, $allowed);
         }
         contactsHelper::normalzieContactFieldValues($fieldValues, $contactFields);
         $this->view->assign('contactFields', $contactFields);
         $this->view->assign('contactFieldsOrder', array_keys($contactFields));
         $this->view->assign('fieldValues', $fieldValues);
         // Contact categories
         $cm = new waContactCategoriesModel();
         $this->view->assign('contact_categories', array_values($cm->getContactCategories($this->id)));
     } else {
         $this->view->assign('contact', array('id' => $this->id));
     }
     return $exists;
 }
コード例 #14
0
 public function editPublicAction()
 {
     if (!wa()->getUser()->isAdmin('webasyst')) {
         throw new waException('Access denied', 403);
     }
     $dashboard_id = waRequest::request('dashboard_id', 0, 'int');
     $dashboard_model = new waDashboardModel();
     $dashboard = $dashboard_model->getById($dashboard_id);
     if (!$dashboard) {
         throw new waException(_w('Not found'), 404);
     }
     // fetch widgets
     $widgets = array();
     $widget_model = new waWidgetModel();
     $rows = $widget_model->getByDashboard($dashboard_id);
     foreach ($rows as $row) {
         $app_widgets = wa($row['app_id'])->getConfig()->getWidgets();
         if (isset($app_widgets[$row['widget']])) {
             $row['size'] = explode('x', $row['size']);
             $row = $row + $app_widgets[$row['widget']];
             $row['href'] = wa()->getAppUrl($row['app_id']) . "?widget={$row['widget']}&id={$row['id']}";
             foreach ($row['sizes'] as $s) {
                 if ($s == array(1, 1)) {
                     $row['has_sizes']['small'] = true;
                 } elseif ($s == array(2, 1)) {
                     $row['has_sizes']['medium'] = true;
                 } elseif ($s == array(2, 2)) {
                     $row['has_sizes']['big'] = true;
                 }
             }
             $widgets[$row['block']][] = $row;
         }
     }
     $dashboard_url = wa()->getConfig()->getRootUrl(true) . wa()->getConfig()->getBackendUrl(false);
     $dashboard_url .= "/dashboard/{$dashboard['hash']}/";
     $this->display(array('dashboard' => $dashboard, 'dashboard_url' => $dashboard_url, 'header_date' => _ws(waDateTime::date('l')) . ', ' . trim(str_replace(date('Y'), '', waDateTime::format('humandate')), ' ,/'), 'widgets' => $widgets));
 }
コード例 #15
0
 public function execute()
 {
     $id = waRequest::post('id', 0, waRequest::TYPE_INT);
     $in_stack = waRequest::post('in_stack', 0, waRequest::TYPE_INT);
     $hash = waRequest::post('hash', null, waRequest::TYPE_STRING_TRIM);
     $hash = urldecode($hash);
     // get photo
     $this->photo_model = new photosPhotoModel();
     $this->photo = $this->photo_model->getById($id);
     if (!$this->photo) {
         throw new waException(_w("Photo doesn't exists"), 404);
     }
     $photo_rights_model = new photosPhotoRightsModel();
     if (!$photo_rights_model->checkRights($this->photo)) {
         throw new waRightsException(_w("You don't have sufficient access rights"));
     }
     $this->photo['name_not_escaped'] = $this->photo['name'];
     $this->photo = photosPhoto::escapeFields($this->photo);
     $this->photo['upload_datetime_formatted'] = waDateTime::format('humandate', $this->photo['upload_datetime']);
     $this->photo['upload_timestamp'] = strtotime($this->photo['upload_datetime']);
     $this->photo['edit_rights'] = $photo_rights_model->checkRights($this->photo, true);
     $this->photo['private_url'] = photosPhotoModel::getPrivateUrl($this->photo);
     $this->photo['thumb'] = photosPhoto::getThumbInfo($this->photo, photosPhoto::getThumbPhotoSize());
     $this->photo['thumb_big'] = photosPhoto::getThumbInfo($this->photo, photosPhoto::getBigPhotoSize());
     $this->photo['thumb_middle'] = photosPhoto::getThumbInfo($this->photo, photosPhoto::getMiddlePhotoSize());
     $original_photo_path = photosPhoto::getOriginalPhotoPath($this->photo);
     if (wa('photos')->getConfig()->getOption('save_original') && file_exists($original_photo_path)) {
         $this->photo['original_exists'] = true;
     } else {
         $this->photo['original_exists'] = false;
     }
     $photo_tags_model = new photosPhotoTagsModel();
     $tags = $photo_tags_model->getTags($id);
     $this->photo['tags'] = $tags;
     $this->response['photo'] = $this->photo;
     // get stack if it's possible
     if (!$in_stack && ($stack = $this->photo_model->getStack($id, array('thumb' => true, 'thumb_crop' => true, 'thumb_big' => true, 'thumb_middle' => true)))) {
         $this->response['stack'] = $stack;
     }
     // get albums
     $album_photos_model = new photosAlbumPhotosModel();
     $albums = $album_photos_model->getAlbums($id, array('id', 'name'));
     $this->response['albums'] = isset($albums[$id]) ? array_values($albums[$id]) : array();
     // exif info
     $exif_model = new photosPhotoExifModel();
     $exif = $exif_model->getByPhoto($this->photo['id']);
     if (isset($exif['DateTimeOriginal'])) {
         $exif['DateTimeOriginal'] = waDateTime::format('humandatetime', $exif['DateTimeOriginal'], date_default_timezone_get());
     }
     $this->response['exif'] = $exif;
     // get author
     $contact = new waContact($this->photo['contact_id']);
     $this->response['author'] = array('id' => $contact['id'], 'name' => photosPhoto::escape($contact['name']), 'photo_url' => $contact->getPhoto(photosPhoto::AUTHOR_PHOTO_SIZE), 'backend_url' => $this->getConfig()->getBackendUrl(true) . 'contacts/#/contact/' . $contact['id']);
     // for making inline-editable widget
     $this->response['frontend_link_template'] = photosFrontendPhoto::getLink(array('url' => '%url%'));
     $hooks = array();
     $parent_id = $this->photo_model->getStackParentId($this->photo);
     $photo_id = $parent_id ? $parent_id : $id;
     /**
      * Extend photo page
      * Add extra widget(s)
      * @event backend_photo
      * @return array[string][string]string $return[%plugin_id%]['bottom'] In bottom, under photo any widget
      */
     $hooks['backend_photo'] = wa()->event('backend_photo', $photo_id);
     $this->response['hooks'] = $hooks;
     if ($hash !== null) {
         $collection = new photosCollection($hash);
         if (strstr($hash, 'rate>0') !== false) {
             $collection->orderBy('p.rate DESC, p.id');
         }
         $this->response['photo_stream'] = $this->getPhotoStream($collection);
         if ($collection->getAlbum()) {
             $this->response['album'] = $collection->getAlbum();
         }
     }
 }
コード例 #16
0
 public function getAuthorInfo($author)
 {
     $wa_app_url = wa()->getAppUrl(null, false);
     $datetime = waDateTime::format('humandatetime', $author['photo_upload_datetime']);
     $html = '<a href="' . $wa_app_url . 'author/' . $author['id'] . '/">' . photosPhoto::escape($author['name']) . '</a> ' . _w('on') . ' ' . $datetime;
     return $html;
 }
コード例 #17
0
 /**
  * Основной метод расчета стоимости доставки.
  * Возвращает массив предварительно рассчитанной стоимости и сроков доступных вариантов доставки,
  * либо сообщение об ошибке для отображения покупателю,
  * либо false, если способ доставки в текущих условиях не дложен быть доступен.
  * 
  * 
  * @example <pre>
  * //возврат массива вариантов доставки
  * return array(
  *     'option_id_1' => array(
  *          'name'         => $this->_w('...'),
  *          'description'  => $this->_w('...'),
  *          'est_delivery' => '...',
  *          'currency'     => $this->currency,
  *          'rate'         => $this->cost,
  *      ),
  *      ...
  * );
  * 
  * //сообщение об ошибке
  * return 'Для расчета стоимости доставки укажите регион доставки';
  * 
  * //способ доставки недоступен
  * return false;</pre>
  *
  * Полезные методы базового класса (waShipping), которые можно использовать в коде метода calculate():
  * 
  *     <pre>
  *     // суммарная стоимость отправления
  *     $price = $this->getTotalPrice();
  *     
  *     // суммарный вес отправления
  *     $weight = $this->getTotalWeight();
  *     
  *     // массив с информацией о заказанных товарах
  *     $items = $this->getItems();
  *     
  *     // массив с полной информацией об адресе получателя либо значение указанного поля адреса
  *     $address = $this->getAddress($field = null);
  *     </pre>
  * 
  * @return mixed
  */
 public function calculate()
 {
     $weight = $this->getTotalWeight();
     if ($weight > $this->max_weight) {
         $services = sprintf("Вес отправления (%0.2f) превышает максимально допустимый (%0.2f)", $weight, $this->max_weight);
     } else {
         $region_id = $this->getAddress('region');
         if ($region_id) {
             if (!empty($this->region[$region_id]) && !empty($this->region[$region_id]['zone'])) {
                 $services = array();
                 $delivery_date = waDateTime::format('humandate', strtotime('+1 week')) . ' — ' . waDateTime::format('humandate', strtotime('+2 week'));
                 $rate = $this->getZoneRates($weight, $this->getTotalPrice(), $this->region[$region_id]['zone']);
                 if (empty($this->region[$region_id]['avia_only'])) {
                     $services['ground'] = array('name' => 'Наземный транспорт', 'id' => 'ground', 'est_delivery' => $delivery_date, 'rate' => $rate['ground'], 'currency' => 'RUB');
                 }
                 $services['avia'] = array('name' => 'Авиа', 'id' => 'avia', 'est_delivery' => $delivery_date, 'rate' => $rate['air'], 'currency' => 'RUB');
             } else {
                 $services = false;
             }
         } else {
             $services = 'Для расчета стоимости доставки укажите регион доставки';
         }
     }
     return $services;
 }
コード例 #18
0
 public function calculate()
 {
     $prices = array();
     $price = null;
     $limit = $this->getPackageProperty($this->rate_by);
     $rates = $this->rate;
     if (!$rates) {
         $rates = array();
     }
     self::sortRates($rates);
     $rates = array_reverse($rates);
     foreach ($rates as $rate) {
         $rate = array_map('floatval', $rate);
         if ($limit !== null && $rate['limit'] < $limit && $price === null) {
             $price = $rate['cost'];
         }
         $prices[] = $rate['cost'];
     }
     if ($this->delivery_time) {
         $delivery_date = array_map('strtotime', explode(',', $this->delivery_time, 2));
         foreach ($delivery_date as &$date) {
             $date = waDateTime::format('humandate', $date);
         }
         unset($date);
         $delivery_date = implode(' —', $delivery_date);
     } else {
         $delivery_date = null;
     }
     return array('delivery' => array('est_delivery' => $delivery_date, 'currency' => $this->currency, 'rate' => $limit === null ? $prices ? array(min($prices), max($prices)) : null : $price));
 }
コード例 #19
0
ファイル: waContact.class.php プロジェクト: Lazary/webasyst
 /**
  * Returns current data and time relative to contact's locale and time zone configuration.
  *
  * @return string
  */
 public function getTime()
 {
     return waDateTime::format("datetime", null, $this->get('timezone'), $this->getLocale());
 }
コード例 #20
0
 private function save($post)
 {
     $options = array();
     if (waRequest::post('transliterate', null)) {
         $options['transliterate'] = true;
     }
     $this->validate_messages = $this->post_model->validate($post, $options);
     if ($this->validate_messages) {
         $this->errors = $this->validate_messages;
     } else {
         $post['text_before_cut'] = null;
         $post['cut_link_label'] = null;
         $template = '<!--[\\s]*?more[\\s]*?(text[\\s]*?=[\\s]*?[\'"]([\\s\\S]*?)[\'"])*[\\s]*?-->';
         $descriptor = preg_split("/{$template}/", $post['text'], 2, PREG_SPLIT_DELIM_CAPTURE);
         if ($descriptor) {
             if (count($descriptor) == 2) {
                 $post['text_before_cut'] = blogPost::closeTags($descriptor[0]);
             } elseif (count($descriptor) > 2) {
                 $post['text_before_cut'] = blogPost::closeTags($descriptor[0]);
                 if (isset($descriptor[2])) {
                     $post['cut_link_label'] = $descriptor[2];
                 }
             }
         }
         if ($post['id']) {
             $prev_post = $this->post_model->getFieldsById($post['id'], 'status');
             if ($prev_post['status'] != blogPostModel::STATUS_PUBLISHED && $post['status'] == blogPostModel::STATUS_PUBLISHED) {
                 $this->inline = false;
             }
             $this->post_model->updateItem($post['id'], $post);
             if ($prev_post['status'] != blogPostModel::STATUS_PUBLISHED && $post['status'] == blogPostModel::STATUS_PUBLISHED) {
                 $this->log('post_publish', 1);
             } else {
                 $this->log('post_edit', 1);
             }
         } else {
             $post['id'] = $this->post_model->updateItem(null, $post);
             $this->log('post_publish', 1);
         }
         $this->saveParams($post['id']);
         $this->clearViewCache($post['id'], $post['url']);
         if (!$this->inline) {
             if ($post['status'] != blogPostModel::STATUS_PUBLISHED) {
                 $params = array('module' => 'post', 'action' => 'edit', 'id' => $post['id']);
             } elseif ($post['blog_status'] == blogBlogModel::STATUS_PUBLIC) {
                 $params = array('blog' => $post['blog_id']);
             } else {
                 $params = array('module' => 'post', 'id' => $post['id']);
             }
             $this->response['redirect'] = $this->getRedirectUrl($params);
         } else {
             $this->response['formatted_datetime'] = waDateTime::format('humandatetime', $post['datetime']);
             $this->response['id'] = $post['id'];
             $this->response['url'] = $post['url'];
             if ($post['status'] != blogPostModel::STATUS_PUBLISHED) {
                 $options = array('contact_id' => $post['contact_id'], 'blog_id' => $post['blog_id'], 'post_id' => $post['id'], 'user_id' => wa()->getUser()->getId());
                 $preview_hash = blogPostModel::getPreviewHash($options);
                 $this->response['preview_hash'] = base64_encode($preview_hash . $options['user_id']);
                 $this->response['debug'] = $options;
             }
         }
     }
 }
コード例 #21
0
ファイル: datetime.php プロジェクト: Lazary/webasyst
function wa_date($format, $time = null, $timezone = null, $locale = null)
{
    return waDateTime::format($format, $time, $timezone, $locale);
}
コード例 #22
0
ファイル: view.php プロジェクト: cjmaximal/webasyst-framework
function wa_header()
{
    $system = waSystem::getInstance();
    if ($system->getEnv() == 'frontend') {
        return '';
    }
    $root_url = $system->getRootUrl();
    $backend_url = $system->getConfig()->getBackendUrl(true);
    $user = $system->getUser();
    $apps = $user->getApps();
    $current_app = $system->getApp();
    $app_settings_model = new waAppSettingsModel();
    $apps_html = '';
    $applist_class = '';
    $counts = wa()->getStorage()->read('apps-count');
    if (is_array($counts)) {
        $applist_class .= ' counts-cached';
    }
    foreach ($apps as $app_id => $app) {
        if (isset($app['img'])) {
            $img = '<img ' . (!empty($app['icon'][96]) ? 'data-src2="' . $root_url . $app['icon'][96] . '"' : '') . ' src="' . $root_url . $app['img'] . '" alt="">';
        } else {
            $img = '';
        }
        $count = '';
        $app_url = $backend_url . $app_id . '/';
        if ($counts && isset($counts[$app_id])) {
            if (is_array($counts[$app_id])) {
                $app_url = $counts[$app_id]['url'];
                $n = $counts[$app_id]['count'];
            } else {
                $n = $counts[$app_id];
            }
            if ($n) {
                $count = '<span class="indicator">' . $n . '</span>';
            }
        }
        $apps_html .= '<li id="wa-app-' . $app_id . '"' . ($app_id == $current_app ? ' class="selected"' : '') . '><a href="' . $app_url . '">' . $img . ' ' . $app['name'] . $count . '</a></li>';
    }
    $announcement_model = new waAnnouncementModel();
    $announcements = array();
    if ($current_app != 'webasyst') {
        $data = $announcement_model->getByApps($user->getId(), array_keys($apps), $user['create_datetime']);
        foreach ($data as $row) {
            // show no more than 1 message per application
            if (isset($announcements[$row['app_id']]) && count($announcements[$row['app_id']]) >= 1) {
                continue;
            }
            $announcements[$row['app_id']][] = $row['text'] . ' <span class="hint">' . waDateTime::format('humandatetime', $row['datetime']) . '</span>';
        }
    }
    $announcements_html = '';
    foreach ($announcements as $app_id => $texts) {
        $announcements_html .= '<a href="#" rel="' . $app_id . '" class="wa-announcement-close" title="close">&times;</a><p>';
        $announcements_html .= implode('<br />', $texts);
        $announcements_html .= '</p>';
    }
    if ($announcements_html) {
        $announcements_html = '<div id="wa-announcement">' . $announcements_html . '</div>';
    }
    $logout = _ws('logout');
    $userpic = '<img width="32" height="32" src="' . $user->getPhoto(32) . '" alt="">';
    $username = htmlspecialchars(waContactNameField::formatName($user), ENT_QUOTES, 'utf-8');
    // If the user has access to contacts app then show a link to his profile
    if (wa()->appExists('contacts')) {
        require_once wa()->getConfig()->getAppsPath('contacts', 'lib/models/contactsRights.model.php');
        try {
            $cr = new contactsRightsModel();
        } catch (waDbException $e) {
            wa('contacts');
            $cr = new contactsRightsModel();
        }
        if ($user->getRights('contacts', 'backend') && $cr->getRight(null, $user['id'])) {
            $userpic = '<a href="' . $backend_url . 'contacts/#/contact/' . $user['id'] . '">' . $userpic . '</a>';
            $username = '******' . $backend_url . 'contacts/#/contact/' . $user['id'] . '" id="wa-my-username">' . $username . '</a>';
        } else {
            $userpic = '<a href="' . $backend_url . '?module=profile">' . $userpic . '</a>';
            $username = '******' . $backend_url . '?module=profile" id="wa-my-username">' . $username . '</a>';
        }
    }
    $more = _ws('more');
    if ($applist_class) {
        $applist_class = ' class="' . trim($applist_class) . '"';
    }
    $company_name = htmlspecialchars($app_settings_model->get('webasyst', 'name', 'Webasyst'), ENT_QUOTES, 'utf-8');
    $company_url = $app_settings_model->get('webasyst', 'url', $system->getRootUrl(true));
    $version = wa()->getVersion();
    $strings = array('customize' => _ws('Customize dashboard'), 'done' => _ws('Done editing'), 'date' => _ws(waDateTime::date('l')) . ', ' . trim(str_replace(date('Y'), '', waDateTime::format('humandate')), ' ,/'));
    $html = <<<HTML
<script type="text/javascript">var backend_url = "{$backend_url}";</script>
{$announcements_html}
<div id="wa-header">
    <div id="wa-account">
HTML;
    if (wa()->getApp() == 'webasyst') {
        $html .= <<<HTML
        <h3>{$company_name} <a href="{$company_url}" class="wa-frontend-link" target="_blank"><i class="icon16 new-window"></i></a></h3>
        <a class="inline-link" id="show-dashboard-editable-mode" href="{$backend_url}"><b><i>{$strings['customize']}</i></b></a>
        <input id="close-dashboard-editable-mode" type="button" value="{$strings['done']}" style="display: none;">
HTML;
    } else {
        $html .= <<<HTML
        <a href="{$backend_url}" class="wa-dashboard-link"><h3>{$company_name}</h3>
        <span class="gray">{$strings['date']}</span></a>
HTML;
    }
    $html .= <<<HTML
    </div>
    <div id="wa-usercorner">
        <div class="profile image32px">
            <div class="image">
                {$userpic}
            </div>
            <div class="details">
                {$username}
                <p class="status"></p>
                <a class="hint" href="{$backend_url}?action=logout">{$logout}</a>
            </div>
        </div>
    </div>
    <div id="wa-applist" {$applist_class}>
        <ul>
            {$apps_html}
            <li>
                <a href="#" id="wa-moreapps"></a>
            </li>
        </ul>
HTML;
    if (wa()->getApp() == 'webasyst') {
        $html .= '<div class="d-dashboard-header-content">
            <div class="d-dashboards-list-wrapper" id="d-dashboards-list-wrapper"></div>
            <div class="d-dashboard-link-wrapper" id="d-dashboard-link-wrapper"><i class="icon10 lock-bw"></i> ' . _w('Only you can see this dashboard.') . '</div>
        </div>';
    }
    $html .= <<<HTML
    </div>
</div>
<script id="wa-header-js" type="text/javascript" src="{$root_url}wa-content/js/jquery-wa/wa.header.js?v{$version}"></script>
HTML;
    return $html;
}
コード例 #23
0
ファイル: view.php プロジェクト: navi8602/wa-shop-ppg
function wa_header()
{
    $system = waSystem::getInstance();
    if ($system->getEnv() == 'frontend') {
        return '';
    }
    $root_url = $system->getRootUrl();
    $backend_url = $system->getConfig()->getBackendUrl(true);
    $user = $system->getUser();
    $apps = $user->getApps();
    $current_app = $system->getApp();
    $app_settings_model = new waAppSettingsModel();
    $apps_html = '';
    $applist_class = '';
    $counts = wa()->getStorage()->read('apps-count');
    if (is_array($counts)) {
        $applist_class .= ' counts-cached';
    }
    foreach ($apps as $app_id => $app) {
        if (isset($app['img'])) {
            $img = '<img src="' . $root_url . $app['img'] . '" alt="">';
        } else {
            $img = '';
        }
        $count = '';
        $app_url = $backend_url . $app_id . '/';
        if ($counts && isset($counts[$app_id])) {
            if (is_array($counts[$app_id])) {
                $app_url = $counts[$app_id]['url'];
                $n = $counts[$app_id]['count'];
            } else {
                $n = $counts[$app_id];
            }
            if ($n) {
                $count = '<span class="indicator">' . $n . '</span>';
            }
        }
        $apps_html .= '<li id="wa-app-' . $app_id . '"' . ($app_id == $current_app ? ' class="selected"' : '') . '><a href="' . $app_url . '">' . $img . ' ' . $app['name'] . $count . '</a></li>';
    }
    if ($system->getRequest()->isMobile(false)) {
        $top_url = '<a href="' . $backend_url . '?mobile=1">mobile version</a>';
    } else {
        $url = $app_settings_model->get('webasyst', 'url', $system->getRootUrl(true));
        $url_info = @parse_url($url);
        if ($url_info) {
            $url_name = '';
            if (empty($url_info['scheme'])) {
                $url = 'http://' . $url;
            }
            if (!empty($url_info['scheme']) && $url_info['scheme'] != 'http') {
                $url_name = $url_info['scheme'] . '://';
            }
            if (isset($url_info['host'])) {
                $url_name .= $url_info['host'];
            }
            if (isset($url_info['path'])) {
                if ($url_info['path'] == '/' && !isset($url_info['query'])) {
                } else {
                    $url_name .= $url_info['path'];
                }
            }
            if (isset($url_info['query'])) {
                $url_name .= '?' . $url_info['query'];
            }
        } else {
            $url = $url_name = $system->getRootUrl(true);
        }
        $top_url = '<a target="_blank" href="' . $url . '">' . $url_name . '</a>';
    }
    $announcement_model = new waAnnouncementModel();
    $data = $announcement_model->getByApps($user->getId(), array_keys($apps), $user['create_datetime']);
    $announcements = array();
    foreach ($data as $row) {
        // show no more than 1 message per application
        if (isset($announcements[$row['app_id']]) && count($announcements[$row['app_id']]) >= 1) {
            continue;
        }
        $announcements[$row['app_id']][] = waDateTime::format('datetime', $row['datetime']) . ': ' . $row['text'];
    }
    $announcements_html = '';
    foreach ($announcements as $app_id => $texts) {
        $announcements_html .= '<a href="#" rel="' . $app_id . '" class="wa-announcement-close" title="close">' . _ws('[close]') . '</a><p>';
        $announcements_html .= implode('<br />', $texts);
        $announcements_html .= '</p>';
    }
    if ($announcements_html) {
        $announcements_html = '<div id="wa-announcement">' . $announcements_html . '</div>';
    }
    $logout = _ws('logout');
    $userpic = '<img width="32" height="32" src="' . $user->getPhoto(32) . '" alt="">';
    $username = htmlspecialchars($user['name'], ENT_QUOTES, 'utf-8');
    // If the user has access to contacts app then show a link to his profile
    if (wa()->getUser()->getRights('contacts', 'backend')) {
        $userpic = '<a href="' . $backend_url . 'contacts/#/contact/' . $user['id'] . '">' . $userpic . '</a>';
        $username = '******' . $backend_url . 'contacts/#/contact/' . $user['id'] . '" id="wa-my-username">' . $username . '</a>';
    }
    $more = _ws('more');
    if ($applist_class) {
        $applist_class = ' class="' . trim($applist_class) . '"';
    }
    $company_name = htmlspecialchars($app_settings_model->get('webasyst', 'name', 'Webasyst'), ENT_QUOTES, 'utf-8');
    $version = wa()->getVersion();
    $html = <<<HTML
<script type="text/javascript">var backend_url = "{$backend_url}";</script>
{$announcements_html}
<div id="wa-header">
    <div id="wa-account">
        <h3>{$company_name}</h3>
        {$top_url}
    </div>
    <div id="wa-usercorner">
        <div class="profile image32px">
            <div class="image">
                {$userpic}
            </div>
            <div class="details">
                {$username}
                <p class="status"></p>
                <a class="hint" href="{$backend_url}?action=logout">{$logout}</a>
            </div>
        </div>
    </div>
    <div id="wa-applist" {$applist_class}>
        <ul>
            {$apps_html}
            <li>
                <a href="#" class="inline-link" id="wa-moreapps"><i class="icon10 darr" id="wa-moreapps-arrow"></i><b><i>{$more}</i></b></a>
            </li>
        </ul>
    </div>
</div>
<script id="wa-header-js" type="text/javascript" src="{$root_url}wa-content/js/jquery-wa/wa.header.js?v{$version}"></script>
HTML;
    return $html;
}