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