PEAR Progress2 logo

HTML_Progress2 : The Definitive Guide

HTML_Progress2 Manual

First Edition

Edited by

Laurent Laville

Copyright © 2005, 2006, 2007, 2008 Laurent Laville

This work is licensed under the Creative Commons Attribution License. To view a copy of this license, visit http://creativecommons.org/licenses/.

Revision History
Revision 2.4.0 | April 20, 2007

  • Finally after one more release, include as promised the HOWTO_AJAX.txt file content to this guide.
  • Change FAQ Howto entries, especially on Upload and AJAX solutions

Revision 2.3.0 | Juin 13, 2007

  • License changed from PHP 3.01 to New BSD
  • Fixed Doc Bug #10879 : add a warning annotation on Progress Monitor usage (about example line 43, see chapter 6)
  • Manual license Creative Commons upgrade from version 2.0 to 3.0

Revision 2.2.0 | January 2, 2007

  • Add new feature to import an existing stylesheet to separate PHP code form HTML layout (with CSS). See migration guide, new features chapter for details.
  • Copyright bumped to 2007
  • New section for 2.2.x revisons in chapter : What is new in version 2?

Revision 2.1.1 | December 21, 2006

  • PHP sources code are now all highlighted to improve readability
  • Fixed path on hide() method page reference for function synopsis info (missing HTML/)
  • Added "alt" html-tag attribute on all images/screenshots to be more xhtml compliant.

Revision 2.1.0 | August 12, 2006

  • FAQ is now up-to-date with the latest informations. See especially the common freeze progress bar problem.
  • What's new chapter splitted by minor version (2.0, 2.1) with their details.
  • Finally a quick start guide to use HTML_Progress2_Generator.
  • New examples with comment in Appendixes section.

Revision 2.0.1 | May 24, 2006

  • TDG revision number follow the package release version.
  • Fixes closing html - style tag of examples in Appendixes.
  • Fixes typo error in chapter 5 (thanks to Stefan Valouch).

Revision 1.0.0 | September 23, 2005

  • The final (stable) first edition of this Guide.

Table of Contents

Preface
Organization of This Book
Pre-requisites
I. Introduction
1. About Progress2
2. What's New in version 2 ?
3. FAQ - Frequently Asked Questions
II. Getting Started
4. Introduction
5. Quick Start with HTML_Progress2
6. Indeterminate Mode
7. Listener
8. Quick Start with HTML_Progress2_Monitor
9. Quick Start with HTML_Progress2_Generator
10. How to to implement an AJAX Progress Bar
11. How to to implement an AJAX Upload with Progress Bar solution
III. Migrating Guide
12. Introduction
13. How to adjust your code
14. New Features in HTML_Progress2
IV. Reference Guide
15. Introduction
16. Error Handler
17. Events to observe
18. HTML_Progress2_Lite
19. API - Application Programming Interface
V. Appendixes
20. HTML_Progress2 and HTML_Progress2_Lite features comparative
21. Examples

List of Figures

21.1. Basic usage with default skin
21.2. Indeterminate Mode usage
21.3. Multi Labels usage
21.4. Progress as a listener to Event_Dispatcher
21.5. Monitoring usage
21.6. Progress Generator wizard usage

List of Tables

14.1. Error Handling major changes
16.1. Error Handler configuration parameters
16.2. Display driver configuration parameters
16.3. Log driver configuration parameters
18.1. HTML_Progress2_Lite : position and size attributes
18.2. HTML_Progress2_Lite : color attributes
18.3. HTML_Progress2_Lite : frame attributes
18.4. HTML_Progress2_Lite : TEXT label attributes
18.5. HTML_Progress2_Lite : BUTTON label attributes
18.6. HTML_Progress2_Lite : STEP label attributes
18.7. HTML_Progress2_Lite : PERCENT label attributes
18.8. HTML_Progress2_Lite : CROSSBAR label attributes
20.1. HTML_Progress2_Lite features comparative

List of Examples

14.1. script: examples/horizontal/ancestor.php
14.2. script: progress2BasicHandler.js
14.3. ancestor.css
14.4. New content of ancestor.css
14.5. ancestor.css with two skins
21.1. Without any customization
21.2. progress bar in indeterminate mode
21.3. Four kind of progress label
21.4. Progress bar listen to user process
21.5. progress bar into a quickform window
21.6. Progress Generator build with PEAR::HTML_Page2
HTML_Progress2 : The Definitive Guide v 2.4.0 : April 20, 2007


Preface

Table of Contents

Organization of This Book
Pre-requisites

Organization of This Book

This book is divided into five parts, they are:

  • Introduction

    This section contains a gentle introduction to what HTML_Progress2 is and has to offer. Included is general information about installing and using this PEAR package, and answers to frequently asked HTML_Progress2 related questions.

  • Getting Started

    This section is intended to provide a quick introduction to get started understanding, installing, and running the bundle examples.

  • Migrating Guide

    This section is intended to help users to migrate easily all their scripts from version 1.2.x to the major 2.0.0.

  • Reference Guide

    This section describes every API in the HTML_Progress2 package. The description of each function may contain some or all of the following parts:

    • Synopsis

      Shows the structure and prototype of the function.

    • Description

      Gives a description about what the function does.

    • Parameter

      Describes each parameter for the function along with the paramater types and names. Both required and optional parameters are listed.

    • Returns

      Describes the returned value, if the function doesn't fail.

    • Throws

      Describes the returned PEAR_Error objects, if the function fails.

    • Note

      Additional notes and information about the function. An example note would be if the function can be called statically.

    • See

      Links to other related functions or manual entries.

    • Example

      An example use of the function or class.

  • Appendixes

    This section is intended to provide some examples included into the distribution. It will also give a features comparative between HTML_Progress2 and HTML_Progress2_Lite.


Pre-requisites

It is assumed that you have installed both PHP and PEAR, and that you have rudimentary knowledge of PHP, HTML and JavaScript. If you are not a PEAR user, don't worry you may use HTML_Progress2 without a PEAR installation, with some features restrictions. See HTML_Progress2_Lite for details.

It is also assumed that your PHP scripts are correctly interpreted by your web server. In most case it will be probably Apache, but you may also have IIS. HTML_Progress2 runs both on Windows and *nix.


Part I. Introduction

Table of Contents

1. About Progress2
What is HTML_Progress2 ?
Intended Audience
Why use HTML_Progress2 ?
2. What's New in version 2 ?
Version 2.0.x
Version 2.1.x
Version 2.2.x
Version 2.3.x
Version 2.4.x
3. FAQ - Frequently Asked Questions


Chapter 1. About Progress2

Table of Contents

What is HTML_Progress2 ?
Intended Audience
Why use HTML_Progress2 ?
Features
Screenshots
System Requirements

What is HTML_Progress2 ?

HTML_Progress2 makes it easy to build and display a progress meter on XHTML document of your choice, and allows user to wait and see status during a long process such a software installation. You get a more or less decent result with just the basic settings, but it's also highly configurable, so you can almost get what you want.

The core class assigns context sensitive default values for most of the parameters which minimizes the learning part. The features are there when you need it.


Intended Audience

This document is written as a guide to and reference for the HTML_Progress2 package, for both beginner and expert users.


Why use HTML_Progress2 ?

Features
Screenshots
System Requirements
Mandatory resources
Optional resources

There are some classes that exists, but never none of them as such degree of customization. You can produce all kind of progress meter you want: from basic horizontal bar, vertical bar, to circle, ellipse, and even free polygonal shape.

Features

  • create horizontal, vertival bar and also circle, ellipse and polygons (square, rectangle).
  • allows usage of existing external StyleSheet and/or JavaScript.
  • all elements (progress, cells, labels) are customizable by their html properties.
  • percent/labels are floating all around the progress meter.
  • compliant with all CSS/XHMTL standards.
  • integration with all template engines is very easy.
  • implements Observer design pattern. It is possible to add Listeners.
  • adds a customizable monitor pattern to display a progress bar. User-end can abort progress at any time.
  • allows many progress meter on same page without uses of iframe solution.
  • error handling system that support native PEAR_Error, but also PEAR_ErrorStack, and any other system you might want to plug-in.
  • PHP 5 ready

Screenshots

Here is a list of samples, to see what kind of render you could have :

  • A very simple horizontal progress bar. See Basic usage with default skin
  • A progress meter when status is unknown. See Indeterminate Mode usage
  • More than one caption around a progress meter. See Multi Labels usage
  • A progress bar and a quickform window. See Monitoring usage

Of course this is not limited to this little sample. For a full list of examples (demos) and screenshots (contains in the distribution), please visit my web site at http://pear.laurent-laville.org/HTML_Progress2/.

System Requirements

Mandatory resources
Optional resources

Mandatory resources

  • Webserver IIS or Apache (recommanded 1.3.x).
  • PHP 4.3.10 or newer.
  • PEAR 1.5.4 or newer.
  • PEAR::HTML_Common 1.2.1 or newer.
  • PEAR::HTML_CSS 1.1.2 or newer (since version 2.2.0).
  • PEAR::PHP_Compat 1.4.1 or newer.
  • PEAR::Event_Dispatcher 0.9.1 or newer.

Optional resources

  • PEAR::HTML_QuickForm 3.2.4 or newer.
  • PEAR::HTML_QuickForm_Controller 1.0.4 or newer.
  • PEAR::HTML_Template_IT 1.1 or newer.
  • PEAR::HTML_Template_Sigma 1.1.2 or newer.
  • PEAR::HTML_Page2 0.5.0 or newer.
  • PEAR::Log 1.8.7 or newer.
  • PEAR::Image_Color 1.0.1 or newer.
  • PEAR::HTML_AJAX 0.5.0 or newer (since version 2.3.0a2).
  • PHP extension APC 3.0.13 or newer.
  • PHP extension uploadprogress 0.3.0 or newer.
  • PHP extension gd 2.0.1 or newer.


Chapter 2. What's New in version 2 ?

Table of Contents

Version 2.0.x
Version 2.1.x
Version 2.2.x
Version 2.3.x
Version 2.4.x

HTML_Progress2 is a major new release includes some great new features like "multiple labels system". Take a look at the update summary below. All these features are covered in greater detail in this guide.

Version 2.0.x

  • Easier programming: with unified API and only one main class, you don't have to remember where method you will use is located.

  • Standardized observer pattern: rather than used a specified and un-optimized listener with its limits, i've rewrote implementation and used now the PEAR::Event_Dispatcher package.

  • Multiple labels system: no more need to choose between display text percent progress or a custom free text zone. You have now ability to add unlimited number of labels around your progress meter.

  • Improved API error handling and plugin system: you can use any error system handler you might want. From standard PEAR_Error to PEAR_ErrorStack or anything else. It's up to you to choose.


Version 2.1.x

  • HTML_Progress2_Generator begin again more flexible with usage of external stylesheet to existing QF renderers (Default, HTMLPage2, ITDynamic, SmartyDynamic, Tableless).


Version 2.2.x

  • New method HTML_Progress2::importStyle() give ability to import content of an existing stylesheet. We can then separate PHP code from HTML layout (with CSS), and change look and feel more easily.

    See Migrating Guide, new features chapter (reuse CSS) for details and know how to adjust your code to use this new function.


Version 2.3.x

After two years of waiting, a PEAR user Request #3985, and help of PEAR::HTML_AJAX package, the AJAX progress bar is born.

  • This important version that add asynchronous progress bar, give also support of file upload, for both PHP4 and PHP5 users.

Asynchronous File Upload support is available with :

AFLAX (stands for Asynchronous Flash and XML)

The AJAX for Adobe Flash Platform 8 or greater. See official website.

PHP5 (5.2.0 or greater) extensions backend

APC that include RFC1867 fileupload processing hook (version 3.0.13 or greater).

uploadprogress that used the RFC1867 hook to track progress of file upload.

PHP patches

Available for versions 4.3.10 and 5.0.3


Version 2.4.x

  • Fixed one bug, not yet found since origin (first version 2.0.0) of HTML_Progress2. Bug #13664: setLabelAttributes does not work. It can be demonstrate when using toHtml() and run(), but not the display() method. See Template example.

  • Implement request #12532: Add addional info to apc5 (one of Upload backend).

    You have now ability to display the current filename by using %F format in any label you want, but also the estimate time left (%E), and speed limit (%S). See examples/ajax/upload/upm5_upload.php script of package distribution as implement example.


Chapter 3. FAQ - Frequently Asked Questions

3.1. General questions
3.1.1. What does it cost ?
3.1.2. Do you offer support ?
3.1.3. I found a bug, what shall i do ?
3.1.4. What is HTML_Progress2_Lite ?
3.1.5. What is PHP_Compat ?
3.1.6. What is HTML_QuickForm ?
3.1.7. What is HTML_QuickForm_Controller ?
3.1.8. What is PEAR ?
3.1.9. What is PEAR_ErrorStack ?
3.1.10. What is Event_Dispatcher ?
3.2. Troubleshooting guide
3.2.1. I saw nothing on my browser screen
3.2.2. The progress meter is running, but I see no changes
3.2.3. The progress meter seems to be frozen at 100%, I see no changes
3.3. How to
3.3.1. How to include a progress meter in my upload form ?
3.3.2. How to implement an AJAX Progress Bar ?

3.1. General questions

3.1.1. What does it cost ?
3.1.2. Do you offer support ?
3.1.3. I found a bug, what shall i do ?
3.1.4. What is HTML_Progress2_Lite ?
3.1.5. What is PHP_Compat ?
3.1.6. What is HTML_QuickForm ?
3.1.7. What is HTML_QuickForm_Controller ?
3.1.8. What is PEAR ?
3.1.9. What is PEAR_ErrorStack ?
3.1.10. What is Event_Dispatcher ?
3.1.1.

What does it cost ?

You can download and use it for free. But don't delete the copyright notice. You can read terms of the license

3.1.2.

Do you offer support ?

YES if there is no answer in this Guide and if you are ready to share some informations such as : your configuration (platform Win *nix mac, PHP version, PEAR packages installed) and perharps your script.

3.1.3.

I found a bug, what shall i do ?

You can report it with the bug tracker at PEAR.

3.1.4.

What is HTML_Progress2_Lite ?

HTML_Progress2_Lite is less customizable than its father HTML_Progress2, but allows to do almost the same things. This class has no dependency and can be used completely outside the PEAR infrastructure.

3.1.5.

What is PHP_Compat ?

PHP_Compat provides missing functionality for older versions of PHP. This class has no dependency and can be used completely outside the PEAR infrastructure.

3.1.6.

What is HTML_QuickForm ?

HTML_QuickForm is a PEAR package that provides methods for creating, validating and processing HTML forms.

The purpose of Keith Edmunds tutorial is to give the new users of QuickForm an overview of its features and usage patterns. It describes a small subset of available functionality.

Don't forget to read also the PEAR Manual, HTML_QuickForm related part.

3.1.7.

What is HTML_QuickForm_Controller ?

HTML_QuickForm_Controller is a PEAR package that implements a PageController design pattern, which essentially means that there is a single page processing requests and actions this page performs.

This package is used only with the HTML_Progress2_Generator (an interactive tools to create your own progress meter).

Don't forget to read also the PEAR Manual, HTML_QuickForm_Controller related part.

3.1.8.

What is PEAR ?

PEAR (an acronym for PHP Extension and Application Repository) is a framework and distribution system for reusable PHP components.

Don't forget to read also the PEAR Manual and PEAR FAQ.

3.1.9.

What is PEAR_ErrorStack ?

PEAR_ErrorStack implements error raising and handling using a stack pattern. This has tremendous advantages over the PEAR_Error Implementation.

Don't forget to read also the PEAR Manual, PEAR_ErrorStack related part.

3.1.10.

What is Event_Dispatcher ?

Event_Dispatcher is a PEAR package that acts as a notification dispatch table. It is used to notify other objects of interesting things.

Event_Dispatcher is used to allow observers to hook into the progress meter process. Whenever a progress bar value changes, a notification onChange is sent. Others notification events are available: onSubmit, onLoad, and onCancel (for monitor only).

Don't forget to read also the PEAR Manual, Event_Dispatcher related part.

3.2. Troubleshooting guide

3.2.1. I saw nothing on my browser screen
3.2.2. The progress meter is running, but I see no changes
3.2.3. The progress meter seems to be frozen at 100%, I see no changes
3.2.1.

I saw nothing on my browser screen

You've forgot to put the necessary styles (CSS) on your HTML document. Add the getStyle() method.

Either with the style tags :

  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. $pb = new HTML_Progress2();
  5. ?>
  6. <style type="text/css">
  7. <!--
  8. <?php echo $pb->getStyle(); ?>
  9.  -->
  10. </style>
  11. <?php
  12. $pb->display();
  13. ?>

Or without the style tags :

  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. $pb = new HTML_Progress2();
  5.
  6. echo $pb->getStyle(false);
  7. $pb->display();
  8. ?>

3.2.2.

The progress meter is running, but I see no changes

The waiting bar of your favorite browser is running, but you don't see anything on the screen. You've forgot to put the necessary javascript code that manage the progress meter. Add the getStcript() method.

Either with the script tags :

  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. $pb = new HTML_Progress2();
  5. $pb->setAnimSpeed(100);
  6. ?>
  7. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  8.     "http://www.w3c.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  9. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  10. <head>
  11. <title>Progress2 Basic example</title>
  12. <style type="text/css">
  13. <!--
  14. <?php echo $pb->getStyle(); ?>
  15.  -->
  16. </style>
  17. <script type="text/javascript">
  18. <!--
  19. <?php echo $pb->getScript(); ?>
  20. //-->
  21. </script>
  22. </head>
  23. <body>
  24. <?php
  25. $pb->display();
  26. $pb->run();
  27. ?>
  28. </body>
  29. </html>

Or without the script tags :

  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. $pb = new HTML_Progress2();
  5. $pb->setAnimSpeed(100);
  6. ?>
  7. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  8.     "http://www.w3c.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  9. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  10. <head>
  11. <title>Progress2 Basic example</title>
  12. <?php
  13. echo $pb->getStyle(false);
  14. echo $pb->getScript(false);
  15. ?>
  16. </head>
  17. <body>
  18. <?php
  19. $pb->display();
  20. $pb->run();
  21. ?>
  22. </body>
  23. </html>
3.2.3.

The progress meter seems to be frozen at 100%, I see no changes

Using run() method rather than coding a loop as in above example, you've forgot to give a delay to progress animation. Because it's not necessary in real world, almost all cases, the delay is fixed at zero (default behavior). Use the setAnimSpeed() method to set the delay from 1 to 1000 milliseconds. In example below delay is only 0.5 second.

  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. $pb = new HTML_Progress2();
  5. $pb->setAnimSpeed(500);
  6. ?>
  7. <html>
  8. <head>
  9. <?php
  10. echo $pb->getStyle(false);
  11. echo $pb->getScript(false);
  12. ?>
  13. </head>
  14. <body>
  15. <?php
  16. $pb->display();
  17. $pb->run();
  18. ?>
  19. </body>
  20. </html>

Another possible reason is due to your firewall or anti-virus software. Check-out if the web content protection is active or not. If is set to true, try to de-activate it and see if you have still the problem.

[Note] Note
Thanks to Mathieu GRELIER for his feedback on anti-virus software problem : Progress2 (and PHP flush function) is not compatible with real-time web parsing softwares.

[Tip] Tip
With Kaspersky Anti-Virus 6, look in configuration panel, network port control, and de-activate the http-standard port 80.

3.3. How to

3.3.1. How to include a progress meter in my upload form ?
3.3.2. How to implement an AJAX Progress Bar ?
3.3.1.

How to include a progress meter in my upload form ?

Before AJAX it was impossible to do with a pure PHP solution. By the way, there are some mixed solutions that exists on the Web. Here is a short list :

http://jupload.biz/

JUpload is an easy to use java applet for uploading multiple files to the webserver using the post method of html forms as described in RFC 1867.

http://www.aspupload.com/

AspUpload is a COM+ component which enables an ASP application to capture, save and process files uploaded to the web server with a browser.

http://www.raditha.com/php/progress.php

Mega Upload is a file uploader with a progress monitor. There are three separate editions for the three most popular web programming languages PHP/Perl/JSP.

http://pdoru.from.ro/

Upload Progress Meter is a patch for PHP4 or PHP5.

Now with AJAX, and some PHP extension (like APC with PHP 5.2+, or PECL uploadprogress) that used the RFC1867 hook to track progress of file upload, dream begin a reality !

See chapter How to to implement an AJAX Upload with Progress Bar solution to learn more.

3.3.2.

How to implement an AJAX Progress Bar ?

Since release 2.3.0, there was an existing text file included into distribution named HOWTO_AJAX.txt. Content of this file is now integrated into this guide. Read chapter How to to implement an AJAX Progress Bar to learn more.


Part II. Getting Started

Table of Contents

4. Introduction
5. Quick Start with HTML_Progress2
Designing
Processing
Strategy of handling
6. Indeterminate Mode
Basic usage
Progress Monitor usage
7. Listener
Events categories
How to observe events ?
8. Quick Start with HTML_Progress2_Monitor
Basic concept
Default render
Default improved render
Sigma template engine integration
9. Quick Start with HTML_Progress2_Generator
Basic concept
Default render and css skin
Template integration
10. How to to implement an AJAX Progress Bar
History
Design details
Progress bar HTML design
Handle polling loop
Refresh progress bar
Examples (full source code)
11. How to to implement an AJAX Upload with Progress Bar solution
AJAX with PEAR package HTML_AJAX
HTML side
Server side
Examples (full source code)


Chapter 4. Introduction

If you've not used the HTML_Progress class before, you should spend few minutes getting to known the basics by reading the Quick Start guide.

Expert users want probably know how to adjust their code to make their V1 scripts V2 compatible. The migration guide is the solution for them.


Chapter 5. Quick Start with HTML_Progress2

