/phocoa/framework/WFPage.php

https://github.com/SwissalpS/phocoa · PHP · 1793 lines · 1049 code · 140 blank · 604 comment · 181 complexity · dfa8dc111617f2149b8796e5e959101e MD5 · raw file

Large files are truncated click here to view the full file

  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4: */
  3. /**
  4. * The WFPage object.
  5. *
  6. * Each request creates a module/page to handle the request. This struct uses exactly 2 pages, a requestPage and a responsePage. The requestPage respesents the UI state of the submitted form, if any, and the responsePage represents the UI state of the page that will be displayed in response to the request. The client responds to the request/action by reading from the requestPage and taking appropriate actions (ie saving data, etc). The client then selects a responsePage and sets up the UI elements as desired. The rendered responsePage is what the user will see.
  7. *
  8. * Clients get access to the instances via {@link outlet} and get/set values as appropriate.
  9. *
  10. * @copyright Copyright (c) 2002 Alan Pinstein. All Rights Reserved.
  11. * @version $Id: smarty_showcase.php,v 1.3 2005/02/01 01:24:37 alanpinstein Exp $
  12. * @author Alan Pinstein <apinstein@mac.com>
  13. * @package UI
  14. * @subpackage PageController
  15. * @todo Some more refactoring... it's odd that the class has to figure out if it's the requestPage or responsePage. I think instead they should be 2 classes.
  16. * The base class, WFPage, should be the response page, and the WFRequestPage subclass should add methods / functionality for restoring state and triggering
  17. * actions, as I think that's the only two things it does more than the responsePage. ** What about errors?**
  18. */
  19. /**
  20. * Informal Protocol declaration for WFPage delegates.
  21. *
  22. * Function in this informal protocol are used to respond to different points in the page life cycle.
  23. *
  24. * Common activities include setting up dynamic widgets, responding to actions, etc.
  25. */
  26. interface WFPageDelegate
  27. {
  28. // delegate functions documented in calling order during page life cycle
  29. /**
  30. * Called when the page instances have been loaded and configured.
  31. *
  32. * You can be certain at this point that all instances in the .yaml files have been loaded and connected.
  33. *
  34. * Of course, dynamically created instances may not exist yet.
  35. *
  36. * @param object WFPage The page.
  37. */
  38. function pageInstancesDidLoad($page);
  39. /**
  40. * Get the list of named parameters for the page.
  41. *
  42. * NOTE: You can also pass an associative array, there are two forms of this extended option:
  43. * array(
  44. * 'param1' => 'defaultValueForParam1'
  45. * 'param2', // default will be NULL
  46. * 'param3' // default will be NULL
  47. * )
  48. * array(
  49. * 'param1' => array(
  50. * 'default' => 'defaultValueForParam1',
  51. * 'greedy' => true // makes this param include the remaining path_info from this parameter on
  52. * // ie /module/page/foo/bar/baz => param1 = foo/bar/baz with greedy=true
  53. * )
  54. * )
  55. * @return array An array of names of parameters, in positional order.
  56. */
  57. function parameterList();
  58. /**
  59. * Called when the page has finished loading.
  60. *
  61. * State is not guaranteed to be totally restored.
  62. *
  63. * The most common use for this callback is to load data objects with which the UI elements will be bound.
  64. *
  65. * NOTE: This is the modern version of _PageDidLoad()
  66. *
  67. * @param object WFPage The page.
  68. * @param array An array of parameters, with their values passed from the client.
  69. */
  70. function parametersDidLoad($page, $params);
  71. /**
  72. * Called just before the batched binding updates are pushed from the UI state back on to the model objects.
  73. *
  74. * Remember, in PHOCOA, we are approximating a stateful environment on top of a stateless one.
  75. * Thus unlike in Cocoa, we have to "batch" apply the changes made via the client. In Cocoa, all bindings are done one-at-a-time because the model is stateful
  76. * and there is no penalty for dealing with one change at a time. On the web, to deal with each change at a time would REQUIRE a "doPostback" kind of mentality
  77. * on every UI click, which leads to very painful applications for users.
  78. *
  79. * NOTE: only gets called for the request page, since if you are the response page,
  80. * there is no client state in existence to which might require application of changes made with bindings.
  81. *
  82. * @param object WFPage The page.
  83. * @param array An array of parameters, with their values passed from the client.
  84. */
  85. function willPushBindings($page, $params);
  86. /**
  87. * Called by PHOCOA when an "action" (form submission) has taken place on the page.
  88. *
  89. * If the action name is "search" then the delegate method is searchAction().
  90. *
  91. * NOTE: This is the modern version of <pageName>_<actionName>_Action()
  92. *
  93. * @param object WFPage The page.
  94. * @param array An array of parameters, with their values passed from the client.
  95. */
  96. function doAction($page, $params);
  97. /**
  98. * Called by PHOCOA when NO action is run for the page.
  99. *
  100. * This is used to set up data default data that is needed should no action be taken. For instance, exeucting a default search query if no SEARCH field and "Search" action was run.
  101. * This is common when loading a page for the first time (thus there is no way an action could have been run).
  102. * Note that this is only run if no action is *specified*. If you want to know if a specified action wasn't run due to invalid data, see {@link WFPageDelegate::willNotRunAction}.
  103. *
  104. * @param object WFPage The page.
  105. * @param array An array of parameters, with their values passed from the client.
  106. */
  107. function noAction($page, $params);
  108. /**
  109. * Called by PHOCOA when an action is specified, but automatied validation failed (ie during propagation of form values via bindings)
  110. *
  111. * If your controller needs to know when an action was invoke by the client but no executed due to invalid data, this is how you find out!
  112. *
  113. * @param object WFPage The page.
  114. * @param array An array of parameters, with their values passed from the client.
  115. */
  116. function willNotRunAction($page, $params);
  117. /**
  118. * Called just befored rendering, but after the skin has been initalized.
  119. *
  120. * This is a good callback to use to add head strings, meta tags, set the HTML title, set the skin to use, etc.
  121. *
  122. * NOTE: This is the modern version of _SetupSkin()
  123. *
  124. * @param object WFPage The page.
  125. * @param array An array of parameters, with their values passed from the client.
  126. * @param object WFSkin The skin.
  127. */
  128. function setupSkin($page, $parameters, $skin);
  129. /**
  130. * Called by PHOCOA just before the page is rendered.
  131. *
  132. * NOTE: Not sure what this would ever be useful for... but I am putting it in here. Please let the PHOCOA communitiy know if you're using this.
  133. * NOTE: This is called AFTER pullBindings() although no one should have to worry about this fact...
  134. *
  135. * UNTESTED!
  136. *
  137. * @param object WFPage The page.
  138. * @param array An array of parameters, with their values passed from the client.
  139. */
  140. function willRenderPage($page, $parameters);
  141. /**
  142. * Called by PHOCOA just before after page is rendered.
  143. *
  144. * This callback can be used to munge the final output of the page rendering before it is returned to the caller.
  145. *
  146. * UNTESTED!
  147. *
  148. * @param object WFPage The page.
  149. * @param array An array of parameters, with their values passed from the client.
  150. * @param string The rendered output. PASSED BY REFERENCE.
  151. */
  152. function didRenderPage($page, $parameters, &$output);
  153. }
  154. /**
  155. * The WFPage encapsulates the UI and Controller Layer state of a page.
  156. *
  157. * The Page infrastructure initializes pages by instantiating all WFView instances (including widgets) in a page (from the .instances file),
  158. * loads all configs for those instances (from the .config file), and also can render the page to HTML using a WFPageRendering-compatible
  159. * template instance.
  160. *
  161. * The page manages the WFView instances with a Mediator pattern.
  162. *
  163. * The page is responsible for helping the widgets restore their state from a request.
  164. *
  165. * SEE COMPOSITE PATTERN IN GoF for ideas about the widget hierarchy.
  166. *
  167. * WFPage automatically adds a few useful variables to your template:
  168. * - __page The current {@link WFPage} being rendered.
  169. * - __module The {@link WFModule} that the page belongs to.
  170. * - __skin The {@link WFSkin} being used to wrap the page. MAY BE NULL! When a page is not the "root" module, it may not be wrapped in a skin, so be careful when using this.
  171. */
  172. class WFPage extends WFObject
  173. {
  174. protected $module; // the module that contains this WFPage instance
  175. protected $pageName; // the name of the "page" (ie UI bundle - needs to be placed in the forms so the requestPage can load the UI instances)
  176. protected $template; // and object conforming to interface WFPageRendering
  177. protected $instances; // assoc array of all instances, 'id' => instance object
  178. protected $parameters; // finalized calculated parameters in effect for the page
  179. protected $errors; // all validation errors for the current page; errors are managed in real-time. Any errors added to widgets of this page
  180. // are automatically added to our page errors list.
  181. protected $delegate; // an object implementing some of WFPageDelegate. OPTIONAL.
  182. protected $ignoreErrors;// whether or not the page should ignore errors that were generated during the page life cycle
  183. function __construct(WFModule $module)
  184. {
  185. parent::__construct();
  186. $this->module = $module;
  187. $this->pageName = NULL;
  188. $this->template = NULL;
  189. $this->instances = array();
  190. $this->errors = array();
  191. $this->parameters = array();
  192. $this->delegate = NULL;
  193. $this->ignoreErrors = false;
  194. WFLog::log("instantiating a page", WFLog::TRACE_LOG, PEAR_LOG_DEBUG);
  195. }
  196. public function destroy($vars = array())
  197. {
  198. parent::destroy(array('module', 'template', 'delegate', 'instances'));
  199. }
  200. public function setIgnoreErrors($bIgnoreErrors)
  201. {
  202. $this->ignoreErrors = $bIgnoreErrors;
  203. }
  204. public function ignoreErrors()
  205. {
  206. return $this->ignoreErrors;
  207. }
  208. /**
  209. * Set the WFPageDelegate to use for this page.
  210. *
  211. * @param object An object implementing some of the WFPageDelegate methods.
  212. * @throws object WFException If the parameter is not an object.
  213. */
  214. function setDelegate($d)
  215. {
  216. if (!is_object($d)) throw( new WFException("Page delegate must be an object!") );
  217. $this->delegate = $d;
  218. }
  219. /**
  220. * Get the WFPageDelegate for this page.
  221. *
  222. * @return object An object implementing some of the WFPageDelegate methods.
  223. */
  224. function delegate()
  225. {
  226. return $this->delegate;
  227. }
  228. /**
  229. * Get the module that the page is a part of.
  230. * @return object A WFModule object.
  231. */
  232. function module()
  233. {
  234. return $this->module;
  235. }
  236. /**
  237. * Get the parameters for the page. These are the parsed parameters of the URL, coalesced with form elements of the same name.
  238. *
  239. * NOTE: This data isn't available until after initPage() has executed.
  240. *
  241. * @return assoc_array Array of parameters in format 'parameterID' => 'parameterValue'
  242. * @todo refactor initPage to move the code from there to here so that it's available earlier in the life cycle.
  243. */
  244. function parameters()
  245. {
  246. return $this->parameters;
  247. }
  248. /**
  249. * Get a named parameter.
  250. *
  251. * @param string The name of the desired parameter.
  252. * @return mixed The value of the desired parameter.
  253. * @throws object WFException If there is no parameter of the passed name.
  254. */
  255. function parameter($name)
  256. {
  257. if (!array_key_exists($name, $this->parameters)) throw( new WFException("Parameter '{$name}' does not exist.") ); // must use array_key_exists b/c we want to legitimately return null.
  258. return $this->parameters[$name];
  259. }
  260. /**
  261. * Get the name of the "page" for the current WFPage instance. The "page" is our equivalent of a nib file, essentially.
  262. * @return string The page name for this instance.
  263. */
  264. function pageName()
  265. {
  266. $this->assertPageInited();
  267. return $this->pageName;
  268. }
  269. /**
  270. * Determine the name of the submitted form, if there is a submitted form for the current module.
  271. *
  272. * This function takes into account the module invocation's respondsToForms setting...
  273. *
  274. * @todo Should this be in WFRequestController?
  275. * @return string The name of the submitted form, if one was submitted. NULL if no form was submitted.
  276. */
  277. function submittedFormName()
  278. {
  279. if (!$this->module->invocation()->respondsToForms()) return NULL;
  280. $formName = NULL;
  281. if (isset($_REQUEST['__modulePath'])
  282. and $_REQUEST['__modulePath'] == ($this->module->invocation()->modulePath() . '/' . $this->pageName())
  283. and $this->module->invocation()->pageName() == $this->pageName())
  284. {
  285. $formName = $_REQUEST['__formName'];
  286. // CSRF Protection
  287. $form = $this->outlet($formName);
  288. if ($form->enableCSRFProtection())
  289. {
  290. if (!(isset($_REQUEST['auth']) and isset($_REQUEST['instanceid']))) throw( new WFRequestController_BadRequestException );
  291. $check = md5(session_id() . $_REQUEST['instanceid']);
  292. if ($check !== $_REQUEST['auth']) throw( new WFRequestController_BadRequestException );
  293. }
  294. }
  295. return $formName;
  296. }
  297. /**
  298. * Does this page have a form that was submitted for it?
  299. *
  300. * @return boolean TRUE if a form was submitted; FALSE otherwise.
  301. */
  302. function hasSubmittedForm()
  303. {
  304. return $this->submittedFormName() != NULL;
  305. }
  306. /**
  307. * Tell the page to use an alternate .tpl file (besides the default, '<pagename>.tpl') for
  308. * rendering the page.
  309. *
  310. * When responding to a request, you will form a response to send back to the client. Depending on the
  311. * nature of the response, there are two options in PHOCOA for building the response page.
  312. *
  313. * In many cases, your application will need to present the same data in different ways. Once example
  314. * of this is on "thank you" pages for contact form submissions. Since you will display the same data
  315. * in the page, but display it differently, it is a good application of setTemplateFile().
  316. *
  317. * The alternative is to use $module->setupResponsePage() to have PHOCOA respond to the request with
  318. * a completely different page. However, this is most useful only if you are going to be displaying
  319. * different data from the request. For instance, the "continue shopping" button of a shopping cart may
  320. * go back to a product list page.
  321. *
  322. * @param string The template file name to use.
  323. * @see WFModule::setupResponsePage()
  324. */
  325. function setTemplateFile($tplFileName)
  326. {
  327. $template = $this->prepareTemplate();
  328. $tplPath = $this->templateFilePath($tplFileName);
  329. $template->setTemplate($tplPath);
  330. }
  331. /**
  332. * Get the template used for this page.
  333. *
  334. * @return object WFPageRendering An object that implemented WFPageRendering
  335. */
  336. function template()
  337. {
  338. $this->prepareTemplate();
  339. return $this->template;
  340. }
  341. private function templateFilePath($templateFile)
  342. {
  343. return $this->module->pathToModule() . '/' . $templateFile;
  344. }
  345. /**
  346. * Make sure a template object (a template engine conforming to WFPageRendering interface) is initialized.
  347. * @return object The template object for this page.
  348. * @throws Exception if there is no template file for the current page.
  349. */
  350. function prepareTemplate()
  351. {
  352. $this->assertPageInited();
  353. if (is_null($this->template))
  354. {
  355. WFLog::log("preparing the template", WFLog::TRACE_LOG);
  356. // instantiate a template object
  357. $this->template = new WFSmarty(); // eventually could use a factory here to use any template mechanism.
  358. // initialize page with default template name; can always update it later. This way we don't store the template file name in 2 places (here and WFPageRendering instance)
  359. $this->template->setTemplate($this->templateFilePath($this->pageName . '.tpl'));
  360. }
  361. return $this->template;
  362. }
  363. /**
  364. * Get a list of all instantiated widgets belonging to this page.
  365. * @return array An array of widgets.
  366. */
  367. function widgets()
  368. {
  369. $this->assertPageInited();
  370. // construct a list of all widgets that are in our instances list.
  371. $widgets = array();
  372. foreach ($this->instances as $id => $obj) {
  373. if (!($obj instanceof WFWidget)) continue;
  374. $widgets[$id] = $obj;
  375. }
  376. return $widgets;
  377. }
  378. /**
  379. * Get all instances of the page.
  380. *
  381. * @return array An array of all instances.
  382. */
  383. function instances()
  384. {
  385. return $this->instances;
  386. }
  387. /**
  388. * Has the page been loaded?
  389. * This becomes true once initPage() is called.
  390. * @return boolean TRUE if loaded, FALSE otherwise.
  391. */
  392. function isLoaded()
  393. {
  394. if (is_null($this->pageName))
  395. {
  396. return false;
  397. }
  398. return true;
  399. }
  400. /**
  401. * Get a reference to an instance of the page.
  402. *
  403. * Using $page->outlet($id) is equivalent to accessing an object through a Cocoa outlet.
  404. *
  405. * @param string The id of the instance to get.
  406. * @return object An outlet (reference) to the specified instance id.
  407. * @throws An exception if no object exists with that id or the page is not inited.
  408. */
  409. function outlet($id)
  410. {
  411. $this->assertPageInited();
  412. if (!isset($this->instances[$id])) throw( new Exception("No object exists with id '{$id}'.") );
  413. return $this->instances[$id];
  414. }
  415. /**
  416. * Determine if there is a page instance for the given id.
  417. *
  418. * @param string The id of the instance to get.
  419. * @return boolean TRUE if there is an instance of that id, false otherwise.
  420. */
  421. function hasOutlet($id)
  422. {
  423. return ( isset($this->instances[$id]) );
  424. }
  425. /**
  426. * Convenience function to make it less verbose to get access to a shared outlet from a $page object (usually from a WFPageDelegate method).
  427. *
  428. * @param string The ID of the outlet.
  429. * @throws object WFException If there is no outlet with that name.
  430. */
  431. function sharedOutlet($id)
  432. {
  433. return $this->module->outlet($id);
  434. }
  435. /**
  436. * Add an instance to our page.
  437. *
  438. * Use this function to add dynamically created instances to the page.
  439. * NOTE: for adding WFView instances, you don't need to do this as the WFView class automatically registers all widgets.
  440. *
  441. * @param string The ID of the instance (must be unique).
  442. * @param object The object.
  443. * @throws If there is a duplicate, or $object is not an object.
  444. */
  445. function addInstance($id, $object)
  446. {
  447. // check params
  448. if (!is_object($object)) throw( new Exception("All instances must be objects. Instance ID '$id' is not an object.") );
  449. // ensure uniqueness
  450. if (isset($this->instances[$id])) throw( new Exception("Instance ID '$id' already declared. Duplicates not allowed.") );
  451. // add to our internal list
  452. $this->instances[$id] = $object;
  453. }
  454. /**
  455. * Remove an instance from the page.
  456. *
  457. * Useful for dynamically created instances, if one needs to re-create them.
  458. *
  459. * @param string $id The id of the page instance to remove.
  460. * @throws object Exception if the instance doesn't exist.
  461. */
  462. function removeInstance($id)
  463. {
  464. if (!isset($this->instances[$id])) throw( new Exception("Instance ID '$id' cannot be removed because it doesn't exist.") );
  465. unset($this->instances[$id]);
  466. }
  467. /**
  468. * Handle the instantiation of the passed object from the instances file.
  469. *
  470. * The .instances mechanism simply looks for a file named <pageName>.instances and a <pageName>.config file in your module's templates directory.
  471. * The .instances contains a list of all WFView instances for the page, and the hierarchy information.
  472. * <code>
  473. * $__instances = array(
  474. * 'instanceID' => array(
  475. * 'class' => 'WFViewSubclass',
  476. * 'children' => array(
  477. * 'subInstanceID' => array('class' => 'WFTextField')
  478. * ),
  479. * 'instanceID2' => array(
  480. * 'class' => 'WFViewSubclass'
  481. * )
  482. * );
  483. * </code>
  484. *
  485. * For each instance id, an instance of the listed class will be added to the view hierarchy. If children are listed, they will be added as well
  486. * at the appropriate place in the hierarchy.
  487. *
  488. * @param string The ID of the instance.
  489. * @param assoc_array The manifest info for the instance. 'class' is the class of the instance, and 'children' contains child items (widgets only!)
  490. * @return object The instantiated object.
  491. */
  492. protected function initInstancePHP($id, $instanceManifest) {
  493. // determine the class
  494. if (!isset($instanceManifest['class'])) throw( new Exception("Instance ID '$id' declared without a class. FATAL!") );
  495. $class = $instanceManifest['class'];
  496. WFLog::log("Instantiating object id '$id'", WFLog::TRACE_LOG);
  497. // we want to see if the class is a WFView subclass before instantiating (so that we can be sure our 'new' call below calls an existing prototype).
  498. // bug in PHP's is_subclass_of() causes segfault sometimes if the class needs to be autoloaded, so in 5.1.0 PHP stops calling autoload.
  499. // Thus, the fix is to load the class ourselves if needed before checking the inheritance.
  500. if (!class_exists($class))
  501. {
  502. __autoload($class);
  503. }
  504. if (!is_subclass_of($class, 'WFView')) throw( new Exception("Only WFView objects can be instantiated in the .instances file. Object id '$id' is of class '$class'.") );
  505. // NOTE!! We don't need to call addInstance() for widgets, as the WFWidget constructor does this automatically.
  506. // instantiate widget
  507. $object = new $class($id, $this);
  508. // determine widgets contained by this widget
  509. if (isset($instanceManifest['children']))
  510. {
  511. if (!is_array($instanceManifest['children'])) throw( new Exception("Widget ID '$id' children list is not an array.") );
  512. // recurse into children
  513. foreach ($instanceManifest['children'] as $id => $childInstanceManifest) {
  514. $childInstance = $this->initInstancePHP($id, $childInstanceManifest);
  515. $object->addChild($childInstance);
  516. }
  517. }
  518. return $object;
  519. }
  520. /**
  521. * Handle the instantiation of the passed object from the .yaml file.
  522. *
  523. * The .yaml mechanism simply looks for a file named <pageName>.yaml in your module's templates directory.
  524. * The .your contains a list of all WFView instances for the page, in a hierarchical tree, and the configuration / binding information for each instance.
  525. *
  526. * <code>
  527. * form:
  528. * class: WFForm
  529. * properties:
  530. * method: post
  531. * children:
  532. * aField:
  533. * class: WFTextField
  534. * properties:
  535. * maxLength: 50
  536. * bindings:
  537. * value:
  538. * instanceID: customer
  539. * controllerKey: selection
  540. * modelKeyPath: creationDTS
  541. * options:
  542. * </code>
  543. *
  544. * For each instance id, an instance of the listed class will be added to the view hierarchy. If children are listed, they will be added as well
  545. * at the appropriate place in the hierarchy.
  546. *
  547. * @param string The ID of the instance.
  548. * @param assoc_array The manifest info for the instance.
  549. * @return object The instantiated object.
  550. */
  551. protected function initInstanceYAML($id, $instanceManifest) {
  552. // determine the class
  553. if (!isset($instanceManifest['class'])) throw( new Exception("Instance ID '$id' declared without a class. FATAL!") );
  554. $class = $instanceManifest['class'];
  555. WFLog::log("Instantiating object id '$id'", WFLog::TRACE_LOG);
  556. // we want to see if the class is a WFView subclass before instantiating (so that we can be sure our 'new' call below calls an existing prototype).
  557. // bug in PHP's is_subclass_of() causes segfault sometimes if the class needs to be autoloaded, so in 5.1.0 PHP stops calling autoload.
  558. // Thus, the fix is to load the class ourselves if needed before checking the inheritance.
  559. if (!class_exists($class) && function_exists('__autoload'))
  560. {
  561. __autoload($class);
  562. }
  563. if (!is_subclass_of($class, 'WFView')) throw( new Exception("Only WFView objects can be instantiated in the .yaml file. Object id '$id' is of class '$class'.") );
  564. // NOTE!! We don't need to call addInstance() for widgets, as the WFWidget constructor does this automatically.
  565. // instantiate widget
  566. $object = new $class($id, $this);
  567. // set up object properties
  568. if (isset($instanceManifest['properties']))
  569. {
  570. // configure widget
  571. WFLog::log("loading properties for id '$id'", WFLog::TRACE_LOG);
  572. // atrributes
  573. foreach ($instanceManifest['properties'] as $keyPath => $value) {
  574. switch (gettype($value)) {
  575. case "boolean":
  576. case "integer":
  577. case "double":
  578. case "string":
  579. case "NULL":
  580. // these are all OK, fall through
  581. break;
  582. default:
  583. throw( new Exception("Config value for WFView instance id::property '$id::$keyPath' is not a vaild type (" . gettype($value) . "). Only boolean, integer, double, string, or NULL allowed.") );
  584. break;
  585. }
  586. if (is_string($value) and strncmp($value, "#module#", 8) === 0)
  587. {
  588. $module_prop_name = substr($value, 8);
  589. WFLog::log("Setting '$id' property, $keyPath => shared object: $module_prop_name", WFLog::TRACE_LOG);
  590. $object->setValueForKeyPath($this->module->valueForKey($module_prop_name), $keyPath);
  591. }
  592. else if (is_string($value) and strncmp($value, "#constant#", 10) === 0)
  593. {
  594. $constant_name = substr($value, 10);
  595. if (!defined($constant_name)) throw new WFException("Undefined constant: {$constant_name}");
  596. WFLog::log("Setting '{$id}' property, $keyPath => constant({$constant_name})", WFLog::TRACE_LOG);
  597. $object->setValueForKeyPath(constant($constant_name), $keyPath);
  598. }
  599. else
  600. {
  601. WFLog::log("Setting '$id' property, $keyPath => $value", WFLog::TRACE_LOG);
  602. $object->setValueForKeyPath($value, $keyPath);
  603. }
  604. }
  605. }
  606. // set up bindings
  607. if (isset($instanceManifest['bindings']))
  608. {
  609. foreach ($instanceManifest['bindings'] as $bindProperty => $bindingInfo) {
  610. if (!isset($bindingInfo['modelKeyPath']))
  611. {
  612. $bindingInfo['modelKeyPath'] = '';
  613. }
  614. WFLog::log("Binding '$id' property '$bindProperty' to {$bindingInfo['instanceID']} => {$bindingInfo['modelKeyPath']}", WFLog::TRACE_LOG);
  615. // determine object to bind to:
  616. if (!is_string($bindingInfo['instanceID'])) throw( new Exception("'$bindProperty' binding parameter instanceID is not a string.") );
  617. if (!isset($bindingInfo['instanceID'])) throw( new Exception("No instance id specified for binding object id '{$id}', property '{$bindProperty}'.") );
  618. // let objects be bound to the module, like "File's Owner" kinda thing...
  619. if ($bindingInfo['instanceID'] == '#module#')
  620. {
  621. $bindToObject = $this->module;
  622. }
  623. else
  624. {
  625. $bindToObject = $this->module->valueForKey($bindingInfo['instanceID']);
  626. }
  627. // at this point we should have an object...
  628. if (!is_object($bindToObject)) throw( new Exception("Module instance var '{$bindingInfo['instanceID']}' does not exist for binding object id '{$id}', property '{$bindProperty}'.") );
  629. // now calculate full modelKeyPath from controllerKey and modelKeyPath (simple concatenation).
  630. $fullKeyPath = '';
  631. if (isset($bindingInfo['controllerKey']))
  632. {
  633. if (!is_string($bindingInfo['controllerKey'])) throw( new Exception("'$bindProperty' binding parameter controllerKey is not a string.") );
  634. $fullKeyPath .= $bindingInfo['controllerKey'];
  635. }
  636. if (isset($bindingInfo['modelKeyPath']))
  637. {
  638. if (!is_string($bindingInfo['modelKeyPath'])) throw( new Exception("'$bindProperty' binding parameter modelKeyPath is not a string.") );
  639. if (!empty($fullKeyPath)) $fullKeyPath .= '.';
  640. $fullKeyPath .= $bindingInfo['modelKeyPath'];
  641. }
  642. if (empty($fullKeyPath)) throw( new Exception("No keyPath specified for binding object id '{$id}', property '{$bindProperty}'.") );
  643. // process options
  644. $options = NULL;
  645. if (isset($bindingInfo['options']))
  646. {
  647. // check type of all options
  648. foreach ($bindingInfo['options'] as $key => $value) {
  649. switch (gettype($value)) {
  650. case "boolean":
  651. case "integer":
  652. case "double":
  653. case "string":
  654. case "NULL":
  655. // these are all OK, fall through
  656. break;
  657. default:
  658. throw( new Exception("Binding option '$key' for WFView instance id::property '$id::$bindProperty' is not a vaild type (" . gettype($value) . "). Only boolean, integer, double, string, or NULL allowed.") );
  659. break;
  660. }
  661. }
  662. $options = $bindingInfo['options'];
  663. }
  664. try {
  665. $object->bind($bindProperty, $bindToObject, $fullKeyPath, $options);
  666. } catch (Exception $e) {
  667. print_r($bindingInfo);
  668. throw($e);
  669. }
  670. }
  671. }
  672. // set up children
  673. if (isset($instanceManifest['children']))
  674. {
  675. if (!is_array($instanceManifest['children'])) throw( new Exception("Widget ID '$id' children list is not an array.") );
  676. // recurse into children
  677. foreach ($instanceManifest['children'] as $id => $childInstanceManifest) {
  678. $childInstance = $this->initInstanceYAML($id, $childInstanceManifest);
  679. $object->addChild($childInstance);
  680. }
  681. }
  682. return $object;
  683. }
  684. /**
  685. * Load the .config file for the page and process it.
  686. *
  687. * The .config file is an OPTIONAL component. If your page has no instances, or the instances don't need configuration, you don't need a .config file.
  688. * The .config file is used to set up 'properties' of the WFView instances AND to configure the 'bindings'.
  689. *
  690. * Only primitive value types may be used. String, boolean, integer, double, NULL. NO arrays or objects allowed.
  691. *
  692. * <code>
  693. * $__config = array(
  694. * 'instanceID' => array(
  695. * 'properties' => array(
  696. * 'propName' => 'Property Value',
  697. * 'propName2' => 123
  698. * 'propName3' => '#module#moduleInstanceVarName' // use the '#module#' syntax to assign data from the module (or shared instances)
  699. * ),
  700. * 'bindings' => array(
  701. * 'value' => array(
  702. * 'instanceID' => 'moduleInstanceVarName', // put the instance name of a module instance var, or "#module#" to bind to the actual module (like File's Owner)
  703. * 'controllerKey' => 'Name of the key of the controller, if the instance is a controller',
  704. * 'modelKeyPath' => 'Key-Value Coding Compliant keyPath to use with the bound object'
  705. * 'options' => array( // Binding options go here.
  706. * 'InsertsNullPlaceholder' => true,
  707. * 'NullPlaceholder' => 'Select something!'
  708. * )
  709. * )
  710. * )
  711. * )
  712. * );
  713. * </code>
  714. *
  715. * NOTE: To see what bindings and options are available for a widget, cd to /framework and run "php showBindings.php WFWidgetName".
  716. *
  717. * @param string The absolute path to the config file.
  718. * @throws Various errors if configs are encountered for for non-existant instances, etc. A properly config'd page should never throw.
  719. */
  720. protected function loadConfig($configFile)
  721. {
  722. // be graceful; if there is no config file, no biggie, just don't load config!
  723. if (!file_exists($configFile)) return;
  724. include($configFile);
  725. foreach ($__config as $id => $config) {
  726. WFLog::log("loading config for id '$id'", WFLog::TRACE_LOG);
  727. // get the instance to apply config to
  728. $configObject = NULL;
  729. try {
  730. $configObject = $this->outlet($id);
  731. } catch (Exception $e) {
  732. throw( new Exception("Attempt to load config for instance ID '$id' failed because it does not exist.") );
  733. }
  734. // atrributes
  735. if (isset($config['properties']))
  736. {
  737. foreach ($config['properties'] as $keyPath => $value) {
  738. switch (gettype($value)) {
  739. case "boolean":
  740. case "integer":
  741. case "double":
  742. case "string":
  743. case "NULL":
  744. // these are all OK, fall through
  745. break;
  746. default:
  747. throw( new Exception("Config value for WFView instance id::property '$id::$keyPath' is not a vaild type (" . gettype($value) . "). Only boolean, integer, double, string, or NULL allowed.") );
  748. break;
  749. }
  750. if (is_string($value) and strncmp($value, "#module#", 8) == 0)
  751. {
  752. $module_prop_name = substr($value, 8);
  753. WFLog::log("Setting '$id' property, $keyPath => shared object: $module_prop_name", WFLog::TRACE_LOG);
  754. $configObject->setValueForKeyPath($this->module->valueForKey($module_prop_name), $keyPath);
  755. }
  756. else
  757. {
  758. WFLog::log("Setting '$id' property, $keyPath => $value", WFLog::TRACE_LOG);
  759. $configObject->setValueForKeyPath($value, $keyPath);
  760. }
  761. }
  762. }
  763. // bindings
  764. if (isset($config['bindings']))
  765. {
  766. foreach ($config['bindings'] as $bindProperty => $bindingInfo) {
  767. WFLog::log("Binding '$id' property '$bindProperty' to {$bindingInfo['instanceID']} => {$bindingInfo['modelKeyPath']}", WFLog::TRACE_LOG);
  768. // determine object to bind to:
  769. if (!is_string($bindingInfo['instanceID'])) throw( new Exception("'$bindProperty' binding parameter instanceID is not a string.") );
  770. if (!isset($bindingInfo['instanceID'])) throw( new Exception("No instance id specified for binding object id '{$id}', property '{$bindProperty}'.") );
  771. // let objects be bound to the module, like "File's Owner" kinda thing...
  772. if ($bindingInfo['instanceID'] == '#module#')
  773. {
  774. $bindToObject = $this->module;
  775. }
  776. else
  777. {
  778. $bindToObject = $this->module->valueForKey($bindingInfo['instanceID']);
  779. }
  780. // at this point we should have an object...
  781. if (!is_object($bindToObject)) throw( new Exception("Module instance var '{$bindingInfo['instanceID']}' does not exist for binding object id '{$id}', property '{$bindProperty}'.") );
  782. // now calculate full modelKeyPath from controllerKey and modelKeyPath (simple concatenation).
  783. $fullKeyPath = '';
  784. if (isset($bindingInfo['controllerKey']))
  785. {
  786. if (!is_string($bindingInfo['controllerKey'])) throw( new Exception("'$bindProperty' binding parameter controllerKey is not a string.") );
  787. $fullKeyPath .= $bindingInfo['controllerKey'];
  788. }
  789. if (isset($bindingInfo['modelKeyPath']))
  790. {
  791. if (!is_string($bindingInfo['modelKeyPath'])) throw( new Exception("'$bindProperty' binding parameter modelKeyPath is not a string.") );
  792. if (!empty($fullKeyPath)) $fullKeyPath .= '.';
  793. $fullKeyPath .= $bindingInfo['modelKeyPath'];
  794. }
  795. if (empty($fullKeyPath)) throw( new Exception("No keyPath specified for binding object id '{$id}', property '{$bindProperty}'.") );
  796. // process options
  797. $options = NULL;
  798. if (isset($bindingInfo['options']))
  799. {
  800. // check type of all options
  801. foreach ($bindingInfo['options'] as $key => $value) {
  802. switch (gettype($value)) {
  803. case "boolean":
  804. case "integer":
  805. case "double":
  806. case "string":
  807. case "NULL":
  808. // these are all OK, fall through
  809. break;
  810. default:
  811. throw( new Exception("Binding option '$key' for WFView instance id::property '$id::$bindProperty' is not a vaild type (" . gettype($value) . "). Only boolean, integer, double, string, or NULL allowed.") );
  812. break;
  813. }
  814. }
  815. $options = $bindingInfo['options'];
  816. }
  817. try {
  818. $configObject->bind($bindProperty, $bindToObject, $fullKeyPath, $options);
  819. } catch (Exception $e) {
  820. print_r($bindingInfo);
  821. throw($e);
  822. }
  823. }
  824. }
  825. }
  826. // after all config info is loaded, certain widget types need to "update" things...
  827. // since we don't control the order of property loading (that would get way too complex) we just handle some things at the end of the loadConfig
  828. foreach ( $this->instances as $viewId => $view ) {
  829. $view->allConfigFinishedLoading();
  830. }
  831. }
  832. /**
  833. * Get a URL that will take you to the current requestPage of the module, with the current state.
  834. * Only meaningful when called on the requestPage of the module.
  835. * @return string A URL to load the current page with the current state, but NOT send the current action. Useful for
  836. * things like a "modify search" link.
  837. * @throws If called on the responseView, as it is not meaningful.
  838. */
  839. function urlToState()
  840. {
  841. if ($this->module->requestPage() !== $this) throw( new Exception("urlToState called on a page other than the requestPage.") );
  842. $rc = WFRequestController::sharedRequestController();
  843. $url = $_SERVER['PHP_SELF'] . '?';
  844. foreach ($_REQUEST as $k => $v) {
  845. if (strncmp($k, 'action|', 7) != 0)
  846. {
  847. $url .= $k . '=' . $v . '&';
  848. }
  849. }
  850. return $url;
  851. }
  852. /**
  853. * For each widget in the current form, give the widget a chance to PULL the values from the bound objects onto the bound properties.
  854. * Only meaningful when called on the responsePage of the module.
  855. * pullBindings() will call the pullBindings() method on all widgets in the form, thus allowing them to determine which bound properties need to
  856. * "lookup" their values from the bound objects.
  857. * @throws If called on the responseView, as it is not meaningful.
  858. */
  859. function pullBindings()
  860. {
  861. if ($this->module->responsePage() !== $this) throw( new Exception("pullBindings called on a page other than the requestPage.") );
  862. $this->assertPageInited();
  863. WFLog::log("pullBindings()", WFLog::TRACE_LOG);
  864. // Call pullBindings for all widgets!
  865. foreach ( $this->widgets() as $widgetID => $widget ) {
  866. try {
  867. // lookup bound values for this widget.
  868. WFLog::log("pullBindings() for " . get_class($widget) . " ($widgetID)", WFLog::TRACE_LOG);
  869. $widget->pullBindings();
  870. } catch (Exception $e) {
  871. WFLog::log("Error in pullBindings() for " . get_class($widget) . " ($widgetID):" . $e->__toString(), WFLog::TRACE_LOG);
  872. }
  873. }
  874. }
  875. /**
  876. * For each widget in the current form, give the widget a chance to PUSH the values from the form onto the bound objects.
  877. * Only meaningful when called on the requestPage of the module.
  878. * pushBindings() will call the pushBindings() method on all widgets in the form, thus allowing them to determine which bound properties need to
  879. * "publish" their values from the form onto the bound objects.
  880. * If the value has changed, validate the value and set it as appropriate (on the bound object).
  881. * WFWidget subclasses do that from their pushBindings() callback using propagateValueToBinding()
  882. * @throws If called on the responseView, as it is not meaningful.
  883. */
  884. function pushBindings()
  885. {
  886. if ($this->module->requestPage() !== $this) throw( new Exception("pushBindings called on a page other than the requestPage.") );
  887. $this->assertPageInited();
  888. if (!$this->hasSubmittedForm()) return; // no need to pushBindings() if no form submitted as nothing could have changed!
  889. WFLog::log("pushBindings()", WFLog::TRACE_LOG);
  890. // Call pushBindings for all widgets in the form!
  891. $idStack = array($this->submittedFormName());
  892. while ( ($widgetID = array_pop($idStack)) != NULL ) {
  893. try {
  894. $view = $this->outlet($widgetID);
  895. // add all children for THIS view to the stack
  896. foreach (array_keys($view->children()) as $id) {
  897. array_push($idStack, $id);
  898. }
  899. if (!($view instanceof WFWidget)) continue; // only need to process WIDGETS below.
  900. $widget = $view;
  901. // restore the UI state for this widget
  902. $widget->pushBindings();
  903. } catch (Exception $e) {
  904. WFLog::log("Error in pushBindings() for widget '$widgetID': " . $e->getMessage(), WFLog::TRACE_LOG);
  905. throw($e);
  906. }
  907. }
  908. }
  909. /**
  910. * Restore the UI state of the page based on the submitted form.
  911. * Only meaningful when called on the requestPage of the module.
  912. * Restore state will call the restoreState() method on all widgets in the form, thus allowing them to re-create the state they should be in
  913. * after the changes that the user made to the form.
  914. * IMPORTANT!!! THIS FUNCTION ONLY RESTORES THE VALUE OF THE UI WIDGET AND DOES NOT PUBLISH THE VALUE BACK THROUGH BINDINGS.
  915. * @see pushBindings
  916. * @throws If called on the responseView, as it is not meaningful.
  917. */
  918. function restoreState()
  919. {
  920. if ($this->module->requestPage() !== $this) throw( new Exception("restoreState called on a page other than the requestPage.") );
  921. $this->assertPageInited();
  922. if (!$this->hasSubmittedForm()) return; // no state to restore if no form was submitted!
  923. WFLog::log("restoreState()", WFLog::TRACE_LOG);
  924. // Restore state of all widgets in the form!
  925. // for each widget in the form, let it restoreState()!
  926. $idStack = array($this->submittedFormName());
  927. while ( ($widgetID = array_pop($idStack)) != NULL ) {
  928. try {
  929. $view = $this->outlet($widgetID);
  930. // add all children for THIS view to the stack
  931. foreach (array_keys($view->children()) as $id) {
  932. array_push($idStack, $id);
  933. }
  934. if (!($view instanceof WFWidget)) continue; // only need to process WIDGETS below.
  935. $widget = $view;
  936. // restore the UI state for this widget, if it hasn't tried already.
  937. if (!$widget->hasRestoredState())
  938. {
  939. WFLog::log("restoring state for widget id '$widgetID'", WFLog::TRACE_LOG);
  940. $widget->restoreState();
  941. }
  942. } catch (WFRequestController_HTTPException $e) {
  943. throw $e;
  944. } catch (Exception $e) {
  945. WFLog::log("Error restoring state for widget '$widgetID': {$e->getMessage()}", WFLog::TRACE_LOG);
  946. }
  947. }
  948. }
  949. /**
  950. * Add an error to the current page.
  951. *
  952. * This function is used by WFWidgets or from action methods to add errors to the current request page.
  953. * Widgets automatically register all errors generated by Key-Value Validation of bound values.
  954. * Clients can call this function from the action method to add other run-time errors to the error mechanism.
  955. *
  956. * If the requestPage has *any* errors, the responsePage will *not* be loaded.
  957. *
  958. * @param object A WFError object.
  959. * @throws If the passed error is not a WFError or if addError() is called on the responsePage.
  960. */
  961. function addError($error)
  962. {
  963. if ($this->module->requestPage() !== $this) throw( new Exception("addError called on a page other than the requestPage.") );
  964. if (!($error instanceof WFError)) throw( new Exception("All errors must be WFError instances (not " . get_class($error) . ").") );
  965. $this->errors[] = $error;
  966. }
  967. function addErrors($arr)
  968. {
  969. foreach ($arr as $err) {
  970. $this->addError($err);
  971. }
  972. }
  973. /**
  974. * Helper function to propagate errors from WFErrorsException to widgets.
  975. *
  976. * @param object WFErrorsException
  977. * @param array Either 1) An array of strings, each string being both the key and corresponding widgetId, or 2) A hash of key => widgetId. You can mix the two as well.
  978. * @param boolean TRUE to prune the errors from the WFErrorCollection once propagated. Default: TRUE
  979. * @throws
  980. */
  981. function propagateErrorsForKeysToWidgets(WFErrorCollection $errors, $keysAndWidgets, $prune = true)
  982. {
  983. if (!is_array($keysAndWidgets)) throw new WFException("Array or Hash required.");
  984. foreach ($keysAndWidgets as $key => $widget) {
  985. if (is_int($key))
  986. {
  987. $key = $widget;
  988. }
  989. if (is_string($widget))
  990. {
  991. $widget = $this->outlet($widget);
  992. }
  993. $this->propagateErrorsForKeyToWidget($errors, $key, $widget, $prune);
  994. }
  995. }
  996. /**
  997. * Helper function to propagate errors from WFErrorsException to widgets.
  998. *
  999. * @param object WFErrorsException
  1000. * @param string The key to propagate errors for
  1001. * @param object WFWidget A widget object to propagate the errors to.
  1002. * @param boolean TRUE to prune the errors from the WFErrorCollection once propagated. Default: TRUE
  1003. * @throws
  1004. */
  1005. function propagateErrorsForKeyToWidget(WFErrorCollection $errors, $key, $widget, $prune = true)
  1006. {
  1007. foreach ($errors->errorsForKey($key) as $keyErr) {
  1008. $widget->addError($keyErr);
  1009. }
  1010. if ($prune && $errors->hasErrorsForKey($key))
  1011. {
  1012. $errors = $errors->errors();
  1013. unset($errors[$key]);
  1014. }
  1015. }