Example #1
1
 /**
  * displays the topics on a forums
  * @return [type] [description]
  */
 public function action_list()
 {
     //in case performing a search
     if (strlen($search = core::get('search')) >= 3) {
         return $this->action_search($search);
     }
     $this->template->styles = array('css/forums.css' => 'screen');
     $this->template->scripts['footer'][] = 'js/forums.js';
     $forum = new Model_Forum();
     $forum->where('seoname', '=', $this->request->param('forum', NULL))->cached()->limit(1)->find();
     if ($forum->loaded()) {
         //template header
         $this->template->title = $forum->name . ' - ' . __('Forum');
         $this->template->meta_description = $forum->description;
         Breadcrumbs::add(Breadcrumb::factory()->set_title($forum->name));
         //count all topics
         $count = DB::select(array(DB::expr('COUNT("id_post")'), 'count'))->from(array('posts', 'p'))->where('id_post_parent', 'IS', NULL)->where('id_forum', '=', $forum->id_forum)->cached()->execute();
         $count = array_keys($count->as_array('count'));
         $pagination = Pagination::factory(array('view' => 'pagination', 'total_items' => isset($count[0]) ? $count[0] : 0))->route_params(array('controller' => $this->request->controller(), 'action' => $this->request->action(), 'forum' => $this->request->param('forum')));
         $pagination->title($this->template->title);
         //getting all the topic for the forum
         $topics = DB::select('p.*')->select(array(DB::select(DB::expr('COUNT("id_post")'))->from(array('posts', 'pc'))->where('pc.id_post_parent', '=', DB::expr(Database::instance('default')->table_prefix() . 'p.id_post'))->where('pc.id_forum', '=', $forum->id_forum)->where('pc.status', '=', Model_Post::STATUS_ACTIVE)->group_by('pc.id_post_parent'), 'count_replies'))->select(array(DB::select('ps.created')->from(array('posts', 'ps'))->where('ps.id_post', '=', DB::expr(Database::instance('default')->table_prefix() . 'p.id_post'))->or_where('ps.id_post_parent', '=', DB::expr(Database::instance('default')->table_prefix() . 'p.id_post'))->where('ps.id_forum', '=', $forum->id_forum)->where('ps.status', '=', Model_Post::STATUS_ACTIVE)->order_by('ps.created', 'DESC')->limit(1), 'last_message'))->from(array('posts', 'p'))->where('id_post_parent', 'IS', NULL)->where('id_forum', '=', $forum->id_forum)->where('status', '=', Model_Post::STATUS_ACTIVE)->order_by('last_message', 'DESC')->limit($pagination->items_per_page)->offset($pagination->offset)->as_object()->execute();
         $pagination = $pagination->render();
         $this->template->bind('content', $content);
         $this->template->content = View::factory('pages/forum/list', array('topics' => $topics, 'forum' => $forum, 'pagination' => $pagination));
     } else {
         //throw 404
         throw HTTP_Exception::factory(404, __('Page not found'));
     }
 }
Example #2
0
 public function action_home()
 {
     $config = $this->config;
     $limit = \Arr::get($this->config, 'limit');
     $numSymbol = \Arr::get($this->config, 'numeric-symbol');
     $page = $this->routeParam('page') ?: 1;
     $letter = $this->routeParam('letter');
     $letters = $this->getLetters();
     $items = Model_Word::query()->where('published', 1)->order_by(Model_Word::title_property());
     if (!empty($letter)) {
         if ($letter === $numSymbol) {
             $checkLetter = array_map('strval', range(0, 9));
             $items->where(\DB::expr('LOWER(SUBSTR(' . Model_Word::title_property() . ',1,1))'), 'NOT', \DB::expr("REGEXP '[a-z]|[:space:]'"));
         } else {
             $items->where(\DB::expr('LOWER(SUBSTR(' . Model_Word::title_property() . ',1,1))'), $letter);
         }
     }
     $countTotal = $items->count();
     if ($limit) {
         $offset = ($page - 1) * $limit;
         $items->rows_limit($limit)->rows_offset($offset);
     }
     $numPage = ceil($countTotal / $limit);
     $items = $items->get();
     return \View::forge('novius_glossary::front/list', array('letters' => $letters, 'numPages' => $numPage, 'items' => $items, 'count' => $countTotal, 'page' => $page, 'letter' => $letter, 'config' => $config), false);
 }
Example #3
0
 public function action_related()
 {
     $request = $this->request->current();
     $limit = $request->query('limit');
     if (empty($limit)) {
         $limit = $this->default_limit;
     }
     $exclude = $request->query('exclude');
     $category = (int) $request->query('category');
     $orm_helper = ORM_Helper::factory('catalog_Element');
     $helper_property = $orm_helper->property_helper();
     $orm = $orm_helper->orm();
     if (!empty($exclude)) {
         $orm->where('id', 'NOT IN', $exclude);
     }
     if (!empty($category)) {
         $orm->where('category_id', '=', $category);
     }
     $db_list = $orm->order_by(DB::expr('RAND()'))->limit($limit)->find_all();
     $keys = $db_list->as_array(NULL, 'id');
     $list = $db_list->as_array();
     $catalog_category = new Catalog_Category();
     $list_categories = $catalog_category->get_list();
     $this->template = View_Theme::factory('widgets/template/catalog/related', array('list' => $list, 'list_categories' => $list_categories));
 }