Table of Contents

Designing
Shape
Cells
Border
Background
Fill direction
Processing
With a user callback
Without user callback
Strategy of handling
Strategy 1: moveNext
Strategy 2: moveStep

Start using HTML_Progress2 straight away.

Through samples code that are possible real cases we will study all features of the HTML_Progress2 package. Additional tutorials will help you to learn what are others features: Indeterminate Mode, Listener, Monitoring, Generator interactive tools.

There are two main phases in developement and use of a progress meter: designing and processing.

Designing

Shape
Cells
Border
Background
Fill direction

You have probably your ideas of what it should look like: shape, size, colors. So how to build it ?

Shape

Even if it's not yet ready to be display, following source code will create a new instance of the HTML_Progress2 class that is ready to build an horizontal (default shape) progress bar:

  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. $pb = new HTML_Progress2();
  5. ?>

If you want to build others shapes like :

  • vertical progress bar, use constant HTML_PROGRESS2_BAR_VERTICAL
  • square or rectangle, use constant HTML_PROGRESS2_POLYGONAL
  • circle or ellipse, use constant HTML_PROGRESS2_CIRCLE

  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. $pb = new HTML_Progress2();
  5. $pb->setOrientation(HTML_PROGRESS2_BAR_VERTICAL);
  6. ?>

Only with horizontal and vertical progress bar, you have ability to choose between smooth or cell rendering. What is it ?

A smooth progress bar is a full bar that look like this:

while cell progress bar look like :

Remember that default progress meter is horizontal progress bar with ten cells (as above). If you want to have smooth progress bar, or change cell spacing (in pixel), use the setCellAttributes() method with spacing attribute.

  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. $pb = new HTML_Progress2();
  5. $pb->setCellAttributes('spacing=0');
  6. ?>

[Note] Note
it's not a real smooth progress meter as HTML_Progress2_Lite can do.

Cells

By default, an horizontal or vertical (and even circle/ellipse) progress meter have ten cells, one for each ten percent.

Among attribute you can change there are: size (height, width) and color(active inactive). See setCellAttributes() method for all details and default values.

We can also enlarge or reduce the cell count of the progress bar with the setCellCount() method.

If we want to have a twelve cells horizontal progress meter with largest square (20x20 pixels) and red skin, then write :

  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. $pb = new HTML_Progress2();
  5. $pb->setCellCount(12);
  6. $pb->setCellAttributes(array(
  7.     'active-color' => '#FF0000',
  8.     'inactive-color' => '#FF9900',
  9.     'width' => 20,
  10.     'height' => 20,
  11.     'spacing' => 4
  12. ));
  13. ?>

[Note] Note
You can also use an html string that defines attributes list. In our sample we will write:
  1. <?php
  2. $pb->setCellAttributes('active-color=#FF0000 inactive-color=#FF9900 width=20 height=20 spacing=4');
  3. ?>

Border

