http://github.com/j4mie/idiorm/ A single-class super-simple database abstraction layer for PHP. Provides (nearly) zero-configuration object-relational mapping and a fluent interface for building basic, commonly-used queries. BSD Licensed. Copyright (c) 2010, Jamie Matthews All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Example #1
0
 public function loadORM(ORM $obj, $namespace = null)
 {
     $this->setElementsBelongTo(lcfirst($namespace));
     $fields = $obj->ormFields();
     foreach ($fields as $field) {
         if ($obj->legacyORMNaming) {
             $field = preg_replace_callback('/_(.)/', create_function('$matches', 'return strtoupper($matches[1]);'), $field);
         }
         if (!is_object($obj->{$field})) {
             if (preg_match('/^date.*/', $field)) {
                 $element = $this->createElement('dateText', $field, array('label' => $this->_prettyName($field)));
             } elseif (preg_match('/.*_id$/', $field)) {
                 $element = $this->createElement('hidden', $field, array('label' => $this->_prettyName($field)));
             } else {
                 $element = $this->createElement('text', $field, array('label' => $this->_prettyName($field)));
             }
             $element->setValue($obj->{$field});
             $this->addElement($element);
         } elseif ($obj->{$field} instanceof ORM) {
             $sf = new WebVista_Form();
             $this->addSubForm($sf, "form" . ucwords($field));
             $sf->loadORM($obj->{$field}, $namespace . '[' . lcfirst($field) . ']');
         }
     }
 }
Example #2
0
 /**
  * Function for easy update a ORM object
  *
  * @param ORM $object ORM object to update
  * @param array $messages Array of custom messages
  */
 public function update(ORM $object, array $messages = array())
 {
     // Check if is a valid object
     if (!$object->loaded()) {
         Messages::warning(isset($messages['warning']) ? $messages['warning'] : 'El elemento que intentas modificar no existe o fue eliminado.');
         $this->go();
     }
     // Only if Request is POST
     if ($this->request->method() == Request::POST) {
         // Catch ORM_Validation
         try {
             // Set object values and update
             $object->values($this->request->post())->update();
             // If object is saved....
             if ($object->saved()) {
                 // Success message & redirect
                 Messages::success(isset($messages['success']) ? $messages['success'] : 'El elemento fue modificado correctamente.');
                 $this->go();
             }
         } catch (ORM_Validation_Exception $e) {
             // Error message
             if (isset($messages['error'])) {
                 Messages::error($messages['error']);
             }
             // Validation messages
             Messages::validation($e);
         }
     }
 }
Example #3
0
 public function change_status(ORM $item)
 {
     if ($item->status) {
         $item->status = false;
     } else {
         $item->status = true;
     }
     $item->save();
 }
Example #4
0
 protected function set_model($model)
 {
     $this->_model = $model;
     if ($this->_model instanceof CM_ModelContainer_Interface) {
         $this->_model = $this->_model->get_model();
     }
     if (!$this->_model instanceof ORM) {
         throw new Exception('model must be an instance of ORM');
     }
 }
Example #5
0
 public function change_status(ORM $item)
 {
     switch ($item->status) {
         case 'open':
             $item->status = 'in_process';
             break;
         case 'in_process':
             $item->status = 'closed';
             break;
         case 'closed':
             $item->status = 'open';
             break;
     }
     $item->save();
 }
Example #6
0
 public function __construct(ORM $orm, array $columns = array(), $options = array())
 {
     $this->_options = $options;
     $this->set_name($orm->object_name());
     foreach ($columns as $name => $column) {
         if (!is_array($column)) {
             $column = array('type' => $column);
         }
         $column_cfg = array('name' => $name, 'header' => Arr::get($orm->labels(), $name), 'params' => Arr::get($column, 'params', array()));
         $column = Arr::merge($column_cfg, (array) $column);
         $column = Grid_Column::factory($column);
         $this[$name] = $column;
     }
     $this->_orm = $orm;
 }
