Source for file Form.php

Documentation is available at Form.php

  1. 1: <?php
  2. 2:  
  3. 3: /**
  4. 4:  * Nette Framework
  5. 5:  *
  6. 6:  * Copyright (c) 2004, 2009 David Grudl (http://davidgrudl.com)
  7. 7:  *
  8. 8:  * This source file is subject to the "Nette license" that is bundled
  9. 9:  * with this package in the file license.txt.
  10. 10:  *
  11. 11:  * For more information please see http://nettephp.com
  12. 12:  *
  13. 13:  * @copyright  Copyright (c) 2004, 2009 David Grudl
  14. 14:  * @license    http://nettephp.com/license  Nette license
  15. 15:  * @link       http://nettephp.com
  16. 16:  * @category   Nette
  17. 17:  * @package    Nette\Forms
  18. 18:  */
  19. 19:  
  20. 20:  
  21. 21:  
  22. 22: require_once dirname(__FILE__'/../Forms/FormContainer.php';
  23. 23:  
  24. 24:  
  25. 25:  
  26. 26: /**
  27. 27:  * Creates, validates and renders HTML forms.
  28. 28:  *
  29. 29:  * @author     David Grudl
  30. 30:  * @copyright  Copyright (c) 2004, 2009 David Grudl
  31. 31:  * @package    Nette\Forms
  32. 32:  *
  33. 33:  * @example    forms/basic-example.php  Form definition using fluent interfaces
  34. 34:  * @example    forms/manual-rendering.php  Manual form rendering and separated form and rules definition
  35. 35:  * @example    forms/localization.php  Localization (with Zend_Translate)
  36. 36:  * @example    forms/custom-rendering.php  Custom form rendering
  37. 37:  * @example    forms/custom-validator.php  How to use custom validator
  38. 38:  * @example    forms/naming-containers.php  How to use naming containers
  39. 39:  * @example    forms/CSRF-protection.php  How to use Cross-Site Request Forgery (CSRF) form protection
  40. 40:  * @example    forms/custom-encoding.php  How to change charset
  41. 41:  *
  42. 42:  * @property   string $action 
  43. 43:  * @property   string $method 
  44. 44:  * @property-read array $groups 
  45. 45:  * @property-read array $httpData 
  46. 46:  * @property   string $encoding 
  47. 47:  * @property   ITranslator $translator 
  48. 48:  * @property-read array $errors 
  49. 49:  * @property-read Html $elementPrototype 
  50. 50:  * @property   IFormRenderer $renderer 
  51. 51:  * @property-read boold $submitted 
  52. 52:  */
  53. 53: class Form extends FormContainer
  54. 54: {
  55. 55:     /**#@+ operation name */
  56. 56:     const EQUAL = ':equal';
  57. 57:     const IS_IN = ':equal';
  58. 58:     const FILLED = ':filled';
  59. 59:     const VALID = ':valid';
  60. 60:  
  61. 61:     // button
  62. 62:     const SUBMITTED = ':submitted';
  63. 63:  
  64. 64:     // text
  65. 65:     const MIN_LENGTH = ':minLength';
  66. 66:     const MAX_LENGTH = ':maxLength';
  67. 67:     const LENGTH = ':length';
  68. 68:     const EMAIL = ':email';
  69. 69:     const URL = ':url';
  70. 70:     const REGEXP = ':regexp';
  71. 71:     const INTEGER = ':integer';
  72. 72:     const NUMERIC = ':integer';
  73. 73:     const FLOAT = ':float';
  74. 74:     const RANGE = ':range';
  75. 75:  
  76. 76:     // file upload
  77. 77:     const MAX_FILE_SIZE = ':fileSize';
  78. 78:     const MIME_TYPE = ':mimeType';
  79. 79:  
  80. 80:     // special case
  81. 81:     const SCRIPT = 'Nette\Forms\InstantClientScript::javascript';
  82. 82:     /**#@-*/
  83. 83:  
  84. 84:     /**#@+ method */
  85. 85:     const GET = 'get';
  86. 86:     const POST = 'post';
  87. 87:     /**#@-*/
  88. 88:  
  89. 89:     /** @ignore internal tracker ID */
  90. 90:     const TRACKER_ID '_form_';
  91. 91:  
  92. 92:     /** @ignore internal protection token ID */
  93. 93:     const PROTECTOR_ID '_token_';
  94. 94:  
  95. 95:     /** @var array of function(Form $sender); Occurs when the form is submitted and successfully validated */
  96. 96:     public $onSubmit;
  97. 97:  
  98. 98:     /** @var array of function(Form $sender); Occurs when the form is submitted and not validated */
  99. 99:     public $onInvalidSubmit;
  100. 100:  
  101. 101:     /** @var mixed or NULL meaning: not detected yet */
  102. 102:     private $submittedBy;
  103. 103:  
  104. 104:     /** @var array */
  105. 105:     private $httpData;
  106. 106:  
  107. 107:     /** @var Html  <form> element */
  108. 108:     private $element;
  109. 109:  
  110. 110:     /** @var IFormRenderer */
  111. 111:     private $renderer;
  112. 112:  
  113. 113:     /** @var ITranslator */
  114. 114:     private $translator;
  115. 115:  
  116. 116:     /** @var array of FormGroup */
  117. 117:     private $groups array();
  118. 118:  
  119. 119:     /** @var array */
  120. 120:     private $errors array();
  121. 121:  
  122. 122:     /** @var array */
  123. 123:     private $encoding 'UTF-8';
  124. 124:  
  125. 125:  
  126. 126:  
  127. 127:     /**
  128. 128:      * Form constructor.
  129. 129:      * @param  string 
  130. 130:      */
  131. 131:     public function __construct($name NULL)
  132. 132:     {
  133. 133:         $this->element Html::el('form');
  134. 134:         $this->element->action ''// RFC 1808 -> empty uri means 'this'
  135. 135:         $this->element->method self::POST;
  136. 136:         $this->monitor(__CLASS__);
  137. 137:         if ($name !== NULL{
  138. 138:             $tracker new HiddenField($name);
  139. 139:             $tracker->unmonitor(__CLASS__);
  140. 140:             $this[self::TRACKER_ID$tracker;
  141. 141:         }
  142. 142:         parent::__construct(NULL$name);
  143. 143:     }
  144. 144:  
  145. 145:  
  146. 146:  
  147. 147:     /**
  148. 148:      * This method will be called when the component (or component's parent)
  149. 149:      * becomes attached to a monitored object. Do not call this method yourself.
  150. 150:      * @param  IComponent 
  151. 151:      * @return void 
  152. 152:      */
  153. 153:     protected function attached($obj)
  154. 154:     {
  155. 155:         if ($obj instanceof self{
  156. 156:             throw new InvalidStateException('Nested forms are forbidden.');
  157. 157:         }
  158. 158:     }
  159. 159:  
  160. 160:  
  161. 161:  
  162. 162:     /**
  163. 163:      * Returns self.
  164. 164:      * @return Form 
  165. 165:      */
  166. 166:     final public function getForm($need TRUE)
  167. 167:     {
  168. 168:         return $this;
  169. 169:     }
  170. 170:  
  171. 171:  
  172. 172:  
  173. 173:     /**
  174. 174:      * Sets form's action.
  175. 175:      * @param  mixed URI
  176. 176:      * @return Form  provides a fluent interface
  177. 177:      */
  178. 178:     public function setAction($url)
  179. 179:     {
  180. 180:         $this->element->action $url;
  181. 181:         return $this;
  182. 182:     }
  183. 183:  
  184. 184:  
  185. 185:  
  186. 186:     /**
  187. 187:      * Returns form's action.
  188. 188:      * @return mixed URI
  189. 189:      */
  190. 190:     public function getAction()
  191. 191:     {
  192. 192:         return $this->element->action;
  193. 193:     }
  194. 194:  
  195. 195:  
  196. 196:  
  197. 197:     /**
  198. 198:      * Sets form's method.
  199. 199:      * @param  string get | post
  200. 200:      * @return Form  provides a fluent interface
  201. 201:      */
  202. 202:     public function setMethod($method)
  203. 203:     {
  204. 204:         if ($this->httpData !== NULL{
  205. 205:             throw new InvalidStateException(__METHOD__ . '() must be called until the form is empty.');
  206. 206:         }
  207. 207:         $this->element->method strtolower($method);
  208. 208:         return $this;
  209. 209:     }
  210. 210:  
  211. 211:  
  212. 212:  
  213. 213:     /**
  214. 214:      * Returns form's method.
  215. 215:      * @return string get | post
  216. 216:      */
  217. 217:     public function getMethod()
  218. 218:     {
  219. 219:         return $this->element->method;
  220. 220:     }
  221. 221:  
  222. 222:  
  223. 223:  
  224. 224:     /**
  225. 225:      * @deprecated
  226. 226:      */
  227. 227:     public function addTracker()
  228. 228:     {
  229. 229:         throw new DeprecatedException(__METHOD__ . '() is deprecated; pass form name to the constructor.');
  230. 230:     }
  231. 231:  
  232. 232:  
  233. 233:  
  234. 234:     /**
  235. 235:      * Cross-Site Request Forgery (CSRF) form protection.
  236. 236:      * @param  string 
  237. 237:      * @param  int 
  238. 238:      * @return void 
  239. 239:      */
  240. 240:     public function addProtection($message NULL$timeout NULL)
  241. 241:     {
  242. 242:         $session $this->getSession()->getNamespace('Nette.Forms.Form/CSRF');
  243. 243:         $key "key$timeout";
  244. 244:         if (isset($session->$key)) {
  245. 245:             $token $session->$key;
  246. 246:         else {
  247. 247:             $session->$key $token md5(uniqid(''TRUE));
  248. 248:         }
  249. 249:         $session->setExpiration($timeout$key);
  250. 250:         $this[self::PROTECTOR_IDnew HiddenField($token);
  251. 251:         $this[self::PROTECTOR_ID]->addRule(':equal'empty($message'Security token did not match. Possible CSRF attack.' $message$token);
  252. 252:     }
  253. 253:  
  254. 254:  
  255. 255:  
  256. 256:     /**
  257. 257:      * Adds fieldset group to the form.
  258. 258:      * @param  string  caption
  259. 259:      * @param  bool    set this group as current
  260. 260:      * @return FormGroup 
  261. 261:      */
  262. 262:     public function addGroup($caption NULL$setAsCurrent TRUE)
  263. 263:     {
  264. 264:         $group new FormGroup;
  265. 265:         $group->setOption('label'$caption);
  266. 266:         $group->setOption('visual'TRUE);
  267. 267:  
  268. 268:         if ($setAsCurrent{
  269. 269:             $this->setCurrentGroup($group);
  270. 270:         }
  271. 271:  
  272. 272:         if (isset($this->groups[$caption])) {
  273. 273:             return $this->groups[$group;
  274. 274:         else {
  275. 275:             return $this->groups[$caption$group;
  276. 276:         }
  277. 277:     }
  278. 278:  
  279. 279:  
  280. 280:  
  281. 281:     /**
  282. 282:      * Removes fieldset group from form.
  283. 283:      * @param  string|FormGroup
  284. 284:      * @return void 
  285. 285:      */
  286. 286:     public function removeGroup($name)
  287. 287:     {
  288. 288:         if (is_string($name&& isset($this->groups[$name])) {
  289. 289:             $group $this->groups[$name];
  290. 290:  
  291. 291:         elseif ($name instanceof FormGroup && in_array($name$this->groupsTRUE)) {
  292. 292:             $group $name;
  293. 293:             $name array_search($group$this->groupsTRUE);
  294. 294:  
  295. 295:         else {
  296. 296:             throw new InvalidArgumentException("Group not found in form '$this->name'");
  297. 297:         }
  298. 298:  
  299. 299:         foreach ($group->getControls(as $control{
  300. 300:             $this->removeComponent($control);
  301. 301:         }
  302. 302:  
  303. 303:         unset($this->groups[$name]);
  304. 304:     }
  305. 305:  
  306. 306:  
  307. 307:  
  308. 308:     /**
  309. 309:      * Returns all defined groups.
  310. 310:      * @return array of FormGroup
  311. 311:      */
  312. 312:     public function getGroups()
  313. 313:     {
  314. 314:         return $this->groups;
  315. 315:     }
  316. 316:  
  317. 317:  
  318. 318:  
  319. 319:     /**
  320. 320:      * Returns the specified group.
  321. 321:      * @param  string  name
  322. 322:      * @return FormGroup 
  323. 323:      */
  324. 324:     public function getGroup($name)
  325. 325:     {
  326. 326:         return isset($this->groups[$name]$this->groups[$nameNULL;
  327. 327:     }
  328. 328:  
  329. 329:  
  330. 330:  
  331. 331:     /**
  332. 332:      * Set the encoding for the values.
  333. 333:      * @param  string 
  334. 334:      * @return Form  provides a fluent interface
  335. 335:      */
  336. 336:     public function setEncoding($value)
  337. 337:     {
  338. 338:         $this->encoding empty($value'UTF-8' strtoupper($value);
  339. 339:         if ($this->encoding !== 'UTF-8' && !extension_loaded('mbstring')) {
  340. 340:             throw new Exception("The PHP extension 'mbstring' is required for this encoding but is not loaded.");
  341. 341:         }
  342. 342:         return $this;
  343. 343:     }
  344. 344:  
  345. 345:  
  346. 346:  
  347. 347:     /**
  348. 348:      * Returns the encoding.
  349. 349:      * @return string 
  350. 350:      */
  351. 351:     final public function getEncoding()
  352. 352:     {
  353. 353:         return $this->encoding;
  354. 354:     }
  355. 355:  
  356. 356:  
  357. 357:  
  358. 358:     /********************* translator ****************d*g**/
  359. 359:  
  360. 360:  
  361. 361:  
  362. 362:     /**
  363. 363:      * Sets translate adapter.
  364. 364:      * @param  ITranslator 
  365. 365:      * @return Form  provides a fluent interface
  366. 366:      */
  367. 367:     public function setTranslator(ITranslator $translator NULL)
  368. 368:     {
  369. 369:         $this->translator $translator;
  370. 370:         return $this;
  371. 371:     }
  372. 372:  
  373. 373:  
  374. 374:  
  375. 375:     /**
  376. 376:      * Returns translate adapter.
  377. 377:      * @return ITranslator|NULL
  378. 378:      */
  379. 379:     final public function getTranslator()
  380. 380:     {
  381. 381:         return $this->translator;
  382. 382:     }
  383. 383:  
  384. 384:  
  385. 385:  
  386. 386:     /********************* submission ****************d*g**/
  387. 387:  
  388. 388:  
  389. 389:  
  390. 390:     /**
  391. 391:      * Tells if the form is anchored.
  392. 392:      * @return bool 
  393. 393:      */
  394. 394:     public function isAnchored()
  395. 395:     {
  396. 396:         return TRUE;
  397. 397:     }
  398. 398:  
  399. 399:  
  400. 400:  
  401. 401:     /**
  402. 402:      * Tells if the form was submitted.
  403. 403:      * @return ISubmitterControl|FALSE submittor control
  404. 404:      */
  405. 405:     final public function isSubmitted()
  406. 406:     {
  407. 407:         if ($this->submittedBy === NULL{
  408. 408:             $this->getHttpData();
  409. 409:             $this->submittedBy !empty($this->httpData);
  410. 410:         }
  411. 411:         return $this->submittedBy;
  412. 412:     }
  413. 413:  
  414. 414:  
  415. 415:  
  416. 416:     /**
  417. 417:      * Sets the submittor control.
  418. 418:      * @param  ISubmitterControl 
  419. 419:      * @return Form  provides a fluent interface
  420. 420:      */
  421. 421:     public function setSubmittedBy(ISubmitterControl $by NULL)
  422. 422:     {
  423. 423:         $this->submittedBy $by === NULL FALSE $by;
  424. 424:         return $this;
  425. 425:     }
  426. 426:  
  427. 427:  
  428. 428:  
  429. 429:     /**
  430. 430:      * Returns submitted HTTP data.
  431. 431:      * @return array 
  432. 432:      */
  433. 433:     final public function getHttpData()
  434. 434:     {
  435. 435:         if ($this->httpData === NULL{
  436. 436:             if (!$this->isAnchored()) {
  437. 437:                 throw new InvalidStateException('Form is not anchored and therefore can not determine whether it was submitted.');
  438. 438:             }
  439. 439:             $this->httpData = (array) $this->receiveHttpData();
  440. 440:         }
  441. 441:         return $this->httpData;
  442. 442:     }
  443. 443:  
  444. 444:  
  445. 445:  
  446. 446:     /**
  447. 447:      * Fires submit/click events.
  448. 448:      * @return void 
  449. 449:      */
  450. 450:     public function fireEvents()
  451. 451:     {
  452. 452:         if (!$this->isSubmitted()) {
  453. 453:             return;
  454. 454:  
  455. 455:         elseif ($this->submittedBy instanceof ISubmitterControl{
  456. 456:             if (!$this->submittedBy->getValidationScope(|| $this->isValid()) {
  457. 457:                 $this->submittedBy->click();
  458. 458:                 $this->onSubmit($this);
  459. 459:             else {
  460. 460:                 $this->submittedBy->onInvalidClick($this->submittedBy);
  461. 461:                 $this->onInvalidSubmit($this);
  462. 462:             }
  463. 463:  
  464. 464:         elseif ($this->isValid()) {
  465. 465:             $this->onSubmit($this);
  466. 466:  
  467. 467:         else {
  468. 468:             $this->onInvalidSubmit($this);
  469. 469:         }
  470. 470:     }
  471. 471:  
  472. 472:  
  473. 473:  
  474. 474:     /**
  475. 475:      * Internal: receives submitted HTTP data.
  476. 476:      * @return array 
  477. 477:      */
  478. 478:     protected function receiveHttpData()
  479. 479:     {
  480. 480:         $httpRequest $this->getHttpRequest();
  481. 481:         if (strcasecmp($this->getMethod()$httpRequest->getMethod())) {
  482. 482:             return;
  483. 483:         }
  484. 484:  
  485. 485:         $httpRequest->setEncoding($this->encoding);
  486. 486:         if ($httpRequest->isMethod('post')) {
  487. 487:             $data ArrayTools::mergeTree($httpRequest->getPost()$httpRequest->getFiles());
  488. 488:         else {
  489. 489:             $data $httpRequest->getQuery();
  490. 490:         }
  491. 491:  
  492. 492:         if ($tracker $this->getComponent(self::TRACKER_IDFALSE)) {
  493. 493:             if (!isset($data[self::TRACKER_ID]|| $data[self::TRACKER_ID!== $tracker->getValue()) {
  494. 494:                 return;
  495. 495:             }
  496. 496:         }
  497. 497:  
  498. 498:         return $data;
  499. 499:     }
  500. 500:  
  501. 501:  
  502. 502:  
  503. 503:     /**
  504. 504:      * @deprecated
  505. 505:      */
  506. 506:     public function processHttpRequest()
  507. 507:     {
  508. 508:         $this->fireEvents();
  509. 509:     }
  510. 510:  
  511. 511:  
  512. 512:  
  513. 513:     /********************* data exchange ****************d*g**/
  514. 514:  
  515. 515:  
  516. 516:  
  517. 517:     /**
  518. 518:      * Returns the values submitted by the form.
  519. 519:      * @return array 
  520. 520:      */
  521. 521:     public function getValues()
  522. 522:     {
  523. 523:         $values parent::getValues();
  524. 524:         unset($values[self::TRACKER_ID]$values[self::PROTECTOR_ID]);
  525. 525:         return $values;
  526. 526:     }
  527. 527:  
  528. 528:  
  529. 529:  
  530. 530:     /********************* validation ****************d*g**/
  531. 531:  
  532. 532:  
  533. 533:  
  534. 534:     /**
  535. 535:      * Adds error message to the list.
  536. 536:      * @param  string  error message
  537. 537:      * @return void 
  538. 538:      */
  539. 539:     public function addError($message)
  540. 540:     {
  541. 541:         if (!in_array($message$this->errorsTRUE)) {
  542. 542:             $this->errors[$message;
  543. 543:             $this->valid = FALSE;
  544. 544:         }
  545. 545:     }
  546. 546:  
  547. 547:  
  548. 548:  
  549. 549:     /**
  550. 550:      * Returns validation errors.
  551. 551:      * @return array 
  552. 552:      */
  553. 553:     public function getErrors()
  554. 554:     {
  555. 555:         return $this->errors;
  556. 556:     }
  557. 557:  
  558. 558:  
  559. 559:  
  560. 560:     /**
  561. 561:      * @return bool 
  562. 562:      */
  563. 563:     public function hasErrors()
  564. 564:     {
  565. 565:         return (bool) $this->getErrors();
  566. 566:     }
  567. 567:  
  568. 568:  
  569. 569:  
  570. 570:     /**
  571. 571:      * @return void 
  572. 572:      */
  573. 573:     public function cleanErrors()
  574. 574:     {
  575. 575:         $this->errors array();
  576. 576:         $this->valid = NULL;
  577. 577:     }
  578. 578:  
  579. 579:  
  580. 580:  
  581. 581:     /********************* rendering ****************d*g**/
  582. 582:  
  583. 583:  
  584. 584:  
  585. 585:     /**
  586. 586:      * Returns form's HTML element template.
  587. 587:      * @return Html 
  588. 588:      */
  589. 589:     public function getElementPrototype()
  590. 590:     {
  591. 591:         return $this->element;
  592. 592:     }
  593. 593:  
  594. 594:  
  595. 595:  
  596. 596:     /**
  597. 597:      * Sets form renderer.
  598. 598:      * @param  IFormRenderer 
  599. 599:      * @return Form  provides a fluent interface
  600. 600:      */
  601. 601:     public function setRenderer(IFormRenderer $renderer)
  602. 602:     {
  603. 603:         $this->renderer $renderer;
  604. 604:         return $this;
  605. 605:     }
  606. 606:  
  607. 607:  
  608. 608:  
  609. 609:     /**
  610. 610:      * Returns form renderer.
  611. 611:      * @return IFormRenderer|NULL
  612. 612:      */
  613. 613:     final public function getRenderer()
  614. 614:     {
  615. 615:         if ($this->renderer === NULL{
  616. 616:             $this->renderer new ConventionalRenderer;
  617. 617:         }
  618. 618:         return $this->renderer;
  619. 619:     }
  620. 620:  
  621. 621:  
  622. 622:  
  623. 623:     /**
  624. 624:      * Renders form.
  625. 625:      * @return void 
  626. 626:      */
  627. 627:     public function render()
  628. 628:     {
  629. 629:         $args func_get_args();
  630. 630:         array_unshift($args$this);
  631. 631:         $s call_user_func_array(array($this->getRenderer()'render')$args);
  632. 632:  
  633. 633:         if (strcmp($this->encoding'UTF-8')) {
  634. 634:             echo mb_convert_encoding($s'HTML-ENTITIES''UTF-8');
  635. 635:         else {
  636. 636:             echo $s;
  637. 637:         }
  638. 638:     }
  639. 639:  
  640. 640:  
  641. 641:  
  642. 642:     /**
  643. 643:      * Renders form to string.
  644. 644:      * @return bool  can throw exceptions? (hidden parameter)
  645. 645:      * @return string 
  646. 646:      */
  647. 647:     public function __toString()
  648. 648:     {
  649. 649:         try {
  650. 650:             if (strcmp($this->encoding'UTF-8')) {
  651. 651:                 return mb_convert_encoding($this->getRenderer()->render($this)'HTML-ENTITIES''UTF-8');
  652. 652:             else {
  653. 653:                 return $this->getRenderer()->render($this);
  654. 654:             }
  655. 655:  
  656. 656:         catch (Exception $e{
  657. 657:             if (func_get_args(&& func_get_arg(0)) {
  658. 658:                 throw $e;
  659. 659:             else {
  660. 660:                 trigger_error($e->getMessage()E_USER_WARNING);
  661. 661:                 return '';
  662. 662:             }
  663. 663:         }
  664. 664:     }
  665. 665:  
  666. 666:  
  667. 667:  
  668. 668:     /********************* backend ****************d*g**/
  669. 669:  
  670. 670:  
  671. 671:  
  672. 672:     /**
  673. 673:      * @return IHttpRequest 
  674. 674:      */
  675. 675:     protected function getHttpRequest()
  676. 676:     {
  677. 677:         return class_exists('Environment'Environment::getHttpRequest(new HttpRequest;
  678. 678:     }
  679. 679:  
  680. 680:  
  681. 681:  
  682. 682:     /**
  683. 683:      * @return Session 
  684. 684:      */
  685. 685:     protected function getSession()
  686. 686:     {
  687. 687:         return Environment::getSession();
  688. 688:     }
  689. 689: