Initial Kohana install
[speedfreak] / Server / application / controllers / examples.php
1 <?php defined('SYSPATH') OR die('No direct access allowed.');
2 /**
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
6  * purposes only!
7  *
8  * $Id: examples.php 4298 2009-04-30 17:06:05Z kiall $
9  *
10  * @package    Core
11  * @author     Kohana Team
12  * @copyright  (c) 2007-2008 Kohana Team
13  * @license    http://kohanaphp.com/license.html
14  */
15 class Examples_Controller extends Controller {
16
17         // Do not allow to run in production
18         const ALLOW_PRODUCTION = FALSE;
19
20         /**
21          * Displays a list of available examples
22          */
23         function index()
24         {
25                 // Get the methods that are only in this class and not the parent class.
26                 $examples = array_diff
27                 (
28                         get_class_methods(__CLASS__),
29                         get_class_methods(get_parent_class($this))
30                 );
31
32                 sort($examples);
33
34                 echo "<strong>Examples:</strong>\n";
35                 echo "<ul>\n";
36
37                 foreach ($examples as $method)
38                 {
39                         if ($method == __FUNCTION__)
40                                 continue;
41
42                         echo '<li>'.html::anchor('examples/'.$method, $method)."</li>\n";
43                 }
44
45                 echo "</ul>\n";
46                 echo '<p>'.Kohana::lang('core.stats_footer')."</p>\n";
47         }
48
49         /**
50          * Demonstrates how to archive a directory. First enable the archive module
51          */
52         //public function archive($build = FALSE)
53         //{
54         //      if ($build === 'build')
55         //      {
56         //              // Load archive
57         //              $archive = new Archive('zip');
58
59         //              // Download the application/views directory
60         //              $archive->add(APPPATH.'views/', 'app_views/', TRUE);
61
62         //              // Download the built archive
63         //              $archive->download('test.zip');
64         //      }
65         //      else
66         //      {
67         //              echo html::anchor(Router::$current_uri.'/build', 'Download views');
68         //      }
69         //}
70
71         /**
72          * Demonstrates how to parse RSS feeds by using DOMDocument.
73          */
74         function rss()
75         {
76                 // Parse an external atom feed
77                 $feed = feed::parse('http://dev.kohanaphp.com/projects/kohana2/activity.atom');
78
79                 // Show debug info
80                 echo Kohana::debug($feed);
81
82                 echo Kohana::lang('core.stats_footer');
83         }
84
85         /**
86          * Demonstrates the Session library and using session data.
87          */
88         function session()
89         {
90                 // Gets the singleton instance of the Session library
91                 $s = Session::instance();
92
93                 echo 'SESSID: <pre>'.session_id()."</pre>\n";
94
95                 echo '<pre>'.print_r($_SESSION, TRUE)."</pre>\n";
96
97                 echo '<br/>{execution_time} seconds';
98         }
99
100         /**
101          * Demonstrates how to use the form helper with the Validation libraryfor file uploads .
102          */
103         function form()
104         {
105                 // Anything submitted?
106                 if ($_POST)
107                 {
108                         // Merge the globals into our validation object.
109                         $post = Validation::factory(array_merge($_POST, $_FILES));
110
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]');
115
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]');
118
119                         if ($post->validate() )
120                         {
121                                 // It worked!
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!';
126                         }
127                         else
128                         {
129                                 // You got validation errors
130                                 echo '<p>validation errors: '.var_export($post->errors(), TRUE).'</p>';
131                                 echo Kohana::debug($post);
132                         }
133                 }
134
135                 // Display the form
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/>';
141
142                 echo form::upload('imageup1').'<br/>';
143                 echo form::upload('imageup2').'<br/>';
144                 echo form::submit('upload', 'Upload!');
145                 echo form::close();
146
147         }
148
149         /**
150          * Demontrates how to use the Validation library to validate an arbitrary array.
151          */
152         function validation()
153         {
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.
157                 $data = array
158                 (
159                         'user' => 'hello',
160                         'pass' => 'bigsecret',
161                         'reme' => '1'
162                 );
163
164                 $validation = new Validation($data);
165
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');
169
170                 $result = $validation->validate();
171
172                 var_dump($validation->errors());
173                 var_dump($validation->as_array());
174
175                 // Yay!
176                 echo '{execution_time} ALL DONE!';
177         }
178
179         /**
180          * Demontrates how to use the Captcha library.
181          */
182         public function captcha()
183         {
184                 // Look at the counters for valid and invalid
185                 // responses in the Session Profiler.
186                 new Profiler;
187
188                 // Load Captcha library, you can supply the name
189                 // of the config group you would like to use.
190                 $captcha = new Captcha;
191
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.');
196
197                 // Form submitted
198                 if ($_POST)
199                 {
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')))
202                         {
203                                 echo '<p style="color:green">Good answer!</p>';
204                         }
205                         else
206                         {
207                                 echo '<p style="color:red">Wrong answer!</p>';
208                         }
209
210                         // Validate other fields here
211                 }
212
213                 // Show form
214                 echo form::open();
215                 echo '<p>Other form fields here...</p>';
216
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())
220                 {
221                         echo '<p>';
222                         echo $captcha->render(); // Shows the Captcha challenge (image/riddle/etc)
223                         echo '</p>';
224                         echo form::input('captcha_response');
225                 }
226                 else
227                 {
228                         echo '<p>You have been promoted to human.</p>';
229                 }
230
231                 // Close form
232                 echo form::submit(array('value' => 'Check'));
233                 echo form::close();
234         }
235
236         /**
237          * Demonstrates the features of the Database library.
238          *
239          * Table Structure:
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;
253          *
254         */
255         function database()
256         {
257                 $db = new Database;
258
259                 $table = 'pages';
260                 echo 'Does the '.$table.' table exist? ';
261                 if ($db->table_exists($table))
262                 {
263                         echo '<p>YES! Lets do some work =)</p>';
264
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)
269                         {
270                                 echo '<p>'.$item->title.'</p>';
271                         }
272                         echo '<h3>Numrows using count(): '.count($query).'</h3>';
273                         echo 'Table Listing:<pre>'.print_r($db->list_tables(), TRUE).'</pre>';
274
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)
281                         {
282                                 echo '<pre>'.print_r($item, true).'</pre>';
283                         }
284
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)
291                         {
292                                 echo '<pre>'.print_r($item, true).'</pre>';
293                         }
294
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 />';
298                         $query->next();
299                         echo 'Second:<pre>'.print_r($query->current(), true).'</pre><br />';
300                         $query->next();
301                         echo 'Third:<pre>'.print_r($query->current(), true).'</pre>';
302                         echo '<h3>And we can reset it to the beginning:</h3>';
303                         $query->rewind();
304                         echo 'Rewound:<pre>'.print_r($query->current(), true).'</pre>';
305
306                         echo '<p>Number of rows using count_records(): '.$db->count_records('pages').'</p>';
307                 }
308                 else
309                 {
310                         echo 'NO! The '.$table.' table doesn\'t exist, so we can\'t continue =( ';
311                 }
312                 echo "<br/><br/>\n";
313                 echo 'done in {execution_time} seconds';
314         }
315
316         /**
317          * Demonstrates how to use the Pagination library and Pagination styles.
318          */
319         function pagination()
320         {
321                 $pagination = new Pagination(array(
322                         // Base_url will default to the current URI
323                         // 'base_url'    => 'welcome/pagination_example/page/x',
324
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',
328
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',
332
333                         // The total items to paginate through (probably need to use a database COUNT query here)
334                         'total_items'    => 254,
335
336                         // The amount of items you want to display per page
337                         'items_per_page' => 10,
338
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',
342
343                         // If there is only one page, completely hide all pagination elements
344                         // Pagination->render() will return an empty string
345                         'auto_hide'      => TRUE,
346                 ));
347
348                 // Just echo to display the links (__toString() rocks!)
349                 echo 'Classic style: '.$pagination;
350
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';
356         }
357
358         /**
359          * Demonstrates the User_Agent library.
360          */
361         function user_agent()
362         {
363                 foreach (array('agent', 'browser', 'version') as $key)
364                 {
365                         echo $key.': '.Kohana::user_agent($key).'<br/>'."\n";
366                 }
367
368                 echo "<br/><br/>\n";
369                 echo 'done in {execution_time} seconds';
370         }
371
372         /**
373          * Demonstrates the Payment library.
374          */
375         /*function payment()
376         {
377                 $credit_card = new Payment;
378
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');
382
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';
390
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'));
398
399                 echo '<pre>'.print_r($credit_card, true).'</pre>';
400
401                 echo 'Success? ';
402                 echo ($response = $credit_card->process() == TRUE) ? 'YES!' : $response;
403         }*/
404
405         function calendar()
406         {
407                 $profiler = new Profiler;
408
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')));
415
416                 echo $calendar->render();
417         }
418
419         /**
420          * Demonstrates how to use the Image libarary..
421          */
422         function image()
423         {
424                 // For testing only, save the new image in DOCROOT
425                 $dir = realpath(DOCROOT);
426
427                 // Original Image filename
428                 $image = DOCROOT.'kohana.png';
429
430                 // Create an instance of Image, with file
431                 // The orginal image is not affected
432                 $image = new Image($image);
433
434                 // Most methods are chainable
435                 // Resize the image, crop the center left
436                 $image->resize(200, 100)->crop(150, 50, 'center', 'left');
437
438                 // Display image in browser.
439                 // Keep the actions, to be applied when saving the image.
440                 $image->render($keep_actions = TRUE);
441
442                 // Save the image, as a jpeg
443                 // Here the actions will be discarded, by default.
444                 $image->save($dir.'/mypic_thumb.jpg');
445
446                 //echo Kohana::debug($image);
447         }
448
449         /**
450          * Demonstrates how to use vendor software with Kohana.
451          */
452         function vendor()
453         {
454                 // Let's do a little Markdown shall we.
455                 $br = "\n\n";
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.';
462
463                 // looks in system/vendor for Markdown.php
464                 require Kohana::find_file('vendor', 'Markdown');
465
466                 echo Markdown($output);
467
468                 echo 'done in {execution_time} seconds';
469         }
470 } // End Examples