A progress bar (horizontal or vertical) can be surrounded by a border (it's not the default).

  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. $pb = new HTML_Progress2();
  5. $pb->setBorderPainted(true);
  6. $pb->setBorderAttributes(array(
  7.     'width' => 2,
  8.     'style' => 'solid',
  9.     'color' => 'red'
  10. ));
  11. ?>

Partial script above, will produce an horizontal progress bar with a red solid border; something like this:

[Important] Important
Without setBorderPainted() method and a TRUE argument, there won't be any border rendering. Even if you set a positive width with setBorderAttributes() method.

Background

A progress bar (horizontal or vertical) has a white background by default, but you can change that. You may even use an image as background. Don't worry if image is smaller (use background-repeat attribute) or bigger than progress meter. Accuracy positionning is possible with usage of background-position attribute.

  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. $pb = new HTML_Progress2();
  5. $pb->setProgressAttributes(array(
  6.     'background-color' => '#339900',
  7.     'background-image' => 'degrade.jpg',
  8.     'background-repeat' => 'repeat-y'
  9. ));
  10. $pb->setCellAttributes('inactive-color=transparent');
  11. ?>

[Tip] Tip
Even if you want to use an image as background, don't forget to add background-color attribute as an alternative.

It's same feature as img tag for html and its alt attribute.

Fill direction

Progress meter can be fill in two directions (ways) called natural or reverse. Default behavior is natural fill.

  • For horizontal progress bar, natural way is from left to right, while reverse way is from right to left.

  • For vertical progress bar, natural way is from down to up, while reverse way is from up to down.

  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. $pb = new HTML_Progress2();
  5. $pb->setOrientation(HTML_PROGRESS2_BAR_VERTICAL);
  6. $pb->setFillWay('reverse');
  7. $pb->setAnimSpeed(50);
  8. $pb->setCellCount(15);
  9. $pb->setCellAttributes('active-color=#970038 inactive-color=#FFDDAA width=50 height=13');
  10. $pb->setBorderPainted(true);
  11. $pb->setBorderAttributes('width=1 color=#000000');
  12. $pb->setLabelAttributes('pct1', array(
  13.     'font-size' => 8,
  14.     'color' => '#FF0000',
  15.     'background-color' => '#C3C6C3',
  16.     'align' => 'center',
  17.     'valign' => 'bottom'
  18. ));
  19. ?>

Partial script above, will produce a vertical progress bar filled in reverse way (top to down), that look like:


Processing

With a user callback
Without user callback

Now we know the basic of progress meter design, its now time to learn how to handle display refresh with the user process.

There are two main ways :

  1. with a user callback. The core of HTML_Progress2 checking progression (until end), and handling display refresh for us.

  2. without user callback. We have to do all tasks that core of HTML_Progress2 can do it for us.

With a user callback

Its the most easy way. We have just to declare the user callback with setProgressHandler() method, and launch execution with run() method. HTML_Progress2 will check progression of meter (both modes supported: indeterminate, determinate) and stop when 100% is reach.

[Tip] Tip
If you don't specify a callback, default behavior will call HTML_Progress2 sleep() method in background: delay animation n milliseconds (default = zero). This delay is set by setAnimSpeed() method.

Here is an example that demonstrates user callback usage. We suppose that we get image count from any data source and we have to build/display these images. It could be generated by jpgraph (for complex graphics), but here we used five times same script that call a pearImage() function. Part of code came from PEAR_Info package.

Here is a copy of such PEAR_Info::pearImage() function, in the pearimage.php script:

  1. <?php
  2. function pearImage()
  3. {
  4.   $pear_image = 'R0lGODlhaAAyAMT/AMDAwP3+/TWaAvD47Pj89vz++zebBDmcBj6fDEekFluvKmu3PvX68ujz4XvBS8LgrNXqxeHw1ZnPaa/dgvv9+cLqj8LmltD2msnuls';
  5.   $pear_image .= '3xmszwmf7+/f///wAAAAAAAAAAACH5BAEAAAAALAAAAABoADIAQAX/ICCOZGmeaKqubOtWWjwJphLLgH1XUu//C1Jisfj9YLEKQnSY3GaixWQqQTkYHM4';
  6.   $pear_image .= 'AMulNLJFC9pEwIW/odKU8cqTfsWoTTtcomU4ZjbR4ZP+AgYKCG0EiZ1AuiossEhwEXRMEg5SVWQ6MmZqKWD0QlqCUEHubpaYlExwRPRZioZZVp7KzKQoS';
  7.   $pear_image .= 'DxANDLsNXA5simd2FcQYb4YAc2jEU80TmAAIztPCMcjKdg4OEsZJmwIWWQPQI4ikIwtoVQnddgrv8PFlCWgYCwkI+fp5dkvJ/IlUKMCy6tYrDhNIIKLFE';
  8.   $pear_image .= 'AWCTxse+ABD4SClWA0zovAjcUJFi6EwahxZwoGqHhFA/4IqoICkyxQSKkbo0gDkuBXV4FRAJkRCnTgi2P28IcEfk5xpWppykFJVuScmEvDTEETAVJ6bEp';
  9.   $pear_image .= 'ypcADPkz3pvKVAICHChkC7siQ08zVqu4Q6hgIFEFZuEn/KMgRUkaBmAQs+cEHgIiHVH5EAFpIgW4+NT6LnaqhDwe/Ov7YOmWZp4MkiAWBIl0kAVsJWuzc';
  10.   $pear_image .= 'YpdiNgddc0E8cKBAu/FElBwagMb88ZZKDRAkWJtkWhHh3wwUbKHQJN3wQAaXGR2LpArv5oFHRR34C7Mf6oLXZNfqBgNI7oOLhj1f8PaGpygHQ0xtP8MDV';
  11.   $pear_image .= 'KwYTSKcgxr9/hS6/pCCAAg5M4B9/sWh1YP9/XSgQWRML/idBfKUc4IBET9lFjggKhDYZAELZJYEBI2BDB3ouNBEABwE8gAwiCcSYgAKqPdEVAG7scM8BP';
  12.   $pear_image .= 'PZ4AIlM+OgjAgpMhRE24OVoBwsIFEGFA7ZkQQBWienWxmRa7XDjKZXhBdAeSmKQwgLuUVLICa6VEKIGcK2mQWoVZHCBXJblJUFkY06yAXlGsPIHBEYdYi';
  13.   $pear_image .= 'WHb+WQBgaIJqqoHFNpgMGB7dT5ZQuG/WbBAIAUEEFNfwxAWpokTIXJAWdgoJ9kRFG2g5eDRpXSBpEIF0oEQFaZhDbaSFANRgqcJoEDRARLREtxOQpsPO9';
  14.   $pear_image .= '06ZUeJgjQB6dZUPBAdwcF8KLXXRVQaKFcsRRLJ6vMiiCNKxRE8ECZKgUA3Va4arOAAqdGRWO7uMZH5AL05gvsjQbg6y4NCjQ1kw8TVGcbdoKGKx8j3bGH';
  15.   $pear_image .= '7nARBArqwi0gkFJBrZiXBQRbHoIgnhSjcEBKfD7c3HMhz+JIQSY3t8GGKW+SUhfUajxGzKd0IoHBNkNQK86ZYEqdzYA8AHQpqXRUm80oHs1CAgMoBxzRq';
  16.   $pear_image .= 'vzs9CIKECC1JBp7enUpfXHApwVYNAfo16c4IrYPLVdSAJVob7IAtCBFQGHcs/RRdiUDPHA33oADEAIAOw==';
  17.   header('content-type: image/gif');
  18.   echo base64_decode($pear_image);
  19. }
  20. pearImage();
  21. ?>

And now, the main script.

  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. $dataSrc = array('pearimage', 'pearimage', 'pearimage', 'pearimage', 'pearimage');
  5.
  6. function myProcess($pValue, &$pBar)
  7. {
  8.     static $q = 0;
  9.     global $dataSrc;
  10.
  11.     $pBar->sleep();
  12.     if (isset($dataSrc[$q])) {
  13.         echo '<tr><td>'
  14.            . '<img src="'. $dataSrc[$q] .'.php?timestamp=' . time() . '" alt=""/>'
  15.            . '<b>'.($q+1).'</b>'
  16.            . '</td></tr>';
  17.     }
  18.     $q++;
  19.     return $q;
  20. }
  21.
  22. $pb = new HTML_Progress2();
  23. $pb->setAnimSpeed(500);
  24. $pb->setIncrement(intval(ceil(100 / count($dataSrc))));
  25. $pb->setProgressHandler('myProcess');
  26. ?>
  27. <html>
  28. <head>
  29. <?php
  30. echo $pb->getStyle(false);
  31. echo $pb->getScript(false);
  32. ?>
  33. </head>
  34. <body>
  35. <?php
  36. $pb->display();
  37. echo '<table width="100%">';
  38. $pb->run();
  39. echo '</table>';
  40. $pb->hide();
  41. ?>
  42. </body>
  43. </html>

Lets review this example step by step :

Line 4 :

$dataSrc identify the data source. Five call to pearimage.php script.

Lines 6-20, 25 :

Main task is to build, and display, five pear logo pictures. This task is defined by user callback : myProcess and linked to progress meter by setProgressHandler() method.

Lines 19, 24 :

We used moveStep strategy with the return $q code, and increment compute.

If you remove this line we use the second strategy called moveNext. We will talk about it later. Don't be afraid if you don't know yet what is the difference.

Line 40 :

Task is completed, five logo built and shown. The progress bar is hidden.

Without user callback

To show difference of two implementations, we will re-used the same example of pear logo.

  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. $dataSrc = array('pearimage', 'pearimage', 'pearimage', 'pearimage', 'pearimage');
  5.
  6. function myProcess()
  7. {
  8.     static $q = 0;
  9.     global $dataSrc;
  10.
  11.     if (isset($dataSrc[$q])) {
  12.         echo '<tr><td>'
  13.            . '<img src="'. $dataSrc[$q] .'.php?timestamp=' . time() . '" alt=""/>'
  14.            . '<b>'.($q+1).'</b>'
  15.            . '</td></tr>';
  16.     }
  17.     $q++;
  18.     return $q;
  19. }
  20.
  21. $pb = new HTML_Progress2();
  22. $pb->setAnimSpeed(500);
  23. $pb->setIncrement(intval(ceil(100 / count($dataSrc))));
  24. ?>
  25. <html>
  26. <head>
  27. <?php
  28. echo $pb->getStyle(false);
  29. echo $pb->getScript(false);
  30. ?>
  31. </head>
  32. <body>
  33. <?php
  34. $pb->display();
  35. echo '<table width="100%">';
  36.
  37. foreach ($dataSrc as $script) {
  38.     if ($pb->getPercentComplete() == 1) {
  39.         break;
  40.     }
  41.     $ret = myProcess();
  42.     $pb->sleep();
  43.     $pb->moveStep($ret);
  44. }
  45.
  46. echo '</table>';
  47. $pb->hide();
  48. ?>
  49. </body>
  50. </html>

Lets review this example step by step :

Line 4 :

$dataSrc identify again the data source. Five call to pearimage.php script.

Lines 6-19 :

myProcess is defined as a reusable function and not a callback for progress meter.

Lines 37-44 :

run() method was replaced by a for-each loop. We must :

  1. check if progress meter reach 100% (getPercentComplete() method).
  2. refresh display with right method depending on strategy used.

Lines 18, 41, 43 :

We use again the same moveStep strategy.

Line 47 :

Task is completed, five logo built and shown. The progress bar is hidden.


Strategy of handling

Strategy 1: moveNext
Strategy 2: moveStep

In previous example (pear logo) we have introduced that progress meter can handle two strategies called moveStep and moveNext.

What are the difference, and when use one rather than the other ? Here is the purpose of this section.

Strategy 1: moveNext

When we don't know how many step a progress meter should handle, or if you want to force display to a special value, the right strategy is the most simple : moveNext.

Progress meter will be refresh with : new value = previous value + increment. Increment is defined by setIncrement() method (default = +1).

What you must do:

  1. NEVER return a value in a user callback or user function (depending on processing strategy used).
  2. use only moveNext() method to refresh progress meter.

Strategy 2: moveStep

When task can be divided in many part (knew at runtime) as pear logo example, the right strategy is : moveStep.

What you must do:

  1. compute the right increment : progress meter max value / task count This number should be integer, and round fractions up.
  2. ALWAYS return the next step value in a user callback or user function (depending on processing strategy used).
  3. use only moveStep() method to refresh progress meter.


Chapter 6. Indeterminate Mode

Table of Contents

Basic usage
Progress Monitor usage

Sometimes you can't immediately determine the length of a long-running task, or the task might stay stuck at the same state of completion for a long time.

You can show work without measurable progress by putting the progress meter in indeterminate mode. A progress meter in indeterminate mode displays animation to indicate that work is occurring. As soon as the progress meter can display more meaningful information, you should switch it back into its default, determinate mode.

We will learn, with two examples, how to use indeterminate mode. The first example apply basic concept, and the second example show an integration with a progress monitor.

Basic usage

In following example we will simulate a task that display a progress meter in indeterminate mode waiting for a ressource (mail post, file upload, ...). We are waiting 12 seconds before switch back to determinate mode (default) and finish process with a full loop from 0 to 100% by +5 step increment.

Strategies used are :

  1. user callback for the waiting process (function: myProcess)
  2. refresh with standard moveNext handling. If you don't know what i means, then you have probably skip the chapter i suggest you to read it now before to continue.

Here is a preview of a progress bar in indeterminate mode. Animation look like a sliding box.

And now the script we will review step by step to understand concepts.

  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. function myProcess($pValue, &$pBar)
  5. {
  6.     static $c, $t;
  7.
  8.     if (!isset($c)) {
  9.         $c = time();
  10.         $t = 0;
  11.     }
  12.
  13.     $pBar->sleep();
  14.
  15.     if ($pBar->isIndeterminate()) {
  16.         $elapse = time() - $c;
  17.
  18.         if ($elapse > $t) {
  19.             echo "myProgressHandler -> elapse time = $elapse s.<br />\n";
  20.             $t++;
  21.         }
  22.         if ($elapse >= 12) {
  23.             $pBar->setIndeterminate(false);
  24.             $pBar->setValue(0);
  25.             $pBar->setIncrement(5);
  26.         }
  27.     }
  28. }
  29.
  30. $pb = new HTML_Progress2();
  31. $pb->setAnimSpeed(200);
  32. $pb->setIncrement(10);
  33. $pb->setProgressAttributes('background-color=#E0E0E0');
  34. $pb->setCellAttributes('active-color=#996');
  35. $pb->setLabelAttributes('pct1', array('color' => '#996'));
  36. $pb->setIndeterminate(true);
  37. $pb->setProgressHandler('myProcess');
  38. ?>
  39. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  40.     "http://www.w3c.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  41. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  42. <head>
  43. <title>Waiting for resource ... (simulation)</title>
  44. <style type="text/css">
  45. <!--
  46. body {
  47.     background-color: #CCCC99;
  48.     color: #996;
  49.     font-family: Verdana, Arial;
  50. }
  51.
  52. <?php echo $pb->getStyle(); ?>
  53.  -->
  54.
  55. </style>
  56. <?php echo $pb->getScript(false); ?>
  57. </head>
  58. <body>
  59.
  60. <?php
  61. $pb->display();
  62. echo '<br /><br />';
  63. $pb->run();
  64. ?>
  65.
  66. <p><b>Process Ended !</b></p>
  67.
  68. </body>
  69. </html>

Line 23 :

Once the progress bar is switch back to determinate mode, we will reset value to zero to start a new standard cycle (from 0 to 100%).

Line 24 :

Without this reset step, the progress meter continue until end (100%) from its current position (unpredictable).

Lines 13, 31, 32 :

Increment is set to 10 to give, with a 0.2 second (200 milisecond) delay, a smooth animation.

Line 36 :

Indeterminate mode is activated(/desactivated) only with setIndeterminate() method.

Lines 4-28, 37 :

myProcess function is the user process that will simulate a waiting resource for 12 seconds, and finish in determinate mode.


Progress Monitor usage

Here is a preview of a progress monitor in indeterminate mode with a custom layout. Differences with basic concept resides mainly into QF renders.

[Important] Important
When you had choice of processing strategy with simple progress meter, it's not the same with a progress monitor.

Due to its architecture, progress monitor only work with progress meter and user callback.

Even if it's pretty same concept as basic example, let's review step by step how the monitor is implemented with a user callback.

  1. <?php
  2. require_once 'HTML/Progress2/Monitor.php';
  3.
  4. function myProcess($pValue, &$pBar)
  5. {
  6.     global $pm;
  7.     static $c;
  8.
  9.     if (!isset($c)) {
  10.         $c = 0;
  11.     }
  12.     $c += 16;
  13.     $pm->setCaption('completed %step% out of 400', array('step' => $c));
  14.
  15.     $pBar->sleep();
  16.
  17.     if ($c >= 240 && $pBar->isIndeterminate()) {
  18.         $pBar->setIndeterminate(false);
  19.         $pBar->setValue(0);
  20.     }
  21.     if ($pBar->getPercentComplete() == 1) {
  22.         if ($pBar->isIndeterminate()) {
  23.             $pBar->setValue(0);
  24.         }
  25.     }
  26. }
  27.
  28. $pm = new HTML_Progress2_Monitor('frmMonitor',
  29.     array( 'button' => array('style' => 'width:80px;'),
  30.            'title'  => 'Progress ...' )
  31. );
  32.
  33. $pb =& $pm->getProgressElement();
  34. $pb->setAnimSpeed(200);
  35. $pb->setIncrement(10);
  36. $pb->setProgressAttributes('background-color=#E0E0E0');
  37. $pb->setCellAttributes('active-color=#996');
  38. $pb->setLabelAttributes('pct1', 'color=#996');
  39. $pb->setLabelAttributes('monitorStatus', 'color=black font-size=10');
  40. $pb->setIndeterminate(true);
  41. $pb->setProgressHandler('myProcess');
  42.
  43. //$pm->setProgressElement($pb);
  44. ?>
  45. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  46.     "http://www.w3c.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  47. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  48. <head>
  49. <title>Waiting for resource ... (simulation)</title>
  50. <style type="text/css">
  51. <!--
  52. body {
  53.     background-color: #444444;
  54.     font-family: Verdana, Arial;
  55. }
  56.
  57. <?php echo $pm->getStyle(); ?>
  58.  -->
  59. </style>
  60. <?php echo $pm->getScript(false); ?>
  61. </head>
  62. <body>
  63.
  64. <?php
  65. $renderer =& HTML_QuickForm::defaultRenderer();
  66. $renderer->setFormTemplate('
  67. <form{attributes}>
  68.  <table width="450" border="0" cellpadding="3" cellspacing="2" bgcolor="#CCCC99">
  69.  {content}
  70.  </table>
  71. </form>
  72. ');
  73. $renderer->setElementTemplate('
  74.  <tr>
  75.    <td valign="top" style="padding-left:15px;">
  76.    {element}
  77.    </td>
  78.  </tr>
  79. ');
  80. $renderer->setHeaderTemplate('
  81.  <tr>
  82.  <td style="background:#996;color:#ffc;" align="left" colspan="2">
  83.    <b>{header}</b>
  84.  </td>
  85.  </tr>
  86. ');
  87. $pm->accept($renderer);
  88.
  89. echo $renderer->toHtml();
  90. $pm->run();
  91. ?>
  92.
  93. </body>
  94. </html>

Line 18 :

Once the progress bar is switch back to determinate mode, we will reset value to zero to start a new standard cycle (from 0 to 100%).

Line 19 :

Without this reset step, the progress meter continue until end (100%) from its current position (unpredictable).

Lines 15, 34, 35 :

Increment is set to 10 to give, with a 0.2 second (200 milisecond) delay, a smooth animation.

Line 40 :

Indeterminate mode is activated(/desactivated) only with setIndeterminate() method.

Lines 4-26, 41 :

myProcess function is the user process that will simulate a waiting resource (that become available on value 240/400), and finish in determinate mode.

Lines 33, 43 :

You need to use setProgressElement() method when you build a complete progress bar from scratch, and don't reuse the basic version included into Progress Monitor. Or if you won't work by reference.

[Warning] Warning
If you change an html layout element such as, cell size, cell count, progress shape ... and you forget to add line 43, then no change you should expected will be applied.

[Caution] Caution
Notice the & that means you work by reference.

Line 87 :

This Progress Monitor use a QF renderer defined by its custom elements:

  • [QF window presentation] setFormTemplate()

  • [QF meter/buttons line] setElementTemplate()

  • [QF window title] setHeaderTemplate()


Chapter 7. Listener

Table of Contents

Events categories
How to observe events ?

HTML_Progress2 class provides an implementation of the observer pattern. It provide a mechanism which you can examine each important event as it is happened. This allow the implementation of special behavior based on the value of the progress meter.

Implementation of a standardized observer pattern is made with help of PEAR::Event_Dispatcher package (manual ).

Events categories

Depending on action triggered, there are four events you may be listen:

  • onSubmit. This event corresponding to start of progress meter (at launch of run() method).

  • onLoad. This event corresponding when progress meter reach 100% (just after run() method execution).

  • onChange This event corresponding when progress meter value is changed. Many reasons :

    • declare or change minimum value with setMinimum() method
    • declare or change maximum value with setMaximum() method
    • change current value with setValue() or incValue() methods
    • refresh display with moveStep() or moveNext() methods

  • onCancel [progress monitor only]. This event corresponding when progress monitor is stopped by user action (cancel key pressed).


How to observe events ?

Suppose we decide to send a mail after a process is over (progress meter reach 100%) and keep aware some users. We will see how to do this now.

First step is to declare a function (user callback) that will observe all progress meter events.

Interface of such function (callback) is pretty easy. It requires only one argument passed by reference ($notification) and that should contains a PEAR::Event_Dispatcher instance.

Here are, in purpose of our tutorial, a function that will observe events and send a mail, at end of process, to webmaster@site.com with a short message that gave time elapsed.

Second step is to attach this function (user callback) to the progress meter with the addListener() method.

  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. function getmicrotime($time)
  5. {
  6.     list($usec, $sec) = explode(' ', $time);
  7.     return ((float)$usec + (float)$sec);
  8.
  9. }
  10.
  11. function myObserver(&$notification)
  12. {
  13.     static $time_start;
  14.
  15.     $notifyName = $notification->getNotificationName();
  16.     $notifyInfo = $notification->getNotificationInfo();
  17.
  18.     switch ($notifyName) {
  19.         case 'onSubmit':
  20.             $time_start = getmicrotime($notifyInfo['time']);
  21.             break;
  22.         case 'onLoad':
  23.             $time_elapse = getmicrotime($notifyInfo['time']) - $time_start;
  24.             error_log ('process ID=5 is over (elapse time = '. $time_elapse . ' sec.)',
  25.                        3, 'progress_observer.log');
  26.             break;
  27.     }
  28. }
  29.
  30. $pb = new HTML_Progress2();
  31. $pb->setAnimSpeed(200);
  32. $pb->setIncrement(10);
  33. $pb->addListener('myObserver');
  34. ?>
  35. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  36.     "http://www.w3c.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  37. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  38. <head>
  39. <title>Observer Pattern</title>
  40.
  41. <?php
  42. echo $pb->getStyle(false);
  43. echo $pb->getScript(false);
  44. ?>
  45. </head>
  46. <body>
  47. <?php
  48. $pb->display();
  49. $pb->run();
  50. ?>
  51. </body>
  52. </html>

Line 15 :

$notifyName contains event name triggered. Three issues : onSubmit, onLoad, onChange.

[Caution] Caution
Event name is case sensitive: onsubmit does not match onSubmit.

Line 16 :

$notifyInfo contains array of additional informations.

For example :

Array
(
    [handler] => run
    [value] => 100
    [sender] => html_progress2
    [time] => 0.26838700 1127382686
)

Line 19 :

When progress meter start, it trigger a onSubmit event through the run() method. This event is catched into user callback and with help of additionnal info we compute and store start time.

Line 22 :

When progress meter reach 100%, it trigger a onLoad event through the run() method. This event is catched into user callback. We compute elapse time and send final result by mail to the webmaster of site.com

Lines 11-28, 33 :

All observers attached, are notified by each event. It's up to you to decide if you have to process an event or not. Here we will proceed only two events: onSubmit, onLoad.

Third step (optional) is stop listen events and then detach user function (callback) to the progress meter with the removeListener() method.

[Note] Note
While there are any observers attached, progress meter will continue to notify them of each event when they occured.


Chapter 8. Quick Start with HTML_Progress2_Monitor

Table of Contents

Basic concept
Default render
Default improved render
Sigma template engine integration

The HTML_Progress2_Monitor class allow to display a progress bar into a dialog box. Renders are customizable by QF rendering system , and both mode determinate/indeterminate are supported. Process may be stop at any time by user action (click on Cancel button).

In three following examples, we will learn how to change layout easily, and observe changes values with new observer pattern (PEAR::Event_Dispatcher).

Basic concept

Design pattern apply the same HTML_QuickForm_Renderer architecture. So it's easy to change presentation of a progress monitor.

Belong presentation aspect, we don't forget that progress monitor allow also to observe changes through the observer pattern (same interface as progress meter), with: addListener() and removeListener() methods.

There are 8 renderers available since release 3.1.1 of QuickForm. The following template engines are directly suported: Smarty, HTML_Template_Sigma, HTML_Template_IT, HTML_Template_Flexy.

Among these 8 renderers, we will have a look on all basic concepts with 3 examples in next sections: default, default improved, sigma template integration.


Default render

Without any change, we can get a decent dialog box with a default progress meter such as :

As you can see in source code below, there are no difficulty.

  1. <?php
  2. require_once 'HTML/Progress2/Monitor.php';
  3.
  4. $pm = new HTML_Progress2_Monitor();
  5.
  6. $pb =& $pm->getProgressElement();
  7. $pb->setAnimSpeed(200);
  8. $pb->setIncrement(10);
  9. ?>
  10. <html>
  11. <head>
  12. <?php
  13. echo $pm->getStyle(false);
  14. echo $pm->getScript(false);
  15. ?>
  16. </head>
  17.
  18. <body>
  19. <?php
  20. $pm->display();
  21. $pm->run();
  22. ?>
  23. </body>
  24. </html>

Line 4 :

Without any arguments, all defaults are applied on HTML_Progress2_Monitor new instance construction.

$formName (argument 1 of class constructor)

Name of monitor dialog box (QuickForm). Default is ProgressMonitor

$attributes (argument 2 of class constructor)

List of renderer options. Default are

  • dialog box title = In progress ...
  • dialog box start button = Start
  • dialog box cancel button = Cancel
  • dialog box button style = no style
  • autorun feature = false
  • dialog box caption = bottom left aligned under progress meter

Line 6 :

For demonstration purpose only, we get embedded basic progress meter into the progress monitor and change increment and speed(delay) to do a smooth animation.

Lines 13, 14 :

We get cascading stylesheet and javascript code mandatory to a good progress meter presentation and handling.

Line 20 :

Show initial state of progress monitor before running. Will works only with default QF renderer.

Line 21 :

Catch user actions (start, stop) and meter progression.

This monitor do nothing yet. In next example we will see how to improve a bit the presentation.


Default improved render

With some options and a new QF renderer, we will improve a lot in few lines, the decent but poor graphic of first example. Enjoy the new result:

Lets review now, how to do this in source code below:

  1. <?php
  2. require_once 'HTML/Progress2/Monitor.php';
  3.
  4. function myFunctionHandler($pValue, &$pb)
  5. {
  6.     global $pm;
  7.
  8.     $pb->sleep();
  9.
  10.     if ((fmod($pValue,10) == 0) and ($pValue > 0)) {
  11.         $pm->setCaption('myFunctionHandler -> progress value is = '.$pValue);
  12.     }
  13. }
  14.
  15. $pm = new HTML_Progress2_Monitor('frmMonitor', array(
  16.     'button' => array('style' => 'width:80px;'),
  17. ));
  18.
  19. $pb =& $pm->getProgressElement();
  20. $pb->setAnimSpeed(75);
  21. $pb->setCellCount(20);
  22. $pb->setProgressAttributes('background-color=#EEE');
  23. $pb->setCellAttributes('inactive-color=#FFF active-color=#444444');
  24. $pb->setLabelAttributes('pct1', 'color=navy');
  25. $pb->setLabelAttributes('monitorStatus', 'color=navy font-size=10');
  26. $pb->setProgressHandler('myFunctionHandler');
  27.
  28. $pm->setProgressElement($pb);
  29. ?>
  30. <html>
  31. <head>
  32. <?php
  33. echo $pm->getStyle(false);
  34. echo $pm->getScript(false);
  35. ?>
  36. </head>
  37. <body>
  38. <?php
  39. $renderer =& HTML_QuickForm::defaultRenderer();
  40. $renderer->setFormTemplate('
  41. <form{attributes}>
  42.  <table width="450" border="0" cellpadding="3" cellspacing="2" bgcolor="#EEEEEE">
  43.  {content}
  44.  </table>
  45. </form>
  46. ');
  47. $renderer->setElementTemplate('
  48.  <tr>
  49.    <td valign="top" style="padding-left:15px;">
  50.    {element}
  51.    </td>
  52.  </tr>
  53. ');
  54. $renderer->setHeaderTemplate('
  55.  <tr>
  56.    <td style="background:#7B7B88;color:#ffc;" align="left" colspan="2">
  57.      <b>{header}</b>
  58.    </td>
  59.  </tr>
  60. ');
  61. $pm->accept($renderer);
  62.
  63. echo $renderer->toHtml();
  64. $pm->run();
  65. ?>
  66. </body>
  67. </html>

Lines 4-13, 26 :

User callback attached to progress meter should be the main task to do. Here we have simplified task to display a message in the monitor caption zone.

Line 17 :

Customization begin by using some HTML_Progress2_Monitor options on new instance construction.

Monitor dialog box is renamed to frmMonitor, and buttons (start, cancel) are 80 pixels width.

Lines 11, 25 :

The monitor caption zone is named by default monitorStatus, and behind it's a progress meter label.

[Warning] Warning
A text label is by default aligned on top left of the progress meter, but for the progress monitor, default is bottom left alignement.

Lines 39, 40, 47, 54 :

Layout is mainly modified by the QF renderer through three template elements: FormTemplate, ElementTemplate, HeaderTemplate.

Line 63 :

Show initial state of progress monitor before running. We can't used here the display() method as in previous example.

Now we know how to customize the skin, in next example we will see how to combine a task with events observation.


Sigma template engine integration

After we have seen how to modify layout presentation, and how to link monitor with the main user task. We will now see how to combine a work to do (task) and listen events when they are triggered.

In this example we will simulate pictures upload monitoring. Here is a preview of final result.

  1. <?php
  2. require_once 'HTML/Progress2/Monitor.php';
  3. require_once 'HTML/QuickForm/Renderer/ITDynamic.php';
  4. require_once 'HTML/Template/Sigma.php';
  5.
  6. function getmicrotime($time)
  7. {
  8.     list($usec, $sec) = explode(' ', $time);
  9.     return ((float)$usec + (float)$sec);
  10.
  11. }
  12.
  13. class myObservatory
  14. {
  15.     function myObserver(&$notification)
  16.     {
  17.         static $time_start;
  18.         global $pm;
  19.
  20.         $notifyName = $notification->getNotificationName();
  21.         $notifyInfo = $notification->getNotificationInfo();
  22.         $notifyObj  =&$notification->getNotificationObject();
  23.
  24.         switch ($notifyName) {
  25.             case 'onSubmit':
  26.                 $time_start = getmicrotime($notifyInfo['time']);
  27.                 break;
  28.             case 'onLoad':
  29.                 $time_elapse = getmicrotime($notifyInfo['time']) - $time_start;
  30.                 $pm->setCaption("upload done (elapse time = $time_elapse  sec.)");
  31.                 break;
  32.             case 'onChange':
  33.                 $pValue = $notifyInfo['value'];
  34.                 if ($pValue == 10) {
  35.                     $pic = 'picture1.jpg';
  36.                 } elseif ($pValue == 45) {
  37.                     $pic = 'picture2.jpg';
  38.                 } elseif ($pValue == 70) {
  39.                     $pic = 'picture3.jpg';
  40.                 } else {
  41.                     $pic = false;
  42.                 }
  43.                 if ($pic) {
  44.                     $pm->setCaption("upload $pic in progress ... "
  45.                                   . "Start at $pValue%");
  46.                 }
  47.         }
  48.         $notifyObj->sleep();
  49.     }
  50. }
  51.
  52. $pm = new HTML_Progress2_Monitor('uploadMonitor', array(
  53.     'title'  => 'Upload your pictures',
  54.     'start'  => 'Upload',
  55.     'cancel' => 'Stop',
  56.     'button' => array('style' => 'width:80px;')
  57. ));
  58.
  59. $pb =& $pm->getProgressElement();
  60. $pb->setAnimSpeed(50);
  61. $pb->setCellCount(20);
  62. $pb->setProgressAttributes('background-color=#EEE');
  63. $pb->setCellAttributes('inactive-color=#FFF active-color=#444');
  64. $pb->setLabelAttributes('pct1', 'color=navy');
  65. $pb->setLabelAttributes('monitorStatus', 'color=navy font-size=10');
  66. $pb->addListener(array('myObservatory','myObserver'));
  67.
  68. $pm->setProgressElement($pb);
  69.
  70. $tpl =& new HTML_Template_Sigma('.');
  71. $tpl->loadTemplateFile('itdynamic.html');
  72.
  73. $tpl->setVariable(array(
  74.     'qf_style'  => $pm->getStyle(),
  75.     'qf_script' => $pm->getScript(false)
  76. ));
  77.
  78. $renderer =& new HTML_QuickForm_Renderer_ITDynamic($tpl);
  79. $renderer->setElementBlock(array('buttons' => 'qf_buttons'));
  80.
  81. $pm->accept($renderer);
  82.
  83. $tpl->show();
  84. $pm->run();
  85. ?>
  86. </body>
  87. </html>

Lines 13-50, 66 :

Main task (upload pictures simulation) is combined with events observation. User callback is not attached to the progress meter but as an observer (myObserver() method of myObservatory class).

Lines 22, 48, 59 :

Progress meter linked to the monitor is retrieved in observer user callback as instance $notifyObj. Smooth animation with HTML_Progress2::sleep() is then possible.

Lines 74, 75 :

Cascading style sheet and javascript code are merged into template file itdynamic.html for a good progress meter presentation and handling.

Lines 70, 78 :

This time we use QF ITDynamic renderer and Sigma as template engine.

Template file itdynamic.html used by Sigma is:

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  2.    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  4. <head>
  5. <title>Progress2 Monitor - ITDynamic renderer </title>
  6. <style type="text/css">
  7. <!--
  8. body {
  9.     font-family: Verdana, Arial;
  10. }
  11. th {
  12.     font-family: sans-serif;
  13.     font-size: small;
  14.     color: #FFF;
  15.     background-color: #AAA;
  16. }
  17. .maintable {
  18.     border: thin dashed #D0D0D0;
  19.     background-color : #EEE;
  20. }
  21. {qf_style}
  22.  -->
  23. </style>
  24. {qf_script}
  25. </head>
  26. <body>
  27.
  28. <h1>ITDynamic QF renderer</h1>
  29. <p>This example simulate a pictures uploads.<br/>
  30. First image upload at 10%, second at 45%, and third at 70%.</p>
  31.
  32. <form{qf_attributes}>
  33. <!-- BEGIN qf_hidden_block -->
  34. <div style="display: none;">
  35.   <!-- BEGIN qf_hidden_loop -->{qf_hidden}<!-- END qf_hidden_loop -->
  36. </div>
  37. <!-- END qf_hidden_block -->
  38.
  39. <table class="maintable" width="600" align="center">
  40. <!-- BEGIN qf_main_loop -->
  41. <tr><td valign="top">
  42.   <table width="100%" cellpadding="4">
  43.   <!-- BEGIN qf_header --><tr><th>{qf_header}</th></tr><!-- END qf_header -->
  44.   <!-- BEGIN qf_element --><tr><td>{qf_element}</td></tr><!-- END qf_element -->
  45.   </table>
  46. </td>
  47. </tr>
  48. <!-- END qf_main_loop -->
  49. </table>
  50.
  51. <!-- BEGIN qf_buttons -->
  52. <table width="600" align="center">
  53. <tr>
  54.   <td align="right">
  55. <!-- BEGIN qf_buttons_loop -->
  56.   <!-- BEGIN qf_buttons_element -->{qf_separator}{qf_element}<!-- END qf_buttons_element -->
  57. <!-- END qf_buttons_loop -->
  58.   </td>
  59. </tr>
  60. </table>
  61. <!-- END qf_buttons -->
  62.
  63. </form>
  64.
  65. <!-- BEGIN qf_errors -->
  66. <!-- BEGIN qf_error_loop -->
  67. {qf_error}<br />
  68. <!-- END qf_error_loop -->
  69. <!-- END qf_errors -->


Chapter 9. Quick Start with HTML_Progress2_Generator

Table of Contents

Basic concept
Default render and css skin
Template integration

The HTML_Progress2_Generator class allow to build your own progress bar and save PHP and/or CSS basic code for later use. Renders are customizable by QF rendering system and external stylesheet.

In two following examples, we will learn how to change the skin easily, and integrate HTML_Progress2_Generator with your favorite template engine.

Basic concept

Design pattern apply the same HTML_QuickForm_Renderer architecture. So it's easy to change presentation of a progress generator. External stylesheets give more options (color, font, ...) to customize look and feel of your own progress generator.

[Note] Note
Usage of external stylesheet is only available since version 2.1.0

There are 8 renderers available since release 3.1.1 of QuickForm. The following template engines are directly suported: Smarty, HTML_Template_Sigma, HTML_Template_IT, and also with packages HTML_Page2, HTML_QuickForm_Renderer_Tableless

Among these 5 renderers (Default, HTMLPage2, ITDynamic, SmartyDynamic, Tableless), we will have a look on all basic concepts with 2 examples in next sections: default render and css skin, template integration.

1. Resume of uses
1.1. You want to use default QF renderer
1.2. You want to use Smarty
1.3. You want to use IT[x] or Sigma
1.4. You want to use the QF Tableless renderer

1. Resume of uses

1.1. You want to use default QF renderer
1.2. You want to use Smarty
1.3. You want to use IT[x] or Sigma
1.4. You want to use the QF Tableless renderer
1.1. | You want to use default QF renderer

Use this driver:

Default

ressource is : HTML/Progress2/Generator/Default.php

default stylesheet is : {data_dir}/HTML_Progress2/default.css

[Tip] Tip
No need to include the driver, HTML_Progress2_Generator do it itself.

1.2. | You want to use Smarty

Use this driver:

SmartyDynamic

ressource is : HTML/Progress2/Generator/SmartyDynamic.php

default stylesheet is : {data_dir}/HTML_Progress2/smartydynamic.css

template root dir is : . (current dir)

template cache dir is : cache/

template filename is : smarty-dynamic.tpl

1.3. | You want to use IT[x] or Sigma

Use this driver:

ITDynamic

ressource is : HTML/Progress2/Generator/ITDynamic.php

default stylesheet is : {data_dir}/HTML_Progress2/itdynamic.css

template root dir is : . (current dir)

template cache dir is : cache/

template filename is : itdynamic.html

1.4. | You want to use the QF Tableless renderer

[Note] Note
HTML_QuickForm_Renderer_Tableless is only available since version 2.1.0

Use this driver:

Tableless

ressource is : HTML/Progress2/Generator/Tableless.php

default stylesheet is : {data_dir}/HTML_Progress2/tableless.css

Explains on {data_dir} reference :

[Note] Note

Where is the PEAR HTML_Progress2 data directory ?

On command line, enter pear config-show, and have a look on data_dir definition. HTML_Progress2 is one of its subdirectories.


Default render and css skin

Without any change, we can get a decent progress generator tabbed wizard such as :

Color, font, size and position are defined by default in stylesheet default.css you can find into PEAR HTML_Progress2 data directory.

As you can see in source code below, there are no difficulty.

  1. <?php
  2. require_once 'HTML/Progress2/Generator.php';
  3.
  4. session_start();
  5.
  6. $tabbed = new HTML_Progress2_Generator();
  7. $tabbed->run();
  8. ?>

Line 4 :

HTML_Progress2_Generator does not start a session automatically, you should explicitly call session_start before instantiating the controller class. A session is required to pass data between the tabbed multi-pages generator wizard.

Line 6 :

Without any arguments, all defaults are applied on HTML_Progress2_Generator new instance construction.

$controllerName (argument 1 of class constructor)

Name of generator tabbed wizard (QuickForm Controller). Default is ProgressGenerator

$attributes (argument 2 of class constructor)

List of renderer options. Default are

  • preview action class = ActionPreview (HTML/Progress2/Generator/Preview.php)
  • display action class = ActionDisplay (HTML/Progress2/Generator/Default.php)
  • process action class = ActionProcess (HTML/Progress2/Generator/Process.php)
  • dump action class = false (no interactive debugging tools by default)

[Note] Note
Since version 2.1.0, you can use the singleton pattern

  1. <?php
  2. $tabbed =& HTML_Progress2_Generator::singleton();
  3. ?>

and of course, continue to use direct instanciation (backward compatibility is not break).

Line 7 :

Catch all user actions (next, back, jump, apply, process) and display controller wizard contents.

Now we have seen basic usage, we will try to change the skin with only a new stylesheet.

  1. <?php
  2. require_once 'HTML/Progress2/Generator.php';
  3.
  4. session_start();
  5.
  6. $tabbed =& HTML_Progress2_Generator::singleton();
  7.
  8. $tabbed->addActions(array('dump' => 'ActionDump'));
  9.
  10. $css = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'generator.css';
  11. $tabbed->addAction('display', new ActionDisplay($css));
  12.
  13. $tabbed->run();
  14. ?>

Line 8 :

This line allow to add/activate the interactive debugging tools that can give you informations on: progress meter, wizard controller forms data, list of included files (see get_included_files), list of declared classes (see get_declared_classes), and list of generator actions defined.

Line 10 :

$css defines the location of the new stylesheet to apply. This file will give a grey-orange look and feel such as :

[Note] Note
You may find this file into examples/generator of PEAR HTML_Progress2 docs directory.

Line 11 :

This line overload the default display action set during the class instantiation.

[Important] Important
We are still using the QF default renderer, and the ActionDisplay class (see HTML/Progress2/Generator/Default.php).

We have also possibility to get and set stylesheet with methods ActionDisplay::getStyleSheet(), ActionDisplay::setStyleSheet() like this :

  1. <?php
  2. require_once 'HTML/Progress2/Generator.php';
  3. require_once 'HTML/Progress2/Generator/Default.php';
  4.
  5. session_start();
  6.
  7. $css = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'generator.css';
  8.
  9. $display = new ActionDisplay();
  10. $display->setStyleSheet($css);
  11.
  12. // var_dump($display->getStyleSheet(true));
  13. // var_dump($display->getStyleSheet());
  14.
  15. $tabbed =& HTML_Progress2_Generator::singleton();
  16. $tabbed->addAction('display', $display);
  17. $tabbed->run();
  18. ?>


Template integration

If you already use HTML_QuickForm you certainly know that the QF default renderer has limited possibilities. But of course HTML_QuickForm provides other renderers that can be used with template engines such as Smarty, Sigma, ... And of course HTML_Progress2_Generator has two interfaces (SmartyDynamic, ITDynamic) to use these QF renderers.

Don't forget that you can also use the PEAR HTML_Page2 package and since the version 2.1.0 the new Tableless QF renderer (PEAR package HTML_QuickForm_Renderer_Tableless).

In this example, we will see how it's so easy to include an instance of HTML_Progress2_Generator in a user page (with header and menus, body, footer); see screenshot below. We will use Sigma, but there is no much more difficulty to implement Smarty, or any other template engine.

Color, font, size and position are defined by default in stylesheet itdynamic.css you can find into PEAR HTML_Progress2 data directory.

Essantial difference with previous examples is to include the right driver (ITDynamic).

  1. <?php
  2. require_once 'HTML/Progress2/Generator.php';
  3. require_once 'HTML/Progress2/Generator/ITDynamic.php';
  4.
  5. session_start();
  6.
  7. $tabbed =& HTML_Progress2_Generator::singleton();
  8. $tabbed->run();
  9. ?>

Line 3 :

Adding this line allow to define an ActionDisplay class (default name to display driver) that will create a new instance of Sigma with current directory '.' as template root dir, and 'cache/' as template cache dir. The template itself is named 'itdynamic.html'.

[Caution] Caution
You can, of course reuse such values with your own documents, or use new ones. In such condition, you will have to create a copy of ActionDisplay class (HTML/Progress2/Generator/ITDynamic.php) and replace lines :
  1. <?php
  2. $tpl =& new HTML_Template_Sigma('.', 'cache/');
  3. $tpl->loadTemplateFile('itdynamic.html');
  4. ?>
No more, no less !


Chapter 10. How to to implement an AJAX Progress Bar

Table of Contents

History
Design details
Progress bar HTML design
Handle polling loop
Refresh progress bar
Examples (full source code)

History

All begun with request #3985 posted on 2005-03-28.

In 2005, I don't know yet AJAX, that I've learned only recently (end of year 2006). I've searched the most simple architecture that won't break current API, and gave immediat benefits for both PHP4 and PHP5 users.

As there are many Ajax frameworks, I wouldn't imposed usage of one between many, and let free choice opened. So 2.3.0 alpha 1 will begin with a standard DOM XML Ajax driver. Later, others drivers (such as YUI, Prototype, ...), will be available and allow to use specifics features.

While I didn't know PEAR package HTML_AJAX, I've took a day to learn it, and I've begun to rewrite implementation of AJAX progress meter. Why this choice ? Because it's more easy to use either a simple asynchronous transfer with client and server, or have a combo with JS librairies such as Scriptaculous, YUI, ... And this with only one PEAR package (Special thanks to Joshua Eichorn, who made it possible).

So alpha 2 and next versions (alpha, beta, stable) will come with HTML_AJAX 0.5.0 or better.


Design details

Tracking the progress of a server-side operation by a client requires only one operation. A polling loop that will iterate one or more times until server task is completed (100%). This is done by JS function HTML_Progress2.statusCheck what will send periodically (update by interval; default is 2 seconds) a request to server either with :

  • class/method :

    HTML_Progress2.serverClassName, HTML_Progress2.serverMethodName

  • or simple php function :

    HTML_Progress2.serverCallback,

as callback.

When the user-task is over and server return progress bar reach 100% (key: percentage, value: 100), client run function identified by HTML_Progress2.onComplete (default behavior is to reload the same page with query string "reload=true").

If you want to change this behavior, you have just to change value of public HTML_Progress2.onComplete variable, and identify another function. See scriptaculous1 and scriptaculous2 examples.

Launching polling loop through asynchronous communication, is done by only one client action: run JS function HTML_Progress2.start with identifier of progress bar (given by HTML_Progress2::getIdent), and with an optional latency (in millisecond) between two request calls.


Progress bar HTML design

[Note] Note

You can continue to use your old design built with versions 2.0.0 to 2.2.0, details are unchanged.

Since version 2.3.0 alpha 2, HTML_Progress2 support now the multiple-labels system introduced with version 2.0.0

See (on package distribution) examples/ajax/RequestStatus.class.php file, method getFullStatus() for a basic implementation example.

You have just to return a key-value pair for each label identified at design level with a "labels" key array.

  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. $pb = new HTML_Progress2();
  5. $pb->addLabel(HTML_PROGRESS2_LABEL_TEXT, 'txt2', 'caption ...');
  6. // label text identifier of "caption ..." is here: txt2
  7. ?>

So if we want to change 'txt2' label value, at middle of progress (50%), we have to return an array with something like that:

  1. <?php
  2. // ...
  3. $status = array('percentage' => 50,
  4.                 'labels' => array('txt2' => 'half task done')
  5.                );
  6. return $status;
  7. // ...
  8. ?>

[Important] Important

An (HTML_)AJAX server may return label values that are unkown at design level. No error/warning will be raise !

See RequestStatus.class.php file, getFullStatus() method, with this line

  1. <?php
  2. $this->status['labels']['txt4'] = 'Q4';
  3. ?>

'txt4' label is undefined on all examples. But if in future we want to add a new text label, we just have to add it in design progress bar level, like this:

  1. <?php
  2. $pb->addLabel(HTML_PROGRESS2_LABEL_TEXT, 'txt4', 'Total tasks : ');
  3. ?>


Handle polling loop

You are free to handle your user task as you want, but to refresh the progress meter status, you must at least return an array with the key "percentage" that identify the new value (from 0 to 100) of progress.

You can also return some new label values.

[Note] Note

You don't have to return all label defined if you want to change only one.

See RequestStatus.class.php file, getFullStatus() method for sample of an implementation.


Refresh progress bar

Highlight cells is still done by default progress javascript code HTML_Progress2.refresh function. See: HTML_Progress::getScript(), or external file "HTML_Progress2.js",

Callback run by HTML_AJAX is HTML_Progress2.statusCheckCallback.

[Important] Important

Server script should return a result object with at least the 'percentage' property defined. 'labels' is optional.


Examples (full source code)

You may find third examples (default1, default2, default3), with their ajax servers, on the package distribution. All are locate in examples/ajax/ directory.


Chapter 11. How to to implement an AJAX Upload with Progress Bar solution

Table of Contents

AJAX with PEAR package HTML_AJAX
HTML side
Server side
Examples (full source code)

AJAX with PEAR package HTML_AJAX

[Caution] Caution

First of all, you need to learn, if its not yet done, the PEAR package HTML_AJAX features before to continue reading.

HTML_Progress2 use help of PEAR::HTML_AJAX to make asynchronous connection with your server. That means, you need to define :

  • A script that will handle all polling loop requests by your browser. I've decided (but you are free to make it different) to build an auto server (auto_server.php) rather than built a single file for each ajax progress bar.

  • Identify what ressources (proxy (server, auto server), client librairies) to use with HTML_Progress2::registerAjax() at design-time of your progress bar.

  • Identify the proxy used, invoked on polling loop by JavaScript variables : HTML_Progress2.serverClassName, HTML_Progress2.serverMethodName or HTML_Progress2.serverCallback (if it's a simple php function, and not method-class).

  • Don't forget to give identifier to track down the file upload, on JS variable HTML_Progress2.requestArgs. It's a key-value pair with always upload_identifier as key. Value is free.

  • When upload is over, HTML_Progress2 need to know with JS variable HTML_Progress2.onComplete what to do. Default behavior is to reload the same page with query string "reload=true".


HTML side

You have to identify what server script will manage the temporary file uploaded when operation is over, with form action attribute. Here in our example it's the same script (apc5_upload1.php) that design the progress bar and form.

You have to tell what action will start upload and progress bar (HTML_Progress2.start). Here in our example it's the form onsubmit handler what begin to iterate the polling loop each 0.5 second (500 ms).

The html code is similar to a classic upload, however, add a field hidden inside form where name attribute depend of backend used (APC or uploadprogress PHP extension).

[Important] Important

With APC, the hidden input indentifier should be named APC_UPLOAD_PROGRESS, and UPLOAD_IDENTIFIER with the uploadprogress PHP extension.

This field is used to store a key that will recognize the form to observe on server-side.

[Note] Note

Several input file can be placed in the same form, in this case the progression is based on the total weight of all files.

The asynchronous mode is achieved through the use of a hidden iframe which is connected to form through the ownership target of the tag form that takes value for the property name of the iframe.

Here is a form design part example (you can find on examples/ajax/upload/apc5_upload1.php) of the package distribution.

<form enctype="multipart/form-data"
      target="tfrm" action="apc5_upload1.php" method="post"
      onsubmit="HTML_Progress2.start('<?php echo $pb->getIdent(); ?>', 500);">
  <input type="hidden" name="APC_UPLOAD_PROGRESS" id="progress_key" value="<?php echo $progress_key; ?>" />
  <input type="file" id="userfile"  name="userfile" />
  <input type="submit" value="Upload!" />
</form>
<iframe id="tfrm" name="tfrm" style="width:1px;height:1px;border:0"></iframe>


Server side

We will find at least two scripts: one, on final step, to manage temporary file upload

  1. // final destination of uploaded files
  2. $path = 'web_files/' ;
  3.
  4. // basic PHP function file upload handler
  5. if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  6.     if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
  7.         if (move_uploaded_file($_FILES['userfile']['tmp_name'], $path . $_FILES['userfile']['name'])) {
  8.             $html_output = 'Upload finished';
  9.             echo '<pre>'; var_dump($_FILES); echo '</pre>';
  10.         } else {
  11.             $html_output = 'Upload failed';
  12.         }
  13.     }
  14.     die($html_output);
  15. }

This chunk of code is found on examples/ajax/upload/apc5_upload1.php of the package distribution.

The second script will manage the polling loop iteration. Here we used an HTML_AJAX auto server. Example apc5_upload1.php used the basic HTML_Progress2_Upload::getStatus() method. This one return an array with four key-value pairs (percentage, labels, bytes_uploaded, bytes_total).

  1. <?php
  2. require_once 'HTML/AJAX/Server.php';
  3.
  4. class AutoServer extends HTML_AJAX_Server
  5. {
  6.     // this flag must be set for your init methods to be used
  7.     var $initMethods = true;
  8.
  9.     function initAPC5UploadStatus()
  10.     {
  11.         require_once 'HTML/Progress2/Upload.php';
  12.         $status = new HTML_Progress2_Upload();
  13.         $this->registerClass($status, 'APC5UploadStatus', array('getStatus'));
  14.     }
  15. }
  16.
  17. $server = new AutoServer();
  18. $server->handleRequest();
  19. ?>

And you will ask: How to display other informations like percentage, filename, estimate time left and speed limit ?

You did it with progress bar labels and a format list. These formats are :

  • %T - for total file size
  • %C - for current file weight uploaded
  • %P - for percentage of full upload task
  • %F - for current filename
  • %E - for estimate time left
  • %S - for speed limit

HTML_Progress2_Upload default behavior is to display an uplStatus label formatted as : "%C / %T (%P%)" on top left of progress bar.

[Note] Note

If you want to see this label information, don't forget to add it on HTML_Progress2 design.

  1. $pb = new HTML_Progress2();
  2. $pb->addLabel(HTML_PROGRESS2_LABEL_TEXT, 'uplStatus');


Examples (full source code)

You may find four examples using the APC backend, and one example using the uploadProgress PHP extension, on the package distribution. All are locate in examples/ajax/upload/ directory.


Part III. Migrating Guide

Table of Contents

12. Introduction
Intended audience
Why these changes ?
What was removed ?
13. How to adjust your code
core class related
User Interface related
Data Management related
14. New Features in HTML_Progress2
Multiple Label System
Error Handling
Reuse CSS


Chapter 12. Introduction

Table of Contents

Intended audience
Why these changes ?
What was removed ?

Intended audience

If you have not already used HTML_Progress 1.x, this guide is not for you. It was written to help users to migrate easily all their scripts from version 1.x to the major 2.0.0.


Why these changes ?

HTML_Progress2 has improved a lot since HTML_Progress 1.2.x. With merge of secondary classes (UI and DM) to the main core class, i've removed duplicated methods and unified API.

With the addition of a new plugin error management, it was the first milestone to have a version a bit less dependent to PEAR. Lot of users are afraid to install a such framework on their system, for many reasons. So second milestone and goal, was to create a new class much lighter and without any dependencies to a such audience: HTML_Progress2_Lite was born.

The HTML_Progress2_Lite class does not allow to do all that is possible with HTML_Progress2 class. See the features comparative.

And last but not least, a multiple labels system was introduced, that give ability to have more than just one percent text information or one custom text label.


What was removed ?

Very few features was removed during this merges :

  • setModel() method.
  • ability to extends UI class to make custom user interface.
  • ability to extends DM class to make custom data management interface.

And some replacements was made with removes of :

  • isStringPainted() method (due to new multiple label system).
  • setStringPainted() method (due to new multiple label system).
  • setStringAttributes() method, replaced by setLabelAttributes().
  • getString() method (due to new multiple label system).
  • setString() method (due to new multiple label system).
  • HTML_PROGRESS_ERRORSTACK_* and HTML_PROGRESS_LOG_TYPE_* constants (due to new error management system).


Chapter 13. How to adjust your code

Table of Contents

core class related
User Interface related
Data Management related

core class related

class constructor

HTML_Progress 1.x allows multiple signatures (5) while HTML_Progress2 allow one unique signature even if all parameters are optional.

Resume of HTML_Progress 1.x signatures :

  1. $bar = new HTML_Progress();
  2. $bar = new HTML_Progress($orient);
  3. $bar = new HTML_Progress($min, $max);
  4. $bar = new HTML_Progress($orient, $min, $max);
  5. $bar = new HTML_Progress($model);

[Caution] Caution
Signature #5 is no more allowed because feature was removed.

HTML_Progress2 signature :

  1. <?php
  2. $bar = new HTML_Progress2($errorPrefs, $orient, $min, $max, $percentLabel);
  3. /*
  4.        $errorPrefs   :hash of options to configure the API error handling system
  5.                       default is empty array (use PEAR_Error object)
  6.        $orient       :orientation of the progress bar (see constants)
  7.        $min          :minimum value of the progress bar (default is zero)
  8.        $max          :maximum value of the progress bar (default is 100)
  9.        $percentLabel :progress bar percent label identifier (default is 'pct1')
  10.  */
  11. ?>

apiVersion()

Returns the current API version compatible with the PHP function : version_compare()

This method return now a string rather than a float, and allow a largest version naming (such as x.y.zRCn)

getPercentComplete()

Returns the percent complete for the progress meter

This method has now an optional parameter that allows to return either

  • a float by default (range 0.00 to 1.00)
  • an integer (range 0 to 100)

display()

Rendering of the progress meter.

[Important] Important
This method has a new behavior. It will now send only toHtml() output to browser, while in previous version this method managed browser refresh. Refresh are now made by the moveNext() or moveStep() method.


User Interface related

setCellCount()

Sets the number of cell in the progress bar

This method accept now zero as minimum value for smooth progress meter. That means that a progress bar with zero cell, will render a full bar as HTML_Progress2_Lite do.

setLabelAttributes(), addLabel()

With HTML_Progress 1.x you might only defines one custom text label. Now with new multiple label system you can do it at infinite. There is no label number limit (except memory).

[Important] Important
You have to define first each label you will put around the progress meter by the addLabel() method, before to set its attributes.

While with HTML_Progress 1.x, you could have a script like this:

  1. <?php
  2. require_once 'HTML/Progress.php';
  3.
  4. $bar = new HTML_Progress();
  5. $bar->setAnimSpeed(100);
  6. $bar->setIncrement(5);
  7. $bar->setStringPainted(true);          // get space for the string
  8. $bar->setString('');                   // but don't paint it
  9.
  10. $ui =& $bar->getUI();
  11. $ui->setStringAttributes('width=350 align=left');
  12. // ...
  13. ?>

which prepare to render a custom string on right side of the progress bar.

Now with HTML_Progress2, you will have a modified script like:

  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. $bar = new HTML_Progress2();
  5. $bar->setAnimSpeed(100);
  6. $bar->setIncrement(5);
  7. $bar->addLabel(HTML_PROGRESS2_LABEL_TEXT, 'txt1', 'Simple static text');
  8. $bar->setLabelAttributes('txt1', array(
  9.     'valign' => 'top',
  10.     'left' => 0
  11. ));
  12. // ...
  13. ?>

The percent info will be render alone at right side of the progress bar (default) and we have added a static text label on top side of the same progress bar.


Data Management related

moveNext(), moveStep()

Changes value of the progress meter to the next value or next step.

These new methods were introduced with the new multiple label system, and should replaced incValue() deprecated.

[Note] Note
incValue() method is almost equivalent to moveStep() except that it did not provide display refresh.

Here is sample of your script version with HTML_Progress 1.x :

  1. <?php
  2. require_once 'HTML/Progress.php';
  3.
  4. $pb = new HTML_Progress();
  5. $pb->setAnimSpeed(100);
  6. ?>
  7. <html>
  8. <head>
  9. <style type="text/css">
  10. <!--
  11. <?php echo $pb->getStyle(); ?>
  12.  -->
  13. </style>
  14. <script type="text/javascript">
  15. <!--
  16. <?php echo $pb->getScript(); ?>
  17. //-->
  18. </script>
  19. </head>
  20. <body>
  21. <?php
  22. echo $pb->toHtml();
  23.
  24. do {
  25.     $pb->display();    // <--- to remove !!!
  26.     if ($pb->getPercentComplete() == 1) {
  27.         break;
  28.     }
  29.     $pb->sleep();
  30.     // your long process goes here !
  31.     $pb->incValue();   // <--- to replace !!!
  32. } while(1);
  33. ?>
  34. </body>
  35. </html>

And your script version with HTML_Progress2 :

  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. $pb = new HTML_Progress2();
  5. $pb->setAnimSpeed(100);
  6. ?>
  7. <html>
  8. <head>
  9. <?php
  10. echo $pb->getStyle(false);
  11. echo $pb->getScript(false);
  12. ?>
  13. </head>
  14. <body>
  15. <?php
  16. $pb->display();
  17.
  18. do {
  19.     if ($pb->getPercentComplete() == 1) {
  20.         break;
  21.     }
  22.     $pb->sleep();
  23.     // your long process goes here !
  24.     $pb->moveNext();
  25. } while(1);
  26. ?>
  27. </body>
  28. </html>

[Tip] Tip
Of course, if you used the run() method instead of the loop, you have nothing to change.


Chapter 14. New Features in HTML_Progress2

Table of Contents

Multiple Label System
Add a new label
Remove existing label
Error Handling
Reuse CSS
Step 1 : Extract Javascript code
Step 2 : Extract CSS code
Step 3 : Remove HTML_Progress2 css properties
Step 4 : Adjust CSS class selector
Step 5 : play with new pattern

This chapter documents all of the differences between HTML_Progress 1.x and the new features introduced in HTML_Progress2.

The most significant change in HTML_Progress2 is the addition of the Multiple Label System.

Multiple Label System

Add a new label
Remove existing label

While with HTML_Progress 1.x you have no choice, or so few, to display informations with text zone also called “string”; In the new API of HTML_Progress2 you may have as much labels as you want all around the progres meter.

No need anymore to do a choice between the percent text info and captions while the progress meter reach particular values. You can have both at same time, and even more.

As in previous version, HTML_Progress 1.x, you can have text zone as label, but also now four more types. Here are the list :

(text) HTML_PROGRESS2_LABEL_TEXT

A simple text zone

(button) HTML_PROGRESS2_LABEL_BUTTON

A simple button

(step) HTML_PROGRESS2_LABEL_STEP

A step zone information to display value of current moveStep()

(percent) HTML_PROGRESS2_LABEL_PERCENT

The basic percent text information formatted as “67 %”.

(crossbar) HTML_PROGRESS2_LABEL_CROSSBAR

A little javascript cross rotate animation

Add a new label

The only label you don't have to set, in most cases, with addLabel() method is the percent text info, identified by pct1 by default.

[Note] Note
You can remove the percent text info at build time with the HTML_Progress2 class construtor and the fifth parameter set to FALSE.
  1. <?php
  2. $bar = new HTML_Progress2($errorPrefs, $orient, $min, $max, $percentLabel);
  3. /*
  4.        $errorPrefs   :hash of options to configure the API error handling system
  5.                       default is empty array (use PEAR_Error object)
  6.        $orient       :orientation of the progress bar (see constants)
  7.        $min          :minimum value of the progress bar (default is zero)
  8.        $max          :maximum value of the progress bar (default is 100)
  9.        $percentLabel :progress bar percent label identifier (default is 'pct1')
  10.  */
  11. ?>
In such condition, if you need after a while to display the percent text again, you shall use the addLabel() method with any free identifier (can be pct1 as any other else).

Goal of this mini tutorial is to build a horizontal progress bar with percent text info on right side, with four other kind of label (text, crossbar, step, button). Something like that :

For a full source code, have a look here.

No special difficulty. We will used four times the couple :

  1. <?php
  2. $bar->addLabel($type, $name, $value);
  3. /*
  4.        $type         :label type / a constant HTML_PROGRESS2_LABEL_* value
  5.        $name         :label name (identifier)
  6.        $value        :initial label value
  7.  */
  8.
  9. $bar->setLabelAttributes($name, $attributes)
  10. /*
  11.        $name         :label name (identifier)
  12.        $attributes   :associative array or string of HTML tag attributes
  13.  */
  14. ?>

With $bar an instance of HTML_Progress2 object.

  1. <?php
  2. $bar = new HTML_Progress2();
  3. ?>

For a full attributes list depending of each label kind, see the Reference Guide, setLabelAttributes() related.

Remains of the script is as usal:

  • complete build of the progress meter (css, js, html parts) : getStyle(), getScript(), display()
  • see the progress meter in action : run()

Remove existing label

This feature is available at build-time, and may be usefull to extend some progress meter from a common source, and remove the unnecessary labels.

For example, if you consider the previous script, as your common/core script, written in two parts/templates (build-meter.php, run-meter.php) splitted at the DTD frontier.

So, if you want to build a new progress meter without the button. You have just to re-used your previous code and complete with :

  1. <?php
  2. include_once 'build-meter.php';
  3.
  4. $pb->removeLabel('btn1');
  5.
  6. include_once 'run-meter.php';
  7. ?>

Pretty easy.


Error Handling

Its not really a new feature but rather an improvement of source code rewrites. All details are behind the reference guide, Error Handler related part.

Here are the major changes to observe in a migration goal :

Table 14.1. Error Handling major changes

 | HTML_Progress 1.x | HTML_Progress2
error protocol obey | error_reporting | display_errors, log_errors : php.ini directives
raiseError return values | PEAR_Error | NULL | FALSE | HTML_Progress2_Error | array()


Reuse CSS

Step 1 : Extract Javascript code
Step 2 : Extract CSS code
Step 3 : Remove HTML_Progress2 css properties
Step 4 : Adjust CSS class selector
Step 5 : play with new pattern

This section is intended to provide a HOWTO guide that you should follow step by step to discover the new feature of HTML_Progress2 version 2.2.0

Until now we should used HTML_Progress2 API to set all styles (color, size, font, ...) of our progress bars. We will discover now with HTML_Progress2::importStyle() method that it can be done in one step and PHP code is more reusable. We can change look and feel only on modify CSS data source.

Step 1 : Extract Javascript code

We will use the Ancestor example (included into the package distribution), all long of this demonstration.

Here are the original source code (without header).

Example 14.1. script: examples/horizontal/ancestor.php

  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. $pb = new HTML_Progress2();
  5. $pb->setAnimSpeed(200);
  6. $pb->setIncrement(10);
  7. $pb->setLabelAttributes('pct1', array(
  8.     'width' => 60,
  9.     'height' => 24,
  10.     'top' => 0,
  11.     'left' => 0,
  12.     'background-color' => '#FFFFFF',
  13.     'font-size' => 14,
  14.     'align' => 'center'
  15.     ));
  16. ?>
  17. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  18.     "http://www.w3c.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  19. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  20. <head>
  21. <title>Ancestor Progress2 example</title>
  22. <style type="text/css">
  23. <!--
  24. <?php echo $pb->getStyle(); ?>
  25.
  26. body {
  27.     background-color: #444444;
  28. }
  29.  -->
  30. </style>
  31. <?php echo $pb->getScript(false); ?>
  32. </head>
  33. <body>
  34.
  35. <?php
  36. $pb->display();
  37. $pb->run();
  38. ?>
  39.
  40. </body>
  41. </html>

Line 31 :

Due to minor fix we have to do later in javascript code, lets begin by replace this line by a reference to an external JS file.

  1. <script type="text/javascript" src="progress2BasicHandler.js"></script>

What content is :

Example 14.2. script: progress2BasicHandler.js

  1. function setProgress(pIdent, pValue, pDeterminate, pCellCount)
  2. {
  3.     if (pValue == pDeterminate) {
  4.         for (var i = 0; i < pCellCount; i++) {
  5.             showCell(i, pIdent, 'I');
  6.         }
  7.     }
  8.     if ((pDeterminate > 0) && (pValue > 0)) {
  9.         var i = (pValue - 1) % pCellCount;
  10.         showCell(i, pIdent, 'A');
  11.     } else {
  12.         for (var i = pValue - 1; i >= 0; i--) {
  13.             showCell(i, pIdent, 'A');
  14.         }
  15.     }
  16. }
  17.
  18. function showCell(pCell, pIdent, pVisibility)
  19. {
  20.     var name = 'pcel' + pCell + pIdent;
  21.     var cellElement = document.getElementById(name);
  22.     cellElement.className = 'cell' + pIdent + pVisibility;
  23. }
  24.
  25. function hideProgress(pIdent)
  26. {
  27.     var name = 'tfrm' + pIdent;
  28.     var tfrm = document.getElementById(name);
  29.     tfrm.style.visibility = "hidden";
  30. }
  31.
  32. function setLabelText(pIdent, pName, pText)
  33. {
  34.     var name = 'plbl' + pName + pIdent;
  35.     document.getElementById(name).firstChild.nodeValue = pText;
  36. }
  37.
  38. function setElementStyle(pPrefix, pName, pIdent, pStyles)
  39. {
  40.     var name = pPrefix + pName + pIdent;
  41.     var styles = pStyles.split(';');
  42.     styles.pop();
  43.     for (var i = 0; i < styles.length; i++) {
  44.         var s = styles[i].split(':');
  45.         var c = 'document.getElementById(name).style.' + s[0] + '="' + s[1] + '"';
  46.         eval(c);
  47.     }
  48. }
  49.
  50. function setRotaryCross(pIdent, pName)
  51. {
  52.     var name = 'plbl' + pName + pIdent;
  53.     var cross = document.getElementById(name).firstChild.nodeValue;
  54.     switch(cross) {
  55.         case "--": cross = "\\"; break;
  56.         case "\\": cross = "|"; break;
  57.         case "|": cross = "/"; break;
  58.         default: cross = "--"; break;
  59.     }
  60.     document.getElementById(name).firstChild.nodeValue = cross;
  61. }

Step 2 : Extract CSS code

First, identify the progress bar with a static identifier, for example PB1. (see line 5), rather than used the default identifier that change on each run.

  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. $pb = new HTML_Progress2();
  5. $pb->setIdent('PB1');
  6. //...
  7. ?>
  8. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  9.     "http://www.w3c.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  10. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  11. <head>
  12. <title>Ancestor Progress2 example</title>
  13. <style type="text/css">
  14. <!--
  15. <?php echo $pb->getStyle(); ?>
  16.
  17. body {
  18.     background-color: #444444;
  19. }
  20.  -->
  21. </style>
  22. <?php echo $pb->getScript(false); ?>
  23. </head>

Line 15 :

Replace dynamic reference HTML_Progress2::getStyle() to inline stylesheet by a reference to a static file ancestor.css.

  1. <link rel="stylesheet" type="text/css" href="ancestor.css" />

What content is :

Example 14.3. ancestor.css

  1. .cellPB1I, .cellPB1A {
  2.   width: 15px;
  3.   height: 20px;
  4.   font-family: Courier, Verdana;
  5.   font-size: 8px;
  6.   float: left;
  7. }
  8.
  9. .progressBorderPB1 {
  10.   width: 172px;
  11.   height: 24px;
  12.   background-color: #FFFFFF;
  13. }
  14.
  15. .progressPercentLabelpct1PB1 {
  16.   width: 60px;
  17.   height: 24px;
  18.   text-align: center;
  19.   background-color: #FFFFFF;
  20.   font-size: 14px;
  21.   font-family: Verdana, Tahoma, Arial;
  22.   font-weight: normal;
  23.   color: #000000;
  24. }
  25.
  26. .cellPB1I {
  27.   background-color: #CCCCCC;
  28. }
  29.
  30. .cellPB1A {
  31.   background-color: #006600;
  32. }

And don't forget to add the new method HTML_Progress2::importStyle() to your PHP script, with url of your external stylesheet.

  1. <?php
  2. // ...
  3.
  4. $pb->importStyle('ancestor.css');
  5. ?>
  6. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  7.     "http://www.w3c.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  8. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  9. <head>
  10.
  11. <!--  ... -->
  12.
  13. </html>

Step 3 : Remove HTML_Progress2 css properties

If you have followed all previous explains, your code should be something like this one :

  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. $pb = new HTML_Progress2();
  5. $pb->setIdent('PB1');
  6. $pb->setAnimSpeed(200);
  7. $pb->setIncrement(10);
  8.
  9. $pb->setLabelAttributes('pct1', array(
  10.     'width' => 60,
  11.     'height' => 24,
  12.     'top' => 0,
  13.     'left' => 0,
  14.     'background-color' => '#FFFFFF',
  15.     'font-size' => 14,
  16.     'align' => 'center'
  17.     ));
  18.
  19. $pb->importStyle('ancestor.css');
  20. ?>
  21. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  22.     "http://www.w3c.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  23. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  24. <head>
  25. <title>Ancestor Progress2 example</title>
  26. <link rel="stylesheet" type="text/css" href="ancestor.css" />
  27. <style type="text/css">
  28. <!--
  29. body {
  30.     background-color: #444444;
  31. }
  32.  -->
  33. </style>
  34. <script type="text/javascript" src="progress2BasicHandler.js"></script>
  35. </head>
  36. <body>
  37.
  38. <?php
  39. $pb->display();
  40. $pb->run();
  41. ?>
  42.
  43. </body>
  44. </html>

Lines 10-11, 14-15 :

These lines corresponding to same CSS properties from .progressPercentLabelpct1PB1 class selector.

Lines 12-13 :

Defines the progress bar position (relative) into browser frame.

Line 16 :

Give percent text label alignment. There is no CSS property equivalence.

[Important] Important
Don't forget to remove lines 10-11, 14-15 to get PHP code without CSS references.

Step 4 : Adjust CSS class selector

To get possibility to handle all your progress bar look and feel (style) with only a stylesheet, we still need to modify the PHP script and a little line in JS script.

Begin with PHP source code :

  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. $pb = new HTML_Progress2();
  5. $pb->setIdent('PB1');
  6. $pb->setAnimSpeed(200);
  7. $pb->setIncrement(10);
  8.
  9. $pb->setBorderAttributes('class=progressBorder');
  10. $pb->setCellAttributes('class=cell');
  11. $pb->setLabelAttributes('pct1', array(
  12.     'class' => 'progressPercentLabel',
  13.     'top' => 0,
  14.     'left' => 0,
  15.     'align' => 'center'
  16.     ));
  17.
  18. $pb->importStyle('ancestor.css');
  19. ?>
  20. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  21.     "http://www.w3c.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  22. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  23. <head>
  24. <title>Ancestor Progress2 example</title>
  25. <link rel="stylesheet" type="text/css" href="ancestor.css" />
  26. <style type="text/css">
  27. <!--
  28. body {
  29.     background-color: #444444;
  30. }
  31.  -->
  32. </style>
  33. <script type="text/javascript" src="progress2BasicHandler.js"></script>
  34. </head>
  35. <body>
  36.
  37. <?php
  38. $pb->display();
  39. $pb->run();
  40. ?>
  41.
  42. </body>
  43. </html>

Line 9 :

Add this line to change the progress border CSS class selector. Remember, default is : progressBorder%s, where %s is the placeholder to include progress bar identifier (return by HTML_Progress2::getIdent()).

Line 10 :

Add this line to change the cell CSS class selector. Remember, default is : cell%s, where %s is the placeholder to include progress bar identifier (return by HTML_Progress2::getIdent()).

Line 12 :

Add this line to change the progress percent label CSS class selector. Remember, default is : progressPercentLabel%s, where %s is the placeholder to include label and progress bar identifiers.

Last, to finish our modifications, we need to remove the progress bar identifier placeholder into JS script: progress2BasicHandler.js at line 22. From :

  1. cellElement.className = 'cell' + pIdent + pVisibility;

To :

  1. cellElement.className = 'cell' + pVisibility;

Step 5 : play with new pattern

Modify again the stylesheet to identify by another way the progress bar identifier that was removed from CSS class selector, in previous step.

Example 14.4. New content of ancestor.css

  1. #pbarPB1 .cellI, #pbarPB1 .cellA {
  2.   width: 15px;
  3.   height: 20px;
  4.   font-family: Courier, Verdana;
  5.   font-size: 8px;
  6.   float: left;
  7. }
  8.
  9. #pbrdPB1.progressBorder {
  10.   width: 172px;
  11.   height: 24px;
  12.   background-color: #FFFFFF;
  13. }
  14.
  15. #plblpct1PB1.progressPercentLabel {
  16.   width: 60px;
  17.   height: 24px;
  18.   text-align: center;
  19.   background-color: #FFFFFF;
  20.   font-size: 14px;
  21.   font-family: Verdana, Tahoma, Arial;
  22.   font-weight: normal;
  23.   color: #000000;
  24. }
  25.
  26. #pbarPB1 .cellI {
  27.   background-color: #CCCCCC;
  28. }
  29.
  30. #pbarPB1 .cellA {
  31.   background-color: #006600;
  32. }

Lines 1, 26, 30 :

Remove reference to progress bar identifier PB1, and add the <div> identifier #pbarPB1 for each cell class selector (active, inactive).

[Caution] Caution
Don't forget to add a blank between #pbarPB1 and .cellI (or .cellA)

Line 9 :

Remove reference to progress bar identifier PB1, and add the <div> identifier #pbrdPB1.

Line 15 :

Remove reference to progress bar identifier PB1, percent label pct1, and add the <div> identifier #plblpct1PB1.

All components (PHP script and CSS file) are ready to play with them and change color, size, ... Almost what you want.

[Tip] Tip
To switch from a skin to another, you just have to change progress bar identifier in PHP script.
  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. $pb = new HTML_Progress2();
  5. $pb->setIdent('PB1');
  6. // $pb->setIdent('PB2');
  7. // ...
  8. ?>

Example 14.5. ancestor.css with two skins

  1. #pbarPB1 .cellI, #pbarPB1 .cellA, #pbarPB2 .cellI, #pbarPB2 .cellA {
  2.   width: 15px;
  3.   height: 20px;
  4.   font-family: Courier, Verdana;
  5.   font-size: 8px;
  6.   float: left;
  7. }
  8. #pbarPB2 .cellI, #pbarPB2 .cellA {
  9.   width: 10px;
  10. }
  11.
  12. #pbrdPB1.progressBorder, #pbrdPB2.progressBorder {
  13.   width: 172px;
  14.   height: 24px;
  15.   background-color: #FFFFFF;
  16. }
  17. #pbrdPB2.progressBorder {
  18.   width: 122px;
  19.   border-width: 1px;
  20.   border-style: solid;
  21.   border-color: navy;
  22. }
  23.
  24. #plblpct1PB1.progressPercentLabel {
  25.   width: 60px;
  26.   height: 24px;
  27.   text-align: center;
  28.   background-color: #FFFFFF;
  29.   font-size: 14px;
  30.   font-family: Verdana, Tahoma, Arial;
  31.   font-weight: normal;
  32.   color: #000000;
  33. }
  34. #plblpct1PB2.progressPercentLabel {
  35.   width: 60px;
  36.   text-align: center;
  37.   background-color: transparent;
  38.   font-size: 14px;
  39.   font-family: Verdana, Tahoma, Arial;
  40.   font-weight: normal;
  41.   color: white;
  42. }
  43.
  44. #pbarPB1 .cellI {
  45.   background-color: #CCCCCC;
  46. }
  47. #pbarPB1 .cellA {
  48.   background-color: #006600;
  49. }
  50.
  51. #pbarPB2 .cellI {
  52.   background-color: #EEEECC;
  53. }
  54. #pbarPB2 .cellA {
  55.   background-color: #3874B4;
  56. }