Example #7
0
 public function before()
 {
     if ($this->auto_render) {
         $hostArr = explode('.', $_SERVER['HTTP_HOST']);
         $preDomain = $hostArr[0];
         $site = ORM::factory('Site')->where('domain', '=', $preDomain)->find();
         if ($site->loaded()) {
             $this->siteId = $site->id;
             $this->category = ORM::factory('Category')->getAll($site->id, Model_Category::STATUS_SHOW);
             $site = $site->as_array();
             $site['logo'] = '/media/image/data/' . $site['logo'];
             $site['category'] = $this->category;
             $site['author'] = '简站(Simple-Site.cn) - 免费建站、微信网站、免费微信网站!';
             $site['copyright'] = 'Copyright © 2015 SimpleSite. All Rights Reserved';
             $site['friendLinks'] = ORM::factory('FriendLink')->getAll($site['id']);
             $this->theme = "themes/{$site['theme']}/";
             $this->template = View::factory($this->theme . 'base');
             foreach ($site as $key => $value) {
                 View::bind_global($key, $site[$key]);
             }
         } else {
             echo '404';
             exit;
         }
     }
 }
Example #8
0
 public function action_index()
 {
     $photos = ORM::factory('Storage')->where('publication_id', '>', '0')->find_all();
     foreach ($photos as $photo) {
         if ($photo->publication_type == 'news') {
             $news = ORM::factory('News', $photo->publication_id);
             if ($news->loaded()) {
                 $title = $news->title;
             }
         } elseif ($photo->publication_type == 'leader') {
             $page = ORM::factory('Leader', $photo->publication_id);
             if ($page->loaded()) {
                 $title = $page->name;
             }
         } else {
             $page = ORM::factory('Pages_content', $photo->publication_id);
             if ($page->loaded()) {
                 $title = $page->name;
             }
         }
         if (!isset($title)) {
             $title = I18n::get("This publication is absent");
         }
         $photo_arr[] = array('date' => $photo->date, 'path' => $photo->file_path, 'publication_id' => $photo->publication_id, 'type' => $photo->publication_type, 'title' => $title);
     }
     $this->set('photos', $photo_arr);
     $this->add_cumb('Photos', '/');
 }
Example #9
0
 public function get_findOrederName()
 {
     $PDO_coupon = ORM::factory('Coupons')->PDO();
     $query = "SELECT orders.name, orders.id\n                        FROM orders\n                         WHERE orders.id = '{$this->order_id}'";
     $result = $PDO_coupon->query($query)->fetch();
     return $result['name'];
 }
Example #10
0
 public function index()
 {
     // Get all active scheduled items
     foreach (ORM::factory('scheduler')->where('scheduler_active', '1')->find_all() as $scheduler) {
         $scheduler_id = $scheduler->id;
         $scheduler_last = $scheduler->scheduler_last;
         // Next run time
         $scheduler_weekday = $scheduler->scheduler_weekday;
         // Day of the week
         $scheduler_day = $scheduler->scheduler_day;
         // Day of the month
         $scheduler_hour = $scheduler->scheduler_hour;
         // Hour
         $scheduler_minute = $scheduler->scheduler_minute;
         // Minute
         // Controller that performs action
         $scheduler_controller = $scheduler->scheduler_controller;
         if ($scheduler_day <= -1) {
             // Ran every day?
             $scheduler_day = "*";
         }
         if ($scheduler_weekday <= -1) {
             // Ran every day?
             $scheduler_weekday = "*";
         }
         if ($scheduler_hour <= -1) {
             // Ran every hour?
             $scheduler_hour = "*";
         }
         if ($scheduler_minute <= -1) {
             // Ran every minute?
             $scheduler_minute = "*";
         }
         $scheduler_cron = $scheduler_minute . " " . $scheduler_hour . " " . $scheduler_day . " * " . $scheduler_weekday;
         //Start new cron parser instance
         $cron = new CronParser($scheduler_cron);
         $lastRan = $cron->getLastRan();
         //Array (0=minute, 1=hour, 2=dayOfMonth, 3=month, 4=week, 5=year)
         $cronRan = mktime($lastRan[1], $lastRan[0], 0, $lastRan[3], $lastRan[2], $lastRan[5]);
         if (!($scheduler_last > $cronRan - 45) || $scheduler_last == 0) {
             // within 45 secs of cronRan time, so Execute control
             $site_url = "http://" . $_SERVER['SERVER_NAME'] . "/";
             $scheduler_status = remote::status($site_url . "scheduler/" . $scheduler_controller);
             // Set last time of last execution
             $schedule_time = time();
             $scheduler->scheduler_last = $schedule_time;
             $scheduler->save();
             // Record Action to Log
             $scheduler_log = new Scheduler_Log_Model();
             $scheduler_log->scheduler_id = $scheduler_id;
             $scheduler_log->scheduler_name = $scheduler->scheduler_name;
             $scheduler_log->scheduler_status = $scheduler_status;
             $scheduler_log->scheduler_date = $schedule_time;
             $scheduler_log->save();
         }
     }
     Header("Content-Type: image/gif");
     // Transparent GIF
     echo base64_decode("R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==");
 }
