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->element->id 'frm-' $name;
  125. 125:  
  126. 126:         $this->monitor(__CLASS__);
  127. 127:         if ($name !== NULL{
  128. 128:             $tracker new HiddenField($name);
  129. 129:             $tracker->unmonitor(__CLASS__);
  130. 130:             $this[self::TRACKER_ID$tracker;
  131. 131:         }
  132. 132:         parent::__construct(NULL$name);
  133. 133:     }
  134. 134:  
  135. 135:  
  136. 136:  
  137. 137:     /**
  138. 138:      * This method will be called when the component (or component's parent)
  139. 139:      * becomes attached to a monitored object. Do not call this method yourself.
  140. 140:      * @param  IComponent 
  141. 141:      * @return void 
  142. 142:      */
  143. 143:     protected function attached($obj)
  144. 144:     {
  145. 145:         if ($obj instanceof self{
  146. 146:             throw new InvalidStateException('Nested forms are forbidden.');
  147. 147:         }
  148. 148:     }
  149. 149:  
  150. 150:  
  151. 151:  
  152. 152:     /**
  153. 153:      * Returns self.
  154. 154:      * @return Form 
  155. 155:      */
  156. 156:     final public function getForm($need TRUE)
  157. 157:     {
  158. 158:         return $this;
  159. 159:     }
  160. 160:  
  161. 161:  
  162. 162:  
  163. 163:     /**
  164. 164:      * Sets form's action.
  165. 165:      * @param  mixed URI
  166. 166:      * @return Form  provides a fluent interface
  167. 167:      */
  168. 168:     public function setAction($url)
  169. 169:     {
  170. 170:         $this->element->action $url;
  171. 171:         return $this;
  172. 172:     }
  173. 173:  
  174. 174:  
  175. 175:  
  176. 176:     /**
  177. 177:      * Returns form's action.
  178. 178:      * @return mixed URI
  179. 179:      */
  180. 180:     public function getAction()
  181. 181:     {
  182. 182:         return $this->element->action;
  183. 183:     }
  184. 184:  
  185. 185:  
  186. 186:  
  187. 187:     /**
  188. 188:      * Sets form's method.
  189. 189:      * @param  string get | post
  190. 190:      * @return Form  provides a fluent interface
  191. 191:      */
  192. 192:     public function setMethod($method)
  193. 193:     {
  194. 194:         if ($this->httpData !== NULL{
  195. 195:             throw new InvalidStateException(__METHOD__ . '() must be called until the form is empty.');
  196. 196:         }
  197. 197:         $this->element->method strtolower($method);
  198. 198:         return $this;
  199. 199:     }
  200. 200:  
  201. 201:  
  202. 202:  
  203. 203:     /**
  204. 204:      * Returns form's method.
  205. 205:      * @return string get | post
  206. 206:      */
  207. 207:     public function getMethod()
  208. 208:     {
  209. 209:         return $this->element->method;
  210. 210:     }
  211. 211:  
  212. 212:  
  213. 213:  
  214. 214:     /**
  215. 215:      * @deprecated
  216. 216:      */
  217. 217:     public function addTracker()
  218. 218:     {
  219. 219:         throw new DeprecatedException(__METHOD__ . '() is deprecated; pass form name to the constructor.');
  220. 220:     }
  221. 221:  
  222. 222:  
  223. 223:  
  224. 224:     /**
  225. 225:      * Cross-Site Request Forgery (CSRF) form protection.
  226. 226:      * @param  string 
  227. 227:      * @param  int 
  228. 228:      * @return void 
  229. 229:      */
  230. 230:     public function addProtection($message NULL$timeout NULL)
  231. 231:     {
  232. 232:         $session $this->getSession()->getNamespace('Nette.Forms.Form/CSRF');
  233. 233:         $key "key$timeout";
  234. 234:         if (isset($session->$key)) {
  235. 235:             $token $session->$key;
  236. 236:         else {
  237. 237:             $session->$key $token md5(uniqid(''TRUE));
  238. 238:         }
  239. 239:         $session->setExpiration($timeout$key);
  240. 240:         $this[self::PROTECTOR_IDnew HiddenField($token);
  241. 241:         $this[self::PROTECTOR_ID]->addRule(':equal'empty($message'Security token did not match. Possible CSRF attack.' $message$token);
  242. 242:     }
  243. 243:  
  244. 244:  
  245. 245:  
  246. 246:     /**
  247. 247:      * Adds fieldset group to the form.
  248. 248:      * @param  string  caption
  249. 249:      * @param  bool    set this group as current
  250. 250:      * @return FormGroup 
  251. 251:      */
  252. 252:     public function addGroup($caption NULL$setAsCurrent TRUE)
  253. 253:     {
  254. 254:         $group new FormGroup;
  255. 255:         $group->setOption('label'$caption);
  256. 256:         $group->setOption('visual'TRUE);
  257. 257:  
  258. 258:         if ($setAsCurrent{
  259. 259:             $this->setCurrentGroup($group);
  260. 260:         }
  261. 261:  
  262. 262:         if (isset($this->groups[$caption])) {
  263. 263:             return $this->groups[$group;
  264. 264:         else {
  265. 265:             return $this->groups[$caption$group;
  266. 266:         }
  267. 267:     }
  268. 268:  
  269. 269:  
  270. 270:  
  271. 271:     /**
  272. 272:      * Removes fieldset group from form.
  273. 273:      * @param  string|FormGroup
  274. 274:      * @return void 
  275. 275:      */
  276. 276:     public function removeGroup($name)
  277. 277:     {
  278. 278:         if (is_string($name&& isset($this->groups[$name])) {
  279. 279:             $group $this->groups[$name];
  280. 280:  
  281. 281:         elseif ($name instanceof FormGroup && in_array($name$this->groupsTRUE)) {
  282. 282:             $group $name;
  283. 283:             $name array_search($group$this->groupsTRUE);
  284. 284:  
  285. 285:         else {
  286. 286:             throw new InvalidArgumentException("Group not found in form '$this->name'");
  287. 287:         }
  288. 288:  
  289. 289:         foreach ($group->getControls(as $control{
  290. 290:             $this->removeComponent($control);
  291. 291:         }
  292. 292:  
  293. 293:         unset($this->groups[$name]);
  294. 294:     }
  295. 295:  
  296. 296:  
  297. 297:  
  298. 298:     /**
  299. 299:      * Returns all defined groups.
  300. 300:      * @return array of FormGroup
  301. 301:      */
  302. 302:     public function getGroups()
  303. 303:     {
  304. 304:         return $this->groups;
  305. 305:     }
  306. 306:  
  307. 307:  
  308. 308:  
  309. 309:     /**
  310. 310:      * Returns the specified group.
  311. 311:      * @param  string  name
  312. 312:      * @return FormGroup 
  313. 313:      */
  314. 314:     public function getGroup($name)
  315. 315:     {
  316. 316:         return isset($this->groups[$name]$this->groups[$nameNULL;
  317. 317:     }
  318. 318:  
  319. 319:  
  320. 320:  
  321. 321:     /**
  322. 322:      * Set the encoding for the values.
  323. 323:      * @param  string 
  324. 324:      * @return Form  provides a fluent interface
  325. 325:      */
  326. 326:     public function setEncoding($value)
  327. 327:     {
  328. 328:         $this->encoding empty($value'UTF-8' strtoupper($value);
  329. 329:         if ($this->encoding !== 'UTF-8' && !extension_loaded('mbstring')) {
  330. 330:             throw new Exception("The PHP extension 'mbstring' is required for this encoding but is not loaded.");
  331. 331:         }
  332. 332:         return $this;
  333. 333:     }
  334. 334:  
  335. 335:  
  336. 336:  
  337. 337:     /**
  338. 338:      * Returns the encoding.
  339. 339:      * @return string 
  340. 340:      */
  341. 341:     final public function getEncoding()
  342. 342:     {
  343. 343:         return $this->encoding;
  344. 344:     }
  345. 345:  
  346. 346:  
  347. 347:  
  348. 348:     /********************* translator ****************d*g**/
  349. 349:  
  350. 350:  
  351. 351:  
  352. 352:     /**
  353. 353:      * Sets translate adapter.
  354. 354:      * @param  ITranslator 
  355. 355:      * @return Form  provides a fluent interface
  356. 356:      */
  357. 357:     public function setTranslator(ITranslator $translator NULL)
  358. 358:     {
  359. 359:         $this->translator $translator;
  360. 360:         return $this;
  361. 361:     }
  362. 362:  
  363. 363:  
  364. 364:  
  365. 365:     /**
  366. 366:      * Returns translate adapter.
  367. 367:      * @return ITranslator|NULL
  368. 368:      */
  369. 369:     final public function getTranslator()
  370. 370:     {
  371. 371:         return $this->translator;
  372. 372:     }
  373. 373:  
  374. 374:  
  375. 375:  
  376. 376:     /********************* submission ****************d*g**/
  377. 377:  
  378. 378:  
  379. 379:  
  380. 380:     /**
  381. 381:      * Tells if the form is anchored.
  382. 382:      * @return bool 
  383. 383:      */
  384. 384:     public function isAnchored()
  385. 385:     {
  386. 386:         return TRUE;
  387. 387:     }
  388. 388:  
  389. 389:  
  390. 390:  
  391. 391:     /**
  392. 392:      * Tells if the form was submitted.
  393. 393:      * @return ISubmitterControl|FALSE submittor control
  394. 394:      */
  395. 395:     final public function isSubmitted()
  396. 396:     {
  397. 397:         if ($this->submittedBy === NULL{
  398. 398:             $this->getHttpData();
  399. 399:             $this->submittedBy !empty($this->httpData);
  400. 400:         }
  401. 401:         return $this->submittedBy;
  402. 402:     }
  403. 403:  
  404. 404:  
  405. 405:  
  406. 406:     /**
  407. 407:      * Sets the submittor control.
  408. 408:      * @param  ISubmitterControl 
  409. 409:      * @return Form  provides a fluent interface
  410. 410:      */
  411. 411:     public function setSubmittedBy(ISubmitterControl $by NULL)
  412. 412:     {
  413. 413:         $this->submittedBy $by === NULL FALSE $by;
  414. 414:         return $this;
  415. 415:     }
  416. 416:  
  417. 417:  
  418. 418:  
  419. 419:     /**
  420. 420:      * Returns submitted HTTP data.
  421. 421:      * @return array 
  422. 422:      */
  423. 423:     final public function getHttpData()
  424. 424:     {
  425. 425:         if ($this->httpData === NULL{
  426. 426:             if (!$this->isAnchored()) {
  427. 427:                 throw new InvalidStateException('Form is not anchored and therefore can not determine whether it was submitted.');
  428. 428:             }
  429. 429:             $this->httpData = (array) $this->receiveHttpData();
  430. 430:         }
  431. 431:         return $this->httpData;
  432. 432:     }
  433. 433:  
  434. 434:  
  435. 435:  
  436. 436:     /**
  437. 437:      * Fires submit/click events.
  438. 438:      * @return void 
  439. 439:      */
  440. 440:     public function fireEvents()
  441. 441:     {
  442. 442:         if (!$this->isSubmitted()) {
  443. 443:             return;
  444. 444:  
  445. 445:         elseif ($this->submittedBy instanceof ISubmitterControl{
  446. 446:             if (!$this->submittedBy->getValidationScope(|| $this->isValid()) {
  447. 447:                 $this->submittedBy->click();
  448. 448:                 $this->onSubmit($this);
  449. 449:             else {
  450. 450:                 $this->submittedBy->onInvalidClick($this->submittedBy);
  451. 451:                 $this->onInvalidSubmit($this);
  452. 452:             }
  453. 453:  
  454. 454:         elseif ($this->isValid()) {
  455. 455:             $this->onSubmit($this);
  456. 456:  
  457. 457:         else {
  458. 458:             $this->onInvalidSubmit($this);
  459. 459:         }
  460. 460:     }
  461. 461:  
  462. 462:  
  463. 463:  
  464. 464:     /**
  465. 465:      * Internal: receives submitted HTTP data.
  466. 466:      * @return array 
  467. 467:      */
  468. 468:     protected function receiveHttpData()
  469. 469:     {
  470. 470:         $httpRequest $this->getHttpRequest();
  471. 471:         if (strcasecmp($this->getMethod()$httpRequest->getMethod())) {
  472. 472:             return;
  473. 473:         }
  474. 474:  
  475. 475:         $httpRequest->setEncoding($this->encoding);
  476. 476:         if ($httpRequest->isMethod('post')) {
  477. 477:             $data ArrayTools::mergeTree($httpRequest->getPost()$httpRequest->getFiles());
  478. 478:         else {
  479. 479:             $data $httpRequest->getQuery();
  480. 480:         }
  481. 481:  
  482. 482:         if ($tracker $this->getComponent(self::TRACKER_IDFALSE)) {
  483. 483:             if (!isset($data[self::TRACKER_ID]|| $data[self::TRACKER_ID!== $tracker->getValue()) {
  484. 484:                 return;
  485. 485:             }
  486. 486:         }
  487. 487:  
  488. 488:         return $data;
  489. 489:     }
  490. 490:  
  491. 491:  
  492. 492:  
  493. 493:     /**
  494. 494:      * @deprecated
  495. 495:      */
  496. 496:     public function processHttpRequest()
  497. 497:     {
  498. 498:         trigger_error(__METHOD__ . '() is deprecated; use fireEvents() instead.'E_USER_WARNING);
  499. 499:         $this->fireEvents();
  500. 500:     }
  501. 501:  
  502. 502:  
  503. 503:  
  504. 504:     /********************* data exchange ****************d*g**/
  505. 505:  
  506. 506:  
  507. 507:  
  508. 508:     /**
  509. 509:      * Returns the values submitted by the form.
  510. 510:      * @return array 
  511. 511:      */
  512. 512:     public function getValues()
  513. 513:     {
  514. 514:         $values parent::getValues();
  515. 515:         unset($values[self::TRACKER_ID]$values[self::PROTECTOR_ID]);
  516. 516:         return $values;
  517. 517:     }
  518. 518:  
  519. 519:  
  520. 520:  
  521. 521:     /********************* validation ****************d*g**/
  522. 522:  
  523. 523:  
  524. 524:  
  525. 525:     /**
  526. 526:      * Adds error message to the list.
  527. 527:      * @param  string  error message
  528. 528:      * @return void 
  529. 529:      */
  530. 530:     public function addError($message)
  531. 531:     {
  532. 532:         $this->valid = FALSE;
  533. 533:         if ($message !== NULL && !in_array($message$this->errorsTRUE)) {
  534. 534:             $this->errors[$message;
  535. 535:         }
  536. 536:     }
  537. 537:  
  538. 538:  
  539. 539:  
  540. 540:     /**
  541. 541:      * Returns validation errors.
  542. 542:      * @return array 
  543. 543:      */
  544. 544:     public function getErrors()
  545. 545:     {
  546. 546:         return $this->errors;
  547. 547:     }
  548. 548:  
  549. 549:  
  550. 550:  
  551. 551:     /**
  552. 552:      * @return bool 
  553. 553:      */
  554. 554:     public function hasErrors()
  555. 555:     {
  556. 556:         return (bool) $this->getErrors();
  557. 557:     }
  558. 558:  
  559. 559:  
  560. 560:  
  561. 561:     /**
  562. 562:      * @return void 
  563. 563:      */
  564. 564:     public function cleanErrors()
  565. 565:     {
  566. 566:         $this->errors array();
  567. 567:         $this->valid = NULL;
  568. 568:     }
  569. 569:  
  570. 570:  
  571. 571:  
  572. 572:     /********************* rendering ****************d*g**/
  573. 573:  
  574. 574:  
  575. 575:  
  576. 576:     /**
  577. 577:      * Returns form's HTML element template.
  578. 578:      * @return Html 
  579. 579:      */
  580. 580:     public function getElementPrototype()
  581. 581:     {
  582. 582:         return $this->element;
  583. 583:     }
  584. 584:  
  585. 585:  
  586. 586:  
  587. 587:     /**
  588. 588:      * Sets form renderer.
  589. 589:      * @param  IFormRenderer 
  590. 590:      * @return Form  provides a fluent interface
  591. 591:      */
  592. 592:     public function setRenderer(IFormRenderer $renderer)
  593. 593:     {
  594. 594:         $this->renderer $renderer;
  595. 595:         return $this;
  596. 596:     }
  597. 597:  
  598. 598:  
  599. 599:  
  600. 600:     /**
  601. 601:      * Returns form renderer.
  602. 602:      * @return IFormRenderer|NULL
  603. 603:      */
  604. 604:     final public function getRenderer()
  605. 605:     {
  606. 606:         if ($this->renderer === NULL{
  607. 607:             $this->renderer new ConventionalRenderer;
  608. 608:         }
  609. 609:         return $this->renderer;
  610. 610:     }
  611. 611:  
  612. 612:  
  613. 613:  
  614. 614:     /**
  615. 615:      * Renders form.
  616. 616:      * @return void 
  617. 617:      */
  618. 618:     public function render()
  619. 619:     {
  620. 620:         $args func_get_args();
  621. 621:         array_unshift($args$this);
  622. 622:         $s call_user_func_array(array($this->getRenderer()'render')$args);
  623. 623:  
  624. 624:         if (strcmp($this->encoding'UTF-8')) {
  625. 625:             echo mb_convert_encoding($s'HTML-ENTITIES''UTF-8');
  626. 626:         else {
  627. 627:             echo $s;
  628. 628:         }
  629. 629:     }
  630. 630:  
  631. 631:  
  632. 632:  
  633. 633:     /**
  634. 634:      * Renders form to string.
  635. 635:      * @return bool  can throw exceptions? (hidden parameter)
  636. 636:      * @return string 
  637. 637:      */
  638. 638:     public function __toString()
  639. 639:     {
  640. 640:         try {
  641. 641:             if (strcmp($this->encoding'UTF-8')) {
  642. 642:                 return mb_convert_encoding($this->getRenderer()->render($this)'HTML-ENTITIES''UTF-8');
  643. 643:             else {
  644. 644:                 return $this->getRenderer()->render($this);
  645. 645:             }
  646. 646:  
  647. 647:         catch (Exception $e{
  648. 648:             if (func_get_args(&& func_get_arg(0)) {
  649. 649:                 throw $e;
  650. 650:             else {
  651. 651:                 Debug::toStringException($e);
  652. 652:             }
  653. 653:         }
  654. 654:     }
  655. 655:  
  656. 656:  
  657. 657:  
  658. 658:     /********************* backend ****************d*g**/
  659. 659:  
  660. 660:  
  661. 661:  
  662. 662:     /**
  663. 663:      * @return IHttpRequest 
  664. 664:      */
  665. 665:     protected function getHttpRequest()
  666. 666:     {
  667. 667:         return class_exists('Environment'Environment::getHttpRequest(new HttpRequest;
  668. 668:     }
  669. 669:  
  670. 670:  
  671. 671:  
  672. 672:     /**
  673. 673:      * @return Session 
  674. 674:      */
  675. 675:     protected function getSession()
  676. 676:     {
  677. 677:         return Environment::getSession();
  678. 678:     }
  679. 679: