Example #1
0
 /**
  * The index action
  * 
  * @access public
  * @return void
  */
 public function action_index()
 {
     $settings = \Config::load('autoresponder.db');
     // $autoResponder = Model_Setting::find(array('where' => array(array('meta_key', '=', 'auto-responders'))));
     if (\Input::post()) {
         $input = \Input::post();
         if (!\Input::is_ajax()) {
             $val = Model_Setting::validate('create');
             if (!$val->run()) {
                 if ($val->error() != array()) {
                     // show validation errors
                     \Messages::error('<strong>There was an error while trying to create settings</strong>');
                     foreach ($val->error() as $e) {
                         \Messages::error($e->get_message());
                     }
                 }
             } else {
                 try {
                     \Config::save('autoresponder.db', array('logo_url' => $input['logo_url'], 'company_name' => $input['company_name'], 'address' => $input['address'], 'website' => $input['website'], 'phone' => $input['phone'], 'email_address' => $input['email_address'], 'sender_email_address' => $input['sender_email_address'], 'contact_us_email_address' => $input['contact_us_email_address'], 'instagram_account_name' => $input['instagram_account_name'], 'facebook_account_name' => $input['facebook_account_name']));
                     // $setting->save();
                     \Messages::success('Settings successfully created.');
                     \Response::redirect('admin/settings');
                 } catch (\Database_Exception $e) {
                     // show validation errors
                     \Messages::error('<strong>There was an error while trying to create settings.</strong>');
                     // Uncomment lines below to show database errors
                     $errors = $e->getMessage();
                     \Messages::error($errors);
                 }
             }
         }
     }
     \View::set_global('title', 'Settings');
     \Theme::instance()->set_partial('content', $this->view_dir . 'index')->set('settings', $settings, false);
 }
Example #2
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 #3
0
 /**
  * Application initialization
  *     - Loads the plugins
  *     - Sets the cookie configuration
  */
 public static function init()
 {
     // Set defaule cache configuration
     Cache::$default = Kohana::$config->load('site')->get('default_cache');
     try {
         $cache = Cache::instance()->get('dummy' . rand(0, 99));
     } catch (Exception $e) {
         // Use the dummy driver
         Cache::$default = 'dummy';
     }
     // Load the plugins
     Swiftriver_Plugins::load();
     // Add the current default theme to the list of modules
     $theme = Model_Setting::get_setting('site_theme');
     if ($theme != "default") {
         Kohana::modules(array_merge(array('themes/' . $theme->value => THEMEPATH . $theme->value), Kohana::modules()));
     }
     // Clean up
     unset($active_plugins, $theme);
     // Load the cookie configuration
     $cookie_config = Kohana::$config->load('cookie');
     Cookie::$httponly = TRUE;
     Cookie::$salt = $cookie_config->get('salt', Swiftriver::DEFAULT_COOKIE_SALT);
     Cookie::$domain = $cookie_config->get('domain') or '';
     Cookie::$secure = $cookie_config->get('secure') or FALSE;
     Cookie::$expiration = $cookie_config->get('expiration') or 0;
     // Set the default site locale
     I18n::$lang = Model_Setting::get_setting('site_locale');
 }
Example #4
0
 static function media_get($media_id)
 {
     require_once PATH_LIBS . "/wechat/jssdk.php";
     $jssdk = new JSSDK(Model_Setting::get("WX_APPID"), Model_Setting::get("WX_APPSECRET"));
     $url = $jssdk->media_get($media_id);
     return $url;
 }
Example #5
0
 public function action_index()
 {
     $this->template->header->css = Html::style("themes/default/media/css/home.css");
     $this->template->header->title = __('Welcome');
     $this->template->content = View::factory('pages/welcome/main');
     $this->template->content->set(array('public_registration_enabled' => (bool) Model_Setting::get_setting('public_registration_enabled'), 'anonymous' => $this->anonymous));
 }
Example #6
0
	public function action_new()
	{
		if (Input::post('contents'))
		{
			if (Input::post('dont-fill-this-out'))
			{
				die ('I told you not to fill it out.');
			}
			$last_scrap = Model_Setting::find(1);
			$last_short_id = ($last_scrap === NULL) ? 0 : $last_scrap->last_short_id;

			$short_id = Scrapyrd::inc($last_short_id);
			$contents = Input::post('contents');
			$private = Input::post('private', '0');

			if ($private != '0')
			{
				$short_id = sha1($contents.microtime(true));
			}
			else
			{
				$last_scrap->last_short_id = $short_id;
				$last_scrap->save();
			}

			$user_id = null;
			if ($this->template->logged_in)
			{
				$user_id = Session::get('user_id');
			}

			$scrap = new Model_Scrap;
			$scrap->contents = $contents;
			$scrap->short_id = $short_id;
			$scrap->type = Input::post('type');
			$scrap->private = $private;
			$scrap->created_at = time();
			$scrap->updated_at = time();
			$scrap->user_id = $user_id;
			$scrap->views = 0;
			$scrap->save();
			
			if (Fuel::$env === Fuel::PRODUCTION)
			{
				Response::redirect('http://scrp.at/'.$short_id);
			}
			else
			{
				Response::redirect($short_id);
			}
		}
		else
		{
			$this->template->title = 'Error';
			$this->template->content = 'Cannot create an empty Scrap!';
		}
	}
Example #7
0
 /**
  * The before() method is called before main controller action.
  * In our template controller we override this method so that we can
  * set up default values. These variables are then available to our
  * controllers if they need to be modified.
  *
  * @return	void
  */
 public function before()
 {
     // Execute parent::before first
     parent::before();
     if (strtolower(Kohana::$config->load('auth.driver')) == 'riverid') {
         $this->riverid_auth = TRUE;
     }
     $this->template->content = View::factory('pages/login/layout');
     $this->template->content->public_registration_enabled = Model_Setting::get_setting('public_registration_enabled');
 }
 public function action_delete($id = null)
 {
     if ($setting = Model_Setting::find($id)) {
         $setting->delete();
         Session::set_flash('success', e('Deleted setting #' . $id));
     } else {
         Session::set_flash('error', e('Could not delete setting #' . $id));
     }
     Response::redirect('admin/settings');
 }
Example #9
0
 /**
  * Logs a user in.
  *
  * @param   string   email
  * @param   string   password
  * @param   boolean  enable autologin
  * @return  boolean
  */
 protected function _login($email, $password, $remember)
 {
     $riverid_api = RiverID_API::instance();
     // Fallback to local auth if user is in the exemption list
     if (in_array($email, Kohana::$config->load('auth.exempt'))) {
         return parent::_login($email, $password, $remember);
     }
     // Check if the email is registered on RiverID
     if ($riverid_api->is_registered($email)) {
         // Success! Proceed to sign in into RiverID
         $login_response = $riverid_api->signin($email, $password);
         if ($login_response and $login_response['status']) {
             // Get the user object that matches the provided email and RiverID
             $user = ORM::factory('user')->where('email', '=', $email)->where('riverid', '=', $login_response['user_id'])->find();
             // User does not exist locally but authenticates via RiverID, create user
             if (!$user->loaded()) {
                 // Check if the email is already registered locally
                 // If so, this will simply append a riverid
                 $user = ORM::factory('user')->where('email', '=', $email)->find();
                 // Only auto register if the site allows it
                 if (!(bool) Model_Setting::get_setting('public_registration_enabled') and !$user->loaded()) {
                     return FALSE;
                 }
                 $user->username = $user->email = $email;
                 $user->riverid = $login_response['user_id'];
                 $user->save();
                 // Allow the user be able to login immediately
                 $login_role = ORM::factory('role', array('name' => 'login'));
                 if (!$user->has('roles', $login_role)) {
                     $user->add('roles', $login_role);
                 }
             }
             // User exists locally and authenticates via RiverID so complete the login
             if ($user->has('roles', ORM::factory('role', array('name' => 'login')))) {
                 if ($remember === TRUE) {
                     // Token data
                     $data = array('user_id' => $user->id, 'expires' => time() + $this->_config['lifetime'], 'user_agent' => sha1(Request::$user_agent));
                     // Create a new autologin token
                     $token = ORM::factory('user_token')->values($data)->create();
                     // Set the autologin cookie
                     Cookie::set('authautologin', $token->token, $this->_config['lifetime']);
                 }
                 // Finish the login
                 $this->complete_login($user);
                 return TRUE;
             }
         }
     }
     return FALSE;
 }
 static function get_all($refresh = false)
 {
     if (empty(static::$settings) === true || $refresh === true) {
         $settings = Model_Setting::query()->get();
         $get_settings = array();
         if (empty($settings) === false) {
             foreach ($settings as $setting) {
                 if ($setting->data == 1) {
                     $setting->data = true;
                 }
                 $get_settings[$setting->name] = $setting->data;
             }
         }
         static::$settings = $get_settings;
     }
     return static::$settings;
 }
