Fixes to OSB to work with KH 3.3

This commit is contained in:
Deon George
2012-11-10 10:13:57 +11:00
parent ea36639638
commit 6db02ae77d
238 changed files with 813 additions and 938 deletions

View File

@@ -0,0 +1,85 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* This class is for rendering HTML body blocks (left, center, right).
*
* It will provide a header, body and footer.
*
* @package lnApp
* @subpackage Page
* @category Helpers
* @author Deon George
* @copyright (c) 2010 Deon George
* @license http://dev.leenooks.net/license.html
* @uses Style
*/
abstract class lnApp_Block extends HTMLRender {
protected static $_data = array();
protected static $_spacer = '<table><tr class="spacer"><td>&nbsp;</td></tr></table>';
protected static $_required_keys = array('body');
/**
* Add a block to be rendered
*
* @param array Block attributes
*/
public static function add($block,$prepend=FALSE) {
// Any body objects should be converted to a string, so that any calls to Style/Script are processed
if (isset($block['body']))
$block['body'] = (string)$block['body'];
parent::add($block);
// Detect any style sheets.
if (! empty($block['style']) && is_array($block['style']))
foreach ($block['style'] as $data=>$media)
Style::add(array(
'type'=>'file',
'data'=>$data,
'media'=>$media,
));
}
/**
* Return an instance of this class
*
* @return Block
*/
public static function factory() {
return new Block;
}
/**
* Render this block
*
* @see HTMLRender::render()
*/
protected function render() {
$output = '';
$styles = array();
$i = 0;
foreach (static::$_data as $value) {
if ($i++)
$output .= static::$_spacer;
$output .= '<table class="block" border="0">';
if (! empty($value['title']))
$output .= sprintf('<tr class="title"><td>%s</td></tr>',$value['title']);
if (! empty($value['subtitle']))
$output .= sprintf('<tr class="subtitle"><td>%s</td></tr>',$value['subtitle']);
$output .= sprintf('<tr class="body"><td>%s</td></tr>',$value['body']);
if (! empty($value['footer']))
$output .= sprintf('<tr class="footer"><td>%s</td></tr>',$value['footer']);
$output .= '</table>';
}
return $output;
}
}
?>

View File

@@ -0,0 +1,95 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* This class is for rendering HTML sub body blocks.
*
* It will provide a header, body and footer.
*
* @package lnApp
* @subpackage Page
* @category Helpers
* @author Deon George
* @copyright (c) 2010 Deon George
* @license http://dev.leenooks.net/license.html
* @uses Style
*/
class lnApp_Block_Sub extends HTMLRender {
protected static $_data = array();
protected static $_spacer = '<table><tr class="spacer"><td>&nbsp;</td></tr></table>';
protected static $_required_keys = array('body','position');
/**
* Add a block to be rendered
*
* @param array Block attributes
*/
public static function add($block,$prepend=FALSE) {
parent::add($block);
// Detect any style sheets.
if (! empty($block['style']) && is_array($block['style']))
foreach ($block['style'] as $data=>$media)
Style::add(array(
'type'=>'file',
'data'=>$data,
'media'=>$media,
));
}
/**
* Return an instance of this class
*
* @return Block
*/
public static function factory() {
return new Block_Sub;
}
/**
* Render this block
*
* @see HTMLRender::render()
*/
protected function render() {
$output = '';
$o = array();
$i = 0;
$x = $y = 0;
Sort::MAsort(static::$_data,'order,position,title,subtitle');
foreach (static::$_data as $value) {
$i = (! isset($value['order'])) ? $i+1 : $value['order'];
// Work out our dimentions
if ($value['position'] > $y)
$y = $value['position'];
if ($i > $x)
$x = $i;
// @todo Alert if a sub block has already been defined.
$o[$i][$value['position']] = '<table class="subblock" border="0">';
if (! empty($value['title']))
$o[$i][$value['position']] .= sprintf('<tr class="title"><td>%s</td></tr>',$value['title']);
if (! empty($value['subtitle']))
$o[$i][$value['position']] .= sprintf('<tr class="subtitle"><td>%s</td></tr>',$value['subtitle']);
$o[$i][$value['position']] .= sprintf('<tr class="body"><td>%s</td></tr>',$value['body']);
if (! empty($value['footer']))
$o[$i][$value['position']] .= sprintf('<tr class="footer"><td>%s</td></tr>',$value['footer']);
$o[$i][$value['position']] .= '</table>';
}
// Render our output.
$output .= '<table class="subblockhead">';
foreach ($o as $k => $v)
$output .= sprintf('<tr><td style="width: %s%%;">%s</td></tr>',$x=round(100/$y,0),implode(sprintf('</td><td style="width: %s%%;">',$x),$v));
$output .= '</table>';
return $output;
}
}
?>

View File

@@ -0,0 +1,93 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* This class is for rendering a BreadCrumb menu.
*
* @package lnApp
* @subpackage Page
* @category Helpers
* @author Deon George
* @copyright (c) 2010 Deon George
* @license http://dev.leenooks.net/license.html
*/
abstract class lnApp_BreadCrumb extends HTMLRender {
protected static $_data = array();
protected static $_spacer = ' &raquo; ';
protected static $_required_keys = array('body');
/**
* Set the BreadCrumb path
*
* @param array Block attributes
*/
public static function set($path) {
$path = strtolower($path);
if (is_string($path))
static::$_data['path'] = explode('/',$path);
elseif (is_array($path))
static::$_data['path'] = $path;
else
throw new Kohana_Exception('Path is not a string, nor an array');
}
/**
* Enable a friendly name to be used for a path
*/
public static function name($path,$name,$override=TRUE) {
if (isset(static::$_data['name'][$path]) AND ! $override)
return;
static::$_data['name'][$path] = $name;
}
/**
* Enable specifying the URL for a path
*/
public static function URL($path,$url,$override=TRUE) {
$path = strtolower($path);
$url = strtolower($url);
if (isset(static::$_data['url'][$path]) AND ! $override)
return;
static::$_data['url'][$path] = $url;
}
/**
* Return an instance of this class
*
* @return BreadCrumb
*/
public static function factory() {
return new BreadCrumb;
}
/**
* Render this BreadCrumb
*/
protected function render() {
$output = '<ul id="breadcrumb">';
$output .= '<li>'.HTML::anchor('/',_('Home')).'</li>';
$data = empty(static::$_data['path']) ? explode('/',preg_replace('/^\//','',Request::detect_uri())) : static::$_data['path'];
$c = count($data);
$i=0;
foreach ($data as $k => $v) {
$i++;
$p = join('/',array_slice($data,0,$k+1));
$output .= $i==$c ? '<li id="active">' : '<li>';
$output .= HTML::anchor(
(empty(static::$_data['url'][$p]) ? $p : static::$_data['url'][$p]),
(empty(static::$_data['name'][$p]) ? ucfirst($v) : static::$_data['name'][$p])
);
$output .= '</li>';
}
$output .= '</ul>';
return $output;
}
}
?>

