/** * Overload Sprig::update() to save revision change * @param bump whether to bump the version number */ public function update($bump = TRUE) { Kohana::$log->add(Kohana::DEBUG, 'Executing Versioned_Sprig::update'); $updated = FALSE; foreach ($this->_fields as $field => $object) { if ($object instanceof Sprig_Field_Tracked and $this->changed($field)) { $this->comment = UTF8::ucwords($object->label) . ' changed from "' . $this->_original[$field] . '" to "' . $this->_changed[$field] . '".'; } if ($object instanceof Sprig_Field_Versioned and $this->changed($field) and $bump) { $diff = ''; if ($this->version != 0) { $diff = Versioned::diff($this->_original[$field], $this->_changed[$field]); $diff = Versioned::clean_array($diff); $diff = serialize($diff); } $this->version++; $revision = Sprig::factory($this->_model . '_revision'); $revision->values(array('entry' => $this->id, 'version' => $this->version, 'editor' => $this->editor, 'diff' => $diff)); $revision->comments = $this->comments; $revision->create(); $updated = TRUE; $this->comments = array(); } } if (!$updated and count($this->comments) > 0) { $revision = Sprig::factory($this->_model . '_revision'); $revision->entry = $this->id; $revision->version = $this->version; $revision->load(); $revision->comments = array_merge($revision->comments, $this->comments); $revision->update(); } return parent::update(); }
/** * Revoke access to $role for resource * * @param mixed string role name or Model_Role object * @param string resource identifier * @param string action [optional] * @param string condition [optional] * @return void */ public static function revoke($role, $resource, $action = NULL, $condition = NULL) { // Normalise $role if (!$role instanceof Model_Role) { $role = Sprig::factory('role', array('name' => $role))->load(); } // Check role exists if (!$role->loaded()) { // Just return without deleting anything return; } $model = Sprig::factory('aacl_rule', array('role' => $role->id)); if ($resource !== '*') { // Add normal reources, resource '*' will delete all rules for this role $model->resource = $resource; } if ($resource !== '*' and !is_null($action)) { $model->action = $action; } if ($resource !== '*' and !is_null($condition)) { $model->condition = $condition; } // Delete rule $model->delete(); }
public function ajax_response() { session_start(); // Проверяем, что форма была разблокирована if (isset($_SESSION['qaptcha_key']) and $_SESSION['qaptcha_key'] == 'iqaptcha' and isset($_POST['iqaptcha']) and empty($_POST['iqaptcha'])) { // Проверяем заполненность всех обязательных полей if (!empty($_POST['fio']) and !empty($_POST['phone']) and !empty($_POST['message'])) { // Обезопасим входные данные $this->set_safe($_POST, FALSE); // Сохраняем в админке // Создаем запрос $feedback = Sprig::factory('feedback'); $feedback->values($_POST); $feedback->create(); // Если в настройках задан email администратора - отправляем письмо if (!empty($this->fos_email)) { // Создаем объект PHPMailer и задаем начальные настройки $mail = new PHPMailer(); $mail->CharSet = 'utf-8'; $mail->From = 'no-reply@' . $_SERVER['HTTP_HOST']; $mail->FromName = $_SERVER['HTTP_HOST']; $mail->AddAddress($this->fos_email, 'Получатель запросов'); $mail->Subject = 'Сообщение с сайта от: ' . $_POST['fio']; $mail->Body = $this->email_tpl_render('feedbackadminmail', $_POST); $mail->Send(); } return 'true'; } } return 'false'; }
public function ajax_response() { session_start(); // Проверяем, что форма была разблокирована if (isset($_SESSION['qaptcha_key']) and $_SESSION['qaptcha_key'] == 'iqaptcha' and isset($_POST['iqaptcha']) and empty($_POST['iqaptcha'])) { // Проверяем заполненность всех обязательных полей if (!empty($_POST['fio']) and !empty($_POST['phone']) and !empty($_POST['catalog_id']) and !empty($_POST['object_data'])) { // Обезопасим входные данные $this->set_safe($_POST, FALSE); // Добавим переводы строк $_POST['object_data'] = str_replace(';', "\r\n", $_POST['object_data']); // Сохраняем в админке // Создаем запрос $reqbuy = Sprig::factory('reqbuy'); $reqbuy->values($_POST); $reqbuy->create(); // Если в настройках задан email администратора - отправляем письмо if (!empty($this->reqbuy_email)) { // Создаем объект PHPMailer и задаем начальные настройки $mail = new PHPMailer(); $mail->CharSet = 'utf-8'; $mail->From = 'no-reply@' . $_SERVER['HTTP_HOST']; $mail->FromName = $_SERVER['HTTP_HOST']; $mail->AddAddress($this->reqbuy_email, 'Получатель запросов'); $mail->Subject = 'Заявка на покупку объекта от: ' . $_POST['fio']; $mail->Body = $this->email_tpl_render('reqbuyadminmail', $_POST); $mail->Send(); } return 'true'; } } return 'false'; }
public function load(Database_Query_Builder_Select $query = NULL, $limit = NULL) { if (!$query) { $query = DB::select()->order_by('id', 'DESC')->order_by('created_on', 'DESC'); } return Sprig::factory('Shindig_Post')->load($query, $limit); }
public function __construct(array $options = NULL) { parent::__construct($options); if ($this->choices === NULL) { $this->choices = Sprig::factory($this->model)->select_list(); } }
/** * Create a new article */ public function action_new() { Kohana::$log->add(Kohana::DEBUG, 'Executing Controller_Admin_Article::action_new'); $this->template->content = View::factory('blog/admin/article_form')->set('legend', __('Create Article'))->set('submit', __('Save'))->set('slug_editable', FALSE)->set('comment_needed', FALSE)->bind('article', $article)->bind('errors', $errors); $article = Sprig::factory('article')->values($_POST); $article->author = $this->a1->get_user(); if ($_POST) { try { $article->create(); //$article->load(); $statistic = Sprig::factory('statistic', array('article' => $article))->create(); Message::instance()->info('The article, :title, has been created.', array(':title' => $article->title)); if (!$this->_internal) { $this->request->redirect($this->request->uri(array('action' => 'list'))); } } catch (Validate_Exception $e) { $errors = $e->array->errors('admin'); } } // Set template scripts and styles $this->template->scripts[] = 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js'; $this->template->scripts[] = Route::get('media')->uri(array('file' => 'js/markitup/jquery.markitup.js')); $this->template->scripts[] = Route::get('media')->uri(array('file' => 'js/markitup/sets/html/set.js')); $this->template->styles[Route::get('media')->uri(array('file' => 'js/markitup/skins/markitup/style.css'))] = 'screen'; $this->template->styles[Route::get('media')->uri(array('file' => 'js/markitup/sets/html/style.css'))] = 'screen'; }
/** * Update an existing post * */ public function action_update() { $this->request->response = View::factory('shindig/admin/edit_post')->set('form_title', __('Update Post'))->bind('use_authors', $use_authors)->bind('site_url', $site_url)->bind('errors', $errors)->bind('post', $post); $use_authors = Kohana::config('shindig.use_authors'); $site_url = URL::site('blog', TRUE) . '/'; $post = Sprig::factory('shindig_post')->values(array('id' => $this->request->param('id')))->load(); if (isset($_POST['shindig_post'])) { try { /* if ($tags = Arr::get($_POST, 'tags')) { foreach ($tags as $tag) { // check to see if tag exsists. // Get id if it does, create it if it doesn't } } */ $post->values($_POST)->update(); Request::instance()->redirect(Route::get(Kohana::config('shindig.post_create_redirect.route'))->uri(array('action' => Kohana::config('shindig.post_create_redirect.action'), 'id' => $post->id))); } catch (Validate_Exception $e) { $errors = $e->array->errors('shindig/crud'); } } }
/** * Loads the “Invite” model with the given primary key * * @param primary key to load * @param dummy value to conform with Sprig * @return Model_Invite */ public static function factory($token, array $dummy = array()) { if (Model_Invite::valid($token)) { $dummy['token'] = $token; } return parent::factory('invite', $dummy); }
/** * Overload Sprig::delete() to update child articles * to become children of the uncategorized subcategory */ public function delete(Database_Query_Builder_Delete $query = NULL) { Kohana::$log->add(Kohana::DEBUG, 'Beginning subcategory deletion for subcategory_id='.$this->id); if (Kohana::$profiling === TRUE) { $benchmark = Profiler::start('blog', 'delete subcategory'); } $uncategorized = Sprig::factory('subcategory', array('name'=>'uncategorized'))->load(); // Modify category IDs for all child articles try { DB::update('articles')->value('subcategory_id', $uncategorized->id) ->where('subcategory_id', '=', $this->id)->execute(); } catch (Database_Exception $e) { Kohana::$log->add(Kohana::ERROR, 'Exception occured while modifying deleted subcategory\'s articles. '.$e->getMessage()); return $this; } if (isset($benchmark)) { Profiler::stop($benchmark); } return parent::delete($query); }
/** * Get all published articles containing this tag */ public function published(Database_Query_Builder_Select $query = NULL, $limit = 1) { $field = $this->_fields['articles']; $model = Sprig::factory($field->model); $query = !$query ? DB::select() : $query; $query->join($field->through)->on($model->fk($field->through), '=', $model->pk(TRUE))->where($this->fk($field->through), '=', $this->{$this->_primary_key}); return $model->load($query, $limit); }
public function action_details() { $plugin = Sprig::factory('plugin', array('id' => $this->request->param('id')))->load(); if (!$plugin->loaded()) { notice::add(__('Invalid Plugin'), 'error'); Request::instance()->redirect(Request::instance('admin')->uri(array('action' => 'list'))); } }
public function __construct($template = NULL, array $partials = NULL) { // Шаблон берем от метода Add $template = 'admin/benefits/add'; parent::__construct($template, $partials); // Создаем объект текущего преимущества $this->cur_benefit = Sprig::factory('benefits', array('id' => $this->id))->load()->as_array(); }
/** * Reset daily statistics */ public function action_stats_reset() { $search = Sprig::factory('blog_search'); $articles = $search->search_by_state('published'); foreach ($articles as $article) { $article->statistic->load()->reset()->update(); } }
/** * Show recent comments */ public function action_recent_comments() { Kohana::$log->add(Kohana::DEBUG, 'Executing Controller_Blog_Stats::action_recent_comments'); $this->template->content = View::factory('blog/stats/comments')->set('legend', __('Recent Comments'))->bind('comments', $comments); $limit = $this->request->param('limit', NULL); $search = Sprig::factory('blog_search'); $comments = $search->get_recent_comments($limit); }
/** * Attempt to find a page in the CMS, return the response * * @param string The url to load, will be autodetected if needed * @return void */ public function action_view($url = NULL) { if (Kohana::$profiling === TRUE) { // Start a new benchmark $benchmark = Profiler::start('Kohanut', 'Kohanut Controller'); } // If no $url is passed, default to the server request uri if ($url === NULL) { $url = $_SERVER['REQUEST_URI']; } // Trim off Kohana::$base_url $url = preg_replace('#^' . Kohana::$base_url . '#', '', $url); // Ensure no trailing slash $url = preg_replace('/\\/$/', '', $url); // Ensure no leading slash $url = preg_replace('/^\\//', '', $url); // Remove anything ofter a ? or # $url = preg_replace('/[\\?#].+/', '', $url); // Try to find what to do on this url try { // Make sure the url is clean. See http://www.faqs.org/rfcs/rfc2396.html see section 2.3 // TODO - this needs to be better if (preg_match("/[^\\/A-Za-z0-9-_\\.!~\\*\\(\\)]/", $url)) { Kohana::$log->add('INFO', "Kohanut - Request had unknown characters. '{$url}'"); throw new Kohanut_Exception("Url request had unknown characters '{$url}'", array(), 404); } // Check for a redirect on this url Sprig::factory('kohanut_redirect', array('url', $url))->go(); // Find the page that matches this url, and isn't an external link $query = DB::select()->where('url', '=', $url)->where('islink', '=', 0); $page = Sprig::factory('kohanut_page')->load($query); if (!$page->loaded()) { // Could not find page in database, throw a 404 Kohana::$log->add('INFO', "Kohanut - Could not find '{$url}' (404)"); throw new Kohanut_Exception("Could not find '{$page->url}'", array(), 404); } // Set the status to 200, rather than 404, which was set by the router with the reflectionexception Kohanut::status(200); $out = $page->render(); } catch (Kohanut_Exception $e) { // Find the error page $error = Sprig::factory('kohanut_page', array('url' => 'error'))->load(); // If i couldn't find the error page, just give a generic message if (!$error->loaded()) { Kohanut::status(404); $this->request->response = View::factory('kohanut/generic404'); return; } // Set the response $out = $error->render(); } if (isset($benchmark)) { // Stop the benchmark Profiler::stop($benchmark); } // Set the response $this->request->response = $out; }
public function input($name, $value, array $attr = NULL) { $model = Sprig::factory($this->model); $choices = $model->select_list($model->pk()); if ($this->empty) { Arr::unshift($choices, '', '-- ' . __('None')); } return Form::select($name, $choices, $this->verbose($value), $attr); }
private function update_infoblock(array $post_arr) { // Привязываем POST данные $this->cur_infoblock->values($post_arr); $this->cur_infoblock->update(); // После обновления инфоблока перегружаем его для вывода актуальной информации $this->cur_infoblock = Sprig::factory('infoblock', array('id' => $post_arr['id']))->load(); return array('text' => 'Блок информации обновлен', 'error' => 0); }
/** * Loading user by name * * @param string $username * @param string $password * @return object / NULL */ public function load_user($username, $password) { $user = Sprig::factory($this->_config['user_model'], array($this->_config['columns']['username'] => $username, $this->_config['columns']['password'] => $password)); $user->load(); if ($user->loaded()) { return $user; } else { return NULL; } }
/** * Display list of pages */ public function action_list() { Kohana::$log->add(Kohana::DEBUG, 'Executing Controller_Admin_Page::action_list'); if ($this->_internal) { $this->template->content = View::factory('cms/pages/list_widget')->bind('pages', $pages); } else { $this->template->content = View::factory('cms/pages/list')->bind('pages', $pages); } $pages = Sprig::factory('page')->load(NULL, FALSE); }
public function __construct($template = NULL, array $partials = NULL) { // Шаблон берем от метода Add $template = 'admin/banner/add'; parent::__construct($template, $partials, TRUE); // Создаем объект текущей новости $this->cur_banner = Sprig::factory('banner', array('id' => $this->id))->load()->as_array(); // Регистрируем метку о типе баннера $this->cur_banner[$this->cur_banner['type']] = TRUE; }
protected function get_have_childrens($category_id) { // Создаем объект категории $category = Sprig::factory('catalog', array('id' => $category_id))->load(); // Получение разделов-детей $childrens = $category->children; // Получаем количество детей $children_count = count($childrens); return !empty($children_count) ? true : false; }
protected function get_have_childrens($page_id) { // Создаем объект страницы $page = Sprig::factory('content', array('id' => $page_id))->load(); // Получение разделов-детей $childrens = $page->children; // Получаем количество детей $children_count = count($childrens); return !empty($children_count) ? true : false; }
/** * Tests if a username exists in the database * * @param Validation * @param string field to check * @return array */ public function username_available(Validate $array, $field) { if ($this->loaded() and !$this->changed($field)) { return TRUE; } // The value is unchanged if (Sprig::factory($this->_user_model, array($field => $array[$field]))->load(null, FALSE)->count()) { $array->error($field, 'username_available'); } }
public function update_page(array $post_arr) { // Загружаем данные о странице $page = Sprig::factory('content', array('id' => $post_arr['id']))->load(); $page->values($post_arr); $page->update(); // После добавления страницы необходимо перезагрузить ткущую категорию // Чтобы обновить список детей //$this->cur_page = Sprig::factory('content', array('id' => $this->id))->load(); return array('text' => 'Страница обновлена', 'error' => 0); }
public function action_index($slug = NULL) { $this->template->content = View::factory('projects/portfolio')->bind('list', $projects)->bind('details', $details)->bind('active', $slug); $projects = Sprig::factory('project')->select_list('slug', 'title'); if ($slug === NULL) { // Get the first project in the list $slug = key($projects); } // Get the project details via a sub-request $details = View::factory('projects/details')->bind('project', $project); $project = Sprig::factory('project', array('slug' => $slug))->load(); }
public function action_login() { $this->template->title = 'Login'; $this->template->content = View::factory('shindig/admin/login')->bind('user', $user)->bind('errors', $errors); // Load an empty user $user = Sprig::factory('user'); $post = Validate::factory($_POST)->rules('username', $user->field('username')->rules)->rules('password', $user->field('password')->rules)->callback('username', array($user, '_login')); if ($post->check()) { $this->request->redirect(Route::get('shindig/admin')->uri()); } $errors = $post->errors('auth/login'); }
/** * Generate menu for comment management */ protected function _menu() { // Get count of ham comments $ham = Sprig::factory('blog_comment', array('state' => 'ham'))->load(NULL, FALSE)->count(); $ham = $ham > 0 ? ' [' . $ham . ']' : ''; // Get count of queued comments $queued = Sprig::factory('blog_comment', array('state' => 'queued'))->load(NULL, FALSE)->count(); $queued = $queued > 0 ? ' [' . $queued . ']' : ''; // Get count of spam comments $spam = Sprig::factory('blog_comment', array('state' => 'spam'))->load(NULL, FALSE)->count(); $spam = $spam > 0 ? ' [' . $spam . ']' : ''; return View::factory('blog/admin/menu')->set('links', array('Approved Comments' . $ham => $this->request->uri(array('action' => 'approved')), 'Moderation Queue' . $queued => $this->request->uri(array('action' => 'queue')), 'Spam Comments' . $spam => $this->request->uri(array('action' => 'spam')))); }
/** * Blog management dashboard, display blog statistics */ public function action_index() { $this->template->content = View::factory('blog/admin/stats')->bind('stats', $stats); $categories = Sprig::factory('category')->load(NULL, FALSE); $tags = Sprig::factory('tag')->load(NULL, FALSE); $articles = Sprig::factory('article')->load(NULL, FALSE); $comments = Sprig::factory('blog_comment')->load(NULL, FALSE); $stats = array(); $stats['categories']['total'] = count($categories); $stats['tags']['total'] = count($tags); $stats['articles']['total'] = count($articles); $stats['comments']['total'] = count($comments); }
/** * Create root user */ public function action_root() { echo '<h1>Root Account:</h1>'; $pass = text::random('alnum', 8); $user = Sprig::factory('user')->values(array('username' => 'root', 'email' => '*****@*****.**', 'password' => $pass, 'password_confirm' => $pass, 'role' => 'admin')); try { $user->create(); echo 'Root user created, password is ' . $pass . '.'; } catch (Exception $e) { echo 'Error creating root user.'; throw $e; } }