Example #11
0
 public function action_index()
 {
     if (!$this->current_user->group->is_admin) {
         return $this->no_permission();
     }
     $this->title('Settings');
     $this->view = $this->theme->view('admin/settings/index');
     if (Input::param() != array()) {
         foreach (Input::param('settings') as $setting => $value) {
             $s = Model_Setting::find('first', array('where' => array('setting' => $setting)));
             $s->value = $value;
             $s->save();
         }
         Session::set_flash('success', 'Settings saved');
         Response::redirect(Uri::current());
     }
 }
 public static function update($settings)
 {
     foreach ($settings as $setting => $data) {
         $update_setting = Model_Setting::query()->where('name', $setting)->get_one();
         if (empty($data) === true) {
             $data = '';
         } elseif ($data == 'on') {
             $data = true;
         }
         // Update setting
         if (empty($update_setting) === false) {
             $update_setting->data = $data;
         } else {
             $update_setting = Model_Setting::Forge(array('name' => $setting, 'data' => $data));
         }
         $update_setting->save();
     }
 }
Example #13
0
 static function convert_gps($latx, $lngy)
 {
     //PtApp::$setting['qq_map']['key_service']
     $key = Model_Setting::get("qq_map_key_service1");
     if (!$key) {
         Model_Setting::add("qq_map_key_service1", "I6OBZ-EFNHR-JAZWY-WHLXW-O3TOH-EIFLA", "QQ地图 SERVICE KEY");
         Model_Setting::add("qq_map_key_js", "66DBZ-IG7WJ-G2CFQ-KVS4Z-PBQA5-WQFLR", "QQ地图 JS KEY");
     }
     $url = "http://apis.map.qq.com/ws/coord/v1/translate";
     $data = array("locations" => $latx . "," . $lngy, "type" => 1, "key" => $key);
     $curl = new Curl();
     $url = $url . "?" . http_build_query($data);
     $res = $curl->get($url);
     $body = json_decode($res['body']);
     if ($body->status > 0) {
         throw new Exception($body->message);
     }
     return $body->locations[0];
 }
Example #14
0
 /**
  * List all the available settings
  *
  * @return  void
  */
 public function action_index()
 {
     $this->template->header->title = __('Application Settings');
     $this->settings_content = View::factory('pages/settings/main')->bind('action_url', $action_url);
     $this->active = 'main';
     $action_url = URL::site('settings/main/manage');
     // Setting items
     $settings = array('site_name' => '', 'site_locale' => '', 'public_registration_enabled' => '', 'anonymous_access_enabled' => '', 'river_active_duration' => '', 'river_expiry_notice_period' => '');
     if ($this->request->post()) {
         // Setup validation for the application settings
         $validation = Validation::factory($this->request->post())->rule('site_name', 'not_empty')->rule('site_locale', 'not_empty')->rule('river_active_duration', 'not_empty')->rule('river_active_duration', 'digit')->rule('river_expiry_notice_period', 'not_empty')->rule('river_expiry_notice_period', 'digit')->rule('form_auth_token', array('CSRF', 'valid'));
         if ($validation->check()) {
             // Set the setting key values
             $settings = array('site_name' => $this->request->post('site_name'), 'site_locale' => $this->request->post('site_locale'), 'public_registration_enabled' => $this->request->post('public_registration_enabled') == 1, 'anonymous_access_enabled' => $this->request->post('anonymous_access_enabled') == 1, 'river_active_duration' => $this->request->post('river_active_duration'), 'river_expiry_notice_period' => $this->request->post('river_expiry_notice_period'));
             // Update the settings
             Model_Setting::update_settings($settings);
             $this->settings_content->set('messages', array(__('The site settings have been updated.')));
         } else {
             $this->settings_content->set('errors', $validation->errors('user'));
         }
     }
     $this->settings_content->settings = Model_Setting::get_settings(array_keys($settings));
 }
Example #15
0
 public function action_set()
 {
     $tagName = filter_input(INPUT_POST, "tag", FILTER_SANITIZE_STRING);
     $tag = ORM::factory("tag")->where("name", "LIKE", $tagName)->find();
     if ($tagName == "") {
         Model_Setting::setSetting(Model_Setting::MVP_TAG, "");
         Message::set(Message::SUCCESS, "MVP tag set.");
         $this->request->redirect("admin/mvp");
     }
     if (!$tag->loaded()) {
         Message::set(Message::ERROR, "Tag {$tagName} could not be found.");
         $this->request->redirect("admin/mvp");
         return;
     }
     if ($tag->photos->count_all() < 2) {
         Message::set(Message::ERROR, "{$tagName} does not have enough images to use.");
         $this->request->redirect("admin/mvp");
         return;
     }
     Model_Setting::setSetting(Model_Setting::MVP_TAG, $tag->id);
     Message::set(Message::SUCCESS, "MVP tag set.");
     $this->request->redirect("admin/mvp");
 }
Example #16
0
 /**
  * Perform the maintenance
  */
 public function action_run()
 {
     if (php_sapi_name() !== 'cli') {
         Kohana::$log->add(Log::ERROR, __("Maintenance must be run in CLI mode"));
         exit;
     }
     Kohana::$log->add(Log::INFO, __("Running river maintenance schedule"));
     // Get settings
     $settings = Model_Setting::get_settings(array('river_active_duration', 'river_expiry_notice_period', 'site_url'));
     $notice_period = $settings['river_expiry_notice_period'];
     $site_url = $settings['site_url'];
     // Templates for the notifications
     $warning_template = View::factory('emails/expiry_warning');
     $notice_template = View::factory('emails/expiry_notice');
     // Fix the current date to the time when the maintenance
     // is being run
     $current_date_timestamp = time();
     $current_date = date("Y-m-d H:i:s", $current_date_timestamp);
     // Compute the filter date
     $filter_date_timestamp = strtotime(sprintf("+%s day", $notice_period), $current_date_timestamp);
     $filter_date = date("Y-m-d H:i:s", $filter_date_timestamp);
     // Get the rivers that have expired or are about to expire
     $candidates = ORM::factory('river')->where('river_expired', '=', 0)->where('river_date_expiry', '<=', $filter_date)->find_all();
     $to_be_expired = array();
     $to_be_flagged = array();
     $rivers = array();
     foreach ($candidates as $river) {
         $days_to_expiry = $river->get_days_to_expiry($current_date);
         $river_url = $site_url . $river->get_base_url();
         // Generate extension token and modify the URL
         if ($days_to_expiry === 0) {
             $token = hash("sha256", Text::random('alnum', 32));
             $river_url .= '/extend?token=' . $token;
             $to_be_expired[$river->id] = $token;
         } else {
             // Is the river to be flagged for expiry
             if ($days_to_expiry > 0 and $river->expiry_candidate == 0) {
                 $to_be_flagged[] = $river->id;
             } else {
                 continue;
             }
         }
         $rivers[$river->id] = array('river_name' => $river->river_name, 'river_url' => $river_url, 'days_to_expiry' => $days_to_expiry);
     }
     // If no rivers found, terminate
     if (count($rivers) == 0) {
         Kohana::$log->add(Log::INFO, __("No rivers found. Exiting..."));
         return;
     }
     // Get the owners for each of the rivers
     $river_owners = $this->_get_river_owners(array_keys($rivers));
     // Expire rivers
     if (count($to_be_expired) > 0) {
         $this->_expire_rivers($to_be_expired);
     }
     // Switch on the expiry flag
     if (count($to_be_flagged) > 0) {
         DB::update('rivers')->set(array('expiry_candidate' => 1))->where('id', 'IN', $to_be_flagged)->execute();
     }
     // Send out notifications
     Kohana::$log->add(Log::INFO, __("Sending out notifications"));
     foreach ($river_owners as $river_id => $owners) {
         $data = $rivers[$river_id];
         // Mail subject
         $subject = __("Your :river_name river will shutdown in :days_to_expiry day(s)!", array(":river_name" => $data['river_name'], ":days_to_expiry" => $data['days_to_expiry']));
         // Mail body - expiry warning is the default
         $mail_body = $warning_template->set(array('river_name' => $data['river_name'], 'days_to_expiry' => $data['days_to_expiry'], 'active_duration' => $settings['river_active_duration'], 'river_url' => $data['river_url']));
         if ($data['days_to_expiry'] === 0) {
             $subject = __("Your :river_name has shutdown!", array(":river_name" => $data['river_name']));
             // Expiry notice message
             $mail_body = $notice_template->set(array('river_name' => $data['river_name'], 'active_duration' => $settings['river_active_duration'], 'activation_url' => $data['river_url']));
         }
         // Construct the mail body
         foreach ($owners as $owner) {
             $mail_body->recipient_name = $owner['name'];
             Swiftriver_Mail::send($owner['email'], $subject, $mail_body);
         }
     }
     Kohana::$log->add(Log::INFO, "Completed maintenance schedule");
 }