View File

@@ -0,0 +1,137 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* This class extends the core Kohana class by adding some core application
* specific functions, and configuration.
*
* @package lnApp
* @subpackage Core
* @category Overrides
* @author Deon George
* @copyright (c) 2010 Deon George
* @license http://dev.leenooks.net/license.html
*/
abstract class lnApp_Config extends Kohana_Config {
protected static $logo = 'img/logo-small.png';
/**
* Some early initialisation
*
* At this point, KH hasnt been fully initialised either, so we cant rely on
* too many KH functions yet.
* NOTE: Kohana doesnt provide a parent construct for the Kohana_Config class.
*/
public function __construct() {
if (defined('PHPUNITTEST'))
$_SERVER['SERVER_NAME'] = PHPUNITTEST;
}
/**
* Return our site name
*/
public static function site() {
return $_SERVER['SERVER_NAME'];
}
/**
* Work out our site ID for multiehosting
*/
public static function siteid() {
return Kohana::$config->load('config.site.id');
}
/**
* Work out our site mode (dev,test,prod)
*/
public static function sitemode() {
return Kohana::$config->load('config.site.mode');
}
public static function sitemodeverbose() {
$modes = array(
Kohana::PRODUCTION=>'Production',
Kohana::STAGING=>'Staging',
Kohana::TESTING=>'Testing',
Kohana::DEVELOPMENT=>'Development',
);
return (! isset($modes[static::sitemode()])) ? 'Unknown' : $modes[static::sitemode()];
}
public static function submode() {
$submode = Kohana::$config->load('config.debug.submode');
return (isset($submode[Request::$client_ip])) ? $submode[Request::$client_ip] : FALSE;
}
public static function sitename() {
return Kohana::$config->load('config')->site_name;
}
// Called in Invoice/Emailing to embed the file.
public static function logo_file() {
list ($path,$suffix) = explode('.',static::$logo);
return ($a=Kohana::find_file(sprintf('media/site/%s',Config::siteid()),$path,$suffix)) ? $a : Kohana::find_file('media',$path,$suffix);
}
public static function logo_uri() {
list ($path,$suffix) = explode('.',static::$logo);
return URL::site(Route::get('default/media')->uri(array('file'=>$path.'.'.$suffix),array('alt'=>static::sitename())),'http');
}
public static function logo() {
return HTML::image(static::logo_uri(),array('class'=>'headlogo','alt'=>_('Logo')));
}
public static function login_uri() {
return ($ao = Auth::instance()->get_user() AND is_object($ao)) ? HTML::anchor('user/account/edit',$ao->name()) : HTML::anchor('login',_('Login'));
}
/**
* Return our caching mechanism
*/
public static function cachetype() {
return is_null(Kohana::$config->load('config')->cache_type) ? 'file' : Kohana::$config->load('config')->cache_type;
}
/**
* Show a date using a site configured format
*/
public static function date($date) {
return $date ? date(Kohana::$config->load('config')->date_format,$date) : '&gt;Not Set&lt;';
}
/**
* Show a date using a site configured format
*/
public static function time($date) {
return date(Kohana::$config->load('config')->time_format,$date);
}
/**
* Show a date using a site configured format
*/
public static function datetime($date) {
return sprintf('%s %s',static::date($date),static::time($date));
}
/**
* See if our emails for the template should be sent to configured admin(s)
*
* @param string template - Template to test for
* @return mixed|array - Email to send test emails to
*/
public static function testmail($template) {
$config = Kohana::$config->load('config')->email_admin_only;
if (is_null($config) OR ! is_array($config) OR empty($config[$template]))
return FALSE;
else
return $config[$template];
}
public static function theme() {
return Kohana::$config->load('config')->theme;
}
}
?>

View File

@@ -0,0 +1,90 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* This class provides the default controller for rendering pages.
*
* @package lnApp
* @subpackage Page
* @category Abstract/Controllers
* @author Deon George
* @copyright (c) 2010 Deon George
* @license http://dev.leenooks.net/license.html
*/
abstract class lnApp_Controller_Default extends Controller {
/**
* The variable that our output is stored in
*/
protected $output = NULL;
/**
* @var string page media route as per [Route]
*/
protected $mediaroute = 'default/media';
/**
* Controls access to this controller.
* Can be set to a string or an array, for example 'login' or array('login', 'admin')
* Note that in second(array) example, user must have both 'login' AND 'admin' roles set in database
*
* @var boolean is authenticate required with this controller
*/
protected $auth_required = FALSE;
/**
* If redirecting to a login page, which page to redirect to
*/
protected $noauth_redirect = 'login';
/**
* Controls access for separate actions, eg:
* 'adminpanel' => 'admin' will only allow users with the role admin to access action_adminpanel
* 'moderatorpanel' => array('login', 'moderator') will only allow users with the roles login and moderator to access action_moderatorpanel
*
* @var array actions that require a valid user
*/
protected $secure_actions = array();
/**
* Check and see if this controller needs authentication
*
* if $this->auth_required is TRUE, then the user must be logged in only.
* if $this->auth_required is FALSE, AND $this->secure_actions has an array of
* methods set to TRUE, then the user must be logged in AND a member of the
* role.
*
* @return boolean
*/
protected function _auth_required() {
// If our global configurable is disabled, then continue
if (! Kohana::$config->load('config')->method_security)
return FALSE;
return (($this->auth_required !== FALSE && Auth::instance()->logged_in() === FALSE) ||
(is_array($this->secure_actions) && array_key_exists($this->request->action(),$this->secure_actions) &&
Auth::instance()->logged_in($this->secure_actions[$this->request->action()]) === FALSE));
}
public function before() {
parent::before();
// Check user auth and role
if ($this->_auth_required()) {
// For AJAX/JSON requests, authorisation is controlled in the method.
if (Request::current()->is_ajax() && $this->request->action() === 'json') {
// Nothing required.
// For no AJAX/JSON requests, display an access page
} elseif (Auth::instance()->logged_in(NULL,get_class($this).'|'.__METHOD__)) {
HTTP::redirect('login/noaccess');
} else {
Session::instance()->set('afterlogin',Request::detect_uri());
HTTP::redirect($this->noauth_redirect);
}
}
}
public function after() {
parent::after();
// Generate and check the ETag for this file
$this->check_cache(sha1($this->response->body()));
}
}
?>