Part IV. Reference Guide

Table of Contents

15. Introduction
16. Error Handler
Introduction
Configuring a Handler
Controlling error generation
Error Context Display
Custom Error Message Generation
17. Events to observe
Events Reference
Additional Events informations
18. HTML_Progress2_Lite
Quick API Reference
Quick-Cards Atttributes Reference
19. API - Application Programming Interface
Error Handler
Listener
Data Handler
Graphical Handler
Common functions


Chapter 15. Introduction

This reference describes every API in the HTML_Progress2 class, but also the new plug-in error system, the observer pattern implementation with PEAR::Event_Dispatcher, and the quick-cards reference for HTML_Progress2_Lite.


Chapter 16. Error Handler

Table of Contents

Introduction
Configuring a Handler
Controlling error generation
Error Context Display
Custom Error Message Generation
Option: message_callback
Option: context_callback

Introduction

After many rewrites, the new error management adding to this major version of HTML_Progress2 provides again more than in branch 1.x

The HTML_Progress2 package is implemented with a flexible error handler plug-in system. You may use any error handler that you want. Using PEAR_Error object (default), but also the PEAR_ErrorStack package, or any other error handler you might want to plug in.

Without any configuration, each HTML_Progress2 API error (basic or exception) will raise a HTML_Progress2_Error object that will be return to call script (user script).

