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; }
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; }
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; }
/** * 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))); }
/** * 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)); }
public function create($name, $background_id = null, $checkRights = true) { $app_id = wa()->getApp(); if ($checkRights && !wa()->getUser()->getRights($app_id, 'add_sheet')) { throw new waRightsException(_w('Not enough rights to add new board')); } $sheet = $this->select('MAX(sort) as max_sort')->fetch(); $data = array('name' => $name, 'sort' => $sheet['max_sort'] + 1, 'background_id' => $background_id, 'creator_contact_id' => wa()->getUser()->getId(), 'create_datetime' => waDateTime::date('Y-m-d H:i:s'), 'qty' => 0); if ($id = $this->insert($data)) { wa()->getUser()->setRight($app_id, sprintf('sheet.%d', $id), true); } return $id; }
/** * 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)); }
/** 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; }
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; }
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; }
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; }
public function execute() { $data = waRequest::post('data', null); if (!$data) { return; } foreach ($data as $name => $value) { if (in_array($name, $this->allowed_fields) === false) { throw new waException("Can't update post: editing of this field is denied"); } if ($name == 'status') { if (in_array($value, array(blogPostModel::STATUS_DRAFT, blogPostModel::STATUS_DEADLINE, blogPostModel::STATUS_SCHEDULED, blogPostModel::STATUS_PUBLISHED)) === false) { throw new waException("Can't change status: unknown value"); } } } $post_id = waRequest::post('post_id', null, waRequest::TYPE_INT); $post_model = new blogPostModel(); $post = null; if ($post_id) { $post = $post_model->getFieldsById($post_id, array('id', 'blog_id', 'contact_id', 'datetime')); } if (!$post) { throw new waException("Unknown post"); } $contact = wa()->getUser(); $contact_id = $contact->getId(); $allow = blogHelper::checkRights($post['blog_id'], $contact_id, $contact_id != $post['contact_id'] ? blogRightConfig::RIGHT_FULL : blogRightConfig::RIGHT_READ_WRITE); if (!$allow) { throw new waException("Access denied"); } if (!$post_model->updateById($post_id, $data)) { throw new waException("Error when updating data"); } $post = array_merge($post, $data); if ($post['status'] == blogPostModel::STATUS_DEADLINE) { $user = wa()->getUser(); $timezone = $user->getTimezone(); $current_datetime = waDateTime::date("Y-m-d", null, $timezone); $datetime = waDateTime::date("Y-m-d", $post['datetime'], $timezone); if ($datetime <= $current_datetime) { $post['overdue'] = true; } } $this->response['post'] = $post; }
public function getTimeOffset() { $source = $this->getSettings('source'); $offset = 0; if ($source == "server") { $user_timezone = wa()->getUser()->get('timezone'); $timezone_offset = intval(waDateTime::date('Z', null, $user_timezone, null)); // in second $offset = $timezone_offset * 1000; } else { if ($source == "local") { $offset = 0; } else { $offset = $source ? $source : 0; } } return $offset; }
/** Using $this->id get waContact and save it in $this->contact; * Load vars into $this->view specific to waContact. */ protected function getContactInfo() { $system = wa(); if ($this->id == $system->getUser()->getId()) { $this->contact = $system->getUser(); $this->view->assign('own_profile', TRUE); } else { $this->contact = new waContact($this->id); } // // Load vars into view // $this->view->assign('contact', $this->contact); // who created this contact and when $this->view->assign('contact_create_time', waDateTime::format('datetime', $this->contact['create_datetime'], $system->getUser()->getTimezone())); if ($this->contact['create_contact_id']) { try { $author = new waContact($this->contact['create_contact_id']); if ($author['name']) { $this->view->assign('author', $author); } } catch (Exception $e) { // Contact not found. Ignore silently. } } // Info above tabs $fields = array('email', 'phone', 'im'); $top = array(); foreach ($fields as $f) { if ($v = $this->contact->get($f, 'top,html')) { $top[] = array('id' => $f, 'name' => waContactFields::get($f)->getName(), 'value' => is_array($v) ? implode(', ', $v) : $v); } } $this->view->assign('top', $top); // Main contact editor data $fieldValues = $this->contact->load('js', TRUE); $contactFields = waContactFields::getInfo($this->contact['is_company'] ? 'company' : 'person', TRUE); $this->view->assign('contactFields', $contactFields); $this->view->assign('fieldValues', $fieldValues); // Contact categories $cm = new waContactCategoriesModel(); $this->view->assign('contact_categories', array_values($cm->getContactCategories($this->id))); }
public function modify($id, $options = array()) { $sheet_id = $this->available($id); $default_data = array('update_datetime' => waDateTime::date('Y-m-d H:i:s')); $update_count = false; if (isset($options['sheet_id']) && $options['sheet_id'] != $sheet_id) { self::availableSheet($options['sheet_id']); $update_count = true; } $res = $this->updateByField(array('id' => $id, 'sheet_id' => $sheet_id), array_merge($options, $default_data), null, true); if ($update_count) { $sheet = new stickiesSheetModel(); $sheet->refresh($sheet_id, $this->countByField('sheet_id', $sheet_id)); $sheet->refresh($options['sheet_id'], $this->countByField('sheet_id', $options['sheet_id'])); } if ($res && $res->affectedRows() >= 0) { return true; } else { return false; } }
public function execute() { $this->getResponse()->addHeader('Content-type', 'application/json'); $post_id = waRequest::post('post_id', null); $date = waRequest::post('date'); if (!is_null($post_id)) { $post_model = new blogPostModel(); $post = $post_model->getFieldsById($post_id, array('status')); $status = $post['status']; if ($status == blogPostModel::STATUS_DEADLINE || $status == blogPostModel::STATUS_DRAFT) { if (strlen($date) == 0) { $this->response['valid'] = true; return; } } } $this->response['valid'] = true; if (!waDateTime::parse('date', $date, wa()->getUser()->getTimezone())) { $this->response['valid'] = false; } }
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; }
public static function extendPostState(&$posts, $mode = false) { $user = wa()->getUser(); $timezone = $user->getTimezone(); $contact_id = $user->getId(); $current_datetime = waDateTime::date("Y-m-d", null, $timezone); $activity_datetime = blogActivity::getUserActivity(); $blog_activity = null; if ('view' === $mode) { $blog_activity = blogActivity::getInstance(); $viewed_ids = array(); } foreach ($posts as &$post) { if ($post['datetime']) { if (in_array($post['status'], array(blogPostModel::STATUS_DEADLINE))) { $datetime = waDateTime::date("Y-m-d", $post['datetime'], $timezone); if ($datetime <= $current_datetime) { $post['overdue'] = true; } } elseif (in_array($post['status'], array(blogPostModel::STATUS_PUBLISHED))) { if ($activity_datetime && $post['datetime'] > $activity_datetime && (!$contact_id || $contact_id != $post['contact_id'])) { if ('view' === $mode) { $post['new'] = $blog_activity->isNew("b.{$post['blog_id']}", $post['id']); if ($post['new'] == blogActivity::STATE_NEW) { if (!isset($viewed_ids[$post['blog_id']])) { $viewed_ids[$post['blog_id']] = array(); } $viewed_ids[$post['blog_id']][] = $post['id']; } elseif (!$post['new']) { unset($post['new']); } } else { $post['new'] = true; } } } } unset($post); } if ($blog_activity && !empty($viewed_ids)) { foreach ($viewed_ids as $blog_id => $post_ids) { $blog_activity->set("b.{$blog_id}", $post_ids); } } }
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; }
public function onCount() { $full = !func_get_args(); $app = $this->getApplication(); $user = waSystem::getInstance()->getUser(); $user_id = $user->getId(); $type = explode(':', $user->getSettings($app, 'type_items_count')); $type = array_filter(array_map('trim', $type), 'strlen'); if (!$type) { $type = array('posts', 'comments_to_my_post', 'overdue'); } $activity_datetime = blogActivity::getUserActivity($user_id, false); $blogs = array_keys(blogHelper::getAvailable(false)); $counter = array(); $post_model = new blogPostModel(); if (in_array('posts', $type) && $full && $blogs) { $post_new_count = $post_model->getAddedPostCount($activity_datetime, $blogs); $post_new_count = array_sum($post_new_count); $counter['posts'] = $post_new_count; } else { $counter['posts'] = false; } if (in_array('comments', $type) && $full && $blogs) { $comment_model = new blogCommentModel(); $counter['comments'] = $comment_model->getCount($blogs, null, $activity_datetime, 0); } else { $counter['comments'] = false; } if (in_array('comments_to_my_post', $type) && $full && $blogs) { $comment_model = new blogCommentModel(); $counter['comments_to_my_post'] = $comment_model->getCount($blogs, null, $activity_datetime, 0, $user_id); } else { $counter['comments_to_my_post'] = false; } if (in_array('overdue', $type) && $blogs) { if (!isset($post_model)) { $post_model = new blogPostModel(); } $where = "status = '" . blogPostModel::STATUS_DEADLINE . "'"; $where .= " AND blog_id IN (" . implode(', ', $blogs) . ")"; $where .= " AND contact_id = {$user_id}"; $where .= " AND datetime <= '" . waDateTime::date("Y-m-d") . "'"; $count_overdue = $post_model->select("count(id)")->where($where)->fetchField(); $counter['overdue'] = $count_overdue ? $count_overdue : 0; } else { $counter['overdue'] = false; } $count = array_sum($counter); $url = $this->getBackendUrl(true) . $this->application . '/'; if ($count) { switch ($count) { case $counter['comments']: case $counter['comments_to_my_post']: $url .= '?module=comments'; break; case $counter['overdue']: $url .= '?action=calendar'; break; } } //debug //$counter['type'] = $type; //$counter['activity_datetime'] = $activity_datetime; //$counter['current_datetime'] = date("Y-m-d H:i:s",time()); //waLog::log('$counter = '.var_export($counter,true),"blog-counter-{$user_id}.log"); return array('count' => $count == 0 ? null : $count, 'url' => $url); }
/** * Validate data * * @param array &$data * @param array $options * * @return array messages or empty array */ public function validate(&$data, $options = array()) { $messages = array(); if ($data['blog_status'] != blogBlogModel::STATUS_PRIVATE) { if (!empty($data['id'])) { $url_validator = new blogSlugValidator(array('id' => $data['id'])); } else { if (!empty($options['transliterate']) && !$data['url']) { if ($data['title']) { $data['url'] = blogHelper::transliterate($data['title']); } else { $data['url'] = $this->genUniqueUrl(''); } } $url_validator = new blogSlugValidator(); } $url_validator->setSubject(blogSlugValidator::SUBJECT_POST); if (!$url_validator->isValid($data['url'])) { $messages['url'] = current($url_validator->getErrors()); if ($url_validator->isError(blogSlugValidator::ERROR_REQUIRED) && ($data['id'] || !$data['id'] && $data['status'] == blogPostModel::STATUS_DRAFT)) { $url = $this->select('url')->where('id = i:id', array('id' => $data['id']))->fetchField('url'); $data['url'] = $url ? $url : $this->genUniqueUrl($data['title']); unset($messages['url']); if (!$url_validator->isValid($data['url'])) { $messages['url'] = current($url_validator->getErrors()); } } elseif (!empty($options['make'])) { $data['url'] = $this->genUniqueUrl($data['url']); unset($messages['url']); if (!$url_validator->isValid($data['url'])) { $messages['url'] = current($url_validator->getErrors()); } } } } else { if (empty($data['id'])) { $data['url'] = $this->genUniqueUrl(empty($data['url']) ? $data['title'] : $data['url']); } else { $url = $this->select('url')->where('id = i:id', array('id' => $data['id']))->fetchField('url'); $data['url'] = $url ? $url : $this->genUniqueUrl($data['title']); } } if (isset($data['datetime']) && !is_null($data['datetime'])) { if (!empty($options['datetime'])) { $formats = (array) $options['datetime']; } elseif (isset($options['datetime'])) { $formats = array(); } elseif (strpos($data['datetime'], ':') !== false) { $formats = array('fulldatetime', 'datetime'); } else { $formats = array('date'); } if ($data['datetime'] != '') { $datetime = $data['datetime']; foreach ($formats as $format) { try { if ($datetime = waDateTime::parse($format, $data['datetime'])) { break; } } catch (Exception $ex) { $messages['datetime'] = _w('Incorrect format'); waLog::log($ex->getMessage()); } } if (preg_match('/^([\\d]{4})\\-([\\d]{1,2})\\-([\\d]{1,2})(\\s|$)/', $datetime, $matches)) { if (!checkdate($matches[2], $matches[3], $matches[1])) { $messages['datetime'] = _w('Incorrect format'); } } $data['datetime'] = $datetime; } else { if ($data['status'] != blogPostModel::STATUS_DRAFT) { $data['datetime'] = false; } } if ($data['datetime'] === false) { $messages['datetime'] = _w('Incorrect format'); } } /** * @event post_validate * @param array [string]mixed $data * @param array ['plugin']['%plugin_id%']mixed plugin data * @return array['%plugin_id%']['field']string error */ $messages['plugin'] = wa()->event('post_validate', $data); if (empty($messages['plugin'])) { unset($messages['plugin']); } return $messages; }
public function execute() { $this->user = $this->getUser(); $blog_id = waRequest::get('blog', null, 'int'); $post_id = waRequest::get('id', null, 'int'); $request = waRequest::get(); $module = waRequest::get('module'); $action = waRequest::get('action'); if (!$action) { $action = waRequest::get('module'); } $view_all_posts = waRequest::get('all', null) !== null || empty($request); $blog_model = new blogBlogModel(); $blogs = $blog_model->getAvailable($this->user, array(), null, array('new' => true, 'expire' => 1, 'link' => false)); $blog_ids = array_keys($blogs); $comment_model = new blogCommentModel(); $comment_count = $comment_model->getCount($blog_ids); $activity_datetime = blogActivity::getUserActivity(); $comment_new_count = $comment_model->getCount($blog_ids, null, $activity_datetime, 1); $post_count = 0; $new_post_count = 0; $writable_blogs = false; foreach ($blogs as $blog) { $post_count += $blog['qty']; if ($blog['rights'] >= blogRightConfig::RIGHT_READ_WRITE) { $writable_blogs = true; } if (isset($blog['new_post']) && $blog['new_post'] > 0) { $new_post_count += $blog['new_post']; } } if ($writable_blogs) { $post_model = new blogPostModel(); $search_options = array('status' => array(blogPostModel::STATUS_DRAFT, blogPostModel::STATUS_DEADLINE, blogPostModel::STATUS_SCHEDULED)); if (!$this->user->isAdmin($this->getApp())) { $search_options['contact_id'] = $this->user->getId(); } $search_options['sort'] = 'overdue'; $drafts = $post_model->search($search_options, array('status' => true, 'link' => false, 'plugin' => false, 'comments' => false), array('blog' => $blogs))->fetchSearchAll(false); $where = "status = '" . blogPostModel::STATUS_DEADLINE . "' AND datetime <= '" . waDateTime::date("Y-m-d") . "'"; if (!$this->getUser()->isAdmin($this->getApp())) { $where .= " AND contact_id = {$this->getUser()->getId()}"; $where .= " AND blog_id IN (" . implode(', ', array_keys($blogs)) . ")"; } $count_overdue = $post_model->select("count(id)")->where($where)->fetchField(); $count_overdue = $count_overdue ? $count_overdue : 0; } else { $drafts = false; $count_overdue = false; } /** * Extend backend sidebar * Add extra sidebar items (menu items, additional sections, system output) * @event backend_sidebar * @example #event handler example * public function sidebarAction() * { * $output = array(); * * #add external link into sidebar menu * $output['menu']='<li> * <a href="http://www.webasyst.com"> * http://www.webasyst.com * </a> * </li>'; * * #add section into sidebar menu * $output['section']=''; * * #add system link into sidebar menu * $output['system']=''; * * return $output; * } * @return array[string][string]string $return[%plugin_id%]['menu'] Single menu items * @return array[string][string]string $return[%plugin_id%]['section'] Sections menu items * @return array[string][string]string $return[%plugin_id%]['system'] Extra menu items */ $this->view->assign('backend_sidebar', wa()->event('backend_sidebar')); $this->view->assign('blog_id', $blog_id); $this->view->assign('blogs', $blogs); $this->view->assign('view_all_posts', $view_all_posts); $this->view->assign('action', $action); $this->view->assign('module', $module); $this->view->assign('post_id', $post_id); $this->view->assign('new_post', waRequest::get('action') == 'edit' && waRequest::get('id') == ''); $this->view->assign('drafts', $drafts); $this->view->assign('comment_count', $comment_count); $this->view->assign('comment_new_count', $comment_new_count); $this->view->assign('post_count', $post_count); $this->view->assign('new_post_count', $new_post_count); $this->view->assign('count_draft_overdue', $count_overdue); $this->view->assign('writable_blogs', $writable_blogs); }
public function format($data) { $prefix = $this->options['prefix']; $date = array(); if ($data['data']['year']) { $value = $data['data']['year']; $date["y"] = $data['data']['year']; } else { // use leap year, for correct formating 29 Febrary $value = date("Y"); while (!date("L", strtotime("{$value}-01-01"))) { $value += 1; } } if ($data['data']['month']) { $value .= "-" . ($data['data']['month'] < 10 ? "0" : "") . $data['data']['month']; $date["f"] = $data['data']['month']; } else { $value .= "-01"; } if ($data['data']['day']) { $value .= "-" . ($data['data']['day'] < 10 ? "0" : "") . $data['data']['day']; $date["j"] = $data['data']['day']; } else { $value .= "-01"; } $format = array(); foreach (explode(" ", waDateTime::getFormat('humandate')) as $p) { $f = strtolower(substr($p, 0, 1)); if (isset($date[$f])) { $format[] = $p; } } $format = implode(" ", $format); $format = preg_replace("/[^yfj]\$/i", "", $format); $date_time = new DateTime($value); // hack to insert month name in lower case if (strpos($format, 'f') !== false) { $format = str_replace('f', '@F@', $format); } $result = $date_time->format($format); // hack to insert localized month name if (strpos($format, 'F') !== false) { $month = $date_time->format('F'); $local = _ws($month, $month, strpos($format, 'j') !== false ? 2 : 1); $result = str_replace(array("@{$month}@", $month), array(mb_strtolower($local), $local), $result); } return $result; }
function wa_parse_date($format, $string, $timezone = null, $locale = null) { return waDateTime::parse($format, $string, $timezone, $locale); }
/** 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; }
/** * 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()); }
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)); }
/** * Основной метод расчета стоимости доставки. * Возвращает массив предварительно рассчитанной стоимости и сроков доступных вариантов доставки, * либо сообщение об ошибке для отображения покупателю, * либо 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; }
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)); }
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">×</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; }