Example #4
0
 /**
  * Automatically executed before the widget action. Can be used to set
  * class properties, do authorization checks, and execute other custom code.
  *
  * @return  void
  */
 public function before()
 {
     $ads = new Model_Ad();
     $ads->where('status', '=', Model_Ad::STATUS_PUBLISHED);
     //if ad have passed expiration time dont show
     if (core::config('advertisement.expire_date') > 0) {
         $ads->where(DB::expr('DATE_ADD( published, INTERVAL ' . core::config('advertisement.expire_date') . ' DAY)'), '>', Date::unix2mysql());
     }
     switch ($this->ads_type) {
         case 'popular':
             $id_ads = array_keys(Model_Visit::popular_ads());
             if (count($id_ads) > 0) {
                 $ads->where('id_ad', 'IN', $id_ads);
             }
             break;
         case 'featured':
             $ads->where('featured', 'IS NOT', NULL)->where('featured', '>', Date::unix2mysql())->order_by('featured', 'desc');
             break;
         case 'latest':
         default:
             $ads->order_by('published', 'desc');
             break;
     }
     $ads = $ads->limit($this->ads_limit)->cached()->find_all();
     //die(print_r($ads));
     $this->ads = $ads;
 }
Example #5
0
 public function action_edit()
 {
     $id = $this->request->param('id');
     $form = new Form('security/groups/edit' . ($id ? '/' . $id : ''));
     $form->add("name", 'Name', Form::STRING, '', array('not_empty'))->add('is_admin', 'Administrative group', Form::BOOL)->add('show_all_jobs', 'Show all jobs (unchecked - show only assigned jobs)', Form::BOOL)->add('allow_assign', 'Allow assigning jobs', Form::BOOL)->add('allow_reports', 'Allow tracking changes', Form::BOOL)->add('allow_submissions', 'Allow tracking submissions', Form::BOOL)->add('allow_finance', 'Financial reports', Form::BOOL)->add('allow_forms', 'Forms submission', Form::BOOL)->add('allow_custom_forms', 'Custom forms submission', Form::BOOL)->add('edit_custom_forms', 'Edit custom forms reports', Form::BOOL)->add('time_machine', 'Time Machine', Form::BOOL);
     $form->add('columns', 'Show columns in job search', Form::INFO);
     foreach (Columns::$fixed as $key => $value) {
         $form->add($key, $value, Form::BOOL);
     }
     $item = $id ? Group::get($id) : array();
     if ($item) {
         $columns = explode(',', $item['columns']);
         foreach ($columns as $column) {
             $item[$column] = 1;
         }
         unset($item['columns']);
     }
     $form->values($item);
     if ($_POST) {
         $value = $form->filter($_POST);
         if ($value['is_admin']) {
             $value['show_all_jobs'] = 1;
             $value['allow_assign'] = 1;
             $value['allow_reports'] = 1;
             $value['allow_submissions'] = 1;
             $value['allow_finance'] = 1;
             $value['allow_forms'] = 0;
             $value['allow_custom_forms'] = 1;
             $value['edit_custom_forms'] = 1;
             $value['time_machine'] = 1;
             $value['columns'] = implode(',', array_keys(Columns::$fixed));
         } else {
             $columns = array();
             foreach (Columns::$fixed as $key => $name) {
                 if (Arr::get($value, $key)) {
                     $columns[] = $key;
                 }
             }
             $value['columns'] = implode(',', $columns);
         }
         $value = array_diff_key($value, Columns::$fixed);
         if (!$form->validate($value)) {
             if ($id) {
                 DB::update('groups')->set($value)->where('id', '=', $id)->execute();
             } else {
                 $origin = Arr::get($_POST, 'permissions');
                 unset($_POST['permissions']);
                 $id = Arr::get(DB::insert('groups', array_keys($value))->values(array_values($value))->execute(), 0);
                 DB::query(Database::INSERT, DB::expr("INSERT INTO `group_columns` (`group_id`, `column_id`, `permissions`) \n                        (SELECT :id, `column_id`, `permissions` FROM `group_columns` WHERE `group_id` = :origin)")->param(':id', $id)->param(':origin', $origin)->compile())->execute();
             }
             Messages::save('Group successfully saved!', 'success');
             $this->redirect('/security/groups');
         }
     }
     if (!$id) {
         $groups = DB::select('id', 'name')->from('groups')->execute()->as_array('id', 'name');
         $form->add('permissions', 'Copy permissions from group', Form::SELECT, $groups);
     }
     $this->response->body($form->render());
 }
Example #6
0
File: users.php Project: sajans/cms
 public function action_grid()
 {
     $userName = Input::post('username');
     if (empty($userName)) {
         $userName = "******";
     } else {
         $userName = "******" . $userName . "%";
     }
     $email = Input::post('email');
     if (empty($email)) {
         $email = "%%";
     } else {
         $email = "%" . $email . "%";
     }
     $limit = (int) Input::post('limit');
     $page = (int) Input::post('page');
     $limit = isset($limit) ? $limit : $this->_paginationConfig['limit_default'];
     $page = isset($page) ? $page : 1;
     $result = DB::select(DB::expr('COUNT(id) as total'))->from('users')->where('username', 'like', $userName)->where('email', 'like', $email)->execute()->as_array();
     $total = $result[0]['total'];
     $pagination = Model_Paginator::getPaginationData($page, $limit, $total, $this->_paginationConfig);
     $data['pagination'] = $pagination;
     $data['users'] = DB::select()->from('users')->where('username', 'like', $userName)->where('email', 'like', $email)->order_by("created_at", "desc")->limit($pagination->limit)->offset($pagination->offset)->as_object()->execute();
     $this->template = View::forge('admin/users/grid', $data, false);
 }