[Note] Note
In HTML_Progress 1.x each API error returns a basic PEAR_Error object.

[Tip] Tip
Easy to distinct basic PEAR_Error from other PEAR packages to HTML_Progress2 errors, even if there is a better and more robust solution: HTML_Progress2::hasErrors(). But also provide a unique way to retrieve the level of progress error (warning, error, exception) with the HTML_Progress2_Error::getLevel() method.

As usual, to check an error, you can use the PEAR error API :

  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. $meter = new HTML_Progress2();
  5.
  6. $result = $meter->setValue('37');
  7. if (PEAR::isError($result)) {
  8.     // do something when an error is raised
  9.     $error =& $result;
  10. }
  11. ?>

as well as with :

  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. $meter = new HTML_Progress2();
  5.
  6. $result = $meter->setValue('37');
  7. if ($meter->hasErrors() > 0) {
  8.     // do something when an error is raised
  9.     $error = $meter->getError();
  10. }
  11. ?>

which provide a portable solution, and output to screen will give something like :

Exception  1: invalid input, parameter #1 "$val" was expecting "integer",
instead got "string"  2  in html_progress2->setvalue (file [path_to]\[filename] on line 6)  3

1 | error level
2 | message body with context informations
3 | call context

Perhaps this standard behavior is not what you want. Don't worry, you can change everything :

  • display or ignore the error
  • display or hide part of message (error level, body, context)

[Important] Important
HTML_Progress2 obey at display_errors and log_errors protocol, while HTML_Progress 1.x obey at error_reporting protocol.


Configuring a Handler

A error handler's configuration is determined by the arguments used in its construction. Here's an overview of these parameters.

  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. $errorConf = array('error_handler' => 'myErrorHandler',
  5.                    'push_callback' => 'myError',
  6.                    // ... more options
  7.                   );
  8. $meter = new HTML_Progress2($errorConf);
  9. ?>

Table 16.1. Error Handler configuration parameters

Option | Type | Description
error_handler | callback | A valid callback (function) to manage errors raised by the HTML_Progress2::raiseError() method. Default is: HTML_Progress2::_errorHandler
push_callback | callback | A valid callback (function) that decides to following action. Default return: PEAR_ERROR_DIE if exception, NULL otherwise.
message_callback | callback | A valid callback (function) to control message generation. Default is: HTML_Progress2_Error::_msgCallback
context_callback | callback | A valid callback (function) to control error context generation. Default is: HTML_Progress2_Error::getBacktrace
handler | mixed | any handler-specific settings


Controlling error generation

There are many scenarios in which fine-grained control over error raising is absolutely necessary.

The first level to control error generation is the php.ini directives display_errors and log_errors. When these directives are set to TRUE, then browser and file outputs are effective.

