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;
 }
 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;
 }
 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;
     }
 }
Exemple #5
0
 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);
 }
 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));
 }
Exemple #7
0
 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);
         }
     }
 }
 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);
 }
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;
}
 public function execute()
 {
     $this->getResponse()->setTitle(_w('Calendar'));
     $this->setLayout(new blogDefaultLayout());
     $blog_model = new blogBlogModel();
     $post_model = new blogPostModel();
     $blogs = $blog_model->getAvailable($this->getUser());
     $timezone = wa()->getUser()->getTimezone();
     // Y-m-d -> 2011-01-01
     $month_date = waRequest::get("month");
     if (!$month_date) {
         $month_date = waDateTime::date("Y-m", null, $timezone);
     } elseif ($month_date <= "1970" || $month_date >= "2033" || !strtotime($month_date)) {
         $this->redirect("?action=calendar");
     }
     $month_date = strtotime($month_date);
     $days_count = date("t", $month_date);
     // Numeric representation of the day of the week
     $first_day = date("w", $month_date);
     $last_day = date("w", strtotime(date("Y-m-{$days_count}", $month_date)));
     // first day is 'Sunday'
     if (waLocale::getFirstDay() == 7) {
         $first_day += 1;
         $last_day += 1;
     }
     $first_day = $first_day == 0 ? 6 : $first_day - 1;
     $last_day = $last_day == 0 ? 0 : 7 - $last_day;
     $date_start = strtotime("-" . $first_day . " days", $month_date);
     $date_end = strtotime("+" . ($days_count + $last_day) . " days", $month_date);
     $search_options = array();
     $search_options['datetime'] = array(date("Y-m-d", $date_start), date("Y-m-d", $date_end));
     $search_options['blog_id'] = array_keys($blogs);
     $search_options['status'] = false;
     if (!$this->getUser()->isAdmin($this->getApp())) {
         $search_options['contact_id'] = $this->getUser()->getId();
     }
     $extend_options = array('status' => true, 'user' => false, 'rights' => true);
     $posts = $post_model->search($search_options, $extend_options, array('blog' => $blogs))->fetchSearchAll(false);
     $current_date_start = $date_start;
     $days = array();
     do {
         $week = (int) date("W", $current_date_start);
         $day = (int) date("w", $current_date_start);
         if (waLocale::getFirstDay() == 7 && $day == 0) {
             $week = (int) date("W", strtotime("+1 week", $current_date_start));
         }
         if (!isset($days[$week])) {
             $days[$week] = array();
         }
         $days[$week][$day] = array("date" => array('day' => date("j", $current_date_start), 'month' => date("n", $current_date_start), 'date' => date("Y-m-d", $current_date_start)), "posts" => array());
         $current_date_start = strtotime("+1 days", $current_date_start);
     } while ($date_end > $current_date_start);
     foreach ($posts as $post) {
         #post.datetime cast to user timezone
         $week = (int) waDateTime::date("W", $post['datetime'], $timezone);
         $day = (int) waDateTime::date("w", $post['datetime'], $timezone);
         $days[$week][$day]["posts"][] = $post;
     }
     $now_date = waDateTime::date("Y-m-d", null, $timezone);
     $where = '';
     $search = false;
     if ($this->getUser()->isAdmin($this->getApp())) {
         $search = true;
     } else {
         $writeable = array();
         $full = array();
         foreach ($blogs as $id => $blog) {
             if ($blog['rights'] >= blogRightConfig::RIGHT_FULL) {
                 $full[] = $id;
             } elseif ($blog['rights'] >= blogRightConfig::RIGHT_READ_WRITE) {
                 $writeable[] = $id;
             }
         }
         $contact_where = array();
         if ($full) {
             $contact_where[] = "blog_id IN (" . implode(', ', $full) . ")";
         }
         if ($writeable) {
             $contact_where[] .= "contact_id = {$this->getUser()->getId()} AND blog_id IN (" . implode(', ', $writeable) . ")";
         }
         if ($contact_where) {
             $search = true;
             $where .= ' AND ( (' . implode(') OR (', $contact_where) . ' ) )';
         }
     }
     if ($search) {
         $posts_overdue_prev = $post_model->select("COUNT(*) AS 'cnt'")->where("status = '" . blogPostModel::STATUS_DEADLINE . "' AND datetime < '" . date("Y-m-d", $date_start) . "' " . $where)->limit(1)->fetchField('cnt');
         $posts_overdue_next = $post_model->select("COUNT(*) AS 'cnt'")->where("status = '" . blogPostModel::STATUS_DEADLINE . "' AND datetime > '" . date("Y-m-d", $date_end) . "' AND datetime < '" . $now_date . "'" . $where)->limit(1)->fetchField('cnt');
         $prev_overdue = $posts_overdue_prev ? true : false;
         $next_overdue = $posts_overdue_next ? true : false;
     } else {
         $prev_overdue = false;
         $next_overdue = false;
     }
     $months = array(1 => _ws('January'), 2 => _ws('February'), 3 => _ws('March'), 4 => _ws('April'), 5 => _ws('May'), 6 => _ws('June'), 7 => _ws('July'), 8 => _ws('August'), 9 => _ws('September'), 10 => _ws('October'), 11 => _ws('November'), 12 => _ws('December'));
     $current_year = date('Y', $month_date);
     $current_month = date('Y', $month_date);
     $boundaries = $post_model->select("MIN(datetime) as min, MAX(datetime) as max")->fetch();
     if ($boundaries) {
         $years = range(min(date('Y', strtotime($boundaries['min'])), $current_year), max(date('Y', strtotime($boundaries['max'])), $current_year, date('Y')));
     } else {
         $now_year = date('Y');
         $years = range(min($current_year, $now_year), max($current_year, $now_year));
     }
     $this->view->assign("prev_overdue", $prev_overdue);
     $this->view->assign("next_overdue", $next_overdue);
     $this->view->assign("allow_add", $search);
     $this->view->assign("days", $days);
     $this->view->assign("week_first_sunday", waLocale::getFirstDay() == 7);
     $this->view->assign("current_month", date("n", $month_date));
     $this->view->assign("current_year", date("Y", $month_date));
     $this->view->assign("prev_month", date("Y-m", strtotime("-1 month", $month_date)));
     $this->view->assign("next_month", date("Y-m", strtotime("+1 month", $month_date)));
     $this->view->assign("years", $years);
     $this->view->assign("months", $months);
     // cast to user timezone
     $this->view->assign("today", waDateTime::date("j", null, $timezone));
     $this->view->assign("today_month", waDateTime::date("n", null, $timezone));
     $this->nocache();
 }
 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'] = '';
         $post['meta_title'] = null;
         $post['meta_keywords'] = null;
         $post['meta_description'] = null;
         $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%]['sidebar'] Plugin sidebar html output
      * @return array[string][string]string $return[%plugin_id%]['toolbar'] Plugin toolbar html output
      * @return array[string][string]string $return[%plugin_id%]['editor_tab'] Plugin editor tab html output
      */
     $this->view->assign('backend_post_edit', wa()->event('backend_post_edit', $post, array('sidebar', 'toolbar', 'editor_tab')));
     $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);
     /**
      * @deprecated 
      * For backward compatibility reason
      */
     $this->view->assign('cron_schedule_time', waSystem::getSetting('cron_schedule', 0, 'blog'));
     $this->view->assign('last_schedule_cron_time', waSystem::getSetting('last_schedule_cron_time', 0, 'blog'));
     $this->view->assign('cron_command', 'php ' . wa()->getConfig()->getRootPath() . '/cli.php blog schedule');
     $this->setLayout(new blogDefaultLayout());
     $this->getResponse()->setTitle($title);
 }