Example #7
0
 public function action_index()
 {
     $this->template->scripts = array("public/js/mvp/mvp.js");
     $tag = Model_Setting::getSetting(Model_Setting::MVP_TAG);
     if (!empty($tag)) {
         $tgMod = ORM::factory("tag", $tag);
         $tgMod2 = ORM::factory("tag", $tag);
         $photo1 = $tgMod->photos->where("moderation_status_id", "=", Model_ModerationStatus::APPROVED)->order_by(DB::expr('RAND()'))->find();
         $photo2 = $tgMod2->photos->where("moderation_status_id", "=", Model_ModerationStatus::APPROVED)->order_by(DB::expr('RAND()'))->find();
     } else {
         $photo1 = ORM::factory("photo")->where("moderation_status_id", "=", Model_ModerationStatus::APPROVED)->order_by(DB::expr('RAND()'))->find();
         $photo2 = ORM::factory("photo")->where("moderation_status_id", "=", Model_ModerationStatus::APPROVED)->order_by(DB::expr('RAND()'))->find();
     }
     while ($photo2->id == $photo1->id) {
         if (!empty($tag)) {
             $tgMod2 = ORM::factory("tag", $tag);
             $photo2 = $tgMod2->photos->where("moderation_status_id", "=", Model_ModerationStatus::APPROVED)->order_by(DB::expr('RAND()'))->find();
         } else {
             $photo2 = ORM::factory("photo")->where("moderation_status_id", "=", Model_ModerationStatus::APPROVED)->order_by(DB::expr('RAND()'))->find();
         }
     }
     $_SESSION['photo1'] = $photo1->id;
     $_SESSION['photo2'] = $photo2->id;
     $this->template->top = View::factory("mvp/index");
     $this->template->top->photo1 = $photo1;
     $this->template->top->photo2 = $photo2;
 }
Example #8
0
 public function action_grid()
 {
     $name = Input::post('name');
     if (empty($name)) {
         $name = "%%";
     } else {
         $name = "%" . $name . "%";
     }
     $category = Input::post('category');
     if (empty($category)) {
         $operator = "!=";
         $category = "";
     } else {
         $operator = "=";
         $category = $category;
     }
     $writter = Input::post('writter');
     if (empty($writter)) {
         $writterOperator = "!=";
         $writter = "";
     } else {
         $writterOperator = "=";
         $writter = $writter;
     }
     $status = Input::post('status');
     if (empty($status)) {
         $statusOperator = "!=";
         $status = "";
     } else {
         $statusOperator = "=";
         $status = $status;
     }
     $deleted = Input::post('deleted');
     if (empty($deleted)) {
         $deletedOperator = "=";
         $deleted = 0;
     } else {
         $deletedOperator = "=";
         $deleted = $deleted;
     }
     $completion = Input::post('completion');
     if (empty($completion)) {
         $completionOperator = "!=";
         $completion = "";
     } else {
         $completionOperator = "=";
         $completion = $completion;
     }
     $limit = (int) Input::post('limit');
     $page = (int) Input::post('page');
     $limit = isset($limit) ? $limit : $this->_paginationConfig['limit_default'];
     $page = isset($page) ? $page : 1;
     $result = DB::select(DB::expr('COUNT(id) as total'))->from('articles')->where('name', 'like', $name)->where('category_id', $operator, $category)->where('user_id', $writterOperator, $writter)->where('status', $statusOperator, $status)->where('deleted', $deletedOperator, $deleted)->where('completion', $completionOperator, $completion)->execute()->as_array();
     $total = $result[0]['total'];
     $pagination = Model_Paginator::getPaginationData($page, $limit, $total, $this->_paginationConfig);
     $data['pagination'] = $pagination;
     $data['articles'] = DB::select()->from('articles')->where('name', 'like', $name)->where('category_id', $operator, $category)->where('user_id', $writterOperator, $writter)->where('status', $statusOperator, $status)->where('deleted', $deletedOperator, $deleted)->where('completion', $completionOperator, $completion)->order_by("created_at", "desc")->limit($pagination->limit)->offset($pagination->offset)->as_object()->execute();
     //echo DB::last_query();
     $this->template = View::forge('admin/article/grid', $data, false);
 }
Example #9
0
 public function action_search()
 {
     $search = addslashes($this->request->param('id', ''));
     $this->set('search', $search);
     $query_m = DB::expr(' MATCH(name_ru, name_kz, name_en) ');
     $query_a = DB::expr(' AGAINST("' . $search . '") ');
     $pages = ORM::factory('Page')->where($query_m, '', $query_a)->find_all();
     $parents = array();
     foreach ($pages as $page) {
         $parents[$page->id] = array();
         $parent_id = $page->parent_id;
         while ($parent_id != 0) {
             $p = ORM::factory('Page', $parent_id);
             $parents[$page->id][] = $p;
             $parent_id = $p->parent_id;
         }
         $parents[$page->id] = array_reverse($parents[$page->id]);
     }
     $this->set('pages', $pages)->set('parents', $parents);
     $totalcount = sizeof($pages);
     $sorry = '';
     if ($totalcount == 0) {
         $sorry = 'Извините, ничего не найдено';
     }
     $this->set('sorry', $sorry);
 }