[Tip] Tip
If you want to ignore all errors raised (no display, no logs) and avoid to include PEAR core class, then you should have something like :
  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. function myErrorHandler()
  5. {
  6.     return null;
  7. }
  8.
  9. $errorConf = array('error_handler' => 'myErrorHandler');
  10. $meter = new HTML_Progress2($errorConf);
  11. // ...
  12. ?>

[Caution] Caution
The previous example will ignore display and logging activity, but NEVER ignore internal stack error. In other words, you'll keep always minimum information in the progress stack error. These informations are :
  1. <?php
  2. array('code' => $code, 'level' => $level, 'params' => $params);
  3. /*
  4.       $code  : API error code (HTML_PROGRESS2_ERROR_* constant value)
  5.       $level : API error level (warning, error, exception)
  6.       $params: API context execution parameters hash (function argument: name, type, value)
  7.  */
  8. ?>
So, these lines are always true (in error condition):
  1. <?php
  2. $meter = new HTML_Progress2();
  3. // ...
  4. if ($meter->hasErrors() > 0) {
  5.     // do something on error ...
  6. }
  7. ?>

It's up to you to choose your programming way. Just keep in mind this warning, in case of code evolution (error handler configuration). Behavior could change, and you won't keep backward compatibility.

With push_callback option, you can decides to stop script execution (as done with exceptions by default: returns PEAR_ERROR_DIE constant), or continue without filtering (returns NULL).

If you want to write your own callback function for the push_callback option, this one should have two arguments: first one will get the error code, and second will get error level. These are all the necessary informations to do a filtering. Example that follow show how to be aware that a deprecated function is used in a script.

  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. function myErrorFilter($code, $level)
  5. {
  6.     if ($code === HTML_PROGRESS2_ERROR_DEPRECATED) {
  7.         error_log('script: '.__FILE__.' still used a deprecated function', 1, 'admin@yoursite.com');
  8.     }
  9.     return null;
  10. }
  11.
  12. $errorConf = array('push_callback' => 'myErrorFilter');
  13. $meter = new HTML_Progress2($errorConf);
  14. // ...
  15. ?>


Error Context Display

In some cases, you may want to customize error generation. For instance, for each error (basic/exception), it is useful to include file, line number, and class/function context information in order to trace it. The default option will be sufficient for most cases but you want perhaps customize the rendering of context information.

With this example we will change display and log renders.

  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. $displayConfig = array(
  5.     'lineFormat' => '<b>%1$s</b>: %2$s<br />%3$s',
  6.     'contextFormat' =>   '<b>File:</b> %1$s <br />'
  7.                        . '<b>Line:</b> %2$s <br />'
  8.                        . '<b>Function:</b> %3$s '
  9. );
  10. $logConfig = array(
  11.     'lineFormat' => '%1$s %2$s [%3$s] %4$s',
  12.     'timeFormat' => '%b'
  13. );
  14.
  15. $prefs = array(
  16.     'handler' => array('display' => $displayConfig,
  17.                        'log'     => $logConfig
  18. ));
  19.
  20. $meter = new HTML_Progress2($prefs);
  21. // ...
  22. $result = $meter->setValue('37');
  23. ?>

Display render will give something like:

Exception  1: invalid input, parameter #1 "$val" was expecting "integer", instead got "string"  2
File: [path_to]\[filename]   3
Line: 23   3
Function: html_progress2->setvalue   3

1 | error level
2 | message body with context informations
3 | call context (file, line, function)

Log render will give something like:

Aug 127.0.0.1  1  [exception  2] invalid input, parameter #1 "$val" was expecting "integer", instead got "string"  3

1 | client ip address and execution date
2 | error level
3 | message body with context informations
[Note] Note
To have both display and log output, check the php.ini display_errors and log_errors values : must be set to TRUE.

Let rewiew, step by step, how to get such results.

Remember that with default classes, there are two drivers : display and log that have both their own configuration parameters. You can override these parameters values with the handler entry in the hash of first argument of the HTML_Progress2 class constructor.

We did it here with the $prefs variable; its a two keys associative array. First key display defines the display driver values, and the second key log defines the log driver values.

Review the display driver custom values. Only two keys: lineFormat, contextFormat are redefined, thats means remains key eol keep its default value. See table below.

Table 16.2. Display driver configuration parameters

Parameter | Type | Default | Description
eol | string | <br />\n | The end-on-line character sequence
lineFormat string <b>%1$s</b>: %2$s %3$s Log line format specification:
  • 1$ = error level
  • 2$ = error message (body)
  • 3$ = error context
contextFormat string in <b>%3$s</b> (file <b>%1$s</b> on line <b>%2$s</b>) Context format (class, file, line) specification:
  • 1$ = script file name
  • 2$ = line in script file
  • 3$ = class/method names

[Tip] Tip
If you don't wish to see context information in the error message, then remove the parameter %3$ in the lineFormat option even if contextFormat is set.

Review now the log driver custom values. Only two keys lineFormat, timeFormat are redefined, thats means six remains keys eol, contextFormat, ident, message_type, destination, extra_headers keep their default values. See table below.

Table 16.3. Log driver configuration parameters

Parameter | Type | Default | Description
eol | string | \n | The end-on-line character sequence
lineFormat string %1$s %2$s [%3$s] %4$s %5$s Log line format specification:
  • $1 = time error
  • 2$ = ident (client ip)
  • 3$ = error level
  • 4$ = error message (body)
  • 5$ = error context
contextFormat string in %3$s (file %1$s on line %2$s) Context format (class, file, line) specification:
  • 1$ = script file name
  • 2$ = line in script file
  • 3$ = class/method names
timeFormat | string | %b %d %H:%M:%S | Time stamp format used by strftime
ident | string | REMOTE_ADDR | Client IP
message_type | string | 3 | Destination type used by error_log
destination | string | html_progress2_error.log | Destination name used by error_log
extra_headers | string | NULL | Extra headers depending of destination type

[Tip] Tip
If you don't wish to see context information in the error message, then remove the parameter %5$ in the lineFormat option even if contextFormat is set.


Custom Error Message Generation

Option: message_callback
Option: context_callback

In the default error class HTML_Progress2_Error there are two methods designed for use with generating error messages efficiently. To use them, you must set the options message_callback, and context_callback.

Option: message_callback

The default message handling callback (HTML_Progress2_Error::_getErrorMessage) get an array mapping error codes to error message templates, like so:

  1. <?php
  2. $messages = array(
  3.     HTML_PROGRESS2_ERROR_UNKNOWN =>
  4.         'unknown error',
  5.     HTML_PROGRESS2_ERROR_INVALID_INPUT =>
  6.         'invalid input, parameter #%paramnum% '
  7.       . '"%var%" was expecting '
  8.       . '"%expected%", instead got "%was%"'
  9. );
  10. ?>

Basically, if a variable name is enclosed in percent signs (%), it will be replaced with the value passed in the associative array.

Option: context_callback

The default context handling callback (HTML_Progress2_Error::getBackTrace) gets an array of execution functions and discovers where the error was generated.


Chapter 17. Events to observe

Table of Contents

Events Reference
Additional Events informations

Events Reference

onSubmit

This event is triggered by run() method when progress meter start process (0%)

onLoad

This event is triggered by run() method when progress meter end process (100%)

onChange

This event is triggered by setMinimum(),
setMaximum(), setValue(),
incValue(), moveStep(), and
moveNext() methods each time the current value change.

onCancel

This event is triggered only by a progress monitor, when user decide (click on button) to stop process.


Additional Events informations

handler

Function (method) that triggered event.

[Caution] Caution
Function name is case sensitive: setvalue does not match setValue.

Function is one of them: setMinimum, setMaximum, setValue, incValue, moveStep, moveNext, run.

value

Current value of progress meter. Between minimum and maximum limits defined by setMinimum and setMaximum methods.

sender

Origin of call. In most cases it should be html_progress2 class.

[Note] Note
It could be different if you extends the main class. Or in special case of progress monitor and onCancel event.

time

Current Unix timestamp of event triggered. Given by PHP microtime function.


Chapter 18. HTML_Progress2_Lite

Table of Contents

Quick API Reference
Quick-Cards Atttributes Reference

This chapter describes every API in the HTML_Progress2_Lite class and provides quick-cards attribute lists reference.

Quick API Reference

setDirection()

Defines the progress bar fill way and shape. Default: horizontal bar filled from left to right.

horizontal bar

  • from left to right (= right)
  • from right to left (= left)

vertical bar

  • from down to up (= up)
  • from up to down (= down)

addLabel()

add a new label to the progress bar

removeLabel()

remove an existing label to the progress bar

addButton()

add a new button to the progress bar

removeButton()

remove an existing button to the progress bar

setFrameAttributes()

build a frame around the progress bar

setLabelAttributes()

defines style of a progress bar label.

moveNext(), moveStep()

changes the value of the progress bar and refresh display

moveMin()

restart at beginning of a progress bar

display()

send progress bar renders to browser

hide()

hide the progress bar on display

show()

show a progress bar already hidden on display


Quick-Cards Atttributes Reference

[Note] Note

Position/size are relative to progress bar itself (left), (top), (width), (height). That means the default text label is on top side of the progress bar.

Width or height sets to zero means there is no size restriction (== auto-size).

Table 18.1. HTML_Progress2_Lite : position and size attributes

Name | Values | Initial value
position | absolute | relative | absolute
left | <integer> | 10
top | <integer> | 25
width | <integer> | 300
height | <integer> | 25
padding | <padding-width> | 0
min | <integer> | 0
max | <integer> | 100

Table 18.2. HTML_Progress2_Lite : color attributes

Name | Values | Initial value
border-style | <border-style> | solid
border-width | <border-width> | 1
border-color | <color> | #000000
background-color | <color> | #C0C0C0
color | <color> | #0033FF

Table 18.3. HTML_Progress2_Lite : frame attributes

Name | Values | Initial value
show | true | false | true
left | <integer> | 200
top | <integer> | 100
width | <integer> | 320
height | <integer> | 90
color | <color> | #C0C0C0
border-width | <border-width> | 2
border-style | <border-style> | solid
border-color | <color>{1,4} | #DFDFDF #404040 #404040 #DFDFDF

Table 18.4. HTML_Progress2_Lite : TEXT label attributes

Name | Values | Initial value
left | <integer> | (left)
top | <integer> | (top) - 16
width | <integer> | 0
height | <integer> | 0
align | left | center | right | left
background-color | transparent | <color> | transparent
font-size | <absolute-size> | <relative-size> | <length> | <percentage> | 11
font-family | <family-name> | Verdana, Tahoma, Arial
font-weight | normal | bold | normal
font-style | normal | italic | oblique | normal
color | <color> | #000000

Table 18.5. HTML_Progress2_Lite : BUTTON label attributes

Name | Values | Initial value
action | none | ??? | none
target | self | ??? | self
left | <integer> | (left)
top | <integer> | (top) + (height) + 10
width | <length> | 0
height | <length> | 0
align | left | center | right | center
background-color | transparent | <color> | transparent
font-size | <absolute-size> | <relative-size> | <length> | <percentage> | 11
font-family | <family-name> | Verdana, Tahoma, Arial
font-weight | normal | bold | normal
font-style | normal | italic | oblique | normal
color | <color> | #000000

Table 18.6. HTML_Progress2_Lite : STEP label attributes

Name | Values | Initial value
left | <integer> | (left) + 5
top | <integer> | (top) + 5
width | <length> | 10
height | <length> | 0
align | left | center | right | right
background-color | transparent | <color> | transparent
font-size | <absolute-size> | <relative-size> | <length> | <percentage> | 11
font-family | <family-name> | Verdana, Tahoma, Arial
font-weight | normal | bold | normal
font-style | normal | italic | oblique | normal
color | <color> | #000000

Table 18.7. HTML_Progress2_Lite : PERCENT label attributes

Name | Values | Initial value
left | <integer> | (left) + width - 50
top | <integer> | (top) - 16
width | <length> | 50
height | <length> | 0
align | left | center | right | right
background-color | transparent | <color> | transparent
font-size | <absolute-size> | <relative-size> | <length> | <percentage> | 11
font-family | <family-name> | Verdana, Tahoma, Arial
font-weight | normal | bold | normal
font-style | normal | italic | oblique | normal
color | <color> | #000000

Table 18.8. HTML_Progress2_Lite : CROSSBAR label attributes

Name | Values | Initial value
left | <integer> | (left) + (width)/2
top | <integer> | (top) - 16
width | <length> | 10
height | <length> | 0
align | left | center | right | center
background-color | transparent | <color> | transparent
font-size | <absolute-size> | <relative-size> | <length> | <percentage> | 11
font-family | <family-name> | Verdana, Tahoma, Arial
font-weight | normal | bold | normal
font-style | normal | italic | oblique | normal
color | <color> | #000000


Chapter 19. API - Application Programming Interface

Table of Contents

Error Handler
Listener
Data Handler
Increment
Minimum
Maximum
Current value
Go to next step
Graphical Handler
Orientation
Fill option
Cells
Border
Frame
Labels
Background color and size
JavaScript handler
Circle/Ellipse
Common functions
Identification
Animation speed
Stylesheet
Rendering
Process

Error Handler

HTML_Progress2::raiseError - A basic wrapper around the default PEAR_Error object
HTML_Progress2::hasErrors - Determine whether there are errors into the HTML_Progress2 stack
HTML_Progress2::getError - Pop an error off of the HTML_Progress2 stack

Unless you want to create extends of HTML_Progress2 class and check new function arguments with raiseError() method, you should only use hasErrors() and getError() methods to catch any API error (wrong programming).


HTML_Progress2::raiseError

Name

HTML_Progress2::raiseError — A basic wrapper around the default PEAR_Error object

Synopsis

      require_once 'HTML/Progress2.php';

mixed HTML_Progress2::raiseError();
;

Description

This method throws any internal API error that could be raised due to a wrong programming. It will use your error handler system defined at class construction (by first argument).

Throws

throws no exceptions thrown

See

see _errorHandler()

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::hasErrors

Name

HTML_Progress2::hasErrors — Determine whether there are errors into the HTML_Progress2 stack

Synopsis

      require_once 'HTML/Progress2.php';

integer HTML_Progress2::hasErrors();
;

Description

This function gave you ability to be aware of API errors presence in user scripts.

Throws

throws no exceptions thrown

See

see HTML_Progress2::getError, HTML_Progress2::raiseError

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::getError

Name

HTML_Progress2::getError — Pop an error off of the HTML_Progress2 stack

Synopsis

      require_once 'HTML/Progress2.php';
FALSE|array|PEAR_Error HTML_Progress2::getError( );
;

Description

Get all error data (code, message, level, context) from an object (PEAR_Error, ...) or a simple php array.

Throws

throws no exceptions thrown

See

see HTML_Progress2::hasErrors, HTML_Progress2::raiseError

Note

since 2.0.0

This function can not be called statically.


Listener

HTML_Progress2::addListener - Attachs a new observer
HTML_Progress2::removeListener - Removes a registered observer.

addListener() and removeListener() methods provides an implementation of the observer pattern. In the content of the HTML_Progress2 package, it provides a mechanism by which you can examine special event as it is happened. This allows the implementation of special behavior.


HTML_Progress2::addListener

Name

HTML_Progress2::addListener — Attachs a new observer

Synopsis

      require_once 'HTML/Progress2.php';

void HTML_Progress2::addListener( | $callback,
 | $nName = EVENT_DISPATCHER_GLOBAL);
mixed | $callback;
string | $nName = EVENT_DISPATCHER_GLOBAL;

Description

Adds a new observer to the Event Dispatcher that will listen for all messages emitted by this HTML_Progress2 instance.

Parameter

mixed $callback

PHP callback that will act as listener

string $nName

(optional) Expected notification name, serves as a filter

See

see HTML_Progress2::removeListener

Throws

throws HTML_PROGRESS2_ERROR_INVALID_CALLBACK, HTML_PROGRESS2_ERROR_INVALID_INPUT

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::removeListener

Name

HTML_Progress2::removeListener — Removes a registered observer.

Synopsis

      require_once 'HTML/Progress2.php';

bool HTML_Progress2::removeListener( | $callback,
 | $nName = EVENT_DISPATCHER_GLOBAL);
mixed | $callback;
string | $nName = EVENT_DISPATCHER_GLOBAL;

Description

Detachs a previously registered observer and remove the Event Dispatcher if there is no more observer registered.

Parameter

mixed $callback

PHP callback that act as listener

string $nName

(optional) Expected notification name, serves as a filter

Return value

returns True if observer was removed, false otherwise

See

see HTML_Progress2::addListener

Throws

throws HTML_PROGRESS2_ERROR_INVALID_CALLBACK, HTML_PROGRESS2_ERROR_INVALID_INPUT

Note

since 2.0.0

This function can not be called statically.


Data Handler

Increment
Minimum
Maximum
Current value
Go to next step

Increment

HTML_Progress2::getIncrement - Returns the progress meter increment value
HTML_Progress2::setIncrement - Sets the progress meter increment value

getIncrement() and setIncrement() methods provides reading and setting of the progress meter's step property.

Minimum

HTML_Progress2::getMinimum - Returns the progress meter minimum value
HTML_Progress2::setMinimum - Sets the progress meter minimum value

getMinimum() and setMinimum() methods provides reading and setting of the progress meter's minimum property.

Maximum

HTML_Progress2::getMaximum - Returns the progress meter maximum value
HTML_Progress2::setMaximum - Sets the progress bar's maximum value.

getMaximum() and setMaximum() methods provides reading and setting of the progress meter's maximum property.

Current value

HTML_Progress2::getValue - Returns the progress meter current value
HTML_Progress2::setValue - Sets the progress meter current value

getValue() and setValue() methods provides reading and setting of the progress meter's current value property.

Go to next step

HTML_Progress2::incValue - Updates the internal progress meter current value
HTML_Progress2::moveStep - Changes new value of the progress meter by step increase
HTML_Progress2::moveNext - Changes new value of the progress meter by increment increase
HTML_Progress2::getPercentComplete - Returns the percent complete of the progress meter

These methods provides setting to go to next step/value of the progress meter, and reading getPercentComplete() to detect if task is completed.


HTML_Progress2::getIncrement

Name

HTML_Progress2::getIncrement — Returns the progress meter increment value

Synopsis

      require_once 'HTML/Progress2.php';
integer HTML_Progress2::getIncrement( );
;

Description

Get step of progress property of a progress meter. The default value is +1.

Throws

throws no exceptions thrown

See

see HTML_Progress2::setIncrement

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::setIncrement

Name

HTML_Progress2::setIncrement — Sets the progress meter increment value

Synopsis

      require_once 'HTML/Progress2.php';
void HTML_Progress2::setIncrement( $inc);
integer $inc;

Description

Defines step of progress property of a progress meter. Allows to ajust default value (+1).

Parameter

integer $inc

progress meter's increment value

See

see HTML_Progress2::getIncrement

Throws

throws HTML_PROGRESS2_ERROR_INVALID_INPUT

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::getMinimum

Name

HTML_Progress2::getMinimum — Returns the progress meter minimum value

Synopsis

      require_once 'HTML/Progress2.php';

integer HTML_Progress2::getMinimum();
;

Description

Get the minimum value at which the progress meter will start. The default value is zero and can't be negative.

Throws

throws no exceptions thrown

See

see HTML_Progress2::setMinimum

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::setMinimum

Name

HTML_Progress2::setMinimum — Sets the progress meter minimum value

Synopsis

      require_once 'HTML/Progress2.php';
void HTML_Progress2::setMinimum( $min);
integer $min;

Description

Set the minimum value at which the progress meter will start. The default value is zero and can't be negative. If the new minimum is different than previous value, all listeners are notified.

Parameter

integer $min

progress meter's minimal value

See

see HTML_Progress2::getMinimum

Throws

throws HTML_PROGRESS2_ERROR_INVALID_INPUT

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::getMaximum

Name

HTML_Progress2::getMaximum — Returns the progress meter maximum value

Synopsis

      require_once 'HTML/Progress2.php';

integer HTML_Progress2::getMaximum();
;

Description

Get the maximum value at which the progress meter will stop. The default value is 100 and can't be less than minimum.

Throws

throws no exceptions thrown

See

see HTML_Progress2::setMaximum

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::setMaximum

Name

HTML_Progress2::setMaximum — Sets the progress bar's maximum value.

Synopsis

      require_once 'HTML/Progress2.php';
void HTML_Progress2::setMaximum( $max);
integer $max;

Description

Set the maximum value at which the progress meter will stop. The default value is 100 and can't be less than minimum. If the new maximum is different than previous value, all listeners are notified.

Parameter

integer $max

progress meter's maximal value

See

see HTML_Progress2::getMaximum

Throws

throws HTML_PROGRESS2_ERROR_INVALID_INPUT

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::getValue

Name

HTML_Progress2::getValue — Returns the progress meter current value

Synopsis

      require_once 'HTML/Progress2.php';

integer HTML_Progress2::getValue();
;

Description

Get the current value of the progress meter that is always between the minimum and maximum values, inclusive. The default value is equal to minimum.

Throws

throws no exceptions thrown

See

see HTML_Progress2::setValue , HTML_Progress2::incValue

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::setValue

Name

HTML_Progress2::setValue — Sets the progress meter current value

Synopsis

      require_once 'HTML/Progress2.php';
void HTML_Progress2::setValue( $val);
integer $val;

Description

Set the current value of the progress meter that is always between the minimum and maximum values, inclusive. If the new value is different from previous, then all listeners are notified.

Parameter

integer $val

progress meter's current value

See

see HTML_Progress2::getValue , HTML_Progress2::incValue

Throws

throws HTML_PROGRESS2_ERROR_INVALID_INPUT

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::incValue

Name

HTML_Progress2::incValue — Updates the internal progress meter current value

Synopsis

      require_once 'HTML/Progress2.php';

void HTML_Progress2::incValue();
;

Description

