Compare commits

...

35 Commits

Author SHA1 Message Date
dbabd89491 Backport Login changes
Password change backport
2018-05-09 15:11:06 +09:00
9842c979b6 Backport of missing password changes for Login class
move password check into method.
do proper check for password change.
remove all password log/error outputs. ever.
2018-05-09 12:26:01 +09:00
85a327f45f Backport new password interface to legacy classes 2018-05-09 11:47:16 +09:00
7b085f86f0 Change to <?php for core core classes
Basic/DB IO/db_pgsql switch only
2018-04-17 10:05:41 +09:00
Clemens Schwaighofer
484444b97a tmp folder in 4dev 2018-03-28 14:31:14 +09:00
6dc6a58765 Fix impossible lang translate call in basic lib 2018-03-28 10:40:27 +09:00
ca8da46a58 Merge branch 'master' of git.tokyo.tequila.jp:/var/lib/git/php_core 2018-03-28 10:02:27 +09:00
a28e5244ab Fixes & code style changes 2018-03-28 10:02:19 +09:00
Clemens Schwaighofer
31acfd1ee4 Update to Smarty 3.1.30
Keep old 3.1.27 around for testing
2018-03-22 10:22:37 +09:00
Clemens Schwaighofer
f1155ad824 Rename wrong named (extension) translation files 2018-03-20 17:09:42 +09:00
Clemens Schwaighofer
eef3a81be7 Minor update for DB psql class include 2018-03-20 14:10:06 +09:00
Clemens Schwaighofer
bf60e9fcbf Readme update 2018-03-20 14:05:37 +09:00
7d42256a30 PHP CodeStandard update
- all if/while/for/etc blocks have brackets on same line
- functions have brackets on new line
- no blocks without brackets
- all code starts on col 0 and there are no tab intends anymore

off: came case for classes and class methods
ignore: _ prefix functions (we can't change that anymore)
2018-03-15 17:38:33 +09:00
Clemens Schwaighofer
5226fbcfc3 error reporting test 2018-03-14 15:36:42 +09:00
Clemens Schwaighofer
87b9af9786 PHP Notice warning fixes 2018-03-13 18:37:04 +09:00
Clemens Schwaighofer
7981e3ab51 Fix Class DB not init for dbh check on close db handler 2018-03-13 13:42:25 +09:00
Clemens Schwaighofer
21b9b99197 Minor white space clean up in login class and DB Array IO 2018-02-19 10:44:25 +09:00
Clemens Schwaighofer
d9df0d64b8 Class DB IO, fix for trailing ; with RETURNING
If an INSERT query has no RETURNING but ; at the end, the RETURNING was
added after the ;

The ; is now stripped before adding RETURNING
2018-02-08 10:58:53 +09:00
Clemens Schwaighofer
73cdbe27c0 Fix JavaScript SetCenter 2018-02-08 10:45:48 +09:00
759b5527f8 Update LICENSE
Switched from wrong lesser GPL v3 to correct GPL v3
2018-01-10 10:58:04 +09:00
8417e60c9d Remove any old BSD License info because we switched to GPL 3
Add missing folders + gitignore files
2018-01-10 10:53:48 +09:00
aec8a5ee70 Merge pull request #1 from gullevek/add-license-1
Create LICENSE
2018-01-10 10:46:41 +09:00
f34d4214f4 Create LICENSE
Added missing GPL 3 License (this overrides all licenses added in the system)
2018-01-10 10:46:26 +09:00
a2b6f29886 Remove old settings info 2017-12-07 14:30:57 +09:00
a95d28a09f Rename the README file for github 2017-12-07 14:27:51 +09:00
Clemens Schwaighofer
57b1aae9b4 Remove Smarty 3.1.21 folder 2017-12-07 14:23:49 +09:00
42b4112a5e Merge branch 'master' of git.tokyo.tequila.jp:/var/lib/git/php_core 2017-11-28 13:33:53 +09:00
63a2495183 white space fixes 2017-11-28 13:33:40 +09:00
Clemens Schwaighofer
717962edc5 Bug fix for session name set in basic class, add info methods for l10n
The session name was never set correctly because it was not checked for
the define var, but for a normal variable in the basic session name
settings flow

The l10n class has two new return methods for lang and mofile to check
if the correct ones are set
2017-11-28 12:01:15 +09:00
Clemens Schwaighofer
dc692f14e4 white space fixes 2017-11-24 16:49:45 +09:00
b1a30b6dde White space fixes 2017-11-24 16:46:31 +09:00
967af4dc37 Core libraries white space fixes 2017-11-24 13:27:13 +09:00
Clemens Schwaighofer
7a8fdcdf07 white space fixes for Form class 2017-11-24 13:22:20 +09:00
Clemens Schwaighofer
a06320c42b white space fixes for Class DB IO 2017-11-24 13:20:28 +09:00
Clemens Schwaighofer
f0ba8c3c50 email regex check update, remove warning surpress in pgsql wrapper, l10n
- l10n class has better mo file load check
- fix email regex for last part is now only on minimum 2 char check
- remove all @ warning surpress in the pgsql wrapper
2017-11-24 13:06:14 +09:00
309 changed files with 35837 additions and 31832 deletions

View File

@@ -5,9 +5,9 @@
#echo "EXIT"; #echo "EXIT";
#exit; #exit;
db='cibavision_jp_cms'; db='<db name>';
host='db.tokyo.tequila.jp'; host='<db host>';
user='ciba_vision'; user='<db user>';
schemas="public dev"; schemas="public dev";
file_prefix="trg"; file_prefix="trg";

View File

@@ -5,9 +5,9 @@
#echo "EXIT"; #echo "EXIT";
#exit; #exit;
db='gullevek'; db='<db name>';
host='db.tokyo.tequila.jp'; host='<db host>';
user='gullevek'; user='<db user>';
#schema="publicv"; #schema="publicv";
for file in `cat ORDER`; for file in `cat ORDER`;

File diff suppressed because one or more lines are too long

View File

@@ -3,10 +3,10 @@
# create path # create path
path=`pwd`"/"$0; path=`pwd`"/"$0;
LOCAL_BASE_DIR=""; LOCAL_BASE_DIR="<local folder>";
LOCAL_DIR=$LOCAL_BASE_DIR""; LOCAL_DIR=$LOCAL_BASE_DIR"";
REMOTE_WEB=""; REMOTE_WEB="<remote folder>";
TARGET_HOST_WEB="developer@10.76.32.25"; TARGET_HOST_WEB="<user>@<host>
TMP_DIR=$LOCAL_BASE_DIR"/4dev/"; TMP_DIR=$LOCAL_BASE_DIR"/4dev/";
tmpf_web=$TMP_DIR"tmp.web"; tmpf_web=$TMP_DIR"tmp.web";

2
4dev/tmp/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
*
!.gitignore

674
LICENSE Normal file
View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, 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
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If 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 convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU 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
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "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 PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM 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 PROGRAM (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 PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

10
README
View File

@@ -1,10 +0,0 @@
PHP Core Library
================
Base PHP class files to setup any project
* login
* database wrapper
* basic helper class for debugging and other features
* admin/frontend split
* domain controlled database/settings split
* dynamic layout groups

25
README.md Normal file
View File

@@ -0,0 +1,25 @@
# PHP Core Library
Base PHP class files to setup any project
* login
* database wrapper
* basic helper class for debugging and other features
* admin/frontend split
* domain controlled database/settings split
* dynamic layout groups
## NOTE
There are three branches:
### master
This is currently the legacy branch set live. This will change to the namespace branch once development is finished
### legacy
The old non namepsace format layout. This will only get bug fixes and no new development
### namespace
The new namespace branch. Once development is finished this branch will be removed or renamed to development only branch

View File

@@ -1 +1 @@
smarty-3.1.27/ smarty-3.1.30

File diff suppressed because it is too large Load Diff

View File

@@ -1,78 +0,0 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsFunction
*/
/**
* Smarty {counter} function plugin
* Type: function<br>
* Name: counter<br>
* Purpose: print out a counter value
*
* @author Monte Ohrt <monte at ohrt dot com>
* @link http://www.smarty.net/manual/en/language.function.counter.php {counter}
* (Smarty online manual)
*
* @param array $params parameters
* @param Smarty_Internal_Template $template template object
*
* @return string|null
*/
function smarty_function_counter($params, $template)
{
static $counters = array();
$name = (isset($params['name'])) ? $params['name'] : 'default';
if (!isset($counters[$name])) {
$counters[$name] = array(
'start' => 1,
'skip' => 1,
'direction' => 'up',
'count' => 1
);
}
$counter =& $counters[$name];
if (isset($params['start'])) {
$counter['start'] = $counter['count'] = (int) $params['start'];
}
if (!empty($params['assign'])) {
$counter['assign'] = $params['assign'];
}
if (isset($counter['assign'])) {
$template->assign($counter['assign'], $counter['count']);
}
if (isset($params['print'])) {
$print = (bool) $params['print'];
} else {
$print = empty($counter['assign']);
}
if ($print) {
$retval = $counter['count'];
} else {
$retval = null;
}
if (isset($params['skip'])) {
$counter['skip'] = $params['skip'];
}
if (isset($params['direction'])) {
$counter['direction'] = $params['direction'];
}
if ($counter['direction'] == "down") {
$counter['count'] -= $counter['skip'];
} else {
$counter['count'] += $counter['skip'];
}
return $retval;
}

View File

@@ -1,50 +0,0 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty unescape modifier plugin
* Type: modifier<br>
* Name: unescape<br>
* Purpose: unescape html entities
*
* @author Rodney Rehm
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_unescape($params)
{
if (!isset($params[1])) {
$params[1] = 'html';
}
if (!isset($params[2])) {
$params[2] = '\'' . addslashes(Smarty::$_CHARSET) . '\'';
} else {
$params[2] = "'" . $params[2] . "'";
}
switch (trim($params[1], '"\'')) {
case 'entity':
case 'htmlall':
if (Smarty::$_MBSTRING) {
return 'mb_convert_encoding(' . $params[0] . ', ' . $params[2] . ', \'HTML-ENTITIES\')';
}
return 'html_entity_decode(' . $params[0] . ', ENT_NOQUOTES, ' . $params[2] . ')';
case 'html':
return 'htmlspecialchars_decode(' . $params[0] . ', ENT_QUOTES)';
case 'url':
return 'rawurldecode(' . $params[0] . ')';
default:
return $params[0];
}
}

View File

@@ -1,47 +0,0 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty wordwrap modifier plugin
* Type: modifier<br>
* Name: wordwrap<br>
* Purpose: wrap a string of text at a given length
*
* @link http://smarty.php.net/manual/en/language.modifier.wordwrap.php wordwrap (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
* @param $compiler
*
* @return string with compiled code
*/
function smarty_modifiercompiler_wordwrap($params, $compiler)
{
if (!isset($params[1])) {
$params[1] = 80;
}
if (!isset($params[2])) {
$params[2] = '"\n"';
}
if (!isset($params[3])) {
$params[3] = 'false';
}
$function = 'wordwrap';
if (Smarty::$_MBSTRING) {
if ($compiler->template->caching && ($compiler->tag_nocache | $compiler->nocache)) {
$compiler->template->required_plugins['nocache']['wordwrap']['modifier']['file'] = SMARTY_PLUGINS_DIR . 'shared.mb_wordwrap.php';
$compiler->template->required_plugins['nocache']['wordwrap']['modifier']['function'] = 'smarty_mb_wordwrap';
} else {
$compiler->template->required_plugins['compiled']['wordwrap']['modifier']['file'] = SMARTY_PLUGINS_DIR . 'shared.mb_wordwrap.php';
$compiler->template->required_plugins['compiled']['wordwrap']['modifier']['function'] = 'smarty_mb_wordwrap';
}
$function = 'smarty_mb_wordwrap';
}
return $function . '(' . $params[0] . ',' . $params[1] . ',' . $params[2] . ',' . $params[3] . ')';
}

View File

@@ -1,53 +0,0 @@
<?php
/**
* Smarty shared plugin
*
* @package Smarty
* @subpackage PluginsShared
*/
if (version_compare(PHP_VERSION, '5.2.3', '>=')) {
/**
* escape_special_chars common function
* Function: smarty_function_escape_special_chars<br>
* Purpose: used by other smarty functions to escape
* special chars except for already escaped ones
*
* @author Monte Ohrt <monte at ohrt dot com>
*
* @param string $string text that should by escaped
*
* @return string
*/
function smarty_function_escape_special_chars($string)
{
if (!is_array($string)) {
$string = htmlspecialchars($string, ENT_COMPAT, Smarty::$_CHARSET, false);
}
return $string;
}
} else {
/**
* escape_special_chars common function
* Function: smarty_function_escape_special_chars<br>
* Purpose: used by other smarty functions to escape
* special chars except for already escaped ones
*
* @author Monte Ohrt <monte at ohrt dot com>
*
* @param string $string text that should by escaped
*
* @return string
*/
function smarty_function_escape_special_chars($string)
{
if (!is_array($string)) {
$string = preg_replace('!&(#?\w+);!', '%%%SMARTY_START%%%\\1%%%SMARTY_END%%%', $string);
$string = htmlspecialchars($string);
$string = str_replace(array('%%%SMARTY_START%%%', '%%%SMARTY_END%%%'), array('&', ';'), $string);
}
return $string;
}
}

View File

@@ -1,442 +0,0 @@
<?php
/**
* Smarty Internal Plugin
*
* @package Smarty
* @subpackage Cacher
*/
/**
* Cache Handler API
*
* @package Smarty
* @subpackage Cacher
* @author Rodney Rehm
*/
abstract class Smarty_CacheResource
{
/**
* cache for Smarty_CacheResource instances
*
* @var array
*/
public static $resources = array();
/**
* resource types provided by the core
*
* @var array
*/
protected static $sysplugins = array(
'file' => true,
);
/**
* populate Cached Object with meta data from Resource
*
* @param Smarty_Template_Cached $cached cached object
* @param Smarty_Internal_Template $_template template object
*
* @return void
*/
abstract public function populate(Smarty_Template_Cached $cached, Smarty_Internal_Template $_template);
/**
* populate Cached Object with timestamp and exists from Resource
*
* @param Smarty_Template_Cached $cached
*
* @return void
*/
abstract public function populateTimestamp(Smarty_Template_Cached $cached);
/**
* Read the cached template and process header
*
* @param Smarty_Internal_Template $_template template object
* @param Smarty_Template_Cached $cached cached object
*
* @return boolean true or false if the cached content does not exist
*/
abstract public function process(Smarty_Internal_Template $_template, Smarty_Template_Cached $cached = null);
/**
* Write the rendered template output to cache
*
* @param Smarty_Internal_Template $_template template object
* @param string $content content to cache
*
* @return boolean success
*/
abstract public function writeCachedContent(Smarty_Internal_Template $_template, $content);
/**
* Return cached content
*
* @param Smarty_Internal_Template $_template template object
*
* @return null|string
*/
public function getCachedContent(Smarty_Internal_Template $_template)
{
if ($_template->cached->handler->process($_template)) {
ob_start();
$_template->properties['unifunc']($_template);
return ob_get_clean();
}
return null;
}
/**
* Empty cache
*
* @param Smarty $smarty Smarty object
* @param integer $exp_time expiration time (number of seconds, not timestamp)
*
* @return integer number of cache files deleted
*/
abstract public function clearAll(Smarty $smarty, $exp_time = null);
/**
* Empty cache for a specific template
*
* @param Smarty $smarty Smarty object
* @param string $resource_name template name
* @param string $cache_id cache id
* @param string $compile_id compile id
* @param integer $exp_time expiration time (number of seconds, not timestamp)
*
* @return integer number of cache files deleted
*/
abstract public function clear(Smarty $smarty, $resource_name, $cache_id, $compile_id, $exp_time);
/**
* @param Smarty $smarty
* @param Smarty_Template_Cached $cached
*
* @return bool|null
*/
public function locked(Smarty $smarty, Smarty_Template_Cached $cached)
{
// theoretically locking_timeout should be checked against time_limit (max_execution_time)
$start = microtime(true);
$hadLock = null;
while ($this->hasLock($smarty, $cached)) {
$hadLock = true;
if (microtime(true) - $start > $smarty->locking_timeout) {
// abort waiting for lock release
return false;
}
sleep(1);
}
return $hadLock;
}
/**
* Check is cache is locked for this template
*
* @param Smarty $smarty
* @param Smarty_Template_Cached $cached
*
* @return bool
*/
public function hasLock(Smarty $smarty, Smarty_Template_Cached $cached)
{
// check if lock exists
return false;
}
/**
* Lock cache for this template
*
* @param Smarty $smarty
* @param Smarty_Template_Cached $cached
*
* @return bool
*/
public function acquireLock(Smarty $smarty, Smarty_Template_Cached $cached)
{
// create lock
return true;
}
/**
* Unlock cache for this template
*
* @param Smarty $smarty
* @param Smarty_Template_Cached $cached
*
* @return bool
*/
public function releaseLock(Smarty $smarty, Smarty_Template_Cached $cached)
{
// release lock
return true;
}
/**
* Load Cache Resource Handler
*
* @param Smarty $smarty Smarty object
* @param string $type name of the cache resource
*
* @throws SmartyException
* @return Smarty_CacheResource Cache Resource Handler
*/
public static function load(Smarty $smarty, $type = null)
{
if (!isset($type)) {
$type = $smarty->caching_type;
}
// try smarty's cache
if (isset($smarty->_cacheresource_handlers[$type])) {
return $smarty->_cacheresource_handlers[$type];
}
// try registered resource
if (isset($smarty->registered_cache_resources[$type])) {
// do not cache these instances as they may vary from instance to instance
return $smarty->_cacheresource_handlers[$type] = $smarty->registered_cache_resources[$type];
}
// try sysplugins dir
if (isset(self::$sysplugins[$type])) {
if (!isset(self::$resources[$type])) {
$cache_resource_class = 'Smarty_Internal_CacheResource_' . ucfirst($type);
self::$resources[$type] = new $cache_resource_class();
}
return $smarty->_cacheresource_handlers[$type] = self::$resources[$type];
}
// try plugins dir
$cache_resource_class = 'Smarty_CacheResource_' . ucfirst($type);
if ($smarty->loadPlugin($cache_resource_class)) {
if (!isset(self::$resources[$type])) {
self::$resources[$type] = new $cache_resource_class();
}
return $smarty->_cacheresource_handlers[$type] = self::$resources[$type];
}
// give up
throw new SmartyException("Unable to load cache resource '{$type}'");
}
/**
* Invalid Loaded Cache Files
*
* @param Smarty $smarty Smarty object
*/
public static function invalidLoadedCache(Smarty $smarty)
{
foreach ($smarty->template_objects as $tpl) {
if (isset($tpl->cached)) {
$tpl->cached->valid = false;
$tpl->cached->processed = false;
}
}
}
}
/**
* Smarty Resource Data Object
* Cache Data Container for Template Files
*
* @package Smarty
* @subpackage TemplateResources
* @author Rodney Rehm
*/
class Smarty_Template_Cached
{
/**
* Source Filepath
*
* @var string
*/
public $filepath = false;
/**
* Source Content
*
* @var string
*/
public $content = null;
/**
* Source Timestamp
*
* @var integer
*/
public $timestamp = false;
/**
* Source Existence
*
* @var boolean
*/
public $exists = false;
/**
* Cache Is Valid
*
* @var boolean
*/
public $valid = false;
/**
* Cache was processed
*
* @var boolean
*/
public $processed = false;
/**
* CacheResource Handler
*
* @var Smarty_CacheResource
*/
public $handler = null;
/**
* Template Compile Id (Smarty_Internal_Template::$compile_id)
*
* @var string
*/
public $compile_id = null;
/**
* Template Cache Id (Smarty_Internal_Template::$cache_id)
*
* @var string
*/
public $cache_id = null;
/**
* Id for cache locking
*
* @var string
*/
public $lock_id = null;
/**
* flag that cache is locked by this instance
*
* @var bool
*/
public $is_locked = false;
/**
* Source Object
*
* @var Smarty_Template_Source
*/
public $source = null;
/**
* create Cached Object container
*
* @param Smarty_Internal_Template $_template template object
*/
public function __construct(Smarty_Internal_Template $_template)
{
$this->compile_id = $_template->compile_id;
$this->cache_id = $_template->cache_id;
$this->source = $_template->source;
$_template->cached = $this;
$smarty = $_template->smarty;
//
// load resource handler
//
$this->handler = $handler = Smarty_CacheResource::load($smarty); // Note: prone to circular references
//
// check if cache is valid
//
if (!($_template->caching == Smarty::CACHING_LIFETIME_CURRENT || $_template->caching == Smarty::CACHING_LIFETIME_SAVED) || $_template->source->recompiled) {
$handler->populate($this, $_template);
return;
}
while (true) {
while (true) {
$handler->populate($this, $_template);
if ($this->timestamp === false || $smarty->force_compile || $smarty->force_cache) {
$this->valid = false;
} else {
$this->valid = true;
}
if ($this->valid && $_template->caching == Smarty::CACHING_LIFETIME_CURRENT && $_template->cache_lifetime >= 0 && time() > ($this->timestamp + $_template->cache_lifetime)) {
// lifetime expired
$this->valid = false;
}
if ($this->valid || !$_template->smarty->cache_locking) {
break;
}
if (!$this->handler->locked($_template->smarty, $this)) {
$this->handler->acquireLock($_template->smarty, $this);
break 2;
}
}
if ($this->valid) {
if (!$_template->smarty->cache_locking || $this->handler->locked($_template->smarty, $this) === null) {
// load cache file for the following checks
if ($smarty->debugging) {
Smarty_Internal_Debug::start_cache($_template);
}
if ($handler->process($_template, $this) === false) {
$this->valid = false;
} else {
$this->processed = true;
}
if ($smarty->debugging) {
Smarty_Internal_Debug::end_cache($_template);
}
} else {
continue;
}
} else {
return;
}
if ($this->valid && $_template->caching === Smarty::CACHING_LIFETIME_SAVED && $_template->properties['cache_lifetime'] >= 0 && (time() > ($_template->cached->timestamp + $_template->properties['cache_lifetime']))) {
$this->valid = false;
}
if (!$this->valid && $_template->smarty->cache_locking) {
$this->handler->acquireLock($_template->smarty, $this);
return;
} else {
return;
}
}
}
/**
* Write this cache object to handler
*
* @param Smarty_Internal_Template $_template template object
* @param string $content content to cache
*
* @return boolean success
*/
public function write(Smarty_Internal_Template $_template, $content)
{
if (!$_template->source->recompiled) {
if ($this->handler->writeCachedContent($_template, $content)) {
$this->content = null;
$this->timestamp = time();
$this->exists = true;
$this->valid = true;
if ($_template->smarty->cache_locking) {
$this->handler->releaseLock($_template->smarty, $this);
}
return true;
}
}
return false;
}
}

View File

@@ -1,94 +0,0 @@
<?php
/**
* Smarty Internal Plugin
*
* @package Smarty
* @subpackage TemplateResources
*/
/**
* Smarty Resource Data Object
* Meta Data Container for Config Files
*
* @package Smarty
* @subpackage TemplateResources
* @author Rodney Rehm
* @property string $content
* @property int $timestamp
* @property bool $exists
*/
class Smarty_Config_Source extends Smarty_Template_Source
{
/**
* create Config Object container
*
* @param Smarty_Resource $handler Resource Handler this source object communicates with
* @param Smarty $smarty Smarty instance this source object belongs to
* @param string $resource full config_resource
* @param string $type type of resource
* @param string $name resource name
* @param string $unique_resource unqiue resource name
*/
public function __construct(Smarty_Resource $handler, Smarty $smarty, $resource, $type, $name, $unique_resource)
{
$this->handler = $handler; // Note: prone to circular references
// Note: these may be ->config_compiler_class etc in the future
//$this->config_compiler_class = $handler->config_compiler_class;
//$this->config_lexer_class = $handler->config_lexer_class;
//$this->config_parser_class = $handler->config_parser_class;
$this->smarty = $smarty;
$this->resource = $resource;
$this->type = $type;
$this->name = $name;
$this->unique_resource = $unique_resource;
}
/**
* <<magic>> Generic setter.
*
* @param string $property_name valid: content, timestamp, exists
* @param mixed $value newly assigned value (not check for correct type)
*
* @throws SmartyException when the given property name is not valid
*/
public function __set($property_name, $value)
{
switch ($property_name) {
case 'content':
case 'timestamp':
case 'exists':
$this->$property_name = $value;
break;
default:
throw new SmartyException("invalid config property '$property_name'.");
}
}
/**
* <<magic>> Generic getter.
*
* @param string $property_name valid: content, timestamp, exists
*
* @return mixed|void
* @throws SmartyException when the given property name is not valid
*/
public function __get($property_name)
{
switch ($property_name) {
case 'timestamp':
case 'exists':
$this->handler->populateTimestamp($this);
return $this->$property_name;
case 'content':
return $this->content = $this->handler->getContent($this);
default:
throw new SmartyException("config property '$property_name' does not exist.");
}
}
}

View File

@@ -1,297 +0,0 @@
<?php
/**
* Smarty Internal Plugin CacheResource File
*
* @package Smarty
* @subpackage Cacher
* @author Uwe Tews
* @author Rodney Rehm
*/
/**
* This class does contain all necessary methods for the HTML cache on file system
* Implements the file system as resource for the HTML cache Version ussing nocache inserts.
*
* @package Smarty
* @subpackage Cacher
*/
class Smarty_Internal_CacheResource_File extends Smarty_CacheResource
{
/**
* populate Cached Object with meta data from Resource
*
* @param Smarty_Template_Cached $cached cached object
* @param Smarty_Internal_Template $_template template object
*
* @return void
*/
public function populate(Smarty_Template_Cached $cached, Smarty_Internal_Template $_template)
{
$_source_file_path = str_replace(':', '.', $_template->source->filepath);
$_cache_id = isset($_template->cache_id) ? preg_replace('![^\w\|]+!', '_', $_template->cache_id) : null;
$_compile_id = isset($_template->compile_id) ? preg_replace('![^\w\|]+!', '_', $_template->compile_id) : null;
$_filepath = $_template->source->uid;
// if use_sub_dirs, break file into directories
if ($_template->smarty->use_sub_dirs) {
$_filepath = substr($_filepath, 0, 2) . DS
. substr($_filepath, 2, 2) . DS
. substr($_filepath, 4, 2) . DS
. $_filepath;
}
$_compile_dir_sep = $_template->smarty->use_sub_dirs ? DS : '^';
if (isset($_cache_id)) {
$_cache_id = str_replace('|', $_compile_dir_sep, $_cache_id) . $_compile_dir_sep;
} else {
$_cache_id = '';
}
if (isset($_compile_id)) {
$_compile_id = $_compile_id . $_compile_dir_sep;
} else {
$_compile_id = '';
}
$_cache_dir = $_template->smarty->getCacheDir();
if ($_template->smarty->cache_locking) {
// create locking file name
// relative file name?
if (!preg_match('/^([\/\\\\]|[a-zA-Z]:[\/\\\\])/', $_cache_dir)) {
$_lock_dir = rtrim(getcwd(), '/\\') . DS . $_cache_dir;
} else {
$_lock_dir = $_cache_dir;
}
$cached->lock_id = $_lock_dir . sha1($_cache_id . $_compile_id . $_template->source->uid) . '.lock';
}
$cached->filepath = $_cache_dir . $_cache_id . $_compile_id . $_filepath . '.' . basename($_source_file_path) . '.php';
$cached->timestamp = @filemtime($cached->filepath);
$cached->exists = !!$cached->timestamp;
}
/**
* populate Cached Object with timestamp and exists from Resource
*
* @param Smarty_Template_Cached $cached cached object
*
* @return void
*/
public function populateTimestamp(Smarty_Template_Cached $cached)
{
$cached->timestamp = @filemtime($cached->filepath);
$cached->exists = !!$cached->timestamp;
}
/**
* Read the cached template and process its header
*
* @param Smarty_Internal_Template $_template template object
* @param Smarty_Template_Cached $cached cached object
*
* @return booleantrue or false if the cached content does not exist
*/
public function process(Smarty_Internal_Template $_template, Smarty_Template_Cached $cached = null)
{
/** @var Smarty_Internal_Template $_smarty_tpl
* used in included file
*/
$_smarty_tpl = $_template;
return @include $_template->cached->filepath;
}
/**
* Write the rendered template output to cache
*
* @param Smarty_Internal_Template $_template template object
* @param string $content content to cache
*
* @return boolean success
*/
public function writeCachedContent(Smarty_Internal_Template $_template, $content)
{
if (Smarty_Internal_Write_File::writeFile($_template->cached->filepath, $content, $_template->smarty) === true) {
$_template->cached->timestamp = @filemtime($_template->cached->filepath);
$_template->cached->exists = !!$_template->cached->timestamp;
if ($_template->cached->exists) {
return true;
}
}
return false;
}
/**
* Empty cache
*
* @param Smarty $smarty
* @param integer $exp_time expiration time (number of seconds, not timestamp)
*
* @return integer number of cache files deleted
*/
public function clearAll(Smarty $smarty, $exp_time = null)
{
return $this->clear($smarty, null, null, null, $exp_time);
}
/**
* Empty cache for a specific template
*
* @param Smarty $smarty
* @param string $resource_name template name
* @param string $cache_id cache id
* @param string $compile_id compile id
* @param integer $exp_time expiration time (number of seconds, not timestamp)
*
* @return integer number of cache files deleted
*/
public function clear(Smarty $smarty, $resource_name, $cache_id, $compile_id, $exp_time)
{
$_cache_id = isset($cache_id) ? preg_replace('![^\w\|]+!', '_', $cache_id) : null;
$_compile_id = isset($compile_id) ? preg_replace('![^\w\|]+!', '_', $compile_id) : null;
$_dir_sep = $smarty->use_sub_dirs ? '/' : '^';
$_compile_id_offset = $smarty->use_sub_dirs ? 3 : 0;
if (($_dir = realpath($smarty->getCacheDir())) === false) {
return 0;
}
$_dir .= '/';
$_dir_length = strlen($_dir);
if (isset($_cache_id)) {
$_cache_id_parts = explode('|', $_cache_id);
$_cache_id_parts_count = count($_cache_id_parts);
if ($smarty->use_sub_dirs) {
foreach ($_cache_id_parts as $id_part) {
$_dir .= $id_part . DS;
}
}
}
if (isset($resource_name)) {
$_save_stat = $smarty->caching;
$smarty->caching = true;
$tpl = new $smarty->template_class($resource_name, $smarty);
$smarty->caching = $_save_stat;
// remove from template cache
$tpl->source; // have the template registered before unset()
if ($smarty->allow_ambiguous_resources) {
$_templateId = $tpl->source->unique_resource . $tpl->cache_id . $tpl->compile_id;
} else {
$_templateId = $smarty->joined_template_dir . '#' . $resource_name . $tpl->cache_id . $tpl->compile_id;
}
if (isset($_templateId[150])) {
$_templateId = sha1($_templateId);
}
unset($smarty->template_objects[$_templateId]);
if ($tpl->source->exists) {
$_resourcename_parts = basename(str_replace('^', '/', $tpl->cached->filepath));
} else {
return 0;
}
}
$_count = 0;
$_time = time();
if (file_exists($_dir)) {
$_cacheDirs = new RecursiveDirectoryIterator($_dir);
$_cache = new RecursiveIteratorIterator($_cacheDirs, RecursiveIteratorIterator::CHILD_FIRST);
foreach ($_cache as $_file) {
if (substr(basename($_file->getPathname()), 0, 1) == '.' || strpos($_file, '.svn') !== false) {
continue;
}
// directory ?
if ($_file->isDir()) {
if (!$_cache->isDot()) {
// delete folder if empty
@rmdir($_file->getPathname());
}
} else {
$_parts = explode($_dir_sep, str_replace('\\', '/', substr((string) $_file, $_dir_length)));
$_parts_count = count($_parts);
// check name
if (isset($resource_name)) {
if ($_parts[$_parts_count - 1] != $_resourcename_parts) {
continue;
}
}
// check compile id
if (isset($_compile_id) && (!isset($_parts[$_parts_count - 2 - $_compile_id_offset]) || $_parts[$_parts_count - 2 - $_compile_id_offset] != $_compile_id)) {
continue;
}
// check cache id
if (isset($_cache_id)) {
// count of cache id parts
$_parts_count = (isset($_compile_id)) ? $_parts_count - 2 - $_compile_id_offset : $_parts_count - 1 - $_compile_id_offset;
if ($_parts_count < $_cache_id_parts_count) {
continue;
}
for ($i = 0; $i < $_cache_id_parts_count; $i ++) {
if ($_parts[$i] != $_cache_id_parts[$i]) {
continue 2;
}
}
}
// expired ?
if (isset($exp_time)) {
if ($exp_time < 0) {
preg_match('#\'cache_lifetime\' =>\s*(\d*)#', file_get_contents($_file), $match);
if ($_time < (@filemtime($_file) + $match[1])) {
continue;
}
} else {
if ($_time - @filemtime($_file) < $exp_time) {
continue;
}
}
}
$_count += @unlink((string) $_file) ? 1 : 0;
}
}
}
return $_count;
}
/**
* Check is cache is locked for this template
*
* @param Smarty $smarty Smarty object
* @param Smarty_Template_Cached $cached cached object
*
* @return boolean true or false if cache is locked
*/
public function hasLock(Smarty $smarty, Smarty_Template_Cached $cached)
{
if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
clearstatcache(true, $cached->lock_id);
} else {
clearstatcache();
}
$t = @filemtime($cached->lock_id);
return $t && (time() - $t < $smarty->locking_timeout);
}
/**
* Lock cache for this template
*
* @param Smarty $smarty Smarty object
* @param Smarty_Template_Cached $cached cached object
*
* @return bool|void
*/
public function acquireLock(Smarty $smarty, Smarty_Template_Cached $cached)
{
$cached->is_locked = true;
touch($cached->lock_id);
}
/**
* Unlock cache for this template
*
* @param Smarty $smarty Smarty object
* @param Smarty_Template_Cached $cached cached object
*
* @return bool|void
*/
public function releaseLock(Smarty $smarty, Smarty_Template_Cached $cached)
{
$cached->is_locked = false;
@unlink($cached->lock_id);
}
}

View File

@@ -1,86 +0,0 @@
<?php
/**
* Smarty Internal Plugin Compile Assign
* Compiles the {assign} tag
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile Assign Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Assign extends Smarty_Internal_CompileBase
{
/**
* Compiles code for the {assign} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
*
* @return string compiled code
*/
public function compile($args, $compiler, $parameter)
{
// the following must be assigned at runtime because it will be overwritten in Smarty_Internal_Compile_Append
$this->required_attributes = array('var', 'value');
$this->shorttag_order = array('var', 'value');
$this->optional_attributes = array('scope');
$_nocache = 'null';
$_scope = Smarty::SCOPE_LOCAL;
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
// nocache ?
if ($compiler->tag_nocache || $compiler->nocache) {
$_nocache = 'true';
// create nocache var to make it know for further compiling
if (isset($compiler->template->tpl_vars[trim($_attr['var'], "'")])) {
$compiler->template->tpl_vars[trim($_attr['var'], "'")]->nocache = true;
} else {
$compiler->template->tpl_vars[trim($_attr['var'], "'")] = new Smarty_variable(null, true);
}
}
// scope setup
if (isset($_attr['scope'])) {
$_attr['scope'] = trim($_attr['scope'], "'\"");
if ($_attr['scope'] == 'parent') {
$_scope = Smarty::SCOPE_PARENT;
} elseif ($_attr['scope'] == 'root') {
$_scope = Smarty::SCOPE_ROOT;
} elseif ($_attr['scope'] == 'global') {
$_scope = Smarty::SCOPE_GLOBAL;
} else {
$compiler->trigger_template_error('illegal value for "scope" attribute', $compiler->lex->taglineno);
}
}
// compiled output
if (isset($parameter['smarty_internal_index'])) {
$output = "<?php \$_smarty_tpl->createLocalArrayVariable($_attr[var], $_nocache, $_scope);\n\$_smarty_tpl->tpl_vars[$_attr[var]]->value$parameter[smarty_internal_index] = $_attr[value];";
} else {
// implement Smarty2's behaviour of variables assigned by reference
if ($compiler->template->smarty instanceof SmartyBC) {
$output = "<?php if (isset(\$_smarty_tpl->tpl_vars[$_attr[var]])) {\$_smarty_tpl->tpl_vars[$_attr[var]] = clone \$_smarty_tpl->tpl_vars[$_attr[var]];";
$output .= "\n\$_smarty_tpl->tpl_vars[$_attr[var]]->value = $_attr[value]; \$_smarty_tpl->tpl_vars[$_attr[var]]->nocache = $_nocache; \$_smarty_tpl->tpl_vars[$_attr[var]]->scope = $_scope;";
$output .= "\n} else \$_smarty_tpl->tpl_vars[$_attr[var]] = new Smarty_variable($_attr[value], $_nocache, $_scope);";
} else {
$output = "<?php \$_smarty_tpl->tpl_vars[$_attr[var]] = new Smarty_variable($_attr[value], $_nocache, $_scope);";
}
}
if ($_scope == Smarty::SCOPE_PARENT) {
$output .= "\nif (\$_smarty_tpl->parent != null) \$_smarty_tpl->parent->tpl_vars[$_attr[var]] = clone \$_smarty_tpl->tpl_vars[$_attr[var]];";
} elseif ($_scope == Smarty::SCOPE_ROOT || $_scope == Smarty::SCOPE_GLOBAL) {
$output .= "\n\$_ptr = \$_smarty_tpl->parent; while (\$_ptr != null) {\$_ptr->tpl_vars[$_attr[var]] = clone \$_smarty_tpl->tpl_vars[$_attr[var]]; \$_ptr = \$_ptr->parent; }";
}
if ($_scope == Smarty::SCOPE_GLOBAL) {
$output .= "\nSmarty::\$global_tpl_vars[$_attr[var]] = clone \$_smarty_tpl->tpl_vars[$_attr[var]];";
}
$output .= '?>';
return $output;
}
}

View File

@@ -1,444 +0,0 @@
<?php
/**
* Smarty Internal Plugin Compile Block
* Compiles the {block}{/block} tags
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile Block Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Block extends Smarty_Internal_CompileBase
{
const parent = '____SMARTY_BLOCK_PARENT____';
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $required_attributes = array('name');
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $shorttag_order = array('name');
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $option_flags = array('hide', 'append', 'prepend', 'nocache');
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $optional_attributes = array('internal_file', 'internal_uid', 'internal_line');
/**
* nested child block names
*
* @var array
*/
public static $nested_block_names = array();
/**
* child block source buffer
*
* @var array
*/
public static $block_data = array();
/**
* Compiles code for the {block} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
*
* @return boolean true
*/
public function compile($args, $compiler)
{
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
$_name = trim($_attr['name'], "\"'");
// existing child must override parent settings
if (isset($compiler->template->block_data[$_name]) && $compiler->template->block_data[$_name]['mode'] == 'replace') {
$_attr['append'] = false;
$_attr['prepend'] = false;
}
// check if we process an inheritance child template
if ($compiler->inheritance_child) {
array_unshift(self::$nested_block_names, $_name);
// build {block} for child block
self::$block_data[$_name]['source'] =
"{$compiler->smarty->left_delimiter}private_child_block name={$_attr['name']} file='{$compiler->template->source->filepath}' type='{$compiler->template->source->type}' resource='{$compiler->template->template_resource}'" .
" uid='{$compiler->template->source->uid}' line={$compiler->lex->line}";
if ($_attr['nocache']) {
self::$block_data[$_name]['source'] .= ' nocache';
}
self::$block_data[$_name]['source'] .= $compiler->smarty->right_delimiter;
$save = array($_attr, $compiler->inheritance);
$this->openTag($compiler, 'block', $save);
// set flag for {block} tag
$compiler->inheritance = true;
$compiler->lex->yypushstate(Smarty_Internal_Templatelexer::CHILDBLOCK);
$compiler->has_code = false;
return;
}
// must merge includes
if ($_attr['nocache'] == true) {
$compiler->tag_nocache = true;
}
$save = array($_attr, $compiler->inheritance, $compiler->parser->current_buffer, $compiler->nocache);
$this->openTag($compiler, 'block', $save);
$compiler->inheritance = true;
$compiler->nocache = $compiler->nocache | $compiler->tag_nocache;
$compiler->parser->current_buffer = new _smarty_template_buffer($compiler->parser);
$compiler->has_code = false;
return true;
}
/**
* Compile saved child block source
*
* @param object $compiler compiler object
* @param string $_name optional name of child block
*
* @return string compiled code of child block
*/
static function compileChildBlock($compiler, $_name = null)
{
if ($compiler->inheritance_child) {
$name1 = Smarty_Internal_Compile_Block::$nested_block_names[0];
if (isset($compiler->template->block_data[$name1])) {
// replace inner block name with generic
Smarty_Internal_Compile_Block::$block_data[$name1]['source'] .= $compiler->template->block_data[$name1]['source'];
Smarty_Internal_Compile_Block::$block_data[$name1]['child'] = true;
}
$compiler->lex->yypushstate(Smarty_Internal_Templatelexer::CHILDBLOCK);
$compiler->has_code = false;
return;
}
// if called by {$smarty.block.child} we must search the name of enclosing {block}
if ($_name == null) {
$stack_count = count($compiler->_tag_stack);
while (--$stack_count >= 0) {
if ($compiler->_tag_stack[$stack_count][0] == 'block') {
$_name = trim($compiler->_tag_stack[$stack_count][1][0]['name'], "\"'");
break;
}
}
}
if ($_name == null) {
$compiler->trigger_template_error(' tag {$smarty.block.child} used outside {block} tags ', $compiler->lex->taglineno);
}
// undefined child?
if (!isset($compiler->template->block_data[$_name]['source'])) {
$compiler->popTrace();
return '';
}
// flag that child is already compile by {$smarty.block.child} inclusion
$compiler->template->block_data[$_name]['compiled'] = true;
$_tpl = new Smarty_Internal_template('string:' . $compiler->template->block_data[$_name]['source'], $compiler->smarty, $compiler->template, $compiler->template->cache_id,
$compiler->template->compile_id, $compiler->template->caching, $compiler->template->cache_lifetime);
if ($compiler->smarty->debugging) {
Smarty_Internal_Debug::ignore($_tpl);
}
$_tpl->tpl_vars = $compiler->template->tpl_vars;
$_tpl->variable_filters = $compiler->template->variable_filters;
$_tpl->properties['nocache_hash'] = $compiler->template->properties['nocache_hash'];
$_tpl->allow_relative_path = true;
$_tpl->compiler->inheritance = true;
$_tpl->compiler->suppressHeader = true;
$_tpl->compiler->suppressFilter = true;
$_tpl->compiler->suppressTemplatePropertyHeader = true;
$_tpl->compiler->suppressMergedTemplates = true;
$nocache = $compiler->nocache || $compiler->tag_nocache;
if (strpos($compiler->template->block_data[$_name]['source'], self::parent) !== false) {
$_output = str_replace(self::parent, $compiler->parser->current_buffer->to_smarty_php(), $_tpl->compiler->compileTemplate($_tpl, $nocache));
} elseif ($compiler->template->block_data[$_name]['mode'] == 'prepend') {
$_output = $_tpl->compiler->compileTemplate($_tpl, $nocache) . $compiler->parser->current_buffer->to_smarty_php();
} elseif ($compiler->template->block_data[$_name]['mode'] == 'append') {
$_output = $compiler->parser->current_buffer->to_smarty_php() . $_tpl->compiler->compileTemplate($_tpl, $nocache);
} elseif (!empty($compiler->template->block_data[$_name])) {
$_output = $_tpl->compiler->compileTemplate($_tpl, $nocache);
}
$compiler->template->properties['file_dependency'] = array_merge($compiler->template->properties['file_dependency'], $_tpl->properties['file_dependency']);
$compiler->template->properties['function'] = array_merge($compiler->template->properties['function'], $_tpl->properties['function']);
$compiler->merged_templates = array_merge($compiler->merged_templates, $_tpl->compiler->merged_templates);
$compiler->template->variable_filters = $_tpl->variable_filters;
if ($_tpl->has_nocache_code) {
$compiler->template->has_nocache_code = true;
}
foreach ($_tpl->required_plugins as $key => $tmp1) {
if ($compiler->nocache && $compiler->template->caching) {
$code = 'nocache';
} else {
$code = $key;
}
foreach ($tmp1 as $name => $tmp) {
foreach ($tmp as $type => $data) {
$compiler->template->required_plugins[$code][$name][$type] = $data;
}
}
}
unset($_tpl);
$compiler->has_code = true;
return $_output;
}
/**
* Compile $smarty.block.parent
*
* @param object $compiler compiler object
* @param string $_name optional name of child block
*
* @return string compiled code of child block
*/
static function compileParentBlock($compiler, $_name = null)
{
// if called by {$smarty.block.parent} we must search the name of enclosing {block}
if ($_name == null) {
$stack_count = count($compiler->_tag_stack);
while (--$stack_count >= 0) {
if ($compiler->_tag_stack[$stack_count][0] == 'block') {
$_name = trim($compiler->_tag_stack[$stack_count][1][0]['name'], "\"'");
break;
}
}
}
if ($_name == null) {
$compiler->trigger_template_error(' tag {$smarty.block.parent} used outside {block} tags ', $compiler->lex->taglineno);
}
if (empty(Smarty_Internal_Compile_Block::$nested_block_names)) {
$compiler->trigger_template_error(' illegal {$smarty.block.parent} in parent template ', $compiler->lex->taglineno);
}
Smarty_Internal_Compile_Block::$block_data[Smarty_Internal_Compile_Block::$nested_block_names[0]]['source'] .= Smarty_Internal_Compile_Block::parent;
$compiler->lex->yypushstate(Smarty_Internal_Templatelexer::CHILDBLOCK);
$compiler->has_code = false;
return;
}
/**
* Process block source
*
* @param $compiler
* @param string $source source text
*
*/
static function blockSource($compiler, $source)
{
Smarty_Internal_Compile_Block::$block_data[Smarty_Internal_Compile_Block::$nested_block_names[0]]['source'] .= $source;
}
}
/**
* Smarty Internal Plugin Compile BlockClose Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Blockclose extends Smarty_Internal_CompileBase
{
/**
* Compiles code for the {/block} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
*
* @return string compiled code
*/
public function compile($args, $compiler)
{
$compiler->has_code = true;
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
$saved_data = $this->closeTag($compiler, array('block'));
$_name = trim($saved_data[0]['name'], "\"'");
// reset flag for {block} tag
$compiler->inheritance = $saved_data[1];
// check if we process an inheritance child template
if ($compiler->inheritance_child) {
$name1 = Smarty_Internal_Compile_Block::$nested_block_names[0];
Smarty_Internal_Compile_Block::$block_data[$name1]['source'] .= "{$compiler->smarty->left_delimiter}/private_child_block{$compiler->smarty->right_delimiter}";
array_shift(Smarty_Internal_Compile_Block::$nested_block_names);
if (!empty(Smarty_Internal_Compile_Block::$nested_block_names)) {
$name2 = Smarty_Internal_Compile_Block::$nested_block_names[0];
if (isset($compiler->template->block_data[$name1]) || !$saved_data[0]['hide']) {
if (isset(Smarty_Internal_Compile_Block::$block_data[$name1]['child']) || !isset($compiler->template->block_data[$name1])) {
Smarty_Internal_Compile_Block::$block_data[$name2]['source'] .= Smarty_Internal_Compile_Block::$block_data[$name1]['source'];
} else {
if ($compiler->template->block_data[$name1]['mode'] == 'append') {
Smarty_Internal_Compile_Block::$block_data[$name2]['source'] .= Smarty_Internal_Compile_Block::$block_data[$name1]['source'] . $compiler->template->block_data[$name1]['source'];
} elseif ($compiler->template->block_data[$name1]['mode'] == 'prepend') {
Smarty_Internal_Compile_Block::$block_data[$name2]['source'] .= $compiler->template->block_data[$name1]['source'] . Smarty_Internal_Compile_Block::$block_data[$name1]['source'];
} else {
Smarty_Internal_Compile_Block::$block_data[$name2]['source'] .= $compiler->template->block_data[$name1]['source'];
}
}
}
unset(Smarty_Internal_Compile_Block::$block_data[$name1]);
$compiler->lex->yypushstate(Smarty_Internal_Templatelexer::CHILDBLOCK);
} else {
if (isset($compiler->template->block_data[$name1]) || !$saved_data[0]['hide']) {
if (isset($compiler->template->block_data[$name1]) && !isset(Smarty_Internal_Compile_Block::$block_data[$name1]['child'])) {
if (strpos($compiler->template->block_data[$name1]['source'], Smarty_Internal_Compile_Block::parent) !== false) {
$compiler->template->block_data[$name1]['source'] =
str_replace(Smarty_Internal_Compile_Block::parent, Smarty_Internal_Compile_Block::$block_data[$name1]['source'], $compiler->template->block_data[$name1]['source']);
} elseif ($compiler->template->block_data[$name1]['mode'] == 'prepend') {
$compiler->template->block_data[$name1]['source'] .= Smarty_Internal_Compile_Block::$block_data[$name1]['source'];
} elseif ($compiler->template->block_data[$name1]['mode'] == 'append') {
$compiler->template->block_data[$name1]['source'] = Smarty_Internal_Compile_Block::$block_data[$name1]['source'] . $compiler->template->block_data[$name1]['source'];
}
} else {
$compiler->template->block_data[$name1]['source'] = Smarty_Internal_Compile_Block::$block_data[$name1]['source'];
}
$compiler->template->block_data[$name1]['mode'] = 'replace';
if ($saved_data[0]['append']) {
$compiler->template->block_data[$name1]['mode'] = 'append';
}
if ($saved_data[0]['prepend']) {
$compiler->template->block_data[$name1]['mode'] = 'prepend';
}
}
unset(Smarty_Internal_Compile_Block::$block_data[$name1]);
$compiler->lex->yypushstate(Smarty_Internal_Templatelexer::CHILDBODY);
}
$compiler->has_code = false;
return;
}
if (isset($compiler->template->block_data[$_name]) && !isset($compiler->template->block_data[$_name]['compiled'])) {
$_output = Smarty_Internal_Compile_Block::compileChildBlock($compiler, $_name);
} else {
if ($saved_data[0]['hide'] && !isset($compiler->template->block_data[$_name]['source'])) {
$_output = '';
} else {
$_output = $compiler->parser->current_buffer->to_smarty_php();
}
}
unset($compiler->template->block_data[$_name]['compiled']);
// reset flags
$compiler->parser->current_buffer = $saved_data[2];
if ($compiler->nocache) {
$compiler->tag_nocache = true;
}
$compiler->nocache = $saved_data[3];
// $_output content has already nocache code processed
$compiler->suppressNocacheProcessing = true;
return $_output;
}
}
/**
* Smarty Internal Plugin Compile Child Block Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Private_Child_Block extends Smarty_Internal_CompileBase
{
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $required_attributes = array('name', 'file', 'uid', 'line', 'type', 'resource');
/**
* Compiles code for the {private_child_block} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
*
* @return boolean true
*/
public function compile($args, $compiler)
{
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
// update template with original template resource of {block}
if (trim($_attr['type'], "'") == 'file') {
$compiler->template->template_resource = 'file:' . realpath(trim($_attr['file'], "'"));
} else {
$compiler->template->template_resource = trim($_attr['resource'], "'");
}
// source object
unset ($compiler->template->source);
$exists = $compiler->template->source->exists;
// must merge includes
if ($_attr['nocache'] == true) {
$compiler->tag_nocache = true;
}
$save = array($_attr, $compiler->nocache);
// set trace back to child block
$compiler->pushTrace(trim($_attr['file'], "\"'"), trim($_attr['uid'], "\"'"), $_attr['line'] - $compiler->lex->line);
$this->openTag($compiler, 'private_child_block', $save);
$compiler->nocache = $compiler->nocache | $compiler->tag_nocache;
$compiler->has_code = false;
return true;
}
}
/**
* Smarty Internal Plugin Compile Child Block Close Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Private_Child_Blockclose extends Smarty_Internal_CompileBase
{
/**
* Compiles code for the {/private_child_block} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
*
* @return boolean true
*/
public function compile($args, $compiler)
{
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
$saved_data = $this->closeTag($compiler, array('private_child_block'));
// end of child block
$compiler->popTrace();
$compiler->nocache = $saved_data[1];
$compiler->has_code = false;
return true;
}
}

View File

@@ -1,127 +0,0 @@
<?php
/**
* Smarty Internal Plugin Compile Function_Call
* Compiles the calls of user defined tags defined by {function}
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile Function_Call Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Call extends Smarty_Internal_CompileBase
{
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $required_attributes = array('name');
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $shorttag_order = array('name');
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $optional_attributes = array('_any');
/**
* Compiles the calls of user defined tags defined by {function}
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
*
* @return string compiled code
*/
public function compile($args, $compiler)
{
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
// save possible attributes
if (isset($_attr['assign'])) {
// output will be stored in a smarty variable instead of being displayed
$_assign = $_attr['assign'];
}
$_name = $_attr['name'];
if ($compiler->compiles_template_function) {
$compiler->called_functions[] = trim($_name, "'\"");
}
unset($_attr['name'], $_attr['assign'], $_attr['nocache']);
// set flag (compiled code of {function} must be included in cache file
if ($compiler->nocache || $compiler->tag_nocache) {
$_nocache = 'true';
} else {
$_nocache = 'false';
}
$_paramsArray = array();
foreach ($_attr as $_key => $_value) {
if (is_int($_key)) {
$_paramsArray[] = "$_key=>$_value";
} else {
$_paramsArray[] = "'$_key'=>$_value";
}
}
if (isset($compiler->template->properties['function'][$_name]['parameter'])) {
foreach ($compiler->template->properties['function'][$_name]['parameter'] as $_key => $_value) {
if (!isset($_attr[$_key])) {
if (is_int($_key)) {
$_paramsArray[] = "$_key=>$_value";
} else {
$_paramsArray[] = "'$_key'=>$_value";
}
}
}
} elseif (isset($compiler->smarty->template_functions[$_name]['parameter'])) {
foreach ($compiler->smarty->template_functions[$_name]['parameter'] as $_key => $_value) {
if (!isset($_attr[$_key])) {
if (is_int($_key)) {
$_paramsArray[] = "$_key=>$_value";
} else {
$_paramsArray[] = "'$_key'=>$_value";
}
}
}
}
//variable name?
if (!(strpos($_name, '$') === false)) {
$call_cache = $_name;
$call_function = '$tmp = "smarty_template_function_".' . $_name . '; $tmp';
} else {
$_name = trim($_name, "'\"");
$call_cache = "'{$_name}'";
$call_function = 'smarty_template_function_' . $_name;
}
$_params = 'array(' . implode(",", $_paramsArray) . ')';
$_hash = str_replace('-', '_', $compiler->template->properties['nocache_hash']);
// was there an assign attribute
if (isset($_assign)) {
if ($compiler->template->caching) {
$_output = "<?php ob_start(); Smarty_Internal_Function_Call_Handler::call ({$call_cache},\$_smarty_tpl,{$_params},'{$_hash}',{$_nocache}); \$_smarty_tpl->assign({$_assign}, ob_get_clean());?>\n";
} else {
$_output = "<?php ob_start(); {$call_function}(\$_smarty_tpl,{$_params}); \$_smarty_tpl->assign({$_assign}, ob_get_clean());?>\n";
}
} else {
if ($compiler->template->caching) {
$_output = "<?php Smarty_Internal_Function_Call_Handler::call ({$call_cache},\$_smarty_tpl,{$_params},'{$_hash}',{$_nocache});?>\n";
} else {
$_output = "<?php {$call_function}(\$_smarty_tpl,{$_params});?>\n";
}
}
return $_output;
}
}

View File

@@ -1,96 +0,0 @@
<?php
/**
* Smarty Internal Plugin Compile Capture
* Compiles the {capture} tag
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile Capture Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Capture extends Smarty_Internal_CompileBase
{
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $shorttag_order = array('name');
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $optional_attributes = array('name', 'assign', 'append');
/**
* Compiles code for the {capture} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
*
* @return string compiled code
*/
public function compile($args, $compiler)
{
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
$buffer = isset($_attr['name']) ? $_attr['name'] : "'default'";
$assign = isset($_attr['assign']) ? $_attr['assign'] : 'null';
$append = isset($_attr['append']) ? $_attr['append'] : 'null';
$compiler->_capture_stack[0][] = array($buffer, $assign, $append, $compiler->nocache);
// maybe nocache because of nocache variables
$compiler->nocache = $compiler->nocache | $compiler->tag_nocache;
$_output = "<?php \$_smarty_tpl->_capture_stack[0][] = array($buffer, $assign, $append); ob_start(); ?>";
return $_output;
}
}
/**
* Smarty Internal Plugin Compile Captureclose Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_CaptureClose extends Smarty_Internal_CompileBase
{
/**
* Compiles code for the {/capture} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
*
* @return string compiled code
*/
public function compile($args, $compiler)
{
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
// must endblock be nocache?
if ($compiler->nocache) {
$compiler->tag_nocache = true;
}
list($buffer, $assign, $append, $compiler->nocache) = array_pop($compiler->_capture_stack[0]);
$_output = "<?php list(\$_capture_buffer, \$_capture_assign, \$_capture_append) = array_pop(\$_smarty_tpl->_capture_stack[0]);\n";
$_output .= "if (!empty(\$_capture_buffer)) {\n";
$_output .= " if (isset(\$_capture_assign)) \$_smarty_tpl->assign(\$_capture_assign, ob_get_contents());\n";
$_output .= " if (isset( \$_capture_append)) \$_smarty_tpl->append( \$_capture_append, ob_get_contents());\n";
$_output .= " Smarty::\$_smarty_vars['capture'][\$_capture_buffer]=ob_get_clean();\n";
$_output .= "} else \$_smarty_tpl->capture_error();?>";
return $_output;
}
}

View File

@@ -1,85 +0,0 @@
<?php
/**
* Smarty Internal Plugin Compile extend
* Compiles the {extends} tag
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile extend Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Extends extends Smarty_Internal_CompileBase
{
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $required_attributes = array('file');
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $shorttag_order = array('file');
/**
* Compiles code for the {extends} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
*
* @return string compiled code
*/
public function compile($args, $compiler)
{
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
if ($_attr['nocache'] === true) {
$compiler->trigger_template_error('nocache option not allowed', $compiler->lex->taglineno);
}
if (strpos($_attr['file'], '$_tmp') !== false) {
$compiler->trigger_template_error('illegal value for file attribute', $compiler->lex->taglineno);
}
$name = $_attr['file'];
/** @var Smarty_Internal_Template $_smarty_tpl
* used in evaluated code
*/
$_smarty_tpl = $compiler->template;
eval("\$tpl_name = $name;");
// create template object
$_template = new $compiler->smarty->template_class($tpl_name, $compiler->smarty, $compiler->template);
// check for recursion
$uid = $_template->source->uid;
if (isset($compiler->extends_uid[$uid])) {
$compiler->trigger_template_error("illegal recursive call of \"$include_file\"", $compiler->lex->line - 1);
}
$compiler->extends_uid[$uid] = true;
if (empty($_template->source->components)) {
array_unshift($compiler->sources, $_template->source);
} else {
foreach ($_template->source->components as $source) {
array_unshift($compiler->sources, $source);
$uid = $source->uid;
if (isset($compiler->extends_uid[$uid])) {
$compiler->trigger_template_error("illegal recursive call of \"{$source->filepath}\"", $compiler->lex->line - 1);
}
$compiler->extends_uid[$uid] = true;
}
}
unset ($_template);
$compiler->inheritance_child = true;
$compiler->lex->yypushstate(Smarty_Internal_Templatelexer::CHILDBODY);
return '';
}
}

View File

@@ -1,229 +0,0 @@
<?php
/**
* Smarty Internal Plugin Compile Foreach
* Compiles the {foreach} {foreachelse} {/foreach} tags
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile Foreach Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Foreach extends Smarty_Internal_CompileBase
{
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $required_attributes = array('from', 'item');
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $optional_attributes = array('name', 'key');
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $shorttag_order = array('from', 'item', 'key', 'name');
/**
* Compiles code for the {foreach} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
*
* @return string compiled code
*/
public function compile($args, $compiler, $parameter)
{
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
$from = $_attr['from'];
$item = $_attr['item'];
if (!strncmp("\$_smarty_tpl->tpl_vars[$item]", $from, strlen($item) + 24)) {
$compiler->trigger_template_error("item variable {$item} may not be the same variable as at 'from'", $compiler->lex->taglineno);
}
if (isset($_attr['key'])) {
$key = $_attr['key'];
} else {
$key = null;
}
$this->openTag($compiler, 'foreach', array('foreach', $compiler->nocache, $item, $key));
// maybe nocache because of nocache variables
$compiler->nocache = $compiler->nocache | $compiler->tag_nocache;
if (isset($_attr['name'])) {
$name = $_attr['name'];
$has_name = true;
$SmartyVarName = '$smarty.foreach.' . trim($name, '\'"') . '.';
} else {
$name = null;
$has_name = false;
}
$ItemVarName = '$' . trim($item, '\'"') . '@';
// evaluates which Smarty variables and properties have to be computed
if ($has_name) {
$usesSmartyFirst = strpos($compiler->lex->data, $SmartyVarName . 'first') !== false;
$usesSmartyLast = strpos($compiler->lex->data, $SmartyVarName . 'last') !== false;
$usesSmartyIndex = strpos($compiler->lex->data, $SmartyVarName . 'index') !== false;
$usesSmartyIteration = strpos($compiler->lex->data, $SmartyVarName . 'iteration') !== false;
$usesSmartyShow = strpos($compiler->lex->data, $SmartyVarName . 'show') !== false;
$usesSmartyTotal = strpos($compiler->lex->data, $SmartyVarName . 'total') !== false;
} else {
$usesSmartyFirst = false;
$usesSmartyLast = false;
$usesSmartyTotal = false;
$usesSmartyShow = false;
}
$usesPropFirst = $usesSmartyFirst || strpos($compiler->lex->data, $ItemVarName . 'first') !== false;
$usesPropLast = $usesSmartyLast || strpos($compiler->lex->data, $ItemVarName . 'last') !== false;
$usesPropIndex = $usesPropFirst || strpos($compiler->lex->data, $ItemVarName . 'index') !== false;
$usesPropIteration = $usesPropLast || strpos($compiler->lex->data, $ItemVarName . 'iteration') !== false;
$usesPropShow = strpos($compiler->lex->data, $ItemVarName . 'show') !== false;
$usesPropTotal = $usesSmartyTotal || $usesSmartyShow || $usesPropShow || $usesPropLast || strpos($compiler->lex->data, $ItemVarName . 'total') !== false;
// generate output code
$output = "<?php ";
$output .= " \$_smarty_tpl->tpl_vars[$item] = new Smarty_Variable; \$_smarty_tpl->tpl_vars[$item]->_loop = false;\n";
if ($key != null) {
$output .= " \$_smarty_tpl->tpl_vars[$key] = new Smarty_Variable;\n";
}
$output .= " \$_from = $from; if (!is_array(\$_from) && !is_object(\$_from)) { settype(\$_from, 'array');}\n";
if ($usesPropTotal) {
$output .= " \$_smarty_tpl->tpl_vars[$item]->total= \$_smarty_tpl->_count(\$_from);\n";
}
if ($usesPropIteration) {
$output .= " \$_smarty_tpl->tpl_vars[$item]->iteration=0;\n";
}
if ($usesPropIndex) {
$output .= " \$_smarty_tpl->tpl_vars[$item]->index=-1;\n";
}
if ($usesPropShow) {
$output .= " \$_smarty_tpl->tpl_vars[$item]->show = (\$_smarty_tpl->tpl_vars[$item]->total > 0);\n";
}
if ($has_name) {
if ($usesSmartyTotal) {
$output .= " \$_smarty_tpl->tpl_vars['smarty']->value['foreach'][$name]['total'] = \$_smarty_tpl->tpl_vars[$item]->total;\n";
}
if ($usesSmartyIteration) {
$output .= " \$_smarty_tpl->tpl_vars['smarty']->value['foreach'][$name]['iteration']=0;\n";
}
if ($usesSmartyIndex) {
$output .= " \$_smarty_tpl->tpl_vars['smarty']->value['foreach'][$name]['index']=-1;\n";
}
if ($usesSmartyShow) {
$output .= " \$_smarty_tpl->tpl_vars['smarty']->value['foreach'][$name]['show']=(\$_smarty_tpl->tpl_vars[$item]->total > 0);\n";
}
}
$output .= "foreach (\$_from as \$_smarty_tpl->tpl_vars[$item]->key => \$_smarty_tpl->tpl_vars[$item]->value) {\n\$_smarty_tpl->tpl_vars[$item]->_loop = true;\n";
if ($key != null) {
$output .= " \$_smarty_tpl->tpl_vars[$key]->value = \$_smarty_tpl->tpl_vars[$item]->key;\n";
}
if ($usesPropIteration) {
$output .= " \$_smarty_tpl->tpl_vars[$item]->iteration++;\n";
}
if ($usesPropIndex) {
$output .= " \$_smarty_tpl->tpl_vars[$item]->index++;\n";
}
if ($usesPropFirst) {
$output .= " \$_smarty_tpl->tpl_vars[$item]->first = \$_smarty_tpl->tpl_vars[$item]->index === 0;\n";
}
if ($usesPropLast) {
$output .= " \$_smarty_tpl->tpl_vars[$item]->last = \$_smarty_tpl->tpl_vars[$item]->iteration === \$_smarty_tpl->tpl_vars[$item]->total;\n";
}
if ($has_name) {
if ($usesSmartyFirst) {
$output .= " \$_smarty_tpl->tpl_vars['smarty']->value['foreach'][$name]['first'] = \$_smarty_tpl->tpl_vars[$item]->first;\n";
}
if ($usesSmartyIteration) {
$output .= " \$_smarty_tpl->tpl_vars['smarty']->value['foreach'][$name]['iteration']++;\n";
}
if ($usesSmartyIndex) {
$output .= " \$_smarty_tpl->tpl_vars['smarty']->value['foreach'][$name]['index']++;\n";
}
if ($usesSmartyLast) {
$output .= " \$_smarty_tpl->tpl_vars['smarty']->value['foreach'][$name]['last'] = \$_smarty_tpl->tpl_vars[$item]->last;\n";
}
}
$output .= "?>";
return $output;
}
}
/**
* Smarty Internal Plugin Compile Foreachelse Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Foreachelse extends Smarty_Internal_CompileBase
{
/**
* Compiles code for the {foreachelse} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
*
* @return string compiled code
*/
public function compile($args, $compiler, $parameter)
{
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
list($openTag, $nocache, $item, $key) = $this->closeTag($compiler, array('foreach'));
$this->openTag($compiler, 'foreachelse', array('foreachelse', $nocache, $item, $key));
return "<?php }\nif (!\$_smarty_tpl->tpl_vars[$item]->_loop) {\n?>";
}
}
/**
* Smarty Internal Plugin Compile Foreachclose Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Foreachclose extends Smarty_Internal_CompileBase
{
/**
* Compiles code for the {/foreach} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
*
* @return string compiled code
*/
public function compile($args, $compiler, $parameter)
{
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
// must endblock be nocache?
if ($compiler->nocache) {
$compiler->tag_nocache = true;
}
list($openTag, $compiler->nocache, $item, $key) = $this->closeTag($compiler, array('foreach', 'foreachelse'));
return "<?php } ?>";
}
}

View File

@@ -1,162 +0,0 @@
<?php
/**
* Smarty Internal Plugin Compile Function
* Compiles the {function} {/function} tags
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile Function Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Function extends Smarty_Internal_CompileBase
{
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $required_attributes = array('name');
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $shorttag_order = array('name');
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $optional_attributes = array('_any');
/**
* Compiles code for the {function} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
*
* @return boolean true
*/
public function compile($args, $compiler, $parameter)
{
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
if ($_attr['nocache'] === true) {
$compiler->trigger_template_error('nocache option not allowed', $compiler->lex->taglineno);
}
unset($_attr['nocache']);
$save = array($_attr, $compiler->parser->current_buffer,
$compiler->template->has_nocache_code, $compiler->template->required_plugins);
$this->openTag($compiler, 'function', $save);
$_name = trim($_attr['name'], "'\"");
unset($_attr['name']);
// set flag that we are compiling a template function
$compiler->compiles_template_function = true;
$compiler->template->properties['function'][$_name]['parameter'] = array();
/** @var Smarty_Internal_Template $_smarty_tpl
* used in evaluated code
*/
$_smarty_tpl = $compiler->template;
foreach ($_attr as $_key => $_data) {
eval ('$tmp=' . $_data . ';');
$compiler->template->properties['function'][$_name]['parameter'][$_key] = $tmp;
}
$compiler->smarty->template_functions[$_name]['parameter'] = $compiler->template->properties['function'][$_name]['parameter'];
if ($compiler->template->caching) {
$output = '';
} else {
$output = "<?php if (!function_exists('smarty_template_function_{$_name}')) {
function smarty_template_function_{$_name}(\$_smarty_tpl,\$params) {
\$saved_tpl_vars = \$_smarty_tpl->tpl_vars;
foreach (\$_smarty_tpl->smarty->template_functions['{$_name}']['parameter'] as \$key => \$value) {\$_smarty_tpl->tpl_vars[\$key] = new Smarty_variable(\$value);};
foreach (\$params as \$key => \$value) {\$_smarty_tpl->tpl_vars[\$key] = new Smarty_variable(\$value);}?>";
}
// Init temporary context
$compiler->template->required_plugins = array('compiled' => array(), 'nocache' => array());
$compiler->parser->current_buffer = new _smarty_template_buffer($compiler->parser);
$compiler->parser->current_buffer->append_subtree(new _smarty_tag($compiler->parser, $output));
$compiler->template->has_nocache_code = false;
$compiler->has_code = false;
$compiler->template->properties['function'][$_name]['compiled'] = '';
return true;
}
}
/**
* Smarty Internal Plugin Compile Functionclose Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Functionclose extends Smarty_Internal_CompileBase
{
/**
* Compiles code for the {/function} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
*
* @return boolean true
*/
public function compile($args, $compiler, $parameter)
{
$_attr = $this->getAttributes($compiler, $args);
$saved_data = $this->closeTag($compiler, array('function'));
$_name = trim($saved_data[0]['name'], "'\"");
// build plugin include code
$plugins_string = '';
if (!empty($compiler->template->required_plugins['compiled'])) {
$plugins_string = '<?php ';
foreach ($compiler->template->required_plugins['compiled'] as $tmp) {
foreach ($tmp as $data) {
$plugins_string .= "if (!is_callable('{$data['function']}')) include '{$data['file']}';\n";
}
}
$plugins_string .= '?>';
}
if (!empty($compiler->template->required_plugins['nocache'])) {
$plugins_string .= "<?php echo '/*%%SmartyNocache:{$compiler->template->properties['nocache_hash']}%%*/<?php ";
foreach ($compiler->template->required_plugins['nocache'] as $tmp) {
foreach ($tmp as $data) {
$plugins_string .= "if (!is_callable(\'{$data['function']}\')) include \'{$data['file']}\';\n";
}
}
$plugins_string .= "?>/*/%%SmartyNocache:{$compiler->template->properties['nocache_hash']}%%*/';?>\n";
}
// if caching save template function for possible nocache call
if ($compiler->template->caching) {
$compiler->template->properties['function'][$_name]['compiled'] .= $plugins_string
. $compiler->parser->current_buffer->to_smarty_php();
$compiler->template->properties['function'][$_name]['nocache_hash'] = $compiler->template->properties['nocache_hash'];
$compiler->template->properties['function'][$_name]['has_nocache_code'] = $compiler->template->has_nocache_code;
$compiler->template->properties['function'][$_name]['called_functions'] = $compiler->called_functions;
$compiler->called_functions = array();
$compiler->smarty->template_functions[$_name] = $compiler->template->properties['function'][$_name];
$compiler->has_code = false;
$output = true;
} else {
$output = $plugins_string . $compiler->parser->current_buffer->to_smarty_php() . "<?php \$_smarty_tpl->tpl_vars = \$saved_tpl_vars;
foreach (Smarty::\$global_tpl_vars as \$key => \$value) if(!isset(\$_smarty_tpl->tpl_vars[\$key])) \$_smarty_tpl->tpl_vars[\$key] = \$value;}}?>\n";
}
// reset flag that we are compiling a template function
$compiler->compiles_template_function = false;
// restore old compiler status
$compiler->parser->current_buffer = $saved_data[1];
$compiler->template->has_nocache_code = $compiler->template->has_nocache_code | $saved_data[2];
$compiler->template->required_plugins = $saved_data[3];
return $output;
}
}

View File

@@ -1,210 +0,0 @@
<?php
/**
* Smarty Internal Plugin Compile If
* Compiles the {if} {else} {elseif} {/if} tags
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile If Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_If extends Smarty_Internal_CompileBase
{
/**
* Compiles code for the {if} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
*
* @return string compiled code
*/
public function compile($args, $compiler, $parameter)
{
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
$this->openTag($compiler, 'if', array(1, $compiler->nocache));
// must whole block be nocache ?
$compiler->nocache = $compiler->nocache | $compiler->tag_nocache;
if (!array_key_exists("if condition", $parameter)) {
$compiler->trigger_template_error("missing if condition", $compiler->lex->taglineno);
}
if (is_array($parameter['if condition'])) {
if ($compiler->nocache) {
$_nocache = ',true';
// create nocache var to make it know for further compiling
if (is_array($parameter['if condition']['var'])) {
$compiler->template->tpl_vars[trim($parameter['if condition']['var']['var'], "'")] = new Smarty_variable(null, true);
} else {
$compiler->template->tpl_vars[trim($parameter['if condition']['var'], "'")] = new Smarty_variable(null, true);
}
} else {
$_nocache = '';
}
if (is_array($parameter['if condition']['var'])) {
$_output = "<?php if (!isset(\$_smarty_tpl->tpl_vars[" . $parameter['if condition']['var']['var'] . "]) || !is_array(\$_smarty_tpl->tpl_vars[" . $parameter['if condition']['var']['var'] . "]->value)) \$_smarty_tpl->createLocalArrayVariable(" . $parameter['if condition']['var']['var'] . "$_nocache);\n";
$_output .= "if (\$_smarty_tpl->tpl_vars[" . $parameter['if condition']['var']['var'] . "]->value" . $parameter['if condition']['var']['smarty_internal_index'] . " = " . $parameter['if condition']['value'] . ") {?>";
} else {
$_output = "<?php if (!isset(\$_smarty_tpl->tpl_vars[" . $parameter['if condition']['var'] . "])) \$_smarty_tpl->tpl_vars[" . $parameter['if condition']['var'] . "] = new Smarty_Variable(null{$_nocache});";
$_output .= "if (\$_smarty_tpl->tpl_vars[" . $parameter['if condition']['var'] . "]->value = " . $parameter['if condition']['value'] . ") {?>";
}
return $_output;
} else {
return "<?php if ({$parameter['if condition']}) {?>";
}
}
}
/**
* Smarty Internal Plugin Compile Else Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Else extends Smarty_Internal_CompileBase
{
/**
* Compiles code for the {else} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
*
* @return string compiled code
*/
public function compile($args, $compiler, $parameter)
{
list($nesting, $compiler->tag_nocache) = $this->closeTag($compiler, array('if', 'elseif'));
$this->openTag($compiler, 'else', array($nesting, $compiler->tag_nocache));
return "<?php } else { ?>";
}
}
/**
* Smarty Internal Plugin Compile ElseIf Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Elseif extends Smarty_Internal_CompileBase
{
/**
* Compiles code for the {elseif} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
*
* @return string compiled code
*/
public function compile($args, $compiler, $parameter)
{
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
list($nesting, $compiler->tag_nocache) = $this->closeTag($compiler, array('if', 'elseif'));
if (!array_key_exists("if condition", $parameter)) {
$compiler->trigger_template_error("missing elseif condition", $compiler->lex->taglineno);
}
if (is_array($parameter['if condition'])) {
$condition_by_assign = true;
if ($compiler->nocache) {
$_nocache = ',true';
// create nocache var to make it know for further compiling
if (is_array($parameter['if condition']['var'])) {
$compiler->template->tpl_vars[trim($parameter['if condition']['var']['var'], "'")] = new Smarty_variable(null, true);
} else {
$compiler->template->tpl_vars[trim($parameter['if condition']['var'], "'")] = new Smarty_variable(null, true);
}
} else {
$_nocache = '';
}
} else {
$condition_by_assign = false;
}
if (empty($compiler->prefix_code)) {
if ($condition_by_assign) {
$this->openTag($compiler, 'elseif', array($nesting + 1, $compiler->tag_nocache));
if (is_array($parameter['if condition']['var'])) {
$_output = "<?php } else { if (!isset(\$_smarty_tpl->tpl_vars[" . $parameter['if condition']['var']['var'] . "]) || !is_array(\$_smarty_tpl->tpl_vars[" . $parameter['if condition']['var']['var'] . "]->value)) \$_smarty_tpl->createLocalArrayVariable(" . $parameter['if condition']['var']['var'] . "$_nocache);\n";
$_output .= "if (\$_smarty_tpl->tpl_vars[" . $parameter['if condition']['var']['var'] . "]->value" . $parameter['if condition']['var']['smarty_internal_index'] . " = " . $parameter['if condition']['value'] . ") {?>";
} else {
$_output = "<?php } else { if (!isset(\$_smarty_tpl->tpl_vars[" . $parameter['if condition']['var'] . "])) \$_smarty_tpl->tpl_vars[" . $parameter['if condition']['var'] . "] = new Smarty_Variable(null{$_nocache});";
$_output .= "if (\$_smarty_tpl->tpl_vars[" . $parameter['if condition']['var'] . "]->value = " . $parameter['if condition']['value'] . ") {?>";
}
return $_output;
} else {
$this->openTag($compiler, 'elseif', array($nesting, $compiler->tag_nocache));
return "<?php } elseif ({$parameter['if condition']}) {?>";
}
} else {
$tmp = '';
foreach ($compiler->prefix_code as $code) {
$tmp .= $code;
}
$compiler->prefix_code = array();
$this->openTag($compiler, 'elseif', array($nesting + 1, $compiler->tag_nocache));
if ($condition_by_assign) {
if (is_array($parameter['if condition']['var'])) {
$_output = "<?php } else {?>{$tmp}<?php if (!isset(\$_smarty_tpl->tpl_vars[" . $parameter['if condition']['var']['var'] . "]) || !is_array(\$_smarty_tpl->tpl_vars[" . $parameter['if condition']['var']['var'] . "]->value)) \$_smarty_tpl->createLocalArrayVariable(" . $parameter['if condition']['var']['var'] . "$_nocache);\n";
$_output .= "if (\$_smarty_tpl->tpl_vars[" . $parameter['if condition']['var']['var'] . "]->value" . $parameter['if condition']['var']['smarty_internal_index'] . " = " . $parameter['if condition']['value'] . ") {?>";
} else {
$_output = "<?php } else {?>{$tmp}<?php if (!isset(\$_smarty_tpl->tpl_vars[" . $parameter['if condition']['var'] . "])) \$_smarty_tpl->tpl_vars[" . $parameter['if condition']['var'] . "] = new Smarty_Variable(null{$_nocache});";
$_output .= "if (\$_smarty_tpl->tpl_vars[" . $parameter['if condition']['var'] . "]->value = " . $parameter['if condition']['value'] . ") {?>";
}
return $_output;
} else {
return "<?php } else {?>{$tmp}<?php if ({$parameter['if condition']}) {?>";
}
}
}
}
/**
* Smarty Internal Plugin Compile Ifclose Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Ifclose extends Smarty_Internal_CompileBase
{
/**
* Compiles code for the {/if} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
*
* @return string compiled code
*/
public function compile($args, $compiler, $parameter)
{
// must endblock be nocache?
if ($compiler->nocache) {
$compiler->tag_nocache = true;
}
list($nesting, $compiler->nocache) = $this->closeTag($compiler, array('if', 'else', 'elseif'));
$tmp = '';
for ($i = 0; $i < $nesting; $i ++) {
$tmp .= '}';
}
return "<?php {$tmp}?>";
}
}

View File

@@ -1,265 +0,0 @@
<?php
/**
* Smarty Internal Plugin Compile Include
* Compiles the {include} tag
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile Include Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Include extends Smarty_Internal_CompileBase
{
/**
* caching mode to create nocache code but no cache file
*/
const CACHING_NOCACHE_CODE = 9999;
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $required_attributes = array('file');
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $shorttag_order = array('file');
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $option_flags = array('nocache', 'inline', 'caching');
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $optional_attributes = array('_any');
/**
* Compiles code for the {include} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
*
* @return string compiled code
*/
public function compile($args, $compiler, $parameter)
{
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
// save possible attributes
$include_file = $_attr['file'];
if (isset($_attr['assign'])) {
// output will be stored in a smarty variable instead of being displayed
$_assign = $_attr['assign'];
}
$_parent_scope = Smarty::SCOPE_LOCAL;
if (isset($_attr['scope'])) {
$_attr['scope'] = trim($_attr['scope'], "'\"");
if ($_attr['scope'] == 'parent') {
$_parent_scope = Smarty::SCOPE_PARENT;
} elseif ($_attr['scope'] == 'root') {
$_parent_scope = Smarty::SCOPE_ROOT;
} elseif ($_attr['scope'] == 'global') {
$_parent_scope = Smarty::SCOPE_GLOBAL;
}
}
$_caching = Smarty::CACHING_OFF;
// flag if included template code should be merged into caller
$merge_compiled_includes = ($compiler->smarty->merge_compiled_includes || ($compiler->inheritance && $compiler->smarty->inheritance_merge_compiled_includes) || $_attr['inline'] === true) && !$compiler->template->source->recompiled;
// set default when in nocache mode
// if ($compiler->template->caching && ($compiler->nocache || $compiler->tag_nocache || $compiler->forceNocache == 2)) {
if ($compiler->template->caching && ((!$compiler->inheritance && !$compiler->nocache && !$compiler->tag_nocache) || ($compiler->inheritance && ($compiler->nocache || $compiler->tag_nocache)))) {
$_caching = self::CACHING_NOCACHE_CODE;
}
/*
* if the {include} tag provides individual parameter for caching
* it will not be included into the common cache file and treated like
* a nocache section
*/
if (isset($_attr['cache_lifetime'])) {
$_cache_lifetime = $_attr['cache_lifetime'];
$compiler->tag_nocache = true;
$_caching = Smarty::CACHING_LIFETIME_CURRENT;
} else {
$_cache_lifetime = 'null';
}
if (isset($_attr['cache_id'])) {
$_cache_id = $_attr['cache_id'];
$compiler->tag_nocache = true;
$_caching = Smarty::CACHING_LIFETIME_CURRENT;
} else {
$_cache_id = '$_smarty_tpl->cache_id';
}
if (isset($_attr['compile_id'])) {
$_compile_id = $_attr['compile_id'];
} else {
$_compile_id = '$_smarty_tpl->compile_id';
}
if ($_attr['caching'] === true) {
$_caching = Smarty::CACHING_LIFETIME_CURRENT;
}
if ($_attr['nocache'] === true) {
$compiler->tag_nocache = true;
if ($merge_compiled_includes) {
$_caching = self::CACHING_NOCACHE_CODE;
} else {
$_caching = Smarty::CACHING_OFF;
}
}
$has_compiled_template = false;
if ($merge_compiled_includes && $_attr['inline'] !== true) {
// variable template name ?
if ($compiler->has_variable_string || !((substr_count($include_file, '"') == 2 || substr_count($include_file, "'") == 2))
|| substr_count($include_file, '(') != 0 || substr_count($include_file, '$_smarty_tpl->') != 0
) {
$merge_compiled_includes = false;
if ($compiler->inheritance && $compiler->smarty->inheritance_merge_compiled_includes) {
$compiler->trigger_template_error(' variable template file names not allow within {block} tags');
}
}
// variable compile_id?
if (isset($_attr['compile_id'])) {
if (!((substr_count($_attr['compile_id'], '"') == 2 || substr_count($_attr['compile_id'], "'") == 2))
|| substr_count($_attr['compile_id'], '(') != 0 || substr_count($_attr['compile_id'], '$_smarty_tpl->') != 0
) {
$merge_compiled_includes = false;
if ($compiler->inheritance && $compiler->smarty->inheritance_merge_compiled_includes) {
$compiler->trigger_template_error(' variable compile_id not allow within {block} tags');
}
}
}
}
if ($merge_compiled_includes) {
if ($compiler->template->caching && ($compiler->tag_nocache || $compiler->nocache) && $_caching != self::CACHING_NOCACHE_CODE) {
$merge_compiled_includes = false;
if ($compiler->inheritance && $compiler->smarty->inheritance_merge_compiled_includes) {
$compiler->trigger_template_error(' invalid caching mode of subtemplate within {block} tags');
}
}
}
if ($merge_compiled_includes) {
// we must observe different compile_id
$uid = sha1($_compile_id);
$tpl_name = null;
$nocache = false;
/** @var Smarty_Internal_Template $_smarty_tpl
* used in evaluated code
*/
$_smarty_tpl = $compiler->template;
eval("\$tpl_name = $include_file;");
if (!isset($compiler->smarty->merged_templates_func[$tpl_name][$uid])) {
$tpl = new $compiler->smarty->template_class ($tpl_name, $compiler->smarty, $compiler->template, $compiler->template->cache_id, $compiler->template->compile_id);
// save unique function name
$compiler->smarty->merged_templates_func[$tpl_name][$uid]['func'] = $tpl->properties['unifunc'] = 'content_' . str_replace(array('.', ','), '_', uniqid('', true));
// use current nocache hash for inlined code
$compiler->smarty->merged_templates_func[$tpl_name][$uid]['nocache_hash'] = $tpl->properties['nocache_hash'] = $compiler->template->properties['nocache_hash'];
if ($compiler->template->caching && $_caching == self::CACHING_NOCACHE_CODE) {
// all code must be nocache
$nocache = true;
}
if ($compiler->inheritance) {
$tpl->compiler->inheritance = true;
}
// make sure whole chain gets compiled
$tpl->mustCompile = true;
if (!($tpl->source->uncompiled) && $tpl->source->exists) {
// get compiled code
$compiled_code = $tpl->compiler->compileTemplate($tpl, $nocache);
// release compiler object to free memory
unset($tpl->compiler);
// merge compiled code for {function} tags
$compiler->template->properties['function'] = array_merge($compiler->template->properties['function'], $tpl->properties['function']);
// merge filedependency
$tpl->properties['file_dependency'][$tpl->source->uid] = array($tpl->source->filepath, $tpl->source->timestamp, $tpl->source->type);
$compiler->template->properties['file_dependency'] = array_merge($compiler->template->properties['file_dependency'], $tpl->properties['file_dependency']);
// remove header code
$compiled_code = preg_replace("/(<\?php \/\*%%SmartyHeaderCode:{$tpl->properties['nocache_hash']}%%\*\/(.+?)\/\*\/%%SmartyHeaderCode%%\*\/\?>\n)/s", '', $compiled_code);
if ($tpl->has_nocache_code) {
// replace nocache_hash
$compiled_code = str_replace("{$tpl->properties['nocache_hash']}", $compiler->template->properties['nocache_hash'], $compiled_code);
$compiler->template->has_nocache_code = true;
}
$compiler->merged_templates[$tpl->properties['unifunc']] = $compiled_code;
$has_compiled_template = true;
unset ($tpl);
}
} else {
$has_compiled_template = true;
}
}
// delete {include} standard attributes
unset($_attr['file'], $_attr['assign'], $_attr['cache_id'], $_attr['compile_id'], $_attr['cache_lifetime'], $_attr['nocache'], $_attr['caching'], $_attr['scope'], $_attr['inline']);
// remaining attributes must be assigned as smarty variable
if (!empty($_attr)) {
if ($_parent_scope == Smarty::SCOPE_LOCAL) {
// create variables
$nccode = '';
foreach ($_attr as $key => $value) {
$_pairs[] = "'$key'=>$value";
$nccode .= "\$_smarty_tpl->tpl_vars['$key'] = new Smarty_variable($value);\n";
}
$_vars = 'array(' . join(',', $_pairs) . ')';
} else {
$compiler->trigger_template_error('variable passing not allowed in parent/global scope', $compiler->lex->taglineno);
}
} else {
$_vars = 'array()';
}
if ($has_compiled_template) {
// never call inline templates in nocache mode
$compiler->suppressNocacheProcessing = true;
$_hash = $compiler->smarty->merged_templates_func[$tpl_name][$uid]['nocache_hash'];
$_output = "<?php /* Call merged included template \"" . $tpl_name . "\" */\n";
$_output .= "\$_tpl_stack[] = \$_smarty_tpl;\n";
if (!empty($nccode) && $_caching == 9999 && $_smarty_tpl->caching) {
$compiler->suppressNocacheProcessing = false;
$_output .= substr($compiler->processNocacheCode('<?php ' .$nccode . "?>\n", true), 6, -3);
$compiler->suppressNocacheProcessing = true;
}
$_output .= " \$_smarty_tpl = \$_smarty_tpl->setupInlineSubTemplate($include_file, $_cache_id, $_compile_id, $_caching, $_cache_lifetime, $_vars, $_parent_scope, '$_hash');\n";
if (isset($_assign)) {
$_output .= 'ob_start(); ';
}
$_output .= $compiler->smarty->merged_templates_func[$tpl_name][$uid]['func'] . "(\$_smarty_tpl);\n";
$_output .= "\$_smarty_tpl = array_pop(\$_tpl_stack); ";
if (isset($_assign)) {
$_output .= " \$_smarty_tpl->tpl_vars[$_assign] = new Smarty_variable(ob_get_clean());";
}
$_output .= "\n/* End of included template \"" . $tpl_name . "\" */?>";
return $_output;
}
// was there an assign attribute
if (isset($_assign)) {
$_output = "<?php \$_smarty_tpl->tpl_vars[$_assign] = new Smarty_variable(\$_smarty_tpl->getSubTemplate ($include_file, $_cache_id, $_compile_id, $_caching, $_cache_lifetime, $_vars, $_parent_scope));?>\n";;
} else {
$_output = "<?php echo \$_smarty_tpl->getSubTemplate ($include_file, $_cache_id, $_compile_id, $_caching, $_cache_lifetime, $_vars, $_parent_scope);?>\n";
}
return $_output;
}
}

View File

@@ -1,85 +0,0 @@
<?php
/**
* Smarty Internal Plugin Compile Block Plugin
* Compiles code for the execution of block plugin
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile Block Plugin Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Private_Block_Plugin extends Smarty_Internal_CompileBase
{
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $optional_attributes = array('_any');
/**
* Compiles code for the execution of block plugin
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
* @param string $tag name of block plugin
* @param string $function PHP function name
*
* @return string compiled code
*/
public function compile($args, $compiler, $parameter, $tag, $function)
{
if (!isset($tag[5]) || substr($tag, - 5) != 'close') {
// opening tag of block plugin
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
if ($_attr['nocache'] === true) {
$compiler->tag_nocache = true;
}
unset($_attr['nocache']);
// convert attributes into parameter array string
$_paramsArray = array();
foreach ($_attr as $_key => $_value) {
if (is_int($_key)) {
$_paramsArray[] = "$_key=>$_value";
} else {
$_paramsArray[] = "'$_key'=>$_value";
}
}
$_params = 'array(' . implode(",", $_paramsArray) . ')';
$this->openTag($compiler, $tag, array($_params, $compiler->nocache));
// maybe nocache because of nocache variables or nocache plugin
$compiler->nocache = $compiler->nocache | $compiler->tag_nocache;
// compile code
$output = "<?php \$_smarty_tpl->smarty->_tag_stack[] = array('{$tag}', {$_params}); \$_block_repeat=true; echo {$function}({$_params}, null, \$_smarty_tpl, \$_block_repeat);while (\$_block_repeat) { ob_start();?>";
} else {
// must endblock be nocache?
if ($compiler->nocache) {
$compiler->tag_nocache = true;
}
// closing tag of block plugin, restore nocache
list($_params, $compiler->nocache) = $this->closeTag($compiler, substr($tag, 0, - 5));
// This tag does create output
$compiler->has_output = true;
// compile code
if (!isset($parameter['modifier_list'])) {
$mod_pre = $mod_post = '';
} else {
$mod_pre = ' ob_start(); ';
$mod_post = 'echo ' . $compiler->compileTag('private_modifier', array(), array('modifierlist' => $parameter['modifier_list'], 'value' => 'ob_get_clean()')) . ';';
}
$output = "<?php \$_block_content = ob_get_clean(); \$_block_repeat=false;" . $mod_pre . " echo {$function}({$_params}, \$_block_content, \$_smarty_tpl, \$_block_repeat); " . $mod_post . " } array_pop(\$_smarty_tpl->smarty->_tag_stack);?>";
}
return $output . "\n";
}
}

View File

@@ -1,86 +0,0 @@
<?php
/**
* Smarty Internal Plugin Compile Object Block Function
* Compiles code for registered objects as block function
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile Object Block Function Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Private_Object_Block_Function extends Smarty_Internal_CompileBase
{
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $optional_attributes = array('_any');
/**
* Compiles code for the execution of block plugin
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
* @param string $tag name of block object
* @param string $method name of method to call
*
* @return string compiled code
*/
public function compile($args, $compiler, $parameter, $tag, $method)
{
if (!isset($tag[5]) || substr($tag, - 5) != 'close') {
// opening tag of block plugin
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
if ($_attr['nocache'] === true) {
$compiler->tag_nocache = true;
}
unset($_attr['nocache']);
// convert attributes into parameter array string
$_paramsArray = array();
foreach ($_attr as $_key => $_value) {
if (is_int($_key)) {
$_paramsArray[] = "$_key=>$_value";
} else {
$_paramsArray[] = "'$_key'=>$_value";
}
}
$_params = 'array(' . implode(",", $_paramsArray) . ')';
$this->openTag($compiler, $tag . '->' . $method, array($_params, $compiler->nocache));
// maybe nocache because of nocache variables or nocache plugin
$compiler->nocache = $compiler->nocache | $compiler->tag_nocache;
// compile code
$output = "<?php \$_smarty_tpl->smarty->_tag_stack[] = array('{$tag}->{$method}', {$_params}); \$_block_repeat=true; echo \$_smarty_tpl->smarty->registered_objects['{$tag}'][0]->{$method}({$_params}, null, \$_smarty_tpl, \$_block_repeat);while (\$_block_repeat) { ob_start();?>";
} else {
$base_tag = substr($tag, 0, - 5);
// must endblock be nocache?
if ($compiler->nocache) {
$compiler->tag_nocache = true;
}
// closing tag of block plugin, restore nocache
list($_params, $compiler->nocache) = $this->closeTag($compiler, $base_tag . '->' . $method);
// This tag does create output
$compiler->has_output = true;
// compile code
if (!isset($parameter['modifier_list'])) {
$mod_pre = $mod_post = '';
} else {
$mod_pre = ' ob_start(); ';
$mod_post = 'echo ' . $compiler->compileTag('private_modifier', array(), array('modifierlist' => $parameter['modifier_list'], 'value' => 'ob_get_clean()')) . ';';
}
$output = "<?php \$_block_content = ob_get_contents(); ob_end_clean(); \$_block_repeat=false;" . $mod_pre . " echo \$_smarty_tpl->smarty->registered_objects['{$base_tag}'][0]->{$method}({$_params}, \$_block_content, \$_smarty_tpl, \$_block_repeat); " . $mod_post . " } array_pop(\$_smarty_tpl->smarty->_tag_stack);?>";
}
return $output . "\n";
}
}

View File

@@ -1,151 +0,0 @@
<?php
/**
* Smarty Internal Plugin Compile Print Expression
* Compiles any tag which will output an expression or variable
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile Print Expression Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Private_Print_Expression extends Smarty_Internal_CompileBase
{
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $optional_attributes = array('assign');
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $option_flags = array('nocache', 'nofilter');
/**
* Compiles code for generating output from any expression
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
*
* @throws SmartyException
* @return string compiled code
*/
public function compile($args, $compiler, $parameter)
{
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
// nocache option
if ($_attr['nocache'] === true) {
$compiler->tag_nocache = true;
}
if (isset($_attr['assign'])) {
// assign output to variable
$output = "<?php \$_smarty_tpl->assign({$_attr['assign']},{$parameter['value']});?>";
} else {
// display value
$output = $parameter['value'];
// tag modifier
if (!empty($parameter['modifierlist'])) {
$output = $compiler->compileTag('private_modifier', array(), array('modifierlist' => $parameter['modifierlist'], 'value' => $output));
}
if (!$_attr['nofilter']) {
// default modifier
if (!empty($compiler->smarty->default_modifiers)) {
if (empty($compiler->default_modifier_list)) {
$modifierlist = array();
foreach ($compiler->smarty->default_modifiers as $key => $single_default_modifier) {
preg_match_all('/(\'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\'|"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"|:|[^:]+)/', $single_default_modifier, $mod_array);
for ($i = 0, $count = count($mod_array[0]); $i < $count; $i ++) {
if ($mod_array[0][$i] != ':') {
$modifierlist[$key][] = $mod_array[0][$i];
}
}
}
$compiler->default_modifier_list = $modifierlist;
}
$output = $compiler->compileTag('private_modifier', array(), array('modifierlist' => $compiler->default_modifier_list, 'value' => $output));
}
// autoescape html
if ($compiler->template->smarty->escape_html) {
$output = "htmlspecialchars({$output}, ENT_QUOTES, '" . addslashes(Smarty::$_CHARSET) . "')";
}
// loop over registered filters
if (!empty($compiler->template->smarty->registered_filters[Smarty::FILTER_VARIABLE])) {
foreach ($compiler->template->smarty->registered_filters[Smarty::FILTER_VARIABLE] as $key => $function) {
if (!is_array($function)) {
$output = "{$function}({$output},\$_smarty_tpl)";
} elseif (is_object($function[0])) {
$output = "\$_smarty_tpl->smarty->registered_filters[Smarty::FILTER_VARIABLE]['{$key}'][0]->{$function[1]}({$output},\$_smarty_tpl)";
} else {
$output = "{$function[0]}::{$function[1]}({$output},\$_smarty_tpl)";
}
}
}
// auto loaded filters
if (isset($compiler->smarty->autoload_filters[Smarty::FILTER_VARIABLE])) {
foreach ((array) $compiler->template->smarty->autoload_filters[Smarty::FILTER_VARIABLE] as $name) {
$result = $this->compile_output_filter($compiler, $name, $output);
if ($result !== false) {
$output = $result;
} else {
// not found, throw exception
throw new SmartyException("Unable to load filter '{$name}'");
}
}
}
if (isset($compiler->template->variable_filters)) {
foreach ($compiler->template->variable_filters as $filter) {
if (count($filter) == 1 && ($result = $this->compile_output_filter($compiler, $filter[0], $output)) !== false) {
$output = $result;
} else {
$output = $compiler->compileTag('private_modifier', array(), array('modifierlist' => array($filter), 'value' => $output));
}
}
}
}
$compiler->has_output = true;
$output = "<?php echo {$output};?>";
}
return $output;
}
/**
* @param object $compiler compiler object
* @param string $name name of variable filter
* @param string $output embedded output
*
* @return string
*/
private function compile_output_filter($compiler, $name, $output)
{
$plugin_name = "smarty_variablefilter_{$name}";
$path = $compiler->smarty->loadPlugin($plugin_name, false);
if ($path) {
if ($compiler->template->caching) {
$compiler->template->required_plugins['nocache'][$name][Smarty::FILTER_VARIABLE]['file'] = $path;
$compiler->template->required_plugins['nocache'][$name][Smarty::FILTER_VARIABLE]['function'] = $plugin_name;
} else {
$compiler->template->required_plugins['compiled'][$name][Smarty::FILTER_VARIABLE]['file'] = $path;
$compiler->template->required_plugins['compiled'][$name][Smarty::FILTER_VARIABLE]['function'] = $plugin_name;
}
} else {
// not found
return false;
}
return "{$plugin_name}({$output},\$_smarty_tpl)";
}
}

View File

@@ -1,111 +0,0 @@
<?php
/**
* Smarty Internal Plugin Compile Registered Block
* Compiles code for the execution of a registered block function
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile Registered Block Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Private_Registered_Block extends Smarty_Internal_CompileBase
{
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $optional_attributes = array('_any');
/**
* Compiles code for the execution of a block function
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
* @param string $tag name of block function
*
* @return string compiled code
*/
public function compile($args, $compiler, $parameter, $tag)
{
if (!isset($tag[5]) || substr($tag, - 5) != 'close') {
// opening tag of block plugin
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
if ($_attr['nocache']) {
$compiler->tag_nocache = true;
}
unset($_attr['nocache']);
if (isset($compiler->smarty->registered_plugins[Smarty::PLUGIN_BLOCK][$tag])) {
$tag_info = $compiler->smarty->registered_plugins[Smarty::PLUGIN_BLOCK][$tag];
} else {
$tag_info = $compiler->default_handler_plugins[Smarty::PLUGIN_BLOCK][$tag];
}
// convert attributes into parameter array string
$_paramsArray = array();
foreach ($_attr as $_key => $_value) {
if (is_int($_key)) {
$_paramsArray[] = "$_key=>$_value";
} elseif ($compiler->template->caching && in_array($_key, $tag_info[2])) {
$_value = str_replace("'", "^#^", $_value);
$_paramsArray[] = "'$_key'=>^#^.var_export($_value,true).^#^";
} else {
$_paramsArray[] = "'$_key'=>$_value";
}
}
$_params = 'array(' . implode(",", $_paramsArray) . ')';
$this->openTag($compiler, $tag, array($_params, $compiler->nocache));
// maybe nocache because of nocache variables or nocache plugin
$compiler->nocache = !$tag_info[1] | $compiler->nocache | $compiler->tag_nocache;
$function = $tag_info[0];
// compile code
if (!is_array($function)) {
$output = "<?php \$_smarty_tpl->smarty->_tag_stack[] = array('{$tag}', {$_params}); \$_block_repeat=true; echo {$function}({$_params}, null, \$_smarty_tpl, \$_block_repeat);while (\$_block_repeat) { ob_start();?>";
} elseif (is_object($function[0])) {
$output = "<?php \$_smarty_tpl->smarty->_tag_stack[] = array('{$tag}', {$_params}); \$_block_repeat=true; echo \$_smarty_tpl->smarty->registered_plugins['block']['{$tag}'][0][0]->{$function[1]}({$_params}, null, \$_smarty_tpl, \$_block_repeat);while (\$_block_repeat) { ob_start();?>";
} else {
$output = "<?php \$_smarty_tpl->smarty->_tag_stack[] = array('{$tag}', {$_params}); \$_block_repeat=true; echo {$function[0]}::{$function[1]}({$_params}, null, \$_smarty_tpl, \$_block_repeat);while (\$_block_repeat) { ob_start();?>";
}
} else {
// must endblock be nocache?
if ($compiler->nocache) {
$compiler->tag_nocache = true;
}
$base_tag = substr($tag, 0, - 5);
// closing tag of block plugin, restore nocache
list($_params, $compiler->nocache) = $this->closeTag($compiler, $base_tag);
// This tag does create output
$compiler->has_output = true;
if (isset($compiler->smarty->registered_plugins[Smarty::PLUGIN_BLOCK][$base_tag])) {
$function = $compiler->smarty->registered_plugins[Smarty::PLUGIN_BLOCK][$base_tag][0];
} else {
$function = $compiler->default_handler_plugins[Smarty::PLUGIN_BLOCK][$base_tag][0];
}
// compile code
if (!isset($parameter['modifier_list'])) {
$mod_pre = $mod_post = '';
} else {
$mod_pre = ' ob_start(); ';
$mod_post = 'echo ' . $compiler->compileTag('private_modifier', array(), array('modifierlist' => $parameter['modifier_list'], 'value' => 'ob_get_clean()')) . ';';
}
if (!is_array($function)) {
$output = "<?php \$_block_content = ob_get_clean(); \$_block_repeat=false;" . $mod_pre . " echo {$function}({$_params}, \$_block_content, \$_smarty_tpl, \$_block_repeat);" . $mod_post . " } array_pop(\$_smarty_tpl->smarty->_tag_stack);?>";
} elseif (is_object($function[0])) {
$output = "<?php \$_block_content = ob_get_clean(); \$_block_repeat=false;" . $mod_pre . " echo \$_smarty_tpl->smarty->registered_plugins['block']['{$base_tag}'][0][0]->{$function[1]}({$_params}, \$_block_content, \$_smarty_tpl, \$_block_repeat); " . $mod_post . "} array_pop(\$_smarty_tpl->smarty->_tag_stack);?>";
} else {
$output = "<?php \$_block_content = ob_get_clean(); \$_block_repeat=false;" . $mod_pre . " echo {$function[0]}::{$function[1]}({$_params}, \$_block_content, \$_smarty_tpl, \$_block_repeat); " . $mod_post . "} array_pop(\$_smarty_tpl->smarty->_tag_stack);?>";
}
}
return $output . "\n";
}
}

View File

@@ -1,79 +0,0 @@
<?php
/**
* Smarty Internal Plugin Compile Registered Function
* Compiles code for the execution of a registered function
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile Registered Function Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Private_Registered_Function extends Smarty_Internal_CompileBase
{
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $optional_attributes = array('_any');
/**
* Compiles code for the execution of a registered function
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
* @param string $tag name of function
*
* @return string compiled code
*/
public function compile($args, $compiler, $parameter, $tag)
{
// This tag does create output
$compiler->has_output = true;
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
if ($_attr['nocache']) {
$compiler->tag_nocache = true;
}
unset($_attr['nocache']);
if (isset($compiler->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION][$tag])) {
$tag_info = $compiler->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION][$tag];
} else {
$tag_info = $compiler->default_handler_plugins[Smarty::PLUGIN_FUNCTION][$tag];
}
// not cachable?
$compiler->tag_nocache = $compiler->tag_nocache || !$tag_info[1];
// convert attributes into parameter array string
$_paramsArray = array();
foreach ($_attr as $_key => $_value) {
if (is_int($_key)) {
$_paramsArray[] = "$_key=>$_value";
} elseif ($compiler->template->caching && in_array($_key, $tag_info[2])) {
$_value = str_replace("'", "^#^", $_value);
$_paramsArray[] = "'$_key'=>^#^.var_export($_value,true).^#^";
} else {
$_paramsArray[] = "'$_key'=>$_value";
}
}
$_params = 'array(' . implode(",", $_paramsArray) . ')';
$function = $tag_info[0];
// compile code
if (!is_array($function)) {
$output = "<?php echo {$function}({$_params},\$_smarty_tpl);?>\n";
} elseif (is_object($function[0])) {
$output = "<?php echo \$_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['{$tag}'][0][0]->{$function[1]}({$_params},\$_smarty_tpl);?>\n";
} else {
$output = "<?php echo {$function[0]}::{$function[1]}({$_params},\$_smarty_tpl);?>\n";
}
return $output;
}
}

View File

@@ -1,114 +0,0 @@
<?php
/**
* Smarty Internal Plugin Compile Special Smarty Variable
* Compiles the special $smarty variables
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile special Smarty Variable Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Private_Special_Variable extends Smarty_Internal_CompileBase
{
/**
* Compiles code for the special $smarty variables
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @param $parameter
*
* @return string compiled code
*/
public function compile($args, $compiler, $parameter)
{
$_index = preg_split("/\]\[/", substr($parameter, 1, strlen($parameter) - 2));
$compiled_ref = ' ';
$variable = trim($_index[0], "'");
switch ($variable) {
case 'foreach':
return "\$_smarty_tpl->getVariable('smarty')->value$parameter";
case 'section':
return "\$_smarty_tpl->getVariable('smarty')->value$parameter";
case 'capture':
return "Smarty::\$_smarty_vars$parameter";
case 'now':
return 'time()';
case 'cookies':
if (isset($compiler->smarty->security_policy) && !$compiler->smarty->security_policy->allow_super_globals) {
$compiler->trigger_template_error("(secure mode) super globals not permitted");
break;
}
$compiled_ref = '$_COOKIE';
break;
case 'get':
case 'post':
case 'env':
case 'server':
case 'session':
case 'request':
if (isset($compiler->smarty->security_policy) && !$compiler->smarty->security_policy->allow_super_globals) {
$compiler->trigger_template_error("(secure mode) super globals not permitted");
break;
}
$compiled_ref = '$_' . strtoupper($variable);
break;
case 'template':
return 'basename($_smarty_tpl->source->filepath)';
case 'template_object':
return '$_smarty_tpl';
case 'current_dir':
return 'dirname($_smarty_tpl->source->filepath)';
case 'version':
$_version = Smarty::SMARTY_VERSION;
return "'$_version'";
case 'const':
if (isset($compiler->smarty->security_policy) && !$compiler->smarty->security_policy->allow_constants) {
$compiler->trigger_template_error("(secure mode) constants not permitted");
break;
}
return "@constant({$_index[1]})";
case 'config':
if (isset($_index[2])) {
return "(is_array(\$tmp = \$_smarty_tpl->getConfigVariable($_index[1])) ? \$tmp[$_index[2]] : null)";
} else {
return "\$_smarty_tpl->getConfigVariable($_index[1])";
}
case 'ldelim':
$_ldelim = $compiler->smarty->left_delimiter;
return "'$_ldelim'";
case 'rdelim':
$_rdelim = $compiler->smarty->right_delimiter;
return "'$_rdelim'";
default:
$compiler->trigger_template_error('$smarty.' . trim($_index[0], "'") . ' is invalid');
break;
}
if (isset($_index[1])) {
array_shift($_index);
foreach ($_index as $_ind) {
$compiled_ref = $compiled_ref . "[$_ind]";
}
}
return $compiled_ref;
}
}

View File

@@ -1,206 +0,0 @@
<?php
/**
* Smarty Internal Plugin Compile Section
* Compiles the {section} {sectionelse} {/section} tags
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile Section Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Section extends Smarty_Internal_CompileBase
{
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $required_attributes = array('name', 'loop');
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $shorttag_order = array('name', 'loop');
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $optional_attributes = array('start', 'step', 'max', 'show');
/**
* Compiles code for the {section} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
*
* @return string compiled code
*/
public function compile($args, $compiler)
{
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
$this->openTag($compiler, 'section', array('section', $compiler->nocache));
// maybe nocache because of nocache variables
$compiler->nocache = $compiler->nocache | $compiler->tag_nocache;
$output = "<?php ";
$section_name = $_attr['name'];
$output .= "if (isset(\$_smarty_tpl->tpl_vars['smarty']->value['section'][$section_name])) unset(\$_smarty_tpl->tpl_vars['smarty']->value['section'][$section_name]);\n";
$section_props = "\$_smarty_tpl->tpl_vars['smarty']->value['section'][$section_name]";
foreach ($_attr as $attr_name => $attr_value) {
switch ($attr_name) {
case 'loop':
$output .= "{$section_props}['loop'] = is_array(\$_loop=$attr_value) ? count(\$_loop) : max(0, (int) \$_loop); unset(\$_loop);\n";
break;
case 'show':
if (is_bool($attr_value)) {
$show_attr_value = $attr_value ? 'true' : 'false';
} else {
$show_attr_value = "(bool) $attr_value";
}
$output .= "{$section_props}['show'] = $show_attr_value;\n";
break;
case 'name':
$output .= "{$section_props}['$attr_name'] = $attr_value;\n";
break;
case 'max':
case 'start':
$output .= "{$section_props}['$attr_name'] = (int) $attr_value;\n";
break;
case 'step':
$output .= "{$section_props}['$attr_name'] = ((int) $attr_value) == 0 ? 1 : (int) $attr_value;\n";
break;
}
}
if (!isset($_attr['show'])) {
$output .= "{$section_props}['show'] = true;\n";
}
if (!isset($_attr['loop'])) {
$output .= "{$section_props}['loop'] = 1;\n";
}
if (!isset($_attr['max'])) {
$output .= "{$section_props}['max'] = {$section_props}['loop'];\n";
} else {
$output .= "if ({$section_props}['max'] < 0)\n" . " {$section_props}['max'] = {$section_props}['loop'];\n";
}
if (!isset($_attr['step'])) {
$output .= "{$section_props}['step'] = 1;\n";
}
if (!isset($_attr['start'])) {
$output .= "{$section_props}['start'] = {$section_props}['step'] > 0 ? 0 : {$section_props}['loop']-1;\n";
} else {
$output .= "if ({$section_props}['start'] < 0)\n" . " {$section_props}['start'] = max({$section_props}['step'] > 0 ? 0 : -1, {$section_props}['loop'] + {$section_props}['start']);\n" . "else\n" . " {$section_props}['start'] = min({$section_props}['start'], {$section_props}['step'] > 0 ? {$section_props}['loop'] : {$section_props}['loop']-1);\n";
}
$output .= "if ({$section_props}['show']) {\n";
if (!isset($_attr['start']) && !isset($_attr['step']) && !isset($_attr['max'])) {
$output .= " {$section_props}['total'] = {$section_props}['loop'];\n";
} else {
$output .= " {$section_props}['total'] = min(ceil(({$section_props}['step'] > 0 ? {$section_props}['loop'] - {$section_props}['start'] : {$section_props}['start']+1)/abs({$section_props}['step'])), {$section_props}['max']);\n";
}
$output .= " if ({$section_props}['total'] == 0)\n" . " {$section_props}['show'] = false;\n" . "} else\n" . " {$section_props}['total'] = 0;\n";
$output .= "if ({$section_props}['show']):\n";
$output .= "
for ({$section_props}['index'] = {$section_props}['start'], {$section_props}['iteration'] = 1;
{$section_props}['iteration'] <= {$section_props}['total'];
{$section_props}['index'] += {$section_props}['step'], {$section_props}['iteration']++):\n";
$output .= "{$section_props}['rownum'] = {$section_props}['iteration'];\n";
$output .= "{$section_props}['index_prev'] = {$section_props}['index'] - {$section_props}['step'];\n";
$output .= "{$section_props}['index_next'] = {$section_props}['index'] + {$section_props}['step'];\n";
$output .= "{$section_props}['first'] = ({$section_props}['iteration'] == 1);\n";
$output .= "{$section_props}['last'] = ({$section_props}['iteration'] == {$section_props}['total']);\n";
$output .= "?>";
return $output;
}
}
/**
* Smarty Internal Plugin Compile Sectionelse Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Sectionelse extends Smarty_Internal_CompileBase
{
/**
* Compiles code for the {sectionelse} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
*
* @return string compiled code
*/
public function compile($args, $compiler)
{
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
list($openTag, $nocache) = $this->closeTag($compiler, array('section'));
$this->openTag($compiler, 'sectionelse', array('sectionelse', $nocache));
return "<?php endfor; else: ?>";
}
}
/**
* Smarty Internal Plugin Compile Sectionclose Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Sectionclose extends Smarty_Internal_CompileBase
{
/**
* Compiles code for the {/section} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
*
* @return string compiled code
*/
public function compile($args, $compiler)
{
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
// must endblock be nocache?
if ($compiler->nocache) {
$compiler->tag_nocache = true;
}
list($openTag, $compiler->nocache) = $this->closeTag($compiler, array('section', 'sectionelse'));
if ($openTag == 'sectionelse') {
return "<?php endif; ?>";
} else {
return "<?php endfor; endif; ?>";
}
}
}

View File

@@ -1,93 +0,0 @@
<?php
/**
* Smarty Internal Plugin Compile While
* Compiles the {while} tag
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile While Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_While extends Smarty_Internal_CompileBase
{
/**
* Compiles code for the {while} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
*
* @return string compiled code
*/
public function compile($args, $compiler, $parameter)
{
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
$this->openTag($compiler, 'while', $compiler->nocache);
if (!array_key_exists("if condition", $parameter)) {
$compiler->trigger_template_error("missing while condition", $compiler->lex->taglineno);
}
// maybe nocache because of nocache variables
$compiler->nocache = $compiler->nocache | $compiler->tag_nocache;
if (is_array($parameter['if condition'])) {
if ($compiler->nocache) {
$_nocache = ',true';
// create nocache var to make it know for further compiling
if (is_array($parameter['if condition']['var'])) {
$compiler->template->tpl_vars[trim($parameter['if condition']['var']['var'], "'")] = new Smarty_variable(null, true);
} else {
$compiler->template->tpl_vars[trim($parameter['if condition']['var'], "'")] = new Smarty_variable(null, true);
}
} else {
$_nocache = '';
}
if (is_array($parameter['if condition']['var'])) {
$_output = "<?php if (!isset(\$_smarty_tpl->tpl_vars[" . $parameter['if condition']['var']['var'] . "]) || !is_array(\$_smarty_tpl->tpl_vars[" . $parameter['if condition']['var']['var'] . "]->value)) \$_smarty_tpl->createLocalArrayVariable(" . $parameter['if condition']['var']['var'] . "$_nocache);\n";
$_output .= "while (\$_smarty_tpl->tpl_vars[" . $parameter['if condition']['var']['var'] . "]->value" . $parameter['if condition']['var']['smarty_internal_index'] . " = " . $parameter['if condition']['value'] . ") {?>";
} else {
$_output = "<?php if (!isset(\$_smarty_tpl->tpl_vars[" . $parameter['if condition']['var'] . "])) \$_smarty_tpl->tpl_vars[" . $parameter['if condition']['var'] . "] = new Smarty_Variable(null{$_nocache});";
$_output .= "while (\$_smarty_tpl->tpl_vars[" . $parameter['if condition']['var'] . "]->value = " . $parameter['if condition']['value'] . ") {?>";
}
return $_output;
} else {
return "<?php while ({$parameter['if condition']}) {?>";
}
}
}
/**
* Smarty Internal Plugin Compile Whileclose Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Whileclose extends Smarty_Internal_CompileBase
{
/**
* Compiles code for the {/while} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
*
* @return string compiled code
*/
public function compile($args, $compiler)
{
// must endblock be nocache?
if ($compiler->nocache) {
$compiler->tag_nocache = true;
}
$compiler->nocache = $this->closeTag($compiler, array('while'));
return "<?php }?>";
}
}

View File

@@ -1,306 +0,0 @@
<?php
/**
* Smarty Internal Plugin Config
*
* @package Smarty
* @subpackage Config
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Config
* Main class for config variables
*
* @package Smarty
* @subpackage Config
* @ignore
*/
class Smarty_Internal_Config
{
/**
* Smarty instance
*
* @var Smarty object
*/
public $smarty = null;
/**
* Object of config var storage
*
* @var object
*/
public $data = null;
/**
* Config resource
*
* @var string
*/
public $config_resource = null;
/**
* Compiled config file
*
* @var string
*/
public $compiled_config = null;
/**
* filepath of compiled config file
*
* @var string
*/
public $compiled_filepath = null;
/**
* Filemtime of compiled config Filemtime
*
* @var int
*/
public $compiled_timestamp = null;
/**
* flag if compiled config file is invalid and must be (re)compiled
*
* @var bool
*/
public $mustCompile = null;
/**
* Config file compiler object
*
* @var Smarty_Internal_Config_File_Compiler object
*/
public $compiler_object = null;
/**
* Constructor of config file object
*
* @param string $config_resource config file resource name
* @param Smarty $smarty Smarty instance
* @param object $data object for config vars storage
*/
public function __construct($config_resource, $smarty, $data = null)
{
$this->data = $data;
$this->smarty = $smarty;
$this->config_resource = $config_resource;
}
/**
* Returns the compiled filepath
*
* @return string the compiled filepath
*/
public function getCompiledFilepath()
{
return $this->compiled_filepath === null ?
($this->compiled_filepath = $this->buildCompiledFilepath()) :
$this->compiled_filepath;
}
/**
* Get file path.
*
* @return string
*/
public function buildCompiledFilepath()
{
$_compile_id = isset($this->smarty->compile_id) ? preg_replace('![^\w\|]+!', '_', $this->smarty->compile_id) : null;
$_flag = (int) $this->smarty->config_read_hidden + (int) $this->smarty->config_booleanize * 2
+ (int) $this->smarty->config_overwrite * 4;
$_filepath = sha1(realpath($this->source->filepath) . $_flag);
// if use_sub_dirs, break file into directories
if ($this->smarty->use_sub_dirs) {
$_filepath = substr($_filepath, 0, 2) . DS
. substr($_filepath, 2, 2) . DS
. substr($_filepath, 4, 2) . DS
. $_filepath;
}
$_compile_dir_sep = $this->smarty->use_sub_dirs ? DS : '^';
if (isset($_compile_id)) {
$_filepath = $_compile_id . $_compile_dir_sep . $_filepath;
}
$_compile_dir = $this->smarty->getCompileDir();
return $_compile_dir . $_filepath . '.' . basename($this->source->name) . '.config' . '.php';
}
/**
* Returns the timestamp of the compiled file
*
* @return integer the file timestamp
*/
public function getCompiledTimestamp()
{
return $this->compiled_timestamp === null
? ($this->compiled_timestamp = (file_exists($this->getCompiledFilepath())) ? filemtime($this->getCompiledFilepath()) : false)
: $this->compiled_timestamp;
}
/**
* Returns if the current config file must be compiled
* It does compare the timestamps of config source and the compiled config and checks the force compile configuration
*
* @return boolean true if the file must be compiled
*/
public function mustCompile()
{
return $this->mustCompile === null ?
$this->mustCompile = ($this->smarty->force_compile || $this->getCompiledTimestamp() === false || $this->smarty->compile_check && $this->getCompiledTimestamp() < $this->source->timestamp) :
$this->mustCompile;
}
/**
* Returns the compiled config file
* It checks if the config file must be compiled or just read the compiled version
*
* @return string the compiled config file
*/
public function getCompiledConfig()
{
if ($this->compiled_config === null) {
// see if template needs compiling.
if ($this->mustCompile()) {
$this->compileConfigSource();
} else {
$this->compiled_config = file_get_contents($this->getCompiledFilepath());
}
}
return $this->compiled_config;
}
/**
* Compiles the config files
*
* @throws Exception
*/
public function compileConfigSource()
{
// compile template
if (!is_object($this->compiler_object)) {
// load compiler
$this->compiler_object = new Smarty_Internal_Config_File_Compiler($this->smarty);
}
// compile locking
if ($this->smarty->compile_locking) {
if ($saved_timestamp = $this->getCompiledTimestamp()) {
touch($this->getCompiledFilepath());
}
}
// call compiler
try {
$this->compiler_object->compileSource($this);
}
catch (Exception $e) {
// restore old timestamp in case of error
if ($this->smarty->compile_locking && $saved_timestamp) {
touch($this->getCompiledFilepath(), $saved_timestamp);
}
throw $e;
}
// compiling succeeded
// write compiled template
Smarty_Internal_Write_File::writeFile($this->getCompiledFilepath(), $this->getCompiledConfig(), $this->smarty);
}
/**
* load config variables
*
* @param mixed $sections array of section names, single section or null
* @param string $scope global,parent or local
*
* @throws Exception
*/
public function loadConfigVars($sections = null, $scope = 'local')
{
if ($this->data instanceof Smarty_Internal_Template) {
$this->data->properties['file_dependency'][sha1($this->source->filepath)] = array($this->source->filepath, $this->source->timestamp, 'file');
}
if ($this->mustCompile()) {
$this->compileConfigSource();
}
// pointer to scope
if ($scope == 'local') {
$scope_ptr = $this->data;
} elseif ($scope == 'parent') {
if (isset($this->data->parent)) {
$scope_ptr = $this->data->parent;
} else {
$scope_ptr = $this->data;
}
} elseif ($scope == 'root' || $scope == 'global') {
$scope_ptr = $this->data;
while (isset($scope_ptr->parent)) {
$scope_ptr = $scope_ptr->parent;
}
}
$_config_vars = array();
include($this->getCompiledFilepath());
// copy global config vars
foreach ($_config_vars['vars'] as $variable => $value) {
if ($this->smarty->config_overwrite || !isset($scope_ptr->config_vars[$variable])) {
$scope_ptr->config_vars[$variable] = $value;
} else {
$scope_ptr->config_vars[$variable] = array_merge((array) $scope_ptr->config_vars[$variable], (array) $value);
}
}
// scan sections
if (!empty($sections)) {
foreach ((array) $sections as $this_section) {
if (isset($_config_vars['sections'][$this_section])) {
foreach ($_config_vars['sections'][$this_section]['vars'] as $variable => $value) {
if ($this->smarty->config_overwrite || !isset($scope_ptr->config_vars[$variable])) {
$scope_ptr->config_vars[$variable] = $value;
} else {
$scope_ptr->config_vars[$variable] = array_merge((array) $scope_ptr->config_vars[$variable], (array) $value);
}
}
}
}
}
}
/**
* set Smarty property in template context
*
* @param string $property_name property name
* @param mixed $value value
*
* @throws SmartyException if $property_name is not valid
*/
public function __set($property_name, $value)
{
switch ($property_name) {
case 'source':
case 'compiled':
$this->$property_name = $value;
return;
}
throw new SmartyException("invalid config property '$property_name'.");
}
/**
* get Smarty property in template context
*
* @param string $property_name property name
*
* @return \Smarty_Config_Source|\Smarty_Template_Compiled
* @throws SmartyException if $property_name is not valid
*/
public function __get($property_name)
{
switch ($property_name) {
case 'source':
if (empty($this->config_resource)) {
throw new SmartyException("Unable to parse resource name \"{$this->config_resource}\"");
}
$this->source = Smarty_Resource::config($this);
return $this->source;
case 'compiled':
$this->compiled = $this->source->getCompiled($this);
return $this->compiled;
}
throw new SmartyException("config attribute '$property_name' does not exist.");
}
}

View File

@@ -1,576 +0,0 @@
<?php
/**
* Smarty Internal Plugin Data
* This file contains the basic classes and methods for template and variable creation
*
* @package Smarty
* @subpackage Template
* @author Uwe Tews
*/
/**
* Base class with template and variable methods
*
* @package Smarty
* @subpackage Template
*/
class Smarty_Internal_Data
{
/**
* name of class used for templates
*
* @var string
*/
public $template_class = 'Smarty_Internal_Template';
/**
* template variables
*
* @var array
*/
public $tpl_vars = array();
/**
* parent template (if any)
*
* @var Smarty_Internal_Template
*/
public $parent = null;
/**
* configuration settings
*
* @var array
*/
public $config_vars = array();
/**
* assigns a Smarty variable
*
* @param array|string $tpl_var the template variable name(s)
* @param mixed $value the value to assign
* @param boolean $nocache if true any output of this variable will be not cached
*
* @return Smarty_Internal_Data current Smarty_Internal_Data (or Smarty or Smarty_Internal_Template) instance for chaining
*/
public function assign($tpl_var, $value = null, $nocache = false)
{
if (is_array($tpl_var)) {
foreach ($tpl_var as $_key => $_val) {
if ($_key != '') {
$this->tpl_vars[$_key] = new Smarty_variable($_val, $nocache);
}
}
} else {
if ($tpl_var != '') {
$this->tpl_vars[$tpl_var] = new Smarty_variable($value, $nocache);
}
}
return $this;
}
/**
* assigns a global Smarty variable
*
* @param string $varname the global variable name
* @param mixed $value the value to assign
* @param boolean $nocache if true any output of this variable will be not cached
*
* @return Smarty_Internal_Data current Smarty_Internal_Data (or Smarty or Smarty_Internal_Template) instance for chaining
*/
public function assignGlobal($varname, $value = null, $nocache = false)
{
if ($varname != '') {
Smarty::$global_tpl_vars[$varname] = new Smarty_variable($value, $nocache);
$ptr = $this;
while ($ptr instanceof Smarty_Internal_Template) {
$ptr->tpl_vars[$varname] = clone Smarty::$global_tpl_vars[$varname];
$ptr = $ptr->parent;
}
}
return $this;
}
/**
* assigns values to template variables by reference
*
* @param string $tpl_var the template variable name
* @param $value
* @param boolean $nocache if true any output of this variable will be not cached
*
* @return Smarty_Internal_Data current Smarty_Internal_Data (or Smarty or Smarty_Internal_Template) instance for chaining
*/
public function assignByRef($tpl_var, &$value, $nocache = false)
{
if ($tpl_var != '') {
$this->tpl_vars[$tpl_var] = new Smarty_variable(null, $nocache);
$this->tpl_vars[$tpl_var]->value = & $value;
}
return $this;
}
/**
* appends values to template variables
*
* @param array|string $tpl_var the template variable name(s)
* @param mixed $value the value to append
* @param boolean $merge flag if array elements shall be merged
* @param boolean $nocache if true any output of this variable will be not cached
*
* @return Smarty_Internal_Data current Smarty_Internal_Data (or Smarty or Smarty_Internal_Template) instance for chaining
*/
public function append($tpl_var, $value = null, $merge = false, $nocache = false)
{
if (is_array($tpl_var)) {
// $tpl_var is an array, ignore $value
foreach ($tpl_var as $_key => $_val) {
if ($_key != '') {
if (!isset($this->tpl_vars[$_key])) {
$tpl_var_inst = $this->getVariable($_key, null, true, false);
if ($tpl_var_inst instanceof Undefined_Smarty_Variable) {
$this->tpl_vars[$_key] = new Smarty_variable(null, $nocache);
} else {
$this->tpl_vars[$_key] = clone $tpl_var_inst;
}
}
if (!(is_array($this->tpl_vars[$_key]->value) || $this->tpl_vars[$_key]->value instanceof ArrayAccess)) {
settype($this->tpl_vars[$_key]->value, 'array');
}
if ($merge && is_array($_val)) {
foreach ($_val as $_mkey => $_mval) {
$this->tpl_vars[$_key]->value[$_mkey] = $_mval;
}
} else {
$this->tpl_vars[$_key]->value[] = $_val;
}
}
}
} else {
if ($tpl_var != '' && isset($value)) {
if (!isset($this->tpl_vars[$tpl_var])) {
$tpl_var_inst = $this->getVariable($tpl_var, null, true, false);
if ($tpl_var_inst instanceof Undefined_Smarty_Variable) {
$this->tpl_vars[$tpl_var] = new Smarty_variable(null, $nocache);
} else {
$this->tpl_vars[$tpl_var] = clone $tpl_var_inst;
}
}
if (!(is_array($this->tpl_vars[$tpl_var]->value) || $this->tpl_vars[$tpl_var]->value instanceof ArrayAccess)) {
settype($this->tpl_vars[$tpl_var]->value, 'array');
}
if ($merge && is_array($value)) {
foreach ($value as $_mkey => $_mval) {
$this->tpl_vars[$tpl_var]->value[$_mkey] = $_mval;
}
} else {
$this->tpl_vars[$tpl_var]->value[] = $value;
}
}
}
return $this;
}
/**
* appends values to template variables by reference
*
* @param string $tpl_var the template variable name
* @param mixed &$value the referenced value to append
* @param boolean $merge flag if array elements shall be merged
*
* @return Smarty_Internal_Data current Smarty_Internal_Data (or Smarty or Smarty_Internal_Template) instance for chaining
*/
public function appendByRef($tpl_var, &$value, $merge = false)
{
if ($tpl_var != '' && isset($value)) {
if (!isset($this->tpl_vars[$tpl_var])) {
$this->tpl_vars[$tpl_var] = new Smarty_variable();
}
if (!is_array($this->tpl_vars[$tpl_var]->value)) {
settype($this->tpl_vars[$tpl_var]->value, 'array');
}
if ($merge && is_array($value)) {
foreach ($value as $_key => $_val) {
$this->tpl_vars[$tpl_var]->value[$_key] = & $value[$_key];
}
} else {
$this->tpl_vars[$tpl_var]->value[] = & $value;
}
}
return $this;
}
/**
* Returns a single or all template variables
*
* @param string $varname variable name or null
* @param object $_ptr optional pointer to data object
* @param boolean $search_parents include parent templates?
*
* @return string variable value or or array of variables
*/
public function getTemplateVars($varname = null, $_ptr = null, $search_parents = true)
{
if (isset($varname)) {
$_var = $this->getVariable($varname, $_ptr, $search_parents, false);
if (is_object($_var)) {
return $_var->value;
} else {
return null;
}
} else {
$_result = array();
if ($_ptr === null) {
$_ptr = $this;
}
while ($_ptr !== null) {
foreach ($_ptr->tpl_vars AS $key => $var) {
if (!array_key_exists($key, $_result)) {
$_result[$key] = $var->value;
}
}
// not found, try at parent
if ($search_parents) {
$_ptr = $_ptr->parent;
} else {
$_ptr = null;
}
}
if ($search_parents && isset(Smarty::$global_tpl_vars)) {
foreach (Smarty::$global_tpl_vars AS $key => $var) {
if (!array_key_exists($key, $_result)) {
$_result[$key] = $var->value;
}
}
}
return $_result;
}
}
/**
* clear the given assigned template variable.
*
* @param string|array $tpl_var the template variable(s) to clear
*
* @return Smarty_Internal_Data current Smarty_Internal_Data (or Smarty or Smarty_Internal_Template) instance for chaining
*/
public function clearAssign($tpl_var)
{
if (is_array($tpl_var)) {
foreach ($tpl_var as $curr_var) {
unset($this->tpl_vars[$curr_var]);
}
} else {
unset($this->tpl_vars[$tpl_var]);
}
return $this;
}
/**
* clear all the assigned template variables.
*
* @return Smarty_Internal_Data current Smarty_Internal_Data (or Smarty or Smarty_Internal_Template) instance for chaining
*/
public function clearAllAssign()
{
$this->tpl_vars = array();
return $this;
}
/**
* load a config file, optionally load just selected sections
*
* @param string $config_file filename
* @param mixed $sections array of section names, single section or null
*
* @return Smarty_Internal_Data current Smarty_Internal_Data (or Smarty or Smarty_Internal_Template) instance for chaining
*/
public function configLoad($config_file, $sections = null)
{
// load Config class
$config = new Smarty_Internal_Config($config_file, $this->smarty, $this);
$config->loadConfigVars($sections);
return $this;
}
/**
* gets the object of a Smarty variable
*
* @param string $variable the name of the Smarty variable
* @param object $_ptr optional pointer to data object
* @param boolean $search_parents search also in parent data
* @param bool $error_enable
*
* @return object the object of the variable
*/
public function getVariable($variable, $_ptr = null, $search_parents = true, $error_enable = true)
{
if ($_ptr === null) {
$_ptr = $this;
}
while ($_ptr !== null) {
if (isset($_ptr->tpl_vars[$variable])) {
// found it, return it
return $_ptr->tpl_vars[$variable];
}
// not found, try at parent
if ($search_parents) {
$_ptr = $_ptr->parent;
} else {
$_ptr = null;
}
}
if (isset(Smarty::$global_tpl_vars[$variable])) {
// found it, return it
return Smarty::$global_tpl_vars[$variable];
}
if ($this->smarty->error_unassigned && $error_enable) {
// force a notice
$x = $$variable;
}
return new Undefined_Smarty_Variable;
}
/**
* gets a config variable
*
* @param string $variable the name of the config variable
* @param bool $error_enable
*
* @return mixed the value of the config variable
*/
public function getConfigVariable($variable, $error_enable = true)
{
$_ptr = $this;
while ($_ptr !== null) {
if (isset($_ptr->config_vars[$variable])) {
// found it, return it
return $_ptr->config_vars[$variable];
}
// not found, try at parent
$_ptr = $_ptr->parent;
}
if ($this->smarty->error_unassigned && $error_enable) {
// force a notice
$x = $$variable;
}
return null;
}
/**
* gets a stream variable
*
* @param string $variable the stream of the variable
*
* @throws SmartyException
* @return mixed the value of the stream variable
*/
public function getStreamVariable($variable)
{
$_result = '';
$fp = fopen($variable, 'r+');
if ($fp) {
while (!feof($fp) && ($current_line = fgets($fp)) !== false) {
$_result .= $current_line;
}
fclose($fp);
return $_result;
}
if ($this->smarty->error_unassigned) {
throw new SmartyException('Undefined stream variable "' . $variable . '"');
} else {
return null;
}
}
/**
* Returns a single or all config variables
*
* @param string $varname variable name or null
* @param bool $search_parents
*
* @return string variable value or or array of variables
*/
public function getConfigVars($varname = null, $search_parents = true)
{
$_ptr = $this;
$var_array = array();
while ($_ptr !== null) {
if (isset($varname)) {
if (isset($_ptr->config_vars[$varname])) {
return $_ptr->config_vars[$varname];
}
} else {
$var_array = array_merge($_ptr->config_vars, $var_array);
}
// not found, try at parent
if ($search_parents) {
$_ptr = $_ptr->parent;
} else {
$_ptr = null;
}
}
if (isset($varname)) {
return '';
} else {
return $var_array;
}
}
/**
* Deassigns a single or all config variables
*
* @param string $varname variable name or null
*
* @return Smarty_Internal_Data current Smarty_Internal_Data (or Smarty or Smarty_Internal_Template) instance for chaining
*/
public function clearConfig($varname = null)
{
if (isset($varname)) {
unset($this->config_vars[$varname]);
} else {
$this->config_vars = array();
}
return $this;
}
}
/**
* class for the Smarty data object
* The Smarty data object will hold Smarty variables in the current scope
*
* @package Smarty
* @subpackage Template
*/
class Smarty_Data extends Smarty_Internal_Data
{
/**
* Smarty object
*
* @var Smarty
*/
public $smarty = null;
/**
* create Smarty data object
*
* @param Smarty|array $_parent parent template
* @param Smarty|Smarty_Internal_Template $smarty global smarty instance
*
* @throws SmartyException
*/
public function __construct($_parent = null, $smarty = null)
{
$this->smarty = $smarty;
if (is_object($_parent)) {
// when object set up back pointer
$this->parent = $_parent;
} elseif (is_array($_parent)) {
// set up variable values
foreach ($_parent as $_key => $_val) {
$this->tpl_vars[$_key] = new Smarty_variable($_val);
}
} elseif ($_parent != null) {
throw new SmartyException("Wrong type for template variables");
}
}
}
/**
* class for the Smarty variable object
* This class defines the Smarty variable object
*
* @package Smarty
* @subpackage Template
*/
class Smarty_Variable
{
/**
* template variable
*
* @var mixed
*/
public $value = null;
/**
* if true any output of this variable will be not cached
*
* @var boolean
*/
public $nocache = false;
/**
* the scope the variable will have (local,parent or root)
*
* @var int
*/
public $scope = Smarty::SCOPE_LOCAL;
/**
* create Smarty variable object
*
* @param mixed $value the value to assign
* @param boolean $nocache if true any output of this variable will be not cached
* @param int $scope the scope the variable will have (local,parent or root)
*/
public function __construct($value = null, $nocache = false, $scope = Smarty::SCOPE_LOCAL)
{
$this->value = $value;
$this->nocache = $nocache;
$this->scope = $scope;
}
/**
* <<magic>> String conversion
*
* @return string
*/
public function __toString()
{
return (string) $this->value;
}
}
/**
* class for undefined variable object
* This class defines an object for undefined variable handling
*
* @package Smarty
* @subpackage Template
*/
class Undefined_Smarty_Variable
{
/**
* Returns FALSE for 'nocache' and NULL otherwise.
*
* @param string $name
*
* @return bool
*/
public function __get($name)
{
if ($name == 'nocache') {
return false;
} else {
return null;
}
}
/**
* Always returns an empty string.
*
* @return string
*/
public function __toString()
{
return "";
}
}

View File

@@ -1,254 +0,0 @@
<?php
/**
* Smarty Internal Plugin Debug
* Class to collect data for the Smarty Debugging Consol
*
* @package Smarty
* @subpackage Debug
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Debug Class
*
* @package Smarty
* @subpackage Debug
*/
class Smarty_Internal_Debug extends Smarty_Internal_Data
{
/**
* template data
*
* @var array
*/
public static $template_data = array();
/**
* List of uid's which shall be ignored
*
* @var array
*/
public static $ignore_uid = array();
/**
* Ignore template
*
* @param object $template
*/
public static function ignore($template)
{
// calculate Uid if not already done
if ($template->source->uid == '') {
$template->source->filepath;
}
self::$ignore_uid[$template->source->uid] = true;
}
/**
* Start logging of compile time
*
* @param object $template
*/
public static function start_compile($template)
{
static $_is_stringy = array('string' => true, 'eval' => true);
if (!empty($template->compiler->trace_uid)) {
$key = $template->compiler->trace_uid;
if (!isset(self::$template_data[$key])) {
if (isset($_is_stringy[$template->source->type])) {
self::$template_data[$key]['name'] = '\'' . substr($template->source->name, 0, 25) . '...\'';
} else {
self::$template_data[$key]['name'] = $template->source->filepath;
}
self::$template_data[$key]['compile_time'] = 0;
self::$template_data[$key]['render_time'] = 0;
self::$template_data[$key]['cache_time'] = 0;
}
} else {
if (isset(self::$ignore_uid[$template->source->uid])) {
return;
}
$key = self::get_key($template);
}
self::$template_data[$key]['start_time'] = microtime(true);
}
/**
* End logging of compile time
*
* @param object $template
*/
public static function end_compile($template)
{
if (!empty($template->compiler->trace_uid)) {
$key = $template->compiler->trace_uid;
} else {
if (isset(self::$ignore_uid[$template->source->uid])) {
return;
}
$key = self::get_key($template);
}
self::$template_data[$key]['compile_time'] += microtime(true) - self::$template_data[$key]['start_time'];
}
/**
* Start logging of render time
*
* @param object $template
*/
public static function start_render($template)
{
$key = self::get_key($template);
self::$template_data[$key]['start_time'] = microtime(true);
}
/**
* End logging of compile time
*
* @param object $template
*/
public static function end_render($template)
{
$key = self::get_key($template);
self::$template_data[$key]['render_time'] += microtime(true) - self::$template_data[$key]['start_time'];
}
/**
* Start logging of cache time
*
* @param object $template cached template
*/
public static function start_cache($template)
{
$key = self::get_key($template);
self::$template_data[$key]['start_time'] = microtime(true);
}
/**
* End logging of cache time
*
* @param object $template cached template
*/
public static function end_cache($template)
{
$key = self::get_key($template);
self::$template_data[$key]['cache_time'] += microtime(true) - self::$template_data[$key]['start_time'];
}
/**
* Opens a window for the Smarty Debugging Consol and display the data
*
* @param Smarty_Internal_Template|Smarty $obj object to debug
*/
public static function display_debug($obj)
{
// prepare information of assigned variables
$ptr = self::get_debug_vars($obj);
if ($obj instanceof Smarty) {
$smarty = clone $obj;
} else {
$smarty = clone $obj->smarty;
}
$_assigned_vars = $ptr->tpl_vars;
ksort($_assigned_vars);
$_config_vars = $ptr->config_vars;
ksort($_config_vars);
$smarty->registered_filters = array();
$smarty->autoload_filters = array();
$smarty->default_modifiers = array();
$smarty->force_compile = false;
$smarty->left_delimiter = '{';
$smarty->right_delimiter = '}';
$smarty->debugging = false;
$smarty->debugging_ctrl = 'NONE';
$smarty->force_compile = false;
$_template = new Smarty_Internal_Template($smarty->debug_tpl, $smarty);
$_template->caching = false;
$_template->disableSecurity();
$_template->cache_id = null;
$_template->compile_id = null;
if ($obj instanceof Smarty_Internal_Template) {
$_template->assign('template_name', $obj->source->type . ':' . $obj->source->name);
}
if ($obj instanceof Smarty) {
$_template->assign('template_data', self::$template_data);
} else {
$_template->assign('template_data', null);
}
$_template->assign('assigned_vars', $_assigned_vars);
$_template->assign('config_vars', $_config_vars);
$_template->assign('execution_time', microtime(true) - $smarty->start_time);
echo $_template->fetch();
}
/**
* Recursively gets variables from all template/data scopes
*
* @param Smarty_Internal_Template|Smarty_Data $obj object to debug
*
* @return StdClass
*/
public static function get_debug_vars($obj)
{
$config_vars = $obj->config_vars;
$tpl_vars = array();
foreach ($obj->tpl_vars as $key => $var) {
$tpl_vars[$key] = clone $var;
if ($obj instanceof Smarty_Internal_Template) {
$tpl_vars[$key]->scope = $obj->source->type . ':' . $obj->source->name;
} elseif ($obj instanceof Smarty_Data) {
$tpl_vars[$key]->scope = 'Data object';
} else {
$tpl_vars[$key]->scope = 'Smarty root';
}
}
if (isset($obj->parent)) {
$parent = self::get_debug_vars($obj->parent);
$tpl_vars = array_merge($parent->tpl_vars, $tpl_vars);
$config_vars = array_merge($parent->config_vars, $config_vars);
} else {
foreach (Smarty::$global_tpl_vars as $name => $var) {
if (!array_key_exists($name, $tpl_vars)) {
$clone = clone $var;
$clone->scope = 'Global';
$tpl_vars[$name] = $clone;
}
}
}
return (object) array('tpl_vars' => $tpl_vars, 'config_vars' => $config_vars);
}
/**
* Return key into $template_data for template
*
* @param object $template template object
*
* @return string key into $template_data
*/
private static function get_key($template)
{
static $_is_stringy = array('string' => true, 'eval' => true);
// calculate Uid if not already done
if ($template->source->uid == '') {
$template->source->filepath;
}
$key = $template->source->uid;
if (isset(self::$template_data[$key])) {
return $key;
} else {
if (isset($_is_stringy[$template->source->type])) {
self::$template_data[$key]['name'] = '\'' . substr($template->source->name, 0, 25) . '...\'';
} else {
self::$template_data[$key]['name'] = $template->source->filepath;
}
self::$template_data[$key]['compile_time'] = 0;
self::$template_data[$key]['render_time'] = 0;
self::$template_data[$key]['cache_time'] = 0;
return $key;
}
}
}

View File

@@ -1,67 +0,0 @@
<?php
/**
* Smarty Internal Plugin Filter Handler
* Smarty filter handler class
*
* @package Smarty
* @subpackage PluginsInternal
* @author Uwe Tews
*/
/**
* Class for filter processing
*
* @package Smarty
* @subpackage PluginsInternal
*/
class Smarty_Internal_Filter_Handler
{
/**
* Run filters over content
* The filters will be lazy loaded if required
* class name format: Smarty_FilterType_FilterName
* plugin filename format: filtertype.filtername.php
* Smarty2 filter plugins could be used
*
* @param string $type the type of filter ('pre','post','output') which shall run
* @param string $content the content which shall be processed by the filters
* @param Smarty_Internal_Template $template template object
*
* @throws SmartyException
* @return string the filtered content
*/
public static function runFilter($type, $content, Smarty_Internal_Template $template)
{
$output = $content;
// loop over autoload filters of specified type
if (!empty($template->smarty->autoload_filters[$type])) {
foreach ((array) $template->smarty->autoload_filters[$type] as $name) {
$plugin_name = "Smarty_{$type}filter_{$name}";
if ($template->smarty->loadPlugin($plugin_name)) {
if (function_exists($plugin_name)) {
// use loaded Smarty2 style plugin
$output = $plugin_name($output, $template);
} elseif (class_exists($plugin_name, false)) {
// loaded class of filter plugin
$output = call_user_func(array($plugin_name, 'execute'), $output, $template);
}
} else {
// nothing found, throw exception
throw new SmartyException("Unable to load filter {$plugin_name}");
}
}
}
// loop over registerd filters of specified type
if (!empty($template->smarty->registered_filters[$type])) {
foreach ($template->smarty->registered_filters[$type] as $key => $name) {
if (is_array($template->smarty->registered_filters[$type][$key])) {
$output = call_user_func($template->smarty->registered_filters[$type][$key], $output, $template);
} else {
$output = $template->smarty->registered_filters[$type][$key]($output, $template);
}
}
}
// return filtered output
return $output;
}
}

View File

@@ -1,52 +0,0 @@
<?php
/**
* Smarty Internal Plugin Function Call Handler
*
* @package Smarty
* @subpackage PluginsInternal
* @author Uwe Tews
*/
/**
* This class does call function defined with the {function} tag
*
* @package Smarty
* @subpackage PluginsInternal
*/
class Smarty_Internal_Function_Call_Handler
{
/**
* This function handles calls to template functions defined by {function}
* It does create a PHP function at the first call
*
* @param string $_name template function name
* @param Smarty_Internal_Template $_template template object
* @param array $_params Smarty variables passed as call parameter
* @param string $_hash nocache hash value
* @param bool $_nocache nocache flag
*/
public static function call($_name, Smarty_Internal_Template $_template, $_params, $_hash, $_nocache)
{
if ($_nocache) {
$_function = "smarty_template_function_{$_name}_nocache";
} else {
$_function = "smarty_template_function_{$_hash}_{$_name}";
}
if (!is_callable($_function)) {
$_code = "function {$_function}(\$_smarty_tpl,\$params) {
\$saved_tpl_vars = \$_smarty_tpl->tpl_vars;
foreach (\$_smarty_tpl->smarty->template_functions['{$_name}']['parameter'] as \$key => \$value) {\$_smarty_tpl->tpl_vars[\$key] = new Smarty_variable(\$value);};
foreach (\$params as \$key => \$value) {\$_smarty_tpl->tpl_vars[\$key] = new Smarty_variable(\$value);}?>";
if ($_nocache) {
$_code .= preg_replace(array("!<\?php echo \\'/\*%%SmartyNocache:{$_template->smarty->template_functions[$_name]['nocache_hash']}%%\*/|/\*/%%SmartyNocache:{$_template->smarty->template_functions[$_name]['nocache_hash']}%%\*/\\';\?>!",
"!\\\'!"), array('', "'"), $_template->smarty->template_functions[$_name]['compiled']);
$_template->smarty->template_functions[$_name]['called_nocache'] = true;
} else {
$_code .= preg_replace("/{$_template->smarty->template_functions[$_name]['nocache_hash']}/", $_template->properties['nocache_hash'], $_template->smarty->template_functions[$_name]['compiled']);
}
$_code .= "<?php \$_smarty_tpl->tpl_vars = \$saved_tpl_vars;}";
eval($_code);
}
$_function($_template, $_params);
}
}

View File

@@ -1,46 +0,0 @@
<?php
/**
* Smarty read include path plugin
*
* @package Smarty
* @subpackage PluginsInternal
* @author Monte Ohrt
*/
/**
* Smarty Internal Read Include Path Class
*
* @package Smarty
* @subpackage PluginsInternal
*/
class Smarty_Internal_Get_Include_Path
{
/**
* Return full file path from PHP include_path
*
* @param string $filepath filepath
*
* @return string|boolean full filepath or false
*/
public static function getIncludePath($filepath)
{
static $_include_path = null;
if (function_exists('stream_resolve_include_path')) {
// available since PHP 5.3.2
return stream_resolve_include_path($filepath);
}
if ($_include_path === null) {
$_include_path = explode(PATH_SEPARATOR, get_include_path());
}
foreach ($_include_path as $_path) {
if (file_exists($_path . DS . $filepath)) {
return $_path . DS . $filepath;
}
}
return false;
}
}

View File

@@ -1,361 +0,0 @@
<?php
/**
* Smarty Internal Plugin Templateparser Parsetrees
* These are classes to build parsetrees in the template parser
*
* @package Smarty
* @subpackage Compiler
* @author Thue Kristensen
* @author Uwe Tews
*/
/**
* @package Smarty
* @subpackage Compiler
* @ignore
*/
abstract class _smarty_parsetree
{
/**
* Parser object
*
* @var object
*/
public $parser;
/**
* Buffer content
*
* @var mixed
*/
public $data;
/**
* Subtree array
*
* @var array
*/
public $subtrees = array();
/**
* Return buffer
*
* @return string buffer content
*/
abstract public function to_smarty_php();
}
/**
* A complete smarty tag.
*
* @package Smarty
* @subpackage Compiler
* @ignore
*/
class _smarty_tag extends _smarty_parsetree
{
/**
* Saved block nesting level
*
* @var int
*/
public $saved_block_nesting;
/**
* Create parse tree buffer for Smarty tag
*
* @param object $parser parser object
* @param string $data content
*/
public function __construct($parser, $data)
{
$this->parser = $parser;
$this->data = $data;
$this->saved_block_nesting = $parser->block_nesting_level;
}
/**
* Return buffer content
*
* @return string content
*/
public function to_smarty_php()
{
return $this->data;
}
/**
* Return complied code that loads the evaluated output of buffer content into a temporary variable
*
* @return string template code
*/
public function assign_to_var()
{
$var = sprintf('$_tmp%d', ++Smarty_Internal_Templateparser::$prefix_number);
$this->parser->compiler->prefix_code[] = sprintf("<?php ob_start();\n%s\n%s=ob_get_clean();?>", preg_replace(array('/^\s*<\?php\s+/','/\s*\?>\s*$/'), '', $this->data), $var);
return $var;
}
}
/**
* Code fragment inside a tag.
*
* @package Smarty
* @subpackage Compiler
* @ignore
*/
class _smarty_code extends _smarty_parsetree
{
/**
* Create parse tree buffer for code fragment
*
* @param object $parser parser object
* @param string $data content
*/
public function __construct($parser, $data)
{
$this->parser = $parser;
$this->data = $data;
}
/**
* Return buffer content in parentheses
*
* @return string content
*/
public function to_smarty_php()
{
return sprintf("(%s)", $this->data);
}
}
/**
* Double quoted string inside a tag.
*
* @package Smarty
* @subpackage Compiler
* @ignore
*/
class _smarty_doublequoted extends _smarty_parsetree
{
/**
* Create parse tree buffer for double quoted string subtrees
*
* @param object $parser parser object
* @param _smarty_parsetree $subtree parsetree buffer
*/
public function __construct($parser, _smarty_parsetree $subtree)
{
$this->parser = $parser;
$this->subtrees[] = $subtree;
if ($subtree instanceof _smarty_tag) {
$this->parser->block_nesting_level = count($this->parser->compiler->_tag_stack);
}
}
/**
* Append buffer to subtree
*
* @param _smarty_parsetree $subtree parsetree buffer
*/
public function append_subtree(_smarty_parsetree $subtree)
{
$last_subtree = count($this->subtrees) - 1;
if ($last_subtree >= 0 && $this->subtrees[$last_subtree] instanceof _smarty_tag && $this->subtrees[$last_subtree]->saved_block_nesting < $this->parser->block_nesting_level) {
if ($subtree instanceof _smarty_code) {
$this->subtrees[$last_subtree]->data .= '<?php echo ' . $subtree->data . ';?>';
} elseif ($subtree instanceof _smarty_dq_content) {
$this->subtrees[$last_subtree]->data .= '<?php echo "' . $subtree->data . '";?>';
} else {
$this->subtrees[$last_subtree]->data .= $subtree->data;
}
} else {
$this->subtrees[] = $subtree;
}
if ($subtree instanceof _smarty_tag) {
$this->parser->block_nesting_level = count($this->parser->compiler->_tag_stack);
}
}
/**
* Merge subtree buffer content together
*
* @return string compiled template code
*/
public function to_smarty_php()
{
$code = '';
foreach ($this->subtrees as $subtree) {
if ($code !== "") {
$code .= ".";
}
if ($subtree instanceof _smarty_tag) {
$more_php = $subtree->assign_to_var();
} else {
$more_php = $subtree->to_smarty_php();
}
$code .= $more_php;
if (!$subtree instanceof _smarty_dq_content) {
$this->parser->compiler->has_variable_string = true;
}
}
return $code;
}
}
/**
* Raw chars as part of a double quoted string.
*
* @package Smarty
* @subpackage Compiler
* @ignore
*/
class _smarty_dq_content extends _smarty_parsetree
{
/**
* Create parse tree buffer with string content
*
* @param object $parser parser object
* @param string $data string section
*/
public function __construct($parser, $data)
{
$this->parser = $parser;
$this->data = $data;
}
/**
* Return content as double quoted string
*
* @return string doubled quoted string
*/
public function to_smarty_php()
{
return '"' . $this->data . '"';
}
}
/**
* Template element
*
* @package Smarty
* @subpackage Compiler
* @ignore
*/
class _smarty_template_buffer extends _smarty_parsetree
{
/**
* Array of template elements
*
* @var array
*/
public $subtrees = Array();
/**
* Create root of parse tree for template elements
*
* @param object $parser parse object
*/
public function __construct($parser)
{
$this->parser = $parser;
}
/**
* Append buffer to subtree
*
* @param _smarty_parsetree $subtree
*/
public function append_subtree(_smarty_parsetree $subtree)
{
if ($subtree->data !== '') {
$this->subtrees[] = $subtree;
}
}
/**
* Sanitize and merge subtree buffers together
*
* @return string template code content
*/
public function to_smarty_php()
{
$code = '';
for ($key = 0, $cnt = count($this->subtrees); $key < $cnt; $key ++) {
if ($this->subtrees[$key] instanceof _smarty_text) {
$subtree = $this->subtrees[$key]->to_smarty_php();
while ($key + 1 < $cnt && ($this->subtrees[$key+1] instanceof _smarty_text || $this->subtrees[$key +1]->data == '')) {
$key++;
if ($this->subtrees[$key]->data == '') {
continue;
}
$subtree .= $this->subtrees[$key]->to_smarty_php();
}
if ($subtree == '') {
continue;
}
$code .= preg_replace('/(<%|%>|<\?php|<\?|\?>|<\/?script)/', "<?php echo '\$1'; ?>\n", $subtree);
continue;
}
if ($this->subtrees[$key] instanceof _smarty_tag) {
$subtree = $this->subtrees[$key]->to_smarty_php();
while ($key + 1 < $cnt && ($this->subtrees[$key+1] instanceof _smarty_tag || $this->subtrees[$key +1]->data == '')) {
$key++;
if ($this->subtrees[$key]->data == '') {
continue;
}
$newCode = $this->subtrees[$key]->to_smarty_php();
if ((preg_match('/^\s*<\?php\s+/', $newCode) && preg_match('/\s*\?>\s*$/', $subtree))) {
$subtree = preg_replace('/\s*\?>\s*$/', "\n", $subtree);
$subtree .= preg_replace('/^\s*<\?php\s+/', '', $newCode);
} else {
$subtree .= $newCode;
}
}
if ($subtree == '') {
continue;
}
$code .= $subtree;
continue;
}
$code .= $this->subtrees[$key]->to_smarty_php();
}
return $code;
}
}
/**
* template text
*
* @package Smarty
* @subpackage Compiler
* @ignore
*/
class _smarty_text extends _smarty_parsetree
{
/**
* Create template text buffer
*
* @param object $parser parser object
* @param string $data text
*/
public function __construct($parser, $data)
{
$this->parser = $parser;
$this->data = $data;
}
/**
* Return buffer content
*
* @return strint text
*/
public function to_smarty_php()
{
return $this->data;
}
}

View File

@@ -1,89 +0,0 @@
<?php
/**
* Smarty Internal Plugin Resource File
*
* @package Smarty
* @subpackage TemplateResources
* @author Uwe Tews
* @author Rodney Rehm
*/
/**
* Smarty Internal Plugin Resource File
* Implements the file system as resource for Smarty templates
*
* @package Smarty
* @subpackage TemplateResources
*/
class Smarty_Internal_Resource_File extends Smarty_Resource
{
/**
* populate Source Object with meta data from Resource
*
* @param Smarty_Template_Source $source source object
* @param Smarty_Internal_Template $_template template object
*/
public function populate(Smarty_Template_Source $source, Smarty_Internal_Template $_template = null)
{
$source->filepath = $this->buildFilepath($source, $_template);
if ($source->filepath !== false) {
if (is_object($source->smarty->security_policy)) {
$source->smarty->security_policy->isTrustedResourceDir($source->filepath);
}
$source->uid = sha1(realpath($source->filepath));
if ($source->smarty->compile_check && !isset($source->timestamp)) {
$source->timestamp = @filemtime($source->filepath);
$source->exists = !!$source->timestamp;
}
}
}
/**
* populate Source Object with timestamp and exists from Resource
*
* @param Smarty_Template_Source $source source object
*/
public function populateTimestamp(Smarty_Template_Source $source)
{
$source->timestamp = @filemtime($source->filepath);
$source->exists = !!$source->timestamp;
}
/**
* Load template's source from file into current template object
*
* @param Smarty_Template_Source $source source object
*
* @return string template source
* @throws SmartyException if source cannot be loaded
*/
public function getContent(Smarty_Template_Source $source)
{
if ($source->timestamp) {
return file_get_contents($source->filepath);
}
if ($source instanceof Smarty_Config_Source) {
throw new SmartyException("Unable to read config {$source->type} '{$source->name}'");
}
throw new SmartyException("Unable to read template {$source->type} '{$source->name}'");
}
/**
* Determine basename for compiled filename
*
* @param Smarty_Template_Source $source source object
*
* @return string resource's basename
*/
public function getBasename(Smarty_Template_Source $source)
{
$_file = $source->name;
if (($_pos = strpos($_file, ']')) !== false) {
$_file = substr($_file, $_pos + 1);
}
return basename($_file);
}
}

View File

@@ -1,140 +0,0 @@
<?php
/**
* Smarty Internal Plugin Smarty Template Compiler Base
* This file contains the basic classes and methods for compiling Smarty templates with lexer/parser
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* @ignore
*/
include 'smarty_internal_parsetree.php';
/**
* Class SmartyTemplateCompiler
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_SmartyTemplateCompiler extends Smarty_Internal_TemplateCompilerBase
{
/**
* Lexer class name
*
* @var string
*/
public $lexer_class;
/**
* Parser class name
*
* @var string
*/
public $parser_class;
/**
* Lexer object
*
* @var object
*/
public $lex;
/**
* Parser object
*
* @var object
*/
public $parser;
/**
* Smarty object
*
* @var object
*/
public $smarty;
/**
* array of vars which can be compiled in local scope
*
* @var array
*/
public $local_var = array();
/**
* Initialize compiler
*
* @param string $lexer_class class name
* @param string $parser_class class name
* @param Smarty $smarty global instance
*/
public function __construct($lexer_class, $parser_class, $smarty)
{
$this->smarty = $smarty;
parent::__construct();
// get required plugins
$this->lexer_class = $lexer_class;
$this->parser_class = $parser_class;
}
/**
* method to compile a Smarty template
*
* @param mixed $_content template source
*
* @return bool true if compiling succeeded, false if it failed
*/
protected function doCompile($_content)
{
/* here is where the compiling takes place. Smarty
tags in the templates are replaces with PHP code,
then written to compiled files. */
// init the lexer/parser to compile the template
$this->lex = new $this->lexer_class($_content, $this);
$this->parser = new $this->parser_class($this->lex, $this);
if ($this->inheritance_child) {
// start state on child templates
$this->lex->yypushstate(Smarty_Internal_Templatelexer::CHILDBODY);
}
if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) {
$mbEncoding = mb_internal_encoding();
mb_internal_encoding('ASCII');
} else {
$mbEncoding = null;
}
if ($this->smarty->_parserdebug) {
$this->parser->PrintTrace();
$this->lex->PrintTrace();
}
// get tokens from lexer and parse them
while ($this->lex->yylex() && !$this->abort_and_recompile) {
if ($this->smarty->_parserdebug) {
echo "<pre>Line {$this->lex->line} Parsing {$this->parser->yyTokenName[$this->lex->token]} Token " .
htmlentities($this->lex->value) . "</pre>";
}
$this->parser->doParse($this->lex->token, $this->lex->value);
}
if ($this->abort_and_recompile) {
// exit here on abort
return false;
}
// finish parsing process
$this->parser->doParse(0, 0);
if ($mbEncoding) {
mb_internal_encoding($mbEncoding);
}
// check for unclosed tags
if (count($this->_tag_stack) > 0) {
// get stacked info
list($openTag, $_data) = array_pop($this->_tag_stack);
$this->trigger_template_error("unclosed {$this->smarty->left_delimiter}" . $openTag . "{$this->smarty->right_delimiter} tag");
}
// return compiled code
// return str_replace(array("? >\n<?php","? ><?php"), array('',''), $this->parser->retvalue);
return $this->parser->retvalue;
}
}

View File

@@ -1,738 +0,0 @@
<?php
/**
* Smarty Internal Plugin Template
* This file contains the Smarty template engine
*
* @package Smarty
* @subpackage Template
* @author Uwe Tews
*/
/**
* Main class with template data structures and methods
*
* @package Smarty
* @subpackage Template
* @property Smarty_Template_Source $source
* @property Smarty_Template_Compiled $compiled
* @property Smarty_Template_Cached $cached
*/
class Smarty_Internal_Template extends Smarty_Internal_TemplateBase
{
/**
* cache_id
*
* @var string
*/
public $cache_id = null;
/**
* $compile_id
* @var string
*/
public $compile_id = null;
/**
* caching enabled
*
* @var boolean
*/
public $caching = null;
/**
* cache lifetime in seconds
*
* @var integer
*/
public $cache_lifetime = null;
/**
* Template resource
*
* @var string
*/
public $template_resource = null;
/**
* flag if compiled template is invalid and must be (re)compiled
*
* @var bool
*/
public $mustCompile = null;
/**
* flag if template does contain nocache code sections
*
* @var bool
*/
public $has_nocache_code = false;
/**
* special compiled and cached template properties
*
* @var array
*/
public $properties = array('file_dependency' => array(),
'nocache_hash' => '',
'function' => array());
/**
* required plugins
*
* @var array
*/
public $required_plugins = array('compiled' => array(), 'nocache' => array());
/**
* Global smarty instance
*
* @var Smarty
*/
public $smarty = null;
/**
* blocks for template inheritance
*
* @var array
*/
public $block_data = array();
/**
* variable filters
*
* @var array
*/
public $variable_filters = array();
/**
* optional log of tag/attributes
*
* @var array
*/
public $used_tags = array();
/**
* internal flag to allow relative path in child template blocks
*
* @var bool
*/
public $allow_relative_path = false;
/**
* internal capture runtime stack
*
* @var array
*/
public $_capture_stack = array(0 => array());
/**
* Create template data object
* Some of the global Smarty settings copied to template scope
* It load the required template resources and cacher plugins
*
* @param string $template_resource template resource string
* @param Smarty $smarty Smarty instance
* @param Smarty_Internal_Template $_parent back pointer to parent object with variables or null
* @param mixed $_cache_id cache id or null
* @param mixed $_compile_id compile id or null
* @param bool $_caching use caching?
* @param int $_cache_lifetime cache life-time in seconds
*/
public function __construct($template_resource, $smarty, $_parent = null, $_cache_id = null, $_compile_id = null, $_caching = null, $_cache_lifetime = null)
{
$this->smarty = & $smarty;
// Smarty parameter
$this->cache_id = $_cache_id === null ? $this->smarty->cache_id : $_cache_id;
$this->compile_id = $_compile_id === null ? $this->smarty->compile_id : $_compile_id;
$this->caching = $_caching === null ? $this->smarty->caching : $_caching;
if ($this->caching === true) {
$this->caching = Smarty::CACHING_LIFETIME_CURRENT;
}
$this->cache_lifetime = $_cache_lifetime === null ? $this->smarty->cache_lifetime : $_cache_lifetime;
$this->parent = $_parent;
// Template resource
$this->template_resource = $template_resource;
// copy block data of template inheritance
if ($this->parent instanceof Smarty_Internal_Template) {
$this->block_data = $this->parent->block_data;
}
}
/**
* Returns if the current template must be compiled by the Smarty compiler
* It does compare the timestamps of template source and the compiled templates and checks the force compile configuration
*
* @throws SmartyException
* @return boolean true if the template must be compiled
*/
public function mustCompile()
{
if (!$this->source->exists) {
if ($this->parent instanceof Smarty_Internal_Template) {
$parent_resource = " in '$this->parent->template_resource}'";
} else {
$parent_resource = '';
}
throw new SmartyException("Unable to load template {$this->source->type} '{$this->source->name}'{$parent_resource}");
}
if ($this->mustCompile === null) {
$this->mustCompile = (!$this->source->uncompiled && ($this->smarty->force_compile || $this->source->recompiled || $this->compiled->timestamp === false ||
($this->smarty->compile_check && $this->compiled->timestamp < $this->source->timestamp)));
}
return $this->mustCompile;
}
/**
* Compiles the template
* If the template is not evaluated the compiled template is saved on disk
*/
public function compileTemplateSource()
{
if (!$this->source->recompiled) {
$this->properties['file_dependency'] = array();
if ($this->source->components) {
// for the extends resource the compiler will fill it
// uses real resource for file dependency
// $source = end($this->source->components);
// $this->properties['file_dependency'][$this->source->uid] = array($this->source->filepath, $this->source->timestamp, $source->type);
} else {
$this->properties['file_dependency'][$this->source->uid] = array($this->source->filepath, $this->source->timestamp, $this->source->type);
}
}
// compile locking
if ($this->smarty->compile_locking && !$this->source->recompiled) {
if ($saved_timestamp = $this->compiled->timestamp) {
touch($this->compiled->filepath);
}
}
// call compiler
try {
$code = $this->compiler->compileTemplate($this);
}
catch (Exception $e) {
// restore old timestamp in case of error
if ($this->smarty->compile_locking && !$this->source->recompiled && $saved_timestamp) {
touch($this->compiled->filepath, $saved_timestamp);
}
throw $e;
}
// compiling succeded
if (!$this->source->recompiled && $this->compiler->write_compiled_code) {
// write compiled template
$_filepath = $this->compiled->filepath;
if ($_filepath === false) {
throw new SmartyException('getCompiledFilepath() did not return a destination to save the compiled template to');
}
Smarty_Internal_Write_File::writeFile($_filepath, $code, $this->smarty);
$this->compiled->exists = true;
$this->compiled->isCompiled = true;
}
// release compiler object to free memory
unset($this->compiler);
}
/**
* Writes the cached template output
*
* @param string $content
*
* @return bool
*/
public function writeCachedContent($content)
{
if ($this->source->recompiled || !($this->caching == Smarty::CACHING_LIFETIME_CURRENT || $this->caching == Smarty::CACHING_LIFETIME_SAVED)) {
// don't write cache file
return false;
}
$this->cached->timestamp = time();
$this->properties['cache_lifetime'] = $this->cache_lifetime;
$this->properties['unifunc'] = 'content_' . str_replace(array('.', ','), '_', uniqid('', true));
$content = $this->createTemplateCodeFrame($content, true);
/** @var Smarty_Internal_Template $_smarty_tpl
* used in evaluated code
*/
$_smarty_tpl = $this;
eval("?>" . $content);
$this->cached->valid = true;
$this->cached->processed = true;
return $this->cached->write($this, $content);
}
/**
* Template code runtime function to get subtemplate content
*
* @param string $template the resource handle of the template file
* @param mixed $cache_id cache id to be used with this template
* @param mixed $compile_id compile id to be used with this template
* @param integer $caching cache mode
* @param integer $cache_lifetime life time of cache data
* @param $data
* @param int $parent_scope scope in which {include} should execute
*
* @returns string template content
*/
public function getSubTemplate($template, $cache_id, $compile_id, $caching, $cache_lifetime, $data, $parent_scope)
{
// already in template cache?
if ($this->smarty->allow_ambiguous_resources) {
$_templateId = Smarty_Resource::getUniqueTemplateName($this, $template) . $cache_id . $compile_id;
} else {
$_templateId = $this->smarty->joined_template_dir . '#' . $template . $cache_id . $compile_id;
}
if (isset($_templateId[150])) {
$_templateId = sha1($_templateId);
}
if (isset($this->smarty->template_objects[$_templateId])) {
// clone cached template object because of possible recursive call
$tpl = clone $this->smarty->template_objects[$_templateId];
$tpl->parent = $this;
$tpl->caching = $caching;
$tpl->cache_lifetime = $cache_lifetime;
} else {
$tpl = new $this->smarty->template_class($template, $this->smarty, $this, $cache_id, $compile_id, $caching, $cache_lifetime);
}
// get variables from calling scope
if ($parent_scope == Smarty::SCOPE_LOCAL) {
$tpl->tpl_vars = $this->tpl_vars;
$tpl->tpl_vars['smarty'] = clone $this->tpl_vars['smarty'];
} elseif ($parent_scope == Smarty::SCOPE_PARENT) {
$tpl->tpl_vars = & $this->tpl_vars;
} elseif ($parent_scope == Smarty::SCOPE_GLOBAL) {
$tpl->tpl_vars = & Smarty::$global_tpl_vars;
} elseif (($scope_ptr = $this->getScopePointer($parent_scope)) == null) {
$tpl->tpl_vars = & $this->tpl_vars;
} else {
$tpl->tpl_vars = & $scope_ptr->tpl_vars;
}
$tpl->config_vars = $this->config_vars;
if (!empty($data)) {
// set up variable values
foreach ($data as $_key => $_val) {
$tpl->tpl_vars[$_key] = new Smarty_variable($_val);
}
}
return $tpl->fetch(null, null, null, null, false, false, true);
}
/**
* Template code runtime function to set up an inline subtemplate
*
* @param string $template the resource handle of the template file
* @param mixed $cache_id cache id to be used with this template
* @param mixed $compile_id compile id to be used with this template
* @param integer $caching cache mode
* @param integer $cache_lifetime life time of cache data
* @param $data
* @param int $parent_scope scope in which {include} should execute
* @param string $hash nocache hash code
*
* @returns string template content
*/
public function setupInlineSubTemplate($template, $cache_id, $compile_id, $caching, $cache_lifetime, $data, $parent_scope, $hash)
{
$tpl = new $this->smarty->template_class($template, $this->smarty, $this, $cache_id, $compile_id, $caching, $cache_lifetime);
$tpl->properties['nocache_hash'] = $hash;
// get variables from calling scope
if ($parent_scope == Smarty::SCOPE_LOCAL) {
$tpl->tpl_vars = $this->tpl_vars;
$tpl->tpl_vars['smarty'] = clone $this->tpl_vars['smarty'];
} elseif ($parent_scope == Smarty::SCOPE_PARENT) {
$tpl->tpl_vars = & $this->tpl_vars;
} elseif ($parent_scope == Smarty::SCOPE_GLOBAL) {
$tpl->tpl_vars = & Smarty::$global_tpl_vars;
} elseif (($scope_ptr = $this->getScopePointer($parent_scope)) == null) {
$tpl->tpl_vars = & $this->tpl_vars;
} else {
$tpl->tpl_vars = & $scope_ptr->tpl_vars;
}
$tpl->config_vars = $this->config_vars;
if (!empty($data)) {
// set up variable values
foreach ($data as $_key => $_val) {
$tpl->tpl_vars[$_key] = new Smarty_variable($_val);
}
}
return $tpl;
}
/**
* Create code frame for compiled and cached templates
*
* @param string $content optional template content
* @param bool $cache flag for cache file
*
* @return string
*/
public function createTemplateCodeFrame($content = '', $cache = false)
{
$plugins_string = '';
// include code for plugins
if (!$cache) {
if (!empty($this->required_plugins['compiled'])) {
$plugins_string = '<?php ';
foreach ($this->required_plugins['compiled'] as $tmp) {
foreach ($tmp as $data) {
$file = addslashes($data['file']);
if (is_Array($data['function'])) {
$plugins_string .= "if (!is_callable(array('{$data['function'][0]}','{$data['function'][1]}'))) include '{$file}';\n";
} else {
$plugins_string .= "if (!is_callable('{$data['function']}')) include '{$file}';\n";
}
}
}
$plugins_string .= '?>';
}
if (!empty($this->required_plugins['nocache'])) {
$this->has_nocache_code = true;
$plugins_string .= "<?php echo '/*%%SmartyNocache:{$this->properties['nocache_hash']}%%*/<?php \$_smarty = \$_smarty_tpl->smarty; ";
foreach ($this->required_plugins['nocache'] as $tmp) {
foreach ($tmp as $data) {
$file = addslashes($data['file']);
if (is_Array($data['function'])) {
$plugins_string .= addslashes("if (!is_callable(array('{$data['function'][0]}','{$data['function'][1]}'))) include '{$file}';\n");
} else {
$plugins_string .= addslashes("if (!is_callable('{$data['function']}')) include '{$file}';\n");
}
}
}
$plugins_string .= "?>/*/%%SmartyNocache:{$this->properties['nocache_hash']}%%*/';?>\n";
}
}
// build property code
$this->properties['has_nocache_code'] = $this->has_nocache_code;
$output = '';
if (!$this->source->recompiled) {
$output = "<?php /*%%SmartyHeaderCode:{$this->properties['nocache_hash']}%%*/";
if ($this->smarty->direct_access_security) {
$output .= "if(!defined('SMARTY_DIR')) exit('no direct access allowed');\n";
}
}
if ($cache) {
// remove compiled code of{function} definition
unset($this->properties['function']);
if (!empty($this->smarty->template_functions)) {
// copy code of {function} tags called in nocache mode
foreach ($this->smarty->template_functions as $name => $function_data) {
if (isset($function_data['called_nocache'])) {
foreach ($function_data['called_functions'] as $func_name) {
$this->smarty->template_functions[$func_name]['called_nocache'] = true;
}
}
}
foreach ($this->smarty->template_functions as $name => $function_data) {
if (isset($function_data['called_nocache'])) {
unset($function_data['called_nocache'], $function_data['called_functions'], $this->smarty->template_functions[$name]['called_nocache']);
$this->properties['function'][$name] = $function_data;
}
}
}
}
$this->properties['version'] = Smarty::SMARTY_VERSION;
if (!isset($this->properties['unifunc'])) {
$this->properties['unifunc'] = 'content_' . str_replace(array('.', ','), '_', uniqid('', true));
}
if (!$this->source->recompiled) {
$output .= "\$_valid = \$_smarty_tpl->decodeProperties(" . var_export($this->properties, true) . ',' . ($cache ? 'true' : 'false') . "); /*/%%SmartyHeaderCode%%*/?>\n";
$output .= '<?php if ($_valid && !is_callable(\'' . $this->properties['unifunc'] . '\')) {function ' . $this->properties['unifunc'] . '($_smarty_tpl) {?>';
}
$output .= $plugins_string;
$output .= $content;
if (!$this->source->recompiled) {
$output .= "<?php }} ?>\n";
}
return $output;
}
/**
* This function is executed automatically when a compiled or cached template file is included
* - Decode saved properties from compiled template and cache files
* - Check if compiled or cache file is valid
*
* @param array $properties special template properties
* @param bool $cache flag if called from cache file
*
* @return bool flag if compiled or cache file is valid
*/
public function decodeProperties($properties, $cache = false)
{
$this->has_nocache_code = $properties['has_nocache_code'];
$this->properties['nocache_hash'] = $properties['nocache_hash'];
if (isset($properties['cache_lifetime'])) {
$this->properties['cache_lifetime'] = $properties['cache_lifetime'];
}
if (isset($properties['file_dependency'])) {
$this->properties['file_dependency'] = array_merge($this->properties['file_dependency'], $properties['file_dependency']);
}
if (!empty($properties['function'])) {
$this->properties['function'] = array_merge($this->properties['function'], $properties['function']);
$this->smarty->template_functions = array_merge($this->smarty->template_functions, $properties['function']);
}
$this->properties['version'] = (isset($properties['version'])) ? $properties['version'] : '';
$this->properties['unifunc'] = $properties['unifunc'];
// check file dependencies at compiled code
$is_valid = true;
if ($this->properties['version'] != Smarty::SMARTY_VERSION) {
$is_valid = false;
} elseif (((!$cache && $this->smarty->compile_check && empty($this->compiled->_properties) && !$this->compiled->isCompiled) || $cache && ($this->smarty->compile_check === true || $this->smarty->compile_check === Smarty::COMPILECHECK_ON)) && !empty($this->properties['file_dependency'])) {
foreach ($this->properties['file_dependency'] as $_file_to_check) {
if ($_file_to_check[2] == 'file' || $_file_to_check[2] == 'php') {
if ($this->source->filepath == $_file_to_check[0] && isset($this->source->timestamp)) {
// do not recheck current template
$mtime = $this->source->timestamp;
} else {
// file and php types can be checked without loading the respective resource handlers
$mtime = @filemtime($_file_to_check[0]);
}
} elseif ($_file_to_check[2] == 'string') {
continue;
} else {
$source = Smarty_Resource::source(null, $this->smarty, $_file_to_check[0]);
$mtime = $source->timestamp;
}
if (!$mtime || $mtime > $_file_to_check[1]) {
$is_valid = false;
break;
}
}
}
if ($cache) {
// CACHING_LIFETIME_SAVED cache expiry has to be validated here since otherwise we'd define the unifunc
if ($this->caching === Smarty::CACHING_LIFETIME_SAVED &&
$this->properties['cache_lifetime'] >= 0 &&
(time() > ($this->cached->timestamp + $this->properties['cache_lifetime']))
) {
$is_valid = false;
}
$this->cached->valid = $is_valid;
} else {
$this->mustCompile = !$is_valid;
}
// store data in reusable Smarty_Template_Compiled
if (!$cache) {
$this->compiled->_properties = $properties;
}
return $is_valid;
}
/**
* Template code runtime function to create a local Smarty variable for array assignments
*
* @param string $tpl_var tempate variable name
* @param bool $nocache cache mode of variable
* @param int $scope scope of variable
*/
public function createLocalArrayVariable($tpl_var, $nocache = false, $scope = Smarty::SCOPE_LOCAL)
{
if (!isset($this->tpl_vars[$tpl_var])) {
$this->tpl_vars[$tpl_var] = new Smarty_variable(array(), $nocache, $scope);
} else {
$this->tpl_vars[$tpl_var] = clone $this->tpl_vars[$tpl_var];
if ($scope != Smarty::SCOPE_LOCAL) {
$this->tpl_vars[$tpl_var]->scope = $scope;
}
if (!(is_array($this->tpl_vars[$tpl_var]->value) || $this->tpl_vars[$tpl_var]->value instanceof ArrayAccess)) {
settype($this->tpl_vars[$tpl_var]->value, 'array');
}
}
}
/**
* Template code runtime function to get pointer to template variable array of requested scope
*
* @param int $scope requested variable scope
*
* @return array array of template variables
*/
public function &getScope($scope)
{
if ($scope == Smarty::SCOPE_PARENT && !empty($this->parent)) {
return $this->parent->tpl_vars;
} elseif ($scope == Smarty::SCOPE_ROOT && !empty($this->parent)) {
$ptr = $this->parent;
while (!empty($ptr->parent)) {
$ptr = $ptr->parent;
}
return $ptr->tpl_vars;
} elseif ($scope == Smarty::SCOPE_GLOBAL) {
return Smarty::$global_tpl_vars;
}
$null = null;
return $null;
}
/**
* Get parent or root of template parent chain
*
* @param int $scope pqrent or root scope
*
* @return mixed object
*/
public function getScopePointer($scope)
{
if ($scope == Smarty::SCOPE_PARENT && !empty($this->parent)) {
return $this->parent;
} elseif ($scope == Smarty::SCOPE_ROOT && !empty($this->parent)) {
$ptr = $this->parent;
while (!empty($ptr->parent)) {
$ptr = $ptr->parent;
}
return $ptr;
}
return null;
}
/**
* [util function] counts an array, arrayaccess/traversable or PDOStatement object
*
* @param mixed $value
*
* @return int the count for arrays and objects that implement countable, 1 for other objects that don't, and 0 for empty elements
*/
public function _count($value)
{
if (is_array($value) === true || $value instanceof Countable) {
return count($value);
} elseif ($value instanceof IteratorAggregate) {
// Note: getIterator() returns a Traversable, not an Iterator
// thus rewind() and valid() methods may not be present
return iterator_count($value->getIterator());
} elseif ($value instanceof Iterator) {
return iterator_count($value);
} elseif ($value instanceof PDOStatement) {
return $value->rowCount();
} elseif ($value instanceof Traversable) {
return iterator_count($value);
} elseif ($value instanceof ArrayAccess) {
if ($value->offsetExists(0)) {
return 1;
}
} elseif (is_object($value)) {
return count($value);
}
return 0;
}
/**
* runtime error not matching capture tags
*/
public function capture_error()
{
throw new SmartyException("Not matching {capture} open/close in \"{$this->template_resource}\"");
}
/**
* Empty cache for this template
*
* @param integer $exp_time expiration time
*
* @return integer number of cache files deleted
*/
public function clearCache($exp_time = null)
{
Smarty_CacheResource::invalidLoadedCache($this->smarty);
return $this->cached->handler->clear($this->smarty, $this->template_name, $this->cache_id, $this->compile_id, $exp_time);
}
/**
* set Smarty property in template context
*
* @param string $property_name property name
* @param mixed $value value
*
* @throws SmartyException
*/
public function __set($property_name, $value)
{
switch ($property_name) {
case 'source':
case 'compiled':
case 'cached':
case 'compiler':
$this->$property_name = $value;
return;
// FIXME: routing of template -> smarty attributes
default:
if (property_exists($this->smarty, $property_name)) {
$this->smarty->$property_name = $value;
return;
}
}
throw new SmartyException("invalid template property '$property_name'.");
}
/**
* get Smarty property in template context
*
* @param string $property_name property name
*
* @throws SmartyException
*/
public function __get($property_name)
{
switch ($property_name) {
case 'source':
if (strlen($this->template_resource) == 0) {
throw new SmartyException('Missing template name');
}
$this->source = Smarty_Resource::source($this);
// cache template object under a unique ID
// do not cache eval resources
if ($this->source->type != 'eval') {
if ($this->smarty->allow_ambiguous_resources) {
$_templateId = $this->source->unique_resource . $this->cache_id . $this->compile_id;
} else {
$_templateId = $this->smarty->joined_template_dir . '#' . $this->template_resource . $this->cache_id . $this->compile_id;
}
if (isset($_templateId[150])) {
$_templateId = sha1($_templateId);
}
$this->smarty->template_objects[$_templateId] = $this;
}
return $this->source;
case 'compiled':
$this->compiled = $this->source->getCompiled($this);
return $this->compiled;
case 'cached':
if (!class_exists('Smarty_Template_Cached')) {
include SMARTY_SYSPLUGINS_DIR . 'smarty_cacheresource.php';
}
$this->cached = new Smarty_Template_Cached($this);
return $this->cached;
case 'compiler':
$this->smarty->loadPlugin($this->source->compiler_class);
$this->compiler = new $this->source->compiler_class($this->source->template_lexer_class, $this->source->template_parser_class, $this->smarty);
return $this->compiler;
// FIXME: routing of template -> smarty attributes
default:
if (property_exists($this->smarty, $property_name)) {
return $this->smarty->$property_name;
}
}
throw new SmartyException("template property '$property_name' does not exist.");
}
/**
* Template data object destructor
*/
public function __destruct()
{
if ($this->smarty->cache_locking && isset($this->cached) && $this->cached->is_locked) {
$this->cached->handler->releaseLock($this->smarty, $this->cached);
}
}
}

View File

@@ -1,860 +0,0 @@
<?php
/**
* Smarty Internal Plugin Smarty Template Base
* This file contains the basic shared methods for template handling
*
* @package Smarty
* @subpackage Template
* @author Uwe Tews
*/
/**
* Class with shared template methods
*
* @package Smarty
* @subpackage Template
*/
abstract class Smarty_Internal_TemplateBase extends Smarty_Internal_Data
{
/**
* fetches a rendered Smarty template
*
* @param string $template the resource handle of the template file or template object
* @param mixed $cache_id cache id to be used with this template
* @param mixed $compile_id compile id to be used with this template
* @param object $parent next higher level of Smarty variables
* @param bool $display true: display, false: fetch
* @param bool $merge_tpl_vars if true parent template variables merged in to local scope
* @param bool $no_output_filter if true do not run output filter
*
* @throws Exception
* @throws SmartyException
* @return string rendered template output
*/
public function fetch($template = null, $cache_id = null, $compile_id = null, $parent = null, $display = false, $merge_tpl_vars = true, $no_output_filter = false)
{
if ($template === null && $this instanceof $this->template_class) {
$template = $this;
}
if ($cache_id !== null && is_object($cache_id)) {
$parent = $cache_id;
$cache_id = null;
}
if ($parent === null && ($this instanceof Smarty || is_string($template))) {
$parent = $this;
}
// create template object if necessary
$_template = ($template instanceof $this->template_class)
? $template
: $this->smarty->createTemplate($template, $cache_id, $compile_id, $parent, false);
// if called by Smarty object make sure we use current caching status
if ($this instanceof Smarty) {
$_template->caching = $this->caching;
}
// merge all variable scopes into template
if ($merge_tpl_vars) {
// save local variables
$save_tpl_vars = $_template->tpl_vars;
$save_config_vars = $_template->config_vars;
$ptr_array = array($_template);
$ptr = $_template;
while (isset($ptr->parent)) {
$ptr_array[] = $ptr = $ptr->parent;
}
$ptr_array = array_reverse($ptr_array);
$parent_ptr = reset($ptr_array);
$tpl_vars = $parent_ptr->tpl_vars;
$config_vars = $parent_ptr->config_vars;
while ($parent_ptr = next($ptr_array)) {
if (!empty($parent_ptr->tpl_vars)) {
$tpl_vars = array_merge($tpl_vars, $parent_ptr->tpl_vars);
}
if (!empty($parent_ptr->config_vars)) {
$config_vars = array_merge($config_vars, $parent_ptr->config_vars);
}
}
if (!empty(Smarty::$global_tpl_vars)) {
$tpl_vars = array_merge(Smarty::$global_tpl_vars, $tpl_vars);
}
$_template->tpl_vars = $tpl_vars;
$_template->config_vars = $config_vars;
}
// dummy local smarty variable
if (!isset($_template->tpl_vars['smarty'])) {
$_template->tpl_vars['smarty'] = new Smarty_Variable;
}
if (isset($this->smarty->error_reporting)) {
$_smarty_old_error_level = error_reporting($this->smarty->error_reporting);
}
// check URL debugging control
if (!$this->smarty->debugging && $this->smarty->debugging_ctrl == 'URL') {
if (isset($_SERVER['QUERY_STRING'])) {
$_query_string = $_SERVER['QUERY_STRING'];
} else {
$_query_string = '';
}
if (false !== strpos($_query_string, $this->smarty->smarty_debug_id)) {
if (false !== strpos($_query_string, $this->smarty->smarty_debug_id . '=on')) {
// enable debugging for this browser session
setcookie('SMARTY_DEBUG', true);
$this->smarty->debugging = true;
} elseif (false !== strpos($_query_string, $this->smarty->smarty_debug_id . '=off')) {
// disable debugging for this browser session
setcookie('SMARTY_DEBUG', false);
$this->smarty->debugging = false;
} else {
// enable debugging for this page
$this->smarty->debugging = true;
}
} else {
if (isset($_COOKIE['SMARTY_DEBUG'])) {
$this->smarty->debugging = true;
}
}
}
// must reset merge template date
$_template->smarty->merged_templates_func = array();
// get rendered template
// disable caching for evaluated code
if ($_template->source->recompiled) {
$_template->caching = false;
}
// checks if template exists
if (!$_template->source->exists) {
if ($_template->parent instanceof Smarty_Internal_Template) {
$parent_resource = " in '{$_template->parent->template_resource}'";
} else {
$parent_resource = '';
}
throw new SmartyException("Unable to load template {$_template->source->type} '{$_template->source->name}'{$parent_resource}");
}
// read from cache or render
if (!($_template->caching == Smarty::CACHING_LIFETIME_CURRENT || $_template->caching == Smarty::CACHING_LIFETIME_SAVED) || !$_template->cached->valid) {
// render template (not loaded and not in cache)
if (!$_template->source->uncompiled) {
/** @var Smarty_Internal_Template $_smarty_tpl
* used in evaluated code
*/
$_smarty_tpl = $_template;
if ($_template->source->recompiled) {
$code = $_template->compiler->compileTemplate($_template);
if ($this->smarty->debugging) {
Smarty_Internal_Debug::start_render($_template);
}
try {
ob_start();
eval("?>" . $code);
unset($code);
}
catch (Exception $e) {
ob_get_clean();
throw $e;
}
} else {
if (!$_template->compiled->exists || ($_template->smarty->force_compile && !$_template->compiled->isCompiled)) {
$_template->compileTemplateSource();
$code = file_get_contents($_template->compiled->filepath);
eval("?>" . $code);
unset($code);
$_template->compiled->loaded = true;
$_template->compiled->isCompiled = true;
}
if ($this->smarty->debugging) {
Smarty_Internal_Debug::start_render($_template);
}
if (!$_template->compiled->loaded) {
include($_template->compiled->filepath);
if ($_template->mustCompile) {
// recompile and load again
$_template->compileTemplateSource();
$code = file_get_contents($_template->compiled->filepath);
eval("?>" . $code);
unset($code);
$_template->compiled->isCompiled = true;
}
$_template->compiled->loaded = true;
} else {
$_template->decodeProperties($_template->compiled->_properties, false);
}
try {
ob_start();
if (empty($_template->properties['unifunc']) || !is_callable($_template->properties['unifunc'])) {
throw new SmartyException("Invalid compiled template for '{$_template->template_resource}'");
}
array_unshift($_template->_capture_stack, array());
//
// render compiled template
//
$_template->properties['unifunc']($_template);
// any unclosed {capture} tags ?
if (isset($_template->_capture_stack[0][0])) {
$_template->capture_error();
}
array_shift($_template->_capture_stack);
}
catch (Exception $e) {
ob_get_clean();
throw $e;
}
}
} else {
if ($_template->source->uncompiled) {
if ($this->smarty->debugging) {
Smarty_Internal_Debug::start_render($_template);
}
try {
ob_start();
$_template->source->renderUncompiled($_template);
}
catch (Exception $e) {
ob_get_clean();
throw $e;
}
} else {
throw new SmartyException("Resource '$_template->source->type' must have 'renderUncompiled' method");
}
}
$_output = ob_get_clean();
if (!$_template->source->recompiled && empty($_template->properties['file_dependency'][$_template->source->uid])) {
$_template->properties['file_dependency'][$_template->source->uid] = array($_template->source->filepath, $_template->source->timestamp, $_template->source->type);
}
if ($_template->parent instanceof Smarty_Internal_Template) {
$_template->parent->properties['file_dependency'] = array_merge($_template->parent->properties['file_dependency'], $_template->properties['file_dependency']);
foreach ($_template->required_plugins as $code => $tmp1) {
foreach ($tmp1 as $name => $tmp) {
foreach ($tmp as $type => $data) {
$_template->parent->required_plugins[$code][$name][$type] = $data;
}
}
}
}
if ($this->smarty->debugging) {
Smarty_Internal_Debug::end_render($_template);
}
// write to cache when nessecary
if (!$_template->source->recompiled && ($_template->caching == Smarty::CACHING_LIFETIME_SAVED || $_template->caching == Smarty::CACHING_LIFETIME_CURRENT)) {
if ($this->smarty->debugging) {
Smarty_Internal_Debug::start_cache($_template);
}
$_template->properties['has_nocache_code'] = false;
// get text between non-cached items
$cache_split = preg_split("!/\*%%SmartyNocache:{$_template->properties['nocache_hash']}%%\*\/(.+?)/\*/%%SmartyNocache:{$_template->properties['nocache_hash']}%%\*/!s", $_output);
// get non-cached items
preg_match_all("!/\*%%SmartyNocache:{$_template->properties['nocache_hash']}%%\*\/(.+?)/\*/%%SmartyNocache:{$_template->properties['nocache_hash']}%%\*/!s", $_output, $cache_parts);
$output = '';
// loop over items, stitch back together
foreach ($cache_split as $curr_idx => $curr_split) {
// escape PHP tags in template content
$output .= preg_replace('/(<%|%>|<\?php|<\?|\?>|<script\s+language\s*=\s*[\"\']?\s*php\s*[\"\']?\s*>)/', "<?php echo '\$1'; ?>\n", $curr_split);
if (isset($cache_parts[0][$curr_idx])) {
$_template->properties['has_nocache_code'] = true;
// remove nocache tags from cache output
$output .= preg_replace("!/\*/?%%SmartyNocache:{$_template->properties['nocache_hash']}%%\*/!", '', $cache_parts[0][$curr_idx]);
}
}
if (!$no_output_filter && !$_template->has_nocache_code && (isset($this->smarty->autoload_filters['output']) || isset($this->smarty->registered_filters['output']))) {
$output = Smarty_Internal_Filter_Handler::runFilter('output', $output, $_template);
}
// rendering (must be done before writing cache file because of {function} nocache handling)
/** @var Smarty_Internal_Template $_smarty_tpl
* used in evaluated code
*/
$_smarty_tpl = $_template;
try {
ob_start();
eval("?>" . $output);
$_output = ob_get_clean();
}
catch (Exception $e) {
ob_get_clean();
throw $e;
}
// write cache file content
$_template->writeCachedContent($output);
if ($this->smarty->debugging) {
Smarty_Internal_Debug::end_cache($_template);
}
} else {
// var_dump('renderTemplate', $_template->has_nocache_code, $_template->template_resource, $_template->properties['nocache_hash'], $_template->parent->properties['nocache_hash'], $_output);
if (!empty($_template->properties['nocache_hash']) && !empty($_template->parent->properties['nocache_hash'])) {
// replace nocache_hash
$_output = str_replace("{$_template->properties['nocache_hash']}", $_template->parent->properties['nocache_hash'], $_output);
$_template->parent->has_nocache_code = $_template->parent->has_nocache_code || $_template->has_nocache_code;
}
}
} else {
if ($this->smarty->debugging) {
Smarty_Internal_Debug::start_cache($_template);
}
try {
ob_start();
array_unshift($_template->_capture_stack, array());
//
// render cached template
//
$_template->properties['unifunc']($_template);
// any unclosed {capture} tags ?
if (isset($_template->_capture_stack[0][0])) {
$_template->capture_error();
}
array_shift($_template->_capture_stack);
$_output = ob_get_clean();
}
catch (Exception $e) {
ob_get_clean();
throw $e;
}
if ($this->smarty->debugging) {
Smarty_Internal_Debug::end_cache($_template);
}
}
if ((!$this->caching || $_template->has_nocache_code || $_template->source->recompiled) && !$no_output_filter && (isset($this->smarty->autoload_filters['output']) || isset($this->smarty->registered_filters['output']))) {
$_output = Smarty_Internal_Filter_Handler::runFilter('output', $_output, $_template);
}
if (isset($this->error_reporting)) {
error_reporting($_smarty_old_error_level);
}
// display or fetch
if ($display) {
if ($this->caching && $this->cache_modified_check) {
$_isCached = $_template->isCached() && !$_template->has_nocache_code;
$_last_modified_date = @substr($_SERVER['HTTP_IF_MODIFIED_SINCE'], 0, strpos($_SERVER['HTTP_IF_MODIFIED_SINCE'], 'GMT') + 3);
if ($_isCached && $_template->cached->timestamp <= strtotime($_last_modified_date)) {
switch (PHP_SAPI) {
case 'cgi': // php-cgi < 5.3
case 'cgi-fcgi': // php-cgi >= 5.3
case 'fpm-fcgi': // php-fpm >= 5.3.3
header('Status: 304 Not Modified');
break;
case 'cli':
if ( /* ^phpunit */
!empty($_SERVER['SMARTY_PHPUNIT_DISABLE_HEADERS']) /* phpunit$ */
) {
$_SERVER['SMARTY_PHPUNIT_HEADERS'][] = '304 Not Modified';
}
break;
default:
header($_SERVER['SERVER_PROTOCOL'] . ' 304 Not Modified');
break;
}
} else {
switch (PHP_SAPI) {
case 'cli':
if ( /* ^phpunit */
!empty($_SERVER['SMARTY_PHPUNIT_DISABLE_HEADERS']) /* phpunit$ */
) {
$_SERVER['SMARTY_PHPUNIT_HEADERS'][] = 'Last-Modified: ' . gmdate('D, d M Y H:i:s', $_template->cached->timestamp) . ' GMT';
}
break;
default:
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $_template->cached->timestamp) . ' GMT');
break;
}
echo $_output;
}
} else {
echo $_output;
}
// debug output
if ($this->smarty->debugging) {
Smarty_Internal_Debug::display_debug($_template);
}
if ($merge_tpl_vars) {
// restore local variables
$_template->tpl_vars = $save_tpl_vars;
$_template->config_vars = $save_config_vars;
}
return;
} else {
if ($merge_tpl_vars) {
// restore local variables
$_template->tpl_vars = $save_tpl_vars;
$_template->config_vars = $save_config_vars;
}
// return fetched content
return $_output;
}
}
/**
* displays a Smarty template
*
* @param string $template the resource handle of the template file or template object
* @param mixed $cache_id cache id to be used with this template
* @param mixed $compile_id compile id to be used with this template
* @param object $parent next higher level of Smarty variables
*/
public function display($template = null, $cache_id = null, $compile_id = null, $parent = null)
{
// display template
$this->fetch($template, $cache_id, $compile_id, $parent, true);
}
/**
* test if cache is valid
*
* @param string|object $template the resource handle of the template file or template object
* @param mixed $cache_id cache id to be used with this template
* @param mixed $compile_id compile id to be used with this template
* @param object $parent next higher level of Smarty variables
*
* @return boolean cache status
*/
public function isCached($template = null, $cache_id = null, $compile_id = null, $parent = null)
{
if ($template === null && $this instanceof $this->template_class) {
return $this->cached->valid;
}
if (!($template instanceof $this->template_class)) {
if ($parent === null) {
$parent = $this;
}
$template = $this->smarty->createTemplate($template, $cache_id, $compile_id, $parent, false);
}
// return cache status of template
return $template->cached->valid;
}
/**
* creates a data object
*
* @param object $parent next higher level of Smarty variables
*
* @returns Smarty_Data data object
*/
public function createData($parent = null)
{
return new Smarty_Data($parent, $this);
}
/**
* Registers plugin to be used in templates
*
* @param string $type plugin type
* @param string $tag name of template tag
* @param callback $callback PHP callback to register
* @param boolean $cacheable if true (default) this fuction is cachable
* @param array $cache_attr caching attributes if any
*
* @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining
* @throws SmartyException when the plugin tag is invalid
*/
public function registerPlugin($type, $tag, $callback, $cacheable = true, $cache_attr = null)
{
if (isset($this->smarty->registered_plugins[$type][$tag])) {
throw new SmartyException("Plugin tag \"{$tag}\" already registered");
} elseif (!is_callable($callback)) {
throw new SmartyException("Plugin \"{$tag}\" not callable");
} else {
$this->smarty->registered_plugins[$type][$tag] = array($callback, (bool) $cacheable, (array) $cache_attr);
}
return $this;
}
/**
* Unregister Plugin
*
* @param string $type of plugin
* @param string $tag name of plugin
*
* @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining
*/
public function unregisterPlugin($type, $tag)
{
if (isset($this->smarty->registered_plugins[$type][$tag])) {
unset($this->smarty->registered_plugins[$type][$tag]);
}
return $this;
}
/**
* Registers a resource to fetch a template
*
* @param string $type name of resource type
* @param Smarty_Resource|array $callback or instance of Smarty_Resource, or array of callbacks to handle resource (deprecated)
*
* @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining
*/
public function registerResource($type, $callback)
{
$this->smarty->registered_resources[$type] = $callback instanceof Smarty_Resource ? $callback : array($callback, false);
return $this;
}
/**
* Unregisters a resource
*
* @param string $type name of resource type
*
* @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining
*/
public function unregisterResource($type)
{
if (isset($this->smarty->registered_resources[$type])) {
unset($this->smarty->registered_resources[$type]);
}
return $this;
}
/**
* Registers a cache resource to cache a template's output
*
* @param string $type name of cache resource type
* @param Smarty_CacheResource $callback instance of Smarty_CacheResource to handle output caching
*
* @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining
*/
public function registerCacheResource($type, Smarty_CacheResource $callback)
{
$this->smarty->registered_cache_resources[$type] = $callback;
return $this;
}
/**
* Unregisters a cache resource
*
* @param string $type name of cache resource type
*
* @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining
*/
public function unregisterCacheResource($type)
{
if (isset($this->smarty->registered_cache_resources[$type])) {
unset($this->smarty->registered_cache_resources[$type]);
}
return $this;
}
/**
* Registers object to be used in templates
*
* @param $object_name
* @param object $object_impl the referenced PHP object to register
* @param array $allowed list of allowed methods (empty = all)
* @param boolean $smarty_args smarty argument format, else traditional
* @param array $block_methods list of block-methods
*
* @throws SmartyException
* @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining
*/
public function registerObject($object_name, $object_impl, $allowed = array(), $smarty_args = true, $block_methods = array())
{
// test if allowed methods callable
if (!empty($allowed)) {
foreach ((array) $allowed as $method) {
if (!is_callable(array($object_impl, $method)) && !property_exists($object_impl, $method)) {
throw new SmartyException("Undefined method or property '$method' in registered object");
}
}
}
// test if block methods callable
if (!empty($block_methods)) {
foreach ((array) $block_methods as $method) {
if (!is_callable(array($object_impl, $method))) {
throw new SmartyException("Undefined method '$method' in registered object");
}
}
}
// register the object
$this->smarty->registered_objects[$object_name] =
array($object_impl, (array) $allowed, (boolean) $smarty_args, (array) $block_methods);
return $this;
}
/**
* return a reference to a registered object
*
* @param string $name object name
*
* @return object
* @throws SmartyException if no such object is found
*/
public function getRegisteredObject($name)
{
if (!isset($this->smarty->registered_objects[$name])) {
throw new SmartyException("'$name' is not a registered object");
}
if (!is_object($this->smarty->registered_objects[$name][0])) {
throw new SmartyException("registered '$name' is not an object");
}
return $this->smarty->registered_objects[$name][0];
}
/**
* unregister an object
*
* @param string $name object name
*
* @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining
*/
public function unregisterObject($name)
{
if (isset($this->smarty->registered_objects[$name])) {
unset($this->smarty->registered_objects[$name]);
}
return $this;
}
/**
* Registers static classes to be used in templates
*
* @param $class_name
* @param string $class_impl the referenced PHP class to register
*
* @throws SmartyException
* @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining
*/
public function registerClass($class_name, $class_impl)
{
// test if exists
if (!class_exists($class_impl)) {
throw new SmartyException("Undefined class '$class_impl' in register template class");
}
// register the class
$this->smarty->registered_classes[$class_name] = $class_impl;
return $this;
}
/**
* Registers a default plugin handler
*
* @param callable $callback class/method name
*
* @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining
* @throws SmartyException if $callback is not callable
*/
public function registerDefaultPluginHandler($callback)
{
if (is_callable($callback)) {
$this->smarty->default_plugin_handler_func = $callback;
} else {
throw new SmartyException("Default plugin handler '$callback' not callable");
}
return $this;
}
/**
* Registers a default template handler
*
* @param callable $callback class/method name
*
* @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining
* @throws SmartyException if $callback is not callable
*/
public function registerDefaultTemplateHandler($callback)
{
if (is_callable($callback)) {
$this->smarty->default_template_handler_func = $callback;
} else {
throw new SmartyException("Default template handler '$callback' not callable");
}
return $this;
}
/**
* Registers a default template handler
*
* @param callable $callback class/method name
*
* @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining
* @throws SmartyException if $callback is not callable
*/
public function registerDefaultConfigHandler($callback)
{
if (is_callable($callback)) {
$this->smarty->default_config_handler_func = $callback;
} else {
throw new SmartyException("Default config handler '$callback' not callable");
}
return $this;
}
/**
* Registers a filter function
*
* @param string $type filter type
* @param callback $callback
*
* @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining
*/
public function registerFilter($type, $callback)
{
$this->smarty->registered_filters[$type][$this->_get_filter_name($callback)] = $callback;
return $this;
}
/**
* Unregisters a filter function
*
* @param string $type filter type
* @param callback $callback
*
* @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining
*/
public function unregisterFilter($type, $callback)
{
$name = $this->_get_filter_name($callback);
if (isset($this->smarty->registered_filters[$type][$name])) {
unset($this->smarty->registered_filters[$type][$name]);
}
return $this;
}
/**
* Return internal filter name
*
* @param callback $function_name
*
* @return string internal filter name
*/
public function _get_filter_name($function_name)
{
if (is_array($function_name)) {
$_class_name = (is_object($function_name[0]) ?
get_class($function_name[0]) : $function_name[0]);
return $_class_name . '_' . $function_name[1];
} else {
return $function_name;
}
}
/**
* load a filter of specified type and name
*
* @param string $type filter type
* @param string $name filter name
*
* @throws SmartyException if filter could not be loaded
*/
public function loadFilter($type, $name)
{
$_plugin = "smarty_{$type}filter_{$name}";
$_filter_name = $_plugin;
if ($this->smarty->loadPlugin($_plugin)) {
if (class_exists($_plugin, false)) {
$_plugin = array($_plugin, 'execute');
}
if (is_callable($_plugin)) {
$this->smarty->registered_filters[$type][$_filter_name] = $_plugin;
return true;
}
}
throw new SmartyException("{$type}filter \"{$name}\" not callable");
}
/**
* unload a filter of specified type and name
*
* @param string $type filter type
* @param string $name filter name
*
* @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining
*/
public function unloadFilter($type, $name)
{
$_filter_name = "smarty_{$type}filter_{$name}";
if (isset($this->smarty->registered_filters[$type][$_filter_name])) {
unset ($this->smarty->registered_filters[$type][$_filter_name]);
}
return $this;
}
/**
* preg_replace callback to convert camelcase getter/setter to underscore property names
*
* @param string $match match string
*
* @return string replacemant
*/
private function replaceCamelcase($match)
{
return "_" . strtolower($match[1]);
}
/**
* Handle unknown class methods
*
* @param string $name unknown method-name
* @param array $args argument array
*
* @throws SmartyException
*/
public function __call($name, $args)
{
static $_prefixes = array('set' => true, 'get' => true);
static $_resolved_property_name = array();
static $_resolved_property_source = array();
// method of Smarty object?
if (method_exists($this->smarty, $name)) {
return call_user_func_array(array($this->smarty, $name), $args);
}
// see if this is a set/get for a property
$first3 = strtolower(substr($name, 0, 3));
if (isset($_prefixes[$first3]) && isset($name[3]) && $name[3] !== '_') {
if (isset($_resolved_property_name[$name])) {
$property_name = $_resolved_property_name[$name];
} else {
// try to keep case correct for future PHP 6.0 case-sensitive class methods
// lcfirst() not available < PHP 5.3.0, so improvise
$property_name = strtolower(substr($name, 3, 1)) . substr($name, 4);
// convert camel case to underscored name
$property_name = preg_replace_callback('/([A-Z])/', array($this, 'replaceCamelcase'), $property_name);
$_resolved_property_name[$name] = $property_name;
}
if (isset($_resolved_property_source[$property_name])) {
$_is_this = $_resolved_property_source[$property_name];
} else {
$_is_this = null;
if (property_exists($this, $property_name)) {
$_is_this = true;
} elseif (property_exists($this->smarty, $property_name)) {
$_is_this = false;
}
$_resolved_property_source[$property_name] = $_is_this;
}
if ($_is_this) {
if ($first3 == 'get') {
return $this->$property_name;
} else {
return $this->$property_name = $args[0];
}
} elseif ($_is_this === false) {
if ($first3 == 'get') {
return $this->smarty->$property_name;
} else {
return $this->smarty->$property_name = $args[0];
}
} else {
throw new SmartyException("property '$property_name' does not exist.");
}
}
if ($name == 'Smarty') {
throw new SmartyException("PHP5 requires you to call __construct() instead of Smarty()");
}
// must be unknown
throw new SmartyException("Call of unknown method '$name'.");
}
}

View File

@@ -1,823 +0,0 @@
<?php
/**
* Smarty Internal Plugin Smarty Template Compiler Base
* This file contains the basic classes and methods for compiling Smarty templates with lexer/parser
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Main abstract compiler class
*
* @package Smarty
* @subpackage Compiler
*/
abstract class Smarty_Internal_TemplateCompilerBase
{
/**
* hash for nocache sections
*
* @var mixed
*/
private $nocache_hash = null;
/**
* suppress generation of nocache code
*
* @var bool
*/
public $suppressNocacheProcessing = false;
/**
* suppress generation of merged template code
*
* @var bool
*/
public $suppressMergedTemplates = false;
/**
* compile tag objects
*
* @var array
*/
public static $_tag_objects = array();
/**
* tag stack
*
* @var array
*/
public $_tag_stack = array();
/**
* current template
*
* @var Smarty_Internal_Template
*/
public $template = null;
/**
* merged templates
*
* @var array
*/
public $merged_templates = array();
/**
* sources which must be compiled
*
* @var array
*/
public $sources = array();
/**
* flag that we are inside {block}
*
* @var bool
*/
public $inheritance = false;
/**
* flag when compiling inheritance child template
*
* @var bool
*/
public $inheritance_child = false;
/**
* uid of templates called by {extends} for recursion check
*
* @var array
*/
public $extends_uid = array();
/**
* source line offset for error messages
*
* @var int
*/
public $trace_line_offset = 0;
/**
* trace uid
*
* @var string
*/
public $trace_uid = '';
/**
* trace file path
*
* @var string
*/
public $trace_filepath = '';
/**
* stack for tracing file and line of nested {block} tags
*
* @var array
*/
public $trace_stack = array();
/**
* plugins loaded by default plugin handler
*
* @var array
*/
public $default_handler_plugins = array();
/**
* saved preprocessed modifier list
*
* @var mixed
*/
public $default_modifier_list = null;
/**
* force compilation of complete template as nocache
*
* @var boolean
*/
public $forceNocache = false;
/**
* suppress Smarty header code in compiled template
*
* @var bool
*/
public $suppressHeader = false;
/**
* suppress template property header code in compiled template
*
* @var bool
*/
public $suppressTemplatePropertyHeader = false;
/**
* suppress pre and post filter
*
* @var bool
*/
public $suppressFilter = false;
/**
* flag if compiled template file shall we written
*
* @var bool
*/
public $write_compiled_code = true;
/**
* flag if currently a template function is compiled
*
* @var bool
*/
public $compiles_template_function = false;
/**
* called subfuntions from template function
*
* @var array
*/
public $called_functions = array();
/**
* flags for used modifier plugins
*
* @var array
*/
public $modifier_plugins = array();
/**
* type of already compiled modifier
*
* @var array
*/
public $known_modifier_type = array();
/**
* method to compile a Smarty template
*
* @param mixed $_content template source
*
* @return bool true if compiling succeeded, false if it failed
*/
abstract protected function doCompile($_content);
/**
* Initialize compiler
*/
public function __construct()
{
$this->nocache_hash = str_replace(array('.', ','), '-', uniqid(rand(), true));
}
/**
* Method to compile a Smarty template
*
* @param Smarty_Internal_Template $template template object to compile
* @param bool $nocache true is shall be compiled in nocache mode
*
* @return bool true if compiling succeeded, false if it failed
*/
public function compileTemplate(Smarty_Internal_Template $template, $nocache = false)
{
if (empty($template->properties['nocache_hash'])) {
$template->properties['nocache_hash'] = $this->nocache_hash;
} else {
$this->nocache_hash = $template->properties['nocache_hash'];
}
// flag for nochache sections
$this->nocache = $nocache;
$this->tag_nocache = false;
// save template object in compiler class
$this->template = $template;
// reset has nocache code flag
$this->template->has_nocache_code = false;
$save_source = $this->template->source;
// template header code
$template_header = '';
if (!$this->suppressHeader) {
$template_header .= "<?php /* Smarty version " . Smarty::SMARTY_VERSION . ", created on " . strftime("%Y-%m-%d %H:%M:%S") . "\n";
$template_header .= " compiled from \"" . $this->template->source->filepath . "\" */ ?>\n";
}
if (empty($this->template->source->components)) {
$this->sources = array($template->source);
} else {
// we have array of inheritance templates by extends: resource
$this->sources = array_reverse($template->source->components);
}
$loop = 0;
// the $this->sources array can get additional elements while compiling by the {extends} tag
while ($this->template->source = array_shift($this->sources)) {
$this->smarty->_current_file = $this->template->source->filepath;
if ($this->smarty->debugging) {
Smarty_Internal_Debug::start_compile($this->template);
}
$no_sources = count($this->sources);
if ($loop || $no_sources) {
$this->template->properties['file_dependency'][$this->template->source->uid] = array($this->template->source->filepath, $this->template->source->timestamp, $this->template->source->type);
}
$loop ++;
if ($no_sources) {
$this->inheritance_child = true;
} else {
$this->inheritance_child = false;
}
do {
$_compiled_code = '';
// flag for aborting current and start recompile
$this->abort_and_recompile = false;
// get template source
$_content = $this->template->source->content;
if ($_content != '') {
// run prefilter if required
if ((isset($this->smarty->autoload_filters['pre']) || isset($this->smarty->registered_filters['pre'])) && !$this->suppressFilter) {
$_content = Smarty_Internal_Filter_Handler::runFilter('pre', $_content, $template);
}
// call compiler
$_compiled_code = $this->doCompile($_content);
}
} while ($this->abort_and_recompile);
if ($this->smarty->debugging) {
Smarty_Internal_Debug::end_compile($this->template);
}
}
// restore source
$this->template->source = $save_source;
unset($save_source);
$this->smarty->_current_file = $this->template->source->filepath;
// free memory
unset($this->parser->root_buffer, $this->parser->current_buffer, $this->parser, $this->lex, $this->template);
self::$_tag_objects = array();
// return compiled code to template object
$merged_code = '';
if (!$this->suppressMergedTemplates && !empty($this->merged_templates)) {
foreach ($this->merged_templates as $code) {
$merged_code .= $code;
}
}
// run postfilter if required on compiled template code
if ((isset($this->smarty->autoload_filters['post']) || isset($this->smarty->registered_filters['post'])) && !$this->suppressFilter && $_compiled_code != '') {
$_compiled_code = Smarty_Internal_Filter_Handler::runFilter('post', $_compiled_code, $template);
}
if ($this->suppressTemplatePropertyHeader) {
$code = $_compiled_code . $merged_code;
} else {
$code = $template_header . $template->createTemplateCodeFrame($_compiled_code) . $merged_code;
}
// unset content because template inheritance could have replace source with parent code
unset ($template->source->content);
return $code;
}
/**
* Compile Tag
* This is a call back from the lexer/parser
* It executes the required compile plugin for the Smarty tag
*
* @param string $tag tag name
* @param array $args array with tag attributes
* @param array $parameter array with compilation parameter
*
* @throws SmartyCompilerException
* @throws SmartyException
* @return string compiled code
*/
public function compileTag($tag, $args, $parameter = array())
{
// $args contains the attributes parsed and compiled by the lexer/parser
// assume that tag does compile into code, but creates no HTML output
$this->has_code = true;
$this->has_output = false;
// log tag/attributes
if (isset($this->smarty->get_used_tags) && $this->smarty->get_used_tags) {
$this->template->used_tags[] = array($tag, $args);
}
// check nocache option flag
if (in_array("'nocache'", $args) || in_array(array('nocache' => 'true'), $args)
|| in_array(array('nocache' => '"true"'), $args) || in_array(array('nocache' => "'true'"), $args)
) {
$this->tag_nocache = true;
}
// compile the smarty tag (required compile classes to compile the tag are autoloaded)
if (($_output = $this->callTagCompiler($tag, $args, $parameter)) === false) {
if (isset($this->smarty->template_functions[$tag])) {
// template defined by {template} tag
$args['_attr']['name'] = "'" . $tag . "'";
$_output = $this->callTagCompiler('call', $args, $parameter);
}
}
if ($_output !== false) {
if ($_output !== true) {
// did we get compiled code
if ($this->has_code) {
// Does it create output?
if ($this->has_output) {
$_output .= "\n";
}
// return compiled code
return $_output;
}
}
// tag did not produce compiled code
return null;
} else {
// map_named attributes
if (isset($args['_attr'])) {
foreach ($args['_attr'] as $key => $attribute) {
if (is_array($attribute)) {
$args = array_merge($args, $attribute);
}
}
}
// not an internal compiler tag
if (strlen($tag) < 6 || substr($tag, - 5) != 'close') {
// check if tag is a registered object
if (isset($this->smarty->registered_objects[$tag]) && isset($parameter['object_method'])) {
$method = $parameter['object_method'];
if (!in_array($method, $this->smarty->registered_objects[$tag][3]) &&
(empty($this->smarty->registered_objects[$tag][1]) || in_array($method, $this->smarty->registered_objects[$tag][1]))
) {
return $this->callTagCompiler('private_object_function', $args, $parameter, $tag, $method);
} elseif (in_array($method, $this->smarty->registered_objects[$tag][3])) {
return $this->callTagCompiler('private_object_block_function', $args, $parameter, $tag, $method);
} else {
// throw exception
$this->trigger_template_error('not allowed method "' . $method . '" in registered object "' . $tag . '"', $this->lex->taglineno);
}
}
// check if tag is registered
foreach (array(Smarty::PLUGIN_COMPILER, Smarty::PLUGIN_FUNCTION, Smarty::PLUGIN_BLOCK) as $plugin_type) {
if (isset($this->smarty->registered_plugins[$plugin_type][$tag])) {
// if compiler function plugin call it now
if ($plugin_type == Smarty::PLUGIN_COMPILER) {
$new_args = array();
foreach ($args as $key => $mixed) {
if (is_array($mixed)) {
$new_args = array_merge($new_args, $mixed);
} else {
$new_args[$key] = $mixed;
}
}
if (!$this->smarty->registered_plugins[$plugin_type][$tag][1]) {
$this->tag_nocache = true;
}
$function = $this->smarty->registered_plugins[$plugin_type][$tag][0];
if (!is_array($function)) {
return $function($new_args, $this);
} elseif (is_object($function[0])) {
return $this->smarty->registered_plugins[$plugin_type][$tag][0][0]->$function[1]($new_args, $this);
} else {
return call_user_func_array($function, array($new_args, $this));
}
}
// compile registered function or block function
if ($plugin_type == Smarty::PLUGIN_FUNCTION || $plugin_type == Smarty::PLUGIN_BLOCK) {
return $this->callTagCompiler('private_registered_' . $plugin_type, $args, $parameter, $tag);
}
}
}
// check plugins from plugins folder
foreach ($this->smarty->plugin_search_order as $plugin_type) {
if ($plugin_type == Smarty::PLUGIN_COMPILER && $this->smarty->loadPlugin('smarty_compiler_' . $tag) && (!isset($this->smarty->security_policy) || $this->smarty->security_policy->isTrustedTag($tag, $this))) {
$plugin = 'smarty_compiler_' . $tag;
if (is_callable($plugin)) {
// convert arguments format for old compiler plugins
$new_args = array();
foreach ($args as $key => $mixed) {
if (is_array($mixed)) {
$new_args = array_merge($new_args, $mixed);
} else {
$new_args[$key] = $mixed;
}
}
return $plugin($new_args, $this->smarty);
}
if (class_exists($plugin, false)) {
$plugin_object = new $plugin;
if (method_exists($plugin_object, 'compile')) {
return $plugin_object->compile($args, $this);
}
}
throw new SmartyException("Plugin \"{$tag}\" not callable");
} else {
if ($function = $this->getPlugin($tag, $plugin_type)) {
if (!isset($this->smarty->security_policy) || $this->smarty->security_policy->isTrustedTag($tag, $this)) {
return $this->callTagCompiler('private_' . $plugin_type . '_plugin', $args, $parameter, $tag, $function);
}
}
}
}
if (is_callable($this->smarty->default_plugin_handler_func)) {
$found = false;
// look for already resolved tags
foreach ($this->smarty->plugin_search_order as $plugin_type) {
if (isset($this->default_handler_plugins[$plugin_type][$tag])) {
$found = true;
break;
}
}
if (!$found) {
// call default handler
foreach ($this->smarty->plugin_search_order as $plugin_type) {
if ($this->getPluginFromDefaultHandler($tag, $plugin_type)) {
$found = true;
break;
}
}
}
if ($found) {
// if compiler function plugin call it now
if ($plugin_type == Smarty::PLUGIN_COMPILER) {
$new_args = array();
foreach ($args as $mixed) {
$new_args = array_merge($new_args, $mixed);
}
$function = $this->default_handler_plugins[$plugin_type][$tag][0];
if (!is_array($function)) {
return $function($new_args, $this);
} elseif (is_object($function[0])) {
return $this->default_handler_plugins[$plugin_type][$tag][0][0]->$function[1]($new_args, $this);
} else {
return call_user_func_array($function, array($new_args, $this));
}
} else {
return $this->callTagCompiler('private_registered_' . $plugin_type, $args, $parameter, $tag);
}
}
}
} else {
// compile closing tag of block function
$base_tag = substr($tag, 0, - 5);
// check if closing tag is a registered object
if (isset($this->smarty->registered_objects[$base_tag]) && isset($parameter['object_method'])) {
$method = $parameter['object_method'];
if (in_array($method, $this->smarty->registered_objects[$base_tag][3])) {
return $this->callTagCompiler('private_object_block_function', $args, $parameter, $tag, $method);
} else {
// throw exception
$this->trigger_template_error('not allowed closing tag method "' . $method . '" in registered object "' . $base_tag . '"', $this->lex->taglineno);
}
}
// registered block tag ?
if (isset($this->smarty->registered_plugins[Smarty::PLUGIN_BLOCK][$base_tag]) || isset($this->default_handler_plugins[Smarty::PLUGIN_BLOCK][$base_tag])) {
return $this->callTagCompiler('private_registered_block', $args, $parameter, $tag);
}
// block plugin?
if ($function = $this->getPlugin($base_tag, Smarty::PLUGIN_BLOCK)) {
return $this->callTagCompiler('private_block_plugin', $args, $parameter, $tag, $function);
}
// registered compiler plugin ?
if (isset($this->smarty->registered_plugins[Smarty::PLUGIN_COMPILER][$tag])) {
// if compiler function plugin call it now
$args = array();
if (!$this->smarty->registered_plugins[Smarty::PLUGIN_COMPILER][$tag][1]) {
$this->tag_nocache = true;
}
$function = $this->smarty->registered_plugins[Smarty::PLUGIN_COMPILER][$tag][0];
if (!is_array($function)) {
return $function($args, $this);
} elseif (is_object($function[0])) {
return $this->smarty->registered_plugins[Smarty::PLUGIN_COMPILER][$tag][0][0]->$function[1]($args, $this);
} else {
return call_user_func_array($function, array($args, $this));
}
}
if ($this->smarty->loadPlugin('smarty_compiler_' . $tag)) {
$plugin = 'smarty_compiler_' . $tag;
if (is_callable($plugin)) {
return $plugin($args, $this->smarty);
}
if (class_exists($plugin, false)) {
$plugin_object = new $plugin;
if (method_exists($plugin_object, 'compile')) {
return $plugin_object->compile($args, $this);
}
}
throw new SmartyException("Plugin \"{$tag}\" not callable");
}
}
$this->trigger_template_error("unknown tag \"" . $tag . "\"", $this->lex->taglineno);
}
}
/**
* lazy loads internal compile plugin for tag and calls the compile method
* compile objects cached for reuse.
* class name format: Smarty_Internal_Compile_TagName
* plugin filename format: Smarty_Internal_Tagname.php
*
* @param string $tag tag name
* @param array $args list of tag attributes
* @param mixed $param1 optional parameter
* @param mixed $param2 optional parameter
* @param mixed $param3 optional parameter
*
* @return string compiled code
*/
public function callTagCompiler($tag, $args, $param1 = null, $param2 = null, $param3 = null)
{
// re-use object if already exists
if (isset(self::$_tag_objects[$tag])) {
// compile this tag
return self::$_tag_objects[$tag]->compile($args, $this, $param1, $param2, $param3);
}
// lazy load internal compiler plugin
$class_name = 'Smarty_Internal_Compile_' . $tag;
if ($this->smarty->loadPlugin($class_name)) {
// check if tag allowed by security
if (!isset($this->smarty->security_policy) || $this->smarty->security_policy->isTrustedTag($tag, $this)) {
// use plugin if found
self::$_tag_objects[$tag] = new $class_name;
// compile this tag
return self::$_tag_objects[$tag]->compile($args, $this, $param1, $param2, $param3);
}
}
// no internal compile plugin for this tag
return false;
}
/**
* Check for plugins and return function name
*
* @param $plugin_name
* @param string $plugin_type type of plugin
*
* @return string call name of function
*/
public function getPlugin($plugin_name, $plugin_type)
{
$function = null;
if ($this->template->caching && ($this->nocache || $this->tag_nocache)) {
if (isset($this->template->required_plugins['nocache'][$plugin_name][$plugin_type])) {
$function = $this->template->required_plugins['nocache'][$plugin_name][$plugin_type]['function'];
} elseif (isset($this->template->required_plugins['compiled'][$plugin_name][$plugin_type])) {
$this->template->required_plugins['nocache'][$plugin_name][$plugin_type] = $this->template->required_plugins['compiled'][$plugin_name][$plugin_type];
$function = $this->template->required_plugins['nocache'][$plugin_name][$plugin_type]['function'];
}
} else {
if (isset($this->template->required_plugins['compiled'][$plugin_name][$plugin_type])) {
$function = $this->template->required_plugins['compiled'][$plugin_name][$plugin_type]['function'];
} elseif (isset($this->template->required_plugins['nocache'][$plugin_name][$plugin_type])) {
$this->template->required_plugins['compiled'][$plugin_name][$plugin_type] = $this->template->required_plugins['nocache'][$plugin_name][$plugin_type];
$function = $this->template->required_plugins['compiled'][$plugin_name][$plugin_type]['function'];
}
}
if (isset($function)) {
if ($plugin_type == 'modifier') {
$this->modifier_plugins[$plugin_name] = true;
}
return $function;
}
// loop through plugin dirs and find the plugin
$function = 'smarty_' . $plugin_type . '_' . $plugin_name;
$file = $this->smarty->loadPlugin($function, false);
if (is_string($file)) {
if ($this->template->caching && ($this->nocache || $this->tag_nocache)) {
$this->template->required_plugins['nocache'][$plugin_name][$plugin_type]['file'] = $file;
$this->template->required_plugins['nocache'][$plugin_name][$plugin_type]['function'] = $function;
} else {
$this->template->required_plugins['compiled'][$plugin_name][$plugin_type]['file'] = $file;
$this->template->required_plugins['compiled'][$plugin_name][$plugin_type]['function'] = $function;
}
if ($plugin_type == 'modifier') {
$this->modifier_plugins[$plugin_name] = true;
}
return $function;
}
if (is_callable($function)) {
// plugin function is defined in the script
return $function;
}
return false;
}
/**
* Check for plugins by default plugin handler
*
* @param string $tag name of tag
* @param string $plugin_type type of plugin
*
* @return boolean true if found
*/
public function getPluginFromDefaultHandler($tag, $plugin_type)
{
$callback = null;
$script = null;
$cacheable = true;
$result = call_user_func_array(
$this->smarty->default_plugin_handler_func, array($tag, $plugin_type, $this->template, &$callback, &$script, &$cacheable)
);
if ($result) {
$this->tag_nocache = $this->tag_nocache || !$cacheable;
if ($script !== null) {
if (is_file($script)) {
if ($this->template->caching && ($this->nocache || $this->tag_nocache)) {
$this->template->required_plugins['nocache'][$tag][$plugin_type]['file'] = $script;
$this->template->required_plugins['nocache'][$tag][$plugin_type]['function'] = $callback;
} else {
$this->template->required_plugins['compiled'][$tag][$plugin_type]['file'] = $script;
$this->template->required_plugins['compiled'][$tag][$plugin_type]['function'] = $callback;
}
include_once $script;
} else {
$this->trigger_template_error("Default plugin handler: Returned script file \"{$script}\" for \"{$tag}\" not found");
}
}
if (!is_string($callback) && !(is_array($callback) && is_string($callback[0]) && is_string($callback[1]))) {
$this->trigger_template_error("Default plugin handler: Returned callback for \"{$tag}\" must be a static function name or array of class and function name");
}
if (is_callable($callback)) {
$this->default_handler_plugins[$plugin_type][$tag] = array($callback, true, array());
return true;
} else {
$this->trigger_template_error("Default plugin handler: Returned callback for \"{$tag}\" not callable");
}
}
return false;
}
/**
* Inject inline code for nocache template sections
* This method gets the content of each template element from the parser.
* If the content is compiled code and it should be not cached the code is injected
* into the rendered output.
*
* @param string $content content of template element
* @param boolean $is_code true if content is compiled code
*
* @return string content
*/
public function processNocacheCode($content, $is_code)
{
// If the template is not evaluated and we have a nocache section and or a nocache tag
if ($is_code && !empty($content)) {
// generate replacement code
if ((!($this->template->source->recompiled) || $this->forceNocache) && $this->template->caching && !$this->suppressNocacheProcessing &&
($this->nocache || $this->tag_nocache)
) {
$this->template->has_nocache_code = true;
$_output = addcslashes($content, '\'\\');
$_output = str_replace("^#^", "'", $_output);
$_output = "<?php echo '/*%%SmartyNocache:{$this->nocache_hash}%%*/" . $_output . "/*/%%SmartyNocache:{$this->nocache_hash}%%*/';?>\n";
// make sure we include modifier plugins for nocache code
foreach ($this->modifier_plugins as $plugin_name => $dummy) {
if (isset($this->template->required_plugins['compiled'][$plugin_name]['modifier'])) {
$this->template->required_plugins['nocache'][$plugin_name]['modifier'] = $this->template->required_plugins['compiled'][$plugin_name]['modifier'];
}
}
} else {
$_output = $content;
}
} else {
$_output = $content;
}
$this->modifier_plugins = array();
$this->suppressNocacheProcessing = false;
$this->tag_nocache = false;
return $_output;
}
/**
* push current file and line offset on stack for tracing {block} source lines
*
* @param string $file new filename
* @param string $uid uid of file
* @param int $line line offset to source
* @param bool $debug false debug end_compile shall not be called
*/
public function pushTrace($file, $uid, $line, $debug = true)
{
if ($this->smarty->debugging && $debug) {
Smarty_Internal_Debug::end_compile($this->template);
}
array_push($this->trace_stack, array($this->smarty->_current_file, $this->trace_filepath, $this->trace_uid, $this->trace_line_offset));
$this->trace_filepath = $this->smarty->_current_file = $file;
$this->trace_uid = $uid;
$this->trace_line_offset = $line;
if ($this->smarty->debugging) {
Smarty_Internal_Debug::start_compile($this->template);
}
}
/**
* restore file and line offset
*/
public function popTrace()
{
if ($this->smarty->debugging) {
Smarty_Internal_Debug::end_compile($this->template);
}
$r = array_pop($this->trace_stack);
$this->smarty->_current_file = $r[0];
$this->trace_filepath = $r[1];
$this->trace_uid = $r[2];
$this->trace_line_offset = $r[3];
if ($this->smarty->debugging) {
Smarty_Internal_Debug::start_compile($this->template);
}
}
/**
* display compiler error messages without dying
* If parameter $args is empty it is a parser detected syntax error.
* In this case the parser is called to obtain information about expected tokens.
* If parameter $args contains a string this is used as error message
*
* @param string $args individual error message or null
* @param string $line line-number
*
* @throws SmartyCompilerException when an unexpected token is found
*/
public function trigger_template_error($args = null, $line = null)
{
// get template source line which has error
if (!isset($line)) {
$line = $this->lex->line;
}
// $line += $this->trace_line_offset;
$match = preg_split("/\n/", $this->lex->data);
$error_text = 'Syntax error in template "' . (empty($this->trace_filepath) ? $this->template->source->filepath : $this->trace_filepath) . '" on line ' . ($line + $this->trace_line_offset) . ' "' . trim(preg_replace('![\t\r\n]+!', ' ', $match[$line - 1])) . '" ';
if (isset($args)) {
// individual error message
$error_text .= $args;
} else {
// expected token from parser
$error_text .= ' - Unexpected "' . $this->lex->value . '"';
if (count($this->parser->yy_get_expected_tokens($this->parser->yymajor)) <= 4) {
foreach ($this->parser->yy_get_expected_tokens($this->parser->yymajor) as $token) {
$exp_token = $this->parser->yyTokenName[$token];
if (isset($this->lex->smarty_token_names[$exp_token])) {
// token type from lexer
$expect[] = '"' . $this->lex->smarty_token_names[$exp_token] . '"';
} else {
// otherwise internal token name
$expect[] = $this->parser->yyTokenName[$token];
}
}
$error_text .= ', expected one of: ' . implode(' , ', $expect);
}
}
$e = new SmartyCompilerException($error_text);
$e->line = $line;
$e->source = trim(preg_replace('![\t\r\n]+!', ' ', $match[$line - 1]));
$e->desc = $args;
$e->template = $this->template->source->filepath;
throw $e;
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,837 +0,0 @@
<?php
/**
* Project: Smarty: the PHP compiling template engine
* File: smarty_internal_utility.php
* SVN: $Id: $
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* For questions, help, comments, discussion, etc., please join the
* Smarty mailing list. Send a blank e-mail to
* smarty-discussion-subscribe@googlegroups.com
*
* @link http://www.smarty.net/
* @copyright 2008 New Digital Group, Inc.
* @author Monte Ohrt <monte at ohrt dot com>
* @author Uwe Tews
* @package Smarty
* @subpackage PluginsInternal
* @version 3-SVN$Rev: 3286 $
*/
/**
* Utility class
*
* @package Smarty
* @subpackage Security
*/
class Smarty_Internal_Utility
{
/**
* private constructor to prevent calls creation of new instances
*/
final private function __construct()
{
// intentionally left blank
}
/**
* Compile all template files
*
* @param string $extension template file name extension
* @param bool $force_compile force all to recompile
* @param int $time_limit set maximum execution time
* @param int $max_errors set maximum allowed errors
* @param Smarty $smarty Smarty instance
*
* @return integer number of template files compiled
*/
public static function compileAllTemplates($extension, $force_compile, $time_limit, $max_errors, Smarty $smarty)
{
// switch off time limit
if (function_exists('set_time_limit')) {
@set_time_limit($time_limit);
}
$smarty->force_compile = $force_compile;
$_count = 0;
$_error_count = 0;
// loop over array of template directories
foreach ($smarty->getTemplateDir() as $_dir) {
$_compileDirs = new RecursiveDirectoryIterator($_dir);
$_compile = new RecursiveIteratorIterator($_compileDirs);
foreach ($_compile as $_fileinfo) {
$_file = $_fileinfo->getFilename();
if (substr(basename($_fileinfo->getPathname()), 0, 1) == '.' || strpos($_file, '.svn') !== false) {
continue;
}
if (!substr_compare($_file, $extension, - strlen($extension)) == 0) {
continue;
}
if ($_fileinfo->getPath() == substr($_dir, 0, - 1)) {
$_template_file = $_file;
} else {
$_template_file = substr($_fileinfo->getPath(), strlen($_dir)) . DS . $_file;
}
echo '<br>', $_dir, '---', $_template_file;
flush();
$_start_time = microtime(true);
try {
$_tpl = $smarty->createTemplate($_template_file, null, null, null, false);
if ($_tpl->mustCompile()) {
$_tpl->compileTemplateSource();
$_count ++;
echo ' compiled in ', microtime(true) - $_start_time, ' seconds';
flush();
} else {
echo ' is up to date';
flush();
}
}
catch (Exception $e) {
echo 'Error: ', $e->getMessage(), "<br><br>";
$_error_count ++;
}
// free memory
$smarty->template_objects = array();
$_tpl->smarty->template_objects = array();
$_tpl = null;
if ($max_errors !== null && $_error_count == $max_errors) {
echo '<br><br>too many errors';
exit();
}
}
}
return $_count;
}
/**
* Compile all config files
*
* @param string $extension config file name extension
* @param bool $force_compile force all to recompile
* @param int $time_limit set maximum execution time
* @param int $max_errors set maximum allowed errors
* @param Smarty $smarty Smarty instance
*
* @return integer number of config files compiled
*/
public static function compileAllConfig($extension, $force_compile, $time_limit, $max_errors, Smarty $smarty)
{
// switch off time limit
if (function_exists('set_time_limit')) {
@set_time_limit($time_limit);
}
$smarty->force_compile = $force_compile;
$_count = 0;
$_error_count = 0;
// loop over array of template directories
foreach ($smarty->getConfigDir() as $_dir) {
$_compileDirs = new RecursiveDirectoryIterator($_dir);
$_compile = new RecursiveIteratorIterator($_compileDirs);
foreach ($_compile as $_fileinfo) {
$_file = $_fileinfo->getFilename();
if (substr(basename($_fileinfo->getPathname()), 0, 1) == '.' || strpos($_file, '.svn') !== false) {
continue;
}
if (!substr_compare($_file, $extension, - strlen($extension)) == 0) {
continue;
}
if ($_fileinfo->getPath() == substr($_dir, 0, - 1)) {
$_config_file = $_file;
} else {
$_config_file = substr($_fileinfo->getPath(), strlen($_dir)) . DS . $_file;
}
echo '<br>', $_dir, '---', $_config_file;
flush();
$_start_time = microtime(true);
try {
$_config = new Smarty_Internal_Config($_config_file, $smarty);
if ($_config->mustCompile()) {
$_config->compileConfigSource();
$_count ++;
echo ' compiled in ', microtime(true) - $_start_time, ' seconds';
flush();
} else {
echo ' is up to date';
flush();
}
}
catch (Exception $e) {
echo 'Error: ', $e->getMessage(), "<br><br>";
$_error_count ++;
}
if ($max_errors !== null && $_error_count == $max_errors) {
echo '<br><br>too many errors';
exit();
}
}
}
return $_count;
}
/**
* Delete compiled template file
*
* @param string $resource_name template name
* @param string $compile_id compile id
* @param integer $exp_time expiration time
* @param Smarty $smarty Smarty instance
*
* @return integer number of template files deleted
*/
public static function clearCompiledTemplate($resource_name, $compile_id, $exp_time, Smarty $smarty)
{
$_compile_dir = realpath($smarty->getCompileDir()) . '/';
$_compile_id = isset($compile_id) ? preg_replace('![^\w\|]+!', '_', $compile_id) : null;
$_dir_sep = $smarty->use_sub_dirs ? '/' : '^';
if (isset($resource_name)) {
$_save_stat = $smarty->caching;
$smarty->caching = false;
$tpl = new $smarty->template_class($resource_name, $smarty);
$smarty->caching = $_save_stat;
// remove from template cache
$tpl->source; // have the template registered before unset()
if ($smarty->allow_ambiguous_resources) {
$_templateId = $tpl->source->unique_resource . $tpl->cache_id . $tpl->compile_id;
} else {
$_templateId = $smarty->joined_template_dir . '#' . $resource_name . $tpl->cache_id . $tpl->compile_id;
}
if (isset($_templateId[150])) {
$_templateId = sha1($_templateId);
}
unset($smarty->template_objects[$_templateId]);
if ($tpl->source->exists) {
$_resource_part_1 = basename(str_replace('^', '/', $tpl->compiled->filepath));
$_resource_part_1_length = strlen($_resource_part_1);
} else {
return 0;
}
$_resource_part_2 = str_replace('.php', '.cache.php', $_resource_part_1);
$_resource_part_2_length = strlen($_resource_part_2);
}
$_dir = $_compile_dir;
if ($smarty->use_sub_dirs && isset($_compile_id)) {
$_dir .= $_compile_id . $_dir_sep;
}
if (isset($_compile_id)) {
$_compile_id_part = str_replace('\\', '/', $_compile_dir . $_compile_id . $_dir_sep);
$_compile_id_part_length = strlen($_compile_id_part);
}
$_count = 0;
try {
$_compileDirs = new RecursiveDirectoryIterator($_dir);
// NOTE: UnexpectedValueException thrown for PHP >= 5.3
}
catch (Exception $e) {
return 0;
}
$_compile = new RecursiveIteratorIterator($_compileDirs, RecursiveIteratorIterator::CHILD_FIRST);
foreach ($_compile as $_file) {
if (substr(basename($_file->getPathname()), 0, 1) == '.' || strpos($_file, '.svn') !== false) {
continue;
}
$_filepath = str_replace('\\', '/', (string) $_file);
if ($_file->isDir()) {
if (!$_compile->isDot()) {
// delete folder if empty
@rmdir($_file->getPathname());
}
} else {
$unlink = false;
if ((!isset($_compile_id) || (isset($_filepath[$_compile_id_part_length]) && $a = !strncmp($_filepath, $_compile_id_part, $_compile_id_part_length)))
&& (!isset($resource_name)
|| (isset($_filepath[$_resource_part_1_length])
&& substr_compare($_filepath, $_resource_part_1, - $_resource_part_1_length, $_resource_part_1_length) == 0)
|| (isset($_filepath[$_resource_part_2_length])
&& substr_compare($_filepath, $_resource_part_2, - $_resource_part_2_length, $_resource_part_2_length) == 0))
) {
if (isset($exp_time)) {
if (time() - @filemtime($_filepath) >= $exp_time) {
$unlink = true;
}
} else {
$unlink = true;
}
}
if ($unlink && @unlink($_filepath)) {
$_count ++;
}
}
}
// clear compiled cache
Smarty_Resource::$sources = array();
Smarty_Resource::$compileds = array();
return $_count;
}
/**
* Return array of tag/attributes of all tags used by an template
*
* @param Smarty_Internal_Template $template
*
* @throws Exception
* @throws SmartyException
* @return array of tag/attributes
*/
public static function getTags(Smarty_Internal_Template $template)
{
$template->smarty->get_used_tags = true;
$template->compileTemplateSource();
return $template->used_tags;
}
/**
* diagnose Smarty setup
* If $errors is secified, the diagnostic report will be appended to the array, rather than being output.
*
* @param Smarty $smarty Smarty instance to test
* @param array $errors array to push results into rather than outputting them
*
* @return bool status, true if everything is fine, false else
*/
public static function testInstall(Smarty $smarty, &$errors = null)
{
$status = true;
if ($errors === null) {
echo "<PRE>\n";
echo "Smarty Installation test...\n";
echo "Testing template directory...\n";
}
$_stream_resolve_include_path = function_exists('stream_resolve_include_path');
// test if all registered template_dir are accessible
foreach ($smarty->getTemplateDir() as $template_dir) {
$_template_dir = $template_dir;
$template_dir = realpath($template_dir);
// resolve include_path or fail existence
if (!$template_dir) {
if ($smarty->use_include_path && !preg_match('/^([\/\\\\]|[a-zA-Z]:[\/\\\\])/', $_template_dir)) {
// try PHP include_path
if ($_stream_resolve_include_path) {
$template_dir = stream_resolve_include_path($_template_dir);
} else {
$template_dir = Smarty_Internal_Get_Include_Path::getIncludePath($_template_dir);
}
if ($template_dir !== false) {
if ($errors === null) {
echo "$template_dir is OK.\n";
}
continue;
} else {
$status = false;
$message = "FAILED: $_template_dir does not exist (and couldn't be found in include_path either)";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['template_dir'] = $message;
}
continue;
}
} else {
$status = false;
$message = "FAILED: $_template_dir does not exist";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['template_dir'] = $message;
}
continue;
}
}
if (!is_dir($template_dir)) {
$status = false;
$message = "FAILED: $template_dir is not a directory";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['template_dir'] = $message;
}
} elseif (!is_readable($template_dir)) {
$status = false;
$message = "FAILED: $template_dir is not readable";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['template_dir'] = $message;
}
} else {
if ($errors === null) {
echo "$template_dir is OK.\n";
}
}
}
if ($errors === null) {
echo "Testing compile directory...\n";
}
// test if registered compile_dir is accessible
$__compile_dir = $smarty->getCompileDir();
$_compile_dir = realpath($__compile_dir);
if (!$_compile_dir) {
$status = false;
$message = "FAILED: {$__compile_dir} does not exist";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['compile_dir'] = $message;
}
} elseif (!is_dir($_compile_dir)) {
$status = false;
$message = "FAILED: {$_compile_dir} is not a directory";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['compile_dir'] = $message;
}
} elseif (!is_readable($_compile_dir)) {
$status = false;
$message = "FAILED: {$_compile_dir} is not readable";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['compile_dir'] = $message;
}
} elseif (!is_writable($_compile_dir)) {
$status = false;
$message = "FAILED: {$_compile_dir} is not writable";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['compile_dir'] = $message;
}
} else {
if ($errors === null) {
echo "{$_compile_dir} is OK.\n";
}
}
if ($errors === null) {
echo "Testing plugins directory...\n";
}
// test if all registered plugins_dir are accessible
// and if core plugins directory is still registered
$_core_plugins_dir = realpath(dirname(__FILE__) . '/../plugins');
$_core_plugins_available = false;
foreach ($smarty->getPluginsDir() as $plugin_dir) {
$_plugin_dir = $plugin_dir;
$plugin_dir = realpath($plugin_dir);
// resolve include_path or fail existence
if (!$plugin_dir) {
if ($smarty->use_include_path && !preg_match('/^([\/\\\\]|[a-zA-Z]:[\/\\\\])/', $_plugin_dir)) {
// try PHP include_path
if ($_stream_resolve_include_path) {
$plugin_dir = stream_resolve_include_path($_plugin_dir);
} else {
$plugin_dir = Smarty_Internal_Get_Include_Path::getIncludePath($_plugin_dir);
}
if ($plugin_dir !== false) {
if ($errors === null) {
echo "$plugin_dir is OK.\n";
}
continue;
} else {
$status = false;
$message = "FAILED: $_plugin_dir does not exist (and couldn't be found in include_path either)";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['plugins_dir'] = $message;
}
continue;
}
} else {
$status = false;
$message = "FAILED: $_plugin_dir does not exist";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['plugins_dir'] = $message;
}
continue;
}
}
if (!is_dir($plugin_dir)) {
$status = false;
$message = "FAILED: $plugin_dir is not a directory";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['plugins_dir'] = $message;
}
} elseif (!is_readable($plugin_dir)) {
$status = false;
$message = "FAILED: $plugin_dir is not readable";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['plugins_dir'] = $message;
}
} elseif ($_core_plugins_dir && $_core_plugins_dir == realpath($plugin_dir)) {
$_core_plugins_available = true;
if ($errors === null) {
echo "$plugin_dir is OK.\n";
}
} else {
if ($errors === null) {
echo "$plugin_dir is OK.\n";
}
}
}
if (!$_core_plugins_available) {
$status = false;
$message = "WARNING: Smarty's own libs/plugins is not available";
if ($errors === null) {
echo $message . ".\n";
} elseif (!isset($errors['plugins_dir'])) {
$errors['plugins_dir'] = $message;
}
}
if ($errors === null) {
echo "Testing cache directory...\n";
}
// test if all registered cache_dir is accessible
$__cache_dir = $smarty->getCacheDir();
$_cache_dir = realpath($__cache_dir);
if (!$_cache_dir) {
$status = false;
$message = "FAILED: {$__cache_dir} does not exist";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['cache_dir'] = $message;
}
} elseif (!is_dir($_cache_dir)) {
$status = false;
$message = "FAILED: {$_cache_dir} is not a directory";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['cache_dir'] = $message;
}
} elseif (!is_readable($_cache_dir)) {
$status = false;
$message = "FAILED: {$_cache_dir} is not readable";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['cache_dir'] = $message;
}
} elseif (!is_writable($_cache_dir)) {
$status = false;
$message = "FAILED: {$_cache_dir} is not writable";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['cache_dir'] = $message;
}
} else {
if ($errors === null) {
echo "{$_cache_dir} is OK.\n";
}
}
if ($errors === null) {
echo "Testing configs directory...\n";
}
// test if all registered config_dir are accessible
foreach ($smarty->getConfigDir() as $config_dir) {
$_config_dir = $config_dir;
$config_dir = realpath($config_dir);
// resolve include_path or fail existence
if (!$config_dir) {
if ($smarty->use_include_path && !preg_match('/^([\/\\\\]|[a-zA-Z]:[\/\\\\])/', $_config_dir)) {
// try PHP include_path
if ($_stream_resolve_include_path) {
$config_dir = stream_resolve_include_path($_config_dir);
} else {
$config_dir = Smarty_Internal_Get_Include_Path::getIncludePath($_config_dir);
}
if ($config_dir !== false) {
if ($errors === null) {
echo "$config_dir is OK.\n";
}
continue;
} else {
$status = false;
$message = "FAILED: $_config_dir does not exist (and couldn't be found in include_path either)";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['config_dir'] = $message;
}
continue;
}
} else {
$status = false;
$message = "FAILED: $_config_dir does not exist";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['config_dir'] = $message;
}
continue;
}
}
if (!is_dir($config_dir)) {
$status = false;
$message = "FAILED: $config_dir is not a directory";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['config_dir'] = $message;
}
} elseif (!is_readable($config_dir)) {
$status = false;
$message = "FAILED: $config_dir is not readable";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['config_dir'] = $message;
}
} else {
if ($errors === null) {
echo "$config_dir is OK.\n";
}
}
}
if ($errors === null) {
echo "Testing sysplugin files...\n";
}
// test if sysplugins are available
$source = SMARTY_SYSPLUGINS_DIR;
if (is_dir($source)) {
$expected = array(
"smarty_cacheresource.php" => true,
"smarty_cacheresource_custom.php" => true,
"smarty_cacheresource_keyvaluestore.php" => true,
"smarty_config_source.php" => true,
"smarty_internal_cacheresource_file.php" => true,
"smarty_internal_compile_append.php" => true,
"smarty_internal_compile_assign.php" => true,
"smarty_internal_compile_block.php" => true,
"smarty_internal_compile_break.php" => true,
"smarty_internal_compile_call.php" => true,
"smarty_internal_compile_capture.php" => true,
"smarty_internal_compile_config_load.php" => true,
"smarty_internal_compile_continue.php" => true,
"smarty_internal_compile_debug.php" => true,
"smarty_internal_compile_eval.php" => true,
"smarty_internal_compile_extends.php" => true,
"smarty_internal_compile_for.php" => true,
"smarty_internal_compile_foreach.php" => true,
"smarty_internal_compile_function.php" => true,
"smarty_internal_compile_if.php" => true,
"smarty_internal_compile_include.php" => true,
"smarty_internal_compile_include_php.php" => true,
"smarty_internal_compile_insert.php" => true,
"smarty_internal_compile_ldelim.php" => true,
"smarty_internal_compile_nocache.php" => true,
"smarty_internal_compile_private_block_plugin.php" => true,
"smarty_internal_compile_private_function_plugin.php" => true,
"smarty_internal_compile_private_modifier.php" => true,
"smarty_internal_compile_private_object_block_function.php" => true,
"smarty_internal_compile_private_object_function.php" => true,
"smarty_internal_compile_private_print_expression.php" => true,
"smarty_internal_compile_private_registered_block.php" => true,
"smarty_internal_compile_private_registered_function.php" => true,
"smarty_internal_compile_private_special_variable.php" => true,
"smarty_internal_compile_rdelim.php" => true,
"smarty_internal_compile_section.php" => true,
"smarty_internal_compile_setfilter.php" => true,
"smarty_internal_compile_while.php" => true,
"smarty_internal_compilebase.php" => true,
"smarty_internal_config.php" => true,
"smarty_internal_config_file_compiler.php" => true,
"smarty_internal_configfilelexer.php" => true,
"smarty_internal_configfileparser.php" => true,
"smarty_internal_data.php" => true,
"smarty_internal_debug.php" => true,
"smarty_internal_filter_handler.php" => true,
"smarty_internal_function_call_handler.php" => true,
"smarty_internal_get_include_path.php" => true,
"smarty_internal_nocache_insert.php" => true,
"smarty_internal_parsetree.php" => true,
"smarty_internal_resource_eval.php" => true,
"smarty_internal_resource_extends.php" => true,
"smarty_internal_resource_file.php" => true,
"smarty_internal_resource_registered.php" => true,
"smarty_internal_resource_stream.php" => true,
"smarty_internal_resource_string.php" => true,
"smarty_internal_smartytemplatecompiler.php" => true,
"smarty_internal_template.php" => true,
"smarty_internal_templatebase.php" => true,
"smarty_internal_templatecompilerbase.php" => true,
"smarty_internal_templatelexer.php" => true,
"smarty_internal_templateparser.php" => true,
"smarty_internal_utility.php" => true,
"smarty_internal_write_file.php" => true,
"smarty_resource.php" => true,
"smarty_resource_custom.php" => true,
"smarty_resource_recompiled.php" => true,
"smarty_resource_uncompiled.php" => true,
"smarty_security.php" => true,
);
$iterator = new DirectoryIterator($source);
foreach ($iterator as $file) {
if (!$file->isDot()) {
$filename = $file->getFilename();
if (isset($expected[$filename])) {
unset($expected[$filename]);
}
}
}
if ($expected) {
$status = false;
$message = "FAILED: files missing from libs/sysplugins: " . join(', ', array_keys($expected));
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['sysplugins'] = $message;
}
} elseif ($errors === null) {
echo "... OK\n";
}
} else {
$status = false;
$message = "FAILED: " . SMARTY_SYSPLUGINS_DIR . ' is not a directory';
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['sysplugins_dir_constant'] = $message;
}
}
if ($errors === null) {
echo "Testing plugin files...\n";
}
// test if core plugins are available
$source = SMARTY_PLUGINS_DIR;
if (is_dir($source)) {
$expected = array(
"block.textformat.php" => true,
"function.counter.php" => true,
"function.cycle.php" => true,
"function.fetch.php" => true,
"function.html_checkboxes.php" => true,
"function.html_image.php" => true,
"function.html_options.php" => true,
"function.html_radios.php" => true,
"function.html_select_date.php" => true,
"function.html_select_time.php" => true,
"function.html_table.php" => true,
"function.mailto.php" => true,
"function.math.php" => true,
"modifier.capitalize.php" => true,
"modifier.date_format.php" => true,
"modifier.debug_print_var.php" => true,
"modifier.escape.php" => true,
"modifier.regex_replace.php" => true,
"modifier.replace.php" => true,
"modifier.spacify.php" => true,
"modifier.truncate.php" => true,
"modifiercompiler.cat.php" => true,
"modifiercompiler.count_characters.php" => true,
"modifiercompiler.count_paragraphs.php" => true,
"modifiercompiler.count_sentences.php" => true,
"modifiercompiler.count_words.php" => true,
"modifiercompiler.default.php" => true,
"modifiercompiler.escape.php" => true,
"modifiercompiler.from_charset.php" => true,
"modifiercompiler.indent.php" => true,
"modifiercompiler.lower.php" => true,
"modifiercompiler.noprint.php" => true,
"modifiercompiler.string_format.php" => true,
"modifiercompiler.strip.php" => true,
"modifiercompiler.strip_tags.php" => true,
"modifiercompiler.to_charset.php" => true,
"modifiercompiler.unescape.php" => true,
"modifiercompiler.upper.php" => true,
"modifiercompiler.wordwrap.php" => true,
"outputfilter.trimwhitespace.php" => true,
"shared.escape_special_chars.php" => true,
"shared.literal_compiler_param.php" => true,
"shared.make_timestamp.php" => true,
"shared.mb_str_replace.php" => true,
"shared.mb_unicode.php" => true,
"shared.mb_wordwrap.php" => true,
"variablefilter.htmlspecialchars.php" => true,
);
$iterator = new DirectoryIterator($source);
foreach ($iterator as $file) {
if (!$file->isDot()) {
$filename = $file->getFilename();
if (isset($expected[$filename])) {
unset($expected[$filename]);
}
}
}
if ($expected) {
$status = false;
$message = "FAILED: files missing from libs/plugins: " . join(', ', array_keys($expected));
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['plugins'] = $message;
}
} elseif ($errors === null) {
echo "... OK\n";
}
} else {
$status = false;
$message = "FAILED: " . SMARTY_PLUGINS_DIR . ' is not a directory';
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['plugins_dir_constant'] = $message;
}
}
if ($errors === null) {
echo "Tests complete.\n";
echo "</PRE>\n";
}
return $status;
}
}

View File

@@ -1,912 +0,0 @@
<?php
/**
* Smarty Resource Plugin
*
* @package Smarty
* @subpackage TemplateResources
* @author Rodney Rehm
*/
/**
* Smarty Resource Plugin
* Base implementation for resource plugins
*
* @package Smarty
* @subpackage TemplateResources
*/
abstract class Smarty_Resource
{
/**
* cache for Smarty_Template_Source instances
*
* @var array
*/
public static $sources = array();
/**
* cache for Smarty_Template_Compiled instances
*
* @var array
*/
public static $compileds = array();
/**
* cache for Smarty_Resource instances
*
* @var array
*/
public static $resources = array();
/**
* resource types provided by the core
*
* @var array
*/
protected static $sysplugins = array(
'file' => true,
'string' => true,
'extends' => true,
'stream' => true,
'eval' => true,
'php' => true
);
/**
* Name of the Class to compile this resource's contents with
*
* @var string
*/
public $compiler_class = 'Smarty_Internal_SmartyTemplateCompiler';
/**
* Name of the Class to tokenize this resource's contents with
*
* @var string
*/
public $template_lexer_class = 'Smarty_Internal_Templatelexer';
/**
* Name of the Class to parse this resource's contents with
*
* @var string
*/
public $template_parser_class = 'Smarty_Internal_Templateparser';
/**
* Load template's source into current template object
* {@internal The loaded source is assigned to $_template->source->content directly.}}
*
* @param Smarty_Template_Source $source source object
*
* @return string template source
* @throws SmartyException if source cannot be loaded
*/
abstract public function getContent(Smarty_Template_Source $source);
/**
* populate Source Object with meta data from Resource
*
* @param Smarty_Template_Source $source source object
* @param Smarty_Internal_Template $_template template object
*/
abstract public function populate(Smarty_Template_Source $source, Smarty_Internal_Template $_template = null);
/**
* populate Source Object with timestamp and exists from Resource
*
* @param Smarty_Template_Source $source source object
*/
public function populateTimestamp(Smarty_Template_Source $source)
{
// intentionally left blank
}
/**
* modify resource_name according to resource handlers specifications
*
* @param Smarty $smarty Smarty instance
* @param string $resource_name resource_name to make unique
* @param boolean $is_config flag for config resource
*
* @return string unique resource name
*/
protected function buildUniqueResourceName(Smarty $smarty, $resource_name, $is_config = false)
{
if ($is_config) {
return get_class($this) . '#' . $smarty->joined_config_dir . '#' . $resource_name;
} else {
return get_class($this) . '#' . $smarty->joined_template_dir . '#' . $resource_name;
}
}
/**
* populate Compiled Object with compiled filepath
*
* @param Smarty_Template_Compiled $compiled compiled object
* @param Smarty_Internal_Template $_template template object
*/
public function populateCompiledFilepath(Smarty_Template_Compiled $compiled, Smarty_Internal_Template $_template)
{
$_compile_id = isset($_template->compile_id) ? preg_replace('![^\w\|]+!', '_', $_template->compile_id) : null;
$_filepath = $compiled->source->uid;
// if use_sub_dirs, break file into directories
if ($_template->smarty->use_sub_dirs) {
$_filepath = substr($_filepath, 0, 2) . DS
. substr($_filepath, 2, 2) . DS
. substr($_filepath, 4, 2) . DS
. $_filepath;
}
$_compile_dir_sep = $_template->smarty->use_sub_dirs ? DS : '^';
if (isset($_compile_id)) {
$_filepath = $_compile_id . $_compile_dir_sep . $_filepath;
}
// caching token
if ($_template->caching) {
$_cache = '.cache';
} else {
$_cache = '';
}
$_compile_dir = $_template->smarty->getCompileDir();
// set basename if not specified
$_basename = $this->getBasename($compiled->source);
if ($_basename === null) {
$_basename = basename(preg_replace('![^\w\/]+!', '_', $compiled->source->name));
}
// separate (optional) basename by dot
if ($_basename) {
$_basename = '.' . $_basename;
}
$compiled->filepath = $_compile_dir . $_filepath . '.' . $compiled->source->type . $_basename . $_cache . '.php';
}
/**
* Normalize Paths "foo/../bar" to "bar"
*
* @param string $_path path to normalize
* @param boolean $ds respect windows directory separator
*
* @return string normalized path
*/
protected function normalizePath($_path, $ds = true)
{
if ($ds) {
// don't we all just love windows?
$_path = str_replace('\\', '/', $_path);
}
$offset = 0;
// resolve simples
$_path = preg_replace('#/\./(\./)*#', '/', $_path);
// resolve parents
while (true) {
$_parent = strpos($_path, '/../', $offset);
if (!$_parent) {
break;
} elseif ($_path[$_parent - 1] === '.') {
$offset = $_parent + 3;
continue;
}
$_pos = strrpos($_path, '/', $_parent - strlen($_path) - 1);
if ($_pos === false) {
// don't we all just love windows?
$_pos = $_parent;
}
$_path = substr_replace($_path, '', $_pos, $_parent + 3 - $_pos);
}
if ($ds && DS != '/') {
// don't we all just love windows?
$_path = str_replace('/', '\\', $_path);
}
return $_path;
}
/**
* build template filepath by traversing the template_dir array
*
* @param Smarty_Template_Source $source source object
* @param Smarty_Internal_Template $_template template object
*
* @return string fully qualified filepath
* @throws SmartyException if default template handler is registered but not callable
*/
protected function buildFilepath(Smarty_Template_Source $source, Smarty_Internal_Template $_template = null)
{
$file = $source->name;
if ($source instanceof Smarty_Config_Source) {
$_directories = $source->smarty->getConfigDir();
$_default_handler = $source->smarty->default_config_handler_func;
} else {
$_directories = $source->smarty->getTemplateDir();
$_default_handler = $source->smarty->default_template_handler_func;
}
// go relative to a given template?
$_file_is_dotted = $file[0] == '.' && ($file[1] == '.' || $file[1] == '/' || $file[1] == "\\");
if ($_template && $_template->parent instanceof Smarty_Internal_Template && $_file_is_dotted) {
if ($_template->parent->source->type != 'file' && $_template->parent->source->type != 'extends' && !$_template->parent->allow_relative_path) {
throw new SmartyException("Template '{$file}' cannot be relative to template of resource type '{$_template->parent->source->type}'");
}
$file = dirname($_template->parent->source->filepath) . DS . $file;
$_file_exact_match = true;
if (!preg_match('/^([\/\\\\]|[a-zA-Z]:[\/\\\\])/', $file)) {
// the path gained from the parent template is relative to the current working directory
// as expansions (like include_path) have already been done
$file = getcwd() . DS . $file;
}
}
// resolve relative path
if (!preg_match('/^([\/\\\\]|[a-zA-Z]:[\/\\\\])/', $file)) {
// don't we all just love windows?
$_path = DS . trim($file, '/');
$_was_relative = true;
} else {
// don't we all just love windows?
$_path = str_replace('\\', '/', $file);
}
$_path = $this->normalizePath($_path, false);
if (DS != '/') {
// don't we all just love windows?
$_path = str_replace('/', '\\', $_path);
}
// revert to relative
if (isset($_was_relative)) {
$_path = substr($_path, 1);
}
// this is only required for directories
$file = rtrim($_path, '/\\');
// files relative to a template only get one shot
if (isset($_file_exact_match)) {
return $this->fileExists($source, $file) ? $file : false;
}
// template_dir index?
if (preg_match('#^\[(?P<key>[^\]]+)\](?P<file>.+)$#', $file, $match)) {
$_directory = null;
// try string indexes
if (isset($_directories[$match['key']])) {
$_directory = $_directories[$match['key']];
} elseif (is_numeric($match['key'])) {
// try numeric index
$match['key'] = (int) $match['key'];
if (isset($_directories[$match['key']])) {
$_directory = $_directories[$match['key']];
} else {
// try at location index
$keys = array_keys($_directories);
$_directory = $_directories[$keys[$match['key']]];
}
}
if ($_directory) {
$_file = substr($file, strpos($file, ']') + 1);
$_filepath = $_directory . $_file;
if ($this->fileExists($source, $_filepath)) {
return $_filepath;
}
}
}
$_stream_resolve_include_path = function_exists('stream_resolve_include_path');
// relative file name?
if (!preg_match('/^([\/\\\\]|[a-zA-Z]:[\/\\\\])/', $file)) {
foreach ($_directories as $_directory) {
$_filepath = $_directory . $file;
if ($this->fileExists($source, $_filepath)) {
return $this->normalizePath($_filepath);
}
if ($source->smarty->use_include_path && !preg_match('/^([\/\\\\]|[a-zA-Z]:[\/\\\\])/', $_directory)) {
// try PHP include_path
if ($_stream_resolve_include_path) {
$_filepath = stream_resolve_include_path($_filepath);
} else {
$_filepath = Smarty_Internal_Get_Include_Path::getIncludePath($_filepath);
}
if ($_filepath !== false) {
if ($this->fileExists($source, $_filepath)) {
return $this->normalizePath($_filepath);
}
}
}
}
}
// try absolute filepath
if ($this->fileExists($source, $file)) {
return $file;
}
// no tpl file found
if ($_default_handler) {
if (!is_callable($_default_handler)) {
if ($source instanceof Smarty_Config_Source) {
throw new SmartyException("Default config handler not callable");
} else {
throw new SmartyException("Default template handler not callable");
}
}
$_return = call_user_func_array($_default_handler,
array($source->type, $source->name, &$_content, &$_timestamp, $source->smarty));
if (is_string($_return)) {
$source->timestamp = @filemtime($_return);
$source->exists = !!$source->timestamp;
return $_return;
} elseif ($_return === true) {
$source->content = $_content;
$source->timestamp = $_timestamp;
$source->exists = true;
return $_filepath;
}
}
// give up
return false;
}
/**
* test is file exists and save timestamp
*
* @param Smarty_Template_Source $source source object
* @param string $file file name
*
* @return bool true if file exists
*/
protected function fileExists(Smarty_Template_Source $source, $file)
{
$source->timestamp = is_file($file) ? @filemtime($file) : false;
return $source->exists = !!$source->timestamp;
}
/**
* Determine basename for compiled filename
*
* @param Smarty_Template_Source $source source object
*
* @return string resource's basename
*/
protected function getBasename(Smarty_Template_Source $source)
{
return null;
}
/**
* Load Resource Handler
*
* @param Smarty $smarty smarty object
* @param string $type name of the resource
*
* @throws SmartyException
* @return Smarty_Resource Resource Handler
*/
public static function load(Smarty $smarty, $type)
{
// try smarty's cache
if (isset($smarty->_resource_handlers[$type])) {
return $smarty->_resource_handlers[$type];
}
// try registered resource
if (isset($smarty->registered_resources[$type])) {
if ($smarty->registered_resources[$type] instanceof Smarty_Resource) {
$smarty->_resource_handlers[$type] = $smarty->registered_resources[$type];
// note registered to smarty is not kept unique!
return $smarty->_resource_handlers[$type];
}
if (!isset(self::$resources['registered'])) {
self::$resources['registered'] = new Smarty_Internal_Resource_Registered();
}
if (!isset($smarty->_resource_handlers[$type])) {
$smarty->_resource_handlers[$type] = self::$resources['registered'];
}
return $smarty->_resource_handlers[$type];
}
// try sysplugins dir
if (isset(self::$sysplugins[$type])) {
if (!isset(self::$resources[$type])) {
$_resource_class = 'Smarty_Internal_Resource_' . ucfirst($type);
self::$resources[$type] = new $_resource_class();
}
return $smarty->_resource_handlers[$type] = self::$resources[$type];
}
// try plugins dir
$_resource_class = 'Smarty_Resource_' . ucfirst($type);
if ($smarty->loadPlugin($_resource_class)) {
if (isset(self::$resources[$type])) {
return $smarty->_resource_handlers[$type] = self::$resources[$type];
}
if (class_exists($_resource_class, false)) {
self::$resources[$type] = new $_resource_class();
return $smarty->_resource_handlers[$type] = self::$resources[$type];
} else {
$smarty->registerResource($type, array(
"smarty_resource_{$type}_source",
"smarty_resource_{$type}_timestamp",
"smarty_resource_{$type}_secure",
"smarty_resource_{$type}_trusted"
));
// give it another try, now that the resource is registered properly
return self::load($smarty, $type);
}
}
// try streams
$_known_stream = stream_get_wrappers();
if (in_array($type, $_known_stream)) {
// is known stream
if (is_object($smarty->security_policy)) {
$smarty->security_policy->isTrustedStream($type);
}
if (!isset(self::$resources['stream'])) {
self::$resources['stream'] = new Smarty_Internal_Resource_Stream();
}
return $smarty->_resource_handlers[$type] = self::$resources['stream'];
}
// TODO: try default_(template|config)_handler
// give up
throw new SmartyException("Unknown resource type '{$type}'");
}
/**
* extract resource_type and resource_name from template_resource and config_resource
* @note "C:/foo.tpl" was forced to file resource up till Smarty 3.1.3 (including).
*
* @param string $resource_name template_resource or config_resource to parse
* @param string $default_resource the default resource_type defined in $smarty
* @param string &$name the parsed resource name
* @param string &$type the parsed resource type
*
* @return void
*/
protected static function parseResourceName($resource_name, $default_resource, &$name, &$type)
{
$parts = explode(':', $resource_name, 2);
if (!isset($parts[1]) || !isset($parts[0][1])) {
// no resource given, use default
// or single character before the colon is not a resource type, but part of the filepath
$type = $default_resource;
$name = $resource_name;
} else {
$type = $parts[0];
$name = $parts[1];
}
}
/**
* modify resource_name according to resource handlers specifications
*
* @param Smarty $smarty Smarty instance
* @param string $resource_name resource_name to make unique
*
* @return string unique resource name
*/
/**
* modify template_resource according to resource handlers specifications
*
* @param Smarty_Internal_template $template Smarty instance
* @param string $template_resource template_resource to extract resource handler and name of
*
* @return string unique resource name
*/
public static function getUniqueTemplateName($template, $template_resource)
{
self::parseResourceName($template_resource, $template->smarty->default_resource_type, $name, $type);
// TODO: optimize for Smarty's internal resource types
$resource = Smarty_Resource::load($template->smarty, $type);
// go relative to a given template?
$_file_is_dotted = $name[0] == '.' && ($name[1] == '.' || $name[1] == '/' || $name[1] == "\\");
if ($template instanceof Smarty_Internal_Template && $_file_is_dotted && ($template->source->type == 'file' || $template->parent->source->type == 'extends')) {
$name = dirname($template->source->filepath) . DS . $name;
}
return $resource->buildUniqueResourceName($template->smarty, $name);
}
/**
* initialize Source Object for given resource
* Either [$_template] or [$smarty, $template_resource] must be specified
*
* @param Smarty_Internal_Template $_template template object
* @param Smarty $smarty smarty object
* @param string $template_resource resource identifier
*
* @return Smarty_Template_Source Source Object
*/
public static function source(Smarty_Internal_Template $_template = null, Smarty $smarty = null, $template_resource = null)
{
if ($_template) {
$smarty = $_template->smarty;
$template_resource = $_template->template_resource;
}
// parse resource_name, load resource handler, identify unique resource name
self::parseResourceName($template_resource, $smarty->default_resource_type, $name, $type);
$resource = Smarty_Resource::load($smarty, $type);
// go relative to a given template?
$_file_is_dotted = isset($name[0]) && $name[0] == '.' && ($name[1] == '.' || $name[1] == '/' || $name[1] == "\\");
if ($_file_is_dotted && isset($_template) && $_template->parent instanceof Smarty_Internal_Template && ($_template->parent->source->type == 'file' || $_template->parent->source->type == 'extends')) {
$name2 = dirname($_template->parent->source->filepath) . DS . $name;
} else {
$name2 = $name;
}
$unique_resource_name = $resource->buildUniqueResourceName($smarty, $name2);
// check runtime cache
$_cache_key = 'template|' . $unique_resource_name;
if ($smarty->compile_id) {
$_cache_key .= '|' . $smarty->compile_id;
}
if (isset(self::$sources[$_cache_key])) {
return self::$sources[$_cache_key];
}
// create source
$source = new Smarty_Template_Source($resource, $smarty, $template_resource, $type, $name, $unique_resource_name);
$resource->populate($source, $_template);
// runtime cache
self::$sources[$_cache_key] = $source;
return $source;
}
/**
* initialize Config Source Object for given resource
*
* @param Smarty_Internal_Config $_config config object
*
* @throws SmartyException
* @return Smarty_Config_Source Source Object
*/
public static function config(Smarty_Internal_Config $_config)
{
static $_incompatible_resources = array('eval' => true, 'string' => true, 'extends' => true, 'php' => true);
$config_resource = $_config->config_resource;
$smarty = $_config->smarty;
// parse resource_name
self::parseResourceName($config_resource, $smarty->default_config_type, $name, $type);
// make sure configs are not loaded via anything smarty can't handle
if (isset($_incompatible_resources[$type])) {
throw new SmartyException ("Unable to use resource '{$type}' for config");
}
// load resource handler, identify unique resource name
$resource = Smarty_Resource::load($smarty, $type);
$unique_resource_name = $resource->buildUniqueResourceName($smarty, $name, true);
// check runtime cache
$_cache_key = 'config|' . $unique_resource_name;
if (isset(self::$sources[$_cache_key])) {
return self::$sources[$_cache_key];
}
// create source
$source = new Smarty_Config_Source($resource, $smarty, $config_resource, $type, $name, $unique_resource_name);
$resource->populate($source, null);
// runtime cache
self::$sources[$_cache_key] = $source;
return $source;
}
}
/**
* Smarty Resource Data Object
* Meta Data Container for Template Files
*
* @package Smarty
* @subpackage TemplateResources
* @author Rodney Rehm
* @property integer $timestamp Source Timestamp
* @property boolean $exists Source Existence
* @property boolean $template Extended Template reference
* @property string $content Source Content
*/
class Smarty_Template_Source
{
/**
* Name of the Class to compile this resource's contents with
*
* @var string
*/
public $compiler_class = null;
/**
* Name of the Class to tokenize this resource's contents with
*
* @var string
*/
public $template_lexer_class = null;
/**
* Name of the Class to parse this resource's contents with
*
* @var string
*/
public $template_parser_class = null;
/**
* Unique Template ID
*
* @var string
*/
public $uid = null;
/**
* Template Resource (Smarty_Internal_Template::$template_resource)
*
* @var string
*/
public $resource = null;
/**
* Resource Type
*
* @var string
*/
public $type = null;
/**
* Resource Name
*
* @var string
*/
public $name = null;
/**
* Unique Resource Name
*
* @var string
*/
public $unique_resource = null;
/**
* Source Filepath
*
* @var string
*/
public $filepath = null;
/**
* Source is bypassing compiler
*
* @var boolean
*/
public $uncompiled = null;
/**
* Source must be recompiled on every occasion
*
* @var boolean
*/
public $recompiled = null;
/**
* The Components an extended template is made of
*
* @var array
*/
public $components = null;
/**
* Resource Handler
*
* @var Smarty_Resource
*/
public $handler = null;
/**
* Smarty instance
*
* @var Smarty
*/
public $smarty = null;
/**
* create Source Object container
*
* @param Smarty_Resource $handler Resource Handler this source object communicates with
* @param Smarty $smarty Smarty instance this source object belongs to
* @param string $resource full template_resource
* @param string $type type of resource
* @param string $name resource name
* @param string $unique_resource unique resource name
*/
public function __construct(Smarty_Resource $handler, Smarty $smarty, $resource, $type, $name, $unique_resource)
{
$this->handler = $handler; // Note: prone to circular references
$this->compiler_class = $handler->compiler_class;
$this->template_lexer_class = $handler->template_lexer_class;
$this->template_parser_class = $handler->template_parser_class;
$this->uncompiled = $this->handler instanceof Smarty_Resource_Uncompiled;
$this->recompiled = $this->handler instanceof Smarty_Resource_Recompiled;
$this->smarty = $smarty;
$this->resource = $resource;
$this->type = $type;
$this->name = $name;
$this->unique_resource = $unique_resource;
}
/**
* get a Compiled Object of this source
*
* @param Smarty_Internal_Template|Smarty_Internal_Config $_template template object
*
* @return Smarty_Template_Compiled compiled object
*/
public function getCompiled($_template)
{
// check runtime cache
$_cache_key = $this->unique_resource . '#' . $_template->compile_id;
if (isset(Smarty_Resource::$compileds[$_cache_key])) {
return Smarty_Resource::$compileds[$_cache_key];
}
$compiled = new Smarty_Template_Compiled($this);
$this->handler->populateCompiledFilepath($compiled, $_template);
$compiled->timestamp = @filemtime($compiled->filepath);
$compiled->exists = !!$compiled->timestamp;
// runtime cache
Smarty_Resource::$compileds[$_cache_key] = $compiled;
return $compiled;
}
/**
* render the uncompiled source
*
* @param Smarty_Internal_Template $_template template object
*/
public function renderUncompiled(Smarty_Internal_Template $_template)
{
return $this->handler->renderUncompiled($this, $_template);
}
/**
* <<magic>> Generic Setter.
*
* @param string $property_name valid: timestamp, exists, content, template
* @param mixed $value new value (is not checked)
*
* @throws SmartyException if $property_name is not valid
*/
public function __set($property_name, $value)
{
switch ($property_name) {
// regular attributes
case 'timestamp':
case 'exists':
case 'content':
// required for extends: only
case 'template':
$this->$property_name = $value;
break;
default:
throw new SmartyException("invalid source property '$property_name'.");
}
}
/**
* <<magic>> Generic getter.
*
* @param string $property_name valid: timestamp, exists, content
*
* @return mixed
* @throws SmartyException if $property_name is not valid
*/
public function __get($property_name)
{
switch ($property_name) {
case 'timestamp':
case 'exists':
$this->handler->populateTimestamp($this);
return $this->$property_name;
case 'content':
return $this->content = $this->handler->getContent($this);
default:
throw new SmartyException("source property '$property_name' does not exist.");
}
}
}
/**
* Smarty Resource Data Object
* Meta Data Container for Template Files
*
* @package Smarty
* @subpackage TemplateResources
* @author Rodney Rehm
* @property string $content compiled content
*/
class Smarty_Template_Compiled
{
/**
* Compiled Filepath
*
* @var string
*/
public $filepath = null;
/**
* Compiled Timestamp
*
* @var integer
*/
public $timestamp = null;
/**
* Compiled Existence
*
* @var boolean
*/
public $exists = false;
/**
* Compiled Content Loaded
*
* @var boolean
*/
public $loaded = false;
/**
* Template was compiled
*
* @var boolean
*/
public $isCompiled = false;
/**
* Source Object
*
* @var Smarty_Template_Source
*/
public $source = null;
/**
* Metadata properties
* populated by Smarty_Internal_Template::decodeProperties()
*
* @var array
*/
public $_properties = null;
/**
* create Compiled Object container
*
* @param Smarty_Template_Source $source source object this compiled object belongs to
*/
public function __construct(Smarty_Template_Source $source)
{
$this->source = $source;
}
}

View File

@@ -1,33 +0,0 @@
<?php
/**
* Smarty Resource Plugin
*
* @package Smarty
* @subpackage TemplateResources
* @author Rodney Rehm
*/
/**
* Smarty Resource Plugin
* Base implementation for resource plugins that don't compile cache
*
* @package Smarty
* @subpackage TemplateResources
*/
abstract class Smarty_Resource_Recompiled extends Smarty_Resource
{
/**
* populate Compiled Object with compiled filepath
*
* @param Smarty_Template_Compiled $compiled compiled object
* @param Smarty_Internal_Template $_template template object
*
* @return void
*/
public function populateCompiledFilepath(Smarty_Template_Compiled $compiled, Smarty_Internal_Template $_template)
{
$compiled->filepath = false;
$compiled->timestamp = false;
$compiled->exists = false;
}
}

View File

@@ -1,480 +0,0 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage Security
* @author Uwe Tews
*/
/*
* FIXME: Smarty_Security API
* - getter and setter instead of public properties would allow cultivating an internal cache properly
* - current implementation of isTrustedResourceDir() assumes that Smarty::$template_dir and Smarty::$config_dir are immutable
* the cache is killed every time either of the variables change. That means that two distinct Smarty objects with differing
* $template_dir or $config_dir should NOT share the same Smarty_Security instance,
* as this would lead to (severe) performance penalty! how should this be handled?
*/
/**
* This class does contain the security settings
*/
class Smarty_Security
{
/**
* This determines how Smarty handles "<?php ... ?>" tags in templates.
* possible values:
* <ul>
* <li>Smarty::PHP_PASSTHRU -> echo PHP tags as they are</li>
* <li>Smarty::PHP_QUOTE -> escape tags as entities</li>
* <li>Smarty::PHP_REMOVE -> remove php tags</li>
* <li>Smarty::PHP_ALLOW -> execute php tags</li>
* </ul>
*
* @var integer
*/
public $php_handling = Smarty::PHP_PASSTHRU;
/**
* This is the list of template directories that are considered secure.
* $template_dir is in this list implicitly.
*
* @var array
*/
public $secure_dir = array();
/**
* This is an array of directories where trusted php scripts reside.
* {@link $security} is disabled during their inclusion/execution.
*
* @var array
*/
public $trusted_dir = array();
/**
* List of regular expressions (PCRE) that include trusted URIs
*
* @var array
*/
public $trusted_uri = array();
/**
* This is an array of trusted static classes.
* If empty access to all static classes is allowed.
* If set to 'none' none is allowed.
*
* @var array
*/
public $static_classes = array();
/**
* This is an array of trusted PHP functions.
* If empty all functions are allowed.
* To disable all PHP functions set $php_functions = null.
*
* @var array
*/
public $php_functions = array(
'isset', 'empty',
'count', 'sizeof',
'in_array', 'is_array',
'time',
'nl2br',
);
/**
* This is an array of trusted PHP modifiers.
* If empty all modifiers are allowed.
* To disable all modifier set $php_modifiers = null.
*
* @var array
*/
public $php_modifiers = array(
'escape',
'count'
);
/**
* This is an array of allowed tags.
* If empty no restriction by allowed_tags.
*
* @var array
*/
public $allowed_tags = array();
/**
* This is an array of disabled tags.
* If empty no restriction by disabled_tags.
*
* @var array
*/
public $disabled_tags = array();
/**
* This is an array of allowed modifier plugins.
* If empty no restriction by allowed_modifiers.
*
* @var array
*/
public $allowed_modifiers = array();
/**
* This is an array of disabled modifier plugins.
* If empty no restriction by disabled_modifiers.
*
* @var array
*/
public $disabled_modifiers = array();
/**
* This is an array of trusted streams.
* If empty all streams are allowed.
* To disable all streams set $streams = null.
*
* @var array
*/
public $streams = array('file');
/**
* + flag if constants can be accessed from template
*
* @var boolean
*/
public $allow_constants = true;
/**
* + flag if super globals can be accessed from template
*
* @var boolean
*/
public $allow_super_globals = true;
/**
* Cache for $resource_dir lookup
*
* @var array
*/
protected $_resource_dir = null;
/**
* Cache for $template_dir lookup
*
* @var array
*/
protected $_template_dir = null;
/**
* Cache for $config_dir lookup
*
* @var array
*/
protected $_config_dir = null;
/**
* Cache for $secure_dir lookup
*
* @var array
*/
protected $_secure_dir = null;
/**
* Cache for $php_resource_dir lookup
*
* @var array
*/
protected $_php_resource_dir = null;
/**
* Cache for $trusted_dir lookup
*
* @var array
*/
protected $_trusted_dir = null;
/**
* @param Smarty $smarty
*/
public function __construct($smarty)
{
$this->smarty = $smarty;
}
/**
* Check if PHP function is trusted.
*
* @param string $function_name
* @param object $compiler compiler object
*
* @return boolean true if function is trusted
* @throws SmartyCompilerException if php function is not trusted
*/
public function isTrustedPhpFunction($function_name, $compiler)
{
if (isset($this->php_functions) && (empty($this->php_functions) || in_array($function_name, $this->php_functions))) {
return true;
}
$compiler->trigger_template_error("PHP function '{$function_name}' not allowed by security setting");
return false; // should not, but who knows what happens to the compiler in the future?
}
/**
* Check if static class is trusted.
*
* @param string $class_name
* @param object $compiler compiler object
*
* @return boolean true if class is trusted
* @throws SmartyCompilerException if static class is not trusted
*/
public function isTrustedStaticClass($class_name, $compiler)
{
if (isset($this->static_classes) && (empty($this->static_classes) || in_array($class_name, $this->static_classes))) {
return true;
}
$compiler->trigger_template_error("access to static class '{$class_name}' not allowed by security setting");
return false; // should not, but who knows what happens to the compiler in the future?
}
/**
* Check if PHP modifier is trusted.
*
* @param string $modifier_name
* @param object $compiler compiler object
*
* @return boolean true if modifier is trusted
* @throws SmartyCompilerException if modifier is not trusted
*/
public function isTrustedPhpModifier($modifier_name, $compiler)
{
if (isset($this->php_modifiers) && (empty($this->php_modifiers) || in_array($modifier_name, $this->php_modifiers))) {
return true;
}
$compiler->trigger_template_error("modifier '{$modifier_name}' not allowed by security setting");
return false; // should not, but who knows what happens to the compiler in the future?
}
/**
* Check if tag is trusted.
*
* @param string $tag_name
* @param object $compiler compiler object
*
* @return boolean true if tag is trusted
* @throws SmartyCompilerException if modifier is not trusted
*/
public function isTrustedTag($tag_name, $compiler)
{
// check for internal always required tags
if (in_array($tag_name, array('assign', 'call', 'private_filter', 'private_block_plugin', 'private_function_plugin', 'private_object_block_function',
'private_object_function', 'private_registered_function', 'private_registered_block', 'private_special_variable', 'private_print_expression', 'private_modifier'))
) {
return true;
}
// check security settings
if (empty($this->allowed_tags)) {
if (empty($this->disabled_tags) || !in_array($tag_name, $this->disabled_tags)) {
return true;
} else {
$compiler->trigger_template_error("tag '{$tag_name}' disabled by security setting", $compiler->lex->taglineno);
}
} elseif (in_array($tag_name, $this->allowed_tags) && !in_array($tag_name, $this->disabled_tags)) {
return true;
} else {
$compiler->trigger_template_error("tag '{$tag_name}' not allowed by security setting", $compiler->lex->taglineno);
}
return false; // should not, but who knows what happens to the compiler in the future?
}
/**
* Check if modifier plugin is trusted.
*
* @param string $modifier_name
* @param object $compiler compiler object
*
* @return boolean true if tag is trusted
* @throws SmartyCompilerException if modifier is not trusted
*/
public function isTrustedModifier($modifier_name, $compiler)
{
// check for internal always allowed modifier
if (in_array($modifier_name, array('default'))) {
return true;
}
// check security settings
if (empty($this->allowed_modifiers)) {
if (empty($this->disabled_modifiers) || !in_array($modifier_name, $this->disabled_modifiers)) {
return true;
} else {
$compiler->trigger_template_error("modifier '{$modifier_name}' disabled by security setting", $compiler->lex->taglineno);
}
} elseif (in_array($modifier_name, $this->allowed_modifiers) && !in_array($modifier_name, $this->disabled_modifiers)) {
return true;
} else {
$compiler->trigger_template_error("modifier '{$modifier_name}' not allowed by security setting", $compiler->lex->taglineno);
}
return false; // should not, but who knows what happens to the compiler in the future?
}
/**
* Check if stream is trusted.
*
* @param string $stream_name
*
* @return boolean true if stream is trusted
* @throws SmartyException if stream is not trusted
*/
public function isTrustedStream($stream_name)
{
if (isset($this->streams) && (empty($this->streams) || in_array($stream_name, $this->streams))) {
return true;
}
throw new SmartyException("stream '{$stream_name}' not allowed by security setting");
}
/**
* Check if directory of file resource is trusted.
*
* @param string $filepath
*
* @return boolean true if directory is trusted
* @throws SmartyException if directory is not trusted
*/
public function isTrustedResourceDir($filepath)
{
$_template = false;
$_config = false;
$_secure = false;
$_template_dir = $this->smarty->getTemplateDir();
$_config_dir = $this->smarty->getConfigDir();
// check if index is outdated
if ((!$this->_template_dir || $this->_template_dir !== $_template_dir)
|| (!$this->_config_dir || $this->_config_dir !== $_config_dir)
|| (!empty($this->secure_dir) && (!$this->_secure_dir || $this->_secure_dir !== $this->secure_dir))
) {
$this->_resource_dir = array();
$_template = true;
$_config = true;
$_secure = !empty($this->secure_dir);
}
// rebuild template dir index
if ($_template) {
$this->_template_dir = $_template_dir;
foreach ($_template_dir as $directory) {
$directory = realpath($directory);
$this->_resource_dir[$directory] = true;
}
}
// rebuild config dir index
if ($_config) {
$this->_config_dir = $_config_dir;
foreach ($_config_dir as $directory) {
$directory = realpath($directory);
$this->_resource_dir[$directory] = true;
}
}
// rebuild secure dir index
if ($_secure) {
$this->_secure_dir = $this->secure_dir;
foreach ((array) $this->secure_dir as $directory) {
$directory = realpath($directory);
$this->_resource_dir[$directory] = true;
}
}
$_filepath = realpath($filepath);
$directory = dirname($_filepath);
$_directory = array();
while (true) {
// remember the directory to add it to _resource_dir in case we're successful
$_directory[$directory] = true;
// test if the directory is trusted
if (isset($this->_resource_dir[$directory])) {
// merge sub directories of current $directory into _resource_dir to speed up subsequent lookup
$this->_resource_dir = array_merge($this->_resource_dir, $_directory);
return true;
}
// abort if we've reached root
if (($pos = strrpos($directory, DS)) === false || !isset($directory[1])) {
break;
}
// bubble up one level
$directory = substr($directory, 0, $pos);
}
// give up
throw new SmartyException("directory '{$_filepath}' not allowed by security setting");
}
/**
* Check if URI (e.g. {fetch} or {html_image}) is trusted
* To simplify things, isTrustedUri() resolves all input to "{$PROTOCOL}://{$HOSTNAME}".
* So "http://username:password@hello.world.example.org:8080/some-path?some=query-string"
* is reduced to "http://hello.world.example.org" prior to applying the patters from {@link $trusted_uri}.
*
* @param string $uri
*
* @return boolean true if URI is trusted
* @throws SmartyException if URI is not trusted
* @uses $trusted_uri for list of patterns to match against $uri
*/
public function isTrustedUri($uri)
{
$_uri = parse_url($uri);
if (!empty($_uri['scheme']) && !empty($_uri['host'])) {
$_uri = $_uri['scheme'] . '://' . $_uri['host'];
foreach ($this->trusted_uri as $pattern) {
if (preg_match($pattern, $_uri)) {
return true;
}
}
}
throw new SmartyException("URI '{$uri}' not allowed by security setting");
}
/**
* Check if directory of file resource is trusted.
*
* @param string $filepath
*
* @return boolean true if directory is trusted
* @throws SmartyException if PHP directory is not trusted
*/
public function isTrustedPHPDir($filepath)
{
if (empty($this->trusted_dir)) {
throw new SmartyException("directory '{$filepath}' not allowed by security setting (no trusted_dir specified)");
}
// check if index is outdated
if (!$this->_trusted_dir || $this->_trusted_dir !== $this->trusted_dir) {
$this->_php_resource_dir = array();
$this->_trusted_dir = $this->trusted_dir;
foreach ((array) $this->trusted_dir as $directory) {
$directory = realpath($directory);
$this->_php_resource_dir[$directory] = true;
}
}
$_filepath = realpath($filepath);
$directory = dirname($_filepath);
$_directory = array();
while (true) {
// remember the directory to add it to _resource_dir in case we're successful
$_directory[] = $directory;
// test if the directory is trusted
if (isset($this->_php_resource_dir[$directory])) {
// merge sub directories of current $directory into _resource_dir to speed up subsequent lookup
$this->_php_resource_dir = array_merge($this->_php_resource_dir, $_directory);
return true;
}
// abort if we've reached root
if (($pos = strrpos($directory, DS)) === false || !isset($directory[2])) {
break;
}
// bubble up one level
$directory = substr($directory, 0, $pos);
}
throw new SmartyException("directory '{$_filepath}' not allowed by security setting");
}
}

View File

@@ -4,8 +4,9 @@
$PRINT_ALL = 1; $PRINT_ALL = 1;
$DB_DEBUG = 1; $DB_DEBUG = 1;
if ($DEBUG_ALL) if ($DEBUG_ALL) {
error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR);
}
define('USE_DATABASE', true); define('USE_DATABASE', true);
// sample config // sample config
@@ -15,8 +16,9 @@
// session_name(EDIT_SESSION_NAME); // session_name(EDIT_SESSION_NAME);
// session_start(); // session_start();
// basic class test file // basic class test file
foreach (array ('Login', 'Admin.Backend') as $class) foreach (array ('Login', 'Admin.Backend') as $class) {
_spl_autoload('Class.'.$class.'.inc'); _spl_autoload('Class.'.$class.'.inc');
}
$lang = 'en_utf8'; $lang = 'en_utf8';
@@ -31,10 +33,11 @@
$edit_access_id = 3; $edit_access_id = 3;
print "ACL UNIT: ".print_r(array_keys($login->acl['unit']), 1)."<br>"; print "ACL UNIT: ".print_r(array_keys($login->acl['unit']), 1)."<br>";
print "ACCESS CHECK: ".$login->login_check_edit_access($edit_access_id)."<br>"; print "ACCESS CHECK: ".$login->login_check_edit_access($edit_access_id)."<br>";
if ($login->login_check_edit_access($edit_access_id)) if ($login->login_check_edit_access($edit_access_id)) {
$basic->edit_access_id = $edit_access_id; $basic->edit_access_id = $edit_access_id;
else } else {
$basic->edit_access_id = $login->acl['unit_id']; $basic->edit_access_id = $login->acl['unit_id'];
}
// $basic->debug('SESSION', $basic->print_ar($_SESSION)); // $basic->debug('SESSION', $basic->print_ar($_SESSION));
@@ -69,8 +72,7 @@
// DEPRICATED CALL // DEPRICATED CALL
// $basic->adbSetACL($login->acl); // $basic->adbSetACL($login->acl);
while ($res = $basic->db_return("SELECT * FROM max_test")) while ($res = $basic->db_return("SELECT * FROM max_test")) {
{
print "TIME: ".$res['time']."<br>"; print "TIME: ".$res['time']."<br>";
} }
@@ -85,6 +87,9 @@
// $status = $basic->db_exec("INSERT INTO foo (test) values ('BAR 1 ".time()."'), ('BAR 2 ".time()."'), ('BAR 3 ".time()."') RETURNING foo_id"); // $status = $basic->db_exec("INSERT INTO foo (test) values ('BAR 1 ".time()."'), ('BAR 2 ".time()."'), ('BAR 3 ".time()."') RETURNING foo_id");
$status = $basic->db_exec("INSERT INTO foo (test) values ('BAR 1 ".time()."'), ('BAR 2 ".time()."'), ('BAR 3 ".time()."') RETURNING foo_id, test"); $status = $basic->db_exec("INSERT INTO foo (test) values ('BAR 1 ".time()."'), ('BAR 2 ".time()."'), ('BAR 3 ".time()."') RETURNING foo_id, test");
print "DIRECT MULTIPLE INSERT STATUS: $status | PRIMARY KEYS: ".print_r($basic->insert_id, 1)." | PRIMARY KEY EXT: ".print_r($basic->insert_id_ext, 1)."<br>"; print "DIRECT MULTIPLE INSERT STATUS: $status | PRIMARY KEYS: ".print_r($basic->insert_id, 1)." | PRIMARY KEY EXT: ".print_r($basic->insert_id_ext, 1)."<br>";
// no returning, but not needed ;
$status = $basic->db_exec("INSERT INTO foo (test) VALUES ('FOO; TEST ".time()."');");
print "DIRECT INSERT STATUS: $status | PRIMARY KEY: ".$basic->insert_id." | PRIMARY KEY EXT: ".print_r($basic->insert_id_ext, 1)."<br>";
# db write class test # db write class test
$table = 'foo'; $table = 'foo';
@@ -188,4 +193,3 @@
print $basic->print_error_msg(); print $basic->print_error_msg();
print "</body></html>"; print "</body></html>";
?>

View File

@@ -29,8 +29,7 @@
ob_start(); ob_start();
include("config.inc"); include("config.inc");
// overrride debug flags // overrride debug flags
if (!DEBUG) if (!DEBUG) {
{
$DEBUG_ALL = 0; $DEBUG_ALL = 0;
$PRINT_ALL = 0; $PRINT_ALL = 0;
$DB_DEBUG = 0; $DB_DEBUG = 0;
@@ -47,8 +46,9 @@
require(LIBS.'Class.Smarty.Extend.inc'); require(LIBS.'Class.Smarty.Extend.inc');
// set default lang if not set otherwise // set default lang if not set otherwise
if (!$lang) if (!$lang) {
$lang = DEFAULT_LANG; $lang = DEFAULT_LANG;
}
// should be utf8 // should be utf8
header("Content-type: text/html; charset=".DEFAULT_ENCODING); header("Content-type: text/html; charset=".DEFAULT_ENCODING);
ob_end_flush(); ob_end_flush();
@@ -57,16 +57,14 @@
// create form class // create form class
$form = new form($DB_CONFIG[MAIN_DB], $lang); $form = new form($DB_CONFIG[MAIN_DB], $lang);
$form->db_exec("SET search_path TO ".LOGIN_DB_SCHEMA); $form->db_exec("SET search_path TO ".LOGIN_DB_SCHEMA);
if ($form->mobile_phone) if ($form->mobile_phone) {
{
echo "I am sorry, but this page cannot be viewed by a mobile phone"; echo "I am sorry, but this page cannot be viewed by a mobile phone";
exit; exit;
} }
// smarty template engine (extended Translation version) // smarty template engine (extended Translation version)
$smarty = new SmartyML($lang); $smarty = new SmartyML($lang);
if (TARGET == 'live' || TARGET == 'remote') if (TARGET == 'live' || TARGET == 'remote') {
{
// login // login
$login->debug_output_all = DEBUG ? 1 : 0; $login->debug_output_all = DEBUG ? 1 : 0;
$login->echo_output_all = 0; $login->echo_output_all = 0;
@@ -78,14 +76,11 @@
} }
// set the template dir // set the template dir
// WARNING: this has a special check for the mailing tool layout (old layout) // WARNING: this has a special check for the mailing tool layout (old layout)
if (defined('LAYOUT')) if (defined('LAYOUT')) {
{
$smarty->setTemplateDir(LAYOUT.DEFAULT_TEMPLATE.TEMPLATES); $smarty->setTemplateDir(LAYOUT.DEFAULT_TEMPLATE.TEMPLATES);
$DATA['css'] = LAYOUT.DEFAULT_TEMPLATE.CSS; $DATA['css'] = LAYOUT.DEFAULT_TEMPLATE.CSS;
$DATA['js'] = LAYOUT.DEFAULT_TEMPLATE.JS; $DATA['js'] = LAYOUT.DEFAULT_TEMPLATE.JS;
} } else {
else
{
$smarty->setTemplateDir(TEMPLATES.DEFAULT_TEMPLATE); $smarty->setTemplateDir(TEMPLATES.DEFAULT_TEMPLATE);
$DATA['css'] = CSS.DEFAULT_TEMPLATE; $DATA['css'] = CSS.DEFAULT_TEMPLATE;
$DATA['js'] = JS.DEFAULT_TEMPLATE; $DATA['js'] = JS.DEFAULT_TEMPLATE;
@@ -138,10 +133,11 @@
// MENU START // MENU START
// request some session vars // request some session vars
if (!$HEADER_COLOR) if (!$HEADER_COLOR) {
$DATA['HEADER_COLOR'] = "#E0E2FF"; $DATA['HEADER_COLOR'] = "#E0E2FF";
else } else {
$DATA['HEADER_COLOR'] = $_SESSION['HEADER_COLOR']; $DATA['HEADER_COLOR'] = $_SESSION['HEADER_COLOR'];
}
$DATA['USER_NAME'] = $_SESSION["USER_NAME"]; $DATA['USER_NAME'] = $_SESSION["USER_NAME"];
$DATA['EUID'] = $_SESSION["EUID"]; $DATA['EUID'] = $_SESSION["EUID"];
$DATA['GROUP_NAME'] = $_SESSION["GROUP_NAME"]; $DATA['GROUP_NAME'] = $_SESSION["GROUP_NAME"];
@@ -151,10 +147,8 @@
//$form->debug('menu', $form->print_ar($PAGES)); //$form->debug('menu', $form->print_ar($PAGES));
// baue nav aus $PAGES ... // baue nav aus $PAGES ...
for ($i = 0; $i < count($PAGES); $i ++) for ($i = 0; $i < count($PAGES); $i ++) {
{ if ($PAGES[$i]["menu"] && $PAGES[$i]["online"]) {
if ($PAGES[$i]["menu"] && $PAGES[$i]["online"])
{
$menuarray[] = $PAGES[$i]; $menuarray[] = $PAGES[$i];
} }
} }
@@ -164,42 +158,35 @@
$SPLIT_FACTOR = 3; $SPLIT_FACTOR = 3;
$START_SPLIT_COUNT = 3; $START_SPLIT_COUNT = 3;
// WTF ?? I dunno what I am doing here ... // WTF ?? I dunno what I am doing here ...
for ($i = 9; $i < $COUNT_NAV_POINTS; $i += $START_SPLIT_COUNT) for ($i = 9; $i < $COUNT_NAV_POINTS; $i += $START_SPLIT_COUNT) {
{ if ($COUNT_NAV_POINTS > $i) {
if ($COUNT_NAV_POINTS > $i)
$SPLIT_FACTOR += 1; $SPLIT_FACTOR += 1;
} }
}
for ($i = 1; $i <= count($menuarray); $i ++) for ($i = 1; $i <= count($menuarray); $i ++) {
{
// do that for new array // do that for new array
$j = $i - 1; $j = $i - 1;
$menu_data[$j]['pagename'] = htmlentities($menuarray[($i-1)]["page_name"]); $menu_data[$j]['pagename'] = htmlentities($menuarray[($i-1)]["page_name"]);
$menu_data[$j]['filename'] = $menuarray[($i-1)]["filename"].$menuarray[($i-1)]["query_string"]; $menu_data[$j]['filename'] = $menuarray[($i-1)]["filename"].$menuarray[($i-1)]["query_string"];
if ($i == 1 || !(($i - 1) % $SPLIT_FACTOR)) if ($i == 1 || !(($i - 1) % $SPLIT_FACTOR)) {
{
$menu_data[$j]['splitfactor_in'] = 1; $menu_data[$j]['splitfactor_in'] = 1;
} }
if ($menuarray[($i - 1)]["filename"] == $form->get_page_name()) if ($menuarray[($i - 1)]["filename"] == $form->get_page_name()) {
{
$position = $i - 1; $position = $i - 1;
$menu_data[$j]['position'] = 1; $menu_data[$j]['position'] = 1;
} } else {
else
{
// add query stuff // add query stuff
// HAS TO DONE LATER ... set urlencode, etc ... // HAS TO DONE LATER ... set urlencode, etc ...
// check if popup needed // check if popup needed
if ($menuarray[($i - 1)]["popup"]) if ($menuarray[($i - 1)]["popup"]) {
{
$menu_data[$j]['popup'] = 1; $menu_data[$j]['popup'] = 1;
$menu_data[$j]['rand'] = uniqid(rand()); $menu_data[$j]['rand'] = uniqid(rand());
$menu_data[$j]['width'] = $menuarray[($i-1)]["popup_x"]; $menu_data[$j]['width'] = $menuarray[($i-1)]["popup_x"];
$menu_data[$j]['height'] = $menuarray[($i-1)]["popup_y"]; $menu_data[$j]['height'] = $menuarray[($i-1)]["popup_y"];
} // popup or not } // popup or not
} // highlight or not } // highlight or not
if (!($i % $SPLIT_FACTOR) || (($i + 1) > count($menuarray))) if (!($i % $SPLIT_FACTOR) || (($i + 1) > count($menuarray))) {
{
$menu_data[$j]['splitfactor_out'] = 1; $menu_data[$j]['splitfactor_out'] = 1;
} // split } // split
} // for } // for
@@ -213,14 +200,12 @@
$DATA['load'] = $form->form_create_load(); $DATA['load'] = $form->form_create_load();
$DATA['new'] = $form->form_create_new(); $DATA['new'] = $form->form_create_new();
// SHOW DATA PART // SHOW DATA PART
if ($form->yes) if ($form->yes) {
{
$DATA['form_yes'] = $form->yes; $DATA['form_yes'] = $form->yes;
$DATA['form_my_page_name'] = $form->my_page_name; $DATA['form_my_page_name'] = $form->my_page_name;
// depending on the "get_page_name()" I show different stuff // depending on the "get_page_name()" I show different stuff
switch ($form->my_page_name) switch ($form->my_page_name) {
{
case "edit_users": case "edit_users":
$elements[] = $form->form_create_element("login_error_count"); $elements[] = $form->form_create_element("login_error_count");
$elements[] = $form->form_create_element("login_error_date_last"); $elements[] = $form->form_create_element("login_error_date_last");
@@ -250,23 +235,20 @@
$elements[] = $form->form_create_element("template"); $elements[] = $form->form_create_element("template");
break; break;
case "edit_pages": case "edit_pages":
if (!$form->table_array["edit_page_id"]["value"]) if (!$form->table_array["edit_page_id"]["value"]) {
{
$q = "DELETE FROM temp_files"; $q = "DELETE FROM temp_files";
$form->db_exec($q); $form->db_exec($q);
// gets all files in the current dir ending with .php // gets all files in the current dir ending with .php
$crap = exec("ls *.php", $output, $status); $crap = exec("ls *.php", $output, $status);
// now get all that are NOT in de DB // now get all that are NOT in de DB
$q = "INSERT INTO temp_files VALUES "; $q = "INSERT INTO temp_files VALUES ";
for ($i = 0; $i < count($output); $i ++) for ($i = 0; $i < count($output); $i ++) {
{
$t_q = "('".$form->db_escape_string($output[$i])."')"; $t_q = "('".$form->db_escape_string($output[$i])."')";
$form->db_exec($q.$t_q, 'NULL'); $form->db_exec($q.$t_q, 'NULL');
} }
$elements[] = $form->form_create_element("filename"); $elements[] = $form->form_create_element("filename");
} } else {
else // show file menu // show file menu
{
// just show name of file ... // just show name of file ...
$DATA['filename_exist'] = 1; $DATA['filename_exist'] = 1;
$DATA['filename'] = $form->table_array["filename"]["value"]; $DATA['filename'] = $form->table_array["filename"]["value"];
@@ -313,9 +295,8 @@
// add name/value list here // add name/value list here
$elements[] = $form->form_show_list_table("edit_access_data"); $elements[] = $form->form_show_list_table("edit_access_data");
break; break;
break;
default: default:
print "NO NO NOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO!"; print "[No valid page definition given]";
break; break;
} }
// $form->debug('edit', "Elements: <pre>".$form->print_ar($elements)); // $form->debug('edit', "Elements: <pre>".$form->print_ar($elements));
@@ -330,8 +311,7 @@
// create main data array // create main data array
$CONTENT_DATA = array_merge($HEADER, $DATA, $DEBUG_DATA); $CONTENT_DATA = array_merge($HEADER, $DATA, $DEBUG_DATA);
// data is 1:1 mapping (all vars, values, etc) // data is 1:1 mapping (all vars, values, etc)
while (list($key, $value) = each($CONTENT_DATA)) while (list($key, $value) = each($CONTENT_DATA)) {
{
$smarty->assign($key, $value); $smarty->assign($key, $value);
} }
@@ -342,4 +322,3 @@
// debug output // debug output
echo $login->print_error_msg(); echo $login->print_error_msg();
echo $form->print_error_msg(); echo $form->print_error_msg();
?>

18
www/admin/error_test.php Normal file
View File

@@ -0,0 +1,18 @@
<?php
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1;
$PRINT_ALL = 1;
$DB_DEBUG = 1;
if ($DEBUG_ALL) {
error_reporting(E_ALL);
}
// sample config
require("config.inc");
require(LIBS."Error.Handling.inc");
if ($var) {
echo "OUT<br>";
}

View File

@@ -28,23 +28,29 @@
$show_type = $_GET['type']; // P (pic), F (flash), V (video), D (document: word), A (document: pdf), B (binary); , separated string $show_type = $_GET['type']; // P (pic), F (flash), V (video), D (document: word), A (document: pdf), B (binary); , separated string
// default view is list // default view is list
if (!$view && !$data_id) if (!$view && !$data_id) {
$view = 'list'; $view = 'list';
elseif (!$view && $data_id) } elseif (!$view && $data_id) {
$view = 'list'; $view = 'list';
}
// default is online // default is online
if (!isset($online)) if (!isset($online)) {
$online = 't'; $online = 't';
}
// if not set, it is a fresh load // if not set, it is a fresh load
if (!$show_amount) if (!$show_amount) {
$fresh_load = 1; $fresh_load = 1;
}
// the next two are for page view // the next two are for page view
if (!$start_row) if (!$start_row) {
$start_row = 0; $start_row = 0;
if (!$show_amount) }
if (!$show_amount) {
$show_amount = 12; $show_amount = 12;
if (!$show_type) }
if (!$show_type) {
$show_type = 'P'; $show_type = 'P';
}
// yes no list (online) // yes no list (online)
$yesno_list['f'] = 'No'; $yesno_list['f'] = 'No';
@@ -57,105 +63,92 @@
$sort_order_list['name_en'] = 'Alt Name English'; $sort_order_list['name_en'] = 'Alt Name English';
$sort_order_list['name_ja'] = 'Alt Name Japanese'; $sort_order_list['name_ja'] = 'Alt Name Japanese';
$sort_order_list['date_updated'] = 'Updated'; $sort_order_list['date_updated'] = 'Updated';
if (!$sort_order) if (!$sort_order) {
$sort_order = 'date_created'; $sort_order = 'date_created';
}
$sort_direction_list['ASC'] = 'Normal'; $sort_direction_list['ASC'] = 'Normal';
$sort_direction_list['DESC'] = 'Reverse'; $sort_direction_list['DESC'] = 'Reverse';
if (!$sort_direction) if (!$sort_direction) {
$sort_direction = 'ASC'; $sort_direction = 'ASC';
}
// set if we need to write to any of the set live queues // set if we need to write to any of the set live queues
// a) on page save with set_live // a) on page save with set_live
// b) global page with live_queue // b) global page with live_queue
// set via QUEUE variable // set via QUEUE variable
// create 0 entries for: templates, menu, data_group? // create 0 entries for: templates, menu, data_group?
if ($cms->action == 'new' && $cms->action_yes == 'true') if ($cms->action == 'new' && $cms->action_yes == 'true') {
{
unset($file_uid); unset($file_uid);
unset($file_id); unset($file_id);
unset($file_type); unset($file_type);
$new_okay = 1; $new_okay = 1;
} }
// file type: P picture, M mouse over picutre, F flash, V video, B binary // file type: P picture, M mouse over picutre, F flash, V video, B binary
if ($cms->action == 'save') if ($cms->action == 'save') {
{ if (!$file_type) {
if (!$file_type)
$file_type = 'B'; $file_type = 'B';
}
$file_ok = false; $file_ok = false;
if (!$_FILES['file_up']['name'] && !$file_uid) if (!$_FILES['file_up']['name'] && !$file_uid) {
{
$cms->messages[] = array('msg' => 'No file name given', 'class' => 'error'); $cms->messages[] = array('msg' => 'No file name given', 'class' => 'error');
$error = 1; $error = 1;
} }
if (!$_FILES['file_up']['name'] && $file_uid) if (!$_FILES['file_up']['name'] && $file_uid) {
$file_ok = true; $file_ok = true;
}
// echo "FILE TYPE: ".$_FILES['file_up']['type']."<br>"; // echo "FILE TYPE: ".$_FILES['file_up']['type']."<br>";
foreach (split(',', $show_type) as $_show_type) foreach (split(',', $show_type) as $_show_type) {
{
// check if the uploaded filename matches to the given type // check if the uploaded filename matches to the given type
if ($_FILES['file_up']['name'] && preg_match("/jpeg|png|gif/", $_FILES['file_up']['type']) && preg_match("/P/", $show_type)) if ($_FILES['file_up']['name'] && preg_match("/jpeg|png|gif/", $_FILES['file_up']['type']) && preg_match("/P/", $show_type)) {
{
$file_ok = true; $file_ok = true;
} }
if ($_FILES['file_up']['name'] && preg_match("/swf/", $_FILES['file_up']['type']) && preg_match("/F/", $show_type)) if ($_FILES['file_up']['name'] && preg_match("/swf/", $_FILES['file_up']['type']) && preg_match("/F/", $show_type)) {
{
$file_ok = true; $file_ok = true;
} }
if ($_FILES['file_up']['name'] && preg_match("/video/", $_FILES['file_up']['type']) && preg_match("/V/", $show_type)) if ($_FILES['file_up']['name'] && preg_match("/video/", $_FILES['file_up']['type']) && preg_match("/V/", $show_type)) {
{
$file_ok = true; $file_ok = true;
} }
if ($_FILES['file_up']['name'] && preg_match("/msword|vnd.oasis.opendocument.text/", $_FILES['file_up']['type']) && preg_match("/D/", $show_type)) if ($_FILES['file_up']['name'] && preg_match("/msword|vnd.oasis.opendocument.text/", $_FILES['file_up']['type']) && preg_match("/D/", $show_type)) {
{
$file_ok = true; $file_ok = true;
} }
if ($_FILES['file_up']['name'] && preg_match("/pdf/", $_FILES['file_up']['type']) && preg_match("/A/", $show_type)) if ($_FILES['file_up']['name'] && preg_match("/pdf/", $_FILES['file_up']['type']) && preg_match("/A/", $show_type)) {
{
$file_ok = true; $file_ok = true;
} }
if ($_FILES['file_up']['name'] && preg_match("/B/", $show_type)) if ($_FILES['file_up']['name'] && preg_match("/B/", $show_type)) {
$file_ok = true; $file_ok = true;
} }
}
// write out error messages according to show type // write out error messages according to show type
if (!$file_ok) if (!$file_ok) {
{ if (preg_match("/P/", $show_type)) {
if (preg_match("/P/", $show_type))
{
$cms->messages[] = array('msg' => 'File is not a JPEG/PNG/GIF file', 'class' => 'error'); $cms->messages[] = array('msg' => 'File is not a JPEG/PNG/GIF file', 'class' => 'error');
$error = 1; $error = 1;
} }
if (preg_match("/F/", $show_type)) if (preg_match("/F/", $show_type)) {
{
$cms->messages[] = array('msg' => 'File is not a Flash File', 'class' => 'error'); $cms->messages[] = array('msg' => 'File is not a Flash File', 'class' => 'error');
$error = 1; $error = 1;
} }
if (preg_match("/V/", $show_type)) if (preg_match("/V/", $show_type)) {
{
$cms->messages[] = array('msg' => 'File is not a Video', 'class' => 'error'); $cms->messages[] = array('msg' => 'File is not a Video', 'class' => 'error');
$error = 1; $error = 1;
} }
if (preg_match("/D/", $show_type)) if (preg_match("/D/", $show_type)) {
{
$cms->messages[] = array('msg' => 'File is not a DOC/ODT file', 'class' => 'error'); $cms->messages[] = array('msg' => 'File is not a DOC/ODT file', 'class' => 'error');
$error = 1; $error = 1;
} }
if (preg_match("/A/", $show_type)) if (preg_match("/A/", $show_type)) {
{
$cms->messages[] = array('msg' => 'File is not a PDF file', 'class' => 'error'); $cms->messages[] = array('msg' => 'File is not a PDF file', 'class' => 'error');
$error = 1; $error = 1;
} }
if (preg_match("/B/", $show_type)) if (preg_match("/B/", $show_type)) {
{
$cms->messages[] = array('msg' => 'No valid file was given', 'class' => 'error'); $cms->messages[] = array('msg' => 'No valid file was given', 'class' => 'error');
$error = 1; $error = 1;
} }
} }
// binary: all okay // binary: all okay
// if no error, save data // if no error, save data
if (!$error) if (!$error) {
{ if ($_FILES['file_up']['name']) {
if ($_FILES['file_up']['name'])
{
$mime_type = $_FILES['file_up']['type']; $mime_type = $_FILES['file_up']['type'];
$file_size = $_FILES['file_up']['size']; $file_size = $_FILES['file_up']['size'];
$file_name = $_FILES['file_up']['name']; $file_name = $_FILES['file_up']['name'];
@@ -163,46 +156,43 @@
list($width, $height) = getimagesize($_FILES['file_up']['tmp_name']); list($width, $height) = getimagesize($_FILES['file_up']['tmp_name']);
$cms->debug('upload', "Width: $width X Height: $height"); $cms->debug('upload', "Width: $width X Height: $height");
// set the file type and the target folder // set the file type and the target folder
if (preg_match("/jpeg|png|gif/", $mime_type)) if (preg_match("/jpeg|png|gif/", $mime_type)) {
$file_type = 'P'; $file_type = 'P';
elseif (preg_match("/swf/", $mime_type)) } elseif (preg_match("/swf/", $mime_type)) {
$file_type = 'F'; $file_type = 'F';
elseif (preg_match("/video/", $mime_type)) } elseif (preg_match("/video/", $mime_type)) {
$file_type = 'V'; $file_type = 'V';
elseif (preg_match("/msword|vnd.oasis.opendocument.text/", $mime_type)) } elseif (preg_match("/msword|vnd.oasis.opendocument.text/", $mime_type)) {
$file_type = 'D'; $file_type = 'D';
elseif (preg_match("/pdf/", $mime_type)) } elseif (preg_match("/pdf/", $mime_type)) {
$file_type = 'A'; $file_type = 'A';
elseif ($mime_type) } elseif ($mime_type) {
$file_type = 'B'; $file_type = 'B';
} }
}
// if we have an id -> updated // if we have an id -> updated
if ($file_uid) if ($file_uid) {
{
$q = "UPDATE file SET"; $q = "UPDATE file SET";
$q_set = " name_en = '".addslashes($name_en)."', name_ja = '".addslashes($name_ja)."', file_name = '".addslashes($file_name)."', online = '".$online."' "; $q_set = " name_en = '".addslashes($name_en)."', name_ja = '".addslashes($name_ja)."', file_name = '".addslashes($file_name)."', online = '".$online."' ";
if ($_FILES['file_up']['name']) if ($_FILES['file_up']['name']) {
{
$q_set .= ", type = '".$file_type."', mime_type = '$mime_type', file_size = $file_size, size_x = $width, size_y = $height "; $q_set .= ", type = '".$file_type."', mime_type = '$mime_type', file_size = $file_size, size_x = $width, size_y = $height ";
} }
$q .= $q_set."WHERE file_uid = '".$file_uid."'"; $q .= $q_set."WHERE file_uid = '".$file_uid."'";
$cms->db_exec($q); $cms->db_exec($q);
if (QUEUE == 'live_queue') if (QUEUE == 'live_queue') {
{
$sql_action = 'UPDATE'; $sql_action = 'UPDATE';
$sql_data = $q_set; $sql_data = $q_set;
} }
} } else {
// insert new data // insert new data
else
{
$file_uid = md5(uniqid(rand(), true)); $file_uid = md5(uniqid(rand(), true));
$q = "INSERT INTO file (name_en, name_ja, file_name, online, mime_type, file_size, size_x, size_y, file_uid, type) VALUES ('".addslashes($name_en)."', '".addslashes($name_ja)."', '".addslashes($file_name)."', '".$online."', '".$mime_type."', $file_size, ".(($width) ? $width : 'NULL').", ".(($height) ? $height : 'NULL').", '".$file_uid."', '".$file_type."')"; $q = "INSERT INTO file (name_en, name_ja, file_name, online, mime_type, file_size, size_x, size_y, file_uid, type) VALUES (";
$q .= "'".addslashes($name_en)."', '".addslashes($name_ja)."', '".addslashes($file_name)."', '".$online."', '".$mime_type."', ";
$q .= "$file_size, ".(($width) ? $width : 'NULL').", ".(($height) ? $height : 'NULL').", '".$file_uid."', '".$file_type."')";
$cms->db_exec($q); $cms->db_exec($q);
$file_id = $cms->insert_id; $file_id = $cms->insert_id;
// if queue // if queue
if (QUEUE == 'live_queue') if (QUEUE == 'live_queue') {
{
$sql_data = $q; $sql_data = $q;
$sql_action = 'INSERT'; $sql_action = 'INSERT';
} }
@@ -211,15 +201,14 @@ $cms->debug('upload', "Width: $width X Height: $height");
$size_y = $height; $size_y = $height;
$file = DEV_SCHEMA."_".$file_uid; $file = DEV_SCHEMA."_".$file_uid;
// now upload the file // now upload the file
if ($_FILES['file_up']['name']) if ($_FILES['file_up']['name']) {
{
$upload_file = ROOT.MEDIA.$cms->data_path[$file_type].$file; $upload_file = ROOT.MEDIA.$cms->data_path[$file_type].$file;
// wipe out any old tmp data for this new upload // wipe out any old tmp data for this new upload
if (is_array(glob(ROOT.TMP."thumb_".$file."*"))) if (is_array(glob(ROOT.TMP."thumb_".$file."*"))) {
{ foreach (glob(ROOT.TMP."thumb_".$file."*") as $filename) {
foreach (glob(ROOT.TMP."thumb_".$file."*") AS $filename)
@unlink($filename); @unlink($filename);
} }
}
# copy file to correct path # copy file to correct path
$error = move_uploaded_file($_FILES['file_up']['tmp_name'], $upload_file); $error = move_uploaded_file($_FILES['file_up']['tmp_name'], $upload_file);
@@ -228,8 +217,7 @@ $cms->debug('file_upload', "Orig: ".$cms->print_ar($_FILES['file_up']));
// because I get bogus error info from move_uploaded_file ... // because I get bogus error info from move_uploaded_file ...
$error = 0; $error = 0;
if ($error) if ($error) {
{
$cms->debug('file_upload', "ERROR: $error | INI FSize: ".ini_get("upload_max_filesize")); $cms->debug('file_upload', "ERROR: $error | INI FSize: ".ini_get("upload_max_filesize"));
$cms->messages[] = array('msg' => 'File upload failed', 'class' => 'error'); $cms->messages[] = array('msg' => 'File upload failed', 'class' => 'error');
$q = "DELETE FROM file WHERE file_uid = '".$file_uid."'"; $q = "DELETE FROM file WHERE file_uid = '".$file_uid."'";
@@ -237,11 +225,9 @@ $cms->debug('file_upload', "ERROR: $error | INI FSize: ".ini_get("upload_max_fil
unset($file_id); unset($file_id);
unset($file_uid); unset($file_uid);
$view = 'list'; $view = 'list';
} } else {
else
{
$cms->messages[] = array('msg' => 'File upload successful', 'class' => 'warning'); $cms->messages[] = array('msg' => 'File upload successful', 'class' => 'warning');
// $vew = 'list'; // $view = 'list';
} }
} // if file upload } // if file upload
// create thumbs + file size // create thumbs + file size
@@ -249,35 +235,34 @@ $cms->debug('file_upload', "ERROR: $error | INI FSize: ".ini_get("upload_max_fil
$picture_small = $cms->cache_pictures.$cms->adbCreateThumbnail($file, 80, 60, $file_type, '', $cms->cache_pictures_root); $picture_small = $cms->cache_pictures.$cms->adbCreateThumbnail($file, 80, 60, $file_type, '', $cms->cache_pictures_root);
$file_size = $cms->adbByteStringFormat($file_size); $file_size = $cms->adbByteStringFormat($file_size);
// for live queue this is here needed // for live queue this is here needed
if (QUEUE == 'live_queue') if (QUEUE == 'live_queue') {
{
$q = "INSERT INTO ".GLOBAL_DB_SCHEMA.".live_queue (queue_key, key_value, key_name, type, target, data, group_key, action"; $q = "INSERT INTO ".GLOBAL_DB_SCHEMA.".live_queue (queue_key, key_value, key_name, type, target, data, group_key, action";
if ($_FILES['file_up']['name']) if ($_FILES['file_up']['name']) {
$q .= ", file"; $q .= ", file";
}
$q .= ") VALUES ('".$cms->queue_name."', '".$file_uid."', 'file_uid', '".$sql_action."', 'file', '".$cms->db_escape_string($sql_data)."', '".$cms->queue_key."', '".$cms->action."'"; $q .= ") VALUES ('".$cms->queue_name."', '".$file_uid."', 'file_uid', '".$sql_action."', 'file', '".$cms->db_escape_string($sql_data)."', '".$cms->queue_key."', '".$cms->action."'";
if ($_FILES['file_up']['name']) if ($_FILES['file_up']['name']) {
$q .= ", '".ROOT.MEDIA.$cms->data_path[$file_type].$file."#".ROOT.MEDIA.$cms->data_path[$file_type].PUBLIC_SCHEMA."_".$file_uid."'"; $q .= ", '".ROOT.MEDIA.$cms->data_path[$file_type].$file."#".ROOT.MEDIA.$cms->data_path[$file_type].PUBLIC_SCHEMA."_".$file_uid."'";
}
$q .= ")"; $q .= ")";
$cms->db_exec($q); $cms->db_exec($q);
} }
} // if not error } // if not error
} }
if ($cms->action == 'delete' && $cms->action_yes == 'true') if ($cms->action == 'delete' && $cms->action_yes == 'true') {
{
$file_uid = $cms->action_id; $file_uid = $cms->action_id;
$q = "SELECT type FROM file WHERE file_uid = '".$file_uid."'"; $q = "SELECT type FROM file WHERE file_uid = '".$file_uid."'";
list ($file_type) = $cms->db_return_row($q); list ($file_type) = $cms->db_return_row($q);
// get the file type for the file path // get the file type for the file path
$q = "DELETE FROM file WHERE file_uid = '".$file_uid."'"; $q = "DELETE FROM file WHERE file_uid = '".$file_uid."'";
$cms->db_exec($q); $cms->db_exec($q);
if (QUEUE == 'set_live') if (QUEUE == 'set_live') {
{
$q = "INSERT INTO ".GLOBAL_DB_SCHEMA.".set_live (table_name, pkid, delete_flag) VALUES ('".$cms->page_name."', ".$file_uid.", 't')"; $q = "INSERT INTO ".GLOBAL_DB_SCHEMA.".set_live (table_name, pkid, delete_flag) VALUES ('".$cms->page_name."', ".$file_uid.", 't')";
$cms->db_exec($q); $cms->db_exec($q);
} }
if (QUEUE == 'live_queue') if (QUEUE == 'live_queue') {
{ $q = "INSERT INTO ".GLOBAL_DB_SCHEMA.".live_queue (queue_key, key_value, key_name, type, target, data, group_key, action, file) VALUES (";
$q = "INSERT INTO ".GLOBAL_DB_SCHEMA.".live_queue (queue_key, key_value, key_name, type, target, data, group_key, action, file) VALUES ('".$cms->queue_name."', '".$file_uid."', 'file_uid', 'DELETE', 'file', '', '".$cms->queue_key."', '".$cms->action."', '".ROOT.MEDIA.$cms->data_path[$file_type].PUBLIC_SCHEMA."_".$file_uid."')"; $q .= "'".$cms->queue_name."', '".$file_uid."', 'file_uid', 'DELETE', 'file', '', '".$cms->queue_key."', '".$cms->action."', '".ROOT.MEDIA.$cms->data_path[$file_type].PUBLIC_SCHEMA."_".$file_uid."')";
} }
@unlink(ROOT.MEDIA.$cms->data_path[$file_type].DEV_SCHEMA."_".$file_uid); @unlink(ROOT.MEDIA.$cms->data_path[$file_type].DEV_SCHEMA."_".$file_uid);
unset($file_uid); unset($file_uid);
@@ -285,8 +270,7 @@ $cms->debug('file_upload', "ERROR: $error | INI FSize: ".ini_get("upload_max_fil
$delete_done = 1; $delete_done = 1;
$view = 'list'; $view = 'list';
} }
if ($cms->action == 'load') if ($cms->action == 'load') {
{
$file_uid = $cms->action_id; $file_uid = $cms->action_id;
// load the data // load the data
$q = "SELECT file_id, name_en, name_ja, file_name, online, mime_type, file_size, size_x, size_y, type FROM file WHERE file_uid = '".$file_uid."'"; $q = "SELECT file_id, name_en, name_ja, file_name, online, mime_type, file_size, size_x, size_y, type FROM file WHERE file_uid = '".$file_uid."'";
@@ -300,20 +284,16 @@ $cms->debug('file_upload', "ERROR: $error | INI FSize: ".ini_get("upload_max_fil
// view to edit // view to edit
$view = 'edit'; $view = 'edit';
} }
if ($cms->action == 'add_new') if ($cms->action == 'add_new') {
{
$view = 'edit'; $view = 'edit';
} }
if ($cms->action == 'view_files' && $cms->action_yes == 'true') if ($cms->action == 'view_files' && $cms->action_yes == 'true') {
{
$view = 'list'; $view = 'list';
} }
// set delete live // set delete live
if ($cms->action_flag == 'set_live' && $cms->action = 'set_delete') if ($cms->action_flag == 'set_live' && $cms->action = 'set_delete') {
{
$q = "SELECT file_uid, pkid, type FROM ".LOGIN_DB_SCHEMA.".set_live sl, file f WHERE sl.pkid = f.file_uid table_name = '".$cms->page_name."' AND delete_flag = 't'"; $q = "SELECT file_uid, pkid, type FROM ".LOGIN_DB_SCHEMA.".set_live sl, file f WHERE sl.pkid = f.file_uid table_name = '".$cms->page_name."' AND delete_flag = 't'";
while ($res = $cms->db_return($q)) while ($res = $cms->db_return($q)) {
{
$q_del = "DELETE FROM ".PUBLIC_SCHEMA.".file WHERE file_uid = '".$res['pkid'].'"'; $q_del = "DELETE FROM ".PUBLIC_SCHEMA.".file WHERE file_uid = '".$res['pkid'].'"';
$cms->db_exec($q_del); $cms->db_exec($q_del);
@unlink(ROOT.MEDIA.$cms->data_path[$res['type']].PUBLIC_SCHEMA."_".$res['file_uid']); @unlink(ROOT.MEDIA.$cms->data_path[$res['type']].PUBLIC_SCHEMA."_".$res['file_uid']);
@@ -321,31 +301,26 @@ $cms->debug('file_upload', "ERROR: $error | INI FSize: ".ini_get("upload_max_fil
$q = "DELETE FROM ".LOGIN_DB_SCHEMA.".set_live WHERE table_name = '".$cms->page_name."' AND delete_flag = 't'"; $q = "DELETE FROM ".LOGIN_DB_SCHEMA.".set_live WHERE table_name = '".$cms->page_name."' AND delete_flag = 't'";
$cms->db_exec($q); $cms->db_exec($q);
} }
if (DEV_SCHEMA != PUBLIC_SCHEMA) if (DEV_SCHEMA != PUBLIC_SCHEMA) {
{
// read out possible deleted, to add "delete from live" // read out possible deleted, to add "delete from live"
$q = "SELECT pkid FROM ".LOGIN_DB_SCHEMA.".set_live WHERE table_name = '".$cms->page_name."' AND delete_flag = 't'"; $q = "SELECT pkid FROM ".LOGIN_DB_SCHEMA.".set_live WHERE table_name = '".$cms->page_name."' AND delete_flag = 't'";
while ($res = $cms->db_return($q, 3)) while ($res = $cms->db_return($q, 3)) {
{
$cms->DATA['set_delete'][]['pkid'] = $res['pkid']; $cms->DATA['set_delete'][]['pkid'] = $res['pkid'];
} }
} }
// get th max entries // get th max entries
$q = "SELECT COUNT(file_uid) FROM file "; $q = "SELECT COUNT(file_uid) FROM file ";
$q_search_where = "WHERE type in ('".str_replace(',', "','", $show_type)."') "; $q_search_where = "WHERE type in ('".str_replace(',', "','", $show_type)."') ";
if ($search_what) if ($search_what) {
{
$q_search_where .= "AND LOWER(name_en) LIKE '%".addslashes(strtolower($search_what))."%' OR name_ja LIKE '%".addslashes($search_what)."%' OR LOWER(file_name) LIKE '%".addslashes(strtolower($search_what))."%' "; $q_search_where .= "AND LOWER(name_en) LIKE '%".addslashes(strtolower($search_what))."%' OR name_ja LIKE '%".addslashes($search_what)."%' OR LOWER(file_name) LIKE '%".addslashes(strtolower($search_what))."%' ";
} }
$q .= $q_search_where; $q .= $q_search_where;
// get selection from show_type // get selection from show_type
list ($file_count) = $cms->db_return_row($q); list ($file_count) = $cms->db_return_row($q);
if ($cms->action == 'browse') if ($cms->action == 'browse') {
{
// browse in the list of data // browse in the list of data
switch ($cms->action_id) switch ($cms->action_id) {
{
case "<<<<": case "<<<<":
$start_row = 0; $start_row = 0;
break; break;
@@ -367,24 +342,24 @@ $cms->debug('file_upload', "ERROR: $error | INI FSize: ".ini_get("upload_max_fil
} }
// check overflow // check overflow
if ($start_row < 0) if ($start_row < 0) {
$start_row = 0; $start_row = 0;
if ($start_row > $file_count) }
if ($start_row > $file_count) {
$start_row = $file_count - $show_amount; $start_row = $file_count - $show_amount;
}
// if we have a "fresh_load" // if we have a "fresh_load"
if ($fresh_load) if ($fresh_load) {
{
$count = 1; $count = 1;
$q = "SELECT file_uid FROM file "; $q = "SELECT file_uid FROM file ";
if ($q_search_where) if ($q_search_where) {
$q .= $q_search_where; $q .= $q_search_where;
}
$q .= "ORDER BY ".$sort_order." ".$sort_direction." "; $q .= "ORDER BY ".$sort_order." ".$sort_direction." ";
while ($res = $cms->db_return($q)) while ($res = $cms->db_return($q)) {
{
// if data_id is set and not file_id, go to the page where the current highlight is, but only if this is a "virgin" load of the page // if data_id is set and not file_id, go to the page where the current highlight is, but only if this is a "virgin" load of the page
if ($data_id && ($data_id == $res['file_uid'])) if ($data_id && ($data_id == $res['file_uid'])) {
{
$current_page = floor(($count / $show_amount)); $current_page = floor(($count / $show_amount));
$start_row = $current_page * $show_amount; $start_row = $current_page * $show_amount;
$current_page ++; $current_page ++;
@@ -394,29 +369,26 @@ $cms->debug('file_upload', "ERROR: $error | INI FSize: ".ini_get("upload_max_fil
} }
// page forward/back buttons settings // page forward/back buttons settings
if ($start_row > 0) if ($start_row > 0) {
{
$cms->DATA['show_back'] = 1; $cms->DATA['show_back'] = 1;
} }
$cms->DATA['page_number'] = ceil($start_row / $show_amount) + 1; $cms->DATA['page_number'] = ceil($start_row / $show_amount) + 1;
$cms->DATA['page_count'] = ceil($file_count / $show_amount); $cms->DATA['page_count'] = ceil($file_count / $show_amount);
if ($cms->DATA['page_count'] > 2 && !$current_page) if ($cms->DATA['page_count'] > 2 && !$current_page) {
{
$current_page = 1; $current_page = 1;
} }
if (($start_row + $show_amount) < $file_count) if (($start_row + $show_amount) < $file_count) {
{
$cms->DATA['show_forward'] = 1; $cms->DATA['show_forward'] = 1;
} }
$q = "SELECT file_id, name_en, name_ja, file_name, online, mime_type, file_size, size_x, size_y, file_uid, type FROM file "; $q = "SELECT file_id, name_en, name_ja, file_name, online, mime_type, file_size, size_x, size_y, file_uid, type FROM file ";
// if search what, search in name_en, name_ja, file_name for the string // if search what, search in name_en, name_ja, file_name for the string
if ($q_search_where) if ($q_search_where) {
$q .= $q_search_where; $q .= $q_search_where;
}
$q .= "ORDER BY ".$sort_order." ".$sort_direction." "; $q .= "ORDER BY ".$sort_order." ".$sort_direction." ";
$q .= "LIMIT ".$show_amount." OFFSET ".$start_row; $q .= "LIMIT ".$show_amount." OFFSET ".$start_row;
while ($res = $cms->db_return($q)) while ($res = $cms->db_return($q)) {
{
$data_files[] = array ( $data_files[] = array (
'id' => $res['file_id'], 'id' => $res['file_id'],
'name_en' => $res['name_en'], 'name_en' => $res['name_en'],
@@ -444,8 +416,7 @@ $cms->debug('file_upload', "ERROR: $error | INI FSize: ".ini_get("upload_max_fil
$cms->DATA['file_uid'] = $file_uid; $cms->DATA['file_uid'] = $file_uid;
// write back all the other vars // write back all the other vars
if (!($delete_done || $new_okay)) if (!($delete_done || $new_okay)) {
{
// data name // data name
$cms->DATA['file_name'] = $file_name; $cms->DATA['file_name'] = $file_name;
$cms->DATA['name_en'] = $name_en; $cms->DATA['name_en'] = $name_en;
@@ -468,8 +439,9 @@ $cms->debug('file_upload', "ERROR: $error | INI FSize: ".ini_get("upload_max_fil
$cms->DATA['yesno_list'] = $yesno_list; $cms->DATA['yesno_list'] = $yesno_list;
$cms->DATA['start_row'] = $start_row; $cms->DATA['start_row'] = $start_row;
$cms->DATA['show_amount'] = $show_amount; $cms->DATA['show_amount'] = $show_amount;
if ($data_id) if ($data_id) {
$cms->DATA['data_id'] = $data_id; $cms->DATA['data_id'] = $data_id;
}
$cms->DATA['top'] = 0; $cms->DATA['top'] = 0;
$cms->DATA['left'] = 0; $cms->DATA['left'] = 0;
@@ -482,5 +454,3 @@ $cms->debug('file_upload', "ERROR: $error | INI FSize: ".ini_get("upload_max_fil
//------------------------------ footer //------------------------------ footer
require("footer.inc"); require("footer.inc");
//------------------------------ footer //------------------------------ footer
?>

View File

@@ -10,4 +10,3 @@
// print debug messages // print debug messages
echo $login->print_error_msg(); echo $login->print_error_msg();
echo $cms->print_error_msg(); echo $cms->print_error_msg();
?>

View File

@@ -9,8 +9,9 @@
//------------------------------ variable init start //------------------------------ variable init start
// for dev test we set full error reporting; writes everything, except E_ERROR into logs/php_error-<day>.log // for dev test we set full error reporting; writes everything, except E_ERROR into logs/php_error-<day>.log
if ($DEBUG_ALL && $ENABLE_ERROR_HANDLING) if ($DEBUG_ALL && $ENABLE_ERROR_HANDLING) {
include("libs/Error.Handling.inc"); include("libs/Error.Handling.inc");
}
// predefine vars // predefine vars
$lang = ''; $lang = '';
$messages = array (); $messages = array ();
@@ -22,25 +23,26 @@
// set output to quiet for load of classes & session settings // set output to quiet for load of classes & session settings
ob_start(); ob_start();
require("config.inc"); require("config.inc");
// set the session name
define('SET_SESSION_NAME', EDIT_SESSION_NAME);
// login class, DB connections & Admin class, Smarty extension // login class, DB connections & Admin class, Smarty extension
foreach (array ('Login', 'Admin.Backend', 'Smarty.Extend') as $class) foreach (array ('Login', 'Admin.Backend', 'Smarty.Extend') as $class) {
_spl_autoload('Class.'.$class.'.inc'); _spl_autoload('Class.'.$class.'.inc');
}
//------------------------------ library include end //------------------------------ library include end
//------------------------------ basic variable settings start //------------------------------ basic variable settings start
// set encoding // set encoding
if (!isset($encoding)) if (!isset($encoding)) {
$encoding = DEFAULT_ENCODING; $encoding = DEFAULT_ENCODING;
}
// set the default lang, if not given // set the default lang, if not given
if (session_id() && $_SESSION['DEFAULT_LANG']) if (session_id() && $_SESSION['DEFAULT_LANG']) {
$lang = $_SESSION['DEFAULT_LANG']; $lang = $_SESSION['DEFAULT_LANG'];
elseif (!$lang) } elseif (!$lang) {
$lang = DEFAULT_LANG; $lang = DEFAULT_LANG;
}
// end the stop of the output flow, but only if we didn't request a csv file download // end the stop of the output flow, but only if we didn't request a csv file download
if (array_key_exists('action', $_POST) && $_POST['action'] != 'download_csv') if (array_key_exists('action', $_POST) && $_POST['action'] != 'download_csv') {
{
header("Content-type: text/html; charset=".$encoding); header("Content-type: text/html; charset=".$encoding);
ob_end_flush(); ob_end_flush();
} }
@@ -50,8 +52,9 @@
// login & page access check // login & page access check
$login = new login($DB_CONFIG[LOGIN_DB], $lang); $login = new login($DB_CONFIG[LOGIN_DB], $lang);
// post login lang check // post login lang check
if ($_SESSION['DEFAULT_LANG']) if ($_SESSION['DEFAULT_LANG']) {
$lang = $_SESSION['DEFAULT_LANG']; $lang = $_SESSION['DEFAULT_LANG'];
}
// create smarty object // create smarty object
$smarty = new SmartyML($lang); $smarty = new SmartyML($lang);
// create new DB class // create new DB class
@@ -77,8 +80,9 @@
); );
// log action // log action
// no log if login // no log if login
if (!$login->login) if (!$login->login) {
$cms->adbEditLog('Submit', $data, 'BINARY'); $cms->adbEditLog('Submit', $data, 'BINARY');
}
//------------------------------ logging end //------------------------------ logging end
//------------------------------ page rights start //------------------------------ page rights start
@@ -89,8 +93,7 @@
// automatic hide for DEBUG messages on live server // automatic hide for DEBUG messages on live server
// can be overridden when setting DEBUG_ALL_OVERRIDE on top of the script (for emergency debugging of one page only) // can be overridden when setting DEBUG_ALL_OVERRIDE on top of the script (for emergency debugging of one page only)
if ((TARGET == 'live' || TARGET == 'remote') && !$DEBUG_ALL_OVERRIDE) if ((TARGET == 'live' || TARGET == 'remote') && !$DEBUG_ALL_OVERRIDE) {
{
$login->debug_output_all = 0; $login->debug_output_all = 0;
$login->echo_output_all = 0; $login->echo_output_all = 0;
$login->print_output_all = 0; $login->print_output_all = 0;
@@ -99,4 +102,3 @@
$cms->print_output_all = 0; $cms->print_output_all = 0;
} }
$cms->DATA['JS_DEBUG'] = DEBUG; $cms->DATA['JS_DEBUG'] = DEBUG;
?>

View File

@@ -49,5 +49,3 @@
$month_short[10] = "Oct"; $month_short[10] = "Oct";
$month_short[11] = "Nov"; $month_short[11] = "Nov";
$month_short[12] = "Dec"; $month_short[12] = "Dec";
?>

View File

@@ -8,28 +8,32 @@
*********************************************************************/ *********************************************************************/
// template path // template path
if ($_SESSION['TEMPLATE']) if ($_SESSION['TEMPLATE']) {
$TEMPLATE = $_SESSION['TEMPLATE']; $TEMPLATE = $_SESSION['TEMPLATE'];
elseif ($LOCAL_TEMPLATE) } elseif ($LOCAL_TEMPLATE) {
$TEMPLATE = $LOCAL_TEMPLATE; $TEMPLATE = $LOCAL_TEMPLATE;
else } else {
$TEMPLATE = DEFAULT_TEMPLATE; $TEMPLATE = DEFAULT_TEMPLATE;
}
$TEMPLATE_DIR = $TEMPLATE.'/'; $TEMPLATE_DIR = $TEMPLATE.'/';
// master template // master template
if (!$MASTER_TEMPLATE_NAME) if (!$MASTER_TEMPLATE_NAME) {
$MASTER_TEMPLATE_NAME = MASTER_TEMPLATE_NAME; $MASTER_TEMPLATE_NAME = MASTER_TEMPLATE_NAME;
}
// just emergency fallback for language // just emergency fallback for language
// set encoding // set encoding
if ($_SESSION['DEFAULT_CHARSET']) if ($_SESSION['DEFAULT_CHARSET']) {
$encoding = $_SESSION['DEFAULT_CHARSET']; $encoding = $_SESSION['DEFAULT_CHARSET'];
elseif (!$encoding) } elseif (!$encoding) {
$encoding = DEFAULT_ENCODING; $encoding = DEFAULT_ENCODING;
}
// just emergency fallback for language // just emergency fallback for language
if ($_SESSION['DEFAULT_LANG']) if ($_SESSION['DEFAULT_LANG']) {
$lang = $_SESSION['DEFAULT_LANG']; $lang = $_SESSION['DEFAULT_LANG'];
elseif (!$lang) } elseif (!$lang) {
$lang = DEFAULT_LANG; $lang = DEFAULT_LANG;
}
// create the char lang encoding // create the char lang encoding
$lang_short = substr($lang, 0, 2); $lang_short = substr($lang, 0, 2);
@@ -59,21 +63,20 @@
$cms->pictures = LAYOUT.$TEMPLATE_DIR.IMAGES."/"; $cms->pictures = LAYOUT.$TEMPLATE_DIR.IMAGES."/";
$cms->cache_pictures = LAYOUT.$TEMPLATE_DIR.CACHE.IMAGES.'/'; $cms->cache_pictures = LAYOUT.$TEMPLATE_DIR.CACHE.IMAGES.'/';
$cms->cache_pictures_root = ROOT.$cms->cache_pictures; $cms->cache_pictures_root = ROOT.$cms->cache_pictures;
if (!is_dir($cms->cache_pictures_root)) if (!is_dir($cms->cache_pictures_root)) {
mkdir($cms->cache_pictures_root); mkdir($cms->cache_pictures_root);
}
$template_set = $TEMPLATE; $template_set = $TEMPLATE;
// if we don't find the master template, set the template path back AND set the insert template as absolute path // if we don't find the master template, set the template path back AND set the insert template as absolute path
if (!file_exists(ROOT.$smarty->getTemplateDir()[0]."/".MASTER_TEMPLATE_NAME)) if (!file_exists(ROOT.$smarty->getTemplateDir()[0]."/".MASTER_TEMPLATE_NAME)) {
{ if (file_exists(ROOT.$smarty->getTemplateDir()[0]."/".$TEMPLATE_NAME)) {
if (file_exists(ROOT.$smarty->getTemplateDir()[0]."/".$TEMPLATE_NAME))
$TEMPLATE_NAME = ROOT.$smarty->getTemplateDir()[0]."/".$TEMPLATE_NAME; $TEMPLATE_NAME = ROOT.$smarty->getTemplateDir()[0]."/".$TEMPLATE_NAME;
}
$smarty->setTemplateDir(LAYOUT.DEFAULT_TEMPLATE.TEMPLATES); $smarty->setTemplateDir(LAYOUT.DEFAULT_TEMPLATE.TEMPLATES);
$template_set = DEFAULT_TEMPLATE; $template_set = DEFAULT_TEMPLATE;
} } elseif (!file_exists(ROOT.$smarty->getTemplateDir()[0]."/".$TEMPLATE_NAME)) {
// check if the template exists in the template path, if not, set path to to default // check if the template exists in the template path, if not, set path to to default
elseif (!file_exists(ROOT.$smarty->getTemplateDir()[0]."/".$TEMPLATE_NAME))
{
$smarty->setTemplateDir(LAYOUT.DEFAULT_TEMPLATE.TEMPLATES); $smarty->setTemplateDir(LAYOUT.DEFAULT_TEMPLATE.TEMPLATES);
$template_set = DEFAULT_TEMPLATE; $template_set = DEFAULT_TEMPLATE;
} }
@@ -81,26 +84,31 @@
// check if file exists, if not reset to default path // check if file exists, if not reset to default path
// check if the javascript folder exists in the template path, if not fall back to default // check if the javascript folder exists in the template path, if not fall back to default
if (!is_dir($cms->javascript)) if (!is_dir($cms->javascript)) {
$cms->javascript = LAYOUT.DEFAULT_TEMPLATE.JS."/"; $cms->javascript = LAYOUT.DEFAULT_TEMPLATE.JS."/";
}
// check if lang_dir folder exists in the template path, if not fall back to default // check if lang_dir folder exists in the template path, if not fall back to default
if (!is_dir($cms->lang_dir)) if (!is_dir($cms->lang_dir)) {
$cms->lang_dir = LAYOUT.DEFAULT_TEMPLATE.LANG."/"; $cms->lang_dir = LAYOUT.DEFAULT_TEMPLATE.LANG."/";
}
// check if include folder exists in the template path, if not fall back to default // check if include folder exists in the template path, if not fall back to default
if (!is_dir($cms->includes)) if (!is_dir($cms->includes)) {
$cms->includes = LAYOUT.DEFAULT_TEMPLATE.INCLUDES."/"; $cms->includes = LAYOUT.DEFAULT_TEMPLATE.INCLUDES."/";
}
// check if css folder exists in the template path, if not fall back to default // check if css folder exists in the template path, if not fall back to default
if (!is_dir($cms->css)) if (!is_dir($cms->css)) {
$cms->css = LAYOUT.DEFAULT_TEMPLATE.CSS."/"; $cms->css = LAYOUT.DEFAULT_TEMPLATE.CSS."/";
if (!is_dir($cms->pictures)) }
if (!is_dir($cms->pictures)) {
$cms->pictures = LAYOUT.DEFAULT_TEMPLATE.PICTURES.'/'; $cms->pictures = LAYOUT.DEFAULT_TEMPLATE.PICTURES.'/';
if (!is_dir($cms->cache_pictures)) }
if (!is_dir($cms->cache_pictures)) {
$cms->cache_pictures = LAYOUT.DEFAULT_TEMPLATE.CACHE.IMAGES.'/'; $cms->cache_pictures = LAYOUT.DEFAULT_TEMPLATE.CACHE.IMAGES.'/';
}
// if the template_dir is != DEFAULT_TEMPLATE, then try to make a lang switch // if the template_dir is != DEFAULT_TEMPLATE, then try to make a lang switch
// if the default lang is not like the lang given, switch lang // if the default lang is not like the lang given, switch lang
if (false === strstr(LAYOUT.DEFAULT_TEMPLATE.LANG, $cms->lang_dir) || strcasecmp(DEFAULT_LANG, $lang)) if (false === strstr(LAYOUT.DEFAULT_TEMPLATE.LANG, $cms->lang_dir) || strcasecmp(DEFAULT_LANG, $lang)) {
{
$cms->debug('LANG', 'Orig: '.LAYOUT.DEFAULT_TEMPLATE.LANG.', New: '.$cms->lang_dir.' | Orig Lang: '.DEFAULT_LANG.', New Lang: '.$lang); $cms->debug('LANG', 'Orig: '.LAYOUT.DEFAULT_TEMPLATE.LANG.', New: '.$cms->lang_dir.' | Orig Lang: '.DEFAULT_LANG.', New Lang: '.$lang);
$cms->l->l10nReloadMOfile($lang, $cms->lang_dir); $cms->l->l10nReloadMOfile($lang, $cms->lang_dir);
$smarty->l10n->l10nReloadMOfile($lang, $cms->lang_dir); $smarty->l10n->l10nReloadMOfile($lang, $cms->lang_dir);
@@ -109,5 +117,3 @@
// $cms->debug("LANGUAGE", "L: $lang | ".$cms->lang_dir." | MO File: ".$cms->l->mofile); // $cms->debug("LANGUAGE", "L: $lang | ".$cms->lang_dir." | MO File: ".$cms->l->mofile);
$cms->debug("LANGUAGE", "SL: ".$_SESSION['DEFAULT_CHARSET']." | ".$_SESSION['LANG']." | ".$_SESSION['DEFAULT_LANG']); $cms->debug("LANGUAGE", "SL: ".$_SESSION['DEFAULT_CHARSET']." | ".$_SESSION['LANG']." | ".$_SESSION['DEFAULT_LANG']);
$cms->debug("TEMPLATE", "P: ".$smarty->getTemplateDir()[0]); $cms->debug("TEMPLATE", "P: ".$smarty->getTemplateDir()[0]);
?>

View File

@@ -10,8 +10,9 @@
// trigger flags // trigger flags
$cms->HEADER['USE_PROTOTYPE'] = USE_PROTOTYPE; $cms->HEADER['USE_PROTOTYPE'] = USE_PROTOTYPE;
// scriptacolous, can only be used with prototype // scriptacolous, can only be used with prototype
if (USE_PROTOTYPE) if (USE_PROTOTYPE) {
$cms->HEADER['USE_SCRIPTACULOUS'] = USE_SCRIPTACULOUS; $cms->HEADER['USE_SCRIPTACULOUS'] = USE_SCRIPTACULOUS;
}
// jquery and prototype should not be used together // jquery and prototype should not be used together
$cms->HEADER['USE_JQUERY'] = USE_JQUERY; // don't use either of those two toger $cms->HEADER['USE_JQUERY'] = USE_JQUERY; // don't use either of those two toger
@@ -19,32 +20,27 @@
// paths are set in the 'set_paths.inc' file // paths are set in the 'set_paths.inc' file
// check if we have an external file with the template name // check if we have an external file with the template name
if (file_exists($cms->includes.$cms->INC_TEMPLATE_NAME) && is_file($cms->includes.$cms->INC_TEMPLATE_NAME)) if (file_exists($cms->includes.$cms->INC_TEMPLATE_NAME) && is_file($cms->includes.$cms->INC_TEMPLATE_NAME)) {
{
include($cms->includes.$cms->INC_TEMPLATE_NAME); include($cms->includes.$cms->INC_TEMPLATE_NAME);
} }
// additional per page Javascript include // additional per page Javascript include
$cms->JS_INCLUDE = ''; $cms->JS_INCLUDE = '';
if (file_exists($cms->javascript.$cms->JS_TEMPLATE_NAME) && is_file($cms->javascript.$cms->JS_TEMPLATE_NAME)) if (file_exists($cms->javascript.$cms->JS_TEMPLATE_NAME) && is_file($cms->javascript.$cms->JS_TEMPLATE_NAME)) {
{
$cms->JS_INCLUDE = $cms->javascript.$cms->JS_TEMPLATE_NAME; $cms->JS_INCLUDE = $cms->javascript.$cms->JS_TEMPLATE_NAME;
} }
// per page css file // per page css file
$cms->CSS_INCLUDE = ''; $cms->CSS_INCLUDE = '';
if (file_exists($cms->css.$cms->CSS_TEMPLATE_NAME) && is_file($cms->css.$cms->CSS_TEMPLATE_NAME)) if (file_exists($cms->css.$cms->CSS_TEMPLATE_NAME) && is_file($cms->css.$cms->CSS_TEMPLATE_NAME)) {
{
$cms->CSS_INCLUDE = $cms->css.$cms->CSS_TEMPLATE_NAME; $cms->CSS_INCLUDE = $cms->css.$cms->CSS_TEMPLATE_NAME;
} }
// optional CSS file // optional CSS file
$cms->CSS_SPECIAL_INCLUDE = ''; $cms->CSS_SPECIAL_INCLUDE = '';
if (file_exists($cms->css.$cms->CSS_SPECIAL_TEMPLATE_NAME) && is_file($cms->css.$cms->CSS_SPECIAL_TEMPLATE_NAME)) if (file_exists($cms->css.$cms->CSS_SPECIAL_TEMPLATE_NAME) && is_file($cms->css.$cms->CSS_SPECIAL_TEMPLATE_NAME)) {
{
$cms->CSS_SPECIAL_INCLUDE = $cms->css.$cms->CSS_SPECIAL_TEMPLATE_NAME; $cms->CSS_SPECIAL_INCLUDE = $cms->css.$cms->CSS_SPECIAL_TEMPLATE_NAME;
} }
// optional JS file // optional JS file
$cms->JS_SPECIAL_INCLUDE = ''; $cms->JS_SPECIAL_INCLUDE = '';
if (file_exists($cms->javascript.$cms->JS_SPECIAL_TEMPLATE_NAME) && is_file($cms->javascript.$cms->JS_SPECIAL_TEMPLATE_NAME)) if (file_exists($cms->javascript.$cms->JS_SPECIAL_TEMPLATE_NAME) && is_file($cms->javascript.$cms->JS_SPECIAL_TEMPLATE_NAME)) {
{
$cms->JS_SPECIAL_INCLUDE = $cms->javascript.$cms->JS_SPECIAL_TEMPLATE_NAME; $cms->JS_SPECIAL_INCLUDE = $cms->javascript.$cms->JS_SPECIAL_TEMPLATE_NAME;
} }
@@ -94,10 +90,7 @@
// create main data array // create main data array
$cms->CONTENT_DATA = array_merge($cms->HEADER, $cms->DATA, $cms->DEBUG_DATA); $cms->CONTENT_DATA = array_merge($cms->HEADER, $cms->DATA, $cms->DEBUG_DATA);
// data is 1:1 mapping (all vars, values, etc) // data is 1:1 mapping (all vars, values, etc)
while (list($key, $value) = each($cms->CONTENT_DATA)) while (list($key, $value) = each($cms->CONTENT_DATA)) {
{
$smarty->assign($key, $value); $smarty->assign($key, $value);
} }
$smarty->display($MASTER_TEMPLATE_NAME, $TEMPLATE.$lang, $TEMPLATE.$lang); $smarty->display($MASTER_TEMPLATE_NAME, $TEMPLATE.$lang, $TEMPLATE.$lang);
?>

View File

@@ -18,4 +18,3 @@
require("smarty.inc"); require("smarty.inc");
require("footer.inc"); require("footer.inc");
?>

View File

@@ -70,9 +70,7 @@
"type" => "hidden", "type" => "hidden",
"fk_id" => 1 # reference main key from master table above "fk_id" => 1 # reference main key from master table above
) )
) )
) )
) )
); );
?>

View File

@@ -97,4 +97,3 @@
) // edit pages ggroup ) // edit pages ggroup
) )
); );
?>

View File

@@ -70,4 +70,3 @@
), ),
"table_name" => "edit_language" "table_name" => "edit_language"
); );
?>

View File

@@ -35,4 +35,3 @@
) )
) )
); );
?>

View File

@@ -175,4 +175,3 @@
) // query_string element list ) // query_string element list
) // element list ) // element list
); );
?>

View File

@@ -52,4 +52,4 @@
) )
) )
); // main array ); // main array
?>

View File

@@ -251,4 +251,3 @@
) // edit pages ggroup ) // edit pages ggroup
) )
); );
?>

View File

@@ -28,4 +28,3 @@
) )
) )
); );
?>

2
www/cache/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
*
!.gitignore

View File

@@ -12,6 +12,8 @@
DEFINE('EDIT_SESSION_NAME', "<ADMIN SESSION NAME>"); DEFINE('EDIT_SESSION_NAME', "<ADMIN SESSION NAME>");
// frontend // frontend
DEFINE('SESSION_NAME', "<SESSION NAME>"); DEFINE('SESSION_NAME', "<SESSION NAME>");
// set the session name
define('SET_SESSION_NAME', EDIT_SESSION_NAME);
/************* LANGUAGE / ENCODING *******/ /************* LANGUAGE / ENCODING *******/
DEFINE('DEFAULT_LANG', "en_utf8"); DEFINE('DEFAULT_LANG', "en_utf8");
@@ -186,9 +188,8 @@
// live frontend pages // live frontend pages
// ** missing live domains ** // ** missing live domains **
// get the name without the port // get the name without the port
list($HOST_NAME) = explode(":", $_SERVER['HTTP_HOST']); list($HOST_NAME, $PORT) = array_pad(explode(":", $_SERVER['HTTP_HOST'], 2), 2, null);
if (!$DB_HOST[$HOST_NAME] && $USE_DATABASE) if (!$DB_HOST[$HOST_NAME] && $USE_DATABASE) {
{
echo "No matching DB config found. Contact Admin<br>"; echo "No matching DB config found. Contact Admin<br>";
exit -1; exit -1;
} }
@@ -229,18 +230,15 @@
'/usr/local/bin' '/usr/local/bin'
); );
// find convert // find convert
foreach ($paths as $path) foreach ($paths as $path) {
{ if (file_exists($path."/convert") && is_file($path."/convert")) {
if (file_exists($path."/convert") && is_file($path."/convert"))
{
// image magick convert location // image magick convert location
DEFINE('CONVERT', $path."/convert"); DEFINE('CONVERT', $path."/convert");
} }
} }
// turn off debug if debug flag is OFF // turn off debug if debug flag is OFF
if (DEBUG == false) if (DEBUG == false) {
{
$ECHO_ALL = 0; $ECHO_ALL = 0;
$DEBUG_ALL = 0; $DEBUG_ALL = 0;
$PRINT_ALL = 0; $PRINT_ALL = 0;
@@ -267,14 +265,11 @@
__DIR__.'/'.SMARTY __DIR__.'/'.SMARTY
); );
// try to find and load the class ifle // try to find and load the class ifle
foreach ($dirs as $folder) foreach ($dirs as $folder) {
{ if (file_exists($folder.$include_file)) {
if (file_exists($folder.$include_file))
{
require_once($folder.$include_file); require_once($folder.$include_file);
return true; return true;
} }
} }
return false; return false;
} }
?>

View File

@@ -12,6 +12,8 @@
DEFINE('EDIT_SESSION_NAME', "<ADMIN SESSION NAME>"); DEFINE('EDIT_SESSION_NAME', "<ADMIN SESSION NAME>");
// frontend // frontend
DEFINE('SESSION_NAME', "<SESSION NAME>"); DEFINE('SESSION_NAME', "<SESSION NAME>");
// set the session name
define('SET_SESSION_NAME', EDIT_SESSION_NAME);
/************* LANGUAGE / ENCODING *******/ /************* LANGUAGE / ENCODING *******/
DEFINE('DEFAULT_LANG', "en_utf8"); DEFINE('DEFAULT_LANG', "en_utf8");
@@ -186,9 +188,8 @@
// live frontend pages // live frontend pages
// ** missing live domains ** // ** missing live domains **
// get the name without the port // get the name without the port
list($HOST_NAME) = explode(":", $_SERVER['HTTP_HOST']); list($HOST_NAME, $PORT) = array_pad(explode(":", $_SERVER['HTTP_HOST'], 2), 2, null);
if (!$DB_HOST[$HOST_NAME] && $USE_DATABASE) if (!$DB_HOST[$HOST_NAME] && $USE_DATABASE) {
{
echo "No matching DB config found. Contact Admin<br>"; echo "No matching DB config found. Contact Admin<br>";
exit -1; exit -1;
} }
@@ -229,18 +230,15 @@
'/usr/local/bin' '/usr/local/bin'
); );
// find convert // find convert
foreach ($paths as $path) foreach ($paths as $path) {
{ if (file_exists($path."/convert") && is_file($path."/convert")) {
if (file_exists($path."/convert") && is_file($path."/convert"))
{
// image magick convert location // image magick convert location
DEFINE('CONVERT', $path."/convert"); DEFINE('CONVERT', $path."/convert");
} }
} }
// turn off debug if debug flag is OFF // turn off debug if debug flag is OFF
if (DEBUG == false) if (DEBUG == false) {
{
$ECHO_ALL = 0; $ECHO_ALL = 0;
$DEBUG_ALL = 0; $DEBUG_ALL = 0;
$PRINT_ALL = 0; $PRINT_ALL = 0;
@@ -267,14 +265,11 @@
__DIR__.'/'.SMARTY __DIR__.'/'.SMARTY
); );
// try to find and load the class ifle // try to find and load the class ifle
foreach ($dirs as $folder) foreach ($dirs as $folder) {
{ if (file_exists($folder.$include_file)) {
if (file_exists($folder.$include_file))
{
require_once($folder.$include_file); require_once($folder.$include_file);
return true; return true;
} }
} }
return false; return false;
} }
?>

View File

@@ -15,416 +15,353 @@
padding: 0; padding: 0;
} */ } */
body body {
{
background-color: white; background-color: white;
color: black; color: black;
font-size : 8pt;
font-family: Verdana,Arial,Helvetica,sans-serif; font-family: Verdana,Arial,Helvetica,sans-serif;
font-size : 8pt;
} }
.large .large {
{ font-family: Verdana,Arial,Helvetica,sans-serif;
font-size : 16pt; font-size : 16pt;
font-family: Verdana,Arial,Helvetica,sans-serif;
} }
.big .big {
{ font-family: Verdana,Arial,Helvetica,sans-serif;
font-size : 12pt; font-size : 12pt;
font-family: Verdana,Arial,Helvetica,sans-serif;
} }
.normal .normal {
{ font-family: Verdana,Arial,Helvetica,sans-serif;
font-size : 9pt; font-size : 9pt;
font-family: Verdana,Arial,Helvetica,sans-serif;
} }
.small .small {
{
font-size : 8pt;
font-family: Verdana,Arial,Helvetica,sans-serif; font-family: Verdana,Arial,Helvetica,sans-serif;
font-size : 8pt;
} }
.smallbold .smallbold {
{
font-size : 8pt;
font-family: Verdana,Arial,Helvetica,sans-serif; font-family: Verdana,Arial,Helvetica,sans-serif;
font-size : 8pt;
font-weight: bold; font-weight: bold;
} }
a:link a:link {
{
color: #FF0000; color: #FF0000;
text-decoration: none; text-decoration: none;
} }
a:active a:active {
{
color: #FFFF00; color: #FFFF00;
text-decoration: none; text-decoration: none;
} }
a:visited a:visited {
{
color: #550000; color: #550000;
text-decoration: none; text-decoration: none;
} }
a:hover, a.item_loaded:hover, a.item_deleted:hover, a.item_loaded_deleted:hover a:hover, a.item_loaded:hover, a.item_deleted:hover, a.item_loaded_deleted:hover {
{
color: #FF0000;
background-color: #e5e5e5; background-color: #e5e5e5;
border-bottom: 1px dotted red; border-bottom: 1px dotted red;
color: #FF0000;
} }
a:focus, a.item_loaded:hover, a.item_deleted:hover, a.item_loaded_deleted:hover a:focus, a.item_loaded:hover, a.item_deleted:hover, a.item_loaded_deleted:hover {
{
color: #ff0000;
background-color: #b3b3b3; background-color: #b3b3b3;
border-top: 1px dotted red;
border-bottom: 1px dotted red; border-bottom: 1px dotted red;
border-top: 1px dotted red;
color: #ff0000;
} }
/* link highlight */ /* link highlight */
a.item_loaded a.item_loaded {
{
font-weight: bold;
color: #451010;
background-color: #d5d6d6; background-color: #d5d6d6;
color: #451010;
font-weight: bold;
} }
a.item_deleted a.item_deleted {
{
text-decoration: line-through; text-decoration: line-through;
} }
a.item_loaded_deleted a.item_loaded_deleted {
{
text-decoration: line-through;
font-weight: bold;
color: #451010;
background-color: #d5d6d6; background-color: #d5d6d6;
color: #451010;
font-weight: bold;
text-decoration: line-through;
} }
/* experimental */ /* experimental */
input[type="text"] input[type="text"] {
{
border: 1px solid #999999;
background-color: #efefef; background-color: #efefef;
}
input[type="password"]
{
border: 1px solid #999999; border: 1px solid #999999;
} }
input[type="submit"] input[type="password"] {
{ border: 1px solid #999999;
}
input[type="submit"] {
border: 1px solid #666666; border: 1px solid #666666;
} }
input[type="checkbox"] input[type="checkbox"] {
{
border: 1px solid #999999; border: 1px solid #999999;
} }
input[type="radio"] input[type="radio"] {
{
border: 1px solid #999999; border: 1px solid #999999;
} }
input[type="file"] input[type="file"] {
{
border: 1px solid #999999; border: 1px solid #999999;
} }
input[type="button"] input[type="button"] {
{
border: 1px solid #999999; border: 1px solid #999999;
} }
textarea textarea {
{
border: 1px solid #999999;
background-color: #efefef; background-color: #efefef;
border: 1px solid #999999;
} }
select select {
{
border: 1px solid #999999;
background-color: #efefef; background-color: #efefef;
border: 1px solid #999999;
} }
/* mouse over */ /* mouse over */
input[type=submit]:hover, input[type=button]:hover, input[type="text"]:hover, input[type="password"]:hover, input[type="checkbox"]:hover, input[type="radio"]:hover, input[type="file"]:hover, textarea:hover, select:hover input[type=submit]:hover, input[type=button]:hover, input[type="text"]:hover, input[type="password"]:hover, input[type="checkbox"]:hover, input[type="radio"]:hover, input[type="file"]:hover, textarea:hover, select:hover {
{
border: 1px dashed red; border: 1px dashed red;
} }
/* selected */ /* selected */
input[type=submit]:focus, input[type=button]:focus, input[type="password"]:focus, input[type="checkbox"]:focus, input[type="radio"]:focus, input[type="file"]:focus input[type=submit]:focus, input[type=button]:focus, input[type="password"]:focus, input[type="checkbox"]:focus, input[type="radio"]:focus, input[type="file"]:focus {
{
border: 1px solid red;
background-color: #ffffff; background-color: #ffffff;
border: 1px solid red;
} }
input[type="text"]:focus, textarea:focus, select:focus input[type="text"]:focus, textarea:focus, select:focus {
{
border: 1px solid red;
background-color: #ffffff; background-color: #ffffff;
border: 1px solid red;
} }
/* error & status layouts for messges */ /* error & status layouts for messges */
.error .error {
{
border: 1px solid red; border: 1px solid red;
margin: 5px;
padding: 2px;
color: red; color: red;
margin: 5px;
padding: 2px;
text-align: center; text-align: center;
} }
.warning .warning {
{
border: 1px solid #df7700; border: 1px solid #df7700;
margin: 5px;
padding: 2px;
color: #d57200; color: #d57200;
text-align: center;
}
.info
{
border: 1px solid #72C47E;
margin: 5px; margin: 5px;
padding: 2px; padding: 2px;
color: #1D731A;
text-align: center; text-align: center;
} }
.div_error .info {
{ border: 1px solid #72C47E;
border: 1px solid red; color: #1D731A;
margin-top: 1px; margin: 5px;
margin-bottom: 1px; padding: 2px;
text-align: center;
} }
.div_warning .div_error {
{ border: 1px solid red;
margin-bottom: 1px;
margin-top: 1px;
}
.div_warning {
border: 1px solid #df7700; border: 1px solid #df7700;
} }
/* borders */ /* borders */
.border_all .border_all {
{
border: 1px solid black; border: 1px solid black;
} }
.border_bottom_title .border_bottom_title {
{
font-weight: bold;
border-bottom: 1px solid black; border-bottom: 1px solid black;
font-weight: bold;
} }
.border_top .border_top {
{
border-top: 1px solid #DCDCCC; border-top: 1px solid #DCDCCC;
} }
.border_all_error .border_all_error {
{
border: 1px solid red; border: 1px solid red;
} }
.border_group .border_group {
{
border: 1px solid #a89c5a; border: 1px solid #a89c5a;
} }
.border_master .border_master {
{
border: 1px solid white; border: 1px solid white;
} }
.border_sub .border_sub {
{
border: 1px solid gray; border: 1px solid gray;
} }
.border_sub_sub .border_sub_sub {
{
border: 1px solid #e5ddba; border: 1px solid #e5ddba;
} }
/* employee hardware/software borders */ /* employee hardware/software borders */
.border_hardware .border_hardware {
{ background-color: #e9e9e9;
border: 2px solid black; border: 2px solid black;
background-color: #e9e9e9;
} }
.border_hardware_usage_end .border_hardware_usage_end {
{ background-color: #e9e9e9;
border: 2px solid red; border: 2px solid red;
background-color: #e9e9e9;
} }
.border_hardware_line .border_hardware_line {
{
border-left: 2px solid black;
border-bottom: 2px solid black; border-bottom: 2px solid black;
border-left: 2px solid black;
} }
.border_software .border_software {
{
border: 2px solid #a89c5a;
background-color: #d5d4c8; background-color: #d5d4c8;
border: 2px solid #a89c5a;
} }
.border_software_line .border_software_line {
{
border-left: 2px solid #a89c5a;
border-bottom: 2px solid #a89c5a; border-bottom: 2px solid #a89c5a;
border-left: 2px solid #a89c5a;
} }
.border_software_line_left .border_software_line_left {
{
border-left: 2px solid #a89c5a; border-left: 2px solid #a89c5a;
padding-bottom: 10px; padding-bottom: 10px;
} }
.border_software_line_bottom .border_software_line_bottom {
{
border-bottom: 2px solid #a89c5a; border-bottom: 2px solid #a89c5a;
padding-left: 2px; padding-left: 2px;
} }
/* highlight */ /* highlight */
.highlight .highlight {
{
background-color: #e7e7e7; background-color: #e7e7e7;
font-weight: bold; font-weight: bold;
} }
/* hide & show */ /* hide & show */
.visible .visible {
{
visibility: visible; visibility: visible;
} }
.hidden .hidden {
{
visibility: hidden;
display: none; display: none;
visibility: hidden;
} }
/* spacer for line break in float elements */ /* spacer for line break in float elements */
div.spacer .spacer {
{
clear: both; clear: both;
} }
/* unique definitions */ /* unique definitions */
/* main body */ /* main body */
/* menu on top */ /* menu on top */
.menu .menu {
{
border-bottom: 1px solid #a4a4a4; border-bottom: 1px solid #a4a4a4;
font-size: 10px; font-size: 10px;
} }
.pagename .pagename {
{
text-align: center; font-size: 15px;
background-color: #e7e7e7; background-color: #e7e7e7;
font-size: 15px;
font-weight: bold; font-weight: bold;
padding: 5px; padding: 5px;
text-align: center;
} }
/* overlay side menu */ /* overlay side menu */
.sidemenu .sidemenu {
{
border: 1px solid black;
background-color: white; background-color: white;
border: 1px solid black;
} }
.buttongroup .buttongroup {
{
border: 1px solid #e5ddba; border: 1px solid #e5ddba;
} }
/* input group field */ /* input group field */
/* normal */ /* normal */
.input_group .input_group {
{
border: 1px solid #e5ddba; border: 1px solid #e5ddba;
} }
/* loaded with id */ /* loaded with id */
.input_group_id .input_group_id {
{
border: 1px solid #8a7d3a; border: 1px solid #8a7d3a;
} }
/* deleted */ /* deleted */
.input_group_deleted .input_group_deleted {
{
border: 1px solid #8a7d3a;
background-color: #d5d4c8; background-color: #d5d4c8;
border: 1px solid #8a7d3a;
} }
/* header part */ /* header part */
/* normal */ /* normal */
.input_group_header .input_group_header {
{
background-color: #e9e9e9; background-color: #e9e9e9;
} }
/* loaded with id */ /* loaded with id */
.input_group_header_id .input_group_header_id {
{
background-color: #d5d5d5; background-color: #d5d5d5;
} }
/* deleted */ /* deleted */
.input_group_header_deleted .input_group_header_deleted {
{
background-color: #bfb59d; background-color: #bfb59d;
} }
/* error & warning messages */ /* error & warning messages */
.top_error_message .top_error_message {
{ border: 2px solid red;
color: red;
font-size: 18px;
margin: 5px; margin: 5px;
padding: 10px; padding: 10px;
border: 2px solid red;
font-size: 18px;
text-align: center; text-align: center;
color: red;
} }
.top_inventory_number .top_inventory_number {
{
margin: 5px;
padding: 10px;
border: 2px solid orange; border: 2px solid orange;
font-size: 18px; font-size: 18px;
text-align: center;
}
.top_info_message
{
border: 2px solid green;
margin: 5px; margin: 5px;
padding: 10px; padding: 10px;
text-align: center; text-align: center;
font-size: 12px;
} }
.debug_message .top_info_message {
{ border: 2px solid green;
font-size: 12px;
margin: 5px;
padding: 10px;
text-align: center;
}
.debug_message {
border-top: 1px solid #a4a4a4; border-top: 1px solid #a4a4a4;
color: #a4a4a4; color: #a4a4a4;
font-size: 8px; font-size: 8px;
@@ -434,78 +371,63 @@ div.spacer
/* set all colors here and not in the config file */ /* set all colors here and not in the config file */
/* for edit interface */ /* for edit interface */
.menu_bgcolor .menu_bgcolor {
{
background-color: #666666; background-color: #666666;
} }
.menu_fgcolor .menu_fgcolor {
{
background-color: #DDDDDD; background-color: #DDDDDD;
} }
.menu_fgcolor_na .menu_fgcolor_na {
{
background-color: #CCCCCC; background-color: #CCCCCC;
} }
.menu_fgcolor_a .menu_fgcolor_a {
{
background-color: #EEEEEE; background-color: #EEEEEE;
} }
.edit_bgcolor .edit_bgcolor {
{
background-color: #666666; background-color: #666666;
} }
.edit_fgcolor .edit_fgcolor {
{
background-color: #FFFFDF; background-color: #FFFFDF;
} }
.edit_fgcolor_mod_a .edit_fgcolor_mod_a {
{
background-color: #CECEB5; background-color: #CECEB5;
} }
.edit_fgcolor_mod_b .edit_fgcolor_mod_b {
{
background-color: #DEDEC3; background-color: #DEDEC3;
} }
.edit_fgcolor_2 .edit_fgcolor_2 {
{
background-color: #AADAA2; background-color: #AADAA2;
} }
.edit_fgcolor_no .edit_fgcolor_no {
{
background-color: #CECEB5; background-color: #CECEB5;
} }
.edit_fgcolor_alt .edit_fgcolor_alt {
{
background-color: #CCCCCC; background-color: #CCCCCC;
} }
.edit_fgcolor_delete .edit_fgcolor_delete {
{
background-color: red; background-color: red;
} }
.font_error .font_error {
{
color: red; color: red;
} }
.edit_fgcolor_special .edit_fgcolor_special {
{
background-color: #EEEEEE; background-color: #EEEEEE;
} }
.edit_temp .edit_temp {
{
background-color: #FFDF6F; background-color: #FFDF6F;
} }

View File

@@ -9,9 +9,8 @@
*/ */
// if debug is set to true, console log messages are printed // if debug is set to true, console log messages are printed
if (!DEBUG) if (!DEBUG) {
{
$($H(window.console)).each(function(w) { $($H(window.console)).each(function(w) {
window.console[w.key] = function() {} window.console[w.key] = function() {};
}); });
} }

View File

@@ -6,50 +6,43 @@
* Some browser detection * Some browser detection
*/ */
var clientPC = navigator.userAgent.toLowerCase(); // Get client info var clientPC = navigator.userAgent.toLowerCase(); // Get client info
var is_gecko = ((clientPC.indexOf('gecko') != -1) && (clientPC.indexOf('spoofer') == -1) var is_gecko = ((clientPC.indexOf('gecko') != -1) && (clientPC.indexOf('spoofer') == -1) &&
&& (clientPC.indexOf('khtml') == -1) && (clientPC.indexOf('netscape/7.0') == -1)); (clientPC.indexOf('khtml') == -1) && (clientPC.indexOf('netscape/7.0') == -1));
var is_safari = ((clientPC.indexOf('AppleWebKit') != -1) && (clientPC.indexOf('spoofer') == -1)); var is_safari = ((clientPC.indexOf('AppleWebKit') != -1) && (clientPC.indexOf('spoofer') == -1));
var is_khtml = (navigator.vendor == 'KDE' || ( document.childNodes && !document.all && !navigator.taintEnabled )); var is_khtml = (navigator.vendor == 'KDE' || ( document.childNodes && !document.all && !navigator.taintEnabled ));
if (clientPC.indexOf('opera') != -1) if (clientPC.indexOf('opera') != -1) {
{
var is_opera = true; var is_opera = true;
var is_opera_preseven = (window.opera && !document.childNodes); var is_opera_preseven = (window.opera && !document.childNodes);
var is_opera_seven = (window.opera && document.childNodes); var is_opera_seven = (window.opera && document.childNodes);
} }
function pop(theURL, winName, features) function pop(theURL, winName, features) {
{
winName = window.open(theURL, winName, features); winName = window.open(theURL, winName, features);
winName.focus(); winName.focus();
} }
function emd_check_checkbox() function emd_check_checkbox() {
{ for (i = 0; i < document.manage_emails.length; i ++) {
for (i = 0; i < document.manage_emails.length; i ++) if (document.manage_emails.elements[i].checked == false && document.manage_emails.elements[i].type == 'checkbox') {
{
if (document.manage_emails.elements[i].checked == false && document.manage_emails.elements[i].type == 'checkbox')
{
document.manage_emails.elements[i].checked = true; document.manage_emails.elements[i].checked = true;
} }
} }
} }
function expandTA(ta_id) function expandTA(ta_id) {
{
var ta; var ta;
// if a string comes, its a get by id, else use it as an element pass on // if a string comes, its a get by id, else use it as an element pass on
if (!ta_id.length) if (!ta_id.length) {
ta = ta_id; ta = ta_id;
else } else {
ta = document.getElementById(ta_id); ta = document.getElementById(ta_id);
}
var maxChars = ta.cols; var maxChars = ta.cols;
var theRows = ta.value.split("\n"); var theRows = ta.value.split("\n");
var numNewRows = 0; var numNewRows = 0;
for ( var i = 0; i < theRows.length; i++ ) for ( var i = 0; i < theRows.length; i++ ) {
{ if ((theRows[i].length+2) > maxChars) {
if ((theRows[i].length+2) > maxChars)
{
numNewRows += Math.ceil( (theRows[i].length+2) / maxChars ) ; numNewRows += Math.ceil( (theRows[i].length+2) / maxChars ) ;
} }
} }
@@ -62,27 +55,27 @@ function expandTA(ta_id)
// DESC: shows or hides the menu // DESC: shows or hides the menu
function ShowHideMenu(status, id) function ShowHideMenu(status, id)
{ {
if (status == 'show') if (status == 'show') {
{
document.getElementById(id).style.visibility = 'visible'; document.getElementById(id).style.visibility = 'visible';
if (document.getElementById('search_results').innerHTML) if (document.getElementById('search_results').innerHTML) {
document.getElementById('search_results').style.visibility = 'visible'; document.getElementById('search_results').style.visibility = 'visible';
} }
else if (status == 'hide') } else if (status == 'hide') {
{
document.getElementById(id).style.visibility = 'hidden'; document.getElementById(id).style.visibility = 'hidden';
if (document.getElementById('search_results').style.visibility == 'visible') if (document.getElementById('search_results').style.visibility == 'visible') {
document.getElementById('search_results').style.visibility = 'hidden'; document.getElementById('search_results').style.visibility = 'hidden';
} }
} }
}
function ShowHideDiv(id) function ShowHideDiv(id)
{ {
element = document.getElementById(id); element = document.getElementById(id);
if (element.className == 'visible' || !element.className) if (element.className == 'visible' || !element.className) {
element.className = 'hidden'; element.className = 'hidden';
else } else {
element.className = 'visible'; element.className = 'visible';
}
// alert('E: ' + element.className + ' -- ' + element.style.visibility); // alert('E: ' + element.className + ' -- ' + element.style.visibility);
} }
@@ -100,15 +93,17 @@ function mv(id, direction)
function le(id) function le(id)
{ {
document.forms[form_name].action.value = 'load'; document.forms[form_name].action.value = 'load';
if (load_id) if (load_id) {
document.forms[form_name].action_yes.value = confirm('Do you want to load this data?'); document.forms[form_name].action_yes.value = confirm('Do you want to load this data?');
else } else {
document.forms[form_name].action_yes.value = 'true'; document.forms[form_name].action_yes.value = 'true';
}
document.forms[form_name].action_id.value = id; document.forms[form_name].action_id.value = id;
document.forms[form_name].action_menu.value = id; document.forms[form_name].action_menu.value = id;
if (document.forms[form_name].action_yes.value == 'true') if (document.forms[form_name].action_yes.value == 'true') {
document.forms[form_name].submit(); document.forms[form_name].submit();
} }
}
// METHOD: getWindowSize // METHOD: getWindowSize
// PARAMS: none // PARAMS: none
@@ -119,7 +114,10 @@ function getWindowSize()
var width, height; var width, height;
width = window.innerWidth || (window.document.documentElement.clientWidth || window.document.body.clientWidth); width = window.innerWidth || (window.document.documentElement.clientWidth || window.document.body.clientWidth);
height = window.innerHeight || (window.document.documentElement.clientHeight || window.document.body.clientHeight); height = window.innerHeight || (window.document.documentElement.clientHeight || window.document.body.clientHeight);
return {width: width, height: height}; return {
width: width,
height: height
};
} }
// METHOD: getScrollOffset // METHOD: getScrollOffset
@@ -131,7 +129,10 @@ function getScrollOffset()
var left, top; var left, top;
left = window.pageXOffset || (window.document.documentElement.scrollLeft || window.document.body.scrollLeft); left = window.pageXOffset || (window.document.documentElement.scrollLeft || window.document.body.scrollLeft);
top = window.pageYOffset || (window.document.documentElement.scrollTop || window.document.body.scrollTop); top = window.pageYOffset || (window.document.documentElement.scrollTop || window.document.body.scrollTop);
return {left: left, top: top}; return {
left: left,
top: top
};
} }
// METHOD: setCenter // METHOD: setCenter
@@ -142,22 +143,23 @@ function setCenter(id, left, top)
{ {
// get size of id // get size of id
var dimensions = $(id).getDimensions(); var dimensions = $(id).getDimensions();
var type = $(id).getStyle('position');
var viewport = getWindowSize(); var viewport = getWindowSize();
var offset = getScrollOffset(); var offset = getScrollOffset();
console.log('Id %s, dimensions %s x %s, viewport %s x %s', id, dimensions.width, dimensions.height, viewport.width, viewport.height); // console.log('Id %s, type: %s, dimensions %s x %s, viewport %s x %s', id, $(id).getStyle('position'), dimensions.width, dimensions.height, viewport.width, viewport.height);
console.log('Scrolloffset left: %s, top: %s', offset.left, offset.top); // console.log('Scrolloffset left: %s, top: %s', offset.left, offset.top);
console.log('Left: %s, Top: %s', parseInt((viewport.width / 2) - (dimensions.width / 2)), parseInt((viewport.height / 2) - (dimensions.height / 2))); // console.log('Left: %s, Top: %s (%s)', parseInt((viewport.width / 2) - (dimensions.width / 2) + offset.left), parseInt((viewport.height / 2) - (dimensions.height / 2) + offset.top), parseInt((viewport.height / 2) - (dimensions.height / 2)));
if (left) if (left) {
{
$(id).setStyle ({ $(id).setStyle ({
left: parseInt((viewport.width / 2) - (dimensions.width / 2) + offset.left) + 'px' left: parseInt((viewport.width / 2) - (dimensions.width / 2) + offset.left) + 'px'
}); });
} }
if (top) if (top) {
{ // if we have fixed, we do not add the offset, else it moves out of the screen
var top_pos = type == 'fixed' ? parseInt((viewport.height / 2) - (dimensions.height / 2)) : parseInt((viewport.height / 2) - (dimensions.height / 2) + offset.top);
$(id).setStyle ({ $(id).setStyle ({
top: parseInt((viewport.height / 2) - (dimensions.height / 2) + offset.top) + 'px' top: top_pos + 'px'
}); });
} }
} }
@@ -175,15 +177,12 @@ function sh(id, showText, hideText)
// get status from element (hidden or visible) // get status from element (hidden or visible)
divStatus = $(id).visible(); divStatus = $(id).visible();
//console.log('Set flag %s for element %s', divStatus, id); //console.log('Set flag %s for element %s', divStatus, id);
if (divStatus) if (divStatus) {
{
// hide the element // hide the element
Effect.BlindUp(id, {duration:0.3}); Effect.BlindUp(id, {duration:0.3});
$(flag).value = 0; $(flag).value = 0;
$(btn).innerHTML = showText; $(btn).innerHTML = showText;
} } else if (!divStatus) {
else if (!divStatus)
{
// show the element // show the element
Effect.BlindDown(id, {duration:0.3}); Effect.BlindDown(id, {duration:0.3});
$(flag).value = 1; $(flag).value = 1;

View File

@@ -10,7 +10,7 @@ var ConsoleSetup = function() {
for (var i = 0; i < names.length; ++i) { for (var i = 0; i < names.length; ++i) {
if (!window.console[names[i]]) { if (!window.console[names[i]]) {
window.console[names[i]] = function() {} window.console[names[i]] = function() {};
} }
} }
}(); }();

View File

@@ -1,5 +1,4 @@
.debug_message .debug_message {
{
border-top: 1px solid #a4a4a4; border-top: 1px solid #a4a4a4;
color: #a4a4a4; color: #a4a4a4;
font-size: 8px; font-size: 8px;

View File

@@ -8,10 +8,10 @@
// PARAMS: front/back -> what image to show // PARAMS: front/back -> what image to show
// RETURN: none // RETURN: none
// DESC: ajax call to switch the main image in the detail view // DESC: ajax call to switch the main image in the detail view
function SwitchImage(image) function SwitchImage(image) {
{ if (image != 'front' || image != 'back') {
if (image != 'front' || image != 'back')
image = 'front'; image = 'front';
}
// disable / enable the href for the other side // disable / enable the href for the other side
x_ajax_afSwitchImage(image, OutputSwitchImage); x_ajax_afSwitchImage(image, OutputSwitchImage);
} }
@@ -20,7 +20,6 @@ function SwitchImage(image)
// PARAMS: data -> the image full path for the new image // PARAMS: data -> the image full path for the new image
// RETURN: none // RETURN: none
// DESC: replace the image in the product detail with the back image // DESC: replace the image in the product detail with the back image
function OutputSwitchImage(data) function OutputSwitchImage(data) {
{
} }

View File

@@ -3,9 +3,7 @@
* AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org) * AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org)
* CREATED: 2006/08/15 * CREATED: 2006/08/15
* VERSION: 0.1.0 * VERSION: 0.1.0
* RELEASED LICENSE: BSD style (use it, u don't have to make YOUR source public) * RELEASED LICENSE: GNU GPL 3
* but let me know if u made changes, and please don't redistribute it
* with your name on it ...
* DESCRIPTION * DESCRIPTION
* Basic Admin interface backend * Basic Admin interface backend
* - sets action flags * - sets action flags
@@ -83,8 +81,7 @@
$this->page_name = $this->get_page_name(); $this->page_name = $this->get_page_name();
// set the action ids // set the action ids
foreach ($this->action_list as $_action) foreach ($this->action_list as $_action) {
{
$this->$_action = (isset($_POST[$_action])) ? $_POST[$_action] : ''; $this->$_action = (isset($_POST[$_action])) ? $_POST[$_action] : '';
} }
@@ -97,9 +94,17 @@
$this->key_length = 4; // pow($this->one_key_length, 4); // hardcoded, should be more than enought (62*62*62*62) $this->key_length = 4; // pow($this->one_key_length, 4); // hardcoded, should be more than enought (62*62*62*62)
// queue key // queue key
if (preg_match("/^(add|save|delete|remove|move|up|down|push_live)$/", $this->action)) if (preg_match("/^(add|save|delete|remove|move|up|down|push_live)$/", $this->action)) {
{ $this->queue_key = join(
$this->queue_key = join('', array_map(function () { $range = $GLOBALS['_KEY_RANGE']; return $range[rand(0, (count($range) - 1))]; }, range(1, 3))); '',
array_map(
function () {
$range = $GLOBALS['_KEY_RANGE'];
return $range[rand(0, (count($range) - 1))];
},
range(1, 3)
)
);
} }
} }
@@ -120,13 +125,11 @@
// DESC: writes all action vars plus other info into edit_log table // DESC: writes all action vars plus other info into edit_log table
public function adbEditLog($event = '', $data = '', $write_type = 'STRING') public function adbEditLog($event = '', $data = '', $write_type = 'STRING')
{ {
if ($write_type == 'BINARY') if ($write_type == 'BINARY') {
{
$data_binary = $this->db_escape_bytea(bzcompress(serialize($data))); $data_binary = $this->db_escape_bytea(bzcompress(serialize($data)));
$data = 'see bzip compressed data_binary field'; $data = 'see bzip compressed data_binary field';
} }
if ($write_type == 'STRING') if ($write_type == 'STRING') {
{
$data = $this->db_escape_string(serialize($data)); $data = $this->db_escape_string(serialize($data));
} }
@@ -136,8 +139,16 @@
$q .= "action, action_id, action_yes, action_flag, action_menu, action_loaded, action_value, action_error) "; $q .= "action, action_id, action_yes, action_flag, action_menu, action_loaded, action_value, action_error) ";
$q .= "VALUES "; $q .= "VALUES ";
$q .= "(".@$_SESSION['EUID'].", NOW(), '".$this->db_escape_string($event)."', '".$data."', '".$data_binary."', '".$this->page_name."', "; $q .= "(".@$_SESSION['EUID'].", NOW(), '".$this->db_escape_string($event)."', '".$data."', '".$data_binary."', '".$this->page_name."', ";
$q .= "'".@$_SERVER["REMOTE_ADDR"]."', '".$this->db_escape_string(@$_SERVER['HTTP_USER_AGENT'])."', '".$this->db_escape_string(@$_SERVER['HTTP_REFERER'])."', '".$this->db_escape_string(@$_SERVER['SCRIPT_FILENAME'])."', '".$this->db_escape_string(@$_SERVER['QUERY_STRING'])."', '".$this->db_escape_string(@$_SERVER['SERVER_NAME'])."', '".$this->db_escape_string(@$_SERVER['HTTP_HOST'])."', '".$this->db_escape_string(@$_SERVER['HTTP_ACCEPT'])."', '".$this->db_escape_string(@$_SERVER['HTTP_ACCEPT_CHARSET'])."', '".$this->db_escape_string(@$_SERVER['HTTP_ACCEPT_ENCODING'])."', '".session_id()."', "; $q .= "'".@$_SERVER["REMOTE_ADDR"]."', '".$this->db_escape_string(@$_SERVER['HTTP_USER_AGENT'])."', ";
$q .= "'".$this->db_escape_string($this->action)."', '".$this->db_escape_string($this->action_id)."', '".$this->db_escape_string($this->action_yes)."', '".$this->db_escape_string($this->action_flag)."', '".$this->db_escape_string($this->action_menu)."', '".$this->db_escape_string($this->action_loaded)."', '".$this->db_escape_string($this->action_value)."', '".$this->db_escape_string($this->action_error)."')"; $q .= "'".$this->db_escape_string(@$_SERVER['HTTP_REFERER'])."', '".$this->db_escape_string(@$_SERVER['SCRIPT_FILENAME'])."', ";
$q .= "'".$this->db_escape_string(@$_SERVER['QUERY_STRING'])."', '".$this->db_escape_string(@$_SERVER['SERVER_NAME'])."', ";
$q .= "'".$this->db_escape_string(@$_SERVER['HTTP_HOST'])."', '".$this->db_escape_string(@$_SERVER['HTTP_ACCEPT'])."', ";
$q .= "'".$this->db_escape_string(@$_SERVER['HTTP_ACCEPT_CHARSET'])."', '".$this->db_escape_string(@$_SERVER['HTTP_ACCEPT_ENCODING'])."', ";
$q .= "'".session_id()."', ";
$q .= "'".$this->db_escape_string($this->action)."', '".$this->db_escape_string($this->action_id)."', ";
$q .= "'".$this->db_escape_string($this->action_yes)."', '".$this->db_escape_string($this->action_flag)."', ";
$q .= "'".$this->db_escape_string($this->action_menu)."', '".$this->db_escape_string($this->action_loaded)."', ";
$q .= "'".$this->db_escape_string($this->action_value)."', '".$this->db_escape_string($this->action_error)."')";
$this->db_exec($q, 'NULL'); $this->db_exec($q, 'NULL');
} }
@@ -154,80 +165,72 @@
// DESC: menu creater // DESC: menu creater
public function adbTopMenu($flag = 0) public function adbTopMenu($flag = 0)
{ {
if ($this->menu_show_flag) if ($this->menu_show_flag) {
$flag = $this->menu_show_flag; $flag = $this->menu_show_flag;
}
// get the session pages array // get the session pages array
$pages = $_SESSION["PAGES"]; $pages = $_SESSION["PAGES"];
if (!is_array($pages)) if (!is_array($pages)) {
$pages = array (); $pages = array ();
}
//$this->debug('pages', $this->print_ar($pages)); //$this->debug('pages', $this->print_ar($pages));
// if flag is 0, then we show all, else, we show only the matching flagges array points // if flag is 0, then we show all, else, we show only the matching flagges array points
// array is already sorted after correct order // array is already sorted after correct order
reset($pages); reset($pages);
for ($i = 0; $i < count($pages); $i ++) for ($i = 0; $i < count($pages); $i ++) {
{
$show = 0; $show = 0;
// is it visible in the menu & is it online // is it visible in the menu & is it online
if ($pages[$i]["menu"] && $pages[$i]["online"]) if ($pages[$i]["menu"] && $pages[$i]["online"]) {
{
// check if it falls into our flag if we have a flag // check if it falls into our flag if we have a flag
if ($flag) if ($flag) {
{ foreach ($pages[$i]["visible"] as $name => $key) {
foreach ($pages[$i]["visible"] AS $name => $key) if ($key == $flag) {
{
if ($key == $flag)
$show = 1; $show = 1;
} }
} }
else } else {
{
// if no flag given, show all menu points // if no flag given, show all menu points
$show = 1; $show = 1;
} }
if ($show) if ($show) {
{
// if it is popup, write popup arrayound // if it is popup, write popup arrayound
if ($pages[$i]["popup"]) if ($pages[$i]["popup"]) {
{
$type = "popup"; $type = "popup";
} } else {
else
{
$type = "normal"; $type = "normal";
} }
$query_string = ''; $query_string = '';
if (count($pages[$i]["query"])) if (count($pages[$i]["query"])) {
{ for ($j = 0; $j < count($pages[$i]["query"]); $j ++) {
for ($j = 0; $j < count($pages[$i]["query"]); $j ++) if (strlen($query_string)) {
{
if (strlen($query_string))
$query_string .= "&"; $query_string .= "&";
}
$query_string .= $pages[$i]["query"][$j]["name"]."="; $query_string .= $pages[$i]["query"][$j]["name"]."=";
if (!$pages[$i]["query"][$j]["dynamic"]) if (!$pages[$i]["query"][$j]["dynamic"]) {
$query_string .= urlencode($pages[$i]["query"][$j]["value"]); $query_string .= urlencode($pages[$i]["query"][$j]["value"]);
else } else {
$query_string .= (($_GET[$pages[$i]["query"][$j]["value"]]) ? urlencode($_GET[$pages[$i]["query"][$j]["value"]]) : urlencode($_POST[$pages[$i]["query"][$j]["value"]])); $query_string .= $_GET[$pages[$i]["query"][$j]["value"]] ? urlencode($_GET[$pages[$i]["query"][$j]["value"]]) : urlencode($_POST[$pages[$i]["query"][$j]["value"]]);
}
} }
} }
$url = $pages[$i]["filename"]; $url = $pages[$i]["filename"];
if (strlen($query_string)) if (strlen($query_string)) {
$url .= "?".$query_string; $url .= "?".$query_string;
}
$name = $pages[$i]["page_name"]; $name = $pages[$i]["page_name"];
// if page name matchs -> set selected flag // if page name matchs -> set selected flag
$selected = 0; $selected = 0;
if ($this->get_page_name() == $pages[$i]["filename"]) if ($this->get_page_name() == $pages[$i]["filename"]) {
{
$selected = 1; $selected = 1;
$this->page_name = $name; $this->page_name = $name;
} }
// last check, is this menu point okay to show // last check, is this menu point okay to show
$enabled = 0; $enabled = 0;
if ($this->adbShowMenuPoint($pages[$i]["filename"])) if ($this->adbShowMenuPoint($pages[$i]["filename"])) {
{
$enabled = 1; $enabled = 1;
} }
// write in to view menu array // write in to view menu array
@@ -245,8 +248,7 @@
public function adbShowMenuPoint($filename) public function adbShowMenuPoint($filename)
{ {
$enabled = 0; $enabled = 0;
switch ($filename) switch ($filename) {
{
default: default:
$enabled = 1; $enabled = 1;
break; break;
@@ -297,17 +299,23 @@
// DESC: wrapper function to fill up the mssages array // DESC: wrapper function to fill up the mssages array
public function adbMsg($level, $msg, $vars = array ()) public function adbMsg($level, $msg, $vars = array ())
{ {
if (!preg_match("/^info|warning|error$/", $level)) if (!preg_match("/^info|warning|error$/", $level)) {
$level = "info"; $level = "info";
}
$this->messages[] = array ( $this->messages[] = array (
'msg' => sprintf($this->l->__($msg), $vars), 'msg' => sprintf($this->l->__($msg), $vars),
'class' => $level 'class' => $level
); );
switch ($level) switch ($level) {
{ case 'info':
case 'info': $this->info = 1; break; $this->info = 1;
case 'warning': $this->warning = 1; break; break;
case 'error': $this->error = 1; break; case 'warning':
$this->warning = 1;
break;
case 'error':
$this->error = 1;
break;
} }
} }
@@ -322,12 +330,16 @@
// file -> string for special file copy actions; mostyle "test#live;..." // file -> string for special file copy actions; mostyle "test#live;..."
// RETURN: none // RETURN: none
// DESC: writes live queue // DESC: writes live queue
public function adbLiveQueue($queue_key, $type, $target, $data, $key_name, $key_value, $associate = NULL, $file = NULL) public function adbLiveQueue($queue_key, $type, $target, $data, $key_name, $key_value, $associate = null, $file = null)
{ {
$q = "INSERT INTO ".GLOBAL_DB_SCHEMA.".live_queue ("; $q = "INSERT INTO ".GLOBAL_DB_SCHEMA.".live_queue (";
$q .= "queue_key, key_value, key_name, type, target, data, group_key, action, associate, file"; $q .= "queue_key, key_value, key_name, type, target, data, group_key, action, associate, file";
$q .= ") VALUES ("; $q .= ") VALUES (";
$q .= "'".$this->db_escape_string($queue_key)."', '".$this->db_escape_string($key_value)."', '".$this->db_escape_string($key_name)."', '".$this->db_escape_string($type)."', '".$this->db_escape_string($target)."', '".$this->db_escape_string($data)."', '".$this->queue_key."', '".$this->action."', '".$this->db_escape_string($associate)."', '".$this->db_escape_string($file)."')"; $q .= "'".$this->db_escape_string($queue_key)."', '".$this->db_escape_string($key_value)."', ";
$q .= "'".$this->db_escape_string($key_name)."', '".$this->db_escape_string($type)."', ";
$q .= "'".$this->db_escape_string($target)."', '".$this->db_escape_string($data)."', ";
$q .= "'".$this->queue_key."', '".$this->action."', '".$this->db_escape_string($associate)."', ";
$q .= "'".$this->db_escape_string($file)."')";
$this->db_exec($q); $this->db_exec($q);
} }
@@ -340,10 +352,12 @@
public function adbPrintDateTime($year, $month, $day, $hour, $min, $suffix = '', $min_steps = 1) public function adbPrintDateTime($year, $month, $day, $hour, $min, $suffix = '', $min_steps = 1)
{ {
// if suffix given, add _ before // if suffix given, add _ before
if ($suffix) if ($suffix) {
$suffix = '_'.$suffix; $suffix = '_'.$suffix;
if ($min_steps < 1 || $min_steps > 59) }
if ($min_steps < 1 || $min_steps > 59) {
$min_steps = 1; $min_steps = 1;
}
$on_change_call = 'dt_list(\''.$suffix.'\');'; $on_change_call = 'dt_list(\''.$suffix.'\');';
@@ -365,33 +379,28 @@
// from now to ? // from now to ?
$string = $this->l->__('Year').' '; $string = $this->l->__('Year').' ';
$string .= '<select id="year'.$suffix.'" name="year'.$suffix.'" onChange="'.$on_change_call.'">'; $string .= '<select id="year'.$suffix.'" name="year'.$suffix.'" onChange="'.$on_change_call.'">';
for ($i = date("Y"); $i <= $max_year; $i ++) for ($i = date("Y"); $i <= $max_year; $i ++) {
{
$string .= '<option value="'.$i.'" '.(($year == $i) ? 'selected' : '').'>'.$i.'</option>'; $string .= '<option value="'.$i.'" '.(($year == $i) ? 'selected' : '').'>'.$i.'</option>';
} }
$string .= '</select> '.$this->l->__('Month').' '; $string .= '</select> '.$this->l->__('Month').' ';
$string .= '<select id="month'.$suffix.'" name="month'.$suffix.'" onChange="'.$on_change_call.'">'; $string .= '<select id="month'.$suffix.'" name="month'.$suffix.'" onChange="'.$on_change_call.'">';
for ($i = 1; $i <= 12; $i ++) for ($i = 1; $i <= 12; $i ++) {
{
$string .= '<option value="'.(($i < 10) ? '0'.$i : $i).'" '.(($month == $i) ? 'selected' : '').'>'.$i.'</option>'; $string .= '<option value="'.(($i < 10) ? '0'.$i : $i).'" '.(($month == $i) ? 'selected' : '').'>'.$i.'</option>';
} }
$string .= '</select> '.$this->l->__('Day').' '; $string .= '</select> '.$this->l->__('Day').' ';
$string .= '<select id="day'.$suffix.'" name="day'.$suffix.'" onChange="'.$on_change_call.'">'; $string .= '<select id="day'.$suffix.'" name="day'.$suffix.'" onChange="'.$on_change_call.'">';
for ($i = 1; $i <= $days_in_month; $i ++) for ($i = 1; $i <= $days_in_month; $i ++) {
{
// set weekday text based on current month ($month) and year ($year) // set weekday text based on current month ($month) and year ($year)
$string .= '<option value="'.(($i < 10) ? '0'.$i : $i).'" '.(($day == $i) ? 'selected' : '').'>'.$i.' ('.$this->l->__(date('D', mktime(0, 0, 0, $month, $i, $year))).')</option>'; $string .= '<option value="'.(($i < 10) ? '0'.$i : $i).'" '.(($day == $i) ? 'selected' : '').'>'.$i.' ('.$this->l->__(date('D', mktime(0, 0, 0, $month, $i, $year))).')</option>';
} }
$string .= '</select> '.$this->l->__('Hour').' '; $string .= '</select> '.$this->l->__('Hour').' ';
$string .= '<select id="hour'.$suffix.'" name="hour'.$suffix.'" onChange="'.$on_change_call.'">'; $string .= '<select id="hour'.$suffix.'" name="hour'.$suffix.'" onChange="'.$on_change_call.'">';
for ($i = 0; $i <= 23; $i ++) for ($i = 0; $i <= 23; $i ++) {
{
$string .= '<option value="'.(($i < 10) ? '0'.$i : $i).'" '.(($hour == $i) ? 'selected' : '').'>'.$i.'</option>'; $string .= '<option value="'.(($i < 10) ? '0'.$i : $i).'" '.(($hour == $i) ? 'selected' : '').'>'.$i.'</option>';
} }
$string .= '</select> '.$this->l->__('Minute').' '; $string .= '</select> '.$this->l->__('Minute').' ';
$string .= '<select id="min'.$suffix.'" name="min'.$suffix.'" onChange="'.$on_change_call.'">'; $string .= '<select id="min'.$suffix.'" name="min'.$suffix.'" onChange="'.$on_change_call.'">';
for ( $i = 0; $i <= 59; $i += $min_steps) for ($i = 0; $i <= 59; $i += $min_steps) {
{
$string .= '<option value="'.(( $i < 10) ? '0'.$i : $i).'" '.(($min == $i) ? 'selected' : '').'>'.$i.'</option>'; $string .= '<option value="'.(( $i < 10) ? '0'.$i : $i).'" '.(($min == $i) ? 'selected' : '').'>'.$i.'</option>';
} }
$string .= '</select>'; $string .= '</select>';
@@ -399,4 +408,3 @@
return $string; return $string;
} }
} }
?>

File diff suppressed because it is too large Load Diff

View File

@@ -3,9 +3,7 @@
* AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org) * AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org)
* CREATED: 2002/12/17 * CREATED: 2002/12/17
* VERSION: 0.4.0 * VERSION: 0.4.0
* RELEASED LICENSE: BSD style (use it, u don't have to make YOUR source public) * RELEASED LICENSE: GNU GPL 3
* but let me know if u made changes, and please don't redistribute it
* with your name on it ...
* SHORT DESCRIPTION: * SHORT DESCRIPTION:
* DB Array IO Class: * DB Array IO Class:
* writes, reads or deletes a complete array (one data set) in/out a * writes, reads or deletes a complete array (one data set) in/out a
@@ -70,13 +68,12 @@
$this->table_name = $table_name; $this->table_name = $table_name;
// set primary key for given table_array // set primary key for given table_array
if ($this->table_array) if ($this->table_array) {
{ while (list($key, $value) = each($table_array)) {
while (list($key, $value) = each($table_array)) if ($value["pk"]) {
{
if ($value["pk"])
$this->pk_name = $key; $this->pk_name = $key;
} }
}
} // set pk_name IF table_array was given } // set pk_name IF table_array was given
// internal // internal
$this->class_info["db_array_io"] = array( $this->class_info["db_array_io"] = array(
@@ -102,14 +99,14 @@
// used with the read function // used with the read function
public function convert_data($text) public function convert_data($text)
{ {
$text = eregi_replace ('&lt;b&gt;', '<B>', $text); $text = str_replace('&lt;b&gt;', '<b>', $text);
$text = eregi_replace ('&lt;/b&gt;', '</B>', $text); $text = str_replace('&lt;/b&gt;', '</b>', $text);
$text = eregi_replace ('&lt;i&gt;', '<I>', $text); $text = str_replace('&lt;i&gt;', '<i>', $text);
$text = eregi_replace ('&lt;/i&gt;', '</I>', $text); $text = str_replace('&lt;/i&gt;', '</i>', $text);
// my need a change // my need a change
$text = eregi_replace ('&lt;a href=&quot;', '<A TARGET="_blank" HREF="', $text); $text = str_replace('&lt;a href=&quot;', '<a target="_blank" href="', $text);
$text = eregi_replace ('&quot;&gt;', '">', $text); $text = str_replace('&quot;&gt;', '">', $text);
$text = eregi_replace ('&lt;/a&gt;', '</A>', $text); $text = str_replace('&lt;/a&gt;', '</a>', $text);
return $text; return $text;
} }
@@ -134,13 +131,13 @@
public function db_dump_array($write = 0) public function db_dump_array($write = 0)
{ {
reset($this->table_array); reset($this->table_array);
while(list($column, $data_array) = each($this->table_array)) while (list($column, $data_array) = each($this->table_array)) {
{
$string .= "<b>".$column."</b> -> ".$data_array["value"]."<br>"; $string .= "<b>".$column."</b> -> ".$data_array["value"]."<br>";
} }
// add output to internal error_msg // add output to internal error_msg
if ($write) if ($write) {
$this->error_msg['db'] .= $string; $this->error_msg['db'] .= $string;
}
return $string; return $string;
} }
@@ -164,19 +161,19 @@
public function db_check_pk_set() public function db_check_pk_set()
{ {
// if pk_id is set, overrule ... // if pk_id is set, overrule ...
if ($this->pk_id) if ($this->pk_id) {
$this->table_array[$this->pk_name]["value"] = $this->pk_id; $this->table_array[$this->pk_name]["value"] = $this->pk_id;
}
// if not set ... produce error // if not set ... produce error
if (!$this->table_array[$this->pk_name]["value"]) if (!$this->table_array[$this->pk_name]["value"]) {
{
// if no PK found, error ... // if no PK found, error ...
$this->error_id = 21; $this->error_id = 21;
$this->_db_error(); $this->_db_error();
return 0; return 0;
} } else {
else
return 1; return 1;
} }
}
// METHOD db_reset_array // METHOD db_reset_array
// PARAMS reset_pk -> if set reset the pk too // PARAMS reset_pk -> if set reset the pk too
@@ -185,14 +182,14 @@
public function db_reset_array($reset_pk = 0) public function db_reset_array($reset_pk = 0)
{ {
reset($this->table_array); reset($this->table_array);
while(list($column, $data_array) = each($this->table_array)) while (list($column, $data_array) = each($this->table_array)) {
{ if (!$this->table_array[$column]["pk"]) {
if (!$this->table_array[$column]["pk"])
unset($this->table_array[$column]["value"]); unset($this->table_array[$column]["value"]);
else if ($reset_pk) } elseif ($reset_pk) {
unset($this->table_array[$column]["value"]); unset($this->table_array[$column]["value"]);
} }
} }
}
// METHOD db_delete // METHOD db_delete
// PARAMS optional the table_array, if not given uses class var // PARAMS optional the table_array, if not given uses class var
@@ -200,32 +197,34 @@
// DESC deletes one dataset // DESC deletes one dataset
public function db_delete($table_array = 0) public function db_delete($table_array = 0)
{ {
if (is_array($table_array)) if (is_array($table_array)) {
$this->table_array = $table_array; $this->table_array = $table_array;
if (!$this->db_check_pk_set()) }
if (!$this->db_check_pk_set()) {
return $this->table_array; return $this->table_array;
}
// delete query // delete query
$q = "DELETE FROM ".$this->table_name." WHERE "; $q = "DELETE FROM ".$this->table_name." WHERE ";
$q .= $this->pk_name." = ".$this->table_array[$this->pk_name]["value"]." "; $q .= $this->pk_name." = ".$this->table_array[$this->pk_name]["value"]." ";
// delete files and build FK query // delete files and build FK query
reset($this->table_array); reset($this->table_array);
while(list($column, $data_array) = each($this->table_array)) while (list($column, $data_array) = each($this->table_array)) {
{
// suchen nach bildern und löschen ... // suchen nach bildern und löschen ...
if ($this->table_array[$column]["file"] && file_exists($this->table_array[$column]["url"].$this->table_array[$column]["value"])) if ($this->table_array[$column]["file"] && file_exists($this->table_array[$column]["url"].$this->table_array[$column]["value"])) {
{ if (file_exists($this->table_array[$column]["path"].$this->table_array[$column]["value"])) {
if (file_exists($this->table_array[$column]["path"].$this->table_array[$column]["value"]))
unlink($this->table_array[$column]["path"].$this->table_array[$column]["value"]); unlink($this->table_array[$column]["path"].$this->table_array[$column]["value"]);
}
$dateiname = str_replace("_tn", "", $this->table_array[$column]["value"]); $dateiname = str_replace("_tn", "", $this->table_array[$column]["value"]);
if (file_exists($this->table_array[$column]["path"].$dateiname)) if (file_exists($this->table_array[$column]["path"].$dateiname)) {
unlink($this->table_array[$column]["path"].$dateiname); unlink($this->table_array[$column]["path"].$dateiname);
} }
}
if ($this->table_array[$column]["fk"]) if ($this->table_array[$column]["fk"]) {
{
// zusammenstellen der FKs // zusammenstellen der FKs
if ($q_where) if ($q_where) {
$q_where .= " AND "; $q_where .= " AND ";
}
$q_where .= $column." = ".$this->table_array[$column]["value"]; $q_where .= $column." = ".$this->table_array[$column]["value"];
} }
// allgemeines zurücksetzen des arrays // allgemeines zurücksetzen des arrays
@@ -233,12 +232,12 @@
} }
// attach fk row if there ... // attach fk row if there ...
if ($q_where) if ($q_where) {
$q .= " AND ".$q_where; $q .= " AND ".$q_where;
}
// if 0, error // if 0, error
unset($this->pk_id); unset($this->pk_id);
if (!$this->db_exec($q)) if (!$this->db_exec($q)) {
{
$this->error_id=22; $this->error_id=22;
$this->_db_error(); $this->_db_error();
} }
@@ -252,23 +251,25 @@
public function db_read($edit = 0, $table_array = 0) public function db_read($edit = 0, $table_array = 0)
{ {
// if array give, overrules internal array // if array give, overrules internal array
if (is_array($table_array)) if (is_array($table_array)) {
$this->table_array = $table_array; $this->table_array = $table_array;
if (!$this->db_check_pk_set()) }
if (!$this->db_check_pk_set()) {
return $this->table_array; return $this->table_array;
}
reset($this->table_array); reset($this->table_array);
// create select part & addition FK part // create select part & addition FK part
while (list($column, $data_array)=each($this->table_array)) while (list($column, $data_array)=each($this->table_array)) {
{ if ($q_select) {
if ($q_select)
$q_select .= ", "; $q_select .= ", ";
}
$q_select .= $column; $q_select .= $column;
// check FK ... // check FK ...
if ($this->table_array[$column]["fk"] && $this->table_array[$column]["value"]) if ($this->table_array[$column]["fk"] && $this->table_array[$column]["value"]) {
{ if ($q_where) {
if ($q_where)
$q_where .= " AND "; $q_where .= " AND ";
}
$q_where .= $column .= " = ".$this->table_array[$column]["value"]; $q_where .= $column .= " = ".$this->table_array[$column]["value"];
} }
} }
@@ -277,31 +278,25 @@
$q .= $q_select; $q .= $q_select;
$q .= " FROM ".$this->table_name." WHERE "; $q .= " FROM ".$this->table_name." WHERE ";
$q .= $this->pk_name." = ".$this->table_array[$this->pk_name]["value"]." "; $q .= $this->pk_name." = ".$this->table_array[$this->pk_name]["value"]." ";
if ($q_where) if ($q_where) {
$q .= " AND ".$q_where; $q .= " AND ".$q_where;
}
// if query was executed okay, else set error // if query was executed okay, else set error
if ($this->db_exec($q)) if ($this->db_exec($q)) {
{ if ($res = $this->db_fetch_array()) {
if ($res = $this->db_fetch_array())
{
reset($this->table_array); reset($this->table_array);
while (list($column, $data_array) = each($this->table_array)) while (list($column, $data_array) = each($this->table_array)) {
{
// wenn "edit" dann gib daten wie in DB zurück, ansonten aufbereiten für ausgabe // wenn "edit" dann gib daten wie in DB zurück, ansonten aufbereiten für ausgabe
// ?? sollte das nicht draußen ??? man weis ja net was da drin steht --> is noch zu überlegen // ?? sollte das nicht draußen ??? man weis ja net was da drin steht --> is noch zu überlegen
// echo "EDIT: $edit | Spalte: $column | type: ".$this->table_array[$column]["type"]." | Res: ".$res[$column]."<br>"; // echo "EDIT: $edit | Spalte: $column | type: ".$this->table_array[$column]["type"]." | Res: ".$res[$column]."<br>";
if ($edit) if ($edit) {
{
$this->table_array[$column]["value"] = $res[$column]; $this->table_array[$column]["value"] = $res[$column];
// if password, also write to hidden // if password, also write to hidden
if ($this->table_array[$column]["type"] == "password") if ($this->table_array[$column]["type"] == "password") {
{
$this->table_array[$column]["HIDDEN_value"] = $res[$column]; $this->table_array[$column]["HIDDEN_value"] = $res[$column];
} }
} } else {
else
{
$this->table_array[$column]["value"] = $this->convert_data(nl2br($res[$column])); $this->table_array[$column]["value"] = $this->convert_data(nl2br($res[$column]));
// had to put out the htmlentities from the line above as it breaks japanese characters // had to put out the htmlentities from the line above as it breaks japanese characters
} }
@@ -309,9 +304,7 @@
} }
// possible db_fetch_array errors ... // possible db_fetch_array errors ...
$this->pk_id = $this->table_array[$this->pk_name]["value"]; $this->pk_id = $this->table_array[$this->pk_name]["value"];
} } else {
else
{
$this->error_id = 22; $this->error_id = 22;
$this->_db_error(); $this->_db_error();
} }
@@ -324,42 +317,41 @@
// DESC writes on set into DB or updates one set (if PK exists) // DESC writes on set into DB or updates one set (if PK exists)
public function db_write($addslashes = 0, $table_array = 0) public function db_write($addslashes = 0, $table_array = 0)
{ {
if (is_array($table_array)) if (is_array($table_array)) {
$this->table_array = $table_array; $this->table_array = $table_array;
}
// PK ID check // PK ID check
// if ($this->pk_id && !$this->table_array[$this->pk_name]["value"]) // if ($this->pk_id && !$this->table_array[$this->pk_name]["value"]) {
// $this->table_array[$this->pk_name]["value"]=$this->pk_id; // $this->table_array[$this->pk_name]["value"]=$this->pk_id;
// }
// checken ob PKs gesetzt, wenn alle -> update, wenn keiner -> insert, wenn ein paar -> ERROR! // checken ob PKs gesetzt, wenn alle -> update, wenn keiner -> insert, wenn ein paar -> ERROR!
if (!$this->table_array[$this->pk_name]["value"]) if (!$this->table_array[$this->pk_name]["value"]) {
$insert = 1; $insert = 1;
else } else {
$insert = 0; $insert = 0;
}
reset($this->table_array); reset($this->table_array);
while (list($column, $data_array) = each($this->table_array)) while (list($column, $data_array) = each($this->table_array)) {
{
/********************************* START FILE *************************************/ /********************************* START FILE *************************************/
// file upload // file upload
if ($this->table_array[$column]["file"]) if ($this->table_array[$column]["file"]) {
{
// falls was im tmp drinnen, sprich ein upload, datei kopieren, Dateinamen in db schreiben // falls was im tmp drinnen, sprich ein upload, datei kopieren, Dateinamen in db schreiben
// falls datei schon am server (physischer pfad), dann einfach url in db schreiben (update) // falls datei schon am server (physischer pfad), dann einfach url in db schreiben (update)
// falls in "delete" "ja" dann loeschen (und gibts eh nur beim update) // falls in "delete" "ja" dann loeschen (und gibts eh nur beim update)
if ($this->table_array[$column]["delete"]) if ($this->table_array[$column]["delete"]) {
{
unset($this->table_array[$column]["delete"]); unset($this->table_array[$column]["delete"]);
if (file_exists($this->table_array[$column]["path"].$this->table_array[$column]["value"])) if (file_exists($this->table_array[$column]["path"].$this->table_array[$column]["value"])) {
unlink($this->table_array[$column]["path"].$this->table_array[$column]["value"]); unlink($this->table_array[$column]["path"].$this->table_array[$column]["value"]);
$dateiname = str_replace("_tn", "", $this->table_array[$column]["value"]);
if (file_exists($this->table_array[$column]["path"].$dateiname))
unlink($this->table_array[$column]["path"].$dateiname);
$this->table_array[$column]["value"] = "";
} }
else $dateiname = str_replace("_tn", "", $this->table_array[$column]["value"]);
{ if (file_exists($this->table_array[$column]["path"].$dateiname)) {
if ($this->table_array[$column]["tmp"] != "none" && $this->table_array[$column]["tmp"]) unlink($this->table_array[$column]["path"].$dateiname);
{ }
$this->table_array[$column]["value"] = "";
} else {
if ($this->table_array[$column]["tmp"] != "none" && $this->table_array[$column]["tmp"]) {
// Dateiname zusammenbasteln: org-name + _pkid liste + .ext // Dateiname zusammenbasteln: org-name + _pkid liste + .ext
list($name, $ext) = explode(".", $this->table_array[$column]["dn"]); list($name, $ext) = explode(".", $this->table_array[$column]["dn"]);
@@ -375,20 +367,17 @@
//echo "Dn: $dateiname"; //echo "Dn: $dateiname";
copy($this->table_array[$column]["tmp"], $this->table_array[$column]["path"].$dateiname); copy($this->table_array[$column]["tmp"], $this->table_array[$column]["path"].$dateiname);
// automatisch thumbnail generieren, geht nur mit convert (ImageMagic!!!), aber nur bei bild .. // automatisch thumbnail generieren, geht nur mit convert (ImageMagic!!!), aber nur bei bild ..
if (strtolower($ext) == "jpeg" || strtolower($ext) == "jpg" || strtolower($ext) == "gif" || strtolower($ext) == "png") if (strtolower($ext) == "jpeg" || strtolower($ext) == "jpg" || strtolower($ext) == "gif" || strtolower($ext) == "png") {
{
$dateiname_tn = $name.$pk_ids_file."_tn.".$ext; $dateiname_tn = $name.$pk_ids_file."_tn.".$ext;
$eingang = $this->table_array[$column]["path"].$dateiname; $eingang = $this->table_array[$column]["path"].$dateiname;
$ausgang = $this->table_array[$column]["path"].$dateiname_tn; $ausgang = $this->table_array[$column]["path"].$dateiname_tn;
$com = "convert -geometry 115 $eingang $ausgang"; $com = "convert -geometry 115 $eingang $ausgang";
exec($com); exec($com);
$this->table_array[$column]["value"] = $dateiname_tn; $this->table_array[$column]["value"] = $dateiname_tn;
} } else {
else
$this->table_array[$column]["value"] = $dateiname; $this->table_array[$column]["value"] = $dateiname;
} }
else if (file_exists($this->table_array[$column]["path"].$this->table_array[$column]["value"])) } elseif (file_exists($this->table_array[$column]["path"].$this->table_array[$column]["value"])) {
{
// mach gar nix, wenn bild schon da ??? // mach gar nix, wenn bild schon da ???
} }
} // delete or upload } // delete or upload
@@ -396,55 +385,52 @@
/********************************* END FILE **************************************/ /********************************* END FILE **************************************/
// do not write 'pk' (primary key) or 'view' values // do not write 'pk' (primary key) or 'view' values
if (!$this->table_array[$column]["pk"] && $this->table_array[$column]['type'] != 'view' && strlen($column) > 0 ) if (!$this->table_array[$column]["pk"] && $this->table_array[$column]['type'] != 'view' && strlen($column) > 0) {
{
// for password use hidden value if main is not set // for password use hidden value if main is not set
if ($this->table_array[$column]["type"] == "password" && !$this->table_array[$column]["value"]) if ($this->table_array[$column]["type"] == "password" && !$this->table_array[$column]["value"]) {
$this->table_array[$column]["value"] = $this->table_array[$column]["HIDDEN_value"]; $this->table_array[$column]["value"] = $this->table_array[$column]["HIDDEN_value"];
if (!$insert)
{
if (strlen($q_data))
$q_data .= ", ";
$q_data .= $column." = ";
} }
else if (!$insert) {
// this is insert if (strlen($q_data)) {
{
if (strlen($q_data))
$q_data .= ", "; $q_data .= ", ";
if ($q_vars) }
$q_data .= $column." = ";
} else {
// this is insert
if (strlen($q_data)) {
$q_data .= ", ";
}
if ($q_vars) {
$q_vars .= ", "; $q_vars .= ", ";
}
$q_vars .= $column; $q_vars .= $column;
} }
// integer is different // integer is different
if ($this->table_array[$column]["int"] || $this->table_array[$column]["int_null"]) if ($this->table_array[$column]["int"] || $this->table_array[$column]["int_null"]) {
{
$this->debug('write_check', "[$column][".$this->table_array[$column]["value"]."] Foo: ".isset($this->table_array[$column]["value"])." | ".$this->table_array[$column]["int_null"]); $this->debug('write_check', "[$column][".$this->table_array[$column]["value"]."] Foo: ".isset($this->table_array[$column]["value"])." | ".$this->table_array[$column]["int_null"]);
if (!$this->table_array[$column]["value"] && $this->table_array[$column]["int_null"]) if (!$this->table_array[$column]["value"] && $this->table_array[$column]["int_null"]) {
$_value = 'NULL'; $_value = 'NULL';
elseif (!isset($this->table_array[$column]["value"])) } elseif (!isset($this->table_array[$column]["value"])) {
$_value = 0; $_value = 0;
else } else {
$_value = $this->table_array[$column]["value"]; $_value = $this->table_array[$column]["value"];
$q_data .= $_value;
} }
elseif ($this->table_array[$column]["interval"]) $q_data .= $_value;
{ } elseif ($this->table_array[$column]["interval"]) {
// for interval we check if no value, then we set null // for interval we check if no value, then we set null
if (!$this->table_array[$column]["value"]) if (!$this->table_array[$column]["value"]) {
$_value = 'NULL'; $_value = 'NULL';
$q_data .= $_value;
} }
else $q_data .= $_value;
} else {
// normal string // normal string
{
$q_data .= "'"; $q_data .= "'";
// if add slashes do convert & add slashes else write AS is // if add slashes do convert & add slashes else write AS is
if ($addslashes) if ($addslashes) {
$q_data .= $this->db_escape_string($this->convert_entities($this->table_array[$column]["value"])); $q_data .= $this->db_escape_string($this->convert_entities($this->table_array[$column]["value"]));
else } else {
$q_data .= $this->db_escape_string($this->table_array[$column]["value"]); $q_data .= $this->db_escape_string($this->table_array[$column]["value"]);
}
$q_data .= "'"; $q_data .= "'";
} }
} }
@@ -454,60 +440,54 @@ $this->debug('write_check', "[$column][".$this->table_array[$column]["value"]."]
// get it at the end, cause now we can be more sure of no double IDs, etc // get it at the end, cause now we can be more sure of no double IDs, etc
reset($this->table_array); reset($this->table_array);
// create select part & addition FK part // create select part & addition FK part
while (list($column, $data_array) = each($this->table_array)) while (list($column, $data_array) = each($this->table_array)) {
{
// check FK ... // check FK ...
if ($this->table_array[$column]["fk"] && $this->table_array[$column]["value"]) if ($this->table_array[$column]["fk"] && $this->table_array[$column]["value"]) {
{ if ($q_where) {
if ($q_where)
$q_where .= " AND "; $q_where .= " AND ";
}
$q_where .= $column .= " = ".$this->table_array[$column]["value"]; $q_where .= $column .= " = ".$this->table_array[$column]["value"];
} }
} }
// if no PK set, then get max ID from DB // if no PK set, then get max ID from DB
if (!$this->table_array[$this->pk_name]["value"]) if (!$this->table_array[$this->pk_name]["value"]) {
{
// max id, falls INSERT // max id, falls INSERT
$q = "SELECT MAX(".$this->pk_name.") + 1 AS pk_id FROM ".$this->table_name; $q = "SELECT MAX(".$this->pk_name.") + 1 AS pk_id FROM ".$this->table_name;
$res = $this->db_return_row($q); $res = $this->db_return_row($q);
if (!$res["pk_id"]) if (!$res["pk_id"]) {
$res["pk_id"] = 1; $res["pk_id"] = 1;
}
$this->table_array[$this->pk_name]["value"] = $res["pk_id"]; $this->table_array[$this->pk_name]["value"] = $res["pk_id"];
} }
if (!$insert) if (!$insert) {
{
$q = "UPDATE ".$this->table_name." SET "; $q = "UPDATE ".$this->table_name." SET ";
$q .= $q_data; $q .= $q_data;
$q .= " WHERE "; $q .= " WHERE ";
$q .= $this->pk_name." = ".$this->table_array[$this->pk_name]["value"]." "; $q .= $this->pk_name." = ".$this->table_array[$this->pk_name]["value"]." ";
if ($q_where) if ($q_where) {
$q .= " AND ".$q_where; $q .= " AND ".$q_where;
}
// set pk_id ... if it has changed or so // set pk_id ... if it has changed or so
$this->pk_id = $this->table_array[$this->pk_name]["value"]; $this->pk_id = $this->table_array[$this->pk_name]["value"];
} } else {
else
{
$q = "INSERT INTO ".$this->table_name." "; $q = "INSERT INTO ".$this->table_name." ";
$q .= "(".$q_vars.") "; $q .= "(".$q_vars.") ";
$q .= "VALUES (".$q_data.")"; $q .= "VALUES (".$q_data.")";
// write primary key too // write primary key too
/* if ($q_data) // if ($q_data)
$q .= ", "; // $q .= ", ";
$q .= $this->pk_name." = ".$this->table_array[$this->pk_name]["value"]." "; // $q .= $this->pk_name." = ".$this->table_array[$this->pk_name]["value"]." ";
$this->pk_id = $this->table_array[$this->pk_name]["value"]; // $this->pk_id = $this->table_array[$this->pk_name]["value"];
*/
} }
// return success or not // return success or not
if (!$this->db_exec($q)) if (!$this->db_exec($q)) {
{
$this->error_id = 22; $this->error_id = 22;
$this->_db_error(); $this->_db_error();
} }
// set primary key // set primary key
if ($insert) if ($insert) {
{
$this->table_array[$this->pk_name]["value"] = $this->insert_id; $this->table_array[$this->pk_name]["value"] = $this->insert_id;
$this->ok = $this->insert_id; $this->ok = $this->insert_id;
} }
@@ -515,4 +495,3 @@ $this->debug('write_check', "[$column][".$this->table_array[$column]["value"]."]
return $this->table_array; return $this->table_array;
} }
} // end of class } // end of class
?>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -3,9 +3,7 @@
* AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org) * AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org)
* CREATED: 2000/06/01 * CREATED: 2000/06/01
* VERSION: 4.0.0 * VERSION: 4.0.0
* RELEASED LICENSE: BSD style (use it, u don't have to make YOUR source public) * RELEASED LICENSE: GNU GPL 3
* but let me know if u made changes, and please don't redistribute it
* with your name on it ...
* SHORT DESCRIPTON: * SHORT DESCRIPTON:
* ~ 2003/03/03: change the whole include file into one class * ~ 2003/03/03: change the whole include file into one class
* advantages are a) can include before actuall call, can control it * advantages are a) can include before actuall call, can control it
@@ -72,8 +70,17 @@
private $logout; // logout button private $logout; // logout button
private $login_error; // login error code, can be matched to the array login_error_msg, which holds the string private $login_error; // login error code, can be matched to the array login_error_msg, which holds the string
private $password_change = false; // if this is set to true, the user can change passwords private $password_change = false; // if this is set to true, the user can change passwords
private $password_change_ok = false; // password change was successful
private $pw_change_deny_users = array (); // array of users for which the password change is forbidden private $pw_change_deny_users = array (); // array of users for which the password change is forbidden
// if we have password change we need to define some rules
private $password_min_length = 8;
// can have several regexes, if nothing set, all is ok
private $password_valid_chars = array (
// '^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!@#$%]{8,}$',
// '^(?.*(\pL)u)(?=.*(\pN)u)(?=.*([^\pL\pN])u).{8,}',
);
// all possible login error conditions // all possible login error conditions
private $login_error_msg = array (); private $login_error_msg = array ();
// this is an array holding all strings & templates passed from the outside (translation) // this is an array holding all strings & templates passed from the outside (translation)
@@ -97,8 +104,7 @@
parent::__construct($db_config, $debug, $db_debug, $echo, $print); parent::__construct($db_config, $debug, $db_debug, $echo, $print);
// no session could be found at all // no session could be found at all
if (!session_id()) if (!session_id()) {
{
echo "<b>Session not started!</b><br>Use 'session_start();'.<br>For less problems with other session, you can set a session name with 'session_name(\"name\");'.<br>"; echo "<b>Session not started!</b><br>Use 'session_start();'.<br>For less problems with other session, you can set a session name with 'session_name(\"name\");'.<br>";
exit; exit;
} }
@@ -114,24 +120,33 @@
$this->euid = array_key_exists('EUID', $_SESSION) ? $_SESSION['EUID'] : 0; // if there is none, there is none, saves me POST/GET check $this->euid = array_key_exists('EUID', $_SESSION) ? $_SESSION['EUID'] : 0; // if there is none, there is none, saves me POST/GET check
// get login vars, are so, can't be changed // get login vars, are so, can't be changed
// prepare // prepare
if (!isset($_POST['login_login'])) if (!isset($_POST['login_login'])) {
$_POST['login_login'] = ''; $_POST['login_login'] = '';
if (!isset($_POST['login_username'])) }
if (!isset($_POST['login_username'])) {
$_POST['login_username'] = ''; $_POST['login_username'] = '';
if (!isset($_POST['login_password'])) }
if (!isset($_POST['login_password'])) {
$_POST['login_password'] = ''; $_POST['login_password'] = '';
if (!isset($_POST['login_logout'])) }
if (!isset($_POST['login_logout'])) {
$_POST['login_logout'] = ''; $_POST['login_logout'] = '';
if (!isset($_POST['change_password'])) }
if (!isset($_POST['change_password'])) {
$_POST['change_password'] = ''; $_POST['change_password'] = '';
if (!isset($_POST['pw_username'])) }
if (!isset($_POST['pw_username'])) {
$_POST['pw_username'] = ''; $_POST['pw_username'] = '';
if (!isset($_POST['pw_old_password'])) }
if (!isset($_POST['pw_old_password'])) {
$_POST['pw_old_password'] = ''; $_POST['pw_old_password'] = '';
if (!isset($_POST['pw_new_password'])) }
if (!isset($_POST['pw_new_password'])) {
$_POST['pw_new_password'] = ''; $_POST['pw_new_password'] = '';
if (!isset($_POST['pw_new_password_confirm'])) }
if (!isset($_POST['pw_new_password_confirm'])) {
$_POST['pw_new_password_confirm'] = ''; $_POST['pw_new_password_confirm'] = '';
}
// pass on vars to Object vars // pass on vars to Object vars
$this->login = $_POST["login_login"]; $this->login = $_POST["login_login"];
$this->username = $_POST["login_username"]; $this->username = $_POST["login_username"];
@@ -148,8 +163,9 @@
// disallow user list for password change // disallow user list for password change
$this->pw_change_deny_users = array ('admin'); $this->pw_change_deny_users = array ('admin');
// set flag if password change is okay // set flag if password change is okay
if (defined('PASSWORD_CHANGE')) if (defined('PASSWORD_CHANGE')) {
$this->password_change = PASSWORD_CHANGE; $this->password_change = PASSWORD_CHANGE;
}
// max login counts before error reporting // max login counts before error reporting
$this->max_login_error_count = 10; $this->max_login_error_count = 10;
// users that never get locked, even if they are set strict // users that never get locked, even if they are set strict
@@ -167,8 +183,7 @@
$_SESSION['DEFAULT_ACL_LIST'] = array (); $_SESSION['DEFAULT_ACL_LIST'] = array ();
// read the current edit_access_right list into an array // read the current edit_access_right list into an array
$q = "SELECT level, type, name FROM edit_access_right WHERE level >= 0 ORDER BY level"; $q = "SELECT level, type, name FROM edit_access_right WHERE level >= 0 ORDER BY level";
while ($res = $this->db_return($q)) while ($res = $this->db_return($q)) {
{
// level to description format (numeric) // level to description format (numeric)
$this->default_acl_list[$res['level']] = array ( $this->default_acl_list[$res['level']] = array (
'type' => $res['type'], 'type' => $res['type'],
@@ -185,25 +200,25 @@
// logsout user // logsout user
$this->login_logout_user(); $this->login_logout_user();
// if the password change flag is okay, run the password change method // if the password change flag is okay, run the password change method
if ($this->password_change) if ($this->password_change) {
$this->login_password_change(); $this->login_password_change();
}
// if !$euid || permission not okay, print login screan // if !$euid || permission not okay, print login screan
echo $this->login_print_login(); echo $this->login_print_login();
// closing all connections, depending on error status, exit // closing all connections, depending on error status, exit
if (!$this->login_close_class()) if (!$this->login_close_class()) {
{
// do not go anywhere, quit processing here // do not go anywhere, quit processing here
// do something with possible debug data? // do something with possible debug data?
if (TARGET == 'live' || TARGET == 'remote') if (TARGET == 'live' || TARGET == 'remote') {
{
// login // login
$this->debug_output_all = DEBUG ? 1 : 0; $this->debug_output_all = DEBUG ? 1 : 0;
$this->echo_output_all = 0; $this->echo_output_all = 0;
$this->print_output_all = DEBUG ? 1 : 0; $this->print_output_all = DEBUG ? 1 : 0;
} }
$status_msg = $this->print_error_msg(); $status_msg = $this->print_error_msg();
if ($this->echo_output_all) if ($this->echo_output_all) {
echo $status_msg; echo $status_msg;
}
exit; exit;
} }
// set acls for this user/group and this page // set acls for this user/group and this page
@@ -219,6 +234,55 @@
parent::__destruct(); parent::__destruct();
} }
// METHOD: loginPasswordCheck
// PARAMS: hash, optional password, to override
// RETURN: true or false
// DESC : checks if password is valid, sets internal error login variable
private function loginPasswordCheck($hash, $password = '')
{
$password_ok = false;
if (!$password) {
$password = $this->password;
}
if ((preg_match("/^\\$2(a|y)\\$/", $hash) && CRYPT_BLOWFISH != 1) ||
(preg_match("/^\\$1\\$/", $hash) && CRYPT_MD5 != 1) ||
(preg_match("/^\\$[0-9A-Za-z.]{12}$/", $hash) && CRYPT_STD_DES != 1)
) {
// this means password cannot be decrypted because of missing crypt methods
$this->login_error = 9999;
$password_ok = false;
} elseif ((preg_match("/^\\$2(a)\\$/", $hash) ||
// old password have $07$ so we check this
(preg_match("/^\\$2(y)\\$/", $hash) && preg_match("/\\$07\\$/", $hash)) ||
preg_match("/^\\$1\\$/", $hash) ||
preg_match("/^\\$[0-9A-Za-z.]{12}$/", $hash)) &&
!$this->verifyCryptString($password, $hash)
) {
// check passwword as crypted, $2a$ or $2y$ is blowfish start, $1$ is MD5 start, $\w{12} is standard DES
// this is only for OLD $07$ password
$this->login_error = 1011;
$password_ok = false;
} elseif (preg_match("/^\\$2y\\$/", $hash) &&
!$this->passwordVerify($password, $hash)
) {
// this is the new password hash methid, is only $2y$
$this->login_error = 1013;
$password_ok = false;
} elseif (!preg_match("/^\\$2(a|y)\\$/", $hash) &&
!preg_match("/^\\$1\\$/", $hash) &&
!preg_match("/^\\$[0-9A-Za-z.]{12}$/", $hash) &&
$hash != $password
) {
// check old plain password, non case sensitive
$this->login_error = 1012;
$password_ok = false;
} else {
// all ok
$password_ok = true;
}
return $password_ok;
}
// METHOD: login_login_user // METHOD: login_login_user
// PARAMS: none // PARAMS: none
// RETURN: none // RETURN: none
@@ -226,14 +290,10 @@
private function login_login_user() private function login_login_user()
{ {
// have to get the global stuff here for setting it later // have to get the global stuff here for setting it later
if (!$this->euid && $this->login) if (!$this->euid && $this->login) {
{ if (!($this->password && $this->username)) {
if (!($this->password && $this->username))
{
$this->login_error = 102; $this->login_error = 102;
} } else {
else
{
// we have to get the themes in here too // we have to get the themes in here too
$q = "SELECT eu.edit_user_id, username, password, eu.edit_group_id, eg.name AS edit_group_name, admin, eu.login_error_count, eu.login_error_date_last, eu.login_error_date_first, eu.strict, eu.locked, "; $q = "SELECT eu.edit_user_id, username, password, eu.edit_group_id, eg.name AS edit_group_name, admin, eu.login_error_count, eu.login_error_date_last, eu.login_error_date_first, eu.strict, eu.locked, ";
$q .= "debug, db_debug, "; $q .= "debug, db_debug, ";
@@ -253,12 +313,9 @@
$q .= "(LOWER(username) = '".strtolower($this->username)."') "; $q .= "(LOWER(username) = '".strtolower($this->username)."') ";
$res = $this->db_return($q); $res = $this->db_return($q);
// username is wrong, but we throw for wrong username and wrong password the same error // username is wrong, but we throw for wrong username and wrong password the same error
if (!$this->cursor_ext[md5($q)]["num_rows"]) if (!$this->cursor_ext[md5($q)]["num_rows"]) {
{
$this->login_error = 1010; $this->login_error = 1010;
} } else {
else
{
// if login errors is half of max errors and the last login error was less than 10s ago, forbid any new login try // if login errors is half of max errors and the last login error was less than 10s ago, forbid any new login try
// check with what kind of prefix the password begins: // check with what kind of prefix the password begins:
@@ -275,39 +332,29 @@
// - encrypted password matches // - encrypted password matches
// - plain password matches // - plain password matches
if (!$res["enabled"]) {
// user is enabled // user is enabled
if (!$res["enabled"])
{
$this->login_error = 104; $this->login_error = 104;
} } elseif ($res['locked']) {
// user is locked, either set or auto set // user is locked, either set or auto set
elseif ($res['locked'])
{
$this->login_error = 105; $this->login_error = 105;
} elseif (!$this->loginPasswordCheck($res['password'])) {
// none to be set, set in login password check
} else {
// check if the current password is an invalid hash and do a rehash and set password
// $this->debug('LOGIN', 'Hash: '.$res['password'].' -> VERIFY: '.($this->passwordVerify($this->password, $res['password']) ? 'OK' : 'FAIL').' => HASH: '.($this->passwordRehashCheck($res['password']) ? 'NEW NEEDED' : 'OK'));
if ($this->passwordRehashCheck($res['password'])) {
$new_hash = $this->passwordSet($this->password);
// update password hash to new one now
$q = "UPDATE edit_user SET password = '".$this->dbEscapeString($new_hash)."' WHERE edit_user_id = ".$res['edit_user_id'];
$this->dbExec($q);
} }
elseif ((preg_match("/^\\$2(a|y)\\$/", $res['password']) && CRYPT_BLOWFISH != 1) || (preg_match("/^\\$1\\$/", $res['password']) && CRYPT_MD5 != 1) || (preg_match("/^\\$[0-9A-Za-z.]{12}$/", $res['password']) && CRYPT_STD_DES != 1)) // normal user processing
{
$this->login_error = 9999; // this means password cannot be decrypted because of missing crypt methods
}
// check passwword as crypted, $2a$ or $2y$ is blowfish start, $1$ is MD5 start, $\w{12} is standard DES
elseif ((preg_match("/^\\$2(a|y)\\$/", $res['password']) || preg_match("/^\\$1\\$/", $res['password']) || preg_match("/^\\$[0-9A-Za-z.]{12}$/", $res['password'])) && !$this->verifyCryptString($this->password, $res['password']))
{
$this->login_error = 1011;
}
// check old plain password, non case sensitive
elseif (!preg_match("/^\\$2(a|y)\\$/", $res['password']) && !preg_match("/^\\$1\\$/", $res['password']) && !preg_match("/^\\$[0-9A-Za-z.]{12}$/", $res['password']) && $res['password'] != $this->password)
{
$this->login_error = 1012;
}
// nromal user processing
else
{
// set class var and session var // set class var and session var
$_SESSION["EUID"] = $this->euid = $res["edit_user_id"]; $_SESSION["EUID"] = $this->euid = $res["edit_user_id"];
// check if user is okay // check if user is okay
$this->login_check_permissions(); $this->login_check_permissions();
if (!$this->login_error) if (!$this->login_error) {
{
// now set all session vars and read page permissions // now set all session vars and read page permissions
$GLOBALS["DEBUG_ALL"] = $_SESSION["DEBUG_ALL"] = $res["debug"]; $GLOBALS["DEBUG_ALL"] = $_SESSION["DEBUG_ALL"] = $res["debug"];
$GLOBALS["DB_DEBUG"] = $_SESSION["DB_DEBUG"] = $res["db_debug"]; $GLOBALS["DB_DEBUG"] = $_SESSION["DB_DEBUG"] = $res["db_debug"];
@@ -324,8 +371,7 @@
$_SESSION["DEFAULT_CHARSET"] = $res["lang_iso"]; $_SESSION["DEFAULT_CHARSET"] = $res["lang_iso"];
$_SESSION["DEFAULT_LANG"] = $res["lang_short"].'_'.strtolower(str_replace('-', '', $res["lang_iso"])); $_SESSION["DEFAULT_LANG"] = $res["lang_short"].'_'.strtolower(str_replace('-', '', $res["lang_iso"]));
// reset any login error count for this user // reset any login error count for this user
if ($res['login_error_count'] > 0) if ($res['login_error_count'] > 0) {
{
$q = "UPDATE edit_user SET login_error_count = 0, login_error_date_last = NULL, login_error_date_first = NULL WHERE edit_user_id = ".$res['edit_user_id']; $q = "UPDATE edit_user SET login_error_count = 0, login_error_date_last = NULL, login_error_date_first = NULL WHERE edit_user_id = ".$res['edit_user_id'];
$this->db_exec($q); $this->db_exec($q);
} }
@@ -337,8 +383,7 @@
$q .= "WHERE ep.edit_page_id = epa.edit_page_id AND ear.edit_access_right_id = epa.edit_access_right_id "; $q .= "WHERE ep.edit_page_id = epa.edit_page_id AND ear.edit_access_right_id = epa.edit_access_right_id ";
$q .= "AND epa.enabled = 1 AND epa.edit_group_id = ".$res["edit_group_id"]." "; $q .= "AND epa.enabled = 1 AND epa.edit_group_id = ".$res["edit_group_id"]." ";
$q .= "ORDER BY ep.order_number"; $q .= "ORDER BY ep.order_number";
while ($res = $this->db_return($q)) while ($res = $this->db_return($q)) {
{
// page id array for sub data readout // page id array for sub data readout
$edit_page_ids[] = $res['edit_page_id']; $edit_page_ids[] = $res['edit_page_id'];
// create the array for pages // create the array for pages
@@ -359,15 +404,12 @@
)); ));
// make reference filename -> level // make reference filename -> level
$pages_acl[$res["filename"]] = $res["level"]; $pages_acl[$res["filename"]] = $res["level"];
} // for each page } // for each page
// get the visible groups for all pages and write them to the pages // get the visible groups for all pages and write them to the pages
$_edit_page_id = 0; $_edit_page_id = 0;
$q = "SELECT epvg.edit_page_id, name, flag FROM edit_visible_group evp, edit_page_visible_group epvg WHERE evp.edit_visible_group_id = epvg.edit_visible_group_id AND epvg.edit_page_id IN (".join(', ', $edit_page_ids).") ORDER BY epvg.edit_page_id"; $q = "SELECT epvg.edit_page_id, name, flag FROM edit_visible_group evp, edit_page_visible_group epvg WHERE evp.edit_visible_group_id = epvg.edit_visible_group_id AND epvg.edit_page_id IN (".join(', ', $edit_page_ids).") ORDER BY epvg.edit_page_id";
while ($res = $this->db_return($q)) while ($res = $this->db_return($q)) {
{ if ($res['edit_page_id'] != $_edit_page_id) {
if ($res['edit_page_id'] != $_edit_page_id)
{
// search the pos in the array push // search the pos in the array push
$pos = $this->array_search_recursive($res['edit_page_id'], $pages, 'edit_page_id'); $pos = $this->array_search_recursive($res['edit_page_id'], $pages, 'edit_page_id');
$_edit_page_id = $res['edit_page_id']; $_edit_page_id = $res['edit_page_id'];
@@ -377,10 +419,8 @@
// get the same for the query strings // get the same for the query strings
$_edit_page_id = 0; $_edit_page_id = 0;
$q = "SELECT eqs.edit_page_id, name, value, dynamic FROM edit_query_string eqs WHERE enabled = 1 AND edit_page_id IN (".join(', ', $edit_page_ids).") ORDER BY eqs.edit_page_id"; $q = "SELECT eqs.edit_page_id, name, value, dynamic FROM edit_query_string eqs WHERE enabled = 1 AND edit_page_id IN (".join(', ', $edit_page_ids).") ORDER BY eqs.edit_page_id";
while ($res = $this->db_return($q)) while ($res = $this->db_return($q)) {
{ if ($res['edit_page_id'] != $_edit_page_id) {
if ($res['edit_page_id'] != $_edit_page_id)
{
// search the pos in the array push // search the pos in the array push
$pos = $this->array_search_recursive($res['edit_page_id'], $pages, 'edit_page_id'); $pos = $this->array_search_recursive($res['edit_page_id'], $pages, 'edit_page_id');
$_edit_page_id = $res['edit_page_id']; $_edit_page_id = $res['edit_page_id'];
@@ -402,13 +442,11 @@
$unit_access = array(); $unit_access = array();
$eauid = array(); $eauid = array();
$unit_acl = array(); $unit_acl = array();
while ($res = $this->db_return($q)) while ($res = $this->db_return($q)) {
{
// read edit access data fields and drop them into the unit access array // read edit access data fields and drop them into the unit access array
$q_sub ="SELECT name, value FROM edit_access_data WHERE enabled = 1 AND edit_access_id = ".$res['edit_access_id']; $q_sub ="SELECT name, value FROM edit_access_data WHERE enabled = 1 AND edit_access_id = ".$res['edit_access_id'];
$ea_data = array (); $ea_data = array ();
while ($res_sub = $this->db_return($q_sub)) while ($res_sub = $this->db_return($q_sub)) {
{
$ea_data[$res_sub['name']] = $res_sub['value']; $ea_data[$res_sub['name']] = $res_sub['value'];
} }
// build master unit array // build master unit array
@@ -423,8 +461,9 @@
'data' => $ea_data 'data' => $ea_data
); );
// set the default unit // set the default unit
if ($res['edit_default']) if ($res['edit_default']) {
$_SESSION["UNIT_DEFAULT"] = $res['edit_access_id']; $_SESSION["UNIT_DEFAULT"] = $res['edit_access_id'];
}
// sub arrays for simple access // sub arrays for simple access
array_push($eauid, $res['edit_access_id']); array_push($eauid, $res['edit_access_id']);
$unit_acl[$res['edit_access_id']] = $res['level']; $unit_acl[$res['edit_access_id']] = $res['level'];
@@ -434,21 +473,19 @@
$_SESSION['EAID'] = $eauid; $_SESSION['EAID'] = $eauid;
} // user has permission to THIS page } // user has permission to THIS page
} // user was not enabled or other login error } // user was not enabled or other login error
if ($this->login_error) if ($this->login_error) {
{ if ($res['login_error_count'] == 0) {
if ($res['login_error_count'] == 0)
$login_error_date_first = ', login_error_date_first = NOW()'; $login_error_date_first = ', login_error_date_first = NOW()';
}
// update login error count for this user // update login error count for this user
$q = "UPDATE edit_user SET login_error_count = login_error_count + 1, login_error_date_last = NOW() $login_error_date_first WHERE edit_user_id = ".$res['edit_user_id']; $q = "UPDATE edit_user SET login_error_count = login_error_count + 1, login_error_date_last = NOW() $login_error_date_first WHERE edit_user_id = ".$res['edit_user_id'];
$this->db_exec($q); $this->db_exec($q);
// totally lock the user if error max is reached // totally lock the user if error max is reached
if ($res['login_error_count'] + 1 > $this->max_login_error_count) if ($res['login_error_count'] + 1 > $this->max_login_error_count) {
{
// do some alert reporting in case this error is too big // do some alert reporting in case this error is too big
// if strict is set, lock this user // if strict is set, lock this user
// this needs manual unlocking by an admin user // this needs manual unlocking by an admin user
if ($res['strict'] && !in_array($this->username, $this->lock_deny_users)) if ($res['strict'] && !in_array($this->username, $this->lock_deny_users)) {
{
$q = "UPDATE edit_user SET locked = 1 WHERE edit_user_id = ".$res['edit_user_id']; $q = "UPDATE edit_user SET locked = 1 WHERE edit_user_id = ".$res['edit_user_id'];
} }
} }
@@ -456,8 +493,7 @@
} // user was not found } // user was not found
} // if not username AND password where given } // if not username AND password where given
// if there was an login error, show login screen // if there was an login error, show login screen
if ($this->login_error) if ($this->login_error) {
{
// reset the perm var, to confirm logout // reset the perm var, to confirm logout
$this->permission_okay = 0; $this->permission_okay = 0;
} }
@@ -470,8 +506,7 @@
// DESC : for every page the user access this script checks if he is allowed to do so // DESC : for every page the user access this script checks if he is allowed to do so
public function login_check_permissions() public function login_check_permissions()
{ {
if ($this->euid && $this->login_error != 103) if ($this->euid && $this->login_error != 103) {
{
$q = "SELECT filename "; $q = "SELECT filename ";
$q .= "FROM edit_page ep, edit_page_access epa, edit_group eg, edit_user eu "; $q .= "FROM edit_page ep, edit_page_access epa, edit_group eg, edit_user eu ";
$q .= "WHERE ep.edit_page_id = epa.edit_page_id AND eg.edit_group_id = epa.edit_group_id AND eg.edit_group_id = eu.edit_group_id "; $q .= "WHERE ep.edit_page_id = epa.edit_page_id AND eg.edit_group_id = epa.edit_group_id AND eg.edit_group_id = eu.edit_group_id ";
@@ -480,12 +515,9 @@
// unset mem limit if debug is set to 1 // unset mem limit if debug is set to 1
// if (($GLOBALS["DEBUG_ALL"] || $GLOBALS["DB_DEBUG"] || $_SESSION["DEBUG_ALL"] || $_SESSION["DB_DEBUG"]) && ini_get('memory_limit') != -1) // if (($GLOBALS["DEBUG_ALL"] || $GLOBALS["DB_DEBUG"] || $_SESSION["DEBUG_ALL"] || $_SESSION["DB_DEBUG"]) && ini_get('memory_limit') != -1)
// ini_set('memory_limit', -1); // ini_set('memory_limit', -1);
if ($res["filename"] == $this->page_name) if ($res["filename"] == $this->page_name) {
{
$this->permission_okay = 1; $this->permission_okay = 1;
} } else {
else
{
$this->login_error = 103; $this->login_error = 103;
$this->permission_okay = 0; $this->permission_okay = 0;
} }
@@ -500,8 +532,7 @@
// DESC : if a user pressed on logout, destroyes session and unsets all global vars // DESC : if a user pressed on logout, destroyes session and unsets all global vars
public function login_logout_user() public function login_logout_user()
{ {
if ($this->logout || $this->login_error) if ($this->logout || $this->login_error) {
{
// unregister and destroy session vars // unregister and destroy session vars
unset($_SESSION["EUID"]); unset($_SESSION["EUID"]);
unset($_SESSION["GROUP_LEVEL"]); unset($_SESSION["GROUP_LEVEL"]);
@@ -546,28 +577,22 @@
$this->acl['base'] = DEFAULT_ACL_LEVEL; $this->acl['base'] = DEFAULT_ACL_LEVEL;
// set admin flag and base to 100 // set admin flag and base to 100
if ($_SESSION['ADMIN']) if ($_SESSION['ADMIN']) {
{
$this->acl['admin'] = 1; $this->acl['admin'] = 1;
$this->acl['base'] = 100; $this->acl['base'] = 100;
} } else {
else
{
// now go throw the flow and set the correct ACL // now go throw the flow and set the correct ACL
// user > page > group // user > page > group
// group ACL 0 // group ACL 0
if ($_SESSION['GROUP_ACL_LEVEL'] != -1) if ($_SESSION['GROUP_ACL_LEVEL'] != -1) {
{
$this->acl['base'] = $_SESSION['GROUP_ACL_LEVEL']; $this->acl['base'] = $_SESSION['GROUP_ACL_LEVEL'];
} }
// page ACL 1 // page ACL 1
if ($_SESSION['PAGES_ACL_LEVEL'][$this->page_name] != -1) if ($_SESSION['PAGES_ACL_LEVEL'][$this->page_name] != -1) {
{
$this->acl['base'] = $_SESSION['PAGES_ACL_LEVEL'][$this->page_name]; $this->acl['base'] = $_SESSION['PAGES_ACL_LEVEL'][$this->page_name];
} }
// user ACL 2 // user ACL 2
if ($_SESSION['USER_ACL_LEVEL'] != -1) if ($_SESSION['USER_ACL_LEVEL'] != -1) {
{
$this->acl['base'] = $_SESSION['USER_ACL_LEVEL']; $this->acl['base'] = $_SESSION['USER_ACL_LEVEL'];
} }
} }
@@ -577,29 +602,24 @@
// set group if not -1, overrides default // set group if not -1, overrides default
// set page if not -1, overrides group set // set page if not -1, overrides group set
$this->acl['page'] = DEFAULT_ACL_LEVEL; $this->acl['page'] = DEFAULT_ACL_LEVEL;
if ($_SESSION['GROUP_ACL_LEVEL'] != -1) if ($_SESSION['GROUP_ACL_LEVEL'] != -1) {
{
$this->acl['page'] = $_SESSION['GROUP_ACL_LEVEL']; $this->acl['page'] = $_SESSION['GROUP_ACL_LEVEL'];
} }
if (isset($_SESSION['PAGES_ACL_LEVEL'][$this->page_name]) && $_SESSION['PAGES_ACL_LEVEL'][$this->page_name] != -1) if (isset($_SESSION['PAGES_ACL_LEVEL'][$this->page_name]) && $_SESSION['PAGES_ACL_LEVEL'][$this->page_name] != -1) {
{
$this->acl['page'] = $_SESSION['PAGES_ACL_LEVEL'][$this->page_name]; $this->acl['page'] = $_SESSION['PAGES_ACL_LEVEL'][$this->page_name];
} }
// PER ACCOUNT (UNIT/edit access)-> // PER ACCOUNT (UNIT/edit access)->
foreach ($_SESSION['UNIT'] as $ea_id => $unit) foreach ($_SESSION['UNIT'] as $ea_id => $unit) {
{
// if admin flag is set, all units are set to 100 // if admin flag is set, all units are set to 100
if ($this->acl['admin']) if ($this->acl['admin']) {
{ $this->acl['unit'][$ea_id] = $this->acl['base'];
} else {
if ($unit['acl_level'] != -1) {
$this->acl['unit'][$ea_id] = $unit['acl_level'];
} else {
$this->acl['unit'][$ea_id] = $this->acl['base']; $this->acl['unit'][$ea_id] = $this->acl['base'];
} }
else
{
if ($unit['acl_level'] != -1)
$this->acl['unit'][$ea_id] = $unit['acl_level'];
else
$this->acl['unit'][$ea_id] = $this->acl['base'];
} }
// detail name/level set // detail name/level set
$this->acl['unit_detail'][$ea_id] = array ( $this->acl['unit_detail'][$ea_id] = array (
@@ -610,23 +630,22 @@
'data' => $unit['data'] 'data' => $unit['data']
); );
// set default // set default
if ($unit['default']) if ($unit['default']) {
{
$this->acl['unit_id'] = $unit['id']; $this->acl['unit_id'] = $unit['id'];
$this->acl['unit_name'] = $unit['name']; $this->acl['unit_name'] = $unit['name'];
$this->acl['unit_uid'] = $unit['uid']; $this->acl['unit_uid'] = $unit['uid'];
} }
} }
// flag if to show extra edit access drop downs (because user has multiple groups assigned) // flag if to show extra edit access drop downs (because user has multiple groups assigned)
if (count($_SESSION['UNIT']) > 1) if (count($_SESSION['UNIT']) > 1) {
$this->acl['show_ea_extra'] = 1; $this->acl['show_ea_extra'] = 1;
else } else {
$this->acl['show_ea_extra'] = 0; $this->acl['show_ea_extra'] = 0;
}
// set the default edit access // set the default edit access
$this->acl['default_edit_access'] = $_SESSION['UNIT_DEFAULT']; $this->acl['default_edit_access'] = $_SESSION['UNIT_DEFAULT'];
// integrate the type acl list, but only for the keyword -> level // integrate the type acl list, but only for the keyword -> level
foreach ($this->default_acl_list as $level => $data) foreach ($this->default_acl_list as $level => $data) {
{
$this->acl['min'][$data['type']] = $level; $this->acl['min'][$data['type']] = $level;
} }
// set the full acl list too // set the full acl list too
@@ -641,11 +660,34 @@
// DESC : checks if this edit access id is valid // DESC : checks if this edit access id is valid
public function login_check_edit_access($edit_access_id) public function login_check_edit_access($edit_access_id)
{ {
if (array_key_exists($edit_access_id, $this->acl['unit'])) if (array_key_exists($edit_access_id, $this->acl['unit'])) {
return true; return true;
else } else {
return false; return false;
} }
}
// METHOD: loginPasswordChangeValidPassword
// PARAMS: the new password
// RETURN: true or false
// DESC : checks if the password is in a valid format
private function loginPasswordChangeValidPassword($password)
{
$is_valid_password = true;
// check for valid in regex arrays in list
if (is_array($this->password_valid_chars)) {
foreach ($this->password_valid_chars as $password_valid_chars) {
if (!preg_match("/$password_valid_chars/", $password)) {
$is_valid_password = false;
}
}
}
// check for min length
if (strlen($password) < $this->password_min_length) {
$is_valid_password = false;
}
return $is_valid_password;
}
// METHOD: login_password_change // METHOD: login_password_change
// PARAMS: none // PARAMS: none
@@ -653,76 +695,70 @@
// DESC : changes a user password // DESC : changes a user password
private function login_password_change() private function login_password_change()
{ {
if ($this->change_password) if ($this->change_password) {
{
$event = 'Password Change'; $event = 'Password Change';
// check that given username is NOT in the deny list, else silent skip (with error log) // check that given username is NOT in the deny list, else silent skip (with error log)
if (!in_array($this->pw_username, $this->pw_change_deny_users)) if (!in_array($this->pw_username, $this->pw_change_deny_users)) {
{ if (!$this->pw_username || !$this->pw_password) {
if (!$this->pw_username || !$this->pw_password)
{
$this->login_error = 200; $this->login_error = 200;
$data = 'Missing username or old password.'; $data = 'Missing username or old password.';
} }
// check user exist, if not -> error // check user exist, if not -> error
if (!$this->login_error) if (!$this->login_error) {
{
$q = "SELECT edit_user_id FROM edit_user WHERE enabled = 1 AND username = '".$this->db_escape_string($this->pw_username)."'"; $q = "SELECT edit_user_id FROM edit_user WHERE enabled = 1 AND username = '".$this->db_escape_string($this->pw_username)."'";
list ($edit_user_id) = $this->db_return_row($q); list ($edit_user_id) = $this->db_return_row($q);
if (!$edit_user_id) if (!$edit_user_id) {
{
// username wrong // username wrong
$this->login_error = 201; $this->login_error = 201;
$data = 'User could not be found'; $data = 'User could not be found';
} }
} }
// check old passwords match -> error // check old passwords match -> error
if (!$this->login_error) if (!$this->login_error) {
{ $q = "SELECT edit_user_id, password FROM edit_user WHERE enabled = 1 AND username = '".$this->dbEscapeString($this->pw_username)."'";
$q = "SELECT edit_user_id FROM edit_user WHERE enabled = 1 AND username = '".$this->db_escape_string($this->pw_username)."' AND password = '".$this->db_escape_string($this->pw_old_password)."'"; list ($edit_user_id, $old_password_hash) = $this->dbReturnRow($q);
list ($edit_user_id) = $this->db_return_row($q); if (!$edit_user_id || !$this->loginPasswordCheck($old_password_hash, $this->pw_old_password)) {
if (!$edit_user_id)
{
// old password wrong // old password wrong
$this->login_error = 202; $this->login_error = 202;
$data = 'The old password does not match'; $data = 'The old password does not match';
} }
} }
// check if new passwords were filled out -> error // check if new passwords were filled out -> error
if (!$this->login_error) if (!$this->login_error) {
{ if (!$this->pw_new_password || !$this->pw_new_password_confirm) {
if (!$this->pw_new_password || !$this->pw_new_password_confirm)
{
$this->login_error = 203; $this->login_error = 203;
$data = 'Missing new password or new password confirm.'; $data = 'Missing new password or new password confirm.';
} }
} }
// check new passwords both match -> error // check new passwords both match -> error
if (!$this->login_error) if (!$this->login_error) {
{ if ($this->pw_new_password != $this->pw_new_password_confirm) {
if ($this->pw_new_password != $this->pw_new_password_confirm)
{
$this->login_error = 204; $this->login_error = 204;
$data = 'The new passwords do not match: '.$this->pw_new_password.' == '.$this->pw_new_password_confirm; $data = 'The new passwords do not match';
}
}
// password shall match to something in minimum length or form
if (!$this->login_error) {
if (!$this->loingPasswordChangeValidPassword($this->pw_new_password)) {
$this->login_error = 205;
$data = 'The new password string is not valid';
} }
} }
// no error change this users password // no error change this users password
if (!$this->login_error) if (!$this->login_error) {
{
// update the user (edit_user_id) with the new password // update the user (edit_user_id) with the new password
$q = "UPDATE edit_user SET password = '".$this->db_escape_string($this->cryptString($this->pw_new_password))."' WHERE edit_user_id = ".$edit_user_id; $q = "UPDATE edit_user SET password = '".$this->db_escape_string($this->passwordSet($this->pw_new_password))."' WHERE edit_user_id = ".$edit_user_id;
$this->db_exec($q); $this->db_exec($q);
$data = 'Password change for user "'.$this->pw_username.'" from "'.$this->pw_old_password.'" to "'.$this->pw_new_password.'"'; $data = 'Password change for user "'.$this->pw_username.'"';
$this->password_change_ok = true;
} }
} } else {
else
{
// illegal user error // illegal user error
$this->login_error = '220'; $this->login_error = '220';
$data = 'Illegal user for password change: '.$this->pw_username; $data = 'Illegal user for password change: '.$this->pw_username;
} }
// log this password change attempt // log this password change attempt
$this->write_log($event, $data, $this->login_error, $pw_username, $pw_old_password); $this->write_log($event, $data, $this->login_error, $pw_username);
} // button pressed } // button pressed
} }
@@ -732,50 +768,61 @@
// DESC : prints out login html part if no permission (error) is set // DESC : prints out login html part if no permission (error) is set
private function login_print_login() private function login_print_login()
{ {
if (!$this->permission_okay) if (!$this->permission_okay) {
{
// set the templates now // set the templates now
$this->login_set_templates(); $this->login_set_templates();
// if there is a global logout target ... // if there is a global logout target ...
if (file_exists($this->logout_target) && $this->logout_target) if (file_exists($this->logout_target) && $this->logout_target) {
{
$LOGOUT_TARGET = $this->logout_target; $LOGOUT_TARGET = $this->logout_target;
} else } else {
{
$LOGOUT_TARGET = ""; $LOGOUT_TARGET = "";
} }
$html_string = $this->login_template['template']; $html_string = $this->login_template['template'];
// if password change is okay // if password change is okay
if ($this->password_change) if ($this->password_change) {
{
$html_string_password_change = $this->login_template['password_change']; $html_string_password_change = $this->login_template['password_change'];
// pre change the data in the PASSWORD_CHANGE_DIV first // pre change the data in the PASSWORD_CHANGE_DIV first
foreach ($this->login_template['strings'] as $string => $data) foreach ($this->login_template['strings'] as $string => $data) {
{ if ($data) {
if ($data)
$html_string_password_change = str_replace("{".$string."}", $data, $html_string_password_change); $html_string_password_change = str_replace("{".$string."}", $data, $html_string_password_change);
} }
}
// print error messagae
if ($this->login_error) {
$html_string_password_change = str_replace("{ERROR_MSG}", $this->login_error_msg[$this->login_error]."<br>", $html_string_password_change);
} else {
$html_string_password_change = str_replace("{ERROR_MSG}", "<br>", $html_string_password_change);
}
// if pw change action, show the float again
if ($this->change_password && !$this->password_change_ok) {
$html_string_password_change = str_replace('{PASSWORD_CHANGE_SHOW}', '<script language="JavaScript">ShowHideDiv(\'pw_change_div\');</script>', $html_string_password_change);
} else {
$html_string_password_change = str_replace('{PASSWORD_CHANGE_SHOW}', '', $html_string_password_change);
}
$this->login_template['strings']['PASSWORD_CHANGE_DIV'] = $html_string_password_change; $this->login_template['strings']['PASSWORD_CHANGE_DIV'] = $html_string_password_change;
} }
// put in the logout redirect string // put in the logout redirect string
if ($this->logout && $LOGOUT_TARGET) if ($this->logout && $LOGOUT_TARGET) {
$html_string = str_replace("{LOGOUT_TARGET}", '<meta http-equiv="refresh" content="0; URL='.$LOGOUT_TARGET.'">', $html_string); $html_string = str_replace("{LOGOUT_TARGET}", '<meta http-equiv="refresh" content="0; URL='.$LOGOUT_TARGET.'">', $html_string);
else } else {
$html_string = str_replace("{LOGOUT_TARGET}", '', $html_string); $html_string = str_replace("{LOGOUT_TARGET}", '', $html_string);
}
// print error messagae // print error messagae
if ($this->login_error) if ($this->login_error) {
$html_string = str_replace("{ERROR_MSG}", $this->login_error_msg[$this->login_error]."<br>", $html_string); $html_string = str_replace("{ERROR_MSG}", $this->login_error_msg[$this->login_error]."<br>", $html_string);
else } elseif ($this->password_change_ok && $this->password_change) {
$html_string = str_replace('{ERROR_MSG}', $this->login_error_msg[300].'<br>', $html_string);
} else {
$html_string = str_replace("{ERROR_MSG}", "<br>", $html_string); $html_string = str_replace("{ERROR_MSG}", "<br>", $html_string);
}
// create the replace array context // create the replace array context
foreach ($this->login_template['strings'] as $string => $data) foreach ($this->login_template['strings'] as $string => $data) {
{
$html_string = str_replace("{".$string."}", $data, $html_string); $html_string = str_replace("{".$string."}", $data, $html_string);
} }
@@ -791,34 +838,30 @@
private function login_close_class() private function login_close_class()
{ {
// write to LOG table ... // write to LOG table ...
if ($this->login_error || $this->login || $this->logout) if ($this->login_error || $this->login || $this->logout) {
{
$username = ''; $username = '';
$password = ''; $password = '';
// set event // set event
if ($this->login) if ($this->login) {
$event = "Login"; $event = "Login";
else if ($this->logout) } elseif ($this->logout) {
$event = "Logout"; $event = "Logout";
else } else {
$event = "No Permission"; $event = "No Permission";
}
// prepare for log // prepare for log
if ($this->euid) if ($this->euid) {
{
// get user from user table // get user from user table
$q = "SELECT username, password FROM edit_user WHERE edit_user_id = ".$this->euid; $q = "SELECT username, password FROM edit_user WHERE edit_user_id = ".$this->euid;
list($username, $password) = $this->db_return_row($q); list($username, $password) = $this->db_return_row($q);
} // if euid is set, get username (or try) } // if euid is set, get username (or try)
$this->write_log($event, '', $this->login_error, $username, $password); $this->write_log($event, '', $this->login_error, $username);
} // write log under certain settings } // write log under certain settings
// now close DB connection // now close DB connection
// $this->error_msg = $this->_login(); // $this->error_msg = $this->_login();
if (!$this->permission_okay) if (!$this->permission_okay) {
{
return false; return false;
} } else {
else
{
return true; return true;
} }
} }
@@ -855,12 +898,13 @@
"202" => $this->l->__("Fatal Error: <b>Password change - The old password is not correct</b>"), "202" => $this->l->__("Fatal Error: <b>Password change - The old password is not correct</b>"),
"203" => $this->l->__("Fatal Error: <b>Password change - Please fill out both new password fields</b>"), "203" => $this->l->__("Fatal Error: <b>Password change - Please fill out both new password fields</b>"),
"204" => $this->l->__("Fatal Error: <b>Password change - The new passwords do not match</b>"), "204" => $this->l->__("Fatal Error: <b>Password change - The new passwords do not match</b>"),
"205" => $this->l->__("Fatal Error: <b>Password change - The new password is not in a valid format</b>"), // we should also not here WHAT is valid
"300" => $this->l->__("Success: <b>Password change successful</b>"), // for OK password change
"9999" => $this->l->__("Fatal Error: <b>necessary crypt engine could not be found</b>. Login is impossible") // this is bad bad error "9999" => $this->l->__("Fatal Error: <b>necessary crypt engine could not be found</b>. Login is impossible") // this is bad bad error
); );
// if password change is okay // if password change is okay
if ($this->password_change) if ($this->password_change) {
{
$strings = array_merge($strings, array ( $strings = array_merge($strings, array (
'TITLE_PASSWORD_CHANGE' => 'Change Password for User', 'TITLE_PASSWORD_CHANGE' => 'Change Password for User',
'OLD_PASSWORD' => $this->l->__("Old Password"), 'OLD_PASSWORD' => $this->l->__("Old Password"),
@@ -882,10 +926,9 @@
<tr><td></td><td><input type="submit" name="change_password" value="{PASSWORD_CHANGE_BUTTON_VALUE}"><input type="button" name="pw_change" value="{CLOSE}" OnClick="ShowHideDiv('pw_change_div');"></td></tr> <tr><td></td><td><input type="submit" name="change_password" value="{PASSWORD_CHANGE_BUTTON_VALUE}"><input type="button" name="pw_change" value="{CLOSE}" OnClick="ShowHideDiv('pw_change_div');"></td></tr>
</table> </table>
</div> </div>
{PASSWORD_CHANGE_SHOW}
EOM; EOM;
} } else {
else
{
$strings = array_merge($strings, array ( $strings = array_merge($strings, array (
'JS_SHOW_HIDE' => '', 'JS_SHOW_HIDE' => '',
'PASSWORD_CHANGE_BUTTON' => '', 'PASSWORD_CHANGE_BUTTON' => '',
@@ -894,26 +937,21 @@ EOM;
} }
// first check if all strings are set from outside, if not, set with default ones // first check if all strings are set from outside, if not, set with default ones
while (list($string, $data) = each($strings)) while (list($string, $data) = each($strings)) {
{ if (!array_key_exists($string, $this->login_template['strings'])) {
if (!array_key_exists($string, $this->login_template['strings']))
{
$this->login_template['strings'][$string] = $data; $this->login_template['strings'][$string] = $data;
} }
} }
// error msgs the same // error msgs the same
while (list($code, $data) = each($error_msgs)) while (list($code, $data) = each($error_msgs)) {
{ if (!array_key_exists($code, $this->login_error_msg)) {
if (!array_key_exists($code, $this->login_error_msg))
{
$this->login_error_msg[$code] = $data; $this->login_error_msg[$code] = $data;
} }
} }
// now check templates // now check templates
if (!$this->login_template['template']) if (!$this->login_template['template']) {
{
$this->login_template['template'] = <<<EOM $this->login_template['template'] = <<<EOM
<html> <html>
<head> <head>
@@ -958,8 +996,7 @@ h3 { font-size: 18px; }
<td><input type="password" name="login_password"></td> <td><input type="password" name="login_password"></td>
</tr> </tr>
<tr> <tr>
<td align="right"> <td align="right"></td>
</td>
<td> <td>
<input type="submit" name="login_login" value="{LOGIN}"> <input type="submit" name="login_login" value="{LOGIN}">
{PASSWORD_CHANGE_BUTTON} {PASSWORD_CHANGE_BUTTON}
@@ -986,12 +1023,15 @@ EOM;
// error -> if error, write error string (not enougth data, etc) // error -> if error, write error string (not enougth data, etc)
// RETURN: none // RETURN: none
// DESC : writes detailed data into the edit user log table (keep log what user does) // DESC : writes detailed data into the edit user log table (keep log what user does)
private function write_log($event, $data, $error = "", $username = "", $password = "") private function write_log($event, $data, $error = '', $username = '')
{ {
if ($this->login) if ($this->login) {
$this->action = 'Login'; $this->action = 'Login';
elseif ($this->logout) } elseif ($this->logout) {
$this->action = 'Logout'; $this->action = 'Logout';
} else {
$this->action = '';
}
$_data_binary = array ( $_data_binary = array (
'_SESSION' => $_SESSION, '_SESSION' => $_SESSION,
'_GET' => $_GET, '_GET' => $_GET,
@@ -1005,14 +1045,15 @@ EOM;
$q .= "(username, password, euid, event_date, event, error, data, data_binary, page, "; $q .= "(username, password, euid, event_date, event, error, data, data_binary, page, ";
$q .= "ip, user_agent, referer, script_name, query_string, server_name, http_host, http_accept, http_accept_charset, http_accept_encoding, session_id, "; $q .= "ip, user_agent, referer, script_name, query_string, server_name, http_host, http_accept, http_accept_charset, http_accept_encoding, session_id, ";
$q .= "action, action_id, action_yes, action_flag, action_menu, action_loaded, action_value, action_error) "; $q .= "action, action_id, action_yes, action_flag, action_menu, action_loaded, action_value, action_error) ";
$q .= "VALUES ('".$this->db_escape_string($username)."', '".$this->db_escape_string($password)."', ".(($this->euid) ? $this->euid : 'NULL').", NOW(), '".$this->db_escape_string($event)."', '".$this->db_escape_string($error)."', '".$this->db_escape_string($data)."', '".$data_binary."', '".$this->page_name."', "; $q .= "VALUES ('".$this->db_escape_string($username)."', 'PASSWORD', ".(($this->euid) ? $this->euid : 'NULL').", ";
foreach (array('REMOTE_ADDR', 'HTTP_USER_AGENT', 'HTTP_REFERER', 'SCRIPT_FILENAME', 'QUERY_STRING', 'SERVER_NAME', 'HTTP_HOST', 'HTTP_ACCEPT', 'HTTP_ACCEPT_CHARSET', 'HTTP_ACCEPT_ENCODING') as $server_code) $q .= "NOW(), '".$this->db_escape_string($event)."', '".$this->db_escape_string($error)."', '".$this->db_escape_string($data)."', '".$data_binary."', '".$this->page_name."', ";
{ foreach (array('REMOTE_ADDR', 'HTTP_USER_AGENT', 'HTTP_REFERER', 'SCRIPT_FILENAME', 'QUERY_STRING', 'SERVER_NAME', 'HTTP_HOST', 'HTTP_ACCEPT', 'HTTP_ACCEPT_CHARSET', 'HTTP_ACCEPT_ENCODING') as $server_code) {
if (array_key_exists($server_code, $_SERVER)) if (array_key_exists($server_code, $_SERVER)) {
$q .= "'".$this->db_escape_string($_SERVER[$server_code])."', "; $q .= "'".$this->db_escape_string($_SERVER[$server_code])."', ";
else } else {
$q .= "NULL, "; $q .= "NULL, ";
} }
}
$q .= "'".session_id()."', "; $q .= "'".session_id()."', ";
$q .= "'".$this->db_escape_string($this->action)."', '".$this->db_escape_string($this->username)."', NULL, '".$this->db_escape_string($this->login_error)."', NULL, NULL, '".$this->db_escape_string($this->permission_okay)."', NULL)"; $q .= "'".$this->db_escape_string($this->action)."', '".$this->db_escape_string($this->username)."', NULL, '".$this->db_escape_string($this->login_error)."', NULL, NULL, '".$this->db_escape_string($this->permission_okay)."', NULL)";
$this->db_exec($q, 'NULL'); $this->db_exec($q, 'NULL');
@@ -1024,11 +1065,12 @@ EOM;
// DESC : checks that the given edit access id is valid for this user // DESC : checks that the given edit access id is valid for this user
public function login_check_edit_access_id($edit_access_id) public function login_check_edit_access_id($edit_access_id)
{ {
if (!array_key_exists($edit_access_id, $_SESSION["UNIT"])) if (!array_key_exists($edit_access_id, $_SESSION["UNIT"])) {
return $_SESSION["UNIT_DEFAULT"]; return $_SESSION["UNIT_DEFAULT"];
else } else {
return $edit_access_id; return $edit_access_id;
} }
}
// METHOD: login_set_edit_access_data // METHOD: login_set_edit_access_data
// PARAMS: edit access id, key value to search for // PARAMS: edit access id, key value to search for
@@ -1036,11 +1078,10 @@ EOM;
// DESC : searchs in the data set for the unit for the data key and returns the value asociated with it // DESC : searchs in the data set for the unit for the data key and returns the value asociated with it
public function login_set_edit_access_data($edit_access_id, $data_key) public function login_set_edit_access_data($edit_access_id, $data_key)
{ {
if (!$_SESSION['UNIT'][$edit_access_id]['data'][$data_key]) if (!$_SESSION['UNIT'][$edit_access_id]['data'][$data_key]) {
return false; return false;
else } else {
return $_SESSION['UNIT'][$edit_access_id]['data'][$data_key]; return $_SESSION['UNIT'][$edit_access_id]['data'][$data_key];
} }
}
} // close class } // close class
?>

View File

@@ -73,10 +73,12 @@ class ProgressBar
public function __construct($width = 0, $height = 0) public function __construct($width = 0, $height = 0)
{ {
$this->code = substr(md5(microtime()), 0, 6); $this->code = substr(md5(microtime()), 0, 6);
if ($width > 0) if ($width > 0) {
$this->width = $width; $this->width = $width;
if ($height > 0) }
if ($height > 0) {
$this->height = $height; $this->height = $height;
}
// needs to be called twice or I do not get any output // needs to be called twice or I do not get any output
$this->_flushCache($this->clear_buffer_size_init); $this->_flushCache($this->clear_buffer_size_init);
$this->_flushCache($this->clear_buffer_size_init); $this->_flushCache($this->clear_buffer_size_init);
@@ -86,8 +88,9 @@ class ProgressBar
private function _flushCache($clear_buffer_size = 0) private function _flushCache($clear_buffer_size = 0)
{ {
if (!$clear_buffer_size) if (!$clear_buffer_size) {
$clear_buffer_size = $this->clear_buffer_size; $clear_buffer_size = $this->clear_buffer_size;
}
echo str_repeat(' ', $clear_buffer_size); echo str_repeat(' ', $clear_buffer_size);
ob_flush(); ob_flush();
flush(); flush();
@@ -96,18 +99,19 @@ class ProgressBar
private function _calculatePercent($step) private function _calculatePercent($step)
{ {
// avoid divison through 0 // avoid divison through 0
if ($this->max - $this->min == 0) if ($this->max - $this->min == 0) {
$this->max ++; $this->max ++;
}
$percent = round(($step - $this->min) / ($this->max - $this->min) * 100); $percent = round(($step - $this->min) / ($this->max - $this->min) * 100);
if ($percent > 100) if ($percent > 100) {
$percent = 100; $percent = 100;
}
return $percent; return $percent;
} }
private function _calculatePosition($step) private function _calculatePosition($step)
{ {
switch ($this->direction) switch ($this->direction) {
{
case 'right': case 'right':
case 'left': case 'left':
$bar = $this->width; $bar = $this->width;
@@ -118,16 +122,18 @@ class ProgressBar
break; break;
} }
// avoid divison through 0 // avoid divison through 0
if ($this->max - $this->min == 0) if ($this->max - $this->min == 0) {
$this->max ++; $this->max ++;
}
$pixel = round(($step - $this->min) * ($bar - ($this->pedding * 2)) / ($this->max - $this->min)); $pixel = round(($step - $this->min) * ($bar - ($this->pedding * 2)) / ($this->max - $this->min));
if ($step <= $this->min) if ($step <= $this->min) {
$pixel = 0; $pixel = 0;
if ($step >= $this->max) }
if ($step >= $this->max) {
$pixel = $bar - ($this->pedding * 2); $pixel = $bar - ($this->pedding * 2);
}
switch ($this->direction) switch ($this->direction) {
{
case 'right': case 'right':
$position['left'] = $this->pedding; $position['left'] = $this->pedding;
$position['top'] = $this->pedding; $position['top'] = $this->pedding;
@@ -158,10 +164,12 @@ class ProgressBar
private function _setStep($step) private function _setStep($step)
{ {
if ($step > $this->max) if ($step > $this->max) {
$step = $this->max; $step = $this->max;
if ($step < $this->min) }
if ($step < $this->min) {
$step = $this->min; $step = $this->min;
}
$this->step = $step; $this->step = $step;
} }
@@ -179,16 +187,17 @@ class ProgressBar
'brd_color' => '#dfdfdf #404040 #404040 #dfdfdf' 'brd_color' => '#dfdfdf #404040 #404040 #dfdfdf'
); );
if ($width > 0) if ($width > 0) {
$this->frame['width'] = $width; $this->frame['width'] = $width;
if ($height > 0) }
if ($height > 0) {
$this->frame['height'] = $height; $this->frame['height'] = $height;
} }
}
public function addLabel($type, $name, $value = '&nbsp;') public function addLabel($type, $name, $value = '&nbsp;')
{ {
switch($type) switch ($type) {
{
case 'text': case 'text':
$this->label[$name] = array( $this->label[$name] = array(
'type' => 'text', 'type' => 'text',
@@ -242,10 +251,11 @@ class ProgressBar
case 'percentlbl': case 'percentlbl':
case 'percent': case 'percent':
// check font size // check font size
if ($this->height <= 11) if ($this->height <= 11) {
$font_size = $this->height - 1; $font_size = $this->height - 1;
else } else {
$font_size = 11; $font_size = 11;
}
$this->label[$name] = array( $this->label[$name] = array(
'type' => $type, // either percent or percentlbl 'type' => $type, // either percent or percentlbl
'value' => $value, 'value' => $value,
@@ -292,19 +302,19 @@ class ProgressBar
{ {
// print "SET POSITION[$name]: $left<br>"; // print "SET POSITION[$name]: $left<br>";
// if this is percent, we ignore anything, it is auto positioned // if this is percent, we ignore anything, it is auto positioned
if ($this->label[$name]['type'] != 'percent') if ($this->label[$name]['type'] != 'percent') {
{ foreach (array('top', 'left', 'width', 'height') as $pos_name) {
if ($$pos_name !== false) {
foreach (array('top', 'left', 'width', 'height') as $pos_name)
if ($$pos_name !== false)
$this->label[$name][$pos_name] = intval($$pos_name); $this->label[$name][$pos_name] = intval($$pos_name);
}
}
if ($align != '') if ($align != '') {
$this->label[$name]['align'] = $align; $this->label[$name]['align'] = $align;
} }
}
// init // init
if ($this->status != 'new') if ($this->status != 'new') {
{
$output = '<script type="text/JavaScript">'; $output = '<script type="text/JavaScript">';
$output .= 'document.getElementById("plbl'.$name.$this->code.'").style.top="'.$this->label[$name]['top'].'px";'; $output .= 'document.getElementById("plbl'.$name.$this->code.'").style.top="'.$this->label[$name]['top'].'px";';
$output .= 'document.getElementById("plbl'.$name.$this->code.'").style.left="'.$this->label[$name]['left'].'px";'; $output .= 'document.getElementById("plbl'.$name.$this->code.'").style.left="'.$this->label[$name]['left'].'px";';
@@ -320,8 +330,7 @@ class ProgressBar
public function setLabelColor($name, $color) public function setLabelColor($name, $color)
{ {
$this->label[$name]['color'] = $color; $this->label[$name]['color'] = $color;
if ($this->status != 'new') if ($this->status != 'new') {
{
echo '<script type="text/JavaScript">document.getElementById("plbl'.$name.$this->code.'").style.color="'.$color.'";</script>'."\n"; echo '<script type="text/JavaScript">document.getElementById("plbl'.$name.$this->code.'").style.color="'.$color.'";</script>'."\n";
$this->_flushCache(); $this->_flushCache();
} }
@@ -330,8 +339,7 @@ class ProgressBar
public function setLabelBackground($name, $color) public function setLabelBackground($name, $color)
{ {
$this->label[$name]['bgr_color'] = $color; $this->label[$name]['bgr_color'] = $color;
if ($this->status != 'new') if ($this->status != 'new') {
{
echo '<script type="text/JavaScript">document.getElementById("plbl'.$name.$this->code.'").style.background="'.$color.'";</script>'."\n"; echo '<script type="text/JavaScript">document.getElementById("plbl'.$name.$this->code.'").style.background="'.$color.'";</script>'."\n";
$this->_flushCache(); $this->_flushCache();
} }
@@ -340,24 +348,28 @@ class ProgressBar
public function setLabelFont($name, $size, $family = '', $weight = '') public function setLabelFont($name, $size, $family = '', $weight = '')
{ {
// just in case if it is too small // just in case if it is too small
if (intval($size) < 0) if (intval($size) < 0) {
$size = 11; $size = 11;
}
// if this is percent, the size is not allowed to be bigger than the bar size - 5px // if this is percent, the size is not allowed to be bigger than the bar size - 5px
if ($this->label[$name]['type'] == 'percent' && intval($size) >= $this->height) if ($this->label[$name]['type'] == 'percent' && intval($size) >= $this->height) {
$size = $this->height - 1; $size = $this->height - 1;
}
// position the label new if this is percent // position the label new if this is percent
if ($this->label[$name]['type'] == 'percent') if ($this->label[$name]['type'] == 'percent') {
$this->label[$name]['top'] = round(($this->height - intval($size)) / log($this->height - intval($size), 7), 0) - $this->pedding; $this->label[$name]['top'] = round(($this->height - intval($size)) / log($this->height - intval($size), 7), 0) - $this->pedding;
}
// print "HEIGHT: ".$this->height.", Size: ".intval($size).", Pedding: ".$this->pedding.", Calc: ".round($this->height - intval($size)).", Log: ".log($this->height - intval($size), 7)."<br>"; // print "HEIGHT: ".$this->height.", Size: ".intval($size).", Pedding: ".$this->pedding.", Calc: ".round($this->height - intval($size)).", Log: ".log($this->height - intval($size), 7)."<br>";
// then set like usual // then set like usual
$this->label[$name]['font-size'] = intval($size); $this->label[$name]['font-size'] = intval($size);
if ($family != '') if ($family != '') {
$this->label[$name]['font-family'] = $family; $this->label[$name]['font-family'] = $family;
if ($weight != '') }
if ($weight != '') {
$this->label[$name]['font-weight'] = $weight; $this->label[$name]['font-weight'] = $weight;
}
if ($this->status != 'new') if ($this->status != 'new') {
{
$output = '<script type="text/JavaScript">'; $output = '<script type="text/JavaScript">';
$output .= 'document.getElementById("plbl'.$name.$this->code.'").style.font-size="'.$this->label[$name]['font-size'].'px";'; $output .= 'document.getElementById("plbl'.$name.$this->code.'").style.font-size="'.$this->label[$name]['font-size'].'px";';
$output .= 'document.getElementById("plbl'.$name.$this->code.'").style.font-family="'.$this->label[$name]['font-family'].'";'; $output .= 'document.getElementById("plbl'.$name.$this->code.'").style.font-family="'.$this->label[$name]['font-family'].'";';
@@ -372,8 +384,7 @@ class ProgressBar
{ {
$this->label[$name]['value'] = $value; $this->label[$name]['value'] = $value;
// print "NAME[$name], Status: ".$this->status.": ".$value."<Br>"; // print "NAME[$name], Status: ".$this->status.": ".$value."<Br>";
if ($this->status != 'new') if ($this->status != 'new') {
{
echo '<script type="text/JavaScript">PBlabelText'.$this->code.'("'.$name.'","'.$this->label[$name]['value'].'");</script>'."\n"; echo '<script type="text/JavaScript">PBlabelText'.$this->code.'("'.$name.'","'.$this->label[$name]['value'].'");</script>'."\n";
$this->_flushCache(); $this->_flushCache();
} }
@@ -382,8 +393,7 @@ class ProgressBar
public function setBarColor($color) public function setBarColor($color)
{ {
$this->color = $color; $this->color = $color;
if ($this->status != 'new') if ($this->status != 'new') {
{
echo '<script type="text/JavaScript">document.getElementById("pbar'.$this->code.'").style.background="'.$color.'";</script>'."\n"; echo '<script type="text/JavaScript">document.getElementById("pbar'.$this->code.'").style.background="'.$color.'";</script>'."\n";
$this->_flushCache(); $this->_flushCache();
} }
@@ -392,8 +402,7 @@ class ProgressBar
public function setBarBackground($color) public function setBarBackground($color)
{ {
$this->bgr_color = $color; $this->bgr_color = $color;
if ($this->status != 'new') if ($this->status != 'new') {
{
echo '<script type="text/JavaScript">document.getElementById("pbrd'.$this->code.'").style.background="'.$color.'";</script>'."\n"; echo '<script type="text/JavaScript">document.getElementById("pbrd'.$this->code.'").style.background="'.$color.'";</script>'."\n";
$this->_flushCache(); $this->_flushCache();
} }
@@ -403,8 +412,7 @@ class ProgressBar
{ {
$this->direction = $direction; $this->direction = $direction;
if ($this->status != 'new') if ($this->status != 'new') {
{
$this->position = $this->_calculatePosition($this->step); $this->position = $this->_calculatePosition($this->step);
echo '<script type="text/JavaScript">'; echo '<script type="text/JavaScript">';
@@ -426,25 +434,30 @@ class ProgressBar
$this->_setStep($this->step); $this->_setStep($this->step);
$this->position = $this->_calculatePosition($this->step); $this->position = $this->_calculatePosition($this->step);
if ($this->top || $this->left) if ($this->top || $this->left) {
$style_master = 'position:relative;top:'.$this->top.'px;left:'.$this->left.'px;width:'.($this->width + 10).'px;'; $style_master = 'position:relative;top:'.$this->top.'px;left:'.$this->left.'px;width:'.($this->width + 10).'px;';
}
$html = '<div id="pbm'.$this->code.'" style="'.$style_master.'background:'.$this->bgr_color_master.';">'; $html = '<div id="pbm'.$this->code.'" style="'.$style_master.'background:'.$this->bgr_color_master.';">';
$style_brd = 'width:'.$this->width.'px;height:'.$this->height.'px;background:'.$this->bgr_color.';'; $style_brd = 'width:'.$this->width.'px;height:'.$this->height.'px;background:'.$this->bgr_color.';';
if ($this->border > 0) if ($this->border > 0) {
$style_brd .= 'border:'.$this->border.'px solid; border-color:'.$this->brd_color.'; -webkit-border-radius: 5px 5px 5px 5px; border-radius: 5px 5px 5px 5px; -webkit-shadow: 2px 2px 10px rgba(0, 0, 0, 0.25) inset; box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.25) inset;'; $style_brd .= 'border:'.$this->border.'px solid; border-color:'.$this->brd_color.'; -webkit-border-radius: 5px 5px 5px 5px; border-radius: 5px 5px 5px 5px; -webkit-shadow: 2px 2px 10px rgba(0, 0, 0, 0.25) inset; box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.25) inset;';
}
$style_bar = 'position:relative;width:'.$this->position['width'].'px;height:'.$this->position['height'].'px;background:'.$this->color.';'; $style_bar = 'position:relative;width:'.$this->position['width'].'px;height:'.$this->position['height'].'px;background:'.$this->color.';';
if ($this->position['top'] !== false) if ($this->position['top'] !== false) {
$style_bar .= 'top:'.$this->position['top'].'px;'; $style_bar .= 'top:'.$this->position['top'].'px;';
if ($this->position['left'] !== false) }
if ($this->position['left'] !== false) {
$style_bar .= 'left:'.$this->position['left'].'px;'; $style_bar .= 'left:'.$this->position['left'].'px;';
if ($this->border > 0) }
if ($this->border > 0) {
$style_bar .= '-webkit-border-radius: 5px 5px 5px 5px; border-radius: 5px 5px 5px 5px; -webkit-shadow: 2px 2px 10px rgba(0, 0, 0, 0.25) inset; box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.25) inset;'; $style_bar .= '-webkit-border-radius: 5px 5px 5px 5px; border-radius: 5px 5px 5px 5px; -webkit-shadow: 2px 2px 10px rgba(0, 0, 0, 0.25) inset; box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.25) inset;';
}
if ($this->frame['show'] == true) if ($this->frame['show'] == true) {
{ if ($this->frame['border'] > 0) {
if ($this->frame['border'] > 0)
$border = 'border:'.$this->frame['border'].'px solid;border-color:'.$this->frame['brd_color'].';margin-top:2px;-webkit-border-radius: 5px 5px 5px 5px; border-radius: 5px 5px 5px 5px;'; $border = 'border:'.$this->frame['border'].'px solid;border-color:'.$this->frame['brd_color'].';margin-top:2px;-webkit-border-radius: 5px 5px 5px 5px; border-radius: 5px 5px 5px 5px;';
}
$html .= '<div id="pfrm'.$this->code.'" style="width:'.$this->frame['width'].'px;height:'.$this->frame['height'].'px;'.$border.'background:'.$this->frame['color'].';">'."\n"; $html .= '<div id="pfrm'.$this->code.'" style="width:'.$this->frame['width'].'px;height:'.$this->frame['height'].'px;'.$border.'background:'.$this->frame['color'].';">'."\n";
} }
@@ -465,34 +478,39 @@ class ProgressBar
$js .= '}'."\n"; $js .= '}'."\n";
//print "DUMP LABEL: <br><pre>".print_r($this->label, 1)."</pre><br>"; //print "DUMP LABEL: <br><pre>".print_r($this->label, 1)."</pre><br>";
foreach ($this->label as $name => $data) foreach ($this->label as $name => $data) {
{
// set what type of move we do // set what type of move we do
$move_prefix = $data['type'] == 'button' ? 'margin' : 'padding'; $move_prefix = $data['type'] == 'button' ? 'margin' : 'padding';
$style_lbl = 'position:relative;'; $style_lbl = 'position:relative;';
if ($data['top'] !== false) if ($data['top'] !== false) {
$style_lbl .= $move_prefix.'-top:'.$data['top'].'px;'; $style_lbl .= $move_prefix.'-top:'.$data['top'].'px;';
if ($data['left'] !== false) }
if ($data['left'] !== false) {
$style_lbl .= $move_prefix.'-left:'.$data['left'].'px;'; $style_lbl .= $move_prefix.'-left:'.$data['left'].'px;';
}
$style_lbl .= 'text-align:'.$data['align'].';'; $style_lbl .= 'text-align:'.$data['align'].';';
if ($data['width'] > 0) if ($data['width'] > 0) {
$style_lbl .= 'width:'.$data['width'].'px;'; $style_lbl .= 'width:'.$data['width'].'px;';
if ($data['height'] > 0) }
if ($data['height'] > 0) {
$style_lbl .= 'height:'.$data['height'].'px;'; $style_lbl .= 'height:'.$data['height'].'px;';
}
if (array_key_exists('font-size', $data)) if (array_key_exists('font-size', $data)) {
$style_lbl .= 'font-size:'.$data['font-size'].'px;'; $style_lbl .= 'font-size:'.$data['font-size'].'px;';
if (array_key_exists('font-family', $data)) }
if (array_key_exists('font-family', $data)) {
$style_lbl .= 'font-family:'.$data['font-family'].';'; $style_lbl .= 'font-family:'.$data['font-family'].';';
if (array_key_exists('font-weight', $data)) }
if (array_key_exists('font-weight', $data)) {
$style_lbl .= 'font-weight:'.$data['font-weight'].';'; $style_lbl .= 'font-weight:'.$data['font-weight'].';';
if (array_key_exists('bgr_color', $data) && ($data['bgr_color'] != '')) }
if (array_key_exists('bgr_color', $data) && ($data['bgr_color'] != '')) {
$style_lbl .= 'background:'.$data['bgr_color'].';'; $style_lbl .= 'background:'.$data['bgr_color'].';';
}
if (array_key_exists('type', $data)) if (array_key_exists('type', $data)) {
{ switch ($data['type']) {
switch ($data['type'])
{
case 'text': case 'text':
$html .= '<div id="plbl'.$name.$this->code.'" style="'.$style_lbl.'margin-bottom:2px;">'.$data['value'].'</div>'."\n"; $html .= '<div id="plbl'.$name.$this->code.'" style="'.$style_lbl.'margin-bottom:2px;">'.$data['value'].'</div>'."\n";
break; break;
@@ -505,8 +523,9 @@ class ProgressBar
case 'percent': case 'percent':
// only one inner percent // only one inner percent
// print "STYLE[$name]: ".$style_lbl."<br>"; // print "STYLE[$name]: ".$style_lbl."<br>";
if (!$html_percent) if (!$html_percent) {
$html_percent = '<div id="plbl'.$name.$this->code.'" style="'.$style_lbl.'width:'.$data['width'].'px;line-height:1;text-shadow: 0 0 .2em white, 0 0 .5em white;">'.$this->_calculatePercent($this->step).'%</div>'."\n"; $html_percent = '<div id="plbl'.$name.$this->code.'" style="'.$style_lbl.'width:'.$data['width'].'px;line-height:1;text-shadow: 0 0 .2em white, 0 0 .5em white;">'.$this->_calculatePercent($this->step).'%</div>'."\n";
}
break; break;
case 'percentlbl': case 'percentlbl':
$html .= '<div id="plbl'.$name.$this->code.'" style="'.$style_lbl.'width:'.$data['width'].'px;">'.$this->_calculatePercent($this->step).'%</div>'."\n"; $html .= '<div id="plbl'.$name.$this->code.'" style="'.$style_lbl.'width:'.$data['width'].'px;">'.$this->_calculatePercent($this->step).'%</div>'."\n";
@@ -535,17 +554,14 @@ class ProgressBar
$html .= $html_bar_bottom; $html .= $html_bar_bottom;
$html .= $html_button; // any buttons on bottom $html .= $html_button; // any buttons on bottom
if (count($this->label) > 0) if (count($this->label) > 0) {
{
$js .= 'function PBlabelText'.$this->code.'(name,text) {'."\n"; $js .= 'function PBlabelText'.$this->code.'(name,text) {'."\n";
$js .= ' name = "plbl" + name + "'.$this->code.'";'."\n"; $js .= ' name = "plbl" + name + "'.$this->code.'";'."\n";
$js .= ' document.getElementById(name).innerHTML=text;'."\n"; $js .= ' document.getElementById(name).innerHTML=text;'."\n";
$js .= '}'."\n"; $js .= '}'."\n";
} }
if ($this->frame['show'] == true) if ($this->frame['show'] == true) {
{
$html .= '</div>'."\n"; $html .= '</div>'."\n";
} }
@@ -572,40 +588,31 @@ class ProgressBar
$js = ''; $js = '';
$new_position = $this->_calculatePosition($this->step); $new_position = $this->_calculatePosition($this->step);
if ($new_position['width'] != $this->position['width'] && ($this->direction == 'right' || $this->direction == 'left')) if ($new_position['width'] != $this->position['width'] && ($this->direction == 'right' || $this->direction == 'left')) {
{ if ($this->direction=='left') {
if ($this->direction=='left')
{
$js .= 'PBposition'.$this->code.'("left",'.$new_position['left'].');'; $js .= 'PBposition'.$this->code.'("left",'.$new_position['left'].');';
} }
$js .= 'PBposition'.$this->code.'("width",'.$new_position['width'].');'; $js .= 'PBposition'.$this->code.'("width",'.$new_position['width'].');';
} }
if ($new_position['height'] != $this->position['height'] && ($this->direction == 'up' || $this->direction == 'down')) if ($new_position['height'] != $this->position['height'] && ($this->direction == 'up' || $this->direction == 'down')) {
{ if ($this->direction=='up') {
if ($this->direction=='up')
{
$js .= 'PBposition'.$this->code.'("top",'.$new_position['top'].');'; $js .= 'PBposition'.$this->code.'("top",'.$new_position['top'].');';
} }
$js .= 'PBposition'.$this->code.'("height",'.$new_position['height'].');'; $js .= 'PBposition'.$this->code.'("height",'.$new_position['height'].');';
} }
$this->position = $new_position; $this->position = $new_position;
foreach($this->label as $name => $data) foreach ($this->label as $name => $data) {
{ if (array_key_exists('type', $data)) {
if (array_key_exists('type', $data)) switch($data['type']) {
{
switch($data['type'])
{
case 'step': case 'step':
if ($this->step != $last_step) if ($this->step != $last_step) {
{
$js .= 'PBlabelText'.$this->code.'("'.$name.'","'.$this->step.'/'.$this->max.'");'; $js .= 'PBlabelText'.$this->code.'("'.$name.'","'.$this->step.'/'.$this->max.'");';
} }
break; break;
case 'percentlbl': case 'percentlbl':
case 'percent': case 'percent':
$percent = $this->_calculatePercent($this->step); $percent = $this->_calculatePercent($this->step);
if ($percent != $this->_calculatePercent($last_step)) if ($percent != $this->_calculatePercent($last_step)) {
{
$js .= 'PBlabelText'.$this->code.'("'.$name.'","'.$percent.'%");'; $js .= 'PBlabelText'.$this->code.'("'.$name.'","'.$percent.'%");';
} }
break; break;
@@ -615,8 +622,7 @@ class ProgressBar
} }
} }
} }
if ($js != '') if ($js != '') {
{
echo '<script type="text/JavaScript">'.$js.'</script>'."\n"; echo '<script type="text/JavaScript">'.$js.'</script>'."\n";
$this->_flushCache(); $this->_flushCache();
} }
@@ -634,8 +640,7 @@ class ProgressBar
public function hide() public function hide()
{ {
if ($this->status == 'show') if ($this->status == 'show') {
{
$this->status = 'hide'; $this->status = 'hide';
$output = '<script type="text/JavaScript">'; $output = '<script type="text/JavaScript">';
@@ -648,8 +653,7 @@ class ProgressBar
public function unhide() public function unhide()
{ {
if ($this->status == 'hide') if ($this->status == 'hide') {
{
$this->status = 'show'; $this->status = 'show';
$output = '<script type="text/JavaScript">'; $output = '<script type="text/JavaScript">';
@@ -659,6 +663,4 @@ class ProgressBar
$this->_flushCache(); $this->_flushCache();
} }
} }
} }
?>

View File

@@ -21,11 +21,9 @@
public function __construct($lang) public function __construct($lang)
{ {
SmartyBC::__construct(); SmartyBC::__construct();
_spl_autoload('Class.l10.inc'); _spl_autoload('Class.l10n.inc');
$this->l10n = new l10n($lang); $this->l10n = new l10n($lang);
// variable variable register // variable variable register
$this->register_modifier('getvar', array(&$this, 'get_template_vars')); $this->register_modifier('getvar', array(&$this, 'get_template_vars'));
} }
} }
?>

View File

@@ -3,9 +3,7 @@
* AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org) * AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org)
* CREATED: 2004/11/18 * CREATED: 2004/11/18
* VERSION: 0.1.1 * VERSION: 0.1.1
* RELEASED LICENSE: BSD style (use it, u don't have to make YOUR source public) * RELEASED LICENSE: GNU GPL 3
* but let me know if u made changes, and please don't redistribute it
* with your name on it ...
* SHORT DESCRIPTION: * SHORT DESCRIPTION:
* init class for gettext. Original was just a function & var setting include for wordpress. * init class for gettext. Original was just a function & var setting include for wordpress.
* I changed that to a class to be more portable with my style of coding * I changed that to a class to be more portable with my style of coding
@@ -35,28 +33,32 @@
private $input; private $input;
private $l10n; private $l10n;
public function __construct($lang = '', $path = '') public function __construct($lang = '', $path = DEFAULT_TEMPLATE)
{ {
foreach (array('streams.php', 'gettext.php') as $include_file) foreach (array('streams.php', 'gettext.php') as $include_file) {
_spl_autoload($include_file); _spl_autoload($include_file);
}
if (!$lang) if (!$lang) {
$this->lang = 'en'; $this->lang = 'en';
else } else {
$this->lang = $lang; $this->lang = $lang;
}
if (!$path) if (is_dir(LAYOUT.$path.LANG)) {
$path = DEFAULT_TEMPLATE; $path = LAYOUT.$path.LANG;
if (!is_dir(LAYOUT.$path.LANG)) } elseif (!is_dir($path)) {
$path = ''; $path = '';
}
$this->mofile = LAYOUT.$path.LANG.$this->lang.".mo"; $this->mofile = $path.$this->lang.".mo";
// check if get a readable mofile // check if get a readable mofile
if (is_readable($this->mofile)) if (is_readable($this->mofile)) {
$this->input = new FileReader($this->mofile); $this->input = new FileReader($this->mofile);
else } else {
$this->input = false; $this->input = false;
}
$this->l10n = new gettext_reader($this->input); $this->l10n = new gettext_reader($this->input);
} }
@@ -69,19 +71,19 @@
$this->lang = $lang; $this->lang = $lang;
if (!is_dir(LAYOUT.$path.LANG)) if (is_dir(LAYOUT.$path.LANG)) {
$path = LAYOUT.$path.LANG;
} elseif (!is_dir($path)) {
$path = ''; $path = '';
}
$this->mofile = LAYOUT.$path.LANG.$this->lang.".mo"; $this->mofile = $path.$this->lang.".mo";
// check if get a readable mofile // check if get a readable mofile
if (is_readable($this->mofile)) if (is_readable($this->mofile)) {
{
$this->input = new FileReader($this->mofile); $this->input = new FileReader($this->mofile);
$this->l10n = new gettext_reader($this->input); $this->l10n = new gettext_reader($this->input);
} } else {
else
{
// else fall back to the old ones // else fall back to the old ones
$this->mofile = $old_mofile; $this->mofile = $old_mofile;
$this->lang = $old_lang; $this->lang = $old_lang;
@@ -103,5 +105,14 @@
{ {
return $this->l10n->ngettext($single, $plural, $number); return $this->l10n->ngettext($single, $plural, $number);
} }
public function __get_lang()
{
return $this->lang;
}
public function __get_mofile()
{
return $this->mofile;
}
} }
?>

View File

@@ -59,34 +59,31 @@
$ROOT = CURRENT_WORKING_DIR; $ROOT = CURRENT_WORKING_DIR;
$LOG = 'log/'; $LOG = 'log/';
// if the log folder is not found, try to create it // if the log folder is not found, try to create it
if (!is_dir($ROOT.$LOG) && !is_file($ROOT.LOG)) if (!is_dir($ROOT.$LOG) && !is_file($ROOT.LOG)) {
$ok = mkdir($ROOT.$LOG); $ok = mkdir($ROOT.$LOG);
}
$error = 0; $error = 0;
// again, if the folder now exists, else set error flag // again, if the folder now exists, else set error flag
if (is_dir($ROOT.$LOG)) if (is_dir($ROOT.$LOG)) {
{
$fn = $ROOT.$LOG.'php_errors-'.date('Y-m-d').'.log'; $fn = $ROOT.$LOG.'php_errors-'.date('Y-m-d').'.log';
// when opening, surpress the warning so we can catch the no file pointer below without throwing a warning for this // when opening, surpress the warning so we can catch the no file pointer below without throwing a warning for this
$fp = @fopen($fn, 'a'); $fp = @fopen($fn, 'a');
// write if we have a file pointer, else set error flag // write if we have a file pointer, else set error flag
if ($fp) if ($fp) {
{
fwrite($fp, $output."\n"); fwrite($fp, $output."\n");
fclose($fp); fclose($fp);
} } else {
else
$error = 1; $error = 1;
} }
else } else {
$error = 1; $error = 1;
}
// if the above writing failed // if the above writing failed
if ($error) if ($error) {
{
// if the display errors is on // if the display errors is on
// pretty print output for HTML // pretty print output for HTML
if (ini_get("display_errors")) if (ini_get("display_errors")) {
{
echo "<div style='border: 1px dotted red; background-color: #ffffe5; color: #000000; padding: 5px; margin-bottom: 2px;'>"; echo "<div style='border: 1px dotted red; background-color: #ffffe5; color: #000000; padding: 5px; margin-bottom: 2px;'>";
echo "<div style='color: orange; font-weight: bold;'>".$error_level[$type].":</div>"; echo "<div style='color: orange; font-weight: bold;'>".$error_level[$type].":</div>";
echo "<b>$message</b> on line <b>$line</b> in <b>$file</b>"; echo "<b>$message</b> on line <b>$line</b> in <b>$file</b>";
@@ -94,9 +91,10 @@
} }
// if write to log is on // if write to log is on
// simplified, remove datetime for log file // simplified, remove datetime for log file
if (ini_get('log_errors')) if (ini_get('log_errors')) {
error_log('{'.$page_temp.'} ['.$file.'] <'.$line.'> ['.$error_level[$type].'|'.$type.']: '.$message); error_log('{'.$page_temp.'} ['.$file.'] <'.$line.'> ['.$error_level[$type].'|'.$type.']: '.$message);
} }
}
// return true, to avoid that php calls its own error stuff // return true, to avoid that php calls its own error stuff
// if E_ERROR, the php one gets called anyway // if E_ERROR, the php one gets called anyway
return true; return true;
@@ -104,4 +102,3 @@
// init the error handler // init the error handler
set_error_handler("MyErrorHandler"); set_error_handler("MyErrorHandler");
?>

View File

@@ -3,12 +3,14 @@
/** /**
* Handle file uploads via XMLHttpRequest * Handle file uploads via XMLHttpRequest
*/ */
class qqUploadedFileXhr { class qqUploadedFileXhr
{
/** /**
* Save the file to the specified path * Save the file to the specified path
* @return boolean TRUE on success * @return boolean TRUE on success
*/ */
function save($path) { public function save($path)
{
$input = fopen("php://input", "r"); $input = fopen("php://input", "r");
$temp = tmpfile(); $temp = tmpfile();
$realSize = stream_copy_to_stream($input, $temp); $realSize = stream_copy_to_stream($input, $temp);
@@ -25,10 +27,12 @@ class qqUploadedFileXhr {
return true; return true;
} }
function getName() { public function getName()
{
return $_GET['qqfile']; return $_GET['qqfile'];
} }
function getSize() { public function getSize()
{
if (isset($_SERVER["CONTENT_LENGTH"])) { if (isset($_SERVER["CONTENT_LENGTH"])) {
return (int)$_SERVER["CONTENT_LENGTH"]; return (int)$_SERVER["CONTENT_LENGTH"];
} else { } else {
@@ -40,31 +44,37 @@ class qqUploadedFileXhr {
/** /**
* Handle file uploads via regular form post (uses the $_FILES array) * Handle file uploads via regular form post (uses the $_FILES array)
*/ */
class qqUploadedFileForm { class qqUploadedFileForm
{
/** /**
* Save the file to the specified path * Save the file to the specified path
* @return boolean TRUE on success * @return boolean TRUE on success
*/ */
function save($path) { public function save($path)
{
if (!move_uploaded_file($_FILES['qqfile']['tmp_name'], $path)) { if (!move_uploaded_file($_FILES['qqfile']['tmp_name'], $path)) {
return false; return false;
} }
return true; return true;
} }
function getName() { public function getName()
{
return $_FILES['qqfile']['name']; return $_FILES['qqfile']['name'];
} }
function getSize() { public function getSize()
{
return $_FILES['qqfile']['size']; return $_FILES['qqfile']['size'];
} }
} }
class qqFileUploader { class qqFileUploader
{
private $allowedExtensions = array(); private $allowedExtensions = array();
private $sizeLimit = 10485760; private $sizeLimit = 10485760;
private $file; private $file;
function __construct(array $allowedExtensions = array(), $sizeLimit = 10485760){ public function __construct(array $allowedExtensions = array(), $sizeLimit = 10485760)
{
$allowedExtensions = array_map("strtolower", $allowedExtensions); $allowedExtensions = array_map("strtolower", $allowedExtensions);
$this->allowedExtensions = $allowedExtensions; $this->allowedExtensions = $allowedExtensions;
@@ -81,7 +91,8 @@ class qqFileUploader {
} }
} }
private function checkServerSettings(){ private function checkServerSettings()
{
$postSize = $this->toBytes(ini_get('post_max_size')); $postSize = $this->toBytes(ini_get('post_max_size'));
$uploadSize = $this->toBytes(ini_get('upload_max_filesize')); $uploadSize = $this->toBytes(ini_get('upload_max_filesize'));
@@ -91,13 +102,19 @@ class qqFileUploader {
} }
} }
private function toBytes($str){ private function toBytes($str)
{
$val = trim($str); $val = trim($str);
$last = strtolower($str[strlen($str)-1]); $last = strtolower($str[strlen($str)-1]);
switch ($last) { switch ($last) {
case 'g': $val *= 1024; case 'g':
case 'm': $val *= 1024; $val *= 1024;
case 'k': $val *= 1024; // no break
case 'm':
$val *= 1024;
// no break
case 'k':
$val *= 1024;
} }
return $val; return $val;
} }
@@ -105,7 +122,8 @@ class qqFileUploader {
/** /**
* Returns array('success'=>true) or array('error'=>'error message') * Returns array('success'=>true) or array('error'=>'error message')
*/ */
function handleUpload($uploadDirectory, $replaceOldFile = FALSE){ public function handleUpload($uploadDirectory, $replaceOldFile = false)
{
if (!is_writable($uploadDirectory)) { if (!is_writable($uploadDirectory)) {
return array('error' => "Server error. Upload directory isn't writable."); return array('error' => "Server error. Upload directory isn't writable.");
} }
@@ -150,8 +168,5 @@ class qqFileUploader {
return array('error'=> 'Could not save uploaded file.' . return array('error'=> 'Could not save uploaded file.' .
'The upload was cancelled, or server error encountered'); 'The upload was cancelled, or server error encountered');
} }
} }
} }
?>

View File

@@ -47,8 +47,7 @@
{ {
// read out the query status and save the query if needed // read out the query status and save the query if needed
$result = @pg_query($dbh, $query); $result = @pg_query($dbh, $query);
if (!$result) if (!$result) {
{
$this->last_error_query = $query; $this->last_error_query = $query;
} }
return $result; return $result;
@@ -136,19 +135,18 @@
private function _db_insert_id($dbh, $query, $pk_name) private function _db_insert_id($dbh, $query, $pk_name)
{ {
// only if an insert has been done // only if an insert has been done
if (preg_match("/^insert /i", $query)) if (preg_match("/^insert /i", $query)) {
{
// get table name from insert // get table name from insert
$array = explode(' ', $query); $array = explode(' ', $query);
$_table = $array[2]; $_table = $array[2];
// if there is a dot inside, we need to split // if there is a dot inside, we need to split
if (strstr($_table, '.')) if (strstr($_table, '.')) {
list ($schema, $table) = explode('.', $_table); list ($schema, $table) = explode('.', $_table);
else } else {
$table = $_table; $table = $_table;
}
// no PK name given at all // no PK name given at all
if (!$pk_name) if (!$pk_name) {
{
// if name is plurar, make it singular // if name is plurar, make it singular
// if (preg_match("/.*s$/i", $table)) // if (preg_match("/.*s$/i", $table))
// $table = substr($table, 0, -1); // $table = substr($table, 0, -1);
@@ -160,12 +158,9 @@
$this->currval_query = $q; $this->currval_query = $q;
//echo "Q: $q<Br>"; //echo "Q: $q<Br>";
// I have to do manually or I overwrite the original insert internal vars ... // I have to do manually or I overwrite the original insert internal vars ...
if ($q = @pg_query($dbh, $q)) if ($q = @pg_query($dbh, $q)) {
{
list($id) = pg_fetch_array($q); list($id) = pg_fetch_array($q);
} } else {
else
{
$id = array(-1, $q); $id = array(-1, $q);
} }
return $id; return $id;
@@ -179,13 +174,11 @@
private function _db_connect($db_host, $db_user, $db_pass, $db_name, $db_port = 5432, $db_ssl = 'allow') private function _db_connect($db_host, $db_user, $db_pass, $db_name, $db_port = 5432, $db_ssl = 'allow')
{ {
// to avoid empty db_port // to avoid empty db_port
if (!$db_port) if (!$db_port) {
{
$db_port = 5432; $db_port = 5432;
} }
$this->dbh = @pg_connect("host=".$db_host." port=".$db_port." user=".$db_user." password=".$db_pass." dbname=".$db_name." sslmode=".$db_ssl); $this->dbh = @pg_connect("host=".$db_host." port=".$db_port." user=".$db_user." password=".$db_pass." dbname=".$db_name." sslmode=".$db_ssl);
if (!$this->dbh) if (!$this->dbh) {
{
die("<!-- Can't connect [host=".$db_host." port=".$db_port." user=".$db_user." password=XXXX dbname=".$db_name." sslmode=".$db_ssl."] //-->"); die("<!-- Can't connect [host=".$db_host." port=".$db_port." user=".$db_user." password=XXXX dbname=".$db_name." sslmode=".$db_ssl."] //-->");
} }
return $this->dbh; return $this->dbh;
@@ -198,15 +191,15 @@
private function _db_print_error($dbh, $cursor = '') private function _db_print_error($dbh, $cursor = '')
{ {
// run the query again for the error result here // run the query again for the error result here
if (!$cursor && $this->last_error_query) if (!$cursor && $this->last_error_query) {
{
pg_send_query($dbh, $this->last_error_query); pg_send_query($dbh, $this->last_error_query);
$this->last_error_query = ""; $this->last_error_query = "";
$cursor = pg_get_result($dbh); $cursor = pg_get_result($dbh);
} }
if (pg_result_error($cursor)) if (pg_result_error($cursor)) {
return "<span style=\"color: red;\"><b>-PostgreSQL-Error-></b> ".pg_result_error($cursor)."</span><br>"; return "<span style=\"color: red;\"><b>-PostgreSQL-Error-></b> ".pg_result_error($cursor)."</span><br>";
} }
}
// METHOD: _db_meta_data // METHOD: _db_meta_data
// PARAMS: database handler, table name // PARAMS: database handler, table name
@@ -243,27 +236,24 @@
// DESC : postgresql array to php array // DESC : postgresql array to php array
private function _db_array_parse($text, &$output, $limit = false, $offset = 1) private function _db_array_parse($text, &$output, $limit = false, $offset = 1)
{ {
if (false === $limit) if (false === $limit) {
{
$limit = strlen($text) - 1; $limit = strlen($text) - 1;
$output = array(); $output = array();
} }
if ('{}' != $text) if ('{}' != $text) {
do do {
{ if ('{' != $text{$offset}) {
if ('{' != $text{$offset})
{
preg_match("/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/", $text, $match, 0, $offset); preg_match("/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/", $text, $match, 0, $offset);
$offset += strlen($match[0]); $offset += strlen($match[0]);
$output[] = ('"' != $match[1]{0} ? $match[1] : stripcslashes(substr($match[1], 1, -1))); $output[] = ('"' != $match[1]{0} ? $match[1] : stripcslashes(substr($match[1], 1, -1)));
if ('},' == $match[3]) if ('},' == $match[3]) {
return $offset; return $offset;
} }
else } else {
$offset = pg_array_parse($text, $output[], $limit, $offset + 1); $offset = pg_array_parse($text, $output[], $limit, $offset + 1);
} }
while ($limit > $offset); } while ($limit > $offset);
}
return $output; return $output;
} }
} }
?>

View File

@@ -1,4 +1,5 @@
<? <?php
/********************************************************************* /*********************************************************************
* AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org) * AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org)
* CREATED: 2003/04/09 * CREATED: 2003/04/09
@@ -41,7 +42,6 @@
{ {
private $last_error_query; private $last_error_query;
private $dbh; private $dbh;
// public $currval_query;
// METHOD: __construct // METHOD: __construct
// PARAMS: none // PARAMS: none
@@ -53,11 +53,12 @@
public function _db_last_error_query() public function _db_last_error_query()
{ {
if ($this->last_error_query) if ($this->last_error_query) {
return true; return true;
else } else {
return false; return false;
} }
}
// METHOD: _db_query // METHOD: _db_query
// PARAMS: query // PARAMS: query
@@ -67,9 +68,10 @@
{ {
$this->last_error_query = ''; $this->last_error_query = '';
// read out the query status and save the query if needed // read out the query status and save the query if needed
$result = @pg_query($this->dbh, $query); $result = pg_query($this->dbh, $query);
if (!$result) if (!$result) {
$this->last_error_query = $query; $this->last_error_query = $query;
}
return $result; return $result;
} }
@@ -79,7 +81,7 @@
// DESC : sends an async query to the server // DESC : sends an async query to the server
public function _db_send_query($query) public function _db_send_query($query)
{ {
return @pg_send_query($this->dbh, $query); return pg_send_query($this->dbh, $query);
} }
// METHOD: _db_get_result // METHOD: _db_get_result
@@ -90,8 +92,9 @@
{ {
$this->last_error_query = ''; $this->last_error_query = '';
$result = pg_get_result($this->dbh); $result = pg_get_result($this->dbh);
if ($error = pg_result_error($result)) if ($error = pg_result_error($result)) {
$this->last_error_query = $error; $this->last_error_query = $error;
}
return $result; return $result;
} }
@@ -101,9 +104,11 @@
// DESC : wrapper for pg_close // DESC : wrapper for pg_close
public function _db_close() public function _db_close()
{ {
if (is_resource($this->dbh)) if (is_resource($this->dbh)) {
if (@pg_connection_status($this->dbh) === PGSQL_CONNECTION_OK) if (pg_connection_status($this->dbh) === PGSQL_CONNECTION_OK) {
@pg_close($this->dbh); pg_close($this->dbh);
}
}
} }
// METHOD: _db_prepare // METHOD: _db_prepare
@@ -112,9 +117,10 @@
// DESC : wrapper for pg_prepare // DESC : wrapper for pg_prepare
public function _db_prepare($name, $query) public function _db_prepare($name, $query)
{ {
$result = @pg_prepare($this->dbh, $name, $query); $result = pg_prepare($this->dbh, $name, $query);
if (!$result) if (!$result) {
$this->last_error_query = $query; $this->last_error_query = $query;
}
return $result; return $result;
} }
@@ -124,9 +130,10 @@
// DESC : wrapper for pg_execute for running a prepared statement // DESC : wrapper for pg_execute for running a prepared statement
public function _db_execute($name, $data) public function _db_execute($name, $data)
{ {
$result = @pg_execute($this->dbh, $name, $data); $result = pg_execute($this->dbh, $name, $data);
if (!$result) if (!$result) {
$this->last_error_query = $query; $this->last_error_query = $query;
}
return $result; return $result;
} }
@@ -164,11 +171,12 @@
public function _db_fetch_array($cursor, $result_type = '') public function _db_fetch_array($cursor, $result_type = '')
{ {
// result type is passed on as is [should be checked] // result type is passed on as is [should be checked]
if ($result_type) if ($result_type) {
return pg_fetch_array($cursor, NULL, $result_type); return pg_fetch_array($cursor, null, $result_type);
else } else {
return pg_fetch_array($cursor); return pg_fetch_array($cursor);
} }
}
// METHOD: _db_fetch_all // METHOD: _db_fetch_all
// PARAMS: cursor // PARAMS: cursor
@@ -198,20 +206,19 @@
public function _db_insert_id($query, $pk_name) public function _db_insert_id($query, $pk_name)
{ {
// only if an insert has been done // only if an insert has been done
if (preg_match("/^insert /i", $query)) if (preg_match("/^insert /i", $query)) {
{
$schema = ''; $schema = '';
// get table name from insert // get table name from insert
$array = explode(' ', $query); $array = explode(' ', $query);
$_table = $array[2]; $_table = $array[2];
// if there is a dot inside, we need to split // if there is a dot inside, we need to split
if (strstr($_table, '.')) if (strstr($_table, '.')) {
list($schema, $table) = explode('.', $_table); list($schema, $table) = explode('.', $_table);
else } else {
$table = $_table; $table = $_table;
}
// no PK name given at all // no PK name given at all
if (!$pk_name) if (!$pk_name) {
{
// if name is plurar, make it singular // if name is plurar, make it singular
// if (preg_match("/.*s$/i", $table)) // if (preg_match("/.*s$/i", $table))
// $table = substr($table, 0, -1); // $table = substr($table, 0, -1);
@@ -220,14 +227,10 @@
} }
$seq = (($schema) ? $schema.'.' : '').$table."_".$pk_name."_seq"; $seq = (($schema) ? $schema.'.' : '').$table."_".$pk_name."_seq";
$q = "SELECT CURRVAL('$seq') AS insert_id"; $q = "SELECT CURRVAL('$seq') AS insert_id";
// $this->currval_query = $q;
// I have to do manually or I overwrite the original insert internal vars ... // I have to do manually or I overwrite the original insert internal vars ...
if ($q = $this->_db_query($q)) if ($q = $this->_db_query($q)) {
{
list($id) = $this->_db_fetch_array($q); list($id) = $this->_db_fetch_array($q);
} } else {
else
{
$id = array(-1, $q); $id = array(-1, $q);
} }
return $id; return $id;
@@ -240,17 +243,14 @@
// DESC : queries database for the primary key name to this table in the selected schema // DESC : queries database for the primary key name to this table in the selected schema
public function _db_primary_key($table, $schema = '') public function _db_primary_key($table, $schema = '')
{ {
if ($table) if ($table) {
{
// check if schema set is different from schema given, only needed if schema is not empty // check if schema set is different from schema given, only needed if schema is not empty
$table_prefix = ''; $table_prefix = '';
if ($schema) if ($schema) {
{
$q = "SHOW search_path"; $q = "SHOW search_path";
$cursor = $this->_db_query($q); $cursor = $this->_db_query($q);
$search_path = $this->_db_fetch_array($cursor)['search_path']; $search_path = $this->_db_fetch_array($cursor)['search_path'];
if ($search_path != $schema) if ($search_path != $schema) {
{
$table_prefix = $schema.'.'; $table_prefix = $schema.'.';
} }
} }
@@ -258,14 +258,14 @@
// faster primary key get // faster primary key get
$q = "SELECT pg_attribute.attname AS column_name, format_type(pg_attribute.atttypid, pg_attribute.atttypmod) AS type "; $q = "SELECT pg_attribute.attname AS column_name, format_type(pg_attribute.atttypid, pg_attribute.atttypmod) AS type ";
$q .= "FROM pg_index, pg_class, pg_attribute "; $q .= "FROM pg_index, pg_class, pg_attribute ";
if ($schema) if ($schema) {
$q .= ", pg_namespace "; $q .= ", pg_namespace ";
}
$q .= "WHERE "; $q .= "WHERE ";
// regclass translates the OID to the name // regclass translates the OID to the name
$q .= "pg_class.oid = '".$table_prefix.$table."'::regclass AND "; $q .= "pg_class.oid = '".$table_prefix.$table."'::regclass AND ";
$q .= "indrelid = pg_class.oid AND "; $q .= "indrelid = pg_class.oid AND ";
if ($schema) if ($schema) {
{
$q .= "nspname = '".$schema."' AND "; $q .= "nspname = '".$schema."' AND ";
$q .= "pg_class.relnamespace = pg_namespace.oid AND "; $q .= "pg_class.relnamespace = pg_namespace.oid AND ";
} }
@@ -273,13 +273,12 @@
$q .= "pg_attribute.attnum = any(pg_index.indkey) "; $q .= "pg_attribute.attnum = any(pg_index.indkey) ";
$q .= "AND indisprimary"; $q .= "AND indisprimary";
$cursor = $this->_db_query($q); $cursor = $this->_db_query($q);
if ($cursor) if ($cursor) {
return $this->_db_fetch_array($cursor)['column_name']; return $this->_db_fetch_array($cursor)['column_name'];
else } else {
return false; return false;
} }
else } else {
{
return false; return false;
} }
} }
@@ -291,13 +290,11 @@
public function _db_connect($db_host, $db_user, $db_pass, $db_name, $db_port = 5432, $db_ssl = 'allow') public function _db_connect($db_host, $db_user, $db_pass, $db_name, $db_port = 5432, $db_ssl = 'allow')
{ {
// to avoid empty db_port // to avoid empty db_port
if (!$db_port) if (!$db_port) {
{
$db_port = 5432; $db_port = 5432;
} }
$this->dbh = @pg_connect("host=".$db_host." port=".$db_port." user=".$db_user." password=".$db_pass." dbname=".$db_name." sslmode=".$db_ssl); $this->dbh = pg_connect("host=".$db_host." port=".$db_port." user=".$db_user." password=".$db_pass." dbname=".$db_name." sslmode=".$db_ssl);
if (!$this->dbh) if (!$this->dbh) {
{
die("<!-- Can't connect [host=".$db_host." port=".$db_port." user=".$db_user." password=XXXX dbname=".$db_name." sslmode=".$db_ssl."] //-->"); die("<!-- Can't connect [host=".$db_host." port=".$db_port." user=".$db_user." password=XXXX dbname=".$db_name." sslmode=".$db_ssl."] //-->");
} }
return $this->dbh; return $this->dbh;
@@ -310,15 +307,15 @@
public function _db_print_error($cursor = '') public function _db_print_error($cursor = '')
{ {
// run the query again for the error result here // run the query again for the error result here
if (!$cursor && $this->last_error_query) if (!$cursor && $this->last_error_query) {
{
pg_send_query($this->dbh, $this->last_error_query); pg_send_query($this->dbh, $this->last_error_query);
$this->last_error_query = ''; $this->last_error_query = '';
$cursor = pg_get_result($this->dbh); $cursor = pg_get_result($this->dbh);
} }
if (pg_result_error($cursor)) if (pg_result_error($cursor)) {
return "<span style=\"color: red;\"><b>-PostgreSQL-Error-></b> ".pg_result_error($cursor)."</span><br>"; return "<span style=\"color: red;\"><b>-PostgreSQL-Error-></b> ".pg_result_error($cursor)."</span><br>";
} }
}
// METHOD: _db_meta_data // METHOD: _db_meta_data
// PARAMS: table name // PARAMS: table name
@@ -326,7 +323,7 @@
// DESC : wrapper for pg_emta_data // DESC : wrapper for pg_emta_data
public function _db_meta_data($table) public function _db_meta_data($table)
{ {
return @pg_meta_data($this->dbh, $table); return pg_meta_data($this->dbh, $table);
} }
// METHOD: _db_escape_string // METHOD: _db_escape_string
@@ -376,27 +373,26 @@
// DESC : postgresql array to php array // DESC : postgresql array to php array
public function _db_array_parse($text, &$output, $limit = false, $offset = 1) public function _db_array_parse($text, &$output, $limit = false, $offset = 1)
{ {
if (false === $limit) if (false === $limit) {
{
$limit = strlen($text) - 1; $limit = strlen($text) - 1;
$output = array(); $output = array();
} }
if ('{}' != $text) if ('{}' != $text) {
do do {
{ if ('{' != $text{$offset}) {
if ('{' != $text{$offset})
{
preg_match("/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/", $text, $match, 0, $offset); preg_match("/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/", $text, $match, 0, $offset);
$offset += strlen($match[0]); $offset += strlen($match[0]);
$output[] = ('"' != $match[1]{0} ? $match[1] : stripcslashes(substr($match[1], 1, -1))); $output[] = ('"' != $match[1]{0} ? $match[1] : stripcslashes(substr($match[1], 1, -1)));
if ('},' == $match[3]) if ('},' == $match[3]) {
return $offset; return $offset;
} }
else } else {
$offset = pg_array_parse($text, $output[], $limit, $offset + 1); $offset = pg_array_parse($text, $output[], $limit, $offset + 1);
} }
while ($limit > $offset); } while ($limit > $offset);
}
return $output; return $output;
} }
} }
?>
# __END__

View File

@@ -28,11 +28,12 @@
public function _db_last_error_query() public function _db_last_error_query()
{ {
if ($this->last_error_query) if ($this->last_error_query) {
return true; return true;
else } else {
return false; return false;
} }
}
// METHOD: _db_query // METHOD: _db_query
// PARAMS: query // PARAMS: query
@@ -47,8 +48,9 @@
$this->last_error_query = $query; */ $this->last_error_query = $query; */
$cursor = $this->_db_prepare(md5($query), $query); $cursor = $this->_db_prepare(md5($query), $query);
$result = $this->_db_execute(md5($query), array ()); $result = $this->_db_execute(md5($query), array ());
if (!$result) if (!$result) {
$this->last_error_query = $query; $this->last_error_query = $query;
}
return $cursor; return $cursor;
} }
@@ -78,8 +80,9 @@
{ {
$this->last_error_query = ''; $this->last_error_query = '';
/* $result = pg_get_result($this->dbh); /* $result = pg_get_result($this->dbh);
if ($error = pg_result_error($result)) if ($error = pg_result_error($result)) {
$this->last_error_query = $error; */ $this->last_error_query = $error;
}*/
return $result; return $result;
} }
@@ -89,10 +92,8 @@
// DESC : wrapper for pg_close // DESC : wrapper for pg_close
public function _db_close() public function _db_close()
{ {
if (is_array($this->cursor)) if (is_array($this->cursor)) {
{ foreach ($this->cursor as $key => $data) {
foreach ($this->cursor as $key => $data)
{
$this->cursor[$key]->closeCursor; $this->cursor[$key]->closeCursor;
$this->cursor[$key] = null; $this->cursor[$key] = null;
} }
@@ -180,20 +181,19 @@
public function _db_insert_id($query, $pk_name) public function _db_insert_id($query, $pk_name)
{ {
// only if an insert has been done // only if an insert has been done
if (preg_match("/^insert /i", $query)) if (preg_match("/^insert /i", $query)) {
{
$schema = ''; $schema = '';
// get table name from insert // get table name from insert
$array = explode(' ', $query); $array = explode(' ', $query);
$_table = $array[2]; $_table = $array[2];
// if there is a dot inside, we need to split // if there is a dot inside, we need to split
if (strstr($_table, '.')) if (strstr($_table, '.')) {
list($schema, $table) = explode('.', $_table); list($schema, $table) = explode('.', $_table);
else } else {
$table = $_table; $table = $_table;
}
// no PK name given at all // no PK name given at all
if (!$pk_name) if (!$pk_name) {
{
// if name is plural, make it singular // if name is plural, make it singular
// if (preg_match("/.*s$/i", $table)) // if (preg_match("/.*s$/i", $table))
// $table = substr($table, 0, -1); // $table = substr($table, 0, -1);
@@ -204,12 +204,9 @@
$q = "SELECT CURRVAL('$seq') AS insert_id"; $q = "SELECT CURRVAL('$seq') AS insert_id";
// I have to do manually or I overwrite the original insert internal vars ... // I have to do manually or I overwrite the original insert internal vars ...
$row = $this->_db_query_result($q); $row = $this->_db_query_result($q);
if ($row['insert_id']) if ($row['insert_id']) {
{
$id = $row['insert_id']; $id = $row['insert_id'];
} } else {
else
{
$id = array(-1, $q); $id = array(-1, $q);
} }
return $id; return $id;
@@ -222,18 +219,15 @@
// DESC : queries database for the primary key name to this table in the selected schema // DESC : queries database for the primary key name to this table in the selected schema
public function _db_primary_key($table, $schema = '') public function _db_primary_key($table, $schema = '')
{ {
if ($table) if ($table) {
{
// check if schema set is different from schema given, only needed if schema is not empty // check if schema set is different from schema given, only needed if schema is not empty
$table_prefix = ''; $table_prefix = '';
if ($schema) if ($schema) {
{
$q = "SHOW search_path"; $q = "SHOW search_path";
// $cursor = $this->_db_query($q); // $cursor = $this->_db_query($q);
// $search_path = $this->_db_fetch_array($cursor)['search_path']; // $search_path = $this->_db_fetch_array($cursor)['search_path'];
$search_path = $this->_db_query_result($q)['search_path']; $search_path = $this->_db_query_result($q)['search_path'];
if ($search_path != $schema) if ($search_path != $schema) {
{
$table_prefix = $schema.'.'; $table_prefix = $schema.'.';
} }
} }
@@ -241,14 +235,14 @@
// faster primary key get // faster primary key get
$q = "SELECT pg_attribute.attname AS column_name, format_type(pg_attribute.atttypid, pg_attribute.atttypmod) AS type "; $q = "SELECT pg_attribute.attname AS column_name, format_type(pg_attribute.atttypid, pg_attribute.atttypmod) AS type ";
$q .= "FROM pg_index, pg_class, pg_attribute "; $q .= "FROM pg_index, pg_class, pg_attribute ";
if ($schema) if ($schema) {
$q .= ", pg_namespace "; $q .= ", pg_namespace ";
}
$q .= "WHERE "; $q .= "WHERE ";
// regclass translates the OID to the name // regclass translates the OID to the name
$q .= "pg_class.oid = '".$table_prefix.$table."'::regclass AND "; $q .= "pg_class.oid = '".$table_prefix.$table."'::regclass AND ";
$q .= "indrelid = pg_class.oid AND "; $q .= "indrelid = pg_class.oid AND ";
if ($schema) if ($schema) {
{
$q .= "nspname = '".$schema."' AND "; $q .= "nspname = '".$schema."' AND ";
$q .= "pg_class.relnamespace = pg_namespace.oid AND "; $q .= "pg_class.relnamespace = pg_namespace.oid AND ";
} }
@@ -256,13 +250,12 @@
$q .= "pg_attribute.attnum = any(pg_index.indkey) "; $q .= "pg_attribute.attnum = any(pg_index.indkey) ";
$q .= "AND indisprimary"; $q .= "AND indisprimary";
$row = $this->_db_query_result($q); $row = $this->_db_query_result($q);
if ($row === FALSE) if ($row === false) {
return false; return false;
else } else {
return $row['column_name']; return $row['column_name'];
} }
else } else {
{
return false; return false;
} }
} }
@@ -274,16 +267,12 @@
public function _db_connect($db_host, $db_user, $db_pass, $db_name, $db_port = 5432, $db_ssl = 'allow') public function _db_connect($db_host, $db_user, $db_pass, $db_name, $db_port = 5432, $db_ssl = 'allow')
{ {
// to avoid empty db_port // to avoid empty db_port
if (!$db_port) if (!$db_port) {
{
$db_port = 5432; $db_port = 5432;
} }
try try {
{
$this->dbh = new PDO('pgsql:host='.$db_host.';dbname='.$db_name.';port='.$db_port.';sslmode='.$db_ssl, $db_user, $db_pass); $this->dbh = new PDO('pgsql:host='.$db_host.';dbname='.$db_name.';port='.$db_port.';sslmode='.$db_ssl, $db_user, $db_pass);
} } catch (PDOException $e) {
catch (PDOException $e)
{
print "Error!: ".$e->getMessage()."\n"; print "Error!: ".$e->getMessage()."\n";
die("<!-- Can't connect [host=".$db_host." port=".$db_port." user=".$db_user." password=XXXX dbname=".$db_name." sslmode=".$db_ssl."]: ".$e->getMEssage()."//-->"); die("<!-- Can't connect [host=".$db_host." port=".$db_port." user=".$db_user." password=XXXX dbname=".$db_name." sslmode=".$db_ssl."]: ".$e->getMEssage()."//-->");
} }
@@ -363,27 +352,24 @@
// DESC : postgresql array to php array // DESC : postgresql array to php array
public function _db_array_parse($text, &$output, $limit = false, $offset = 1) public function _db_array_parse($text, &$output, $limit = false, $offset = 1)
{ {
if (false === $limit) if (false === $limit) {
{
$limit = strlen($text) - 1; $limit = strlen($text) - 1;
$output = array(); $output = array();
} }
if ('{}' != $text) if ('{}' != $text) {
do do {
{ if ('{' != $text{$offset}) {
if ('{' != $text{$offset})
{
preg_match("/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/", $text, $match, 0, $offset); preg_match("/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/", $text, $match, 0, $offset);
$offset += strlen($match[0]); $offset += strlen($match[0]);
$output[] = ('"' != $match[1]{0} ? $match[1] : stripcslashes(substr($match[1], 1, -1))); $output[] = ('"' != $match[1]{0} ? $match[1] : stripcslashes(substr($match[1], 1, -1)));
if ('},' == $match[3]) if ('},' == $match[3]) {
return $offset; return $offset;
} }
else } else {
$offset = pg_array_parse($text, $output[], $limit, $offset + 1); $offset = pg_array_parse($text, $output[], $limit, $offset + 1);
} }
while ($limit > $offset); } while ($limit > $offset);
}
return $output; return $output;
} }
} }
?>

View File

@@ -18,7 +18,6 @@
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with PHP-gettext; if not, write to the Free Software along with PHP-gettext; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/ */
/** /**
@@ -33,22 +32,23 @@
* second parameter in the constructor (e.g. whenusing very large MO files * second parameter in the constructor (e.g. whenusing very large MO files
* that you don't want to keep in memory) * that you don't want to keep in memory)
*/ */
class gettext_reader { class gettext_reader
{
// public: // public:
var $error = 0; // public variable that holds error code (0 if no error) public $error = 0; // public variable that holds error code (0 if no error)
//private: //private:
var $BYTEORDER = 0; // 0: low endian, 1: big endian private $BYTEORDER = 0; // 0: low endian, 1: big endian
var $STREAM = NULL; private $STREAM = null;
var $short_circuit = false; private $short_circuit = false;
var $enable_cache = false; private $enable_cache = false;
var $originals = NULL; // offset of original table private $originals = null; // offset of original table
var $translations = NULL; // offset of translation table private $translations = null; // offset of translation table
var $pluralheader = NULL; // cache header field for plural forms private $pluralheader = null; // cache header field for plural forms
var $total = 0; // total string count private $total = 0; // total string count
var $table_originals = NULL; // table for original strings (offsets) private $table_originals = null; // table for original strings (offsets)
var $table_translations = NULL; // table for translated strings (offsets) private $table_translations = null; // table for translated strings (offsets)
var $cache_translations = NULL; // original -> translation mapping private $cache_translations = null; // original -> translation mapping
/* Methods */ /* Methods */
@@ -60,7 +60,8 @@ class gettext_reader {
* @access private * @access private
* @return Integer from the Stream * @return Integer from the Stream
*/ */
function readint() { private function readint()
{
if ($this->BYTEORDER == 0) { if ($this->BYTEORDER == 0) {
// low endian // low endian
$input = unpack('V', $this->STREAM->read(4)); $input = unpack('V', $this->STREAM->read(4));
@@ -72,7 +73,8 @@ class gettext_reader {
} }
} }
function read($bytes) { public function read($bytes)
{
return $this->STREAM->read($bytes); return $this->STREAM->read($bytes);
} }
@@ -82,7 +84,8 @@ class gettext_reader {
* @param int count How many elements should be read * @param int count How many elements should be read
* @return Array of Integers * @return Array of Integers
*/ */
function readintarray($count) { public function readintarray($count)
{
if ($this->BYTEORDER == 0) { if ($this->BYTEORDER == 0) {
// low endian // low endian
return unpack('V'.$count, $this->STREAM->read(4 * $count)); return unpack('V'.$count, $this->STREAM->read(4 * $count));
@@ -98,7 +101,8 @@ class gettext_reader {
* @param object Reader the StreamReader object * @param object Reader the StreamReader object
* @param boolean enable_cache Enable or disable caching of strings (default on) * @param boolean enable_cache Enable or disable caching of strings (default on)
*/ */
function __construct($Reader, $enable_cache = true) { public function __construct($Reader, $enable_cache = true)
{
// If there isn't a StreamReader, turn on short circuit mode. // If there isn't a StreamReader, turn on short circuit mode.
if (!$Reader || isset($Reader->error)) { if (!$Reader || isset($Reader->error)) {
$this->short_circuit = true; $this->short_circuit = true;
@@ -137,11 +141,13 @@ class gettext_reader {
* *
* @access private * @access private
*/ */
function load_tables() { private function load_tables()
{
if (is_array($this->cache_translations) && if (is_array($this->cache_translations) &&
is_array($this->table_originals) && is_array($this->table_originals) &&
is_array($this->table_translations)) is_array($this->table_translations)) {
return; return;
}
/* get original and translations tables */ /* get original and translations tables */
if (!is_array($this->table_originals)) { if (!is_array($this->table_originals)) {
@@ -173,11 +179,13 @@ class gettext_reader {
* @param int num Offset number of original string * @param int num Offset number of original string
* @return string Requested string if found, otherwise '' * @return string Requested string if found, otherwise ''
*/ */
function get_original_string($num) { private function get_original_string($num)
{
$length = $this->table_originals[$num * 2 + 1]; $length = $this->table_originals[$num * 2 + 1];
$offset = $this->table_originals[$num * 2 + 2]; $offset = $this->table_originals[$num * 2 + 2];
if (! $length) if (!$length) {
return ''; return '';
}
$this->STREAM->seekto($offset); $this->STREAM->seekto($offset);
$data = $this->STREAM->read($length); $data = $this->STREAM->read($length);
return (string)$data; return (string)$data;
@@ -190,11 +198,13 @@ class gettext_reader {
* @param int num Offset number of original string * @param int num Offset number of original string
* @return string Requested string if found, otherwise '' * @return string Requested string if found, otherwise ''
*/ */
function get_translation_string($num) { private function get_translation_string($num)
{
$length = $this->table_translations[$num * 2 + 1]; $length = $this->table_translations[$num * 2 + 1];
$offset = $this->table_translations[$num * 2 + 2]; $offset = $this->table_translations[$num * 2 + 2];
if (! $length) if (!$length) {
return ''; return '';
}
$this->STREAM->seekto($offset); $this->STREAM->seekto($offset);
$data = $this->STREAM->read($length); $data = $this->STREAM->read($length);
return (string)$data; return (string)$data;
@@ -209,7 +219,8 @@ class gettext_reader {
* @param int end (internally used in recursive function) * @param int end (internally used in recursive function)
* @return int string number (offset in originals table) * @return int string number (offset in originals table)
*/ */
function find_string($string, $start = -1, $end = -1) { private function find_string($string, $start = -1, $end = -1)
{
if (($start == -1) or ($end == -1)) { if (($start == -1) or ($end == -1)) {
// find_string is called with only one parameter, set start end end // find_string is called with only one parameter, set start end end
$start = 0; $start = 0;
@@ -218,10 +229,11 @@ class gettext_reader {
if (abs($start - $end) <= 1) { if (abs($start - $end) <= 1) {
// We're done, now we either found the string, or it doesn't exist // We're done, now we either found the string, or it doesn't exist
$txt = $this->get_original_string($start); $txt = $this->get_original_string($start);
if ($string == $txt) if ($string == $txt) {
return $start; return $start;
else } else {
return -1; return -1;
}
} elseif ($start > $end) { } elseif ($start > $end) {
// start > end -> turn around and start over // start > end -> turn around and start over
return $this->find_string($string, $end, $start); return $this->find_string($string, $end, $start);
@@ -229,17 +241,18 @@ class gettext_reader {
// Divide table in two parts // Divide table in two parts
$half = (int)(($start + $end) / 2); $half = (int)(($start + $end) / 2);
$cmp = strcmp($string, $this->get_original_string($half)); $cmp = strcmp($string, $this->get_original_string($half));
if ($cmp == 0) if ($cmp == 0) {
// string is exactly in the middle => return it // string is exactly in the middle => return it
return $half; return $half;
else if ($cmp < 0) } elseif ($cmp < 0) {
// The string is in the upper half // The string is in the upper half
return $this->find_string($string, $start, $half); return $this->find_string($string, $start, $half);
else } else {
// The string is in the lower half // Translateshe string is in the lower half
return $this->find_string($string, $half, $end); return $this->find_string($string, $half, $end);
} }
} }
}
/** /**
* Translates a string * Translates a string
@@ -248,26 +261,30 @@ class gettext_reader {
* @param string string to be translated * @param string string to be translated
* @return string translated string (or original, if not found) * @return string translated string (or original, if not found)
*/ */
function translate($string) { public function translate($string)
if ($this->short_circuit) {
if ($this->short_circuit) {
return $string; return $string;
}
$this->load_tables(); $this->load_tables();
if ($this->enable_cache) { if ($this->enable_cache) {
// Caching enabled, get translated string from cache // Caching enabled, get translated string from cache
if (array_key_exists($string, $this->cache_translations)) if (array_key_exists($string, $this->cache_translations)) {
return $this->cache_translations[$string]; return $this->cache_translations[$string];
else } else {
return $string; return $string;
}
} else { } else {
// Caching not enabled, try to find string // Caching not enabled, try to find string
$num = $this->find_string($string); $num = $this->find_string($string);
if ($num == -1) if ($num == -1) {
return $string; return $string;
else } else {
return $this->get_translation_string($num); return $this->get_translation_string($num);
} }
} }
}
/** /**
* Sanitize plural form expression for use in PHP eval call. * Sanitize plural form expression for use in PHP eval call.
@@ -275,7 +292,8 @@ class gettext_reader {
* @access private * @access private
* @return string sanitized plural form expression * @return string sanitized plural form expression
*/ */
function sanitize_plural_expression($expr) { private function sanitize_plural_expression($expr)
{
// Get rid of disallowed characters. // Get rid of disallowed characters.
$expr = preg_replace('@[^a-zA-Z0-9_:;\(\)\?\|\&=!<>+*/\%-]@', '', $expr); $expr = preg_replace('@[^a-zA-Z0-9_:;\(\)\?\|\&=!<>+*/\%-]@', '', $expr);
@@ -310,11 +328,13 @@ class gettext_reader {
* @access private * @access private
* @return string verbatim plural form header field * @return string verbatim plural form header field
*/ */
function extract_plural_forms_header_from_po_header($header) { private function extract_plural_forms_header_from_po_header($header)
if (preg_match("/(^|\n)plural-forms: ([^\n]*)\n/i", $header, $regs)) {
if (preg_match("/(^|\n)plural-forms: ([^\n]*)\n/i", $header, $regs)) {
$expr = $regs[2]; $expr = $regs[2];
else } else {
$expr = "nplurals=2; plural=n == 1 ? 0 : 1;"; $expr = "nplurals=2; plural=n == 1 ? 0 : 1;";
}
return $expr; return $expr;
} }
@@ -324,7 +344,8 @@ class gettext_reader {
* @access private * @access private
* @return string plural form header * @return string plural form header
*/ */
function get_plural_forms() { private function get_plural_forms()
{
// lets assume message number 0 is header // lets assume message number 0 is header
// this is true, right? // this is true, right?
$this->load_tables(); $this->load_tables();
@@ -349,7 +370,8 @@ class gettext_reader {
* @param n count * @param n count
* @return int array index of the right plural form * @return int array index of the right plural form
*/ */
function select_string($n) { private function select_string($n)
{
$string = $this->get_plural_forms(); $string = $this->get_plural_forms();
$string = str_replace('nplurals', "\$total", $string); $string = str_replace('nplurals', "\$total", $string);
$string = str_replace("n", $n, $string); $string = str_replace("n", $n, $string);
@@ -359,7 +381,9 @@ class gettext_reader {
$plural = 0; $plural = 0;
eval("$string"); eval("$string");
if ($plural >= $total) $plural = $total - 1; if ($plural >= $total) {
$plural = $total - 1;
}
return $plural; return $plural;
} }
@@ -372,13 +396,15 @@ class gettext_reader {
* @param string number * @param string number
* @return translated plural form * @return translated plural form
*/ */
function ngettext($single, $plural, $number) { public function ngettext($single, $plural, $number)
{
if ($this->short_circuit) { if ($this->short_circuit) {
if ($number != 1) if ($number != 1) {
return $plural; return $plural;
else } else {
return $single; return $single;
} }
}
// find out the appropriate form // find out the appropriate form
$select = $this->select_string($number); $select = $this->select_string($number);
@@ -386,7 +412,6 @@ class gettext_reader {
// this should contains all strings separated by NULLs // this should contains all strings separated by NULLs
$key = $single . chr(0) . $plural; $key = $single . chr(0) . $plural;
if ($this->enable_cache) { if ($this->enable_cache) {
if (! array_key_exists($key, $this->cache_translations)) { if (! array_key_exists($key, $this->cache_translations)) {
return ($number != 1) ? $plural : $single; return ($number != 1) ? $plural : $single;
@@ -407,26 +432,25 @@ class gettext_reader {
} }
} }
function pgettext($context, $msgid) { public function pgettext($context, $msgid)
{
$key = $context.chr(4).$msgid; $key = $context.chr(4).$msgid;
$ret = $this->translate($key); $ret = $this->translate($key);
if (strpos($ret, "\004") !== FALSE) { if (strpos($ret, "\004") !== false) {
return $msgid; return $msgid;
} else { } else {
return $ret; return $ret;
} }
} }
function npgettext($context, $singular, $plural, $number) { public function npgettext($context, $singular, $plural, $number)
{
$key = $context.chr(4).$singular; $key = $context.chr(4).$singular;
$ret = $this->ngettext($key, $plural, $number); $ret = $this->ngettext($key, $plural, $number);
if (strpos($ret, "\004") !== FALSE) { if (strpos($ret, "\004") !== false) {
return $singular; return $singular;
} else { } else {
return $ret; return $ret;
} }
} }
} }
?>

View File

@@ -17,78 +17,90 @@
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with PHP-gettext; if not, write to the Free Software along with PHP-gettext; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/ */
// Simple class to wrap file streams, string streams, etc. // Simple class to wrap file streams, string streams, etc.
// seek is essential, and it should be byte stream // seek is essential, and it should be byte stream
class StreamReader { class StreamReader
{
// should return a string [FIXME: perhaps return array of bytes?] // should return a string [FIXME: perhaps return array of bytes?]
function read($bytes) { public function read($bytes)
{
return false; return false;
} }
// should return new position // should return new position
function seekto($position) { public function seekto($position)
{
return false; return false;
} }
// returns current position // returns current position
function currentpos() { public function currentpos()
{
return false; return false;
} }
// returns length of entire stream (limit for seekto()s) // returns length of entire stream (limit for seekto()s)
function length() { public function length()
{
return false; return false;
} }
}; }
class StringReader { class StringReader
var $_pos; {
var $_str; public $_pos;
public $_str;
function __construct($str='') { public function __construct($str = '')
{
$this->_str = $str; $this->_str = $str;
$this->_pos = 0; $this->_pos = 0;
} }
function read($bytes) { public function read($bytes)
{
$data = substr($this->_str, $this->_pos, $bytes); $data = substr($this->_str, $this->_pos, $bytes);
$this->_pos += $bytes; $this->_pos += $bytes;
if (strlen($this->_str)<$this->_pos) if (strlen($this->_str) < $this->_pos) {
$this->_pos = strlen($this->_str); $this->_pos = strlen($this->_str);
}
return $data; return $data;
} }
function seekto($pos) { public function seekto($pos)
{
$this->_pos = $pos; $this->_pos = $pos;
if (strlen($this->_str)<$this->_pos) if (strlen($this->_str) < $this->_pos) {
$this->_pos = strlen($this->_str); $this->_pos = strlen($this->_str);
}
return $this->_pos; return $this->_pos;
} }
function currentpos() { public function currentpos()
{
return $this->_pos; return $this->_pos;
} }
function length() { public function length()
{
return strlen($this->_str); return strlen($this->_str);
} }
}
};
class FileReader { class FileReader
var $_pos; {
var $_fd; public $_pos;
var $_length; public $_fd;
public $_length;
function __construct($filename) { public function __construct($filename)
{
if (file_exists($filename)) { if (file_exists($filename)) {
$this->_length = filesize($filename); $this->_length = filesize($filename);
$this->_pos = 0; $this->_pos = 0;
$this->_fd = fopen($filename, 'rb'); $this->_fd = fopen($filename, 'rb');
@@ -102,7 +114,8 @@ class FileReader {
} }
} }
function read($bytes) { public function read($bytes)
{
if ($bytes) { if ($bytes) {
fseek($this->_fd, $this->_pos); fseek($this->_fd, $this->_pos);
@@ -117,35 +130,41 @@ class FileReader {
$this->_pos = ftell($this->_fd); $this->_pos = ftell($this->_fd);
return $data; return $data;
} else return ''; } else {
return '';
}
} }
function seekto($pos) { public function seekto($pos)
{
fseek($this->_fd, $pos); fseek($this->_fd, $pos);
$this->_pos = ftell($this->_fd); $this->_pos = ftell($this->_fd);
return $this->_pos; return $this->_pos;
} }
function currentpos() { public function currentpos()
{
return $this->_pos; return $this->_pos;
} }
function length() { public function length()
{
return $this->_length; return $this->_length;
} }
function close() { public function close()
{
fclose($this->_fd); fclose($this->_fd);
} }
}
};
// Preloads entire file in memory first, then creates a StringReader // Preloads entire file in memory first, then creates a StringReader
// over it (it assumes knowledge of StringReader internals) // over it (it assumes knowledge of StringReader internals)
class CachedFileReader extends StringReader { class CachedFileReader extends StringReader
function __construct($filename) { {
public function __construct($filename)
{
if (file_exists($filename)) { if (file_exists($filename)) {
$length = filesize($filename); $length = filesize($filename);
$fd = fopen($filename, 'rb'); $fd = fopen($filename, 'rb');
@@ -155,13 +174,9 @@ class CachedFileReader extends StringReader {
} }
$this->_str = fread($fd, $length); $this->_str = fread($fd, $length);
fclose($fd); fclose($fd);
} else { } else {
$this->error = 2; // File doesn't exist $this->error = 2; // File doesn't exist
return false; return false;
} }
} }
}; }
?>

2
www/media/binaires/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
*
!.gitignore

2
www/media/images/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
*
!.gitignore

2
www/media/pdf/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
*
!.gitignore

Some files were not shown because too many files have changed in this diff Show More