/** * 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); }
/** * 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 __construct(array $options = NULL) { parent::__construct($options); if ($this->choices === NULL) { $this->choices = Sprig::factory($this->model)->select_list(); } }
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 __set($field, $value) { if ($field === 'password') { $value = sha1($value); } return parent::__set($field, $value); }
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 delete(Database_Query_Builder_Delete $query = NULL) { //------------------- // Add the related Component to the Autoloader-paths, so it can be found by Kohana //------------------- // Get component path $componentpath = Wi3::inst()->pathof->pagefiller("default") . "components/"; // Loop over component-modules and add the one for this specific field $dir = new DirectoryIterator($componentpath); foreach ($dir as $file) { if ($file->isDir() and !$file->isDot() and $file->getFilename() == $this->type) { Kohana::modules(Kohana::modules() + array($file->getPathname())); continue; } } // For robustness, do not assume a field-type if (!empty($this->type)) { $component = $this->getComponent(); // Send the component of this field an event notice $component->fieldevent("delete", $this); } // Finally delete the field return parent::delete($query); // Pass the create function to the parent }
/** * 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); }
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); }
/** * 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); }
/** * 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(); } }
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(); }
/** * Overload Sprig::__set() to serialize comments * * @param string variable name * @param string variable value * @return void */ public function __set($key, $value) { if ($key == 'comments') { $this->comment = serialize($value); return; } parent::__set($key, $value); }
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'))); } }
/** * 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); }
public function __SET($key, $val) { $fields = (array) $this->fields(); if (array_key_exists($key, $fields)) { return parent::__SET($key, $val); } else { return $this->{$key} = $val; } }
/** * Overload Sprig::__get() to return * * - email md5 hash for gravatar */ public function __get($name) { if ($name == 'gravatar') { $email = md5(strtolower(trim($this->email))); return $email; } else { return parent::__get($name); } }
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; } }
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; }
/** * 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); }
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; }
/** * 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'); } }
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; }
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 __get($field) { if ($field === 'post_excerpt') { if (!parent::__get('post_excerpt')) { return Text::limit_words(parent::__get('post_content'), 50, ' ...'); } } if ($field === 'link') { return Route::get('public/blog')->uri(array('slug' => $this->slug)); } return parent::__get($field); }
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'); }