PageRenderTime 41ms CodeModel.GetById 1ms RepoModel.GetById 1ms app.codeStats 0ms

/phocoa/framework/WFPage.php

https://github.com/SwissalpS/phocoa
PHP | 1793 lines | 1049 code | 140 blank | 604 comment | 181 complexity | dfa8dc111617f2149b8796e5e959101e MD5 | raw file
Possible License(s): LGPL-2.1
  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. }
  1016. /**
  1017. * Get a list of all errors on the page.
  1018. * @return array An array of WFErrors, or an empty array if there are no errors.
  1019. */
  1020. function errors()
  1021. {
  1022. return $this->errors;
  1023. }
  1024. /**
  1025. * Is the form valid? A form (ie requestPage submission) is considered valid if there are NO errors after it has been processed.
  1026. * @return boolean TRUE if the form is valid, FALSE otherwise.
  1027. * @throws If called on a view besides the requestPage, or if no form was submitted.
  1028. */
  1029. function formIsValid()
  1030. {
  1031. if ($this->module->requestPage() !== $this) throw( new Exception("formIsValid called on a page other than the requestPage.") );
  1032. $this->assertPageInited();
  1033. if (!$this->hasSubmittedForm()) throw( new Exception("formIsValid called, but no form was submitted.") );
  1034. if (count($this->errors) > 0)
  1035. {
  1036. return false;
  1037. }
  1038. return true;
  1039. }
  1040. /**
  1041. * Initialize the named page. This will load the widget instances and prepare for manipulating the UI.
  1042. *
  1043. * Each page has two parts, the HTML template, and the page instances config file (also called the .yaml file).
  1044. * On the filesystem, they are named <pageName>.tpl (the template file) and <pageName>.yaml (the config file).
  1045. *
  1046. * Once the instances are initialized and configured, the module will be given a chance to load default settings for the page via a callback.
  1047. * This is the time to set up select lists, default values, etc.
  1048. * The method name that will be called on the module is "<pageName>_PageDidLoad". Here is the prototype for that method:
  1049. * void <pageName>_PageDidLoad($page, $parameters);
  1050. *
  1051. * The parameters argument is an associative array, with "name" => "value". The items that will be in the array are determined by the page's parameterList,
  1052. * which is provided by the <pageName>_ParameterList() method, you can implement if your page needs parameters. This method should simply return a list of
  1053. * strings, which will become the "names" passed into your _PageDidLoad method.
  1054. *
  1055. * Here's how the parameterization works... for each item in the array, first the PATH_INFO is mapped to the items. So, if your parameterList is:
  1056. *
  1057. * array('itemID', 'otherParameter')
  1058. *
  1059. * And the PATH_INFO is /12/moreData then the parameters passed in will be array('itemID' => '12', 'otherParameter' => 'moreData').
  1060. * Any data that cannot be matched up will be passed with a NULL value.
  1061. * Also, if there is a form submitted, then the values for the parameters will be replaced by the "value" of the outlets of the same name.
  1062. * Thus, if your form has an "itemID" hidden field, the value from the form will supercede the value from PATH_INFO.
  1063. *
  1064. * After the _PageDidLoad call, the UI state from the request will be applied on top of the defaults.
  1065. *
  1066. * @todo Something is goofy with the detection of isRequestPage surrounding the action processor... seems to be getting called on the response page too. investiage.
  1067. * @todo Rename this to executePage or something... this actually runs the whole page infrastructure!
  1068. */
  1069. function initPage($pageName)
  1070. {
  1071. WFLog::log("Initing page $pageName", WFLog::TRACE_LOG);
  1072. if (!empty($this->pageName)) throw( new Exception("Page already inited with: {$this->pageName}. Cannot initPage twice.") );
  1073. $this->pageName = $pageName;
  1074. // look for page delegate
  1075. $pageDelegateClassName = $this->module->moduleName() . '_' . $this->pageName;
  1076. if (class_exists($pageDelegateClassName, false))
  1077. {
  1078. $delegate = new $pageDelegateClassName;
  1079. // look for case mismatch b/w instantiated name and name in URL; php class names are case-insensitive, so class_exists() can kinda false-positive on us here
  1080. // the mistmatch of cases means that downstream users of the name (loading yaml files, etc) will unexpectedly fail.
  1081. if ($pageDelegateClassName !== get_class($delegate))
  1082. {
  1083. throw new WFRequestController_NotFoundException("Page {$this->pageName} not found.");
  1084. // $this->pageName = substr(get_class($delegate), strlen($this->module->moduleName() . '_')); // upgrade name to correct for case
  1085. }
  1086. $this->setDelegate($delegate);
  1087. }
  1088. // calculate various file paths
  1089. $basePagePath = $this->module->pathToPage($this->pageName);
  1090. $yamlFile = $basePagePath . '.yaml';
  1091. $instancesFile = $basePagePath . '.instances';
  1092. $configFile = $basePagePath . '.config';
  1093. if (file_exists($yamlFile))
  1094. {
  1095. WFLog::log("Loading YAML config: {$pageName}.yaml", WFLog::TRACE_LOG);
  1096. $yamlConfig = WFYaml::load($yamlFile);
  1097. //print_r($yamlConfig);
  1098. foreach ($yamlConfig as $id => $instanceManifest) {
  1099. $this->initInstanceYAML($id, $instanceManifest);
  1100. }
  1101. // after all config info is loaded, certain widget types need to "update" things...
  1102. // 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
  1103. foreach ( $this->instances as $viewId => $view ) {
  1104. $view->allConfigFinishedLoading();
  1105. }
  1106. }
  1107. else
  1108. {
  1109. // parse instances file and instantiate all objects be graceful -- no need to have fatal error if there are no instances
  1110. if (file_exists($instancesFile))
  1111. {
  1112. include($instancesFile);
  1113. foreach ($__instances as $id => $instanceManifest) {
  1114. $this->initInstancePHP($id, $instanceManifest);
  1115. }
  1116. // parse config file - for each instance, see if there is a config setup for that instance ID and apply it.
  1117. // note: this will call allConfigFinishedLoading automatically
  1118. $this->loadConfig($configFile);
  1119. }
  1120. }
  1121. // let delegate know the page instances are ready
  1122. $this->pageInstancesDidLoad();
  1123. // restore UI state, if this is the requestPage
  1124. // must happen AFTER config is loaded b/c some config options may affect how the widgets interpret the form data.
  1125. // must happen BEFORE _PageDidLoad callback because that callback may need to access widget data, before it's available via bindings.
  1126. if ($this->isRequestPage())
  1127. {
  1128. $this->restoreState();
  1129. }
  1130. // the PARAMTERS are ONLY determined for the requestPage!
  1131. // Calculate parameters
  1132. $parameters = array();
  1133. $parameterList = $this->parameterList(); // get parameter definition from delegate
  1134. if ($this->isRequestPage())
  1135. {
  1136. WFLog::log("Parameterizing $pageName", WFLog::TRACE_LOG);
  1137. if (count($parameterList) > 0)
  1138. {
  1139. // first map all items through from PATH_INFO
  1140. // @todo Right now this doesn't allow DEFAULT parameter values (uses NULL). Would be nice if this supported assoc_array so we could have defaults.
  1141. $invocationParameters = $this->module->invocation()->parameters();
  1142. $defaultOpts = array(
  1143. 'defaultValue' => NULL,
  1144. 'greedy' => false
  1145. );
  1146. $i = 0;
  1147. $lastI = count($parameterList) - 1;
  1148. foreach ($parameterList as $k => $v) {
  1149. if (gettype($k) === 'integer') // has options
  1150. {
  1151. $opts = $defaultOpts;
  1152. $parameterKey = $v;
  1153. }
  1154. else
  1155. {
  1156. $parameterKey = $k;
  1157. if (is_array($v))
  1158. {
  1159. $opts = array_merge($defaultOpts, $v);
  1160. }
  1161. else
  1162. {
  1163. $opts = $defaultOpts;
  1164. $opts['defaultValue'] = $v;
  1165. }
  1166. }
  1167. if (isset($invocationParameters[$i]))
  1168. {
  1169. // handle greedy
  1170. if ($i === $lastI and $opts['greedy'] === true and count($invocationParameters) > count($parameterList))
  1171. {
  1172. $parameters[$parameterKey] = join('/', array_slice($invocationParameters, $i));
  1173. }
  1174. else
  1175. {
  1176. $parameters[$parameterKey] = $invocationParameters[$i];
  1177. }
  1178. }
  1179. else
  1180. {
  1181. $parameters[$parameterKey] = isset($_REQUEST[$parameterKey]) ? $_REQUEST[$parameterKey] : $opts['defaultValue'];
  1182. }
  1183. $i++;
  1184. }
  1185. // then over-ride with from form, if one has been submitted
  1186. if ($this->hasSubmittedForm())
  1187. {
  1188. foreach ($parameterList as $id) {
  1189. if (!$this->hasOutlet($id)) continue;
  1190. // see if there is an instance of the same name in the submitted form
  1191. $instance = $this->outlet($id);
  1192. if ($instance instanceof WFWidget)
  1193. {
  1194. // walk up looking for parent
  1195. $parent = $instance->parent();
  1196. do {
  1197. if ($parent and $parent instanceof WFForm and $parent->name() == $this->submittedFormName())
  1198. {
  1199. $parameters[$id] = $this->outlet($id)->value();
  1200. break;
  1201. }
  1202. if (!is_object($parent)) throw( new Exception("Error processing parameter overload for parameter id: '$id': found widget of same id, but cannot determine the form that it belongs to. Are you sure that widget id: '$id' is in a WFForm?") );
  1203. $parent = $parent->parent();
  1204. } while ($parent);
  1205. }
  1206. }
  1207. }
  1208. }
  1209. }
  1210. else
  1211. {
  1212. WFLog::log("Skipping Parameterization for $pageName", WFLog::TRACE_LOG);
  1213. if (count($parameterList) > 0)
  1214. {
  1215. // NULL-ify all params
  1216. for ($i = 0; $i < count($parameterList); $i++) {
  1217. $parameters[$parameterList[$i]] = NULL;
  1218. }
  1219. }
  1220. }
  1221. // save completed parameters
  1222. $this->parameters = $parameters;
  1223. // inform delegate that params are ready
  1224. $this->parametersDidLoad();
  1225. // parametersDidLoad may have affected the arrayControllers
  1226. $this->createDynamicWidgets();
  1227. // restore UI state AGAIN so that any controls created dynamically can update their values based on the UI state.
  1228. if ($this->isRequestPage())
  1229. {
  1230. $this->restoreState();
  1231. }
  1232. // now that the UI is set up (instantiated), it's time to propagate the values from widgets to bound objects if this is the requestPage!
  1233. // then, once the values are propagated, we should call the action handler for the current event, if there is one.
  1234. if ($this->isRequestPage())
  1235. {
  1236. // let delegate know that we're about to push bindings - this is effectively a statement of "we're in 'postback', deal with it if you must"
  1237. $this->willPushBindings();
  1238. // willPushBindings may have affected the arrayControllers
  1239. $this->createDynamicWidgets();
  1240. // push values of bound properties back to their bound objects
  1241. $this->module->requestPage()->pushBindings();
  1242. // Determine action: do we need to call the noAction handler?
  1243. $rpc = NULL;
  1244. if ($this->hasSubmittedForm())
  1245. {
  1246. // look for action in the form data
  1247. $rpc = WFRPC::rpcFromRequest($this->module()->invocation()->invocationPath());
  1248. if (!$rpc) // if not found; look for action specified via submit button in form (gracefully degrade for non-js client)
  1249. {
  1250. // look for the submit button;
  1251. // look up the instance ID for the specified action... look for "action|<actionOutletID>" in $_REQUEST...
  1252. // but need to skip the _x and _y fields submitted with image submit buttons
  1253. $actionOutletID = NULL;
  1254. foreach ($_REQUEST as $name => $value)
  1255. {
  1256. if (strncmp("action|", $name, 7) == 0 and !in_array(substr($name, -2, 2), array('_x', '_y')))
  1257. {
  1258. list(,$actionOutletID) = explode('|', $name);
  1259. break;
  1260. }
  1261. }
  1262. // if there is no button found in the parameters, we ask the WFForm what the default submit button is
  1263. if (!$actionOutletID)
  1264. {
  1265. $form = $this->outlet($this->submittedFormName());
  1266. $actionOutletID = $form->defaultSubmitID();
  1267. WFLog::log("Form submitted, but no action button detected. Using default button: {$actionOutletID}", WFLog::TRACE_LOG);
  1268. }
  1269. // call the ACTION handler for the page, if there is an action.
  1270. if ($actionOutletID)
  1271. {
  1272. try {
  1273. $action = $this->outlet($actionOutletID)->submitAction();
  1274. $action->rpc()->setArguments( array( $actionOutletID, 'click' ) );
  1275. $rpc = $action->rpc();
  1276. } catch (Exception $e) {
  1277. throw( new WFException("Could not find form button (outlet) for current action: {$actionOutletID}. Make sure that you don't have nested forms!") );
  1278. }
  1279. }
  1280. else
  1281. {
  1282. WFLog::log("No action occurred (no action specified in form data)", WFLog::WARN_LOG);
  1283. }
  1284. }
  1285. }
  1286. else
  1287. {
  1288. // look for action in Params
  1289. // new-school WFAction stuff;
  1290. $rpc = WFRPC::rpcFromRequest($this->module()->invocation()->invocationPath());
  1291. }
  1292. // deal with action
  1293. if ($rpc)
  1294. {
  1295. $shouldRun = false;
  1296. if ($this->hasSubmittedForm())
  1297. {
  1298. if ( $rpc->runsIfInvalid() or (!$rpc->runsIfInvalid() and $this->formIsValid()))
  1299. {
  1300. if ($rpc->runsIfInvalid())
  1301. {
  1302. $this->setIgnoreErrors(true); // runsIfInvalid by default implies ignoreErrors
  1303. }
  1304. $shouldRun = true;
  1305. }
  1306. else if ($rpc->isAjax()) // form data not valid (pre-action) and runsIfInvalid is false
  1307. {
  1308. $this->sendPageErrorsOverAjax();
  1309. }
  1310. if ($shouldRun === false)
  1311. {
  1312. $this->willNotRunAction();
  1313. }
  1314. }
  1315. else
  1316. {
  1317. $shouldRun = true;
  1318. }
  1319. if ($shouldRun)
  1320. {
  1321. try {
  1322. $rpc->execute($this);
  1323. } catch (WFErrorCollection $e) {
  1324. // Automagically map all errors for keys to widgets with the same ID
  1325. // note that propagateErrorsForKey* functions may prune errors
  1326. // from the original WFErrorCollection before we get here.
  1327. foreach ($this->instances as $id => $obj) {
  1328. if ($e->hasErrorsForKey($id))
  1329. {
  1330. $this->propagateErrorsForKeyToWidget($e, $id, $obj, true);
  1331. }
  1332. }
  1333. // add all remaining errors to the general error display
  1334. $this->addErrors($e->allErrors());
  1335. }
  1336. if ($rpc->isAjax() and count($this->errors())) // errors can also occur in the action method
  1337. {
  1338. $this->sendPageErrorsOverAjax();
  1339. }
  1340. }
  1341. }
  1342. else
  1343. {
  1344. $this->noAction();
  1345. }
  1346. // action/noAction may have affecting the arrayControllers
  1347. $this->createDynamicWidgets();
  1348. }
  1349. }
  1350. private function sendPageErrorsOverAjax()
  1351. {
  1352. // Collect all errors and send them back in a WFActionResponseWFErrorsException
  1353. $errorSmarty = new WFSmarty;
  1354. $errorSmarty->setTemplate(WFWebApplication::appDirPath(WFWebApplication::DIR_SMARTY) . '/form_error.tpl');
  1355. $uiUpdates = new WFActionResponseWFErrorsException();
  1356. foreach ($this->widgets() as $id => $obj) {
  1357. $errors = $obj->errors();
  1358. if (count($errors))
  1359. {
  1360. $errorSmarty->assign('errorList', $errors);
  1361. $errorSmarty->assign('id', $id);
  1362. $errId = "phocoaWFFormError_{$id}";
  1363. $uiUpdates->addReplaceHTML($errId, $errorSmarty->render(false));
  1364. }
  1365. }
  1366. // put "all errors" in the submitted form err handler
  1367. $errorSmarty->assign('errorList', $this->errors());
  1368. $errorSmarty->assign('id', $this->submittedFormName());
  1369. $errId = "phocoaWFFormError_" . $this->submittedFormName();
  1370. $uiUpdates->addReplaceHTML($errId, $errorSmarty->render(false));
  1371. $uiUpdates->send();
  1372. }
  1373. /**
  1374. * Call createWidgets on all WFDynamics.
  1375. *
  1376. * This function is idempotent since the underlying createWidgets() is now idempotent.
  1377. *
  1378. * This allows us to call it often without performance penalty.
  1379. */
  1380. private function createDynamicWidgets()
  1381. {
  1382. // call into all WFDynamic widgets to set up their dynamic controls.
  1383. foreach ($this->widgets() as $id => $obj) {
  1384. if ($obj instanceof WFDynamic)
  1385. {
  1386. $obj->createWidgets();
  1387. }
  1388. }
  1389. }
  1390. /**
  1391. * Is this instance the responsePage for the module?
  1392. * @return boolean TRUE if this is the responsePage, false if it is not (thus it's the requestPage).
  1393. */
  1394. function isResponsePage()
  1395. {
  1396. if ($this->module->responsePage() === $this)
  1397. {
  1398. return true;
  1399. }
  1400. return false;
  1401. }
  1402. /**
  1403. * Is this instance the requestPage for the module?
  1404. * @return boolean TRUE if this is the requestPage, false if it is not (thus it's the responsePage).
  1405. */
  1406. function isRequestPage()
  1407. {
  1408. if ($this->module->requestPage() === $this)
  1409. {
  1410. return true;
  1411. }
  1412. return false;
  1413. }
  1414. /**
  1415. * Ensure the page is inited.
  1416. * @internal
  1417. */
  1418. protected function assertPageInited()
  1419. {
  1420. if (!$this->isLoaded()) throw( new Exception("Attempted to access an uninitialized page.") );
  1421. }
  1422. /**
  1423. * Assign a value to the underlying template engine.
  1424. * @param string Name of the value in the template engine.
  1425. * @param mixed The value to assign.
  1426. */
  1427. function assign($name, $value)
  1428. {
  1429. $this->prepareTemplate();
  1430. $this->template->assign($name, $value);
  1431. }
  1432. /**
  1433. * Get the HTML output of the page.
  1434. *
  1435. * This function will call the <pageName>_SetupSkin() callback IFF this page belongs to the root module.
  1436. * This function is useful if a page wants to munge skin settings such as Title or Meta Info. It is called
  1437. * just prior to rendering the page, as this way the client can be certain that all data is loaded prior to this call.
  1438. *
  1439. * The prototype is:
  1440. *
  1441. * void <pageName>_SetupSkin($skin)
  1442. *
  1443. * @return string The HTML output of the module.
  1444. */
  1445. function render()
  1446. {
  1447. if (!$this->isResponsePage()) throw( new Exception("Render called on a page that is not the responsePage.") );
  1448. // there isn't always a skin; only on the ROOT invocation.
  1449. $skin = $this->module->invocation()->skin();
  1450. // ensure that a template object is instantiated
  1451. $this->prepareTemplate();
  1452. // stuff a copy of the current module in the template...
  1453. $this->template->assign('__module', $this->module());
  1454. // stuff a copy of the current page in the template...
  1455. $this->template->assign('__page', $this);
  1456. // stuff a copy of the skin in the template...
  1457. $this->template->assign('__skin', $skin);
  1458. $this->template->assign('__rootSkin', $this->module()->invocation()->rootSkin());
  1459. // pull bound values into all widgets based on bindings.
  1460. $this->pullBindings();
  1461. // let the page set up stuff on the skin, IFF there is a skin and a delegate method, and we're the root invocation (which now should be redundant with skin in invocation
  1462. if ($skin)
  1463. {
  1464. $this->setupSkin($skin);
  1465. }
  1466. // return the rendered output of the page. we do this in an output buffer so that if there's an error, we can display it cleanly in the skin rather than have a
  1467. // half-finished template dumped on screen (which is apparently what smarty does when an error is thrown from within it)
  1468. $output = NULL;
  1469. // let delegate do anything it needs to pre-render
  1470. $this->willRenderPage();
  1471. try {
  1472. ob_start();
  1473. $output = $this->template->render(false);
  1474. ob_end_clean();
  1475. } catch(Exception $e) {
  1476. ob_end_clean();
  1477. throw($e);
  1478. }
  1479. // let delegate munge output
  1480. $this->didRenderPage($output);
  1481. return $output;
  1482. }
  1483. // DELEGATE FUNCTIONS
  1484. function pageInstancesDidLoad()
  1485. {
  1486. if ($this->delegate && method_exists($this->delegate, 'pageInstancesDidLoad'))
  1487. {
  1488. $this->delegate->pageInstancesDidLoad($this);
  1489. }
  1490. }
  1491. function parameterList()
  1492. {
  1493. $parameters = array();
  1494. if ($this->delegate)
  1495. {
  1496. // WFPageDelegate
  1497. if (method_exists($this->delegate, 'parameterList'))
  1498. {
  1499. $parameters = $this->delegate->parameterList();
  1500. }
  1501. }
  1502. else
  1503. {
  1504. // old-school callback on module
  1505. $parameterManifestMethod = "{$this->pageName}_ParameterList";
  1506. if (method_exists($this->module, $parameterManifestMethod))
  1507. {
  1508. $parameters = $this->module->$parameterManifestMethod();
  1509. }
  1510. }
  1511. return $parameters;
  1512. }
  1513. function parametersDidLoad()
  1514. {
  1515. if ($this->delegate)
  1516. {
  1517. // WFPageDelegate
  1518. if (method_exists($this->delegate, 'parametersDidLoad'))
  1519. {
  1520. $parameters = $this->delegate->parametersDidLoad($this, $this->parameters());
  1521. }
  1522. }
  1523. else
  1524. {
  1525. // old-school callback on module
  1526. // this is where pages will set up their bound objects, etc.
  1527. $didLoadMethod = "{$this->pageName}_PageDidLoad";
  1528. if (method_exists($this->module, $didLoadMethod))
  1529. {
  1530. $this->module->$didLoadMethod($this, $this->parameters());
  1531. }
  1532. }
  1533. }
  1534. function willPushBindings()
  1535. {
  1536. if (!$this->hasSubmittedForm()) return; // pushBindings() doesn't run if no form submitted as nothing could have changed, thus we should skip the delegate call as well
  1537. if ($this->delegate)
  1538. {
  1539. if (method_exists($this->delegate, 'willPushBindings'))
  1540. {
  1541. $this->delegate->willPushBindings($this, $this->parameters());
  1542. }
  1543. }
  1544. }
  1545. /**
  1546. * @todo Has this been deprecated? I don't think it's ever used... I think WFRPC::execute() is used in practice...
  1547. */
  1548. function doAction($actionName)
  1549. {
  1550. WFLog::log("Running action: '{$actionName}'", WFLog::TRACE_LOG);
  1551. if ($this->delegate)
  1552. {
  1553. $actionMethod = $actionName . 'Action';
  1554. if (!method_exists($this->delegate, $actionMethod)) throw( new Exception("Action method {$actionMethod} does not exist in page delegate for page " . $this->pageName . " of module " . $this->module->moduleName()) );
  1555. $this->delegate->$actionMethod($this, $this->parameters());
  1556. }
  1557. else
  1558. {
  1559. // old-school callback on module
  1560. $actionMethod = $this->pageName . '_' . $actionName . '_Action';
  1561. if (!method_exists($this->module, $actionMethod)) throw( new Exception("Action method {$actionMethod} does not exist for module " . $this->module->moduleName()) );
  1562. $this->module->$actionMethod($this);
  1563. }
  1564. }
  1565. function noAction()
  1566. {
  1567. WFLog::log("Running noAction...", WFLog::TRACE_LOG);
  1568. if ($this->delegate && method_exists($this->delegate, 'noAction'))
  1569. {
  1570. $this->delegate->noAction($this, $this->parameters());
  1571. }
  1572. }
  1573. function willNotRunAction()
  1574. {
  1575. WFLog::log("Running willNotRunAction...", WFLog::TRACE_LOG);
  1576. if ($this->delegate && method_exists($this->delegate, 'willNotRunAction'))
  1577. {
  1578. $this->delegate->willNotRunAction($this, $this->parameters());
  1579. }
  1580. }
  1581. function setupSkin($skin)
  1582. {
  1583. if ($this->delegate)
  1584. {
  1585. if (method_exists($this->delegate, 'setupSkin'))
  1586. {
  1587. $this->delegate->setupSkin($this, $this->parameters(), $skin);
  1588. }
  1589. }
  1590. else
  1591. {
  1592. // old-school callback on module
  1593. $pageSkinSetupMethod = "{$this->pageName}_SetupSkin";
  1594. if ($this->module->invocation()->isRootInvocation() and method_exists($this->module, $pageSkinSetupMethod))
  1595. {
  1596. $this->module->$pageSkinSetupMethod($skin);
  1597. }
  1598. }
  1599. }
  1600. function willRenderPage()
  1601. {
  1602. if ($this->delegate && method_exists($this->delegate, 'willRenderPage'))
  1603. {
  1604. $this->delegate->willRenderPage($this, $this->parameters());
  1605. }
  1606. }
  1607. function didRenderPage(&$output)
  1608. {
  1609. if ($this->delegate && method_exists($this->delegate, 'didRenderPage'))
  1610. {
  1611. $this->delegate->didRenderPage($this, $this->parameters(), $output);
  1612. }
  1613. }
  1614. /**
  1615. * Debug function for dumping the instance tree for the page.
  1616. *
  1617. * Recursive. Call dumpTree() to use.
  1618. */
  1619. function dumpTree($obj = NULL)
  1620. {
  1621. static $depth = 0;
  1622. if ($depth == 0) print "\nInstance tree:\n";
  1623. if ($obj === NULL)
  1624. {
  1625. foreach ($this->instances as $inst) {
  1626. if ($inst->parent() === NULL)
  1627. {
  1628. $this->dumpTree($inst);
  1629. }
  1630. }
  1631. }
  1632. else
  1633. {
  1634. $depth++;
  1635. print str_repeat(' ', $depth * 2 - 2) . '\-> ' . $obj->id() . ' => ' . get_class($obj) . "\n";
  1636. if (count($obj->children()))
  1637. {
  1638. foreach ($obj->children() as $inst) {
  1639. $this->dumpTree($inst);
  1640. }
  1641. }
  1642. $depth--;
  1643. }
  1644. }
  1645. }
  1646. ?>