Example #17
0
 private function _update_settings()
 {
     // Validate current password
     $validated = FALSE;
     $current_password = $_POST['current_password'];
     if ($this->riverid_auth) {
         $response = RiverID_API::instance()->signin($this->user->email, $_POST['current_password']);
         $validated = ($response and $response['status']);
     } else {
         $validated = Auth::instance()->hash($current_password) == $this->user->password;
     }
     if (!$validated) {
         $this->errors = __('Current password is incorrect');
         return;
     }
     $messages = array();
     // Password is changing and we are using RiverID authentication
     if (!empty($_POST['password']) or !empty($_POST['password_confirm'])) {
         $post = Model_Auth_User::get_password_validation($_POST);
         if (!$post->check()) {
             $this->errors = $post->errors('user');
             return;
         }
         // Are we using RiverID?
         if ($this->riverid_auth) {
             $resp = RiverID_API::instance()->change_password($this->user->email, $_POST['current_password'], $_POST['password']);
             if (!$resp['status']) {
                 $this->errors = $resp['error'];
                 return;
             }
             // For API calls below, use this new password
             $current_password = $_POST['password'];
             unset($_POST['password'], $_POST['password_confirm']);
         }
     }
     // Email address is changing
     if ($_POST['email'] != $this->user->email) {
         $new_email = $_POST['email'];
         if (!Valid::email($new_email)) {
             $this->errors = __('Invalid email address');
             return;
         }
         if ($this->riverid_auth) {
             // RiverID email change process
             $mail_body = View::factory('emails/changeemail')->bind('secret_url', $secret_url);
             $secret_url = url::site('login/changeemail/' . urlencode($this->user->email) . '/' . urlencode($new_email) . '/%token%', TRUE, TRUE);
             $site_email = Kohana::$config->load('useradmin.email_address');
             $mail_subject = __(':sitename: Email Change', array(':sitename' => Model_Setting::get_setting('site_name')));
             $resp = RiverID_API::instance()->change_email($this->user->email, $new_email, $current_password, $mail_body, $mail_subject, $site_email);
             if (!$resp['status']) {
                 $this->errors = $resp['error'];
                 return;
             }
         } else {
             // Make sure the new email address is not yet registered
             $user = ORM::factory('user', array('email' => $new_email));
             if ($user->loaded()) {
                 $this->errors = __('The new email address has already been registered');
                 return;
             }
             $auth_token = Model_Auth_Token::create_token('change_email', array('new_email' => $new_email, 'old_email' => $this->user->email));
             if ($auth_token->loaded()) {
                 // Send an email with a secret token URL
                 $mail_body = View::factory('emails/changeemail')->bind('secret_url', $secret_url);
                 $secret_url = URL::site('login/changeemail/' . urlencode($this->user->email) . '/' . urlencode($new_email) . '/' . $auth_token->token, TRUE, TRUE);
                 // Send email to the user using the new address
                 $mail_subject = __(':sitename: Email Change', array(':sitename' => Model_Setting::get_setting('site_name')));
                 Swiftriver_Mail::send($new_email, $mail_subject, $mail_body);
             } else {
                 $this->errors = __('Error');
                 return;
             }
             $messages[] = __("A confirmation email has been sent to :email", array(':email' => $new_email));
         }
         // Don't change email address immediately.
         // Only do so after the tokens sent above are validated
         unset($_POST['email']);
     }
     // END if - email address change
     // Nickname is changing
     if ($_POST['nickname'] != $this->user->account->account_path) {
         $nickname = $_POST['nickname'];
         // Make sure the account path is not already taken
         $account = ORM::factory('account', array('account_path' => $nickname));
         if ($account->loaded()) {
             $this->errors = __('Nickname is already taken');
             return;
         }
         // Update
         $this->user->account->account_path = $nickname;
         $this->user->account->save();
     }
     $this->user->update_user($_POST, array('name', 'password', 'email'));
     $messages[] = __("Account settings were saved successfully.");
     Session::instance()->set("messages", $messages);
     $this->request->redirect(URL::site($this->user->account->account_path . '/settings'));
 }
Example #18
0
 * This file was automatically generated By Code Smith 
 * Modifications will be overwritten when code smith is run
 *
 * PLEASE DO NOT MAKE MODIFICATIONS TO THIS FILE
 * Date Created 5/6/2012
 *
 */