Example #10
0
 public function action_get()
 {
     try {
         if (is_numeric($id_ad = $this->request->param('id'))) {
             $ad = new Model_Ad();
             //get distance to the ad
             if (isset($this->_params['latitude']) and isset($this->_params['longitude'])) {
                 $ad->select(array(DB::expr('degrees(acos(sin(radians(' . $this->_params['latitude'] . ')) * sin(radians(`latitude`)) + cos(radians(' . $this->_params['latitude'] . ')) * cos(radians(`latitude`)) * cos(radians(abs(' . $this->_params['longitude'] . ' - `longitude`))))) * 69.172'), 'distance'));
             }
             $ad->where('id_ad', '=', $id_ad)->where('status', '=', Model_Ad::STATUS_PUBLISHED)->cached()->find();
             if ($ad->loaded()) {
                 $a = $ad->as_array();
                 $a['price'] = i18n::money_format($ad->price);
                 $a['images'] = array_values($ad->get_images());
                 $a['category'] = $ad->category->as_array();
                 $a['location'] = $ad->location->as_array();
                 $a['user'] = Controller_Api_Users::get_user_array($ad->user);
                 $a['customfields'] = Model_Field::get_by_category($ad->id_category);
                 //sorting by distance, lets add it!
                 if (isset($ad->distance)) {
                     $a['distance'] = i18n::format_measurement($ad->distance);
                 }
                 $a['url'] = Route::url('ad', array('category' => $ad->category->seoname, 'seotitle' => $ad->seotitle));
                 $this->rest_output(array('ad' => $a));
             } else {
                 $this->_error(__('Advertisement not found'), 404);
             }
         } else {
             $this->_error(__('Advertisement not found'), 404);
         }
     } catch (Kohana_HTTP_Exception $khe) {
         $this->_error($khe);
         return;
     }
 }
Example #11
0
 public function has_role($role_id)
 {
     if (!$this->loaded()) {
         throw new Kohana_Exception("Can't operate on unloaded Model_User");
     }
     return (bool) DB::select(array(DB::expr('COUNT(*)'), 'total_count'))->from("roles_users")->where("user_id", '=', $this->id)->where("role_id", '=', $role_id)->execute($this->_db)->get('total_count');
 }
Example #12
0
 /**
  * Returns the descendants of the current node.
  *
  * @access public
  * @param bool $self include the current loaded node?
  * @param string $direction direction to order the left column by.
  * @param array $where additional where clause
  * @return Sprig_MPTT_MOD
  */
 public function descendants($self = FALSE, $direction = 'ASC', $direct_children_only = FALSE, $leaves_only = FALSE, $limit = FALSE, $where = FALSE)
 {
     var_dump($val[0], $val[1], $val_2);
     $left_operator = $self ? '>=' : '>';
     $right_operator = $self ? '<=' : '<';
     $query = DB::select()->where($this->left_column, $left_operator, $this->{$this->left_column})->where($this->right_column, $right_operator, $this->{$this->right_column})->where($this->scope_column, '=', $this->{$this->scope_column})->order_by('ord', $direction);
     if ($direct_children_only) {
         if ($self) {
             $query->and_where_open()->where($this->level_column, '=', $this->{$this->level_column})->or_where($this->level_column, '=', $this->{$this->level_column} + 1)->and_where_close();
         } else {
             $query->where($this->level_column, '=', $this->{$this->level_column} + 1);
         }
     }
     if ($leaves_only) {
         $query->where($this->right_column, '=', new Database_Expression('`' . $this->left_column . '` + 1'));
     }
     if ($where) {
         foreach ($where as $key => $val) {
             $val_2 = isset($val[3]) && $val[3] ? DB::expr($val[2]) : $val[2];
             var_dump($val[0], $val[1], $val_2);
             $query->where($val[0], $val[1], $val_2);
         }
     }
     return Sprig_MPTT_MOD::factory($this->_model)->load($query, $limit);
 }
Example #13
0
 public function action_index()
 {
     $tags = array();
     $imager = new SimpleImage();
     if ($this->request->param('path')) {
         // Берем новость
         $post = ORM::factory('blog')->where('url', '=', $this->request->param('path'))->find();
     } else {
         $post = ORM::factory('blog');
     }
     if ($_POST) {
         $post_name = Arr::get($_POST, 'post_name');
         $post_url = Arr::get($_POST, 'post_url');
         $short_text = Arr::get($_POST, 'short_text');
         $full_text = Arr::get($_POST, 'full_text');
         $tag = Arr::get($_POST, 'tag');
         // Загрузка изображения
         $image = $_FILES["imgupload"]["name"];
         if (!empty($image)) {
             $imager = new SimpleImage();
             //$this->news->deleteImage($post->id);
             //$image = $this->image->upload_image($image['tmp_name'], $image['name'], $this->config->news_images_dir."big/");
             move_uploaded_file($_FILES["imgupload"]["tmp_name"], "files/blog/" . $_FILES["imgupload"]["name"]);
             $imager->load("files/blog/" . $image);
             $imager->resize(200, 200);
             $imager->save("files/blog/miniatures/" . $image);
         }
         $post->set('name', $post_name)->set('url', $post_url)->set('date', DB::expr('now()'))->set('short_text', $short_text)->set('full_text', $full_text)->set('image', $image)->set('tag_id', ORM::factory('tags')->where('name', '=', $tag)->find())->save();
     }
     $tags = ORM::factory('tags')->find_all();
     $content = View::factory('/admin/post')->bind('tags', $tags)->bind('post', $post);
     $this->template->content = $content;
 }
