Evoadmin-web is now a "public project".
This commit is contained in:
commit
48eb1c16b1
|
@ -0,0 +1,3 @@
|
|||
* Ajouter l'utilisateur qui fait tourner l'application dans le groupe shadow
|
||||
* Ajouter les autorisations sudo nécessaires
|
||||
* Désactiver les magic quotes de PHP
|
|
@ -0,0 +1,339 @@
|
|||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 2, June 1991
|
||||
|
||||
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
License is intended to guarantee your freedom to share and change free
|
||||
software--to make sure the software is free for all its users. This
|
||||
General Public License applies to most of the Free Software
|
||||
Foundation's software and to any other program whose authors commit to
|
||||
using it. (Some other Free Software Foundation software is covered by
|
||||
the GNU Lesser General Public License instead.) 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
|
||||
this service 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 make restrictions that forbid
|
||||
anyone to deny you these rights or to ask you to surrender the rights.
|
||||
These restrictions translate to certain responsibilities for you if you
|
||||
distribute copies of the software, or if you modify it.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must give the recipients all the rights that
|
||||
you have. 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.
|
||||
|
||||
We protect your rights with two steps: (1) copyright the software, and
|
||||
(2) offer you this license which gives you legal permission to copy,
|
||||
distribute and/or modify the software.
|
||||
|
||||
Also, for each author's protection and ours, we want to make certain
|
||||
that everyone understands that there is no warranty for this free
|
||||
software. If the software is modified by someone else and passed on, we
|
||||
want its recipients to know that what they have is not the original, so
|
||||
that any problems introduced by others will not reflect on the original
|
||||
authors' reputations.
|
||||
|
||||
Finally, any free program is threatened constantly by software
|
||||
patents. We wish to avoid the danger that redistributors of a free
|
||||
program will individually obtain patent licenses, in effect making the
|
||||
program proprietary. To prevent this, we have made it clear that any
|
||||
patent must be licensed for everyone's free use or not licensed at all.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License applies to any program or other work which contains
|
||||
a notice placed by the copyright holder saying it may be distributed
|
||||
under the terms of this General Public License. The "Program", below,
|
||||
refers to any such program or work, and a "work based on the Program"
|
||||
means either the Program or any derivative work under copyright law:
|
||||
that is to say, a work containing the Program or a portion of it,
|
||||
either verbatim or with modifications and/or translated into another
|
||||
language. (Hereinafter, translation is included without limitation in
|
||||
the term "modification".) Each licensee is addressed as "you".
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running the Program is not restricted, and the output from the Program
|
||||
is covered only if its contents constitute a work based on the
|
||||
Program (independent of having been made by running the Program).
|
||||
Whether that is true depends on what the Program does.
|
||||
|
||||
1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the
|
||||
notices that refer to this License and to the absence of any warranty;
|
||||
and give any other recipients of the Program a copy of this License
|
||||
along with the Program.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy, and
|
||||
you may at your option offer warranty protection in exchange for a fee.
|
||||
|
||||
2. You may modify your copy or copies of the Program or any portion
|
||||
of it, thus forming a work based on the Program, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) You must cause the modified files to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
b) You must cause any work that you distribute or publish, that in
|
||||
whole or in part contains or is derived from the Program or any
|
||||
part thereof, to be licensed as a whole at no charge to all third
|
||||
parties under the terms of this License.
|
||||
|
||||
c) If the modified program normally reads commands interactively
|
||||
when run, you must cause it, when started running for such
|
||||
interactive use in the most ordinary way, to print or display an
|
||||
announcement including an appropriate copyright notice and a
|
||||
notice that there is no warranty (or else, saying that you provide
|
||||
a warranty) and that users may redistribute the program under
|
||||
these conditions, and telling the user how to view a copy of this
|
||||
License. (Exception: if the Program itself is interactive but
|
||||
does not normally print such an announcement, your work based on
|
||||
the Program is not required to print an announcement.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Program,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Program, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Program.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Program
|
||||
with the Program (or with a work based on the Program) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may copy and distribute the Program (or a work based on it,
|
||||
under Section 2) in object code or executable form under the terms of
|
||||
Sections 1 and 2 above provided that you also do one of the following:
|
||||
|
||||
a) Accompany it with the complete corresponding machine-readable
|
||||
source code, which must be distributed under the terms of Sections
|
||||
1 and 2 above on a medium customarily used for software interchange; or,
|
||||
|
||||
b) Accompany it with a written offer, valid for at least three
|
||||
years, to give any third party, for a charge no more than your
|
||||
cost of physically performing source distribution, a complete
|
||||
machine-readable copy of the corresponding source code, to be
|
||||
distributed under the terms of Sections 1 and 2 above on a medium
|
||||
customarily used for software interchange; or,
|
||||
|
||||
c) Accompany it with the information you received as to the offer
|
||||
to distribute corresponding source code. (This alternative is
|
||||
allowed only for noncommercial distribution and only if you
|
||||
received the program in object code or executable form with such
|
||||
an offer, in accord with Subsection b above.)
|
||||
|
||||
The source code for a work means the preferred form of the work for
|
||||
making modifications to it. For an executable work, complete source
|
||||
code means all the source code for all modules it contains, plus any
|
||||
associated interface definition files, plus the scripts used to
|
||||
control compilation and installation of the executable. However, as a
|
||||
special exception, the source code distributed need not include
|
||||
anything that is normally distributed (in either source or binary
|
||||
form) with the major components (compiler, kernel, and so on) of the
|
||||
operating system on which the executable runs, unless that component
|
||||
itself accompanies the executable.
|
||||
|
||||
If distribution of executable or object code is made by offering
|
||||
access to copy from a designated place, then offering equivalent
|
||||
access to copy the source code from the same place counts as
|
||||
distribution of the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
4. You may not copy, modify, sublicense, or distribute the Program
|
||||
except as expressly provided under this License. Any attempt
|
||||
otherwise to copy, modify, sublicense or distribute the Program is
|
||||
void, and will automatically terminate your rights under this License.
|
||||
However, parties who have received copies, or rights, from you under
|
||||
this License will not have their licenses terminated so long as such
|
||||
parties remain in full compliance.
|
||||
|
||||
5. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Program or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Program (or any work based on the
|
||||
Program), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Program or works based on it.
|
||||
|
||||
6. Each time you redistribute the Program (or any work based on the
|
||||
Program), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute or modify the Program subject to
|
||||
these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties to
|
||||
this License.
|
||||
|
||||
7. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Program at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Program by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Program.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under
|
||||
any particular circumstance, the balance of the section is intended to
|
||||
apply and the section as a whole is intended to apply in other
|
||||
circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system, which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
8. If the distribution and/or use of the Program is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Program under this License
|
||||
may add an explicit geographical distribution limitation excluding
|
||||
those countries, so that distribution is permitted only in or among
|
||||
countries not thus excluded. In such case, this License incorporates
|
||||
the limitation as if written in the body of this License.
|
||||
|
||||
9. The Free Software Foundation may publish revised and/or new versions
|
||||
of the 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 a version number of this License which applies to it and "any
|
||||
later version", you have the option of following the terms and conditions
|
||||
either of that version or of any later version published by the Free
|
||||
Software Foundation. If the Program does not specify a version number of
|
||||
this License, you may choose any version ever published by the Free Software
|
||||
Foundation.
|
||||
|
||||
10. If you wish to incorporate parts of the Program into other free
|
||||
programs whose distribution conditions are different, write to the author
|
||||
to ask for permission. For software which is copyrighted by the Free
|
||||
Software Foundation, write to the Free Software Foundation; we sometimes
|
||||
make exceptions for this. Our decision will be guided by the two goals
|
||||
of preserving the free status of all derivatives of our free software and
|
||||
of promoting the sharing and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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.
|
||||
|
||||
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
|
||||
REDISTRIBUTE THE 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.
|
||||
|
||||
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
|
||||
convey the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
|
||||
Copyright (C) 2013 Benoît.S
|
||||
|
||||
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 2 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, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program is interactive, make it output a short notice like this
|
||||
when it starts in an interactive mode:
|
||||
|
||||
Gnomovision version 69, Copyright (C) year name of author
|
||||
Gnomovision 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, the commands you use may
|
||||
be called something other than `show w' and `show c'; they could even be
|
||||
mouse-clicks or menu items--whatever suits your program.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your
|
||||
school, if any, to sign a "copyright disclaimer" for the program, if
|
||||
necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
|
||||
`Gnomovision' (which makes passes at compilers) written by James Hacker.
|
||||
|
||||
{signature of Ty Coon}, 1 April 1989
|
||||
Ty Coon, President of Vice
|
||||
|
||||
This 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.
|
|
@ -0,0 +1,72 @@
|
|||
INSTALLATION & CONFIGURATION EVOADMIN EN MODE CLUSTER
|
||||
=====================================================
|
||||
|
||||
|
||||
1. Infra type à mettre en place
|
||||
-------------------------------
|
||||
|
||||
.---.
|
||||
| | adm
|
||||
'-.-'
|
||||
.------------+------------.
|
||||
v v v
|
||||
.---. .---. .---.
|
||||
| | www00 | | www01 | | wwwnn
|
||||
'---' '---' '---'
|
||||
|
||||
* adm : machine hébergeant evoadmin-cluster. Doit pouvoir se connecter en
|
||||
root sur tous les frontaux ;
|
||||
|
||||
* wwwXX : frontaux configurés en tant que pack-web/pack-mail.
|
||||
|
||||
|
||||
2. Configuration sur la machine d'admin
|
||||
---------------------------------------
|
||||
|
||||
* Récupérer le code ;
|
||||
* Créer le virtual host pointant dans htdocs/ ;
|
||||
* Initialiser la base de données SQLite :
|
||||
* copier le contenu de scripts/ du dépôt dans /usr/share/scripts/evoadmin/.
|
||||
|
||||
3. Configuration des frontaux
|
||||
-----------------------------
|
||||
|
||||
* Configurer un pack-web et pack-mail+evoadmin-mail classique ;
|
||||
* ouvrir l'accès SSH entre tous les frontaux (nécessaire pour les
|
||||
réplications) ;
|
||||
* Ouvrir l'accès SSH en root depuis la machine d'admin vers chaque frontal ;
|
||||
* Copier les scripts scripts/sync-master-to-slave* du dépôt dans
|
||||
/opt/evocluster/, puis `chmod -R 755 /opt/evocluster/`.
|
||||
|
||||
Cas de la réplication MySQL :
|
||||
* Configurer la réplication MySQL de manière standard (comme décrit ici [1]) ;
|
||||
* Rajouter sur la machine slave dans le my.cnf la directive replicate-do-db,
|
||||
qui contiendra la liste des bases des comptes à répliquer.
|
||||
|
||||
[1] http://trac.evolix.net/infogerance/wiki/HowtoMySQL#R%C3%A9plicationMySQL
|
||||
|
||||
4. Configuration d'Evoadmin
|
||||
---------------------------
|
||||
|
||||
Afin d'activer Evoadmin en mode Cluster, remplir les variables suivantes dans
|
||||
/home/evoadmin/www/conf/config.local.php :
|
||||
|
||||
$localconf['cluster'] = TRUE;
|
||||
$localconf['cache'] = '/home/evoadmin/www/cache.sqlite'; // cache sqlite
|
||||
$localconf['servers'] = array('www00', 'www01', ..., 'wwwnn');
|
||||
|
||||
Créer le cache après avoir renseigner le fichier de conf :
|
||||
# cd /home/evoadmin/www/bin && php init_cache.php
|
||||
www00 added in cache
|
||||
[...]
|
||||
Cache initialisé
|
||||
# chown www-evoadmin:evoadmin /home/evoadmin/www/cache.sqlite
|
||||
# chmod ug+rx /home/evoadmin/www/cache.sqlite
|
||||
|
||||
S'assurer que /home/evoadmin/www appartient bien à www-evoadmin:evoadmin.
|
||||
|
||||
Il est possible de dumper le cache grâce à au script list_domain.php et de
|
||||
rajouter des serveurs dans le cache grâce au script add_server.php :
|
||||
# php add_server.php www42
|
||||
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
evoadmin-web
|
||||
============
|
||||
Panel d'administration de serveur web.
|
|
@ -0,0 +1,7 @@
|
|||
* Verification des paramètres passés dans le script ftpadmin.sh
|
||||
* Vérifier lors de la suppression que c'est bien la personne a qui appartient le compte qui lance la commande
|
||||
* Tableau "sortable" (TableKit ?)
|
||||
* Mettre en place EvoLog et logger la sortie des scripts
|
||||
* Validation plus (très) stricte sur les entrées de formulaire
|
||||
* Listage des comptes utilisateurs
|
||||
* Total espace disque FTP
|
|
@ -0,0 +1,34 @@
|
|||
<?php
|
||||
|
||||
require '../lib/bdd.php';
|
||||
require_once '../conf/config.php';
|
||||
require_once '../conf/config.local.php';
|
||||
|
||||
|
||||
if ($argc==1) {
|
||||
echo "Specify a server name";
|
||||
exit(1);
|
||||
}
|
||||
|
||||
$conf = array_merge($oriconf, $localconf);
|
||||
|
||||
$bdd = new bdd();
|
||||
|
||||
$file=$conf['cache'];
|
||||
|
||||
if (!file_exists($file)) {
|
||||
echo "$file doesn't exist\n";
|
||||
exit(1);
|
||||
}
|
||||
|
||||
$bdd->open($file);
|
||||
|
||||
$server = array("name" => $argv[1]);
|
||||
|
||||
$bdd->add_server(array("name" => "$server"));
|
||||
exec('ssh -o "UserKnownHostsFile '.$conf['known_host'].'" '.$argv[1].' /bin/true');
|
||||
|
||||
echo "$server added in cache\n";
|
||||
exit(0);
|
||||
?>
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
<?php
|
||||
|
||||
require '../lib/bdd.php';
|
||||
require_once '../conf/config.php';
|
||||
require_once '../conf/config.local.php';
|
||||
|
||||
$conf = array_merge($oriconf, $localconf);
|
||||
|
||||
|
||||
$bdd = new bdd();
|
||||
|
||||
$file=$conf['cache'];
|
||||
|
||||
if (!file_exists($file))
|
||||
$bdd->create($file);
|
||||
else {
|
||||
echo "$file is already created";
|
||||
exit(1);
|
||||
}
|
||||
|
||||
foreach ($conf['servers'] as $server) {
|
||||
echo "$server added in cache\n";
|
||||
$bdd->add_server(array("name" => "$server"));
|
||||
}
|
||||
|
||||
echo "Cache initialisé\n";
|
||||
exit(0);
|
||||
?>
|
|
@ -0,0 +1,26 @@
|
|||
<?php
|
||||
|
||||
require '../lib/bdd.php';
|
||||
require_once '../conf/config.php';
|
||||
require_once '../conf/config.local.php';
|
||||
|
||||
$conf = array_merge($oriconf, $localconf);
|
||||
|
||||
|
||||
$bdd = new bdd();
|
||||
|
||||
$file=$conf['cache'];
|
||||
|
||||
if (!file_exists($file)) {
|
||||
echo "$file is not created\n";
|
||||
exit(1);
|
||||
}
|
||||
|
||||
$bdd->open($file);
|
||||
|
||||
$domains = $bdd->list_domains();
|
||||
print_r($domains);
|
||||
|
||||
exit(0);
|
||||
|
||||
?>
|
|
@ -0,0 +1,18 @@
|
|||
#!/bin/sh
|
||||
|
||||
# Pré-requis pour utiliser ce script :
|
||||
# * Evoadmin-web est installé dans /home/evoadmin/www
|
||||
# * Etre loggué avec le compte evoadmin (sudo su evoadmin)
|
||||
|
||||
# Note : Ce script utilise une connexion SVN anonyme pour récupérer le code source
|
||||
# Note : Ce script ne met *pas* en prod les scripts dans /usr/share/scripts
|
||||
|
||||
SVNREPO="svn://svn.evolix.org/svn/packweb/trunk/evoadmin"
|
||||
|
||||
tmpdir=`mktemp -d $HOME/tmp.XXXXXX`
|
||||
svn export --force $SVNREPO $tmpdir
|
||||
svn info $SVNREPO >$tmpdir/svn.txt
|
||||
rsync -rlvt --delete --exclude config.local.php $tmpdir/ /home/evoadmin/www
|
||||
rm -rf $tmpdir
|
||||
svn info $SVNREPO | mail -s "Mise en prod Evoadmin ($HOSTNAME)" root
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* Configuration page
|
||||
*
|
||||
* Copyright (c) 2009 Evolix - Tous droits reserves
|
||||
*
|
||||
* $Id: config.php 273 2009-05-12 13:54:50Z tmartin $
|
||||
* vim: expandtab softtabstop=4 tabstop=4 shiftwidth=4 showtabline=2
|
||||
*
|
||||
* @author Gregory Colpart <reg@evolix.fr>
|
||||
* @author Thomas Martin <tmartin@evolix.fr>
|
||||
* @author Sebastien Palma <spalma@evolix.fr>
|
||||
* @version 1.0
|
||||
*/
|
||||
|
||||
|
||||
// Email pour les notifications
|
||||
$oriconf['admin']['mail'] = 'admin@example.com';
|
||||
$oriconf['techmail'] = 'jdoe@example.com';
|
||||
$oriconf['debug'] = FALSE;
|
||||
$oriconf['superadmin'] = array('superadmin');
|
||||
$oriconf['script_path'] = '/usr/share/scripts/evoadmin';
|
||||
$oriconf['cluster'] = FALSE;
|
||||
$oriconf['servers'] = array('servers');
|
||||
$oriconf['cache'] = '/home/evoadmin/www/cache.sqlite';
|
||||
$localconf['known_host'] = '/home/evoadmin/www/known_host';
|
||||
$oriconf['ftpadmin'] = TRUE;
|
||||
|
||||
/* cluster mode
|
||||
* $oriconf['noreplication'] = array('www00');
|
||||
* $oriconf['postponedreplication'] = array('www00', 'www01');
|
||||
* $oriconf['immediatereplication'] = array('www00', 'www01');
|
||||
* $oriconf['postponedreplication_mode'] = array('3 fois/jour', '1 fois/jour', '1 fois/heure');
|
||||
*/
|
||||
|
||||
/* Il est possible de définir pour chaque mode de
|
||||
* postponedreplication_mode une liste de serveurs,
|
||||
* qui seront utilisés à la place des serveurs du
|
||||
* tableau postponedreplication.
|
||||
*
|
||||
* $localconf['1 fois/jour'] = array('www00', 'www01');
|
||||
* $localconf['1 fois/heure'] = array('www01', 'www00');
|
||||
*/
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* Secrete parameters
|
||||
*
|
||||
* Copyright (c) 2009 Evolix - Tous droits reserves
|
||||
*
|
||||
* vim: expandtab softtabstop=4 tabstop=4 shiftwidth=4 showtabline=2
|
||||
*
|
||||
* @author Gregory Colpart <reg@evolix.fr>
|
||||
* @author Thomas Martin <tmartin@evolix.fr>
|
||||
* @author Sebastien Palma <spalma@evolix.fr>
|
||||
* @version 1.0
|
||||
*/
|
||||
|
||||
define("SUDOBIN","/usr/bin/sudo");
|
||||
define("SUDOSCRIPT","/usr/share/scripts/evoadmin.sh");
|
||||
define("SUDOPASS","xxxxxx");
|
||||
|
|
@ -0,0 +1,998 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* Bibliotheques FORM (PHP5)
|
||||
*
|
||||
* Copyright (c) 2004-2009 Evolix - Tous droits reserves
|
||||
*
|
||||
* $Id: Form.php 168 2009-08-14 14:41:42Z tmartin $
|
||||
* vim: expandtab softtabstop=4 tabstop=4 shiftwidth=4 showtabline=2
|
||||
*
|
||||
* @author Gregory Colpart <reg@evolix.fr>
|
||||
* @author Thomas Martin <tmartin@evolix.fr>
|
||||
* @author Sebastien Palma <spalma@evolix.fr>
|
||||
*
|
||||
* Fonctions utiles pour la creation de formulaires
|
||||
*
|
||||
* v 1.0
|
||||
*/
|
||||
|
||||
class FormPageController {
|
||||
private $pages = array();
|
||||
private $current_page = NULL;
|
||||
|
||||
/* Affiche la page de formulaire in-line */
|
||||
public function __toString() {
|
||||
$out = '';
|
||||
$out = $this->pages[$this->current_page];
|
||||
$out .= "\n\n";
|
||||
return $out;
|
||||
}
|
||||
|
||||
/* Vérifie les champs et redirige vers la dernière page valide.
|
||||
Retourne TRUE si le formulaire est entièrement valide.
|
||||
Retourne FALSE en cas d'erreur sur la page courante. */
|
||||
public function verify($set_error=TRUE) {
|
||||
$valid = TRUE;
|
||||
foreach($this->pages as $pagenum => $page) {
|
||||
if(!$page->verify($set_error)) {
|
||||
$valid = FALSE;
|
||||
}
|
||||
}
|
||||
if($valid) {
|
||||
return TRUE;
|
||||
} else {
|
||||
return FALSE;
|
||||
}
|
||||
}
|
||||
|
||||
public function setCurrentPage($current_page) {
|
||||
$this->current_page = $current_page;
|
||||
$this->pages[$current_page]->isCurrentPage(TRUE);
|
||||
}
|
||||
|
||||
public function getCurrentPage() {
|
||||
return $this->pages[$this->current_page];
|
||||
}
|
||||
|
||||
public function addPage($pagenum, $obj) {
|
||||
$this->pages[$pagenum] = $obj;
|
||||
}
|
||||
|
||||
/* Doit être appelé après les addField() */
|
||||
public function init() {
|
||||
foreach($this->pages as $pagenum=>$page) {
|
||||
$page->initFields();
|
||||
}
|
||||
}
|
||||
|
||||
/* Retourne le numéro de page suivant, ou FALSE si on est à la fin */
|
||||
public function getNextPage() {
|
||||
$numpage = count($this->pages);
|
||||
if($this->current_page == $numpage) {
|
||||
return FALSE;
|
||||
} else {
|
||||
return $this->current_page+1;
|
||||
}
|
||||
}
|
||||
|
||||
/* Retourne des infos sur les pages du formulaire, pour construire un fil
|
||||
d'ariane par exemple */
|
||||
public function getPagesList() {
|
||||
return $this->pages;
|
||||
}
|
||||
|
||||
public function getPage($num = null) {
|
||||
if($num) {
|
||||
return $this->pages[$num];
|
||||
} else {
|
||||
return $this->pages[$this->current_page];
|
||||
}
|
||||
}
|
||||
|
||||
/* Renvoie une collection d'objets "Field" */
|
||||
public function getFieldsList() {
|
||||
$fields = array();
|
||||
foreach($this->pages as $page) {
|
||||
foreach($page->getFieldsList() as $field) {
|
||||
$fields[$field[0]] = $field[1];
|
||||
}
|
||||
}
|
||||
return $fields;
|
||||
}
|
||||
|
||||
/* Renvoie une structure de données injectable dans ldap_add() ou
|
||||
ldap_modify() */
|
||||
public function toLDAP() {
|
||||
|
||||
$info = array();
|
||||
|
||||
foreach($this->getFieldsList() as $name=>$obj) {
|
||||
if(is_array($obj->getValue()) && count($obj->getValue()) == 1) {
|
||||
$tmp = $obj->getValue();
|
||||
$value = $tmp[0];
|
||||
} else {
|
||||
$value = $obj->getValue();
|
||||
}
|
||||
|
||||
if(!empty($value)) {
|
||||
$info[strtolower($name)] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $info;
|
||||
}
|
||||
|
||||
/* Permet de définir à posteriori une liste de champs obligatoires */
|
||||
public function setMandatoryFields($list) {
|
||||
foreach($this->getFieldsList() as $fname=>$fobj) {
|
||||
if(in_array($fname, $list)) {
|
||||
$fobj->setMandatory(TRUE);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Permet d'utiliser un stockage différent de celui par défaut
|
||||
* ($_SESSION) pour tous les FormFields déjà ajouté au controlleur. Prend
|
||||
* en paramètre la référence d'un tableau
|
||||
*/
|
||||
public function setSessionStorage(& $storage) {
|
||||
foreach($this->getFieldsList() as $fname=>$fobj) {
|
||||
$fobj->setSessionStorage($storage);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class FormPage {
|
||||
private $fields = array();
|
||||
private $label = NULL;
|
||||
private $is_current_page = FALSE;
|
||||
private $use_session = NULL;
|
||||
|
||||
public function __construct($label, $use_session=TRUE) {
|
||||
$this->label = $label;
|
||||
$this->use_session = $use_session;
|
||||
}
|
||||
|
||||
public function __toString() {
|
||||
$out = '';
|
||||
foreach($this->fields as $field) {
|
||||
$obj = $field[1];
|
||||
$out .= "$obj\n\n";
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
public function getLabel() {
|
||||
return $this->label;
|
||||
}
|
||||
|
||||
public function verify($set_error) {
|
||||
$num_error = 0;
|
||||
|
||||
foreach($this->fields as $field) {
|
||||
$obj = $field[1];
|
||||
if($obj->verify($set_error)) {
|
||||
$this->use_session && $obj->storeSession();
|
||||
} else {
|
||||
$num_error++;
|
||||
$this->use_session && $obj->deleteSession();
|
||||
}
|
||||
}
|
||||
|
||||
if($num_error > 0) {
|
||||
return FALSE;
|
||||
} else {
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
|
||||
public function addField($name, $obj) {
|
||||
$obj->setName($name);
|
||||
array_push($this->fields, array($name, $obj));
|
||||
}
|
||||
|
||||
public function addFieldsArray($array) {
|
||||
foreach($array as $name=>$obj) {
|
||||
$this->addField($name, $obj);
|
||||
}
|
||||
}
|
||||
|
||||
/* Petit hack : la page doit savoir si c'est elle qui est affiché, pour
|
||||
gérer le cas des checkbox */
|
||||
public function initFields($is_current_page=FALSE) {
|
||||
foreach($this->fields as $field) {
|
||||
$name = $field[0];
|
||||
$obj = $field[1];
|
||||
|
||||
if((is_a($obj, 'CheckBoxInputFormField')
|
||||
|| is_a($obj, 'MultipleCheckBoxInputFormField'))
|
||||
&& $this->is_current_page
|
||||
&& !empty($_POST) && !array_key_exists($name, $_POST)) {
|
||||
$obj->setValue(0);
|
||||
} else if(is_a($obj, 'UploadFileInputFormField')
|
||||
&& $this->is_current_page
|
||||
&& array_key_exists($name, $_FILES) && $_FILES[$name]['error']==0) {
|
||||
$obj->saveTmpFile($_FILES[$name]);
|
||||
} else if(array_key_exists($name, $_POST)) {
|
||||
$obj->setValue($_POST[$name]);
|
||||
} else if($this->use_session && $obj->sessionKeyExist($name)) {
|
||||
$obj->setSessionValue($name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function isCurrentPage($is=NULL) {
|
||||
if(is_bool($is)) {
|
||||
$this->is_current_page = $is;
|
||||
}
|
||||
return $this->is_current_page;
|
||||
}
|
||||
|
||||
|
||||
/* Renvoie la liste des objets Fields de la page */
|
||||
public function getFieldsList() {
|
||||
return $this->fields;
|
||||
}
|
||||
|
||||
/* Renvoie la liste des objets Fields de la page */
|
||||
public function getFieldsName() {
|
||||
$ret = array();
|
||||
foreach($this->fields as $field) {
|
||||
$ret[] = $field[0];
|
||||
}
|
||||
return $ret;
|
||||
}
|
||||
|
||||
public function getField($name) {
|
||||
foreach($this->fields as $f) {
|
||||
if($f[0] == $name) {
|
||||
return $f[1];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class FormField {
|
||||
protected $value = null;
|
||||
protected $error = null;
|
||||
protected $label = null;
|
||||
protected $name = null;
|
||||
protected $css_class = null;
|
||||
protected $read_only = null;
|
||||
protected $disabled = null;
|
||||
private $storage = NULL;
|
||||
|
||||
protected function __construct($label) {
|
||||
$this->storage = & $_SESSION;
|
||||
$this->label = $label;
|
||||
}
|
||||
|
||||
public function storeSession() {
|
||||
if(strlen($this->value) > 0) {
|
||||
$this->storage[$this->name] = $this->value;
|
||||
}
|
||||
}
|
||||
|
||||
public function deleteSession() {
|
||||
unset($this->storage[$this->name]);
|
||||
}
|
||||
|
||||
public function setSessionValue($name) {
|
||||
$this->setValue($this->storage[$name]);
|
||||
}
|
||||
|
||||
public function sessionKeyExist($name) {
|
||||
#echo "$name ".$this->storage[$name]." ";
|
||||
return array_key_exists($name, $this->storage);
|
||||
}
|
||||
|
||||
public function setSessionStorage(& $storage) {
|
||||
$this->storage = & $storage;
|
||||
}
|
||||
|
||||
protected function verify($set_error) {
|
||||
if(empty($this->error)) {
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
|
||||
public function getError() {
|
||||
if(isset($this->value) && !$this->verify(FALSE)) {
|
||||
return $this->error;
|
||||
}
|
||||
}
|
||||
|
||||
public function getErrorHTML() {
|
||||
return '<span class="form-error">'.$this->error.'</span>';
|
||||
}
|
||||
|
||||
public function setError($error) {
|
||||
$this->error = $error;
|
||||
}
|
||||
|
||||
public function getLabel() {
|
||||
return $this->label;
|
||||
}
|
||||
|
||||
public function setName($name) {
|
||||
$this->name = $name;
|
||||
}
|
||||
|
||||
public function getName() {
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
public function setValue($value) {
|
||||
$this->value = $value;
|
||||
}
|
||||
|
||||
public function getValue() {
|
||||
return $this->value;
|
||||
}
|
||||
|
||||
public function getReadableValue() {
|
||||
return $this->getValue();
|
||||
}
|
||||
|
||||
public function getLabelHTML() {
|
||||
$label = '';
|
||||
$label .= '<label for="'.$this->name.'">';
|
||||
$label .= $this->label.' ';
|
||||
if ($this->mandatory) {
|
||||
if($this->verify(false)) {
|
||||
$label .= '<span class="form-mandatory-ok">[*]</span> ';
|
||||
} else {
|
||||
$label .= '<span class="form-mandatory">[*]</span> ';
|
||||
}
|
||||
}
|
||||
$label .= ': ';
|
||||
$label .= "</label>\n";
|
||||
return $label;
|
||||
}
|
||||
|
||||
public function setCSSClass($name) {
|
||||
$this->css_class = $name;
|
||||
}
|
||||
|
||||
public function setReadOnly() {
|
||||
$this->read_only = true;
|
||||
}
|
||||
|
||||
public function setDisabled($state = TRUE) {
|
||||
$this->disabled = $state;
|
||||
}
|
||||
|
||||
public function setMandatory($bool) {
|
||||
$this->mandatory = $bool;
|
||||
}
|
||||
}
|
||||
|
||||
/* $textsize = array( size, maxlength ) */
|
||||
class TextInputFormField extends FormField {
|
||||
protected $mandatory = NULL;
|
||||
protected $textsize = NULL;
|
||||
|
||||
public function __construct($label, $mandatory=TRUE, $textsize=array(20, 40)) {
|
||||
parent::__construct($label);
|
||||
$this->mandatory = $mandatory;
|
||||
$this->textsize = $textsize;
|
||||
}
|
||||
|
||||
public function verify($set_error) {
|
||||
if($this->mandatory && (!strlen($this->value))) {
|
||||
if($set_error) $this->error = 'Champ obligatoire';
|
||||
return FALSE;
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
public function getInputHTML() {
|
||||
$input = '';
|
||||
$input .= '<input type="text" id="'.$this->name.'"';
|
||||
$input .= ' name="'.$this->name.'" value="'.htmlspecialchars($this->value,ENT_QUOTES).'"';
|
||||
#$input .= sprintf(' name="%s" value="%s"', $this->name, htmlspecialchars($this->value, ENT_QUOTES));
|
||||
$input .= ' maxlength="'.$this->textsize[1].'" size="'.$this->textsize[0].'" ';
|
||||
if($this->read_only) { $input .= 'readonly="readonly="'; }
|
||||
if($this->disabled) { $input .= 'disabled="disabled="'; }
|
||||
$input .= '/>';
|
||||
return $input;
|
||||
}
|
||||
|
||||
public function __toString() {
|
||||
$out = '';
|
||||
$out .= "<p>\n";
|
||||
$out .= $this->getLabelHTML();
|
||||
$out .= $this->getInputHTML();
|
||||
$out .= $this->getErrorHTML();
|
||||
$out .= "</p>\n\n";
|
||||
return $out;
|
||||
}
|
||||
}
|
||||
|
||||
class DateInputFormField extends TextInputFormField {
|
||||
public function __construct($label, $mandatory=TRUE) {
|
||||
parent::__construct($label, $mandatory, array(7, 10));
|
||||
}
|
||||
|
||||
public function verify($set_error) {
|
||||
if(!parent::verify($set_error)) return FALSE;
|
||||
if(!empty($this->value) &&
|
||||
!preg_match('#^\d{2}/\d{2}/\d{4}$#', $this->value)) {
|
||||
if($set_error) $this->error = 'Format de date non valide';
|
||||
return FALSE;
|
||||
}
|
||||
$arr_date = split('/', $this->value);
|
||||
if(!empty($this->value) &&
|
||||
!checkdate($arr_date[1],$arr_date[0],$arr_date[2])) {
|
||||
if($set_error) $this->error = "La date saisie n'existe pas";
|
||||
return FALSE;
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
|
||||
class YearDateInputFormField extends TextInputFormField {
|
||||
public function __construct($label, $mandatory=TRUE) {
|
||||
parent::__construct($label, $mandatory, array(4, 4));
|
||||
}
|
||||
|
||||
public function verify($set_error) {
|
||||
if(!parent::verify($set_error)) return FALSE;
|
||||
if(!empty($this->value) && (!ctype_digit($this->value) || $this->value < 1900)) {
|
||||
if($set_error) $this->error = 'Vous devez saisir une année valide';
|
||||
return FALSE;
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
|
||||
class TelephoneInputFormField extends TextInputFormField {
|
||||
public function setValue($value) {
|
||||
$value = preg_replace('/[^\d -\.\(\)\+]/', '-', $value);
|
||||
parent::setValue($value);
|
||||
}
|
||||
}
|
||||
|
||||
class IntegerInputFormField extends TextInputFormField {
|
||||
public function verify($set_error) {
|
||||
if(!parent::verify($set_error)) return FALSE;
|
||||
if(!empty($this->value) && !is_numeric($this->value)) {
|
||||
if($set_error) $this->error = 'Vous devez saisir un chiffre';
|
||||
return FALSE;
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
|
||||
class FloatInputFormField extends TextInputFormField {
|
||||
public function verify($set_error) {
|
||||
if(!parent::verify($set_error)) return FALSE;
|
||||
if(!empty($this->value) && !is_numeric($this->value)) {
|
||||
if($set_error) $this->error = 'Vous devez saisir un chiffre';
|
||||
return FALSE;
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
|
||||
class EmailInputFormField extends TextInputFormField {
|
||||
|
||||
public function verify($set_error) {
|
||||
if(!parent::verify($set_error)) {
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
if(!empty($this->value) && !eregi('^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$',$this->value)){
|
||||
if($set_error) $this->error = 'Adresse email invalide';
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
|
||||
class TextareaFormField extends FormField {
|
||||
protected $mandatory = NULL;
|
||||
protected $cols = NULL;
|
||||
protected $rows = NULL;
|
||||
|
||||
public function __construct($label, $mandatory=TRUE, $cols=45, $rows=5) {
|
||||
parent::__construct($label);
|
||||
$this->mandatory = $mandatory;
|
||||
$this->rows = $rows;
|
||||
$this->cols = $cols;
|
||||
}
|
||||
|
||||
public function verify($set_error) {
|
||||
if($this->mandatory && empty($this->value)) {
|
||||
if($set_error) $this->error = 'Champ obligatoire';
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
public function getInputHTML() {
|
||||
$input = '';
|
||||
$input .= '<textarea cols="'.$this->cols.'" rows="'.$this->rows.'" id="'.$this->name.'"';
|
||||
$input .= ' name="'.$this->name.'">'.htmlspecialchars($this->value,ENT_QUOTES).'</textarea>';
|
||||
return $input;
|
||||
}
|
||||
|
||||
public function __toString() {
|
||||
$out = '';
|
||||
$out .= "<p class='form-textarea'>\n";
|
||||
$out .= $this->getLabelHTML();
|
||||
$out .= $this->getInputHTML();
|
||||
$out .= $this->getErrorHTML();
|
||||
$out .= "</p>\n\n";
|
||||
return $out;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class PasswordInputFormField extends FormField {
|
||||
protected $mandatory = NULL;
|
||||
|
||||
public function __construct($label, $mandatory=TRUE) {
|
||||
parent::__construct($label);
|
||||
$this->mandatory = $mandatory;
|
||||
}
|
||||
|
||||
public function verify($set_error) {
|
||||
if(empty($this->value)) {
|
||||
if($this->mandatory) {
|
||||
if($set_error) $this->error = 'Champ obligatoire';
|
||||
return FALSE;
|
||||
} else {
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
|
||||
if(strlen($this->value) < 8) {
|
||||
if($set_error) $this->error = '8 caracteres minimum';
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
#if(preg_match('#.*[A-Z]+.*$#',$this->value)==0){
|
||||
# if($set_error) $this->error = 'Votre mot de passe doit contenir au moins une majuscule';
|
||||
# return FALSE;
|
||||
# }
|
||||
|
||||
if(preg_match('#.*[0-9]+.*#',$this->value)==0){
|
||||
if($set_error) $this->error = 'Votre mot de passe doit contenir au moins un chiffre';
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
|
||||
public function getInputHTML() {
|
||||
$input = sprintf('<input type="password" id="%s" name="%s" value="%s"',
|
||||
$this->name, $this->name,
|
||||
htmlspecialchars($this->value, ENT_QUOTES));
|
||||
if($this->read_only) $input .= ' readonly="readonly"';
|
||||
if($this->disabled) { $input .= 'disabled="disabled="'; }
|
||||
$input .= '/>';
|
||||
return $input;
|
||||
}
|
||||
|
||||
public function __toString() {
|
||||
$out = '';
|
||||
$out .= "<p>\n";
|
||||
$out .= $this->getLabelHTML();
|
||||
$out .= $this->getInputHTML();
|
||||
$out .= $this->getErrorHTML();
|
||||
$out .= "</p>\n\n";
|
||||
return $out;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class CheckBoxInputFormField extends FormField {
|
||||
protected $mandatory = NULL;
|
||||
|
||||
public function __construct($label, $mandatory=TRUE) {
|
||||
parent::__construct($label);
|
||||
$this->mandatory = $mandatory;
|
||||
}
|
||||
|
||||
public function verify($set_error) {
|
||||
if(!parent::verify($set_error)) return FALSE;
|
||||
if($this->mandatory && empty($this->value)) {
|
||||
if($set_error) $this->error = 'Champ obligatoire';
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
|
||||
public function getInputHTML() {
|
||||
$input = sprintf('<input type="checkbox" id="%s" name="%s"',
|
||||
$this->name, $this->name);
|
||||
if($this->value) $input .= ' checked="checked"';
|
||||
if($this->disabled) $input .= ' disabled="disabled"';
|
||||
$input .= ' value="1" />';
|
||||
return $input;
|
||||
}
|
||||
|
||||
public function __toString() {
|
||||
$out = '';
|
||||
$out .= "<p>\n";
|
||||
$out .= $this->getLabelHTML();
|
||||
$out .= $this->getInputHTML();
|
||||
$out .= $this->getErrorHTML();
|
||||
$out .= "</p>\n\n";
|
||||
return $out;
|
||||
}
|
||||
}
|
||||
|
||||
class MultipleCheckBoxInputFormField extends FormField {
|
||||
protected $mandatory = NULL;
|
||||
protected $list = array();
|
||||
|
||||
public function __construct($label, $mandatory=TRUE, $list) {
|
||||
parent::__construct($label);
|
||||
$this->mandatory = $mandatory;
|
||||
$this->list = $list;
|
||||
}
|
||||
|
||||
public function verify($set_error) {
|
||||
if($this->mandatory && empty($this->value)) {
|
||||
if($set_error) $this->error = 'Vous devez faire au moins un choix';
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
public function getInputHTML() {
|
||||
$input = '';
|
||||
$n = 0;
|
||||
foreach ($this->list as $value => $label) {
|
||||
$input .= '<input type="checkbox" name="'.$this->name.'[]" value="'.htmlspecialchars($value,ENT_QUOTES).'"';
|
||||
if (is_array($this->value) && in_array($value, $this->value)) {
|
||||
$input.=' checked="checked"';
|
||||
}
|
||||
if($this->read_only) { $input .= 'readonly="readonly="'; }
|
||||
$input .= "/>$label";
|
||||
$n++;
|
||||
if($n < count($this->list)) $input .= "<br/>\n";
|
||||
}
|
||||
return $input;
|
||||
}
|
||||
|
||||
public function getErrorHTML() {
|
||||
if($this->error) {
|
||||
return "<br/><span class='form-error form-incolumn-error'>{$this->error}</span>";
|
||||
} else {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
public function __toString() {
|
||||
$out = '';
|
||||
$out .= "<p>\n";
|
||||
$out .= $this->getLabelHTML();
|
||||
$out .= $this->getInputHTML();
|
||||
$out .= $this->getErrorHTML();
|
||||
$out .= "</p>\n\n";
|
||||
return $out;
|
||||
}
|
||||
|
||||
public function getValue() {
|
||||
$out = array();
|
||||
foreach($this->value as $index) {
|
||||
#$out[] = $this->list[$index];
|
||||
$out[] = $index;
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
public function getReadableValue() {
|
||||
$n = 1;
|
||||
$out = '';
|
||||
foreach($this->value as $index) {
|
||||
$out .= $this->list[$index];
|
||||
if($n < count($this->value)) $out .= ', ';
|
||||
$n++;
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
public function setValue($value) {
|
||||
if(!is_array($value)) {
|
||||
$this->value = array($value);
|
||||
} else {
|
||||
parent::setValue($value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class SelectFormField extends FormField {
|
||||
protected $mandatory = NULL;
|
||||
protected $list = array();
|
||||
|
||||
public function __construct($label, $mandatory=TRUE, $list) {
|
||||
parent::__construct($label);
|
||||
$this->mandatory = $mandatory;
|
||||
$this->list = $list;
|
||||
}
|
||||
|
||||
public function verify($set_error) {
|
||||
if($this->mandatory && empty($this->value)) {
|
||||
if($set_error) $this->error = 'Champ obligatoire';
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
|
||||
public function getInputHTML() {
|
||||
$input = '';
|
||||
$input .= '<select id="'.$this->name.'" name="'.$this->name.'">'."\n";
|
||||
$input .= ' <option value="">-- Choisissez --</option>'."\n";
|
||||
foreach ($this->list as $value => $label) {
|
||||
$input .= ' <option value="'.htmlspecialchars($value,ENT_QUOTES).'"';
|
||||
if ($this->value == $value) $input.=' selected="selected"';
|
||||
$input .= '>'.$label.'</option>'."\n";
|
||||
}
|
||||
$input .= "</select>\n";
|
||||
return $input;
|
||||
}
|
||||
|
||||
public function __toString() {
|
||||
$out = '';
|
||||
$out .= "<p>\n";
|
||||
$out .= $this->getLabelHTML();
|
||||
$out .= $this->getInputHTML();
|
||||
$out .= $this->getErrorHTML();
|
||||
$out .= "</p>\n\n";
|
||||
return $out;
|
||||
}
|
||||
|
||||
public function getValue() {
|
||||
return $this->value;
|
||||
}
|
||||
|
||||
public function getReadableValue() {
|
||||
if(array_key_exists($this->value, $this->list)) {
|
||||
return $this->list[$this->value];
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class RadioFormField extends FormField {
|
||||
protected $mandatory = NULL;
|
||||
protected $list = array();
|
||||
|
||||
public function __construct($label, $mandatory=TRUE, $list, $default = null) {
|
||||
parent::__construct($label);
|
||||
$this->mandatory = $mandatory;
|
||||
$this->list = $list;
|
||||
if($default) {
|
||||
$this->value = $default;
|
||||
}
|
||||
}
|
||||
|
||||
public function verify($set_error) {
|
||||
if($this->mandatory && empty($this->value)) {
|
||||
if($set_error) $this->error = 'Champ obligatoire';
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
public function getInputHTML() {
|
||||
$input = '';
|
||||
$input .= '<span class="form-radio">';
|
||||
foreach ($this->list as $value => $label) {
|
||||
$input .= '<input type="radio" name="'.$this->name.'" value="'.htmlspecialchars($value,ENT_QUOTES).'"';
|
||||
if ($this->value == $value) $input.=' checked="checked"';
|
||||
$input .= "/>$label<br/>";
|
||||
}
|
||||
$input .= '</span>';
|
||||
return $input;
|
||||
}
|
||||
|
||||
public function getErrorHTML() {
|
||||
return "<span class='form-error form-incolumn-error'>{$this->error}</span>";
|
||||
}
|
||||
|
||||
public function __toString() {
|
||||
$out = '';
|
||||
$out .= "<p>\n";
|
||||
$out .= $this->getLabelHTML();
|
||||
$out .= $this->getInputHTML();
|
||||
$out .= $this->getErrorHTML();
|
||||
$out .= "</p>\n\n";
|
||||
return $out;
|
||||
}
|
||||
|
||||
public function getValue() {
|
||||
return $this->value;
|
||||
}
|
||||
|
||||
public function getReadableValue() {
|
||||
if(array_key_exists($this->value, $this->list)) {
|
||||
return $this->list[$this->value];
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class ButtonInputFormField extends FormField {
|
||||
protected $mandatory = NULL;
|
||||
protected $event = NULL;
|
||||
protected $action = NULL;
|
||||
|
||||
public function __construct($label,$mandatory=FALSE, $event, $action) {
|
||||
parent::__construct($label);
|
||||
$this->mandatory = $mandatory;
|
||||
$this->event = $event;
|
||||
$this->action = $action;
|
||||
}
|
||||
|
||||
public function verify($set_error) {
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
|
||||
public function getInputHTML() {
|
||||
$input = '';
|
||||
$input .= '<input type="button" name="'.$this->name.'" ';
|
||||
if (!empty($this->event) && !empty($this->action)) {
|
||||
$input .= $this->event.'='.$this->action.' ';
|
||||
}
|
||||
$input .= 'value="'.htmlspecialchars($this->label,ENT_QUOTES).'" />';
|
||||
return $input;
|
||||
}
|
||||
|
||||
public function __toString() {
|
||||
$out = '';
|
||||
$out .= "<p>\n";
|
||||
$out .= $this->getInputHTML();
|
||||
$out .= $this->getErrorHTML();
|
||||
$out .= "</p>\n\n";
|
||||
return $out;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class SubmitInputFormField extends FormField {
|
||||
protected $mandatory = NULL;
|
||||
protected $event = NULL;
|
||||
protected $action = NULL;
|
||||
|
||||
public function __construct($label,$mandatory=FALSE) {
|
||||
parent::__construct($label);
|
||||
$this->mandatory = $mandatory;
|
||||
}
|
||||
|
||||
public function verify($set_error) {
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
|
||||
public function getInputHTML() {
|
||||
$input = '';
|
||||
$input .= '<input type="submit" name="'.$this->name.'" ';
|
||||
$input .= 'class="'.$this->css_class.'" value="'.htmlspecialchars($this->label,ENT_QUOTES).'" />';
|
||||
return $input;
|
||||
}
|
||||
|
||||
public function __toString() {
|
||||
$out = '';
|
||||
$out .= "<p>\n";
|
||||
$out .= $this->getInputHTML();
|
||||
$out .= $this->getErrorHTML();
|
||||
$out .= "</p>\n\n";
|
||||
return $out;
|
||||
}
|
||||
}
|
||||
|
||||
class UploadFileInputFormField extends FormField {
|
||||
protected $mandatory = NULL;
|
||||
protected $delete_url = NULL;
|
||||
|
||||
public function __construct($label,$mandatory=FALSE) {
|
||||
parent::__construct($label);
|
||||
$this->mandatory = $mandatory;
|
||||
}
|
||||
|
||||
public function verify($set_error) {
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
public function setDeleteUrl($url) {
|
||||
$this->delete_url = $url;
|
||||
}
|
||||
|
||||
|
||||
public function deleteUploadedFile() {
|
||||
if(!is_array($this->value)) {
|
||||
return "Value is not an array";
|
||||
}
|
||||
|
||||
if(file_exists('/tmp/'.$this->value['tempname'])) {
|
||||
unlink('/tmp/'.$this->value['tempname']);
|
||||
}
|
||||
|
||||
$this->value = NULL;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function saveTmpFile($upload_array) {
|
||||
$this->value['filename'] = $upload_array['name'];
|
||||
$this->value['file_ext'] = end(explode(".", $this->value['filename']));
|
||||
$this->value['tempname'] = 'tmp_'.time().'.'.$this->value['file_ext'];
|
||||
$up_filename = $upload_array['tmp_name'];
|
||||
|
||||
if(!move_uploaded_file($up_filename, '/tmp/'.$this->value['tempname'])) {
|
||||
$this->error = $this->value['error'];
|
||||
}
|
||||
}
|
||||
|
||||
public function moveTmpFile($filename, $dest_path) {
|
||||
$this->value['filename'] = $filename.'.'.$this->value['file_ext'];
|
||||
|
||||
if(!file_exists('/tmp/'.$this->value['tempname'])) {
|
||||
$this->error = "Impossible de trouver le fichier /tmp/{$this->value['tempname']}";
|
||||
return "";
|
||||
}
|
||||
|
||||
if((rename('/tmp/'.$this->value['tempname'],$dest_path.$this->value['filename']))===FALSE) {
|
||||
$this->error = "Impossible de déplacer le fichier vers $dest_path{$this->value['filename']}";
|
||||
return "";
|
||||
}
|
||||
return $dest_path.$this->value['filename'];
|
||||
|
||||
}
|
||||
|
||||
public function getInputHTML($delete_url='') {
|
||||
$input = '';
|
||||
$input .= '<input type="file" name="'.$this->name.'" id="'.$this->name.'" />';
|
||||
if(is_array($this->value)) {
|
||||
$filename = $this->value['filename'];
|
||||
} elseif (!empty($this->value)){
|
||||
$filename = $this->value;
|
||||
}
|
||||
|
||||
if (!empty($filename)) {
|
||||
$input .= "<br/><div class='form-comment'>Fichier uploadé : ";
|
||||
$input .= "<a href=\"/inscription/viewcv/$filename\">$filename</a>";
|
||||
if(!empty($this->delete_url)) {
|
||||
$input .= ' <a href="'.$this->delete_url.'" target="_blank" style="text-decoration:none"><font color="red"><b>X</b></font></a>';
|
||||
}
|
||||
$input .= "</div>";
|
||||
}
|
||||
|
||||
return $input;
|
||||
}
|
||||
|
||||
public function __toString() {
|
||||
$out = '';
|
||||
$out .= "<p>\n";
|
||||
$out .= $this->getLabelHTML();
|
||||
$out .= $this->getInputHTML();
|
||||
$out .= $this->getErrorHTML();
|
||||
$out .= "</p>\n\n";
|
||||
return $out;
|
||||
}
|
||||
|
||||
public function getReadableValue() {
|
||||
return $this->value['filename'];
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
|
@ -0,0 +1,5 @@
|
|||
RewriteEngine on
|
||||
RewriteCond %{REQUEST_FILENAME} !-f
|
||||
RewriteCond %{REQUEST_FILENAME} !-d
|
||||
RewriteRule . /index.php [L]
|
||||
|
|
@ -0,0 +1,87 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* file included in every PHP file
|
||||
*
|
||||
* Copyright (c) 2009 Evolix - Tous droits reserves
|
||||
*
|
||||
* vim: expandtab softtabstop=4 tabstop=4 shiftwidth=4 showtabline=2
|
||||
*
|
||||
* @author Gregory Colpart <reg@evolix.fr>
|
||||
* @author Thomas Martin <tmartin@evolix.fr>
|
||||
* @author Sebastien Palma <spalma@evolix.fr>
|
||||
* @version 1.0
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Functions
|
||||
*/
|
||||
function test_exist($file) {
|
||||
if(!file_exists($file)) {
|
||||
die("Erreur, vous devez mettre en place le fichier $file !\n");
|
||||
}
|
||||
if(!is_readable($file)) {
|
||||
die("Erreur, le fichier $file n'est pas accessible en lecture !\n");
|
||||
}
|
||||
}
|
||||
|
||||
function http_redirect($path) {
|
||||
header('Location: http://'.$_SERVER['HTTP_HOST'].$path);
|
||||
exit(0);
|
||||
}
|
||||
|
||||
function findexts ($filename)
|
||||
{
|
||||
$filename = strtolower($filename) ;
|
||||
$exts = split("[/\\.]", $filename) ;
|
||||
$n = count($exts)-1;
|
||||
$exts = $exts[$n];
|
||||
return $exts;
|
||||
}
|
||||
|
||||
function is_superadmin() {
|
||||
global $conf;
|
||||
if(!empty($_SESSION['user']) && in_array($_SESSION['user'], $conf['superadmin'])) {
|
||||
return 1;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
function sudoexec($cmd, &$output, &$return_var) {
|
||||
global $conf;
|
||||
|
||||
/* -H The -H (HOME) option sets the HOME environment variable to the
|
||||
* homedir of the target user */
|
||||
/* => Nécessaire pour l'utilisation du .my.cnf de root */
|
||||
$cmd = sprintf('sudo -H %s/%s', $conf['script_path'], $cmd);
|
||||
|
||||
exec($cmd, $output, $return_var);
|
||||
}
|
||||
|
||||
/**
|
||||
* Includes
|
||||
*/
|
||||
|
||||
// PEAR libs
|
||||
if (!(ini_set('include_path', ini_get('include_path')))) {
|
||||
die('bibliotheques PEAR non presentes');
|
||||
} else {
|
||||
|
||||
require_once 'PEAR.php';
|
||||
require_once 'Log.php';
|
||||
|
||||
// config files
|
||||
// (here because need Log PEAR lib)
|
||||
test_exist('../conf/connect.php');
|
||||
require_once('../conf/connect.php');
|
||||
test_exist('../conf/config.php');
|
||||
require_once('../conf/config.php');
|
||||
test_exist('../conf/config.local.php');
|
||||
require_once('../conf/config.local.php');
|
||||
# il faut un acces en lecture au fichier shadow pour pam_auth()
|
||||
test_exist('/etc/shadow');
|
||||
$conf = array_merge($oriconf, $localconf);
|
||||
}
|
||||
|
|
@ -0,0 +1,166 @@
|
|||
|
||||
/**
|
||||
* Feuille de style
|
||||
*
|
||||
* copyright (c) 2009 evolix - tous droits reserves
|
||||
*
|
||||
* $id: index.php 3 2009-04-28 08:43:39z tmartin $
|
||||
* vim: expandtab softtabstop=4 tabstop=4 shiftwidth=4 showtabline=2
|
||||
*
|
||||
* @author Thomas Martin <tmartin@evolix.fr>
|
||||
* @version 1.0
|
||||
*/
|
||||
|
||||
body {
|
||||
background-color: white;
|
||||
color: black;
|
||||
font-size: small;
|
||||
font-family: "Lucida Grande", Helvetica, Arial, Verdana, sans-serif;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
div#main {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
h1#top {
|
||||
background-color: blue;
|
||||
margin: 0;
|
||||
color: white;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
div#disclaimer {
|
||||
margin-top: 30px;
|
||||
}
|
||||
|
||||
ul#menu li {
|
||||
list-style-type: none;
|
||||
float: left;
|
||||
margin-right: 10px;
|
||||
}
|
||||
|
||||
ul#menu {
|
||||
margin: auto;
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
|
||||
a {
|
||||
color: blue;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
/* Tableaux "liste" */
|
||||
|
||||
table#tab-list {
|
||||
border-collapse: collapse;
|
||||
margin: auto;
|
||||
width: 70%;
|
||||
}
|
||||
|
||||
table#tab-list tr:hover {
|
||||
background-color: blue;
|
||||
color: white;
|
||||
}
|
||||
|
||||
table#tab-list tr:hover a {
|
||||
background-color: blue;
|
||||
color: white;
|
||||
}
|
||||
|
||||
|
||||
table#tab-list th {
|
||||
border: 1px black solid;
|
||||
background-color: blue;
|
||||
color: white;
|
||||
}
|
||||
|
||||
table#tab-list td {
|
||||
border: 1px black solid;
|
||||
}
|
||||
|
||||
div#disclaimer {
|
||||
border-top: 1px blue solid;
|
||||
padding-top: 5px;
|
||||
}
|
||||
|
||||
td.auth-error {
|
||||
color: red;
|
||||
}
|
||||
|
||||
p.form-error {
|
||||
color: red;
|
||||
}
|
||||
|
||||
fieldset {
|
||||
width: 50%;
|
||||
margin: auto;
|
||||
border: 1px blue solid;
|
||||
}
|
||||
|
||||
fieldset dl {
|
||||
}
|
||||
|
||||
fieldset dt {
|
||||
text-align: right;
|
||||
float: left;
|
||||
width: 45%;
|
||||
padding-right: 10px;
|
||||
}
|
||||
|
||||
fieldset dd {
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
p label {
|
||||
position: absolute;
|
||||
text-align:right;
|
||||
width:300px;
|
||||
}
|
||||
|
||||
p input {
|
||||
margin-left: 310px;
|
||||
}
|
||||
|
||||
p select {
|
||||
margin-left: 310px;
|
||||
}
|
||||
|
||||
p textarea {
|
||||
margin-left: 310px;
|
||||
}
|
||||
|
||||
span.form-error {
|
||||
color: red;
|
||||
margin-left: 4px;
|
||||
}
|
||||
|
||||
span.form-mandatory {
|
||||
color: red;
|
||||
}
|
||||
|
||||
span.form-mandatory-ok {
|
||||
color: #900000;
|
||||
}
|
||||
|
||||
/* Formulaires d'ajout d'objets */
|
||||
|
||||
form#form-add {
|
||||
margin: auto;
|
||||
}
|
||||
|
||||
form#form-add fieldset {
|
||||
width: 69%;
|
||||
border: 1px black solid;
|
||||
}
|
||||
|
||||
form#form-add legend {
|
||||
border: 1px black solid;
|
||||
background-color: blue;
|
||||
color: white;
|
||||
}
|
||||
|
||||
form#form-add p {
|
||||
text-align: left;
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
|
||||
// vim: expandtab softtabstop=4 tabstop=4 shiftwidth=4 showtabline=2
|
||||
|
||||
function fill_directory_field(value) {
|
||||
if(document.forms['addftp'].path.value == '') {
|
||||
document.forms['addftp'].path.value = value;
|
||||
}
|
||||
}
|
||||
|
||||
function check_form_ftp_add() {
|
||||
field_passwd = document.getElementById('passwd').value;
|
||||
if(field_passwd.length < 6) {
|
||||
alert('Le mot de passe doit contenir au moins 6 caractères ');
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
document.observe("dom:loaded", function() {
|
||||
document.getElementById('login').onblur = function() {
|
||||
path = document.getElementById('path');
|
||||
if(!path.value) {
|
||||
path.value = document.getElementById('login').value;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
|
@ -0,0 +1,4320 @@
|
|||
/* Prototype JavaScript framework, version 1.6.0.3
|
||||
* (c) 2005-2008 Sam Stephenson
|
||||
*
|
||||
* Prototype is freely distributable under the terms of an MIT-style license.
|
||||
* For details, see the Prototype web site: http://www.prototypejs.org/
|
||||
*
|
||||
*--------------------------------------------------------------------------*/
|
||||
|
||||
var Prototype = {
|
||||
Version: '1.6.0.3',
|
||||
|
||||
Browser: {
|
||||
IE: !!(window.attachEvent &&
|
||||
navigator.userAgent.indexOf('Opera') === -1),
|
||||
Opera: navigator.userAgent.indexOf('Opera') > -1,
|
||||
WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
|
||||
Gecko: navigator.userAgent.indexOf('Gecko') > -1 &&
|
||||
navigator.userAgent.indexOf('KHTML') === -1,
|
||||
MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
|
||||
},
|
||||
|
||||
BrowserFeatures: {
|
||||
XPath: !!document.evaluate,
|
||||
SelectorsAPI: !!document.querySelector,
|
||||
ElementExtensions: !!window.HTMLElement,
|
||||
SpecificElementExtensions:
|
||||
document.createElement('div')['__proto__'] &&
|
||||
document.createElement('div')['__proto__'] !==
|
||||
document.createElement('form')['__proto__']
|
||||
},
|
||||
|
||||
ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
|
||||
JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,
|
||||
|
||||
emptyFunction: function() { },
|
||||
K: function(x) { return x }
|
||||
};
|
||||
|
||||
if (Prototype.Browser.MobileSafari)
|
||||
Prototype.BrowserFeatures.SpecificElementExtensions = false;
|
||||
|
||||
|
||||
/* Based on Alex Arnell's inheritance implementation. */
|
||||
var Class = {
|
||||
create: function() {
|
||||
var parent = null, properties = $A(arguments);
|
||||
if (Object.isFunction(properties[0]))
|
||||
parent = properties.shift();
|
||||
|
||||
function klass() {
|
||||
this.initialize.apply(this, arguments);
|
||||
}
|
||||
|
||||
Object.extend(klass, Class.Methods);
|
||||
klass.superclass = parent;
|
||||
klass.subclasses = [];
|
||||
|
||||
if (parent) {
|
||||
var subclass = function() { };
|
||||
subclass.prototype = parent.prototype;
|
||||
klass.prototype = new subclass;
|
||||
parent.subclasses.push(klass);
|
||||
}
|
||||
|
||||
for (var i = 0; i < properties.length; i++)
|
||||
klass.addMethods(properties[i]);
|
||||
|
||||
if (!klass.prototype.initialize)
|
||||
klass.prototype.initialize = Prototype.emptyFunction;
|
||||
|
||||
klass.prototype.constructor = klass;
|
||||
|
||||
return klass;
|
||||
}
|
||||
};
|
||||
|
||||
Class.Methods = {
|
||||
addMethods: function(source) {
|
||||
var ancestor = this.superclass && this.superclass.prototype;
|
||||
var properties = Object.keys(source);
|
||||
|
||||
if (!Object.keys({ toString: true }).length)
|
||||
properties.push("toString", "valueOf");
|
||||
|
||||
for (var i = 0, length = properties.length; i < length; i++) {
|
||||
var property = properties[i], value = source[property];
|
||||
if (ancestor && Object.isFunction(value) &&
|
||||
value.argumentNames().first() == "$super") {
|
||||
var method = value;
|
||||
value = (function(m) {
|
||||
return function() { return ancestor[m].apply(this, arguments) };
|
||||
})(property).wrap(method);
|
||||
|
||||
value.valueOf = method.valueOf.bind(method);
|
||||
value.toString = method.toString.bind(method);
|
||||
}
|
||||
this.prototype[property] = value;
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
};
|
||||
|
||||
var Abstract = { };
|
||||
|
||||
Object.extend = function(destination, source) {
|
||||
for (var property in source)
|
||||
destination[property] = source[property];
|
||||
return destination;
|
||||
};
|
||||
|
||||
Object.extend(Object, {
|
||||
inspect: function(object) {
|
||||
try {
|
||||
if (Object.isUndefined(object)) return 'undefined';
|
||||
if (object === null) return 'null';
|
||||
return object.inspect ? object.inspect() : String(object);
|
||||
} catch (e) {
|
||||
if (e instanceof RangeError) return '...';
|
||||
throw e;
|
||||
}
|
||||
},
|
||||
|
||||
toJSON: function(object) {
|
||||
var type = typeof object;
|
||||
switch (type) {
|
||||
case 'undefined':
|
||||
case 'function':
|
||||
case 'unknown': return;
|
||||
case 'boolean': return object.toString();
|
||||
}
|
||||
|
||||
if (object === null) return 'null';
|
||||
if (object.toJSON) return object.toJSON();
|
||||
if (Object.isElement(object)) return;
|
||||
|
||||
var results = [];
|
||||
for (var property in object) {
|
||||
var value = Object.toJSON(object[property]);
|
||||
if (!Object.isUndefined(value))
|
||||
results.push(property.toJSON() + ': ' + value);
|
||||
}
|
||||
|
||||
return '{' + results.join(', ') + '}';
|
||||
},
|
||||
|
||||
toQueryString: function(object) {
|
||||
return $H(object).toQueryString();
|
||||
},
|
||||
|
||||
toHTML: function(object) {
|
||||
return object && object.toHTML ? object.toHTML() : String.interpret(object);
|
||||
},
|
||||
|
||||
keys: function(object) {
|
||||
var keys = [];
|
||||
for (var property in object)
|
||||
keys.push(property);
|
||||
return keys;
|
||||
},
|
||||
|
||||
values: function(object) {
|
||||
var values = [];
|
||||
for (var property in object)
|
||||
values.push(object[property]);
|
||||
return values;
|
||||
},
|
||||
|
||||
clone: function(object) {
|
||||
return Object.extend({ }, object);
|
||||
},
|
||||
|
||||
isElement: function(object) {
|
||||
return !!(object && object.nodeType == 1);
|
||||
},
|
||||
|
||||
isArray: function(object) {
|
||||
return object != null && typeof object == "object" &&
|
||||
'splice' in object && 'join' in object;
|
||||
},
|
||||
|
||||
isHash: function(object) {
|
||||
return object instanceof Hash;
|
||||
},
|
||||
|
||||
isFunction: function(object) {
|
||||
return typeof object == "function";
|
||||
},
|
||||
|
||||
isString: function(object) {
|
||||
return typeof object == "string";
|
||||
},
|
||||
|
||||
isNumber: function(object) {
|
||||
return typeof object == "number";
|
||||
},
|
||||
|
||||
isUndefined: function(object) {
|
||||
return typeof object == "undefined";
|
||||
}
|
||||
});
|
||||
|
||||
Object.extend(Function.prototype, {
|
||||
argumentNames: function() {
|
||||
var names = this.toString().match(/^[\s\(]*function[^(]*\(([^\)]*)\)/)[1]
|
||||
.replace(/\s+/g, '').split(',');
|
||||
return names.length == 1 && !names[0] ? [] : names;
|
||||
},
|
||||
|
||||
bind: function() {
|
||||
if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this;
|
||||
var __method = this, args = $A(arguments), object = args.shift();
|
||||
return function() {
|
||||
return __method.apply(object, args.concat($A(arguments)));
|
||||
}
|
||||
},
|
||||
|
||||
bindAsEventListener: function() {
|
||||
var __method = this, args = $A(arguments), object = args.shift();
|
||||
return function(event) {
|
||||
return __method.apply(object, [event || window.event].concat(args));
|
||||
}
|
||||
},
|
||||
|
||||
curry: function() {
|
||||
if (!arguments.length) return this;
|
||||
var __method = this, args = $A(arguments);
|
||||
return function() {
|
||||
return __method.apply(this, args.concat($A(arguments)));
|
||||
}
|
||||
},
|
||||
|
||||
delay: function() {
|
||||
var __method = this, args = $A(arguments), timeout = args.shift() * 1000;
|
||||
return window.setTimeout(function() {
|
||||
return __method.apply(__method, args);
|
||||
}, timeout);
|
||||
},
|
||||
|
||||
defer: function() {
|
||||
var args = [0.01].concat($A(arguments));
|
||||
return this.delay.apply(this, args);
|
||||
},
|
||||
|
||||
wrap: function(wrapper) {
|
||||
var __method = this;
|
||||
return function() {
|
||||
return wrapper.apply(this, [__method.bind(this)].concat($A(arguments)));
|
||||
}
|
||||
},
|
||||
|
||||
methodize: function() {
|
||||
if (this._methodized) return this._methodized;
|
||||
var __method = this;
|
||||
return this._methodized = function() {
|
||||
return __method.apply(null, [this].concat($A(arguments)));
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
Date.prototype.toJSON = function() {
|
||||
return '"' + this.getUTCFullYear() + '-' +
|
||||
(this.getUTCMonth() + 1).toPaddedString(2) + '-' +
|
||||
this.getUTCDate().toPaddedString(2) + 'T' +
|
||||
this.getUTCHours().toPaddedString(2) + ':' +
|
||||
this.getUTCMinutes().toPaddedString(2) + ':' +
|
||||
this.getUTCSeconds().toPaddedString(2) + 'Z"';
|
||||
};
|
||||
|
||||
var Try = {
|
||||
these: function() {
|
||||
var returnValue;
|
||||
|
||||
for (var i = 0, length = arguments.length; i < length; i++) {
|
||||
var lambda = arguments[i];
|
||||
try {
|
||||
returnValue = lambda();
|
||||
break;
|
||||
} catch (e) { }
|
||||
}
|
||||
|
||||
return returnValue;
|
||||
}
|
||||
};
|
||||
|
||||
RegExp.prototype.match = RegExp.prototype.test;
|
||||
|
||||
RegExp.escape = function(str) {
|
||||
return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
|
||||
};
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
var PeriodicalExecuter = Class.create({
|
||||
initialize: function(callback, frequency) {
|
||||
this.callback = callback;
|
||||
this.frequency = frequency;
|
||||
this.currentlyExecuting = false;
|
||||
|
||||
this.registerCallback();
|
||||
},
|
||||
|
||||
registerCallback: function() {
|
||||
this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
|
||||
},
|
||||
|
||||
execute: function() {
|
||||
this.callback(this);
|
||||
},
|
||||
|
||||
stop: function() {
|
||||
if (!this.timer) return;
|
||||
clearInterval(this.timer);
|
||||
this.timer = null;
|
||||
},
|
||||
|
||||
onTimerEvent: function() {
|
||||
if (!this.currentlyExecuting) {
|
||||
try {
|
||||
this.currentlyExecuting = true;
|
||||
this.execute();
|
||||
} finally {
|
||||
this.currentlyExecuting = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
Object.extend(String, {
|
||||
interpret: function(value) {
|
||||
return value == null ? '' : String(value);
|
||||
},
|
||||
specialChar: {
|
||||
'\b': '\\b',
|
||||
'\t': '\\t',
|
||||
'\n': '\\n',
|
||||
'\f': '\\f',
|
||||
'\r': '\\r',
|
||||
'\\': '\\\\'
|
||||
}
|
||||
});
|
||||
|
||||
Object.extend(String.prototype, {
|
||||
gsub: function(pattern, replacement) {
|
||||
var result = '', source = this, match;
|
||||
replacement = arguments.callee.prepareReplacement(replacement);
|
||||
|
||||
while (source.length > 0) {
|
||||
if (match = source.match(pattern)) {
|
||||
result += source.slice(0, match.index);
|
||||
result += String.interpret(replacement(match));
|
||||
source = source.slice(match.index + match[0].length);
|
||||
} else {
|
||||
result += source, source = '';
|
||||
}
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
sub: function(pattern, replacement, count) {
|
||||
replacement = this.gsub.prepareReplacement(replacement);
|
||||
count = Object.isUndefined(count) ? 1 : count;
|
||||
|
||||
return this.gsub(pattern, function(match) {
|
||||
if (--count < 0) return match[0];
|
||||
return replacement(match);
|
||||
});
|
||||
},
|
||||
|
||||
scan: function(pattern, iterator) {
|
||||
this.gsub(pattern, iterator);
|
||||
return String(this);
|
||||
},
|
||||
|
||||
truncate: function(length, truncation) {
|
||||
length = length || 30;
|
||||
truncation = Object.isUndefined(truncation) ? '...' : truncation;
|
||||
return this.length > length ?
|
||||
this.slice(0, length - truncation.length) + truncation : String(this);
|
||||
},
|
||||
|
||||
strip: function() {
|
||||
return this.replace(/^\s+/, '').replace(/\s+$/, '');
|
||||
},
|
||||
|
||||
stripTags: function() {
|
||||
return this.replace(/<\/?[^>]+>/gi, '');
|
||||
},
|
||||
|
||||
stripScripts: function() {
|
||||
return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
|
||||
},
|
||||
|
||||
extractScripts: function() {
|
||||
var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
|
||||
var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
|
||||
return (this.match(matchAll) || []).map(function(scriptTag) {
|
||||
return (scriptTag.match(matchOne) || ['', ''])[1];
|
||||
});
|
||||
},
|
||||
|
||||
evalScripts: function() {
|
||||
return this.extractScripts().map(function(script) { return eval(script) });
|
||||
},
|
||||
|
||||
escapeHTML: function() {
|
||||
var self = arguments.callee;
|
||||
self.text.data = this;
|
||||
return self.div.innerHTML;
|
||||
},
|
||||
|
||||
unescapeHTML: function() {
|
||||
var div = new Element('div');
|
||||
div.innerHTML = this.stripTags();
|
||||
return div.childNodes[0] ? (div.childNodes.length > 1 ?
|
||||
$A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue }) :
|
||||
div.childNodes[0].nodeValue) : '';
|
||||
},
|
||||
|
||||
toQueryParams: function(separator) {
|
||||
var match = this.strip().match(/([^?#]*)(#.*)?$/);
|
||||
if (!match) return { };
|
||||
|
||||
return match[1].split(separator || '&').inject({ }, function(hash, pair) {
|
||||
if ((pair = pair.split('='))[0]) {
|
||||
var key = decodeURIComponent(pair.shift());
|
||||
var value = pair.length > 1 ? pair.join('=') : pair[0];
|
||||
if (value != undefined) value = decodeURIComponent(value);
|
||||
|
||||
if (key in hash) {
|
||||
if (!Object.isArray(hash[key])) hash[key] = [hash[key]];
|
||||
hash[key].push(value);
|
||||
}
|
||||
else hash[key] = value;
|
||||
}
|
||||
return hash;
|
||||
});
|
||||
},
|
||||
|
||||
toArray: function() {
|
||||
return this.split('');
|
||||
},
|
||||
|
||||
succ: function() {
|
||||
return this.slice(0, this.length - 1) +
|
||||
String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
|
||||
},
|
||||
|
||||
times: function(count) {
|
||||
return count < 1 ? '' : new Array(count + 1).join(this);
|
||||
},
|
||||
|
||||
camelize: function() {
|
||||
var parts = this.split('-'), len = parts.length;
|
||||
if (len == 1) return parts[0];
|
||||
|
||||
var camelized = this.charAt(0) == '-'
|
||||
? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
|
||||
: parts[0];
|
||||
|
||||
for (var i = 1; i < len; i++)
|
||||
camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
|
||||
|
||||
return camelized;
|
||||
},
|
||||
|
||||
capitalize: function() {
|
||||
return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
|
||||
},
|
||||
|
||||
underscore: function() {
|
||||
return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
|
||||
},
|
||||
|
||||
dasherize: function() {
|
||||
return this.gsub(/_/,'-');
|
||||
},
|
||||
|
||||
inspect: function(useDoubleQuotes) {
|
||||
var escapedString = this.gsub(/[\x00-\x1f\\]/, function(match) {
|
||||
var character = String.specialChar[match[0]];
|
||||
return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16);
|
||||
});
|
||||
if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"';
|
||||
return "'" + escapedString.replace(/'/g, '\\\'') + "'";
|
||||
},
|
||||
|
||||
toJSON: function() {
|
||||
return this.inspect(true);
|
||||
},
|
||||
|
||||
unfilterJSON: function(filter) {
|
||||
return this.sub(filter || Prototype.JSONFilter, '#{1}');
|
||||
},
|
||||
|
||||
isJSON: function() {
|
||||
var str = this;
|
||||
if (str.blank()) return false;
|
||||
str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
|
||||
return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
|
||||
},
|
||||
|
||||
evalJSON: function(sanitize) {
|
||||
var json = this.unfilterJSON();
|
||||
try {
|
||||
if (!sanitize || json.isJSON()) return eval('(' + json + ')');
|
||||
} catch (e) { }
|
||||
throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
|
||||
},
|
||||
|
||||
include: function(pattern) {
|
||||
return this.indexOf(pattern) > -1;
|
||||
},
|
||||
|
||||
startsWith: function(pattern) {
|
||||
return this.indexOf(pattern) === 0;
|
||||
},
|
||||
|
||||
endsWith: function(pattern) {
|
||||
var d = this.length - pattern.length;
|
||||
return d >= 0 && this.lastIndexOf(pattern) === d;
|
||||
},
|
||||
|
||||
empty: function() {
|
||||
return this == '';
|
||||
},
|
||||
|
||||
blank: function() {
|
||||
return /^\s*$/.test(this);
|
||||
},
|
||||
|
||||
interpolate: function(object, pattern) {
|
||||
return new Template(this, pattern).evaluate(object);
|
||||
}
|
||||
});
|
||||
|
||||
if (Prototype.Browser.WebKit || Prototype.Browser.IE) Object.extend(String.prototype, {
|
||||
escapeHTML: function() {
|
||||
return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
|
||||
},
|
||||
unescapeHTML: function() {
|
||||
return this.stripTags().replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
|
||||
}
|
||||
});
|
||||
|
||||
String.prototype.gsub.prepareReplacement = function(replacement) {
|
||||
if (Object.isFunction(replacement)) return replacement;
|
||||
var template = new Template(replacement);
|
||||
return function(match) { return template.evaluate(match) };
|
||||
};
|
||||
|
||||
String.prototype.parseQuery = String.prototype.toQueryParams;
|
||||
|
||||
Object.extend(String.prototype.escapeHTML, {
|
||||
div: document.createElement('div'),
|
||||
text: document.createTextNode('')
|
||||
});
|
||||
|
||||
String.prototype.escapeHTML.div.appendChild(String.prototype.escapeHTML.text);
|
||||
|
||||
var Template = Class.create({
|
||||
initialize: function(template, pattern) {
|
||||
this.template = template.toString();
|
||||
this.pattern = pattern || Template.Pattern;
|
||||
},
|
||||
|
||||
evaluate: function(object) {
|
||||
if (Object.isFunction(object.toTemplateReplacements))
|
||||
object = object.toTemplateReplacements();
|
||||
|
||||
return this.template.gsub(this.pattern, function(match) {
|
||||
if (object == null) return '';
|
||||
|
||||
var before = match[1] || '';
|
||||
if (before == '\\') return match[2];
|
||||
|
||||
var ctx = object, expr = match[3];
|
||||
var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;
|
||||
match = pattern.exec(expr);
|
||||
if (match == null) return before;
|
||||
|
||||
while (match != null) {
|
||||
var comp = match[1].startsWith('[') ? match[2].gsub('\\\\]', ']') : match[1];
|
||||
ctx = ctx[comp];
|
||||
if (null == ctx || '' == match[3]) break;
|
||||
expr = expr.substring('[' == match[3] ? match[1].length : match[0].length);
|
||||
match = pattern.exec(expr);
|
||||
}
|
||||
|
||||
return before + String.interpret(ctx);
|
||||
});
|
||||
}
|
||||
});
|
||||
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
|
||||
|
||||
var $break = { };
|
||||
|
||||
var Enumerable = {
|
||||
each: function(iterator, context) {
|
||||
var index = 0;
|
||||
try {
|
||||
this._each(function(value) {
|
||||
iterator.call(context, value, index++);
|
||||
});
|
||||
} catch (e) {
|
||||
if (e != $break) throw e;
|
||||
}
|
||||
return this;
|
||||
},
|
||||
|
||||
eachSlice: function(number, iterator, context) {
|
||||
var index = -number, slices = [], array = this.toArray();
|
||||
if (number < 1) return array;
|
||||
while ((index += number) < array.length)
|
||||
slices.push(array.slice(index, index+number));
|
||||
return slices.collect(iterator, context);
|
||||
},
|
||||
|
||||
all: function(iterator, context) {
|
||||
iterator = iterator || Prototype.K;
|
||||
var result = true;
|
||||
this.each(function(value, index) {
|
||||
result = result && !!iterator.call(context, value, index);
|
||||
if (!result) throw $break;
|
||||
});
|
||||
return result;
|
||||
},
|
||||
|
||||
any: function(iterator, context) {
|
||||
iterator = iterator || Prototype.K;
|
||||
var result = false;
|
||||
this.each(function(value, index) {
|
||||
if (result = !!iterator.call(context, value, index))
|
||||
throw $break;
|
||||
});
|
||||
return result;
|
||||
},
|
||||
|
||||
collect: function(iterator, context) {
|
||||
iterator = iterator || Prototype.K;
|
||||
var results = [];
|
||||
this.each(function(value, index) {
|
||||
results.push(iterator.call(context, value, index));
|
||||
});
|
||||
return results;
|
||||
},
|
||||
|
||||
detect: function(iterator, context) {
|
||||
var result;
|
||||
this.each(function(value, index) {
|
||||
if (iterator.call(context, value, index)) {
|
||||
result = value;
|
||||
throw $break;
|
||||
}
|
||||
});
|
||||
return result;
|
||||
},
|
||||
|
||||
findAll: function(iterator, context) {
|
||||
var results = [];
|
||||
this.each(function(value, index) {
|
||||
if (iterator.call(context, value, index))
|
||||
results.push(value);
|
||||
});
|
||||
return results;
|
||||
},
|
||||
|
||||
grep: function(filter, iterator, context) {
|
||||
iterator = iterator || Prototype.K;
|
||||
var results = [];
|
||||
|
||||
if (Object.isString(filter))
|
||||
filter = new RegExp(filter);
|
||||
|
||||
this.each(function(value, index) {
|
||||
if (filter.match(value))
|
||||
results.push(iterator.call(context, value, index));
|
||||
});
|
||||
return results;
|
||||
},
|
||||
|
||||
include: function(object) {
|
||||
if (Object.isFunction(this.indexOf))
|
||||
if (this.indexOf(object) != -1) return true;
|
||||
|
||||
var found = false;
|
||||
this.each(function(value) {
|
||||
if (value == object) {
|
||||
found = true;
|
||||
throw $break;
|
||||
}
|
||||
});
|
||||
return found;
|
||||
},
|
||||
|
||||
inGroupsOf: function(number, fillWith) {
|
||||
fillWith = Object.isUndefined(fillWith) ? null : fillWith;
|
||||
return this.eachSlice(number, function(slice) {
|
||||
while(slice.length < number) slice.push(fillWith);
|
||||
return slice;
|
||||
});
|
||||
},
|
||||
|
||||
inject: function(memo, iterator, context) {
|
||||
this.each(function(value, index) {
|
||||
memo = iterator.call(context, memo, value, index);
|
||||
});
|
||||
return memo;
|
||||
},
|
||||
|
||||
invoke: function(method) {
|
||||
var args = $A(arguments).slice(1);
|
||||
return this.map(function(value) {
|
||||
return value[method].apply(value, args);
|
||||
});
|
||||
},
|
||||
|
||||
max: function(iterator, context) {
|
||||
iterator = iterator || Prototype.K;
|
||||
var result;
|
||||
this.each(function(value, index) {
|
||||
value = iterator.call(context, value, index);
|
||||
if (result == null || value >= result)
|
||||
result = value;
|
||||
});
|
||||
return result;
|
||||
},
|
||||
|
||||
min: function(iterator, context) {
|
||||
iterator = iterator || Prototype.K;
|
||||
var result;
|
||||
this.each(function(value, index) {
|
||||
value = iterator.call(context, value, index);
|
||||
if (result == null || value < result)
|
||||
result = value;
|
||||
});
|
||||
return result;
|
||||
},
|
||||
|
||||
partition: function(iterator, context) {
|
||||
iterator = iterator || Prototype.K;
|
||||
var trues = [], falses = [];
|
||||
this.each(function(value, index) {
|
||||
(iterator.call(context, value, index) ?
|
||||
trues : falses).push(value);
|
||||
});
|
||||
return [trues, falses];
|
||||
},
|
||||
|
||||
pluck: function(property) {
|
||||
var results = [];
|
||||
this.each(function(value) {
|
||||
results.push(value[property]);
|
||||
});
|
||||
return results;
|
||||
},
|
||||
|
||||
reject: function(iterator, context) {
|
||||
var results = [];
|
||||
this.each(function(value, index) {
|
||||
if (!iterator.call(context, value, index))
|
||||
results.push(value);
|
||||
});
|
||||
return results;
|
||||
},
|
||||
|
||||
sortBy: function(iterator, context) {
|
||||
return this.map(function(value, index) {
|
||||
return {
|
||||
value: value,
|
||||
criteria: iterator.call(context, value, index)
|
||||
};
|
||||
}).sort(function(left, right) {
|
||||
var a = left.criteria, b = right.criteria;
|
||||
return a < b ? -1 : a > b ? 1 : 0;
|
||||
}).pluck('value');
|
||||
},
|
||||
|
||||
toArray: function() {
|
||||
return this.map();
|
||||
},
|
||||
|
||||
zip: function() {
|
||||
var iterator = Prototype.K, args = $A(arguments);
|
||||
if (Object.isFunction(args.last()))
|
||||
iterator = args.pop();
|
||||
|
||||
var collections = [this].concat(args).map($A);
|
||||
return this.map(function(value, index) {
|
||||
return iterator(collections.pluck(index));
|
||||
});
|
||||
},
|
||||
|
||||
size: function() {
|
||||
return this.toArray().length;
|
||||
},
|
||||
|
||||
inspect: function() {
|
||||
return '#<Enumerable:' + this.toArray().inspect() + '>';
|
||||
}
|
||||
};
|
||||
|
||||
Object.extend(Enumerable, {
|
||||
map: Enumerable.collect,
|
||||
find: Enumerable.detect,
|
||||
select: Enumerable.findAll,
|
||||
filter: Enumerable.findAll,
|
||||
member: Enumerable.include,
|
||||
entries: Enumerable.toArray,
|
||||
every: Enumerable.all,
|
||||
some: Enumerable.any
|
||||
});
|
||||
function $A(iterable) {
|
||||
if (!iterable) return [];
|
||||
if (iterable.toArray) return iterable.toArray();
|
||||
var length = iterable.length || 0, results = new Array(length);
|
||||
while (length--) results[length] = iterable[length];
|
||||
return results;
|
||||
}
|
||||
|
||||
if (Prototype.Browser.WebKit) {
|
||||
$A = function(iterable) {
|
||||
if (!iterable) return [];
|
||||
// In Safari, only use the `toArray` method if it's not a NodeList.
|
||||
// A NodeList is a function, has an function `item` property, and a numeric
|
||||
// `length` property. Adapted from Google Doctype.
|
||||
if (!(typeof iterable === 'function' && typeof iterable.length ===
|
||||
'number' && typeof iterable.item === 'function') && iterable.toArray)
|
||||
return iterable.toArray();
|
||||
var length = iterable.length || 0, results = new Array(length);
|
||||
while (length--) results[length] = iterable[length];
|
||||
return results;
|
||||
};
|
||||
}
|
||||
|
||||
Array.from = $A;
|
||||
|
||||
Object.extend(Array.prototype, Enumerable);
|
||||
|
||||
if (!Array.prototype._reverse) Array.prototype._reverse = Array.prototype.reverse;
|
||||
|
||||
Object.extend(Array.prototype, {
|
||||
_each: function(iterator) {
|
||||
for (var i = 0, length = this.length; i < length; i++)
|
||||
iterator(this[i]);
|
||||
},
|
||||
|
||||
clear: function() {
|
||||
this.length = 0;
|
||||
return this;
|
||||
},
|
||||
|
||||
first: function() {
|
||||
return this[0];
|
||||
},
|
||||
|
||||
last: function() {
|
||||
return this[this.length - 1];
|
||||
},
|
||||
|
||||
compact: function() {
|
||||
return this.select(function(value) {
|
||||
return value != null;
|
||||
});
|
||||
},
|
||||
|
||||
flatten: function() {
|
||||
return this.inject([], function(array, value) {
|
||||
return array.concat(Object.isArray(value) ?
|
||||
value.flatten() : [value]);
|
||||
});
|
||||
},
|
||||
|
||||
without: function() {
|
||||
var values = $A(arguments);
|
||||
return this.select(function(value) {
|
||||
return !values.include(value);
|
||||
});
|
||||
},
|
||||
|
||||
reverse: function(inline) {
|
||||
return (inline !== false ? this : this.toArray())._reverse();
|
||||
},
|
||||
|
||||
reduce: function() {
|
||||
return this.length > 1 ? this : this[0];
|
||||
},
|
||||
|
||||
uniq: function(sorted) {
|
||||
return this.inject([], function(array, value, index) {
|
||||
if (0 == index || (sorted ? array.last() != value : !array.include(value)))
|
||||
array.push(value);
|
||||
return array;
|
||||
});
|
||||
},
|
||||
|
||||
intersect: function(array) {
|
||||
return this.uniq().findAll(function(item) {
|
||||
return array.detect(function(value) { return item === value });
|
||||
});
|
||||
},
|
||||
|
||||
clone: function() {
|
||||
return [].concat(this);
|
||||
},
|
||||
|
||||
size: function() {
|
||||
return this.length;
|
||||
},
|
||||
|
||||
inspect: function() {
|
||||
return '[' + this.map(Object.inspect).join(', ') + ']';
|
||||
},
|
||||
|
||||
toJSON: function() {
|
||||
var results = [];
|
||||
this.each(function(object) {
|
||||
var value = Object.toJSON(object);
|
||||
if (!Object.isUndefined(value)) results.push(value);
|
||||
});
|
||||
return '[' + results.join(', ') + ']';
|
||||
}
|
||||
});
|
||||
|
||||
// use native browser JS 1.6 implementation if available
|
||||
if (Object.isFunction(Array.prototype.forEach))
|
||||
Array.prototype._each = Array.prototype.forEach;
|
||||
|
||||
if (!Array.prototype.indexOf) Array.prototype.indexOf = function(item, i) {
|
||||
i || (i = 0);
|
||||
var length = this.length;
|
||||
if (i < 0) i = length + i;
|
||||
for (; i < length; i++)
|
||||
if (this[i] === item) return i;
|
||||
return -1;
|
||||
};
|
||||
|
||||
if (!Array.prototype.lastIndexOf) Array.prototype.lastIndexOf = function(item, i) {
|
||||
i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1;
|
||||
var n = this.slice(0, i).reverse().indexOf(item);
|
||||
return (n < 0) ? n : i - n - 1;
|
||||
};
|
||||
|
||||
Array.prototype.toArray = Array.prototype.clone;
|
||||
|
||||
function $w(string) {
|
||||
if (!Object.isString(string)) return [];
|
||||
string = string.strip();
|
||||
return string ? string.split(/\s+/) : [];
|
||||
}
|
||||
|
||||
if (Prototype.Browser.Opera){
|
||||
Array.prototype.concat = function() {
|
||||
var array = [];
|
||||
for (var i = 0, length = this.length; i < length; i++) array.push(this[i]);
|
||||
for (var i = 0, length = arguments.length; i < length; i++) {
|
||||
if (Object.isArray(arguments[i])) {
|
||||
for (var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
|
||||
array.push(arguments[i][j]);
|
||||
} else {
|
||||
array.push(arguments[i]);
|
||||
}
|
||||
}
|
||||
return array;
|
||||
};
|
||||
}
|
||||
Object.extend(Number.prototype, {
|
||||
toColorPart: function() {
|
||||
return this.toPaddedString(2, 16);
|
||||
},
|
||||
|
||||
succ: function() {
|
||||
return this + 1;
|
||||
},
|
||||
|
||||
times: function(iterator, context) {
|
||||
$R(0, this, true).each(iterator, context);
|
||||
return this;
|
||||
},
|
||||
|
||||
toPaddedString: function(length, radix) {
|
||||
var string = this.toString(radix || 10);
|
||||
return '0'.times(length - string.length) + string;
|
||||
},
|
||||
|
||||
toJSON: function() {
|
||||
return isFinite(this) ? this.toString() : 'null';
|
||||
}
|
||||
});
|
||||
|
||||
$w('abs round ceil floor').each(function(method){
|
||||
Number.prototype[method] = Math[method].methodize();
|
||||
});
|
||||
function $H(object) {
|
||||
return new Hash(object);
|
||||
};
|
||||
|
||||
var Hash = Class.create(Enumerable, (function() {
|
||||
|
||||
function toQueryPair(key, value) {
|
||||
if (Object.isUndefined(value)) return key;
|
||||
return key + '=' + encodeURIComponent(String.interpret(value));
|
||||
}
|
||||
|
||||
return {
|
||||
initialize: function(object) {
|
||||
this._object = Object.isHash(object) ? object.toObject() : Object.clone(object);
|
||||
},
|
||||
|
||||
_each: function(iterator) {
|
||||
for (var key in this._object) {
|
||||
var value = this._object[key], pair = [key, value];
|
||||
pair.key = key;
|
||||
pair.value = value;
|
||||
iterator(pair);
|
||||
}
|
||||
},
|
||||
|
||||
set: function(key, value) {
|
||||
return this._object[key] = value;
|
||||
},
|
||||
|
||||
get: function(key) {
|
||||
// simulating poorly supported hasOwnProperty
|
||||
if (this._object[key] !== Object.prototype[key])
|
||||
return this._object[key];
|
||||
},
|
||||
|
||||
unset: function(key) {
|
||||
var value = this._object[key];
|
||||
delete this._object[key];
|
||||
return value;
|
||||
},
|
||||
|
||||
toObject: function() {
|
||||
return Object.clone(this._object);
|
||||
},
|
||||
|
||||
keys: function() {
|
||||
return this.pluck('key');
|
||||
},
|
||||
|
||||
values: function() {
|
||||
return this.pluck('value');
|
||||
},
|
||||
|
||||
index: function(value) {
|
||||
var match = this.detect(function(pair) {
|
||||
return pair.value === value;
|
||||
});
|
||||
return match && match.key;
|
||||
},
|
||||
|
||||
merge: function(object) {
|
||||
return this.clone().update(object);
|
||||
},
|
||||
|
||||
update: function(object) {
|
||||
return new Hash(object).inject(this, function(result, pair) {
|
||||
result.set(pair.key, pair.value);
|
||||
return result;
|
||||
});
|
||||
},
|
||||
|
||||
toQueryString: function() {
|
||||
return this.inject([], function(results, pair) {
|
||||
var key = encodeURIComponent(pair.key), values = pair.value;
|
||||
|
||||
if (values && typeof values == 'object') {
|
||||
if (Object.isArray(values))
|
||||
return results.concat(values.map(toQueryPair.curry(key)));
|
||||
} else results.push(toQueryPair(key, values));
|
||||
return results;
|
||||
}).join('&');
|
||||
},
|
||||
|
||||
inspect: function() {
|
||||
return '#<Hash:{' + this.map(function(pair) {
|
||||
return pair.map(Object.inspect).join(': ');
|
||||
}).join(', ') + '}>';
|
||||
},
|
||||
|
||||
toJSON: function() {
|
||||
return Object.toJSON(this.toObject());
|
||||
},
|
||||
|
||||
clone: function() {
|
||||
return new Hash(this);
|
||||
}
|
||||
}
|
||||
})());
|
||||
|
||||
Hash.prototype.toTemplateReplacements = Hash.prototype.toObject;
|
||||
Hash.from = $H;
|
||||
var ObjectRange = Class.create(Enumerable, {
|
||||
initialize: function(start, end, exclusive) {
|
||||
this.start = start;
|
||||
this.end = end;
|
||||
this.exclusive = exclusive;
|
||||
},
|
||||
|
||||
_each: function(iterator) {
|
||||
var value = this.start;
|
||||
while (this.include(value)) {
|
||||
iterator(value);
|
||||
value = value.succ();
|
||||
}
|
||||
},
|
||||
|
||||
include: function(value) {
|
||||
if (value < this.start)
|
||||
return false;
|
||||
if (this.exclusive)
|
||||
return value < this.end;
|
||||
return value <= this.end;
|
||||
}
|
||||
});
|
||||
|
||||
var $R = function(start, end, exclusive) {
|
||||
return new ObjectRange(start, end, exclusive);
|
||||
};
|
||||
|
||||
var Ajax = {
|
||||
getTransport: function() {
|
||||
return Try.these(
|
||||
function() {return new XMLHttpRequest()},
|
||||
function() {return new ActiveXObject('Msxml2.XMLHTTP')},
|
||||
function() {return new ActiveXObject('Microsoft.XMLHTTP')}
|
||||
) || false;
|
||||
},
|
||||
|
||||
activeRequestCount: 0
|
||||
};
|
||||
|
||||
Ajax.Responders = {
|
||||
responders: [],
|
||||
|
||||
_each: function(iterator) {
|
||||
this.responders._each(iterator);
|
||||
},
|
||||
|
||||
register: function(responder) {
|
||||
if (!this.include(responder))
|
||||
this.responders.push(responder);
|
||||
},
|
||||
|
||||
unregister: function(responder) {
|
||||
this.responders = this.responders.without(responder);
|
||||
},
|
||||
|
||||
dispatch: function(callback, request, transport, json) {
|
||||
this.each(function(responder) {
|
||||
if (Object.isFunction(responder[callback])) {
|
||||
try {
|
||||
responder[callback].apply(responder, [request, transport, json]);
|
||||
} catch (e) { }
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
Object.extend(Ajax.Responders, Enumerable);
|
||||
|
||||
Ajax.Responders.register({
|
||||
onCreate: function() { Ajax.activeRequestCount++ },
|
||||
onComplete: function() { Ajax.activeRequestCount-- }
|
||||
});
|
||||
|
||||
Ajax.Base = Class.create({
|
||||
initialize: function(options) {
|
||||
this.options = {
|
||||
method: 'post',
|
||||
asynchronous: true,
|
||||
contentType: 'application/x-www-form-urlencoded',
|
||||
encoding: 'UTF-8',
|
||||
parameters: '',
|
||||
evalJSON: true,
|
||||
evalJS: true
|
||||
};
|
||||
Object.extend(this.options, options || { });
|
||||
|
||||
this.options.method = this.options.method.toLowerCase();
|
||||
|
||||
if (Object.isString(this.options.parameters))
|
||||
this.options.parameters = this.options.parameters.toQueryParams();
|
||||
else if (Object.isHash(this.options.parameters))
|
||||
this.options.parameters = this.options.parameters.toObject();
|
||||
}
|
||||
});
|
||||
|
||||
Ajax.Request = Class.create(Ajax.Base, {
|
||||
_complete: false,
|
||||
|
||||
initialize: function($super, url, options) {
|
||||
$super(options);
|
||||
this.transport = Ajax.getTransport();
|
||||
this.request(url);
|
||||
},
|
||||
|
||||
request: function(url) {
|
||||
this.url = url;
|
||||
this.method = this.options.method;
|
||||
var params = Object.clone(this.options.parameters);
|
||||
|
||||
if (!['get', 'post'].include(this.method)) {
|
||||
// simulate other verbs over post
|
||||
params['_method'] = this.method;
|
||||
this.method = 'post';
|
||||
}
|
||||
|
||||
this.parameters = params;
|
||||
|
||||
if (params = Object.toQueryString(params)) {
|
||||
// when GET, append parameters to URL
|
||||
if (this.method == 'get')
|
||||
this.url += (this.url.include('?') ? '&' : '?') + params;
|
||||
else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent))
|
||||
params += '&_=';
|
||||
}
|
||||
|
||||
try {
|
||||
var response = new Ajax.Response(this);
|
||||
if (this.options.onCreate) this.options.onCreate(response);
|
||||
Ajax.Responders.dispatch('onCreate', this, response);
|
||||
|
||||
this.transport.open(this.method.toUpperCase(), this.url,
|
||||
this.options.asynchronous);
|
||||
|
||||
if (this.options.asynchronous) this.respondToReadyState.bind(this).defer(1);
|
||||
|
||||
this.transport.onreadystatechange = this.onStateChange.bind(this);
|
||||
this.setRequestHeaders();
|
||||
|
||||
this.body = this.method == 'post' ? (this.options.postBody || params) : null;
|
||||
this.transport.send(this.body);
|
||||
|
||||
/* Force Firefox to handle ready state 4 for synchronous requests */
|
||||
if (!this.options.asynchronous && this.transport.overrideMimeType)
|
||||
this.onStateChange();
|
||||
|
||||
}
|
||||
catch (e) {
|
||||
this.dispatchException(e);
|
||||
}
|
||||
},
|
||||
|
||||
onStateChange: function() {
|
||||
var readyState = this.transport.readyState;
|
||||
if (readyState > 1 && !((readyState == 4) && this._complete))
|
||||
this.respondToReadyState(this.transport.readyState);
|
||||
},
|
||||
|
||||
setRequestHeaders: function() {
|
||||
var headers = {
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
'X-Prototype-Version': Prototype.Version,
|
||||
'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
|
||||
};
|
||||
|
||||
if (this.method == 'post') {
|
||||
headers['Content-type'] = this.options.contentType +
|
||||
(this.options.encoding ? '; charset=' + this.options.encoding : '');
|
||||
|
||||
/* Force "Connection: close" for older Mozilla browsers to work
|
||||
* around a bug where XMLHttpRequest sends an incorrect
|
||||
* Content-length header. See Mozilla Bugzilla #246651.
|
||||
*/
|
||||
if (this.transport.overrideMimeType &&
|
||||
(navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
|
||||
headers['Connection'] = 'close';
|
||||
}
|
||||
|
||||
// user-defined headers
|
||||
if (typeof this.options.requestHeaders == 'object') {
|
||||
var extras = this.options.requestHeaders;
|
||||
|
||||
if (Object.isFunction(extras.push))
|
||||
for (var i = 0, length = extras.length; i < length; i += 2)
|
||||
headers[extras[i]] = extras[i+1];
|
||||
else
|
||||
$H(extras).each(function(pair) { headers[pair.key] = pair.value });
|
||||
}
|
||||
|
||||
for (var name in headers)
|
||||
this.transport.setRequestHeader(name, headers[name]);
|
||||
},
|
||||
|
||||
success: function() {
|
||||
var status = this.getStatus();
|
||||
return !status || (status >= 200 && status < 300);
|
||||
},
|
||||
|
||||
getStatus: function() {
|
||||
try {
|
||||
return this.transport.status || 0;
|
||||
} catch (e) { return 0 }
|
||||
},
|
||||
|
||||
respondToReadyState: function(readyState) {
|
||||
var state = Ajax.Request.Events[readyState], response = new Ajax.Response(this);
|
||||
|
||||
if (state == 'Complete') {
|
||||
try {
|
||||
this._complete = true;
|
||||
(this.options['on' + response.status]
|
||||
|| this.options['on' + (this.success() ? 'Success' : 'Failure')]
|
||||
|| Prototype.emptyFunction)(response, response.headerJSON);
|
||||
} catch (e) {
|
||||
this.dispatchException(e);
|
||||
}
|
||||
|
||||
var contentType = response.getHeader('Content-type');
|
||||
if (this.options.evalJS == 'force'
|
||||
|| (this.options.evalJS && this.isSameOrigin() && contentType
|
||||
&& contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i)))
|
||||
this.evalResponse();
|
||||
}
|
||||
|
||||
try {
|
||||
(this.options['on' + state] || Prototype.emptyFunction)(response, response.headerJSON);
|
||||
Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON);
|
||||
} catch (e) {
|
||||
this.dispatchException(e);
|
||||
}
|
||||
|
||||
if (state == 'Complete') {
|
||||
// avoid memory leak in MSIE: clean up
|
||||
this.transport.onreadystatechange = Prototype.emptyFunction;
|
||||
}
|
||||
},
|
||||
|
||||
isSameOrigin: function() {
|
||||
var m = this.url.match(/^\s*https?:\/\/[^\/]*/);
|
||||
return !m || (m[0] == '#{protocol}//#{domain}#{port}'.interpolate({
|
||||
protocol: location.protocol,
|
||||
domain: document.domain,
|
||||
port: location.port ? ':' + location.port : ''
|
||||
}));
|
||||
},
|
||||
|
||||
getHeader: function(name) {
|
||||
try {
|
||||
return this.transport.getResponseHeader(name) || null;
|
||||
} catch (e) { return null }
|
||||
},
|
||||
|
||||
evalResponse: function() {
|
||||
try {
|
||||
return eval((this.transport.responseText || '').unfilterJSON());
|
||||
} catch (e) {
|
||||
this.dispatchException(e);
|
||||
}
|
||||
},
|
||||
|
||||
dispatchException: function(exception) {
|
||||
(this.options.onException || Prototype.emptyFunction)(this, exception);
|
||||
Ajax.Responders.dispatch('onException', this, exception);
|
||||
}
|
||||
});
|
||||
|
||||
Ajax.Request.Events =
|
||||
['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];
|
||||
|
||||
Ajax.Response = Class.create({
|
||||
initialize: function(request){
|
||||
this.request = request;
|
||||
var transport = this.transport = request.transport,
|
||||
readyState = this.readyState = transport.readyState;
|
||||
|
||||
if((readyState > 2 && !Prototype.Browser.IE) || readyState == 4) {
|
||||
this.status = this.getStatus();
|
||||
this.statusText = this.getStatusText();
|
||||
this.responseText = String.interpret(transport.responseText);
|
||||
this.headerJSON = this._getHeaderJSON();
|
||||
}
|
||||
|
||||
if(readyState == 4) {
|
||||
var xml = transport.responseXML;
|
||||
this.responseXML = Object.isUndefined(xml) ? null : xml;
|
||||
this.responseJSON = this._getResponseJSON();
|
||||
}
|
||||
},
|
||||
|
||||
status: 0,
|
||||
statusText: '',
|
||||
|
||||
getStatus: Ajax.Request.prototype.getStatus,
|
||||
|
||||
getStatusText: function() {
|
||||
try {
|
||||
return this.transport.statusText || '';
|
||||
} catch (e) { return '' }
|
||||
},
|
||||
|
||||
getHeader: Ajax.Request.prototype.getHeader,
|
||||
|
||||
getAllHeaders: function() {
|
||||
try {
|
||||
return this.getAllResponseHeaders();
|
||||
} catch (e) { return null }
|
||||
},
|
||||
|
||||
getResponseHeader: function(name) {
|
||||
return this.transport.getResponseHeader(name);
|
||||
},
|
||||
|
||||
getAllResponseHeaders: function() {
|
||||
return this.transport.getAllResponseHeaders();
|
||||
},
|
||||
|
||||
_getHeaderJSON: function() {
|
||||
var json = this.getHeader('X-JSON');
|
||||
if (!json) return null;
|
||||
json = decodeURIComponent(escape(json));
|
||||
try {
|
||||
return json.evalJSON(this.request.options.sanitizeJSON ||
|
||||
!this.request.isSameOrigin());
|
||||
} catch (e) {
|
||||
this.request.dispatchException(e);
|
||||
}
|
||||
},
|
||||
|
||||
_getResponseJSON: function() {
|
||||
var options = this.request.options;
|
||||
if (!options.evalJSON || (options.evalJSON != 'force' &&
|
||||
!(this.getHeader('Content-type') || '').include('application/json')) ||
|
||||
this.responseText.blank())
|
||||
return null;
|
||||
try {
|
||||
return this.responseText.evalJSON(options.sanitizeJSON ||
|
||||
!this.request.isSameOrigin());
|
||||
} catch (e) {
|
||||
this.request.dispatchException(e);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ajax.Updater = Class.create(Ajax.Request, {
|
||||
initialize: function($super, container, url, options) {
|
||||
this.container = {
|
||||
success: (container.success || container),
|
||||
failure: (container.failure || (container.success ? null : container))
|
||||
};
|
||||
|
||||
options = Object.clone(options);
|
||||
var onComplete = options.onComplete;
|
||||
options.onComplete = (function(response, json) {
|
||||
this.updateContent(response.responseText);
|
||||
if (Object.isFunction(onComplete)) onComplete(response, json);
|
||||
}).bind(this);
|
||||
|
||||
$super(url, options);
|
||||
},
|
||||
|
||||
updateContent: function(responseText) {
|
||||
var receiver = this.container[this.success() ? 'success' : 'failure'],
|
||||
options = this.options;
|
||||
|
||||
if (!options.evalScripts) responseText = responseText.stripScripts();
|
||||
|
||||
if (receiver = $(receiver)) {
|
||||
if (options.insertion) {
|
||||
if (Object.isString(options.insertion)) {
|
||||
var insertion = { }; insertion[options.insertion] = responseText;
|
||||
receiver.insert(insertion);
|
||||
}
|
||||
else options.insertion(receiver, responseText);
|
||||
}
|
||||
else receiver.update(responseText);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ajax.PeriodicalUpdater = Class.create(Ajax.Base, {
|
||||
initialize: function($super, container, url, options) {
|
||||
$super(options);
|
||||
this.onComplete = this.options.onComplete;
|
||||
|
||||
this.frequency = (this.options.frequency || 2);
|
||||
this.decay = (this.options.decay || 1);
|
||||
|
||||
this.updater = { };
|
||||
this.container = container;
|
||||
this.url = url;
|
||||
|
||||
this.start();
|
||||
},
|
||||
|
||||
start: function() {
|
||||
this.options.onComplete = this.updateComplete.bind(this);
|
||||
this.onTimerEvent();
|
||||
},
|
||||
|
||||
stop: function() {
|
||||
this.updater.options.onComplete = undefined;
|
||||
clearTimeout(this.timer);
|
||||
(this.onComplete || Prototype.emptyFunction).apply(this, arguments);
|
||||
},
|
||||
|
||||
updateComplete: function(response) {
|
||||
if (this.options.decay) {
|
||||
this.decay = (response.responseText == this.lastText ?
|
||||
this.decay * this.options.decay : 1);
|
||||
|
||||
this.lastText = response.responseText;
|
||||
}
|
||||
this.timer = this.onTimerEvent.bind(this).delay(this.decay * this.frequency);
|
||||
},
|
||||
|
||||
onTimerEvent: function() {
|
||||
this.updater = new Ajax.Updater(this.container, this.url, this.options);
|
||||
}
|
||||
});
|
||||
function $(element) {
|
||||
if (arguments.length > 1) {
|
||||
for (var i = 0, elements = [], length = arguments.length; i < length; i++)
|
||||
elements.push($(arguments[i]));
|
||||
return elements;
|
||||
}
|
||||
if (Object.isString(element))
|
||||
element = document.getElementById(element);
|
||||
return Element.extend(element);
|
||||
}
|
||||
|
||||
if (Prototype.BrowserFeatures.XPath) {
|
||||
document._getElementsByXPath = function(expression, parentElement) {
|
||||
var results = [];
|
||||
var query = document.evaluate(expression, $(parentElement) || document,
|
||||
null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
|
||||
for (var i = 0, length = query.snapshotLength; i < length; i++)
|
||||
results.push(Element.extend(query.snapshotItem(i)));
|
||||
return results;
|
||||
};
|
||||
}
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
if (!window.Node) var Node = { };
|
||||
|
||||
if (!Node.ELEMENT_NODE) {
|
||||
// DOM level 2 ECMAScript Language Binding
|
||||
Object.extend(Node, {
|
||||
ELEMENT_NODE: 1,
|
||||
ATTRIBUTE_NODE: 2,
|
||||
TEXT_NODE: 3,
|
||||
CDATA_SECTION_NODE: 4,
|
||||
ENTITY_REFERENCE_NODE: 5,
|
||||
ENTITY_NODE: 6,
|
||||
PROCESSING_INSTRUCTION_NODE: 7,
|
||||
COMMENT_NODE: 8,
|
||||
DOCUMENT_NODE: 9,
|
||||
DOCUMENT_TYPE_NODE: 10,
|
||||
DOCUMENT_FRAGMENT_NODE: 11,
|
||||
NOTATION_NODE: 12
|
||||
});
|
||||
}
|
||||
|
||||
(function() {
|
||||
var element = this.Element;
|
||||
this.Element = function(tagName, attributes) {
|
||||
attributes = attributes || { };
|
||||
tagName = tagName.toLowerCase();
|
||||
var cache = Element.cache;
|
||||
if (Prototype.Browser.IE && attributes.name) {
|
||||
tagName = '<' + tagName + ' name="' + attributes.name + '">';
|
||||
delete attributes.name;
|
||||
return Element.writeAttribute(document.createElement(tagName), attributes);
|
||||
}
|
||||
if (!cache[tagName]) cache[tagName] = Element.extend(document.createElement(tagName));
|
||||
return Element.writeAttribute(cache[tagName].cloneNode(false), attributes);
|
||||
};
|
||||
Object.extend(this.Element, element || { });
|
||||
if (element) this.Element.prototype = element.prototype;
|
||||
}).call(window);
|
||||
|
||||
Element.cache = { };
|
||||
|
||||
Element.Methods = {
|
||||
visible: function(element) {
|
||||
return $(element).style.display != 'none';
|
||||
},
|
||||
|
||||
toggle: function(element) {
|
||||
element = $(element);
|
||||
Element[Element.visible(element) ? 'hide' : 'show'](element);
|
||||
return element;
|
||||
},
|
||||
|
||||
hide: function(element) {
|
||||
element = $(element);
|
||||
element.style.display = 'none';
|
||||
return element;
|
||||
},
|
||||
|
||||
show: function(element) {
|
||||
element = $(element);
|
||||
element.style.display = '';
|
||||
return element;
|
||||
},
|
||||
|
||||
remove: function(element) {
|
||||
element = $(element);
|
||||
element.parentNode.removeChild(element);
|
||||
return element;
|
||||
},
|
||||
|
||||
update: function(element, content) {
|
||||
element = $(element);
|
||||
if (content && content.toElement) content = content.toElement();
|
||||
if (Object.isElement(content)) return element.update().insert(content);
|
||||
content = Object.toHTML(content);
|
||||
element.innerHTML = content.stripScripts();
|
||||
content.evalScripts.bind(content).defer();
|
||||
return element;
|
||||
},
|
||||
|
||||
replace: function(element, content) {
|
||||
element = $(element);
|
||||
if (content && content.toElement) content = content.toElement();
|
||||
else if (!Object.isElement(content)) {
|
||||
content = Object.toHTML(content);
|
||||
var range = element.ownerDocument.createRange();
|
||||
range.selectNode(element);
|
||||
content.evalScripts.bind(content).defer();
|
||||
content = range.createContextualFragment(content.stripScripts());
|
||||
}
|
||||
element.parentNode.replaceChild(content, element);
|
||||
return element;
|
||||
},
|
||||
|
||||
insert: function(element, insertions) {
|
||||
element = $(element);
|
||||
|
||||
if (Object.isString(insertions) || Object.isNumber(insertions) ||
|
||||
Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML)))
|
||||
insertions = {bottom:insertions};
|
||||
|
||||
var content, insert, tagName, childNodes;
|
||||
|
||||
for (var position in insertions) {
|
||||
content = insertions[position];
|
||||
position = position.toLowerCase();
|
||||
insert = Element._insertionTranslations[position];
|
||||
|
||||
if (content && content.toElement) content = content.toElement();
|
||||
if (Object.isElement(content)) {
|
||||
insert(element, content);
|
||||
continue;
|
||||
}
|
||||
|
||||
content = Object.toHTML(content);
|
||||
|
||||
tagName = ((position == 'before' || position == 'after')
|
||||
? element.parentNode : element).tagName.toUpperCase();
|
||||
|
||||
childNodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
|
||||
|
||||
if (position == 'top' || position == 'after') childNodes.reverse();
|
||||
childNodes.each(insert.curry(element));
|
||||
|
||||
content.evalScripts.bind(content).defer();
|
||||
}
|
||||
|
||||
return element;
|
||||
},
|
||||
|
||||
wrap: function(element, wrapper, attributes) {
|
||||
element = $(element);
|
||||
if (Object.isElement(wrapper))
|
||||
$(wrapper).writeAttribute(attributes || { });
|
||||
else if (Object.isString(wrapper)) wrapper = new Element(wrapper, attributes);
|
||||
else wrapper = new Element('div', wrapper);
|
||||
if (element.parentNode)
|
||||
element.parentNode.replaceChild(wrapper, element);
|
||||
wrapper.appendChild(element);
|
||||
return wrapper;
|
||||
},
|
||||
|
||||
inspect: function(element) {
|
||||
element = $(element);
|
||||
var result = '<' + element.tagName.toLowerCase();
|
||||
$H({'id': 'id', 'className': 'class'}).each(function(pair) {
|
||||
var property = pair.first(), attribute = pair.last();
|
||||
var value = (element[property] || '').toString();
|
||||
if (value) result += ' ' + attribute + '=' + value.inspect(true);
|
||||
});
|
||||
return result + '>';
|
||||
},
|
||||
|
||||
recursivelyCollect: function(element, property) {
|
||||
element = $(element);
|
||||
var elements = [];
|
||||
while (element = element[property])
|
||||
if (element.nodeType == 1)
|
||||
elements.push(Element.extend(element));
|
||||
return elements;
|
||||
},
|
||||
|
||||
ancestors: function(element) {
|
||||
return $(element).recursivelyCollect('parentNode');
|
||||
},
|
||||
|
||||
descendants: function(element) {
|
||||
return $(element).select("*");
|
||||
},
|
||||
|
||||
firstDescendant: function(element) {
|
||||
element = $(element).firstChild;
|
||||
while (element && element.nodeType != 1) element = element.nextSibling;
|
||||
return $(element);
|
||||
},
|
||||
|
||||
immediateDescendants: function(element) {
|
||||
if (!(element = $(element).firstChild)) return [];
|
||||
while (element && element.nodeType != 1) element = element.nextSibling;
|
||||
if (element) return [element].concat($(element).nextSiblings());
|
||||
return [];
|
||||
},
|
||||
|
||||
previousSiblings: function(element) {
|
||||
return $(element).recursivelyCollect('previousSibling');
|
||||
},
|
||||
|
||||
nextSiblings: function(element) {
|
||||
return $(element).recursivelyCollect('nextSibling');
|
||||
},
|
||||
|
||||
siblings: function(element) {
|
||||
element = $(element);
|
||||
return element.previousSiblings().reverse().concat(element.nextSiblings());
|
||||
},
|
||||
|
||||
match: function(element, selector) {
|
||||
if (Object.isString(selector))
|
||||
selector = new Selector(selector);
|
||||
return selector.match($(element));
|
||||
},
|
||||
|
||||
up: function(element, expression, index) {
|
||||
element = $(element);
|
||||
if (arguments.length == 1) return $(element.parentNode);
|
||||
var ancestors = element.ancestors();
|
||||
return Object.isNumber(expression) ? ancestors[expression] :
|
||||
Selector.findElement(ancestors, expression, index);
|
||||
},
|
||||
|
||||
down: function(element, expression, index) {
|
||||
element = $(element);
|
||||
if (arguments.length == 1) return element.firstDescendant();
|
||||
return Object.isNumber(expression) ? element.descendants()[expression] :
|
||||
Element.select(element, expression)[index || 0];
|
||||
},
|
||||
|
||||
previous: function(element, expression, index) {
|
||||
element = $(element);
|
||||
if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element));
|
||||
var previousSiblings = element.previousSiblings();
|
||||
return Object.isNumber(expression) ? previousSiblings[expression] :
|
||||
Selector.findElement(previousSiblings, expression, index);
|
||||
},
|
||||
|
||||
next: function(element, expression, index) {
|
||||
element = $(element);
|
||||
if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element));
|
||||
var nextSiblings = element.nextSiblings();
|
||||
return Object.isNumber(expression) ? nextSiblings[expression] :
|
||||
Selector.findElement(nextSiblings, expression, index);
|
||||
},
|
||||
|
||||
select: function() {
|
||||
var args = $A(arguments), element = $(args.shift());
|
||||
return Selector.findChildElements(element, args);
|
||||
},
|
||||
|
||||
adjacent: function() {
|
||||
var args = $A(arguments), element = $(args.shift());
|
||||
return Selector.findChildElements(element.parentNode, args).without(element);
|
||||
},
|
||||
|
||||
identify: function(element) {
|
||||
element = $(element);
|
||||
var id = element.readAttribute('id'), self = arguments.callee;
|
||||
if (id) return id;
|
||||
do { id = 'anonymous_element_' + self.counter++ } while ($(id));
|
||||
element.writeAttribute('id', id);
|
||||
return id;
|
||||
},
|
||||
|
||||
readAttribute: function(element, name) {
|
||||
element = $(element);
|
||||
if (Prototype.Browser.IE) {
|
||||
var t = Element._attributeTranslations.read;
|
||||
if (t.values[name]) return t.values[name](element, name);
|
||||
if (t.names[name]) name = t.names[name];
|
||||
if (name.include(':')) {
|
||||
return (!element.attributes || !element.attributes[name]) ? null :
|
||||
element.attributes[name].value;
|
||||
}
|
||||
}
|
||||
return element.getAttribute(name);
|
||||
},
|
||||
|
||||
writeAttribute: function(element, name, value) {
|
||||
element = $(element);
|
||||
var attributes = { }, t = Element._attributeTranslations.write;
|
||||
|
||||
if (typeof name == 'object') attributes = name;
|
||||
else attributes[name] = Object.isUndefined(value) ? true : value;
|
||||
|
||||
for (var attr in attributes) {
|
||||
name = t.names[attr] || attr;
|
||||
value = attributes[attr];
|
||||
if (t.values[attr]) name = t.values[attr](element, value);
|
||||
if (value === false || value === null)
|
||||
element.removeAttribute(name);
|
||||
else if (value === true)
|
||||
element.setAttribute(name, name);
|
||||
else element.setAttribute(name, value);
|
||||
}
|
||||
return element;
|
||||
},
|
||||
|
||||
getHeight: function(element) {
|
||||
return $(element).getDimensions().height;
|
||||
},
|
||||
|
||||
getWidth: function(element) {
|
||||
return $(element).getDimensions().width;
|
||||
},
|
||||
|
||||
classNames: function(element) {
|
||||
return new Element.ClassNames(element);
|
||||
},
|
||||
|
||||
hasClassName: function(element, className) {
|
||||
if (!(element = $(element))) return;
|
||||
var elementClassName = element.className;
|
||||
return (elementClassName.length > 0 && (elementClassName == className ||
|
||||
new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
|
||||
},
|
||||
|
||||
addClassName: function(element, className) {
|
||||
if (!(element = $(element))) return;
|
||||
if (!element.hasClassName(className))
|
||||
element.className += (element.className ? ' ' : '') + className;
|
||||
return element;
|
||||
},
|
||||
|
||||
removeClassName: function(element, className) {
|
||||
if (!(element = $(element))) return;
|
||||
element.className = element.className.replace(
|
||||
new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ').strip();
|
||||
return element;
|
||||
},
|
||||
|
||||
toggleClassName: function(element, className) {
|
||||
if (!(element = $(element))) return;
|
||||
return element[element.hasClassName(className) ?
|
||||
'removeClassName' : 'addClassName'](className);
|
||||
},
|
||||
|
||||
// removes whitespace-only text node children
|
||||
cleanWhitespace: function(element) {
|
||||
element = $(element);
|
||||
var node = element.firstChild;
|
||||
while (node) {
|
||||
var nextNode = node.nextSibling;
|
||||
if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
|
||||
element.removeChild(node);
|
||||
node = nextNode;
|
||||
}
|
||||
return element;
|
||||
},
|
||||
|
||||
empty: function(element) {
|
||||
return $(element).innerHTML.blank();
|
||||
},
|
||||
|
||||
descendantOf: function(element, ancestor) {
|
||||
element = $(element), ancestor = $(ancestor);
|
||||
|
||||
if (element.compareDocumentPosition)
|
||||
return (element.compareDocumentPosition(ancestor) & 8) === 8;
|
||||
|
||||
if (ancestor.contains)
|
||||
return ancestor.contains(element) && ancestor !== element;
|
||||
|
||||
while (element = element.parentNode)
|
||||
if (element == ancestor) return true;
|
||||
|
||||
return false;
|
||||
},
|
||||
|
||||
scrollTo: function(element) {
|
||||
element = $(element);
|
||||
var pos = element.cumulativeOffset();
|
||||
window.scrollTo(pos[0], pos[1]);
|
||||
return element;
|
||||
},
|
||||
|
||||
getStyle: function(element, style) {
|
||||
element = $(element);
|
||||
style = style == 'float' ? 'cssFloat' : style.camelize();
|
||||
var value = element.style[style];
|
||||
if (!value || value == 'auto') {
|
||||
var css = document.defaultView.getComputedStyle(element, null);
|
||||
value = css ? css[style] : null;
|
||||
}
|
||||
if (style == 'opacity') return value ? parseFloat(value) : 1.0;
|
||||
return value == 'auto' ? null : value;
|
||||
},
|
||||
|
||||
getOpacity: function(element) {
|
||||
return $(element).getStyle('opacity');
|
||||
},
|
||||
|
||||
setStyle: function(element, styles) {
|
||||
element = $(element);
|
||||
var elementStyle = element.style, match;
|
||||
if (Object.isString(styles)) {
|
||||
element.style.cssText += ';' + styles;
|
||||
return styles.include('opacity') ?
|
||||
element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element;
|
||||
}
|
||||
for (var property in styles)
|
||||
if (property == 'opacity') element.setOpacity(styles[property]);
|
||||
else
|
||||
elementStyle[(property == 'float' || property == 'cssFloat') ?
|
||||
(Object.isUndefined(elementStyle.styleFloat) ? 'cssFloat' : 'styleFloat') :
|
||||
property] = styles[property];
|
||||
|
||||
return element;
|
||||
},
|
||||
|
||||
setOpacity: function(element, value) {
|
||||
element = $(element);
|
||||
element.style.opacity = (value == 1 || value === '') ? '' :
|
||||
(value < 0.00001) ? 0 : value;
|
||||
return element;
|
||||
},
|
||||
|
||||
getDimensions: function(element) {
|
||||
element = $(element);
|
||||
var display = element.getStyle('display');
|
||||
if (display != 'none' && display != null) // Safari bug
|
||||
return {width: element.offsetWidth, height: element.offsetHeight};
|
||||
|
||||
// All *Width and *Height properties give 0 on elements with display none,
|
||||
// so enable the element temporarily
|
||||
var els = element.style;
|
||||
var originalVisibility = els.visibility;
|
||||
var originalPosition = els.position;
|
||||
var originalDisplay = els.display;
|
||||
els.visibility = 'hidden';
|
||||
els.position = 'absolute';
|
||||
els.display = 'block';
|
||||
var originalWidth = element.clientWidth;
|
||||
var originalHeight = element.clientHeight;
|
||||
els.display = originalDisplay;
|
||||
els.position = originalPosition;
|
||||
els.visibility = originalVisibility;
|
||||
return {width: originalWidth, height: originalHeight};
|
||||
},
|
||||
|
||||
makePositioned: function(element) {
|
||||
element = $(element);
|
||||
var pos = Element.getStyle(element, 'position');
|
||||
if (pos == 'static' || !pos) {
|
||||
element._madePositioned = true;
|
||||
element.style.position = 'relative';
|
||||
// Opera returns the offset relative to the positioning context, when an
|
||||
// element is position relative but top and left have not been defined
|
||||
if (Prototype.Browser.Opera) {
|
||||
element.style.top = 0;
|
||||
element.style.left = 0;
|
||||
}
|
||||
}
|
||||
return element;
|
||||
},
|
||||
|
||||
undoPositioned: function(element) {
|
||||
element = $(element);
|
||||
if (element._madePositioned) {
|
||||
element._madePositioned = undefined;
|
||||
element.style.position =
|
||||
element.style.top =
|
||||
element.style.left =
|
||||
element.style.bottom =
|
||||
element.style.right = '';
|
||||
}
|
||||
return element;
|
||||
},
|
||||
|
||||
makeClipping: function(element) {
|
||||
element = $(element);
|
||||
if (element._overflow) return element;
|
||||
element._overflow = Element.getStyle(element, 'overflow') || 'auto';
|
||||
if (element._overflow !== 'hidden')
|
||||
element.style.overflow = 'hidden';
|
||||
return element;
|
||||
},
|
||||
|
||||
undoClipping: function(element) {
|
||||
element = $(element);
|
||||
if (!element._overflow) return element;
|
||||
element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
|
||||
element._overflow = null;
|
||||
return element;
|
||||
},
|
||||
|
||||
cumulativeOffset: function(element) {
|
||||
var valueT = 0, valueL = 0;
|
||||
do {
|
||||
valueT += element.offsetTop || 0;
|
||||
valueL += element.offsetLeft || 0;
|
||||
element = element.offsetParent;
|
||||
} while (element);
|
||||
return Element._returnOffset(valueL, valueT);
|
||||
},
|
||||
|
||||
positionedOffset: function(element) {
|
||||
var valueT = 0, valueL = 0;
|
||||
do {
|
||||
valueT += element.offsetTop || 0;
|
||||
valueL += element.offsetLeft || 0;
|
||||
element = element.offsetParent;
|
||||
if (element) {
|
||||
if (element.tagName.toUpperCase() == 'BODY') break;
|
||||
var p = Element.getStyle(element, 'position');
|
||||
if (p !== 'static') break;
|
||||
}
|
||||
} while (element);
|
||||
return Element._returnOffset(valueL, valueT);
|
||||
},
|
||||
|
||||
absolutize: function(element) {
|
||||
element = $(element);
|
||||
if (element.getStyle('position') == 'absolute') return element;
|
||||
// Position.prepare(); // To be done manually by Scripty when it needs it.
|
||||
|
||||
var offsets = element.positionedOffset();
|
||||
var top = offsets[1];
|
||||
var left = offsets[0];
|
||||
var width = element.clientWidth;
|
||||
var height = element.clientHeight;
|
||||
|
||||
element._originalLeft = left - parseFloat(element.style.left || 0);
|
||||
element._originalTop = top - parseFloat(element.style.top || 0);
|
||||
element._originalWidth = element.style.width;
|
||||
element._originalHeight = element.style.height;
|
||||
|
||||
element.style.position = 'absolute';
|
||||
element.style.top = top + 'px';
|
||||
element.style.left = left + 'px';
|
||||
element.style.width = width + 'px';
|
||||
element.style.height = height + 'px';
|
||||
return element;
|
||||
},
|
||||
|
||||
relativize: function(element) {
|
||||
element = $(element);
|
||||
if (element.getStyle('position') == 'relative') return element;
|
||||
// Position.prepare(); // To be done manually by Scripty when it needs it.
|
||||
|
||||
element.style.position = 'relative';
|
||||
var top = parseFloat(element.style.top || 0) - (element._originalTop || 0);
|
||||
var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);
|
||||
|
||||
element.style.top = top + 'px';
|
||||
element.style.left = left + 'px';
|
||||
element.style.height = element._originalHeight;
|
||||
element.style.width = element._originalWidth;
|
||||
return element;
|
||||
},
|
||||
|
||||
cumulativeScrollOffset: function(element) {
|
||||
var valueT = 0, valueL = 0;
|
||||
do {
|
||||
valueT += element.scrollTop || 0;
|
||||
valueL += element.scrollLeft || 0;
|
||||
element = element.parentNode;
|
||||
} while (element);
|
||||
return Element._returnOffset(valueL, valueT);
|
||||
},
|
||||
|
||||
getOffsetParent: function(element) {
|
||||
if (element.offsetParent) return $(element.offsetParent);
|
||||
if (element == document.body) return $(element);
|
||||
|
||||
while ((element = element.parentNode) && element != document.body)
|
||||
if (Element.getStyle(element, 'position') != 'static')
|
||||
return $(element);
|
||||
|
||||
return $(document.body);
|
||||
},
|
||||
|
||||
viewportOffset: function(forElement) {
|
||||
var valueT = 0, valueL = 0;
|
||||
|
||||
var element = forElement;
|
||||
do {
|
||||
valueT += element.offsetTop || 0;
|
||||
valueL += element.offsetLeft || 0;
|
||||
|
||||
// Safari fix
|
||||
if (element.offsetParent == document.body &&
|
||||
Element.getStyle(element, 'position') == 'absolute') break;
|
||||
|
||||
} while (element = element.offsetParent);
|
||||
|
||||
element = forElement;
|
||||
do {
|
||||
if (!Prototype.Browser.Opera || (element.tagName && (element.tagName.toUpperCase() == 'BODY'))) {
|
||||
valueT -= element.scrollTop || 0;
|
||||
valueL -= element.scrollLeft || 0;
|
||||
}
|
||||
} while (element = element.parentNode);
|
||||
|
||||
return Element._returnOffset(valueL, valueT);
|
||||
},
|
||||
|
||||
clonePosition: function(element, source) {
|
||||
var options = Object.extend({
|
||||
setLeft: true,
|
||||
setTop: true,
|
||||
setWidth: true,
|
||||
setHeight: true,
|
||||
offsetTop: 0,
|
||||
offsetLeft: 0
|
||||
}, arguments[2] || { });
|
||||
|
||||
// find page position of source
|
||||
source = $(source);
|
||||
var p = source.viewportOffset();
|
||||
|
||||
// find coordinate system to use
|
||||
element = $(element);
|
||||
var delta = [0, 0];
|
||||
var parent = null;
|
||||
// delta [0,0] will do fine with position: fixed elements,
|
||||
// position:absolute needs offsetParent deltas
|
||||
if (Element.getStyle(element, 'position') == 'absolute') {
|
||||
parent = element.getOffsetParent();
|
||||
delta = parent.viewportOffset();
|
||||
}
|
||||
|
||||
// correct by body offsets (fixes Safari)
|
||||
if (parent == document.body) {
|
||||
delta[0] -= document.body.offsetLeft;
|
||||
delta[1] -= document.body.offsetTop;
|
||||
}
|
||||
|
||||
// set position
|
||||
if (options.setLeft) element.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px';
|
||||
if (options.setTop) element.style.top = (p[1] - delta[1] + options.offsetTop) + 'px';
|
||||
if (options.setWidth) element.style.width = source.offsetWidth + 'px';
|
||||
if (options.setHeight) element.style.height = source.offsetHeight + 'px';
|
||||
return element;
|
||||
}
|
||||
};
|
||||
|
||||
Element.Methods.identify.counter = 1;
|
||||
|
||||
Object.extend(Element.Methods, {
|
||||
getElementsBySelector: Element.Methods.select,
|
||||
childElements: Element.Methods.immediateDescendants
|
||||
});
|
||||
|
||||
Element._attributeTranslations = {
|
||||
write: {
|
||||
names: {
|
||||
className: 'class',
|
||||
htmlFor: 'for'
|
||||
},
|
||||
values: { }
|
||||
}
|
||||
};
|
||||
|
||||
if (Prototype.Browser.Opera) {
|
||||
Element.Methods.getStyle = Element.Methods.getStyle.wrap(
|
||||
function(proceed, element, style) {
|
||||
switch (style) {
|
||||
case 'left': case 'top': case 'right': case 'bottom':
|
||||
if (proceed(element, 'position') === 'static') return null;
|
||||
case 'height': case 'width':
|
||||
// returns '0px' for hidden elements; we want it to return null
|
||||
if (!Element.visible(element)) return null;
|
||||
|
||||
// returns the border-box dimensions rather than the content-box
|
||||
// dimensions, so we subtract padding and borders from the value
|
||||
var dim = parseInt(proceed(element, style), 10);
|
||||
|
||||
if (dim !== element['offset' + style.capitalize()])
|
||||
return dim + 'px';
|
||||
|
||||
var properties;
|
||||
if (style === 'height') {
|
||||
properties = ['border-top-width', 'padding-top',
|
||||
'padding-bottom', 'border-bottom-width'];
|
||||
}
|
||||
else {
|
||||
properties = ['border-left-width', 'padding-left',
|
||||
'padding-right', 'border-right-width'];
|
||||
}
|
||||
return properties.inject(dim, function(memo, property) {
|
||||
var val = proceed(element, property);
|
||||
return val === null ? memo : memo - parseInt(val, 10);
|
||||
}) + 'px';
|
||||
default: return proceed(element, style);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
Element.Methods.readAttribute = Element.Methods.readAttribute.wrap(
|
||||
function(proceed, element, attribute) {
|
||||
if (attribute === 'title') return element.title;
|
||||
return proceed(element, attribute);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
else if (Prototype.Browser.IE) {
|
||||
// IE doesn't report offsets correctly for static elements, so we change them
|
||||
// to "relative" to get the values, then change them back.
|
||||
Element.Methods.getOffsetParent = Element.Methods.getOffsetParent.wrap(
|
||||
function(proceed, element) {
|
||||
element = $(element);
|
||||
// IE throws an error if element is not in document
|
||||
try { element.offsetParent }
|
||||
catch(e) { return $(document.body) }
|
||||
var position = element.getStyle('position');
|
||||
if (position !== 'static') return proceed(element);
|
||||
element.setStyle({ position: 'relative' });
|
||||
var value = proceed(element);
|
||||
element.setStyle({ position: position });
|
||||
return value;
|
||||
}
|
||||
);
|
||||
|
||||
$w('positionedOffset viewportOffset').each(function(method) {
|
||||
Element.Methods[method] = Element.Methods[method].wrap(
|
||||
function(proceed, element) {
|
||||
element = $(element);
|
||||
try { element.offsetParent }
|
||||
catch(e) { return Element._returnOffset(0,0) }
|
||||
var position = element.getStyle('position');
|
||||
if (position !== 'static') return proceed(element);
|
||||
// Trigger hasLayout on the offset parent so that IE6 reports
|
||||
// accurate offsetTop and offsetLeft values for position: fixed.
|
||||
var offsetParent = element.getOffsetParent();
|
||||
if (offsetParent && offsetParent.getStyle('position') === 'fixed')
|
||||
offsetParent.setStyle({ zoom: 1 });
|
||||
element.setStyle({ position: 'relative' });
|
||||
var value = proceed(element);
|
||||
element.setStyle({ position: position });
|
||||
return value;
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
Element.Methods.cumulativeOffset = Element.Methods.cumulativeOffset.wrap(
|
||||
function(proceed, element) {
|
||||
try { element.offsetParent }
|
||||
catch(e) { return Element._returnOffset(0,0) }
|
||||
return proceed(element);
|
||||
}
|
||||
);
|
||||
|
||||
Element.Methods.getStyle = function(element, style) {
|
||||
element = $(element);
|
||||
style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize();
|
||||
var value = element.style[style];
|
||||
if (!value && element.currentStyle) value = element.currentStyle[style];
|
||||
|
||||
if (style == 'opacity') {
|
||||
if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
|
||||
if (value[1]) return parseFloat(value[1]) / 100;
|
||||
return 1.0;
|
||||
}
|
||||
|
||||
if (value == 'auto') {
|
||||
if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none'))
|
||||
return element['offset' + style.capitalize()] + 'px';
|
||||
return null;
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
Element.Methods.setOpacity = function(element, value) {
|
||||
function stripAlpha(filter){
|
||||
return filter.replace(/alpha\([^\)]*\)/gi,'');
|
||||
}
|
||||
element = $(element);
|
||||
var currentStyle = element.currentStyle;
|
||||
if ((currentStyle && !currentStyle.hasLayout) ||
|
||||
(!currentStyle && element.style.zoom == 'normal'))
|
||||
element.style.zoom = 1;
|
||||
|
||||
var filter = element.getStyle('filter'), style = element.style;
|
||||
if (value == 1 || value === '') {
|
||||
(filter = stripAlpha(filter)) ?
|
||||
style.filter = filter : style.removeAttribute('filter');
|
||||
return element;
|
||||
} else if (value < 0.00001) value = 0;
|
||||
style.filter = stripAlpha(filter) +
|
||||
'alpha(opacity=' + (value * 100) + ')';
|
||||
return element;
|
||||
};
|
||||
|
||||
Element._attributeTranslations = {
|
||||
read: {
|
||||
names: {
|
||||
'class': 'className',
|
||||
'for': 'htmlFor'
|
||||
},
|
||||
values: {
|
||||
_getAttr: function(element, attribute) {
|
||||
return element.getAttribute(attribute, 2);
|
||||
},
|
||||
_getAttrNode: function(element, attribute) {
|
||||
var node = element.getAttributeNode(attribute);
|
||||
return node ? node.value : "";
|
||||
},
|
||||
_getEv: function(element, attribute) {
|
||||
attribute = element.getAttribute(attribute);
|
||||
return attribute ? attribute.toString().slice(23, -2) : null;
|
||||
},
|
||||
_flag: function(element, attribute) {
|
||||
return $(element).hasAttribute(attribute) ? attribute : null;
|
||||
},
|
||||
style: function(element) {
|
||||
return element.style.cssText.toLowerCase();
|
||||
},
|
||||
title: function(element) {
|
||||
return element.title;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Element._attributeTranslations.write = {
|
||||
names: Object.extend({
|
||||
cellpadding: 'cellPadding',
|
||||
cellspacing: 'cellSpacing'
|
||||
}, Element._attributeTranslations.read.names),
|
||||
values: {
|
||||
checked: function(element, value) {
|
||||
element.checked = !!value;
|
||||
},
|
||||
|
||||
style: function(element, value) {
|
||||
element.style.cssText = value ? value : '';
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Element._attributeTranslations.has = {};
|
||||
|
||||
$w('colSpan rowSpan vAlign dateTime accessKey tabIndex ' +
|
||||
'encType maxLength readOnly longDesc frameBorder').each(function(attr) {
|
||||
Element._attributeTranslations.write.names[attr.toLowerCase()] = attr;
|
||||
Element._attributeTranslations.has[attr.toLowerCase()] = attr;
|
||||
});
|
||||
|
||||
(function(v) {
|
||||
Object.extend(v, {
|
||||
href: v._getAttr,
|
||||
src: v._getAttr,
|
||||
type: v._getAttr,
|
||||
action: v._getAttrNode,
|
||||
disabled: v._flag,
|
||||
checked: v._flag,
|
||||
readonly: v._flag,
|
||||
multiple: v._flag,
|
||||
onload: v._getEv,
|
||||
onunload: v._getEv,
|
||||
onclick: v._getEv,
|
||||
ondblclick: v._getEv,
|
||||
onmousedown: v._getEv,
|
||||
onmouseup: v._getEv,
|
||||
onmouseover: v._getEv,
|
||||
onmousemove: v._getEv,
|
||||
onmouseout: v._getEv,
|
||||
onfocus: v._getEv,
|
||||
onblur: v._getEv,
|
||||
onkeypress: v._getEv,
|
||||
onkeydown: v._getEv,
|
||||
onkeyup: v._getEv,
|
||||
onsubmit: v._getEv,
|
||||
onreset: v._getEv,
|
||||
onselect: v._getEv,
|
||||
onchange: v._getEv
|
||||
});
|
||||
})(Element._attributeTranslations.read.values);
|
||||
}
|
||||
|
||||
else if (Prototype.Browser.Gecko && /rv:1\.8\.0/.test(navigator.userAgent)) {
|
||||
Element.Methods.setOpacity = function(element, value) {
|
||||
element = $(element);
|
||||
element.style.opacity = (value == 1) ? 0.999999 :
|
||||
(value === '') ? '' : (value < 0.00001) ? 0 : value;
|
||||
return element;
|
||||
};
|
||||
}
|
||||
|
||||
else if (Prototype.Browser.WebKit) {
|
||||
Element.Methods.setOpacity = function(element, value) {
|
||||
element = $(element);
|
||||
element.style.opacity = (value == 1 || value === '') ? '' :
|
||||
(value < 0.00001) ? 0 : value;
|
||||
|
||||
if (value == 1)
|
||||
if(element.tagName.toUpperCase() == 'IMG' && element.width) {
|
||||
element.width++; element.width--;
|
||||
} else try {
|
||||
var n = document.createTextNode(' ');
|
||||
element.appendChild(n);
|
||||
element.removeChild(n);
|
||||
} catch (e) { }
|
||||
|
||||
return element;
|
||||
};
|
||||
|
||||
// Safari returns margins on body which is incorrect if the child is absolutely
|
||||
// positioned. For performance reasons, redefine Element#cumulativeOffset for
|
||||
// KHTML/WebKit only.
|
||||
Element.Methods.cumulativeOffset = function(element) {
|
||||
var valueT = 0, valueL = 0;
|
||||
do {
|
||||
valueT += element.offsetTop || 0;
|
||||
valueL += element.offsetLeft || 0;
|
||||
if (element.offsetParent == document.body)
|
||||
if (Element.getStyle(element, 'position') == 'absolute') break;
|
||||
|
||||
element = element.offsetParent;
|
||||
} while (element);
|
||||
|
||||
return Element._returnOffset(valueL, valueT);
|
||||
};
|
||||
}
|
||||
|
||||
if (Prototype.Browser.IE || Prototype.Browser.Opera) {
|
||||
// IE and Opera are missing .innerHTML support for TABLE-related and SELECT elements
|
||||
Element.Methods.update = function(element, content) {
|
||||
element = $(element);
|
||||
|
||||
if (content && content.toElement) content = content.toElement();
|
||||
if (Object.isElement(content)) return element.update().insert(content);
|
||||
|
||||
content = Object.toHTML(content);
|
||||
var tagName = element.tagName.toUpperCase();
|
||||
|
||||
if (tagName in Element._insertionTranslations.tags) {
|
||||
$A(element.childNodes).each(function(node) { element.removeChild(node) });
|
||||
Element._getContentFromAnonymousElement(tagName, content.stripScripts())
|
||||
.each(function(node) { element.appendChild(node) });
|
||||
}
|
||||
else element.innerHTML = content.stripScripts();
|
||||
|
||||
content.evalScripts.bind(content).defer();
|
||||
return element;
|
||||
};
|
||||
}
|
||||
|
||||
if ('outerHTML' in document.createElement('div')) {
|
||||
Element.Methods.replace = function(element, content) {
|
||||
element = $(element);
|
||||
|
||||
if (content && content.toElement) content = content.toElement();
|
||||
if (Object.isElement(content)) {
|
||||
element.parentNode.replaceChild(content, element);
|
||||
return element;
|
||||
}
|
||||
|
||||
content = Object.toHTML(content);
|
||||
var parent = element.parentNode, tagName = parent.tagName.toUpperCase();
|
||||
|
||||
if (Element._insertionTranslations.tags[tagName]) {
|
||||
var nextSibling = element.next();
|
||||
var fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
|
||||
parent.removeChild(element);
|
||||
if (nextSibling)
|
||||
fragments.each(function(node) { parent.insertBefore(node, nextSibling) });
|
||||
else
|
||||
fragments.each(function(node) { parent.appendChild(node) });
|
||||
}
|
||||
else element.outerHTML = content.stripScripts();
|
||||
|
||||
content.evalScripts.bind(content).defer();
|
||||
return element;
|
||||
};
|
||||
}
|
||||
|
||||
Element._returnOffset = function(l, t) {
|
||||
var result = [l, t];
|
||||
result.left = l;
|
||||
result.top = t;
|
||||
return result;
|
||||
};
|
||||
|
||||
Element._getContentFromAnonymousElement = function(tagName, html) {
|
||||
var div = new Element('div'), t = Element._insertionTranslations.tags[tagName];
|
||||
if (t) {
|
||||
div.innerHTML = t[0] + html + t[1];
|
||||
t[2].times(function() { div = div.firstChild });
|
||||
} else div.innerHTML = html;
|
||||
return $A(div.childNodes);
|
||||
};
|
||||
|
||||
Element._insertionTranslations = {
|
||||
before: function(element, node) {
|
||||
element.parentNode.insertBefore(node, element);
|
||||
},
|
||||
top: function(element, node) {
|
||||
element.insertBefore(node, element.firstChild);
|
||||
},
|
||||
bottom: function(element, node) {
|
||||
element.appendChild(node);
|
||||
},
|
||||
after: function(element, node) {
|
||||
element.parentNode.insertBefore(node, element.nextSibling);
|
||||
},
|
||||
tags: {
|
||||
TABLE: ['<table>', '</table>', 1],
|
||||
TBODY: ['<table><tbody>', '</tbody></table>', 2],
|
||||
TR: ['<table><tbody><tr>', '</tr></tbody></table>', 3],
|
||||
TD: ['<table><tbody><tr><td>', '</td></tr></tbody></table>', 4],
|
||||
SELECT: ['<select>', '</select>', 1]
|
||||
}
|
||||
};
|
||||
|
||||
(function() {
|
||||
Object.extend(this.tags, {
|
||||
THEAD: this.tags.TBODY,
|
||||
TFOOT: this.tags.TBODY,
|
||||
TH: this.tags.TD
|
||||
});
|
||||
}).call(Element._insertionTranslations);
|
||||
|
||||
Element.Methods.Simulated = {
|
||||
hasAttribute: function(element, attribute) {
|
||||
attribute = Element._attributeTranslations.has[attribute] || attribute;
|
||||
var node = $(element).getAttributeNode(attribute);
|
||||
return !!(node && node.specified);
|
||||
}
|
||||
};
|
||||
|
||||
Element.Methods.ByTag = { };
|
||||
|
||||
Object.extend(Element, Element.Methods);
|
||||
|
||||
if (!Prototype.BrowserFeatures.ElementExtensions &&
|
||||
document.createElement('div')['__proto__']) {
|
||||
window.HTMLElement = { };
|
||||
window.HTMLElement.prototype = document.createElement('div')['__proto__'];
|
||||
Prototype.BrowserFeatures.ElementExtensions = true;
|
||||
}
|
||||
|
||||
Element.extend = (function() {
|
||||
if (Prototype.BrowserFeatures.SpecificElementExtensions)
|
||||
return Prototype.K;
|
||||
|
||||
var Methods = { }, ByTag = Element.Methods.ByTag;
|
||||
|
||||
var extend = Object.extend(function(element) {
|
||||
if (!element || element._extendedByPrototype ||
|
||||
element.nodeType != 1 || element == window) return element;
|
||||
|
||||
var methods = Object.clone(Methods),
|
||||
tagName = element.tagName.toUpperCase(), property, value;
|
||||
|
||||
// extend methods for specific tags
|
||||
if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]);
|
||||
|
||||
for (property in methods) {
|
||||
value = methods[property];
|
||||
if (Object.isFunction(value) && !(property in element))
|
||||
element[property] = value.methodize();
|
||||
}
|
||||
|
||||
element._extendedByPrototype = Prototype.emptyFunction;
|
||||
return element;
|
||||
|
||||
}, {
|
||||
refresh: function() {
|
||||
// extend methods for all tags (Safari doesn't need this)
|
||||
if (!Prototype.BrowserFeatures.ElementExtensions) {
|
||||
Object.extend(Methods, Element.Methods);
|
||||
Object.extend(Methods, Element.Methods.Simulated);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
extend.refresh();
|
||||
return extend;
|
||||
})();
|
||||
|
||||
Element.hasAttribute = function(element, attribute) {
|
||||
if (element.hasAttribute) return element.hasAttribute(attribute);
|
||||
return Element.Methods.Simulated.hasAttribute(element, attribute);
|
||||
};
|
||||
|
||||
Element.addMethods = function(methods) {
|
||||
var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag;
|
||||
|
||||
if (!methods) {
|
||||
Object.extend(Form, Form.Methods);
|
||||
Object.extend(Form.Element, Form.Element.Methods);
|
||||
Object.extend(Element.Methods.ByTag, {
|
||||
"FORM": Object.clone(Form.Methods),
|
||||
"INPUT": Object.clone(Form.Element.Methods),
|
||||
"SELECT": Object.clone(Form.Element.Methods),
|
||||
"TEXTAREA": Object.clone(Form.Element.Methods)
|
||||
});
|
||||
}
|
||||
|
||||
if (arguments.length == 2) {
|
||||
var tagName = methods;
|
||||
methods = arguments[1];
|
||||
}
|
||||
|
||||
if (!tagName) Object.extend(Element.Methods, methods || { });
|
||||
else {
|
||||
if (Object.isArray(tagName)) tagName.each(extend);
|
||||
else extend(tagName);
|
||||
}
|
||||
|
||||
function extend(tagName) {
|
||||
tagName = tagName.toUpperCase();
|
||||
if (!Element.Methods.ByTag[tagName])
|
||||
Element.Methods.ByTag[tagName] = { };
|
||||
Object.extend(Element.Methods.ByTag[tagName], methods);
|
||||
}
|
||||
|
||||
function copy(methods, destination, onlyIfAbsent) {
|
||||
onlyIfAbsent = onlyIfAbsent || false;
|
||||
for (var property in methods) {
|
||||
var value = methods[property];
|
||||
if (!Object.isFunction(value)) continue;
|
||||
if (!onlyIfAbsent || !(property in destination))
|
||||
destination[property] = value.methodize();
|
||||
}
|
||||
}
|
||||
|
||||
function findDOMClass(tagName) {
|
||||
var klass;
|
||||
var trans = {
|
||||
"OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph",
|
||||
"FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList",
|
||||
"DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading",
|
||||
"H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote",
|
||||
"INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION":
|
||||
"TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD":
|
||||
"TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR":
|
||||
"TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET":
|
||||
"FrameSet", "IFRAME": "IFrame"
|
||||
};
|
||||
if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element';
|
||||
if (window[klass]) return window[klass];
|
||||
klass = 'HTML' + tagName + 'Element';
|
||||
if (window[klass]) return window[klass];
|
||||
klass = 'HTML' + tagName.capitalize() + 'Element';
|
||||
if (window[klass]) return window[klass];
|
||||
|
||||
window[klass] = { };
|
||||
window[klass].prototype = document.createElement(tagName)['__proto__'];
|
||||
return window[klass];
|
||||
}
|
||||
|
||||
if (F.ElementExtensions) {
|
||||
copy(Element.Methods, HTMLElement.prototype);
|
||||
copy(Element.Methods.Simulated, HTMLElement.prototype, true);
|
||||
}
|
||||
|
||||
if (F.SpecificElementExtensions) {
|
||||
for (var tag in Element.Methods.ByTag) {
|
||||
var klass = findDOMClass(tag);
|
||||
if (Object.isUndefined(klass)) continue;
|
||||
copy(T[tag], klass.prototype);
|
||||
}
|
||||
}
|
||||
|
||||
Object.extend(Element, Element.Methods);
|
||||
delete Element.ByTag;
|
||||
|
||||
if (Element.extend.refresh) Element.extend.refresh();
|
||||
Element.cache = { };
|
||||
};
|
||||
|
||||
document.viewport = {
|
||||
getDimensions: function() {
|
||||
var dimensions = { }, B = Prototype.Browser;
|
||||
$w('width height').each(function(d) {
|
||||
var D = d.capitalize();
|
||||
if (B.WebKit && !document.evaluate) {
|
||||
// Safari <3.0 needs self.innerWidth/Height
|
||||
dimensions[d] = self['inner' + D];
|
||||
} else if (B.Opera && parseFloat(window.opera.version()) < 9.5) {
|
||||
// Opera <9.5 needs document.body.clientWidth/Height
|
||||
dimensions[d] = document.body['client' + D]
|
||||
} else {
|
||||
dimensions[d] = document.documentElement['client' + D];
|
||||
}
|
||||
});
|
||||
return dimensions;
|
||||
},
|
||||
|
||||
getWidth: function() {
|
||||
return this.getDimensions().width;
|
||||
},
|
||||
|
||||
getHeight: function() {
|
||||
return this.getDimensions().height;
|
||||
},
|
||||
|
||||
getScrollOffsets: function() {
|
||||
return Element._returnOffset(
|
||||
window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
|
||||
window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
|
||||
}
|
||||
};
|
||||
/* Portions of the Selector class are derived from Jack Slocum's DomQuery,
|
||||
* part of YUI-Ext version 0.40, distributed under the terms of an MIT-style
|
||||
* license. Please see http://www.yui-ext.com/ for more information. */
|
||||
|
||||
var Selector = Class.create({
|
||||
initialize: function(expression) {
|
||||
this.expression = expression.strip();
|
||||
|
||||
if (this.shouldUseSelectorsAPI()) {
|
||||
this.mode = 'selectorsAPI';
|
||||
} else if (this.shouldUseXPath()) {
|
||||
this.mode = 'xpath';
|
||||
this.compileXPathMatcher();
|
||||
} else {
|
||||
this.mode = "normal";
|
||||
this.compileMatcher();
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
shouldUseXPath: function() {
|
||||
if (!Prototype.BrowserFeatures.XPath) return false;
|
||||
|
||||
var e = this.expression;
|
||||
|
||||
// Safari 3 chokes on :*-of-type and :empty
|
||||
if (Prototype.Browser.WebKit &&
|
||||
(e.include("-of-type") || e.include(":empty")))
|
||||
return false;
|
||||
|
||||
// XPath can't do namespaced attributes, nor can it read
|
||||
// the "checked" property from DOM nodes
|
||||
if ((/(\[[\w-]*?:|:checked)/).test(e))
|
||||
return false;
|
||||
|
||||
return true;
|
||||
},
|
||||
|
||||
shouldUseSelectorsAPI: function() {
|
||||
if (!Prototype.BrowserFeatures.SelectorsAPI) return false;
|
||||
|
||||
if (!Selector._div) Selector._div = new Element('div');
|
||||
|
||||
// Make sure the browser treats the selector as valid. Test on an
|
||||
// isolated element to minimize cost of this check.
|
||||
try {
|
||||
Selector._div.querySelector(this.expression);
|
||||
} catch(e) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
},
|
||||
|
||||
compileMatcher: function() {
|
||||
var e = this.expression, ps = Selector.patterns, h = Selector.handlers,
|
||||
c = Selector.criteria, le, p, m;
|
||||
|
||||
if (Selector._cache[e]) {
|
||||
this.matcher = Selector._cache[e];
|
||||
return;
|
||||
}
|
||||
|
||||
this.matcher = ["this.matcher = function(root) {",
|
||||
"var r = root, h = Selector.handlers, c = false, n;"];
|
||||
|
||||
while (e && le != e && (/\S/).test(e)) {
|
||||
le = e;
|
||||
for (var i in ps) {
|
||||
p = ps[i];
|
||||
if (m = e.match(p)) {
|
||||
this.matcher.push(Object.isFunction(c[i]) ? c[i](m) :
|
||||
new Template(c[i]).evaluate(m));
|
||||
e = e.replace(m[0], '');
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.matcher.push("return h.unique(n);\n}");
|
||||
eval(this.matcher.join('\n'));
|
||||
Selector._cache[this.expression] = this.matcher;
|
||||
},
|
||||
|
||||
compileXPathMatcher: function() {
|
||||
var e = this.expression, ps = Selector.patterns,
|
||||
x = Selector.xpath, le, m;
|
||||
|
||||
if (Selector._cache[e]) {
|
||||
this.xpath = Selector._cache[e]; return;
|
||||
}
|
||||
|
||||
this.matcher = ['.//*'];
|
||||
while (e && le != e && (/\S/).test(e)) {
|
||||
le = e;
|
||||
for (var i in ps) {
|
||||
if (m = e.match(ps[i])) {
|
||||
this.matcher.push(Object.isFunction(x[i]) ? x[i](m) :
|
||||
new Template(x[i]).evaluate(m));
|
||||
e = e.replace(m[0], '');
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.xpath = this.matcher.join('');
|
||||
Selector._cache[this.expression] = this.xpath;
|
||||
},
|
||||
|
||||
findElements: function(root) {
|
||||
root = root || document;
|
||||
var e = this.expression, results;
|
||||
|
||||
switch (this.mode) {
|
||||
case 'selectorsAPI':
|
||||
// querySelectorAll queries document-wide, then filters to descendants
|
||||
// of the context element. That's not what we want.
|
||||
// Add an explicit context to the selector if necessary.
|
||||
if (root !== document) {
|
||||
var oldId = root.id, id = $(root).identify();
|
||||
e = "#" + id + " " + e;
|
||||
}
|
||||
|
||||
results = $A(root.querySelectorAll(e)).map(Element.extend);
|
||||
root.id = oldId;
|
||||
|
||||
return results;
|
||||
case 'xpath':
|
||||
return document._getElementsByXPath(this.xpath, root);
|
||||
default:
|
||||
return this.matcher(root);
|
||||
}
|
||||
},
|
||||
|
||||
match: function(element) {
|
||||
this.tokens = [];
|
||||
|
||||
var e = this.expression, ps = Selector.patterns, as = Selector.assertions;
|
||||
var le, p, m;
|
||||
|
||||
while (e && le !== e && (/\S/).test(e)) {
|
||||
le = e;
|
||||
for (var i in ps) {
|
||||
p = ps[i];
|
||||
if (m = e.match(p)) {
|
||||
// use the Selector.assertions methods unless the selector
|
||||
// is too complex.
|
||||
if (as[i]) {
|
||||
this.tokens.push([i, Object.clone(m)]);
|
||||
e = e.replace(m[0], '');
|
||||
} else {
|
||||
// reluctantly do a document-wide search
|
||||
// and look for a match in the array
|
||||
return this.findElements(document).include(element);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var match = true, name, matches;
|
||||
for (var i = 0, token; token = this.tokens[i]; i++) {
|
||||
name = token[0], matches = token[1];
|
||||
if (!Selector.assertions[name](element, matches)) {
|
||||
match = false; break;
|
||||
}
|
||||
}
|
||||
|
||||
return match;
|
||||
},
|
||||
|
||||
toString: function() {
|
||||
return this.expression;
|
||||
},
|
||||
|
||||
inspect: function() {
|
||||
return "#<Selector:" + this.expression.inspect() + ">";
|
||||
}
|
||||
});
|
||||
|
||||
Object.extend(Selector, {
|
||||
_cache: { },
|
||||
|
||||
xpath: {
|
||||
descendant: "//*",
|
||||
child: "/*",
|
||||
adjacent: "/following-sibling::*[1]",
|
||||
laterSibling: '/following-sibling::*',
|
||||
tagName: function(m) {
|
||||
if (m[1] == '*') return '';
|
||||
return "[local-name()='" + m[1].toLowerCase() +
|
||||
"' or local-name()='" + m[1].toUpperCase() + "']";
|
||||
},
|
||||
className: "[contains(concat(' ', @class, ' '), ' #{1} ')]",
|
||||
id: "[@id='#{1}']",
|
||||
attrPresence: function(m) {
|
||||
m[1] = m[1].toLowerCase();
|
||||
return new Template("[@#{1}]").evaluate(m);
|
||||
},
|
||||
attr: function(m) {
|
||||
m[1] = m[1].toLowerCase();
|
||||
m[3] = m[5] || m[6];
|
||||
return new Template(Selector.xpath.operators[m[2]]).evaluate(m);
|
||||
},
|
||||
pseudo: function(m) {
|
||||
var h = Selector.xpath.pseudos[m[1]];
|
||||
if (!h) return '';
|
||||
if (Object.isFunction(h)) return h(m);
|
||||
return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m);
|
||||
},
|
||||
operators: {
|
||||
'=': "[@#{1}='#{3}']",
|
||||
'!=': "[@#{1}!='#{3}']",
|
||||
'^=': "[starts-with(@#{1}, '#{3}')]",
|
||||
'$=': "[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']",
|
||||
'*=': "[contains(@#{1}, '#{3}')]",
|
||||
'~=': "[contains(concat(' ', @#{1}, ' '), ' #{3} ')]",
|
||||
'|=': "[contains(concat('-', @#{1}, '-'), '-#{3}-')]"
|
||||
},
|
||||
pseudos: {
|
||||
'first-child': '[not(preceding-sibling::*)]',
|
||||
'last-child': '[not(following-sibling::*)]',
|
||||
'only-child': '[not(preceding-sibling::* or following-sibling::*)]',
|
||||
'empty': "[count(*) = 0 and (count(text()) = 0)]",
|
||||
'checked': "[@checked]",
|
||||
'disabled': "[(@disabled) and (@type!='hidden')]",
|
||||
'enabled': "[not(@disabled) and (@type!='hidden')]",
|
||||
'not': function(m) {
|
||||
var e = m[6], p = Selector.patterns,
|
||||
x = Selector.xpath, le, v;
|
||||
|
||||
var exclusion = [];
|
||||
while (e && le != e && (/\S/).test(e)) {
|
||||
le = e;
|
||||
for (var i in p) {
|
||||
if (m = e.match(p[i])) {
|
||||
v = Object.isFunction(x[i]) ? x[i](m) : new Template(x[i]).evaluate(m);
|
||||
exclusion.push("(" + v.substring(1, v.length - 1) + ")");
|
||||
e = e.replace(m[0], '');
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return "[not(" + exclusion.join(" and ") + ")]";
|
||||
},
|
||||
'nth-child': function(m) {
|
||||
return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ", m);
|
||||
},
|
||||
'nth-last-child': function(m) {
|
||||
return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ", m);
|
||||
},
|
||||
'nth-of-type': function(m) {
|
||||
return Selector.xpath.pseudos.nth("position() ", m);
|
||||
},
|
||||
'nth-last-of-type': function(m) {
|
||||
return Selector.xpath.pseudos.nth("(last() + 1 - position()) ", m);
|
||||
},
|
||||
'first-of-type': function(m) {
|
||||
m[6] = "1"; return Selector.xpath.pseudos['nth-of-type'](m);
|
||||
},
|
||||
'last-of-type': function(m) {
|
||||
m[6] = "1"; return Selector.xpath.pseudos['nth-last-of-type'](m);
|
||||
},
|
||||
'only-of-type': function(m) {
|
||||
var p = Selector.xpath.pseudos; return p['first-of-type'](m) + p['last-of-type'](m);
|
||||
},
|
||||
nth: function(fragment, m) {
|
||||
var mm, formula = m[6], predicate;
|
||||
if (formula == 'even') formula = '2n+0';
|
||||
if (formula == 'odd') formula = '2n+1';
|
||||
if (mm = formula.match(/^(\d+)$/)) // digit only
|
||||
return '[' + fragment + "= " + mm[1] + ']';
|
||||
if (mm = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
|
||||
if (mm[1] == "-") mm[1] = -1;
|
||||
var a = mm[1] ? Number(mm[1]) : 1;
|
||||
var b = mm[2] ? Number(mm[2]) : 0;
|
||||
predicate = "[((#{fragment} - #{b}) mod #{a} = 0) and " +
|
||||
"((#{fragment} - #{b}) div #{a} >= 0)]";
|
||||
return new Template(predicate).evaluate({
|
||||
fragment: fragment, a: a, b: b });
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
criteria: {
|
||||
tagName: 'n = h.tagName(n, r, "#{1}", c); c = false;',
|
||||
className: 'n = h.className(n, r, "#{1}", c); c = false;',
|
||||
id: 'n = h.id(n, r, "#{1}", c); c = false;',
|
||||
attrPresence: 'n = h.attrPresence(n, r, "#{1}", c); c = false;',
|
||||
attr: function(m) {
|
||||
m[3] = (m[5] || m[6]);
|
||||
return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}", c); c = false;').evaluate(m);
|
||||
},
|
||||
pseudo: function(m) {
|
||||
if (m[6]) m[6] = m[6].replace(/"/g, '\\"');
|
||||
return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m);
|
||||
},
|
||||
descendant: 'c = "descendant";',
|
||||
child: 'c = "child";',
|
||||
adjacent: 'c = "adjacent";',
|
||||
laterSibling: 'c = "laterSibling";'
|
||||
},
|
||||
|
||||
patterns: {
|
||||
// combinators must be listed first
|
||||
// (and descendant needs to be last combinator)
|
||||
laterSibling: /^\s*~\s*/,
|
||||
child: /^\s*>\s*/,
|
||||
adjacent: /^\s*\+\s*/,
|
||||
descendant: /^\s/,
|
||||
|
||||
// selectors follow
|
||||
tagName: /^\s*(\*|[\w\-]+)(\b|$)?/,
|
||||
id: /^#([\w\-\*]+)(\b|$)/,
|
||||
className: /^\.([\w\-\*]+)(\b|$)/,
|
||||
pseudo:
|
||||
/^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s|[:+~>]))/,
|
||||
attrPresence: /^\[((?:[\w]+:)?[\w]+)\]/,
|
||||
attr: /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/
|
||||
},
|
||||
|
||||
// for Selector.match and Element#match
|
||||
assertions: {
|
||||
tagName: function(element, matches) {
|
||||
return matches[1].toUpperCase() == element.tagName.toUpperCase();
|
||||
},
|
||||
|
||||
className: function(element, matches) {
|
||||
return Element.hasClassName(element, matches[1]);
|
||||
},
|
||||
|
||||
id: function(element, matches) {
|
||||
return element.id === matches[1];
|
||||
},
|
||||
|
||||
attrPresence: function(element, matches) {
|
||||
return Element.hasAttribute(element, matches[1]);
|
||||
},
|
||||
|
||||
attr: function(element, matches) {
|
||||
var nodeValue = Element.readAttribute(element, matches[1]);
|
||||
return nodeValue && Selector.operators[matches[2]](nodeValue, matches[5] || matches[6]);
|
||||
}
|
||||
},
|
||||
|
||||
handlers: {
|
||||
// UTILITY FUNCTIONS
|
||||
// joins two collections
|
||||
concat: function(a, b) {
|
||||
for (var i = 0, node; node = b[i]; i++)
|
||||
a.push(node);
|
||||
return a;
|
||||
},
|
||||
|
||||
// marks an array of nodes for counting
|
||||
mark: function(nodes) {
|
||||
var _true = Prototype.emptyFunction;
|
||||
for (var i = 0, node; node = nodes[i]; i++)
|
||||
node._countedByPrototype = _true;
|
||||
return nodes;
|
||||
},
|
||||
|
||||
unmark: function(nodes) {
|
||||
for (var i = 0, node; node = nodes[i]; i++)
|
||||
node._countedByPrototype = undefined;
|
||||
return nodes;
|
||||
},
|
||||
|
||||
// mark each child node with its position (for nth calls)
|
||||
// "ofType" flag indicates whether we're indexing for nth-of-type
|
||||
// rather than nth-child
|
||||
index: function(parentNode, reverse, ofType) {
|
||||
parentNode._countedByPrototype = Prototype.emptyFunction;
|
||||
if (reverse) {
|
||||
for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) {
|
||||
var node = nodes[i];
|
||||
if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
|
||||
}
|
||||
} else {
|
||||
for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++)
|
||||
if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
|
||||
}
|
||||
},
|
||||
|
||||
// filters out duplicates and extends all nodes
|
||||
unique: function(nodes) {
|
||||
if (nodes.length == 0) return nodes;
|
||||
var results = [], n;
|
||||
for (var i = 0, l = nodes.length; i < l; i++)
|
||||
if (!(n = nodes[i])._countedByPrototype) {
|
||||
n._countedByPrototype = Prototype.emptyFunction;
|
||||
results.push(Element.extend(n));
|
||||
}
|
||||
return Selector.handlers.unmark(results);
|
||||
},
|
||||
|
||||
// COMBINATOR FUNCTIONS
|
||||
descendant: function(nodes) {
|
||||
var h = Selector.handlers;
|
||||
for (var i = 0, results = [], node; node = nodes[i]; i++)
|
||||
h.concat(results, node.getElementsByTagName('*'));
|
||||
return results;
|
||||
},
|
||||
|
||||
child: function(nodes) {
|
||||
var h = Selector.handlers;
|
||||
for (var i = 0, results = [], node; node = nodes[i]; i++) {
|
||||
for (var j = 0, child; child = node.childNodes[j]; j++)
|
||||
if (child.nodeType == 1 && child.tagName != '!') results.push(child);
|
||||
}
|
||||
return results;
|
||||
},
|
||||
|
||||
adjacent: function(nodes) {
|
||||
for (var i = 0, results = [], node; node = nodes[i]; i++) {
|
||||
var next = this.nextElementSibling(node);
|
||||
if (next) results.push(next);
|
||||
}
|
||||
return results;
|
||||
},
|
||||
|
||||
laterSibling: function(nodes) {
|
||||
var h = Selector.handlers;
|
||||
for (var i = 0, results = [], node; node = nodes[i]; i++)
|
||||
h.concat(results, Element.nextSiblings(node));
|
||||
return results;
|
||||
},
|
||||
|
||||
nextElementSibling: function(node) {
|
||||
while (node = node.nextSibling)
|
||||
if (node.nodeType == 1) return node;
|
||||
return null;
|
||||
},
|
||||
|
||||
previousElementSibling: function(node) {
|
||||
while (node = node.previousSibling)
|
||||
if (node.nodeType == 1) return node;
|
||||
return null;
|
||||
},
|
||||
|
||||
// TOKEN FUNCTIONS
|
||||
tagName: function(nodes, root, tagName, combinator) {
|
||||
var uTagName = tagName.toUpperCase();
|
||||
var results = [], h = Selector.handlers;
|
||||
if (nodes) {
|
||||
if (combinator) {
|
||||
// fastlane for ordinary descendant combinators
|
||||
if (combinator == "descendant") {
|
||||
for (var i = 0, node; node = nodes[i]; i++)
|
||||
h.concat(results, node.getElementsByTagName(tagName));
|
||||
return results;
|
||||
} else nodes = this[combinator](nodes);
|
||||
if (tagName == "*") return nodes;
|
||||
}
|
||||
for (var i = 0, node; node = nodes[i]; i++)
|
||||
if (node.tagName.toUpperCase() === uTagName) results.push(node);
|
||||
return results;
|
||||
} else return root.getElementsByTagName(tagName);
|
||||
},
|
||||
|
||||
id: function(nodes, root, id, combinator) {
|
||||
var targetNode = $(id), h = Selector.handlers;
|
||||
if (!targetNode) return [];
|
||||
if (!nodes && root == document) return [targetNode];
|
||||
if (nodes) {
|
||||
if (combinator) {
|
||||
if (combinator == 'child') {
|
||||
for (var i = 0, node; node = nodes[i]; i++)
|
||||
if (targetNode.parentNode == node) return [targetNode];
|
||||
} else if (combinator == 'descendant') {
|
||||
for (var i = 0, node; node = nodes[i]; i++)
|
||||
if (Element.descendantOf(targetNode, node)) return [targetNode];
|
||||
} else if (combinator == 'adjacent') {
|
||||
for (var i = 0, node; node = nodes[i]; i++)
|
||||
if (Selector.handlers.previousElementSibling(targetNode) == node)
|
||||
return [targetNode];
|
||||
} else nodes = h[combinator](nodes);
|
||||
}
|
||||
for (var i = 0, node; node = nodes[i]; i++)
|
||||
if (node == targetNode) return [targetNode];
|
||||
return [];
|
||||
}
|
||||
return (targetNode && Element.descendantOf(targetNode, root)) ? [targetNode] : [];
|
||||
},
|
||||
|
||||
className: function(nodes, root, className, combinator) {
|
||||
if (nodes && combinator) nodes = this[combinator](nodes);
|
||||
return Selector.handlers.byClassName(nodes, root, className);
|
||||
},
|
||||
|
||||
byClassName: function(nodes, root, className) {
|
||||
if (!nodes) nodes = Selector.handlers.descendant([root]);
|
||||
var needle = ' ' + className + ' ';
|
||||
for (var i = 0, results = [], node, nodeClassName; node = nodes[i]; i++) {
|
||||
nodeClassName = node.className;
|
||||
if (nodeClassName.length == 0) continue;
|
||||
if (nodeClassName == className || (' ' + nodeClassName + ' ').include(needle))
|
||||
results.push(node);
|
||||
}
|
||||
return results;
|
||||
},
|
||||
|
||||
attrPresence: function(nodes, root, attr, combinator) {
|
||||
if (!nodes) nodes = root.getElementsByTagName("*");
|
||||
if (nodes && combinator) nodes = this[combinator](nodes);
|
||||
var results = [];
|
||||
for (var i = 0, node; node = nodes[i]; i++)
|
||||
if (Element.hasAttribute(node, attr)) results.push(node);
|
||||
return results;
|
||||
},
|
||||
|
||||
attr: function(nodes, root, attr, value, operator, combinator) {
|
||||
if (!nodes) nodes = root.getElementsByTagName("*");
|
||||
if (nodes && combinator) nodes = this[combinator](nodes);
|
||||
var handler = Selector.operators[operator], results = [];
|
||||
for (var i = 0, node; node = nodes[i]; i++) {
|
||||
var nodeValue = Element.readAttribute(node, attr);
|
||||
if (nodeValue === null) continue;
|
||||
if (handler(nodeValue, value)) results.push(node);
|
||||
}
|
||||
return results;
|
||||
},
|
||||
|
||||
pseudo: function(nodes, name, value, root, combinator) {
|
||||
if (nodes && combinator) nodes = this[combinator](nodes);
|
||||
if (!nodes) nodes = root.getElementsByTagName("*");
|
||||
return Selector.pseudos[name](nodes, value, root);
|
||||
}
|
||||
},
|
||||
|
||||
pseudos: {
|
||||
'first-child': function(nodes, value, root) {
|
||||
for (var i = 0, results = [], node; node = nodes[i]; i++) {
|
||||
if (Selector.handlers.previousElementSibling(node)) continue;
|
||||
results.push(node);
|
||||
}
|
||||
return results;
|
||||
},
|
||||
'last-child': function(nodes, value, root) {
|
||||
for (var i = 0, results = [], node; node = nodes[i]; i++) {
|
||||
if (Selector.handlers.nextElementSibling(node)) continue;
|
||||
results.push(node);
|
||||
}
|
||||
return results;
|
||||
},
|
||||
'only-child': function(nodes, value, root) {
|
||||
var h = Selector.handlers;
|
||||
for (var i = 0, results = [], node; node = nodes[i]; i++)
|
||||
if (!h.previousElementSibling(node) && !h.nextElementSibling(node))
|
||||
results.push(node);
|
||||
return results;
|
||||
},
|
||||
'nth-child': function(nodes, formula, root) {
|
||||
return Selector.pseudos.nth(nodes, formula, root);
|
||||
},
|
||||
'nth-last-child': function(nodes, formula, root) {
|
||||
return Selector.pseudos.nth(nodes, formula, root, true);
|
||||
},
|
||||
'nth-of-type': function(nodes, formula, root) {
|
||||
return Selector.pseudos.nth(nodes, formula, root, false, true);
|
||||
},
|
||||
'nth-last-of-type': function(nodes, formula, root) {
|
||||
return Selector.pseudos.nth(nodes, formula, root, true, true);
|
||||
},
|
||||
'first-of-type': function(nodes, formula, root) {
|
||||
return Selector.pseudos.nth(nodes, "1", root, false, true);
|
||||
},
|
||||
'last-of-type': function(nodes, formula, root) {
|
||||
return Selector.pseudos.nth(nodes, "1", root, true, true);
|
||||
},
|
||||
'only-of-type': function(nodes, formula, root) {
|
||||
var p = Selector.pseudos;
|
||||
return p['last-of-type'](p['first-of-type'](nodes, formula, root), formula, root);
|
||||
},
|
||||
|
||||
// handles the an+b logic
|
||||
getIndices: function(a, b, total) {
|
||||
if (a == 0) return b > 0 ? [b] : [];
|
||||
return $R(1, total).inject([], function(memo, i) {
|
||||
if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i);
|
||||
return memo;
|
||||
});
|
||||
},
|
||||
|
||||
// handles nth(-last)-child, nth(-last)-of-type, and (first|last)-of-type
|
||||
nth: function(nodes, formula, root, reverse, ofType) {
|
||||
if (nodes.length == 0) return [];
|
||||
if (formula == 'even') formula = '2n+0';
|
||||
if (formula == 'odd') formula = '2n+1';
|
||||
var h = Selector.handlers, results = [], indexed = [], m;
|
||||
h.mark(nodes);
|
||||
for (var i = 0, node; node = nodes[i]; i++) {
|
||||
if (!node.parentNode._countedByPrototype) {
|
||||
h.index(node.parentNode, reverse, ofType);
|
||||
indexed.push(node.parentNode);
|
||||
}
|
||||
}
|
||||
if (formula.match(/^\d+$/)) { // just a number
|
||||
formula = Number(formula);
|
||||
for (var i = 0, node; node = nodes[i]; i++)
|
||||
if (node.nodeIndex == formula) results.push(node);
|
||||
} else if (m = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
|
||||
if (m[1] == "-") m[1] = -1;
|
||||
var a = m[1] ? Number(m[1]) : 1;
|
||||
var b = m[2] ? Number(m[2]) : 0;
|
||||
var indices = Selector.pseudos.getIndices(a, b, nodes.length);
|
||||
for (var i = 0, node, l = indices.length; node = nodes[i]; i++) {
|
||||
for (var j = 0; j < l; j++)
|
||||
if (node.nodeIndex == indices[j]) results.push(node);
|
||||
}
|
||||
}
|
||||
h.unmark(nodes);
|
||||
h.unmark(indexed);
|
||||
return results;
|
||||
},
|
||||
|
||||
'empty': function(nodes, value, root) {
|
||||
for (var i = 0, results = [], node; node = nodes[i]; i++) {
|
||||
// IE treats comments as element nodes
|
||||
if (node.tagName == '!' || node.firstChild) continue;
|
||||
results.push(node);
|
||||
}
|
||||
return results;
|
||||
},
|
||||
|
||||
'not': function(nodes, selector, root) {
|
||||
var h = Selector.handlers, selectorType, m;
|
||||
var exclusions = new Selector(selector).findElements(root);
|
||||
h.mark(exclusions);
|
||||
for (var i = 0, results = [], node; node = nodes[i]; i++)
|
||||
if (!node._countedByPrototype) results.push(node);
|
||||
h.unmark(exclusions);
|
||||
return results;
|
||||
},
|
||||
|
||||
'enabled': function(nodes, value, root) {
|
||||
for (var i = 0, results = [], node; node = nodes[i]; i++)
|
||||
if (!node.disabled && (!node.type || node.type !== 'hidden'))
|
||||
results.push(node);
|
||||
return results;
|
||||
},
|
||||
|
||||
'disabled': function(nodes, value, root) {
|
||||
for (var i = 0, results = [], node; node = nodes[i]; i++)
|
||||
if (node.disabled) results.push(node);
|
||||
return results;
|
||||
},
|
||||
|
||||
'checked': function(nodes, value, root) {
|
||||
for (var i = 0, results = [], node; node = nodes[i]; i++)
|
||||
if (node.checked) results.push(node);
|
||||
return results;
|
||||
}
|
||||
},
|
||||
|
||||
operators: {
|
||||
'=': function(nv, v) { return nv == v; },
|
||||
'!=': function(nv, v) { return nv != v; },
|
||||
'^=': function(nv, v) { return nv == v || nv && nv.startsWith(v); },
|
||||
'$=': function(nv, v) { return nv == v || nv && nv.endsWith(v); },
|
||||
'*=': function(nv, v) { return nv == v || nv && nv.include(v); },
|
||||
'$=': function(nv, v) { return nv.endsWith(v); },
|
||||
'*=': function(nv, v) { return nv.include(v); },
|
||||
'~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); },
|
||||
'|=': function(nv, v) { return ('-' + (nv || "").toUpperCase() +
|
||||
'-').include('-' + (v || "").toUpperCase() + '-'); }
|
||||
},
|
||||
|
||||
split: function(expression) {
|
||||
var expressions = [];
|
||||
expression.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) {
|
||||
expressions.push(m[1].strip());
|
||||
});
|
||||
return expressions;
|
||||
},
|
||||
|
||||
matchElements: function(elements, expression) {
|
||||
var matches = $$(expression), h = Selector.handlers;
|
||||
h.mark(matches);
|
||||
for (var i = 0, results = [], element; element = elements[i]; i++)
|
||||
if (element._countedByPrototype) results.push(element);
|
||||
h.unmark(matches);
|
||||
return results;
|
||||
},
|
||||
|
||||
findElement: function(elements, expression, index) {
|
||||
if (Object.isNumber(expression)) {
|
||||
index = expression; expression = false;
|
||||
}
|
||||
return Selector.matchElements(elements, expression || '*')[index || 0];
|
||||
},
|
||||
|
||||
findChildElements: function(element, expressions) {
|
||||
expressions = Selector.split(expressions.join(','));
|
||||
var results = [], h = Selector.handlers;
|
||||
for (var i = 0, l = expressions.length, selector; i < l; i++) {
|
||||
selector = new Selector(expressions[i].strip());
|
||||
h.concat(results, selector.findElements(element));
|
||||
}
|
||||
return (l > 1) ? h.unique(results) : results;
|
||||
}
|
||||
});
|
||||
|
||||
if (Prototype.Browser.IE) {
|
||||
Object.extend(Selector.handlers, {
|
||||
// IE returns comment nodes on getElementsByTagName("*").
|
||||
// Filter them out.
|
||||
concat: function(a, b) {
|
||||
for (var i = 0, node; node = b[i]; i++)
|
||||
if (node.tagName !== "!") a.push(node);
|
||||
return a;
|
||||
},
|
||||
|
||||
// IE improperly serializes _countedByPrototype in (inner|outer)HTML.
|
||||
unmark: function(nodes) {
|
||||
for (var i = 0, node; node = nodes[i]; i++)
|
||||
node.removeAttribute('_countedByPrototype');
|
||||
return nodes;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function $$() {
|
||||
return Selector.findChildElements(document, $A(arguments));
|
||||
}
|
||||
var Form = {
|
||||
reset: function(form) {
|
||||
$(form).reset();
|
||||
return form;
|
||||
},
|
||||
|
||||
serializeElements: function(elements, options) {
|
||||
if (typeof options != 'object') options = { hash: !!options };
|
||||
else if (Object.isUndefined(options.hash)) options.hash = true;
|
||||
var key, value, submitted = false, submit = options.submit;
|
||||
|
||||
var data = elements.inject({ }, function(result, element) {
|
||||
if (!element.disabled && element.name) {
|
||||
key = element.name; value = $(element).getValue();
|
||||
if (value != null && element.type != 'file' && (element.type != 'submit' || (!submitted &&
|
||||
submit !== false && (!submit || key == submit) && (submitted = true)))) {
|
||||
if (key in result) {
|
||||
// a key is already present; construct an array of values
|
||||
if (!Object.isArray(result[key])) result[key] = [result[key]];
|
||||
result[key].push(value);
|
||||
}
|
||||
else result[key] = value;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
});
|
||||
|
||||
return options.hash ? data : Object.toQueryString(data);
|
||||
}
|
||||
};
|
||||
|
||||
Form.Methods = {
|
||||
serialize: function(form, options) {
|
||||
return Form.serializeElements(Form.getElements(form), options);
|
||||
},
|
||||
|
||||
getElements: function(form) {
|
||||
return $A($(form).getElementsByTagName('*')).inject([],
|
||||
function(elements, child) {
|
||||
if (Form.Element.Serializers[child.tagName.toLowerCase()])
|
||||
elements.push(Element.extend(child));
|
||||
return elements;
|
||||
}
|
||||
);
|
||||
},
|
||||
|
||||
getInputs: function(form, typeName, name) {
|
||||
form = $(form);
|
||||
var inputs = form.getElementsByTagName('input');
|
||||
|
||||
if (!typeName && !name) return $A(inputs).map(Element.extend);
|
||||
|
||||
for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
|
||||
var input = inputs[i];
|
||||
if ((typeName && input.type != typeName) || (name && input.name != name))
|
||||
continue;
|
||||
matchingInputs.push(Element.extend(input));
|
||||
}
|
||||
|
||||
return matchingInputs;
|
||||
},
|
||||
|
||||
disable: function(form) {
|
||||
form = $(form);
|
||||
Form.getElements(form).invoke('disable');
|
||||
return form;
|
||||
},
|
||||
|
||||
enable: function(form) {
|
||||
form = $(form);
|
||||
Form.getElements(form).invoke('enable');
|
||||
return form;
|
||||
},
|
||||
|
||||
findFirstElement: function(form) {
|
||||
var elements = $(form).getElements().findAll(function(element) {
|
||||
return 'hidden' != element.type && !element.disabled;
|
||||
});
|
||||
var firstByIndex = elements.findAll(function(element) {
|
||||
return element.hasAttribute('tabIndex') && element.tabIndex >= 0;
|
||||
}).sortBy(function(element) { return element.tabIndex }).first();
|
||||
|
||||
return firstByIndex ? firstByIndex : elements.find(function(element) {
|
||||
return ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
|
||||
});
|
||||
},
|
||||
|
||||
focusFirstElement: function(form) {
|
||||
form = $(form);
|
||||
form.findFirstElement().activate();
|
||||
return form;
|
||||
},
|
||||
|
||||
request: function(form, options) {
|
||||
form = $(form), options = Object.clone(options || { });
|
||||
|
||||
var params = options.parameters, action = form.readAttribute('action') || '';
|
||||
if (action.blank()) action = window.location.href;
|
||||
options.parameters = form.serialize(true);
|
||||
|
||||
if (params) {
|
||||
if (Object.isString(params)) params = params.toQueryParams();
|
||||
Object.extend(options.parameters, params);
|
||||
}
|
||||
|
||||
if (form.hasAttribute('method') && !options.method)
|
||||
options.method = form.method;
|
||||
|
||||
return new Ajax.Request(action, options);
|
||||
}
|
||||
};
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
Form.Element = {
|
||||
focus: function(element) {
|
||||
$(element).focus();
|
||||
return element;
|
||||
},
|
||||
|
||||
select: function(element) {
|
||||
$(element).select();
|
||||
return element;
|
||||
}
|
||||
};
|
||||
|
||||
Form.Element.Methods = {
|
||||
serialize: function(element) {
|
||||
element = $(element);
|
||||
if (!element.disabled && element.name) {
|
||||
var value = element.getValue();
|
||||
if (value != undefined) {
|
||||
var pair = { };
|
||||
pair[element.name] = value;
|
||||
return Object.toQueryString(pair);
|
||||
}
|
||||
}
|
||||
return '';
|
||||
},
|
||||
|
||||
getValue: function(element) {
|
||||
element = $(element);
|
||||
var method = element.tagName.toLowerCase();
|
||||
return Form.Element.Serializers[method](element);
|
||||
},
|
||||
|
||||
setValue: function(element, value) {
|
||||
element = $(element);
|
||||
var method = element.tagName.toLowerCase();
|
||||
Form.Element.Serializers[method](element, value);
|
||||
return element;
|
||||
},
|
||||
|
||||
clear: function(element) {
|
||||
$(element).value = '';
|
||||
return element;
|
||||
},
|
||||
|
||||
present: function(element) {
|
||||
return $(element).value != '';
|
||||
},
|
||||
|
||||
activate: function(element) {
|
||||
element = $(element);
|
||||
try {
|
||||
element.focus();
|
||||
if (element.select && (element.tagName.toLowerCase() != 'input' ||
|
||||
!['button', 'reset', 'submit'].include(element.type)))
|
||||
element.select();
|
||||
} catch (e) { }
|
||||
return element;
|
||||
},
|
||||
|
||||
disable: function(element) {
|
||||
element = $(element);
|
||||
element.disabled = true;
|
||||
return element;
|
||||
},
|
||||
|
||||
enable: function(element) {
|
||||
element = $(element);
|
||||
element.disabled = false;
|
||||
return element;
|
||||
}
|
||||
};
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
var Field = Form.Element;
|
||||
var $F = Form.Element.Methods.getValue;
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
Form.Element.Serializers = {
|
||||
input: function(element, value) {
|
||||
switch (element.type.toLowerCase()) {
|
||||
case 'checkbox':
|
||||
case 'radio':
|
||||
return Form.Element.Serializers.inputSelector(element, value);
|
||||
default:
|
||||
return Form.Element.Serializers.textarea(element, value);
|
||||
}
|
||||
},
|
||||
|
||||
inputSelector: function(element, value) {
|
||||
if (Object.isUndefined(value)) return element.checked ? element.value : null;
|
||||
else element.checked = !!value;
|
||||
},
|
||||
|
||||
textarea: function(element, value) {
|
||||
if (Object.isUndefined(value)) return element.value;
|
||||
else element.value = value;
|
||||
},
|
||||
|
||||
select: function(element, value) {
|
||||
if (Object.isUndefined(value))
|
||||
return this[element.type == 'select-one' ?
|
||||
'selectOne' : 'selectMany'](element);
|
||||
else {
|
||||
var opt, currentValue, single = !Object.isArray(value);
|
||||
for (var i = 0, length = element.length; i < length; i++) {
|
||||
opt = element.options[i];
|
||||
currentValue = this.optionValue(opt);
|
||||
if (single) {
|
||||
if (currentValue == value) {
|
||||
opt.selected = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
else opt.selected = value.include(currentValue);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
selectOne: function(element) {
|
||||
var index = element.selectedIndex;
|
||||
return index >= 0 ? this.optionValue(element.options[index]) : null;
|
||||
},
|
||||
|
||||
selectMany: function(element) {
|
||||
var values, length = element.length;
|
||||
if (!length) return null;
|
||||
|
||||
for (var i = 0, values = []; i < length; i++) {
|
||||
var opt = element.options[i];
|
||||
if (opt.selected) values.push(this.optionValue(opt));
|
||||
}
|
||||
return values;
|
||||
},
|
||||
|
||||
optionValue: function(opt) {
|
||||
// extend element because hasAttribute may not be native
|
||||
return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
|
||||
}
|
||||
};
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
Abstract.TimedObserver = Class.create(PeriodicalExecuter, {
|
||||
initialize: function($super, element, frequency, callback) {
|
||||
$super(callback, frequency);
|
||||
this.element = $(element);
|
||||
this.lastValue = this.getValue();
|
||||
},
|
||||
|
||||
execute: function() {
|
||||
var value = this.getValue();
|
||||
if (Object.isString(this.lastValue) && Object.isString(value) ?
|
||||
this.lastValue != value : String(this.lastValue) != String(value)) {
|
||||
this.callback(this.element, value);
|
||||
this.lastValue = value;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Form.Element.Observer = Class.create(Abstract.TimedObserver, {
|
||||
getValue: function() {
|
||||
return Form.Element.getValue(this.element);
|
||||
}
|
||||
});
|
||||
|
||||
Form.Observer = Class.create(Abstract.TimedObserver, {
|
||||
getValue: function() {
|
||||
return Form.serialize(this.element);
|
||||
}
|
||||
});
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
Abstract.EventObserver = Class.create({
|
||||
initialize: function(element, callback) {
|
||||
this.element = $(element);
|
||||
this.callback = callback;
|
||||
|
||||
this.lastValue = this.getValue();
|
||||
if (this.element.tagName.toLowerCase() == 'form')
|
||||
this.registerFormCallbacks();
|
||||
else
|
||||
this.registerCallback(this.element);
|
||||
},
|
||||
|
||||
onElementEvent: function() {
|
||||
var value = this.getValue();
|
||||
if (this.lastValue != value) {
|
||||
this.callback(this.element, value);
|
||||
this.lastValue = value;
|
||||
}
|
||||
},
|
||||
|
||||
registerFormCallbacks: function() {
|
||||
Form.getElements(this.element).each(this.registerCallback, this);
|
||||
},
|
||||
|
||||
registerCallback: function(element) {
|
||||
if (element.type) {
|
||||
switch (element.type.toLowerCase()) {
|
||||
case 'checkbox':
|
||||
case 'radio':
|
||||
Event.observe(element, 'click', this.onElementEvent.bind(this));
|
||||
break;
|
||||
default:
|
||||
Event.observe(element, 'change', this.onElementEvent.bind(this));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Form.Element.EventObserver = Class.create(Abstract.EventObserver, {
|
||||
getValue: function() {
|
||||
return Form.Element.getValue(this.element);
|
||||
}
|
||||
});
|
||||
|
||||
Form.EventObserver = Class.create(Abstract.EventObserver, {
|
||||
getValue: function() {
|
||||
return Form.serialize(this.element);
|
||||
}
|
||||
});
|
||||
if (!window.Event) var Event = { };
|
||||
|
||||
Object.extend(Event, {
|
||||
KEY_BACKSPACE: 8,
|
||||
KEY_TAB: 9,
|
||||
KEY_RETURN: 13,
|
||||
KEY_ESC: 27,
|
||||
KEY_LEFT: 37,
|
||||
KEY_UP: 38,
|
||||
KEY_RIGHT: 39,
|
||||
KEY_DOWN: 40,
|
||||
KEY_DELETE: 46,
|
||||
KEY_HOME: 36,
|
||||
KEY_END: 35,
|
||||
KEY_PAGEUP: 33,
|
||||
KEY_PAGEDOWN: 34,
|
||||
KEY_INSERT: 45,
|
||||
|
||||
cache: { },
|
||||
|
||||
relatedTarget: function(event) {
|
||||
var element;
|
||||
switch(event.type) {
|
||||
case 'mouseover': element = event.fromElement; break;
|
||||
case 'mouseout': element = event.toElement; break;
|
||||
default: return null;
|
||||
}
|
||||
return Element.extend(element);
|
||||
}
|
||||
});
|
||||
|
||||
Event.Methods = (function() {
|
||||
var isButton;
|
||||
|
||||
if (Prototype.Browser.IE) {
|
||||
var buttonMap = { 0: 1, 1: 4, 2: 2 };
|
||||
isButton = function(event, code) {
|
||||
return event.button == buttonMap[code];
|
||||
};
|
||||
|
||||
} else if (Prototype.Browser.WebKit) {
|
||||
isButton = function(event, code) {
|
||||
switch (code) {
|
||||
case 0: return event.which == 1 && !event.metaKey;
|
||||
case 1: return event.which == 1 && event.metaKey;
|
||||
default: return false;
|
||||
}
|
||||
};
|
||||
|
||||
} else {
|
||||
isButton = function(event, code) {
|
||||
return event.which ? (event.which === code + 1) : (event.button === code);
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
isLeftClick: function(event) { return isButton(event, 0) },
|
||||
isMiddleClick: function(event) { return isButton(event, 1) },
|
||||
isRightClick: function(event) { return isButton(event, 2) },
|
||||
|
||||
element: function(event) {
|
||||
event = Event.extend(event);
|
||||
|
||||
var node = event.target,
|
||||
type = event.type,
|
||||
currentTarget = event.currentTarget;
|
||||
|
||||
if (currentTarget && currentTarget.tagName) {
|
||||
// Firefox screws up the "click" event when moving between radio buttons
|
||||
// via arrow keys. It also screws up the "load" and "error" events on images,
|
||||
// reporting the document as the target instead of the original image.
|
||||
if (type === 'load' || type === 'error' ||
|
||||
(type === 'click' && currentTarget.tagName.toLowerCase() === 'input'
|
||||
&& currentTarget.type === 'radio'))
|
||||
node = currentTarget;
|
||||
}
|
||||
if (node.nodeType == Node.TEXT_NODE) node = node.parentNode;
|
||||
return Element.extend(node);
|
||||
},
|
||||
|
||||
findElement: function(event, expression) {
|
||||
var element = Event.element(event);
|
||||
if (!expression) return element;
|
||||
var elements = [element].concat(element.ancestors());
|
||||
return Selector.findElement(elements, expression, 0);
|
||||
},
|
||||
|
||||
pointer: function(event) {
|
||||
var docElement = document.documentElement,
|
||||
body = document.body || { scrollLeft: 0, scrollTop: 0 };
|
||||
return {
|
||||
x: event.pageX || (event.clientX +
|
||||
(docElement.scrollLeft || body.scrollLeft) -
|
||||
(docElement.clientLeft || 0)),
|
||||
y: event.pageY || (event.clientY +
|
||||
(docElement.scrollTop || body.scrollTop) -
|
||||
(docElement.clientTop || 0))
|
||||
};
|
||||
},
|
||||
|
||||
pointerX: function(event) { return Event.pointer(event).x },
|
||||
pointerY: function(event) { return Event.pointer(event).y },
|
||||
|
||||
stop: function(event) {
|
||||
Event.extend(event);
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
event.stopped = true;
|
||||
}
|
||||
};
|
||||
})();
|
||||
|
||||
Event.extend = (function() {
|
||||
var methods = Object.keys(Event.Methods).inject({ }, function(m, name) {
|
||||
m[name] = Event.Methods[name].methodize();
|
||||
return m;
|
||||
});
|
||||
|
||||
if (Prototype.Browser.IE) {
|
||||
Object.extend(methods, {
|
||||
stopPropagation: function() { this.cancelBubble = true },
|
||||
preventDefault: function() { this.returnValue = false },
|
||||
inspect: function() { return "[object Event]" }
|
||||
});
|
||||
|
||||
return function(event) {
|
||||
if (!event) return false;
|
||||
if (event._extendedByPrototype) return event;
|
||||
|
||||
event._extendedByPrototype = Prototype.emptyFunction;
|
||||
var pointer = Event.pointer(event);
|
||||
Object.extend(event, {
|
||||
target: event.srcElement,
|
||||
relatedTarget: Event.relatedTarget(event),
|
||||
pageX: pointer.x,
|
||||
pageY: pointer.y
|
||||
});
|
||||
return Object.extend(event, methods);
|
||||
};
|
||||
|
||||
} else {
|
||||
Event.prototype = Event.prototype || document.createEvent("HTMLEvents")['__proto__'];
|
||||
Object.extend(Event.prototype, methods);
|
||||
return Prototype.K;
|
||||
}
|
||||
})();
|
||||
|
||||
Object.extend(Event, (function() {
|
||||
var cache = Event.cache;
|
||||
|
||||
function getEventID(element) {
|
||||
if (element._prototypeEventID) return element._prototypeEventID[0];
|
||||
arguments.callee.id = arguments.callee.id || 1;
|
||||
return element._prototypeEventID = [++arguments.callee.id];
|
||||
}
|
||||
|
||||
function getDOMEventName(eventName) {
|
||||
if (eventName && eventName.include(':')) return "dataavailable";
|
||||
return eventName;
|
||||
}
|
||||
|
||||
function getCacheForID(id) {
|
||||
return cache[id] = cache[id] || { };
|
||||
}
|
||||
|
||||
function getWrappersForEventName(id, eventName) {
|
||||
var c = getCacheForID(id);
|
||||
return c[eventName] = c[eventName] || [];
|
||||
}
|
||||
|
||||
function createWrapper(element, eventName, handler) {
|
||||
var id = getEventID(element);
|
||||
var c = getWrappersForEventName(id, eventName);
|
||||
if (c.pluck("handler").include(handler)) return false;
|
||||
|
||||
var wrapper = function(event) {
|
||||
if (!Event || !Event.extend ||
|
||||
(event.eventName && event.eventName != eventName))
|
||||
return false;
|
||||
|
||||
Event.extend(event);
|
||||
handler.call(element, event);
|
||||
};
|
||||
|
||||
wrapper.handler = handler;
|
||||
c.push(wrapper);
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
function findWrapper(id, eventName, handler) {
|
||||
var c = getWrappersForEventName(id, eventName);
|
||||
return c.find(function(wrapper) { return wrapper.handler == handler });
|
||||
}
|
||||
|
||||
function destroyWrapper(id, eventName, handler) {
|
||||
var c = getCacheForID(id);
|
||||
if (!c[eventName]) return false;
|
||||
c[eventName] = c[eventName].without(findWrapper(id, eventName, handler));
|
||||
}
|
||||
|
||||
function destroyCache() {
|
||||
for (var id in cache)
|
||||
for (var eventName in cache[id])
|
||||
cache[id][eventName] = null;
|
||||
}
|
||||
|
||||
|
||||
// Internet Explorer needs to remove event handlers on page unload
|
||||
// in order to avoid memory leaks.
|
||||
if (window.attachEvent) {
|
||||
window.attachEvent("onunload", destroyCache);
|
||||
}
|
||||
|
||||
// Safari has a dummy event handler on page unload so that it won't
|
||||
// use its bfcache. Safari <= 3.1 has an issue with restoring the "document"
|
||||
// object when page is returned to via the back button using its bfcache.
|
||||
if (Prototype.Browser.WebKit) {
|
||||
window.addEventListener('unload', Prototype.emptyFunction, false);
|
||||
}
|
||||
|
||||
return {
|
||||
observe: function(element, eventName, handler) {
|
||||
element = $(element);
|
||||
var name = getDOMEventName(eventName);
|
||||
|
||||
var wrapper = createWrapper(element, eventName, handler);
|
||||
if (!wrapper) return element;
|
||||
|
||||
if (element.addEventListener) {
|
||||
element.addEventListener(name, wrapper, false);
|
||||
} else {
|
||||
element.attachEvent("on" + name, wrapper);
|
||||
}
|
||||
|
||||
return element;
|
||||
},
|
||||
|
||||
stopObserving: function(element, eventName, handler) {
|
||||
element = $(element);
|
||||
var id = getEventID(element), name = getDOMEventName(eventName);
|
||||
|
||||
if (!handler && eventName) {
|
||||
getWrappersForEventName(id, eventName).each(function(wrapper) {
|
||||
element.stopObserving(eventName, wrapper.handler);
|
||||
});
|
||||
return element;
|
||||
|
||||
} else if (!eventName) {
|
||||
Object.keys(getCacheForID(id)).each(function(eventName) {
|
||||
element.stopObserving(eventName);
|
||||
});
|
||||
return element;
|
||||
}
|
||||
|
||||
var wrapper = findWrapper(id, eventName, handler);
|
||||
if (!wrapper) return element;
|
||||
|
||||
if (element.removeEventListener) {
|
||||
element.removeEventListener(name, wrapper, false);
|
||||
} else {
|
||||
element.detachEvent("on" + name, wrapper);
|
||||
}
|
||||
|
||||
destroyWrapper(id, eventName, handler);
|
||||
|
||||
return element;
|
||||
},
|
||||
|
||||
fire: function(element, eventName, memo) {
|
||||
element = $(element);
|
||||
if (element == document && document.createEvent && !element.dispatchEvent)
|
||||
element = document.documentElement;
|
||||
|
||||
var event;
|
||||
if (document.createEvent) {
|
||||
event = document.createEvent("HTMLEvents");
|
||||
event.initEvent("dataavailable", true, true);
|
||||
} else {
|
||||
event = document.createEventObject();
|
||||
event.eventType = "ondataavailable";
|
||||
}
|
||||
|
||||
event.eventName = eventName;
|
||||
event.memo = memo || { };
|
||||
|
||||
if (document.createEvent) {
|
||||
element.dispatchEvent(event);
|
||||
} else {
|
||||
element.fireEvent(event.eventType, event);
|
||||
}
|
||||
|
||||
return Event.extend(event);
|
||||
}
|
||||
};
|
||||
})());
|
||||
|
||||
Object.extend(Event, Event.Methods);
|
||||
|
||||
Element.addMethods({
|
||||
fire: Event.fire,
|
||||
observe: Event.observe,
|
||||
stopObserving: Event.stopObserving
|
||||
});
|
||||
|
||||
Object.extend(document, {
|
||||
fire: Element.Methods.fire.methodize(),
|
||||
observe: Element.Methods.observe.methodize(),
|
||||
stopObserving: Element.Methods.stopObserving.methodize(),
|
||||
loaded: false
|
||||
});
|
||||
|
||||
(function() {
|
||||
/* Support for the DOMContentLoaded event is based on work by Dan Webb,
|
||||
Matthias Miller, Dean Edwards and John Resig. */
|
||||
|
||||
var timer;
|
||||
|
||||
function fireContentLoadedEvent() {
|
||||
if (document.loaded) return;
|
||||
if (timer) window.clearInterval(timer);
|
||||
document.fire("dom:loaded");
|
||||
document.loaded = true;
|
||||
}
|
||||
|
||||
if (document.addEventListener) {
|
||||
if (Prototype.Browser.WebKit) {
|
||||
timer = window.setInterval(function() {
|
||||
if (/loaded|complete/.test(document.readyState))
|
||||
fireContentLoadedEvent();
|
||||
}, 0);
|
||||
|
||||
Event.observe(window, "load", fireContentLoadedEvent);
|
||||
|
||||
} else {
|
||||
document.addEventListener("DOMContentLoaded",
|
||||
fireContentLoadedEvent, false);
|
||||
}
|
||||
|
||||
} else {
|
||||
document.write("<script id=__onDOMContentLoaded defer src=//:><\/script>");
|
||||
$("__onDOMContentLoaded").onreadystatechange = function() {
|
||||
if (this.readyState == "complete") {
|
||||
this.onreadystatechange = null;
|
||||
fireContentLoadedEvent();
|
||||
}
|
||||
};
|
||||
}
|
||||
})();
|
||||
/*------------------------------- DEPRECATED -------------------------------*/
|
||||
|
||||
Hash.toQueryString = Object.toQueryString;
|
||||
|
||||
var Toggle = { display: Element.toggle };
|
||||
|
||||
Element.Methods.childOf = Element.Methods.descendantOf;
|
||||
|
||||
var Insertion = {
|
||||
Before: function(element, content) {
|
||||
return Element.insert(element, {before:content});
|
||||
},
|
||||
|
||||
Top: function(element, content) {
|
||||
return Element.insert(element, {top:content});
|
||||
},
|
||||
|
||||
Bottom: function(element, content) {
|
||||
return Element.insert(element, {bottom:content});
|
||||
},
|
||||
|
||||
After: function(element, content) {
|
||||
return Element.insert(element, {after:content});
|
||||
}
|
||||
};
|
||||
|
||||
var $continue = new Error('"throw $continue" is deprecated, use "return" instead');
|
||||
|
||||
// This should be moved to script.aculo.us; notice the deprecated methods
|
||||
// further below, that map to the newer Element methods.
|
||||
var Position = {
|
||||
// set to true if needed, warning: firefox performance problems
|
||||
// NOT neeeded for page scrolling, only if draggable contained in
|
||||
// scrollable elements
|
||||
includeScrollOffsets: false,
|
||||
|
||||
// must be called before calling withinIncludingScrolloffset, every time the
|
||||
// page is scrolled
|
||||
prepare: function() {
|
||||
this.deltaX = window.pageXOffset
|
||||
|| document.documentElement.scrollLeft
|
||||
|| document.body.scrollLeft
|
||||
|| 0;
|
||||
this.deltaY = window.pageYOffset
|
||||
|| document.documentElement.scrollTop
|
||||
|| document.body.scrollTop
|
||||
|| 0;
|
||||
},
|
||||
|
||||
// caches x/y coordinate pair to use with overlap
|
||||
within: function(element, x, y) {
|
||||
if (this.includeScrollOffsets)
|
||||
return this.withinIncludingScrolloffsets(element, x, y);
|
||||
this.xcomp = x;
|
||||
this.ycomp = y;
|
||||
this.offset = Element.cumulativeOffset(element);
|
||||
|
||||
return (y >= this.offset[1] &&
|
||||
y < this.offset[1] + element.offsetHeight &&
|
||||
x >= this.offset[0] &&
|
||||
x < this.offset[0] + element.offsetWidth);
|
||||
},
|
||||
|
||||
withinIncludingScrolloffsets: function(element, x, y) {
|
||||
var offsetcache = Element.cumulativeScrollOffset(element);
|
||||
|
||||
this.xcomp = x + offsetcache[0] - this.deltaX;
|
||||
this.ycomp = y + offsetcache[1] - this.deltaY;
|
||||
this.offset = Element.cumulativeOffset(element);
|
||||
|
||||
return (this.ycomp >= this.offset[1] &&
|
||||
this.ycomp < this.offset[1] + element.offsetHeight &&
|
||||
this.xcomp >= this.offset[0] &&
|
||||
this.xcomp < this.offset[0] + element.offsetWidth);
|
||||
},
|
||||
|
||||
// within must be called directly before
|
||||
overlap: function(mode, element) {
|
||||
if (!mode) return 0;
|
||||
if (mode == 'vertical')
|
||||
return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
|
||||
element.offsetHeight;
|
||||
if (mode == 'horizontal')
|
||||
return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
|
||||
element.offsetWidth;
|
||||
},
|
||||
|
||||
// Deprecation layer -- use newer Element methods now (1.5.2).
|
||||
|
||||
cumulativeOffset: Element.Methods.cumulativeOffset,
|
||||
|
||||
positionedOffset: Element.Methods.positionedOffset,
|
||||
|
||||
absolutize: function(element) {
|
||||
Position.prepare();
|
||||
return Element.absolutize(element);
|
||||
},
|
||||
|
||||
relativize: function(element) {
|
||||
Position.prepare();
|
||||
return Element.relativize(element);
|
||||
},
|
||||
|
||||
realOffset: Element.Methods.cumulativeScrollOffset,
|
||||
|
||||
offsetParent: Element.Methods.getOffsetParent,
|
||||
|
||||
page: Element.Methods.viewportOffset,
|
||||
|
||||
clone: function(source, target, options) {
|
||||
options = options || { };
|
||||
return Element.clonePosition(target, source, options);
|
||||
}
|
||||
};
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
if (!document.getElementsByClassName) document.getElementsByClassName = function(instanceMethods){
|
||||
function iter(name) {
|
||||
return name.blank() ? null : "[contains(concat(' ', @class, ' '), ' " + name + " ')]";
|
||||
}
|
||||
|
||||
instanceMethods.getElementsByClassName = Prototype.BrowserFeatures.XPath ?
|
||||
function(element, className) {
|
||||
className = className.toString().strip();
|
||||
var cond = /\s/.test(className) ? $w(className).map(iter).join('') : iter(className);
|
||||
return cond ? document._getElementsByXPath('.//*' + cond, element) : [];
|
||||
} : function(element, className) {
|
||||
className = className.toString().strip();
|
||||
var elements = [], classNames = (/\s/.test(className) ? $w(className) : null);
|
||||
if (!classNames && !className) return elements;
|
||||
|
||||
var nodes = $(element).getElementsByTagName('*');
|
||||
className = ' ' + className + ' ';
|
||||
|
||||
for (var i = 0, child, cn; child = nodes[i]; i++) {
|
||||
if (child.className && (cn = ' ' + child.className + ' ') && (cn.include(className) ||
|
||||
(classNames && classNames.all(function(name) {
|
||||
return !name.toString().blank() && cn.include(' ' + name + ' ');
|
||||
}))))
|
||||
elements.push(Element.extend(child));
|
||||
}
|
||||
return elements;
|
||||
};
|
||||
|
||||
return function(className, parentElement) {
|
||||
return $(parentElement || document.body).getElementsByClassName(className);
|
||||
};
|
||||
}(Element.Methods);
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
Element.ClassNames = Class.create();
|
||||
Element.ClassNames.prototype = {
|
||||
initialize: function(element) {
|
||||
this.element = $(element);
|
||||
},
|
||||
|
||||
_each: function(iterator) {
|
||||
this.element.className.split(/\s+/).select(function(name) {
|
||||
return name.length > 0;
|
||||
})._each(iterator);
|
||||
},
|
||||
|
||||
set: function(className) {
|
||||
this.element.className = className;
|
||||
},
|
||||
|
||||
add: function(classNameToAdd) {
|
||||
if (this.include(classNameToAdd)) return;
|
||||
this.set($A(this).concat(classNameToAdd).join(' '));
|
||||
},
|
||||
|
||||
remove: function(classNameToRemove) {
|
||||
if (!this.include(classNameToRemove)) return;
|
||||
this.set($A(this).without(classNameToRemove).join(' '));
|
||||
},
|
||||
|
||||
toString: function() {
|
||||
return $A(this).join(' ');
|
||||
}
|
||||
};
|
||||
|
||||
Object.extend(Element.ClassNames.prototype, Enumerable);
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
Element.addMethods();
|
|
@ -0,0 +1,50 @@
|
|||
|
||||
/**
|
||||
* Javascript pour la gestion webadmin
|
||||
*
|
||||
* Copyright (c) 2009 Evolix - Tous droits reserves
|
||||
*
|
||||
* vim: expandtab softtabstop=4 tabstop=4 shiftwidth=4 showtabline=2
|
||||
*
|
||||
* @author Thomas Martin <tmartin@evolix.fr>
|
||||
* @version 1.0
|
||||
*/
|
||||
|
||||
function switch_disabled(name) {
|
||||
element = document.getElementById(name);
|
||||
state = element.disabled;
|
||||
if(state == true) {
|
||||
element.disabled = false;
|
||||
} else {
|
||||
element.disabled = true;
|
||||
}
|
||||
}
|
||||
|
||||
document.observe("dom:loaded", function() {
|
||||
document.getElementById('password_random').onclick = function() {
|
||||
switch_disabled('password');
|
||||
}
|
||||
document.getElementById('mysql_db').onclick = function() {
|
||||
switch_disabled('mysql_dbname');
|
||||
switch_disabled('mysql_password_random');
|
||||
if(this.checked) {
|
||||
|
||||
/* On préremplit le champ mysql_dbname avec la valeur de username,
|
||||
mais seulement s'il est vidé au préalable */
|
||||
mysql_dbname = document.getElementById('mysql_dbname');
|
||||
if(!mysql_dbname.value) {
|
||||
mysql_dbname.value = document.getElementById('username').value;
|
||||
}
|
||||
|
||||
if(document.getElementById('mysql_password_random').checked) {
|
||||
document.getElementById('mysql_password').disabled = true;
|
||||
}
|
||||
} else {
|
||||
document.getElementById('mysql_password').disabled = true;
|
||||
}
|
||||
}
|
||||
document.getElementById('mysql_password_random').onclick = function() {
|
||||
switch_disabled('mysql_password');
|
||||
}
|
||||
} );
|
||||
|
|
@ -0,0 +1,70 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* common DirectoryIndex page
|
||||
*
|
||||
* Copyright (c) 2009 Evolix - Tous droits reserves
|
||||
*
|
||||
* vim: expandtab softtabstop=4 tabstop=4 shiftwidth=4 showtabline=2
|
||||
*
|
||||
* @author Gregory Colpart <reg@evolix.fr>
|
||||
* @author Thomas Martin <tmartin@evolix.fr>
|
||||
* @author Sebastien Palma <spalma@evolix.fr>
|
||||
* @version 1.0
|
||||
*/
|
||||
|
||||
/**
|
||||
* Path
|
||||
*/
|
||||
define('EVOADMIN_BASE','./');
|
||||
|
||||
/**
|
||||
* PHP cookies session
|
||||
*/
|
||||
session_name('EVOPMI_SESS');
|
||||
session_start();
|
||||
|
||||
error_reporting(E_ALL | E_NOTICE);
|
||||
header('Content-Type: text/html; charset=utf-8');
|
||||
|
||||
/**
|
||||
* Requires
|
||||
*/
|
||||
require_once EVOADMIN_BASE . 'common.php';
|
||||
|
||||
|
||||
$uri = $_SERVER['REQUEST_URI'];
|
||||
$params = array();
|
||||
|
||||
if (!array_key_exists('auth', $_SESSION) || $_SESSION['auth']!=1) {
|
||||
|
||||
include_once EVOADMIN_BASE . '../inc/auth.php';
|
||||
|
||||
} elseif (preg_match('#^/ftpadmin/?(edit|add|delete)?/?(.*)?/?$#', $uri, $params)) {
|
||||
|
||||
include_once EVOADMIN_BASE . '../inc/ftpadmin.php';
|
||||
|
||||
} elseif (preg_match('#^/webadmin/?$#', $uri, $params)) {
|
||||
|
||||
include_once EVOADMIN_BASE . '../inc/webadmin.php';
|
||||
|
||||
} elseif (preg_match('#^/webadmin/edit/(.*)/?$#', $uri, $params)) {
|
||||
|
||||
include_once EVOADMIN_BASE . '../inc/webadmin-edit.php';
|
||||
|
||||
} elseif (is_superadmin() && preg_match('#^/accounts/?#', $uri, $params)) {
|
||||
|
||||
include_once EVOADMIN_BASE . '../inc/accounts.php';
|
||||
|
||||
} elseif (preg_match('#^//?$#', $uri, $params)) {
|
||||
|
||||
include_once EVOADMIN_BASE . '../inc/home.php';
|
||||
|
||||
} elseif (preg_match('#^/destroy/?$#', $uri, $params)) {
|
||||
|
||||
include_once EVOADMIN_BASE . '../inc/destroy.php';
|
||||
|
||||
} else {
|
||||
die ("Cette page n'existe pas !!!");
|
||||
}
|
||||
|
Binary file not shown.
|
@ -0,0 +1,380 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* Gestion des comptes utilisateurs
|
||||
*
|
||||
* Copyright (c) 2009 Evolix - Tous droits reserves
|
||||
*
|
||||
* vim: expandtab softtabstop=4 tabstop=4 shiftwidth=4 showtabline=2
|
||||
*
|
||||
* @author Gregory Colpart <reg@evolix.fr>
|
||||
* @author Thomas Martin <tmartin@evolix.fr>
|
||||
* @author Sebastien Palma <spalma@evolix.fr>
|
||||
* @version 1.0
|
||||
*/
|
||||
|
||||
require_once EVOADMIN_BASE . '../evolibs/Form.php';
|
||||
require_once EVOADMIN_BASE . '../lib/bdd.php';
|
||||
|
||||
global $conf;
|
||||
|
||||
$servers=$conf['servers'];
|
||||
$servers_slave=$conf['servers'];
|
||||
|
||||
$servers_slave[]='Aucun';
|
||||
$cache=$conf['cache'];
|
||||
|
||||
|
||||
function domain_add($name, $IP, $with_mxs, $gmail=false) {
|
||||
|
||||
$exec_cmd = 'bind-add-ng.sh';
|
||||
|
||||
if ( $with_mxs == true ) {
|
||||
/* Quai13 specific: use Gmail MXs if wanted */
|
||||
if ( $gmail ) {
|
||||
$exec_cmd .= ' -m ASPMX.L.GOOGLE.com.,10';
|
||||
$exec_cmd .= ' -m ALT1.ASPMX.L.GOOGLE.com.,20';
|
||||
$exec_cmd .= ' -m ALT2.ASPMX.L.GOOGLE.com.,20';
|
||||
$exec_cmd .= ' -m ASPMX2.GOOGLEMAIL.com.,30';
|
||||
$exec_cmd .= ' -m ASPMX3.GOOGLEMAIL.com.,30';
|
||||
}
|
||||
else {
|
||||
$exec_cmd .= ' -m mail,10';
|
||||
$exec_cmd .= ' -m backup.quai13.net.,20';
|
||||
}
|
||||
mail("$conf['techmail']", '[TAF] Ajouter '.$name.' sur le serveur de mail', wordwrap('Ajouter le domaine '.$name.' à la directive relay_domains dans le fichier /etc/postfix/main.cf sur le serveur mail, pour mettre en place le MX secondaire du domaine.', 70));
|
||||
}
|
||||
|
||||
$exec_cmd .= " -a $IP $name";
|
||||
|
||||
//echo $exec_cmd."\n";
|
||||
sudoexec($exec_cmd, $exec_output, $exec_return);
|
||||
return array($exec_cmd, $exec_return, $exec_output);
|
||||
}
|
||||
|
||||
function web_add($form, $admin_mail) {
|
||||
|
||||
$exec_cmd = 'web-add.sh add -y';
|
||||
|
||||
|
||||
if(!$form->getField('password_random')->getValue()) {
|
||||
$exec_cmd .= sprintf(' -p %s',
|
||||
$form->getField('password')->getValue());
|
||||
}
|
||||
|
||||
/* Ajout des options spécifiques à MySQL si nécessaire */
|
||||
if($form->getField('mysql_db')->getValue()) {
|
||||
$exec_cmd .= sprintf(' -m %s',
|
||||
$form->getField('mysql_dbname')->getValue());
|
||||
|
||||
if(!$form->getField('mysql_password_random')->getValue()) {
|
||||
$exec_cmd .= sprintf(' -P %s',
|
||||
$form->getField('mysql_password')->getValue());
|
||||
}
|
||||
}
|
||||
|
||||
$exec_cmd .= sprintf(' -l %s %s %s 2>&1', $admin_mail,
|
||||
$form->getField('username')->getValue(),
|
||||
$form->getField('domain')->getValue());
|
||||
|
||||
sudoexec($exec_cmd, $exec_output, $exec_return);
|
||||
|
||||
return array($exec_cmd, $exec_return, $exec_output);
|
||||
}
|
||||
|
||||
function web_add_cluster($form, $admin_mail) {
|
||||
global $cache;
|
||||
global $conf;
|
||||
|
||||
$exec_cmd = 'web-add-cluster.sh add';
|
||||
|
||||
$realtime=0;
|
||||
|
||||
/* array account with infos for sqlite cache */
|
||||
$account = array();
|
||||
|
||||
if(!$form->getField('password_random')->getValue()) {
|
||||
$exec_cmd .= sprintf(' -p %s',
|
||||
$form->getField('password')->getValue());
|
||||
}
|
||||
|
||||
/* Ajout des options spécifiques à MySQL si nécessaire */
|
||||
if($form->getField('mysql_db')->getValue()) {
|
||||
$exec_cmd .= sprintf(' -m %s',
|
||||
$form->getField('mysql_dbname')->getValue());
|
||||
|
||||
if(!$form->getField('mysql_password_random')->getValue()) {
|
||||
$exec_cmd .= sprintf(' -P %s',
|
||||
$form->getField('mysql_password')->getValue());
|
||||
}
|
||||
|
||||
$account['bdd'] = $form->getField('mysql_dbname')->getValue();
|
||||
|
||||
}
|
||||
else $account['bdd'] = '' ;
|
||||
|
||||
/* Replication */
|
||||
$value_cluster_mode = $form->getField('cluster_mode')->getValue();
|
||||
|
||||
/* decode $value */
|
||||
// noreplication : 1-x
|
||||
// postponedreplication : 2-x-y-m
|
||||
// immediate : 3-x-y
|
||||
|
||||
list($crepl, $cmaster, $cslave, $cmode) = explode('-', $value_cluster_mode);
|
||||
|
||||
switch ($crepl) {
|
||||
case 1: // noreplication, single server
|
||||
$account['replication'] = '';
|
||||
$realtime = 1;// hack
|
||||
$master = $conf['noreplication'][$cmaster];
|
||||
$slave="null";
|
||||
|
||||
break;
|
||||
case 2: // postponed
|
||||
$mode = $conf['postponedreplication_mode'][$cmode];
|
||||
if (isset($conf[$mode])) {
|
||||
$master = $conf[$mode][$cmaster];
|
||||
$slave = $conf[$mode][$cslave];
|
||||
}
|
||||
|
||||
$master = $conf['postponedreplication'][$cmaster];
|
||||
$slave = $conf['postponedreplication'][$cslave];
|
||||
|
||||
// en dur pour le moment à améliorer plus tard ...
|
||||
switch ($cmode) {
|
||||
case 0: // 3/day
|
||||
$cron_freq_opt=8;
|
||||
$cron_unit_opt='hour';
|
||||
break;
|
||||
case 1: // 1/day
|
||||
$cron_freq_opt=24;
|
||||
$cron_unit_opt='hour';
|
||||
break;
|
||||
case 2: // 1/hour
|
||||
$cron_freq_opt=1; /* 1/hour */
|
||||
$cron_unit_opt='hour';
|
||||
break;
|
||||
}
|
||||
|
||||
$account['replication'] = $conf['postponedreplication_mode'][$cmode];
|
||||
|
||||
$exec_cmd .= sprintf(' -f %d -c %s', $cron_freq_opt, $cron_unit_opt);
|
||||
|
||||
break;
|
||||
case 3: // realtime
|
||||
$realtime = 1;
|
||||
$account['replication'] = 'realtime';
|
||||
|
||||
$master = $conf['immediatereplication'][$cmaster];
|
||||
$slave = $conf['immediatereplication'][$cslave];
|
||||
break;
|
||||
}
|
||||
|
||||
$exec_cmd .= sprintf(' -l %s %s %s %s %s %s 2>&1',
|
||||
$admin_mail,
|
||||
$form->getField('username')->getValue(),
|
||||
$form->getField('domain')->getValue(),
|
||||
$master,
|
||||
$slave,
|
||||
($realtime ? 'realtime': 'deferred'));
|
||||
|
||||
domain_add($form->getField('domain')->getValue(), gethostbyname($master), true, $form->getField('use_gmail_mxs')->getValue());
|
||||
sudoexec($exec_cmd, $exec_output, $exec_return);
|
||||
|
||||
/* Gestion des noms de domaines supplementaires */
|
||||
if ( $form->getField('domain_alias')->getValue() ) {
|
||||
$domain_alias = preg_split('/,/', $form->getField('domain_alias')->getValue());
|
||||
foreach ( $domain_alias as $alias ) {
|
||||
$exec_cmd = 'web-add-cluster.sh add-alias '.$form->getField('username')->getValue().' ';
|
||||
$alias = trim($alias);
|
||||
$exec_cmd .= $alias.' '.$master.' '.$slave;
|
||||
sudoexec($exec_cmd, $exec_output2, $exec_return2);
|
||||
//print $exec_cmd."\n";
|
||||
domain_add($alias, gethostbyname($master), true);
|
||||
}
|
||||
$exec_return |= $exec_return2;
|
||||
array_push($exec_output, $exec_output2);
|
||||
}
|
||||
|
||||
/* insertion des infos dans le cache sqlite */
|
||||
if ($exec_return == 0) {
|
||||
|
||||
$bdd=new bdd();
|
||||
$bdd->open($cache);
|
||||
|
||||
$account['name'] = $form->getField('username')->getValue();
|
||||
$account['domain'] = $form->getField('domain')->getValue();
|
||||
|
||||
$bdd->add_account($account);
|
||||
|
||||
$bdd->add_role($account['name'], $master, 'master');
|
||||
if ($slave != "null");
|
||||
$bdd->add_role($account['name'], $slave, 'slave');
|
||||
|
||||
if (substr_compare($account['domain'], 'www.', 0, strlen('www.')) == 0) {
|
||||
$wwwalias = ltrim($account['domain'], 'www.');
|
||||
$serveralias = array (
|
||||
'domain' => $account['name'],
|
||||
'alias' => $wwwalias,
|
||||
);
|
||||
$bdd->add_serveralias($serveralias);
|
||||
}
|
||||
|
||||
/* Ajout des serveralias dans la base de donnée */
|
||||
if ( $form->getField('domain_alias')->getValue() ) {
|
||||
|
||||
$domain = $form->getField('username')->getValue();
|
||||
$domain_alias = preg_split('/,/', $form->getField('domain_alias')->getValue());
|
||||
foreach ( $domain_alias as $alias ) {
|
||||
$alias = trim($alias);
|
||||
$serveralias = array (
|
||||
'domain' => "$domain",
|
||||
'alias' => "$alias"
|
||||
);
|
||||
$bdd->add_serveralias($serveralias);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return array($exec_cmd, $exec_return, $exec_output);
|
||||
}
|
||||
|
||||
/* Construction du formulaire d'ajout */
|
||||
$form = new FormPage("Ajout d'un compte web", FALSE);
|
||||
$form->addField('username', new TextInputFormField("Nom d'utilisateur", TRUE));
|
||||
$form->addField('domain', new TextInputFormField("Nom de domaine", TRUE));
|
||||
$form->addField('domain_alias', new TextInputFormField("Alias (séparés par une virgule)", FALSE));
|
||||
$form->addField('password_random',
|
||||
new CheckboxInputFormField("Mot de passe aléatoire ?", FALSE));
|
||||
$form->getField('password_random')->setValue(TRUE);
|
||||
$form->addField('password', new PasswordInputFormField('Mot de passe', FALSE));
|
||||
$form->getField('password')->setDisabled();
|
||||
$form->addField('mysql_db',
|
||||
new CheckboxInputFormField("Créer une base de données MySQL ?",
|
||||
FALSE));
|
||||
$form->getField('mysql_db')->setValue(TRUE);
|
||||
$form->addField('mysql_dbname',
|
||||
new TextInputFormField("Nom de la base MySQL", FALSE));
|
||||
//$form->getField('mysql_dbname')->setDisabled();
|
||||
$form->addField('mysql_password_random',
|
||||
new CheckboxInputFormField("Mot de passe MySQL aléatoire ?",
|
||||
FALSE));
|
||||
$form->getField('mysql_password_random')->setValue(TRUE);
|
||||
//$form->getField('mysql_password_random')->setDisabled();
|
||||
$form->addField('mysql_password',
|
||||
new PasswordInputFormField('Mot de passe MySQL', FALSE));
|
||||
$form->getField('mysql_password')->setDisabled();
|
||||
|
||||
if ($conf['cluster']) {
|
||||
|
||||
/* construction of $choices */
|
||||
$choices = array();
|
||||
$elmt = "";
|
||||
|
||||
/* 1-x noreplication */
|
||||
$key_server = 0;
|
||||
foreach($conf['noreplication'] as $server) {
|
||||
$key="1-". $key_server;
|
||||
$choices[$key] = "Aucun ($server)";
|
||||
$key_server ++;
|
||||
}
|
||||
|
||||
/* 2-x-y-m postponedreplication */
|
||||
$size_tab = count($conf['postponedreplication']);
|
||||
|
||||
if ($size_tab >= 2) { // compute all possibilities ...
|
||||
$key_mode = 0;
|
||||
foreach($conf['postponedreplication_mode'] as $mode) {
|
||||
|
||||
// ... unless a restrictive list is given for a $mode in config.local.php
|
||||
if (isset($conf[$mode])) {
|
||||
$size_sub_tab = count($conf["$mode"]);
|
||||
|
||||
// pair x -> y
|
||||
if (($size_sub_tab >= 2) && (($size_sub_tab % 2) == 0))
|
||||
for ( $k = 0; $k < $size_sub_tab; $k = $k + 2 ) {
|
||||
$elmt = "$mode (" . $conf["$mode"][$k] . " => " . $conf["$mode"][$k+1] . ")";
|
||||
$key= "2-" . substr($conf[$mode][$k], -1) . "-" . substr($conf[$mode][$k+1], -1) . "-" . $key_mode;
|
||||
$choices[$key] = $elmt;
|
||||
}
|
||||
$key_mode++;
|
||||
continue; // done for $conf[$mode], next !
|
||||
}
|
||||
|
||||
// for the others, give every combination
|
||||
$key_server = 0; // pivot
|
||||
foreach($conf['postponedreplication'] as $server) {
|
||||
for ( $i = 0; $i < $size_tab; $i++) {
|
||||
|
||||
if ( $key_server <> $i ) {
|
||||
$elmt = "$mode ($server =>" . $conf['postponedreplication'][$i] . ")";
|
||||
$key = "2-" . $key_server . "-" . $i . "-" . $key_mode;
|
||||
$choices[$key] = $elmt;
|
||||
}
|
||||
}
|
||||
$key_server++;
|
||||
}
|
||||
$key_mode++;
|
||||
}
|
||||
}
|
||||
|
||||
/* 3-x-y immediatereplication */
|
||||
$size_tab = count($conf['immediatereplication']);
|
||||
|
||||
// pair x -> y
|
||||
if (($size_tab >= 2) && (($size_tab % 2) == 0))
|
||||
for ( $i = 0; $i < $size_tab; $i = $i + 2 ) {
|
||||
$elmt = "Immediat (" . $conf['immediatereplication'][$i] . " => " . $conf['immediatereplication'][$i+1] . ")";
|
||||
$key = "3-".$i."-".($i+1);
|
||||
$choices[$key] = $elmt;
|
||||
}
|
||||
|
||||
/* final form */
|
||||
$form->addField('cluster_mode', new SelectFormField('Mode de réplication', FALSE, $choices));
|
||||
}
|
||||
|
||||
/* Quai13 specific: allow to switch between Gmail MX/Quai13 MX */
|
||||
$form->addField('use_gmail_mxs', new CheckboxInputFormField("Utilisation des serveurs Gmail en MX ?", FALSE));
|
||||
|
||||
/* Traitement du formulaire */
|
||||
if(!empty($_POST)) {
|
||||
$form->isCurrentPage(TRUE);
|
||||
$form->initFields();
|
||||
|
||||
/* Le champ password devient obligatoire si le champ password_random est
|
||||
* décoché */
|
||||
if(!$form->getField('password_random')->getValue()) {
|
||||
$form->getField('password')->setMandatory(TRUE);
|
||||
$form->getField('password')->setDisabled(FALSE);
|
||||
}
|
||||
|
||||
/* Erreur si mysql_db est coché */
|
||||
if($form->getField('mysql_db')->getValue()) {
|
||||
$form->getField('mysql_dbname')->setMandatory(TRUE);
|
||||
$form->getField('mysql_dbname')->setDisabled(FALSE);
|
||||
$form->getField('mysql_password_random')->setDisabled(FALSE);
|
||||
|
||||
/* Le champ mysql_passwd devient obligatoire si le champ
|
||||
* mysql_password_random est coché */
|
||||
if(!$form->getField('mysql_password_random')->getValue()) {
|
||||
$form->getField('mysql_password')->setMandatory(TRUE);
|
||||
$form->getField('mysql_password')->setDisabled(FALSE);
|
||||
}
|
||||
}
|
||||
|
||||
/* Test de validation du formulaire */
|
||||
if($form->verify(TRUE)) {
|
||||
if ($conf['cluster'])
|
||||
$exec_info = web_add_cluster($form, $conf['admin']['mail']);
|
||||
else
|
||||
$exec_info = web_add($form, $conf['admin']['mail']);
|
||||
}
|
||||
}
|
||||
|
||||
include_once EVOADMIN_BASE . '../tpl/header.tpl.php';
|
||||
include_once EVOADMIN_BASE . '../tpl/menu.tpl.php';
|
||||
include_once EVOADMIN_BASE . '../tpl/accounts.tpl.php';
|
||||
include_once EVOADMIN_BASE . '../tpl/footer.tpl.php';
|
||||
|
||||
?>
|
|
@ -0,0 +1,57 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* Authentification page
|
||||
*
|
||||
* Copyright (c) 2009 Evolix - Tous droits reserves
|
||||
*
|
||||
* vim: expandtab softtabstop=4 tabstop=4 shiftwidth=4 showtabline=2
|
||||
*
|
||||
* @author Gregory Colpart <reg@evolix.fr>
|
||||
* @author Thomas Martin <tmartin@evolix.fr>
|
||||
* @author Sebastien Palma <spalma@evolix.fr>
|
||||
* @version 1.0
|
||||
*/
|
||||
|
||||
|
||||
|
||||
if ((empty($_GET['form']) || $_GET['form']!=1) && !empty($_POST)) {
|
||||
$login=0;
|
||||
$username=$_POST['login'];
|
||||
$password=$_POST['passw'];
|
||||
|
||||
|
||||
$login = pam_auth($username, $password);
|
||||
|
||||
if ($login==1) {
|
||||
$_SESSION['auth']=1;
|
||||
$_SESSION['user']=$username;
|
||||
$_SESSION['error']='';
|
||||
|
||||
$user = posix_getpwnam($username);
|
||||
// On nettoie le nom complet
|
||||
$gecos = split(',',$user['gecos']);
|
||||
$user['gecos'] = $gecos[0];
|
||||
$_SESSION['user_id'] = $user['uid'];
|
||||
$_SESSION['user_gid'] = $user['gid'];
|
||||
$_SESSION['user_name'] = $user['gecos'];
|
||||
} else {
|
||||
$_SESSION['auth']=0;
|
||||
$_SESSION['user']='';
|
||||
$_SESSION['error']=1;
|
||||
}
|
||||
http_redirect('/');
|
||||
|
||||
} else {
|
||||
|
||||
if(!empty($_SESSION['error'])) {
|
||||
$error=$_SESSION['error'];
|
||||
}
|
||||
|
||||
include_once EVOADMIN_BASE . '../tpl/header.tpl.php';
|
||||
include_once EVOADMIN_BASE . '../tpl/auth.tpl.php';
|
||||
include_once EVOADMIN_BASE . '../tpl/footer.tpl.php';
|
||||
|
||||
}
|
||||
|
||||
?>
|
|
@ -0,0 +1,18 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* Session destroyer
|
||||
*
|
||||
* Copyright (c) 2009 Evolix - Tous droits reserves
|
||||
*
|
||||
* vim: expandtab softtabstop=4 tabstop=4 shiftwidth=4 showtabline=2
|
||||
*
|
||||
* @author Gregory Colpart <reg@evolix.fr>
|
||||
* @author Thomas Martin <tmartin@evolix.fr>
|
||||
* @author Sebastien Palma <spalma@evolix.fr>
|
||||
* @version 1.0
|
||||
*/
|
||||
|
||||
session_destroy();
|
||||
|
||||
http_redirect('/');
|
|
@ -0,0 +1,268 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* Virtual FTP Accounts Management Page
|
||||
*
|
||||
* Copyright (c) 2009 Evolix - Tous droits reserves
|
||||
*
|
||||
* vim: expandtab softtabstop=4 tabstop=4 shiftwidth=4 showtabline=2
|
||||
*
|
||||
* @author Gregory Colpart <reg@evolix.fr>
|
||||
* @author Thomas Martin <tmartin@evolix.fr>
|
||||
* @author Sebastien Palma <spalma@evolix.fr>
|
||||
* @version 1.0
|
||||
*/
|
||||
|
||||
$action=$params[1];
|
||||
$account=$params[2];
|
||||
|
||||
$errors = array();
|
||||
$errors[1] = "Les mots de passe de correspondent pas";
|
||||
$errors[2] = "Le login doit contenir entre 6 et 16 caractères";
|
||||
$errors[3] = "Le répertoire existe, continuer quand même ?";
|
||||
$errors[4] = "Impossible de créer le dossier racine. Merci de contacter votre administrateur";
|
||||
$errors[5] = "Le nom de compte choisi est déjà utilisé sur le système. Merci de le modifier";
|
||||
$errors[6] = "Le chemin saisi n'est pas valide. Merci d'en saisir un autre";
|
||||
$errors[7] = "Le mot de passe doit contenir au moins 6 caractères";
|
||||
|
||||
$user_id = $_SESSION['user_id'];
|
||||
|
||||
if ($action=="add") {
|
||||
$owner_list = get_owner_list();
|
||||
|
||||
if(array_key_exists('submit_button', $_POST)) {
|
||||
//print "Ajout du compte {$_POST['login']}";
|
||||
$login = $_POST['login'];
|
||||
$passw = $_POST['passwd'];
|
||||
$pass2 = $_POST['passwd_c'];
|
||||
$dossier = $_POST['path'];
|
||||
if (array_key_exists('confirm', $_POST)) $confirm = $_POST['confirm'];
|
||||
|
||||
// On vérifie que le login choisi n'est pas déjà pris
|
||||
$output = "";
|
||||
exec("cat /etc/proftpd/vpasswd | grep $login:", $output, $exec_return);
|
||||
if (!empty($output)) {
|
||||
$_SESSION['error']=5;
|
||||
$_SESSION['form']['login'] = $login;
|
||||
$_SESSION['form']['passw'] = $passw;
|
||||
$_SESSION['form']['pass2'] = $pass2;
|
||||
$_SESSION['form']['dossier'] = $dossier;
|
||||
http_redirect('/ftpadmin/add');
|
||||
}
|
||||
|
||||
|
||||
|
||||
// On vérifie la taille du login
|
||||
if (strlen($login)<6 || strlen($login)>16) {
|
||||
$login='';
|
||||
$_SESSION['error']=2;
|
||||
http_redirect("/ftpadmin/add");
|
||||
}
|
||||
|
||||
// On vérifie qu'on a bien saisi un mot de passe
|
||||
if (strlen($passw) < 6) {
|
||||
$_SESSION['error'] = 7;
|
||||
$_SESSION['form']['login'] = $login;
|
||||
$_SESSION['form']['passw'] = '';
|
||||
$_SESSION['form']['pass2'] = '';
|
||||
$_SESSION['form']['dossier'] = $dossier;
|
||||
http_redirect('/ftpadmin/add');
|
||||
}
|
||||
|
||||
// On vérifie que les 2 mots de passe sont identiques
|
||||
if ($passw != $pass2) {
|
||||
$passw = $pass2 = '';
|
||||
$_SESSION['error']=1;
|
||||
$_SESSION['form']['login'] = $login;
|
||||
$_SESSION['form']['passw'] = '';
|
||||
$_SESSION['form']['pass2'] = '';
|
||||
$_SESSION['form']['dossier'] = $dossier;
|
||||
http_redirect("/ftpadmin/add");
|
||||
}
|
||||
|
||||
/* Le superadmin est capable de créer un compte pour quelqu'un d'autre */
|
||||
/* ATTENTION : dans la suite du code $user_id est modifié */
|
||||
if(is_superadmin()) {
|
||||
$owner_info = posix_getpwnam($_POST['owner']);
|
||||
$user_id = $owner_info['uid'];
|
||||
$complete_path = sprintf('/home/%s/%s', $_POST['owner'], $dossier);
|
||||
} else {
|
||||
$complete_path = "/home/{$_SESSION['user']}/$dossier";
|
||||
}
|
||||
|
||||
$_SESSION['error']=null;
|
||||
$_SESSION['form']=null;
|
||||
// Création du répertoire source
|
||||
$complete_path = str_replace('//', '/', $complete_path);
|
||||
|
||||
// Vérification de l'intégrité du chemin saisi
|
||||
if (strpos($complete_path, '../')!==FALSE) {
|
||||
$_SESSION['error']=6;
|
||||
$_SESSION['form']['login'] = $login;
|
||||
$_SESSION['form']['passw'] = $passw;
|
||||
$_SESSION['form']['pass2'] = $pass2;
|
||||
$_SESSION['form']['dossier'] = $dossier;
|
||||
http_redirect('/ftpadmin/add');
|
||||
}
|
||||
|
||||
// Utilmisation du script de vérification d'existence d'un répertoire en sudo
|
||||
$exists = '';
|
||||
exec("sudo /usr/share/scripts/evoadmin/directorycheck.sh $complete_path", $exists, $return);
|
||||
|
||||
// On teste d'abord si le répertoire n'existe pas déjà ou si l'utilisateur
|
||||
if ($exists[0]=="1" && !isset($confirm)) {
|
||||
$_SESSION['error']=3;
|
||||
$_SESSION['form']['login'] = $login;
|
||||
$_SESSION['form']['passw'] = $passw;
|
||||
$_SESSION['form']['pass2'] = $pass2;
|
||||
$_SESSION['form']['dossier'] = $dossier;
|
||||
|
||||
http_redirect('/ftpadmin/add');
|
||||
} elseif ($exists[0]=="1" && isset($confirm) && $confirm==0) {
|
||||
$_SESSION['error']=null;
|
||||
$_SESSION['form']['login'] = $login;
|
||||
$_SESSION['form']['passw'] = $passw;
|
||||
$_SESSION['form']['pass2'] = $pass2;
|
||||
$_SESSION['form']['dossier'] = "";
|
||||
http_redirect('/ftpadmin/add');
|
||||
} elseif ($exists[0]==0 || (isset($confirm) && $confirm==1)) {
|
||||
|
||||
// On appelle le script de création de compte FTP
|
||||
sudoexec("ftpadmin.sh -a a -u $user_id -n $login -f $complete_path -p $passw", $standard_output, $function_output);
|
||||
|
||||
// On revient à la page de listing
|
||||
$_SESSION['error']=null;
|
||||
$_SESSION['form']=null;
|
||||
$ftp_added_login = $login;
|
||||
|
||||
} else {
|
||||
print "Le cas de figure présent n'existe pas... Avez-vous essayé de modifier l'adresse manuellement ?";
|
||||
}
|
||||
}
|
||||
|
||||
include_once EVOADMIN_BASE . '../tpl/header.tpl.php';
|
||||
include_once EVOADMIN_BASE . '../tpl/menu.tpl.php';
|
||||
if(!empty($ftp_added_login)) {
|
||||
include_once EVOADMIN_BASE . '../tpl/ftpadmin-new-ok.tpl.php';
|
||||
} else {
|
||||
include_once EVOADMIN_BASE . '../tpl/ftpadmin-new.tpl.php';
|
||||
}
|
||||
include_once EVOADMIN_BASE . '../tpl/footer.tpl.php';
|
||||
|
||||
} elseif ($action=="edit") {
|
||||
|
||||
print "Modification du mot de passe de $account";
|
||||
|
||||
} elseif ($action=="delete") {
|
||||
|
||||
sudoexec("ftpadmin.sh -a d -u $user_id -n $account -f /dev/null -p azertyuiop", $standard_output, $function_output);
|
||||
|
||||
|
||||
$_SESSION['error'] = null;
|
||||
$_SESSION['form'] = null;
|
||||
http_redirect('/ftpadmin/');
|
||||
|
||||
} else {
|
||||
|
||||
|
||||
$account_list = array();
|
||||
$table = array();
|
||||
$num_line=0;
|
||||
|
||||
#exec("sudo /usr/share/scripts/evoadmin/ftpadmin.sh -a l -u $user_id", $account_list, $exec_return);
|
||||
$list_cmd = "ftpadmin.sh -a l";
|
||||
if(!is_superadmin()) {
|
||||
$list_cmd .= " -u $user_id";
|
||||
}
|
||||
sudoexec($list_cmd, $account_list, $exec_return);
|
||||
|
||||
sort($account_list);
|
||||
|
||||
$size_total = 0;
|
||||
|
||||
foreach ($account_list as $account) {
|
||||
|
||||
$infos = split(':', $account);
|
||||
|
||||
|
||||
if (!empty($infos[0])) {
|
||||
$table[$num_line]['owner'] = $infos[0];
|
||||
$table[$num_line]['name'] = $infos[1];
|
||||
|
||||
$path = split("/", $infos[2]);
|
||||
$rel_path='';
|
||||
foreach($path as $id => $folder) {
|
||||
if ($id>2) $rel_path.='/'.$folder;
|
||||
}
|
||||
$table[$num_line]['path'] = str_replace('//', '/', $rel_path);
|
||||
|
||||
if ($infos[3]>0) {
|
||||
$size_total += $infos[3];
|
||||
$table[$num_line]['size'] = formatBytes($infos[3]);
|
||||
} else {
|
||||
$table[$num_line]['size'] = 0;
|
||||
}
|
||||
|
||||
if ($infos[4]>0) {
|
||||
$table[$num_line]['date'] = date("d/m/Y h:i:s", $infos[4]);
|
||||
} else {
|
||||
$table[$num_line]['date'] = "01/01/1970";
|
||||
}
|
||||
|
||||
$num_line++;
|
||||
}
|
||||
}
|
||||
|
||||
$size_total = formatBytes($size_total);
|
||||
|
||||
/* Création d'un tableau trié contenant la liste de tous les comptes,
|
||||
utilisé pour la sélection du propriétaire en mode superadmin */
|
||||
$owner_list = get_owner_list();
|
||||
|
||||
include_once EVOADMIN_BASE . '../tpl/header.tpl.php';
|
||||
include_once EVOADMIN_BASE . '../tpl/menu.tpl.php';
|
||||
include_once EVOADMIN_BASE . '../tpl/ftpadmin.tpl.php';
|
||||
include_once EVOADMIN_BASE . '../tpl/footer.tpl.php';
|
||||
|
||||
}
|
||||
|
||||
$_SESSION['error']=null;
|
||||
$_SESSION['form']=null;
|
||||
|
||||
function formatBytes($bytes, $precision = 2) {
|
||||
$bytes *= 1024;
|
||||
$units = array('o', 'Ko', 'Mo', 'Go', 'To');
|
||||
|
||||
$bytes = max($bytes, 0);
|
||||
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
|
||||
$pow = min($pow, count($units) - 1);
|
||||
|
||||
$bytes /= pow(1024, $pow);
|
||||
|
||||
return round($bytes, $precision) . ' ' . $units[$pow];
|
||||
}
|
||||
|
||||
|
||||
function get_owner_list() {
|
||||
$owner_list = array();
|
||||
|
||||
$fd_passwd = fopen('/etc/passwd', 'r');
|
||||
|
||||
$usernames = array();
|
||||
while($line = fgets($fd_passwd)) {
|
||||
$tmp = explode(':', $line);
|
||||
$usernames[$tmp[0]] = 1;
|
||||
}
|
||||
|
||||
foreach(array_keys($usernames) as $cur) {
|
||||
if(preg_match('/^www-/', $cur)) { continue; }
|
||||
if(empty($usernames["www-$cur"])) { continue; }
|
||||
$owner_list[] = $cur;
|
||||
}
|
||||
|
||||
asort($owner_list);
|
||||
|
||||
return $owner_list;
|
||||
}
|
||||
|
||||
?>
|
|
@ -0,0 +1,19 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* HomePage
|
||||
*
|
||||
* Copyright (c) 2009 Evolix - Tous droits reserves
|
||||
*
|
||||
* vim: expandtab softtabstop=4 tabstop=4 shiftwidth=4 showtabline=2
|
||||
*
|
||||
* @author Gregory Colpart <reg@evolix.fr>
|
||||
* @author Thomas Martin <tmartin@evolix.fr>
|
||||
* @author Sebastien Palma <spalma@evolix.fr>
|
||||
* @version 1.0
|
||||
*/
|
||||
|
||||
include_once EVOADMIN_BASE . '../tpl/header.tpl.php';
|
||||
include_once EVOADMIN_BASE . '../tpl/menu.tpl.php';
|
||||
include_once EVOADMIN_BASE . '../tpl/home.tpl.php';
|
||||
include_once EVOADMIN_BASE . '../tpl/footer.tpl.php';
|
|
@ -0,0 +1,172 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* Apache VirtualHost Management Page
|
||||
*
|
||||
* Copyright (c) 2009 Evolix - Tous droits reserves
|
||||
*
|
||||
* vim: expandtab softtabstop=4 tabstop=4 shiftwidth=4 showtabline=2
|
||||
*
|
||||
* @author Gregory Colpart <reg@evolix.fr>
|
||||
* @author Thomas Martin <tmartin@evolix.fr>
|
||||
* @author Sebastien Palma <spalma@evolix.fr>
|
||||
* @version 1.0
|
||||
*/
|
||||
|
||||
require_once EVOADMIN_BASE . '../lib/bdd.php';
|
||||
|
||||
global $conf;
|
||||
|
||||
if (isset($_GET['del']) ) {
|
||||
|
||||
include_once EVOADMIN_BASE . '../tpl/header.tpl.php';
|
||||
include_once EVOADMIN_BASE . '../tpl/menu.tpl.php';
|
||||
|
||||
$alias = htmlspecialchars($_GET['del']);
|
||||
|
||||
if (isset($_GET['modif']) && ($_GET['modif'] == 'yes')) {
|
||||
|
||||
print "<center>";
|
||||
print "<p>Suppression de $alias...</p>";
|
||||
|
||||
|
||||
$serveralias = array (
|
||||
'domain' => htmlspecialchars(basename($_SERVER['REDIRECT_SCRIPT_URL'])),
|
||||
'alias' => $alias
|
||||
);
|
||||
|
||||
if ($conf['cluster']) {
|
||||
|
||||
$cache = $conf['cache'];
|
||||
$bdd = new bdd();
|
||||
$bdd->open($cache);
|
||||
|
||||
if (! $bdd->del_serveralias($serveralias))
|
||||
print "<p>La suppression a échouée. Veuillez contacter votre administrateur.</p>";
|
||||
}
|
||||
printf ('<p><a href="%s">Retour à la liste des alias</a></p>', $_SERVER['REDIRECT_SCRIPT_URL']);
|
||||
print "</center>";
|
||||
|
||||
} else if ( ! isset($_GET['modif']) ) {
|
||||
|
||||
print "<center>";
|
||||
print "<p>Confirmez vous la suppression de $alias ?</p>";
|
||||
printf ('<p><a href="%s?del=%s&modif=yes">Confirmer la suppression</a></p>', $_SERVER['REDIRECT_SCRIPT_URL'], $alias);
|
||||
printf ('<p><a href="%s">Retour à la liste des alias</a></p>', $_SERVER['REDIRECT_SCRIPT_URL']);
|
||||
print "</center>";
|
||||
}
|
||||
|
||||
|
||||
include_once EVOADMIN_BASE . '../tpl/footer.tpl.php';
|
||||
|
||||
} else if (isset($_GET['add']) ) {
|
||||
|
||||
require_once EVOADMIN_BASE . '../evolibs/Form.php';
|
||||
|
||||
include_once EVOADMIN_BASE . '../tpl/header.tpl.php';
|
||||
include_once EVOADMIN_BASE . '../tpl/menu.tpl.php';
|
||||
|
||||
$form = new FormPage("Ajout d'un alias", FALSE);
|
||||
$form->addField('domain_alias', new TextInputFormField("Alias", FALSE));
|
||||
|
||||
if (!empty($_POST)) {
|
||||
$form->isCurrentPage(TRUE);
|
||||
$form->initFields();
|
||||
|
||||
if ($form->verify(TRUE)) {
|
||||
if ($conf['cluster']) {
|
||||
$cache = $conf['cache'];
|
||||
$bdd = new bdd();
|
||||
$bdd->open($cache);
|
||||
|
||||
$serveralias = array (
|
||||
'domain' => htmlspecialchars(basename($_SERVER['REDIRECT_SCRIPT_URL'])),
|
||||
'alias' => $form->getField('domain_alias')->getValue(),
|
||||
);
|
||||
|
||||
$account_name=$serveralias['domain'];
|
||||
$account = $bdd->get_account($account_name);
|
||||
|
||||
if (sizeof($account) == 0)
|
||||
die("Anomalie... Contactez votre administrateur.");
|
||||
|
||||
$master = $bdd->get_server_from_roleid($account['id_master']);
|
||||
$slave = $bdd->get_server_from_roleid($account['id_slave']);
|
||||
|
||||
/* web-add-cluster addalias */
|
||||
$exec_cmd = 'web-add-cluster.sh add-alias '.$serveralias['domain'].' '.$serveralias['alias'].' '.$master.' '.$slave;
|
||||
sudoexec($exec_cmd, $exec_output, $exec_return);
|
||||
|
||||
/* bind add */
|
||||
$exec_cmd = 'bind-add-ng.sh';
|
||||
$exec_cmd .= ' -a '. gethostbyname($master) .' '.$serveralias['alias'];
|
||||
sudoexec($exec_cmd, $exec_output, $exec_return2);
|
||||
|
||||
$exec_return |= $exec_return2;
|
||||
|
||||
if ($exec_return == 0) {
|
||||
/* Ajout BDD */
|
||||
$bdd->add_serveralias($serveralias);
|
||||
|
||||
domain_add($serveralias['alias'], gethostbyname($master) , false);
|
||||
|
||||
# Si le compte en question est en replication temps
|
||||
# reel, il faut faire un restart manuel de lsyncd
|
||||
# pour prendre en compte le nouveau domaine.
|
||||
if ($account['replication'] == "realtime") {
|
||||
mail('tech@evolix.fr', "[TAF] Redemarrer lsyncd sur $master", wordwrap('killer tous les processus lsyncd lancé par vmail pour le compte '.$account['name'].' et les relancer (cf. la ligne correspondante à ce compte dans la crontab de vmail).\n', 70));
|
||||
}
|
||||
|
||||
print "<center>";
|
||||
printf ('<p>L\'alias %s du domaine %s a bien été créé</p>', $serveralias['alias'], $serveralias['domain']);
|
||||
printf ('<p><a href="%s">Retour à la liste des alias</a></p>', $_SERVER['REDIRECT_SCRIPT_URL']);
|
||||
print "</center>";
|
||||
} else {
|
||||
print "<center>";
|
||||
printf ('<p>Echec dans la creation de l\'alias %s du domaine %s</p>', $serveralias['alias'], $serveralias['domain']);
|
||||
printf ('<p><a href="%s">Retour à la liste des alias</a></p>', $_SERVER['REDIRECT_SCRIPT_URL']);
|
||||
print "</center>";
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
|
||||
print "<form name=\"form-add\" id=\"form-add\" action=\"\" method=\"POST\">";
|
||||
print " <fieldset>";
|
||||
print " <legend>Ajout d'un serveralias</legend>";
|
||||
print $form;
|
||||
print " <p><input type=\"submit\" value=\"Créer\"/></p>";
|
||||
print " </fieldset>";
|
||||
print "</form>";
|
||||
|
||||
}
|
||||
|
||||
include_once EVOADMIN_BASE . '../tpl/footer.tpl.php';
|
||||
|
||||
|
||||
} else {
|
||||
|
||||
$domain = $params[1];
|
||||
$alias_list = array();
|
||||
|
||||
if ($conf['cluster']) {
|
||||
|
||||
$cache = $conf['cache'];
|
||||
|
||||
$alias_list = array();
|
||||
|
||||
/* parcours de la table Serveralias */
|
||||
$bdd = new bdd();
|
||||
$bdd->open($cache);
|
||||
|
||||
$alias_list = $bdd->list_serveralias($domain);
|
||||
}
|
||||
|
||||
include_once EVOADMIN_BASE . '../tpl/header.tpl.php';
|
||||
include_once EVOADMIN_BASE . '../tpl/menu.tpl.php';
|
||||
include_once EVOADMIN_BASE . '../tpl/webadmin-edit.tpl.php';
|
||||
include_once EVOADMIN_BASE . '../tpl/footer.tpl.php';
|
||||
|
||||
}
|
||||
|
||||
?>
|
|
@ -0,0 +1,83 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* Apache VirtualHost Management Page
|
||||
*
|
||||
* Copyright (c) 2009 Evolix - Tous droits reserves
|
||||
*
|
||||
* vim: expandtab softtabstop=4 tabstop=4 shiftwidth=4 showtabline=2
|
||||
*
|
||||
* @author Gregory Colpart <reg@evolix.fr>
|
||||
* @author Thomas Martin <tmartin@evolix.fr>
|
||||
* @author Sebastien Palma <spalma@evolix.fr>
|
||||
* @version 1.0
|
||||
*/
|
||||
|
||||
/* Appel du script pour récupérer les vhost appartenant à l'utilisateur */
|
||||
|
||||
require_once EVOADMIN_BASE . '../lib/bdd.php';
|
||||
|
||||
global $conf;
|
||||
|
||||
if (!$conf['cluster']) {
|
||||
|
||||
$cmd = 'web-add.sh list-vhost';
|
||||
if(!is_superadmin()) {
|
||||
$cmd = sprintf('%s %s', $cmd, $_SESSION['user']);
|
||||
}
|
||||
sudoexec($cmd, $data_output, $exec_return);
|
||||
|
||||
/* Récupération de cette liste dans le tableau $vhost_list */
|
||||
$vhost_list = array();
|
||||
foreach($data_output as $data_line) {
|
||||
$data_split = split(':', $data_line);
|
||||
array_push($vhost_list, array(
|
||||
'owner' => $data_split[0],
|
||||
'configid' => $data_split[1],
|
||||
'server_name' => $data_split[2],
|
||||
'server_alias' => $data_split[3])
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
else {
|
||||
|
||||
$cache=$conf['cache'];
|
||||
|
||||
$vhost_list = array();
|
||||
|
||||
/* parcours de la table account */
|
||||
$bdd=new bdd();
|
||||
$bdd->open($cache);
|
||||
|
||||
$accounts = $bdd->list_accounts();
|
||||
|
||||
if (!empty($accounts)) {
|
||||
foreach($accounts as $account) {
|
||||
|
||||
$master = $bdd->get_server_from_roleid($account['id_master']);
|
||||
|
||||
$slave = '';
|
||||
if (!empty($account['id_slave']))
|
||||
$slave = $bdd->get_server_from_roleid($account['id_slave']);
|
||||
|
||||
array_push($vhost_list, array(
|
||||
'owner' => $account['name'],
|
||||
'server_name'=> $account['domain'],
|
||||
'bdd' => $account['bdd'],
|
||||
'replication' => $account['replication'],
|
||||
'master' => $master,
|
||||
'slave' => $slave)
|
||||
);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
include_once EVOADMIN_BASE . '../tpl/header.tpl.php';
|
||||
include_once EVOADMIN_BASE . '../tpl/menu.tpl.php';
|
||||
include_once EVOADMIN_BASE . '../tpl/webadmin.tpl.php';
|
||||
include_once EVOADMIN_BASE . '../tpl/footer.tpl.php';
|
||||
|
||||
?>
|
|
@ -0,0 +1,491 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* @desc mini class to manipulate sqlite db for evocluster.
|
||||
*
|
||||
* @example
|
||||
* <?php
|
||||
* require 'bdd.php';
|
||||
*
|
||||
* // create bdd
|
||||
* $bdd = new bdd();
|
||||
*
|
||||
* if (!file_exists("evocluster.sqlite"))
|
||||
* $bdd->create("evocluster.sqlite");
|
||||
* else
|
||||
* $bdd->open("evocluster.sqlite");
|
||||
*
|
||||
* // declare account
|
||||
* $account_demo = array(
|
||||
* "name" => "demo",
|
||||
* "domain" => "demo.quai13.fr",
|
||||
* "bdd" => "demo_bdd",
|
||||
* "replication" => "realtime");
|
||||
*
|
||||
* $bdd->add_account($account_demo);
|
||||
*
|
||||
* // declare servers
|
||||
* $server1 = array("name" => "quai13-www00");
|
||||
* $server2 = array("name" => "quai13-www01");
|
||||
*
|
||||
* // declare roles
|
||||
* $bdd->add_role($account_demo['name'], 'quai13-www00', 'master');
|
||||
* $bdd->add_role($account_demo['name'], 'quai13-www01', 'slave');
|
||||
*
|
||||
* // list domains
|
||||
* $domains = $bdd->list_domains();
|
||||
*
|
||||
* ?>
|
||||
*/
|
||||
|
||||
class bdd {
|
||||
|
||||
private $db; /* resource of a created database */
|
||||
|
||||
/**
|
||||
* @desc Open a sqlite database. Create it if it doesn't exist.
|
||||
* @param string $db_name Name of the sqlite database
|
||||
*/
|
||||
public function open($db_name)
|
||||
{
|
||||
try {
|
||||
$this->db = new SQLiteDatabase($db_name, 0666, $error);
|
||||
}
|
||||
catch(Exception $e)
|
||||
{
|
||||
die ($error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @desc Close the current database instance
|
||||
*
|
||||
* Note: php close automatically the instance on exit
|
||||
*/
|
||||
public function close()
|
||||
{
|
||||
sqlite_close($this->db);
|
||||
}
|
||||
|
||||
/**
|
||||
* @desc Install the table structure on a new sqlite database
|
||||
* @param string $dn_name Name of the sqlite database
|
||||
*/
|
||||
public function create($db_name)
|
||||
{
|
||||
/*
|
||||
* open a database or create it if it doesn't exist
|
||||
*/
|
||||
$this->open($db_name);
|
||||
|
||||
$database = $this->db;
|
||||
|
||||
|
||||
/* Table Accounts */
|
||||
$query = 'CREATE Table Accounts ' .
|
||||
'(id INTEGER PRIMARY KEY , name TEXT, domain TEXT, bdd TEXT, replication TEXT, id_master INTEGER, id_slave INTEGER)';
|
||||
|
||||
if (!$database->queryExec($query, $error))
|
||||
{
|
||||
die($error);
|
||||
}
|
||||
|
||||
/* Table Servers */
|
||||
$query = 'CREATE Table Servers ' .
|
||||
'(id INTEGER PRIMARY KEY , name TEXT, ip TEXT)';
|
||||
|
||||
if (!$database->queryExec($query, $error))
|
||||
{
|
||||
die($error);
|
||||
}
|
||||
|
||||
/* Table ServersAlias */
|
||||
$query = 'CREATE Table Serveralias ' .
|
||||
'(id INTEGER PRIMARY KEY , domain TEXT, alias TEXT)';
|
||||
|
||||
if (!$database->queryExec($query, $error))
|
||||
{
|
||||
die($error);
|
||||
}
|
||||
|
||||
/* Table Roles */
|
||||
$query = 'CREATE Table Roles ' .
|
||||
'(id INTEGER PRIMARY KEY , name TEXT, id_account INTEGER, id_server INTEGER)';
|
||||
|
||||
if (!$database->queryExec($query, $error))
|
||||
{
|
||||
die($error);
|
||||
}
|
||||
}
|
||||
|
||||
public function get_server_from_roleid($roleid)
|
||||
{
|
||||
$database = $this->db;
|
||||
|
||||
$query = "SELECT Servers.name FROM Servers, Roles where Roles.id = '$roleid' and Roles.id_server = Servers.id";
|
||||
|
||||
if ($result = $database->query($query, SQLITE_ASSOC, $error))
|
||||
{
|
||||
$row = $result->fetch();
|
||||
if (isset($row))
|
||||
return $row['Servers.name'];
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @desc Get the account id of an account_name
|
||||
* @param string $account_name Name of the account
|
||||
* @return int 0 if account_name doesn't exist,
|
||||
* id else
|
||||
*/
|
||||
private function get_account_id($account_name)
|
||||
{
|
||||
$database = $this->db;
|
||||
|
||||
$query = "SELECT id FROM Accounts where name = '$account_name'";
|
||||
|
||||
if ($result = $database->query($query, SQLITE_ASSOC, $error))
|
||||
{
|
||||
$row = $result->fetch();
|
||||
if (isset($row))
|
||||
return $row['id'];
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @desc Get account
|
||||
* @param account name
|
||||
* @return array
|
||||
*/
|
||||
public function get_account($account_name)
|
||||
{
|
||||
$database = $this->db;
|
||||
|
||||
$query = "SELECT * FROM Accounts where name = '$account_name'";
|
||||
|
||||
if ($result = $database->query($query, SQLITE_ASSOC, $error))
|
||||
{
|
||||
$row = $result->fetch();
|
||||
if (isset($row))
|
||||
return $row;
|
||||
else
|
||||
return array();
|
||||
}
|
||||
|
||||
return array();
|
||||
}
|
||||
|
||||
/**
|
||||
* @desc Check if account_name entry exists on table Accounts
|
||||
* @param string $account_name Name of the account
|
||||
* @return int 1 if it exists,
|
||||
* 0 else
|
||||
*/
|
||||
public function is_account($account_name)
|
||||
{
|
||||
return !!($this->get_account_id($account_name));
|
||||
}
|
||||
|
||||
/**
|
||||
* @desc Add an account to the table Accounts
|
||||
* @param array {
|
||||
* 'name' => "$name",
|
||||
* 'domain' => "$domain",
|
||||
* 'bdd' => "bdd",
|
||||
* 'replication' => "replication"
|
||||
* }
|
||||
* @return 1 on success,
|
||||
* 0 else
|
||||
*/
|
||||
public function add_account($account)
|
||||
{
|
||||
$database = $this->db;
|
||||
|
||||
$name = $account["name"];
|
||||
$domain = $account["domain"];
|
||||
$bdd = $account["bdd"];
|
||||
$replication = $account["replication"];
|
||||
|
||||
/* check if account exists */
|
||||
if ($this->is_account($name))
|
||||
return 0;
|
||||
|
||||
$query = "INSERT INTO Accounts (name, domain, bdd, replication)
|
||||
VALUES (
|
||||
'$name',
|
||||
'$domain',
|
||||
'$bdd',
|
||||
'$replication');";
|
||||
|
||||
if (!$database->queryExec($query, $error))
|
||||
{
|
||||
die($error);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @desc Add an alias to the table Serveralias
|
||||
* @param array {
|
||||
* 'domain' => "$domain",
|
||||
* 'alias' => "$alias",
|
||||
* }
|
||||
* @return 1 on success,
|
||||
* 0 else
|
||||
*/
|
||||
public function add_serveralias($serveralias)
|
||||
{
|
||||
$database = $this->db;
|
||||
|
||||
$domain = $serveralias["domain"];
|
||||
$alias = $serveralias["alias"];
|
||||
|
||||
$query = "INSERT INTO Serveralias (domain, alias)
|
||||
VALUES (
|
||||
'$domain',
|
||||
'$alias');";
|
||||
|
||||
if (!$database->queryExec($query, $error))
|
||||
{
|
||||
die($error);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* @desc Del an alias from the table Serveralias
|
||||
* @param array {
|
||||
* 'domain' => "$domain",
|
||||
* 'alias' => "$alias",
|
||||
* }
|
||||
* @return 1 on success,
|
||||
* 0 else
|
||||
*/
|
||||
public function del_serveralias($serveralias)
|
||||
{
|
||||
$database = $this->db;
|
||||
|
||||
|
||||
$domain = $serveralias['domain'];
|
||||
$alias = $serveralias['alias'];
|
||||
|
||||
$query = "DELETE FROM Serveralias WHERE domain='$domain' AND alias='$alias';";
|
||||
|
||||
if (!$database->queryExec($query, $error))
|
||||
die($error);
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* @desc Get the server id of a server_name
|
||||
* @param string $server_name Name of the server
|
||||
* @return int 0 if server_name doesn't exist,
|
||||
* id else
|
||||
*/
|
||||
private function get_server_id($server_name)
|
||||
{
|
||||
$database = $this->db;
|
||||
|
||||
$query = "SELECT id FROM Servers where name = '$server_name'";
|
||||
|
||||
if ($result = $database->query($query, SQLITE_ASSOC, $error))
|
||||
{
|
||||
$row = $result->fetch();
|
||||
if (isset($row))
|
||||
return $row['id'];
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @desc Check if server_name entry exists on table Servers
|
||||
* @param string $server_name Name of the server
|
||||
* @return int 1 if it exists,
|
||||
* 0 else
|
||||
*/
|
||||
public function is_server($server_name)
|
||||
{
|
||||
return !!($this->get_server_id($server_name));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @desc Add an server to the table Servers
|
||||
* @param array {
|
||||
* 'name' => "$name",
|
||||
* }
|
||||
* @return 1 on success,
|
||||
* 0 else
|
||||
*/
|
||||
public function add_server($server)
|
||||
{
|
||||
$database = $this->db;
|
||||
|
||||
$name = $server["name"];
|
||||
|
||||
/* check if server exists */
|
||||
if ($this->is_server($name))
|
||||
return 0;
|
||||
|
||||
$query = "INSERT INTO Servers (name)
|
||||
VALUES (
|
||||
'$name'
|
||||
);";
|
||||
|
||||
if (!$database->queryExec($query, $error))
|
||||
die($error);
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* @desc Add a role to the table Roles
|
||||
* @param string $account_name
|
||||
* string $server_name
|
||||
* string $role master or slave
|
||||
* @return 1 on success,
|
||||
* 0 else.
|
||||
*/
|
||||
public function add_role($account_name, $server_name, $role)
|
||||
{
|
||||
$database = $this->db;
|
||||
|
||||
/* get id_account */
|
||||
$id_account = $this->get_account_id($account_name);
|
||||
if ($id_account == 0)
|
||||
return 0;
|
||||
|
||||
/* get id_server */
|
||||
$id_server = $this->get_server_id($server_name);
|
||||
if ($id_server == 0)
|
||||
return 0;
|
||||
|
||||
$query = "INSERT INTO Roles (name, id_account, id_server)
|
||||
VALUES (
|
||||
'$role',
|
||||
'$id_account',
|
||||
'$id_server')";
|
||||
|
||||
if (!$database->queryExec($query, $error))
|
||||
die($error);
|
||||
|
||||
$id = $database->lastInsertRowid();
|
||||
|
||||
/* update id_master or id_slave */
|
||||
if (($role === 'master') || ($role === 'slave'))
|
||||
$query = "UPDATE Accounts SET id_$role = '$id' WHERE id = '$id_account'";
|
||||
|
||||
if (!$database->queryExec($query, $error))
|
||||
die($error);
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @desc List domains by server's role
|
||||
* @param none
|
||||
* @return list of array
|
||||
* example : Array (
|
||||
* [0] => Array
|
||||
* (
|
||||
* [Accounts.id] => 1
|
||||
* [Accounts.name] => demo
|
||||
* [Accounts.domain] => demo.quai13.fr
|
||||
* [Accounts.bdd] => demo_bdd
|
||||
* [Accounts.replication] => realtime
|
||||
* [Accounts.id_master] => 1
|
||||
* [Accounts.id_slave] => 2
|
||||
* [Roles.id] => 1
|
||||
* [Roles.name] => master
|
||||
* [Roles.id_account] => 1
|
||||
* [Roles.id_server] => 1
|
||||
* [Servers.id] => 1
|
||||
* [Servers.name] => quai13-www00
|
||||
* [Servers.ip] =>
|
||||
* )
|
||||
* [1] => Array
|
||||
* (
|
||||
* ...
|
||||
* )
|
||||
* ...
|
||||
* )
|
||||
*/
|
||||
public function list_domains()
|
||||
{
|
||||
$database = $this->db;
|
||||
|
||||
$query = "SELECT * FROM Accounts, Roles, Servers WHERE Accounts.id = Roles.id_account AND Roles.id_server = Servers.id";
|
||||
if($result = $database->query($query, SQLITE_ASSOC, $error))
|
||||
{
|
||||
$domains = array();
|
||||
$i = 0;
|
||||
|
||||
while($row = $result->fetch())
|
||||
{
|
||||
$domains[$i] = $row;
|
||||
++$i;
|
||||
}
|
||||
}
|
||||
else
|
||||
die($error);
|
||||
|
||||
return $domains;
|
||||
}
|
||||
|
||||
public function list_accounts()
|
||||
{
|
||||
$database = $this->db;
|
||||
|
||||
$query = "SELECT * FROM Accounts";
|
||||
|
||||
if($result = $database->query($query, SQLITE_ASSOC, $error))
|
||||
{
|
||||
$accounts = array();
|
||||
$i = 0;
|
||||
|
||||
while($row = $result->fetch())
|
||||
{
|
||||
$accounts[$i] = $row;
|
||||
++$i;
|
||||
}
|
||||
}
|
||||
else
|
||||
die($error);
|
||||
|
||||
return $accounts;
|
||||
}
|
||||
|
||||
public function list_serveralias($domain)
|
||||
{
|
||||
$database = $this->db;
|
||||
|
||||
if ($domain == NULL)
|
||||
return NULL;
|
||||
|
||||
$query = "SELECT * FROM Serveralias WHERE domain = '$domain'";
|
||||
|
||||
if ($result = $database->query($query, SQLITE_ASSOC, $error))
|
||||
{
|
||||
$serveralias = array();
|
||||
$i = 0;
|
||||
|
||||
while($row = $result->fetch())
|
||||
{
|
||||
$serveralias[$i] = $row;
|
||||
++$i;
|
||||
}
|
||||
}
|
||||
else
|
||||
die($error);
|
||||
|
||||
return $serveralias;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
Include "/etc/awstats/awstats.conf.local"
|
||||
LogFile="HOME_DIR/XXX/log/access.log"
|
||||
SiteDomain="SERVERNAME"
|
||||
DirData="HOME_DIR/XXX/awstats"
|
|
@ -0,0 +1,100 @@
|
|||
#!/bin/sh
|
||||
# Script called
|
||||
|
||||
|
||||
set -e
|
||||
|
||||
LOGFILE=~/log/evocluster.log
|
||||
|
||||
MAIL="jdoe@example.com"
|
||||
|
||||
mail_error() {
|
||||
echo "From: John Doe <jdoe@example.com>
|
||||
To: $MAIL
|
||||
Subject: [evocluster] check_cron_state.sh
|
||||
|
||||
$1
|
||||
|
||||
"|/usr/lib/sendmail -oi -t -f "$MAIL"
|
||||
}
|
||||
|
||||
error() {
|
||||
echo -n "$(date +"%b %d %T") " >>$LOGFILE
|
||||
echo "ERROR: $1" |tee -a $LOGFILE >&2
|
||||
mail_error "$1"
|
||||
}
|
||||
|
||||
info() {
|
||||
echo -n "$(date +"%b %d %T") " >>$LOGFILE
|
||||
echo "INFO: $1" |tee -a $LOGFILE
|
||||
}
|
||||
|
||||
|
||||
# Read the state file
|
||||
if [ -e ~/state ]; then
|
||||
. ~/state
|
||||
else
|
||||
error '~/state file does not exist, I dont know who am I!'
|
||||
exit 2
|
||||
fi
|
||||
|
||||
|
||||
# Check if all required variables are set
|
||||
if [ -n "$STATE" ] && [ -n "$IP" ]; then
|
||||
LOCAL_STATE=$STATE
|
||||
REMOTE_IP=$IP
|
||||
else
|
||||
error '$STATE or $IP not set in state file!'
|
||||
exit 2
|
||||
fi
|
||||
|
||||
[ -n "$FORCE_CRON" ] && info 'FORCE_CRON=yes setted. Master is mandated to execute cron.'
|
||||
|
||||
|
||||
if [ "$STATE" = "slave" ]; then
|
||||
info 'Account is in state slave, execution of cron is disabled'
|
||||
exit 1
|
||||
else
|
||||
# env var $FORCE_CRON is set to yes, execute the cron
|
||||
[ "$FORCE_CRON" = "yes" ] && exit 0;
|
||||
|
||||
### rajouter une règle sudo pour pouvoir exécuter ping ?
|
||||
# test if the remote server is alive
|
||||
#if ! ping -c1 -w1 $REMOTE_IP; then
|
||||
# error "Remote server $IP doesn't seem to be up, I don't know what to do...Add 'FORCE_CRON=yes' in ~/state file to execute user cron"
|
||||
# exit 1
|
||||
#fi
|
||||
###
|
||||
|
||||
# try to connect to the remote server and check if it isn't a master
|
||||
REMOTE_STATE=$(mktemp)
|
||||
if ssh $REMOTE_IP [ -e ~/state ]; then
|
||||
ssh $REMOTE_IP cat ~/state >$REMOTE_STATE
|
||||
elif [ $? -eq 255 ]; then
|
||||
error "Failed to connect to slave ($REMOTE_IP)! I don't know what to do.."
|
||||
exit 1
|
||||
else
|
||||
error "State file does not exist on slave !"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
. $REMOTE_STATE
|
||||
rm -rf $REMOTE_STATE
|
||||
if [ -n "$STATE" ]; then
|
||||
REMOTE_STATE=$STATE
|
||||
else
|
||||
error '$STATE not set in remote state file!'
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ "$REMOTE_STATE" = "master" ]; then
|
||||
error "Remote server $IP is master too. (incoherent state)..."
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# Remote server is slave
|
||||
# State is coherent, execute the cron
|
||||
info 'Execute user cron'
|
||||
|
||||
exit 0
|
|
@ -0,0 +1,9 @@
|
|||
#!/bin/sh
|
||||
|
||||
directory=$1
|
||||
|
||||
if [ -d "$directory" ]; then
|
||||
echo -e -n "1"
|
||||
else
|
||||
echo -e -n "0"
|
||||
fi
|
|
@ -0,0 +1,174 @@
|
|||
#!/bin/bash
|
||||
|
||||
############################################################
|
||||
# #
|
||||
# EvoAdmin : gestion des comptes FTP virtuels de ProFTPd #
|
||||
# #
|
||||
# Copyright (c) 2009 Evolix - Tous droits reserves #
|
||||
# #
|
||||
# @author Sebastien Palma <spalma@evolix.fr> #
|
||||
# @version 1.0 #
|
||||
# #
|
||||
############################################################
|
||||
|
||||
# vim: expandtab softtabstop=4 tabstop=4 shiftwidth=4 showtabline=2
|
||||
|
||||
VPASSWD_PATH="/etc/proftpd/vpasswd"
|
||||
FTPLOG_PATH="/var/log/evolix-ftp.log"
|
||||
|
||||
usage() {
|
||||
|
||||
cat <<EOT >&2
|
||||
|
||||
Usage: $0 [ACTION UID [PARAMS]]
|
||||
|
||||
Manage ProFTPd virtual accounts.
|
||||
|
||||
-a ACTION
|
||||
l (list), a (add), m (modify), d (delete) ProFTPd virtual account(s)
|
||||
|
||||
-u UID
|
||||
UID of the real account the virtual FTP accounts will be related to
|
||||
|
||||
Available PARAMS are :
|
||||
|
||||
-n ACCOUNTNAME
|
||||
Name of the ProFTPd virtual account you want to add/edit/delete.
|
||||
Mandatory in all actions.
|
||||
|
||||
-f FOLDER
|
||||
Directory that the virtual account will have as home directory.
|
||||
Mandatory for add and modify action.
|
||||
|
||||
-p PASSWD
|
||||
Password for the virtual account.
|
||||
Mandatory for add and modify action.
|
||||
|
||||
EOT
|
||||
}
|
||||
|
||||
log_msg() {
|
||||
curdate=`date +"%Y/%m/%d %H:%M:%S"`
|
||||
echo "$curdate $1" >>$FTPLOG_PATH
|
||||
}
|
||||
|
||||
get_user_login_by_UID() {
|
||||
uid=$1
|
||||
grep $uid /etc/passwd | awk -F : "{if (\$3==$uid) print \$1}"
|
||||
}
|
||||
|
||||
list_accounts_by_UID() {
|
||||
uid=$1
|
||||
|
||||
account_list=''
|
||||
oldIFS=IFS
|
||||
IFS=$'\n'
|
||||
|
||||
for line in `cat $VPASSWD_PATH`
|
||||
do
|
||||
line_uid=`echo $line | cut -d":" -f3`
|
||||
|
||||
if [ ! "$uid" ] || [ "$line_uid" == "$uid" ]; then
|
||||
username=`get_user_login_by_UID $line_uid`
|
||||
account=`echo $line | cut -d":" -f1`
|
||||
path=`echo $line | cut -d":" -f6`
|
||||
if [ -r $path/.size ]; then
|
||||
size=`cat $path/.size`
|
||||
else
|
||||
size=0
|
||||
fi
|
||||
#modif=`cat $path/.lastmodified`
|
||||
# Passage en minuscule ?
|
||||
#account=`echo $account | tr '[A-Z]' '[a-z]'`
|
||||
#path=`echo $path | tr '[A-Z]' '[a-z]'`
|
||||
|
||||
account_list="${account_list}$username:$account:$path:$size:$modif\n"
|
||||
|
||||
fi
|
||||
done
|
||||
|
||||
echo "$account_list"
|
||||
|
||||
IFS=$oldIFS
|
||||
}
|
||||
|
||||
add_account() {
|
||||
user_id=$1
|
||||
account_name=$2
|
||||
path=$3
|
||||
passwd=$4
|
||||
|
||||
cmd="{if (\$3==$user_id) print \$4}"
|
||||
user_gid=`awk -F : "$cmd" /etc/passwd`
|
||||
|
||||
# Si le répoertoire de travail du compte FTP n'existe pas, on le crée
|
||||
if [ ! -d "$path" ]; then
|
||||
mkdir -p $path
|
||||
chown $user_id:$user_gid $path
|
||||
# fix by tmartin : s/655/755/
|
||||
chmod 755 $path
|
||||
setfacl -R -d -m 'o:rX' $path
|
||||
fi
|
||||
|
||||
echo `echo $passwd | ftpasswd --passwd --file=$VPASSWD_PATH --name=$account_name --uid=$user_id --gid=$user_gid --home=$path --shell=/bin/false --stdin`
|
||||
log_msg "Creation du compte $account_name (uid=$user_id, gid=$user_gid, home=$path)"
|
||||
}
|
||||
|
||||
edit_password() {
|
||||
account_name=$1
|
||||
passwd=$2
|
||||
|
||||
echo `echo $passwd | ftpasswd --passwd --file=$VPASSWD_PATH --name=$account_name --uid=9999 --gid=9999 --home=/dev/null --shell=/dev/null --change-password --stdin`
|
||||
|
||||
}
|
||||
|
||||
|
||||
delete_account() {
|
||||
|
||||
account_name=$1
|
||||
|
||||
echo `ftpasswd --passwd --file=$VPASSWD_PATH --name=$account_name --uid=9999 --gid=9999 --home=/dev/null --shell=/dev/null --delete-user`
|
||||
log_msg "Suppression du compte $account_name"
|
||||
}
|
||||
|
||||
|
||||
while getopts a:u:n:f:p: opt; do
|
||||
case "$opt" in
|
||||
a)
|
||||
in_action=$OPTARG
|
||||
;;
|
||||
u)
|
||||
in_userid=$OPTARG
|
||||
;;
|
||||
n)
|
||||
in_accountname=$OPTARG
|
||||
;;
|
||||
f)
|
||||
in_workpath=$OPTARG
|
||||
;;
|
||||
p)
|
||||
in_password=$OPTARG
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
case "$in_action" in
|
||||
l)
|
||||
account_list=`list_accounts_by_UID $in_userid`
|
||||
echo -e -n $account_list
|
||||
exit 1
|
||||
;;
|
||||
a)
|
||||
echo -e -n `add_account $in_userid $in_accountname $in_workpath $in_password`
|
||||
exit 1
|
||||
;;
|
||||
m)
|
||||
echo -e -n `edit_password $in_accountname $in_password`
|
||||
exit 1;
|
||||
;;
|
||||
d)
|
||||
echo -e -n `delete_account $in_accountname`
|
||||
exit 1;
|
||||
;;
|
||||
esac
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
#!/bin/sh
|
||||
#
|
||||
# Get main domain and aliases for a specified account from the Apache
|
||||
# virtualhost.
|
||||
# It's part of Evocluster project.
|
||||
|
||||
set -e
|
||||
|
||||
if [ $# -ne 1 ]; then
|
||||
echo >&2 "Usage: $0 <account>"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
vhost="/etc/apache2/sites-available/$1"
|
||||
|
||||
# Extract ServerName and ServerAlias, remove third level part of domains,
|
||||
# remove duplicate domains, and print the list to stdout, one domain per line.
|
||||
perl -ne 'print $3 if (/^\s*Server(Name|Alias)\s+(.*\.)?([^\.]+\.[^\.]+)$/)' $vhost |sort -u
|
|
@ -0,0 +1,100 @@
|
|||
#!/bin/sh
|
||||
|
||||
# Script to install MySQL and lsync replication on master and slave host.
|
||||
# It's part of Evocluster project.
|
||||
|
||||
|
||||
set -e
|
||||
|
||||
LOGFILE=~/log/evocluster.log
|
||||
|
||||
error() {
|
||||
echo -n "$(date +"%b %d %T") " >>$LOGFILE
|
||||
echo "ERROR: $1" |tee -a $LOGFILE >&2
|
||||
}
|
||||
|
||||
info() {
|
||||
echo -n "$(date +"%b %d %T") " >>$LOGFILE
|
||||
echo "INFO: $1" |tee -a $LOGFILE
|
||||
}
|
||||
|
||||
if [ $# -ne 1 ] && ([ $1 != 'master' ] || [ $1 != 'slave']); then
|
||||
error 'You must specify one argument: master or slave'
|
||||
exit 2
|
||||
fi
|
||||
|
||||
if [ $1 = 'master' ]; then
|
||||
|
||||
# **
|
||||
# Warning: script supposes the database to configure is empty and stay
|
||||
# empty during all the configuration process.
|
||||
# **
|
||||
|
||||
# Change MySQL configuration
|
||||
sed -i 's/^bind-address\t.*$/#&/' /etc/mysql/my.cnf
|
||||
sed -i 's/^#\(server-id\t.*\)$/\1/' /etc/mysql/my.cnf
|
||||
sed -i 's/^#\(log_bin\t.*\)$/\1/' /etc/mysql/my.cnf
|
||||
/etc/init.d/mysql restart # a voir...
|
||||
|
||||
# Create repl user if it doesn't exist
|
||||
pass=$(apg -c /dev/urandom -n1 -E \&\\\/\"\')
|
||||
if [ -z "$(mysql -e "SELECT user FROM mysql.user WHERE user='repl'")" ]
|
||||
then
|
||||
mysql -e "GRANT REPLICATION SLAVE ON *.* to repl@'%' IDENTIFIED BY
|
||||
'$pass'"
|
||||
fi
|
||||
|
||||
# lsyncd daemon
|
||||
(crontab -l; echo "@reboot lsyncd ~/www slave:www") |crontab -
|
||||
|
||||
# TODO: Monitoring lsyncd a mettre en place
|
||||
|
||||
MASTER_LOG_FILE=$(mysql -Ne "SHOW MASTER STATUS" |cut -f 1)
|
||||
MASTER_LOG_POS=$(mysql -Ne "SHOW MASTER STATUS" |cut -f 2)
|
||||
if [ -z $MASTER_LOG_FILE ] || [ -z $MASTER_LOG_POS ]; then
|
||||
error 'MASTER_LOG_FILE or MASTER_LOG_POS are not set, bin-log seem not
|
||||
working correctly.'
|
||||
fi
|
||||
|
||||
# Return some MySQL information
|
||||
# (required to configure slave)
|
||||
echo "MASTER_PASSWORD=$pass"
|
||||
echo "MASTER_LOG_FILE=$MASTER_LOG_FILE"
|
||||
echo "MASTER_LOG_POS=$MASTER_LOG_POS"
|
||||
|
||||
else
|
||||
|
||||
# Source stding
|
||||
# doesn't POSIX compatible :'(
|
||||
#. <(grep -E '^MASTER_(HOST|DATABASE|PASSWORD|LOG_FILE|LOG_POS)=')
|
||||
tmpfile=$(mktemp)
|
||||
grep -E '^MASTER_(HOST|DATABASE|PASSWORD|LOG_FILE|LOG_POS)=' >$tmpfile
|
||||
. $tmpfile
|
||||
rm $tmpfile
|
||||
|
||||
# Change MySQL configuration
|
||||
sed -i 's/^#(server-id\t.*)\d$/\12/' /etc/mysql/my.cnf
|
||||
if grep -q '^replicate-do-db' /etc/mysql/my.cnf; then
|
||||
sed -i "/^replicate-do-db\t.*/&, $MASTER_DATABASE"
|
||||
else
|
||||
sed -i "/^#binlog_ignore_db/a replicate-do-db = $MASTER_DATABASE"
|
||||
fi
|
||||
/etc/init.d/mysql restart # a voir...
|
||||
|
||||
# Start replication
|
||||
mysql -e "CHANGE MASTER TO
|
||||
MASTER_HOST='$MASTER_HOST',
|
||||
MASTER_USER='repl',
|
||||
MASTER_PASSWORD='$MASTER_PASSWORD',
|
||||
MASTER_LOG_FILE='$MASTER_LOG_FILE',
|
||||
MASTER_LOG_POS=$MASTER_LOG_FILE"
|
||||
mysql -e "START SLAVE"
|
||||
sleep 2
|
||||
mysql -Ne "SHOW SLAVE STATUS"
|
||||
|
||||
# TODO: Add nagios check
|
||||
|
||||
# info a retourner :
|
||||
# - show slave status pour etre sur que la replication a demarre
|
||||
|
||||
fi
|
|
@ -0,0 +1,43 @@
|
|||
|
||||
echo "Ajout d'un compte/base MySQL"
|
||||
echo "Entrez le nom de la nouvelle base MySQL"
|
||||
read base
|
||||
|
||||
echo "Entrez le login qui aura tous les droits sur cette base"
|
||||
echo "(Vous pouvez entrer un login existant)"
|
||||
read login
|
||||
|
||||
echo -n "Cet utilisateur est-il deja existant ? [y|N] "
|
||||
read confirm
|
||||
|
||||
if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
|
||||
echo "Attention, si l'utilisateur etait existant, il sera ecrase !"
|
||||
echo "Entrez le mot de passe MySQL (ou vide pour aleatoire) :"
|
||||
read -s passe2
|
||||
echo ""
|
||||
|
||||
length=${#passe2}
|
||||
|
||||
if [ ! -n "$passe2" ]; then
|
||||
echo "Generation du mot de passe aleatoire. "
|
||||
passe2=$(apg -n1 -E I0O)
|
||||
fi
|
||||
|
||||
mysql -umysqladmin << END_SCRIPT
|
||||
CREATE DATABASE \`$base\`;
|
||||
GRANT ALL PRIVILEGES ON \`$base\`.* TO \`$login\`@localhost IDENTIFIED BY "$passe2";
|
||||
FLUSH PRIVILEGES;
|
||||
END_SCRIPT
|
||||
|
||||
else
|
||||
|
||||
mysql -umysqladmin << END_SCRIPT
|
||||
CREATE DATABASE \`$base\`;
|
||||
GRANT ALL PRIVILEGES ON \`$base\`.* TO \`$login\`@localhost;
|
||||
FLUSH PRIVILEGES;
|
||||
END_SCRIPT
|
||||
|
||||
fi
|
||||
|
||||
echo "Si aucune erreur, creation de la base MySQL $base OK"
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
#!/bin/bash
|
||||
|
||||
# TODO:
|
||||
# - check if database and/or role already exist
|
||||
|
||||
# To integrate it to web-add.sh, add this into web-add.local.sh:
|
||||
#
|
||||
# read -p "Créer un compte PostgreSQL ? [Y|n] : " r
|
||||
# if [ "$r" != "n" ] || [ "$r" != "N" ]; then
|
||||
# /usr/share/scripts/pgsql-add.sh
|
||||
# fi
|
||||
|
||||
|
||||
set -e
|
||||
|
||||
read -p "Nom de la base de données : " base
|
||||
read -p "Utilisateur propriétaire de la base : " user
|
||||
read -s -p "Mot de passe (vide pour aléatoire) : " password
|
||||
echo
|
||||
|
||||
if [ ! -n "$password" ]; then
|
||||
password=$(apg -n1 -E I0O)
|
||||
echo "> Mot de passe généré : $password"
|
||||
fi
|
||||
|
||||
su postgres -c "psql -qc \"CREATE ROLE $user WITH PASSWORD '$password'\""
|
||||
su postgres -c "psql -qc \"CREATE DATABASE $base WITH OWNER $user\""
|
||||
|
||||
echo "Creation de la base OK."
|
|
@ -0,0 +1,23 @@
|
|||
#!/bin/sh
|
||||
|
||||
for dir in `cat /etc/proftpd/vpasswd | cut -d : -f 6`; do
|
||||
#for dir in /home/dalleFTP/reynaud_mila; do
|
||||
if [ -d $dir ]; then
|
||||
du -s $dir | cut -f 1 >$dir/.size
|
||||
chmod 644 $dir/.size
|
||||
|
||||
#mtime=0
|
||||
#export IFS=$'\n'
|
||||
#for file in `find $dir -type f -not -name .size -not -name .last-modified`; do
|
||||
# timestamp=`stat -c %Y $file`
|
||||
# if [ $timestamp -gt $mtime ]; then
|
||||
# mtime=$timestamp
|
||||
# fi
|
||||
#done
|
||||
#unset IFS
|
||||
|
||||
#echo $mtime >$dir/.lastmodified
|
||||
#chmod 644 $dir/.lastmodified
|
||||
fi
|
||||
done
|
||||
|
|
@ -0,0 +1,90 @@
|
|||
#!/bin/sh
|
||||
#
|
||||
# Script to do a per account synchronization of files, database and user's
|
||||
# crontab.
|
||||
# It's part of Evocluster project.
|
||||
|
||||
|
||||
set -e
|
||||
|
||||
LOGFILE=~/log/evocluster.log
|
||||
PIDFILE=/tmp/evocluster-$USER.pid
|
||||
|
||||
sync() {
|
||||
set +e
|
||||
mysqldump >~/dump.sql
|
||||
crontab -l >~/crontab
|
||||
rsync -a --delete ~/www ~/dump.sql ~/crontab $1:
|
||||
set -e
|
||||
}
|
||||
|
||||
error() {
|
||||
echo -n "$(date +"%b %d %T") " >>$LOGFILE
|
||||
echo "ERROR: $1" |tee -a $LOGFILE >&2
|
||||
}
|
||||
|
||||
info() {
|
||||
echo -n "$(date +"%b %d %T") " >>$LOGFILE
|
||||
echo "INFO: $1" |tee -a $LOGFILE
|
||||
}
|
||||
|
||||
|
||||
# Read the state file
|
||||
if [ -e ~/state ]; then
|
||||
. ~/state
|
||||
else
|
||||
error 'state file does not exist, I do not know who am I!'
|
||||
exit 2
|
||||
fi
|
||||
|
||||
# Check if all required variables are set
|
||||
if [ -n "$STATE" ] && [ -n "$IP" ]; then
|
||||
LOCAL_STATE=$STATE
|
||||
REMOTE_IP=$IP
|
||||
else
|
||||
error '$STATE or $IP not set in state file!'
|
||||
exit 2
|
||||
fi
|
||||
|
||||
# Check if there is not another instance of the script running
|
||||
if [ -e $PIDFILE ]; then
|
||||
error "$0 already running (PID $(cat $PIDFILE))!"
|
||||
exit 2
|
||||
fi
|
||||
echo "$$" > $PIDFILE
|
||||
trap "rm -f $PIDFILE" EXIT
|
||||
|
||||
if [ $LOCAL_STATE = 'master' ]; then
|
||||
|
||||
# Try to connect to the remote server and check if it is a slave
|
||||
REMOTE_STATE=$(mktemp)
|
||||
if ssh $REMOTE_IP [ -e ~/state ]; then
|
||||
ssh $REMOTE_IP cat ~/state >$REMOTE_STATE
|
||||
elif [ $? -eq 255 ]; then
|
||||
error "failed to connect to slave ($REMOTE_IP)!"
|
||||
exit 2
|
||||
else
|
||||
error "state file does not exist on slave!"
|
||||
exit 2
|
||||
fi
|
||||
|
||||
. $REMOTE_STATE
|
||||
rm -f $REMOTE_STATE
|
||||
if [ -n "$STATE" ]; then
|
||||
REMOTE_STATE=$STATE
|
||||
else
|
||||
error '$STATE not set in remote state file!'
|
||||
exit 2
|
||||
fi
|
||||
|
||||
if [ $REMOTE_STATE = 'slave' ]; then
|
||||
info 'local server is master and remote server is slave.'
|
||||
info "starting replication at $(/bin/date +"%Y-%m-%d %H:%M")."
|
||||
sync $REMOTE_IP
|
||||
info "replication ended at $(/bin/date +"%Y-%m-%d %H:%M")."
|
||||
else
|
||||
info 'remote server is not slave. Doing nothing.'
|
||||
fi
|
||||
else
|
||||
info 'local server is not master. Doing nothing.'
|
||||
fi
|
|
@ -0,0 +1,112 @@
|
|||
#!/bin/sh
|
||||
#
|
||||
# Script to do a per domain synchronization of user's maildirs and ldap
|
||||
# entries.
|
||||
# It's part of Evocluster project.
|
||||
|
||||
|
||||
set -e
|
||||
|
||||
sync() {
|
||||
set +e
|
||||
ldapsearch >~/$DOMAIN/dump.sql
|
||||
rsync -a --delete ~/$DOMAIN $1:
|
||||
set -e
|
||||
}
|
||||
|
||||
error() {
|
||||
echo -n "$(date +"%b %d %T") " >>$LOGFILE
|
||||
echo "ERROR: $1" |tee -a $LOGFILE >&2
|
||||
}
|
||||
|
||||
info() {
|
||||
echo -n "$(date +"%b %d %T") " >>$LOGFILE
|
||||
echo "INFO: $1" >>$LOGFILE
|
||||
if [ -t 0 ]; then
|
||||
echo "INFO: $1"
|
||||
fi
|
||||
}
|
||||
|
||||
|
||||
# Check input parameters
|
||||
if [ $# -eq 2 ]; then
|
||||
if [ -d ~/$1 ]; then
|
||||
DOMAIN=$1
|
||||
LOGFILE=~/$DOMAIN/evocluster.log
|
||||
PIDFILE=/tmp/evocluster-mail-$DOMAIN.pid
|
||||
else
|
||||
if [ -t 0 ]; then
|
||||
echo "$HOME/$1 does not exist. Guess no mail configured for this domain."
|
||||
fi
|
||||
exit 0
|
||||
fi
|
||||
if [ -d /home/$2 ]; then
|
||||
ACCOUNT=$2
|
||||
else
|
||||
error "/home/$2 does not exist."
|
||||
exit 2
|
||||
fi
|
||||
else
|
||||
echo "Usage: $0 <mail domain> <web account>"
|
||||
exit 2
|
||||
fi
|
||||
|
||||
# Read the state file
|
||||
if [ -e /home/$ACCOUNT/state ]; then
|
||||
. /home/$ACCOUNT/state
|
||||
else
|
||||
error 'state file does not exist, I do not know who am I!'
|
||||
exit 2
|
||||
fi
|
||||
|
||||
# Check if all required variables are set
|
||||
if [ -n "$STATE" ] && [ -n "$IP" ]; then
|
||||
LOCAL_STATE=$STATE
|
||||
REMOTE_IP=$IP
|
||||
else
|
||||
error '$STATE or $IP not set in state file!'
|
||||
exit 2
|
||||
fi
|
||||
|
||||
# Check if there is not another instance of the script running
|
||||
if [ -e $PIDFILE ]; then
|
||||
error "$0 already running (PID $(cat $PIDFILE))!"
|
||||
exit 2
|
||||
fi
|
||||
echo "$$" > $PIDFILE
|
||||
trap "rm -f $PIDFILE" EXIT
|
||||
|
||||
if [ $LOCAL_STATE = 'master' ]; then
|
||||
|
||||
# Try to connect to the remote server and check if it is a slave
|
||||
REMOTE_STATE=$(mktemp)
|
||||
if ssh $REMOTE_IP [ -e /home/$ACCOUNT/state ]; then
|
||||
ssh $REMOTE_IP cat /home/$ACCOUNT/state >$REMOTE_STATE
|
||||
elif [ $? -eq 255 ]; then
|
||||
error "failed to connect to slave ($REMOTE_IP)!"
|
||||
exit 2
|
||||
else
|
||||
error "state file does not exist on slave!"
|
||||
exit 2
|
||||
fi
|
||||
|
||||
. $REMOTE_STATE
|
||||
rm -f $REMOTE_STATE
|
||||
if [ -n "$STATE" ]; then
|
||||
REMOTE_STATE=$STATE
|
||||
else
|
||||
error '$STATE not set in remote state file!'
|
||||
exit 2
|
||||
fi
|
||||
|
||||
if [ $REMOTE_STATE = 'slave' ]; then
|
||||
info 'local server is master and remote server is slave.'
|
||||
info "starting replication at $(/bin/date +"%Y-%m-%d %H:%M")."
|
||||
sync $REMOTE_IP
|
||||
info "replication ended at $(/bin/date +"%Y-%m-%d %H:%M")."
|
||||
else
|
||||
info 'remote server is not slave. Doing nothing.'
|
||||
fi
|
||||
else
|
||||
info 'local server is not master. Doing nothing.'
|
||||
fi
|
|
@ -0,0 +1,72 @@
|
|||
<VirtualHost *:80>
|
||||
|
||||
# FQDN principal
|
||||
ServerName SERVERNAME
|
||||
#ServerAlias SERVERNAME
|
||||
|
||||
# Repertoire principal
|
||||
DocumentRoot HOME_DIR/XXX/www/
|
||||
|
||||
# Propriete du repertoire
|
||||
<Directory HOME_DIR/XXX/www/>
|
||||
#Options Indexes SymLinksIfOwnerMatch
|
||||
Options SymLinksIfOwnerMatch
|
||||
AllowOverride AuthConfig Limit FileInfo
|
||||
</Directory>
|
||||
|
||||
# CGI
|
||||
ScriptAlias /cgi-RANDOM /usr/lib/cgi-bin/
|
||||
<Directory /usr/lib/cgi-bin/>
|
||||
Options ExecCGI -MultiViews
|
||||
AllowOverride None
|
||||
|
||||
AuthName "Restricted"
|
||||
AuthUserFile HOME_DIR/XXX/.htpasswd
|
||||
AuthGroupFile /dev/null
|
||||
AuthType Basic
|
||||
require valid-user
|
||||
|
||||
Order Deny,Allow
|
||||
Deny from all
|
||||
#Allow from YYY.YYY.YYY.YYY
|
||||
|
||||
Satisfy any
|
||||
</Directory>
|
||||
|
||||
# user - group (thanks to sesse@debian.org)
|
||||
AssignUserID www-XXX XXX
|
||||
|
||||
# LOG
|
||||
CustomLog /var/log/apache2/access.log combined
|
||||
CustomLog HOME_DIR/XXX/log/access.log combined
|
||||
ErrorLog HOME_DIR/XXX/log/error.log
|
||||
|
||||
# AWSTATS
|
||||
SetEnv AWSTATS_FORCE_CONFIG XXX
|
||||
|
||||
# REWRITE
|
||||
UseCanonicalName On
|
||||
RewriteEngine On
|
||||
RewriteLog "/var/log/apache2/rewrite.log"
|
||||
RewriteLogLevel 0
|
||||
RewriteCond %{HTTP_HOST} !^SERVERNAME$
|
||||
RewriteRule ^/(.*) http://%{SERVER_NAME}/$1 [L,R]
|
||||
|
||||
# PHP
|
||||
#php_admin_flag engine off
|
||||
#AddType text/html .html
|
||||
#php_admin_flag display_errors On
|
||||
#php_flag short_open_tag On
|
||||
#php_flag register_globals On
|
||||
#php_admin_value memory_limit 256M
|
||||
#php_admin_value max_execution_time 60
|
||||
#php_admin_value upload_max_filesize 8M
|
||||
#php_admin_flag allow_url_fopen Off
|
||||
php_admin_value sendmail_path "/usr/sbin/sendmail -t -i -f www-XXX"
|
||||
php_admin_value error_log "HOME_DIR/XXX/log/php.log"
|
||||
php_admin_value open_basedir "/usr/share/php:HOME_DIR/XXX:/tmp"
|
||||
|
||||
</VirtualHost>
|
||||
|
||||
# vim: set filetype=apache expandtab shiftwidth=4 softtabstop=4 tabstop=4 :
|
||||
|
|
@ -0,0 +1,53 @@
|
|||
<VirtualHost *:80>
|
||||
ServerName SERVERNAME
|
||||
ServerAdmin webmaster@localhost
|
||||
|
||||
DocumentRoot /var/www/
|
||||
<Directory />
|
||||
Options FollowSymLinks
|
||||
AllowOverride None
|
||||
|
||||
Deny from all
|
||||
#Allow from XXX.XXX.XXX.XXX
|
||||
</Directory>
|
||||
|
||||
<Directory /var/www/>
|
||||
Options Indexes FollowSymLinks MultiViews
|
||||
AllowOverride None
|
||||
</Directory>
|
||||
|
||||
ErrorDocument 403 http://www.evolix.fr/
|
||||
|
||||
ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
|
||||
<Directory "/usr/lib/cgi-bin">
|
||||
AllowOverride None
|
||||
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
|
||||
</Directory>
|
||||
|
||||
ErrorLog /var/log/apache2/error.log
|
||||
|
||||
Alias /munin /var/cache/munin/www
|
||||
|
||||
Alias /phpmyadmin-RANDOM /usr/share/phpmyadmin/
|
||||
|
||||
# Possible values include: debug, info, notice, warn, error, crit,
|
||||
# alert, emerg.
|
||||
LogLevel warn
|
||||
|
||||
CustomLog /var/log/apache2/access.log combined
|
||||
|
||||
#Alias /horde3 /usr/share/horde3
|
||||
#<Directory /usr/share/horde3>
|
||||
# Options FollowSymLinks
|
||||
# AllowOverride Limit
|
||||
# Allow from all
|
||||
#</Directory>
|
||||
|
||||
<Files ~ "\.(inc|bak)$">
|
||||
deny from all
|
||||
</Files>
|
||||
|
||||
</VirtualHost>
|
||||
|
||||
# vim: set filetype=apache expandtab shiftwidth=4 softtabstop=4 tabstop=4 :
|
||||
|
|
@ -0,0 +1,658 @@
|
|||
#!/bin/bash
|
||||
|
||||
#
|
||||
# Gestion des comptes web et des hôtes virtuels Apache sur un EvoCluster
|
||||
#
|
||||
# Copyright (c) 2009 Evolix - Tous droits reserves
|
||||
# $Id: web-add.sh 221 2012-02-22 15:52:18Z reg $
|
||||
#
|
||||
|
||||
# TODO
|
||||
# - Gestion des quota
|
||||
# - Possibilité de créer un compte FTP-only
|
||||
# - Pouvoir spécifier le CONTACT_MAIL dans un fichier de conf
|
||||
# - Traduire usage() en francais, ou l'inverse ??
|
||||
|
||||
set -e
|
||||
|
||||
HOME="/root"
|
||||
CONTACT_MAIL=""
|
||||
WWWBOUNCE_MAIL=""
|
||||
LOCAL_SCRIPT="/usr/share/scripts/web-add.local.sh"
|
||||
PRE_LOCAL_SCRIPT="/usr/share/scripts/web-add.pre-local.sh"
|
||||
TPL_VHOST="/usr/share/scripts/vhost"
|
||||
TPL_AWSTATS="/usr/share/scripts/awstats.XXX.conf"
|
||||
TPL_MAIL="/usr/share/scripts/web-mail.tpl"
|
||||
VHOST_PATH="/etc/apache2/sites-enabled/"
|
||||
MAX_LOGIN_CHAR=16
|
||||
HOME_DIR="/home"
|
||||
MYSQL_CREATE_DB_OPTS=""
|
||||
MIN_UID=5000
|
||||
NOBODY_UID=65534
|
||||
SSH="/usr/bin/ssh"
|
||||
WEBADD="/usr/share/scripts/web-add.sh"
|
||||
SSH_USER="root"
|
||||
LAST_UID="cut -d: -f3 /etc/passwd | grep -v $NOBODY_UID | sort -n | tail -1"
|
||||
VMAIL_USER="vmail"
|
||||
|
||||
# Utiliser ce fichier pour redefinir la valeur des variables ci-dessus
|
||||
config_file="/etc/evolix/web-add.conf"
|
||||
[ -r $config_file ] && . $config_file
|
||||
|
||||
usage() {
|
||||
cat <<EOT >&2
|
||||
|
||||
Usage: $0 COMMAND [ARG]
|
||||
|
||||
add [[OPTIONS] LOGIN WWWDOMAIN IP_MASTER IP_SLAVE REPLICATION_MODE]
|
||||
|
||||
Create web account LOGIN on Master and Slave servers, state file in
|
||||
/home/LOGIN and push ssh public key of Master in Slave .ssh/authorized.
|
||||
|
||||
-p PASSWD
|
||||
FTP and SFTP password (default : random)
|
||||
|
||||
-m DBNAME
|
||||
Name of MySQL database (default : same as account)
|
||||
|
||||
-P DBPASSWD
|
||||
MySQL password (default : random)
|
||||
|
||||
-l MAIL
|
||||
Send summary email to MAIL
|
||||
|
||||
If REPLICATION_MODE is deferred:
|
||||
|
||||
-f interval
|
||||
interval between each replication
|
||||
|
||||
-c min|hour
|
||||
Unit for -f argument
|
||||
Eg.: -f 4 -c hour meens do replication each 4 hours.
|
||||
|
||||
Example : web-add-cluster.sh add -m testdb -f 4 -c hour testlogin testdomain.com 192.168.0.1 192.168.0.2 deferred
|
||||
|
||||
del LOGIN IP_MASTER IP_SLAVE [DBNAME]
|
||||
|
||||
Delete account and all files related (Apache, Awstats, etc) in Master and
|
||||
Slave server.
|
||||
Archive home directory.
|
||||
Remove MySQL database if DBNAME is specified.
|
||||
|
||||
add-alias WWWDOMAIN ALIAS IP_MASTER IP_SLAVE
|
||||
|
||||
Add a ServerAlias to an Apache vhost on Master and Slave
|
||||
|
||||
del-alias WWWDOMAIN ALIAS IP_MASTER IP_SLAVE
|
||||
|
||||
Del a ServerAlias from an Apache vhost on Master and Slave
|
||||
|
||||
NOTE: to create an account or add/del an alias on only one server (without
|
||||
replication to a slave), we must pass "null" keyword instead of IP_SLAVE.
|
||||
|
||||
EOT
|
||||
}
|
||||
|
||||
#
|
||||
# Affiche un message d'erreur de validation
|
||||
#
|
||||
in_error() {
|
||||
msg=$1
|
||||
cat >&2 <<EOT
|
||||
***
|
||||
Erreur : $msg
|
||||
***
|
||||
EOT
|
||||
}
|
||||
|
||||
gen_random_passwd() {
|
||||
apg -c /dev/urandom -n1 -E oOlL10\&\\\/\"\'
|
||||
}
|
||||
|
||||
validate_login() {
|
||||
login=$1
|
||||
|
||||
length=${#login}
|
||||
|
||||
if [ $length -lt 3 ]; then
|
||||
in_error "Le login doit contenir plus de 2 caracteres"
|
||||
return 1
|
||||
fi
|
||||
|
||||
if [ $length -gt $MAX_LOGIN_CHAR ]; then
|
||||
in_error "Le login ne doit pas contenir plus de $MAX_LOGIN_CHAR caracteres"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
validate_passwd() {
|
||||
passwd=$1
|
||||
length=${#passwd}
|
||||
|
||||
if [ $length -lt 6 ] && [ $length -gt 0 ]; then
|
||||
in_error "Le mot de passe doit avoir au moins 6 caracteres"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
validate_dbname() {
|
||||
dbname=$1
|
||||
# aandre 18/06
|
||||
# if mysql -ss -e "show databases" | grep "^$dbname$" >/dev/null; then
|
||||
# in_error "Base de données déjà existante"
|
||||
# return 1
|
||||
# fi
|
||||
}
|
||||
|
||||
validate_wwwdomain() {
|
||||
wwwdomain=$1
|
||||
if [ -z "$wwwdomain" ]; then
|
||||
in_error "Le nom de domaine est obligatoire"
|
||||
return 1
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
validate_mail() {
|
||||
return 0
|
||||
}
|
||||
|
||||
validate_replmode() {
|
||||
if [ $in_replmode != "realtime" ] && [ $in_replmode != "deferred" ]; then
|
||||
in_error "Le mode de replication doit etre realtime ou deferred"
|
||||
return 1
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
validate_replinterval() {
|
||||
if [ -z "$in_replunit" ]; then
|
||||
in_error "L'unite de l'intervalle de replication doit etre specifiee"
|
||||
return 1
|
||||
elif [ $in_replunit != "min" ] && [ $in_replunit != "hour" ]; then
|
||||
in_error "L'unite de l'intervalle de replication doit etre min (minute), hour (heure)"
|
||||
return 1
|
||||
fi
|
||||
if [ -z "$in_replinterval" ]; then
|
||||
in_error "L'intervalle de replication doit etre specifiee"
|
||||
return 1
|
||||
elif [ $in_replunit = "min" ]; then
|
||||
if [ $in_replinterval -lt 1 ] || [ $in_replinterval -gt 60 ]; then
|
||||
in_error "Valeur incorecte pour l'intervalle en minute"
|
||||
return 1
|
||||
fi
|
||||
elif [ $in_replunit = "hour" ]; then
|
||||
if [ $in_replinterval -lt 1 ] || [ $in_replinterval -gt 24 ]; then
|
||||
in_error "Valeur incorecte pour l'intervalle en heure"
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
step_ok() {
|
||||
msg=$1
|
||||
echo "[OK] $msg"
|
||||
}
|
||||
|
||||
create_www_accounts() {
|
||||
|
||||
CMD_MASTER="$SSH -T $SSH_USER@$in_master"
|
||||
CMD_SLAVE="$SSH -T $SSH_USER@$in_slave"
|
||||
|
||||
|
||||
|
||||
# On verifie que le compte n'existe pas sur master et slave
|
||||
|
||||
if [ -n "$($CMD_MASTER cut -d: -f1 /etc/passwd| grep ^$in_login$)" ]; then
|
||||
in_error "Le compte $in_login existe sur $in_master";
|
||||
exit 1;
|
||||
fi
|
||||
|
||||
if [ $in_slave != "null" ]; then
|
||||
if [ -n "$($CMD_SLAVE cut -d: -f1 /etc/passwd| grep ^$in_login$)" ]; then
|
||||
in_error "Le compte $in_login existe sur $in_slave";
|
||||
exit 1;
|
||||
fi
|
||||
fi
|
||||
|
||||
|
||||
# Trouver un UID valide et commun pour le compte cree sur Master et Slave
|
||||
|
||||
last_uid_master=$($CMD_MASTER $LAST_UID)
|
||||
if [ -z "$last_uid_master" ]; then
|
||||
echo "error while fetching uid in master";
|
||||
return 1
|
||||
fi
|
||||
|
||||
if [ $in_slave != "null" ]; then
|
||||
last_uid_slave=$($CMD_SLAVE $LAST_UID)
|
||||
if [ -z "$last_uid_slave" ]; then
|
||||
echo "error while fetching uid in slave";
|
||||
return 1
|
||||
fi
|
||||
|
||||
if [ $last_uid_master -ge $last_uid_slave ]; then
|
||||
max_uid=$(($last_uid_master + 1))
|
||||
else
|
||||
max_uid=$(($last_uid_slave + 1))
|
||||
fi
|
||||
|
||||
if [ $max_uid -lt $MIN_UID ]; then
|
||||
uid=$MIN_UID
|
||||
else
|
||||
uid=$max_uid
|
||||
fi
|
||||
else
|
||||
uid=$(($last_uid_master + 1))
|
||||
fi
|
||||
|
||||
echo "UID libre: $uid"
|
||||
|
||||
# options mysql
|
||||
opts_mysql='';
|
||||
[ -n "$in_dbname" ] && opts_mysql="-m $in_dbname -P '$in_dbpasswd'"
|
||||
|
||||
# Creation web account on Master
|
||||
|
||||
echo "MASTER: $CMD_MASTER $WEBADD add -p '$in_passwd' $opts_mysql -l $in_mail -y -u $uid -g $uid -U $(($uid + 1)) $in_login $in_wwwdomain"
|
||||
|
||||
$CMD_MASTER $WEBADD add -p \'$in_passwd\' $opts_mysql -l $in_mail -y -u $uid -g $uid -U $(($uid + 1)) $in_login $in_wwwdomain || (in_error "creation du compte master sur $in_master: $?" && exit 1)
|
||||
|
||||
# Creation web account on Slave
|
||||
|
||||
if [ $in_slave != "null" ]; then
|
||||
|
||||
if [ "$in_replmode" != "realtime" ]; then
|
||||
|
||||
echo "SLAVE: $CMD_SLAVE $WEBADD add -p '$in_passwd' $opts_mysql -l $in_mail -y -u $uid -g $uid -U $(($uid + 1)) $in_login $in_wwwdomain"
|
||||
$CMD_SLAVE $WEBADD add -p \'$in_passwd\' $opts_mysql -l $in_mail -y -u $uid -g $uid -U $(($uid + 1)) $in_login $in_wwwdomain || (in_error "creation du compte slave sur $in_slave: $?" && exit 1)
|
||||
|
||||
else
|
||||
|
||||
echo "SLAVE: $CMD_SLAVE $WEBADD add -p '$in_passwd' -l $in_mail -y -u $uid -g $uid -U $(($uid + 1)) $in_login $in_wwwdomain"
|
||||
$CMD_SLAVE $WEBADD add -p \'$in_passwd\' -l $in_mail -y -u $uid -g $uid -U $(($uid + 1)) $in_login $in_wwwdomain || (in_error "creation du compte slave sur $in_slave: $?" && exit 1)
|
||||
|
||||
fi
|
||||
fi
|
||||
|
||||
# Les operation suivantes sont faites uniquement si une replication doit
|
||||
# etre mise en place.
|
||||
|
||||
if [ $in_slave != "null" ]; then
|
||||
|
||||
# Creation des fichiers state
|
||||
|
||||
$CMD_MASTER "echo -e \"STATE=master\nIP=$in_slave\" >> ~$in_login/state"
|
||||
$CMD_SLAVE "echo -e \"STATE=slave\nIP=$in_master\" >> ~$in_login/state"
|
||||
|
||||
# Create id_dsa.pub on master
|
||||
|
||||
$CMD_MASTER << ENDSSH
|
||||
mkdir -p ~$in_login/.ssh
|
||||
chown $in_login:$in_login ~$in_login/.ssh
|
||||
chmod 700 ~$in_login/.ssh
|
||||
su $in_login -c "ssh-keygen -t dsa -f ~$in_login/.ssh/id_dsa <<<\"\" "
|
||||
ENDSSH
|
||||
|
||||
# push id_dsa.pub to authorized_keys of slave
|
||||
|
||||
master_key=$($CMD_MASTER "cat /home/$in_login/.ssh/id_dsa.pub")
|
||||
|
||||
$CMD_SLAVE << ENDSSH
|
||||
mkdir -p ~$in_login/.ssh
|
||||
chown $in_login:$in_login ~$in_login/.ssh
|
||||
chmod 700 ~$in_login/.ssh
|
||||
su $in_login -c "echo $master_key >> ~$in_login/.ssh/authorized_keys"
|
||||
ENDSSH
|
||||
|
||||
# create known_hosts
|
||||
|
||||
$CMD_MASTER << ENDSSH
|
||||
/usr/bin/ssh-keyscan $in_slave > /home/$in_login/.ssh/known_hosts
|
||||
chown $in_login:$in_login /home/$in_login/.ssh/known_hosts
|
||||
ENDSSH
|
||||
|
||||
$CMD_SLAVE << ENDSSH
|
||||
/usr/bin/ssh-keyscan $in_master > /home/$in_login/.ssh/known_hosts
|
||||
chown $in_login:$in_login /home/$in_login/.ssh/known_hosts
|
||||
ENDSSH
|
||||
|
||||
echo "--------------------------------------------------------------------"
|
||||
|
||||
# Mise en place de la methode de replication choisie
|
||||
if [ $in_replmode = "realtime" ]; then
|
||||
|
||||
# demon lsyncd
|
||||
$CMD_MASTER <<ENDSSH
|
||||
(crontab -lu $in_login 2>/dev/null; echo "@reboot lsyncd ~$in_login/www $in_slave:www") |crontab -u $in_login -
|
||||
sudo -u $in_login lsyncd ~$in_login/www $in_slave:www
|
||||
ENDSSH
|
||||
# Pour les mails
|
||||
# La réplication se fait au niveau du domaine (réplication de tout
|
||||
# /home/vmail/example.com/).
|
||||
domain=$(remove_subdomain $wwwdomain)
|
||||
$CMD_MASTER <<ENDSSH
|
||||
if [ ! -d ~$VMAIL_USER/$domain ]; then
|
||||
mkdir ~$VMAIL_USER/$domain
|
||||
chown $VMAIL_USER:$VMAIL_USER ~$VMAIL_USER/$domain
|
||||
(crontab -lu $VMAIL_USER 2>/dev/null; echo '@reboot /opt/evocluster/get-domains.sh $in_login |while read domain; do lsyncd ~$VMAIL_USER/\$domain $VMAIL_USER@$in_slave:\$domain; done'; echo '* * * * * /opt/evocluster/get-domains.sh $in_login |while read domain; do ldapsearch >~/\$domain/dump.sql; done') |crontab -u $VMAIL_USER -
|
||||
sudo -u $VMAIL_USER /opt/evocluster/get-domains.sh $in_login |while read domain; do lsyncd ~$VMAIL_USER/\$domain $VMAIL_USER@$in_slave:\$domain; done
|
||||
fi
|
||||
ENDSSH
|
||||
$CMD_SLAVE <<ENDSSH
|
||||
[ -d ~$VMAIL_USER/$domain ] || mkdir ~$VMAIL_USER/$domain && chown $VMAIL_USER:$VMAIL_USER ~$VMAIL_USER/$domain
|
||||
ENDSSH
|
||||
|
||||
# replication MySQL
|
||||
# On eteint le slave en attendant qu'un evoman ajoute la db dans le
|
||||
# replicate-to-db et redemarre MySQL sur le slave. Comme ceci, il n'y a
|
||||
# pas besoin de faire un dump de la nouvelle base, lors du start slave
|
||||
# les donnees seront copiees.
|
||||
$CMD_SLAVE mysqladmin stop-slave
|
||||
mail -s "[TAF][Quai13] Replication MySQL pour $in_login" $CONTACT_MAIL <<ENDMAIL
|
||||
Le compte $in_login a été crée sur $in_master (master) et $in_slave
|
||||
(slave).
|
||||
Pour terminer sa mise en place, il faut :
|
||||
- sur le slave, ajouter la base de données $in_dbname à la directive
|
||||
replicate-do-db dans la conf de MySQL ;
|
||||
- redémarrer MySQL sur le slave, et s'assurer que la réplication est
|
||||
ok (SHOW SLAVE STATUS et test d'écriture sur le master).
|
||||
|
||||
--
|
||||
Evocluster
|
||||
ENDMAIL
|
||||
# crontab
|
||||
$CMD_MASTER <<ENDSSH
|
||||
(crontab -lu $in_login; echo " */5 * * * * crontab -l |ssh $in_slave \"cat >crontab\"") |crontab -u $in_login -
|
||||
ENDSSH
|
||||
|
||||
elif [ $in_replmode = "deferred" ]; then
|
||||
|
||||
domain=$(remove_subdomain $wwwdomain)
|
||||
|
||||
if [ $in_replunit = "min" ]; then
|
||||
cron_line="*/$in_replinterval * * * * /opt/evocluster/sync-master-to-slave.sh"
|
||||
cron_line2="*/$in_replinterval * * * * /opt/evocluster/get-domains.sh $in_login |while read domain; do /opt/evocluster/sync-master-to-slave_mail.sh \$domain $in_login; done"
|
||||
elif [ $in_replunit = "hour" ]; then
|
||||
minute=$(($RANDOM % 60))
|
||||
offset=5
|
||||
cron_line="$minute */$in_replinterval * * * /opt/evocluster/sync-master-to-slave.sh"
|
||||
cron_line2="$(($minute+$offset)) */$in_replinterval * * * /opt/evocluster/get-domains.sh $in_login |while read domain; do /opt/evocluster/sync-master-to-slave_mail.sh \$domain $in_login; done"
|
||||
fi
|
||||
$CMD_MASTER "(crontab -lu $in_login; echo \"$cron_line\") |crontab -u $in_login -"
|
||||
$CMD_MASTER "(crontab -lu $VMAIL_USER; echo '$cron_line2') |crontab -u $VMAIL_USER -"
|
||||
fi
|
||||
|
||||
# log
|
||||
|
||||
DATE=$(date +"%Y-%m-%d")
|
||||
echo "$DATE [web-add-cluster.sh] $in_login added on $in_master and $in_slave" >> /var/log/evolix.log
|
||||
else
|
||||
DATE=$(date +"%Y-%m-%d")
|
||||
echo "$DATE [web-add-cluster.sh] $in_login added on $in_master" >> /var/log/evolix.log
|
||||
fi
|
||||
}
|
||||
|
||||
op_del() {
|
||||
if [ $# -lt 3 ]; then
|
||||
usage
|
||||
exit 1
|
||||
else
|
||||
login=$1
|
||||
master=$2
|
||||
slave=$3
|
||||
if [ $# -eq 4 ]; then
|
||||
dbname=$4
|
||||
fi
|
||||
|
||||
fi
|
||||
|
||||
if [ $slave != "null" ]; then
|
||||
echo "Deleting account $login on $master and $slave. Continue ?"
|
||||
else
|
||||
echo "Deleting account $login on $master. Continue ?"
|
||||
fi
|
||||
read
|
||||
|
||||
CMD_MASTER="$SSH $SSH_USER@$master"
|
||||
CMD_SLAVE="$SSH $SSH_USER@$slave"
|
||||
|
||||
# check account exist on master and slave
|
||||
if [ -z "$($CMD_MASTER cut -d: -f1 /etc/passwd| grep ^$login$)" ]; then
|
||||
error "Account $login doesn't exist on $master";
|
||||
exit 1;
|
||||
fi
|
||||
|
||||
if [ $slave != "null" ]; then
|
||||
if [ -z "$($CMD_SLAVE cut -d: -f1 /etc/passwd| grep ^$login$)" ]; then
|
||||
error "Account $login doesn't exist on $slave";
|
||||
exit 1;
|
||||
fi
|
||||
fi
|
||||
|
||||
yes | $CMD_MASTER $WEBADD del $login $dbname
|
||||
if [ $slave != "null" ]; then
|
||||
yes | $CMD_SLAVE $WEBADD del $login $dbname
|
||||
fi
|
||||
|
||||
DATE=$(date +"%Y-%m-%d")
|
||||
if [ $slave != "null" ]; then
|
||||
echo "$DATE [web-add-cluster.sh] $login deleted from $master and $slave" >> /var/log/evolix.log
|
||||
else
|
||||
echo "$DATE [web-add-cluster.sh] $login deleted from $master" >> /var/log/evolix.log
|
||||
fi
|
||||
}
|
||||
|
||||
op_aliasadd() {
|
||||
if [ $# -lt 3 ]; then
|
||||
usage
|
||||
exit 1
|
||||
fi
|
||||
|
||||
vhost=$1
|
||||
alias=$2
|
||||
master=$3
|
||||
slave=$4
|
||||
|
||||
CMD_MASTER="$SSH $SSH_USER@$master"
|
||||
CMD_SLAVE="$SSH $SSH_USER@$slave"
|
||||
|
||||
$CMD_MASTER $WEBADD add-alias $vhost $alias
|
||||
|
||||
if [ $slave != "null" ]; then
|
||||
$CMD_SLAVE $WEBADD add-alias $vhost $alias
|
||||
fi
|
||||
|
||||
DATE=$(date +"%Y-%m-%d")
|
||||
if [ $slave != "null" ]; then
|
||||
echo "$DATE [web-add-cluster.sh] $alias added to $vhost on $master and $slave" >> /var/log/evolix.log
|
||||
else
|
||||
echo "$DATE [web-add-cluster.sh] $login added to $vhost on $master" >> /var/log/evolix.log
|
||||
fi
|
||||
}
|
||||
|
||||
op_aliasdel() {
|
||||
if [ $# -lt 3 ]; then
|
||||
usage
|
||||
exit 1
|
||||
fi
|
||||
|
||||
vhost=$1
|
||||
alias=$2
|
||||
master=$3
|
||||
slave=$4
|
||||
|
||||
CMD_MASTER="$SSH $SSH_USER@$master"
|
||||
CMD_SLAVE="$SSH $SSH_USER@$slave"
|
||||
|
||||
$CMD_MASTER $WEBADD del-alias $vhost $alias
|
||||
|
||||
if [ $slave != "null" ]; then
|
||||
$CMD_SLAVE $WEBADD del-alias $vhost $alias
|
||||
fi
|
||||
|
||||
DATE=$(date +"%Y-%m-%d")
|
||||
if [ $slave != "null" ]; then
|
||||
echo "$DATE [web-add-cluster.sh] $alias deleted from $vhost on $master and $slave" >> /var/log/evolix.log
|
||||
else
|
||||
echo "$DATE [web-add-cluster.sh] $login deleted from $vhost on $master" >> /var/log/evolix.log
|
||||
fi
|
||||
}
|
||||
|
||||
|
||||
|
||||
arg_processing() {
|
||||
|
||||
# Détermination de la commande
|
||||
|
||||
if [ $# -lt 1 ]; then
|
||||
usage
|
||||
else
|
||||
commandname=$1
|
||||
shift
|
||||
|
||||
case "$commandname" in
|
||||
add)
|
||||
op_add $*
|
||||
;;
|
||||
del)
|
||||
op_del $*
|
||||
;;
|
||||
list-vhost)
|
||||
op_listvhost $*
|
||||
;;
|
||||
add-alias)
|
||||
op_aliasadd $*
|
||||
;;
|
||||
del-alias)
|
||||
op_aliasdel $*
|
||||
;;
|
||||
*)
|
||||
usage
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
}
|
||||
|
||||
op_listvhost() {
|
||||
if [ $# -eq 1 ]; then
|
||||
configlist="$VHOST_PATH/$1";
|
||||
else
|
||||
configlist="$VHOST_PATH/*";
|
||||
fi
|
||||
|
||||
|
||||
for configfile in $configlist; do
|
||||
if [ -r "$configfile" ]; then
|
||||
servername=`awk '/^[[:space:]]*ServerName (.*)/ { print $2 }' $configfile | head -n 1`
|
||||
serveraliases=`perl -ne 'print $1 if /^[[:space:]]*ServerAlias (.*)/' $configfile | head -n 1`
|
||||
serveraliases=`echo $serveraliases | sed 's/ \+/, /g'`
|
||||
userid=`awk '/^[[:space:]]*AssignUserID.*/ { print $3 }' $configfile | head -n 1`
|
||||
if [ "$servername" ] && [ "$userid" ]; then
|
||||
configid=`basename $configfile`
|
||||
echo "$userid:$configid:$servername:$serveraliases"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
op_add() {
|
||||
while getopts hyp:m:P:s:l:f:c: opt; do
|
||||
case "$opt" in
|
||||
p)
|
||||
in_passwd=$OPTARG
|
||||
;;
|
||||
m)
|
||||
in_dbname=$OPTARG
|
||||
;;
|
||||
P)
|
||||
in_dbpasswd=$OPTARG
|
||||
;;
|
||||
l)
|
||||
in_mail=$OPTARG
|
||||
;;
|
||||
f)
|
||||
in_replinterval=$OPTARG
|
||||
;;
|
||||
c)
|
||||
in_replunit=$OPTARG
|
||||
;;
|
||||
h)
|
||||
usage
|
||||
exit 1
|
||||
;;
|
||||
?)
|
||||
usage
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
shift $(($OPTIND - 1))
|
||||
if [ $# -ne 5 ]; then
|
||||
usage
|
||||
exit 1
|
||||
fi
|
||||
|
||||
in_login=$1
|
||||
in_wwwdomain=$2
|
||||
in_master=$3
|
||||
in_slave=$4
|
||||
in_replmode=$5
|
||||
|
||||
# in_master doit etre different d'in_slave
|
||||
[ "$in_master" = "$in_slave" ] && in_slave="null";
|
||||
|
||||
validate_login $in_login || exit 1
|
||||
[ -z "$in_passwd" ] && in_passwd=`gen_random_passwd`
|
||||
validate_passwd $in_passwd || exit 1
|
||||
|
||||
if [ -n "$in_dbname" ]; then
|
||||
validate_dbname $in_dbname || exit 1
|
||||
if [ -z "$in_dbpasswd" ]; then
|
||||
in_dbpasswd=`gen_random_passwd`
|
||||
validate_passwd $in_dbpasswd || exit 1
|
||||
echo "validate mysql passwd $in_dbpasswd";
|
||||
fi
|
||||
echo " ? validate mysql passwd $in_dbpasswd";
|
||||
fi
|
||||
|
||||
validate_wwwdomain $in_wwwdomain || exit 1
|
||||
[ -z "$in_mail" ] && in_mail=$CONTACT_MAIL
|
||||
validate_mail $in_mail || exit 1
|
||||
validate_replmode $in_replmode || exit 1
|
||||
if [ $in_replmode = "deferred" ]; then
|
||||
validate_replinterval $in_replinterval $in_replunit || exit 1
|
||||
fi
|
||||
|
||||
echo
|
||||
echo "----------------------------------------------"
|
||||
echo "Nom du compte : $in_login"
|
||||
echo "Mot de passe : $in_passwd"
|
||||
if [ -n "$in_dbname" ]; then
|
||||
echo "Base de données MySQL : $in_dbname"
|
||||
echo "Mot de passe MySQL : $in_dbpasswd"
|
||||
fi
|
||||
echo "Nom de domaine : $in_wwwdomain"
|
||||
echo "IP compte master : $in_master"
|
||||
echo "IP compte slave : $in_slave"
|
||||
echo "Mode de replication : $in_replmode"
|
||||
echo "Envoi du mail récapitulatif à : $in_mail"
|
||||
echo "----------------------------------------------"
|
||||
echo
|
||||
|
||||
create_www_accounts
|
||||
echo
|
||||
echo " => Compte $in_login créé avec succès"
|
||||
echo
|
||||
}
|
||||
|
||||
remove_subdomain() {
|
||||
#return $(echo $1 |sed 's/\([^\.]\+\.[^\.]\+\)$/\1/')
|
||||
echo $1 |perl -ne 'print $1 if ( /([^\.]+\.[^\.]+)$/ )'
|
||||
}
|
||||
|
||||
# Point d'entrée
|
||||
arg_processing $*
|
||||
|
|
@ -0,0 +1,643 @@
|
|||
#!/bin/bash
|
||||
|
||||
#
|
||||
# Gestion des comptes web et des hôtes virtuels Apache
|
||||
#
|
||||
# Copyright (c) 2009 Evolix - Tous droits reserves
|
||||
# $Id$
|
||||
#
|
||||
|
||||
# TODO
|
||||
# - Gestion des quota
|
||||
# - Possibilité de créer un compte FTP-only
|
||||
# - Pouvoir spécifier le CONTACT_MAIL dans un fichier de conf
|
||||
# - Traduire usage() en francais, ou l'inverse ??
|
||||
|
||||
set -e
|
||||
|
||||
HOME="/root"
|
||||
CONTACT_MAIL=""
|
||||
WWWBOUNCE_MAIL=""
|
||||
LOCAL_SCRIPT="/usr/share/scripts/web-add.local.sh"
|
||||
PRE_LOCAL_SCRIPT="/usr/share/scripts/web-add.pre-local.sh"
|
||||
TPL_VHOST="/usr/share/scripts/vhost"
|
||||
TPL_AWSTATS="/usr/share/scripts/awstats.XXX.conf"
|
||||
TPL_MAIL="/usr/share/scripts/web-mail.tpl"
|
||||
VHOST_PATH="/etc/apache2/sites-enabled/"
|
||||
MAX_LOGIN_CHAR=16
|
||||
HOME_DIR="/home"
|
||||
MYSQL_CREATE_DB_OPTS=""
|
||||
|
||||
# Utiliser ce fichier pour redefinir la valeur des variables ci-dessus
|
||||
config_file="/etc/evolix/web-add.conf"
|
||||
[ -r $config_file ] && . $config_file
|
||||
|
||||
usage() {
|
||||
cat <<EOT >&2
|
||||
|
||||
Usage: $0 COMMAND [ARG]
|
||||
|
||||
add [ [OPTIONS] LOGIN WWWDOMAIN ]
|
||||
|
||||
Create web account LOGIN.
|
||||
No arguments starts interactive mode.
|
||||
|
||||
-p PASSWD
|
||||
FTP and SFTP password (default : random)
|
||||
|
||||
-m DBNAME
|
||||
Name of MySQL database (default : same as account)
|
||||
|
||||
-P DBPASSWD
|
||||
MySQL password (default : random)
|
||||
|
||||
-l MAIL
|
||||
Send summary email to MAIL
|
||||
|
||||
-k SSHKEY
|
||||
Use this SSH key
|
||||
|
||||
-u UID
|
||||
Force account UID (only in command line)
|
||||
|
||||
-g GID
|
||||
Force account GID (only in command line)
|
||||
|
||||
-U UID
|
||||
Force www-account UID (only in command line)
|
||||
|
||||
-y
|
||||
Don't ask for confirmation
|
||||
|
||||
Example : web-add.sh add -m testdb testlogin testdomain.com
|
||||
|
||||
del LOGIN [DBNAME]
|
||||
|
||||
Delete account and all files related (Apache, Awstats, etc)
|
||||
Archive home directory.
|
||||
Remove MySQL database only if DBNAME is specified.
|
||||
|
||||
list-vhost LOGIN
|
||||
|
||||
List Apache vhost for user LOGIN
|
||||
|
||||
add-alias VHOST ALIAS
|
||||
|
||||
Add a ServerAlias to an Apache vhost
|
||||
|
||||
del-alias VHOST ALIAS
|
||||
|
||||
Del a ServerAlias from an Apache vhost
|
||||
|
||||
EOT
|
||||
}
|
||||
|
||||
#
|
||||
# Affiche un message d'erreur de validation
|
||||
#
|
||||
in_error() {
|
||||
msg=$1
|
||||
cat >&2 <<EOT
|
||||
***
|
||||
Erreur : $msg
|
||||
***
|
||||
EOT
|
||||
}
|
||||
|
||||
gen_random_passwd() {
|
||||
apg -c /dev/urandom -n1 -E oOlL10\&\\\/\"\'
|
||||
}
|
||||
|
||||
validate_login() {
|
||||
login=$1
|
||||
|
||||
length=${#login}
|
||||
|
||||
if [ $length -lt 3 ]; then
|
||||
in_error "Le login doit contenir plus de 2 caracteres"
|
||||
return 1
|
||||
fi
|
||||
|
||||
if [ $length -gt $MAX_LOGIN_CHAR ]; then
|
||||
in_error "Le login ne doit pas contenir plus de $MAX_LOGIN_CHAR caracteres"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
validate_passwd() {
|
||||
passwd=$1
|
||||
length=${#passwd}
|
||||
|
||||
if [ $length -lt 6 ] && [ $length -gt 0 ]; then
|
||||
in_error "Le mot de passe doit avoir au moins 6 caracteres"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
validate_dbname() {
|
||||
dbname=$1
|
||||
if mysql -ss -e "show databases" | grep "^$dbname$" >/dev/null; then
|
||||
in_error "Base de données déjà existante"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
validate_wwwdomain() {
|
||||
wwwdomain=$1
|
||||
if [ -z "$wwwdomain" ]; then
|
||||
in_error "Le nom de domaine est obligatoire"
|
||||
return 1
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
validate_mail() {
|
||||
return 0
|
||||
}
|
||||
|
||||
step_ok() {
|
||||
msg=$1
|
||||
echo "[OK] $msg"
|
||||
}
|
||||
|
||||
create_www_account() {
|
||||
|
||||
# Vérifications
|
||||
for filetocheck in $TPL_VHOST $TPL_AWSTATS $TPL_MAIL; do
|
||||
if [ ! -f $filetocheck ]; then
|
||||
in_error "Fichier inexistant : $filetocheck"
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
############################################################################
|
||||
|
||||
if [ -f $PRE_LOCAL_SCRIPT ]; then
|
||||
source $PRE_LOCAL_SCRIPT
|
||||
fi
|
||||
|
||||
step_ok "Exécution du pre-script spécifique"
|
||||
|
||||
############################################################################
|
||||
|
||||
if [ -z "$HOME_DIR_USER" ]; then
|
||||
HOME_DIR_USER="$HOME_DIR/$in_login"
|
||||
fi
|
||||
|
||||
############################################################################
|
||||
|
||||
if [ -d "$HOME_DIR_USER" ]; then
|
||||
in_error "Ce compte existe deja (ou il a mal été effacé)"
|
||||
return 1
|
||||
fi
|
||||
|
||||
############################################################################
|
||||
|
||||
# Force UID GID if specified
|
||||
|
||||
[ -n "$in_uid" ] && OPT_UID="--uid" && OPT_UID_ARG="$in_uid"
|
||||
[ -n "$in_gid" ] && OPT_GID="--gid" && OPT_GID_ARG="$in_gid"
|
||||
[ -n "$in_wwwuid" ] && OPT_WWWUID="--uid" && OPT_WWWUID_ARG="$in_wwwuid"
|
||||
|
||||
############################################################################
|
||||
|
||||
|
||||
/usr/sbin/adduser --gecos "User $in_login" --disabled-password "$in_login" --shell /bin/bash $OPT_UID $OPT_UID_ARG --force-badname --home "$HOME_DIR_USER" >/dev/null
|
||||
[ -z "$in_sshkey" ] && echo "$in_login:$in_passwd" | chpasswd --md5
|
||||
[ -z "$in_sshkey" ] || [ -n "$HOME_DIR_USER" ] && mkdir "$HOME_DIR_USER/.ssh" && echo "$in_sshkey" > "$HOME_DIR_USER/.ssh/authorized_keys" \
|
||||
&& chmod -R u=rwX,g=,o= "$HOME_DIR_USER/.ssh/authorized_keys" && chown -R "$in_login":"$in_login" "$HOME_DIR_USER/.ssh"
|
||||
|
||||
/usr/sbin/adduser --disabled-password --home $HOME_DIR_USER/www \
|
||||
--no-create-home --shell /bin/false --gecos "WWW $in_login" www-$in_login $OPT_WWWUID $OPT_WWWUID_ARG --ingroup $in_login --force-badname >/dev/null
|
||||
|
||||
sed -i "s/^AllowUsers .*/& $in_login/" /etc/ssh/sshd_config
|
||||
/etc/init.d/ssh reload
|
||||
|
||||
step_ok "Création des utilisateurs"
|
||||
|
||||
############################################################################
|
||||
|
||||
echo "www-$login: $login" >> /etc/aliases
|
||||
echo "$login: $WWWBOUNCE_MAIL" >> /etc/aliases
|
||||
newaliases
|
||||
|
||||
step_ok "Alias mail"
|
||||
|
||||
############################################################################
|
||||
|
||||
chmod 750 $HOME_DIR_USER/
|
||||
|
||||
# Répertoires par défaut
|
||||
mkdir -p $HOME_DIR_USER/{log,www,awstats}
|
||||
chown $in_login:$in_login $HOME_DIR_USER/www
|
||||
chgrp $in_login $HOME_DIR_USER/{log,awstats}
|
||||
chmod 750 $HOME_DIR_USER/{log,www,awstats}
|
||||
|
||||
# Ajout des logs par defaut
|
||||
touch $HOME_DIR_USER/log/access.log
|
||||
touch $HOME_DIR_USER/log/error.log
|
||||
touch $HOME_DIR_USER/log/php.log
|
||||
chgrp $in_login $HOME_DIR_USER/log/access.log
|
||||
chgrp $in_login $HOME_DIR_USER/log/error.log
|
||||
chown www-$in_login:$in_login $HOME_DIR_USER/log/php.log
|
||||
chmod 640 $HOME_DIR_USER/log/access.log
|
||||
chmod 640 $HOME_DIR_USER/log/error.log
|
||||
chmod 640 $HOME_DIR_USER/log/php.log
|
||||
|
||||
step_ok "Création du répertoire personnel"
|
||||
|
||||
############################################################################
|
||||
|
||||
random=$RANDOM
|
||||
vhostfile="/etc/apache2/sites-available/$in_login"
|
||||
|
||||
cat $TPL_VHOST | \
|
||||
sed -e "s/XXX/$in_login/g ; s/SERVERNAME/$in_wwwdomain/ ; s/RANDOM/$random/ ; s#HOME_DIR#$HOME_DIR#" >$vhostfile
|
||||
|
||||
# On active aussi example.com si domaine commence par "www." comme www.example
|
||||
if echo $in_wwwdomain | grep '^www.' > /dev/null; then
|
||||
subweb=`echo $in_wwwdomain | sed -e "s/www.//"`
|
||||
sed -i -e "s/^\(.*\)#\(ServerAlias\).*$/\1\2 $subweb/" $vhostfile
|
||||
fi
|
||||
|
||||
a2ensite $in_login >/dev/null
|
||||
|
||||
step_ok "Configuration d'Apache"
|
||||
|
||||
############################################################################
|
||||
|
||||
cat $TPL_AWSTATS | \
|
||||
sed -e "s/XXX/$in_login/ ; s/SERVERNAME/$in_wwwdomain/ ; s#HOME_DIR#$HOME_DIR#" \
|
||||
> /etc/awstats/awstats.$in_login.conf
|
||||
chmod 644 /etc/awstats/awstats.$in_login.conf
|
||||
|
||||
VAR=`grep -v "^#" /etc/cron.d/awstats |tail -1 | cut -d " " -f1`
|
||||
if [ "$VAR" = "" ] || [ $VAR -ge 59 ]; then
|
||||
VAR=1
|
||||
else
|
||||
VAR=$(($VAR +1))
|
||||
fi
|
||||
|
||||
echo "$VAR * * * * root umask 033; [ -x /usr/lib/cgi-bin/awstats.pl -a -f /etc/awstats/awstats.$in_login.conf -a -r $HOME_DIR_USER/log/access.log ] && /usr/lib/cgi-bin/awstats.pl -config=$in_login -update >/dev/null" >> /etc/cron.d/awstats
|
||||
|
||||
step_ok "Activation d'Awstats"
|
||||
|
||||
############################################################################
|
||||
|
||||
if [ "$in_dbname" ]; then
|
||||
echo "CREATE DATABASE \`$in_dbname\` $MYSQL_CREATE_DB_OPTS;" | mysql
|
||||
echo "GRANT ALL PRIVILEGES ON \`$in_dbname\`.* TO \`$in_login\`@localhost IDENTIFIED BY '$in_dbpasswd';" | mysql
|
||||
echo "FLUSH PRIVILEGES;" | mysql
|
||||
|
||||
my_cnf_file="$HOME_DIR_USER/.my.cnf"
|
||||
cat >$my_cnf_file <<-EOT
|
||||
[client]
|
||||
user = $in_login
|
||||
password = "$in_dbpasswd"
|
||||
|
||||
[mysql]
|
||||
database = $in_dbname
|
||||
EOT
|
||||
chown $in_login $my_cnf_file
|
||||
chmod 600 $my_cnf_file
|
||||
|
||||
step_ok "Création base de données et compte MySQL"
|
||||
fi
|
||||
|
||||
############################################################################
|
||||
|
||||
cat $TPL_MAIL | \
|
||||
sed -e "s/LOGIN/$in_login/g ; s/SERVERNAME/$in_wwwdomain/ ; s/PASSE1/$in_passwd/ ; s/PASSE2/$in_dbpasswd/ ; s/RANDOM/$random/ ; s/QUOTA/$quota/ ; s/RCPTTO/$in_mail/ ; s/DBNAME/$in_dbname/ ; s#HOME_DIR#$HOME_DIR#"| \
|
||||
/usr/lib/sendmail -oi -t -f "$CONTACT_MAIL"
|
||||
|
||||
step_ok "Envoi du mail récapitulatif"
|
||||
|
||||
############################################################################
|
||||
|
||||
if [ -f $LOCAL_SCRIPT ]; then
|
||||
source $LOCAL_SCRIPT
|
||||
fi
|
||||
|
||||
step_ok "Exécution du script spécifique"
|
||||
|
||||
############################################################################
|
||||
|
||||
apache2ctl configtest 2>/dev/null
|
||||
/etc/init.d/apache2 force-reload >/dev/null
|
||||
|
||||
step_ok "Rechargement d'Apache"
|
||||
|
||||
############################################################################
|
||||
|
||||
DATE=$(date +"%Y-%m-%d")
|
||||
echo "$DATE [web-add.sh] Ajout $in_login" >> /var/log/evolix.log
|
||||
}
|
||||
|
||||
op_del() {
|
||||
if [ $# -lt 1 ]; then
|
||||
usage
|
||||
exit 1
|
||||
else
|
||||
login=$1
|
||||
if [ $# -eq 2 ]; then
|
||||
dbname=$2
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "Deleting account $login. Continue ?"
|
||||
read
|
||||
|
||||
set -x
|
||||
userdel $login
|
||||
userdel www-$login
|
||||
sed -i.bak "/^$login:/d" /etc/aliases
|
||||
sed -i.bak "/^www-$login:/d" /etc/aliases
|
||||
|
||||
sed -i "s/^\(AllowUsers .*\)$login/\1/" /etc/ssh/sshd_config
|
||||
/etc/init.d/ssh reload
|
||||
|
||||
if [ -d "$HOME_DIR/$login" ]; then
|
||||
mv -i $HOME_DIR/$login $HOME_DIR/$login.`date '+%Y%m%d-%H%M%S'`.bak
|
||||
else
|
||||
echo "warning : $HOME_DIR/$login does not exist"
|
||||
fi
|
||||
|
||||
a2dissite $login
|
||||
rm /etc/apache2/sites-available/$login
|
||||
rm /etc/awstats/awstats.$login.conf
|
||||
sed -i.bak "/-config=$login/d" /etc/cron.d/awstats
|
||||
apache2ctl configtest
|
||||
set +x
|
||||
|
||||
if [ -n "$dbname" ]; then
|
||||
echo "Deleting mysql DATABASE $dbname and mysql user $login. Continue ?"
|
||||
read
|
||||
|
||||
set -x
|
||||
echo "DROP DATABASE $dbname; delete from mysql.user where user='$login' ; FLUSH PRIVILEGES;" | mysql
|
||||
set +x
|
||||
fi
|
||||
}
|
||||
|
||||
arg_processing() {
|
||||
|
||||
# Détermination de la commande
|
||||
|
||||
if [ $# -lt 1 ]; then
|
||||
usage
|
||||
else
|
||||
commandname=$1
|
||||
shift
|
||||
|
||||
case "$commandname" in
|
||||
add)
|
||||
op_add $*
|
||||
;;
|
||||
del)
|
||||
op_del $*
|
||||
;;
|
||||
list-vhost)
|
||||
op_listvhost $*
|
||||
;;
|
||||
add-alias)
|
||||
op_aliasadd $*
|
||||
;;
|
||||
del-alias)
|
||||
op_aliasdel $*
|
||||
;;
|
||||
*)
|
||||
usage
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
}
|
||||
|
||||
op_listvhost() {
|
||||
if [ $# -eq 1 ]; then
|
||||
configlist="$VHOST_PATH/$1";
|
||||
else
|
||||
configlist="$VHOST_PATH/*";
|
||||
fi
|
||||
|
||||
|
||||
for configfile in $configlist; do
|
||||
if [ -r "$configfile" ]; then
|
||||
servername=`awk '/^[[:space:]]*ServerName (.*)/ { print $2 }' $configfile | head -n 1`
|
||||
serveraliases=`perl -ne 'print $1 if /^[[:space:]]*ServerAlias (.*)/' $configfile | head -n 1`
|
||||
serveraliases=`echo $serveraliases | sed 's/ \+/, /g'`
|
||||
userid=`awk '/^[[:space:]]*AssignUserID.*/ { print $3 }' $configfile | head -n 1`
|
||||
if [ "$servername" ] && [ "$userid" ]; then
|
||||
configid=`basename $configfile`
|
||||
echo "$userid:$configid:$servername:$serveraliases"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
op_aliasadd() {
|
||||
if [ $# -eq 2 ]; then
|
||||
vhost=$1
|
||||
alias=$2
|
||||
|
||||
[ -f $VHOST_PATH/$vhost ] && sed -i -e "s/\(ServerName .*\)/\1\n\tServerAlias $alias/" $VHOST_PATH/$vhost
|
||||
|
||||
apache2ctl configtest 2>/dev/null
|
||||
/etc/init.d/apache2 force-reload >/dev/null
|
||||
|
||||
else usage
|
||||
fi
|
||||
}
|
||||
|
||||
op_aliasdel() {
|
||||
if [ $# -eq 2 ]; then
|
||||
vhost=$1
|
||||
alias=$2
|
||||
|
||||
[ -f $VHOST_PATH/$vhost ] && sed -i -e "/ServerAlias $alias/d" $VHOST_PATH/$vhost
|
||||
|
||||
apache2ctl configtest 2>/dev/null
|
||||
/etc/init.d/apache2 force-reload >/dev/null
|
||||
|
||||
else usage
|
||||
fi
|
||||
}
|
||||
|
||||
op_add() {
|
||||
|
||||
#
|
||||
# Mode interactif
|
||||
#
|
||||
if [ $# -eq 0 ]; then
|
||||
echo
|
||||
echo "Ajout d'un compte WEB"
|
||||
echo
|
||||
|
||||
until [ "$in_login" ]; do
|
||||
echo -n "Entrez le login du nouveau compte : "
|
||||
read tmp
|
||||
if validate_login "$tmp"; then
|
||||
in_login="$tmp"
|
||||
fi
|
||||
done
|
||||
|
||||
until [ "$in_passwd" ]; do
|
||||
echo -n "Entrez le mot de passe FTP/SFTP/SSH (ou vide pour aleatoire) : "
|
||||
read -s tmp
|
||||
echo
|
||||
|
||||
if [ -z "$tmp" ]; then
|
||||
tmp=`gen_random_passwd`
|
||||
fi
|
||||
|
||||
if validate_passwd "$tmp"; then
|
||||
in_passwd="$tmp"
|
||||
fi
|
||||
done
|
||||
|
||||
echo -n "Voulez-vous aussi un compte/base MySQL ? [Y|n] "
|
||||
read confirm
|
||||
|
||||
if [ "$confirm" != "n" ] && [ "$confirm" != "N" ]; then
|
||||
until [ "$in_dbname" ]; do
|
||||
echo -n "Entrez le nom de la base de donnees ($in_login par defaut) : "
|
||||
read tmp
|
||||
|
||||
if [ -z "$tmp" ]; then
|
||||
tmp=$in_login
|
||||
fi
|
||||
|
||||
if validate_dbname "$tmp"; then
|
||||
in_dbname="$tmp"
|
||||
fi
|
||||
done
|
||||
|
||||
until [ "$in_dbpasswd" ]; do
|
||||
echo -n "Entrez le mot de passe MySQL (ou vide pour aleatoire) : "
|
||||
read -s tmp
|
||||
echo
|
||||
|
||||
if [ -z "$tmp" ]; then
|
||||
tmp=`gen_random_passwd`
|
||||
fi
|
||||
|
||||
if validate_passwd "$tmp"; then
|
||||
in_dbpasswd="$tmp"
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
until [ "$in_wwwdomain" ]; do
|
||||
echo -n "Entrez le nom de domaine web (ex: foo.example.com) : "
|
||||
read tmp
|
||||
if validate_wwwdomain "$tmp"; then
|
||||
in_wwwdomain="$tmp"
|
||||
fi
|
||||
done
|
||||
|
||||
until [ "$in_mail" ]; do
|
||||
echo -n "Entrez votre adresse mail pour recevoir le mail de creation ($CONTACT_MAIL par défaut) : "
|
||||
read tmp
|
||||
if [ -z "$tmp" ]; then
|
||||
tmp="$CONTACT_MAIL"
|
||||
fi
|
||||
if validate_mail "$tmp"; then
|
||||
in_mail="$tmp"
|
||||
fi
|
||||
done
|
||||
|
||||
#
|
||||
# Mode non interactif
|
||||
#
|
||||
else
|
||||
while getopts hyp:m:P:w:l:k:u:g:U: opt; do
|
||||
case "$opt" in
|
||||
p)
|
||||
in_passwd=$OPTARG
|
||||
;;
|
||||
m)
|
||||
in_dbname=$OPTARG
|
||||
;;
|
||||
P)
|
||||
in_dbpasswd=$OPTARG
|
||||
;;
|
||||
l)
|
||||
in_mail=$OPTARG
|
||||
;;
|
||||
k)
|
||||
in_sshkey=$OPTARG
|
||||
;;
|
||||
y)
|
||||
force_confirm=1
|
||||
;;
|
||||
u)
|
||||
in_uid=$OPTARG
|
||||
;;
|
||||
g)
|
||||
in_gid=$OPTARG
|
||||
;;
|
||||
U)
|
||||
in_wwwuid=$OPTARG
|
||||
;;
|
||||
h)
|
||||
usage
|
||||
exit 1
|
||||
;;
|
||||
?)
|
||||
usage
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
shift $(($OPTIND - 1))
|
||||
if [ $# -ne 2 ]; then
|
||||
usage
|
||||
exit 1
|
||||
else
|
||||
in_login=$1
|
||||
in_wwwdomain=$2
|
||||
validate_login $in_login || exit 1
|
||||
[ -z "$in_passwd" ] && [ -z "$in_sshkey" ] && in_passwd=`gen_random_passwd`
|
||||
[ -z "$in_sshkey" ] && ( validate_passwd $in_passwd || exit 1 )
|
||||
[ -n "$in_dbname" ] && ( validate_dbname $in_dbname || exit 1 )
|
||||
[ -z "$in_dbpasswd" ] && [ -n "$in_dbname" ] && in_dbpasswd=`gen_random_passwd`
|
||||
[ -n "$in_dbname" ] && ( validate_passwd $in_dbpasswd || exit 1 )
|
||||
validate_wwwdomain $in_wwwdomain || exit 1
|
||||
[ -z "$in_mail" ] && in_mail=$CONTACT_MAIL
|
||||
validate_mail $in_mail || exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
echo
|
||||
echo "----------------------------------------------"
|
||||
echo "Nom du compte : $in_login"
|
||||
echo "Mot de passe : $in_passwd"
|
||||
if [ "$in_dbname" ]; then
|
||||
echo "Base de données MySQL : $in_dbname"
|
||||
echo "Mot de passe MySQL : $in_dbpasswd"
|
||||
fi
|
||||
echo "Nom de domaine : $in_wwwdomain"
|
||||
echo "Envoi du mail récapitulatif à : $in_mail"
|
||||
echo "----------------------------------------------"
|
||||
echo
|
||||
|
||||
if [ -z "$force_confirm" ]; then
|
||||
echo -n "Confirmer la création ? [y/N] : "
|
||||
read tmp
|
||||
echo
|
||||
if [ "$tmp" != "y" ] && [ "$tmp" != "Y" ]; then
|
||||
echo "Annulation..."
|
||||
echo
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
create_www_account
|
||||
echo
|
||||
echo " => Compte $in_login créé avec succès"
|
||||
echo
|
||||
}
|
||||
|
||||
# Point d'entrée
|
||||
arg_processing $*
|
||||
|
|
@ -0,0 +1,86 @@
|
|||
From: %MAIL_FROM%
|
||||
To: RCPTTO
|
||||
Bcc: %MAIL_BCC%
|
||||
Subject: Parametres hebergement web : LOGIN
|
||||
|
||||
Bonjour,
|
||||
|
||||
Votre compte d'hebergement web a ete cree.
|
||||
|
||||
**********************************
|
||||
* CONNEXION SFTP/SSH
|
||||
**********************************
|
||||
|
||||
NOM DU SERVEUR : %SERVER_NAME%
|
||||
USER : LOGIN
|
||||
PASSWORD : PASSE1
|
||||
|
||||
*****************************************
|
||||
* Details sur l'environnement Apache/PHP
|
||||
*****************************************
|
||||
|
||||
URL du site :
|
||||
http://SERVERNAME
|
||||
|
||||
URL des stats :
|
||||
http://SERVERNAME/cgi-RANDOM/awstats.pl
|
||||
(acces par IP ou login a demander !)
|
||||
|
||||
Repertoire de connexion : HOME_DIR/LOGIN/
|
||||
Repertoire pour site web : HOME_DIR/LOGIN/www/
|
||||
|
||||
Apache/PHP tourne en www-LOGIN:LOGIN c'est-a-dire qu'il a acces
|
||||
uniquement *en lecture* aux differents fichiers/repertoires
|
||||
(a condition d'avoir 'g=rx' sur les repertoires et 'g=r' sur les
|
||||
fichiers ce qui est le comportement par defaut).
|
||||
|
||||
Lorsqu'on a besoin d'autoriser *l'ecriture* pour certains
|
||||
fichiers/repertoires, il suffit d'ajouter le droit 'g+w'.
|
||||
|
||||
***********************************
|
||||
* MySQL
|
||||
***********************************
|
||||
|
||||
SERVEUR : 127.0.0.1
|
||||
PORT DU SERVEUR : 3306
|
||||
USER : LOGIN
|
||||
PASSWORD : PASSE2
|
||||
NOM BASE : DBNAME
|
||||
URL interface d'admin :
|
||||
%PMA_URL%
|
||||
|
||||
***********************************
|
||||
* Rappels divers
|
||||
***********************************
|
||||
|
||||
Votre nom de domaine doit etre configure pour pointer
|
||||
sur l'adresse IP %SERVER_ADDR% (enregistrement DNS A)
|
||||
ou etre un alias de %SERVER_NAME% (enregistrement DNS CNAME).
|
||||
|
||||
Si vous avez besoin de faire des tests, vous devez
|
||||
ajouter la ligne suivante au fichier "/etc/hosts" sous Linux/Unix
|
||||
ou au fichier "system32\drivers\etc\hosts" sous Windows NT/XP :
|
||||
%SERVER_ADDR% SERVERNAME
|
||||
|
||||
Attention, par defaut, toutes les connexions vers l'exterieur
|
||||
sont bloquees. Si vous avez besoin de recuperer des donnees
|
||||
a l'exterieur (flux RSS, BDD externe, etc.), contactez nous
|
||||
afin de mettre en oeuvre les autorisations necessaires.
|
||||
|
||||
Afin de securiser au maximum le serveur, certaines URL
|
||||
particulieres sont non autorisees pour eviter diverses
|
||||
attaques (XSS, robots, trojans, injections, etc.).
|
||||
Exemple d'URL refusee :
|
||||
http://SERVERNAME/cmd32.exe
|
||||
En cas de soucis avec votre application, prevenez-nous.
|
||||
|
||||
Si vous desirez mettre en place des parametres particuliers
|
||||
pour votre site (PHP, etc.) ou pour tout autre demande (scripts en crontab,
|
||||
etc.), n'hesitez pas a nous contacter a l'adresse
|
||||
%MAIL_STANDARD% (ou %MAIL_URGENT% si votre demande est
|
||||
urgente).
|
||||
|
||||
|
||||
Cordialement,
|
||||
--
|
||||
%FOOTER%
|
|
@ -0,0 +1,47 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* Gestion des comptes utilisateurs
|
||||
*
|
||||
* Copyright (c) 2009 Evolix - Tous droits reserves
|
||||
*
|
||||
* vim: expandtab softtabstop=4 tabstop=4 shiftwidth=4 showtabline=2
|
||||
*
|
||||
* @author Gregory Colpart <reg@evolix.fr>
|
||||
* @author Thomas Martin <tmartin@evolix.fr>
|
||||
* @author Sebastien Palma <spalma@evolix.fr>
|
||||
* @version 1.0
|
||||
*/
|
||||
|
||||
?>
|
||||
|
||||
<?php
|
||||
if(!empty($exec_info)) {
|
||||
print '<pre>';
|
||||
if ($conf['debug'] == TRUE)
|
||||
printf("Exécution de : %s\n", $exec_info[0]);
|
||||
|
||||
if ($exec_info[1]) {
|
||||
print "La commande a <strong>échoué</strong>\n";
|
||||
print_r($exec_info);
|
||||
}
|
||||
else print "Le compte a été créé avec succès\n";
|
||||
|
||||
if ($conf['debug'] == TRUE)
|
||||
foreach($exec_info[2] as $exec_line) {
|
||||
printf("%s\n", $exec_line);
|
||||
}
|
||||
|
||||
print '</pre>';
|
||||
} else {
|
||||
?>
|
||||
|
||||
<form name="form-add" id="form-add" action="" method="POST">
|
||||
<fieldset>
|
||||
<legend>Ajout d'un compte</legend>
|
||||
<?php print $form; ?>
|
||||
<p><input type="submit" value="Créer"/></p>
|
||||
</fieldset>
|
||||
</form>
|
||||
|
||||
<?php } ?>
|
|
@ -0,0 +1,43 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* Authentification form
|
||||
*
|
||||
* Copyright (c) 2009 Evolix - Tous droits reserves
|
||||
*
|
||||
* vim: expandtab softtabstop=4 tabstop=4 shiftwidth=4 showtabline=2
|
||||
*
|
||||
* @author Gregory Colpart <reg@evolix.fr>
|
||||
* @author Thomas Martin <tmartin@evolix.fr>
|
||||
* @author Sebastien Palma <spalma@evolix.fr>
|
||||
* @version 1.0
|
||||
*/
|
||||
|
||||
?>
|
||||
|
||||
<br/><br/>
|
||||
<form method="POST">
|
||||
<table width="300" align="center">
|
||||
<tr>
|
||||
<td align="right">Utilisateur : </td>
|
||||
<td align="left"><input type="text" name="login" /></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="right">Mot de passe : </td>
|
||||
<td align="left"><input type="password" name="passw" /></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td> </td>
|
||||
<td align="left"><br/><input type="submit" value="Connexion" /></td>
|
||||
</tr>
|
||||
<?php
|
||||
if (!empty($error)) {
|
||||
?>
|
||||
<tr>
|
||||
<td colspan="2" class="auth-error">Identifiants invalides. Veuillez ré-essayer</td>
|
||||
</tr>
|
||||
<?php
|
||||
}
|
||||
?>
|
||||
</table>
|
||||
</form>
|
|
@ -0,0 +1,22 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* Footer template for all pages
|
||||
*
|
||||
* Copyright (c) 2009 Evolix - Tous droits reserves
|
||||
*
|
||||
* vim: expandtab softtabstop=4 tabstop=4 shiftwidth=4 showtabline=2
|
||||
*
|
||||
* @author Gregory Colpart <reg@evolix.fr>
|
||||
* @author Thomas Martin <tmartin@evolix.fr>
|
||||
* @author Sebastien Palma <spalma@evolix.fr>
|
||||
* @version 1.0
|
||||
*/
|
||||
|
||||
?>
|
||||
<div id="disclaimer">
|
||||
Propulsé par <a href="http://www.evolix.fr" target="_blank">Evolix</a>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,3 @@
|
|||
<p>
|
||||
Compte <?php print $ftp_added_login ?> créé avec succès.
|
||||
</p>
|
|
@ -0,0 +1,74 @@
|
|||
|
||||
|
||||
<form name="form-add" id="form-add" action="/ftpadmin/add/" method="POST">
|
||||
<fieldset>
|
||||
<legend>Ajouter un compte FTP</legend>
|
||||
|
||||
<?php
|
||||
if (array_key_exists('error', $_SESSION) && is_numeric($_SESSION['error']) && $_SESSION['error']!=3) {
|
||||
?>
|
||||
<p class="form-error">
|
||||
<?php print $errors[$_SESSION['error']]; ?></td>
|
||||
</p>
|
||||
<?php } ?>
|
||||
|
||||
<?php
|
||||
if(is_superadmin()) {
|
||||
print '<dl>';
|
||||
print '<dt><label for="owner">Propriétaire : </label></dt>';
|
||||
print '<dd><select id="owner" name="owner">';
|
||||
foreach($owner_list as $owner_name) {
|
||||
printf('<option>%s</option>', $owner_name);
|
||||
}
|
||||
print '</select></dd>';
|
||||
print '</dl>';
|
||||
}
|
||||
?>
|
||||
|
||||
<dl>
|
||||
<dt><label for="login">Utilisateur : </label></dt>
|
||||
<dd><input type="text" name="login"
|
||||
id="login" onblur="fill_directory_field(this.value);"
|
||||
value="<?php @print $_SESSION['form']['login'];?>" <?php print $readonly ?>/></dd>
|
||||
</dl>
|
||||
|
||||
<dl>
|
||||
<dt><label for="passwd">Mot de passe : </label></dt>
|
||||
<dd><input type="password" name="passwd" id="passwd" value="<?php @print $_SESSION['form']['passw']; ?>" <?php print $readonly ?>/></dd>
|
||||
</dl>
|
||||
|
||||
<dl>
|
||||
<dt><label for="passwd_c">Confirmation du mot de passe : </label></dt>
|
||||
<dd><input type="password" name="passwd_c" id="passwd_c" value="<?php @print $_SESSION['form']['pass2']; ?>" <?php print $readonly ?>/></dd>
|
||||
</dl>
|
||||
|
||||
<dl>
|
||||
<dt><label for="path">Répertoire : </label></dt>
|
||||
<dd><input type="text" name="path" id="path" value="<?php @print $_SESSION['form']['dossier']; ?>" <?php print $readonly ?>/></dd>
|
||||
</dl>
|
||||
|
||||
<?php
|
||||
if (array_key_exists('error', $_SESSION) && $_SESSION['error']==3) {
|
||||
?>
|
||||
<dl>
|
||||
<dt><label><?php print $errors[3]; ?></label></dt>
|
||||
<dd>
|
||||
<label>
|
||||
<input type="radio" name="confirm" value="1" checked="checked"/>
|
||||
Oui
|
||||
</label>
|
||||
<label>
|
||||
<input type="radio" name="confirm" value="0" />
|
||||
Non
|
||||
</label>
|
||||
</dd>
|
||||
</dl>
|
||||
<?php } ?>
|
||||
|
||||
<dl>
|
||||
<dt> </dt>
|
||||
<dd><input type="submit" value="Exécuter" name="submit_button"
|
||||
onclick="return check_form_ftp_add()" /></dd>
|
||||
</dl>
|
||||
</fieldset>
|
||||
</form>
|
|
@ -0,0 +1,77 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* Template Page for the ProFTPD's virtual accounts
|
||||
*
|
||||
* Copyright (c) 2009 Evolix - Tous droits reserves
|
||||
*
|
||||
* vim: expandtab softtabstop=4 tabstop=4 shiftwidth=4 showtabline=2
|
||||
*
|
||||
* @author Gregory Colpart <reg@evolix.fr>
|
||||
* @author Thomas Martin <tmartin@evolix.fr>
|
||||
* @author Sebastien Palma <spalma@evolix.fr>
|
||||
* @version 1.0
|
||||
*/
|
||||
|
||||
function html_render_account($line) {
|
||||
print "<tr>\n";
|
||||
if(is_superadmin()) {
|
||||
print " <td>{$line['owner']}</td>\n";
|
||||
}
|
||||
print " <td>{$line['name']}</td>\n";
|
||||
print " <td>{$line['path']}</td>\n";
|
||||
print " <td>{$line['size']}</td>\n";
|
||||
//print " <td>{$line['date']}</td>\n";
|
||||
print " <td><!-- <a href='/ftpadmin/edit/{$line['name']}'>Change password</a> --><a href='/ftpadmin/delete/{$line['name']}' onClick='return confirm('Voulez-vous vraiment supprimer le compte {$line['name']}');'>Supprimer</a></td>\n";
|
||||
print "</tr>\n";
|
||||
}
|
||||
|
||||
?>
|
||||
|
||||
<h2>Comptes FTP</h2>
|
||||
|
||||
<br/><br/>
|
||||
|
||||
<?php if(count($table) > 0) { ?>
|
||||
<table id="tab-list" class="tab-list">
|
||||
<thead>
|
||||
<tr>
|
||||
<?php if(is_superadmin()) { ?>
|
||||
<th>Propriétaire</th>
|
||||
<?php } ?>
|
||||
<th>Compte</th>
|
||||
<th>Répertoire</th>
|
||||
<th>Espace utilisé</th>
|
||||
<!--<th>Dernière modif.</th>-->
|
||||
<th>Actions</th>
|
||||
<tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php
|
||||
foreach ($table as $table_line) {
|
||||
echo html_render_account($table_line);
|
||||
}
|
||||
?>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<p>
|
||||
Espace total utilisé : <?php print $size_total ?>.
|
||||
</p>
|
||||
<br/>
|
||||
<br/>
|
||||
<?php } ?>
|
||||
|
||||
|
||||
<?php
|
||||
|
||||
$readonly="";
|
||||
if (array_key_exists('error', $_SESSION) && $_SESSION['error']==3) $readonly="readonly='readonly'";
|
||||
|
||||
?>
|
||||
|
||||
<br/>
|
||||
|
||||
<a id="ftp-add"></a>
|
||||
<pre>
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* Header template for all pages
|
||||
*
|
||||
* Copyright (c) 2009 Evolix - Tous droits reserves
|
||||
*
|
||||
* vim: expandtab softtabstop=4 tabstop=4 shiftwidth=4 showtabline=2
|
||||
*
|
||||
* @author Gregory Colpart <reg@evolix.fr>
|
||||
* @author Thomas Martin <tmartin@evolix.fr>
|
||||
* @author Sebastien Palma <spalma@evolix.fr>
|
||||
* @version 1.0
|
||||
*/
|
||||
|
||||
?>
|
||||
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
|
||||
|
||||
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
|
||||
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
||||
<title>EvoAdmin - Powered by Evolix</title>
|
||||
<link rel="stylesheet" href="/inc/css/main.css" type="text/css" media="screen, projection" />
|
||||
<script type="text/javascript" src="/inc/js/lib/prototype-1.6.0.3.js"></script>
|
||||
<script type="text/javascript" src="/inc/js/ftpadmin.js"></script>
|
||||
<script type="text/javascript" src="/inc/js/webadmin.js"></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
<div id="main">
|
||||
<h1 id="top">EvoAdmin
|
||||
<?php
|
||||
if(!empty($_SESSION['user'])) {
|
||||
print ' - '.$_SESSION['user'];
|
||||
}
|
||||
if(is_superadmin()) {
|
||||
print ' (Administrateur)';
|
||||
}
|
||||
?>
|
||||
</h1>
|
|
@ -0,0 +1,21 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* HomePage template
|
||||
*
|
||||
* Copyright (c) 2009 Evolix - Tous droits reserves
|
||||
*
|
||||
* vim: expandtab softtabstop=4 tabstop=4 shiftwidth=4 showtabline=2
|
||||
*
|
||||
* @author Gregory Colpart <reg@evolix.fr>
|
||||
* @author Thomas Martin <tmartin@evolix.fr>
|
||||
* @author Sebastien Palma <spalma@evolix.fr>
|
||||
* @version 1.0
|
||||
*/
|
||||
|
||||
?>
|
||||
|
||||
<p>
|
||||
Bienvenue, utilisez le menu ci-dessus pour administrer votre compte.
|
||||
</p>
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* Menu principal
|
||||
*
|
||||
* Copyright (c) 2009 Evolix - Tous droits reserves
|
||||
*
|
||||
* vim: expandtab softtabstop=4 tabstop=4 shiftwidth=4 showtabline=2
|
||||
*
|
||||
* @author Gregory Colpart <reg@evolix.fr>
|
||||
* @author Thomas Martin <tmartin@evolix.fr>
|
||||
* @author Sebastien Palma <spalma@evolix.fr>
|
||||
* @version 1.0
|
||||
*/
|
||||
|
||||
?>
|
||||
|
||||
<ul id="menu">
|
||||
<li><a href="/">Accueil</a>
|
||||
<?php if(is_superadmin()) {
|
||||
print '<li><a href="/accounts">Ajout d\'un compte</a></li>';
|
||||
} ?>
|
||||
<li><a href="/webadmin">Liste des comptes</a></li>
|
||||
<?php if ($conf['ftpadmin']) { ?>
|
||||
<li><a href="/ftpadmin/add">Ajout FTP</a></li>
|
||||
<li><a href="/ftpadmin">Comptes FTP</a></li>
|
||||
<?php } ?>
|
||||
<li><a href="/destroy">Déconnexion</a></li>
|
||||
</ul>
|
||||
<br/>
|
||||
|
|
@ -0,0 +1,64 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* Edition d'un domaine
|
||||
*
|
||||
* Copyright (c) 2009 Evolix - Tous droits reserves
|
||||
*
|
||||
* vim: expandtab softtabstop=4 tabstop=4 shiftwidth=4 showtabline=2
|
||||
*
|
||||
* @author Thomas Martin <tmartin@evolix.fr>
|
||||
* @version 1.0
|
||||
*/
|
||||
|
||||
?>
|
||||
|
||||
<h2>Server Alias</h2>
|
||||
|
||||
<?php
|
||||
if ($conf['cluster']) {
|
||||
|
||||
if(count($alias_list) > 0) {
|
||||
|
||||
if (is_superadmin()) {
|
||||
print "<center>";
|
||||
printf('<p><a href="/webadmin/edit/%s?add">Ajouter un alias</a></p>', $domain);
|
||||
print "</center>";
|
||||
}?>
|
||||
|
||||
<table id="tab-list">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Alias</th>
|
||||
<?php if (is_superadmin()) {
|
||||
print '<th>Action</th>';
|
||||
} ?>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php
|
||||
for ( $i=0; $i < count($alias_list); ++$i ) {
|
||||
print '<tr>';
|
||||
printf('<td><a href="http://%s">http://%s</a></td>',
|
||||
$alias_list[$i]['alias'], $alias_list[$i]['alias']);
|
||||
if (is_superadmin())
|
||||
printf('<td><a href="/webadmin/edit/%s?del=%s">Supprimer</a></td>',
|
||||
$domain, $alias_list[$i]['alias']);
|
||||
print '</tr>';
|
||||
} ?>
|
||||
</tbody>
|
||||
</table>
|
||||
<?php
|
||||
} else {
|
||||
print "<p>Aucun alias existant pour le domaine $domain !</p>";
|
||||
if (is_superadmin()) {
|
||||
print "<center>";
|
||||
printf('<p><a href="/webadmin/edit/%s?add">Ajouter un alias</a></p>', $domain);
|
||||
print "</center>";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
?>
|
||||
|
|
@ -0,0 +1,86 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* Gestion des domaines
|
||||
*
|
||||
* Copyright (c) 2009 Evolix - Tous droits reserves
|
||||
*
|
||||
* vim: expandtab softtabstop=4 tabstop=4 shiftwidth=4 showtabline=2
|
||||
*
|
||||
* @author Gregory Colpart <reg@evolix.fr>
|
||||
* @author Thomas Martin <tmartin@evolix.fr>
|
||||
* @author Sebastien Palma <spalma@evolix.fr>
|
||||
* @version 1.0
|
||||
*/
|
||||
|
||||
?>
|
||||
|
||||
<h2>Domaines</h2>
|
||||
|
||||
<?php if(count($vhost_list) > 0) { ?>
|
||||
<table id="tab-list">
|
||||
<thead>
|
||||
<tr>
|
||||
<?php if(is_superadmin()) {
|
||||
print '<th>Propriétaire</th>';
|
||||
} ?>
|
||||
<th>Domaine</th>
|
||||
<!--<th>Opérations</th>-->
|
||||
<?php if($conf['cluster']) { ?>
|
||||
<th>Bdd</th>
|
||||
<th>Replication</th>
|
||||
<th>Master</th>
|
||||
<th>Slave</th>
|
||||
<?php } else
|
||||
print('<th>Alias</th>');
|
||||
?>
|
||||
<tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach($vhost_list as $vhost_info) {
|
||||
print '<tr>';
|
||||
if(is_superadmin()) {
|
||||
printf('<td>%s</td>', $vhost_info['owner']);
|
||||
}
|
||||
printf('<td><a href="http://%s">http://%s</a></td>',
|
||||
$vhost_info['server_name'], $vhost_info['server_name']);
|
||||
|
||||
if ($conf['cluster']) {
|
||||
|
||||
if (empty($vhost_info['bdd']))
|
||||
printf('<td bgcolor="#696969"/>');
|
||||
else
|
||||
printf('<td>%s</td>', $vhost_info['bdd']);
|
||||
|
||||
if (empty($vhost_info['replication']))
|
||||
printf('<td bgcolor="#696969" />');
|
||||
else
|
||||
printf('<td>%s</td>', $vhost_info['replication']);
|
||||
|
||||
printf('<td>%s</td>', $vhost_info['master']);
|
||||
|
||||
if (empty($vhost_info['slave']))
|
||||
printf('<td bgcolor="#696969"/>');
|
||||
else
|
||||
printf('<td>%s</td>', $vhost_info['slave']);
|
||||
|
||||
if (is_superadmin()) {
|
||||
printf('<td><a href="/webadmin/edit/%s">Lister/Modifier</a></td>',
|
||||
$vhost_info['owner']);
|
||||
}
|
||||
|
||||
} else {
|
||||
if (empty($vhost_info['server_alias']))
|
||||
printf('<td bgcolor="#696969"/>');
|
||||
else
|
||||
printf('<td>%s</td>', $vhost_info['server_alias']);
|
||||
}
|
||||
print '</tr>';
|
||||
} ?>
|
||||
</tbody>
|
||||
</table>
|
||||
<?php
|
||||
} else {
|
||||
print '<p>Aucun domaine existant !</p>';
|
||||
}
|
||||
?>
|
Loading…
Reference in New Issue