Example #11
0
 static function stats()
 {
     $remaining = db::build()->from("items")->join("search_records", "items.id", "search_records.item_id", "left")->and_open()->where("search_records.item_id", "IS", null)->or_where("search_records.dirty", "=", 1)->close()->count_records();
     $total = ORM::factory("item")->count_all();
     $percent = round(100 * ($total - $remaining) / $total);
     return array($remaining, $total, $percent);
 }
Example #12
0
 static function feed($feed_id, $offset, $limit, $id)
 {
     $feed = new stdClass();
     switch ($feed_id) {
         case "latest":
             $feed->items = ORM::factory("item")->viewable()->where("type", "<>", "album")->order_by("created", "DESC")->find_all($limit, $offset);
             $all_items = ORM::factory("item")->viewable()->where("type", "<>", "album")->order_by("created", "DESC");
             $feed->max_pages = ceil($all_items->find_all()->count() / $limit);
             $feed->title = t("%site_title - Recent updates", array("site_title" => item::root()->title));
             $feed->description = t("Recent updates");
             return $feed;
         case "album":
             $item = ORM::factory("item", $id);
             access::required("view", $item);
             $feed->items = $item->viewable()->descendants($limit, $offset, array(array("type", "=", "photo")));
             $feed->max_pages = ceil($item->viewable()->descendants_count(array(array("type", "=", "photo"))) / $limit);
             if ($item->id == item::root()->id) {
                 $feed->title = html::purify($item->title);
             } else {
                 $feed->title = t("%site_title - %item_title", array("site_title" => item::root()->title, "item_title" => $item->title));
             }
             $feed->description = nl2br(html::purify($item->description));
             return $feed;
     }
 }
Example #13
0
 public function print_proxy($site_key, $file_id)
 {
     // This function retrieves the full-sized image for fotomoto.
     //   As this function by-passes normal Gallery security, a private
     //   site-key is used to try and prevent people other then fotomoto
     //   from finding the URL.
     // If the site key doesn't match, display a 404 error.
     if ($site_key != module::get_var("fotomotorw", "fotomoto_private_key")) {
         throw new Kohana_404_Exception();
     }
     // Load the photo from the provided id.  If the id# is invalid, display a 404 error.
     $item = ORM::factory("item", $file_id);
     if (!$item->loaded()) {
         throw new Kohana_404_Exception();
     }
     // If the image file doesn't exist for some reason, display a 404 error.
     if (!file_exists($item->file_path())) {
         throw new Kohana_404_Exception();
     }
     // Display the image.
     header("Content-Type: {$item->mime_type}");
     Kohana::close_buffers(false);
     $fd = fopen($item->file_path(), "rb");
     fpassthru($fd);
     fclose($fd);
 }
Example #14
0
 static function album_menu($menu, $theme)
 {
     $descendants_count = ORM::factory("item", $theme->item()->id)->descendants_count(array("type" => "photo"));
     if ($descendants_count > 1) {
         $menu->append(Menu::factory("link")->id("slideshow")->label(t("View slideshow"))->url("javascript:cooliris.embed.show(" . "{maxScale:0,feed:'" . self::_feed_url($theme) . "'})")->css_id("g-slideshow-link"));
     }
 }