The new current value is equal to previous value increase by increment value. All listeners are notified. See also moveNext() method if you want a refresh display too.

Throws

throws no exceptions thrown

See

see HTML_Progress2::getValue , HTML_Progress2::setValue , HTML_Progress2::moveNext

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::moveStep

Name

HTML_Progress2::moveStep — Changes new value of the progress meter by step increase

Synopsis

      require_once 'HTML/Progress2.php';
void HTML_Progress2::moveStep( $step);
integer $step;

Description

Move current value to the next step of the progress meter defined by its increment. If result value is different than previous, then all listeners are notified. Caution: a step is always between 1 and (maximum / taskcount) rounded fractions up.

Parameter

integer $step

new step value

See

see HTML_Progress2::moveNext

Throws

throws HTML_PROGRESS2_ERROR_INVALID_INPUT

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::moveNext

Name

HTML_Progress2::moveNext — Changes new value of the progress meter by increment increase

Synopsis

      require_once 'HTML/Progress2.php';

void HTML_Progress2::moveNext();
;

Description

Move current value to the next value of the progress meter defined by its increment. If result value is different than previous, then all listeners are notified.

Throws

throws no exceptions thrown

See

see HTML_Progress2::moveStep

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::getPercentComplete

Name

HTML_Progress2::getPercentComplete — Returns the percent complete of the progress meter

Synopsis

      require_once 'HTML/Progress2.php';
float HTML_Progress2::getPercentComplete( $float = TRUE);
boolean $float = TRUE;

Description

Note that this number is between 0.00 and 1.00 when $float = true. And this number is between 0 and 100 when $float = false.

Parameter

boolean $float

(optional) float or integer format

See

see HTML_Progress2::getValue , HTML_Progress2::getMaximum

Throws

throws HTML_PROGRESS2_ERROR_INVALID_INPUT

Note

since 2.0.0

This function can not be called statically.


Graphical Handler

Orientation
Fill option
Cells
Border
Frame
Labels
Background color and size
JavaScript handler
Circle/Ellipse

Orientation

HTML_Progress2::getOrientation - Returns orientation of the progress bar
HTML_Progress2::setOrientation - Sets orientation of the progress bar

getOrientation() and setOrientation() methods provides reading and setting of the progress meter's orientation property.

Fill option

HTML_Progress2::getFillWay - Returns fill option of the progress meter
HTML_Progress2::setFillWay - Sets fill option of the progress meter

getFillWay() and setFillWay() methods provides reading and setting of the progress meter's fill property.

Cells

HTML_Progress2::getCellCount - Returns count of cell in the progress meter
HTML_Progress2::setCellCount - count of cell in the progress meter
HTML_Progress2::getCellAttributes - Returns cell attributes values
HTML_Progress2::setCellAttributes - Sets cell attributes values
HTML_Progress2::getCellCoordinates - Returns coordinates of each cell for a polygonal progress meter
HTML_Progress2::setCellCoordinates - Sets coordinates of each cell for a polygonal progress meter

getCellCount() and setCellCount() methods provides reading and setting of the progress meter's cell count property.

getCellAttributes() and setCellAttributes() methods provides reading and setting of the progress meter's cells properties.

getCellCoordinates() and setCellCoordinates() methods provides reading and setting of the progress meter's cells coordinates properties, that defined a polygonal progress meter (square, rectangle, ...).

Border

HTML_Progress2::getBorderAttributes - Returns progress bar's border attributes values
HTML_Progress2::setBorderAttributes - Sets the progress bar's border attributes
HTML_Progress2::isBorderPainted - Determines whether the progress bar border is painted or not
HTML_Progress2::setBorderPainted - Decides to paint or not a border to the progress bar.

getBorderAttributes() and setBorderAttributes() methods provides reading and setting of the progress meter's border property.

Frame

HTML_Progress2::getFrameAttributes - Returns frame attributes values
HTML_Progress2::setFrameAttributes - Build a frame around the progress bar

getFrameAttributes() and setFrameAttributes() methods provides reading and setting of the progress meter's frame properties.

Labels

HTML_Progress2::getLabelAttributes - Returns attributes values of an existing label
HTML_Progress2::setLabelAttributes - Sets label attributes.
HTML_Progress2::addLabel - Add a new label to the progress meter
HTML_Progress2::removeLabel - Removes a label to the progress meter

getLabelAttributes() and setLabelAttributes() methods provides reading and setting of the progress meter's label(s) items.

addLabel() and removeLabel() methods provides ability to add and remove unlimited progress meter's label(s) items.

Background color and size

HTML_Progress2::getProgressAttributes - Returns the progress background attributes values
HTML_Progress2::setProgressAttributes - Sets the progress background attributes values

getProgressAttributes() and setProgressAttributes() methods provides reading and setting of progress meter's background color and size properties.

JavaScript handler

HTML_Progress2::getScript - Returns javascript progress meter handler
HTML_Progress2::setScript - Sets the javascript progress meter handler

getScript() and setScript() methods provides reading and setting of the progress meter's javascript source code, that will handle display refresh.

Circle/Ellipse

HTML_Progress2::drawCircleSegments - Draw all circle segment pictures

drawCircleSegments() method provides building of all circle/ellipse segment PNG pictures.


HTML_Progress2::getOrientation

Name

HTML_Progress2::getOrientation — Returns orientation of the progress bar

Synopsis

      require_once 'HTML/Progress2.php';
integer HTML_Progress2::getOrientation( );
;

Description

There are only two distinct orientations for a progress bar: horizontal and vertical, identified by two constants: HTML_PROGRESS2_BAR_HORIZONTAL and HTML_PROGRESS2_BAR_VERTICAL. While circle and other polygonal progress meter are identified by two other constants: HTML_PROGRESS2_CIRCLE and HTML_PROGRESS2_POLYGONAL. The default orientation is horizontal.

Throws

throws no exceptions thrown

See

see HTML_Progress2::setOrientation

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::setOrientation

Name

HTML_Progress2::setOrientation — Sets orientation of the progress bar

Synopsis

      require_once 'HTML/Progress2.php';
void HTML_Progress2::setOrientation( $orient);
integer $orient;

Description

There are only two distinct orientations for a progress bar: horizontal and vertical, identified by two constants: HTML_PROGRESS2_BAR_HORIZONTAL and HTML_PROGRESS2_BAR_VERTICAL. While circle and other polygonal progress meter are identified by two other constants: HTML_PROGRESS2_CIRCLE and HTML_PROGRESS2_POLYGONAL. The default orientation is horizontal.

Parameter

integer $orient

Orientation (horizontal or vertical)

See

see HTML_Progress2::getOrientation

Throws

throws HTML_PROGRESS2_ERROR_INVALID_INPUT

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::getFillWay

Name

HTML_Progress2::getFillWay — Returns fill option of the progress meter

Synopsis

      require_once 'HTML/Progress2.php';

string HTML_Progress2::getFillWay();
;

Description

Get 'natural' or 'reverse', depending of the fill way of progress meter. For horizontal progress bar, natural way is from left to right, and reverse way is from right to left. For vertical progress bar, natural way is from down to up, and reverse way is from up to down. The default fill way is 'natural'.

Throws

throws no exceptions thrown

See

see HTML_Progress2::setFillWay

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::setFillWay

Name

HTML_Progress2::setFillWay — Sets fill option of the progress meter

Synopsis

      require_once 'HTML/Progress2.php';
void HTML_Progress2::setFillWay( $way);
string $way;

Description

Sets the progress meter fill option: must be 'natural' or 'reverse'. The default fill way is 'natural'.

Parameter

string $way

fill direction (natural or reverse)

See

see HTML_Progress2::getFillWay

Throws

throws HTML_PROGRESS2_ERROR_INVALID_INPUT

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::getCellCount

Name

HTML_Progress2::getCellCount — Returns count of cell in the progress meter

Synopsis

      require_once 'HTML/Progress2.php';
integer HTML_Progress2::getCellCount( );
;

Description

Get the number of cell defined to a progress meter. It must be positive. The default value is 10.

Throws

throws no exceptions thrown

See

see HTML_Progress2::setCellCount

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::setCellCount

Name

HTML_Progress2::setCellCount — count of cell in the progress meter

Synopsis

      require_once 'HTML/Progress2.php';
void HTML_Progress2::setCellCount( $cells);
integer $cells;

Description

Defines the number of cell to a progress meter. It must be positive. The default value is 10.

Parameter

integer $cells

Cell count on progress meter

See

see HTML_Progress2::getCellCount

Throws

throws HTML_PROGRESS2_ERROR_INVALID_INPUT

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::getCellAttributes

Name

HTML_Progress2::getCellAttributes — Returns cell attributes values

Synopsis

      require_once 'HTML/Progress2.php';
mixed HTML_Progress2::getCellAttributes( $asString = FALSE);
bool $asString = FALSE;

Description

Get all cell attributes in a associative array with key-value couple (by default). Get the attributes as string is also possible.

Parameter

boolean $asString

(optional) whether to return the attributes as string

See

see HTML_Progress2::setCellAttributes

Throws

throws HTML_PROGRESS2_ERROR_INVALID_INPUT

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::setCellAttributes

Name

HTML_Progress2::setCellAttributes — Sets cell attributes values

Synopsis

      require_once 'HTML/Progress2.php';

void HTML_Progress2::setCellAttributes( | $attributes,
 | $cell = NULL);
mixed | $attributes;
int | $cell = NULL;

Description

Sets cell attributes for all cells (default) or a specific an existing cell.

Defaults are:

  • Common :

    • id = pcel%01s

    • class = cell

    • spacing = 2

    • active-color = #006600

    • inactive-color = #CCCCCC

    • font-family = Courier, Verdana

    • font-size = lowest value from cell width, cell height, and font size

    • color = #000000

    • background-color = #FFFFFF

    • background-image = none

    • background-repeat = no-repeat

    • background-position = top left

    • Horizontal Bar :

      • width = 15

      • height = 20

    • Vertical Bar :

      • width = 20

      • height = 15

Parameter

mixed $attributes

Associative array or string of HTML tag attributes

integer $cell

(optional) Cell index

See

see HTML_Progress2::getCellAttributes

Throws

throws HTML_PROGRESS2_ERROR_INVALID_INPUT

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::getCellCoordinates

Name

HTML_Progress2::getCellCoordinates — Returns coordinates of each cell for a polygonal progress meter

Synopsis

      require_once 'HTML/Progress2.php';
array HTML_Progress2::getCellCoordinates( );
;

Description

Get array of all cell coordinates (x,y) that define a polygonal progress meter. For example, a 3x3 square as: (0,0) for top left corner, (2,0) for top right corner, (2,2) for bottom right corner, and (0,2) for bottom left corner.

Throws

throws no exceptions thrown

See

see HTML_Progress2::setCellCoordinates

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::setCellCoordinates

Name

HTML_Progress2::setCellCoordinates — Sets coordinates of each cell for a polygonal progress meter

Synopsis

      require_once 'HTML/Progress2.php';

void HTML_Progress2::setCellCoordinates( | $xgrid,
 | $ygrid,
 | $coord = array());
integer | $xgrid;
integer | $ygrid;
array | $coord = array();

Description

A polygonal progress meter is defined by its size (width, height) and its cells coordinates (array of couple x,y screen coordinates).

Parameter

integer $xgrid

The grid width in cell size

integer $ygrid

The grid height in cell size

array $coord

(optional) Coordinates (x,y) in the grid, of each cell

See

see HTML_Progress2::getCellCoordinates

Throws

throws HTML_PROGRESS2_ERROR_INVALID_INPUT

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::getBorderAttributes

Name

HTML_Progress2::getBorderAttributes — Returns progress bar's border attributes values

Synopsis

      require_once 'HTML/Progress2.php';
mixed HTML_Progress2::getBorderAttributes( $asString = FALSE);
bool $asString = FALSE;

Description

Get all border attributes in a associative array with key-value couple (by default). Get the attributes as string is also possible.

Parameter

boolean $asString

(optional) whether to return the attributes as string

See

see HTML_Progress2::setBorderAttributes

Throws

throws HTML_PROGRESS2_ERROR_INVALID_INPUT

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::setBorderAttributes

Name

HTML_Progress2::setBorderAttributes — Sets the progress bar's border attributes

Synopsis

      require_once 'HTML/Progress2.php';
void HTML_Progress2::setBorderAttributes( $attributes);
mixed $attributes;

Description

Defines all border attributes (color, size, ...) a progress bar (only horizontal or vertical) can handle.

Defaults are:

  • class = progressBorder%s

  • width = 0

  • style = solid

  • color = #000000

Parameter

mixed $attributes

Associative array or string of HTML tag attributes

Throws

throws no exceptions thrown

See

see HTML_Progress2::getBorderAttributes

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::isBorderPainted

Name

HTML_Progress2::isBorderPainted — Determines whether the progress bar border is painted or not

Synopsis

      require_once 'HTML/Progress2.php';
boolean HTML_Progress2::isBorderPainted( );
;

Description

By default, each progress bar (horizontal, vertical) has no border. This function gave ability to know if you've already set a border (return TRUE), or not (return FALSE).

Throws

throws no exceptions thrown

See

see HTML_Progress2::setBorderPainted

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::setBorderPainted

Name

HTML_Progress2::setBorderPainted — Decides to paint or not a border to the progress bar.

Synopsis

      require_once 'HTML/Progress2.php';
void HTML_Progress2::setBorderPainted( $paint);
boolean $paint;

Description

This function gave ability to set ($paint = TRUE) or remove ($paint = FALSE) a border to the current progress bar.

Parameter

boolean $paint

whether the progress bar should paint its border

See

see HTML_Progress2::isBorderPainted

Throws

throws HTML_PROGRESS2_ERROR_INVALID_INPUT

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::getFrameAttributes

Name

HTML_Progress2::getFrameAttributes — Returns frame attributes values

Synopsis

      require_once 'HTML/Progress2.php';
mixed HTML_Progress2::getFrameAttributes( $asString = FALSE);
bool $asString = FALSE;

Description

Get all frame attributes in a associative array with key-value couple (by default). Get the attributes as string is also possible.

Parameter

boolean $asString

(optional) whether to return the attributes as string

See

see HTML_Progress2::setFrameAttributes

Throws

throws HTML_PROGRESS2_ERROR_INVALID_INPUT

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::setFrameAttributes

Name

HTML_Progress2::setFrameAttributes — Build a frame around the progress bar

Synopsis

      require_once 'HTML/Progress2.php';
void HTML_Progress2::setFrameAttributes( $attributes = array());
NULL|array $attributes = array();

Description

Allows to build a customisable frame (color, size) around the progress meter.

Defaults are:

  • show = true

  • left = 200

  • top = 100

  • width = 320

  • height = 90

  • color = #C0C0C0

  • border-width = 2

  • border-style = solid

  • border-color = #DFDFDF #404040 #404040 #DFDFDF

Parameter

NULL|array $attributes

(optional) hash of style parameters

Throws

throws HTML_PROGRESS2_ERROR_INVALID_INPUT, HTML_PROGRESS2_ERROR_INVALID_OPTION

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::getLabelAttributes

Name

HTML_Progress2::getLabelAttributes — Returns attributes values of an existing label

Synopsis

      require_once 'HTML/Progress2.php';

mixed HTML_Progress2::getLabelAttributes( | $name,
 | $asString = FALSE);
string | $name;
bool | $asString = FALSE;

Description

Get all attributes of an existing label identified by $name argument. This identifier must be the same as the one given to addLabel() method. Return attributes values in a associative array with key-value couple (by default). Get the attributes as string is also possible.

Parameter

string $name

progress label id.

boolean $asString

(optional) whether to return the attributes as string

See

see HTML_Progress2::setLabelAttributes

Throws

throws HTML_PROGRESS2_ERROR_INVALID_INPUT

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::setLabelAttributes

Name

HTML_Progress2::setLabelAttributes — Sets label attributes.

Synopsis

      require_once 'HTML/Progress2.php';

void HTML_Progress2::setLabelAttributes( | $name,
 | $attributes);
string | $name;
mixed | $attributes;

Description

Defines attributes (font, color, size, alignement ...) of an existing label. Whether an attribute is not specified, previous or default value is used instead.

Defaults are:

  • class = progressPercentLabel%s

  • width = 50

  • height = 0

  • font-size = 11

  • font-family = Verdana, Tahoma, Arial

  • font-weight = normal

  • color = #000000

  • background-color = transparent

  • align = right

  • valign = right

Parameter

string $name

progress label id.

mixed $attributes

Associative array or string of HTML tag attributes

See

see HTML_Progress2::getLabelAttributes , HTML_Progress2::addLabel

Throws

throws HTML_PROGRESS2_ERROR_INVALID_INPUT

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::addLabel

Name

HTML_Progress2::addLabel — Add a new label to the progress meter

Synopsis

      require_once 'HTML/Progress2.php';

void HTML_Progress2::addLabel( | $type,
 | $name,
 | $value = ' ');
string | $type;
string | $name;
string | $value = ' ';

Description

Defines a new label identifier choosen between five categories:

  • HTML_PROGRESS2_LABEL_TEXT constant if you want a simple text zone
  • HTML_PROGRESS2_LABEL_BUTTON constant if you want a form button
  • HTML_PROGRESS2_LABEL_STEP constant if you want a step resume progress
  • HTML_PROGRESS2_LABEL_PERCENT constant if you want current progress value
  • HTML_PROGRESS2_LABEL_CROSSBAR constant if you want a little javascript animation

Parameter

string $type

Label type (text,button,step,percent,crossbar)

string $name

Label name

string $value

(optional) default label value

See

see HTML_Progress2::setLabelAttributes , HTML_Progress2::removeLabel

Throws

throws HTML_PROGRESS2_ERROR_INVALID_INPUT

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::removeLabel

Name

HTML_Progress2::removeLabel — Removes a label to the progress meter

Synopsis

      require_once 'HTML/Progress2.php';
void HTML_Progress2::removeLabel( $name);
string $name;

Description

The label identifier must exists or it cannot be remove. This is the same identifier as the one given to addLabel() method.

Parameter

string $name

Label name

See

see HTML_Progress2::addLabel

Throws

throws HTML_PROGRESS2_ERROR_INVALID_INPUT

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::getProgressAttributes

Name

HTML_Progress2::getProgressAttributes — Returns the progress background attributes values

Synopsis

      require_once 'HTML/Progress2.php';
mixed HTML_Progress2::getProgressAttributes( $asString = FALSE);
bool $asString = FALSE;

Description

Get all background attributes in a associative array with key-value couple (by default). Get the attributes as string is also possible.

Parameter

boolean $asString

(optional) whether to return the attributes as string

See

see HTML_Progress2::setProgressAttributes

Throws

throws HTML_PROGRESS2_ERROR_INVALID_INPUT

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::setProgressAttributes

Name

HTML_Progress2::setProgressAttributes — Sets the progress background attributes values

Synopsis

      require_once 'HTML/Progress2.php';
void HTML_Progress2::setProgressAttributes( $attributes);
mixed $attributes;

Description

Background attributes are color and size, with default values:

  • background-color = #FFFFFF

  • background-image = none

  • background-repeat = no-repeat

  • background-position = top left

  • Horizontal Bar :

    • width = (cell_count * (cell_width + cell_spacing)) + cell_spacing

    • height = cell_height + (2 * cell_spacing)

  • Vertical Bar :

    • width = cell_width + (2 * cell_spacing)

    • height = (cell_count * (cell_height + cell_spacing)) + cell_spacing

Parameter

mixed $attributes

Associative array or string of HTML tag attributes

Throws

throws no exceptions thrown

See

see HTML_Progress2::getProgressAttributes

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::getScript

Name

HTML_Progress2::getScript — Returns javascript progress meter handler

Synopsis

      require_once 'HTML/Progress2.php';
string HTML_Progress2::getScript( $raw = TRUE);
boolean $raw = TRUE;

Description

Get the javascript URL or inline code that will handle the progress meter refresh.

Parameter

boolean $raw

(optional) html output with script tags or just raw data

See

see HTML_Progress2::setScript

Throws

throws HTML_PROGRESS2_ERROR_INVALID_INPUT

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::setScript

Name

HTML_Progress2::setScript — Sets the javascript progress meter handler

Synopsis

      require_once 'HTML/Progress2.php';
void HTML_Progress2::setScript( $url);
string $url;

Description

Defines the javascript source (URL or inline code) that will handle the progress meter refresh.

Parameter

string $url

URL to the linked Progress JavaScript

See

see HTML_Progress2::getScript

Throws

throws HTML_PROGRESS2_ERROR_INVALID_INPUT

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::drawCircleSegments

Name

HTML_Progress2::drawCircleSegments — Draw all circle segment pictures

Synopsis

      require_once 'HTML/Progress2.php';

array HTML_Progress2::drawCircleSegments( | $dir = '.',
 | $fileMask = 'c%s.png');
string | $dir = '.';
string | $fileMask = 'c%s.png';

Description

This function build/prepare all circle segment PNG pictures that will be send to browser output. Requires PEAR::Image_Color and PHP:gd extension.

Parameter

string $dir

(optional) Directory where pictures should be created

string $fileMask

(optional) sprintf format for pictures filename

See

see HTML_Progress2::setCellAttributes

Throws

throws HTML_PROGRESS2_ERROR_INVALID_INPUT

Note

since 2.0.0

This function can not be called statically.


Common functions

Identification
Animation speed
Stylesheet
Rendering
Process

Identification

HTML_Progress2::getIdent - Returns the progress meter identifier
HTML_Progress2::setIdent - Sets the progress meter identifier

getIdent() and setIdent() methods provides reading and setting of the progress meter's id property.

Animation speed

HTML_Progress2::getAnimSpeed - Returns delay execution of the progress meter
HTML_Progress2::setAnimSpeed - Sets delay execution of the progress meter

getAnimSpeed() and setAnimSpeed() methods provides reading and setting of the progress meter's animation speed property.

