package.xml0000664000175000017500000005050612654104300011300 0ustar janjan Horde_View pear.horde.org View Horde View API A simple View pattern implementation. Chuck Hagenbuch chuck chuck@horde.org yes Mike Naberezny mnaberez mike@maintainable.com yes 2016-02-02 2.0.6 1.1.0 stable stable LGPL-2.1 * [jan] Mark PHP 7 as supported. 5.3.0 8.0.0alpha1 8.0.0alpha1 1.7.0 Horde_Exception pear.horde.org 2.0.0 3.0.0alpha1 3.0.0alpha1 Horde_Support pear.horde.org 2.0.0 3.0.0alpha1 3.0.0alpha1 Horde_Util pear.horde.org 2.0.0 3.0.0alpha1 3.0.0alpha1 Horde_Controller pear.horde.org 2.0.0 3.0.0alpha1 3.0.0alpha1 Horde_Routes pear.horde.org 2.0.0 3.0.0alpha1 3.0.0alpha1 Horde_Test pear.horde.org 2.1.0 3.0.0alpha1 3.0.0alpha1 json 0.2.1 0.2.0 beta beta 2011-03-06 LGPL-2.1 * Better Helper architecture, improved View/Helper registration 1.0.0alpha1 1.0.0 alpha alpha 2011-03-08 LGPL-2.1 * First alpha release for Horde 4. 1.0.0beta1 1.0.0 beta beta 2011-03-16 LGPL-2.1 * First beta release for Horde 4. 1.0.0RC1 1.0.0 beta beta 2011-03-22 LGPL-2.1 * First release candidate for Horde 4. 1.0.0RC2 1.0.0 beta beta 2011-03-29 LGPL-2.1 * Second release candidate for Horde 4. 1.0.0 1.0.0 stable stable 2011-04-06 LGPL-2.1 * First stable release for Horde 4. 1.0.1 1.0.0 stable stable 2011-11-22 LGPL-2.1 * [jan] Make unit tests Windows compatible. 2.0.0alpha1 1.1.0 alpha stable 2012-07-06 LGPL-2.1 * First alpha release for Horde 5. * [mms] Added Horde_View_Helper_FormTag#optionTag(). 2.0.0beta1 1.1.0 beta stable 2012-07-19 LGPL-2.1 * First beta release for Horde 5. 2.0.0 1.1.0 stable stable 2012-10-30 LGPL-2.1 * First stable release for Horde 5. 2.0.1 1.1.0 stable stable 2012-11-19 LGPL-2.1 * [mms] Use new Horde_Test layout. 2.0.2 1.1.0 stable stable 2013-02-11 LGPL-2.1 * [jan] Fix generating form tags. 2.0.3 1.1.0 stable stable 2013-08-22 LGPL-2.1 * [jan] Allow collections with arbitrary keys when rendering partials. 2.0.4 1.1.0 stable stable 2014-05-14 LGPL-2.1 * [jan] Change Horde_View_Helper_Date#distanceOfTimeInWords() to not round up the distance. * [jan] Make Horde_View_Helper_Text#truncate() and truncateMiddle() multibyte-safe (Bug #13163). 2.0.5 1.1.0 stable stable 2015-04-28 LGPL-2.1 * [jan] Fix issues with certain locales like Turkish. 2.0.6 1.1.0 stable stable 2016-02-02 LGPL-2.1 * [jan] Mark PHP 7 as supported. Horde_View-2.0.6/doc/Horde/View/examples/template.php0000664000175000017500000000067012654104300020536 0ustar janjanbooks): ?> books as $key => $val): ?>
Author Title
escape($val['author']) ?> escape($val['title']) ?>

There are no books to display.