Example #15
0
 public function create_comment_for_user_test()
 {
     $rand = rand();
     $root = ORM::factory("item", 1);
     $admin = user::lookup(2);
     $comment = comment::create($root, $admin, "text_{$rand}", "name_{$rand}", "email_{$rand}", "url_{$rand}");
     $this->assert_equal($admin->full_name, $comment->author_name());
     $this->assert_equal($admin->email, $comment->author_email());
     $this->assert_equal($admin->url, $comment->author_url());
     $this->assert_equal("text_{$rand}", $comment->text);
     $this->assert_equal(1, $comment->item_id);
     $this->assert_equal("REMOTE_ADDR", $comment->server_remote_addr);
     $this->assert_equal("HTTP_USER_AGENT", $comment->server_http_user_agent);
     $this->assert_equal("HTTP_ACCEPT", $comment->server_http_accept);
     $this->assert_equal("HTTP_ACCEPT_CHARSET", $comment->server_http_accept_charset);
     $this->assert_equal("HTTP_ACCEPT_ENCODING", $comment->server_http_accept_encoding);
     $this->assert_equal("HTTP_ACCEPT_LANGUAGE", $comment->server_http_accept_language);
     $this->assert_equal("HTTP_CONNECTION", $comment->server_http_connection);
     $this->assert_equal("HTTP_HOST", $comment->server_http_host);
     $this->assert_equal("HTTP_REFERER", $comment->server_http_referer);
     $this->assert_equal("HTTP_USER_AGENT", $comment->server_http_user_agent);
     $this->assert_equal("QUERY_STRING", $comment->server_query_string);
     $this->assert_equal("REMOTE_ADDR", $comment->server_remote_addr);
     $this->assert_equal("REMOTE_HOST", $comment->server_remote_host);
     $this->assert_equal("REMOTE_PORT", $comment->server_remote_port);
     $this->assert_true(!empty($comment->created));
 }
Example #16
0
 public function action_index()
 {
     $data_pages = ORM::factory('Page')->where('title_en', '=', 'contacts')->find()->as_array();
     $id = $data_pages['id'];
     $data_contacts = ORM::factory('Setting', 1)->as_array();
     if (isset($_POST['submit'])) {
         $data_pages = Arr::extract($_POST, array('seo_snippet', 'keywords', 'title_head'));
         $data_contacts = Arr::extract($_POST, array('main_adress', 'branch_adress'));
         try {
             $page = ORM::factory('Page', $id);
             $page->values($data_pages);
             $page->save();
             $contacts = ORM::factory('Setting', 1);
             $contacts->values($data_contacts);
             $contacts->save();
             Controller::redirect('admin/contacts');
         } catch (ORM_Validation_Exception $e) {
             $errors = $e->errors('validation');
         }
     }
     $content = View::factory('admin/contacts/v_contacts_edit');
     $content->bind('errors', $errors);
     $content->bind('data_pages', $data_pages);
     $content->bind('data_contacts', $data_contacts);
     $this->template->page_title = 'Контакты';
     $this->template->block_center = array($content);
 }
