PageRenderTime 332ms CodeModel.GetById 131ms app.highlight 63ms RepoModel.GetById 107ms app.codeStats 1ms

/phocoa/framework/WFPage.php

https://github.com/SwissalpS/phocoa
PHP | 1781 lines | 1040 code | 140 blank | 601 comment | 179 complexity | 58832bf5cd1ec07de7bfd9c7243dc1a9 MD5 | raw file

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

Large files files are truncated, but you can click here to view the full file