Horde_View-2.0.6/doc/Horde/View/examples/view.php0000664000175000017500000000127312654104300017675 0ustar janjan 'Hernando de Soto', 'title' => 'The Mystery of Capitalism' ), array( 'author' => 'Henry Hazlitt', 'title' => 'Economics in One Lesson' ), array( 'author' => 'Milton Friedman', 'title' => 'Free to Choose' ) ); $view = new Horde_View; $view->books = $data; // and render a template called "template.php" echo $view->render('template.php'); Horde_View-2.0.6/doc/Horde/View/COPYING0000664000175000017500000005764612654104300015446 0ustar janjan GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Horde_View-2.0.6/doc/Horde/View/TODO.txt0000664000175000017500000000011012654104300015667 0ustar janjan- support embedded [CSS] images (see http://bugs.horde.org/ticket/7174) Horde_View-2.0.6/lib/Horde/View/Helper/Benchmark/Timer.php0000664000175000017500000000512012654104300021272 0ustar janjan * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ /** * An instance of this class is returned by * Horde_View_Helper_Benchmark::benchmark(). * * @author Mike Naberezny * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ class Horde_View_Helper_Benchmark_Timer { /** * (Micro-)time that the benchmark was started. * * @var float */ protected $_start; /** * Logger instance that will be used to record the time after the benchmark * has ended. * * @var Horde_Log_Logger */ protected $_logger; /** * Message to log after the benchmark has ended * * @var string */ protected $_message; /** * Log level to log after the benchmark has ended. * * @var string|integer */ protected $_level; /** * Starts a new benchmark. * * @param string $message Message to log after the benchmark has * ended. * @param string|integer $level Log level to log after the benchmark * has ended. * @param Horde_Log_Logger $logger Logger instance. */ public function __construct($message, $level = 'info', $logger = null) { $this->_message = $message; $this->_level = $level; $this->_logger = $logger; $this->_start = microtime(true); } /** * Ends the benchmark and log the result. */ public function end() { if ($this->_logger) { // Compute elapsed time and build message. $elapsed = microtime(true) - $this->_start; $message = sprintf('%s (%.5f)', $this->_message, $elapsed); // Log message (level may be specified as integer or string). if (is_integer($this->_level)) { $this->_logger->log($message, $this->_level); } else { $this->_logger->{$this->_level}($message); } } } } Horde_View-2.0.6/lib/Horde/View/Helper/Capture/Base.php0000664000175000017500000000265212654104300020604 0ustar janjan * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ /** * An instance of this class is returned by * Horde_View_Helper_Capture::capture(). * * @author Mike Naberezny * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ class Horde_View_Helper_Capture_Base { /** * Are we currently buffering? * * @var boolean */ protected $_buffering = true; /** * Starts capturing. */ public function __construct() { ob_start(); } /** * Stops capturing and returns what was captured. * * @return string The captured string. * @throws Horde_View_Exception */ public function end() { if ($this->_buffering) { $this->_buffering = false; $output = ob_get_clean(); return $output; } else { throw new Horde_View_Exception('Capture already ended'); } } } Horde_View-2.0.6/lib/Horde/View/Helper/Capture/ContentFor.php0000664000175000017500000000324112654104300022006 0ustar janjan * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ /** * An instance of this class is returned by * Horde_View_Helper_Capture::contentFor(). * * @author Mike Naberezny * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ class Horde_View_Helper_Capture_ContentFor extends Horde_View_Helper_Capture_Base { /** * Name that will become "$this->contentForName". * * @var string */ private $_name; /** * Starts capturing content that will be stored as $view->contentForName. * * @param string $name Name of the content that becomes the * instance variable name. * "foo" -> "$this->contentForFoo" * @param Horde_View_Base $view A view object. */ public function __construct($name, $view) { $this->_name = $name; $this->_view = $view; parent::__construct(); } /** * Stops capturing content and stores it in the view. */ public function end() { $name = 'contentFor' . Horde_String::ucfirst($this->_name); $this->_view->$name = parent::end(); } } Horde_View-2.0.6/lib/Horde/View/Helper/Form/InstanceTag/Base.php0000664000175000017500000001066312654104300022305 0ustar janjan * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ /** * @author Mike Naberezny * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ class Horde_View_Helper_Form_InstanceTag_Base extends Horde_View_Helper_Tag { protected $_defaultFieldOptions = array('size' => 30); protected $_defaultRadioOptions = array(); protected $_defaultTextAreaOptions = array('cols' => 40, 'rows' => 20); protected $_defaultDateOptions = array('discardType' => true); protected $objectName; protected $objectProperty; protected $object; protected $autoIndex; /** */ public function __construct($objectName, $objectProperty, $view, $object = null) { $this->_view = $view; $this->objectProperty = $objectProperty; $this->object = $object; if (strpos($objectName, '[]')) { $objectName = rtrim($objectName, '[]'); if (!isset($object)) { $object = $view->{$objectName}; } if (isset($object) && isset($object->id_before_type_cast)) { $this->autoIndex = $object->id_before_type_cast; } else { throw new InvalidArgumentException("object[] naming but object param and @object var don't exist or don't respond to id_before_type_cast"); } } $this->objectName = $objectName; } public function object() { if (isset($this->object)) { return $this->object; } else { return $this->_view->{$this->objectName}; } } public function value($object) { if (is_object($object)) { return $object->{$this->objectProperty}; } else { return null; } } protected function valueBeforeTypeCast($object) { if (!is_object($object)) { return null; } if (isset($object->{"{$this->objectProperty}_before_type_cast"})) { return $object->{"{$this->objectProperty}_before_type_cast"}; } if (isset($object->{$this->objectProperty})) { return $object->{$this->objectProperty}; } return null; } protected function addDefaultNameAndId($options) { if (isset($options['index'])) { if (!isset($options['name'])) { $options['name'] = $this->tagNameWithIndex($options['index']); } if (!isset($options['id'])) { $options['id'] = $this->tagIdWithIndex($options['index']); } unset($options['index']); } elseif (isset($this->autoIndex)) { if (!isset($options['name'])) { $options['name'] = $this->tagNameWithIndex($this->autoIndex); } if (!isset($options['id'])) { $options['id'] = $this->tagIdWithIndex($this->autoIndex); } } else { if (!isset($options['name'])) { $options['name'] = $this->tagName() . (isset($options['multiple']) ? '[]' : ''); } if (!isset($options['id'])) { $options['id'] = $this->tagId(); } } return $options; } protected function tagName() { return "{$this->objectName}[$this->objectProperty]"; } protected function tagNameWithIndex($index) { return "{$this->objectName}[$index][$this->objectProperty]"; } protected function tagId() { return $this->sanitizedObjectName() . "_{$this->objectProperty}"; } protected function tagIdWithIndex($index) { return $this->sanitizedObjectName() . "_{$index}_{$this->objectProperty}"; } protected function sanitizedObjectName() { $name = preg_replace('/[^-a-zA-Z0-9:.]/', '_', $this->objectName); $name = preg_replace('/_$/', '', $name); return $name; } } Horde_View-2.0.6/lib/Horde/View/Helper/Form/InstanceTag/Form.php0000664000175000017500000001205512654104300022333 0ustar janjan * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ /** * @author Mike Naberezny * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ class Horde_View_Helper_Form_InstanceTag_Form extends Horde_View_Helper_Form_InstanceTag_Base { public function toLabelTag($text, $options = array()) { return $this->contentTag('label', $text, $options); } public function toInputFieldTag($fieldType, $options = array()) { if (!isset($options['size'])) { $options['size'] = isset($options['maxlength']) ? $options['maxlength'] : $this->_defaultFieldOptions['size']; } $options = array_merge($this->_defaultFieldOptions, $options); if ($fieldType == 'hidden') { unset($options['size']); } $options['type'] = $fieldType; if ($fieldType != 'file') { if (!isset($options['value'])) { $options['value'] = $this->valueBeforeTypeCast($this->object()); } } $options = $this->addDefaultNameAndId($options); return $this->tag('input', $options); } public function toRadioButtonTag($tagValue, $options = array()) { $options = array_merge($this->_defaultRadioOptions, $options); $options['type'] = 'radio'; $options['value'] = $tagValue; if (isset($options['checked'])) { $cv = $options['checked']; unset($options['checked']); $checked = ($cv == true || $cv == 'checked'); } else { $checked = $this->isRadioButtonChecked($this->value($this->object()), $tagValue); } $options['checked'] = (boolean)$checked; $prettyTagValue = strval($tagValue); $prettyTagValue = preg_replace('/\s/', '_', $prettyTagValue); $prettyTagValue = preg_replace('/\W/', '', $prettyTagValue); $prettyTagValue = Horde_String::lower($prettyTagValue); if (! isset($options['id'])) { if (isset($this->autoIndex)) { $options['id'] = "{$this->objectName}_{$this->autoIndex}_{$this->objectProperty}_$prettyTagValue"; } else { $options['id'] = "{$this->objectName}_{$this->objectProperty}_$prettyTagValue"; } } $options = $this->addDefaultNameAndId($options); return $this->tag('input', $options); } public function toTextAreaTag($options = array()) { $options = array_merge($this->_defaultTextAreaOptions, $options); $options = $this->addDefaultNameAndId($options); if (isset($options['size'])) { $size = $options['size']; unset($options['size']); list($options['cols'], $options['rows']) = explode('x', $size); } if (isset($options['value'])) { $value = $options['value']; unset($options['value']); } else { $value = $this->valueBeforeTypeCast($this->object(), $options); } return $this->contentTag('textarea', htmlentities($value), $options); } public function toCheckBoxTag($options = array(), $checkedValue = '1', $uncheckedValue = '0') { $options['type'] = 'checkbox'; $options['value'] = $checkedValue; if (isset($options['checked'])) { $cv = $options['checked']; unset($options['checked']); $checked = ($cv == true || $cv == 'checked'); } else { $checked = $this->isCheckBoxChecked($this->value($this->object()), $checkedValue); } $options['checked'] = (boolean)$checked; $options = $this->addDefaultNameAndId($options); // Hidden must output first in PHP to not overwrite checkbox value. $tags = $this->tag('input', array('name' => $options['name'], 'type' => 'hidden', 'value' => $uncheckedValue)) . $this->tag('input', $options); return $tags; } protected function isCheckBoxChecked($value, $checkedValue) { switch (gettype($value)) { case 'boolean': return $value; case 'NULL': return false; case 'integer': return $value != 0; case 'string': return $value == $checkedValue; default: return intval($value) != 0; } } protected function isRadioButtonChecked($value, $checkedValue) { return (strval($value) == strval($checkedValue)); } } Horde_View-2.0.6/lib/Horde/View/Helper/Form/Builder.php0000664000175000017500000000524312654104300020617 0ustar janjan * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ /** * @author Mike Naberezny * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ class Horde_View_Helper_Form_Builder { private $_objectName; private $_object; private $_view; private $_options; private $_end; public function __construct($objectName, $object, $view, $options) { $this->_objectName = $objectName; $this->_object = $object; $this->_view = $view; $this->_end = isset($options['end']) ? $options['end'] : ''; unset($options['end']); $this->_options = $options; } public function __call($method, $args) { if (empty($args)) { throw new InvalidArgumentException('No object property specified'); } $objectProperty = $args[0]; $options = array_merge(isset($args[1]) ? $args[1] : array(), array('object' => $this->_object)); return $this->_view->{$method}($this->_objectName, $objectProperty, $options); } public function fieldsFor($name) { $name = "{$this->_objectName}[$name]"; $args = func_get_args(); $args[0] = $name; return call_user_func_array(array($this->_view, 'fieldsFor'), $args); } public function checkBox($method, $options = array(), $checkedValue = '1', $uncheckedValue = '0') { $options = array_merge($options, array('object' => $this->_object)); return $this->_view->checkBox($this->_objectName, $method, $options, $checkedValue, $uncheckedValue); } public function radioButton($method, $tagValue, $options = array()) { $options = array_merge($options, array('object' => $this->_object)); return $this->_view->radioButton($this->_objectName, $method, $tagValue, $options); } public function submit($value = 'Save changes', $options = array()) { $options = array_merge(array('id' => "{$this->_objectName}_submit"), $options); return $this->_view->submitTag($value, $options); } public function end() { echo $this->_end; } } Horde_View-2.0.6/lib/Horde/View/Helper/Text/Cycle.php0000664000175000017500000000351212654104300020306 0ustar janjan * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ /** * View helpers for URLs * * @author Mike Naberezny * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ class Horde_View_Helper_Text_Cycle { /** * Array of values to cycle through * @var array */ private $_values; /** * Construct a new cycler * * @param array $values Values to cycle through */ public function __construct($values) { if (func_num_args() != 1 || !is_array($values)) { throw new InvalidArgumentException(); } if (count($values) < 2) { throw new InvalidArgumentException('must have at least two values'); } $this->_values = $values; $this->reset(); } /** * Returns the current element in the cycle * and advance the cycle * * @return mixed Current element */ public function __toString() { $value = next($this->_values); return strval(($value !== false) ? $value : reset($this->_values)); } /** * Reset the cycle */ public function reset() { end($this->_values); } /** * Returns the values of this cycler. * * @return array */ public function getValues() { return $this->_values; } } Horde_View-2.0.6/lib/Horde/View/Helper/Base.php0000664000175000017500000000303312654104300017173 0ustar janjan_view = $view; $view->addHelper($this); } /** * Proxy on undefined property access (get). */ public function __get($name) { return $this->_view->$name; } /** * Proxy on undefined property access (set). */ public function __set($name, $value) { return $this->_view->$name = $value; } /** * Call chaining so members of the view can be called (including other * helpers). * * @param string $method The method. * @param array $args The parameters for the method. * * @return mixed The result of the method. */ public function __call($method, $args) { return call_user_func_array(array($this->_view, $method), $args); } } Horde_View-2.0.6/lib/Horde/View/Helper/Benchmark.php0000664000175000017500000000366612654104300020227 0ustar janjan * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ /** * Measures the execution time of a block in a template and reports the result * to the log. * * Example: * * * benchmark('Notes section') ?> * expensiveNotesOperation() ?> * end() ?> * * * Will add something like "Notes section (0.34523)" to the log. * * You may give an optional logger level as the second argument ('debug', * 'info', 'warn', 'error'). The default is 'info'. The level may also be * given as a Horde_Log::* constant. * * @author Mike Naberezny * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ class Horde_View_Helper_Benchmark extends Horde_View_Helper_Base { /** * Starts a new benchmark. * * @param string $message Message to log after the benchmark has * ended. * @param string|integer $level Log level to log after the benchmark has * ended. * * @return Horde_View_Helper_Benchmark_Timer A benchmark timer object. */ public function benchmark($message = 'Benchmarking', $level = 'info') { return new Horde_View_Helper_Benchmark_Timer($message, $level, $this->_view->logger); } } Horde_View-2.0.6/lib/Horde/View/Helper/Block.php0000664000175000017500000000602112654104300017353 0ustar janjan * @category Horde * @package View * @subpackage Helper */ /** * View helper for displaying Horde block objects. * * @author Chuck Hagenbuch * @category Horde * @package View * @subpackage Helper */ class Horde_View_Helper_Block extends Horde_View_Helper_Base { /** * Blocks that have already been fetched. * * @var array */ protected $_blockCache = array(); /** * Returns the title of the specified block. * * @param string $block The name of the block to get the title for. * @param mixed $arg1 The first argument to the Block constructor. * * @return string The requested Block's title. * @throws Horde_View_Exception * @throws InvalidArgumentException */ public function blockTitle() { list($block, $params) = $this->_args(func_get_args()); return $this->_block($block, $params)->getTitle(); } /** * Returns the content of the specified block. * * @param string $block The name of the block to get the content for. * @param mixed $arg1 The first argument to the Block constructor. * * @return string The requested Block's content. * @throws Horde_View_Exception * @throws InvalidArgumentException */ public function blockContent() { list($block, $params) = $this->_args(func_get_args()); return $this->_block($block, $params)->getContent(); } /** * Instantiates and caches Block objects. * * @param string $block The name of the block to fetch. * @param array $params Any arguments to the Block constructor. * * @return Horde_Core_Block The requested Block object. * @throws Horde_View_Exception */ protected function _block($block, $params) { $hash = sha1(serialize(array($block, $params))); if (!isset($this->_blockCache[$hash])) { try { $this->_blockCache[$hash] = $GLOBALS['injector'] ->getInstance('Horde_Core_Factory_BlockCollection') ->create() ->getBlock($block, $params); } catch (Exception $e) { throw new Horde_View_Exception($e); } } return $this->_blockCache[$hash]; } /** * Parses any argument style for the Block-fetching functions. * * @param array $args */ protected function _args($args) { $argc = count($args); if ($argc == 1) { if (is_array($args[0])) { $args = $args[0]; $argc = count($args); } } if ($argc < 2) { throw new InvalidArgumentException('You must provide at least an application name and a block name.'); } $app = array_shift($args); $block = array_shift($args); return array($app, $block, $args); } } Horde_View-2.0.6/lib/Horde/View/Helper/Capture.php0000664000175000017500000000440512654104300017730 0ustar janjan * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ /** * Capture lets you extract parts of code which can be used in other points of * the template or even layout file. * * @author Mike Naberezny * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ class Horde_View_Helper_Capture extends Horde_View_Helper_Base { /** * Capture allows you to extract a part of the template into an instance * variable. * * You can use this instance variable anywhere in your templates and even * in your layout. Example: * * * capture() ?> * Welcome To my shiny new web page! * greeting = $capture->end() ?> * * * @return Horde_View_Helper_Capture_Base */ public function capture() { return new Horde_View_Helper_Capture_Base(); } /** * Calling contentFor() stores the block of markup for later use. * * Subsequently, you can retrieve it inside an instance variable * that will be named "contentForName" in another template * or in the layout. Example: * * * contentFor("header") ?> * * end() ?> * * // Use $this->contentForHeader anywhere in your templates: * contentForHeader ?> * * * @param string $name Name of the content that becomes the instance * variable name. "foo" -> "$this->contentForFoo" * @return Horde_View_Helper_Capture_ContentFor */ public function contentFor($name) { return new Horde_View_Helper_Capture_ContentFor($name, $this->_view); } } Horde_View-2.0.6/lib/Horde/View/Helper/Date.php0000664000175000017500000000725612654104300017211 0ustar janjan * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ /** * @author Mike Naberezny * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ class Horde_View_Helper_Date extends Horde_View_Helper_Base { private $_instanceTag = 'Horde_View_Helper_Form_InstanceTag_Date'; /** * @todo possibly convert from time object */ public function distanceOfTimeInWords($fromTime, $toTime = 0, $includeSeconds = false) { $distanceInMinutes = floor(abs($toTime - $fromTime) / 60); $distanceInSeconds = floor(abs($toTime - $fromTime)); if ($distanceInMinutes >= 0 && $distanceInMinutes <= 1) { if (!$includeSeconds) { return ($distanceInMinutes == 0) ? 'less than a minute' : '1 minute'; } if ($distanceInSeconds >= 0 && $distanceInSeconds <= 4) { return 'less than 5 seconds'; } elseif ($distanceInSeconds >= 5 && $distanceInSeconds <= 9) { return 'less than 10 seconds'; } elseif ($distanceInSeconds >= 10 && $distanceInSeconds <= 19) { return 'less than 20 seconds'; } elseif ($distanceInSeconds >= 20 && $distanceInSeconds <= 39) { return 'half a minute'; } elseif ($distanceInSeconds >= 40 && $distanceInSeconds <= 59) { return 'less than a minute'; } else { return '1 minute'; } } elseif ($distanceInMinutes >= 2 && $distanceInMinutes <= 44) { return "$distanceInMinutes minutes"; } elseif ($distanceInMinutes >= 45 && $distanceInMinutes <= 89) { return 'about 1 hour'; } elseif ($distanceInMinutes >= 90 && $distanceInMinutes <= 1439) { return 'about ' . round($distanceInMinutes / 60) . ' hours'; } elseif ($distanceInMinutes >= 1440 && $distanceInMinutes <= 2879) { return '1 day'; } elseif ($distanceInMinutes >= 2880 && $distanceInMinutes <= 43199) { return intval($distanceInMinutes / 1440) . ' days'; } elseif ($distanceInMinutes >= 43200 && $distanceInMinutes <= 86399) { return 'about 1 month'; } elseif ($distanceInMinutes >= 86400 && $distanceInMinutes <= 525959) { return round(($distanceInMinutes / 43200)) . ' months'; } elseif ($distanceInMinutes >= 525960 && $distanceInMinutes <= 1051919) { return 'about 1 year'; } else { return 'over ' . round($distanceInMinutes / 525600) . ' years'; } } /** * Like distanceOfTimeInWords(), but where $toTime is fixed to now. */ public function timeAgoInWords($fromTime, $includeSeconds = false) { return $this->distanceOfTimeInWords($fromTime, time(), $includeSeconds); } public function dateSelect($objectName, $method, $options = array()) { $object = isset($options['object']) ? $options['object'] : null; unset($options['object']); $tag = new $this->_instanceTag($objectName, $method, $this->_view, $object); return $tag->toDateSelectTag($options); } } Horde_View-2.0.6/lib/Horde/View/Helper/Debug.php0000664000175000017500000000724112654104300017354 0ustar janjan * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ /** * Dumps a variable for inspection. * * Portions borrowed from Paul M. Jones' Solar_Debug * * @author Mike Naberezny * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ class Horde_View_Helper_Debug extends Horde_View_Helper_Base { /** * Dumps a variable for inspection. * * @param mixed $var A variable. * * @return string Debug output of the variable. */ public function debug($var) { return '
'
            . htmlspecialchars($this->_fetch($var))
            . '