Example #17
0
 /**
  * Create a new comment.
  * @param Item_MOdel $item         the parent item
  * @param User_Model $author       the author User_Model
  * @param string     $text         comment body
  * @param string     $guest_name   guest's name (if the author is a guest user, default empty)
  * @param string     $guest_email  guest's email (if the author is a guest user, default empty)
  * @param string     $guest_url    guest's url (if the author is a guest user, default empty)
  * @return Comment_Model
  */
 static function create($item, $author, $text, $guest_name = null, $guest_email = null, $guest_url = null)
 {
     $comment = ORM::factory("comment");
     $comment->author_id = $author->id;
     $comment->guest_email = $guest_email;
     $comment->guest_name = $guest_name;
     $comment->guest_url = $guest_url;
     $comment->item_id = $item->id;
     $comment->text = $text;
     $comment->state = "published";
     // These values are useful for spam fighting, so save them with the comment.
     $input = Input::instance();
     $comment->server_http_accept = substr($input->server("HTTP_ACCEPT"), 0, 128);
     $comment->server_http_accept_charset = substr($input->server("HTTP_ACCEPT_CHARSET"), 0, 64);
     $comment->server_http_accept_encoding = substr($input->server("HTTP_ACCEPT_ENCODING"), 0, 64);
     $comment->server_http_accept_language = substr($input->server("HTTP_ACCEPT_LANGUAGE"), 0, 64);
     $comment->server_http_connection = substr($input->server("HTTP_CONNECTION"), 0, 64);
     $comment->server_http_host = substr($input->server("HTTP_HOST"), 0, 64);
     $comment->server_http_referer = substr($input->server("HTTP_REFERER"), 0, 255);
     $comment->server_http_user_agent = substr($input->server("HTTP_USER_AGENT"), 0, 128);
     $comment->server_query_string = substr($input->server("QUERY_STRING"), 0, 64);
     $comment->server_remote_addr = substr($input->server("REMOTE_ADDR"), 0, 32);
     $comment->server_remote_host = substr($input->server("REMOTE_HOST"), 0, 64);
     $comment->server_remote_port = substr($input->server("REMOTE_PORT"), 0, 16);
     $comment->save();
     return $comment;
 }
Example #18
0
 /**
  * Send register sms
  * @param $mobile
  * @param $event
  * @return bool
  */
 public function sendEventSMS($mobile, $event)
 {
     if (empty($mobile) || !isset(self::$types[$event])) {
         return 4001;
     }
     # Detection is already register
     $user = ORM::factory('user');
     $count = $user->where('mobile', '=', $mobile)->find_all()->count();
     if (empty($count)) {
         $cache = Cache::instance();
         $lastSendTime = $cache->get(self::$types[$event]['sendTimeKey'] . $mobile);
         if (!empty($lastSendTime) && time()->{$lastSendTime} < self::MIN_SEND_TIME) {
             return 2001;
         }
         $code = substr(str_shuffle('0123456789'), 0, 6);
         if (self::sendSMS($mobile, $code, self::$types[$event]['tplID']) === TRUE) {
             $cache->set(self::$types[$event]['codeKey'] . $mobile, $code);
             $cache->set(self::$types[$event]['sendTimeKey'] . $mobile, time());
             return TRUE;
         } else {
             return 2003;
         }
     } else {
         return 2000;
     }
 }
Example #19
0
 /**
  * Task to run pending migrations
  *
  * @return null
  */
 protected function _execute(array $params)
 {
     $migrations = new MigrationManager();
     Database::$default = $params['db'];
     $this->db = Database::instance();
     $db_config = Kohana::$config->load('database')->{$params['db']};
     if (!ORM::factory('Migration')->is_installed()) {
         /**
          * Get platform from database config
          */
         $platform = strtolower($db_config['type']);
         if ('mysqli' == $platform) {
             $platform = 'mysql';
         }
         /**
          * Get SQL from file for selected platform
          */
         $file = realpath(substr(__DIR__, 0, strlen(__DIR__) - strlen('classes/Task/Db')) . 'sql/' . $platform . '.sql');
         $handle = fopen($file, 'rb');
         $sql_create = fread($handle, filesize($file));
         $this->db->query(0, $sql_create);
         $msg = Minion_CLI::color("-----------------------------\n", 'green');
         $msg .= Minion_CLI::color("| Migration table create!!! |\n", 'green');
         $msg .= Minion_CLI::color("-----------------------------\n", 'green');
         Minion_CLI::write($msg);
     }
     $migrations->migrate($params['db'], $params['step']);
 }