Example #14
0
File: date.php Project: sajans/cms
 public function action_grid()
 {
     $title = Input::post('title');
     if (empty($title)) {
         $title = "%%";
     } else {
         $title = "%" . $title . "%";
     }
     $summary = Input::post('summary');
     if (empty($summary)) {
         $summary = "%%";
     } else {
         $summary = "%" . $summary . "%";
     }
     $date = Input::post('date');
     if (empty($date)) {
         $date = "%%";
     } else {
         $date = "%" . $date . "%";
     }
     $limit = (int) Input::post('limit');
     $page = (int) Input::post('page');
     $limit = isset($limit) ? $limit : $this->_paginationConfig['limit_default'];
     $page = isset($page) ? $page : 1;
     $result = DB::select(DB::expr('COUNT(id) as total'))->from('dates')->where('title', 'like', $title)->where('summary', 'like', $summary)->execute()->as_array();
     $total = $result[0]['total'];
     $pagination = Model_Paginator::getPaginationData($page, $limit, $total, $this->_paginationConfig);
     $data['pagination'] = $pagination;
     $data['dates'] = DB::select()->from('dates')->where('title', 'like', $title)->where('summary', 'like', $summary)->order_by("created_at", "desc")->limit($pagination->limit)->offset($pagination->offset)->as_object()->execute();
     $this->template = View::forge('admin/date/grid', $data, false);
 }
Example #15
0
 public function action_index()
 {
     //template header
     $this->template->title = '';
     // $this->template->meta_keywords    = 'keywords';
     $this->template->meta_description = Core::config('general.site_description');
     //setting main view/template and render pages
     // swith to decide on ads_in_home
     $ads = new Model_Ad();
     $ads->where('status', '=', Model_Ad::STATUS_PUBLISHED);
     switch (core::config('advertisement.ads_in_home')) {
         case 2:
             $id_ads = array_keys(Model_Visit::popular_ads());
             if (count($id_ads) > 0) {
                 $ads->where('id_ad', 'IN', $id_ads);
             }
             break;
         case 1:
             $ads->where('featured', 'IS NOT', NULL)->where('featured', 'BETWEEN', array(DB::expr('NOW()'), Date::unix2mysql(time() + core::config('payment.featured_days') * 24 * 60 * 60)))->order_by('featured', 'desc');
             break;
         case 0:
         default:
             $ads->order_by('published', 'desc');
             break;
     }
     //if ad have passed expiration time dont show
     if (core::config('advertisement.expire_date') > 0) {
         $ads->where(DB::expr('DATE_ADD( published, INTERVAL ' . core::config('advertisement.expire_date') . ' DAY)'), '>', DB::expr('NOW()'));
     }
     $ads = $ads->limit(Theme::get('num_home_latest_ads', 4))->cached()->find_all();
     $this->ads = $ads;
     $categs = Model_Category::get_category_count();
     $this->template->bind('content', $content);
     $this->template->content = View::factory('pages/home', array('ads' => $ads, 'categs' => $categs));
 }
Example #16
0
 /**
  * returns the user rate from all the reviews
  * @param  Model_User $user [description]
  * @return [type]                 [description]
  */
 public static function get_user_rate(Model_User $user)
 {
     $db_prefix = Database::instance('default')->table_prefix();
     $query = DB::select(DB::expr('AVG(' . $db_prefix . 'reviews.rate) rates'))->from('reviews')->join('ads', 'RIGHT')->using('id_ad')->where('ads.id_user', '=', $user->id_user)->where('reviews.status', '=', Model_Review::STATUS_ACTIVE)->group_by('reviews.id_ad')->execute();
     $rates = $query->as_array();
     return isset($rates[0]) ? round($rates[0]['rates'], 2) : FALSE;
 }
Example #17
0
 public function action_index()
 {
     $users = DB::select('users.id', DB::expr('CONCAT(`users`.`name`, " (", `login`, ")") as name'), array('groups.name', 'group'))->from('users')->join('groups', 'left')->on('group_id', '=', 'groups.id')->order_by('group')->order_by('name')->execute()->as_array();
     $companies = DB::select('id', 'name')->from('companies')->execute()->as_array('id', 'name');
     $view = View::factory('Notifications')->bind('users', $users)->bind('companies', $companies);
     $this->response->body($view);
 }
