Projekt

Obecné

Profil

« Předchozí | Další » 

Revize 790

Přidáno uživatelem Michal Kliment před téměř 14 roky(ů)

Vytvoreni adresare testing pro testovaci verzi (mezistupen mezi branchem a trunkem).

Zobrazit rozdíly:

freenetis/testing/application/libraries/MY_Controller.php
<?php defined('SYSPATH') or die('No direct script access.');
// numbers of errors
define("ACCESS", "1");
define("EMAIL", "2");
define("DATABASE", "3");
define("RECORD", "4");
define("PAGE", "5");
define("UPGRADE", "6");
define("WRITABLE", "7");
// numbers of warnings, their identifier numbers have to differ from error messages
// for example when programmer misleads error and warning
define("PARAMETER", "1001");
/**
* Main controller creates menu, handles changes in svn repository (database upgrade), ...
*
*/
class Controller extends Controller_Core
{
/** @staticvar Controller Controller singleton */
private static $instance;
/** @var gacl PHP GACL class */
public $gacl_class;
/** @var unknown_type */
public $arr;
/** @var Setting_Model Settings */
public $settings = NULL;
/** @var array */
public $upgrade_sql = array();
/** @var integer */
public $current_svn_db_schema_version = 0;
/** @var integer */
public $popup = 0;
/** @var integer */
public $dialog = 0;
/** @var integer */
private $ICON_ERROR = 1;
/** @var integer */
private $ICON_GOOD = 2;
/** @var integer */
private $ICON_HELP = 3;
/** @var integer */
private $ICON_INFO = 4;
/** @var integer */
private $ICON_WARNING = 5;
public function __construct()
{
parent::__construct();
// This part only needs to be run once
if (self::$instance === NULL)
{
$this->session = Session::instance();
$this->settings = new Settings();
// if true, freenetis will run in popup mode (without header and menu)
$this->popup = (isset($_GET['popup']) && $_GET['popup']) ? 1 : 0;
// if true, freenetis will run in text mod for dialog
$this->dialog = (isset($_GET['dialog']) && $_GET['dialog']) ? 1 : 0;
// database upgrade goes here
$this->get_current_svn_db_schema_info();
// config file doesn't exist, we must create it
if (!file_exists('config.php'))
{
// protection before loop
if (url_lang::current(1) == 'setup_config')
return;
url::redirect(url_lang::base().'setup_config');
}
// protection before loop
if (url_lang::current(1) == 'installation')
return;
// test database connection
if (!db::test())
Controller::error(DATABASE);
// db schema version is null
if (!$this->settings->get('db_schema_version'))
{
// we must run install
url::redirect(url_lang::base().'installation');
}
// db schema is not up to date
else if ($this->current_svn_db_schema_version != $this->settings->get('db_schema_version'))
{
// we must run upgrade
$this->upgrade_sql($this->settings->get('db_schema_version'));
}
// test if visitor is logged in, or he accesses public controllers like registration, redirect, installation
if (!$this->session->get('user_id', 0) &&
url_lang::current()!='login' &&
url_lang::current()!='forgotten_password' &&
url_lang::current() != 'registration' &&
url_lang::current()!='scheduler/run' &&
strpos(url_lang::current(), 'redirect')===false &&
url_lang::current()!='installation')
{
// Not logged in - redirect to login page
$this->session->set_flash('err_message', url_lang::lang('texts.Must be logged in'));
if (url_lang::current()!='installation')
{
$this->session->set('referer',url_lang::current());
}
url::redirect(url_lang::base().'login');
die();
}
/**
* @todo: after removing all direct calls made through $gacl_class,
* remove the phpgacl initialization - so components which does not
* need it would save the 1.5MB of RAM requested by phpgacl
*/
$this->phpgacl_init();
// Singleton instance
self::$instance = $this;
}
}
/**
* @author Michal Kliment
* Singleton instance of Controller.
* @return Controller object
*/
public static function instance()
{
// Create the instance if it does not exist
empty(self::$instance) and new Controller;
return self::$instance;
}
/**
* Function shows error of given message number.
* @param $message
* @param $content
* @return unknown_type
*/
public function error($message_type, $content = NULL)
{
switch ($message_type)
{
case ACCESS:
$message = url_lang::lang('states.Access denied');
$this->showbox($message, $this->ICON_ERROR, $content);
break;
case EMAIL:
$message = url_lang::lang('states.Failed to send e-mail').'<br />'.url_lang::lang('states.Please check settings.');
$this->showbox($message, $this->ICON_ERROR, $content);
break;
case DATABASE:
$message = url_lang::lang('states.Failed to connect to database').'<br />'.url_lang::lang('states.Please check settings.');
$this->showbox($message, $this->ICON_ERROR, $content);
break;
case RECORD:
$message = url_lang::lang('states.This record does not exist');
$this->showbox($message, $this->ICON_ERROR, $content);
break;
case PAGE:
$message = url_lang::lang('states.Page not found');
$this->showbox($message, $this->ICON_ERROR, $content);
break;
case UPGRADE:
$message = url_lang::lang('states.Database upgrade failed');
$this->showbox($message, $this->ICON_ERROR, $content);
break;
case WRITABLE:
$message = url_lang::lang('states.Directory or file is not writable.');
$this->showbox($message, $this->ICON_ERROR, $content);
break;
default:
$message = url_lang::lang('states.Unknown error message');
$this->showbox($message, $this->ICON_WARNING, $content);
break;
}
}
/**
* Function shows warning of given message number.
* @param $message
* @param $content
* @return unknown_type
*/
public function warning($message, $content = NULL)
{
switch ($message)
{
case PARAMETER:
$message = url_lang::lang('states.Parameter required');
$this->showbox($message, $this->ICON_WARNING, $content);
break;
default:
$message = url_lang::lang('states.Unknown warning message');
$this->showbox($message, $this->ICON_WARNING, $content);
break;
}
}
/**
* Function renders error and warning messages.
* @param $message
* @param $type
* @param $content
* @return unknown_type
*/
private function showbox($message, $type, $content = NULL)
{
$view = new View('main');
$view->content = new View('statesbox');
switch ($type)
{
case $this->ICON_ERROR:
$view->title = url_lang::lang('texts.Error');
$view->content->icon = html::image(array('src' => 'media/images/states/error.png', 'width' => '100', 'height' => '100', 'alt' => 'Image', 'class' => 'noborder'));
break;
case $this->ICON_GOOD:
$view->title = url_lang::lang('texts.Good');
$view->content->icon = html::image(array('src' => 'media/images/states/good.png', 'width' => '100', 'height' => '100', 'alt' => 'Image', 'class' => 'noborder'));
break;
case $this->ICON_HELP:
$view->title = url_lang::lang('texts.Help');
$view->content->icon = html::image(array('src' => 'media/images/states/help.png', 'width' => '100', 'height' => '100', 'alt' => 'Image', 'class' => 'noborder'));
break;
case $this->ICON_INFO:
$view->title = url_lang::lang('texts.Info');
$view->content->icon = html::image(array('src' => 'media/images/states/info.png', 'width' => '100', 'height' => '100', 'alt' => 'Image', 'class' => 'noborder'));
break;
case $this->ICON_WARNING:
$view->title = url_lang::lang('texts.Warning');
$view->content->icon = html::image(array('src' => 'media/images/states/warning.png', 'width' => '100', 'height' => '100', 'alt' => 'Image', 'class' => 'noborder'));
break;
}
$view->content->message = $message;
if (isset($content))
$view->content->content = $content;
$view->render(TRUE);
// must be die() - else it will be render twice !
die();
}
/**
* Setup revision database schema.
*/
function get_current_svn_db_schema_info()
{
require_once("application/upgrade_sql/upgrade_sql.php");
$this->current_svn_db_schema_version = get_SVN_rev();
$this->upgrade_sql[$this->current_svn_db_schema_version] = $upgrade_sql[$this->current_svn_db_schema_version];
}
/**
* Upgrade database from current version to latest version.
* @todo Using database transaction, because of data integrity.
* THERE IS NO WAY TO DO SO IN MYSQL... :-(
* Code which using transactions was commented. (saved for future..)
* @param integer $from_version From which version(revision) upgrade starts
*/
function upgrade_sql($from_version = 0)
{
$ok = true;
$this->db = new Database();
$config = new Config_Model();
// for each revision
for ($i = ($from_version+1); $i<($this->current_svn_db_schema_version); $i++)
{
if (file_exists("application/upgrade_sql/upgrade_sql_".$i.".php"))
{
require("application/upgrade_sql/upgrade_sql_".$i.".php");
// database transaction
try
{
/*if (!$this->db->query('SET AUTOCOMMIT=0'))
{
throw new Kohana_Database_Exception();
}
if (!$this->db->query('BEGIN'))
{
throw new Kohana_Database_Exception();
}*/
foreach ($upgrade_sql[$i] as $query)
{
if(!$this->db->query($query))
{
throw new Kohana_Database_Exception();
}
}
/*if (!$this->db->query('COMMIT'))
{
throw new Kohana_Database_Exception();
}
if (!$this->db->query('SET AUTOCOMMIT=1'))
{
throw new Kohana_Database_Exception();
}*/
}
catch (Kohana_Database_Exception $e)
{
/*$this->db->query('ROLLBACK');
$this->db->query('SET AUTOCOMMIT=1');*/
$message = "SVN: $i <br />"
.url_lang::lang('texts.file').": upgrade_sql_$i.php<br /><br />
$query";
$this->error(UPGRADE, $message);
}
// set up db schema
$config->set_db_schema_version($i);
}
}
// do SQL queries from upgrade_sql file
try
{
/*if (!$this->db->query('SET AUTOCOMMIT=0'))
{
throw new Kohana_Database_Exception();
}
if (!$this->db->query('BEGIN'))
{
throw new Kohana_Database_Exception();
}*/
foreach ($this->upgrade_sql[$this->current_svn_db_schema_version] as $query)
{
if(!$this->db->query($query))
{
throw new Kohana_Database_Exception();
}
}
/*if (!$this->db->query('COMMIT'))
{
throw new Kohana_Database_Exception();
}
if (!$this->db->query('SET AUTOCOMMIT=1'))
{
throw new Kohana_Database_Exception();
}*/
}
catch (Kohana_Database_Exception $e)
{
/*$this->db->query('ROLLBACK');
$this->db->query('SET AUTOCOMMIT=1');*/
$message = "SVN: $i <br />"
.url_lang::lang('texts.file').": upgrade_sql.php<br /><br />
$query";
$this->error(UPGRADE, $message);
}
// set up db schema
$config->set_db_schema_version($this->current_svn_db_schema_version);
}
/**
* Inicialization of PHP GACL modul.
*/
public function phpgacl_init() {
require_once(APPPATH.'vendors/phpgacl/gacl.class.php');
$this->gacl_class = new gacl();
}
/**
* acl_check_2D checks the current user's rights to access an $aco_section/$aco_value
*/
public function acl_check_2D($aco_section, $aco_value) {
if (!isset($this->gacl_class)) $this->phpgacl_init();
return $this->gacl_class->acl_check($aco_section, $aco_value, 'all', $_SESSION['username']);
}
/**
* acl_check_3D checks the current user's rights to access
* an $axo_value object in ***current controller*** (!!!) by
* operation specified by $aco_section/$aco_value
*/
public function acl_check_3D($aco_section, $aco_value, $axo_value) {
if (!isset($this->gacl_class)) $this->phpgacl_init();
return $this->gacl_class->acl_check($aco_section, $aco_value, 'all', $_SESSION['username'],get_class($this),$axo_value);
}
/**
* Fuction checks access rights
* Return true if currently logged user (stored in $_SESSION['username'])
* may view own $axo_value object in $axo_section
* (and in variable $member_id is his own id of member) or if currently logged user
* may view all $axo_value object in $axo_section else return false
*
* @param $axo_section group of objects to view
* @param $axo_value object to view
* @param $member_id optional variable, id of other member who is being showed by logged member
* @return boolean returns true if member has enough access rights
*/
public function acl_check_view($axo_section, $axo_value, $member_id = NULL)
{
$return = false;
if (!isset($this->gacl_class)) $this->phpgacl_init();
if($member_id==$_SESSION['member_id'])
{
if ($this->gacl_class->acl_check('freenetis', 'view_own', 'all', $_SESSION['username'],$axo_section,$axo_value)) $return = true;
}
if ($this->gacl_class->acl_check('freenetis', 'view_all', 'all', $_SESSION['username'],$axo_section,$axo_value)) $return = true;
return $return;
}
/**
* Fuction checks access rights
* Return true if currently logged user (stored in $_SESSION['username'])
* may view own $axo_value object in $axo_section
* (and in variable $member_id is his own id of member) or if currently logged user
* may edit all $axo_value object in $axo_section else return false
*
* @param $axo_section group of objects to edit
* @param $axo_value object to edit
* @param $member_id optional variable, id of other member who is being showed by logged member
* @return boolean returns true if member has enough access rights
*/
public function acl_check_edit($axo_section, $axo_value, $member_id = NULL)
{
$return = false;
if (!isset($this->gacl_class)) $this->phpgacl_init();
if($member_id==$_SESSION['member_id'])
{
if ($this->gacl_class->acl_check('freenetis', 'edit_own', 'all', $_SESSION['username'],$axo_section,$axo_value)) $return = true;
}
if ($this->gacl_class->acl_check('freenetis', 'edit_all', 'all', $_SESSION['username'],$axo_section,$axo_value)) $return = true;
return $return;
}
/**
* Fuction checks access rights
* Return true if currently logged user (stored in $_SESSION['username'])
* may view own $axo_value object in $axo_section
* (and in variable $member_id is his own id of member) or if currently logged user
* may add all $axo_value object in $axo_section else return false
*
* @param $axo_section group of objects to edit
* @param $axo_value object to add
* @param $member_id optional variable, id of other member who is being showed by logged member
* @return boolean returns true if member has enough access rights
*/
public function acl_check_new($axo_section, $axo_value, $member_id = NULL)
{
$return = false;
if (!isset($this->gacl_class)) $this->phpgacl_init();
if($member_id==$_SESSION['member_id'])
{
if ($this->gacl_class->acl_check('freenetis', 'new_own', 'all', $_SESSION['username'],$axo_section,$axo_value)) $return = true;
}
if ($this->gacl_class->acl_check('freenetis', 'new_all', 'all', $_SESSION['username'],$axo_section,$axo_value)) $return = true;
return $return;
}
/**
* Fuction checks access rights
* Return true if currently logged user (stored in $_SESSION['username'])
* may view own $axo_value object in $axo_section
* (and in variable $member_id is his own id of member) or if currently logged user
* may delete all $axo_value object in $axo_section else return false
*
* @param $axo_section group of objects to edit
* @param $axo_value object to delete
* @param $member_id optional variable, id of other member who is being showed by logged member
* @return boolean returns true if member has enough access rights
*/
public function acl_check_delete($axo_section, $axo_value, $member_id = NULL)
{
$return = false;
if (!isset($this->gacl_class)) $this->phpgacl_init();
if($member_id==$_SESSION['member_id'])
{
if ($this->gacl_class->acl_check('freenetis', 'delete_own', 'all', $_SESSION['username'],$axo_section,$axo_value)) $return = true;
}
if ($this->gacl_class->acl_check('freenetis', 'delete_all', 'all', $_SESSION['username'],$axo_section,$axo_value)) $return = true;
return $return;
}
/**
* Fuction checks access rights
* Return true if currently logged user (stored in $_SESSION['username'])
* may view own $axo_value object in $axo_section
* (and in variable $member_id is his own id of member) or if currently logged user
* may confirm all $axo_value object in $axo_section else return false
*
* @param $axo_section group of objects to edit
* @param $axo_value object to confirm
* @param $member_id optional variable, id of other member who is being showed by logged member
* @return boolean returns true if member has enough access rights
*/
public function acl_check_confirm($axo_section, $axo_value, $member_id = NULL)
{
if (!isset($this->gacl_class)) $this->phpgacl_init();
if($member_id==$_SESSION['member_id'])
{
return $this->gacl_class->acl_check('freenetis', 'confirm_own', 'all', $_SESSION['username'],$axo_section,$axo_value);
}
else
{
return $this->gacl_class->acl_check('freenetis', 'confirm_all', 'all', $_SESSION['username'],$axo_section,$axo_value);
}
}
/**
* Function probably assigns role to user.
* @param $user_id
* @param $username
* @param $value
* @param $group
* @param $is_edit
* @return unknown_type
*/
public function insert_phpgacl($user_id,$username,$value,$group, $is_edit = false)
{
$aro_group_data = new Groups_aro_map_Model();
switch ($group) {
case 'member':
$group_id = 22;
break;
case 'wannabe':
$group_id = 23;
break;
default:
$group_id = 22;
break;
}
$group_arr = array();
$group_arr['group_id'] = $group_id;
if ($is_edit)
{
$aro_group_data->insert_data($group_arr, $user_id);
}
else
{
$group_arr['aro_id'] = $user_id;
$aro_group_data->insert_data($group_arr);
}
}
}
?>
freenetis/testing/application/libraries/Form_Input.php
<?php defined('SYSPATH') or die('No direct script access.');
/**
* FORGE base input library.
*
* $Id: Form_Input.php 1923 2008-02-05 14:49:08Z Shadowhand $
*
* @package Forge
* @author Kohana Team
* @copyright (c) 2007-2008 Kohana Team
* @license http://kohanaphp.com/license.html
*/
class Form_Input_Core {
// Input method
public $method;
// Element data
protected $data = array
(
'type' => 'text',
'class' => 'textbox',
'value' => ''
);
// Protected data keys
protected $protect = array();
// Validation rules, matches, and callbacks
protected $rules = array();
protected $matches = array();
protected $callbacks = array();
// Validation check
protected $is_valid;
// Errors
protected $errors = array();
protected $error_messages = array();
/**
* Sets the input element name.
*/
public function __construct($name)
{
$this->data['name'] = $name;
}
/**
* Sets form attributes, or return rules.
*/
public function __call($method, $args)
{
if ($method == 'rules')
{
if (empty($args))
return $this->rules;
// Set rules and action
$rules = $args[0];
$action = substr($rules, 0, 1);
if (in_array($action, array('-', '+', '=')))
{
// Remove the action from the rules
$rules = substr($rules, 1);
}
else
{
// Default action is append
$action = '';
}
$this->add_rules(explode('|', $rules), $action);
}
elseif ($method == 'name')
{
// Do nothing. The name should stay static once it is set.
}
else
{
$this->data[$method] = $args[0];
}
return $this;
}
/**
* Returns form attributes.
*
* @param string attribute name
* @return string
*/
public function __get($key)
{
if (isset($this->data[$key]))
{
return $this->data[$key];
}
}
/**
* Sets a form element that this element must match the value of.
*
* @chainable
* @param object another Forge input
* @return object
*/
public function matches($input)
{
if ( ! in_array($input, $this->matches, TRUE))
{
$this->matches[] = $input;
}
return $this;
}
/**
* Sets a callback method as a rule for this input.
*
* @chainable
* @param callback
* @return object
*/
public function callback($callback)
{
if ( ! in_array($callback, $this->callbacks, TRUE))
{
$this->callbacks[] = $callback;
}
return $this;
}
public function name($val = NULL)
{
if ($val === NULL)
{
return $this->data['name'];
}
else
{
$this->data['name'] = $val;
}
}
/**
* Sets or returns the input label.
*
* @chainable
* @param string label to set
* @return string|object
*/
public function label($val = NULL)
{
if ($val === NULL)
{
if (isset($this->data['name']) AND isset($this->data['label']))
{
return form::label($this->data['name'], $this->data['label']);
}
return FALSE;
}
else
{
$this->data['label'] = ($val === TRUE) ? utf8::ucwords(inflector::humanize($this->name)) : $val;
return $this;
}
}
public function help($val = NULL)
{
if ($val === NULL)
{
if (isset($this->data['help']))
return $this->data['help'];
}
else
{
$this->data['help'] = $val;
return $this;
}
}
public function script($type, $val = NULL)
{
if ($val === NULL)
{
if (isset($this->data[$type]))
return $this->data[$type];
}
else
{
$this->data[$type] = $val;
return $this;
}
}
/**
* Set or return the error message.
*
* @chainable
* @param string error message
* @return strong|object
*/
public function message($val = NULL)
{
if ($val === NULL)
{
if (isset($this->data['message']))
return $this->data['message'];
}
else
{
$this->data['message'] = $val;
return $this;
}
}
/**
* Runs validation and returns the element HTML.
*
* @return string
*/
public function html()
{
// Make sure validation runs
$this->validate();
return $this->html_element();
}
/**
* Returns the form input HTML.
*
* @return string
*/
protected function html_element()
{
$data = $this->data;
unset($data['label']);
unset($data['message']);
unset($data['help']);
// array with aliases of validation function
$alias = array('numeric' => 'number');
// convert to array
$data['class'] = array($data['class']);
foreach ($this->rules as $rule)
{
if (substr($rule,0,6)=='valid_')
{
$arr = explode('_',$rule);
array_shift($arr);
$rule = implode('_',$arr);
$rule = (isset($alias[$rule])) ? $alias[$rule] : $rule;
$data['class'][] = $rule;
}
else
{
if (preg_match ("/length\[([0-9]+),([0-9]+)\]/", $rule, $matches))
{
$data['minlength'] = $matches[1];
$data['maxlength'] = $matches[2];
}
}
}
foreach ($this->callbacks as $callback)
{
$callback = $callback[1];
if (substr($callback,0,6)=='valid_')
{
$arr = explode('_',$callback);
array_shift($arr);
$callback = implode('_',$arr);
$callback = (isset($alias[$callback])) ? $alias[$callback] : $callback;
$data['class'][] = $callback;
}
}
$data['class'] = implode (' ',$data['class']);
return form::input($data);
}
/**
* Replace, remove, or append rules.
*
* @param array rules to change
* @param string action to use: replace, remove, append
*/
protected function add_rules( array $rules, $action)
{
if ($action === '=')
{
// Just replace the rules
$this->rules = $rules;
return;
}
foreach($rules as $rule)
{
if ($action === '-')
{
if (($key = array_search($rule, $this->rules)) !== FALSE)
{
// Remove the rule
unset($this->rules[$key]);
}
}
else
{
if ( ! in_array($rule, $this->rules))
{
if ($action == '+')
{
array_unshift($this->rules, $rule);
}
else
{
$this->rules[] = $rule;
}
}
}
}
}
/**
* Add an error to the input.
*
* @chainable
* @return object
*/
public function add_error($key, $val)
{
if ( ! isset($this->errors[$key]))
{
$this->errors[$key] = $val;
}
return $this;
}
/**
* Set or return the error messages.
*
* @chainable
* @param string|array failed validation function, or an array of messages
* @param string error message
* @return object|array
*/
public function error_messages($func = NULL, $message = NULL)
{
// Set custom error messages
if ( ! empty($func))
{
if (is_array($func))
{
// Replace all
$this->error_messages = $func;
}
else
{
if (empty($message))
{
// Single error, replaces all others
$this->error_messages = $func;
}
else
{
// Add custom error
$this->error_messages[$func] = $message;
}
}
return $this;
}
// Make sure validation runs
is_null($this->is_valid) and $this->validate();
// Return single error
if ( ! is_array($this->error_messages) AND ! empty($this->errors))
return array($this->error_messages);
$messages = array();
foreach($this->errors as $func => $args)
{
if (is_string($args))
{
$error = $args;
}
else
{
// Force args to be an array
$args = is_array($args) ? $args : array();
// Add the label or name to the beginning of the args
array_unshift($args, $this->label ? utf8::strtolower($this->label) : $this->name);
if (isset($this->error_messages[$func]))
{
// Use custom error message
$error = vsprintf($this->error_messages[$func], $args);
}
else
{
// Get the proper i18n entry, very hacky but it works
switch($func)
{
case 'valid_url':
case 'valid_email':
case 'valid_ip':
// Fetch an i18n error message
$error = Kohana::lang('validation.'.$func, $args);
break;
case 'valid_suffix':
$error = Kohana::lang('validation.valid_suffix', $args);
break;
case substr($func, 0, 6) === 'valid_':
// Strip 'valid_' from func name
$func = (substr($func, 0, 6) === 'valid_') ? substr($func, 6) : $func;
case 'alpha':
case 'alpha_dash':
case 'digit':
case 'numeric':
// i18n strings have to be inserted into valid_type
$args[] = Kohana::lang('validation.'.$func);
$error = Kohana::lang('validation.valid_type', $args);
break;
default:
$error = Kohana::lang('validation.'.$func, $args);
}
}
}
// Add error to list
$messages[] = $error;
}
return $messages;
}
/**
* Get the global input value.
*
* @return string|bool
*/
protected function input_value()
{
static $input, $method;
if ($input === NULL)
{
// Load the Input library
$input = new Input;
}
// Fetch the method for this object
$method = $this->method;
if (func_num_args() > 0)
{
$name = func_get_arg(0);
if (preg_match ("/^([^\[]+)(\[([0-9]+)\])+$/", $name, $matches))
{
$name = $matches[1];
$value = $input->$method($name);
return (isset($value[$matches[3]])) ? $value[$matches[3]] : '';
}
return $input->$method($name);
}
else
return $input->$method();
}
/**
* Load the value of the input, if form data is present.
*
* @return void
*/
protected function load_value()
{
if (is_bool($this->is_valid))
return;
if ($name = $this->name)
{
// Load POSTed value, but only for named inputs
$this->data['value'] = $this->input_value($name);
}
if (is_string($this->data['value']))
{
// Trim string values
$this->data['value'] = trim($this->data['value']);
}
}
/**
* Validate this input based on the set rules.
*
* @return bool
*/
public function validate()
{
// Validation has already run
if (is_bool($this->is_valid))
return $this->is_valid;
// No data to validate
if ($this->input_value() == FALSE)
return $this->is_valid = FALSE;
// Load the submitted value
$this->load_value();
// No rules to validate
if (count($this->rules) == 0 AND count($this->matches) == 0 AND count($this->callbacks) == 0)
return $this->is_valid = TRUE;
if ( ! empty($this->rules))
{
foreach($this->rules as $rule)
{
if (($offset = strpos($rule, '[')) !== FALSE)
{
// Get the args
$args = preg_split('/, ?/', trim(substr($rule, $offset), '[]'));
// Remove the args from the rule
$rule = substr($rule, 0, $offset);
}
if (substr($rule, 0, 6) === 'valid_' AND method_exists('valid', substr($rule, 6)))
{
$func = substr($rule, 6);
if ($this->value AND ! valid::$func($this->value))
{
$this->errors[$rule] = TRUE;
}
}
elseif (method_exists($this, 'rule_'.$rule))
{
// The rule function is always prefixed with rule_
$rule = 'rule_'.$rule;
if (isset($args))
{
// Manually call up to 2 args for speed
switch(count($args))
{
case 1:
$this->$rule($args[0]);
break;
case 2:
$this->$rule($args[0], $args[1]);
break;
default:
call_user_func_array(array($this, $rule), $args);
break;
}
}
else
{
// Just call the rule
$this->$rule();
}
// Prevent args from being re-used
unset($args);
}
else
{
throw new Kohana_Exception('validation.invalid_rule', $rule);
}
// Stop when an error occurs
if ( ! empty($this->errors))
break;
}
}
if ( ! empty($this->matches))
{
foreach($this->matches as $input)
{
if ($this->value != $input->value)
{
// Field does not match
$this->errors['matches'] = array($input->name);
break;
}
}
}
if ( ! empty($this->callbacks))
{
foreach($this->callbacks as $callback)
{
call_user_func($callback, $this);
// Stop when an error occurs
if ( ! empty($this->errors))
break;
}
}
// If there are errors, validation failed
return $this->is_valid = empty($this->errors);
}
/**
* @author Ondřej Fibich
* Chceck if value is GPS coordinate if it is not empty
*/
protected function rule_gps()
{
if ($this->value)
{
if (preg_match("/^[0-9]+\.[0-9]+$/", strval($this->value)) == 0)
{
if (! gps::is_valid_degrees_coordinate(strval($this->value)))
{
$this->errors['required'] = TRUE;
}
}
}
}
/**
* Validate required.
*/
protected function rule_required()
{
if ($this->value == FALSE)
{
$this->errors['required'] = TRUE;
}
}
/**
* Validate length.
*/
protected function rule_length($min, $max = NULL)
{
// Get the length, return if zero
if (($length = strlen($this->value)) === 0)
return;
if ($max == NULL)
{
if ($length != $min)
{
$this->errors['exact_length'] = array($min);
}
}
else
{
if ($length < $min)
{
$this->errors['min_length'] = array($min);
}
elseif($length > $max)
{
$this->errors['max_length'] = array($max);
}
}
}
} // End Form Input
freenetis/testing/application/libraries/Parser_Ebanka.php
<?php defined('SYSPATH') or die('No direct script access.');
require_once("Parser_Html_Table.php");
/*
ALTER TABLE `money_transfer_bank_infos`
ADD COLUMN `comment` VARCHAR(255) after `date_time`;
ALTER TABLE `accounts`
ADD COLUMN `number` VARCHAR(255) after `name`;
* */
/**
* @author Tomas <Dulik at unart dot cz>
* @version 1.0
* Parser_Ebanka is a parser for getting data from bank account transaction listing
* in the HTML format used by the Czech bank called "Ebanka" (now Raiffeisen Bank).
*
* The parsing is a bit peculiar, because Ebanka uses different format for
* listings that are visible to general public (the "transparent" listing used
* by NGOV non-profit organizations) and different format for regular listing used in the
* ebanking application.
* This parser autodetects these two formats and parses the data according to it.
*
* Benchmarks:
* Machine: Notebook FSC Lifebook S7110, CPU: Pentium T2400 @ 1.8 GHz
* Win XP SP2, Apache 2.2.3, PHP 5.2.0
* Regular listing with 136 table rows (1 week listing): time=0.1 sec, memory=205 kB
* Regular listing with 2175 table rows (whole year listing): time=1.6 sec, memory=205 kB
* Transparent listing with 467 table rows: time=0.14 sec, memory=122 kB
* */
class Parser_Ebanka extends Parser_Html_Table {
const START_STRING="Pohyby na"; //Poslední řetězec před začátkem hlavní <TABLE>
const YEAR_STRING=" za "; //U běžných (netransparentních) výpisů
const ACCOUNT_STRING="IBAN:"; //
protected $year=false; //rok výpisu ze záhlaví výpisu
/**
* $callback obsahuje jméno funkce, která se má zavolat poté, co naparsujeme
* 1 kompletní řádek HTML tabulky. Více viz metoda
* @see set_callback
* @var string|mixed
*/
protected $callback; //callback funkce, kterou můžeme volat např. pro uložení každého řádku výpisu do DB
/**
* @var object $result je vkládán do 1. parametru $callback funkce, která přes něj předává jeden řádek výsledku.
* Pokud $result není nastaven funkcí set_callback, pak jde je nastaven na instanci std_class */
protected $result;
/**
* funkce get_year(..) slouží k tomu, aby z bufferu, který začíná
* za řetězcem "Za obdob", např. buffer="í 1.12.2007/31.12.2007</td>
* vytáhla rok výpisu - v tomto příkladě "2007" */
protected function get_year() {
while (($dotPos=strpos($this->buffer, "."))===false &&
$this->get_line()); // hledej první "." v datumu
if ($dotPos===false) die("Nemůžu najít první znak '.' v řetězci ' za [období] ...'");
else {
$toDot=substr($this->buffer, $dotPos+1);
// hledej 2. tečku zpět od lomítka:
if (($dotPos2=strpos($toDot, "."))===false)
die("Nemůžu najít druhý znak '.' v řetězci 'za [období] ...'");
}
$this->year=substr($toDot, $dotPos2+1, 4); // získej rok výpisu
}
protected function get_cislo_uctu() {
while (($czPos=stripos($this->buffer, "CZ"))===false &&
$this->get_line()); // hledej lomítko
if ($czPos===false) die("Nemůžu najít 'CZ' v IBAN čísle účtu'");
else {
$this->result->parsed_acc_bank_nr=substr($this->buffer, $czPos+4, 4);
$account_nr=(int)substr($this->buffer, $czPos+8, 16);
$this->result->parsed_acc_nr="$account_nr";
}
}
protected function get_amount($field) {
$field=strip_tags($field);
$field=str_replace(array(" ", " "), "", $field);
return strtr($field, ",", ".");
}
/**
* V posledním sloupci HTML výpisu ebanka dává tyto poplatky: Poplatek, směna, zpráva.
* Poplatky jsou odděleny značkami <br>, u transp. výpisu <br/>
* @param $field
* @param $transparent
* @return součet všech poplatků generovaných pro daný řádek
*/
protected function get_fee($field, $transparent) {
$field=str_replace(array(" ", " "), "", $field);
$field=strtr($field, ",", ".");
if ($transparent) $br_tag="<br/>";
else $br_tag="<br>";
$arr=preg_split("/<br>/si", $field);
$fee=0;
foreach ($arr as $value)
$fee+=$value;
return $fee;
}
protected function get_data_from_transparent() {
$res = $this->result;
$first=true;
$line_nr=0;
do {
$status=$this->get_table_rows();
$nr=count($this->matches[1]);
$fields=str_replace(array("\r", "\n", "\t"), "", $this->matches[1]);
/*
if ($first) {
$i=6;
$first=false;
} else $i=0;
*/
for ($i=0; $i<$nr; $i++) {
$field_nr=$i % 6;
$field=$fields[$i];
switch ($field_nr) {
case 0: // příklad: 31.08.2008<br/>06:1
$arr=explode("<br/>", $field);
$arrDate=explode(".", $arr[0]);
$res->date_time=$arrDate[0];
//$res->date_time=$arrDate[2]."-".$arrDate[1]."-".$arrDate[0]." ".$arr[1];
break;
case 1: // Poznámky<br/>Název účtu plátce
$field=html_entity_decode($field,ENT_QUOTES,"UTF-8");
$arr=explode("<br/>", $field);
$res->comment=$arr[0];
$res->name=$arr[1];
break;
case 2: //2x za sebou datum odepsání<br/>typ platby
$arr=explode("<br/>", $field);
$res->type=html_entity_decode($arr[2],ENT_QUOTES,"UTF-8");
break;
case 3:
$arr=explode("<br/>", $field); //VS<br/>KS<br/>SS
$res->variable_symbol=(int)$arr[0];
$res->constant_symbol=$arr[1];
$res->specific_symbol=(int)$arr[2];
break;
case 4:
$res->amount=$this->get_amount($field); // částka
break;
case 5:
$res->fee=$this->get_fee($field, TRUE); // fee
$line_nr++;
$res->number=$line_nr;
//ted uz muzeme ulozit ziskane data do databaze:
if (isset($this->callback)) call_user_func($this->callback, $res);
break;
} // switch
} // for
} while ( $status!== false );
}
protected function get_data_from_regular() {
$res = $this->result;
$first=true;
do {
if (($status=$this->get_table_rows())!==FALSE) {
$nr=count($this->matches[1]);
$fields=str_replace(array("\r", "\n", "\t"), "", $this->matches[1]);
if ($first) {
$i=7;
$first=false;
} else $i=0;
for (; $i<$nr; $i++) {
$field_nr=$i % 7;
$field=$fields[$i];
$field=html_entity_decode($field,ENT_QUOTES,"UTF-8"); // odstraneni &nbsp;
$field=str_replace(" ", "", $field);
switch ($field_nr) {
case 0: // číslo výpisu, každý měsíc od 1 do N
if (!is_numeric($field)) {
ob_flush();
flush();
trigger_error("Parser error: ".
"očekával jsem číslo výpisu, ale dostal jsem:<br/>\n".$field.
"<br/> \nPoslední správně načtený řádek výpisu má číslo ".$res->number.
"<br/> \nCelý vstupní buffer je: <br/>\n". htmlentities($this->buffer)
//,E_USER_ERROR
);
}
$res->number=$field;
break;
case 1: // datum a čas příklad: 08.08.<br>06:11
$arr=preg_split("/<br>/si", $field);
if (count($arr)<2)
trigger_error("Parser error: ".
"očekávám datum/čas jako dd.mm.&lt;br&gt;hh:mm ale dostal jsem:<br/>\n".$field.
"<br/> \nPoslední správně načtený řádek výpisu má číslo ".$res->number.
"<br/> \nCelý vstupní buffer je: <br/>\n". htmlentities($this->buffer),
E_USER_ERROR);
else {
$arrDate=explode(".", $arr[0]);
if (count($arrDate)<2)
trigger_error("Parser error: ".
"očekávám datum jako dd.mm. ale dostal jsem:<br/>\n".$arr[0].
"<br/> \nPoslední správně načtený řádek výpisu má číslo ".$res->number.
"<br/> \nCelý vstupní buffer je: <br/>\n". htmlentities($this->buffer),
E_USER_ERROR);
$res->date_time=$this->year."-".$arrDate[1]."-".$arrDate[0]." ".$arr[1];
}
break;
case 2: // Poznámky<br>Název účtu a<br>číslo účtu plátce
$arr=preg_split("/<br>/si", $field); // dělelní dle <BR> nebo <br>
if (isset($arr[0])) $res->comment=$arr[0];
if (isset($arr[1])) $res->name=$arr[1];
if (isset($arr[2])) {
$account_arr=explode("/", $arr[2]);
if (isset($account_arr[0])) $res->account_nr=$account_arr[0];
if (isset($account_arr[1])) $res->account_bank_nr=$account_arr[1];
}
break;
case 3: //datum odepsání<br><br>typ platby
$arr=preg_split("/<br>/si", $field);
$res->type=$arr[2];
break;
case 4: //SS<br>VS<br>KS
$arr=preg_split("/<br>/si", $field);
$res->variable_symbol=$arr[1];
$res->constant_symbol=$arr[2];
$res->specific_symbol=$arr[0];
break;
case 5: // částka
$res->amount=$this->get_amount($field);
break;
case 6: // fee
... Rozdílový soubor je zkrácen, protože jeho délka přesahuje max. limit.

Také k dispozici: Unified diff