Example #20
0
 public static function checkExist($field, $value, $id = '')
 {
     $flag = 'true';
     $model = ORM::factory('tool_link');
     if (!empty($id)) {
         $model->where('id', '!=', $id);
     }
     //如果是关键词名称
     if ($field == 'title') {
         $arr = $model->get_all();
         $tarr = array();
         foreach ($arr as $row) {
             $title = explode(',', $row['title']);
             foreach ($title as $v) {
                 array_push($tarr, $v);
             }
         }
         if (in_array($value, $tarr)) {
             $flag = 'false';
         }
     } else {
         $model->and_where($field, '=', $value)->find();
         if ($model->loaded() && !empty($model->id)) {
             $flag = 'false';
         }
     }
     return $flag;
 }
Example #21
0
 public function after_submit()
 {
     Email::send($this->get_field('email')->get_value()->get_raw(), array('*****@*****.**', 'zgol-web.by'), $this->get_field('subject')->get_value()->get_raw(), $this->get_field('answer')->get_value()->get_raw(), TRUE);
     $model = ORM::factory('Feedback')->where('id', '=', $this->_model->id)->find();
     $model->answers++;
     $model->save();
 }
 /**
  * List first 15 twitter messages.
  *
  * @return array
  */
 private function _list_twitter_msgs()
 {
     $ret_json_or_xml = '';
     // Will hold the return JSON/XML string
     $items = ORM::factory('message')->where('service_id', '3')->where('message_type', '1')->orderby('message_date', 'desc')->find_all($this->list_limit);
     // Set the no. of records fetched
     $this->record_count = $items->count();
     $json_categories = array();
     $i = 0;
     //No record found.
     if ($items->count() == 0) {
         $this->response_data = $this->response(4);
         return;
     }
     foreach ($items as $twitter) {
         if ($response_type == 'json') {
             $json_categories[] = array("twitter" => $item);
         } else {
             $json_categories['twitter' . $i] = array('twitter' => $twitter);
             $this->replar[] = 'twitter' . $i;
         }
     }
     // Create the json array
     $data = array("payload" => array("domain" => $this->domain, "count" => $json_categories), "error" => $this->api_service->get_error_msg(0));
     if ($this->response_type == 'json') {
         $ret_json_or_xml = $this->array_as_json($data);
     } else {
         $ret_json_or_xml = $this->array_as_xml($data, $this->replar);
     }
     $this->response_data = $ret_json_or_xml;
 }
Example #23
0
 public static function documents(array $data = array())
 {
     if ($data) {
         $document = ORM::factory('document')->join('documents_courses')->on('documents.id', '=', 'documents_courses.document_id')->join('documents_roles')->on('documents.id', '=', 'documents_roles.document_id');
         if (isset($data['filter_by']) && $data['filter_by']) {
             $document->join('users')->on('documents.user_id', '=', 'users.id');
         }
         if (isset($data['course'])) {
             $course = $data['course'] instanceof Model_Course ? $data['course'] : ORM::factory('course', (int) $data['course']);
             $document->where('documents_courses.course_id', '=', $course->id);
         }
         if (isset($data['role'])) {
             $role = $data['role'] instanceof Model_Role ? $data['role'] : ORM::factory('role', (int) $data['role']);
             $document->where('documents_roles.role_id', '=', $role->id);
         }
         if (isset($data['filter_title']) && $data['filter_title']) {
             $document->where('documents.title', 'LIKE', '%' . $data['filter_title'] . '%');
         }
         if (isset($data['filter_by']) && $data['filter_by']) {
             $document->where('users.firstname', 'LIKE', '%' . $data['filter_by'] . '%');
         }
         $document->group_by('documents.id');
         return $document->find_all();
     } else {
         return ORM::factory('document')->find_all();
     }
 }
 public function test_check_answer()
 {
     $ques = ORM::factory('question', 10);
     $question = Question::factory($ques);
     $submitted = array(0 => array(0 => "s dasda s", 1 => "asd asd"), 1 => array(0 => "asd asdasdasd", 1 => "asda sasdasd"), 2 => array(0 => "dsf dsdfsdfsdf", 1 => "sa asasd assad"));
     $this->assertTrue($question->check_answer($submitted));
 }
