1 <?php defined('SYSPATH') OR die('No direct access allowed.');
3 * Contains examples of various Kohana library examples. You can access these
4 * samples in your own installation of Kohana by going to ROOT_URL/examples.
5 * This controller should NOT be used in production. It is for demonstration
8 * $Id: examples.php 4298 2009-04-30 17:06:05Z kiall $
12 * @copyright (c) 2007-2008 Kohana Team
13 * @license http://kohanaphp.com/license.html
15 class Examples_Controller extends Controller {
17 // Do not allow to run in production
18 const ALLOW_PRODUCTION = FALSE;
21 * Displays a list of available examples
25 // Get the methods that are only in this class and not the parent class.
26 $examples = array_diff
28 get_class_methods(__CLASS__),
29 get_class_methods(get_parent_class($this))
34 echo "<strong>Examples:</strong>\n";
37 foreach ($examples as $method)
39 if ($method == __FUNCTION__)
42 echo '<li>'.html::anchor('examples/'.$method, $method)."</li>\n";
46 echo '<p>'.Kohana::lang('core.stats_footer')."</p>\n";
50 * Demonstrates how to archive a directory. First enable the archive module
52 //public function archive($build = FALSE)
54 // if ($build === 'build')
57 // $archive = new Archive('zip');
59 // // Download the application/views directory
60 // $archive->add(APPPATH.'views/', 'app_views/', TRUE);
62 // // Download the built archive
63 // $archive->download('test.zip');
67 // echo html::anchor(Router::$current_uri.'/build', 'Download views');
72 * Demonstrates how to parse RSS feeds by using DOMDocument.
76 // Parse an external atom feed
77 $feed = feed::parse('http://dev.kohanaphp.com/projects/kohana2/activity.atom');
80 echo Kohana::debug($feed);
82 echo Kohana::lang('core.stats_footer');
86 * Demonstrates the Session library and using session data.
90 // Gets the singleton instance of the Session library
91 $s = Session::instance();
93 echo 'SESSID: <pre>'.session_id()."</pre>\n";
95 echo '<pre>'.print_r($_SESSION, TRUE)."</pre>\n";
97 echo '<br/>{execution_time} seconds';
101 * Demonstrates how to use the form helper with the Validation libraryfor file uploads .
105 // Anything submitted?
108 // Merge the globals into our validation object.
109 $post = Validation::factory(array_merge($_POST, $_FILES));
111 // Ensure upload helper is correctly configured, config/upload.php contains default entries.
112 // Uploads can be required or optional, but should be valid
113 $post->add_rules('imageup1', 'upload::required', 'upload::valid', 'upload::type[gif,jpg,png]', 'upload::size[1M]');
114 $post->add_rules('imageup2', 'upload::required', 'upload::valid', 'upload::type[gif,jpg,png]', 'upload::size[1M]');
116 // Alternative syntax for multiple file upload validation rules
117 //$post->add_rules('imageup.*', 'upload::required', 'upload::valid', 'upload::type[gif,jpg,png]', 'upload::size[1M]');
119 if ($post->validate() )
122 // Move (and rename) the files from php upload folder to configured application folder
123 upload::save('imageup1');
124 upload::save('imageup2');
125 echo 'Validation successfull, check your upload folder!';
129 // You got validation errors
130 echo '<p>validation errors: '.var_export($post->errors(), TRUE).'</p>';
131 echo Kohana::debug($post);
136 echo form::open('examples/form', array('enctype' => 'multipart/form-data'));
137 echo form::label('imageup', 'Image Uploads').':<br/>';
138 // Use discrete upload fields
139 // Alternative syntax for multiple file uploads
140 // echo form::upload('imageup[]').'<br/>';
142 echo form::upload('imageup1').'<br/>';
143 echo form::upload('imageup2').'<br/>';
144 echo form::submit('upload', 'Upload!');
150 * Demontrates how to use the Validation library to validate an arbitrary array.
152 function validation()
154 // To demonstrate Validation being able to validate any array, I will
155 // be using a pre-built array. When you load validation with no arguments
156 // it will default to validating the POST array.
160 'pass' => 'bigsecret',
164 $validation = new Validation($data);
166 $validation->add_rules('user', 'required', 'length[1,12]')->pre_filter('trim', 'user');
167 $validation->add_rules('pass', 'required')->post_filter('sha1', 'pass');
168 $validation->add_rules('reme', 'required');
170 $result = $validation->validate();
172 var_dump($validation->errors());
173 var_dump($validation->as_array());
176 echo '{execution_time} ALL DONE!';
180 * Demontrates how to use the Captcha library.
182 public function captcha()
184 // Look at the counters for valid and invalid
185 // responses in the Session Profiler.
188 // Load Captcha library, you can supply the name
189 // of the config group you would like to use.
190 $captcha = new Captcha;
192 // Ban bots (that accept session cookies) after 50 invalid responses.
193 // Be careful not to ban real people though! Set the threshold high enough.
194 if ($captcha->invalid_count() > 49)
195 exit('Bye! Stupid bot.');
200 // Captcha::valid() is a static method that can be used as a Validation rule also.
201 if (Captcha::valid($this->input->post('captcha_response')))
203 echo '<p style="color:green">Good answer!</p>';
207 echo '<p style="color:red">Wrong answer!</p>';
210 // Validate other fields here
215 echo '<p>Other form fields here...</p>';
217 // Don't show Captcha anymore after the user has given enough valid
218 // responses. The "enough" count is set in the captcha config.
219 if ( ! $captcha->promoted())
222 echo $captcha->render(); // Shows the Captcha challenge (image/riddle/etc)
224 echo form::input('captcha_response');
228 echo '<p>You have been promoted to human.</p>';
232 echo form::submit(array('value' => 'Check'));
237 * Demonstrates the features of the Database library.
240 * CREATE TABLE `pages` (
241 * `id` mediumint( 9 ) NOT NULL AUTO_INCREMENT ,
242 * `page_name` varchar( 100 ) NOT NULL ,
243 * `title` varchar( 255 ) NOT NULL ,
244 * `content` longtext NOT NULL ,
245 * `menu` tinyint( 1 ) NOT NULL default '0',
246 * `filename` varchar( 255 ) NOT NULL ,
247 * `order` mediumint( 9 ) NOT NULL ,
248 * `date` int( 11 ) NOT NULL ,
249 * `child_of` mediumint( 9 ) NOT NULL default '0',
250 * PRIMARY KEY ( `id` ) ,
251 * UNIQUE KEY `filename` ( `filename` )
252 * ) ENGINE = MYISAM DEFAULT CHARSET = utf8 PACK_KEYS =0;
260 echo 'Does the '.$table.' table exist? ';
261 if ($db->table_exists($table))
263 echo '<p>YES! Lets do some work =)</p>';
265 $query = $db->select('DISTINCT pages.*')->from($table)->get();
266 echo $db->last_query();
267 echo '<h3>Iterate through the result:</h3>';
268 foreach ($query as $item)
270 echo '<p>'.$item->title.'</p>';
272 echo '<h3>Numrows using count(): '.count($query).'</h3>';
273 echo 'Table Listing:<pre>'.print_r($db->list_tables(), TRUE).'</pre>';
275 echo '<h3>Try Query Binding with objects:</h3>';
276 $sql = 'SELECT * FROM '.$table.' WHERE id = ?';
277 $query = $db->query($sql, array(1));
278 echo '<p>'.$db->last_query().'</p>';
279 $query->result(TRUE);
280 foreach ($query as $item)
282 echo '<pre>'.print_r($item, true).'</pre>';
285 echo '<h3>Try Query Binding with arrays (returns both associative and numeric because I pass MYSQL_BOTH to result():</h3>';
286 $sql = 'SELECT * FROM '.$table.' WHERE id = ?';
287 $query = $db->query($sql, array(1));
288 echo '<p>'.$db->last_query().'</p>';
289 $query->result(FALSE, MYSQL_BOTH);
290 foreach ($query as $item)
292 echo '<pre>'.print_r($item, true).'</pre>';
295 echo '<h3>Look, we can also manually advance the result pointer!</h3>';
296 $query = $db->select('title')->from($table)->get();
297 echo 'First:<pre>'.print_r($query->current(), true).'</pre><br />';
299 echo 'Second:<pre>'.print_r($query->current(), true).'</pre><br />';
301 echo 'Third:<pre>'.print_r($query->current(), true).'</pre>';
302 echo '<h3>And we can reset it to the beginning:</h3>';
304 echo 'Rewound:<pre>'.print_r($query->current(), true).'</pre>';
306 echo '<p>Number of rows using count_records(): '.$db->count_records('pages').'</p>';
310 echo 'NO! The '.$table.' table doesn\'t exist, so we can\'t continue =( ';
313 echo 'done in {execution_time} seconds';
317 * Demonstrates how to use the Pagination library and Pagination styles.
319 function pagination()
321 $pagination = new Pagination(array(
322 // Base_url will default to the current URI
323 // 'base_url' => 'welcome/pagination_example/page/x',
325 // The URI segment (integer) in which the pagination number can be found
326 // The URI segment (string) that precedes the pagination number (aka "label")
327 'uri_segment' => 'page',
329 // You could also use the query string for pagination instead of the URI segments
330 // Just set this to the $_GET key that contains the page number
331 // 'query_string' => 'page',
333 // The total items to paginate through (probably need to use a database COUNT query here)
334 'total_items' => 254,
336 // The amount of items you want to display per page
337 'items_per_page' => 10,
339 // The pagination style: classic (default), digg, extended or punbb
340 // Easily add your own styles to views/pagination and point to the view name here
341 'style' => 'classic',
343 // If there is only one page, completely hide all pagination elements
344 // Pagination->render() will return an empty string
348 // Just echo to display the links (__toString() rocks!)
349 echo 'Classic style: '.$pagination;
351 // You can also use the render() method and pick a style on the fly if you want
352 echo '<hr /> Digg style: ', $pagination->render('digg');
353 echo '<hr /> Extended style: ', $pagination->render('extended');
354 echo '<hr /> PunBB style: ', $pagination->render('punbb');
355 echo 'done in {execution_time} seconds';
359 * Demonstrates the User_Agent library.
361 function user_agent()
363 foreach (array('agent', 'browser', 'version') as $key)
365 echo $key.': '.Kohana::user_agent($key).'<br/>'."\n";
369 echo 'done in {execution_time} seconds';
373 * Demonstrates the Payment library.
377 $credit_card = new Payment;
379 // You can also pass the driver name to the library to use multiple ones:
380 $credit_card = new Payment('Paypal');
381 $credit_card = new Payment('Authorize');
383 // You can specify one parameter at a time:
384 $credit_card->login = 'this';
385 $credit_card->first_name = 'Jeremy';
386 $credit_card->last_name = 'Bush';
387 $credit_card->card_num = '1234567890';
388 $credit_card->exp_date = '0910';
389 $credit_card->amount = '478.41';
391 // Or you can also set fields with an array and the <Payment.set_fields> method:
392 $credit_card->set_fields(array('login' => 'test',
393 'first_name' => 'Jeremy',
394 'last_name' => 'Bush',
395 'card_num' => '1234567890',
396 'exp_date' => '0910',
397 'amount' => '487.41'));
399 echo '<pre>'.print_r($credit_card, true).'</pre>';
402 echo ($response = $credit_card->process() == TRUE) ? 'YES!' : $response;
407 $profiler = new Profiler;
409 $calendar = new Calendar($this->input->get('month', date('m')), $this->input->get('year', date('Y')));
410 $calendar->attach($calendar->event()
411 ->condition('year', 2008)
412 ->condition('month', 8)
413 ->condition('day', 8)
414 ->output(html::anchor('http://forum.kohanaphp.com/comments.php?DiscussionID=275', 'Learning about Kohana Calendar')));
416 echo $calendar->render();
420 * Demonstrates how to use the Image libarary..
424 // For testing only, save the new image in DOCROOT
425 $dir = realpath(DOCROOT);
427 // Original Image filename
428 $image = DOCROOT.'kohana.png';
430 // Create an instance of Image, with file
431 // The orginal image is not affected
432 $image = new Image($image);
434 // Most methods are chainable
435 // Resize the image, crop the center left
436 $image->resize(200, 100)->crop(150, 50, 'center', 'left');
438 // Display image in browser.
439 // Keep the actions, to be applied when saving the image.
440 $image->render($keep_actions = TRUE);
442 // Save the image, as a jpeg
443 // Here the actions will be discarded, by default.
444 $image->save($dir.'/mypic_thumb.jpg');
446 //echo Kohana::debug($image);
450 * Demonstrates how to use vendor software with Kohana.
454 // Let's do a little Markdown shall we.
456 $output = '#Marked Down!#'.$br;
457 $output .= 'This **_markup_** is created *on-the-fly*, by ';
458 $output .= '[php-markdown-extra](http://michelf.com/projects/php-markdown/extra)'.$br;
459 $output .= 'It\'s *great* for user <input> & writing about `<HTML>`'.$br;
460 $output .= 'It\'s also good at footnotes :-) [^1]'.$br;
461 $output .= '[^1]: A footnote.';
463 // looks in system/vendor for Markdown.php
464 require Kohana::find_file('vendor', 'Markdown');
466 echo Markdown($output);
468 echo 'done in {execution_time} seconds';