PageRenderTime 53ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/application/controllers/examples.php

https://github.com/Toushi/flow
PHP | 468 lines | 223 code | 71 blank | 174 comment | 9 complexity | 91bf421bf5b488b44d9bba712ad1d05e MD5 | raw file
  1. <?php defined('SYSPATH') or die('No direct script access.');
  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 3318 2008-08-09 00:53:59Z Shadowhand $
  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. // Do not allow to run in production
  17. const ALLOW_PRODUCTION = FALSE;
  18. /**
  19. * Displays a list of available examples
  20. */
  21. function index()
  22. {
  23. // Get the methods that are only in this class and not the parent class.
  24. $examples = array_diff
  25. (
  26. get_class_methods(__CLASS__),
  27. get_class_methods(get_parent_class($this))
  28. );
  29. sort($examples);
  30. echo "<strong>Examples:</strong>\n";
  31. echo "<ul>\n";
  32. foreach ($examples as $method)
  33. {
  34. if ($method == __FUNCTION__)
  35. continue;
  36. echo '<li>'.html::anchor('examples/'.$method, $method)."</li>\n";
  37. }
  38. echo "</ul>\n";
  39. echo '<p>'.Kohana::lang('core.stats_footer')."</p>\n";
  40. }
  41. /**
  42. * Demonstrates how to archive a directory. First enable the archive module
  43. */
  44. //public function archive($build = FALSE)
  45. //{
  46. // if ($build === 'build')
  47. // {
  48. // // Load archive
  49. // $archive = new Archive('zip');
  50. // // Download the application/views directory
  51. // $archive->add(APPPATH.'views/', 'app_views/', TRUE);
  52. // // Download the built archive
  53. // $archive->download('test.zip');
  54. // }
  55. // else
  56. // {
  57. // echo html::anchor(Router::$current_uri.'/build', 'Download views');
  58. // }
  59. //}
  60. /**
  61. * Demonstrates how to parse RSS feeds by using DOMDocument.
  62. */
  63. function rss()
  64. {
  65. // Parse an external atom feed
  66. $feed = feed::parse('http://trac.kohanaphp.com/timeline?changeset=on&format=rss');
  67. // Show debug info
  68. echo Kohana::debug($feed);
  69. echo Kohana::lang('core.stats_footer');
  70. }
  71. /**
  72. * Demonstrates the Session library and using session data.
  73. */
  74. function session()
  75. {
  76. // Gets the singleton instance of the Session library
  77. $s = Session::instance();
  78. echo 'SESSID: <pre>'.session_id()."</pre>\n";
  79. echo '<pre>'.print_r($_SESSION, TRUE)."</pre>\n";
  80. echo '<br/>{execution_time} seconds';
  81. }
  82. /**
  83. * Demonstrates how to use the form helper with the Validation libraryfor file uploads .
  84. */
  85. function form()
  86. {
  87. // Anything submitted?
  88. if ($_POST)
  89. {
  90. // Merge the globals into our validation object.
  91. $post = Validation::factory(array_merge($_POST, $_FILES));
  92. // Ensure upload helper is correctly configured, config/upload.php contains default entries.
  93. // Uploads can be required or optional, but should be valid
  94. $post->add_rules('imageup1', 'upload::required', 'upload::valid', 'upload::type[gif,jpg,png]', 'upload::size[1M]');
  95. $post->add_rules('imageup2', 'upload::required', 'upload::valid', 'upload::type[gif,jpg,png]', 'upload::size[1M]');
  96. // Alternative syntax for multiple file upload validation rules
  97. //$post->add_rules('imageup.*', 'upload::required', 'upload::valid', 'upload::type[gif,jpg,png]', 'upload::size[1M]');
  98. if ($post->validate() )
  99. {
  100. // It worked!
  101. // Move (and rename) the files from php upload folder to configured application folder
  102. upload::save('imageup1');
  103. upload::save('imageup2');
  104. echo 'Validation successfull, check your upload folder!';
  105. }
  106. else
  107. {
  108. // You got validation errors
  109. echo '<p>validation errors: '.var_export($post->errors(), TRUE).'</p>';
  110. echo Kohana::debug($post);
  111. }
  112. }
  113. // Display the form
  114. echo form::open('examples/form', array('enctype' => 'multipart/form-data'));
  115. echo form::label('imageup', 'Image Uploads').':<br/>';
  116. // Use discrete upload fields
  117. // Alternative syntax for multiple file uploads
  118. // echo form::upload('imageup[]').'<br/>';
  119. echo form::upload('imageup1').'<br/>';
  120. echo form::upload('imageup2').'<br/>';
  121. echo form::submit('upload', 'Upload!');
  122. echo form::close();
  123. }
  124. /**
  125. * Demontrates how to use the Validation library to validate an arbitrary array.
  126. */
  127. function validation()
  128. {
  129. // To demonstrate Validation being able to validate any array, I will
  130. // be using a pre-built array. When you load validation with no arguments
  131. // it will default to validating the POST array.
  132. $data = array
  133. (
  134. 'user' => 'hello',
  135. 'pass' => 'bigsecret',
  136. 'reme' => '1'
  137. );
  138. $validation = new Validation($data);
  139. $validation->add_rules('user', 'required', 'length[1,12]')->pre_filter('trim', 'user');
  140. $validation->add_rules('pass', 'required')->post_filter('sha1', 'pass');
  141. $validation->add_rules('reme', 'required');
  142. $result = $validation->validate();
  143. var_dump($validation->errors());
  144. var_dump($validation->as_array());
  145. // Yay!
  146. echo '{execution_time} ALL DONE!';
  147. }
  148. /**
  149. * Demontrates how to use the Captcha library.
  150. */
  151. public function captcha()
  152. {
  153. // Look at the counters for valid and invalid
  154. // responses in the Session Profiler.
  155. new Profiler;
  156. // Load Captcha library, you can supply the name
  157. // of the config group you would like to use.
  158. $captcha = new Captcha;
  159. // Ban bots (that accept session cookies) after 50 invalid responses.
  160. // Be careful not to ban real people though! Set the threshold high enough.
  161. if ($captcha->invalid_count() > 49)
  162. exit('Bye! Stupid bot.');
  163. // Form submitted
  164. if ($_POST)
  165. {
  166. // Captcha::valid() is a static method that can be used as a Validation rule also.
  167. if (Captcha::valid($this->input->post('captcha_response')))
  168. {
  169. echo '<p style="color:green">Good answer!</p>';
  170. }
  171. else
  172. {
  173. echo '<p style="color:red">Wrong answer!</p>';
  174. }
  175. // Validate other fields here
  176. }
  177. // Show form
  178. echo form::open();
  179. echo '<p>Other form fields here...</p>';
  180. // Don't show Captcha anymore after the user has given enough valid
  181. // responses. The "enough" count is set in the captcha config.
  182. if ( ! $captcha->promoted())
  183. {
  184. echo '<p>';
  185. echo $captcha->render(); // Shows the Captcha challenge (image/riddle/etc)
  186. echo '</p>';
  187. echo form::input('captcha_response');
  188. }
  189. else
  190. {
  191. echo '<p>You have been promoted to human.</p>';
  192. }
  193. // Close form
  194. echo form::submit(array('value' => 'Check'));
  195. echo form::close();
  196. }
  197. /**
  198. * Demonstrates the features of the Database library.
  199. *
  200. * Table Structure:
  201. * CREATE TABLE `pages` (
  202. * `id` mediumint( 9 ) NOT NULL AUTO_INCREMENT ,
  203. * `page_name` varchar( 100 ) NOT NULL ,
  204. * `title` varchar( 255 ) NOT NULL ,
  205. * `content` longtext NOT NULL ,
  206. * `menu` tinyint( 1 ) NOT NULL default '0',
  207. * `filename` varchar( 255 ) NOT NULL ,
  208. * `order` mediumint( 9 ) NOT NULL ,
  209. * `date` int( 11 ) NOT NULL ,
  210. * `child_of` mediumint( 9 ) NOT NULL default '0',
  211. * PRIMARY KEY ( `id` ) ,
  212. * UNIQUE KEY `filename` ( `filename` )
  213. * ) ENGINE = MYISAM DEFAULT CHARSET = utf8 PACK_KEYS =0;
  214. *
  215. */
  216. function database()
  217. {
  218. $db = new Database;
  219. $table = 'pages';
  220. echo 'Does the '.$table.' table exist? ';
  221. if ($db->table_exists($table))
  222. {
  223. echo '<p>YES! Lets do some work =)</p>';
  224. $query = $db->select('DISTINCT pages.*')->from($table)->get();
  225. echo $db->last_query();
  226. echo '<h3>Iterate through the result:</h3>';
  227. foreach ($query as $item)
  228. {
  229. echo '<p>'.$item->title.'</p>';
  230. }
  231. echo '<h3>Numrows using count(): '.count($query).'</h3>';
  232. echo 'Table Listing:<pre>'.print_r($db->list_tables(), TRUE).'</pre>';
  233. echo '<h3>Try Query Binding with objects:</h3>';
  234. $sql = 'SELECT * FROM '.$table.' WHERE id = ?';
  235. $query = $db->query($sql, array(1));
  236. echo '<p>'.$db->last_query().'</p>';
  237. $query->result(TRUE);
  238. foreach ($query as $item)
  239. {
  240. echo '<pre>'.print_r($item, true).'</pre>';
  241. }
  242. echo '<h3>Try Query Binding with arrays (returns both associative and numeric because I pass MYSQL_BOTH to result():</h3>';
  243. $sql = 'SELECT * FROM '.$table.' WHERE id = ?';
  244. $query = $db->query($sql, array(1));
  245. echo '<p>'.$db->last_query().'</p>';
  246. $query->result(FALSE, MYSQL_BOTH);
  247. foreach ($query as $item)
  248. {
  249. echo '<pre>'.print_r($item, true).'</pre>';
  250. }
  251. echo '<h3>Look, we can also manually advance the result pointer!</h3>';
  252. $query = $db->select('title')->from($table)->get();
  253. echo 'First:<pre>'.print_r($query->current(), true).'</pre><br />';
  254. $query->next();
  255. echo 'Second:<pre>'.print_r($query->current(), true).'</pre><br />';
  256. $query->next();
  257. echo 'Third:<pre>'.print_r($query->current(), true).'</pre>';
  258. echo '<h3>And we can reset it to the beginning:</h3>';
  259. $query->rewind();
  260. echo 'Rewound:<pre>'.print_r($query->current(), true).'</pre>';
  261. echo '<p>Number of rows using count_records(): '.$db->count_records('pages').'</p>';
  262. }
  263. else
  264. {
  265. echo 'NO! The '.$table.' table doesn\'t exist, so we can\'t continue =( ';
  266. }
  267. echo "<br/><br/>\n";
  268. echo 'done in {execution_time} seconds';
  269. }
  270. /**
  271. * Demonstrates how to use the Pagination library and Pagination styles.
  272. */
  273. function pagination()
  274. {
  275. $pagination = new Pagination(array(
  276. // Base_url will default to the current URI
  277. // 'base_url' => 'welcome/pagination_example/page/x',
  278. // The URI segment (integer) in which the pagination number can be found
  279. // The URI segment (string) that precedes the pagination number (aka "label")
  280. 'uri_segment' => 'page',
  281. // You could also use the query string for pagination instead of the URI segments
  282. // Just set this to the $_GET key that contains the page number
  283. // 'query_string' => 'page',
  284. // The total items to paginate through (probably need to use a database COUNT query here)
  285. 'total_items' => 254,
  286. // The amount of items you want to display per page
  287. 'items_per_page' => 10,
  288. // The pagination style: classic (default), digg, extended or punbb
  289. // Easily add your own styles to views/pagination and point to the view name here
  290. 'style' => 'classic',
  291. // If there is only one page, completely hide all pagination elements
  292. // Pagination->render() will return an empty string
  293. 'auto_hide' => TRUE,
  294. ));
  295. // Just echo to display the links (__toString() rocks!)
  296. echo 'Classic style: '.$pagination;
  297. // You can also use the render() method and pick a style on the fly if you want
  298. echo '<hr /> Digg style: ', $pagination->render('digg');
  299. echo '<hr /> Extended style: ', $pagination->render('extended');
  300. echo '<hr /> PunBB style: ', $pagination->render('punbb');
  301. echo 'done in {execution_time} seconds';
  302. }
  303. /**
  304. * Demonstrates the User_Agent library.
  305. */
  306. function user_agent()
  307. {
  308. foreach (array('agent', 'browser', 'version') as $key)
  309. {
  310. echo $key.': '.Kohana::user_agent($key).'<br/>'."\n";
  311. }
  312. echo "<br/><br/>\n";
  313. echo 'done in {execution_time} seconds';
  314. }
  315. /**
  316. * Demonstrates the Payment library.
  317. */
  318. /*function payment()
  319. {
  320. $credit_card = new Payment;
  321. // You can also pass the driver name to the library to use multiple ones:
  322. $credit_card = new Payment('Paypal');
  323. $credit_card = new Payment('Authorize');
  324. // You can specify one parameter at a time:
  325. $credit_card->login = 'this';
  326. $credit_card->first_name = 'Jeremy';
  327. $credit_card->last_name = 'Bush';
  328. $credit_card->card_num = '1234567890';
  329. $credit_card->exp_date = '0910';
  330. $credit_card->amount = '478.41';
  331. // Or you can also set fields with an array and the <Payment.set_fields> method:
  332. $credit_card->set_fields(array('login' => 'test',
  333. 'first_name' => 'Jeremy',
  334. 'last_name' => 'Bush',
  335. 'card_num' => '1234567890',
  336. 'exp_date' => '0910',
  337. 'amount' => '487.41'));
  338. echo '<pre>'.print_r($credit_card, true).'</pre>';
  339. echo 'Success? ';
  340. echo ($response = $credit_card->process() == TRUE) ? 'YES!' : $response;
  341. }*/
  342. function calendar()
  343. {
  344. $profiler = new Profiler;
  345. $calendar = new Calendar($this->input->get('month', date('m')), $this->input->get('year', date('Y')));
  346. $calendar->attach($calendar->event()
  347. ->condition('year', 2008)
  348. ->condition('month', 8)
  349. ->condition('day', 8)
  350. ->output(html::anchor('http://forum.kohanaphp.com/comments.php?DiscussionID=275', 'Learning about Kohana Calendar')));
  351. echo $calendar->render();
  352. }
  353. /**
  354. * Demonstrates how to use the Image libarary..
  355. */
  356. function image()
  357. {
  358. // Application Upload directory
  359. $dir = realpath(DOCROOT.'upload').'/';
  360. // Image filename
  361. $image = DOCROOT.'kohana.png';
  362. // Create an instance of Image, with file
  363. // The orginal image is not affected
  364. $image = new Image($image);
  365. // Most methods are chainable
  366. // Resize the image, crop the center left
  367. $image->resize(200, 100)->crop(150, 50, 'center', 'left');
  368. // Display image in browser
  369. $image->render();
  370. // Save the image
  371. $image->save($dir.'mypic_thumb.jpg');
  372. //echo Kohana::debug($image);
  373. }
  374. /**
  375. * Demonstrates how to use vendor software with Kohana.
  376. */
  377. function vendor()
  378. {
  379. // Let's do a little Markdown shall we.
  380. $br = "\n\n";
  381. $output = '#Marked Down!#'.$br;
  382. $output .= 'This **_markup_** is created *on-the-fly*, by ';
  383. $output .= '[php-markdown-extra](http://michelf.com/projects/php-markdown/extra)'.$br;
  384. $output .= 'It\'s *great* for user <input> & writing about `<HTML>`'.$br;
  385. $output .= 'It\'s also good at footnotes :-) [^1]'.$br;
  386. $output .= '[^1]: A footnote.';
  387. // looks in system/vendor for Markdown.php
  388. require Kohana::find_file('vendor', 'Markdown');
  389. echo Markdown($output);
  390. echo 'done in {execution_time} seconds';
  391. }
  392. } // End Examples