'; } /** * Pretty exception dumper. * * Inspired by: * http://www.sitepoint.com/blogs/2006/04/04/pretty-blue-screen/ and * http://www.sitepoint.com/blogs/2006/08/12/pimpin-harrys-pretty-bluescreen/. * * Also see for future ideas: * http://mikenaberezny.com/archives/55 * * @param Exception $e An exception to dump. * * @return string Debug output of the exception. */ public function dump(Exception $e) { $input = array( 'type' => get_class($e), 'code' => $e->getCode(), 'message' => $e->getMessage(), 'line' => $e->getLine(), 'file' => $e->getFile(), 'trace' => $e->getTrace(), ); // Store previous output. $previous_output = ob_get_contents(); $desc = $input['type'] . ' making ' . $_SERVER['REQUEST_METHOD'] . ' request to ' . $_SERVER['REQUEST_URI']; return $this->render('_dump.html.php'); } /** * Returns formatted output from var_dump(). * * Buffers the var_dump() output for a variable and applies some simple * formatting for readability. * * @param mixed $var Variable to dump. * * @return string Formatted results of var_dump(). */ protected function _fetch($var) { ob_start(); var_dump($var); return preg_replace('/\]\=\>\n(\s+)/m', '] => ', ob_get_clean()); } protected function _sub($f) { $loc = ''; if (isset($f['class'])) { $loc .= $f['class'] . $f['type']; } if (isset($f['function'])) { $loc .= $f['function']; } if (!empty($loc)) { $loc = htmlspecialchars($loc); $loc = "$loc"; } return $loc; } protected function _clean($line) { $l = trim(strip_tags($line)); return $l ? $l : ' '; } protected function _parms($f) { if (isset($f['function'])) { try { if (isset($f['class'])) { $r = new ReflectionMethod($f['class'] . '::' . $f['function']); } else { $r = new ReflectionFunction($f['function']); } return $r->getParameters(); } catch(Exception $e) { } } return array(); } protected function _src2lines($file) { $src = nl2br(highlight_file($file, true)); return explode('
', $src); } } Horde_View-2.0.6/lib/Horde/View/Helper/Form.php0000664000175000017500000001307512654104300017233 0ustar janjan * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ /** * @author Mike Naberezny * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ class Horde_View_Helper_Form extends Horde_View_Helper_Base { private $_instanceTag = 'Horde_View_Helper_Form_InstanceTag_Form'; public function formFor($objectName) { $args = func_get_args(); $options = is_array(end($args)) ? array_pop($args) : array(); if (isset($options['url'])) { $urlOptions = $options['url']; unset($options['url']); } else { $urlOptions = array(); } if (isset($options['html'])) { $htmlOptions = $options['html']; unset($options['url']); } else { $htmlOptions = array(); } echo $this->formTag($urlOptions, $htmlOptions); $options['end'] = ''; $args[] = $options; return call_user_func_array(array($this, 'fieldsFor'), $args); } public function fieldsFor($objectName) { $args = func_get_args(); $options = is_array(end($args)) ? array_pop($args) : array(); $object = isset($args[1]) ? $args[1] : null; $builder = isset($options['builder']) ? $options['builder'] : Horde_View_Base::$defaultFormBuilder; return new $builder($objectName, $object, $this->_view, $options); } /** * Returns a label tag tailored for labelling an input field for a * specified attribute (identified by $method) on an object assigned to the * template (identified by $objectName). * * The text of label will default to the attribute name unless you specify * it explicitly. Additional options on the label tag can be passed as a * hash with $options. These options will be tagged onto the HTML as an * HTML element attribute as in the example shown. * * Examples: * * * $this->label('post', 'title'); * // => * * $this->label('post', 'title', 'A short title') * // => * * $this->label('post', 'title', 'A short title', * array('class' => 'title_label')); * // => * */ public function label($objectName, $method, $text, $options = array()) { $object = isset($options['object']) ? $options['object'] : null; unset($options['object']); $tag = new $this->_instanceTag($objectName, $method, $this->_view, $object); return $tag->toLabelTag($text, $options); } public function textField($objectName, $method, $options = array()) { $object = isset($options['object']) ? $options['object'] : null; unset($options['object']); $tag = new $this->_instanceTag($objectName, $method, $this->_view, $object); return $tag->toInputFieldTag('text', $options); } public function passwordField($objectName, $method, $options = array()) { $object = isset($options['object']) ? $options['object'] : null; unset($options['object']); $tag = new $this->_instanceTag($objectName, $method, $this->_view, $object); return $tag->toInputFieldTag('password', $options); } public function hiddenField($objectName, $method, $options = array()) { $object = isset($options['object']) ? $options['object'] : null; unset($options['object']); $tag = new $this->_instanceTag($objectName, $method, $this->_view, $object); return $tag->toInputFieldTag('hidden', $options); } public function fileField($objectName, $method, $options = array()) { $object = isset($options['object']) ? $options['object'] : null; unset($options['object']); $tag = new $this->_instanceTag($objectName, $method, $this->_view, $object); return $tag->toInputFieldTag('file', $options); } public function checkBox($objectName, $method, $options = array(), $checkedValue = '1', $uncheckedValue = '0') { $object = isset($options['object']) ? $options['object'] : null; unset($options['object']); $tag = new $this->_instanceTag($objectName, $method, $this->_view, $object); return $tag->toCheckBoxTag($options, $checkedValue, $uncheckedValue); } public function radioButton($objectName, $method, $tagValue, $options = array()) { $object = isset($options['object']) ? $options['object'] : null; unset($options['object']); $tag = new $this->_instanceTag($objectName, $method, $this->_view, $object); return $tag->toRadioButtonTag($tagValue, $options); } public function textArea($objectName, $method, $options = array()) { $object = isset($options['object']) ? $options['object'] : null; unset($options['object']); $tag = new $this->_instanceTag($objectName, $method, $this->_view, $object); return $tag->toTextAreaTag($options); } } Horde_View-2.0.6/lib/Horde/View/Helper/FormTag.php0000664000175000017500000001562412654104300017671 0ustar janjan * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ /** * @author Mike Naberezny * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ class Horde_View_Helper_FormTag extends Horde_View_Helper_Base { public function formTag($urlForOptions = array(), $options = array()) // , *parameters_for_url { $htmlOptions = $this->htmlOptionsForForm($urlForOptions, $options ); // , *parameters_for_url return $this->formTagHtml($htmlOptions); } public function endFormTag() { return ''; } public function selectTag($name, $optionTags = null, $options = array()) { return $this->contentTag('select', $optionTags, array_merge(array('name' => $name, 'id' => $name), $options)); } public function optionTag($value = null, $label = null, $selected = false, $options = array()) { return $this->contentTag('option', $label, array_merge(array( 'selected' => $selected, 'value' => $value ), $options)); } public function textFieldTag($name, $value = null, $options = array()) { return $this->tag('input', array_merge(array('type' => 'text', 'name' => $name, 'id' => $name, 'value' => $value), $options)); } public function hiddenFieldTag($name, $value = null, $options = array()) { return $this->textFieldTag($name, $value, array_merge($options, array('type' => 'hidden'))); } public function fileFieldTag($name, $options = array()) { return $this->textFieldTag($name, null, array_merge($options, array('type' => 'file'))); } public function passwordFieldTag($name = 'password', $value = null, $options = array()) { return $this->textFieldTag($name, $value, array_merge($options, array('type' => 'password'))); } public function textAreaTag($name, $content = null, $options = array()) { if (isset($options['size'])) { $size = $options['size']; unset($options['size']); if (strpos($size, 'x') !== false) { list($options['cols'], $options['rows']) = explode('x', $size); } } return $this->contentTag('textarea', $content, array_merge(array('name' => $name, 'id' => $name), $options)); } public function checkBoxTag($name, $value = '1', $checked = false, $options = array()) { $htmlOptions = array_merge(array('type' => 'checkbox', 'name' => $name, 'id' => $name, 'value' => $value, 'checked' => $checked), $options); return $this->tag('input', $htmlOptions); } public function radioButtonTag($name, $value, $checked = false, $options = array()) { $prettyTagValue = preg_replace('/\s/', '_', $value); $prettyTagValue = Horde_String::lower(preg_replace('/(?!-)\W/', '', $prettyTagValue)); $htmlOptions = array_merge(array('type' => 'radio', 'name' => $name, 'id' => "{$name}_{$prettyTagValue}", 'value' => $value, 'checked' => $checked), $options); return $this->tag('input', $htmlOptions); } public function submitTag($value = 'Save changes', $options = array()) { if (isset($options['disableWith'])) { $disableWith = $options['disableWith']; unset($options['disableWith']); $options['onclick'] = implode(';', array( "this.setAttribute('originalValue', this.value)", "this.disabled=true", "this.value='$disableWith'", "{$options['onclick']}", "result = (this.form.onsubmit ? (this.form.onsubmit() ? this.form.submit() : false) : this.form.submit())", "if (result == false) { this.value = this.getAttribute('originalValue'); this.disabled = false }", "return result" )); } return $this->tag('input', array_merge(array('type' => 'submit', 'name' => 'commit', 'value' => $value), $options)); } public function imageSubmitTag($source, $options = array()) { // source is passed to Horde_View_Helper_Asset->imagePath return $this->tag('input', array_merge(array('type' => 'image', 'src' => $this->imagePath($source)), $options)); } private function extraTagsForForm($htmlOptions) { $method = isset($htmlOptions['method']) ? Horde_String::lower($htmlOptions['method']) : ''; if ($method == 'get') { $htmlOptions['method'] = 'get'; return array('', $htmlOptions); } else if ($method == 'post' || $method == '') { $htmlOptions['method'] = 'post'; return array('', $htmlOptions); } else { $htmlOptions['method'] = 'post'; $extraTags = $this->contentTag('div', $this->tag('input', array('type' => 'hidden', 'name' => '_method', 'value' => $method)), array('style' => 'margin:0;padding:0')); return array($extraTags, $htmlOptions); } } private function formTagHtml($htmlOptions) { list($extraTags, $htmlOptions) = $this->extraTagsForForm($htmlOptions); return substr($this->contentTag('form', '', $htmlOptions), 0, -7) . $extraTags; } /** @todo url_for */ private function htmlOptionsForForm($urlForOptions, $options) { if (isset($options['multipart'])) { unset($options['multipart']); $options['enctype'] = 'multipart/form-data'; } $options['action'] = $this->urlFor($urlForOptions); // , *parameters_for_url // @todo : // html_options["action"] = url_for(url_for_options, *parameters_for_url) return $options; } } Horde_View-2.0.6/lib/Horde/View/Helper/Javascript.php0000664000175000017500000000261512654104300020434 0ustar janjan * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ /** * @author Mike Naberezny * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ class Horde_View_Helper_Javascript extends Horde_View_Helper_Base { public function escapeJavascript($javascript) { return str_replace(array('\\', "\r\n", "\r", "\n", '"', "'"), array('\0\0', "\\n", "\\n", "\\n", '\"', "\'"), $javascript); } public function javascriptTag($content, $htmlOptions = array()) { return $this->contentTag('script', $this->javascriptCdataSection($content), array_merge($htmlOptions, array('type' => 'text/javascript'))); } public function javascriptCdataSection($content) { return "\n//" . $this->cdataSection("\n$content\n//") . "\n"; } } Horde_View-2.0.6/lib/Horde/View/Helper/Number.php0000664000175000017500000000455012654104300017556 0ustar janjan * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ /** * View helpers for numbers. * * @author Mike Naberezny * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ class Horde_View_Helper_Number extends Horde_View_Helper_Base { /** * Formats the bytes in $size into a more understandable representation. * * Useful for reporting file sizes to users. This method returns NULL if * $size cannot be converted into a number. You can change the default * precision of 1 in $precision. * *
     * $this->numberToHumanSize(123)           => 123 Bytes
     * $this->numberToHumanSize(1234)          => 1.2 KB
     * $this->numberToHumanSize(12345)         => 12.1 KB
     * $this->numberToHumanSize(1234567)       => 1.2 MB
     * $this->numberToHumanSize(1234567890)    => 1.1 GB
     * $this->numberToHumanSize(1234567890123) => 1.1 TB
     * $this->numberToHumanSize(1234567, 2)    => 1.18 MB
     * 