View File

@@ -0,0 +1,70 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* This class provides login capability
*
* @package lnApp
* @subpackage Page/Login
* @category Controllers
* @author Deon George
* @copyright (c) 2010 Deon George
* @license http://dev.leenooks.net/license.html
* @also [logout]
*/
class lnApp_Controller_Login extends Controller_TemplateDefault {
protected $auth_required = FALSE;
public function action_index() {
// If user already signed-in
if (Auth::instance()->logged_in()!= 0) {
// Redirect to the user account
HTTP::redirect('user/welcome/index');
}
// If there is a post and $_POST is not empty
if ($_POST) {
// Store our details in a session key
Session::instance()->set(Kohana::$config->load('auth')->session_key,$_POST['username']);
Session::instance()->set('password',$_POST['password']);
// If the post data validates using the rules setup in the user model
if (Auth::instance()->login($_POST['username'],$_POST['password'])) {
// Redirect to the user account
if ($redir = Session::instance()->get('afterlogin')) {
Session::instance()->delete('afterlogin');
HTTP::redirect($redir);
} else
HTTP::redirect('user/welcome/index');
} else {
SystemMessage::add(array(
'title'=>_('Invalid username or password'),
'type'=>'error',
'body'=>_('The username or password was invalid.')
));
}
}
Block::add(array(
'title'=>_('Login to server'),
'body'=>View::factory('login'),
'style'=>array('css/login.css'=>'screen'),
));
Script::add(array('type'=>'stdin','data'=>'
$(document).ready(function() {
$("#ajxbody").click(function() {$("#ajBODY").load("'.$this->request->uri().'/"); return false;});
});'
));
}
public function action_noaccess() {
SystemMessage::add(array(
'title'=>_('No access to requested resource'),
'type'=>'error',
'body'=>_('You do not have access to the requested resource, please contact your administrator.')
));
}
}
?>

View File

@@ -0,0 +1,28 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* This class provides logout capability
*
* @package lnApp
* @subpackage Page/Logout
* @category Controllers
* @author Deon George
* @copyright (c) 2010 Deon George
* @license http://dev.leenooks.net/license.html
* @also [login]
*/
class lnApp_Controller_Logout extends Controller {
public function action_index() {
# If user already signed-in
if (Auth::instance()->logged_in()!= 0) {
$ao = Auth::instance()->get_user();
Auth::instance()->logout();
$ao->log('Logged Out');
HTTP::redirect('login');
}
HTTP::redirect('welcome/index');
}
}
?>

View File

@@ -0,0 +1,64 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* This class provides access to rendering media items (javascript, images and css).
*
* @package lnApp
* @subpackage Page/Media
* @category Controllers
* @author Deon George
* @copyright (c) 2010 Deon George
* @license http://dev.leenooks.net/license.html
*/
abstract class lnApp_Controller_Media extends Controller {
/**
* This action will render all the media related files for a page
*
* @return void
*/
final public function action_get() {
// Get the file path from the request
$file = $this->request->param('file');
// Find the file extension
$ext = pathinfo($file,PATHINFO_EXTENSION);
// Remove the extension from the filename
$file = substr($file,0,-(strlen($ext)+1));
$f = '';
// If our file is pathed with session, our file is in our session.
if ($fd = Session::instance()->get_once($this->request->param('file'))) {
$this->response->body($fd);
// First try and find media files for the theme-site_id
} elseif ($f = Kohana::find_file($x=sprintf('media/site/%s/theme/%s',Config::siteid(),Config::theme()),$file,$ext)) {
// Send the file content as the response
$this->response->body(file_get_contents($f));
// Try and find media files for the site_id
} elseif ($f = Kohana::find_file(sprintf('media/site/%s',Config::siteid()),$file,$ext)) {
// Send the file content as the response
$this->response->body(file_get_contents($f));
// If not found try a default media file
} elseif ($f = Kohana::find_file('media',$file,$ext)) {
// Send the file content as the response
$this->response->body(file_get_contents($f));
} else {
// Return a 404 status
$this->response->status(404);
}
// Generate and check the ETag for this file
if (Kohana::$environment === Kohana::PRODUCTION OR Kohana::$config->load('debug')->etag)
$this->check_cache(sha1($this->response->body()));
// Set the proper headers to allow caching
$this->response->headers('Content-Type',File::mime_by_ext($ext));
$this->response->headers('Content-Length',(string)$this->response->content_length());
$this->response->headers('Last-Modified',date('r',$f ? filemtime($f) : time()));
}
}
?>

View File

@@ -0,0 +1,21 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* This class provides the default controller for tasks.
*
* @package lnApp
* @subpackage Task
* @category Abstract/Controllers
* @author Deon George
* @copyright (c) 2010 Deon George
* @license http://dev.leenooks.net/license.html
*/
abstract class lnApp_Controller_Task extends Controller {
public function before() {
if (! Kohana::$is_cli)
throw new Kohana_Exception('Cant run :method, it must be run by the CLI',array(':method'=>$this->request->action()));
parent::before();
}
}
?>

View File