Stylesheet

HTML_Progress2::getStyle - Returns the cascading style sheet (CSS)

getStyle() method provides getting of the progress meter's styles (CSS) to display the progress meter in a HTML document.

Rendering

HTML_Progress2::toArray - Returns the progress meter structure into an array
HTML_Progress2::toHtml - Returns the progress meter structure as HTML
HTML_Progress2::display - Renders the new value of progress meter
HTML_Progress2::hide - Hides the progress meter

toArray() method provides a dump of the progress meter's structure that will help in debugging.

toHtml() method provides html code generation of the progress meter, while display() method provides visible render of this code generation to browser.

Once the process is over hide() method provides a solution to remove/hide the progress meter of the browser screen.

Process

HTML_Progress2::sleep - Delay execution
HTML_Progress2::setProgressHandler - Sets the user progress callback function
HTML_Progress2::process - Performs the progress user process
HTML_Progress2::run - Runs the progress meter


HTML_Progress2::getIdent

Name

HTML_Progress2::getIdent — Returns the progress meter identifier

Synopsis

      require_once 'HTML/Progress2.php';

string HTML_Progress2::getIdent();
;

Description

Each progress meter has its own identifier. That allows to display more than only once meter at same time on same page.

Throws

throws no exceptions thrown

See

see HTML_Progress2::setIdent

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::setIdent

Name

HTML_Progress2::setIdent — Sets the progress meter identifier

Synopsis

      require_once 'HTML/Progress2.php';
void HTML_Progress2::setIdent( $ident = NULL);
mixed $ident = NULL;

Description

Each progress meter has its own identifier. That allows to display more than only once meter at same time on same page. If no identification string is given, then the default identifier will be six first characters of md5 hash value of the current unix timestamp.

Parameter

mixed $ident

(optional) the new identification string.

Throws

throws no exceptions thrown

See

see HTML_Progress2::getIdent

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::getAnimSpeed

Name

HTML_Progress2::getAnimSpeed — Returns delay execution of the progress meter

Synopsis

      require_once 'HTML/Progress2.php';
integer HTML_Progress2::getAnimSpeed( );
;

Description

Given a delay in process of the progress meter is only necessary if you need demonstration or also smooth animation. The default value is zero (no delay).

Throws

throws no exceptions thrown

See

see HTML_Progress2::setAnimSpeed

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::setAnimSpeed

Name

HTML_Progress2::setAnimSpeed — Sets delay execution of the progress meter

Synopsis

      require_once 'HTML/Progress2.php';
void HTML_Progress2::setAnimSpeed( $delay);
integer $delay;

Description

The delay (in milisecond) cannot exceed 1000 (1 second), that is enough to smooth an animation. User process should slow down animation and in most case the default value (zero) will be efficient.

Parameter

integer $delay

Delay in milisecond.

See

see HTML_Progress2::getAnimSpeed

Throws

throws HTML_PROGRESS2_ERROR_INVALID_INPUT

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::getStyle

Name

HTML_Progress2::getStyle — Returns the cascading style sheet (CSS)

Synopsis

      require_once 'HTML/Progress2.php';
string HTML_Progress2::getStyle( $raw = TRUE);
boolean $raw = TRUE;

Description

Get the CSS required to display the progress meter in a HTML document.

Parameter

boolean $raw

(optional) html output with script tags or just raw data

Throws

throws HTML_PROGRESS2_ERROR_INVALID_INPUT

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::toArray

Name

HTML_Progress2::toArray — Returns the progress meter structure into an array

Synopsis

      require_once 'HTML/Progress2.php';

array HTML_Progress2::toArray();
;

Description

Get all progress meter properties, couple key-value, into a php array. This structure is read-only, a dump-like information.

Throws

throws no exceptions thrown

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::toHtml

Name

HTML_Progress2::toHtml — Returns the progress meter structure as HTML

Synopsis

      require_once 'HTML/Progress2.php';

string HTML_Progress2::toHtml();
;

Description

Get html code required to display the progress meter in any html document.

Throws

throws no exceptions thrown

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::display

Name

HTML_Progress2::display — Renders the new value of progress meter

Synopsis

      require_once 'HTML/Progress2.php';

void HTML_Progress2::display();
;

Description

This method should be used only to display initial state of the progress meter. Next steps to refresh display must use either moveStep() or moveNext() methods.

Throws

throws no exceptions thrown

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::hide

Name

HTML_Progress2::hide — Hides the progress meter

Synopsis

      require_once 'HTML/Progress2.php';

void HTML_Progress2::hide();
;

Description

Once the process is over hide() method provides a solution to remove/hide the progress meter of the browser screen.

Throws

throws no exceptions thrown

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::sleep

Name

HTML_Progress2::sleep — Delay execution

Synopsis

      require_once 'HTML/Progress2.php';

void HTML_Progress2::sleep();
;

Description

The HTML_Progress2::sleep() function delays program execution for the given number of milliseconds. This is the default user callback when none are defined.

NOTE: The function http://www.php.net/manual/en/function.usleep.php did not work on Windows systems until PHP 5.0.0

Throws

throws no exceptions thrown

See

see HTML_Progress2::getAnimSpeed , HTML_Progress2::setAnimSpeed , HTML_Progress2::process

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::setProgressHandler

Name

HTML_Progress2::setProgressHandler — Sets the user progress callback function

Synopsis

      require_once 'HTML/Progress2.php';
void HTML_Progress2::setProgressHandler( $handler);
mixed $handler;

Description

The process() function will call the user-callback defined here by this setProgressHandler() method.

The user-supplied progress function must return either positive for a step progression, using moveStep() method, or NULL for a standard progression, using moveNext() method.

Parameter

mixed $handler

Name of function or a class-method.

See

see HTML_Progress2::process

Throws

throws HTML_PROGRESS2_ERROR_INVALID_CALLBACK

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::process

Name

HTML_Progress2::process — Performs the progress user process

Synopsis

      require_once 'HTML/Progress2.php';

mixed HTML_Progress2::process();
;

Description

This function call the user-specified progress function, defined by setProgressHandler() method. Default callback is the HTML_Progress2::sleep() method.

Throws

throws no exceptions thrown

See

see HTML_Progress2::sleep , HTML_Progress2::setProgressHandler

Note

since 2.0.0

This function can not be called statically.


HTML_Progress2::run

Name

HTML_Progress2::run — Runs the progress meter

Synopsis

      require_once 'HTML/Progress2.php';

void HTML_Progress2::run();
;

Description

This function accept both modes: indeterminate and determinate, and execute all actions defined in the user callback identified by setProgressHandler() method.

All observers are also notified of main changes (start, stop meter).

Throws

throws no exceptions thrown

See

see HTML_Progress2::process , HTML_Progress2::setProgressHandler

Note

since 2.0.0

This function can not be called statically.


Part V. Appendixes

Table of Contents

20. HTML_Progress2 and HTML_Progress2_Lite features comparative
21. Examples
Basic usage
Indeterminate Mode usage
Multiple Labels usage
Observer usage
Monitoring usage
Progress Generator wizard usage

Here is a list of samples, you can find in this package (PEAR binary distribution). Much more are available into the examples/ directory.


Chapter 20. HTML_Progress2 and HTML_Progress2_Lite features comparative

The HTML_Progress2_Lite class does not allow to do all that is possible with HTML_Progress2 class. This chapter describes differences between two classes.

Table 20.1. HTML_Progress2_Lite features comparative

Features | HTML_Progress2 | HTML_Progress2_Lite
Horizontal progress meter | yes | yes
Vertical progress meter | yes | yes
Polygonal progress meter | yes | no
Ellipse/Circle progress meter | yes | no
API error handling | yes | no
Multiple progress meter on same page | yes | yes
Multiple labels system | yes | yes
Smooth progress meter rendering | yes | yes
Cells progress meter rendering | yes | no
May use external stylesheet | yes | no
May use external javascript | yes | no
Implements observer pattern | yes | no
Monitoring | yes | simulate with frame and buttons but no listener


Chapter 21. Examples

Table of Contents

Basic usage
Indeterminate Mode usage
Multiple Labels usage
Observer usage
Monitoring usage
Progress Generator wizard usage

Basic usage

Figure 21.1. Basic usage with default skin

Basic usage with default skin

This example has no particular goals. It should be your first run to show the minimum stuff required for a demo to works.

Example 21.1. Without any customization

  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. $pb = new HTML_Progress2();
  5. $pb->setAnimSpeed(100);
  6. ?>
  7. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  8.     "http://www.w3c.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  9. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  10. <head>
  11. <title>Progress2 Basic example</title>
  12. <?php
  13. echo $pb->getStyle(false);
  14. echo $pb->getScript(false);
  15. ?>
  16. </head>
  17. <body>
  18.
  19. <?php
  20. $pb->display();
  21. $pb->run();
  22. ?>
  23.
  24. </body>
  25. </html>


Indeterminate Mode usage

Figure 21.2. Indeterminate Mode usage

Indeterminate Mode usage

Goal of this example is to show how to display a progress bar in indeterminate mode then switch it to determinate mode after a while. We will consider that after 12 seconds elapsed we got awaiting (supposed) missing information.

Example 21.2. progress bar in indeterminate mode

  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. function myProgressHandler($pValue, &$pBar)
  5. {
  6.     static $c, $t;
  7.
  8.     if (!isset($c)) {
  9.         $c = time();
  10.         $t = 0;
  11.     }
  12.
  13.     $pBar->sleep();
  14.
  15.     if ($pBar->isIndeterminate()) {
  16.         $elapse = time() - $c;
  17.
  18.         if ($elapse > $t) {
  19.             echo "myProgressHandler -> elapse time = $elapse s.<br />".PHP_EOL;
  20.             $t++;
  21.         }
  22.         if ($elapse >= 12) {
  23.             $pBar->setIndeterminate(false);
  24.             $pBar->setValue(0);
  25.             $pBar->setIncrement(5);
  26.         }
  27.     }
  28. }
  29.
  30. $pb = new HTML_Progress2();
  31. $pb->setAnimSpeed(200);
  32. $pb->setIncrement(10);
  33. $pb->setProgressAttributes('background-color=#E0E0E0');
  34. $pb->setCellAttributes('active-color=#996');
  35. $pb->setLabelAttributes('pct1', array('color' => '#996'));
  36. $pb->setIndeterminate(true);
  37. $pb->setProgressHandler('myProgressHandler');
  38. ?>
  39. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  40.     "http://www.w3c.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  41. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  42. <head>
  43. <title>Half Indeterminate Progress2 example</title>
  44. <style type="text/css">
  45. <!--
  46. body {
  47.     background-color: #CCCC99;
  48.     color: #996;
  49.     font-family: Verdana, Arial;
  50. }
  51.
  52. <?php echo $pb->getStyle(); ?>
  53.  -->
  54. </style>
  55. <?php echo $pb->getScript(false); ?>
  56. </head>
  57. <body>
  58.
  59. <?php
  60. $pb->display();
  61. echo '<br /><br />';
  62. $pb->run();
  63. ?>
  64. <p><b>Process Ended !</b></p>
  65.
  66. </body>
  67. </html>


Multiple Labels usage

Figure 21.3. Multi Labels usage

Multi Labels usage

Goals of this example is to show multiple labels usage. All four kind of label are presented with addLabel() and setLabelAttributes() methods implementation.

Example 21.3. Four kind of progress label

  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. $pb = new HTML_Progress2();
  5. $pb->setAnimSpeed(300);
  6. $pb->setIncrement(10);
  7.
  8. // Adds additional labels
  9. $pb->addLabel(HTML_PROGRESS2_LABEL_TEXT, 'txt1', 'Fire at will');
  10.
  11. $pb->addLabel(HTML_PROGRESS2_LABEL_CROSSBAR, 'crs1');
  12. $pb->setLabelAttributes('crs1', array(
  13.     'valign' => 'top',
  14.     'align'  => 'center',
  15.     'width'  => 170,
  16.     'color'  => 'blue'
  17. ));
  18.
  19. $pb->addLabel(HTML_PROGRESS2_LABEL_STEP, 'stp1');
  20. $pb->setLabelAttributes('stp1', array(
  21.     'valign' => 'bottom',
  22.     'color'  => 'blue'
  23. ));
  24.
  25. $pb->addLabel(HTML_PROGRESS2_LABEL_BUTTON, 'btn1', 'Run again');
  26. $pb->setLabelAttributes('btn1', array(
  27.     'width' => 100,
  28.     'top' => 0,
  29.     'color' => 'red'
  30. ));
  31. ?>
  32. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  33.     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  34. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  35. <head>
  36. <title>Labels Progress2 example</title>
  37. <style type="text/css">
  38. <!--
  39. <?php echo $pb->getStyle(); ?>
  40.
  41. body {
  42.     background-color: #E0E0E0;
  43.     color: #000000;
  44.     font-family: Verdana, Arial;
  45. }
  46.  -->
  47. </style>
  48. <?php echo $pb->getScript(false); ?>
  49. </head>
  50. <body>
  51.
  52. <?php
  53. $pb->display();
  54. $pb->run();
  55. ?>
  56.
  57. </body>
  58. </html>


Observer usage

Figure 21.4. Progress as a listener to Event_Dispatcher

Progress as a listener to Event_Dispatcher

This example show how to implement the ProgressMeter Event_Dispatcher to listen user-process (simulation of mail send) that decide to refresh itself the progress bar.

[Warning] Warning
This example requires at least the version 2.1.0 of HTML_Progress2

Example 21.4. Progress bar listen to user process

  1. <?php
  2. require_once 'HTML/Progress2.php';
  3.
  4. class myClass
  5. {
  6.     function doSomething()
  7.     {
  8.        $usecs = 1000 * 1000;  // wait 1 seconde
  9.        $dispatch =& Event_Dispatcher::getInstance('ProgressMeter');
  10.
  11.        // A long task to do ... for example sending 10 mails
  12.        for ($i = 0; $i < 10; ++$i) {
  13.
  14.            // simulate by a sleep 1 sec function
  15.            if ((substr(PHP_OS, 0, 3) == 'WIN') && (substr(PHP_VERSION,0,1) < '5') ){
  16.                for ($w = 0; $w < $usecs; $w++) { }
  17.            } else {
  18.                usleep($usecs);
  19.            } //
  20.
  21.            $dispatch->post($this, 'onTick', array($i));
  22.        }
  23.     }
  24. }
  25.
  26. class myBar extends HTML_Progress2
  27. {
  28.     function myBar()
  29.     {
  30.         parent::HTML_Progress2();
  31.         $this->setIncrement(10);
  32.
  33.         $this->addLabel(HTML_PROGRESS2_LABEL_TEXT, 'txt1');
  34.         $this->setLabelAttributes('txt1', array(
  35.             'valign' => 'top',
  36.             'left' => 0,
  37.             ));
  38.     }
  39.
  40.     function notify(&$notification)
  41.     {
  42.         $notifyName = $notification->getNotificationName();
  43.
  44.         if (strcasecmp($notifyName, 'onTick') == 0) {
  45.             $notifyInfo = $notification->getNotificationInfo();
  46.
  47.             if ($notifyInfo[0] == 0) {
  48.                 $this->setLabelAttributes('txt1', array('value' => 'Sending mail ...'));
  49.
  50.             } elseif ($notifyInfo[0] == 9) {
  51.                 $this->setLabelAttributes('txt1', array('value' => 'Mail sent with success.'));
  52.             }
  53.             $this->moveNext();
  54.         }
  55.     }
  56.
  57. }
  58.
  59. $bar = new myBar();
  60. $bar->addListener(array(&$bar, 'notify'), 'onTick');
  61.
  62. ?>
  63. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  64.     "http://www.w3c.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  65. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  66. <head>
  67. <title>doSomething</title>
  68. <style type="text/css">
  69. <!--
  70. <?php echo $bar->getStyle(); ?>
  71.
  72. body {
  73.     background-color: #FFFFFF;
  74. }
  75.  -->
  76. </style>
  77. <?php echo $bar->getScript(false); ?>
  78. </head>
  79. <body>
  80.
  81. <?php
  82. $bar->display();
  83.
  84. $process = new myClass();
  85. $process->doSomething();
  86. ?>
  87.
  88. </body>
  89. </html>


Monitoring usage

Figure 21.5. Monitoring usage

Goals of this example are to show how to include a progress bar into a quickform window, that can be stop at any time by user-end, and used this monitor with the indeterminate mode.

Example 21.5. progress bar into a quickform window

  1. <?php
  2. require_once 'HTML/Progress2/Monitor.php';
  3.
  4. function myFunctionHandler($pValue, &$pb)
  5. {
  6.     global $pm;
  7.
  8.     $pb->sleep();
  9.
  10.     if (!$pb->isIndeterminate()) {
  11.         if (fmod($pValue,10) == 0) {
  12.             $pm->setCaption('myFunctionHandler -> progress value is = %value%',
  13.                 array('value' => $pValue)
  14.             );
  15.         }
  16.     } elseif ($pValue == 60) {
  17.         $pb->setIndeterminate(false);
  18.         $pb->setValue(0);
  19.     }
  20. }
  21.
  22. $pm = new HTML_Progress2_Monitor('frmMonitor4', array(
  23.     'button' => array('style' => 'width:80px;'),
  24.     'autorun' => true
  25.     )
  26. );
  27.
  28. $pb =& $pm->getProgressElement();
  29. $pb->setAnimSpeed(100);
  30. $pb->setCellCount(20);
  31. $pb->setProgressAttributes('background-color=#EEE');
  32. $pb->setCellAttributes('inactive-color=#FFF active-color=#444444');
  33. $pb->setLabelAttributes('pct1', 'color=navy');
  34. $pb->setLabelAttributes('monitorStatus', 'color=navy font-size=10');
  35. $pb->setIndeterminate(true);
  36. $pb->setProgressHandler('myFunctionHandler');
  37.
  38. $pm->setProgressElement($pb);
  39. ?>
  40. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  41.     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  42. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  43. <head>
  44. <title>Custom Progress2 Monitor </title>
  45. <style type="text/css">
  46. <!--
  47. body {
  48.     background-color: lightgrey;
  49.     font-family: Verdana, Arial;
  50. }
  51. <?php echo $pm->getStyle(); ?>
  52.  -->
  53. </style>
  54. <?php echo $pm->getScript(false); ?>
  55. </head>
  56. <body>
  57.
  58. <?php
  59. $renderer =& HTML_QuickForm::defaultRenderer();
  60. $renderer->setFormTemplate('
  61. <form{attributes}>
  62.  <table width="450" border="0" cellpadding="3" cellspacing="2" bgcolor="#EEEEEE">
  63.  {content}
  64.  </table>
  65. </form>
  66. ');
  67. $renderer->setElementTemplate('
  68.  <tr>
  69.    <td valign="top" style="padding-left:15px;">
  70.    {element}
  71.    </td>
  72.  </tr>
  73. ');
  74. $renderer->setHeaderTemplate('
  75.  <tr>
  76.    <td style="background:#7B7B88;color:#ffc;" align="left" colspan="2">
  77.      <b>{header}</b>
  78.    </td>
  79.  </tr>
  80. ');
  81. $pm->accept($renderer);
  82.
  83. echo $renderer->toHtml();
  84. $pm->run();
  85. ?>
  86.
  87. </body>
  88. </html>


Progress Generator wizard usage

Figure 21.6. Progress Generator wizard usage

Progress Generator wizard usage

Goals of this example are to show how to use another driver (HTMLPage2) than the standard (Default), use another external stylesheet to change color scheme easily, and add a user-process to download the PHP/CSS code results.

HTMLPage2 driver used its own default stylesheet which is a blue skin. Here, we prefer to use the dark-grey skin of SmartyDynamic driver (see $css).

Example 21.6. Progress Generator build with PEAR::HTML_Page2

  1. <?php
  2. require_once 'HTML/Progress2/Generator.php';
  3. require_once 'HTML/Progress2/Generator/HTMLPage2.php';
  4. require_once 'HTML/Progress2/Generator/Process.php';
  5.
  6. class MyProcessHandler extends ActionProcess
  7. {
  8.     function perform(&$page, $actionName)
  9.     {
  10.         if ($actionName == 'cancel') {
  11.             echo '<h1>Progress2 Generator Demonstration is Over</h1>';
  12.             echo '<p>Hope you\'ve enjoyed. See you later!</p>';
  13.         } else {
  14.             // Checks whether the pages of the controller are valid
  15.             $page->isFormBuilt() or $page->buildForm();
  16.             $page->controller->isValid();
  17.
  18.             // what kind of source code is requested
  19.             $code = $page->exportValue('phpcss');
  20.             $pb = $page->controller->createProgressBar();
  21.
  22.             $phpCode = (isset($code['P']) === true);
  23.             $cssCode = (isset($code['C']) === true);
  24.
  25.             if ($cssCode && !$phpCode) {
  26.                 $strCSS = $this->sprintCSS($pb);
  27.                 $this->exportOutput($strCSS, 'text/css');
  28.             }
  29.             if ($phpCode) {
  30.                 $strPHP = $this->sprintPHP($pb, $cssCode);
  31.                 $this->exportOutput($strPHP, 'text/php');
  32.             }
  33.
  34.             // reset session data
  35.             $page->controller->container(true);
  36.         }
  37.     }
  38. }
  39.
  40. session_start();
  41.
  42. $tabbed =& HTML_Progress2_Generator::singleton();
  43.
  44. $tabbed->addActions(array('dump' => 'ActionDump', 'process' => 'MyProcessHandler'));
  45.
  46. $pear = 'c:\php4';
  47. $css  = $pear . '\pear\data\HTML_Progress2\smartydynamic.css';
  48. $tabbed->addAction('display', new ActionDisplay($css));
  49.
  50. $tabbed->run();
  51. ?>

[Caution] Caution
Of course you should fix the path of $pear to your own PEAR directory installation.