* * @param integer|float $size Size to format. * @param integer $preceision Level of precision. * * @return string Formatted size value. */ public function numberToHumanSize($size, $precision = 1) { if (!is_numeric($size)) { return null; } if ($size == 1) { $size = '1 Byte'; } elseif ($size < 1024) { $size = sprintf('%d Bytes', $size); } elseif ($size < 1048576) { $size = sprintf("%.{$precision}f KB", $size / 1024); } elseif ($size < 1073741824) { $size = sprintf("%.{$precision}f MB", $size / 1048576); } elseif ($size < 1099511627776) { $size = sprintf("%.{$precision}f GB", $size / 1073741824); } else { $size = sprintf("%.{$precision}f TB", $size / 1099511627776); } return str_replace('.0', '', $size); } } Horde_View-2.0.6/lib/Horde/View/Helper/Tag.php0000664000175000017500000001304312654104300017036 0ustar janjan * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ /** * Use these methods to generate HTML tags programmatically. * * By default, they output HTML 4.01 Strict compliant tags. * * @author Mike Naberezny * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ class Horde_View_Helper_Tag extends Horde_View_Helper_Base { /** * Boolean HTML attributes. * * @var array */ private $_booleanAttributes = array('checked', 'disabled', 'multiple', 'readonly', 'selected'); /** * Returns an empty HTML tag of type $name. * * Add HTML attributes by passing an attributes hash to $options. For * attributes with no value (like disabled and readonly), give it a value * of TRUE in the $options array. * * * $this->tag('br') * // =>
* $this->tag('input', array('type' => 'text', 'disabled' => true)) * // => *
* * @param string $name Tag name. * @param string $options Tag attributes. * * @return string Generated HTML tag. */ public function tag($name, $options = null) { return "<$name" . ($options ? $this->tagOptions($options) : '') . ' />'; } /** * Returns an HTML block tag of type $name surrounding the $content. * * Add HTML attributes by passing an attributes hash to $options. For * attributes with no value (like disabled and readonly), give it a value * of TRUE in the $options array. * * * $this->contentTag('p', 'Hello world!') * // =>

Hello world!

* $this->contentTag('div', * $this->contentTag('p', 'Hello world!'), * array('class' => 'strong')) * // =>

Hello world!

* $this->contentTag('select', $options, array('multiple' => true)) * // => *
* * @param string $name Tag name. * @param string $content Content to place between the tags. * @param array $options Tag attributes. * * @return string Generated HTML tags with content between. */ public function contentTag($name, $content, $options = null) { $tagOptions = ($options ? $this->tagOptions($options) : ''); return "<$name$tagOptions>$content"; } /** * Returns a CDATA section with the given $content. * * CDATA sections are used to escape blocks of text containing characters * which would otherwise be recognized as markup. CDATA sections begin with * the string "". * * * $this->cdataSection(''); * // => ]]> * * @param string $content Content for inside CDATA section. * * @return string CDATA section with content. */ public function cdataSection($content) { return ""; } /** * Escapes a value for output in a view template. * * *

escape($this->templateVar) ?>

*
* * @param string $var The output to escape. * * @return string The escaped value. */ public function escape($var) { return htmlspecialchars($var, ENT_QUOTES, $this->_view->getEncoding()); } /** * Returns the escaped $html without affecting existing escaped entities. * * * $this->escapeOnce('1 > 2 & 3') * // => '1 < 2 & 3' * * @param string $html HTML to be escaped. * * @return string Escaped HTML without affecting existing escaped entities. */ public function escapeOnce($html) { return $this->_fixDoubleEscape($this->escape($html)); } /** * Converts an associative array of $options into a string of HTML * attributes. * * @param array $options Key/value pairs. * * @return string 'key1="value1" key2="value2"' */ public function tagOptions($options) { foreach ($options as $k => $v) { if ($v === null || $v === false) { unset($options[$k]); } } if (!empty($options)) { foreach ($options as $k => &$v) { if (in_array($k, $this->_booleanAttributes)) { $v = $k; } else { $v = $k . '="' . $this->escapeOnce($v) . '"'; } } sort($options); return ' ' . implode(' ', $options); } else { return ''; } } /** * Fix double-escaped entities, such as &amp;, &#123;, etc. * * @param string $escaped Double-escaped entities. * * @return string Entities fixed. */ private function _fixDoubleEscape($escaped) { return preg_replace('/&([a-z]+|(#\d+));/i', '&\\1;', $escaped); } } Horde_View-2.0.6/lib/Horde/View/Helper/Text.php0000664000175000017500000002276412654104300017261 0ustar janjan * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ /** * View helpers for text * * @author Mike Naberezny * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ class Horde_View_Helper_Text extends Horde_View_Helper_Base { /** * @var array */ protected $_cycles = array(); /** * @var Horde_Support_Inflector */ protected $_inflector; /** * Escapes a value for output in a view template. * * *

h($this->templateVar) ?>

*
* * @param mixed $var The output to escape. * * @return mixed The escaped value. */ public function h($var) { return htmlspecialchars($var, ENT_QUOTES, $this->_view->getEncoding()); } /** * Pluralizes the $singular word unless $count is one. If $plural * form is not supplied, inflector will be used. * * @param integer $count Count determines singular or plural. * @param string $singular Singular form. * @param string $plural Plural form (optional). */ public function pluralize($count, $singular, $plural = null) { if ($count == '1') { $word = $singular; } elseif ($plural) { $word = $plural; } else { if (!$this->_inflector) { $this->_inflector = new Horde_Support_Inflector(); } $word = $this->_inflector->pluralize($singular); } return "$count $word"; } /** * Creates a Cycle object whose __toString() method cycles through elements * of an array every time it is called. * * This can be used for example, to alternate classes for table rows: * * * * "> * item * * * * * You can use named cycles to allow nesting in loops. Passing an array as * the last parameter with a name key will create a named cycle. * You can manually reset a cycle by calling resetCycle() and passing the * name of the cycle: * * * * * * values as $value): ?> * * * * * resetCycle('colors') ?> * * * * */ public function cycle($firstValue) { $values = func_get_args(); $last = end($values); if (is_array($last)) { $options = array_pop($values); $name = isset($options['name']) ? $options['name'] : 'default'; } else { $name = 'default'; } if (empty($this->_cycles[$name]) || $this->_cycles[$name]->getValues() != $values) { $this->_cycles[$name] = new Horde_View_Helper_Text_Cycle($values); } return $this->_cycles[$name]; } /** * Resets a cycle so that it starts from the first element the next time * it is called. * * Pass in $name to reset a named cycle. * * @param string $name Name of cycle to reset. */ public function resetCycle($name = 'default') { if (isset($this->_cycles[$name])) { $this->_cycles[$name]->reset(); } } /** * Highlights a phrase where it is found in the text by surrounding it * like I'm highlighted. * * The Highlighter can be customized by passing $highlighter as a string * containing $1 as a placeholder where the phrase is supposed to be * inserted. * * @param string $text A text containing phrases to highlight. * @param string $phrase A phrase to highlight in $text. * @param string $highlighter A highlighting replacement. * * @return string The highlighted text. */ public function highlight($text, $phrase, $highlighter = null) { if (empty($highlighter)) { $highlighter = '$1'; } if (empty($phrase) || empty($text)) { return $text; } return preg_replace('/(' . preg_quote($phrase, '/') . ')/', $highlighter, $text); } /** * If $text is longer than $length, $text will be truncated to the length * of $length and the last three characters will be replaced with the * $truncateString. * * * $this->truncate('Once upon a time in a world far far away', 14); * // => Once upon a... * * * @param string $text A text to truncate. * @param integer $length The maximum length of the text * @param string $truncateString Replacement string for the truncated * text. * * @return string The truncated text. */ public function truncate($text, $length = 30, $truncateString = '...') { if (empty($text)) { return $text; } return Horde_String::length($text) > $length ? rtrim(Horde_String::substr($text, 0, $length - Horde_String::length($truncateString))) . $truncateString : $text; } /** * Limits a string to a given maximum length in a smarter way than just * using substr(). * * Namely, cut from the MIDDLE instead of from the end so that if we're * doing this on (for instance) a bunch of binder names that start off with * the same verbose description, and then are different only at the very * end, they'll still be different from one another after truncating. * * * $str = 'The quick brown fox jumps over the lazy dog tomorrow morning.'; * $shortStr = $this->truncateMiddle($str, 40); * // $shortStr == 'The quick brown fox... tomorrow morning.' * * * @param string $str A text to truncate. * @param integer $maxLength The maximum length of the text * @param string $joiner Replacement string for the truncated text. * * @return string The truncated text. */ public function truncateMiddle($str, $maxLength = 80, $joiner = '...') { if (Horde_String::length($str) <= $maxLength) { return $str; } $maxLength = $maxLength - Horde_String::length($joiner); if ($maxLength <= 0) { return $str; } $startPieceLength = (int) ceil($maxLength / 2); $endPieceLength = (int) floor($maxLength / 2); $trimmedString = rtrim(Horde_String::substr($str, 0, $startPieceLength)) . $joiner; if ($endPieceLength > 0) { $trimmedString .= ltrim(Horde_String::substr($str, (-1 * $endPieceLength))); } return $trimmedString; } /** * Inserts HTML code to allow linebreaks in a string after slashes or * underscores. * * @param string $str A string to mark up with linebreak markers. * * @return string The marked-up string. */ public function makeBreakable($str) { return str_replace( array('/', '_'), array('/', '_'), $str ); } /** * Removes smart quotes. * * @see http://shiflett.org/blog/2005/oct/convert-smart-quotes-with-php * * @param string $str A string with potential smart quotes. * * @return string The cleaned-up string. */ public function cleanSmartQuotes($str) { $search = array( '/\x96/', '/\xE2\x80\x93/', '/\x97/', '/\xE2\x80\x94/', '/\x91/', '/\xE2\x80\x98/', '/\x92/', '/\xE2\x80\x99/', '/\x93/', '/\xE2\x80\x9C/', '/\x94/', '/\xE2\x80\x9D/', '/\x85/', '/\xE2\x80\xA6/', '/\x95/', '/\xE2\x80\xA2/', '/\x09/', // The order of these is very important. '/\xC2\xBC/', '/\xBC/', '/\xC2\xBD/', '/\xBD/', '/\xC2\xBE/', '/\xBE/', ); $replace = array( '-', '-', '--', '--', "'", "'", "'", "'", '"', '"', '"', '"', '...', '...', '*', '*', ' ', '1/4', '1/4', '1/2', '1/2', '3/4', '3/4', ); return preg_replace($search, $replace, $str); } } Horde_View-2.0.6/lib/Horde/View/Helper/Url.php0000664000175000017500000004603512654104300017074 0ustar janjan * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ /** * View helpers for URLs * * @author Mike Naberezny * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage Helper */ class Horde_View_Helper_Url extends Horde_View_Helper_Base { /** * Returns the URL for the set of +options+ provided. This takes the * same options as url_for in ActionController (see the * documentation for ActionController::Base#url_for). Note that by default * :only_path is true so you'll get the relative /controller/action * instead of the fully qualified URL like http://example.com/controller/action. * * When called from a view, url_for returns an HTML escaped url. If you * need an unescaped url, pass :escape => false in the +options+. * * ==== Options * * :anchor -- specifies the anchor name to be appended to the path. * * :only_path -- if true, returns the relative URL (omitting the protocol, host name, and port) (true by default unless :host is specified) * * :trailing_slash -- if true, adds a trailing slash, as in "/archive/2005/". Note that this * is currently not recommended since it breaks caching. * * :host -- overrides the default (current) host if provided * * :protocol -- overrides the default (current) protocol if provided * * :user -- Inline HTTP authentication (only plucked out if :password is also present) * * :password -- Inline HTTP authentication (only plucked out if :user is also present) * * :escape -- Determines whether the returned URL will be HTML escaped or not (true by default) * * ==== Relying on named routes * * If you instead of a hash pass a record (like an Active Record or Active Resource) as the options parameter, * you'll trigger the named route for that record. The lookup will happen on the name of the class. So passing * a Workshop object will attempt to use the workshop_path route. If you have a nested route, such as * admin_workshop_path you'll have to call that explicitly (it's impossible for url_for to guess that route). * * ==== Examples * <%= url_for(:action => 'index') %> * # => /blog/ * * <%= url_for(:action => 'find', :controller => 'books') %> * # => /books/find * * <%= url_for(:action => 'login', :controller => 'members', :only_path => false, :protocol => 'https') %> * # => https://www.railsapplication.com/members/login/ * * <%= url_for(:action => 'play', :anchor => 'player') %> * # => /messages/play/#player * * <%= url_for(:action => 'checkout', :anchor => 'tax&ship') %> * # => /testing/jump/#tax&ship * * <%= url_for(:action => 'checkout', :anchor => 'tax&ship', :escape => false) %> * # => /testing/jump/#tax&ship * * <%= url_for(Workshop.new) %> * # relies on Workshop answering a new_record? call (and in this case returning true) * # => /workshops * * <%= url_for(@workshop) %> * # calls @workshop.to_s * # => /workshops/5 * * @return string */ public function urlFor($first = array(), $second = array()) { return is_string($first) ? $first : $this->controller->getUrlWriter()->urlFor($first, $second); } /** * Creates a link tag of the given +name+ using a URL created by the set of * +options+. See the valid options in the documentation for url_for. It's * also possible to pass a string instead of an options hash to get a link * tag that uses the value of the string as the href for the link, or use * +:back+ to link to the referrer - a JavaScript back link will be used in * place of a referrer if none exists. If nil is passed as a name, the link * itself will become the name. * * ==== Options * * :confirm => 'question?' -- This will add a JavaScript confirm * prompt with the question specified. If the user accepts, the link is * processed normally, otherwise no action is taken. * * :popup => true || array of window options -- This will force the * link to open in a popup window. By passing true, a default browser window * will be opened with the URL. You can also specify an array of options * that are passed-thru to JavaScripts window.open method. * * :method => symbol of HTTP verb -- This modifier will dynamically * create an HTML form and immediately submit the form for processing using * the HTTP verb specified. Useful for having links perform a POST operation * in dangerous actions like deleting a record (which search bots can follow * while spidering your site). Supported verbs are :post, :delete and :put. * Note that if the user has JavaScript disabled, the request will fall back * to using GET. If you are relying on the POST behavior, you should check * for it in your controller's action by using the request object's methods * for post?, delete? or put?. * * The +html_options+ will accept a hash of html attributes for the link tag. * * Note that if the user has JavaScript disabled, the request will fall back * to using GET. If :href=>'#' is used and the user has JavaScript disabled * clicking the link will have no effect. If you are relying on the POST * behavior, your should check for it in your controller's action by using * the request object's methods for post?, delete? or put?. * * You can mix and match the +html_options+ with the exception of :popup and * :method which will raise an ActionView::ActionViewError exception. * * ==== Examples * link_to "Visit Other Site", "http://www.rubyonrails.org/", :confirm => "Are you sure?" * # => Visit Other Site * * link_to "Help", { :action => "help" }, :popup => true * # => Help * * link_to "View Image", { :action => "view" }, :popup => ['new_window_name', 'height=300,width=600'] * # => View Image * * link_to "Delete Image", { :action => "delete", :id => @image.id }, :confirm => "Are you sure?", :method => :delete * # => Delete Image */ public function linkTo($name, $options = array(), $htmlOptions = array()) { $url = $this->urlFor($options); if ($htmlOptions) { $href = isset($htmlOptions['href']) ? $htmlOptions['href'] : null; // @todo convert_options_to_javascript!(html_options, url) $tagOptions = $this->tagOptions($htmlOptions); } else { $tagOptions = null; } $hrefAttr = isset($href) ? null : 'href="' . $url . '"'; $nameOrUrl = isset($name) ? $name : $url; return '' . $nameOrUrl . ''; } /** * Creates a link tag of the given +name+ using a URL created by the set of * +options+ unless the current request URI is the same as the links, in * which case only the name is returned (or the given block is yielded, if * one exists). You can give link_to_unless_current a block which will * specialize the default behavior (e.g., show a "Start Here" link rather * than the link's text). * * ==== Examples * Let's say you have a navigation menu... * * * * If in the "about" action, it will render... * * * * ...but if in the "home" action, it will render: * * * * The implicit block given to link_to_unless_current is evaluated if the current * action is the action given. So, if we had a comments page and wanted to render a * "Go Back" link instead of a link to the comments page, we could do something like this... * * <%= * link_to_unless_current("Comment", { :controller => 'comments', :action => 'new}) do * link_to("Go back", { :controller => 'posts', :action => 'index' }) * end * %> */ public function linkToUnlessCurrent($name, $url, $htmlOptions = array()) { return $this->linkToUnless($this->isCurrentPage($url), $name, $url, $htmlOptions); } /** * Creates a link tag of the given +name+ using a URL created by the set of * +options+ unless +condition+ is true, in which case only the name is * returned. To specialize the default behavior (i.e., show a login link * rather than just the plaintext link text), you can pass a block that * accepts the name or the full argument list for link_to_unless. * * ==== Examples * <%= link_to_unless(@current_user.nil?, "Reply", { :action => "reply" }) %> * # If the user is logged in... * # => Reply * * <%= * link_to_unless(@current_user.nil?, "Reply", { :action => "reply" }) do |name| * link_to(name, { :controller => "accounts", :action => "signup" }) * end * %> * # If the user is logged in... * # => Reply * # If not... * # => Reply */ public function linkToUnless($condition, $name, $url, $htmlOptions = array()) { return $condition ? $name : $this->linkTo($name, $url, $htmlOptions); } /** * Creates a link tag of the given +name+ using a URL created by the set of * +options+ if +condition+ is true, in which case only the name is * returned. To specialize the default behavior, you can pass a block that * accepts the name or the full argument list for link_to_unless (see the examples * in link_to_unless). * * ==== Examples * <%= link_to_if(@current_user.nil?, "Login", { :controller => "sessions", :action => "new" }) %> * # If the user isn't logged in... * # => Login * * <%= * link_to_if(@current_user.nil?, "Login", { :controller => "sessions", :action => "new" }) do * link_to(@current_user.login, { :controller => "accounts", :action => "show", :id => @current_user }) * end * %> * # If the user isn't logged in... * # => Login * # If they are logged in... * # => my_username */ public function linkToIf($condition, $name, $url, $htmlOptions = array()) { return $this->linkToUnless(!$condition, $name, $url, $htmlOptions); } /** * Creates a mailto link tag to the specified +email_address+, which is * also used as the name of the link unless +name+ is specified. Additional * HTML attributes for the link can be passed in +html_options+. * * mail_to has several methods for hindering email harvestors and customizing * the email itself by passing special keys to +html_options+. * * ==== Options * * encode - This key will accept the strings "javascript" or "hex". * Passing "javascript" will dynamically create and encode the mailto: link then * eval it into the DOM of the page. This method will not show the link on * the page if the user has JavaScript disabled. Passing "hex" will hex * encode the +email_address+ before outputting the mailto: link. * * replace_at - When the link +name+ isn't provided, the * +email_address+ is used for the link label. You can use this option to * obfuscate the +email_address+ by substituting the @ sign with the string * given as the value. * * replace_dot - When the link +name+ isn't provided, the * +email_address+ is used for the link label. You can use this option to * obfuscate the +email_address+ by substituting the . in the email with the * string given as the value. * * subject - Preset the subject line of the email. * * body - Preset the body of the email. * * cc - Carbon Copy addition recipients on the email. * * bcc - Blind Carbon Copy additional recipients on the email. * * ==== Examples * mailTo("me@domain.com") * # => me@domain.com * * mailTo("me@domain.com", "My email", array('encode' => "javascript")) * # => * * mailTo("me@domain.com", "My email", array('encode' => "hex")) * # => My email * * mailTo("me@domain.com", null, array('replaceAt' => "_at_", 'replaceDot' => "_dot_", 'class' => "email")) * # => * * mailTo("me@domain.com", "My email", array('cc' => "ccaddress@domain.com", * 'subject' => "This is an example email")) * # => My email */ public function mailTo($emailAddress, $name = null, $htmlOptions = array()) { // extra options "cc", "bcc", "subject", "body" $extras = ''; $extraParts = array('cc', 'bcc', 'body', 'subject'); foreach ($extraParts as $partName) { if (isset($htmlOptions[$partName])) { $partValue = str_replace('+', '%20', urlencode($htmlOptions[$partName])); $extras .= "{$partName}={$partValue}&"; } unset($htmlOptions[$partName]); } if (! empty($extras)) { $extras = '?' . rtrim($extras, '&'); } // obfuscation options "replaceAt" and "replaceDot" $emailAddressObfuscated = $emailAddress; foreach (array('replaceAt' => '@', 'replaceDot' => '.') as $option => $find) { if (isset($htmlOptions[$option])) { $emailAddressObfuscated = str_replace($find, $htmlOptions[$option], $emailAddressObfuscated); } unset($htmlOptions[$option]); } $string = ''; $encode = isset($htmlOptions['encode']) ? $htmlOptions['encode'] : null; unset($htmlOptions['encode']); if ($encode == 'javascript') { $name = isset($name) ? $name : $emailAddress; $htmlOptions = array_merge($htmlOptions, array('href' => "mailto:{$emailAddress}{$extras}")); $tag = $this->contentTag('a', $name, $htmlOptions); foreach (str_split("document.write('$tag');") as $c) { $string .= sprintf("%%%x", ord($c)); } return ""; } elseif ($encode == 'hex') { $emailAddressEncoded = ''; foreach (str_split($emailAddressObfuscated) as $c) { $emailAddressEncoded .= sprintf("&#%d;", ord($c)); } foreach (str_split('mailto:') as $c) { $string .= sprintf("&#%d;", ord($c)); } foreach (str_split($emailAddress) as $c) { if (preg_match('/\w/', $c)) { $string .= sprintf("%%%x", ord($c)); } else { $string .= $c; } } $name = isset($name) ? $name : $emailAddressEncoded; $htmlOptions = array_merge($htmlOptions, array('href' => $string . $extras)); return $this->contentTag('a', $name, $htmlOptions); } else { $name = isset($name) ? $name : $emailAddressObfuscated; $htmlOptions = array_merge($htmlOptions, array('href' => "mailto:{$emailAddress}{$extras}")); return $this->contentTag('a', $name, $htmlOptions); } } /** * True if the current request URI was generated by the given +options+. * * ==== Examples * Let's say we're in the /shop/checkout action. * * current_page?(:action => 'process') * # => false * * current_page?(:controller => 'shop', :action => 'checkout') * # => true * * current_page?(:action => 'checkout') * # => true * * current_page?(:controller => 'library', :action => 'checkout') * # => false * * @todo finish implementation */ public function isCurrentPage($options) { $urlString = htmlentities($this->urlFor($options)); if (preg_match('/^\w+:\/\//', $urlString)) { // @todo implement // url_string == "#{request.protocol}#{request.host_with_port}#{request.request_uri}" throw new Horde_View_Exception('not implemented'); } else { if ($this->controller) { // @todo prepending "/" is a hack, need to fix request object $request = $this->controller->getRequest(); $requestUri = '/' . ltrim($request->getPath(), '/'); } else { // @todo accessing $_REQUEST directly is a hack $requestUri = $_SERVER['REQUEST_URI']; } return rtrim($urlString, '/') == rtrim($requestUri, '/'); } } } Horde_View-2.0.6/lib/Horde/View/Base.php0000664000175000017500000002501512654104300015760 0ustar janjansetEncoding($config['encoding']); } // User-defined template path. if (!empty($config['templatePath'])) { $this->addTemplatePath($config['templatePath']); } $this->_protectedProperties = get_class_vars(__CLASS__); } /** * Undefined variables return null. * * @return null */ public function __get($name) { return null; } /** * Accesses a helper object from within a template. * * @param string $method The helper method. * @param array $args The parameters for the helper. * * @return string The result of the helper method. * @throws Horde_View_Exception */ public function __call($method, $args) { if (isset($this->_helpers[$method])) { return call_user_func_array(array($this->_helpers[$method], $method), $args); } throw new Horde_View_Exception('Helper for ' . $method . ' not found.'); } /** * Adds to the stack of template paths in LIFO order. * * @param string|array The directory (-ies) to add. */ public function addTemplatePath($path) { foreach ((array)$path as $dir) { // Attempt to strip any possible separator and append a // directory separator. $dir = rtrim($dir, '\\/' . DIRECTORY_SEPARATOR) . '/'; // Add to the top of the stack. array_unshift($this->_templatePath, $dir); } } /** * Resets the stack of template paths. * * To clear all paths, use Horde_View::setTemplatePath(null). * * @param string|array The directory (-ies) to set as the path. */ public function setTemplatePath($path) { $this->_templatePath = array(); $this->addTemplatePath($path); } /** * Returns the template paths. * * @return array The stack of current template paths. */ public function getTemplatePaths() { return $this->_templatePath; } /** * Adds to the stack of helpers in LIFO order. * * If the $helper parameter is a string instead of a Helper instance, then * it will be treated as a class name. Names without "_" and that do not * have "Helper" in them will be prefixed with Horde_View_Helper_; other * names will be treated as literal class names. Examples: * * * // Adds a new Horde_View_Helper_Tag to the view: * $v->addHelper('Tag'); * // Adds a new AppHelper object to the view if it exists, otherwise * // throws an exception: * $v->addHelper('AppHelper'); * * * @param Horde_View_Helper|string $helper The helper instance to add. * * @return Horde_View_Helper Returns the helper object that was added. * @throws Horde_View_Exception */ public function addHelper($helper) { if (is_string($helper)) { if (strpos($helper, '_') === false && strpos($helper, 'Helper') === false) { $class = 'Horde_View_Helper_' . $helper; } else { $class = $helper; } if (!class_exists($class)) { throw new Horde_View_Exception('Helper class ' . $helper . ' not found'); } $helper = new $class($this); } foreach (get_class_methods($helper) as $method) { if (isset($this->_helpers[$method])) { $msg = 'Helper method ' . get_class($this->_helpers[$method]) . '#' . $method . ' overridden by ' . get_class($helper) . '#' . $method; if ($this->_throwOnHelperCollision) { throw new Horde_View_Exception($msg); } if ($this->logger) { $this->logger->warn($msg); } } $this->_helpers[$method] = $helper; } return $helper; } /** * Assigns multiple variables to the view. * * The array keys are used as names, each assigned their corresponding * array value. * * @param array $array The array of key/value pairs to assign. */ public function assign($array) { foreach ($array as $key => $val) { if (isset($this->_protectedProperties[$key])) { throw new Horde_View_Exception('Cannot overwrite internal variables in assign()'); } $this->$key = $val; } } /** * Processes a template and returns the output. * * @param string $name The template to process. * * @return string The template output. */ public function render($name, $locals = array()) { // Render partial. if (is_array($name) && $partial = $name['partial']) { unset($name['partial']); return $this->renderPartial($partial, $name); } // Find the template file name. $this->_file = $this->_template($name); // Remove $name from local scope. unset($name); ob_start(); $this->_run($this->_file, $locals); return ob_get_clean(); } /** * Renders a partial template. * * Partial template filenames are named with a leading underscore, although * this underscore is not used when specifying the name of the partial. * * We would reference the file /views/shared/_sidebarInfo.html in our * template using: * * *
* renderPartial('sidebarInfo') ?> *
*
* * @param string $name * @param array $options * * @return string The template output. */ public function renderPartial($name, $options = array()) { // Pop name off of the path. $parts = strstr($name, '/') ? explode('/', $name) : array($name); $name = array_pop($parts); $path = count($parts) ? implode('/', $parts) . '/' : ''; // Check if they passed in a collection before validating keys. $useCollection = array_key_exists('collection', $options); $valid = array('object' => null, 'locals' => array(), 'collection' => array()); $options = array_merge($valid, $options); $locals = array($name => null); // Set the object variable. if ($options['object']) { $locals[$name] = $options['object']; } // Set local variables to be used in the partial. if (isset($options['locals']) && (is_array($options['locals']) || $options['locals'] instanceof Traversable)) { foreach ($options['locals'] as $key => $val) { $locals[$key] = $val; } } if ($useCollection) { // Collection. $rendered = ''; if (is_array($options['collection'])) { foreach (array_values($options['collection']) as $i => $item) { $locals["{$name}Counter"] = $i; $locals[$name] = $item; $rendered .= $this->render("{$path}_{$name}", $locals); } } } else { // Single render. $rendered = $this->render("{$path}_{$name}", $locals); } return $rendered; } /** * Sets the output encoding. * * @param string $encoding A character set name. */ public function setEncoding($encoding) { $this->_encoding = $encoding; } /** * Returns the current output encoding. * * @return string The current character set. */ public function getEncoding() { return $this->_encoding; } /** * Controls the behavior when a helper method is overridden by another * helper. * * @param boolean $throw Throw an exception when helper methods collide? */ public function throwOnHelperCollision($throw = true) { $this->_throwOnHelperCollision = $throw; } /** * Finds a template from the available directories. * * @param $name string The base name of the template. * * @return string The full path to the first matching template. */ protected function _template($name) { // Append missing .html. if (!strstr($name, '.')) { $name .= '.html.php'; } if (!count($this->_templatePath)) { throw new Horde_View_Exception('No template directory set; unable to locate ' . $name); } foreach ($this->_templatePath as $dir) { if (is_readable($dir . $name)) { return $dir . $name; } } throw new Horde_View_Exception("\"$name\" not found in template path (\"" . implode(':', $this->_templatePath) . '")'); } /** * Includes the template in a scope with only public variables. * * @param string The template to execute. Not declared in the function * signature so it stays out of the view's public scope. * @param array Any local variables to declare. */ abstract protected function _run(); } Horde_View-2.0.6/lib/Horde/View/Exception.php0000664000175000017500000000022012654104300017033 0ustar janjan $value) { ${$key} = $value; } } include func_get_arg(0); } } Horde_View-2.0.6/test/Horde/View/fixtures/subdir/testRender.html.php0000664000175000017500000000005412654104300023536 0ustar janjan
subdir myVar ?>
Horde_View-2.0.6/test/Horde/View/fixtures/testEscape.html.php0000664000175000017500000000007312654104300022230 0ustar janjan
test h($this->myVar) ?> quotes
Horde_View-2.0.6/test/Horde/View/fixtures/testPartial.html.php0000664000175000017500000000012612654104300022423 0ustar janjan
myVar1 ?>renderPartial('myPartial') ?>
Horde_View-2.0.6/test/Horde/View/fixtures/testPartialCollection.html.php0000664000175000017500000000015112654104300024435 0ustar janjan
renderPartial('myPartialObject', array('collection' => $this->myObjects)) ?>
Horde_View-2.0.6/test/Horde/View/fixtures/testPartialLocals.html.php0000664000175000017500000000017212654104300023562 0ustar janjan
renderPartial('myPartialLocals', array('locals' => array('a' => 'hello', 'b' => 'world'))) ?>
Horde_View-2.0.6/test/Horde/View/fixtures/testPartialObject.html.php0000664000175000017500000000014412654104300023552 0ustar janjan
renderPartial('myPartialObject', array('object' => $this->myObject)) ?>
Horde_View-2.0.6/test/Horde/View/fixtures/testRender.html.php0000664000175000017500000000004512654104300022246 0ustar janjan
myVar ?>
Horde_View-2.0.6/test/Horde/View/fixtures/_myPartial.html.php0000664000175000017500000000004212654104300022225 0ustar janjan

myVar2 ?>

Horde_View-2.0.6/test/Horde/View/fixtures/_myPartialLocals.html.php0000664000175000017500000000005012654104300023362 0ustar janjan

Horde_View-2.0.6/test/Horde/View/fixtures/_myPartialObject.html.php0000664000175000017500000000006312654104300023357 0ustar janjan

string_value ?>

Horde_View-2.0.6/test/Horde/View/Helper/BenchmarkTest.php0000664000175000017500000000476712654104300021303 0ustar janjan * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage UnitTests */ /** * @group view * @author Mike Naberezny * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage UnitTests */ class Horde_View_Helper_BenchmarkTest extends PHPUnit_Framework_TestCase { public function setUp() { $this->view = new Horde_View(); $this->view->addHelper(new Horde_View_Helper_Benchmark($this->view)); $log = new Horde_Log_Logger($this->mock = new Horde_Log_Handler_Mock()); $this->view->logger = $log; } public function testWithoutLogger() { $this->view = new Horde_View(); $this->view->addHelper(new Horde_View_Helper_Benchmark($this->view)); $bench = $this->view->benchmark(); $bench->end(); } public function testDefaults() { $bench = $this->view->benchmark(); $bench->end(); $this->assertEquals(1, count($this->mock->events)); $this->assertLastLogged(); } public function testWithMessage() { $bench = $this->view->benchmark('test_run'); $bench->end(); $this->assertEquals(1, count($this->mock->events)); $this->assertLastLogged('test_run'); } public function testWithMessageAndLevelAsString() { $bench = $this->view->benchmark('debug_run', 'debug'); $bench->end(); $this->assertEquals(1, count($this->mock->events)); $this->assertLastLogged('debug_run', 'debug'); } public function testWithMessageAndLevelAsInteger() { $bench = $this->view->benchmark('debug_run', Horde_Log::DEBUG); $bench->end(); $this->assertEquals(1, count($this->mock->events)); $this->assertLastLogged('debug_run', 'debug'); } public function assertLastLogged($message = 'Benchmarking', $level = 'info') { $last = end($this->mock->events); $this->assertEquals(strtoupper($level), $last['levelName']); $this->assertRegExp("/^$message \(.*\)$/", $last['message']); } } Horde_View-2.0.6/test/Horde/View/Helper/CaptureTest.php0000664000175000017500000000333512654104300021002 0ustar janjan * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage UnitTests */ /** * @group view * @author Mike Naberezny * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage UnitTests */ class Horde_View_Helper_CaptureTest extends PHPUnit_Framework_TestCase { public function setUp() { $this->view = new Horde_View(); $this->helper = new Horde_View_Helper_Capture($this->view); } public function testCapture() { $capture = $this->helper->capture(); echo $expected = 'foo'; $this->assertEquals($expected, $capture->end()); } public function testCaptureThrowsWhenAlreadyEnded() { $capture = $this->helper->capture(); $capture->end(); try { $capture->end(); $this->fail(); } catch (Exception $e) { $this->assertInstanceOf('Horde_View_Exception', $e); $this->assertRegExp('/capture already ended/i', $e->getMessage()); } } public function testContentFor() { $capture = $this->helper->contentFor('foo'); echo $expected = 'foo'; $capture->end(); $this->assertEquals($expected, $this->view->contentForFoo); } } Horde_View-2.0.6/test/Horde/View/Helper/DateTest.php0000664000175000017500000001500712654104300020253 0ustar janjan * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage UnitTests */ /** * @group view * @author Mike Naberezny * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage UnitTests */ class Horde_View_Helper_DateTest extends Horde_Test_Case { public function setUp() { $this->helper = new Horde_View_Helper_Date(new Horde_View()); } public function testDistanceInWords() { $from = mktime(21, 45, 0, 6, 6, 2004); // 0..1 with $includeSeconds $this->assertEquals('less than 5 seconds', $this->helper->distanceOfTimeInWords($from, $from + 0, true)); $this->assertEquals('less than 5 seconds', $this->helper->distanceOfTimeInWords($from, $from + 4, true)); $this->assertEquals('less than 10 seconds', $this->helper->distanceOfTimeInWords($from, $from + 5, true)); $this->assertEquals('less than 10 seconds', $this->helper->distanceOfTimeInWords($from, $from + 9, true)); $this->assertEquals('less than 20 seconds', $this->helper->distanceOfTimeInWords($from, $from + 10, true)); $this->assertEquals('less than 20 seconds', $this->helper->distanceOfTimeInWords($from, $from + 19, true)); $this->assertEquals('half a minute', $this->helper->distanceOfTimeInWords($from, $from + 20, true)); $this->assertEquals('half a minute', $this->helper->distanceOfTimeInWords($from, $from + 39, true)); $this->assertEquals('less than a minute', $this->helper->distanceOfTimeInWords($from, $from + 40, true)); $this->assertEquals('less than a minute', $this->helper->distanceOfTimeInWords($from, $from + 59, true)); $this->assertEquals('1 minute', $this->helper->distanceOfTimeInWords($from, $from + 60, true)); $this->assertEquals('1 minute', $this->helper->distanceOfTimeInWords($from, $from + 89, true)); // First case 0..1 $this->assertEquals('less than a minute', $this->helper->distanceOfTimeInWords($from, $from + 0)); $this->assertEquals('less than a minute', $this->helper->distanceOfTimeInWords($from, $from + 29)); $this->assertEquals('less than a minute', $this->helper->distanceOfTimeInWords($from, $from + 30)); $this->assertEquals('1 minute', $this->helper->distanceOfTimeInWords($from, $from + (1*60) + 29)); // 2..44 $this->assertEquals('2 minutes', $this->helper->distanceOfTimeInWords($from, $from + (2*60) + 30)); $this->assertEquals('44 minutes', $this->helper->distanceOfTimeInWords($from, $from + (44*60) + 29)); // 45..89 $this->assertEquals('about 1 hour', $this->helper->distanceOfTimeInWords($from, $from + (45*60))); $this->assertEquals('about 1 hour', $this->helper->distanceOfTimeInWords($from, $from + (89*60) + 29)); // 90..1439 $this->assertEquals('about 2 hours', $this->helper->distanceOfTimeInWords($from, $from + (90*60))); $this->assertEquals('about 24 hours', $this->helper->distanceOfTimeInWords($from, $from + (23*3600) + (59*60) + 29)); // 2880..43199 $this->assertEquals('2 days', $this->helper->distanceOfTimeInWords($from, $from + (47*3600) + (60*60))); $this->assertEquals('29 days', $this->helper->distanceOfTimeInWords($from, $from + (29*86400) + (23*3600) + (59*60) + 29)); // 43200..86399 $this->assertEquals('about 1 month', $this->helper->distanceOfTimeInWords($from, $from + (29*86400) + (23*3600) + (60*60))); $this->assertEquals('about 1 month', $this->helper->distanceOfTimeInWords($from, $from + (59*86400) + (23*3600) + (59*60) + 29)); // 86400..525599 $this->assertEquals('2 months', $this->helper->distanceOfTimeInWords($from, $from + (59*86400) + (23*3600) + (60*60))); $this->assertEquals('12 months', $this->helper->distanceOfTimeInWords($from, $from + (1*31557600) - 31)); // 525960..1051919 $this->assertEquals('about 1 year', $this->helper->distanceOfTimeInWords($from, $from + (1*31557600))); $this->assertEquals('about 1 year', $this->helper->distanceOfTimeInWords($from, $from + (2*31557600) - 31)); // > 1051920 $this->assertEquals('over 2 years', $this->helper->distanceOfTimeInWords($from, $from + (2*31557600))); $this->assertEquals('over 10 years', $this->helper->distanceOfTimeInWords($from, $from + (10*31557600))); // test to < from $this->assertEquals('about 4 hours', $this->helper->distanceOfTimeInWords($from + (4*3600), $from)); $this->assertEquals('less than 20 seconds', $this->helper->distanceOfTimeInWords($from + 19, $from, true)); } public function testDistanceInWordsWithIntegers() { // test with integers $this->assertEquals('less than a minute', $this->helper->distanceOfTimeInWords(59)); $this->assertEquals('about 1 hour', $this->helper->distanceOfTimeInWords(60*60)); $this->assertEquals('less than a minute', $this->helper->distanceOfTimeInWords(0, 59)); $this->assertEquals('about 1 hour', $this->helper->distanceOfTimeInWords(60*60, 0)); } } Horde_View-2.0.6/test/Horde/View/Helper/DebugTest.php0000664000175000017500000000241012654104300020416 0ustar janjan * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage UnitTests */ /** * @group view * @author Mike Naberezny * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage UnitTests */ class Horde_View_Helper_DebugTest extends PHPUnit_Framework_TestCase { public function setUp() { $this->helper = new Horde_View_Helper_Debug(new Horde_View()); } // test truncate public function testDebug() { $xdebug = ini_get('xdebug.overload_var_dump'); ini_set('xdebug.overload_var_dump', 0); $expected = '
string(7) "foo&bar"';
        $output = $this->helper->debug('foo&bar');
        ini_set('xdebug.overload_var_dump', $xdebug);
        $this->assertContains($expected, $output);
    }

}
Horde_View-2.0.6/test/Horde/View/Helper/FormTagTest.php0000664000175000017500000001703612654104300020741 0ustar  janjan
 * @author     Derek DeVries 
 * @author     Chuck Hagenbuch 
 * @license    http://www.horde.org/licenses/bsd
 * @category   Horde
 * @package    View
 * @subpackage UnitTests
 */

/**
 * @group      view
 * @author     Mike Naberezny 
 * @author     Derek DeVries 
 * @author     Chuck Hagenbuch 
 * @license    http://www.horde.org/licenses/bsd
 * @category   Horde
 * @package    View
 * @subpackage UnitTests
 */
class Horde_View_Helper_FormTagTest extends Horde_Test_Functional
{
    public function setUp()
    {
        $this->view = new Horde_View();
        $this->view->addHelper('FormTag');
        $this->view->addHelper('Tag');
        $this->view->addHelper(new Horde_View_Helper_FormTagTest_MockUrlHelper($this->view));
    }

    public function testFormTag()
    {
        $actual   = $this->view->formTag();
        $expected = '
'; $this->assertEquals($expected, $actual); } public function testFormTagWithExplicitUrl() { $actual = $this->view->formTag('/controller/action'); $expected = ''; $this->assertEquals($expected, $actual); } public function testFormTagMultipart() { $actual = $this->view->formTag(array(), array('multipart' => true)); $expected = ''; $this->assertEquals($expected, $actual); } public function testFormTagWithMethod() { $actual = $this->view->formTag(array(), array('method' => 'put')); $expected = '
'; $this->assertEquals($expected, $actual); } public function testCheckBoxTag() { $actual = $this->view->checkBoxTag('admin'); $expected = ''; $this->assertHtmlDomEquals($expected, $actual); } public function testHiddenFieldTag() { $actual = $this->view->hiddenFieldTag('id', 3); $expected = ''; $this->assertHtmlDomEquals($expected, $actual); } public function testFileFieldTag() { $actual = $this->view->fileFieldTag('id'); $expected = ''; $this->assertHtmlDomEquals($expected, $actual); } public function testPasswordFieldTag() { $actual = $this->view->passwordFieldTag(); $expected = ''; $this->assertHtmlDomEquals($expected, $actual); } public function testRadioButtonTag() { $actual = $this->view->radioButtonTag('people', 'david'); $expected = ''; $this->assertHtmlDomEquals($expected, $actual); $actual = $this->view->radioButtonTag('num_people', 5); $expected = ''; $this->assertHtmlDomEquals($expected, $actual); $actual = $this->view->radioButtonTag('gender', 'm') . $this->view->radioButtonTag('gender', 'f'); $expected = '' . ''; $this->assertEquals($expected, $actual); // @todo assertHtmlDomEquals $actual = $this->view->radioButtonTag('opinion', '-1') . $this->view->radioButtonTag('opinion', '1'); $expected = '' . ''; $this->assertEquals($expected, $actual); // @todo assertHtmlDomEquals } public function testSelectTag() { $actual = $this->view->selectTag('people', ''); $expected = ''; $this->assertHtmlDomEquals($expected, $actual); } public function testTextAreaTagSizeString() { $actual = $this->view->textAreaTag('body', 'hello world', array('size' => '20x40')); $expected = ''; $this->assertHtmlDomEquals($expected, $actual); } public function testTextAreaTagShouldDisregardSizeIfGivenAsAnInteger() { $actual = $this->view->textAreaTag('body', 'hello world', array('size' => 20)); $expected = ''; $this->assertHtmlDomEquals($expected, $actual); } public function testTextFieldTag() { $actual = $this->view->textFieldTag('title', 'Hello!'); $expected = ''; $this->assertHtmlDomEquals($expected, $actual); } public function testTextFieldTagClassString() { $actual = $this->view->textFieldTag('title', 'Hello!', array('class' => 'admin')); $expected = ''; $this->assertHtmlDomEquals($expected, $actual); } public function testBooleanOptions() { $this->assertHtmlDomEquals('', $this->view->checkBoxTag("admin", 1, true, array('disabled' => true, 'readonly' => "yes"))); $this->assertHtmlDomEquals('', $this->view->checkBoxTag('admin', 1, true, array('disabled' => false, 'readonly' => null))); $this->assertHtmlDomEquals('', $this->view->selectTag('people', '', array('multiple' => true))); $this->assertHtmlDomEquals('', $this->view->selectTag('people', '', array('multiple' => null))); } public function testSubmitTag() { $expected = ''; $actual = $this->view->submitTag('Save', array('disableWith' => 'Saving...', 'onclick' => "alert('hello!')")); $this->assertHtmlDomEquals($expected, $actual); } } class Horde_View_Helper_FormTagTest_MockUrlHelper extends Horde_View_Helper_Url { public function urlFor($first = array(), $second = array()) { return $first ? parent::urlFor($first, $second) : 'http://www.example.com'; } } Horde_View-2.0.6/test/Horde/View/Helper/FormTest.php0000664000175000017500000005167112654104300020310 0ustar janjan * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage UnitTests */ /** * @group view * @author Mike Naberezny * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage UnitTests */ class Horde_View_Helper_FormTest extends Horde_Test_Case { public function setUp() { $this->view = new Horde_View(); $this->view->addHelper('Form'); $this->view->addHelper('FormTag'); $this->view->addHelper('Tag'); $this->view->addHelper(new Horde_View_Helper_FormTest_MockUrlHelper($this->view)); $this->post = (object)array('title', 'authorName', 'body', 'secret', 'writtenOn', 'cost'); $this->post->title = 'Hello World'; $this->post->authorName = ''; $this->post->body = 'Back to the hill and over it again!'; $this->post->secret = 1; $this->post->writtenOn = mktime(2004, 6, 15); $this->post->id = 123; $this->post->id_before_type_cast = 123; $this->view->post = $this->post; } public function testTextField() { $this->assertEquals( '', $this->view->textField('post', 'title')); $this->assertEquals( '', $this->view->passwordField('post', 'title')); $this->assertEquals( '', $this->view->passwordField("person", "name")); } public function testTextFieldWithEscapes() { $this->post->title = 'Hello World'; $this->assertEquals( '', $this->view->textField('post', 'title')); } public function testTextFieldWithOptions() { $expected = ''; $this->assertEquals($expected, $this->view->textField('post', 'title', array('size' => 35))); } public function testTextFieldAssumingSize() { $expected = ''; $this->assertEquals($expected, $this->view->textField('post', 'title', array('maxlength' => 35))); } public function testTextFieldDoesntChangeParamValues() { $objectName = 'post[]'; $expected = ''; $this->assertEquals($expected, $this->view->textField($objectName, 'title')); $this->assertEquals($objectName, 'post[]'); } public function testCheckBox() { $this->assertEquals( '', $this->view->checkBox('post', 'secret')); $this->post->secret = 0; $this->assertEquals( '', $this->view->checkBox('post', 'secret')); $this->assertEquals( '', $this->view->checkBox('post', 'secret', array('checked' => true))); $this->post->secret = true; $this->assertEquals( '', $this->view->checkBox('post', 'secret')); } public function testCheckBoxWithExplicitCheckedAndUncheckedValues() { $this->post->secret = 'on'; $this->assertEquals( '', $this->view->checkBox('post', 'secret', array(), 'on', 'off')); } public function testRadioButton() { $this->assertEquals( '', $this->view->radioButton('post', 'title', 'Hello World')); $this->assertEquals( '', $this->view->radioButton('post', 'title', 'Goodbye World')); } public function testRadioButtonIsCheckedWithIntegers() { $this->assertEquals( '', $this->view->radioButton('post', 'secret', '1')); } public function testRadioButtonRespectsPassedInId() { $this->assertEquals( '', $this->view->radioButton('post', 'secret', '1', array('id' => 'foo'))); } public function testTextArea() { $this->assertEquals( '', $this->view->textArea('post', 'body')); } public function testTextAreaWithEscapes() { $this->post->body = "Back to the hill and over it again!"; $this->assertEquals( '', $this->view->textArea('post', 'body')); } public function testTextAreaWithAlternateValue() { $this->assertEquals( '', $this->view->textArea('post', 'body', array('value' => 'Testing alternate values.'))); } public function testTextAreaWithSizeOption() { $this->assertEquals( '', $this->view->textArea('post', 'body', array('size' => '183x820'))); } public function testExplicitName() { $this->assertEquals( '', $this->view->textField("post", "title", array("name" => "dont guess"))); $this->assertEquals( '', $this->view->textArea("post", "body", array("name" => "really!"))); $this->assertEquals( '', $this->view->checkBox("post", "secret", array("name" => "i mean it"))); } public function testExplicitId() { $this->assertEquals( '', $this->view->textField("post", "title", array("id" => "dont guess"))); $this->assertEquals( '', $this->view->textArea("post", "body", array("id" => "really!"))); $this->assertEquals( '', $this->view->checkBox("post", "secret", array("id" => "i mean it"))); } public function testAutoIndex() { $pid = $this->post->id; $this->assertEquals( "", $this->view->textField("post[]", "title")); $this->assertEquals( "", $this->view->textArea("post[]", "body")); $this->assertEquals( "", $this->view->checkBox('post[]', 'secret')); $this->assertEquals( "", $this->view->radioButton('post[]', 'title', 'Hello World')); $this->assertEquals( "", $this->view->radioButton('post[]', 'title', 'Goodbye World')); } public function testFormFor() { ob_start(); $form = $this->view->formFor('post', $this->post, array('html' => array('id' => 'create-post'))); echo $form->textField('title'); echo $form->textArea('body'); echo $form->checkBox('secret'); echo $form->submit('Create post'); $form->end(); $expected = '' . '' . '' . '' . '' . '' . ""; $this->assertEquals($expected, ob_get_clean()); } public function testFormForWithMethod() { ob_start(); $form = $this->view->formFor('post', $this->post, array('html' => array('id' => 'create-post', 'method' => 'put'))); echo $form->textField('title'); echo $form->textArea('body'); echo $form->checkBox('secret'); $form->end(); $expected = '
' . '
' . '' . '' . '' . '' . "
"; $this->assertEquals($expected, ob_get_clean()); } public function testFormForWithoutObject() { ob_start(); $form = $this->view->formFor('post', array('html' => array('id' => 'create-post'))); echo $form->textField('title'); echo $form->textArea('body'); echo $form->checkBox('secret'); $form->end(); $expected = '
' . '' . '' . '' . '' . "
"; $this->assertEquals($expected, ob_get_clean()); } public function testFormForWithIndex() { ob_start(); $form = $this->view->formFor('post[]', $this->post); echo $form->textField('title'); echo $form->textArea('body'); echo $form->checkBox('secret'); $form->end(); $expected = '
' . '' . '' . '' . '' . '
'; $this->assertEquals($expected, ob_get_clean()); } public function testFieldsFor() { ob_start(); $fields = $this->view->fieldsFor('post', $this->post); echo $fields->textField('title'); echo $fields->textArea('body'); echo $fields->checkBox('secret'); $fields->end(); $expected = '' . '' . '' . ''; $this->assertEquals($expected, ob_get_clean()); } public function testNestedFieldsFor() { ob_start(); $form = $this->view->formFor('post', $this->post); $fields = $form->fieldsFor('comment', $this->post); echo $fields->textField('title'); $fields->end(); $form->end(); $expected = '
' . '' . '
'; $this->assertEquals($expected, ob_get_clean()); } public function testFieldsForWithoutObject() { ob_start(); $fields = $this->view->fieldsFor('post'); echo $fields->textField('title'); echo $fields->textArea('body'); echo $fields->checkBox('secret'); $fields->end(); $expected = '' . '' . '' . ''; $this->assertEquals($expected, ob_get_clean()); } public function testFieldsForObjectWithBracketedName() { ob_start(); $fields = $this->view->fieldsFor('author[post]', $this->post); echo $fields->textField('title'); $fields->end(); $this->assertEquals( '', ob_get_clean()); } public function testFormBuilderDoesNotHaveFormForMethod() { $methods = get_class_methods('Horde_View_Helper_Form_Builder'); $this->assertTrue(empty($methods['formFor'])); } public function testFormForAndFieldsFor() { ob_start(); $postForm = $this->view->formFor('post', $this->post, array('html' => array('id' => 'create-post'))); echo $postForm->textField('title'); echo $postForm->textArea('body'); $parentFields = $this->view->fieldsFor('parent_post', $this->post); echo $parentFields->checkBox('secret'); $parentFields->end(); $postForm->end(); $expected = '
' . '' . '' . '' . '' . '
'; $this->assertEquals($expected, ob_get_clean()); } public function testFormForWithCustomBuilder() { ob_start(); $form = $this->view->formFor('post', $this->post, array('builder' => 'Horde_View_Helper_FormTest_BuilderMock')); echo $form->textField('bar'); echo $form->foo(); $form->end(); $expected = '
' . '' . ''; $this->assertEquals($expected, ob_get_clean()); } public function testDefaultFormBuilder() { $oldDefaultFormBuilder = Horde_View_Base::$defaultFormBuilder; Horde_View_Base::$defaultFormBuilder = 'Horde_View_Helper_FormTest_BuilderMock'; try { ob_start(); $form = $this->view->formFor('post', $this->post); echo $form->textField('bar'); echo $form->foo(); $form->end(); $expected = '
' . '' . ''; $this->assertEquals($expected, ob_get_clean()); } catch (Exception $e) {} Horde_View_Base::$defaultFormBuilder = $oldDefaultFormBuilder; } // @todo test_default_form_builder_with_active_record_helpers // @todo test_remote_form_for_with_labelled_builder public function testFieldsForWithCustomBuilder() { ob_start(); $fields = $this->view->fieldsFor('post', $this->post, array('builder' => 'Horde_View_Helper_FormTest_BuilderMock')); echo $fields->textField('bar'); echo $fields->foo(); $fields->end(); $this->assertEquals( '', ob_get_clean()); } public function testFormForWithHtmlOptionsAddsOptionsToFormTag() { ob_start(); $form = $this->view->formFor('post', $this->post, array('html' => array('id' => 'some_form', 'class' => 'some_class'))); $form->end(); $this->assertEquals( '
', ob_get_clean()); } public function testFormForWithHiddenField() { ob_start(); $form = $this->view->formFor('post', $this->post); echo $form->hiddenField('title'); $form->end(); $expected = '
' . '' . '
'; $this->assertEquals($expected, ob_get_clean()); } public function testFormForWithFileField() { ob_start(); $form = $this->view->formFor('post', $this->post); echo $form->fileField('title'); $form->end(); $expected = '
' . '' . '
'; $this->assertEquals($expected, ob_get_clean()); } // @todo test_form_for_with_string_url_option // @todo test_form_for_with_hash_url_option // @todo test_remote_form_for_with_html_options_adds_options_to_form_tag } class Horde_View_Helper_FormTest_MockUrlHelper extends Horde_View_Helper_Base { public function urlFor($options) { return 'http://www.example.com'; } } class Horde_View_Helper_FormTest_BuilderMock extends Horde_View_Helper_Form_Builder { public function foo() { return ''; } } Horde_View-2.0.6/test/Horde/View/Helper/JavascriptTest.php0000664000175000017500000000220112654104300021474 0ustar janjan * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage UnitTests */ /** * @group view * @author Mike Naberezny * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage UnitTests */ class Horde_View_Helper_JavascriptTest extends Horde_Test_Case { public function setUp() { $this->view = new Horde_View(); $this->view->addHelper('Javascript'); $this->view->addHelper('Tag'); } public function testJavascriptTag() { $this->assertEquals("", $this->view->javascriptTag('foo = 1;')); } } Horde_View-2.0.6/test/Horde/View/Helper/NumberTest.php0000664000175000017500000000477212654104300020635 0ustar janjan * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage UnitTests */ /** * @group view * @author Mike Naberezny * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage UnitTests */ class Horde_View_Helper_NumberTest extends Horde_Test_Case { public function setUp() { $this->helper = new Horde_View_Helper_Number(new Horde_View()); } public function testNumberToHumanSize() { setlocale(LC_NUMERIC, 'C'); $this->assertEquals('0 Bytes', $this->helper->numberToHumanSize(0)); $this->assertEquals('0 Bytes', $this->helper->numberToHumanSize(0)); $this->assertEquals('1 Byte', $this->helper->numberToHumanSize(1)); $this->assertEquals('3 Bytes', $this->helper->numberToHumanSize(3.14159265)); $this->assertEquals('123 Bytes', $this->helper->numberToHumanSize(123.0)); $this->assertEquals('123 Bytes', $this->helper->numberToHumanSize(123)); $this->assertEquals('1.2 KB', $this->helper->numberToHumanSize(1234)); $this->assertEquals('12.1 KB', $this->helper->numberToHumanSize(12345)); $this->assertEquals('1.2 MB', $this->helper->numberToHumanSize(1234567)); $this->assertEquals('1.1 GB', $this->helper->numberToHumanSize(1234567890)); $this->assertEquals('1.1 TB', $this->helper->numberToHumanSize(1234567890123)); $this->assertEquals('444 KB', $this->helper->numberToHumanSize(444 * 1024)); $this->assertEquals('1023 MB', $this->helper->numberToHumanSize(1023 * 1048576)); $this->assertEquals('3 TB', $this->helper->numberToHumanSize(3 * 1099511627776)); $this->assertEquals('1.18 MB', $this->helper->numberToHumanSize(1234567, 2)); $this->assertEquals('3 Bytes', $this->helper->numberToHumanSize(3.14159265, 4)); $this->assertEquals("123 Bytes", $this->helper->numberToHumanSize("123")); $this->assertNull($this->helper->numberToHumanSize('x')); $this->assertNull($this->helper->numberToHumanSize(null)); } } Horde_View-2.0.6/test/Horde/View/Helper/TagTest.php0000664000175000017500000000637312654104300020117 0ustar janjan * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage UnitTests */ /** * @group view * @author Mike Naberezny * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage UnitTests */ class Horde_View_Helper_TagTest extends Horde_Test_Case { public function setUp() { $this->view = new Horde_View(); $this->view->addHelper('Tag'); } public function testTag() { $this->assertEquals('
', $this->view->tag('br')); $this->assertEquals('
', $this->view->tag('br', array('clear' => 'left'))); } public function testTagOptions() { $this->assertRegExp('/\A

\z/', $this->view->tag('p', array('class' => 'show', 'class' => 'elsewhere'))); } public function testTagOptionsRejectsNullOption() { $this->assertEquals('

', $this->view->tag('p', array('ignored' => null))); } public function testTagOptionsAcceptsBlankOption() { $this->assertEquals('

', $this->view->tag('p', array('included' => ''))); } public function testTagOptionsConvertsBooleanOption() { $this->assertEquals('

', $this->view->tag('p', array('disabled' => true, 'multiple' => true, 'readonly' => true))); } public function testContentTag() { $this->assertEquals('Create', $this->view->contentTag('a', 'Create', array('href' => 'create'))); } public function testCdataSection() { $this->assertEquals(']]>', $this->view->cdataSection('')); } public function testEscapeOnce() { $this->assertEquals('1 < 2 & 3', $this->view->escapeOnce('1 < 2 & 3')); } public function testDoubleEscapingAttributes() { $attributes = array('1&2', '1 < 2', '“test“'); foreach ($attributes as $escaped) { $this->assertEquals("", $this->view->tag('a', array('href' => $escaped))); } } public function testSkipInvalidEscapedAttributes() { $attributes = array('&1;', 'dfa3;', '& #123;'); foreach ($attributes as $escaped) { $this->assertEquals('', $this->view->tag('a', array('href' => $escaped))); } } } Horde_View-2.0.6/test/Horde/View/Helper/TextTest.php0000664000175000017500000001606712654104300020331 0ustar janjan * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage UnitTests */ /** * @group view * @author Mike Naberezny * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage UnitTests */ class Horde_View_Helper_TextTest extends Horde_Test_Case { public function setUp() { $this->view = new Horde_View(); $this->view->addHelper('Text'); } // test escaping data public function testEscape() { $text = "Test 'escaping html' \"quotes\" and & amps"; $expected = "Test 'escaping html' "quotes" and & amps"; $this->assertEquals($expected, $this->view->h($text)); } // test truncate public function testTruncate() { $str = 'The quick brown fox jumps over the lazy dog tomorrow morning.'; $expected = 'The quick brown fox jumps over the la...'; $this->assertEquals($expected, $this->view->truncate($str, 40)); } // test truncate public function testTruncateMiddle() { $str = 'The quick brown fox jumps over the lazy dog tomorrow morning.'; $expected = 'The quick brown fox...tomorrow morning.'; $this->assertEquals($expected, $this->view->truncateMiddle($str, 40)); } // text too short to trucate public function testTruncateMiddleTooShort() { $str = 'The quick brown fox jumps over the dog.'; $expected = 'The quick brown fox jumps over the dog.'; $this->assertEquals($expected, $this->view->truncateMiddle($str, 40)); } // test highlighter public function testHighlightDefault() { $str = 'The quick brown fox jumps over the dog.'; $expected = 'The quick brown fox jumps over the dog.'; $this->assertEquals($expected, $this->view->highlight($str, 'brown')); } // test failure to highlight public function testHighlightCustom() { $str = 'The quick brown fox jumps over the dog.'; $expected = 'The quick brown fox jumps over the dog.'; $this->assertEquals($expected, $this->view->highlight($str, 'brown', '$1')); } // test failure to highlight public function testHighlightNoMatch() { $str = 'The quick brown fox jumps over the dog.'; $this->assertEquals($str, $this->view->highlight($str, 'black')); } public function testCycleClass() { $value = new Horde_View_Helper_Text_Cycle(array('one', 2, '3')); $this->assertEquals('one', (string)$value); $this->assertEquals('2', (string)$value); $this->assertEquals('3', (string)$value); $this->assertEquals('one', (string)$value); $value->reset(); $this->assertEquals('one', (string)$value); $this->assertEquals('2', (string)$value); $this->assertEquals('3', (string)$value); } public function testCycleClassWithInvalidArguments() { try { $value = new Horde_View_Helper_Text_Cycle('bad'); $this->fail(); } catch (InvalidArgumentException $e) {} try { $value = new Horde_View_Helper_Text_Cycle(array('foo')); $this->fail(); } catch (InvalidArgumentException $e) {} try { $value = new Horde_View_Helper_Text_Cycle(array('foo', 'bar'), 'bad-arg'); $this->fail(); } catch (InvalidArgumentException $e) {} } public function testCycleResetsWithNewValues() { $this->assertEquals('even', (string)$this->view->cycle('even', 'odd')); $this->assertEquals('odd', (string)$this->view->cycle('even', 'odd')); $this->assertEquals('even', (string)$this->view->cycle('even', 'odd')); $this->assertEquals('1', (string)$this->view->cycle(1, 2, 3)); $this->assertEquals('2', (string)$this->view->cycle(1, 2, 3)); $this->assertEquals('3', (string)$this->view->cycle(1, 2, 3)); } public function testNamedCycles() { $this->assertEquals('1', (string)$this->view->cycle(1, 2, 3, array('name' => 'numbers'))); $this->assertEquals('red', (string)$this->view->cycle('red', 'blue', array('name' => 'colors'))); $this->assertEquals('2', (string)$this->view->cycle(1, 2, 3, array('name' => 'numbers'))); $this->assertEquals('blue', (string)$this->view->cycle('red', 'blue', array('name' => 'colors'))); $this->assertEquals('3', (string)$this->view->cycle(1, 2, 3, array('name' => 'numbers'))); $this->assertEquals('red', (string)$this->view->cycle('red', 'blue', array('name' => 'colors'))); } public function testDefaultNamedCycle() { $this->assertEquals('1', (string)$this->view->cycle(1, 2, 3)); $this->assertEquals('2', (string)$this->view->cycle(1, 2, 3, array('name' => 'default'))); $this->assertEquals('3', (string)$this->view->cycle(1, 2, 3)); } public function testResetCycle() { $this->assertEquals('1', (string)$this->view->cycle(1, 2, 3)); $this->assertEquals('2', (string)$this->view->cycle(1, 2, 3)); $this->view->resetCycle(); $this->assertEquals('1', (string)$this->view->cycle(1, 2, 3)); } public function testResetUnknownCycle() { $this->view->resetCycle('colors'); } public function testResetNamedCycle() { $this->assertEquals('1', (string)$this->view->cycle(1, 2, 3, array('name' => 'numbers'))); $this->assertEquals('red', (string)$this->view->cycle('red', 'blue', array('name' => 'colors'))); $this->view->resetCycle('numbers'); $this->assertEquals('1', (string)$this->view->cycle(1, 2, 3, array('name' => 'numbers'))); $this->assertEquals('blue', (string)$this->view->cycle('red', 'blue', array('name' => 'colors'))); $this->assertEquals('2', (string)$this->view->cycle(1, 2, 3, array('name' => 'numbers'))); $this->assertEquals('red', (string)$this->view->cycle('red', 'blue', array('name' => 'colors'))); } public function testPluralization() { $this->assertEquals('1 count', $this->view->pluralize(1, 'count')); $this->assertEquals('2 counts', $this->view->pluralize(2, 'count')); $this->assertEquals('1 count', $this->view->pluralize('1', 'count')); $this->assertEquals('2 counts', $this->view->pluralize('2', 'count')); $this->assertEquals('1,066 counts', $this->view->pluralize('1,066', 'count')); $this->assertEquals('1.25 counts', $this->view->pluralize('1.25', 'count')); $this->assertEquals('2 counters', $this->view->pluralize('2', 'count', 'counters')); } } Horde_View-2.0.6/test/Horde/View/Helper/UrlTest.php0000664000175000017500000001656412654104300020151 0ustar janjan * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage UnitTests */ /** * @group view * @author Mike Naberezny * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage UnitTests */ class Horde_View_Helper_UrlTest extends Horde_Test_Case { public function setUp() { $controller = new Horde_View_Helper_UrlTest_MockController(); $this->view = new Horde_View(); $this->view->controller = $controller; $this->view->addHelper('Url'); $this->view->addHelper('Tag'); } public function testLinkTagWithStraightUrl() { $this->assertEquals('Hello', $this->view->linkTo('Hello', 'http://www.example.com')); } public function testLinkTagWithQuery() { $this->assertEquals('Hello', $this->view->linkTo('Hello', 'http://www.example.com?q1=v1&q2=v2')); } public function testLinkTagWithQueryAndNoName() { $this->assertEquals("http://www.example.com?q1=v1&q2=v2", $this->view->linkTo(null, 'http://www.example.com?q1=v1&q2=v2')); } public function testLinkTagWithImg() { $this->assertEquals("", $this->view->linkTo("", "http://www.example.com")); } public function testLinkToUnless() { $this->markTestIncomplete('Needs a a real routes mapper.'); $this->assertEquals('Showing', $this->view->linkToUnless(true, 'Showing', array('action' => 'show', 'controller' => 'weblog'))); $this->assertEquals("Listing", // @todo http://www.example.com $this->view->linkToUnless(false, 'Listing', array('action' => 'list', 'controller' => 'weblog'))); $this->assertEquals('Showing', $this->view->linkToUnless(true, 'Showing', array('action' => 'show', 'controller' => 'weblog', 'id' => 1))); } public function testLinkToIf() { $this->markTestIncomplete('Needs a a real routes mapper.'); $this->assertEquals('Showing', $this->view->linkToIf(false, 'Showing', array('action' => 'show', 'controller' => 'weblog'))); $this->assertEquals("Listing", // @todo http://www.example.com $this->view->linkToIf(true, 'Listing', array('action' => 'list', 'controller' => 'weblog'))); $this->assertEquals('Showing', $this->view->linkToIf(false, 'Showing', array('action' => 'show', 'controller' => 'weblog', 'id' => 1))); } public function testMailTo() { $this->assertEquals("david@loudthinking.com", $this->view->mailTo("david@loudthinking.com")); $this->assertEquals("David Heinemeier Hansson", $this->view->mailTo("david@loudthinking.com", "David Heinemeier Hansson")); $this->assertEquals("David Heinemeier Hansson", $this->view->mailTo("david@loudthinking.com", "David Heinemeier Hansson", array("class" => "admin"))); } public function testMailToWithJavascript() { $this->assertEquals("", $this->view->mailTo("me@domain.com", "My email", array('encode' => 'javascript'))); } public function testMailWithOptions() { $this->assertEquals('My email', $this->view->mailTo("me@example.com", "My email", array('cc' => "ccaddress@example.com", 'bcc' => "bccaddress@example.com", 'subject' => "This is an example email", 'body' => "This is the body of the message."))); } public function testMailToWithImg() { $this->assertEquals('', $this->view->mailTo('feedback@example.com', '')); } public function testMailToWithHex() { $this->assertEquals("My email", $this->view->mailTo("me@domain.com", "My email", array('encode' => "hex"))); $this->assertEquals("me@domain.com", $this->view->mailTo("me@domain.com", null, array('encode' => "hex"))); } public function testMailToWithReplaceOptions() { $this->assertEquals("wolfgang(at)stufenlos(dot)net", $this->view->mailTo("wolfgang@stufenlos.net", null, array('replaceAt' => "(at)", 'replaceDot' => "(dot)"))); $this->assertEquals("me(at)domain.com", $this->view->mailTo("me@domain.com", null, array('encode' => "hex", 'replaceAt' => "(at)"))); $this->assertEquals("My email", $this->view->mailTo("me@domain.com", "My email", array('encode' => "hex", 'replaceAt' => "(at)"))); $this->assertEquals("me(at)domain(dot)com", $this->view->mailTo("me@domain.com", null, array('encode' => "hex", 'replaceAt' => "(at)", 'replaceDot' => "(dot)"))); } } class Horde_View_Helper_UrlTest_MockController extends Horde_Controller_Base { public function processRequest(Horde_Controller_Request $request, Horde_Controller_Response $response) { } public function getUrlWriter() { return new Horde_Controller_UrlWriter(new Horde_Routes_Utils(new Horde_Routes_Mapper())); } } Horde_View-2.0.6/test/Horde/View/AllTests.php0000664000175000017500000000013212654104300017043 0ustar janjanrun(); Horde_View-2.0.6/test/Horde/View/BaseTest.php0000664000175000017500000002003312654104300017024 0ustar janjan * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage UnitTests */ /** * @group view * @author Mike Naberezny * @author Derek DeVries * @author Chuck Hagenbuch * @license http://www.horde.org/licenses/bsd * @category Horde * @package View * @subpackage UnitTests */ class Horde_View_BaseTest extends Horde_Test_Case { protected $_view = null; public function setUp() { $this->_view = new Horde_View(); $this->_view->addTemplatePath(__DIR__ . '/fixtures/'); } /*########################################################################## # Assignment ##########################################################################*/ // test setting/getting dynamic properties public function testSet() { $this->_view->publicVar = 'test'; $this->assertEquals('test', $this->_view->publicVar); } public function testAssign() { $this->_view->assign(array('publicVar' => 'test')); $this->assertEquals('test', $this->_view->publicVar); } public function testAssignDoesntOverridePrivateVariables() { try { $this->_view->assign(array('_templatePath' => 'test')); } catch (Exception $e) { return; } $this->fail('Overwriting a private/protected variable should fail'); } public function testAssignAllowsUnderscoreVariables() { $this->_view->assign(array('_private' => 'test')); $this->assertEquals('test', $this->_view->_private); } // test accessing variable public function testAccessVar() { $this->_view->testVar = 'test'; $this->assertTrue(!empty($this->_view->testVar)); $this->_view->testVar2 = ''; $this->assertTrue(empty($this->_view->testVar2)); $this->assertTrue(isset($this->_view->testVar2)); $this->assertTrue(!isset($this->_view->testVar3)); } // test adding a template path public function testAddTemplatePath() { $this->_view->addTemplatePath('app/views/shared/'); $expected = array('app/views/shared/', __DIR__ . '/fixtures/', './'); $this->assertEquals($expected, $this->_view->getTemplatePaths()); } // test adding a template path public function testAddTemplatePathAddSlash() { $this->_view->addTemplatePath('app/views/shared'); $expected = array('app/views/shared/', __DIR__ . '/fixtures/', './'); $this->assertEquals($expected, $this->_view->getTemplatePaths()); } /*########################################################################## # Rendering ##########################################################################*/ // test rendering public function testRender() { $this->_view->myVar = 'test'; $expected = "

test
"; $this->assertEquals($expected, $this->_view->render('testRender.html.php')); } // test rendering public function testRenderNoExtension() { $this->_view->myVar = 'test'; $expected = "
test
"; $this->assertEquals($expected, $this->_view->render('testRender')); } // test that the public function testRenderPathOrder() { $this->_view->myVar = 'test'; // we should be rendering the testRender.html in fixtures/ $expected = "
test
"; $this->assertEquals($expected, $this->_view->render('testRender')); // after we specify the 'subdir' path, it should read from subdir path first $this->_view->addTemplatePath(__DIR__ . '/fixtures/subdir/'); $expected = "
subdir test
"; $this->assertEquals($expected, $this->_view->render('testRender')); } /*########################################################################## # Partials ##########################################################################*/ // test rendering partial public function testRenderPartial() { $this->_view->myVar1 = 'main'; $this->_view->myVar2 = 'partial'; $expected = '
main

partial

'; $this->assertEquals($expected, $this->_view->render('testPartial')); } // test rendering partial with object passed in public function testRenderPartialObject() { $this->_view->myObject = (object)array('string_value' => 'hello world'); $expected = '

hello world

'; $this->assertEquals($expected, $this->_view->render('testPartialObject')); } // test rendering partial with locals passed in public function testRenderPartialLocals() { $expected = '

hello world

'; $this->assertEquals($expected, $this->_view->render('testPartialLocals')); } // test rendering partial with collection passed in public function testRenderPartialCollection() { $this->_view->myObjects = array((object)array('string_value' => 'hello'), (object)array('string_value' => 'world')); $expected = '

hello

world

'; $this->assertEquals($expected, $this->_view->render('testPartialCollection')); } // test rendering partial with empty set as collection public function testRenderPartialCollectionEmpty() { $this->_view->myObjects = null; $expected = '
'; $this->assertEquals($expected, $this->_view->render('testPartialCollection')); } // test rendering partial with empty array as collection public function testRenderPartialCollectionEmptyArray() { $this->_view->myObjects = array(); $expected = '
'; $this->assertEquals($expected, $this->_view->render('testPartialCollection')); } // partial collection is a model collection public function testRenderPartialModelCollection() { $this->_view->myObjects = array((object)array('string_value' => 'name a'), (object)array('string_value' => 'name b')); $expected = '

name a

name b

'; $this->assertEquals($expected, $this->_view->render('testPartialCollection')); } /*########################################################################## # Escape output ##########################################################################*/ public function testEscapeTemplate() { $this->_view->myVar = '"escaping"'; $this->_view->addHelper(new Horde_View_Helper_Text($this->_view)); $expected = "
test "escaping" quotes
"; $this->assertEquals($expected, $this->_view->render('testEscape')); } // test adding a helper public function testAddHorde_View_Helper_Text() { $str = 'The quick brown fox jumps over the lazy dog tomorrow morning.'; // helper doesn't exist try { $this->_view->truncateMiddle($str, 40); } catch (Exception $e) {} $this->assertTrue($e instanceof Horde_View_Exception); // add text helper $this->_view->addHelper(new Horde_View_Helper_Text($this->_view)); $expected = 'The quick brown fox...tomorrow morning.'; $this->assertEquals($expected, $this->_view->truncateMiddle($str, 40)); } // test adding a helper where methods conflict public function testAddHorde_View_Helper_TextMethodOverwrite() { // add text helper $this->_view->addHelper(new Horde_View_Helper_Text($this->_view)); // successful when trying to add it again $this->_view->addHelper(new Horde_View_Helper_Text($this->_view)); } } Horde_View-2.0.6/test/Horde/View/bootstrap.php0000664000175000017500000000014312654104300017327 0ustar janjan * @category Horde * @package View * @subpackage UnitTests */ /** * @group view * @author Chuck Hagenbuch * @category Horde * @package View * @subpackage UnitTests */ class Horde_View_InterfaceTest extends PHPUnit_Framework_TestCase { public function testViewInterface() { eval('class Test_View extends Horde_View implements Horde_View_Interface {};'); } } Horde_View-2.0.6/test/Horde/View/phpunit.xml0000664000175000017500000000030612654104300017013 0ustar janjan ../../../lib