@@ -0,0 +1,274 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* This class provides the default template controller for rendering pages.
*
* @package lnApp
* @subpackage Page/Template
* @category Controllers
* @author Deon George
* @copyright (c) 2010 Deon George
* @license http://dev.leenooks.net/license.html
*/
abstract class lnApp_Controller_TemplateDefault extends Controller_Template {
/**
* @var string page template
*/
public $template = 'lnapp/default';
/**
* @var object meta object information as per [meta]
*/
protected $meta;
/**
* Controls access to this controller.
* Can be set to a string or an array, for example 'login' or array('login', 'admin')
* Note that in second(array) example, user must have both 'login' AND 'admin' roles set in database
*
* @var boolean is authenticate required with this controller
*/
protected $auth_required = FALSE;
/**
* If redirecting to a login page, which page to redirect to
*/
protected $noauth_redirect = 'login';
/**
* Controls access for separate actions, eg:
* 'adminpanel' => 'admin' will only allow users with the role admin to access action_adminpanel
* 'moderatorpanel' => array('login', 'moderator') will only allow users with the roles login and moderator to access action_moderatorpanel
*
* @var array actions that require a valid user
*/
protected $secure_actions = array(
);
public function __construct(Request $request,Response $response) {
// Our Menu's can run without method authentication by default.
if (! isset($this->secure_actions['menu']))
$this->secure_actions['menu'] = FALSE;
return parent::__construct($request,$response);
}
/**
* Check and see if this controller needs authentication
*
* if $this->auth_required is TRUE, then the user must be logged in only.
* if $this->auth_required is FALSE, AND $this->secure_actions has an array of
* methods set to TRUE, then the user must be logged in AND a member of the
* role.
*
* @return boolean
*/
protected function _auth_required() {
// If our global configurable is disabled, then continue
if (! Kohana::$config->load('config')->method_security)
return FALSE;
return (($this->auth_required !== FALSE && Auth::instance()->logged_in(NULL,get_class($this).'|'.__METHOD__) === FALSE) ||
(is_array($this->secure_actions) && array_key_exists($this->request->action(),$this->secure_actions) &&
Auth::instance()->logged_in($this->secure_actions[$this->request->action()],get_class($this).'|'.__METHOD__) === FALSE));
}
/**
* Loads the template [View] object.
*
* Page information is provided by [meta].
* @uses meta
*/
public function before() {
// Do not template media files
if ($this->request->action() === 'media') {
$this->auto_render = FALSE;
return;
}
// Actions that start with ajax, should only be ajax
if (! Kohana::$config->load('debug')->ajax AND preg_match('/^ajax/',Request::current()->action()) AND ! Request::current()->is_ajax())
die();
parent::before();
// Check user auth and role
if ($this->_auth_required()) {
if (Kohana::$is_cli)
throw new Kohana_Exception('Cant run :method, authentication not possible',array(':method'=>$this->request->action()));
// If auth is required and the user is logged in, then they dont have access.
// (We have already checked authorisation.)
if (Auth::instance()->logged_in(NULL,get_class($this).'|'.__METHOD__)) {
if (Config::sitemode() == Kohana::DEVELOPMENT)
SystemMessage::add(array(
'title'=>_('Insufficient Access'),
'type'=>'debug',
'body'=>Debug::vars(array('required'=>$this->auth_required,'action'=>$this->request->action(),'user'=>Auth::instance()->get_user()->username)),
));
// @todo Login No Access redirects are not handled in JS?
if ($this->request->is_ajax()) {
echo _('You dont have enough permissions.');
die();
} else
HTTP::redirect('login/noaccess');
} else {
Session::instance()->set('afterlogin',Request::detect_uri());
HTTP::redirect($this->noauth_redirect);
}
}
// For AJAX calls, we dont need to render the complete page.
if ($this->request->is_ajax()) {
$this->auto_render = FALSE;
return;
}
// Bind our template meta variable
$this->meta = new Meta;
View::bind_global('meta',$this->meta);
// Add our logo
Style::add(array(
'type'=>'stdin',
'data'=>'h1 span{background:url('.Config::logo_uri().') no-repeat;}',
));
// Our default script(s)
foreach (array('file'=>array_reverse(array(
'js/jquery-1.6.4.min.js',
'js/jquery.jstree-1.0rc3.js',
'js/jquery.cookie.js',
))) as $type => $datas) {
foreach ($datas as $data) {
Script::add(array(
'type'=>$type,
'data'=>$data,
),TRUE);
}
}
// Initialise our content
$this->template->left = '';
$this->template->content = '';
$this->template->right = '';
}
public function after() {
if (! is_string($this->template) AND empty($this->template->content))
$this->template->content = Block::factory();
if ($this->auto_render) {
// Application Title
if ($mo=ORM::factory('Module',array('name'=>Request::current()->controller())) AND $mo->loaded())
$this->meta->title = sprintf('%s: %s',Kohana::$config->load('config')->appname,$mo->display('name'));
else
$this->meta->title = Kohana::$config->load('config')->appname;
$this->template->title = '';
// Language
$this->meta->language = Config::instance()->so->language->iso;
// Description
$this->meta->description = sprintf('%s::%s',$this->request->controller(),$this->request->action());
// Link images on the header line
$this->template->headimages = $this->_headimages();
// System Messages line
$this->template->sysmsg = $this->_sysmsg();
// Left Item
$this->template->left = $this->_left();
// Right Item
$this->template->right = $this->_right();
// Footer
$this->template->footer = $this->_footer();
// For any ajax rendered actions, we'll need to capture the content and put it in the response
} elseif ($this->request->is_ajax() && isset($this->template->content) && ! $this->response->body()) {
// @todo move this formatting to a view?
if ($s = $this->_sysmsg() AND (string)$s)
$this->response->body(sprintf('<table class="sysmsg"><tr><td>%s</td></tr></table>',$s));
// In case there any style sheets for this render.
$this->response->bodyadd(Style::factory());
// Since we are ajax, we should re-render the breadcrumb
Session::instance()->set('breadcrumb',(string)BreadCrumb::factory());
$this->response->bodyadd(Script::add(array('type'=>'stdin','data'=>'$().ready($("#ajCONTROL").load("'.URL::site('welcome/breadcrumb').'",null,function(x,s,r) {}));')));
// In case there any javascript for this render.
$this->response->bodyadd(Script::factory());
// Get the response body
$this->response->bodyadd(sprintf('<table class="content"><tr><td>%s</td></tr></table>',$this->template->content));
}
parent::after();
// Generate and check the ETag for this file
if (Kohana::$environment === Kohana::PRODUCTION OR Kohana::$config->load('debug')->etag)
$this->check_cache(sha1($this->response->body()));
}
/**
* Default Method to call from the tree menu
*/
public function action_menu() {
$this->template->content = _('Please choose from the menu on the left - you may need to expand the items by pressing on the plus.');
}
protected function _headimages() {
HeadImages::add(array(
'url'=>'http://dev.leenooks.net',
'img'=>'img/forum-big.png',
'attrs'=>array('onclick'=>"target='_blank';",'title'=>'Link')
));
return HeadImages::factory();
}
protected function _sysmsg() {
return SystemMessage::factory();
}
protected function _left() {
return empty($this->template->left) ? Controller_Tree::js() : $this->template->left;
}
protected function _right() {
return empty($this->template->right) ? '' : $this->template->right;
}
public function _footer() {
return sprintf('&copy; %s',Config::SiteName());
}
/**
* Generate a view path to help View::factory() calls
*
* The purpose of this method is to ensure that we have a consistant
* layout for our view files, including those that are needed by
* plugins
*
* @param string Plugin Name (optional)
*/
public function viewpath($plugin='') {
$request = Request::current();
$path = $request->controller();
if ($request->directory())
$path .= ($path ? '/' : '').$request->directory();
if ($plugin)
$path .= ($path ? '/' : '').$plugin;
$path .= ($path ? '/' : '').$request->action();
return strtolower($path);
}
}
?>