Example #18
0
 /**
  * 
  * @return array [$archive]
  */
 public function fetch_data()
 {
     $datasource = Datasource_Data_Manager::load($this->ds_id);
     if ($datasource === NULL) {
         return array();
     }
     $is_system = TRUE;
     if ($this->date_field == 'created_on') {
         $field = 'd.' . $this->date_field;
     } else {
         $field = 'ds.' . $this->date_field;
         $is_system = FALSE;
     }
     switch ($this->archive_type) {
         case 'day':
             $type = '%Y/%m/%d';
             break;
         case 'year':
             $type = '%Y';
             break;
         default:
             $type = '%Y/%m';
     }
     $query = DB::select(array(DB::expr('DATE_FORMAT(' . Database::instance()->quote_column($field) . ', "' . $type . '")'), 'date'))->select(array(DB::expr('COUNT(*)'), 'total'))->distinct(TRUE)->from(array('dshybrid', 'd'))->where('d.published', '=', 1)->where('d.ds_id', '=', $this->ds_id)->group_by('date')->order_by($field, $this->order_by == 'asc' ? 'asc' : 'desc');
     if ($is_system === FALSE) {
         $query->join(array('dshybrid_' . $this->ds_id, 'ds'))->on('ds.id', '=', 'd.id');
     }
     $result = $query->execute()->as_array();
     return array('archive' => $result);
 }
 public function builder_call_update_children(Database_Query $builder, Jam_Event_Data $data, $old_path, $new_path)
 {
     if (FALSE === $builder instanceof Jam_Query_Builder_Update) {
         throw new InvalidArgumentException('Can only be used on "update" queries');
     }
     $builder->value('path', DB::expr("TRIM(BOTH '/' FROM REPLACE(path, :old_path, :new_path))", array(':old_path' => $old_path, ':new_path' => $new_path)));
 }
Example #20
0
 public function action_index()
 {
     header('Access-Control-Allow-Origin: *');
     $search = Security::xss_clean(isset($_GET['search']) ? $_GET['search'] : '');
     if (!empty($search)) {
         $query_b = '%' . $search . '%';
         $this->searchText = Database::instance()->escape($search);
         $query_a = DB::expr(' AGAINST(' . $this->searchText . ') ');
         $list = ORM::factory('Publication')->distinct('true')->where(DB::expr('MATCH(title_' . $this->language . ')'), '', $query_a)->or_where(DB::expr('MATCH(desc_' . $this->language . ')'), '', $query_a)->or_where(DB::expr('MATCH(text_' . $this->language . ')'), '', $query_a)->or_where('title_' . $this->language, 'like', $query_b)->and_where('published', '=', 1)->limit($this->limit)->offset($this->offset)->find_all();
     } else {
         $list = ORM::factory('Publication')->where('title_' . $this->language, '<>', '')->where('published', '=', 1)->order_by('order', 'DESC');
         $this->data['page_count'] = Paginate::factory($list)->paginate(NULL, NULL, 10)->page_count();
         $list = $list->find_all();
     }
     $pub = array();
     $this->data['search'] = $search;
     foreach ($list as $k => $v) {
         $pub['id'] = $v->id;
         $pub['url'] = 'http://' . $_SERVER['HTTP_HOST'] . '/' . $this->language . URL::site('api/smartpublications/view/' . $v->id);
         $pub['title'] = $v->title;
         $pub['desc'] = strip_tags($v->desc);
         $pub['image'] = 'http://' . $_SERVER['HTTP_HOST'] . URL::media('/images/w205-h160/' . $v->picture->file_path);
         $this->data['publications'][] = $pub;
     }
     $this->response->body(json_encode($this->data));
 }
Example #21
0
 /**
  * Restock shops
  *
  * @return null
  */
 protected function _execute(array $params)
 {
     $shops = array();
     // find items that need to be restocked
     $restocks = ORM::factory('Shop_Restock')->where('next_restock', '<=', time())->order_by(DB::expr('RAND()'))->find_all();
     foreach ($restocks as $restock) {
         // cache the shop's cap limit and stock total
         if (!array_key_exists($restock->shop_id, $shops)) {
             $shops[$restock->shop_id] = array('cap' => $restock->shop->stock_cap, 'stock' => ORM::factory('Shop_Inventory')->where('shop_id', '=', $restock->shop_id)->count_all());
         }
         // only restock if we haven't reached the shop's item stack cap
         if ($shops[$restock->shop_id]['cap'] != $shops[$restock->shop_id]['stock']) {
             // get randomised values for price and amount
             $price = mt_rand($restock->min_price, $restock->max_price);
             $amount = mt_rand($restock->min_amount, $restock->max_amount);
             $inventory = ORM::factory('Shop_Inventory')->where('shop_id', '=', $restock->shop_id)->where('item_id', '=', $restock->item_id)->find();
             // the item was still in stock, just update it
             if ($inventory->loaded()) {
                 $amount = $amount + $inventory->stock > $restock->cap_amount ? $restock->cap_amount : $amount + $inventory->stock;
             } else {
                 // add 1 to the shop's stock
                 $shops[$restock->shop_id]['stock']++;
                 // prepare the new item
                 $inventory = ORM::factory('Shop_Inventory')->values(array('shop_id' => $restock->shop_id, 'item_id' => $restock->item_id));
             }
             // update stock & price
             $inventory->price = $price;
             $inventory->stock = $amount;
             $inventory->save();
             // set the next restock
             $restock->next_restock = time() + $restock->frequency;
             $restock->save();
         }
     }
 }
Example #22
0
 public function action_index()
 {
     // clear redirect referrer
     \Session::delete('submitted_redirect');
     // read flash message for display errors.
     $form_status = \Session::get_flash('form_status');
     if (isset($form_status['form_status']) && isset($form_status['form_status_message'])) {
         $output['form_status'] = $form_status['form_status'];
         $output['form_status_message'] = $form_status['form_status_message'];
     }
     unset($form_status);
     // list tables
     $output['list_tables'] = \DB::list_tables();
     // if form submitted
     if (\Input::method() == 'POST') {
         $table_name = trim(\Input::post('table_name'));
         $output['table_name'] = $table_name;
         if (!\Extension\NoCsrf::check()) {
             // validate token failed
             $output['form_status'] = 'error';
             $output['form_status_message'] = \Lang::get('fslang_invalid_csrf_token');
         } elseif ($table_name == null) {
             $output['form_status'] = 'error';
             $output['form_status_message'] = \Lang::get('dbhelper_please_select_db_table');
         } else {
             $output['list_columns'] = \DB::list_columns(\DB::expr('`' . $table_name . '`'));
         }
     }
     // endif; form submitted
     // <head> output ---------------------------------------------------------------------
     $output['page_title'] = $this->generateTitle(\Lang::get('dbhelper'));
     // <head> output ---------------------------------------------------------------------
     return $this->generatePage('admin/templates/index/index_v', $output, false);
 }