Example #25
0
 protected function _execute()
 {
     if (!isset($this->_data->email) or !$this->_data->email or !isset($this->_data->password) or !$this->_data->password) {
         throw new Exception("Login error: missing email and/or password.");
     }
     $user = ORM::Factory('user')->where('email', 'LIKE', $this->_data->email)->find();
     if (!$user->loaded()) {
         throw new Exception("Login error: that email address was not found.");
     }
     if ($user->password != $this->_beans_auth_password($user->id, $this->_data->password)) {
         throw new Exception("Login error: that password was incorrect.");
     }
     if (!$user->role->loaded()) {
         throw new Exception("Login error: that user does not have any defined role.");
     }
     if ($user->password_change) {
         $user->reset = $this->_generate_reset($user->id);
         $user->reset_expiration = time() + 2 * 60;
         $user->save();
         return (object) array("reset" => $user->reset);
     }
     $expiration = $user->role->auth_expiration_length != 0 ? time() + $user->role->auth_expiration_length : rand(11111, 99999);
     $user->auth_expiration = $expiration;
     $user->save();
     return (object) array("auth" => $this->_return_auth_element($user, $expiration));
 }
Example #26
0
 public function delete_tool()
 {
     if ($this->loaded) {
         ORM::factory('calendar_item')->where(array('fk_site' => $this->fk_site, 'calendar_id' => $this->id))->delete_all();
         return parent::delete($this->id);
     }
 }
Example #27
0
 public function action_login()
 {
     // Проверям, вдруг пользователь уже зашел
     if (Auth::instance()->logged_in()) {
         // И если это так, то отправляем его сразу на страницу пользователей
         return $this->redirect('/visiter');
     }
     // Если же пользователь не зашел, но данные на страницу пришли, то:
     if ($_POST) {
         // Создаем переменную, отвечающую за связь с моделью данных User
         $user = ORM::factory('User');
         // в $status помещаем результат функции login
         $status = Auth::instance()->login($_POST['username'], $_POST['password']);
         // Если логин успешен, то
         if ($status) {
             // Отправляем пользователя на его страницу
             $this->redirect('/visiter');
         } else {
             // Иначе ничего не получилось, пишем failed
             $this->template->content = 'failed';
         }
     }
     // Грузим view логина
     $content = View::factory('/pages/login');
     $this->template->content = $content;
 }
Example #28
0
 public function getParam($mid, $pid)
 {
     //получаем значения
     $values = DB::select('value')->from('group_param_values')->where('mid', '=', $mid)->and_where('pid', '=', $pid)->execute()->current();
     $prices = ORM::factory('Prices')->where('id', '=', $values['value'])->find();
     return $prices->value / 100;
 }
Example #29
0
 public function random($item_id)
 {
     $item = ORM::factory("item", $item_id);
     access::required("view", $item);
     item::set_display_context_callback("Albums_Controller::get_display_context");
     url::redirect($item->abs_url());
 }
Example #30
0
 /**
  * Add new action
  */
 public function action_add()
 {
     $data = array();
     //get all sys controller available
     $controllers = ORM::factory('SysController')->find_all();
     $_c = array();
     foreach ($controllers as $ctl) {
         $_c[$ctl->id] = $ctl->name;
     }
     $data['controllers'] = $_c;
     unset($_c);
     unset($controllers);
     //if page is post back
     if ($_POST) {
         $controlder_id = $_POST['controller'];
         $_sysA = new Model_SysAction();
         $post = $_sysA->validate_create($_POST);
         if ($post->check()) {
             $_sysA->values($post);
             $controller = new Model_SysController($controlder_id);
             $_sysA->controller = $controller;
             $_sysA->save_create();
             Request::instance()->redirect('sysaction/index');
         } else {
             $data['errors'] = $post->errors('sysaction/add');
             #Repopulate $_POST data
             $_POST = $post->as_array();
             //fix not show selected index after post
             $_POST['controller'] = $controlder_id;
         }
     }
     $this->template->title = 'Add Action in Controller';
     $view = View::factory('pages/sysaction/add', $data);
     $this->template->content = $view->render();
 }