View File

@@ -0,0 +1,117 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* This class extends renders OSB menu tree.
*
* @package lnApp
* @subpackage Tree
* @category Controllers
* @author Deon George
* @copyright (c) 2010 Open Source Billing
* @license http://dev.osbill.net/license.html
*/
class lnApp_Controller_Tree extends Controller_Default {
/**
* @var string page media route as per [Route]
*/
protected static $jsmediaroute = 'default/media';
public function after() {
$this->response->headers('Content-Type','application/json');
$this->response->body(json_encode($this->output));
parent::after();
}
public static function js() {
$mediapath = Route::get(static::$jsmediaroute);
return '
<div id="tree" class=""></div>
<script type="text/javascript">
<!--
$(function () {
var use_ajax = false;
$("#tree").jstree({
themes : {
"theme" : "classic",
},
ui : {
"select_limit" : 1,
"select_node" : false,
},
cookies : {
"save_selected" : false,
"cookie_options" : { path : "'.URL::site().'" }
},
json_data : {
"correct_state" : "true",
"progressive_render" : "true",
"ajax" : {
"url" : "'.URL::site('tree/json').'",
"data" : function (n) {
return { id : n.attr ? n.attr("id") : "N_"+0 };
}
}
},
plugins : [ "themes", "json_data", "ui", "cookies" ],
});
// On selection
$("#tree").bind("select_node.jstree", function (e, data) {
if (a = data.rslt.obj.attr(\'id\').indexOf(\'_\')) {
id = data.rslt.obj.attr(\'id\').substr(a+1);
if (href = $("#N_"+id).attr("href")) {
if (! use_ajax) {
window.location = href;
return;
}
$("#ajBODY").empty().html("<img src=\"'.URL::site('media/img/ajax-progress.gif').'\" alt=\"Loading...\" />");
$("#ajBODY").load(href, function(r,s,x) {
if (s == "error") {
var msg = "Sorry but there was an error: ";
$("#ajBODY").html(msg + x.status + " " + x.statusText + r);
}
});
} else
alert("Unknown: "+id+" HREF:"+href);
}
});
});
// -->
</script>';
}
/**
* Draw the Tree Menu
*
* The incoming ID is either a Branch B_x or a Node N_x
* Where X is actually the module.
*
* @param array $data Tree data passed in by inherited methods
*/
public function action_json(array $data=array()) {
if ($this->_auth_required() AND ! Auth::instance()->logged_in()) {
$this->output = array('attr'=>array('id'=>'a_login'),
'data'=>array('title'=>_('Please Login').'...','attr'=>array('id'=>'N_login','href'=>URL::site('login'))));
return;
}
$this->output = array();
foreach ($data as $branch) {
array_push($this->output,array(
'attr'=>array('id'=>sprintf('B_%s',$branch['id'])),
'state'=>$branch['state'],
'data'=>array('title'=>$branch['name']),
'attr'=>array('id'=>sprintf('N_%s',$branch['id']),'href'=>empty($branch['attr_href']) ? URL::site(sprintf('user/%s/menu',$branch['name'])) : $branch['attr_href']),
)
);
}
}
}
?>

View File

@@ -0,0 +1,21 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* This class extends Kohana's HTML
*
* @package lnApp/Modifications
* @category Classes
* @category Helpers
* @author Deon George
* @copyright (c) 2010 Deon George
* @license http://dev.leenooks.net/license.html
*/
abstract class lnApp_HTML extends Kohana_HTML {
public static function nbsp($string) {
if (strlen((string)$string))
return $string;
else
return '&nbsp;';
}
}
?>

View File

@@ -0,0 +1,92 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* This class is the base used for common static methods that are used
* for rendering.
*
* @package lnApp
* @subpackage Page
* @category Abstract/Helpers
* @author Deon George
* @copyright (c) 2010 Deon George
* @license http://dev.leenooks.net/license.html
*/
abstract class lnApp_HTMLRender {
protected static $_media_path = 'default/media';
protected static $_required_keys = array();
protected static $_unique_vals = array();
public function __construct() {
if (! isset(static::$_data))
throw new Kohana_Exception(':class is missing important static variables',array(':class'=>get_called_class()));
}
/**
* Add an item to be rendered
*
* @param array Item to be added
*/
public static function add($item,$prepend=FALSE) {
foreach (static::$_required_keys as $key)
if (! isset($item[$key]))
throw new Kohana_Exception('Missing key :key for image',array(':key'=>$key));
// Check for unique keys
if (static::$_unique_vals)
foreach (static::$_unique_vals as $v=>$u)
foreach (static::$_data as $d)
if (isset($d[$u]) && $d['data'] == $item['data'])
return;
if ($prepend)
array_unshift(static::$_data,$item);
else
array_push(static::$_data,$item);
}
/**
* Set the space used between rendering output
*/
public static function setSpacer($spacer) {
static::$_spacer = $spacer;
}
/**
* Set the Kohana Media Path, used to determine where to find additional
* HTML content required for rendering.
*/
public static function setMediaPath($path) {
static::$_media_path = $path;
}
/**
* Factory instance method must be declared by the child class
*/
public static function factory() {
throw new Kohana_Exception(':class is calling :method, when it should have its own method',
array(':class'=>get_called_class(),':method'=>__METHOD__));
}
/**
* Return the HTML to render the header images
*/
public function __toString() {
try {
return static::render();
}
// Display the exception message
catch (Exception $e) {
Kohana_Exception::handler($e);
}
}
/**
* Rendering must be declared by the child class
*/
protected function render() {
throw new Kohana_Exception(':class is calling :method, when it should have its own method',
array(':class'=>get_called_class(),':method'=>__METHOD__));
}
}
?>

View File

@@ -0,0 +1,48 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* This class is for all image icons shown on the page header.
*
* @package lnApp
* @subpackage Page
* @category Helpers
* @author Deon George
* @copyright (c) 2010 Deon George
* @license http://dev.leenooks.net/license.html
*/
abstract class lnApp_HeadImages extends HTMLRender {
protected static $_data = array();
protected static $_spacer = '&nbsp;';
protected static $_required_keys = array('img');
/**
* Return an instance of this class
*
* @return HeadImage
*/
public static function factory() {
return new HeadImages;
}
/**
* Render this Header Image
*
* @see HTMLRender::render()
*/
protected function render() {
$output = '';
$mediapath = Route::get(static::$_media_path);
foreach (static::$_data as $value) {
$i = HTML::image($mediapath->uri(array('file'=>$value['img'])),array('alt'=>isset($value['attrs']['title']) ? $value['attrs']['title'] : ''));
if (isset($value['url']))
$output .= HTML::anchor($value['url'],$i,(isset($value['attrs']) && is_array($value['attrs'])) ? $value['attrs'] : NULL);
else
$output .= $i;
$output .= static::$_spacer;
}
return $output;
}
}
?>

View File

@@ -0,0 +1,34 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* This is class is for all HTML page attributes.
*
* @package lnApp
* @subpackage Page
* @category Helpers
* @author Deon George
* @copyright (c) 2010 Deon George
* @license http://dev.leenooks.net/license.html
*/
abstract class lnApp_Meta {
private $_data = array();
private $_array_keys = array();
public function __get($key) {
if (in_array($key,$this->_array_keys) && empty($this->_data[$key]))
return array();
if (empty($this->_data[$key]))
return NULL;
else
return $this->_data[$key];
}
public function __set($key,$value) {
if (in_array($key,$this->_array_keys) && ! is_array($value))
throw new Kohana_Exception('Key :key must be an array',array(':key'=>$key));
$this->_data[$key] = $value;
}
}
?>

View File

@@ -0,0 +1,36 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* This class is for providing password from a password genarator
*
* @package lnApp
* @subpackage PWGen
* @category Helpers
* @author Deon George
* @copyright (c) 2010 Deon George
* @license http://dev.leenooks.net/license.html
*/
abstract class lnApp_PWgen {
public static function get($pwonly=TRUE) {
if (! Kohana::$config->load('pwgen')->host OR ! Kohana::$config->load('pwgen')->port)
throw new Kohana_Exception('No configuration for host or port (:host/:port)',array(':host'=>Kohana::$config->load('pwgen')->host,':port'=>Kohana::$config->load('pwgen')->port));
$ps = socket_create(AF_INET,SOCK_STREAM,0);
if (! socket_connect($ps,Kohana::$config->load('pwgen')->host,Kohana::$config->load('pwgen')->port))
throw new Kohana_Exception('Unable to connect to password server');
// echo "Reading response:\n\n";
$pw = '';
while ($out = socket_read($ps,64))
$pw .= rtrim($out);
// echo "Closing socket...";
socket_close ($ps);
list($passwd,$passwdSay) = explode(' ',$pw);
// print " Password [$passwd] ($passwdSay) [$pw] ".md5($passwd)."<BR>";
return $pwonly ? $passwd : array('pw'=>$passwd,'say'=>$passwdSay);
}
}
?>

View File

@@ -0,0 +1,17 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* This class is for generating Random data.
*
* @package lnApp
* @category Helpers
* @author Deon George
* @copyright (c) 2010 Deon George
* @license http://dev.leenooks.net/license.html
*/
abstract class lnApp_Random {
public static function char($num=NULL) {
return substr(md5(rand()),0,is_null($num) ? rand(6,10) : $num-1);
}
}
?>

View File

@@ -0,0 +1,65 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* This class is for rendering HTML script tags
*
* @package lnApp
* @subpackage Page
* @category Helpers
* @author Deon George
* @copyright (c) 2010 Deon George
* @license http://dev.leenooks.net/license.html
*/
abstract class lnApp_Script extends HTMLRender {
protected static $_data = array();
protected static $_spacer = "\n";
protected static $_required_keys = array('type','data');
protected static $_unique_vals = array('file'=>'type');
protected static $_rendered = FALSE;
/**
* Return an instance of this class
*
* @return Script
*/
public static function factory() {
return new Script;
}
/**
* Render the script tag
*
* @see HTMLRender::render()
*/
protected function render() {
$foutput = $soutput = '';
$mediapath = Route::get(static::$_media_path);
foreach (static::$_data as $value) {
switch ($value['type']) {
case 'file':
$foutput .= HTML::script($mediapath->uri(array('file'=>$value['data'])));
break;
case 'src':
$foutput .= HTML::script($value['data']);
break;
case 'stdin':
$soutput .= sprintf("<script type=\"text/javascript\">//<![CDATA[\n%s\n//]]></script>",$value['data']);
break;
default:
throw new Kohana_Exception('Unknown style type :type',array(':type'=>$value['type']));
}
}
static::$_rendered = TRUE;
return $foutput.static::$_spacer.$soutput;
}
public static function add($item,$prepend=FALSE,$x='') {
if (static::$_rendered)
throw new Kohana_Exception('Already rendered?');
return parent::add($item,$prepend);
}
}
?>

View File

@@ -0,0 +1,90 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* This class is used to sort multiple dimension arrays.
*
* @package lnApp
* @subpackage Sort
* @category Helpers
* @author Deon George
* @copyright (c) 2010 Deon George
* @license http://dev.leenooks.net/license.html
* @uses Style
*/
abstract class lnApp_Sort {
/**
* Sort a multi dimensional array.
*
* @param array Multi demension array passed by reference
* @param string Comma delimited string of sort keys.
* @param boolean Whether to reverse sort.
* @return array Sorted multi demension array.
*/
public static function MAsort(&$data,$sortby,$rev=0) {
// if the array to sort is null or empty, or our sortby is bad
if (! preg_match('/^([a-zA-Z0-9_]+(\([a-zA-Z0-9_,]*\)(->[a-zA-Z0-9])?)?,?)+$/',$sortby) || ! $data)
return;
$code = '$c=0;';
foreach (explode(',',$sortby) as $key) {
$code .= 'if (is_object($a) || is_object($b)) {';
foreach (array('a','b') as $x) {
$code .= 'if (is_array($'.$x.'->'.$key.')) {';
$code .= 'asort($'.$x.'->'.$key.');';
$code .= '$x'.$x.' = array_shift($'.$x.'->'.$key.');';
$code .= '} else';
$code .= '$x'.$x.' = $'.$x.'->'.$key.';';
}
$code .= 'if ($xa != $xb)';
if ($rev)
$code .= 'return ($xa < $xb ? 1 : -1);';
else
$code .= 'return ($xa > $xb ? 1 : -1);';
$code .= '} else {';
foreach (array('a','b') as $x)
$code .= '$'.$x.' = array_change_key_case($'.$x.');';
$key = strtolower($key);
$code .= 'if ((! isset($a[\''.$key.'\'])) && isset($b[\''.$key.'\'])) return 1;';
$code .= 'if (isset($a[\''.$key.'\']) && (! isset($b[\''.$key.'\']))) return -1;';
$code .= 'if ((isset($a[\''.$key.'\'])) && (isset($b[\''.$key.'\']))) {';
foreach (array('a','b') as $x) {
$code .= 'if (is_array($'.$x.'[\''.$key.'\'])) {';
$code .= 'asort($'.$x.'[\''.$key.'\']);';
$code .= '$x'.$x.' = array_shift($'.$x.'[\''.$key.'\']);';
$code .= '} else';
$code .= '$x'.$x.' = $'.$x.'[\''.$key.'\'];';
}
$code .= 'if ($xa != $xb)';
$code .= 'if (is_numeric($xa) && is_numeric($xb)) {';
if ($rev)
$code .= 'return ($xa < $xb ? 1 : -1);';
else
$code .= 'return ($xa > $xb ? 1 : -1);';
$code .= '} else {';
if ($rev)
$code .= 'if (($c = strcasecmp($xb,$xa)) != 0) return $c;';
else
$code .= 'if (($c = strcasecmp($xa,$xb)) != 0) return $c;';
$code .= '}}}';
}
$code .= 'return $c;';
$result = create_function('$a, $b',$code);
uasort($data,$result);
}
}
?>

View File

@@ -0,0 +1,54 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* This class is for rendering HTML style tags
*
* @package lnApp
* @subpackage Page
* @category Helpers
* @author Deon George
* @copyright (c) 2010 Deon George
* @license http://dev.leenooks.net/license.html
*/
abstract class lnApp_Style extends HTMLRender {
protected static $_data = array();
protected static $_spacer = "\n";
protected static $_required_keys = array('type','data');
protected static $_unique_vals = array('file'=>'type');
/**
* Return an instance of this class
*
* @return Style
*/
public static function factory() {
return new Style;
}
/**
* Render the style tag
*
* @see HTMLRender::render()
*/
protected function render() {
$foutput = $soutput = '';
$mediapath = Route::get(static::$_media_path);
foreach (static::$_data as $value) {
switch ($value['type']) {
case 'file':
$foutput .= HTML::style($mediapath->uri(array('file'=>$value['data'])),
array('media'=>(! empty($value['media'])) ? $value['media'] : 'screen'),TRUE);
break;
case 'stdin':
$soutput .= sprintf("<style type=\"text/css\">%s</style>",$value['data']);
break;
default:
throw new Kohana_Exception('Unknown style type :type',array(':type'=>$value['type']));
}
}
return $foutput.static::$_spacer.$soutput;
}
}
?>

View File

@@ -0,0 +1,129 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* This class is for rendering system information messages.
*
* @package lnApp
* @subpackage SystemMessage
* @category Helpers
* @author Deon George
* @copyright (c) 2010 Deon George
* @license http://dev.leenooks.net/license.html
*/
abstract class lnApp_SystemMessage extends HTMLRender {
protected static $_data = array();
protected static $_spacer = '<table><tr class="spacer"><td>&nbsp;</td></tr></table>';
protected static $_required_keys = array('title','body','type');
/**
* Add a system message to be rendered
*
* @param array System Message attributes
*/
public static function add($msg,$prepend=FALSE) {
if ($msgs = Session::instance()->get('sessionmsgs')) {
static::$_data = $msgs;
}
parent::add($msg);
// Add a gribber popup
Style::add(array(
'type'=>'file',
'data'=>'css/jquery.gritter.css',
'media'=>'screen',
));
Script::add(array(
'type'=>'file',
'data'=>'js/jquery.gritter-1.5.js',
));
Script::add(array(
'type'=>'stdin',
'data'=>sprintf(
'$(document).ready(function() {
$.extend($.gritter.options, {
fade_in_speed: "medium",
fade_out_speed: 2000,
time: "3000",
sticky: false,
});
$.gritter.add({
title: "%s",
text: "%s",
image: "%s",
});});',$msg['title'],$msg['body'],URL::site().static::image($msg['type'],true))));
// Save our messages in our session, so that we get them for redirects
Session::instance()->set('sessionmsgs',static::$_data);
}
/**
* Return an instance of this class
*
* @return SystemMessage
*/
public static function factory() {
return new SystemMessage;
}
/**
* Render an image for the System Message
*/
public static function image($type,$raw=false,$big=false,$alt='') {
$mediapath = Route::get(static::$_media_path);
switch ($type) {
case 'error':
$file = sprintf('img/dialog-error%s.png',$big ? '-big' : '');
break;
case 'info':
$file = sprintf('img/dialog-information%s.png',$big ? '-big' : '');
break;
case 'warning':
$file = sprintf('img/dialog-warning%s.png',$big ? '-big' : '');
break;
case 'debug':
$file = sprintf('img/dialog-question%s.png',$big ? '-big' : '');
break;
default:
throw new Kohana_Exception('Unknown system message type :type',array(':type'=>$value['type']));
}
if ($raw)
return $mediapath->uri(array('file'=>$file));
else
return HTML::image($mediapath->uri(array('file'=>$file)),array('alt'=>$alt ? $alt : '','class'=>'sysicon'));
}
/**
* Render this system message
*
* @see HTMLRender::render()
*/
protected function render() {
$output = '';
$mediapath = Route::get(static::$_media_path);
// Reload our message from the session
if ($msgs = Session::instance()->get('sessionmsgs')) {
Session::instance()->delete('sessionmsgs');
static::$_data = $msgs;
}
$i = 0;
foreach (static::$_data as $value) {
if ($i++)
$output .= static::$_spacer;
$output .= '<table><tr>';
$output .= sprintf('<td class="icon" rowspan="2">%s</td>',static::image($value['type'],false,false,isset($value['alt']) ? $value['alt'] : ''));
$output .= sprintf('<td class="head">%s</td>',$value['title']);
$output .= '</tr><tr>';
$output .= sprintf('<td class="body">%s</td>',$value['body']);
$output .= '</tr></table>';
}
return $output;
}
}
?>

View File

@@ -0,0 +1,276 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* This class is for rendering a table of data.
*
* @package lnApp
* @subpackage Page
* @category Helpers
* @author Deon George
* @copyright (c) 2010 Deon George
* @license http://dev.leenooks.net/license.html
* @uses Style
*/
abstract class lnApp_Table {
public static function resolve($d,$key) {
if (is_array($d) AND isset($d[$key]))
$x = $d[$key];
// If the key is a method, we need to eval it
elseif (preg_match('/\(/',$key) OR preg_match('/-\>/',$key))
eval("\$x = \$d->$key;");
elseif (preg_match('/^__VALUE__$/',$key))
$x = $d;
else
$x = $d->display($key);
return $x;
}
public static function display($data,$rows,array $cols,array $option) {
if (! (array)$data)
return '';
$pag = NULL;
$view = $output = $button = '';
if (isset($option['type']) AND $option['type'])
switch ($option['type']) {
case 'select':
$view = 'table/select';
if (! empty($option['button']))
$button = implode('',$option['button']);
else
$button = Form::button('Submit','View/Edit',array('class'=>'form_button','type'=>'submit'));
Script::add(array(
'type'=>'stdin',
'data'=>'
(function($) {
// Enable Range Selection
$.fn.enableCheckboxRangeSelection = function() {
var lastCheckbox = null;
var followOn = 0;
var $spec = this;
$spec.bind("click", function(e) {
if (lastCheckbox != null && e.shiftKey) {
x = y = 0;
if (followOn != 0) {
if ($spec.index(lastCheckbox) < $spec.index(e.target)) {
x = 1 - ((followOn == 1) ? 1 : 0);
} else {
y = 1 - ((followOn == -1) ? 1 : 0);
}
}
$spec.slice(
Math.min($spec.index(lastCheckbox) - x, $spec.index(e.target)) + 1,
Math.max($spec.index(lastCheckbox), $spec.index(e.target)) + y
).attr("checked",function() { return ! this.checked; })
.parent().parent().toggleClass("selected");
followOn = ($spec.index(lastCheckbox) < $spec.index(e.target)) ? 1 : -1;
} else {
followOn = 0;
}
lastCheckbox = e.target;
});
return $spec;
};
// Enable Toggle, (De)Select All
$.fn.check = function(mode) {
// if mode is undefined, use "on" as default
var mode = mode || "on";
switch(mode) {
case "on":
$("#select-table tr:not(.head)")
.filter(":has(:checkbox:not(checked))")
.toggleClass("selected")
break;
case "off":
$("#select-table tr:not(.head)")
.filter(":has(:checkbox:checked)")
.toggleClass("selected")
break;
case "toggle":
$("#select-table tr:not(.head)")
.toggleClass("selected");
break;
}
return this.each(function(e) {
switch(mode) {
case "on":
this.checked = true;
break;
case "off":
this.checked = false;
break;
case "toggle":
this.checked = !this.checked;
break;
}
});
};
})(jQuery);
// Bind our actions
$(document).ready(function() {
$("#select-table :checkbox").enableCheckboxRangeSelection();
$("#select-menu > #toggle").bind("click",function() {
$("#select-table :checkbox").check("toggle");
});
$("#select-menu > #all_on").bind("click",function() {
$("#select-table :checkbox").check("on");
});
$("#select-menu > #all_off").bind("click",function() {
$("#select-table :checkbox").check("off");
});
// Our mouse over row highlight
$("#select-table tr:not(.head)").hover(function() {
$(this).children().toggleClass("highlight");
},
function() {
$(this).children().toggleClass("highlight");
});
// Click to select Row
$("#select-table tr:not(.head)")
.filter(":has(:checkbox:checked)")
.addClass("selected")
.end()
.click(function(e) {
$(this).toggleClass("selected");
if (e.target.type !== "checkbox") {
$(":checkbox", this).attr("checked", function() {
return !this.checked;
});
}
});
// Double click to select a row
$("#select-table tr:not(.head)")
.dblclick(function(e) {
window.location = $("a", this).attr("href");
});
});
'));
$output .= Form::open((isset($option['form']) ? $option['form'] : ''));
if (! empty($option['hidden']))
$output .= '<div>'.implode('',$option['hidden']).'</div>';
break;
case 'list':
default:
Script::add(array(
'type'=>'stdin',
'data'=>'
// Bind our actions
$(document).ready(function() {
// Our mouse over row highlight
$("#list-table tr:not(.head)").hover(function() {
$(this).children().toggleClass("highlight");
},
function() {
$(this).children().toggleClass("highlight");
});
});
'));
}
If (! $view)
$view = 'table/list';
if (isset($option['page']) AND $option['page']) {
$pag = new Pagination(array(
'total_items'=>count($data),
'items_per_page'=>$rows,
));
$output .= (string)$pag;
}
$other = $i = 0;
$td = $th = array();
foreach ($cols as $col => $details) {
$th[$col] = isset($details['label']) ? $details['label'] : '';
$td[$col]['class'] = isset($details['class']) ? $details['class'] : '';
$td[$col]['url'] = isset($details['url']) ? $details['url'] : '';
}
$output .= View::factory($view.'_head')
->set('th',array_values($th));
foreach ($data as $do) {
if ($pag) {
if (++$i < $pag->current_first_item())
continue;
elseif ($i > $pag->current_last_item())
break;
}
if ($pag OR ($i++ < $rows) OR is_null($rows)) {
foreach (array_keys($cols) as $col)
$td[$col]['value'] = Table::resolve($do,$col);
$output .= View::factory($view.'_body')
->set('td',$td);
} elseif (isset($option['show_other']) AND ($col=$option['show_other'])) {
$other += Table::resolve($do,$col);
}
}
if ($other)
$output .= View::factory($view.'_xtra')
->set('td',array_values($cols))
->set('count',$i-$rows)
->set('other',$other);
$output .= View::factory($view.'_foot')
->set('button',$button);
if (isset($option['type']) AND $option['type'])
switch ($option['type']) {
case 'select':
$output .= Form::close();
}
return $output;
}
public static function post($key,$i='id') {
if (isset($_POST[$i]))
Session::instance()->set('page_table_view'.$key,$_POST[$i]);
}
public static function page($key) {
// We have preference for parameters passed to the action.
if (is_null($id = Request::current()->param('id'))) {
if (isset($_POST['id']) AND is_array($_POST['id']))
Table::post($key,'id');
if ($ids = Session::instance()->get('page_table_view'.$key)) {
$pag = new Pagination(array(
'total_items'=>count($ids),
'items_per_page'=>1,
));
return array($ids[$pag->current_first_item()-1],(string)$pag);
}
}
// If we get here, then there is no previous data to retrieve.
return array($id,'');
}
}
?>