Example #23
0
 /**
  * Count the number of records in the table. Modified does not reset!
  * @param bool $reset optional to reset the query
  * @return integer
  */
 public function count_all($reset = FALSE)
 {
     $selects = array();
     foreach ($this->_db_pending as $key => $method) {
         if ($method['name'] == 'select') {
             // Ignore any selected columns for now
             $selects[] = $method;
             unset($this->_db_pending[$key]);
         }
     }
     if (!empty($this->_load_with)) {
         foreach ($this->_load_with as $alias) {
             // Bind relationship
             $this->with($alias);
         }
     }
     $this->_build(Database::SELECT);
     $records = $this->_db_builder->from(array($this->_table_name, $this->_object_name))->select(array(DB::expr('COUNT(' . $this->_db->quote_column($this->_object_name . '.' . $this->_primary_key) . ')'), 'records_found'))->execute($this->_db)->get('records_found');
     // Add back in selected columns
     $this->_db_pending += $selects;
     //Edited!
     if ($reset === TRUE) {
         $this->reset();
     }
     // Return the total number of records in a table
     return (int) $records;
 }
Example #24
0
 /**
  * Triggers error if identity exists.
  * Validation callback.
  *
  * @param   Validation  Validation object
  * @param   string    field name
  * @return  void
  */
 public function unique_identity(Validation $validation, $field)
 {
     $identity_exists = (bool) DB::select(array(DB::expr('COUNT(*)'), 'total_count'))->from($this->_table_name)->where('identity', '=', $validation['identity'])->and_where('provider', '=', $validation['provider'])->execute($this->_db)->get('total_count');
     if ($identity_exists) {
         $validation->error($field, 'identity_available', array($validation[$field]));
     }
 }
Example #25
0
 public function rest_get()
 {
     $start = $this->param('start', NULL, TRUE);
     $end = $this->param('end', NULL, TRUE);
     $events = DB::select()->from('calendar')->where(DB::expr('DATE(start)'), 'between', array($start, $end))->where_open()->or_where('user_id', '=', Auth::get_id())->or_where('user_id', '=', 0)->where_close()->execute()->as_array();
     $this->response($events);
 }
Example #26
0
 public function action_process_user_payments()
 {
     // уведомляем пользователей, у которых осталось мало времени пользования аккаунтом
     $disable_event_period = DB::select('days')->from('payment_settings')->where('status', '=', 'N')->where('system_name', '=', 'disable_event_period')->limit(1)->execute()->get('days');
     if (empty($disable_event_period)) {
         $disable_event_period = 5;
     }
     $date = new DateTime();
     $date->modify($disable_event_period - 1 . " days");
     $exp = ORM::factory('user')->where(DB::expr('DATE(expires)'), '=', $date->format("Y-m-d"));
     $exp->reset(FALSE);
     if (count($exp->find_all()) > 0) {
         Email::connect();
         $exp_date = $date->format("d.m.Y");
         $title = "Действие вашего аккаунта заканчивается";
         $text = "Добрый день, %s.<br><br>Действие вашего аккаунта заканчивается %s.<br>Вы можете продлить аккаунт в <a href='http://www.as-avtoservice.ru/cabinet/payment'>личном кабинете</a>";
         foreach ($exp->find_all() as $e) {
             Email::send($e->email, array('*****@*****.**', 'Ассоциация автосервисов'), $title, sprintf($text, $e->username, $exp_date), TRUE);
             echo "date: " . $exp_date . " email: " . $e->email . "\n";
         }
     }
     //  1) ставим статус просрочен всем
     $payment_expires_period = DB::select('days')->from('payment_settings')->where('status', '=', 'N')->where('system_name', '=', 'payment_expires_period')->limit(1)->execute()->get('days');
     if (empty($payment_expires_period)) {
         $payment_expires_period = 5;
     }
     $date = new DateTime();
     $date->modify("-" . $payment_expires_period . " days");
     DB::update("invoice")->set(array('status' => 'E'))->where('status', '=', 'N')->where('create_date', '<', $date->format("Y-m-d"))->execute();
     $date = new DateTime();
     //  Вимикаєм користувачів з просроченими кабінетами
     $query = DB::update("users")->set(array('user_type' => 'disabled'))->where_open()->where('expires', '<', $date->format("Y-m-d"))->or_where('expires', '=', NULL)->where_close()->execute();
 }