/// <summary>
/// Implementations of slsettings represent a Setting
///
/// </summary>
chdir("..");
/* TODO: Add code here */
require 'config/globalconfig.php';
include_once 'class/model_setting.php';
$objSetting = new Model_Setting($objConnection);
if ($_pgR["act"] == model_Setting::ACT_ADD) {
    if (global_common::isCLogin()) {
        //get user info
        //$c_userInfo = $_SESSION[consts::SES_C_USERINFO];
        //if ($objMenu->getMenuByName($_pgR['name'])) {
        //	echo global_common::convertToXML($arrHeader, array("rs",'info'), array(0,global_common::STRING_NAME_EXIST), array(0,1));
        //	return;
        //}
        $settingID = $_pgR['SettingID'];
        $settingID = global_editor::rteSafe(html_entity_decode($settingID, ENT_COMPAT, 'UTF-8'));
        $settingName = $_pgR['SettingName'];
        $settingName = global_editor::rteSafe(html_entity_decode($settingName, ENT_COMPAT, 'UTF-8'));
        $settingValue = $_pgR['SettingValue'];
        $settingValue = global_editor::rteSafe(html_entity_decode($settingValue, ENT_COMPAT, 'UTF-8'));
        $status = $_pgR['Status'];
Example #19
0
 /**
  * Test REST interface.
  * 
  * @return void
  */
 public function testREST()
 {
     testpack('Test new Resty BeanCan');
     $user = R::dispense('user');
     $user->name = 'me';
     $site = R::dispense('site');
     $site->name = 'site 1';
     $page = R::dispense('page');
     $page->name = 'page 1';
     $ad = R::dispense('ad');
     $ad->name = 'an ad';
     $ad2 = R::dispense('ad');
     $ad2->name = 'an ad2';
     $page->sharedAd[] = $ad;
     $page->sharedAd[] = $ad2;
     $site->ownPage[] = $page;
     $user->ownSite[] = $site;
     R::store($user);
     testpack('Test REST Lists');
     $can = new RedBean_Plugin_BeanCanResty(R::$toolbox);
     $can->setWhitelist('all');
     $resp = $can->handleREST($user, 'site/list', 'GET');
     asrt(count($resp['result']), 1);
     $resp = $can->handleREST($user, 'site/' . $site->id . '/page/' . $page->id . '/shared-ad/list', 'GET');
     asrt(count($resp['result']), 2);
     $can = new RedBean_Plugin_BeanCanResty();
     $can->setWhitelist('all');
     $resp = $can->handleREST($user, 'site/' . $site->id . '/page/' . $page->id . '/shared-ad/list', 'GET');
     asrt(count($resp['result']), 2);
     $resp = $can->handleREST($user, 'site/' . $site->id . '/page/' . $page->id . '/shared-ad/list', 'GET', array(), array('shared-ad' => array('LIMIT 1')));
     asrt(count($resp['result']), 1);
     $can->setWhitelist(array('ad' => array('GET')));
     $resp = $can->handleREST($user, 'site/' . $site->id . '/page/' . $page->id . '/shared-ad/list', 'GET', array(), array('shared-ad' => array('LIMIT 1', array())));
     asrt(count($resp['result']), 1);
     $can->setWhitelist(array('ad' => array('GET')));
     $resp = $can->handleREST($user, 'site/' . $site->id . '/page/' . $page->id . '/shared-ad/list', 'GET', array(), array('shared-ad' => array(' ORDER BY ad.id DESC ', array())));
     asrt(count($resp['result']), 2);
     $entry1 = reset($resp['result']);
     $entry2 = end($resp['result']);
     asrt($entry1['id'] > $entry2['id'], TRUE);
     $can->setWhitelist(array('ad' => array('GET')));
     $resp = $can->handleREST($user, 'site/' . $site->id . '/page/' . $page->id . '/shared-ad/list', 'GET', array(), array('shared-ad' => array(' ORDER BY ad.id ASC ', array())));
     asrt(count($resp['result']), 2);
     $entry1 = reset($resp['result']);
     $entry2 = end($resp['result']);
     asrt($entry1['id'] < $entry2['id'], TRUE);
     $can->setWhitelist(array('page' => array('GET')));
     $resp = $can->handleREST($user, 'site/' . $site->id . '/page/' . $page->id . '/shared-ad/list', 'GET', array(), array('shared-ad' => array('LIMIT 1', array())));
     asrt(isset($resp['error']), TRUE);
     $resp = $can->handleREST($user, 'site/' . $site->id . '/page/list', 'GET', array(), array('shared-ad' => array(' id = ? ', array(0))));
     asrt(count($resp['result']), 1);
     //works also with names param?
     $resp = $can->handleREST($user, 'site/' . $site->id . '/page/list', 'GET', array(), array('page' => array(' id > :id ', array(':id' => 0))));
     asrt(count($resp['result']), 1);
     $resp = $can->handleREST($user, 'site/' . $site->id . '/page/list', 'GET', array(), array('shared-ad' => array(' id = ? ')));
     asrt(count($resp['result']), 1);
     $resp = $can->handleREST($user, 'site/' . $site->id . '/page/list', 'GET', array(), array('page' => array(' id = ? ', array($page->id))));
     asrt(count($resp['result']), 1);
     $resp = $can->handleREST($user, 'site/' . $site->id . '/page/list', 'GET', array(), array('page' => array(' id = ? ', array(0))));
     asrt(count($resp['result']), 0);
     $can->setWhitelist('all');
     $resp = $can->handleREST($user, '@!#?', 'GET');
     asrt((string) $resp['error']['message'], 'URI contains invalid characters.');
     asrt((string) $resp['error']['code'], '400');
     $resp = $can->handleREST($user, 'blah', 'GET');
     asrt((string) $resp['error']['message'], 'Invalid path: needs 1 more element.');
     asrt((string) $resp['error']['code'], '404');
     asrt((string) $resp['red-resty'], '1.0');
     $resp = $can->handleREST($user, '/blah', 'GET');
     asrt((string) $resp['error']['message'], 'Cannot access list.');
     asrt((string) $resp['error']['code'], '404');
     asrt((string) $resp['red-resty'], '1.0');
     $resp = $can->handleREST($user, 'site/2', 'GET');
     asrt((string) $resp['error']['message'], 'Cannot access bean.');
     asrt((string) $resp['error']['code'], '404');
     asrt((string) $resp['red-resty'], '1.0');
     $resp = $can->handleREST($user, 'blah/2', 'GET');
     asrt((string) $resp['error']['message'], 'Cannot access bean.');
     $resp = $can->handleREST($user, '', 'GET');
     asrt((string) $resp['red-resty'], '1.0');
     asrt((string) $resp['result']['name'], 'me');
     $resp = $can->handleREST($user, 'book', 'POST', '');
     asrt((string) $resp['error']['code'], '400');
     asrt((string) $resp['error']['message'], 'Payload needs to be array.');
     $resp = $can->handleREST($user, '', 'POST', array());
     asrt((string) $resp['error']['code'], '400');
     asrt((string) $resp['error']['message'], 'Missing list.');
     $resp = $can->handleREST($user, 'shared-bo-ok', 'POST', array());
     asrt((string) $resp['error']['code'], '400');
     asrt((string) $resp['error']['message'], 'Invalid list.');
     $resp = $can->handleREST($user, 'book', 'POST', array('type' => 'book'));
     asrt((string) $resp['error']['code'], '400');
     asrt((string) $resp['error']['message'], 'Missing parameter \'bean\'.');
     // Send a GET /site/1 request to BeanCan Server
     $resp = $can->handleREST($user, 'site/' . $site->id, 'GET');
     asrt((string) $resp['result']['id'], (string) $site->id);
     asrt((string) $resp['result']['name'], (string) $site->name);
     asrt((string) $resp['result']['user_id'], (string) $site->user_id);
     $can->setWhitelist(array('page' => array('PUT')));
     $resp = $can->handleREST($user, 'site/' . $site->id, 'GET');
     asrt((string) $resp['error']['message'], 'This bean is not available. Set whitelist to "all" or add to whitelist.');
     asrt((string) $resp['error']['code'], '403');
     $can->setWhitelist(array('site' => array('PUT')));
     $resp = $can->handleREST($user, 'site/' . $site->id, 'GET');
     asrt((string) $resp['error']['message'], 'This bean is not available. Set whitelist to "all" or add to whitelist.');
     asrt((string) $resp['error']['code'], '403');
     $can->setWhitelist(array('site' => array('GET')));
     $resp = $can->handleREST($user, 'site/' . $site->id, 'GET');
     asrt((string) $resp['result']['id'], (string) $site->id);
     asrt((string) $resp['result']['name'], (string) $site->name);
     asrt((string) $resp['result']['user_id'], (string) $site->user_id);
     asrt(!isset($resp['error']), TRUE);
     $can->setWhitelist('all');
     // Send a GET /site/1/page/1 request to BeanCan Server
     $resp = $can->handleREST($user, 'site/' . $site->id . '/page/' . $page->id, 'GET');
     asrt((string) $resp['result']['id'], (string) $page->id);
     asrt((string) $resp['result']['name'], (string) $page->name);
     asrt((string) $resp['result']['site_id'], (string) $page->site_id);
     // Send a GET /site/1/page/1/shared-ad/1
     $resp = $can->handleREST($user, 'site/' . $site->id . '/page/' . $page->id . '/shared-ad/' . $ad->id, 'GET');
     asrt((string) $resp['result']['id'], (string) $ad->id);
     asrt((string) $resp['result']['name'], (string) $ad->name);
     // Send a POST /site/1/page
     $payLoad = array('bean' => array('name' => 'my new page'));
     $resp = $can->handleREST($user, 'site/' . $site->id . '/page', 'POST', $payLoad);
     $newPage = R::findOne('page', ' name = ? ', array('my new page'));
     asrt((string) $resp['result']['id'], (string) $newPage->id);
     asrt((string) $resp['result']['name'], (string) $newPage->name);
     $payload = array('bean' => array('does' => 'fly'));
     $resp = $can->handleREST($user, 'teapot', 'POST', $payload);
     $newTeapot = R::findOne('teapot');
     asrt((string) $newTeapot->id, (string) $resp['result']['id']);
     asrt((string) $newTeapot->does, 'fly');
     $badPayLoad = array('type' => 'ad', 'bean' => 42);
     $incompletePayLoad = array('type' => 'ad');
     // Send a PUT /site/1/page/2/shared-ad
     $resp = $can->handleREST($user, 'site/' . $site->id . '/page/' . $page->id . '/shared-ad', 'POST', $badPayLoad);
     asrt((string) $resp['error']['message'], 'Parameter \'bean\' must be object/array.');
     asrt((string) $resp['error']['code'], '400');
     $payLoad = array('type' => 'ad', 'bean' => array('name' => 'my new ad'));
     $resp = $can->handleREST($user, 'site/' . $site->id . '/page/' . $page->id . '/shared-ad', 'POST', $payLoad);
     $newAd = R::findOne('ad', ' name = ? ', array('my new ad'));
     asrt((string) $resp['result']['id'], (string) $newAd->id);
     asrt((string) $resp['result']['name'], (string) $newAd->name);
     // Send a POST /site/1
     $exception = NULL;
     $resp = $can->handleREST($user, 'site/' . $site->id, 'PUT', $incompletePayLoad);
     asrt((string) $resp['error']['message'], 'Missing parameter \'bean\'.');
     asrt((string) $resp['error']['code'], '400');
     $resp = $can->handleREST($user, 'site/' . $site->id, 'PUT', $badPayLoad);
     asrt((string) $resp['error']['message'], 'Parameter \'bean\' must be object/array.');
     asrt((string) $resp['error']['code'], '400');
     $badPayLoad = array('type' => 'ad', 'bean' => array(array()));
     $resp = $can->handleREST($user, 'site/' . $site->id, 'PUT', $badPayLoad);
     asrt((string) $resp['error']['message'], 'Object "bean" invalid.');
     asrt((string) $resp['error']['code'], '400');
     $payLoad = array('bean' => array('name' => 'The Original'));
     $resp = $can->handleREST($user, 'site/' . $site->id, 'PUT', $payLoad);
     asrt((string) $resp['result']['id'], (string) $site->id);
     asrt((string) $resp['result']['name'], 'The Original');
     // Send a DELETE /site/1/page/2/shared-ad/2
     $resp = $can->handleREST($user, 'site/' . $site->id . '/page/' . $page->id . '/shared-ad/' . $newAd->id, 'DELETE');
     $newAd = R::findOne('ad', ' name = ? ', array('my new ad'));
     asrt((string) $resp['result'], 'OK');
     asrt($newAd, NULL);
     // Send a MAIL /site/1/page/1
     $resp = $can->handleREST($user, 'site/' . $site->id . '/page/' . $page->id, 'mail', array());
     asrt((string) $resp['result'], 'mail has been sent to nobody');
     $resp = $can->handleREST($user, 'site/' . $site->id . '/page/' . $page->id, 'mail', array('param' => 123));
     asrt((string) $resp['error']['message'], 'Parameter \'param\' must be object/array.');
     asrt((string) $resp['error']['code'], '400');
     $resp = $can->handleREST($user, 'site/' . $site->id . '/page/' . $page->id, 'mail', array('param' => array('me')));
     asrt((string) $resp['result'], 'mail has been sent to me');
     $resp = $can->handleREST($user, 'site/' . $site->id . '/page/' . $page->id, 'err', array('param' => array('me')));
     asrt((string) $resp['error']['message'], 'Exception: 123');
     asrt((string) $resp['error']['code'], '500');
     // Test Access control
     $setting = R::dispense('setting');
     $option = R::dispense('option');
     $setting->ownOption[] = $option;
     $user->ownSetting[] = $setting;
     $option->name = 'secret';
     R::store($user);
     $resp = $can->handleREST($user, 'setting/' . $setting->id . '/option/' . $option->id, 'GET');
     asrt($resp['result']['name'], 'secret');
     $user2 = R::load('user', R::store(R::dispense('user')));
     $resp = $can->handleREST($user2, 'setting/' . $setting->id . '/option/' . $option->id, 'GET');
     asrt(isset($resp['error']), TRUE);
     Model_Setting::$closed = TRUE;
     $resp = $can->handleREST($user, 'setting/' . $setting->id . '/option/' . $option->id, 'GET');
     asrt(isset($resp['error']), TRUE);
     Model_Setting::$closed = FALSE;
     // Some other scenarios, not allowed to post nested sets.
     $village = R::dispense('village');
     $village->user = $user;
     R::store($village);
     asrt(count($village->ownBuilding), 0);
     $resp = $can->handleREST($user, 'village/' . $village->id . '/building', 'POST', array('bean' => array('name' => 'house')));
     $village = $village->fresh();
     asrt(count($village->ownBuilding), 1);
     $resp = $can->handleREST($user, 'village/' . $village->id . '/building', 'POST', array('bean' => array('name' => 'house', 'ownFurniture' => array('chair'))));
     asrt($resp['error']['message'], "Object 'bean' invalid.");
     asrt(count($village->ownBuilding), 1);
     // Test some combination with cache, needs more testing
     R::nuke();
     R::$writer->setUseCache(TRUE);
     $village = R::dispense('village');
     $village->user = R::dispense('user');
     R::store($village);
     asrt(count($village->ownBuilding), 0);
     $resp = $can->handleREST($user, 'village/' . $village->id . '/building', 'POST', array('bean' => array('name' => 'house')));
     $village = $village->fresh();
     asrt(count($village->ownBuilding), 1);
     $resp = $can->handleREST($user, 'village/' . $village->id . '/building', 'POST', array('bean' => array('name' => 'house', 'ownFurniture' => array('chair'))));
     asrt($resp['error']['message'], "Object 'bean' invalid.");
     asrt(count($village->ownBuilding), 1);
     R::$writer->setUseCache(FALSE);
     testpack("Test BeanCan Server 1 / create");
     R::nuke();
     $rs = fakeBeanCanServerRequest("candybar:store", array(array("brand" => "funcandy", "taste" => "sweet")));
     asrt(is_string($rs), TRUE);
     $rs = json_decode($rs, TRUE);
     asrt(is_array($rs), TRUE);
     asrt(empty($rs), FALSE);
     asrt(isset($rs["jsonrpc"]), TRUE);
     asrt($rs["jsonrpc"], "2.0");
     asrt(isset($rs["id"]), TRUE);
     asrt($rs["id"], "1234");
     asrt(isset($rs["result"]), TRUE);
     asrt($rs["result"] > 0, TRUE);
     asrt(isset($rs["error"]), FALSE);
     asrt(count($rs), 3);
     $oldid = $rs["result"];
     testpack("Test retrieve");
     $rs = json_decode(fakeBeanCanServerRequest("candybar:load", array($oldid)), TRUE);
     asrt(is_array($rs), TRUE);
     asrt(empty($rs), FALSE);
     asrt(count($rs), 3);
     asrt(isset($rs["jsonrpc"]), TRUE);
     asrt($rs["jsonrpc"], "2.0");
     asrt(isset($rs["id"]), TRUE);
     asrt($rs["id"], "1234");
     asrt(isset($rs["result"]), TRUE);
     asrt(isset($rs["error"]), FALSE);
     asrt(is_array($rs["result"]), TRUE);
     asrt(count($rs["result"]), 3);
     asrt($rs["result"]["id"], (string) $oldid);
     asrt($rs["result"]["brand"], "funcandy");
     asrt($rs["result"]["taste"], "sweet");
     testpack("Test update");
     $rs = json_decode(fakeBeanCanServerRequest("candybar:store", array(array("id" => $oldid, "taste" => "salty")), "42"), TRUE);
     asrt(is_array($rs), TRUE);
     asrt(empty($rs), FALSE);
     asrt(count($rs), 3);
     asrt(isset($rs["jsonrpc"]), TRUE);
     asrt($rs["jsonrpc"], "2.0");
     asrt(isset($rs["id"]), TRUE);
     asrt($rs["id"], "42");
     asrt(isset($rs["result"]), TRUE);
     asrt(isset($rs["error"]), FALSE);
     $rs = json_decode(fakeBeanCanServerRequest("candybar:load", array($oldid)), TRUE);
     asrt($rs["result"]["taste"], "salty");
     $rs = json_decode(fakeBeanCanServerRequest("candybar:load", array()), TRUE);
     asrt($rs["error"]["message"], "First param needs to be Bean ID");
     asrt((string) $rs["error"]["code"], "-32602");
     $rs = json_decode(fakeBeanCanServerRequest("candybar:export", array()), TRUE);
     asrt($rs["error"]["message"], "First param needs to be Bean ID");
     asrt((string) $rs["error"]["code"], "-32602");
     $rs = json_decode(fakeBeanCanServerRequest("candybar:trash", array()), TRUE);
     asrt($rs["error"]["message"], "First param needs to be Bean ID");
     asrt((string) $rs["error"]["code"], "-32602");
     $rs = json_decode(fakeBeanCanServerRequest("candybar:store", array(array("brand" => "darkchoco", "taste" => "bitter"))), TRUE);
     $id2 = $rs["result"];
     $rs = json_decode(fakeBeanCanServerRequest("candybar:load", array($oldid)), TRUE);
     asrt($rs["result"]["brand"], "funcandy");
     asrt($rs["result"]["taste"], "salty");
     $rs = json_decode(fakeBeanCanServerRequest("candybar:load", array($id2)), TRUE);
     asrt($rs["result"]["brand"], "darkchoco");
     asrt($rs["result"]["taste"], "bitter");
     testpack("Test delete");
     $rs = json_decode(fakeBeanCanServerRequest("candybar:trash", array($oldid)), TRUE);
     asrt(is_array($rs), TRUE);
     asrt(empty($rs), FALSE);
     asrt(count($rs), 3);
     asrt(isset($rs["jsonrpc"]), TRUE);
     asrt($rs["jsonrpc"], "2.0");
     asrt(isset($rs["id"]), TRUE);
     asrt($rs["id"], "1234");
     asrt(isset($rs["result"]), TRUE);
     asrt(isset($rs["error"]), FALSE);
     asrt($rs["result"], "OK");
     $rs = json_decode(fakeBeanCanServerRequest("candybar:load", array($oldid)), TRUE);
     asrt(isset($rs["result"]), TRUE);
     asrt(isset($rs["error"]), FALSE);
     asrt($rs["result"]["id"], 0);
     $rs = json_decode(fakeBeanCanServerRequest("candybar:load", array($id2)), TRUE);
     asrt($rs["result"]["brand"], "darkchoco");
     asrt($rs["result"]["taste"], "bitter");
     testpack("Test Custom Method");
     $rs = json_decode(fakeBeanCanServerRequest("candybar:customMethod", array("test")), TRUE);
     asrt(is_array($rs), TRUE);
     asrt(empty($rs), FALSE);
     asrt(count($rs), 3);
     asrt(isset($rs["jsonrpc"]), TRUE);
     asrt($rs["jsonrpc"], "2.0");
     asrt(isset($rs["id"]), TRUE);
     asrt($rs["id"], "1234");
     asrt(isset($rs["result"]), TRUE);
     asrt(isset($rs["error"]), FALSE);
     asrt($rs["result"], "test!");
     $rs = json_decode(fakeBeanCanServerRequest("candybar:customMethodWithException", array("test")), TRUE);
     asrt($rs["error"]["code"], -32099);
     asrt($rs["error"]["message"], '0-Oops!');
     testpack("Test Whitelist");
     $can = new RedBean_Plugin_BeanCan();
     $can->setWhitelist('all');
     $rs = json_decode(fakeBeanCanServerRequest("candybar:store", array(array("brand" => "darkchoco", "taste" => "bitter")), 1, ''), TRUE);
     asrt(is_array($rs), TRUE);
     asrt(empty($rs), FALSE);
     asrt(count($rs), 3);
     asrt(isset($rs["jsonrpc"]), TRUE);
     asrt($rs["jsonrpc"], "2.0");
     asrt(isset($rs["id"]), TRUE);
     asrt(isset($rs["result"]), FALSE);
     asrt(isset($rs["error"]), TRUE);
     asrt(isset($rs["error"]["code"]), TRUE);
     asrt($rs["error"]["code"], -32600);
     asrt($rs["error"]["message"], 'This bean is not available. Set whitelist to "all" or add to whitelist.');
     $can = new RedBean_Plugin_BeanCan();
     $rs = json_decode(fakeBeanCanServerRequest("candybar:store", array(array("brand" => "darkchoco", "taste" => "bitter")), 1, array('candybar' => array('like'))), TRUE);
     asrt(is_array($rs), TRUE);
     asrt(empty($rs), FALSE);
     asrt(count($rs), 3);
     asrt(isset($rs["jsonrpc"]), TRUE);
     asrt($rs["jsonrpc"], "2.0");
     asrt(isset($rs["id"]), TRUE);
     asrt(isset($rs["result"]), FALSE);
     asrt(isset($rs["error"]), TRUE);
     asrt(isset($rs["error"]["code"]), TRUE);
     asrt($rs["error"]["code"], -32600);
     asrt($rs["error"]["message"], 'This bean is not available. Set whitelist to "all" or add to whitelist.');
     $can = new RedBean_Plugin_BeanCan();
     $rs = json_decode(fakeBeanCanServerRequest("candybar:store", array(array("brand" => "darkchoco", "taste" => "bitter")), 1, array('candybar' => array('store'))), TRUE);
     asrt(is_array($rs), TRUE);
     asrt(empty($rs), FALSE);
     asrt(count($rs), 3);
     asrt(isset($rs["jsonrpc"]), TRUE);
     asrt($rs["jsonrpc"], "2.0");
     asrt(isset($rs["id"]), TRUE);
     asrt(isset($rs["result"]), TRUE);
     asrt(isset($rs["error"]), FALSE);
     testpack("Test Negatives: parse error");
     $rs = json_decode($can->handleJSONRequest("crap"), TRUE);
     asrt(is_array($rs), TRUE);
     asrt(empty($rs), FALSE);
     asrt(count($rs), 2);
     asrt(isset($rs["jsonrpc"]), TRUE);
     asrt($rs["jsonrpc"], "2.0");
     asrt(isset($rs["id"]), FALSE);
     asrt(isset($rs["result"]), FALSE);
     asrt(isset($rs["error"]), TRUE);
     asrt(isset($rs["error"]["code"]), TRUE);
     asrt($rs["error"]["code"], -32700);
     testpack("invalid request");
     $can = new RedBean_Plugin_BeanCan();
     $can->setWhitelist('all');
     $rs = json_decode($can->handleJSONRequest('{"aa":"bb"}'), TRUE);
     asrt(is_array($rs), TRUE);
     asrt(empty($rs), FALSE);
     asrt(count($rs), 2);
     asrt(isset($rs["jsonrpc"]), TRUE);
     asrt($rs["jsonrpc"], "2.0");
     asrt(isset($rs["id"]), FALSE);
     asrt(isset($rs["result"]), FALSE);
     asrt(isset($rs["error"]), TRUE);
     asrt(isset($rs["error"]["code"]), TRUE);
     asrt($rs["error"]["code"], -32600);
     $can->setWhitelist('all');
     $rs = json_decode($can->handleJSONRequest('{"jsonrpc":"9.1"}'), TRUE);
     asrt(is_array($rs), TRUE);
     asrt(empty($rs), FALSE);
     asrt(count($rs), 2);
     asrt(isset($rs["jsonrpc"]), TRUE);
     asrt($rs["jsonrpc"], "2.0");
     asrt(isset($rs["id"]), FALSE);
     asrt(isset($rs["result"]), FALSE);
     asrt(isset($rs["error"]), TRUE);
     asrt(isset($rs["error"]["code"]), TRUE);
     asrt($rs["error"]["code"], -32600);
     $can->setWhitelist('all');
     $rs = json_decode($can->handleJSONRequest('{"id":9876,"jsonrpc":"9.1"}'), TRUE);
     asrt(is_array($rs), TRUE);
     asrt(empty($rs), FALSE);
     asrt(count($rs), 2);
     asrt(isset($rs["jsonrpc"]), TRUE);
     asrt($rs["jsonrpc"], "2.0");
     asrt(isset($rs["id"]), FALSE);
     asrt(isset($rs["result"]), FALSE);
     asrt(isset($rs["error"]), TRUE);
     asrt(isset($rs["error"]["code"]), TRUE);
     asrt($rs["error"]["code"], -32600);
     $rs = json_decode(fakeBeanCanServerRequest("wrong", array("test")), TRUE);
     asrt(is_array($rs), TRUE);
     asrt(empty($rs), FALSE);
     asrt(count($rs), 3);
     asrt(isset($rs["jsonrpc"]), TRUE);
     asrt($rs["jsonrpc"], "2.0");
     asrt(isset($rs["id"]), TRUE);
     asrt($rs["id"], "1234");
     asrt(isset($rs["result"]), FALSE);
     asrt(isset($rs["error"]), TRUE);
     asrt($rs["error"]["code"], -32600);
     asrt($rs["error"]["message"], "Invalid method signature. Use: BEAN:ACTION");
     $rs = json_decode(fakeBeanCanServerRequest(".;':wrong", array("test")), TRUE);
     asrt(is_array($rs), TRUE);
     asrt(empty($rs), FALSE);
     asrt(count($rs), 3);
     asrt(isset($rs["jsonrpc"]), TRUE);
     asrt($rs["jsonrpc"], "2.0");
     asrt(isset($rs["id"]), TRUE);
     asrt($rs["id"], "1234");
     asrt(isset($rs["result"]), FALSE);
     asrt(isset($rs["error"]), TRUE);
     asrt($rs["error"]["code"], -32600);
     asrt($rs["error"]["message"], "Invalid Bean Type String");
     $rs = json_decode(fakeBeanCanServerRequest("wrong:.;'", array("test")), TRUE);
     asrt(is_array($rs), TRUE);
     asrt(empty($rs), FALSE);
     asrt(count($rs), 3);
     asrt(isset($rs["jsonrpc"]), TRUE);
     asrt($rs["jsonrpc"], "2.0");
     asrt(isset($rs["id"]), TRUE);
     asrt($rs["id"], "1234");
     asrt(isset($rs["result"]), FALSE);
     asrt(isset($rs["error"]), TRUE);
     asrt($rs["error"]["code"], -32600);
     asrt($rs["error"]["message"], "Invalid Action String");
     $rs = json_decode(fakeBeanCanServerRequest("wrong:wrong", array("test")), TRUE);
     asrt(is_array($rs), TRUE);
     asrt(empty($rs), FALSE);
     asrt(count($rs), 3);
     asrt(isset($rs["jsonrpc"]), TRUE);
     asrt($rs["jsonrpc"], "2.0");
     asrt(isset($rs["id"]), TRUE);
     asrt($rs["id"], "1234");
     asrt(isset($rs["result"]), FALSE);
     asrt(isset($rs["error"]), TRUE);
     asrt($rs["error"]["code"], -32601);
     asrt($rs["error"]["message"], "No such bean in the can!");
     $rs = json_decode(fakeBeanCanServerRequest("candybar:beHealthy", array("test")), TRUE);
     asrt(is_array($rs), TRUE);
     asrt(empty($rs), FALSE);
     asrt(count($rs), 3);
     asrt(isset($rs["jsonrpc"]), TRUE);
     asrt($rs["jsonrpc"], "2.0");
     asrt(isset($rs["id"]), TRUE);
     asrt($rs["id"], "1234");
     asrt(isset($rs["result"]), FALSE);
     asrt(isset($rs["error"]), TRUE);
     asrt($rs["error"]["code"], -32601);
     asrt($rs["error"]["message"], "Method not found in Bean: candybar ");
     $rs = json_decode(fakeBeanCanServerRequest("candybar:store"), TRUE);
     asrt(is_array($rs), TRUE);
     asrt(empty($rs), FALSE);
     asrt(count($rs), 3);
     asrt(isset($rs["jsonrpc"]), TRUE);
     asrt($rs["jsonrpc"], "2.0");
     asrt(isset($rs["id"]), TRUE);
     asrt($rs["id"], "1234");
     asrt(isset($rs["result"]), FALSE);
     asrt(isset($rs["error"]), TRUE);
     asrt($rs["error"]["code"], -32602);
     $rs = json_decode(fakeBeanCanServerRequest("pdo:connect", array("abc")), TRUE);
     asrt($rs["error"]["code"], -32601);
     $rs = json_decode(fakeBeanCanServerRequest("stdClass:__toString", array("abc")), TRUE);
     asrt($rs["error"]["code"], -32601);
     $j = array("jsonrpc" => "2.0", 'id' => '1');
     $can = new RedBean_Plugin_BeanCan();
     $request = json_encode($j);
     $out = $can->handleJSONRequest($request);
     $rs = json_decode($out, TRUE);
     asrt((string) $rs["error"]["message"], 'No method');
     asrt((string) $rs["error"]["code"], '-32600');
     $j = array("jsonrpc" => "2.0", 'method' => 'method');
     $can = new RedBean_Plugin_BeanCan();
     $request = json_encode($j);
     $out = $can->handleJSONRequest($request);
     $rs = json_decode($out, TRUE);
     asrt((string) $rs["error"]["message"], 'No ID');
     asrt((string) $rs["error"]["code"], '-32600');
     R::nuke();
     $server = new RedBean_Plugin_BeanCan();
     $book = R::dispense('book');
     $book->title = 'book 1';
     $id1 = R::store($book);
     $book = R::dispense('book');
     $book->title = 'book 2';
     $id2 = R::store($book);
     asrt(json_decode($server->handleRESTGetRequest('book/' . $id1))->result->title, 'book 1');
     asrt(json_decode($server->handleRESTGetRequest('book/' . $id2))->result->title, 'book 2');
     $r = json_decode($server->handleRESTGetRequest('book'), TRUE);
     $a = $r['result'];
     asrt(count($a), 2);
     $r = json_decode($server->handleRESTGetRequest(''), TRUE);
     $a = $r['error']['message'];
     asrt($a, 'Internal Error');
     $r = json_decode($server->handleRESTGetRequest(array()), TRUE);
     $a = $r['error']['message'];
     asrt($a, 'IR');
     testpack('Test BeanCan:export');
     R::nuke();
     $briefcase = R::dispense('briefcase');
     $documents = R::dispense('document', 2);
     $page = R::dispense('page');
     $author = R::dispense('author');
     $briefcase->name = 'green';
     $documents[0]->name = 'document 1';
     $page->content = 'Lorem Ipsum';
     $author->name = 'Someone';
     $briefcase->ownDocument = $documents;
     $documents[1]->ownPage[] = $page;
     $page->sharedAuthor[] = $author;
     $id = R::store($briefcase);
     $rs = json_decode(fakeBeanCanServerRequest('briefcase:export', array($id)), TRUE);
     asrt((int) $rs['result'][0]['id'], (int) $id);
     asrt($rs['result'][0]['name'], 'green');
     asrt($rs['result'][0]['ownDocument'][0]['name'], 'document 1');
     asrt($rs['result'][0]['ownDocument'][1]['ownPage'][0]['content'], 'Lorem Ipsum');
     asrt($rs['result'][0]['ownDocument'][1]['ownPage'][0]['sharedAuthor'][0]['name'], 'Someone');
     $rs = json_decode(fakeBeanCanServerRequest('document:export', array($documents[1]->id)), TRUE);
     asrt((int) $rs['result'][0]['id'], (int) $documents[1]->id);
     asrt($rs['result'][0]['ownPage'][0]['content'], 'Lorem Ipsum');
     asrt($rs['result'][0]['ownPage'][0]['sharedAuthor'][0]['name'], 'Someone');
     asrt($rs['result'][0]['briefcase']['name'], 'green');
     testpack('BeanCan does not include the request id in the response if it is 0');
     $id = R::store(R::dispense('foo')->setAttr('prop1', 'val1'));
     $can->setWhitelist('all');
     $rs = json_decode($can->handleJSONRequest('{"jsonrpc":"2.0","method":"foo:load","params":[' . $id . '],"id":0}'), TRUE);
     asrt(isset($rs['id']), TRUE);
     asrt($rs['id'], 0);
 }
Example #20
0
 /**
  * Extends the lifetime of the river by pushing forward the expiry date 
  * of the river - by the no. of days that a river is active. This SHOULD only 
  * be triggered by an owner of the river. The extension counter is incremented
  * each time the expiry date is incremented
  *
  * @param bool $reactivate_channels When TRUE, reactivates the channels for the 
  * current river so that the crawlers can resume fetching content from them
  */
 public function extend_lifetime($reactivate_channels = TRUE)
 {
     $lifetime = Model_Setting::get_setting('river_active_duration');
     $expiry_start_date = strtotime($this->river_date_expiry);
     if ($this->get_days_to_expiry() == 0) {
         $expiry_start_date = time();
     }
     $expiry_date = strtotime(sprintf("+%s day", $lifetime), $expiry_start_date);
     $this->river_expired = 0;
     $this->expiry_extension_token = NULL;
     $this->river_date_expiry = date("Y-m-d H:i:s", $expiry_date);
     $this->extension_count += 1;
     $this->expiry_candidate = 0;
     parent::save();
     if ($reactivate_channels) {
         // Disable the channel filters for the river
         DB::update('channel_filters')->set(array('filter_enabled' => 1))->where('river_id', '=', $this->id)->execute();
         $this->_toggle_channel_option_status(TRUE);
     }
 }
Example #21
0
				<?php 
}
?>
			</div>
		</article>
			
		<?php 
if ($anonymous) {
    ?>
			<h3 class="push-up"><span><?php 
    echo __('In the mean time...');
    ?>
</h3>
			
			<?php 
    if ((bool) Model_Setting::get_setting('public_registration_enabled')) {
        ?>
			<div class="panel-left">
				<div class="login" id="nothing_to_display_login_form">
					<div class="loading center"></div>
					<div class="system_error" style="display:none"></div>
					<div class="system_success" style="display:none"></div>
					<div class="form">
						<h3><?php 
        echo __('Create An Account');
        ?>
</h3>
						<p>
							<strong><label><?php 
        echo __('Your email address');
        ?>
Example #22
0
 /**
  * Password reset for ORM auth.
  *
  */
 private static function password_reset_orm($email)
 {
     $ret = array();
     $auth_token = Model_Auth_Token::create_token('password_reset', array('email' => $email));
     if ($auth_token->loaded()) {
         //Send an email with a secret token URL
         $mail_body = View::factory('emails/resetpassword')->bind('secret_url', $secret_url);
         $secret_url = url::site('login/reset/' . urlencode($email) . '/' . $auth_token->token, TRUE, TRUE);
         $mail_subject = __(':sitename: Password Reset', array(':sitename' => Model_Setting::get_setting('site_name')));
         Swiftriver_Mail::send($email, $mail_subject, $mail_body);
         $ret['messages'] = array(__('An email has been sent with instructions to complete the password reset process.'));
     } else {
         $ret['errors'] = array(__('Error'));
     }
     return $ret;
 }
Example #23
0
			
			window.logged_in_user = <?php 
    echo $user->id;
    ?>
;
		<?php 
} else {
    ?>
			window.logged_in_account = null;
			window.logged_in_account_path = null;
			window.logged_in_user = null;
		<?php 
}
?>
		window.public_registration_enabled = <?php 
echo Model_Setting::get_setting('public_registration_enabled');
?>
;
		window.site_url = "<?php 
echo URL::base(TRUE, FALSE);
?>
";
	</script>
	
	<?php 
echo Html::script("themes/default/media/js/jquery-1.7.2.min.js");
// Outside events plugin
echo Html::script("themes/default/media/js/jquery.outside.js");
// Masonry plugin
echo Html::script("themes/default/media/js/jquery.masonry.min.js");
echo Html::script("themes/default/media/js/jquery.imagesloaded.min.js");
Example #24
0
 /**
  * The before() method is called before main controller action.
  * In our template controller we override this method so that we can
  * set up default values. These variables are then available to our
  * controllers if they need to be modified.
  *
  * @return	void
  */
 public function before()
 {
     // Execute parent::before first
     parent::before();
     try {
         $this->session = Session::instance();
     } catch (ErrorException $e) {
         session_destroy();
     }
     // Load the default Cache engine
     $this->cache = Cache::instance();
     // Open session
     $this->session = Session::instance();
     // If an api key has been provided, login that user
     $api_key = $this->request->query('api_key');
     if ($api_key) {
         $user_orm = ORM::factory('user', array('api_key' => $api_key));
         if ($user_orm->loaded() and $user_orm->username != 'public') {
             Auth::instance()->force_login($user_orm);
         } else {
             // api_keys used by apps. Instead of giving the login page
             // tell them something went wrong.
             throw new HTTP_Exception_403();
         }
     }
     // In case anonymous setting changed and user had a session,
     // log out
     if (Auth::instance()->logged_in() and Auth::instance()->get_user()->username == 'public' and !(bool) Model_Setting::get_setting('anonymous_access_enabled')) {
         Auth::instance()->logout();
     }
     // Anonymous logged in and login controller requested, logout
     if (Auth::instance()->logged_in() and Auth::instance()->get_user()->username == 'public' and $this->request->controller() == 'login') {
         Auth::instance()->logout();
     }
     // If we're not logged in, gives us chance to auto login
     $supports_auto_login = new ReflectionClass(get_class(Auth::instance()));
     $supports_auto_login = $supports_auto_login->hasMethod('auto_login');
     if (!Auth::instance()->logged_in() and $supports_auto_login) {
         // Controller exempt from auth check
         $exempt_controllers = Kohana::$config->load('auth.ignore_controllers');
         Auth::instance()->auto_login();
         if (!Auth::instance()->get_user() and !in_array($this->request->controller(), $exempt_controllers)) {
             $this->login_required();
         }
     }
     if ($this->auth_required !== FALSE and Auth::instance()->logged_in($this->auth_required) === FALSE) {
         if (Auth::instance()->logged_in()) {
             // User is logged in but not on the secure_actions list
             $this->access_required();
         } else {
             $this->login_required();
         }
     }
     // Get the logged In User
     $this->user = Auth::instance()->get_user();
     if ($this->user) {
         // Is anonymous logged in?
         if ($this->user->username == 'public') {
             $this->anonymous = TRUE;
         }
         // Is this user an admin?
         $this->admin = $this->user->is_admin();
         if (strtolower(Kohana::$config->load('auth.driver')) == 'riverid' and !in_array($this->user->username, Kohana::$config->load('auth.exempt'))) {
             $this->riverid_auth = TRUE;
         }
         // Does this user have an account space?
         if (!($this->account = $this->cache->get('user_account_' . $this->user->id, FALSE))) {
             $this->account = ORM::factory('account')->where('user_id', '=', $this->user->id)->find();
             $this->cache->set('user_account_' . $this->user->id, $this->account, 3600 + rand(0, 3600));
         }
         if (!$this->account->loaded() and $this->request->uri() != 'register') {
             // Make the user create an account
             Request::current()->redirect('register');
         }
         // Logged in user's dashboard url
         if ($this->anonymous) {
             $this->dashboard_url = URL::site('welcome');
         } else {
             $this->dashboard_url = URL::site() . $this->account->account_path;
         }
         // Build the base URL
         $visited_account_path = $this->request->param('account');
         if ($visited_account_path and $visited_account_path != $this->account->account_path) {
             $this->base_url = URL::site() . $visited_account_path . '/' . $this->request->controller();
             $this->visited_account = ORM::factory('account', array('account_path' => $visited_account_path));
             // Visited account doesn't exist?
             if (!$this->visited_account->loaded()) {
                 $this->request->redirect($this->dashboard_url);
             }
         } else {
             $this->base_url = URL::site() . $this->account->account_path . '/' . $this->request->controller();
             $this->visited_account = $this->account;
         }
     }
     // Load Header & Footer & variables
     if ($this->auto_render) {
         $this->template->header = View::factory('template/header')->bind('user', $this->user)->bind('site_name', $site_name)->bind('dashboard_url', $this->dashboard_url);
         $this->template->header->js = '';
         // Dynamic Javascript
         $this->template->header->css = '';
         // Dynamic CSS
         $this->template->header->meta = '';
         $this->template->header->show_nav = TRUE;
         $site_name = Model_Setting::get_setting('site_name');
         // Header Nav
         $this->template->header->nav_header = View::factory('template/nav/header')->bind('user', $this->user)->bind('admin', $this->admin)->bind('account', $this->account)->bind('anonymous', $this->anonymous);
         $this->template->header->nav_header->controller = $this->request->controller();
         if ($this->user) {
             $this->template->header->nav_header->num_notifications = Model_User_Action::count_notifications($this->user->id);
             if (!($buckets = Cache::instance()->get('user_buckets_' . $this->user->id, FALSE))) {
                 $buckets = json_encode($this->user->get_buckets_array($this->user));
                 Cache::instance()->set('user_buckets_' . $this->user->id, $buckets, 3600 + rand(0, 3600));
             }
             $this->template->header->bucket_list = $buckets;
             if (!($rivers = Cache::instance()->get('user_rivers_' . $this->user->id, FALSE))) {
                 $rivers = json_encode($this->user->get_rivers_array($this->user));
                 Cache::instance()->set('user_rivers_' . $this->user->id, $rivers, 3600 + rand(0, 3600));
             }
             $this->template->header->river_list = $rivers;
         }
         $this->template->content = '';
         $this->template->footer = View::factory('template/footer');
         if (!in_array($this->request->controller(), array('river', 'bucket', 'search'))) {
             // Reset cookies
             Cookie::set(Swiftriver::COOKIE_SEARCH_SCOPE, 'all');
         }
     }
 }
Example #25
0
 /**
  * @return	void
  */
 public function action_index()
 {
     // Get the id of the current river
     $river_id = $this->river->id;
     // Cookies to help determine the search options to display
     Cookie::set(Swiftriver::COOKIE_SEARCH_SCOPE, 'river');
     Cookie::set(Swiftriver::COOKIE_SEARCH_ITEM_ID, $river_id);
     // The maximum droplet id for pagination and polling
     $max_droplet_id = 0;
     if (!($max_droplet_id = $this->cache->get('river_max_id_' . $river_id, FALSE))) {
         $max_droplet_id = Model_River::get_max_droplet_id($river_id);
         // Cache for 90s
         $this->cache->set('river_max_id_' . $river_id, $max_droplet_id, 90);
     }
     // River filters
     $filters = $this->_get_filters();
     //Get Droplets
     $droplets_array = Model_River::get_droplets($this->user->id, $river_id, 0, 1, $max_droplet_id, NULL, $filters, $this->photos);
     // Bootstrap the droplet list
     $this->template->header->js .= Html::script("themes/default/media/js/drops.js");
     $droplet_js = View::factory('pages/drop/js/drops');
     $droplet_js->fetch_base_url = $this->river_base_url;
     $droplet_js->default_view = $this->river->default_layout;
     $droplet_js->photos = $this->photos ? 1 : 0;
     // Check if any filters exist and modify the fetch urls
     $droplet_js->filters = NULL;
     if (!empty($filters)) {
         $droplet_js->filters = json_encode($filters);
     }
     $droplet_js->droplet_list = json_encode($droplets_array['droplets']);
     $droplet_js->max_droplet_id = $max_droplet_id;
     $droplet_js->channels = json_encode($this->river->get_channels());
     // Select droplet list view with drops view as the default if list not specified
     $this->droplets_view = View::factory('pages/drop/drops')->bind('droplet_js', $droplet_js)->bind('user', $this->user)->bind('owner', $this->owner)->bind('anonymous', $this->anonymous);
     // Show expiry notice to owners only
     if ($this->owner and $this->river->is_expired($this->owner)) {
         $this->droplets_view->nothing_to_display = "";
         $expiry_notice = View::factory('pages/river/expiry_notice');
         $expiry_notice->river_base_url = $this->river_base_url;
         $expiry_notice->expiry_extension_token = $this->river->expiry_extension_token;
         $expiry_notice->extension_period = Model_Setting::get_setting('river_active_duration');
         $this->droplets_view->expiry_notice = $expiry_notice;
     } else {
         $this->droplets_view->expiry_notice = '';
         $this->droplets_view->nothing_to_display = View::factory('pages/river/nothing_to_display')->bind('anonymous', $this->anonymous);
         $this->droplets_view->nothing_to_display->river_url = $this->request->url(TRUE);
     }
 }