Example #27
0
 public function action_files()
 {
     $files = array();
     $limit = arr::get($_GET, 'limit', 10);
     $offset = arr::get($_GET, 'offset', 0);
     $query = ORM::factory('File');
     if (arr::get($_GET, 'tags', false)) {
         $tags = arr::get($_GET, 'tags');
         if (arr::get($_GET, 'matchAll', false) == "true") {
             $tagsquery = DB::select('files_tags.file_id')->from('files_tags')->where('files_tags.tag_id', 'IN', $tags)->group_by('files_tags.file_id')->having(DB::expr('COUNT(files_tags.file_id)'), '=', count($tags))->execute();
             //die(var_dump($tagsquery));
         } else {
             $tagsquery = DB::select('files_tags.file_id')->distinct(true)->from('files_tags')->where('files_tags.tag_id', 'IN', $tags)->execute();
             //die(var_dump($tagsquery));
         }
         if ((bool) $tagsquery->count()) {
             $ids = array();
             foreach ($tagsquery as $q) {
                 $ids[] = arr::get($q, 'file_id');
                 //$files[] = ORM::factory('File', arr::get($q, 'file_id'))->info();
             }
             $query = $query->where('id', 'IN', $ids);
         } else {
             // Empty resultset
             ajax::success('ok', array('files' => array()));
         }
     }
     $query = $query->order_by('created', 'DESC')->limit($limit)->offset($offset)->find_all();
     if ((bool) $query->count()) {
         foreach ($query as $file) {
             $files[] = $file->info();
         }
     }
     ajax::success('ok', array('files' => $files));
 }
Example #28
0
 public function action_get_index_collection()
 {
     // Get the post query
     $posts_query = $this->_build_query();
     // Get the count of ALL records
     $count_query = clone $posts_query;
     $total_records = (int) $count_query->select(array(DB::expr('COUNT(DISTINCT `post`.`id`)'), 'records_found'))->limit(NULL)->offset(NULL)->find_all()->get('records_found');
     // Fetch posts from db
     $posts = $posts_query->find_all();
     // Get query count
     $post_query_sql = $posts_query->last_query();
     // Generate filename using hashed query params and ids
     $filename = 'export-' . hash('sha256', implode('-', $this->request->query()) . '~' . '-' . $this->request->param('id')) . '.csv';
     // Get existing tsv file
     $tsv_file = Kohana::$config->load('media.media_upload_dir') . $filename;
     // Only generate a new if the file doesn't exist
     if (!file_exists($tsv_file)) {
         // Supported headers for the TSV file
         $tsv_headers = array("ID", "PARENT", "USER", "FORM", "TITLE", "CONTENT", "TYPE", "STATUS", "SLUG", "LOCALE", "CREATED", "UPDATED", "TAGS", "SETS");
         // Generate tab separated values (tsv)
         $tsv_text = $this->_generate_tsv($tsv_headers, $posts);
         // Write tsv to file
         $this->_write_tsv_to_file($tsv_text, $filename);
     }
     // Relative path
     $relative_path = str_replace(APPPATH . 'media' . DIRECTORY_SEPARATOR, '', Kohana::$config->load('media.media_upload_dir'));
     // Build download link
     $download_link = URL::site(Media::uri($relative_path . $filename), Request::current());
     // Respond with download link and record count
     $this->_response_payload = array('total_count' => $total_records, 'link' => $download_link);
 }
Example #29
0
 public static function getForm()
 {
     $alert = $success = $message = $email_phone = $temp = $name = $check = false;
     /* defining variables values */
     if (!empty($_POST)) {
         $check = true;
         if (!empty($_POST['message'])) {
             $temp = self::trim($_POST['message']);
             if (!empty($temp)) {
                 $message = $temp;
             }
         }
         if (!empty($_POST['name'])) {
             $temp = self::trim($_POST['name']);
             if (!empty($temp)) {
                 $name = $temp;
             }
         }
         if (!empty($_POST['email_phone'])) {
             $temp = self::trim($_POST['email_phone']);
             if (!empty($temp)) {
                 $email_phone = $temp;
             }
         }
     }
     /* validating */
     if ($check === true) {
         if (empty($name)) {
             $alert = self::$emptyNameAlertText;
         } elseif (empty($email_phone)) {
             $alert = self::$emptyEmailPhoneAlertText;
         } elseif (empty($message)) {
             $alert = self::$emptyMessageAlertText;
         } else {
             /* spam defence */
             self::checkTable();
             $today = date('Y-m-d');
             $identity = self::getIdentity();
             $todayMessages = DB::select([DB::expr('COUNT(id)'), 'c'])->from(self::$tableName)->where('`date`', '=', $today)->where('identity', '=', $identity)->execute()->get('c');
             if ($todayMessages < self::$attempsPerDay) {
                 $model = new Model_Feedback();
                 $model->date = $today;
                 $model->message = $message;
                 $model->name = $name;
                 $model->email_phone = $email_phone;
                 $model->identity = $identity;
                 $model->save();
                 self::afterSuccess($today, $name, $email_phone, $message);
                 $message = $email_phone = $name = '';
                 $success = self::$successText;
             } else {
                 $alert = self::$spamAlertText;
             }
         }
     }
     /* rendering */
     $form = View::factory('feedback/form', ['message' => $message, 'name' => $name, 'alert' => $alert, 'success' => $success, 'email_phone' => $email_phone]);
     return $form;
 }
Example #30
0
 /**
  * Get a token
  *
  * @param $token
  * @param $type
  * @return mixed
  */
 public static function get_token($token, $type, $delete = TRUE)
 {
     $auth_token = ORM::factory("auth_token")->where("token", "=", $token)->where("type", "=", $type)->where("expire_date", ">", DB::expr("SYSDATE()"))->find();
     if ($auth_token->loaded()) {
         return $auth_token;
     }
     return FALSE;
 }