OSDN Git Service

Initial version.
authorTaku Amano <taku@toi-planning.net>
Wed, 16 Sep 2009 12:44:22 +0000 (21:44 +0900)
committerTaku Amano <taku@toi-planning.net>
Wed, 16 Sep 2009 12:44:22 +0000 (21:44 +0900)
31 files changed:
Build.PL [new file with mode: 0644]
COPYING [new file with mode: 0644]
MANIFEST [new file with mode: 0644]
MANIFEST.SKIP [new file with mode: 0644]
config.yaml [new file with mode: 0644]
extlib/Archive/.exists [new file with mode: 0644]
extlib/Archive/Tar.pm [new file with mode: 0644]
extlib/Archive/Tar/Constant.pm [new file with mode: 0644]
extlib/Archive/Tar/File.pm [new file with mode: 0644]
extlib/Digest/Perl/.exists [new file with mode: 0644]
extlib/Digest/Perl/MD5.pm [new file with mode: 0755]
extlib/File/Copy/.exists [new file with mode: 0644]
extlib/File/Copy/Recursive.pm [new file with mode: 0644]
lib/PluginManager/App.pm [new file with mode: 0644]
lib/PluginManager/Command.pm [new file with mode: 0644]
lib/PluginManager/Installed.pm [new file with mode: 0644]
lib/PluginManager/L10N.pm [new file with mode: 0644]
lib/PluginManager/L10N/en_us.pm [new file with mode: 0644]
lib/PluginManager/L10N/ja.pm [new file with mode: 0644]
lib/PluginManager/Packages.pm [new file with mode: 0644]
lib/PluginManager/Repository.pm [new file with mode: 0644]
lib/PluginManager/Util.pm [new file with mode: 0644]
tmpl/include/pm_menus.tmpl [new file with mode: 0644]
tmpl/include/pm_package_list_table.tmpl [new file with mode: 0644]
tmpl/pm_export.tmpl [new file with mode: 0644]
tmpl/pm_ftp_prompt.tmpl [new file with mode: 0644]
tmpl/pm_import.tmpl [new file with mode: 0644]
tmpl/pm_package_list.tmpl [new file with mode: 0644]
tmpl/pm_repository.tmpl [new file with mode: 0644]
tmpl/pm_setting.tmpl [new file with mode: 0644]
tools/plugin-manager [new file with mode: 0755]

diff --git a/Build.PL b/Build.PL
new file mode 100644 (file)
index 0000000..a784bef
--- /dev/null
+++ b/Build.PL
@@ -0,0 +1,119 @@
+use strict;
+use warnings;
+use Module::Build;
+use File::Spec;
+use File::Basename;
+use YAML qw/ Load /;
+
+my $class = Module::Build->subclass(
+       class => 'MovableTypePluginManagerBuilder',
+       code => q{
+               # Don't make blib
+               # sub ACTION_code {};
+               # Don't make blib
+               sub ACTION_docs {};
+               # Don't make META.yml
+               sub ACTION_distmeta {
+                       # no warning on ACTION_distdir
+                       $_[0]->{metafile} = 'MANIFEST';
+               };
+               # Don't add MEATA.yml to MANIFEST
+               sub ACTION_manifest {
+                       $_[0]->{metafile} = 'MANIFEST',
+                       $_[0]->SUPER::ACTION_manifest(@_);
+               };
+               sub ACTION_test {
+                       my $p = $_[0]->{properties};
+                       unshift(
+                               @INC,
+                               File::Spec->catdir($p->{base_dir}, 'extlib'),
+                               File::Spec->catdir($p->{base_dir}, '../../lib'),
+                               File::Spec->catdir($p->{base_dir}, '../../extlib'),
+                       );
+
+                       $_[0]->SUPER::ACTION_test(@_);
+               };
+
+               sub ACTION_zipdist {
+                       my ($self) = @_;
+                       my $dist_dir = $self->dist_dir;
+                       $self->depends_on('distdir');
+                       print "Creating $dist_dir.zip\n";
+                       system("zip -r $dist_dir.zip $dist_dir") == 0 or die $?;
+                       $self->delete_filetree($dist_dir);
+               }
+
+               sub ACTION_distdir {
+                       my ($self) = @_;
+
+                       $_[0]->SUPER::ACTION_distdir(@_);
+
+                       my $dist_dir = $self->dist_dir;
+                       rename($dist_dir, $self->{properties}{dist_name});
+                       use File::Path;
+                       use File::Spec;
+                       use File::Basename;
+                       my $plugins = File::Spec->catfile($dist_dir, 'plugins');
+                       mkpath($plugins, 1, 0755);
+
+                       my $new_dist_dir = File::Spec->catfile(
+                               $plugins, $self->{properties}{dist_name}
+                       );
+                       rename($self->{properties}{dist_name}, $new_dist_dir);
+
+                       foreach my $f (glob(File::Spec->catfile($new_dist_dir, 'COPYING'))) {
+                               rename($f, File::Spec->catfile($dist_dir, basename($f)));
+                       }
+
+                       if (my @statics = glob(File::Spec->catfile($new_dist_dir, 'static/*'))) {
+                               my $static = File::Spec->catfile(
+                                       $dist_dir, 'mt-static/plugins'
+                               );
+                               mkpath($static, 1, 0755);
+
+                               my $d = File::Spec->catfile(
+                                       $static, $self->{properties}{dist_name}
+                               );
+                               mkpath($d, 1, 0755);
+
+                               foreach my $f (@statics) {
+                                       rename($f, File::Spec->catfile($d, basename($f)));
+                               }
+
+                               rmdir(File::Spec->catfile($new_dist_dir, 'static'));
+                       }
+
+                       if (my @tools = glob(File::Spec->catfile($new_dist_dir, 'tools/*'))) {
+                               my $tool = File::Spec->catfile(
+                                       $dist_dir, 'tools'
+                               );
+                               mkpath($tool, 1, 0755);
+
+                               foreach my $f (@tools) {
+                                       rename($f, File::Spec->catfile($tool, basename($f)));
+                               }
+
+                               rmdir(File::Spec->catfile($new_dist_dir, 'tools'));
+                       }
+               }
+       }
+);
+
+my $yaml_string = do {
+       open(my $fh, File::Spec->catfile(dirname(__FILE__), 'config.yaml'));
+       local $/;
+       <$fh>
+};
+$yaml_string =~ s/^(\s*)\*/$1App::\*/gm;
+my $yaml = Load($yaml_string);
+
+my $builder = $class->new(
+       dist_name           => $yaml->{name},
+    dist_author         => 'Movable Type Plugin Manager Project',
+    dist_version        => $yaml->{version},
+    module_name         => $yaml->{name} . '::App',
+    license             => 'GPL',
+    add_to_cleanup      => [ $yaml->{name} . '-*' ],
+);
+
+$builder->create_build_script();
diff --git a/COPYING b/COPYING
new file mode 100644 (file)
index 0000000..d511905
--- /dev/null
+++ b/COPYING
@@ -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.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 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.
diff --git a/MANIFEST b/MANIFEST
new file mode 100644 (file)
index 0000000..9684ab4
--- /dev/null
+++ b/MANIFEST
@@ -0,0 +1,28 @@
+config.yaml
+COPYING
+extlib/Archive/.exists
+extlib/Archive/Tar.pm
+extlib/Archive/Tar/Constant.pm
+extlib/Archive/Tar/File.pm
+extlib/Digest/Perl/.exists
+extlib/Digest/Perl/MD5.pm
+extlib/File/Copy/.exists
+extlib/File/Copy/Recursive.pm
+lib/PluginManager/App.pm
+lib/PluginManager/Command.pm
+lib/PluginManager/Installed.pm
+lib/PluginManager/L10N.pm
+lib/PluginManager/L10N/en_us.pm
+lib/PluginManager/L10N/ja.pm
+lib/PluginManager/Packages.pm
+lib/PluginManager/Repository.pm
+lib/PluginManager/Util.pm
+tmpl/include/pm_menus.tmpl
+tmpl/include/pm_package_list_table.tmpl
+tmpl/pm_export.tmpl
+tmpl/pm_ftp_prompt.tmpl
+tmpl/pm_import.tmpl
+tmpl/pm_package_list.tmpl
+tmpl/pm_repository.tmpl
+tmpl/pm_setting.tmpl
+tools/plugin-manager
diff --git a/MANIFEST.SKIP b/MANIFEST.SKIP
new file mode 100644 (file)
index 0000000..ec6d23b
--- /dev/null
@@ -0,0 +1,48 @@
+^MANIFEST
+\bBuild.PL$
+#^Makefile
+#^META.yml$
+#^blib/
+#~$
+
+
+# Avoid version control files.
+\bRCS\b
+\bCVS\b
+,v$
+\B\.svn\b
+\B\.cvsignore$
+\B.git
+
+# Avoid Makemaker generated and utility files.
+\bMakefile$
+\bblib
+\bMakeMaker-\d
+\bpm_to_blib$
+\bblibdirs$
+^MANIFEST\.SKIP$
+
+# Avoid Module::Build generated and utility files.
+\bBuild$
+\bBuild.bat$
+\b_build
+
+# Avoid Devel::Cover generated files
+\bcover_db
+
+# Avoid temp and backup files.
+~$
+\.tmp$
+\.old$
+\.bak$
+\#$
+\.#
+\.rej$
+
+# Avoid OS-specific files/dirs
+#   Mac OSX metadata
+\B\.DS_Store
+#   Mac OSX SMB mount metadata files
+\B\._
+# Avoid archives of this distribution
+\bArchiveUploader-[\d\.\_]+
diff --git a/config.yaml b/config.yaml
new file mode 100644 (file)
index 0000000..81e8179
--- /dev/null
@@ -0,0 +1,47 @@
+#plugin name
+name: PluginManager
+version: 0.1.0
+
+#about this plugin
+description: <__trans phrase="A plugin to manage plugins.">
+author_name: Movable Type Plugin Manager Project
+author_link: http://mtpm.sourceforge.jp/
+plugin_link: http://mtpm.sourceforge.jp/
+doc_link: http://sourceforge.jp/projects/mtpm/wiki/FrontPage
+
+#Localization
+l10n_class: PluginManager::L10N
+
+#objects
+schema_version: 0.6
+object_types:
+    pm_packages: PluginManager::Packages
+    pm_installed: PluginManager::Installed
+
+settings:
+    repositories:
+        Default:
+            - http://mtpm.sourceforge.jp/mt/mt-static/support/mpm/
+    download_unit:
+        Default: 512
+
+    ftp_host:
+    ftp_user:
+    ftp_directory:
+
+callbacks:
+    MT::App::CMS::init_request: PluginManager::App::init_request
+
+applications:
+    cms:
+        menus:
+            tools:pluginmanager:
+                label: Plugin Manager
+                order: 1000
+                mode: pluginmanager
+                view: system
+                permission: administer_blog
+                system_permission: manage_plugins
+
+        methods:
+            pluginmanager: PluginManager::App::pluginmanager
diff --git a/extlib/Archive/.exists b/extlib/Archive/.exists
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/extlib/Archive/Tar.pm b/extlib/Archive/Tar.pm
new file mode 100644 (file)
index 0000000..508bcfe
--- /dev/null
@@ -0,0 +1,1866 @@
+### the gnu tar specification:
+### http://www.gnu.org/software/tar/manual/tar.html
+###
+### and the pax format spec, which tar derives from:
+### http://www.opengroup.org/onlinepubs/007904975/utilities/pax.html
+
+package Archive::Tar;
+require 5.005_03;
+
+use strict;
+use vars qw[$DEBUG $error $VERSION $WARN $FOLLOW_SYMLINK $CHOWN $CHMOD
+            $DO_NOT_USE_PREFIX $HAS_PERLIO $HAS_IO_STRING
+            $INSECURE_EXTRACT_MODE
+         ];
+
+$DEBUG                  = 0;
+$WARN                   = 1;
+$FOLLOW_SYMLINK         = 0;
+$VERSION                = "1.38";
+$CHOWN                  = 1;
+$CHMOD                  = 1;
+$DO_NOT_USE_PREFIX      = 0;
+$INSECURE_EXTRACT_MODE  = 0;
+
+BEGIN {
+    use Config;
+    $HAS_PERLIO = $Config::Config{useperlio};
+
+    ### try and load IO::String anyway, so you can dynamically
+    ### switch between perlio and IO::String
+    eval {
+        require IO::String;
+        import IO::String;
+    };
+    $HAS_IO_STRING = $@ ? 0 : 1;
+
+}
+
+use Cwd;
+use IO::File;
+use Carp                qw(carp croak);
+use File::Spec          ();
+use File::Spec::Unix    ();
+use File::Path          ();
+
+use Archive::Tar::File;
+use Archive::Tar::Constant;
+
+=head1 NAME
+
+Archive::Tar - module for manipulations of tar archives
+
+=head1 SYNOPSIS
+
+    use Archive::Tar;
+    my $tar = Archive::Tar->new;
+
+    $tar->read('origin.tgz',1);
+    $tar->extract();
+
+    $tar->add_files('file/foo.pl', 'docs/README');
+    $tar->add_data('file/baz.txt', 'This is the contents now');
+
+    $tar->rename('oldname', 'new/file/name');
+
+    $tar->write('files.tar');
+
+=head1 DESCRIPTION
+
+Archive::Tar provides an object oriented mechanism for handling tar
+files.  It provides class methods for quick and easy files handling
+while also allowing for the creation of tar file objects for custom
+manipulation.  If you have the IO::Zlib module installed,
+Archive::Tar will also support compressed or gzipped tar files.
+
+An object of class Archive::Tar represents a .tar(.gz) archive full
+of files and things.
+
+=head1 Object Methods
+
+=head2 Archive::Tar->new( [$file, $compressed] )
+
+Returns a new Tar object. If given any arguments, C<new()> calls the
+C<read()> method automatically, passing on the arguments provided to
+the C<read()> method.
+
+If C<new()> is invoked with arguments and the C<read()> method fails
+for any reason, C<new()> returns undef.
+
+=cut
+
+my $tmpl = {
+    _data   => [ ],
+    _file   => 'Unknown',
+};
+
+### install get/set accessors for this object.
+for my $key ( keys %$tmpl ) {
+    no strict 'refs';
+    *{__PACKAGE__."::$key"} = sub {
+        my $self = shift;
+        $self->{$key} = $_[0] if @_;
+        return $self->{$key};
+    }
+}
+
+sub new {
+    my $class = shift;
+    $class = ref $class if ref $class;
+
+    ### copying $tmpl here since a shallow copy makes it use the
+    ### same aref, causing for files to remain in memory always.
+    my $obj = bless { _data => [ ], _file => 'Unknown' }, $class;
+
+    if (@_) {
+        unless ( $obj->read( @_ ) ) {
+            $obj->_error(qq[No data could be read from file]);
+            return;
+        }
+    }
+
+    return $obj;
+}
+
+=head2 $tar->read ( $filename|$handle, $compressed, {opt => 'val'} )
+
+Read the given tar file into memory.
+The first argument can either be the name of a file or a reference to
+an already open filehandle (or an IO::Zlib object if it's compressed)
+The second argument indicates whether the file referenced by the first
+argument is compressed.
+
+The C<read> will I<replace> any previous content in C<$tar>!
+
+The second argument may be considered optional if IO::Zlib is
+installed, since it will transparently Do The Right Thing.
+Archive::Tar will warn if you try to pass a compressed file if
+IO::Zlib is not available and simply return.
+
+Note that you can currently B<not> pass a C<gzip> compressed
+filehandle, which is not opened with C<IO::Zlib>, nor a string
+containing the full archive information (either compressed or
+uncompressed). These are worth while features, but not currently
+implemented. See the C<TODO> section.
+
+The third argument can be a hash reference with options. Note that
+all options are case-sensitive.
+
+=over 4
+
+=item limit
+
+Do not read more than C<limit> files. This is useful if you have
+very big archives, and are only interested in the first few files.
+
+=item extract
+
+If set to true, immediately extract entries when reading them. This
+gives you the same memory break as the C<extract_archive> function.
+Note however that entries will not be read into memory, but written
+straight to disk.
+
+=back
+
+All files are stored internally as C<Archive::Tar::File> objects.
+Please consult the L<Archive::Tar::File> documentation for details.
+
+Returns the number of files read in scalar context, and a list of
+C<Archive::Tar::File> objects in list context.
+
+=cut
+
+sub read {
+    my $self = shift;
+    my $file = shift;
+    my $gzip = shift || 0;
+    my $opts = shift || {};
+
+    unless( defined $file ) {
+        $self->_error( qq[No file to read from!] );
+        return;
+    } else {
+        $self->_file( $file );
+    }
+
+    my $handle = $self->_get_handle($file, $gzip, READ_ONLY->( ZLIB ) )
+                    or return;
+
+    my $data = $self->_read_tar( $handle, $opts ) or return;
+
+    $self->_data( $data );
+
+    return wantarray ? @$data : scalar @$data;
+}
+
+sub _get_handle {
+    my $self = shift;
+    my $file = shift;   return unless defined $file;
+                        return $file if ref $file;
+
+    my $gzip = shift || 0;
+    my $mode = shift || READ_ONLY->( ZLIB ); # default to read only
+
+    my $fh; my $bin;
+
+    ### only default to ZLIB if we're not trying to /write/ to a handle ###
+    if( ZLIB and $gzip || MODE_READ->( $mode ) ) {
+
+        ### IO::Zlib will Do The Right Thing, even when passed
+        ### a plain file ###
+        $fh = new IO::Zlib;
+
+    } else {
+        if( $gzip ) {
+            $self->_error(qq[Compression not available - Install IO::Zlib!]);
+            return;
+
+        } else {
+            $fh = new IO::File;
+            $bin++;
+        }
+    }
+
+    unless( $fh->open( $file, $mode ) ) {
+        $self->_error( qq[Could not create filehandle for '$file': $!!] );
+        return;
+    }
+
+    binmode $fh if $bin;
+
+    return $fh;
+}
+
+sub _read_tar {
+    my $self    = shift;
+    my $handle  = shift or return;
+    my $opts    = shift || {};
+
+    my $count   = $opts->{limit}    || 0;
+    my $extract = $opts->{extract}  || 0;
+
+    ### set a cap on the amount of files to extract ###
+    my $limit   = 0;
+    $limit = 1 if $count > 0;
+
+    my $tarfile = [ ];
+    my $chunk;
+    my $read = 0;
+    my $real_name;  # to set the name of a file when
+                    # we're encountering @longlink
+    my $data;
+
+    LOOP:
+    while( $handle->read( $chunk, HEAD ) ) {
+        ### IO::Zlib doesn't support this yet
+        my $offset = eval { tell $handle } || 'unknown';
+
+        unless( $read++ ) {
+            my $gzip = GZIP_MAGIC_NUM;
+            if( $chunk =~ /$gzip/ ) {
+                $self->_error( qq[Cannot read compressed format in tar-mode] );
+                return;
+            }
+        }
+
+        ### if we can't read in all bytes... ###
+        last if length $chunk != HEAD;
+
+        ### Apparently this should really be two blocks of 512 zeroes,
+        ### but GNU tar sometimes gets it wrong. See comment in the
+        ### source code (tar.c) to GNU cpio.
+        next if $chunk eq TAR_END;
+
+        ### according to the posix spec, the last 12 bytes of the header are
+        ### null bytes, to pad it to a 512 byte block. That means if these
+        ### bytes are NOT null bytes, it's a corrrupt header. See:
+        ### www.koders.com/c/fidCE473AD3D9F835D690259D60AD5654591D91D5BA.aspx
+        ### line 111
+        {   my $nulls = join '', "\0" x 12;
+            unless( $nulls eq substr( $chunk, 500, 12 ) ) {
+                $self->_error( qq[Invalid header block at offset $offset] );
+                next LOOP;
+            }
+        }
+
+        ### pass the realname, so we can set it 'proper' right away
+        ### some of the heuristics are done on the name, so important
+        ### to set it ASAP
+        my $entry;
+        {   my %extra_args = ();
+            $extra_args{'name'} = $$real_name if defined $real_name;
+            
+            unless( $entry = Archive::Tar::File->new(   chunk => $chunk, 
+                                                        %extra_args ) 
+            ) {
+                $self->_error( qq[Couldn't read chunk at offset $offset] );
+                next LOOP;
+            }
+        }
+
+        ### ignore labels:
+        ### http://www.gnu.org/manual/tar/html_node/tar_139.html
+        next if $entry->is_label;
+
+        if( length $entry->type and ($entry->is_file || $entry->is_longlink) ) {
+
+            if ( $entry->is_file && !$entry->validate ) {
+                ### sometimes the chunk is rather fux0r3d and a whole 512
+                ### bytes ends up in the ->name area.
+                ### clean it up, if need be
+                my $name = $entry->name;
+                $name = substr($name, 0, 100) if length $name > 100;
+                $name =~ s/\n/ /g;
+
+                $self->_error( $name . qq[: checksum error] );
+                next LOOP;
+            }
+
+            my $block = BLOCK_SIZE->( $entry->size );
+
+            $data = $entry->get_content_by_ref;
+
+            ### just read everything into memory
+            ### can't do lazy loading since IO::Zlib doesn't support 'seek'
+            ### this is because Compress::Zlib doesn't support it =/
+            ### this reads in the whole data in one read() call.
+            if( $handle->read( $$data, $block ) < $block ) {
+                $self->_error( qq[Read error on tarfile (missing data) '].
+                                    $entry->full_path ."' at offset $offset" );
+                next LOOP;
+            }
+
+            ### throw away trailing garbage ###
+            substr ($$data, $entry->size) = "" if defined $$data;
+
+            ### part II of the @LongLink munging -- need to do /after/
+            ### the checksum check.
+            if( $entry->is_longlink ) {
+                ### weird thing in tarfiles -- if the file is actually a
+                ### @LongLink, the data part seems to have a trailing ^@
+                ### (unprintable) char. to display, pipe output through less.
+                ### but that doesn't *always* happen.. so check if the last
+                ### character is a control character, and if so remove it
+                ### at any rate, we better remove that character here, or tests
+                ### like 'eq' and hashlook ups based on names will SO not work
+                ### remove it by calculating the proper size, and then
+                ### tossing out everything that's longer than that size.
+
+                ### count number of nulls
+                my $nulls = $$data =~ tr/\0/\0/;
+
+                ### cut data + size by that many bytes
+                $entry->size( $entry->size - $nulls );
+                substr ($$data, $entry->size) = "";
+            }
+        }
+
+        ### clean up of the entries.. posix tar /apparently/ has some
+        ### weird 'feature' that allows for filenames > 255 characters
+        ### they'll put a header in with as name '././@LongLink' and the
+        ### contents will be the name of the /next/ file in the archive
+        ### pretty crappy and kludgy if you ask me
+
+        ### set the name for the next entry if this is a @LongLink;
+        ### this is one ugly hack =/ but needed for direct extraction
+        if( $entry->is_longlink ) {
+            $real_name = $data;
+            next LOOP;
+        } elsif ( defined $real_name ) {
+            $entry->name( $$real_name );
+            $entry->prefix('');
+            undef $real_name;
+        }
+
+        $self->_extract_file( $entry ) if $extract
+                                            && !$entry->is_longlink
+                                            && !$entry->is_unknown
+                                            && !$entry->is_label;
+
+        ### Guard against tarfiles with garbage at the end
+           last LOOP if $entry->name eq '';
+
+        ### push only the name on the rv if we're extracting
+        ### -- for extract_archive
+        push @$tarfile, ($extract ? $entry->name : $entry);
+
+        if( $limit ) {
+            $count-- unless $entry->is_longlink || $entry->is_dir;
+            last LOOP unless $count;
+        }
+    } continue {
+        undef $data;
+    }
+
+    return $tarfile;
+}
+
+=head2 $tar->contains_file( $filename )
+
+Check if the archive contains a certain file.
+It will return true if the file is in the archive, false otherwise.
+
+Note however, that this function does an exact match using C<eq>
+on the full path. So it cannot compensate for case-insensitive file-
+systems or compare 2 paths to see if they would point to the same
+underlying file.
+
+=cut
+
+sub contains_file {
+    my $self = shift;
+    my $full = shift;
+    
+    return unless defined $full;
+
+    ### don't warn if the entry isn't there.. that's what this function
+    ### is for after all.
+    local $WARN = 0;
+    return 1 if $self->_find_entry($full);
+    return;
+}
+
+=head2 $tar->extract( [@filenames] )
+
+Write files whose names are equivalent to any of the names in
+C<@filenames> to disk, creating subdirectories as necessary. This
+might not work too well under VMS.
+Under MacPerl, the file's modification time will be converted to the
+MacOS zero of time, and appropriate conversions will be done to the
+path.  However, the length of each element of the path is not
+inspected to see whether it's longer than MacOS currently allows (32
+characters).
+
+If C<extract> is called without a list of file names, the entire
+contents of the archive are extracted.
+
+Returns a list of filenames extracted.
+
+=cut
+
+sub extract {
+    my $self    = shift;
+    my @args    = @_;
+    my @files;
+
+    # use the speed optimization for all extracted files
+    local($self->{cwd}) = cwd() unless $self->{cwd};
+
+    ### you requested the extraction of only certian files
+    if( @args ) {
+        for my $file ( @args ) {
+            
+            ### it's already an object?
+            if( UNIVERSAL::isa( $file, 'Archive::Tar::File' ) ) {
+                push @files, $file;
+                next;
+
+            ### go find it then
+            } else {
+            
+                my $found;
+                for my $entry ( @{$self->_data} ) {
+                    next unless $file eq $entry->full_path;
+    
+                    ### we found the file you're looking for
+                    push @files, $entry;
+                    $found++;
+                }
+    
+                unless( $found ) {
+                    return $self->_error( 
+                        qq[Could not find '$file' in archive] );
+                }
+            }
+        }
+
+    ### just grab all the file items
+    } else {
+        @files = $self->get_files;
+    }
+
+    ### nothing found? that's an error
+    unless( scalar @files ) {
+        $self->_error( qq[No files found for ] . $self->_file );
+        return;
+    }
+
+    ### now extract them
+    for my $entry ( @files ) {
+        unless( $self->_extract_file( $entry ) ) {
+            $self->_error(q[Could not extract ']. $entry->full_path .q['] );
+            return;
+        }
+    }
+
+    return @files;
+}
+
+=head2 $tar->extract_file( $file, [$extract_path] )
+
+Write an entry, whose name is equivalent to the file name provided to
+disk. Optionally takes a second parameter, which is the full native
+path (including filename) the entry will be written to.
+
+For example:
+
+    $tar->extract_file( 'name/in/archive', 'name/i/want/to/give/it' );
+
+    $tar->extract_file( $at_file_object,   'name/i/want/to/give/it' );
+
+Returns true on success, false on failure.
+
+=cut
+
+sub extract_file {
+    my $self = shift;
+    my $file = shift;   return unless defined $file;
+    my $alt  = shift;
+
+    my $entry = $self->_find_entry( $file )
+        or $self->_error( qq[Could not find an entry for '$file'] ), return;
+
+    return $self->_extract_file( $entry, $alt );
+}
+
+sub _extract_file {
+    my $self    = shift;
+    my $entry   = shift or return;
+    my $alt     = shift;
+
+    ### you wanted an alternate extraction location ###
+    my $name = defined $alt ? $alt : $entry->full_path;
+
+                            ### splitpath takes a bool at the end to indicate
+                            ### that it's splitting a dir
+    my ($vol,$dirs,$file);
+    if ( defined $alt ) { # It's a local-OS path
+        ($vol,$dirs,$file) = File::Spec->splitpath(       $alt,
+                                                          $entry->is_dir );
+    } else {
+        ($vol,$dirs,$file) = File::Spec::Unix->splitpath( $name,
+                                                          $entry->is_dir );
+    }
+
+    my $dir;
+    ### is $name an absolute path? ###
+    if( File::Spec->file_name_is_absolute( $dirs ) ) {
+
+        ### absolute names are not allowed to be in tarballs under
+        ### strict mode, so only allow it if a user tells us to do it
+        if( not defined $alt and not $INSECURE_EXTRACT_MODE ) {
+            $self->_error( 
+                q[Entry ']. $entry->full_path .q[' is an absolute path. ].
+                q[Not extracting absolute paths under SECURE EXTRACT MODE]
+            );  
+            return;
+        }
+        
+        ### user asked us to, it's fine.
+        $dir = $dirs;
+
+    ### it's a relative path ###
+    } else {
+        my $cwd     = (defined $self->{cwd} ? $self->{cwd} : cwd());
+
+        my @dirs = defined $alt
+            ? File::Spec->splitdir( $dirs )         # It's a local-OS path
+            : File::Spec::Unix->splitdir( $dirs );  # it's UNIX-style, likely
+                                                    # straight from the tarball
+
+        ### paths that leave the current directory are not allowed under
+        ### strict mode, so only allow it if a user tells us to do this.
+        if( not defined $alt            and 
+            not $INSECURE_EXTRACT_MODE  and 
+            grep { $_ eq '..' } @dirs
+        ) {
+            $self->_error(
+                q[Entry ']. $entry->full_path .q[' is attempting to leave the ].
+                q[current working directory. Not extracting under SECURE ].
+                q[EXTRACT MODE]
+            );
+            return;
+        }            
+        
+        ### '.' is the directory delimiter, of which the first one has to
+        ### be escaped/changed.
+        map tr/\./_/, @dirs if ON_VMS;        
+
+        my ($cwd_vol,$cwd_dir,$cwd_file) 
+                    = File::Spec->splitpath( $cwd );
+        my @cwd     = File::Spec->splitdir( $cwd_dir );
+        push @cwd, $cwd_file if length $cwd_file;
+
+        ### We need to pass '' as the last elemant to catpath. Craig Berry
+        ### explains why (msgid <p0624083dc311ae541393@[172.16.52.1]>):
+        ### The root problem is that splitpath on UNIX always returns the 
+        ### final path element as a file even if it is a directory, and of
+        ### course there is no way it can know the difference without checking
+        ### against the filesystem, which it is documented as not doing.  When
+        ### you turn around and call catpath, on VMS you have to know which bits
+        ### are directory bits and which bits are file bits.  In this case we
+        ### know the result should be a directory.  I had thought you could omit
+        ### the file argument to catpath in such a case, but apparently on UNIX
+        ### you can't.
+        $dir        = File::Spec->catpath( 
+                            $cwd_vol, File::Spec->catdir( @cwd, @dirs ), '' 
+                        );
+
+        ### catdir() returns undef if the path is longer than 255 chars on VMS
+        unless ( defined $dir ) {
+            $^W && $self->_error( qq[Could not compose a path for '$dirs'\n] );
+            return;
+        }
+
+    }
+
+    if( -e $dir && !-d _ ) {
+        $^W && $self->_error( qq['$dir' exists, but it's not a directory!\n] );
+        return;
+    }
+
+    unless ( -d _ ) {
+        eval { File::Path::mkpath( $dir, 0, 0777 ) };
+        if( $@ ) {
+            $self->_error( qq[Could not create directory '$dir': $@] );
+            return;
+        }
+        
+        ### XXX chown here? that might not be the same as in the archive
+        ### as we're only chown'ing to the owner of the file we're extracting
+        ### not to the owner of the directory itself, which may or may not
+        ### be another entry in the archive
+        ### Answer: no, gnu tar doesn't do it either, it'd be the wrong
+        ### way to go.
+        #if( $CHOWN && CAN_CHOWN ) {
+        #    chown $entry->uid, $entry->gid, $dir or
+        #        $self->_error( qq[Could not set uid/gid on '$dir'] );
+        #}
+    }
+
+    ### we're done if we just needed to create a dir ###
+    return 1 if $entry->is_dir;
+
+    my $full = File::Spec->catfile( $dir, $file );
+
+    if( $entry->is_unknown ) {
+        $self->_error( qq[Unknown file type for file '$full'] );
+        return;
+    }
+
+    if( length $entry->type && $entry->is_file ) {
+        my $fh = IO::File->new;
+        $fh->open( '>' . $full ) or (
+            $self->_error( qq[Could not open file '$full': $!] ),
+            return
+        );
+
+        if( $entry->size ) {
+            binmode $fh;
+            syswrite $fh, $entry->data or (
+                $self->_error( qq[Could not write data to '$full'] ),
+                return
+            );
+        }
+
+        close $fh or (
+            $self->_error( qq[Could not close file '$full'] ),
+            return
+        );
+
+    } else {
+        $self->_make_special_file( $entry, $full ) or return;
+    }
+
+    utime time, $entry->mtime - TIME_OFFSET, $full or
+        $self->_error( qq[Could not update timestamp] );
+
+    if( $CHOWN && CAN_CHOWN ) {
+        chown $entry->uid, $entry->gid, $full or
+            $self->_error( qq[Could not set uid/gid on '$full'] );
+    }
+
+    ### only chmod if we're allowed to, but never chmod symlinks, since they'll
+    ### change the perms on the file they're linking too...
+    if( $CHMOD and not -l $full ) {
+        chmod $entry->mode, $full or
+            $self->_error( qq[Could not chown '$full' to ] . $entry->mode );
+    }
+
+    return 1;
+}
+
+sub _make_special_file {
+    my $self    = shift;
+    my $entry   = shift     or return;
+    my $file    = shift;    return unless defined $file;
+
+    my $err;
+
+    if( $entry->is_symlink ) {
+        my $fail;
+        if( ON_UNIX ) {
+            symlink( $entry->linkname, $file ) or $fail++;
+
+        } else {
+            $self->_extract_special_file_as_plain_file( $entry, $file )
+                or $fail++;
+        }
+
+        $err =  qq[Making symbolink link from '] . $entry->linkname .
+                qq[' to '$file' failed] if $fail;
+
+    } elsif ( $entry->is_hardlink ) {
+        my $fail;
+        if( ON_UNIX ) {
+            link( $entry->linkname, $file ) or $fail++;
+
+        } else {
+            $self->_extract_special_file_as_plain_file( $entry, $file )
+                or $fail++;
+        }
+
+        $err =  qq[Making hard link from '] . $entry->linkname .
+                qq[' to '$file' failed] if $fail;
+
+    } elsif ( $entry->is_fifo ) {
+        ON_UNIX && !system('mknod', $file, 'p') or
+            $err = qq[Making fifo ']. $entry->name .qq[' failed];
+
+    } elsif ( $entry->is_blockdev or $entry->is_chardev ) {
+        my $mode = $entry->is_blockdev ? 'b' : 'c';
+
+        ON_UNIX && !system('mknod', $file, $mode,
+                            $entry->devmajor, $entry->devminor) or
+            $err =  qq[Making block device ']. $entry->name .qq[' (maj=] .
+                    $entry->devmajor . qq[ min=] . $entry->devminor .
+                    qq[) failed.];
+
+    } elsif ( $entry->is_socket ) {
+        ### the original doesn't do anything special for sockets.... ###
+        1;
+    }
+
+    return $err ? $self->_error( $err ) : 1;
+}
+
+### don't know how to make symlinks, let's just extract the file as
+### a plain file
+sub _extract_special_file_as_plain_file {
+    my $self    = shift;
+    my $entry   = shift     or return;
+    my $file    = shift;    return unless defined $file;
+
+    my $err;
+    TRY: {
+        my $orig = $self->_find_entry( $entry->linkname );
+
+        unless( $orig ) {
+            $err =  qq[Could not find file '] . $entry->linkname .
+                    qq[' in memory.];
+            last TRY;
+        }
+
+        ### clone the entry, make it appear as a normal file ###
+        my $clone = $entry->clone;
+        $clone->_downgrade_to_plainfile;
+        $self->_extract_file( $clone, $file ) or last TRY;
+
+        return 1;
+    }
+
+    return $self->_error($err);
+}
+
+=head2 $tar->list_files( [\@properties] )
+
+Returns a list of the names of all the files in the archive.
+
+If C<list_files()> is passed an array reference as its first argument
+it returns a list of hash references containing the requested
+properties of each file.  The following list of properties is
+supported: name, size, mtime (last modified date), mode, uid, gid,
+linkname, uname, gname, devmajor, devminor, prefix.
+
+Passing an array reference containing only one element, 'name', is
+special cased to return a list of names rather than a list of hash
+references, making it equivalent to calling C<list_files> without
+arguments.
+
+=cut
+
+sub list_files {
+    my $self = shift;
+    my $aref = shift || [ ];
+
+    unless( $self->_data ) {
+        $self->read() or return;
+    }
+
+    if( @$aref == 0 or ( @$aref == 1 and $aref->[0] eq 'name' ) ) {
+        return map { $_->full_path } @{$self->_data};
+    } else {
+
+        #my @rv;
+        #for my $obj ( @{$self->_data} ) {
+        #    push @rv, { map { $_ => $obj->$_() } @$aref };
+        #}
+        #return @rv;
+
+        ### this does the same as the above.. just needs a +{ }
+        ### to make sure perl doesn't confuse it for a block
+        return map {    my $o=$_;
+                        +{ map { $_ => $o->$_() } @$aref }
+                    } @{$self->_data};
+    }
+}
+
+sub _find_entry {
+    my $self = shift;
+    my $file = shift;
+
+    unless( defined $file ) {
+        $self->_error( qq[No file specified] );
+        return;
+    }
+
+    ### it's an object already
+    return $file if UNIVERSAL::isa( $file, 'Archive::Tar::File' );
+
+    for my $entry ( @{$self->_data} ) {
+        my $path = $entry->full_path;
+        return $entry if $path eq $file;
+    }
+
+    $self->_error( qq[No such file in archive: '$file'] );
+    return;
+}
+
+=head2 $tar->get_files( [@filenames] )
+
+Returns the C<Archive::Tar::File> objects matching the filenames
+provided. If no filename list was passed, all C<Archive::Tar::File>
+objects in the current Tar object are returned.
+
+Please refer to the C<Archive::Tar::File> documentation on how to
+handle these objects.
+
+=cut
+
+sub get_files {
+    my $self = shift;
+
+    return @{ $self->_data } unless @_;
+
+    my @list;
+    for my $file ( @_ ) {
+        push @list, grep { defined } $self->_find_entry( $file );
+    }
+
+    return @list;
+}
+
+=head2 $tar->get_content( $file )
+
+Return the content of the named file.
+
+=cut
+
+sub get_content {
+    my $self = shift;
+    my $entry = $self->_find_entry( shift ) or return;
+
+    return $entry->data;
+}
+
+=head2 $tar->replace_content( $file, $content )
+
+Make the string $content be the content for the file named $file.
+
+=cut
+
+sub replace_content {
+    my $self = shift;
+    my $entry = $self->_find_entry( shift ) or return;
+
+    return $entry->replace_content( shift );
+}
+
+=head2 $tar->rename( $file, $new_name )
+
+Rename the file of the in-memory archive to $new_name.
+
+Note that you must specify a Unix path for $new_name, since per tar
+standard, all files in the archive must be Unix paths.
+
+Returns true on success and false on failure.
+
+=cut
+
+sub rename {
+    my $self = shift;
+    my $file = shift; return unless defined $file;
+    my $new  = shift; return unless defined $new;
+
+    my $entry = $self->_find_entry( $file ) or return;
+
+    return $entry->rename( $new );
+}
+
+=head2 $tar->remove (@filenamelist)
+
+Removes any entries with names matching any of the given filenames
+from the in-memory archive. Returns a list of C<Archive::Tar::File>
+objects that remain.
+
+=cut
+
+sub remove {
+    my $self = shift;
+    my @list = @_;
+
+    my %seen = map { $_->full_path => $_ } @{$self->_data};
+    delete $seen{ $_ } for @list;
+
+    $self->_data( [values %seen] );
+
+    return values %seen;
+}
+
+=head2 $tar->clear
+
+C<clear> clears the current in-memory archive. This effectively gives
+you a 'blank' object, ready to be filled again. Note that C<clear>
+only has effect on the object, not the underlying tarfile.
+
+=cut
+
+sub clear {
+    my $self = shift or return;
+
+    $self->_data( [] );
+    $self->_file( '' );
+
+    return 1;
+}
+
+
+=head2 $tar->write ( [$file, $compressed, $prefix] )
+
+Write the in-memory archive to disk.  The first argument can either
+be the name of a file or a reference to an already open filehandle (a
+GLOB reference). If the second argument is true, the module will use
+IO::Zlib to write the file in a compressed format.  If IO::Zlib is
+not available, the C<write> method will fail and return.
+
+Note that when you pass in a filehandle, the compression argument
+is ignored, as all files are printed verbatim to your filehandle.
+If you wish to enable compression with filehandles, use an
+C<IO::Zlib> filehandle instead.
+
+Specific levels of compression can be chosen by passing the values 2
+through 9 as the second parameter.
+
+The third argument is an optional prefix. All files will be tucked
+away in the directory you specify as prefix. So if you have files
+'a' and 'b' in your archive, and you specify 'foo' as prefix, they
+will be written to the archive as 'foo/a' and 'foo/b'.
+
+If no arguments are given, C<write> returns the entire formatted
+archive as a string, which could be useful if you'd like to stuff the
+archive into a socket or a pipe to gzip or something.
+
+=cut
+
+sub write {
+    my $self        = shift;
+    my $file        = shift; $file = '' unless defined $file;
+    my $gzip        = shift || 0;
+    my $ext_prefix  = shift; $ext_prefix = '' unless defined $ext_prefix;
+    my $dummy       = '';
+    
+    ### only need a handle if we have a file to print to ###
+    my $handle = length($file)
+                    ? ( $self->_get_handle($file, $gzip, WRITE_ONLY->($gzip) )
+                        or return )
+                    : $HAS_PERLIO    ? do { open my $h, '>', \$dummy; $h }
+                    : $HAS_IO_STRING ? IO::String->new 
+                    : __PACKAGE__->no_string_support();
+
+
+
+    for my $entry ( @{$self->_data} ) {
+        ### entries to be written to the tarfile ###
+        my @write_me;
+
+        ### only now will we change the object to reflect the current state
+        ### of the name and prefix fields -- this needs to be limited to
+        ### write() only!
+        my $clone = $entry->clone;
+
+
+        ### so, if you don't want use to use the prefix, we'll stuff 
+        ### everything in the name field instead
+        if( $DO_NOT_USE_PREFIX ) {
+
+            ### you might have an extended prefix, if so, set it in the clone
+            ### XXX is ::Unix right?
+            $clone->name( length $ext_prefix
+                            ? File::Spec::Unix->catdir( $ext_prefix,
+                                                        $clone->full_path)
+                            : $clone->full_path );
+            $clone->prefix( '' );
+
+        ### otherwise, we'll have to set it properly -- prefix part in the
+        ### prefix and name part in the name field.
+        } else {
+
+            ### split them here, not before!
+            my ($prefix,$name) = $clone->_prefix_and_file( $clone->full_path );
+
+            ### you might have an extended prefix, if so, set it in the clone
+            ### XXX is ::Unix right?
+            $prefix = File::Spec::Unix->catdir( $ext_prefix, $prefix )
+                if length $ext_prefix;
+
+            $clone->prefix( $prefix );
+            $clone->name( $name );
+        }
+
+        ### names are too long, and will get truncated if we don't add a
+        ### '@LongLink' file...
+        my $make_longlink = (   length($clone->name)    > NAME_LENGTH or
+                                length($clone->prefix)  > PREFIX_LENGTH
+                            ) || 0;
+
+        ### perhaps we need to make a longlink file?
+        if( $make_longlink ) {
+            my $longlink = Archive::Tar::File->new(
+                            data => LONGLINK_NAME,
+                            $clone->full_path,
+                            { type => LONGLINK }
+                        );
+
+            unless( $longlink ) {
+                $self->_error(  qq[Could not create 'LongLink' entry for ] .
+                                qq[oversize file '] . $clone->full_path ."'" );
+                return;
+            };
+
+            push @write_me, $longlink;
+        }
+
+        push @write_me, $clone;
+
+        ### write the one, optionally 2 a::t::file objects to the handle
+        for my $clone (@write_me) {
+
+            ### if the file is a symlink, there are 2 options:
+            ### either we leave the symlink intact, but then we don't write any
+            ### data OR we follow the symlink, which means we actually make a
+            ### copy. if we do the latter, we have to change the TYPE of the
+            ### clone to 'FILE'
+            my $link_ok =  $clone->is_symlink && $Archive::Tar::FOLLOW_SYMLINK;
+            my $data_ok = !$clone->is_symlink && $clone->has_content;
+
+            ### downgrade to a 'normal' file if it's a symlink we're going to
+            ### treat as a regular file
+            $clone->_downgrade_to_plainfile if $link_ok;
+
+            ### get the header for this block
+            my $header = $self->_format_tar_entry( $clone );
+            unless( $header ) {
+                $self->_error(q[Could not format header for: ] .
+                                    $clone->full_path );
+                return;
+            }
+
+            unless( print $handle $header ) {
+                $self->_error(q[Could not write header for: ] .
+                                    $clone->full_path);
+                return;
+            }
+
+            if( $link_ok or $data_ok ) {
+                unless( print $handle $clone->data ) {
+                    $self->_error(q[Could not write data for: ] .
+                                    $clone->full_path);
+                    return;
+                }
+
+                ### pad the end of the clone if required ###
+                print $handle TAR_PAD->( $clone->size ) if $clone->size % BLOCK
+            }
+
+        } ### done writing these entries
+    }
+
+    ### write the end markers ###
+    print $handle TAR_END x 2 or
+            return $self->_error( qq[Could not write tar end markers] );
+
+    ### did you want it written to a file, or returned as a string? ###
+    my $rv =  length($file) ? 1
+                        : $HAS_PERLIO ? $dummy
+                        : do { seek $handle, 0, 0; local $/; <$handle> };
+
+    ### make sure to close the handle;
+    close $handle;
+    
+    return $rv;
+}
+
+sub _format_tar_entry {
+    my $self        = shift;
+    my $entry       = shift or return;
+    my $ext_prefix  = shift; $ext_prefix = '' unless defined $ext_prefix;
+    my $no_prefix   = shift || 0;
+
+    my $file    = $entry->name;
+    my $prefix  = $entry->prefix; $prefix = '' unless defined $prefix;
+
+    ### remove the prefix from the file name
+    ### not sure if this is still neeeded --kane
+    ### no it's not -- Archive::Tar::File->_new_from_file will take care of
+    ### this for us. Even worse, this would break if we tried to add a file
+    ### like x/x.
+    #if( length $prefix ) {
+    #    $file =~ s/^$match//;
+    #}
+
+    $prefix = File::Spec::Unix->catdir($ext_prefix, $prefix)
+                if length $ext_prefix;
+
+    ### not sure why this is... ###
+    my $l = PREFIX_LENGTH; # is ambiguous otherwise...
+    substr ($prefix, 0, -$l) = "" if length $prefix >= PREFIX_LENGTH;
+
+    my $f1 = "%06o"; my $f2  = "%11o";
+
+    ### this might be optimizable with a 'changed' flag in the file objects ###
+    my $tar = pack (
+                PACK,
+                $file,
+
+                (map { sprintf( $f1, $entry->$_() ) } qw[mode uid gid]),
+                (map { sprintf( $f2, $entry->$_() ) } qw[size mtime]),
+
+                "",  # checksum field - space padded a bit down
+
+                (map { $entry->$_() }                 qw[type linkname magic]),
+
+                $entry->version || TAR_VERSION,
+
+                (map { $entry->$_() }                 qw[uname gname]),
+                (map { sprintf( $f1, $entry->$_() ) } qw[devmajor devminor]),
+
+                ($no_prefix ? '' : $prefix)
+    );
+
+    ### add the checksum ###
+    substr($tar,148,7) = sprintf("%6o\0", unpack("%16C*",$tar));
+
+    return $tar;
+}
+
+=head2 $tar->add_files( @filenamelist )
+
+Takes a list of filenames and adds them to the in-memory archive.
+
+The path to the file is automatically converted to a Unix like
+equivalent for use in the archive, and, if on MacOS, the file's
+modification time is converted from the MacOS epoch to the Unix epoch.
+So tar archives created on MacOS with B<Archive::Tar> can be read
+both with I<tar> on Unix and applications like I<suntar> or
+I<Stuffit Expander> on MacOS.
+
+Be aware that the file's type/creator and resource fork will be lost,
+which is usually what you want in cross-platform archives.
+
+Returns a list of C<Archive::Tar::File> objects that were just added.
+
+=cut
+
+sub add_files {
+    my $self    = shift;
+    my @files   = @_ or return;
+
+    my @rv;
+    for my $file ( @files ) {
+        unless( -e $file || -l $file ) {
+            $self->_error( qq[No such file: '$file'] );
+            next;
+        }
+
+        my $obj = Archive::Tar::File->new( file => $file );
+        unless( $obj ) {
+            $self->_error( qq[Unable to add file: '$file'] );
+            next;
+        }
+
+        push @rv, $obj;
+    }
+
+    push @{$self->{_data}}, @rv;
+
+    return @rv;
+}
+
+=head2 $tar->add_data ( $filename, $data, [$opthashref] )
+
+Takes a filename, a scalar full of data and optionally a reference to
+a hash with specific options.
+
+Will add a file to the in-memory archive, with name C<$filename> and
+content C<$data>. Specific properties can be set using C<$opthashref>.
+The following list of properties is supported: name, size, mtime
+(last modified date), mode, uid, gid, linkname, uname, gname,
+devmajor, devminor, prefix, type.  (On MacOS, the file's path and
+modification times are converted to Unix equivalents.)
+
+Valid values for the file type are the following constants defined in
+Archive::Tar::Constants:
+
+=over 4
+
+=item FILE
+
+Regular file.
+
+=item HARDLINK
+
+=item SYMLINK
+
+Hard and symbolic ("soft") links; linkname should specify target.
+
+=item CHARDEV
+
+=item BLOCKDEV
+
+Character and block devices. devmajor and devminor should specify the major
+and minor device numbers.
+
+=item DIR
+
+Directory.
+
+=item FIFO
+
+FIFO (named pipe).
+
+=item SOCKET
+
+Socket.
+
+=back
+
+Returns the C<Archive::Tar::File> object that was just added, or
+C<undef> on failure.
+
+=cut
+
+sub add_data {
+    my $self    = shift;
+    my ($file, $data, $opt) = @_;
+
+    my $obj = Archive::Tar::File->new( data => $file, $data, $opt );
+    unless( $obj ) {
+        $self->_error( qq[Unable to add file: '$file'] );
+        return;
+    }
+
+    push @{$self->{_data}}, $obj;
+
+    return $obj;
+}
+
+=head2 $tar->error( [$BOOL] )
+
+Returns the current errorstring (usually, the last error reported).
+If a true value was specified, it will give the C<Carp::longmess>
+equivalent of the error, in effect giving you a stacktrace.
+
+For backwards compatibility, this error is also available as
+C<$Archive::Tar::error> although it is much recommended you use the
+method call instead.
+
+=cut
+
+{
+    $error = '';
+    my $longmess;
+
+    sub _error {
+        my $self    = shift;
+        my $msg     = $error = shift;
+        $longmess   = Carp::longmess($error);
+
+        ### set Archive::Tar::WARN to 0 to disable printing
+        ### of errors
+        if( $WARN ) {
+            carp $DEBUG ? $longmess : $msg;
+        }
+
+        return;
+    }
+
+    sub error {
+        my $self = shift;
+        return shift() ? $longmess : $error;
+    }
+}
+
+=head2 $tar->setcwd( $cwd );
+
+C<Archive::Tar> needs to know the current directory, and it will run
+C<Cwd::cwd()> I<every> time it extracts a I<relative> entry from the 
+tarfile and saves it in the file system. (As of version 1.30, however,
+C<Archive::Tar> will use the speed optimization described below 
+automatically, so it's only relevant if you're using C<extract_file()>).
+
+Since C<Archive::Tar> doesn't change the current directory internally
+while it is extracting the items in a tarball, all calls to C<Cwd::cwd()>
+can be avoided if we can guarantee that the current directory doesn't
+get changed externally.
+
+To use this performance boost, set the current directory via
+
+    use Cwd;
+    $tar->setcwd( cwd() );
+
+once before calling a function like C<extract_file> and
+C<Archive::Tar> will use the current directory setting from then on
+and won't call C<Cwd::cwd()> internally. 
+
+To switch back to the default behaviour, use
+
+    $tar->setcwd( undef );
+
+and C<Archive::Tar> will call C<Cwd::cwd()> internally again.
+
+If you're using C<Archive::Tar>'s C<exract()> method, C<setcwd()> will
+be called for you.
+
+=cut 
+
+sub setcwd {
+    my $self     = shift;
+    my $cwd      = shift;
+
+    $self->{cwd} = $cwd;
+}
+
+=head2 $bool = $tar->has_io_string
+
+Returns true if we currently have C<IO::String> support loaded.
+
+Either C<IO::String> or C<perlio> support is needed to support writing 
+stringified archives. Currently, C<perlio> is the preferred method, if
+available.
+
+See the C<GLOBAL VARIABLES> section to see how to change this preference.
+
+=cut
+
+sub has_io_string { return $HAS_IO_STRING; }
+
+=head2 $bool = $tar->has_perlio
+
+Returns true if we currently have C<perlio> support loaded.
+
+This requires C<perl-5.8> or higher, compiled with C<perlio> 
+
+Either C<IO::String> or C<perlio> support is needed to support writing 
+stringified archives. Currently, C<perlio> is the preferred method, if
+available.
+
+See the C<GLOBAL VARIABLES> section to see how to change this preference.
+
+=cut
+
+sub has_perlio { return $HAS_PERLIO; }
+
+
+=head1 Class Methods
+
+=head2 Archive::Tar->create_archive($file, $compression, @filelist)
+
+Creates a tar file from the list of files provided.  The first
+argument can either be the name of the tar file to create or a
+reference to an open file handle (e.g. a GLOB reference).
+
+The second argument specifies the level of compression to be used, if
+any.  Compression of tar files requires the installation of the
+IO::Zlib module.  Specific levels of compression may be
+requested by passing a value between 2 and 9 as the second argument.
+Any other value evaluating as true will result in the default
+compression level being used.
+
+Note that when you pass in a filehandle, the compression argument
+is ignored, as all files are printed verbatim to your filehandle.
+If you wish to enable compression with filehandles, use an
+C<IO::Zlib> filehandle instead.
+
+The remaining arguments list the files to be included in the tar file.
+These files must all exist. Any files which don't exist or can't be
+read are silently ignored.
+
+If the archive creation fails for any reason, C<create_archive> will
+return false. Please use the C<error> method to find the cause of the
+failure.
+
+Note that this method does not write C<on the fly> as it were; it
+still reads all the files into memory before writing out the archive.
+Consult the FAQ below if this is a problem.
+
+=cut
+
+sub create_archive {
+    my $class = shift;
+
+    my $file    = shift; return unless defined $file;
+    my $gzip    = shift || 0;
+    my @files   = @_;
+
+    unless( @files ) {
+        return $class->_error( qq[Cowardly refusing to create empty archive!] );
+    }
+
+    my $tar = $class->new;
+    $tar->add_files( @files );
+    return $tar->write( $file, $gzip );
+}
+
+=head2 Archive::Tar->list_archive ($file, $compressed, [\@properties])
+
+Returns a list of the names of all the files in the archive.  The
+first argument can either be the name of the tar file to list or a
+reference to an open file handle (e.g. a GLOB reference).
+
+If C<list_archive()> is passed an array reference as its third
+argument it returns a list of hash references containing the requested
+properties of each file.  The following list of properties is
+supported: full_path, name, size, mtime (last modified date), mode, 
+uid, gid, linkname, uname, gname, devmajor, devminor, prefix.
+
+See C<Archive::Tar::File> for details about supported properties.
+
+Passing an array reference containing only one element, 'name', is
+special cased to return a list of names rather than a list of hash
+references.
+
+=cut
+
+sub list_archive {
+    my $class   = shift;
+    my $file    = shift; return unless defined $file;
+    my $gzip    = shift || 0;
+
+    my $tar = $class->new($file, $gzip);
+    return unless $tar;
+
+    return $tar->list_files( @_ );
+}
+
+=head2 Archive::Tar->extract_archive ($file, $gzip)
+
+Extracts the contents of the tar file.  The first argument can either
+be the name of the tar file to create or a reference to an open file
+handle (e.g. a GLOB reference).  All relative paths in the tar file will
+be created underneath the current working directory.
+
+C<extract_archive> will return a list of files it extracted.
+If the archive extraction fails for any reason, C<extract_archive>
+will return false.  Please use the C<error> method to find the cause
+of the failure.
+
+=cut
+
+sub extract_archive {
+    my $class   = shift;
+    my $file    = shift; return unless defined $file;
+    my $gzip    = shift || 0;
+
+    my $tar = $class->new( ) or return;
+
+    return $tar->read( $file, $gzip, { extract => 1 } );
+}
+
+=head2 Archive::Tar->can_handle_compressed_files
+
+A simple checking routine, which will return true if C<Archive::Tar>
+is able to uncompress compressed archives on the fly with C<IO::Zlib>,
+or false if C<IO::Zlib> is not installed.
+
+You can use this as a shortcut to determine whether C<Archive::Tar>
+will do what you think before passing compressed archives to its
+C<read> method.
+
+=cut
+
+sub can_handle_compressed_files { return ZLIB ? 1 : 0 }
+
+sub no_string_support {
+    croak("You have to install IO::String to support writing archives to strings");
+}
+
+1;
+
+__END__
+
+=head1 GLOBAL VARIABLES
+
+=head2 $Archive::Tar::FOLLOW_SYMLINK
+
+Set this variable to C<1> to make C<Archive::Tar> effectively make a
+copy of the file when extracting. Default is C<0>, which
+means the symlink stays intact. Of course, you will have to pack the
+file linked to as well.
+
+This option is checked when you write out the tarfile using C<write>
+or C<create_archive>.
+
+This works just like C</bin/tar>'s C<-h> option.
+
+=head2 $Archive::Tar::CHOWN
+
+By default, C<Archive::Tar> will try to C<chown> your files if it is
+able to. In some cases, this may not be desired. In that case, set
+this variable to C<0> to disable C<chown>-ing, even if it were
+possible.
+
+The default is C<1>.
+
+=head2 $Archive::Tar::CHMOD
+
+By default, C<Archive::Tar> will try to C<chmod> your files to
+whatever mode was specified for the particular file in the archive.
+In some cases, this may not be desired. In that case, set this
+variable to C<0> to disable C<chmod>-ing.
+
+The default is C<1>.
+
+=head2 $Archive::Tar::DO_NOT_USE_PREFIX
+
+By default, C<Archive::Tar> will try to put paths that are over 
+100 characters in the C<prefix> field of your tar header, as
+defined per POSIX-standard. However, some (older) tar programs 
+do not implement this spec. To retain compatibility with these older 
+or non-POSIX compliant versions, you can set the C<$DO_NOT_USE_PREFIX> 
+variable to a true value, and C<Archive::Tar> will use an alternate 
+way of dealing with paths over 100 characters by using the 
+C<GNU Extended Header> feature.
+
+Note that clients who do not support the C<GNU Extended Header>
+feature will not be able to read these archives. Such clients include
+tars on C<Solaris>, C<Irix> and C<AIX>.
+
+The default is C<0>.
+
+=head2 $Archive::Tar::DEBUG
+
+Set this variable to C<1> to always get the C<Carp::longmess> output
+of the warnings, instead of the regular C<carp>. This is the same
+message you would get by doing:
+
+    $tar->error(1);
+
+Defaults to C<0>.
+
+=head2 $Archive::Tar::WARN
+
+Set this variable to C<0> if you do not want any warnings printed.
+Personally I recommend against doing this, but people asked for the
+option. Also, be advised that this is of course not threadsafe.
+
+Defaults to C<1>.
+
+=head2 $Archive::Tar::error
+
+Holds the last reported error. Kept for historical reasons, but its
+use is very much discouraged. Use the C<error()> method instead:
+
+    warn $tar->error unless $tar->extract;
+
+=head2 $Archive::Tar::INSECURE_EXTRACT_MODE
+
+This variable indicates whether C<Archive::Tar> should allow
+files to be extracted outside their current working directory.
+
+Allowing this could have security implications, as a malicious
+tar archive could alter or replace any file the extracting user
+has permissions to. Therefor, the default is to not allow 
+insecure extractions. 
+
+If you trust the archive, or have other reasons to allow the 
+archive to write files outside your current working directory, 
+set this variable to C<true>.
+
+Note that this is a backwards incompatible change from version
+C<1.36> and before.
+
+=head2 $Archive::Tar::HAS_PERLIO
+
+This variable holds a boolean indicating if we currently have 
+C<perlio> support loaded. This will be enabled for any perl
+greater than C<5.8> compiled with C<perlio>. 
+
+If you feel strongly about disabling it, set this variable to
+C<false>. Note that you will then need C<IO::String> installed
+to support writing stringified archives.
+
+Don't change this variable unless you B<really> know what you're
+doing.
+
+=head2 $Archive::Tar::HAS_IO_STRING
+
+This variable holds a boolean indicating if we currently have 
+C<IO::String> support loaded. This will be enabled for any perl
+that has a loadable C<IO::String> module.
+
+If you feel strongly about disabling it, set this variable to
+C<false>. Note that you will then need C<perlio> support from
+your perl to be able to  write stringified archives.
+
+Don't change this variable unless you B<really> know what you're
+doing.
+
+=head1 FAQ
+
+=over 4
+
+=item What's the minimum perl version required to run Archive::Tar?
+
+You will need perl version 5.005_03 or newer.
+
+=item Isn't Archive::Tar slow?
+
+Yes it is. It's pure perl, so it's a lot slower then your C</bin/tar>
+However, it's very portable. If speed is an issue, consider using
+C</bin/tar> instead.
+
+=item Isn't Archive::Tar heavier on memory than /bin/tar?
+
+Yes it is, see previous answer. Since C<Compress::Zlib> and therefore
+C<IO::Zlib> doesn't support C<seek> on their filehandles, there is little
+choice but to read the archive into memory.
+This is ok if you want to do in-memory manipulation of the archive.
+If you just want to extract, use the C<extract_archive> class method
+instead. It will optimize and write to disk immediately.
+
+=item Can't you lazy-load data instead?
+
+No, not easily. See previous question.
+
+=item How much memory will an X kb tar file need?
+
+Probably more than X kb, since it will all be read into memory. If
+this is a problem, and you don't need to do in memory manipulation
+of the archive, consider using C</bin/tar> instead.
+
+=item What do you do with unsupported filetypes in an archive?
+
+C<Unix> has a few filetypes that aren't supported on other platforms,
+like C<Win32>. If we encounter a C<hardlink> or C<symlink> we'll just
+try to make a copy of the original file, rather than throwing an error.
+
+This does require you to read the entire archive in to memory first,
+since otherwise we wouldn't know what data to fill the copy with.
+(This means that you cannot use the class methods on archives that
+have incompatible filetypes and still expect things to work).
+
+For other filetypes, like C<chardevs> and C<blockdevs> we'll warn that
+the extraction of this particular item didn't work.
+
+=item I'm using WinZip, or some other non-POSIX client, and files are not being extracted properly!
+
+By default, C<Archive::Tar> is in a completely POSIX-compatible
+mode, which uses the POSIX-specification of C<tar> to store files.
+For paths greather than 100 characters, this is done using the
+C<POSIX header prefix>. Non-POSIX-compatible clients may not support
+this part of the specification, and may only support the C<GNU Extended
+Header> functionality. To facilitate those clients, you can set the
+C<$Archive::Tar::DO_NOT_USE_PREFIX> variable to C<true>. See the 
+C<GLOBAL VARIABLES> section for details on this variable.
+
+Note that GNU tar earlier than version 1.14 does not cope well with
+the C<POSIX header prefix>. If you use such a version, consider setting
+the C<$Archive::Tar::DO_NOT_USE_PREFIX> variable to C<true>.
+
+=item How do I extract only files that have property X from an archive?
+
+Sometimes, you might not wish to extract a complete archive, just
+the files that are relevant to you, based on some criteria.
+
+You can do this by filtering a list of C<Archive::Tar::File> objects
+based on your criteria. For example, to extract only files that have
+the string C<foo> in their title, you would use:
+
+    $tar->extract( 
+        grep { $_->full_path =~ /foo/ } $tar->get_files
+    ); 
+
+This way, you can filter on any attribute of the files in the archive.
+Consult the C<Archive::Tar::File> documentation on how to use these
+objects.
+
+=item How do I access .tar.Z files?
+
+The C<Archive::Tar> module can optionally use C<Compress::Zlib> (via
+the C<IO::Zlib> module) to access tar files that have been compressed
+with C<gzip>. Unfortunately tar files compressed with the Unix C<compress>
+utility cannot be read by C<Compress::Zlib> and so cannot be directly
+accesses by C<Archive::Tar>.
+
+If the C<uncompress> or C<gunzip> programs are available, you can use
+one of these workarounds to read C<.tar.Z> files from C<Archive::Tar>
+
+Firstly with C<uncompress>
+
+    use Archive::Tar;
+
+    open F, "uncompress -c $filename |";
+    my $tar = Archive::Tar->new(*F);
+    ...
+
+and this with C<gunzip>
+
+    use Archive::Tar;
+
+    open F, "gunzip -c $filename |";
+    my $tar = Archive::Tar->new(*F);
+    ...
+
+Similarly, if the C<compress> program is available, you can use this to
+write a C<.tar.Z> file
+
+    use Archive::Tar;
+    use IO::File;
+
+    my $fh = new IO::File "| compress -c >$filename";
+    my $tar = Archive::Tar->new();
+    ...
+    $tar->write($fh);
+    $fh->close ;
+
+=item How do I handle Unicode strings?
+
+C<Archive::Tar> uses byte semantics for any files it reads from or writes
+to disk. This is not a problem if you only deal with files and never
+look at their content or work solely with byte strings. But if you use
+Unicode strings with character semantics, some additional steps need
+to be taken.
+
+For example, if you add a Unicode string like
+
+    # Problem
+    $tar->add_data('file.txt', "Euro: \x{20AC}");
+
+then there will be a problem later when the tarfile gets written out
+to disk via C<$tar->write()>:
+
+    Wide character in print at .../Archive/Tar.pm line 1014.
+
+The data was added as a Unicode string and when writing it out to disk,
+the C<:utf8> line discipline wasn't set by C<Archive::Tar>, so Perl
+tried to convert the string to ISO-8859 and failed. The written file
+now contains garbage.
+
+For this reason, Unicode strings need to be converted to UTF-8-encoded
+bytestrings before they are handed off to C<add_data()>:
+
+    use Encode;
+    my $data = "Accented character: \x{20AC}";
+    $data = encode('utf8', $data);
+
+    $tar->add_data('file.txt', $data);
+
+A opposite problem occurs if you extract a UTF8-encoded file from a 
+tarball. Using C<get_content()> on the C<Archive::Tar::File> object
+will return its content as a bytestring, not as a Unicode string.
+
+If you want it to be a Unicode string (because you want character
+semantics with operations like regular expression matching), you need
+to decode the UTF8-encoded content and have Perl convert it into 
+a Unicode string:
+
+    use Encode;
+    my $data = $tar->get_content();
+    
+    # Make it a Unicode string
+    $data = decode('utf8', $data);
+
+There is no easy way to provide this functionality in C<Archive::Tar>, 
+because a tarball can contain many files, and each of which could be
+encoded in a different way.
+
+=back
+
+=head1 TODO
+
+=over 4
+
+=item Check if passed in handles are open for read/write
+
+Currently I don't know of any portable pure perl way to do this.
+Suggestions welcome.
+
+=item Allow archives to be passed in as string
+
+Currently, we only allow opened filehandles or filenames, but
+not strings. The internals would need some reworking to facilitate
+stringified archives.
+
+=item Facilitate processing an opened filehandle of a compressed archive
+
+Currently, we only support this if the filehandle is an IO::Zlib object.
+Environments, like apache, will present you with an opened filehandle
+to an uploaded file, which might be a compressed archive.
+
+=back
+
+=head1 SEE ALSO
+
+=over 4
+
+=item The GNU tar specification
+
+C<http://www.gnu.org/software/tar/manual/tar.html>
+
+=item The PAX format specication
+
+The specifcation which tar derives from; C< http://www.opengroup.org/onlinepubs/007904975/utilities/pax.html>
+
+=item A comparison of GNU and POSIX tar standards; C<http://www.delorie.com/gnu/docs/tar/tar_114.html>
+
+=item GNU tar intends to switch to POSIX compatibility
+
+GNU Tar authors have expressed their intention to become completely
+POSIX-compatible; C<http://www.gnu.org/software/tar/manual/html_node/Formats.html>
+
+=item A Comparison between various tar implementations
+
+Lists known issues and incompatibilities; C<http://gd.tuwien.ac.at/utils/archivers/star/README.otherbugs>
+
+=back
+
+=head1 AUTHOR
+
+This module by Jos Boumans E<lt>kane@cpan.orgE<gt>.
+
+Please reports bugs to E<lt>bug-archive-tar@rt.cpan.orgE<gt>.
+
+=head1 ACKNOWLEDGEMENTS
+
+Thanks to Sean Burke, Chris Nandor, Chip Salzenberg, Tim Heaney and
+especially Andrew Savige for their help and suggestions.
+
+=head1 COPYRIGHT
+
+This module is copyright (c) 2002 - 2007 Jos Boumans 
+E<lt>kane@cpan.orgE<gt>. All rights reserved.
+
+This library is free software; you may redistribute and/or modify 
+it under the same terms as Perl itself.
+
+=cut
diff --git a/extlib/Archive/Tar/Constant.pm b/extlib/Archive/Tar/Constant.pm
new file mode 100644 (file)
index 0000000..00416d5
--- /dev/null
@@ -0,0 +1,78 @@
+package Archive::Tar::Constant;
+
+BEGIN {
+    require Exporter;
+    $VERSION= '0.02';
+    @ISA    = qw[Exporter];
+    @EXPORT = qw[
+                FILE HARDLINK SYMLINK CHARDEV BLOCKDEV DIR FIFO SOCKET UNKNOWN
+                BUFFER HEAD READ_ONLY WRITE_ONLY UNPACK PACK TIME_OFFSET ZLIB
+                BLOCK_SIZE TAR_PAD TAR_END ON_UNIX BLOCK CAN_READLINK MAGIC 
+                TAR_VERSION UNAME GNAME CAN_CHOWN MODE CHECK_SUM UID GID 
+                GZIP_MAGIC_NUM MODE_READ LONGLINK LONGLINK_NAME PREFIX_LENGTH
+                LABEL NAME_LENGTH STRIP_MODE ON_VMS
+            ];
+
+    require Time::Local if $^O eq "MacOS";
+}
+
+use constant FILE           => 0;
+use constant HARDLINK       => 1;
+use constant SYMLINK        => 2;
+use constant CHARDEV        => 3;
+use constant BLOCKDEV       => 4;
+use constant DIR            => 5;
+use constant FIFO           => 6;
+use constant SOCKET         => 8;
+use constant UNKNOWN        => 9;
+use constant LONGLINK       => 'L';
+use constant LABEL          => 'V';
+
+use constant BUFFER         => 4096;
+use constant HEAD           => 512;
+use constant BLOCK          => 512;
+
+use constant BLOCK_SIZE     => sub { my $n = int($_[0]/BLOCK); $n++ if $_[0] % BLOCK; $n * BLOCK };
+use constant TAR_PAD        => sub { my $x = shift || return; return "\0" x (BLOCK - ($x % BLOCK) ) };
+use constant TAR_END        => "\0" x BLOCK;
+
+use constant READ_ONLY      => sub { shift() ? 'rb' : 'r' };
+use constant WRITE_ONLY     => sub { $_[0] ? 'wb' . shift : 'w' };
+use constant MODE_READ      => sub { $_[0] =~ /^r/ ? 1 : 0 };
+
+# Pointless assignment to make -w shut up
+my $getpwuid; $getpwuid = 'unknown' unless eval { my $f = getpwuid (0); };
+my $getgrgid; $getgrgid = 'unknown' unless eval { my $f = getgrgid (0); };
+use constant UNAME          => sub { $getpwuid || scalar getpwuid( shift() ) || '' };
+use constant GNAME          => sub { $getgrgid || scalar getgrgid( shift() ) || '' };
+use constant UID            => $>;
+use constant GID            => (split ' ', $) )[0];
+
+use constant MODE           => do { 0666 & (0777 & ~umask) };
+use constant STRIP_MODE     => sub { shift() & 0777 };
+use constant CHECK_SUM      => "      ";
+
+use constant UNPACK         => 'A100 A8 A8 A8 A12 A12 A8 A1 A100 A6 A2 A32 A32 A8 A8 A155 x12';
+use constant PACK           => 'a100 a8 a8 a8 a12 a12 A8 a1 a100 a6 a2 a32 a32 a8 a8 a155 x12';
+use constant NAME_LENGTH    => 100;
+use constant PREFIX_LENGTH  => 155;
+
+use constant TIME_OFFSET    => ($^O eq "MacOS") ? Time::Local::timelocal(0,0,0,1,0,70) : 0;    
+use constant MAGIC          => "ustar";
+use constant TAR_VERSION    => "00";
+use constant LONGLINK_NAME  => '././@LongLink';
+
+                            ### allow ZLIB to be turned off using ENV
+                            ### DEBUG only
+use constant ZLIB           => do { !$ENV{'PERL5_AT_NO_ZLIB'} and
+                                        eval { require IO::Zlib };
+                                    $ENV{'PERL5_AT_NO_ZLIB'} || $@ ? 0 : 1 };
+                                    
+use constant GZIP_MAGIC_NUM => qr/^(?:\037\213|\037\235)/;
+
+use constant CAN_CHOWN      => do { ($> == 0 and $^O ne "MacOS" and $^O ne "MSWin32") };
+use constant CAN_READLINK   => ($^O ne 'MSWin32' and $^O !~ /RISC(?:[ _])?OS/i and $^O ne 'VMS');
+use constant ON_UNIX        => ($^O ne 'MSWin32' and $^O ne 'MacOS' and $^O ne 'VMS');
+use constant ON_VMS         => $^O eq 'VMS'; 
+
+1;
diff --git a/extlib/Archive/Tar/File.pm b/extlib/Archive/Tar/File.pm
new file mode 100644 (file)
index 0000000..8c96577
--- /dev/null
@@ -0,0 +1,606 @@
+package Archive::Tar::File;
+use strict;
+
+use IO::File;
+use File::Spec::Unix    ();
+use File::Spec          ();
+use File::Basename      ();
+
+use Archive::Tar::Constant;
+
+use vars qw[@ISA $VERSION];
+@ISA        = qw[Archive::Tar];
+$VERSION    = '0.02';
+
+### set value to 1 to oct() it during the unpack ###
+my $tmpl = [
+        name        => 0,   # string
+        mode        => 1,   # octal
+        uid         => 1,   # octal
+        gid         => 1,   # octal
+        size        => 1,   # octal
+        mtime       => 1,   # octal
+        chksum      => 1,   # octal
+        type        => 0,   # character
+        linkname    => 0,   # string
+        magic       => 0,   # string
+        version     => 0,   # 2 bytes
+        uname       => 0,   # string
+        gname       => 0,   # string
+        devmajor    => 1,   # octal
+        devminor    => 1,   # octal
+        prefix      => 0,
+
+### end UNPACK items ###
+        raw         => 0,   # the raw data chunk
+        data        => 0,   # the data associated with the file --
+                            # This  might be very memory intensive
+];
+
+### install get/set accessors for this object.
+for ( my $i=0; $i<scalar @$tmpl ; $i+=2 ) {
+    my $key = $tmpl->[$i];
+    no strict 'refs';
+    *{__PACKAGE__."::$key"} = sub {
+        my $self = shift;
+        $self->{$key} = $_[0] if @_;
+
+        ### just in case the key is not there or undef or something ###
+        {   local $^W = 0;
+            return $self->{$key};
+        }
+    }
+}
+
+=head1 NAME
+
+Archive::Tar::File - a subclass for in-memory extracted file from Archive::Tar
+
+=head1 SYNOPSIS
+
+    my @items = $tar->get_files;
+
+    print $_->name, ' ', $_->size, "\n" for @items;
+
+    print $object->get_content;
+    $object->replace_content('new content');
+
+    $object->rename( 'new/full/path/to/file.c' );
+
+=head1 DESCRIPTION
+
+Archive::Tar::Files provides a neat little object layer for in-memory
+extracted files. It's mostly used internally in Archive::Tar to tidy
+up the code, but there's no reason users shouldn't use this API as
+well.
+
+=head2 Accessors
+
+A lot of the methods in this package are accessors to the various
+fields in the tar header:
+
+=over 4
+
+=item name
+
+The file's name
+
+=item mode
+
+The file's mode
+
+=item uid
+
+The user id owning the file
+
+=item gid
+
+The group id owning the file
+
+=item size
+
+File size in bytes
+
+=item mtime
+
+Modification time. Adjusted to mac-time on MacOS if required
+
+=item chksum
+
+Checksum field for the tar header
+
+=item type
+
+File type -- numeric, but comparable to exported constants -- see
+Archive::Tar's documentation
+
+=item linkname
+
+If the file is a symlink, the file it's pointing to
+
+=item magic
+
+Tar magic string -- not useful for most users
+
+=item version
+
+Tar version string -- not useful for most users
+
+=item uname
+
+The user name that owns the file
+
+=item gname
+
+The group name that owns the file
+
+=item devmajor
+
+Device major number in case of a special file
+
+=item devminor
+
+Device minor number in case of a special file
+
+=item prefix
+
+Any directory to prefix to the extraction path, if any
+
+=item raw
+
+Raw tar header -- not useful for most users
+
+=back
+
+=head1 Methods
+
+=head2 new( file => $path )
+
+Returns a new Archive::Tar::File object from an existing file.
+
+Returns undef on failure.
+
+=head2 new( data => $path, $data, $opt )
+
+Returns a new Archive::Tar::File object from data.
+
+C<$path> defines the file name (which need not exist), C<$data> the
+file contents, and C<$opt> is a reference to a hash of attributes
+which may be used to override the default attributes (fields in the
+tar header), which are described above in the Accessors section.
+
+Returns undef on failure.
+
+=head2 new( chunk => $chunk )
+
+Returns a new Archive::Tar::File object from a raw 512-byte tar
+archive chunk.
+
+Returns undef on failure.
+
+=cut
+
+sub new {
+    my $class   = shift;
+    my $what    = shift;
+
+    my $obj =   ($what eq 'chunk') ? __PACKAGE__->_new_from_chunk( @_ ) :
+                ($what eq 'file' ) ? __PACKAGE__->_new_from_file( @_ ) :
+                ($what eq 'data' ) ? __PACKAGE__->_new_from_data( @_ ) :
+                undef;
+
+    return $obj;
+}
+
+### copies the data, creates a clone ###
+sub clone {
+    my $self = shift;
+    return bless { %$self }, ref $self;
+}
+
+sub _new_from_chunk {
+    my $class = shift;
+    my $chunk = shift or return;    # 512 bytes of tar header
+    my %hash  = @_;
+
+    ### filter any arguments on defined-ness of values.
+    ### this allows overriding from what the tar-header is saying
+    ### about this tar-entry. Particularly useful for @LongLink files
+    my %args  = map { $_ => $hash{$_} } grep { defined $hash{$_} } keys %hash;
+
+    ### makes it start at 0 actually... :) ###
+    my $i = -1;
+    my %entry = map {
+        $tmpl->[++$i] => $tmpl->[++$i] ? oct $_ : $_
+    } map { /^([^\0]*)/ } unpack( UNPACK, $chunk );
+
+    my $obj = bless { %entry, %args }, $class;
+
+       ### magic is a filetype string.. it should have something like 'ustar' or
+       ### something similar... if the chunk is garbage, skip it
+       return unless $obj->magic !~ /\W/;
+
+    ### store the original chunk ###
+    $obj->raw( $chunk );
+
+    $obj->type(FILE) if ( (!length $obj->type) or ($obj->type =~ /\W/) );
+    $obj->type(DIR)  if ( ($obj->is_file) && ($obj->name =~ m|/$|) );
+
+
+    return $obj;
+
+}
+
+sub _new_from_file {
+    my $class       = shift;
+    my $path        = shift;        
+    
+    ### path has to at least exist
+    return unless defined $path;
+    
+    my $type        = __PACKAGE__->_filetype($path);
+    my $data        = '';
+
+    READ: { 
+        unless ($type == DIR ) {
+            my $fh = IO::File->new;
+        
+            unless( $fh->open($path) ) {
+                ### dangling symlinks are fine, stop reading but continue
+                ### creating the object
+                last READ if $type == SYMLINK;
+                
+                ### otherwise, return from this function --
+                ### anything that's *not* a symlink should be
+                ### resolvable
+                return;
+            }
+
+            ### binmode needed to read files properly on win32 ###
+            binmode $fh;
+            $data = do { local $/; <$fh> };
+            close $fh;
+        }
+    }
+
+    my @items       = qw[mode uid gid size mtime];
+    my %hash        = map { shift(@items), $_ } (lstat $path)[2,4,5,7,9];
+
+    ### you *must* set size == 0 on symlinks, or the next entry will be
+    ### though of as the contents of the symlink, which is wrong.
+    ### this fixes bug #7937
+    $hash{size}     = 0 if ($type == DIR or $type == SYMLINK);
+    $hash{mtime}    -= TIME_OFFSET;
+
+    ### strip the high bits off the mode, which we don't need to store
+    $hash{mode}     = STRIP_MODE->( $hash{mode} );
+
+
+    ### probably requires some file path munging here ... ###
+    ### name and prefix are set later
+    my $obj = {
+        %hash,
+        name        => '',
+        chksum      => CHECK_SUM,
+        type        => $type,
+        linkname    => ($type == SYMLINK and CAN_READLINK)
+                            ? readlink $path
+                            : '',
+        magic       => MAGIC,
+        version     => TAR_VERSION,
+        uname       => UNAME->( $hash{uid} ),
+        gname       => GNAME->( $hash{gid} ),
+        devmajor    => 0,   # not handled
+        devminor    => 0,   # not handled
+        prefix      => '',
+        data        => $data,
+    };
+
+    bless $obj, $class;
+
+    ### fix up the prefix and file from the path
+    my($prefix,$file) = $obj->_prefix_and_file( $path );
+    $obj->prefix( $prefix );
+    $obj->name( $file );
+
+    return $obj;
+}
+
+sub _new_from_data {
+    my $class   = shift;
+    my $path    = shift;    return unless defined $path;
+    my $data    = shift;    return unless defined $data;
+    my $opt     = shift;
+
+    my $obj = {
+        data        => $data,
+        name        => '',
+        mode        => MODE,
+        uid         => UID,
+        gid         => GID,
+        size        => length $data,
+        mtime       => time - TIME_OFFSET,
+        chksum      => CHECK_SUM,
+        type        => FILE,
+        linkname    => '',
+        magic       => MAGIC,
+        version     => TAR_VERSION,
+        uname       => UNAME->( UID ),
+        gname       => GNAME->( GID ),
+        devminor    => 0,
+        devmajor    => 0,
+        prefix      => '',
+    };
+
+    ### overwrite with user options, if provided ###
+    if( $opt and ref $opt eq 'HASH' ) {
+        for my $key ( keys %$opt ) {
+
+            ### don't write bogus options ###
+            next unless exists $obj->{$key};
+            $obj->{$key} = $opt->{$key};
+        }
+    }
+
+    bless $obj, $class;
+
+    ### fix up the prefix and file from the path
+    my($prefix,$file) = $obj->_prefix_and_file( $path );
+    $obj->prefix( $prefix );
+    $obj->name( $file );
+
+    return $obj;
+}
+
+sub _prefix_and_file {
+    my $self = shift;
+    my $path = shift;
+
+    my ($vol, $dirs, $file) = File::Spec->splitpath( $path, $self->is_dir );
+    my @dirs = File::Spec->splitdir( $dirs );
+
+    ### so sometimes the last element is '' -- probably when trailing
+    ### dir slashes are encountered... this is is of course pointless,
+    ### so remove it
+    pop @dirs while @dirs and not length $dirs[-1];
+
+    ### if it's a directory, then $file might be empty
+    $file = pop @dirs if $self->is_dir and not length $file;
+
+    my $prefix = File::Spec::Unix->catdir(
+                        grep { length } $vol, @dirs
+                    );
+    return( $prefix, $file );
+}
+
+sub _filetype {
+    my $self = shift;
+    my $file = shift;
+    
+    return unless defined $file;
+
+    return SYMLINK  if (-l $file);     # Symlink
+
+    return FILE     if (-f _);         # Plain file
+
+    return DIR      if (-d _);         # Directory
+
+    return FIFO     if (-p _);         # Named pipe
+
+    return SOCKET   if (-S _);         # Socket
+
+    return BLOCKDEV if (-b _);         # Block special
+
+    return CHARDEV  if (-c _);         # Character special
+
+    ### shouldn't happen, this is when making archives, not reading ###
+    return LONGLINK if ( $file eq LONGLINK_NAME );
+
+    return UNKNOWN;                        # Something else (like what?)
+
+}
+
+### this method 'downgrades' a file to plain file -- this is used for
+### symlinks when FOLLOW_SYMLINKS is true.
+sub _downgrade_to_plainfile {
+    my $entry = shift;
+    $entry->type( FILE );
+    $entry->mode( MODE );
+    $entry->linkname('');
+
+    return 1;
+}
+
+=head2 full_path
+
+Returns the full path from the tar header; this is basically a
+concatenation of the C<prefix> and C<name> fields.
+
+=cut
+
+sub full_path {
+    my $self = shift;
+
+    ### if prefix field is emtpy
+    return $self->name unless defined $self->prefix and length $self->prefix;
+
+    ### or otherwise, catfile'd
+    return File::Spec::Unix->catfile( $self->prefix, $self->name );
+}
+
+
+=head2 validate
+
+Done by Archive::Tar internally when reading the tar file:
+validate the header against the checksum to ensure integer tar file.
+
+Returns true on success, false on failure
+
+=cut
+
+sub validate {
+    my $self = shift;
+
+    my $raw = $self->raw;
+
+    ### don't know why this one is different from the one we /write/ ###
+    substr ($raw, 148, 8) = "        ";
+       return unpack ("%16C*", $raw) == $self->chksum ? 1 : 0;
+}
+
+=head2 has_content
+
+Returns a boolean to indicate whether the current object has content.
+Some special files like directories and so on never will have any
+content. This method is mainly to make sure you don't get warnings
+for using uninitialized values when looking at an object's content.
+
+=cut
+
+sub has_content {
+    my $self = shift;
+    return defined $self->data() && length $self->data() ? 1 : 0;
+}
+
+=head2 get_content
+
+Returns the current content for the in-memory file
+
+=cut
+
+sub get_content {
+    my $self = shift;
+    $self->data( );
+}
+
+=head2 get_content_by_ref
+
+Returns the current content for the in-memory file as a scalar
+reference. Normal users won't need this, but it will save memory if
+you are dealing with very large data files in your tar archive, since
+it will pass the contents by reference, rather than make a copy of it
+first.
+
+=cut
+
+sub get_content_by_ref {
+    my $self = shift;
+
+    return \$self->{data};
+}
+
+=head2 replace_content( $content )
+
+Replace the current content of the file with the new content. This
+only affects the in-memory archive, not the on-disk version until
+you write it.
+
+Returns true on success, false on failure.
+
+=cut
+
+sub replace_content {
+    my $self = shift;
+    my $data = shift || '';
+
+    $self->data( $data );
+    $self->size( length $data );
+    return 1;
+}
+
+=head2 rename( $new_name )
+
+Rename the current file to $new_name.
+
+Note that you must specify a Unix path for $new_name, since per tar
+standard, all files in the archive must be Unix paths.
+
+Returns true on success and false on failure.
+
+=cut
+
+sub rename {
+    my $self = shift;
+    my $path = shift;
+    
+    return unless defined $path;
+
+    my ($prefix,$file) = $self->_prefix_and_file( $path );
+
+    $self->name( $file );
+    $self->prefix( $prefix );
+
+       return 1;
+}
+
+=head1 Convenience methods
+
+To quickly check the type of a C<Archive::Tar::File> object, you can
+use the following methods:
+
+=over 4
+
+=item is_file
+
+Returns true if the file is of type C<file>
+
+=item is_dir
+
+Returns true if the file is of type C<dir>
+
+=item is_hardlink
+
+Returns true if the file is of type C<hardlink>
+
+=item is_symlink
+
+Returns true if the file is of type C<symlink>
+
+=item is_chardev
+
+Returns true if the file is of type C<chardev>
+
+=item is_blockdev
+
+Returns true if the file is of type C<blockdev>
+
+=item is_fifo
+
+Returns true if the file is of type C<fifo>
+
+=item is_socket
+
+Returns true if the file is of type C<socket>
+
+=item is_longlink
+
+Returns true if the file is of type C<LongLink>.
+Should not happen after a successful C<read>.
+
+=item is_label
+
+Returns true if the file is of type C<Label>.
+Should not happen after a successful C<read>.
+
+=item is_unknown
+
+Returns true if the file type is C<unknown>
+
+=back
+
+=cut
+
+#stupid perl5.5.3 needs to warn if it's not numeric
+sub is_file     { local $^W;    FILE      == $_[0]->type }
+sub is_dir      { local $^W;    DIR       == $_[0]->type }
+sub is_hardlink { local $^W;    HARDLINK  == $_[0]->type }
+sub is_symlink  { local $^W;    SYMLINK   == $_[0]->type }
+sub is_chardev  { local $^W;    CHARDEV   == $_[0]->type }
+sub is_blockdev { local $^W;    BLOCKDEV  == $_[0]->type }
+sub is_fifo     { local $^W;    FIFO      == $_[0]->type }
+sub is_socket   { local $^W;    SOCKET    == $_[0]->type }
+sub is_unknown  { local $^W;    UNKNOWN   == $_[0]->type }
+sub is_longlink { local $^W;    LONGLINK  eq $_[0]->type }
+sub is_label    { local $^W;    LABEL     eq $_[0]->type }
+
+1;
diff --git a/extlib/Digest/Perl/.exists b/extlib/Digest/Perl/.exists
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/extlib/Digest/Perl/MD5.pm b/extlib/Digest/Perl/MD5.pm
new file mode 100755 (executable)
index 0000000..e81877c
--- /dev/null
@@ -0,0 +1,481 @@
+#! /usr/bin/false
+#
+# $Id: MD5.pm,v 1.23 2004/08/27 20:28:25 lackas Exp $
+#
+
+package Digest::Perl::MD5;
+use strict;
+use integer;
+use Exporter;
+use vars qw($VERSION @ISA @EXPORTER @EXPORT_OK);
+
+@EXPORT_OK = qw(md5 md5_hex md5_base64);
+
+@ISA = 'Exporter';
+$VERSION = '1.8';
+
+# I-Vektor
+sub A() { 0x67_45_23_01 }
+sub B() { 0xef_cd_ab_89 }
+sub C() { 0x98_ba_dc_fe }
+sub D() { 0x10_32_54_76 }
+
+# for internal use
+sub MAX() { 0xFFFFFFFF }
+
+# padd a message to a multiple of 64
+sub padding {
+    my $l = length (my $msg = shift() . chr(128));    
+    $msg .= "\0" x (($l%64<=56?56:120)-$l%64);
+    $l = ($l-1)*8;
+    $msg .= pack 'VV', $l & MAX , ($l >> 16 >> 16);
+}
+
+
+sub rotate_left($$) {
+       #$_[0] << $_[1] | $_[0] >> (32 - $_[1]);
+       #my $right = $_[0] >> (32 - $_[1]);
+       #my $rmask = (1 << $_[1]) - 1;
+       ($_[0] << $_[1]) | (( $_[0] >> (32 - $_[1])  )  & ((1 << $_[1]) - 1));
+       #$_[0] << $_[1] | (($_[0]>> (32 - $_[1])) & (1 << (32 - $_[1])) - 1);
+}
+
+sub gen_code {
+  # Discard upper 32 bits on 64 bit archs.
+  my $MSK = ((1 << 16) << 16) ? ' & ' . MAX : '';
+#      FF => "X0=rotate_left(((X1&X2)|(~X1&X3))+X0+X4+X6$MSK,X5)+X1$MSK;",
+#      GG => "X0=rotate_left(((X1&X3)|(X2&(~X3)))+X0+X4+X6$MSK,X5)+X1$MSK;",
+  my %f = (
+       FF => "X0=rotate_left((X3^(X1&(X2^X3)))+X0+X4+X6$MSK,X5)+X1$MSK;",
+       GG => "X0=rotate_left((X2^(X3&(X1^X2)))+X0+X4+X6$MSK,X5)+X1$MSK;",
+       HH => "X0=rotate_left((X1^X2^X3)+X0+X4+X6$MSK,X5)+X1$MSK;",
+       II => "X0=rotate_left((X2^(X1|(~X3)))+X0+X4+X6$MSK,X5)+X1$MSK;",
+  );
+  #unless ( (1 << 16) << 16) { %f = %{$CODES{'32bit'}} }
+  #else { %f = %{$CODES{'64bit'}} }
+
+  my %s = (  # shift lengths
+       S11 => 7, S12 => 12, S13 => 17, S14 => 22, S21 => 5, S22 => 9, S23 => 14,
+       S24 => 20, S31 => 4, S32 => 11, S33 => 16, S34 => 23, S41 => 6, S42 => 10,
+       S43 => 15, S44 => 21
+  );
+
+  my $insert = "\n";
+  while(<DATA>) {
+       chomp;
+       next unless /^[FGHI]/;
+       my ($func,@x) = split /,/;
+       my $c = $f{$func};
+       $c =~ s/X(\d)/$x[$1]/g;
+       $c =~ s/(S\d{2})/$s{$1}/;
+       $c =~ s/^(.*)=rotate_left\((.*),(.*)\)\+(.*)$//;
+
+       my $su = 32 - $3;
+       my $sh = (1 << $3) - 1;
+
+       $c = "$1=(((\$r=$2)<<$3)|((\$r>>$su)&$sh))+$4";
+
+       #my $rotate = "(($2 << $3) || (($2 >> (32 - $3)) & (1 << $2) - 1)))"; 
+       # $c = "\$r = $2;
+       # $1 = ((\$r << $3) | ((\$r >> (32 - $3))  & ((1 << $3) - 1))) + $4";
+       $insert .= "\t$c\n";
+  }
+  close DATA;
+  
+  my $dump = '
+  sub round {
+       my ($a,$b,$c,$d) = @_[0 .. 3];
+       my $r;' . $insert . '
+       $_[0]+$a' . $MSK . ', $_[1]+$b ' . $MSK . 
+        ', $_[2]+$c' . $MSK . ', $_[3]+$d' . $MSK . ';
+  }';
+  eval $dump;
+  # print "$dump\n";
+  # exit 0;
+}
+
+gen_code();
+
+#########################################
+# Private output converter functions:
+sub _encode_hex { unpack 'H*', $_[0] }
+sub _encode_base64 {
+       my $res;
+       while ($_[0] =~ /(.{1,45})/gs) {
+               $res .= substr pack('u', $1), 1;
+               chop $res;
+       }
+       $res =~ tr|` -_|AA-Za-z0-9+/|;#`
+       chop $res; chop $res;
+       $res
+}
+
+#########################################
+# OOP interface:
+sub new {
+       my $proto = shift;
+       my $class = ref $proto || $proto;
+       my $self = {};
+       bless $self, $class;
+       $self->reset();
+       $self
+}
+
+sub reset {
+       my $self = shift;
+       delete $self->{_data};
+       $self->{_state} = [A,B,C,D];
+       $self->{_length} = 0;
+       $self
+}
+
+sub add {
+       my $self = shift;
+       $self->{_data} .= join '', @_ if @_;
+       my ($i,$c);
+       for $i (0 .. (length $self->{_data})/64-1) {
+               my @X = unpack 'V16', substr $self->{_data}, $i*64, 64;
+               @{$self->{_state}} = round(@{$self->{_state}},@X);
+               ++$c;
+       }
+       if ($c) {
+               substr ($self->{_data}, 0, $c*64) = '';
+               $self->{_length} += $c*64;
+       }
+       $self
+}
+
+sub finalize {
+       my $self = shift;
+       $self->{_data} .= chr(128);
+    my $l = $self->{_length} + length $self->{_data};
+    $self->{_data} .= "\0" x (($l%64<=56?56:120)-$l%64);
+    $l = ($l-1)*8;
+    $self->{_data} .= pack 'VV', $l & MAX , ($l >> 16 >> 16);
+       $self->add();
+       $self
+}
+
+sub addfile {
+       my ($self,$fh) = @_;
+       if (!ref($fh) && ref(\$fh) ne "GLOB") {
+           require Symbol;
+           $fh = Symbol::qualify($fh, scalar caller);
+       }
+       # $self->{_data} .= do{local$/;<$fh>};
+       my $read = 0;
+       my $buffer = '';
+       $self->add($buffer) while $read = read $fh, $buffer, 8192;
+       die __PACKAGE__, " read failed: $!" unless defined $read;
+       $self
+}
+
+sub add_bits {
+       my $self = shift;
+       return $self->add( pack 'B*', shift ) if @_ == 1;
+       my ($b,$n) = @_;
+       die __PACKAGE__, " Invalid number of bits\n" if $n%8;
+       $self->add( substr $b, 0, $n/8 )
+}
+
+sub digest {
+       my $self = shift;
+       $self->finalize();
+       my $res = pack 'V4', @{$self->{_state}};
+       $self->reset();
+       $res
+}
+
+sub hexdigest {
+       _encode_hex($_[0]->digest)
+}
+
+sub b64digest {
+       _encode_base64($_[0]->digest)
+}
+
+sub clone {
+       my $self = shift;
+       my $clone = { 
+               _state => [@{$self->{_state}}],
+               _length => $self->{_length},
+               _data => $self->{_data}
+       };
+       bless $clone, ref $self || $self;
+}
+
+#########################################
+# Procedural interface:
+sub md5 {
+       my $message = padding(join'',@_);
+       my ($a,$b,$c,$d) = (A,B,C,D);
+       my $i;
+       for $i (0 .. (length $message)/64-1) {
+               my @X = unpack 'V16', substr $message,$i*64,64; 
+               ($a,$b,$c,$d) = round($a,$b,$c,$d,@X);
+       }
+       pack 'V4',$a,$b,$c,$d;
+}
+sub md5_hex { _encode_hex &md5 } 
+sub md5_base64 { _encode_base64 &md5 }
+
+
+1;
+
+=head1 NAME
+
+Digest::MD5::Perl - Perl implementation of Ron Rivests MD5 Algorithm
+
+=head1 DISCLAIMER
+
+This is B<not> an interface (like C<Digest::MD5>) but a Perl implementation of MD5.
+It is written in perl only and because of this it is slow but it works without C-Code.
+You should use C<Digest::MD5> instead of this module if it is available.
+This module is only usefull for
+
+=over 4
+
+=item
+
+computers where you cannot install C<Digest::MD5> (e.g. lack of a C-Compiler)
+
+=item
+
+encrypting only small amounts of data (less than one million bytes). I use it to
+hash passwords.
+
+=item
+
+educational purposes
+
+=back
+
+=head1 SYNOPSIS
+
+ # Functional style
+ use Digest::MD5  qw(md5 md5_hex md5_base64);
+
+ $hash = md5 $data;
+ $hash = md5_hex $data;
+ $hash = md5_base64 $data;
+    
+
+ # OO style
+ use Digest::MD5;
+
+ $ctx = Digest::MD5->new;
+
+ $ctx->add($data);
+ $ctx->addfile(*FILE);
+
+ $digest = $ctx->digest;
+ $digest = $ctx->hexdigest;
+ $digest = $ctx->b64digest;
+
+=head1 DESCRIPTION
+
+This modules has the same interface as the much faster C<Digest::MD5>. So you can
+easily exchange them, e.g.
+
+       BEGIN {
+         eval {
+           require Digest::MD5;
+           import Digest::MD5 'md5_hex'
+         };
+         if ($@) { # ups, no Digest::MD5
+           require Digest::Perl::MD5;
+           import Digest::Perl::MD5 'md5_hex'
+         }             
+       }
+
+If the C<Digest::MD5> module is available it is used and if not you take
+C<Digest::Perl::MD5>.
+
+You can also install the Perl part of Digest::MD5 together with Digest::Perl::MD5
+and use Digest::MD5 as normal, it falls back to Digest::Perl::MD5 if it
+cannot load its object files.
+
+For a detailed Documentation see the C<Digest::MD5> module.
+
+=head1 EXAMPLES
+
+The simplest way to use this library is to import the md5_hex()
+function (or one of its cousins):
+
+    use Digest::Perl::MD5 'md5_hex';
+    print 'Digest is ', md5_hex('foobarbaz'), "\n";
+
+The above example would print out the message
+
+    Digest is 6df23dc03f9b54cc38a0fc1483df6e21
+
+provided that the implementation is working correctly.  The same
+checksum can also be calculated in OO style:
+
+    use Digest::MD5;
+    
+    $md5 = Digest::MD5->new;
+    $md5->add('foo', 'bar');
+    $md5->add('baz');
+    $digest = $md5->hexdigest;
+    
+    print "Digest is $digest\n";
+
+The digest methods are destructive. That means you can only call them
+once and the $md5 objects is reset after use. You can make a copy with clone:
+
+       $md5->clone->hexdigest
+
+=head1 LIMITATIONS
+
+This implementation of the MD5 algorithm has some limitations:
+
+=over 4
+
+=item
+
+It's slow, very slow. I've done my very best but Digest::MD5 is still about 100 times faster.
+You can only encrypt Data up to one million bytes in an acceptable time. But it's very usefull
+for encrypting small amounts of data like passwords.
+
+=item
+
+You can only encrypt up to 2^32 bits = 512 MB on 32bit archs. But You should
+use C<Digest::MD5> for those amounts of data anyway.
+
+=back
+
+=head1 SEE ALSO
+
+L<Digest::MD5>
+
+L<md5(1)>
+
+RFC 1321
+
+tools/md5: a small BSD compatible md5 tool written in pure perl.
+
+=head1 COPYRIGHT
+
+This library is free software; you can redistribute it and/or
+modify it under the same terms as Perl itself.
+
+ Copyright 2000 Christian Lackas, Imperia Software Solutions
+ Copyright 1998-1999 Gisle Aas.
+ Copyright 1995-1996 Neil Winton.
+ Copyright 1991-1992 RSA Data Security, Inc.
+
+The MD5 algorithm is defined in RFC 1321. The basic C code
+implementing the algorithm is derived from that in the RFC and is
+covered by the following copyright:
+
+=over 4
+
+=item
+
+Copyright (C) 1991-1992, RSA Data Security, Inc. Created 1991. All
+rights reserved.
+
+License to copy and use this software is granted provided that it
+is identified as the "RSA Data Security, Inc. MD5 Message-Digest
+Algorithm" in all material mentioning or referencing this software
+or this function.
+
+License is also granted to make and use derivative works provided
+that such works are identified as "derived from the RSA Data
+Security, Inc. MD5 Message-Digest Algorithm" in all material
+mentioning or referencing the derived work.
+
+RSA Data Security, Inc. makes no representations concerning either
+the merchantability of this software or the suitability of this
+software for any particular purpose. It is provided "as is"
+without express or implied warranty of any kind.
+
+These notices must be retained in any copies of any part of this
+documentation and/or software.
+
+=back
+
+This copyright does not prohibit distribution of any version of Perl
+containing this extension under the terms of the GNU or Artistic
+licenses.
+
+=head1 AUTHORS
+
+The original MD5 interface was written by Neil Winton
+(<N.Winton (at) axion.bt.co.uk>).
+
+C<Digest::MD5> was made by Gisle Aas <gisle (at) aas.no> (I took his Interface
+and part of the documentation).
+
+Thanks to Guido Flohr for his 'use integer'-hint.
+
+This release was made by Christian Lackas <delta (at) lackas.net>.
+
+=cut
+
+__DATA__
+FF,$a,$b,$c,$d,$_[4],7,0xd76aa478,/* 1 */
+FF,$d,$a,$b,$c,$_[5],12,0xe8c7b756,/* 2 */
+FF,$c,$d,$a,$b,$_[6],17,0x242070db,/* 3 */
+FF,$b,$c,$d,$a,$_[7],22,0xc1bdceee,/* 4 */
+FF,$a,$b,$c,$d,$_[8],7,0xf57c0faf,/* 5 */
+FF,$d,$a,$b,$c,$_[9],12,0x4787c62a,/* 6 */
+FF,$c,$d,$a,$b,$_[10],17,0xa8304613,/* 7 */
+FF,$b,$c,$d,$a,$_[11],22,0xfd469501,/* 8 */
+FF,$a,$b,$c,$d,$_[12],7,0x698098d8,/* 9 */
+FF,$d,$a,$b,$c,$_[13],12,0x8b44f7af,/* 10 */
+FF,$c,$d,$a,$b,$_[14],17,0xffff5bb1,/* 11 */
+FF,$b,$c,$d,$a,$_[15],22,0x895cd7be,/* 12 */
+FF,$a,$b,$c,$d,$_[16],7,0x6b901122,/* 13 */
+FF,$d,$a,$b,$c,$_[17],12,0xfd987193,/* 14 */
+FF,$c,$d,$a,$b,$_[18],17,0xa679438e,/* 15 */
+FF,$b,$c,$d,$a,$_[19],22,0x49b40821,/* 16 */ 
+GG,$a,$b,$c,$d,$_[5],5,0xf61e2562,/* 17 */
+GG,$d,$a,$b,$c,$_[10],9,0xc040b340,/* 18 */
+GG,$c,$d,$a,$b,$_[15],14,0x265e5a51,/* 19 */
+GG,$b,$c,$d,$a,$_[4],20,0xe9b6c7aa,/* 20 */
+GG,$a,$b,$c,$d,$_[9],5,0xd62f105d,/* 21 */
+GG,$d,$a,$b,$c,$_[14],9,0x2441453,/* 22 */
+GG,$c,$d,$a,$b,$_[19],14,0xd8a1e681,/* 23 */
+GG,$b,$c,$d,$a,$_[8],20,0xe7d3fbc8,/* 24 */
+GG,$a,$b,$c,$d,$_[13],5,0x21e1cde6,/* 25 */
+GG,$d,$a,$b,$c,$_[18],9,0xc33707d6,/* 26 */
+GG,$c,$d,$a,$b,$_[7],14,0xf4d50d87,/* 27 */
+GG,$b,$c,$d,$a,$_[12],20,0x455a14ed,/* 28 */
+GG,$a,$b,$c,$d,$_[17],5,0xa9e3e905,/* 29 */
+GG,$d,$a,$b,$c,$_[6],9,0xfcefa3f8,/* 30 */
+GG,$c,$d,$a,$b,$_[11],14,0x676f02d9,/* 31 */
+GG,$b,$c,$d,$a,$_[16],20,0x8d2a4c8a,/* 32 */
+HH,$a,$b,$c,$d,$_[9],4,0xfffa3942,/* 33 */
+HH,$d,$a,$b,$c,$_[12],11,0x8771f681,/* 34 */
+HH,$c,$d,$a,$b,$_[15],16,0x6d9d6122,/* 35 */
+HH,$b,$c,$d,$a,$_[18],23,0xfde5380c,/* 36 */
+HH,$a,$b,$c,$d,$_[5],4,0xa4beea44,/* 37 */
+HH,$d,$a,$b,$c,$_[8],11,0x4bdecfa9,/* 38 */
+HH,$c,$d,$a,$b,$_[11],16,0xf6bb4b60,/* 39 */
+HH,$b,$c,$d,$a,$_[14],23,0xbebfbc70,/* 40 */
+HH,$a,$b,$c,$d,$_[17],4,0x289b7ec6,/* 41 */
+HH,$d,$a,$b,$c,$_[4],11,0xeaa127fa,/* 42 */
+HH,$c,$d,$a,$b,$_[7],16,0xd4ef3085,/* 43 */
+HH,$b,$c,$d,$a,$_[10],23,0x4881d05,/* 44 */
+HH,$a,$b,$c,$d,$_[13],4,0xd9d4d039,/* 45 */
+HH,$d,$a,$b,$c,$_[16],11,0xe6db99e5,/* 46 */
+HH,$c,$d,$a,$b,$_[19],16,0x1fa27cf8,/* 47 */
+HH,$b,$c,$d,$a,$_[6],23,0xc4ac5665,/* 48 */
+II,$a,$b,$c,$d,$_[4],6,0xf4292244,/* 49 */
+II,$d,$a,$b,$c,$_[11],10,0x432aff97,/* 50 */
+II,$c,$d,$a,$b,$_[18],15,0xab9423a7,/* 51 */
+II,$b,$c,$d,$a,$_[9],21,0xfc93a039,/* 52 */
+II,$a,$b,$c,$d,$_[16],6,0x655b59c3,/* 53 */
+II,$d,$a,$b,$c,$_[7],10,0x8f0ccc92,/* 54 */
+II,$c,$d,$a,$b,$_[14],15,0xffeff47d,/* 55 */
+II,$b,$c,$d,$a,$_[5],21,0x85845dd1,/* 56 */
+II,$a,$b,$c,$d,$_[12],6,0x6fa87e4f,/* 57 */
+II,$d,$a,$b,$c,$_[19],10,0xfe2ce6e0,/* 58 */
+II,$c,$d,$a,$b,$_[10],15,0xa3014314,/* 59 */
+II,$b,$c,$d,$a,$_[17],21,0x4e0811a1,/* 60 */
+II,$a,$b,$c,$d,$_[8],6,0xf7537e82,/* 61 */
+II,$d,$a,$b,$c,$_[15],10,0xbd3af235,/* 62 */
+II,$c,$d,$a,$b,$_[6],15,0x2ad7d2bb,/* 63 */
+II,$b,$c,$d,$a,$_[13],21,0xeb86d391,/* 64 */
diff --git a/extlib/File/Copy/.exists b/extlib/File/Copy/.exists
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/extlib/File/Copy/Recursive.pm b/extlib/File/Copy/Recursive.pm
new file mode 100644 (file)
index 0000000..a191adb
--- /dev/null
@@ -0,0 +1,641 @@
+package File::Copy::Recursive;
+
+use strict;
+BEGIN {
+    # Keep older versions of Perl from trying to use lexical warnings
+    $INC{'warnings.pm'} = "fake warnings entry for < 5.6 perl ($])" if $] < 5.006;
+}
+use warnings;
+
+use Carp;
+use File::Copy; 
+use File::Spec; #not really needed because File::Copy already gets it, but for good measure :)
+
+use vars qw( 
+    @ISA      @EXPORT_OK $VERSION  $MaxDepth $KeepMode $CPRFComp $CopyLink 
+    $PFSCheck $RemvBase $NoFtlPth  $ForcePth $CopyLoop $RMTrgFil $RMTrgDir 
+    $CondCopy $BdTrgWrn $SkipFlop
+);
+
+require Exporter;
+@ISA = qw(Exporter);
+@EXPORT_OK = qw(fcopy rcopy dircopy fmove rmove dirmove pathmk pathrm pathempty pathrmdir);
+$VERSION = '0.36';
+
+$MaxDepth = 0;
+$KeepMode = 1;
+$CPRFComp = 0; 
+$CopyLink = eval { local $SIG{'__DIE__'};symlink '',''; 1 } || 0;
+$PFSCheck = 1;
+$RemvBase = 0;
+$NoFtlPth = 0;
+$ForcePth = 0;
+$CopyLoop = 0;
+$RMTrgFil = 0;
+$RMTrgDir = 0;
+$CondCopy = {};
+$BdTrgWrn = 0;
+$SkipFlop = 0;
+
+my $samecheck = sub {
+   return 1 if $^O eq 'MSWin32'; # need better way to check for this on winders...
+   return if @_ != 2 || !defined $_[0] || !defined $_[1];
+   return if $_[0] eq $_[1];
+
+   my $one = '';
+   if($PFSCheck) {
+      $one    = join( '-', ( stat $_[0] )[0,1] ) || '';
+      my $two = join( '-', ( stat $_[1] )[0,1] ) || '';
+      if ( $one eq $two && $one ) {
+          carp "$_[0] and $_[1] are identical";
+          return;
+      }
+   }
+
+   if(-d $_[0] && !$CopyLoop) {
+      $one    = join( '-', ( stat $_[0] )[0,1] ) if !$one;
+      my $abs = File::Spec->rel2abs($_[1]);
+      my @pth = File::Spec->splitdir( $abs );
+      while(@pth) {
+         my $cur = File::Spec->catdir(@pth);
+         last if !$cur; # probably not necessary, but nice to have just in case :)
+         my $two = join( '-', ( stat $cur )[0,1] ) || '';
+         if ( $one eq $two && $one ) {
+             # $! = 62; # Too many levels of symbolic links
+             carp "Caught Deep Recursion Condition: $_[0] contains $_[1]";
+             return;
+         }
+      
+         pop @pth;
+      }
+   }
+
+   return 1;
+};
+
+my $move = sub {
+   my $fl = shift;
+   my @x;
+   if($fl) {
+      @x = fcopy(@_) or return;
+   } else {
+      @x = dircopy(@_) or return;
+   }
+   if(@x) {
+      if($fl) {
+         unlink $_[0] or return;
+      } else {
+         pathrmdir($_[0]) or return;
+      }
+      if($RemvBase) {
+         my ($volm, $path) = File::Spec->splitpath($_[0]);
+         pathrm(File::Spec->catpath($volm,$path,''), $ForcePth, $NoFtlPth) or return;
+      }
+   }
+  return wantarray ? @x : $x[0];
+};
+
+my $ok_todo_asper_condcopy = sub {
+    my $org = shift;
+    my $copy = 1;
+    if(exists $CondCopy->{$org}) {
+        if($CondCopy->{$org}{'md5'}) {
+
+        }
+        if($copy) {
+
+        }
+    }
+    return $copy;
+};
+
+sub fcopy { 
+   $samecheck->(@_) or return;
+   if($RMTrgFil && (-d $_[1] || -e $_[1]) ) {
+      my $trg = $_[1];
+      if( -d $trg ) {
+        my @trgx = File::Spec->splitpath( $_[0] );
+        $trg = File::Spec->catfile( $_[1], $trgx[ $#trgx ] );
+      }
+      $samecheck->($_[0], $trg) or return;
+      if(-e $trg) {
+         if($RMTrgFil == 1) {
+            unlink $trg or carp "\$RMTrgFil failed: $!";
+         } else {
+            unlink $trg or return;
+         }
+      }
+   }
+   my ($volm, $path) = File::Spec->splitpath($_[1]);
+   if($path && !-d $path) {
+      pathmk(File::Spec->catpath($volm,$path,''), $NoFtlPth);
+   }
+   if( -l $_[0] && $CopyLink ) {
+      carp "Copying a symlink ($_[0]) whose target does not exist" 
+          if !-e readlink($_[0]) && $BdTrgWrn;
+      symlink readlink(shift()), shift() or return;
+   } else {  
+      copy(@_) or return;
+
+      my @base_file = File::Spec->splitpath($_[0]);
+      my $mode_trg = -d $_[1] ? File::Spec->catfile($_[1], $base_file[ $#base_file ]) : $_[1];
+
+      chmod scalar((stat($_[0]))[2]), $mode_trg if $KeepMode;
+   }
+   return wantarray ? (1,0,0) : 1; # use 0's incase they do math on them and in case rcopy() is called in list context = no uninit val warnings
+}
+
+sub rcopy { 
+    -d $_[0] || substr( $_[0], ( 1 * -1), 1) eq '*' ? dircopy(@_) 
+                                                    : fcopy(@_); 
+}
+
+sub dircopy {
+   if($RMTrgDir && -d $_[1]) {
+      if($RMTrgDir == 1) {
+         pathrmdir($_[1]) or carp "\$RMTrgDir failed: $!";
+      } else {
+         pathrmdir($_[1]) or return;
+      }
+   }
+   my $globstar = 0;
+   my $_zero = $_[0];
+   my $_one = $_[1];
+   if ( substr( $_zero, ( 1 * -1 ), 1 ) eq '*') {
+       $globstar = 1;
+       $_zero = substr( $_zero, 0, ( length( $_zero ) - 1 ) );
+   }
+
+   $samecheck->(  $_zero, $_[1] ) or return;
+   if ( !-d $_zero || ( -e $_[1] && !-d $_[1] ) ) {
+       $! = 20; 
+       return;
+   } 
+
+   if(!-d $_[1]) {
+      pathmk($_[1], $NoFtlPth) or return;
+   } else {
+      if($CPRFComp && !$globstar) {
+         my @parts = File::Spec->splitdir($_zero);
+         while($parts[ $#parts ] eq '') { pop @parts; }
+         $_one = File::Spec->catdir($_[1], $parts[$#parts]);
+      }
+   }
+   my $baseend = $_one;
+   my $level   = 0;
+   my $filen   = 0;
+   my $dirn    = 0;
+
+   my $recurs; #must be my()ed before sub {} since it calls itself
+   $recurs =  sub {
+      my ($str,$end,$buf) = @_;
+      $filen++ if $end eq $baseend; 
+      $dirn++ if $end eq $baseend;
+      mkdir $end or return if !-d $end;
+      chmod scalar((stat($str))[2]), $end if $KeepMode;
+      if($MaxDepth && $MaxDepth =~ m/^\d+$/ && $level >= $MaxDepth) {
+         return ($filen,$dirn,$level) if wantarray;
+         return $filen;
+      }
+      $level++;
+
+      
+      my @files;
+      if ( $] < 5.006 ) {
+          opendir(STR_DH, $str) or return;
+          @files = grep( $_ ne '.' && $_ ne '..', readdir(STR_DH));
+          closedir STR_DH;
+      }
+      else {
+          opendir(my $str_dh, $str) or return;
+          @files = grep( $_ ne '.' && $_ ne '..', readdir($str_dh));
+          closedir $str_dh;
+      }
+
+      for my $file (@files) {
+          my ($file_ut) = $file =~ m{ (.*) }xms;
+          my $org = File::Spec->catfile($str, $file_ut);
+          my $new = File::Spec->catfile($end, $file_ut);
+          if( -l $org && $CopyLink ) {
+              carp "Copying a symlink ($org) whose target does not exist" 
+                  if !-e readlink($org) && $BdTrgWrn;
+              symlink readlink($org), $new or return;
+          } 
+          elsif(-d $org) {
+              $recurs->($org,$new,$buf) if defined $buf;
+              $recurs->($org,$new) if !defined $buf;
+              $filen++;
+              $dirn++;
+          } 
+          else {
+              if($ok_todo_asper_condcopy->($org)) {
+                  if($SkipFlop) {
+                      fcopy($org,$new,$buf) or next if defined $buf;
+                      fcopy($org,$new) or next if !defined $buf;                      
+                  }
+                  else {
+                      fcopy($org,$new,$buf) or return if defined $buf;
+                      fcopy($org,$new) or return if !defined $buf;
+                  }
+                  chmod scalar((stat($org))[2]), $new if $KeepMode;
+                  $filen++;
+              }
+          }
+      }
+      1;
+   };
+
+   $recurs->($_zero, $_one, $_[2]) or return;
+   return wantarray ? ($filen,$dirn,$level) : $filen;
+}
+
+sub fmove { $move->(1, @_) } 
+
+sub rmove { 
+    my $_zero = shift;
+    $_zero = substr( $_zero, 0, ( length( $_zero ) - 1 ) )
+        if substr( $_[0], ( 1 * -1), 1) eq '*';
+
+    -d $_zero ? dirmove($_zero, @_) : fmove($_zero, @_);
+}
+
+sub dirmove { $move->(0, @_) }
+
+sub pathmk {
+   my @parts = File::Spec->splitdir( shift() );
+   my $nofatal = shift;
+   my $pth = $parts[0];
+   my $zer = 0;
+   if(!$pth) {
+      $pth = File::Spec->catdir($parts[0],$parts[1]);
+      $zer = 1;
+   }
+   for($zer..$#parts) {
+      mkdir $pth or return if !-d $pth && !$nofatal;
+      mkdir $pth if !-d $pth && $nofatal;
+      $pth = File::Spec->catdir($pth, $parts[$_ + 1]) unless $_ == $#parts;
+   }
+   1;
+} 
+
+sub pathempty {
+   my $pth = shift; 
+
+   return 2 if !-d $pth;
+
+   my @names;
+   my $pth_dh;
+   if ( $] < 5.006 ) {
+       opendir(PTH_DH, $pth) or return;
+       @names = grep !/^\.+$/, readdir(PTH_DH);
+   }
+   else {
+       opendir($pth_dh, $pth) or return;
+       @names = grep !/^\.+$/, readdir($pth_dh);       
+   }
+   
+   for my $name (@names) {
+      my ($name_ut) = $name =~ m{ (.*) }xms;
+      my $flpth     = File::Spec->catdir($pth, $name_ut);
+
+      if( -l $flpth ) {
+             unlink $flpth or return; 
+      }
+      elsif(-d $flpth) {
+          pathrmdir($flpth) or return;
+      } 
+      else {
+          unlink $flpth or return;
+      }
+   }
+
+   if ( $] < 5.006 ) {
+       closedir PTH_DH;
+   }
+   else {
+       closedir $pth_dh;
+   }
+   
+   1;
+}
+
+sub pathrm {
+   my $path = shift;
+   return 2 if !-d $path;
+   my @pth = File::Spec->splitdir( $path );
+   my $force = shift;
+
+   while(@pth) { 
+      my $cur = File::Spec->catdir(@pth);
+      last if !$cur; # necessary ??? 
+      if(!shift()) {
+         pathempty($cur) or return if $force;
+         rmdir $cur or return;
+      } 
+      else {
+         pathempty($cur) if $force;
+         rmdir $cur;
+      }
+      pop @pth;
+   }
+   1;
+}
+
+sub pathrmdir {
+    my $dir = shift;
+    if( -e $dir ) {
+        return if !-d $dir;
+    }
+    else {
+        return 2;
+    }
+
+    pathempty($dir) or return;
+    
+    rmdir $dir or return;
+}
+
+1;
+
+__END__
+
+=head1 NAME
+
+File::Copy::Recursive - Perl extension for recursively copying files and directories
+
+=head1 SYNOPSIS
+
+  use File::Copy::Recursive qw(fcopy rcopy dircopy fmove rmove dirmove);
+
+  fcopy($orig,$new[,$buf]) or die $!;
+  rcopy($orig,$new[,$buf]) or die $!;
+  dircopy($orig,$new[,$buf]) or die $!;
+
+  fmove($orig,$new[,$buf]) or die $!;
+  rmove($orig,$new[,$buf]) or die $!;
+  dirmove($orig,$new[,$buf]) or die $!;
+
+=head1 DESCRIPTION
+
+This module copies and moves directories recursively (or single files, well... singley) to an optional depth and attempts to preserve each file or directory's mode.
+
+=head1 EXPORT
+
+None by default. But you can export all the functions as in the example above and the path* functions if you wish.
+
+=head2 fcopy()
+
+This function uses File::Copy's copy() function to copy a file but not a directory. Any directories are recursively created if need be.
+One difference to File::Copy::copy() is that fcopy attempts to preserve the mode (see Preserving Mode below)
+The optional $buf in the synopsis if the same as File::Copy::copy()'s 3rd argument
+returns the same as File::Copy::copy() in scalar context and 1,0,0 in list context to accomidate rcopy()'s list context on regular files. (See below for more info)
+
+=head2 dircopy()
+
+This function recursively traverses the $orig directory's structure and recursively copies it to the $new directory.
+$new is created if necessary (multiple non existant directories is ok (IE foo/bar/baz). The script logically and portably creates all of them if necessary).
+It attempts to preserve the mode (see Preserving Mode below) and 
+by default it copies all the way down into the directory, (see Managing Depth) below.
+If a directory is not specified it croaks just like fcopy croaks if its not a file that is specified.
+
+returns true or false, for true in scalar context it returns the number of files and directories copied,
+In list context it returns the number of files and directories, number of directories only, depth level traversed.
+
+  my $num_of_files_and_dirs = dircopy($orig,$new);
+  my($num_of_files_and_dirs,$num_of_dirs,$depth_traversed) = dircopy($orig,$new);
+  
+Normally it stops and return's if a copy fails, to continue on regardless set $File::Copy::Recursive::SkipFlop to true.
+
+    local $File::Copy::Recursive::SkipFlop = 1;
+
+That way it will copy everythgingit can ina directory and won't stop because of permissions, etc...
+
+=head2 rcopy()
+
+This function will allow you to specify a file *or* directory. It calls fcopy() if its a file and dircopy() if its a directory.
+If you call rcopy() (or fcopy() for that matter) on a file in list context, the values will be 1,0,0 since no directories and no depth are used. 
+This is important becasue if its a directory in list context and there is only the initial directory the return value is 1,1,1.
+
+=head2 fmove()
+
+Copies the file then removes the original. You can manage the path the original file is in according to $RemvBase.
+
+=head2 dirmove()
+
+Uses dircopy() to copy the directory then removes the original. You can manage the path the original directory is in according to $RemvBase.
+
+=head2 rmove()
+
+Like rcopy() but calls fmove() or dirmove() instead.
+
+=head3 $RemvBase
+
+Default is false. When set to true the *move() functions will not only attempt to remove the original file or directory but will remove the given path it is in.
+
+So if you:
+
+   rmove('foo/bar/baz', '/etc/');
+   # "baz" is removed from foo/bar after it is successfully copied to /etc/
+   
+   local $File::Copy::Recursive::Remvbase = 1;
+   rmove('foo/bar/baz','/etc/');
+   # if baz is successfully copied to /etc/ :
+   # first "baz" is removed from foo/bar
+   # then "foo/bar is removed via pathrm()
+
+=head4 $ForcePth
+
+Default is false. When set to true it calls pathempty() before any directories are removed to empty the directory so it can be rmdir()'ed when $RemvBase is in effect.
+
+=head2 Creating and Removing Paths
+
+=head3 $NoFtlPth
+
+Default is false. If set to true  rmdir(), mkdir(), and pathempty() calls in pathrm() and pathmk() do not return() on failure.
+
+If its set to true they just silently go about their business regardless. This isn't a good idea but its there if you want it.
+
+=head3 Path functions
+
+These functions exist soley because they were necessary for the move and copy functions to have the features they do and not because they are of themselves the purpose of this module. That being said, here is how they work so you can understand how the copy and move funtions work and use them by themselves if you wish.
+
+=head4 pathrm()
+
+Removes a given path recursively. It removes the *entire* path so be carefull!!!
+
+Returns 2 if the given path is not a directory.
+
+  File::Copy::Recursive::pathrm('foo/bar/baz') or die $!;
+  # foo no longer exists
+
+Same as:
+
+  rmdir 'foo/bar/baz' or die $!;
+  rmdir 'foo/bar' or die $!;
+  rmdir 'foo' or die $!;
+
+An optional second argument makes it call pathempty() before any rmdir()'s when set to true.
+
+  File::Copy::Recursive::pathrm('foo/bar/baz', 1) or die $!;
+  # foo no longer exists
+
+Same as:
+
+  File::Copy::Recursive::pathempty('foo/bar/baz') or die $!;
+  rmdir 'foo/bar/baz' or die $!;
+  File::Copy::Recursive::pathempty('foo/bar/') or die $!;
+  rmdir 'foo/bar' or die $!;
+  File::Copy::Recursive::pathempty('foo/') or die $!;
+  rmdir 'foo' or die $!;
+
+An optional third argument acts like $File::Copy::Recursive::NoFtlPth, again probably not a good idea.
+
+=head4 pathempty()
+
+Recursively removes the given directory's contents so it is empty. returns 2 if argument is not a directory, 1 on successfully emptying the directory.
+
+   File::Copy::Recursive::pathempty($pth) or die $!;
+   # $pth is now an empty directory
+
+=head4 pathmk()
+
+Creates a given path recursively. Creates foo/bar/baz even if foo does not exist.
+
+   File::Copy::Recursive::pathmk('foo/bar/baz') or die $!;
+
+An optional second argument if true acts just like $File::Copy::Recursive::NoFtlPth, which means you'd never get your die() if something went wrong. Again, probably a *bad* idea.
+
+=head4 pathrmdir()
+
+Same as rmdir() but it calls pathempty() first to recursively empty it first since rmdir can not remove a directory with contents.
+Just removes the top directory the path given insetad of the entire path like pathrm(). Return 2 if the given argument is not a directory.
+
+=head2 Preserving Mode
+
+By default a quiet attempt is made to change the new file or directory to the mode of the old one.
+To turn this behavior off set
+  $File::Copy::Recursive::KeepMode
+to false;
+
+=head2 Managing Depth
+
+You can set the maximum depth a directory structure is recursed by setting:
+  $File::Copy::Recursive::MaxDepth 
+to a whole number greater than 0.
+
+=head2 SymLinks
+
+If your system supports symlinks then symlinks will be copied as symlinks instead of as the target file.
+Perl's symlink() is used instead of File::Copy's copy()
+You can customize this behavior by setting $File::Copy::Recursive::CopyLink to a true or false value.
+It is already set to true or false dending on your system's support of symlinks so you can check it with an if statement to see how it will behave:
+
+    if($File::Copy::Recursive::CopyLink) {
+        print "Symlinks will be preserved\n";
+    } else {
+        print "Symlinks will not be preserved because your system does not support it\n";
+    }
+
+If symlinks are being copied you can set $File::Copy::Recursive::BdTrgWrn to true to make it carp when it copies a link whose target does not exist. Its false by default.
+
+    local $File::Copy::Recursive::BdTrgWrn  = 1;
+
+=head2 Removing existing target file or directory before copying.
+
+This can be done by setting $File::Copy::Recursive::RMTrgFil or $File::Copy::Recursive::RMTrgDir for file or directory behavior respectively.
+
+0 = off (This is the default)
+
+1 = carp() $! if removal fails
+
+2 = return if removal fails
+
+    local $File::Copy::Recursive::RMTrgFil = 1;
+    fcopy($orig, $target) or die $!;
+    # if it fails it does warn() and keeps going
+
+    local $File::Copy::Recursive::RMTrgDir = 2;
+    dircopy($orig, $target) or die $!;
+    # if it fails it does your "or die"
+
+This should be unnecessary most of the time but its there if you need it :)
+
+=head2 Turning off stat() check
+
+By default the files or directories are checked to see if they are the same (IE linked, or two paths (absolute/relative or different relative paths) to the same file) by comparing the file's stat() info. 
+It's a very efficient check that croaks if they are and shouldn't be turned off but if you must for some weird reason just set $File::Copy::Recursive::PFSCheck to a false value. ("PFS" stands for "Physical File System")
+
+=head2 Emulating cp -rf dir1/ dir2/
+
+By default dircopy($dir1,$dir2) will put $dir1's contents right into $dir2 whether $dir2 exists or not.
+
+You can make dircopy() emulate cp -rf by setting $File::Copy::Recursive::CPRFComp to true.
+
+NOTE: This only emulates -f in the sense that it does not prompt. It does not remove the target file or directory if it exists.
+If you need to do that then use the variables $RMTrgFil and $RMTrgDir described in "Removing existing target file or directory before copying" above.
+
+That means that if $dir2 exists it puts the contents into $dir2/$dir1 instead of $dir2 just like cp -rf.
+If $dir2 does not exist then the contents go into $dir2 like normal (also like cp -rf)
+
+So assuming 'foo/file':
+
+    dircopy('foo', 'bar') or die $!;
+    # if bar does not exist the result is bar/file
+    # if bar does exist the result is bar/file
+
+    $File::Copy::Recursive::CPRFComp = 1;
+    dircopy('foo', 'bar') or die $!;
+    # if bar does not exist the result is bar/file
+    # if bar does exist the result is bar/foo/file
+
+You can also specify a star for cp -rf glob type behavior:
+
+    dircopy('foo/*', 'bar') or die $!;
+    # if bar does not exist the result is bar/file
+    # if bar does exist the result is bar/file
+
+    $File::Copy::Recursive::CPRFComp = 1;
+    dircopy('foo/*', 'bar') or die $!;
+    # if bar does not exist the result is bar/file
+    # if bar does exist the result is bar/file
+
+NOTE: The '*' is only like cp -rf foo/* and *DOES NOT EXPAND PARTIAL DIRECTORY NAMES LIKE YOUR SHELL DOES* (IE not like cp -rf fo* to copy foo/*)
+
+=head2 Allowing Copy Loops
+
+If you want to allow:
+
+  cp -rf . foo/
+
+type behavior set $File::Copy::Recursive::CopyLoop to true.
+
+This is false by default so that a check is done to see if the source directory will contain the target directory and croaks to avoid this problem.
+
+If you ever find a situation where $CopyLoop = 1 is desirable let me know (IE its a bad bad idea but is there if you want it)
+
+(Note: On Windows this was necessary since it uses stat() to detemine samedness and stat() is essencially useless for this on Windows. 
+The test is now simply skipped on Windows but I'd rather have an actual reliable check if anyone in Microsoft land would care to share)
+
+=head1 SEE ALSO
+
+L<File::Copy> L<File::Spec>
+
+=head1 TO DO
+
+Add OO interface so you can have different behavior with different objects instead of relying on global variables.
+This will give better control in environments where behavior based on global variables is not very desireable.
+
+I'll add this after the latest verision has been out for a while with no new features or issues found :)
+
+=head1 AUTHOR
+
+Daniel Muey, L<http://drmuey.com/cpan_contact.pl>
+
+=head1 COPYRIGHT AND LICENSE
+
+Copyright 2004 by Daniel Muey
+
+This library is free software; you can redistribute it and/or modify
+it under the same terms as Perl itself. 
+
+=cut
diff --git a/lib/PluginManager/App.pm b/lib/PluginManager/App.pm
new file mode 100644 (file)
index 0000000..0e26116
--- /dev/null
@@ -0,0 +1,1134 @@
+package PluginManager::App;
+
+use File::Basename;
+use POSIX;
+use File::Find;
+use YAML::Tiny;
+use Encode;
+use PluginManager::Util;
+
+use strict;
+
+sub init_request {
+       my ($plugin, $app) = @_;
+       if (my $mode = $app->param('__mode')) {
+               if ($mode eq 'pluginmanager') {
+                       $app->{upgrade_required} = 0;
+               }
+       }
+}
+
+sub is_upgrade_required {
+       my $app = MT->instance;
+       my $comps = @MT::Components;
+       $app->{upgrade_required} = 0;
+
+       my $schema  = $app->config('SchemaVersion');
+       my $version = $app->config('MTVersion');
+       if (   !$schema
+               || ( $schema < $app->schema_version )
+               || ( ( !$version || ( $version < $app->version_number ) )
+                       && $app->config->NotifyUpgrade )
+               )
+       {
+               $app->{upgrade_required} = 1;
+       }
+       else {
+               foreach my $plugin (@MT::Components) {
+                       if ( $plugin->needs_upgrade ) {
+                               $app->{upgrade_required} = 1;
+                               last;
+                       }
+               }
+       }
+
+       $app->{upgrade_required};
+}
+
+sub pluginmanager {
+    my $app = shift;
+
+       if (my $blog_id = $app->param('blog_id')) {
+               $app->redirect($app->app_uri . '?blog_id=' . $blog_id);
+       }
+
+    my $plugin = MT->component('PluginManager');
+       my $op = $app->param('op') || 'package_list';
+
+       $app->config->AltTemplatePath(File::Spec->catfile(
+               $plugin->{full_path}, 'tmpl'
+       ));
+
+       if ($op eq 'setting') {
+               &setting($plugin, $app, &default_param);
+       }
+       elsif ($op eq 'update_setting') {
+               &update_setting($plugin, $app, &default_param);
+       }
+       elsif ($op eq 'ftp_prompt') {
+               &ftp_prompt($plugin, $app, &default_param);
+       }
+       elsif ($op eq 'import') {
+               &import($plugin, $app, &default_param);
+       }
+       elsif ($op eq 'do_import') {
+               &do_import($plugin, $app, &default_param);
+       }
+       elsif ($op eq 'export') {
+               &export($plugin, $app, &default_param);
+       }
+       elsif ($op eq 'do_export') {
+               &do_export($plugin, $app, &default_param);
+       }
+       elsif ($op eq 'repository') {
+               &repository($plugin, $app, &default_param);
+       }
+       elsif ($op eq 'create_repository') {
+               &create_repository($plugin, $app, &default_param);
+       }
+       elsif ($op eq 'package_update') {
+               &package_update($plugin, $app, &default_param);
+       }
+       elsif ($op eq 'upgrade') {
+               &upgrade($plugin, $app, &default_param);
+       }
+       elsif ($op eq 'task') {
+               &task($plugin, $app, &default_param);
+       }
+       else {
+       &package_list($plugin, $app, &default_param);
+       }
+}
+
+sub default_param {
+       my $app = MT->instance;
+    my $plugin = MT->component('PluginManager');
+       my %param = ();
+
+       my @ignores = (
+               'time', 'updated', 'created', 'initialize',
+               'imported_package', 'imported_distribution',
+               'created_package', 'created_distribution',
+       );
+    my $q = new CGI('');
+       foreach my $p ($app->param) {
+               if (! grep({ $_ eq $p } @ignores)) {
+                       $q->param($p, $app->param($p));
+               }
+       }
+       my $app_uri = $app->app_uri;
+
+       local $CGI::USE_PARAM_SEMICOLONS;
+       $CGI::USE_PARAM_SEMICOLONS = 0;
+
+       foreach my $o (
+        'package_list', 'setting', 'package_update', 'upgrade',
+               'import', 'export', 'repository',
+    ) {
+               $q->param('op', $o);
+               $param{'link_' . $o} = $app_uri . '?' . $q->query_string;
+       }
+
+       return \%param;
+}
+
+sub packages_merge {
+       my ($original, $add) = @_;
+       foreach my $p (keys(%$add)) {
+               if (exists($original->{$p})) {
+                       foreach my $v (keys(%{ $add->{$p} })) {
+                               $original->{$p}->{$v} = $add->{$p}->{$v};
+                       }
+               }
+               else {
+                       $original->{$p} = $add->{$p};
+               }
+       }
+
+       $original;
+}
+
+sub packages_load {
+       require Compress::Zlib;
+       require YAML::Tiny;
+
+    my ($plugin, $app, $param) = @_;
+
+    my $packages_class = MT->model('pm_packages');
+    my $locale = $app->current_language;
+    my @pkgs = $packages_class->load({ 'locale' => $locale });
+
+       my $packages = {};
+       foreach my $p (@pkgs) {
+               my $str = Compress::Zlib::memGunzip($p->packages);
+               my $yaml = YAML::Tiny->read_string(decode('utf8', $str));
+
+               &packages_merge($packages, $yaml->[0]);
+       }
+
+       $packages;
+}
+
+sub writable {
+       my $plugin = MT->component('PluginManager');
+       my $dir = dirname($plugin->{full_path});
+       my $file = File::Spec->catfile($dir, 'test');
+       for (my $i = 0;;$i++) {
+               last if (! -f $file);
+               $file .= $i;
+       }
+
+       open(my $fh, '>', $file) or return 0;
+       close($fh) or return 0;
+       unlink($file) or return 0;
+
+       return 1;
+}
+
+sub has_ftp_settings {
+       my $plugin = MT->component('PluginManager');
+       my $hash = $plugin->get_config_hash;
+       $hash->{'ftp_user'} || 0;
+}
+
+sub package_list {
+    my ($plugin, $app, $param) = @_;
+
+       my $packages = &packages_load(@_);
+       my $writable = &writable;
+
+       if (! $app->param('time')) {
+               if (
+                       (! $writable) && (! &has_ftp_settings)
+               ) {
+                       return $app->redirect(
+                               $app->app_uri . '?__mode=pluginmanager&op=setting&initialize=1'
+                       );
+               }
+
+               if (! scalar(%$packages)) {
+                       return $app->redirect(
+                               $app->app_uri . '?__mode=pluginmanager&op=package_update&initialize=1'
+                       );
+               }
+       }
+
+    my $installed_class = MT->model('pm_installed');
+       my @installeds = $installed_class->load;
+       foreach my $i (@installeds) {
+               my $control = $i->make_control_locale(
+                       $app->current_language
+               );
+               $control->{'installed'} = 1;
+
+               $packages->{$i->signature} ||= {};
+               $packages->{$i->signature}{$control->{version}} = $control;
+       }
+
+       $param->{packages} = $packages;
+
+       $param->{listing_screen} = 1;
+       $param->{updated} = $app->param('updated') ? 1 : 0;
+       $param->{writable} = $writable;
+
+    $plugin->load_tmpl('pm_package_list.tmpl', $param);
+}
+
+sub package_update {
+    require LWP::UserAgent;
+       require Compress::Zlib;
+       require YAML::Tiny;
+
+    my ($plugin, $app, $param) = @_;
+
+    my @repos = $plugin->get_config_value('repositories');
+       while(@repos && ref $repos[0]) {
+               @repos = @{ $repos[0] };
+       }
+       @repos = map({ split /\n/ } @repos);
+
+    my $packages_class = MT->model('pm_packages');
+    my $locale = $app->current_language;
+    $packages_class->remove({ 'locale' => $locale });
+    
+       my $ua = LWP::UserAgent->new;
+       if (my $proxy = MT->config('HTTPProxy')) {
+               $ua->proxy('http', $proxy);
+       }
+       $ua->timeout(10);
+
+    foreach my $r (@repos) {
+        $r =~ s/\/$//;
+        my $yaml_gz = $r . '/packages-' . $locale . '.yaml.gz';
+
+        my $response = $ua->get($yaml_gz);
+        if ($response->is_success) {
+                       my $str = Compress::Zlib::memGunzip($response->content);
+                       my $yaml = YAML::Tiny->read_string($str);
+                       my $packs = $yaml->[0];
+
+                       foreach my $p (keys(%$packs)) {
+                               foreach my $v (keys(%{ $packs->{$p} })) {
+                                       $packs->{$p}->{$v}->{'repository'} = $r;
+                               }
+                       }
+
+                       $yaml = YAML::Tiny->new;
+                       $yaml->[0] = $packs;
+                       $str = Compress::Zlib::memGzip($yaml->write_string, 9);
+
+            my $pkgs = $packages_class->new;
+            $pkgs->locale($locale);
+            $pkgs->repository($r);
+            $pkgs->packages($str);
+                       $pkgs->save();
+        }
+        else {
+            die $response->status_line;
+        }
+    }
+
+       my $updated = $app->param('initialize') ? '' : '&updated=1';
+    $app->redirect(
+        $app->app_uri . '?__mode=pluginmanager&op=package_list' . $updated . '&time=' . time
+    );
+}
+
+sub execute_script {
+       package PluginManager::App::execute_script;
+       our $manager = MT->component('PluginManager');
+       do($_[0]) if -f $_[0];
+       if ($@) {
+               $_[1]->($@) if ref $_[1];
+               0;
+       }
+       else {
+               1;
+       }
+}
+
+sub install_distribution {
+       require Archive::Tar;
+
+       my ($file, $plugin_base, $handler) = @_;
+
+       my $app = MT->instance;
+       my $plugin = MT->component('PluginManager');
+       my $temp_dir =  tempdir(undef, CLEANUP => 1);
+
+       ## extract
+       my $tar = Archive::Tar->new;
+
+       my $cwd = getcwd;
+       chdir($temp_dir);
+       $tar->read($file);
+       $tar->extract;
+       chdir($cwd);
+
+       foreach my $f (glob(File::Spec->catfile($temp_dir, 'pool', '*.mpm'))) {
+               &install($f);
+       }
+}
+
+sub rcopy {
+       my ($src, $dst) = @_;
+
+       my $app = MT->instance;
+       my $plugin = MT->component('PluginManager');
+
+       if (my $password = $app->param('ftp_password')) {
+               require Net::FTP;
+               require File::Find;
+
+               my $hash = $plugin->get_config_hash;
+
+               my $ftp = Net::FTP->new($hash->{'ftp_host'});
+               $ftp->login($hash->{'ftp_user'}, $password);
+               $ftp->cwd($hash->{'ftp_directory'});
+               $ftp->binary;
+               if (-d $src) {
+                       if ($dst) {
+                               $ftp->mkdir($dst, 1);
+                               $ftp->cwd($dst);
+                       }
+
+                       my $cwd = getcwd;
+                       chdir($src);
+                       File::Find::find({
+                               wanted => sub {
+                                       if (-d $_) {
+                                               $ftp->mkdir($_);
+                                       }
+                                       else {
+                                               $ftp->put($_, $_);
+                                       }
+                                       $ftp->site(
+                                               'CHMOD ' . sprintf('%04lo', (stat($_))[2]) . ' ' . $_
+                                       );
+                               },
+                               no_chdir => 1,
+                       }, '.');
+                       chdir($cwd);
+               }
+               else {
+                       $ftp->put($src, $dst);
+               }
+       }
+       else {
+               require File::Copy::Recursive;
+
+               File::Copy::Recursive::rcopy(
+                       $src,
+                       File::Spec->catdir($app->server_path(), $dst)
+               );
+       }
+}
+
+sub install {
+       require Archive::Tar;
+
+       my ($file, $plugin_base, $handler) = @_;
+
+       my $app = MT->instance;
+       my $plugin = MT->component('PluginManager');
+       $plugin_base ||= dirname($plugin->{full_path});
+       my $temp_dir =  tempdir(undef, CLEANUP => 1);
+
+       ## extract
+       my $tar = Archive::Tar->new;
+
+       my $cwd = getcwd;
+       chdir($temp_dir);
+
+       my @extracted = sort(grep($_, map({
+               my $name = $_->full_path;
+               my $is_dist = $name =~ s#[^/]*(/|\\)dist(/|\\)##;
+               if (! $is_dist) {
+                       '';
+               }
+               elsif ($name =~ m/^plugins$|^mt-static(.plugins)?$/) {
+                       '';
+               }
+               else {
+                       $name;
+               }
+       } $tar->read($file, 1))));
+       $tar->extract;
+       chdir($cwd);
+
+       my ($dir) = grep(-d $_, glob(File::Spec->catfile($temp_dir, '*')));
+
+
+       # do preinst script
+       {
+               &execute_script(
+                       File::Spec->catfile($dir, 'script', 'preinst.pl'), $handler
+               ) or return;
+       }
+
+       ## installation process
+       # plugins/
+       foreach my $f (glob(File::Spec->catfile($dir, 'dist', 'plugins', '*'))) {
+               &rcopy($f, File::Spec->catdir(basename($plugin_base), basename($f)));
+       }
+
+       # mt-static/plugins
+       my $static_base = File::Spec->catdir(
+               'mt-static', basename($plugin_base)
+       );
+       foreach my $f (glob(File::Spec->catfile($dir, 'dist', 'mt-static', 'plugins', '*'))) {
+               &rcopy($f, File::Spec->catdir($static_base, basename($f)));
+       }
+
+       # top-level script plugins.cgi
+       my $server_path = $app->server_path();
+       foreach my $f (glob(File::Spec->catfile($dir, 'dist', '*'))) {
+               my $base = basename($f);
+               if (grep(/^mt-static$|^plugins$/, $base)) {
+                       next;
+               }
+               &rcopy($f, $base);
+       }
+
+       # do postinst script
+       {
+               &execute_script(
+                       File::Spec->catfile($dir, 'script', 'postinst.pl'), $handler
+               ) or return;
+       }
+
+       ## save package information
+       # script/
+       my $script_tgz = '';
+       {
+               my $cwd = getcwd;
+               chdir($dir);
+
+               if (glob(File::Spec->catfile('script', '*'))) {
+
+                       require Archive::Tar;
+                       my $tar = Archive::Tar->new;
+                       finddepth({
+                               wanted => sub {
+                                       $tar->add_files($_);
+                               },
+                               no_chdir => 1,
+                       }, 'script');
+
+                       $tar->write('script.tar.gz', 1);
+                       $script_tgz = do{
+                               open(my $fh, 'script.tar.gz'); local $/; <$fh>
+                       };
+               }
+
+               chdir($cwd);
+       }
+
+       my ($signature, $version);
+       # control/
+       my $control = '';
+       {
+               my $control_data = {};
+               foreach my $ctrl (glob(File::Spec->catfile($dir, 'control', '*'))) {
+                       my ($locale) = ($ctrl =~ m/control-(.*).yaml$/);
+                       my $yaml = YAML::Tiny->read($ctrl);
+                       $control_data->{$locale} = $yaml->[0];
+
+                       if (! $signature) {
+                               $signature = $control_data->{$locale}{'id'};
+                               $version = $control_data->{$locale}{'version'};
+                       }
+               }
+
+               my $yaml = YAML::Tiny->new;
+               $yaml->[0] = $control_data;
+               $control = $yaml->write_string;
+       }
+
+       # seve
+       my $installed_class = MT->model('pm_installed');
+       my ($inst) = $installed_class->load(
+               {'signature' => $signature}
+       );
+       $inst ||= $installed_class->new;
+       $inst->files(join("\n", @extracted));
+       $inst->signature($signature);
+       $inst->version($version);
+       $inst->control($control);
+       $inst->script($script_tgz);
+       $inst->save();
+}
+
+sub task {
+       require File::Spec;
+
+    my ($plugin, $app, $param) = @_;
+
+       my $type = $app->param('type');
+       my $index = $app->param('index');
+       my $upgrade = $app->session('pluginmanager_upgrade');
+
+       my $task = undef;
+       foreach my $set (@{ $upgrade->{tasks} }) {
+               if ($set->{type} eq $type) {
+                       $task = $set->{tasks}->[$index];
+               }
+       }
+       if (! $task) {
+               return;
+       }
+
+       my $execute_script = sub {
+               &execute_script(@_, sub { ($task->{error}) = @_ });
+       };
+
+       my $do_install = sub {
+               ## prepare installation file
+               my $file = File::Spec->catfile(
+                       $upgrade->{temp_dir}, $task->{filename}
+               );
+
+               # concatinate downloaded files
+               open(my $fh, '>', $file);
+               foreach my $f (sort(glob($file . '.*'))) {
+                       my $cont = do{ open(my $fh, $f); local $/; <$fh> };
+                       print($fh $cont);
+               }
+               close($fh);
+
+               &install($file, undef, sub { ($task->{error}) = @_ });
+       };
+
+       my $do_remove = sub {
+               my $installed_class = MT->model('pm_installed');
+
+               my $installed = $installed_class->load({
+                       'signature' => $task->{signature},
+               });
+               if (! $installed) {
+                       return;
+               }
+
+               my $tempdir = tempdir(undef, CLEANUP => 1);
+               open(my $fh, '>', File::Spec->catfile($tempdir, 'script.tar.gz'));
+               print($fh $installed->script);
+               close($fh);
+
+               require Archive::Tar;
+               my $tar = Archive::Tar->new;
+               my $cwd = getcwd;
+               chdir($tempdir);
+               $tar->read('script.tar.gz', 1);
+               $tar->extract;
+               chdir($cwd);
+
+               # do preremove script
+               {
+                       $execute_script->(
+                               File::Spec->catfile($tempdir, 'script', 'prerm.pl')
+                       ) or return;
+               }
+
+               # remove
+               my $plugin_base = dirname($plugin->{full_path});
+               my $static_base = File::Spec->catdir(
+                       $app->server_path(), 'mt-static', 'plugins'
+               );
+               my $server_path = $app->server_path();
+
+               my $ftp = undef;
+               if (my $password = $app->param('ftp_password')) {
+                       require Net::FTP;
+
+                       my $hash = $plugin->get_config_hash;
+
+                       $ftp = Net::FTP->new($hash->{'ftp_host'});
+                       $ftp->login($hash->{'ftp_user'}, $password);
+                       $ftp->cwd($hash->{'ftp_directory'});
+                       $ftp->binary;
+
+                       $plugin_base = basename(dirname($plugin->{full_path}));
+                       $static_base = File::Spec->catdir(
+                               'mt-static', $plugin_base
+                       );
+                       $server_path = '';
+               }
+
+               foreach my $f (reverse(split(/\n/, $installed->files))) {
+                       if ($f =~ s{^plugins/}{}) {
+                               $f = File::Spec->catfile($plugin_base, $f);
+                       }
+                       elsif ($f =~ s{^mt-static/}{}) {
+                               $f = File::Spec->catfile($static_base, $f);
+                       }
+                       else {
+                               $f = $server_path ?
+                                       File::Spec->catfile($server_path, $f) : $f;
+                       }
+
+                       if ($ftp) {
+                               if (-d $f) {
+                                       $ftp->rmdir($f);
+                               }
+                               elsif (-f $f) {
+                                       $ftp->delete($f);
+                               }
+                       }
+                       else {
+                               if (-d $f) {
+                                       rmdir($f);
+                               }
+                               elsif (-f $f) {
+                                       unlink($f);
+                               }
+                       }
+               }
+
+               $installed_class->remove({
+                       'signature' => $task->{'signature'},
+               });
+
+               # do postremove script
+               {
+                       $execute_script->(
+                               File::Spec->catfile($tempdir, 'script', 'postrm.pl')
+                       ) or return;
+               }
+       };
+
+       if ($type eq 'download') {
+           require LWP::UserAgent;
+               require File::Basename;
+
+               my $index = $app->param('download_index');
+               my $bytes = $app->param('bytes');
+
+               my $ua = LWP::UserAgent->new();
+               if (my $proxy = MT->config('HTTPProxy')) {
+                       $ua->proxy('http', $proxy);
+               }
+               $ua->timeout(10);
+
+               my $request = HTTP::Request->new(
+                       'GET', $task->{url}, HTTP::Headers->new(
+                               'Range' => 'bytes=' . $bytes,
+                       ),
+               );
+
+               #my $response = $ua->get($task->{url});
+               my $response = $ua->request($request);
+        if ($response->is_success) {
+                       my $filename = File::Spec->catfile(
+                               $upgrade->{temp_dir},
+                               $task->{filename} . '.' . $index
+                       );
+                       open(my $fh, '>', $filename);
+                       print($fh $response->content);
+               }
+               else {
+                       return;
+               }
+       }
+       elsif ($type eq 'install') {
+               $do_install->();
+       }
+       elsif ($type eq 'remove') {
+               $do_remove->();
+       }
+       elsif ($type eq 'install') {
+               $do_remove->();
+               $do_install->();
+       }
+
+       $task->{upgrade_required} = &is_upgrade_required;
+
+       require JSON;
+       my $json = JSON::objToJson($task);
+       return $json;
+}
+
+sub create_task_common {
+       my ($app, $linker, $set, $hash, $pkg, $ver) = @_;
+       my $app_uri = $app->app_uri;
+       my $task = {
+               signature => $pkg,
+               version => $ver,
+       };
+
+       $linker->param('op', 'task');
+       $linker->param('type', $set->{'type'});
+       $linker->param('index', scalar(@{ $set->{tasks} }));
+
+       local $CGI::USE_PARAM_SEMICOLONS;
+       $CGI::USE_PARAM_SEMICOLONS = 0;
+
+       $task->{action} = $app_uri . '?' . $linker->query_string;
+       $task->{name} = $hash->{name};
+
+       push(@{ $set->{tasks} }, $task);
+       $task;
+}
+
+sub upgrade {
+    my ($plugin, $app, $param) = @_;
+
+       my $upgrade = {};
+       my ($task_download, $task_install, $task_remove, $task_upgrade) = (
+               {
+                       name => $plugin->translate('Download'),
+                       type => 'download',
+                       tasks => [],
+               },
+               {
+                       name => $plugin->translate('Install'),
+                       type => 'install',
+                       tasks => [],
+               },
+               {
+                       name => $plugin->translate('Uninstall'),
+                       type => 'remove',
+                       tasks => [],
+               },
+               {
+                       name => $plugin->translate('Upgrade'),
+                       type => 'upgrade',
+                       tasks => [],
+               },
+       );
+
+    my $linker = new CGI({
+               '__mode' => 'pluginmanager'
+       });
+
+       my $create_task_download = sub {
+               my ($pkg) = @_;
+               my $task = &create_task_common($app, $linker, $task_download, @_);
+
+               my $action = $task->{action};
+               delete($task->{action});
+               $task->{tasks} = [];
+
+               $task->{url} = $pkg->{'repository'} . '/' . $pkg->{'filename'};
+               #$task->{filename} = basename($pkg->{'filename'}, '.mpm');
+               $task->{filename} = basename($pkg->{'filename'});
+
+               my $size = $pkg->{size};
+               my $offset = 0;
+               my $unit = int($plugin->get_config_value('download_unit')) || 512;
+               my $split_size = $unit * 1024;
+
+               while($offset < $size) {
+                       my $end = $offset + $split_size - 1;
+                       if ($end > $size - 1) {
+                               $end = $size - 1;
+                       }
+                       push(@{ $task->{tasks} }, {
+                               action =>
+                                       $action . '&bytes=' . $offset . '-' . $end .
+                                       '&download_index=' .
+                                       sprintf('%03d', scalar(@{ $task->{tasks} }))
+                       });
+                       $offset = $end + 1;
+               }
+
+               $task;
+       };
+
+       my $create_task_upgrade = sub {
+               &create_task_common($app, $linker, $task_upgrade, @_);
+       };
+
+       my $create_task_install = sub {
+               my ($pkg) = @_;
+               my $task = &create_task_common($app, $linker, $task_install, @_);
+               #$task->{filename} = basename($pkg->{'filename'}, '.mpm');
+               $task->{filename} = basename($pkg->{'filename'});
+
+               $task;
+       };
+
+       my $create_task_remove = sub {
+               my $installed = shift;
+               my $control = $installed->make_control_locale(
+                       $app->current_language
+               );
+
+               my $task = &create_task_common($app, $linker, $task_remove, $control, @_);
+       };
+
+    my $installed_class = MT->model('pm_installed');
+       my @installeds = $installed_class->load;
+
+       my $availables = &packages_load(@_);
+
+       my @pkgs = $app->param('packages');
+       foreach my $p (@pkgs) {
+               my $new = $app->param($p);
+               if (! $new) {
+                       my ($installed) = grep({ $_->signature eq $p } @installeds);
+                       if ($installed) {
+                               # uninstall
+                               $create_task_remove->($installed, $p, $new);
+                               next;
+                       }
+                       else {
+                               # do nothing
+                               next;
+                       }
+               }
+               else {
+                       my ($inst) = grep({ $_->signature eq $p } @installeds);
+                       if ($inst && ($inst->version eq $new)) {
+                               # do nothing
+                               next;
+                       }
+
+                       my $new_pkg = $availables->{$p}->{$new};
+
+                       $create_task_download->($new_pkg, $p, $new);
+                       if (grep({ $_->signature eq $p } @installeds)) {
+                               # upgrade
+                               $create_task_upgrade->($new_pkg, $p, $new);
+                       }
+                       else {
+                               # install
+                               $create_task_install->($new_pkg, $p, $new);
+                       }
+               }
+       }
+
+       $upgrade->{tasks} = [
+               (@{ $task_download->{tasks} } ? ($task_download) : ()),
+               (@{ $task_install->{tasks} } ? ($task_install) : ()),
+               (@{ $task_remove->{tasks} } ? ($task_remove) : ()),
+               (@{ $task_upgrade->{tasks} } ? ($task_upgrade) : ()),
+       ];
+
+       $upgrade->{temp_dir} = tempdir();
+
+       $upgrade->{upgrade_script} = $app->mt_path . $app->config->UpgradeScript;
+
+       $app->session('pluginmanager_upgrade', $upgrade);
+
+       require JSON;
+       my $json = JSON::objToJson($upgrade);
+       return $json;
+}
+
+my @config_scalar_keys = (
+       'download_unit', 'ftp_host', 'ftp_user', 'ftp_directory',
+);
+my @config_array_keys = (
+       'repositories',
+);
+
+sub ftp_prompt {
+    my ($plugin, $app, $param) = @_;
+       $param->{'id'} = $app->param('id');
+    $plugin->load_tmpl('pm_ftp_prompt.tmpl', $param);
+}
+
+sub setting {
+    my ($plugin, $app, $param) = @_;
+
+       my $hash = $plugin->get_config_hash;
+
+       foreach my $k (@config_scalar_keys) {
+               $param->{$k} = $hash->{$k} if $hash->{$k};
+       }
+
+       foreach my $k (@config_array_keys) {
+               $param->{$k} = join("\n", @{ $hash->{$k} }) if $hash->{$k};
+       }
+
+       $param->{updated} = $app->param('updated') ? 1 : 0;
+       $param->{initialize} = $app->param('initialize') ? 1 : 0;
+
+    $plugin->load_tmpl('pm_setting.tmpl', $param);
+}
+
+sub update_setting {
+    my ($plugin, $app, $param) = @_;
+
+       my $hash = $plugin->get_config_hash;
+
+       foreach my $k (@config_scalar_keys) {
+               if (my $v = $app->param($k)) {
+                       $hash->{$k} = $v;
+               }
+       }
+
+       foreach my $k (@config_array_keys) {
+               if (my $v = $app->param($k)) {
+                       $hash->{$k} = [ split(/\r\n|\r|\n/, $v) ];
+               }
+       }
+
+       $plugin->set_config_value($hash);
+
+    $app->redirect(
+        $app->app_uri . '?__mode=pluginmanager&op=setting&updated=1&time=' . time
+    );
+}
+
+sub import {
+    my ($plugin, $app, $param) = @_;
+
+       my $writable = &writable;
+
+       if (! $app->param('time')) {
+               if (
+                       (! $writable) && (! &has_ftp_settings)
+               ) {
+                       return $app->redirect(
+                               $app->app_uri . '?__mode=pluginmanager&op=setting&initialize=1'
+                       );
+               }
+       }
+
+
+       $param->{listing_screen} = 1;
+       $param->{imported_package} = $app->param('imported_package') ? 1 : 0;
+       $param->{imported_distribution} = $app->param('imported_distribution') ? 1 : 0;
+       $param->{writable} = $writable;
+
+    $plugin->load_tmpl('pm_import.tmpl', $param);
+}
+
+sub do_import {
+    my ($plugin, $app, $param) = @_;
+       my ($imported, $c);
+
+    require LWP::UserAgent;
+
+       my $ua = LWP::UserAgent->new;
+       if (my $proxy = MT->config('HTTPProxy')) {
+               $ua->proxy('http', $proxy);
+       }
+       $ua->timeout(10);
+
+       if (my $fh = $app->param('import_package_file')) {
+               my ($temp, $filename) = tempfile();
+               while (read($fh, $c, 1024)) {
+                       print($temp $c);
+               }
+               close($temp);
+               close($fh);
+
+               &install($filename);
+               $imported = 'imported_package';
+       }
+
+       if (my $url = $app->param('import_package_url')) {
+        my $response = $ua->get($url);
+        if ($response->is_success) {
+                       my ($temp, $filename) = tempfile();
+                       print($temp $response->content);
+                       close($temp);
+
+                       &install($filename);
+        }
+        else {
+            die $response->status_line;
+        }
+               $imported = 'imported_package';
+       }
+
+       if (my $fh = $app->param('import_distribution_file')) {
+               my ($temp, $filename) = tempfile();
+               while (read($fh, $c, 1024)) {
+                       print($temp $c);
+               }
+               close($temp);
+               close($fh);
+
+               &install_distribution($filename);
+               $imported = 'imported_distribution';
+       }
+
+       if (my $url = $app->param('import_distribution_url')) {
+        my $response = $ua->get($url);
+        if ($response->is_success) {
+                       my ($temp, $filename) = tempfile();
+                       print($temp $response->content);
+                       close($temp);
+
+                       &install_distribution($filename);
+        }
+        else {
+            die $response->status_line;
+        }
+               $imported = 'imported_distribution';
+       }
+
+    $app->redirect(
+        $app->app_uri . '?__mode=pluginmanager&op=import&' . $imported . '=1&time=' . time
+    );
+}
+
+sub export {
+    my ($plugin, $app, $param) = @_;
+
+       my $cwd = getcwd;
+
+       require PluginManager::Repository;
+       my $url = PluginManager::Repository::repository_url();
+
+       my $pool = PluginManager::Repository::repository_pool();
+       chdir($pool);
+       my @pkgs = map({
+               my $hash = {};
+               $hash = {
+                       'filename' => $_,
+                       'url' => $url . 'pool/' . $_,
+               };
+               $hash;
+       } glob(File::Spec->catfile('*.mpm')));
+       chdir($cwd);
+       $param->{'packages'} = \@pkgs if @pkgs;
+
+       my $root = PluginManager::Repository::repository_root();
+       chdir($root);
+       my @dists = map({
+               my $hash = {};
+               $hash = {
+                       'filename' => $_,
+                       'url' => $url . $_,
+               };
+               $hash;
+       } glob(File::Spec->catfile('*.mpd')));
+       chdir($cwd);
+       $param->{'distributions'} = \@dists if @dists;
+
+       $param->{'available_components'} = [ map({
+               my $c = $app->component($_);
+               my %hash = ();
+               $hash{$_} = $c->$_ for ('id', 'name');
+               \%hash;
+       } PluginManager::Repository::available_components()) ];
+
+       $param->{listing_screen} = 1;
+       $param->{created_package} = $app->param('created_package') ? 1 : 0;
+       $param->{created_distribution} = $app->param('created_distribution') ? 1 : 0;
+
+    $plugin->load_tmpl('pm_export.tmpl', $param);
+}
+
+sub do_export {
+    my ($plugin, $app, $param) = @_;
+
+       my $created = 'created_package';
+
+       my @packages = $app->param('packages');
+
+       require PluginManager::Command;
+       my $maker = PluginManager::Command::MakePackage->new;
+       $maker->process({'q' => 1}, @packages);
+
+       if ($app->param('distribution')) {
+               my $updater = PluginManager::Command::MakeDistribution->new;
+               $updater->process();
+               my $created = 'created_distribution';
+       }
+
+    $app->redirect(
+        $app->app_uri . '?__mode=pluginmanager&op=export&' . $created . '=1&time=' . time
+    );
+}
+
+sub repository {
+    my ($plugin, $app, $param) = @_;
+
+       require PluginManager::Repository;
+       $param->{'repository_url'} = PluginManager::Repository::repository_url();
+       $param->{'available_components'} = [ map({
+               my $c = $app->component($_);
+               my %hash = ();
+               $hash{$_} = $c->$_ for ('id', 'name');
+               \%hash;
+       } PluginManager::Repository::available_components()) ];
+
+       $param->{listing_screen} = 1;
+       $param->{created} = $app->param('created') ? 1 : 0;
+
+    $plugin->load_tmpl('pm_repository.tmpl', $param);
+}
+
+sub create_repository {
+    my ($plugin, $app, $param) = @_;
+
+       my @packages = $app->param('packages');
+
+       require PluginManager::Command;
+       my $maker = PluginManager::Command::MakePackage->new;
+       $maker->process({'q' => 1}, @packages);
+
+       my $updater = PluginManager::Command::UpdateRepository->new;
+       $updater->process();
+
+    $app->redirect(
+        $app->app_uri . '?__mode=pluginmanager&op=repository&created=1&time=' . time
+    );
+}
+
+1;
diff --git a/lib/PluginManager/Command.pm b/lib/PluginManager/Command.pm
new file mode 100644 (file)
index 0000000..f31cdbe
--- /dev/null
@@ -0,0 +1,479 @@
+package PluginManager::Command;
+use base qw( Class::Accessor::Fast );
+
+use strict;
+
+use YAML::Tiny;
+use PluginManager::Util;
+use PluginManager::Repository;
+
+sub new {
+       my $class = shift;
+       my $self = shift || {};
+       bless $self , $class;
+
+       return $self;
+}
+
+sub options {
+       ();
+}
+
+sub process {
+       undef;
+}
+
+sub usage {
+       '';
+}
+
+sub repository_root {
+       PluginManager::Repository::repository_root(1);
+}
+
+sub repository_pool {
+       PluginManager::Repository::repository_pool(1);
+}
+
+sub instance_for {
+       my $class = shift;
+       my ($cmd) = @_;
+
+       if ($cmd eq 'make_package') {
+               PluginManager::Command::MakePackage->new;
+       }
+       elsif ($cmd eq 'update_repository') {
+               PluginManager::Command::UpdateRepository->new;
+       }
+       else {
+               PluginManager::Command::Usage->new;
+       }
+}
+
+
+package PluginManager::Command::Error;
+
+sub new {
+       my $class = shift;
+       my $self = { @_ };
+       bless $self , $class;
+
+       $self->{status} ||= -1;
+
+       return $self;
+}
+
+
+package PluginManager::Command::Usage;
+use base qw( PluginManager::Command );
+
+sub usage {
+       <<__EOM__;
+usage: $0 <subcommand> [options] [args]
+__EOM__
+}
+
+sub process {
+       my $self = shift;
+       PluginManager::Command::Error->new(message => $self->usage);
+}
+
+
+package PluginManager::Command::MakePackage;
+use base qw( PluginManager::Command );
+
+use File::Basename;
+use File::Spec;
+use File::Copy::Recursive qw/ rcopy /;
+use File::Find;
+use File::Path;
+use POSIX;
+
+sub usage {
+       <<__EOM__;
+usage: $0 make_package [options] PluginName1 [PluginName2 [PluginName3]]
+__EOM__
+}
+
+sub options {
+       ('all');
+}
+
+sub translate_value {
+       my $self = shift;
+       my ($mod, $word) = @_;
+
+       if (ref($word) eq 'HASH') {
+               foreach my $key (keys(%$word)) {
+                       $word->{$key} = $self->translate_value($mod, $word->{$key});
+               }
+               $word;
+       }
+       elsif (ref($word)) {
+               $word;
+       }
+       else {
+               $mod->translate($word);
+       }
+}
+
+sub make_control_locale {
+       my $self = shift;
+       my ($mod, $locale) = @_;
+
+       MT->set_language($locale);
+
+       my %ctrl = ();
+       foreach my $key (
+               'id', 'name', 'version', 'description',
+               'author_name', 'author_link',
+               'plugin_link', 'doc_link',
+       ) {
+               $ctrl{$key} = $mod->$key;
+       }
+       $ctrl{locale} = $locale;
+
+       my $config = File::Spec->catfile($mod->{full_path}, 'mpm', 'config.yaml');
+       if (-f $config) {
+               my $yaml = YAML::Tiny->read($config);
+               my $info = $yaml->[0];
+               foreach my $key (
+                       'category', 'compatiblity', 'license', 'target',
+               ) {
+                       $ctrl{$key} = $self->translate_value($mod, $info->{$key})
+                               if $info->{$key};
+               }
+       }
+
+       \%ctrl;
+}
+
+sub make_control {
+       my $self = shift;
+       my ($mod) = @_;
+
+       my @ctrls = ();
+
+       my @locales = ();
+       if (my $l10n = $mod->l10n_class) {
+               eval(" require $l10n ; ");
+
+               foreach my $l (keys(%{ MT->supported_languages })) {
+                       my $handle = $l10n->get_handle($l);
+                       if ($handle->language_tag eq $l) {
+                               push(@locales, $l);
+                       }
+               }
+       }
+       else {
+               @locales = ('en-us');
+       }
+
+       foreach my $l (@locales) {
+               my $ctrl = $self->make_control_locale($mod, $l);
+               $ctrl->{locales} = \@locales;
+               push(@ctrls, $ctrl);
+       }
+
+       \@ctrls;
+}
+
+sub make_dir {
+       my $self = shift;
+       my ($mod, $ctrls) = @_;
+
+       my $basename = basename($mod->{full_path}, '.pl');
+       my $ver = $mod->version;
+       my $mpmname = $basename . '-' . $ver;
+
+       my $tmpdir = tempdir( CLEANUP => 1 ); 
+       my $destdir = File::Spec->catdir($tmpdir, $mpmname);
+       mkdir($destdir);
+
+       $destdir;
+}
+
+sub copy_cgi {
+       my $self = shift;
+       my ($mod, $ctrls, $destdir) = @_;
+
+       my $basename = basename($mod->{full_path});
+
+       rcopy(
+               $mod->{full_path},
+               File::Spec->catdir($destdir, 'dist', 'plugins', $basename)
+       );
+}
+
+sub copy_static {
+       my $self = shift;
+       my ($mod, $ctrls, $destdir) = @_;
+
+       my $app = MT->instance;
+       my $static = File::Spec->catdir(
+               $app->server_path(), 'mt-static', 'plugins'
+       );
+       my $basename = basename($mod->{full_path});
+       my $plugin_static = File::Spec->catdir($static, $basename);
+
+       if (-e $plugin_static) {
+               rcopy(
+                       $plugin_static,
+                       File::Spec->catdir($destdir, 'dist', 'mt-static', 'plugins', $basename)
+               );
+       }
+}
+
+sub copy_control {
+       my $self = shift;
+       my ($mod, $ctrls, $destdir) = @_;
+       my $ctrl_dir = File::Spec->catdir(
+               $destdir, 'control'
+       );
+       mkdir($ctrl_dir);
+
+       my $yaml = new YAML::Tiny;
+       foreach my $c (@$ctrls) {
+               my $name = 'control-' . $c->{locale} . '.yaml';
+               $yaml->[0] = $c;
+               $yaml->write(File::Spec->catfile($ctrl_dir, $name));
+       }
+
+       foreach my $f (glob(File::Spec->catdir($mod->{full_path}, 'mpm' , '*'))) {
+               next if not -d $f;
+               my $base = basename($f);
+               rcopy($f, File::Spec->catdir($destdir, $base));
+       }
+}
+
+sub package {
+       my $self = shift;
+       my ($mod, $ctrls, $destdir) = @_;
+
+       my $cwd = getcwd();
+       chdir(dirname($destdir));
+
+       require Archive::Tar;
+       my $tar = Archive::Tar->new;
+       finddepth({
+               wanted => sub {
+                       if ($_ !~ m/(^|\/)(\.svn|CVS|\.git(attributes|ignore)?)(\/|$)/) {
+                               $tar->add_files($_);
+                       }
+
+                       if (-f $_) {
+                               unlink($_);
+                       }
+                       elsif (-d $_) {
+                               rmdir($_);
+                       }
+               },
+               no_chdir => 1,
+       }, basename($destdir));
+
+       chdir($cwd);
+
+       my $pool = $self->repository_pool;
+
+       mkpath($pool);
+
+       my $outfile = File::Spec->catfile($pool, basename($destdir) . '.mpm');
+       $tar->write($outfile, 1);
+
+    my $file_mode = (~ oct(MT->config('UploadUmask'))) & oct('666');
+       chmod($file_mode, $outfile);
+
+       $outfile;
+}
+
+sub available_components {
+       PluginManager::Repository::available_components(@_);
+}
+
+sub process {
+       my $self = shift;
+       my $app = MT->instance;
+       my ($opts, @names) = @_;
+
+       if ($opts->{all}) {
+               @names = $self->available_components;
+       }
+       elsif (! @names) {
+               return PluginManager::Command::Error->new(message => $self->usage);
+       }
+
+       foreach my $name (@names) {
+               my $mod = $app->component($name);
+               if (! $mod) {
+                       my $msg =
+                               "Installed plugins:\n"
+                               . join("\n", $self->available_components)
+                               . "\n";
+                       return PluginManager::Command::Error->new(message => $msg);
+               }
+
+               my $ctrls = $self->make_control($mod);
+               my $destdir = $self->make_dir($mod, $ctrls);
+               $self->copy_cgi($mod, $ctrls, $destdir);
+               $self->copy_static($mod, $ctrls, $destdir);
+               $self->copy_control($mod, $ctrls, $destdir);
+               my $file = $self->package($mod, $ctrls, $destdir);
+
+               if (! $opts->{q}) {
+                       print("$file\n");
+               }
+       }
+}
+
+package PluginManager::Command::UpdateRepository;
+use base qw( PluginManager::Command );
+
+use File::Basename;
+use File::Spec;
+use Digest::MD5  qw(md5 md5_hex md5_base64);
+
+sub usage {
+       <<__EOM__;
+usage: $0 update_repository [options]
+__EOM__
+}
+
+sub process {
+       my $self = shift;
+       my $app = MT->instance;
+       my ($opts) = @_;
+
+       my $root = $self->repository_root;
+       my $packages = {};
+
+       require Archive::Tar;
+       foreach my $mpm (glob(File::Spec->catfile($self->repository_pool, '*.mpm'))) {
+               my $basename = basename($mpm, '.mpm');
+               (my $relative = $mpm) =~ s/$root//;
+               $relative =~ s#^/?#./#;
+
+               my $tar = Archive::Tar->new;
+               $tar->read($mpm, 1);
+
+               my $get_info = sub {
+                       my $file = shift;
+
+                       my $yaml_string = $tar->get_content($file);
+                       my $yaml = YAML::Tiny->read_string($yaml_string);
+
+                       my $pkg = $yaml->[0];
+
+                       $pkg->{filename} = $relative;
+                       $pkg->{size} = (stat($mpm))[7];
+                       $pkg->{md5sum} = md5_hex(do {
+                               open(my $fh, '<', $mpm); local $/; <$fh>;
+                       });
+
+                       $pkg;
+               };
+
+               my $en_us_hash = undef;
+               foreach my $l (keys(%{ MT->supported_languages })) {
+                       my $yaml_file = File::Spec->catfile(
+                               $basename, 'control', 'control-' . $l . '.yaml'
+                       );
+                       if (! $tar->contains_file($yaml_file)) {
+                               $yaml_file = File::Spec->catfile(
+                                       $basename, 'control', 'control-en-us.yaml'
+                               );
+                       }
+
+                       my $pkg = undef;
+                       if ($yaml_file =~ m/en-us\.yaml$/) {
+                               if (! $en_us_hash) {
+                                       $en_us_hash = $pkg = $get_info->($yaml_file);
+                               }
+                               else {
+                                       $pkg = $en_us_hash;
+                               }
+                       }
+                       else {
+                               $pkg = $get_info->($yaml_file);
+                       }
+
+                       my $version = quotemeta($pkg->{version});
+                       #(my $sig = $basename) =~ s/-$version//;
+                       my $sig = $pkg->{id};
+
+                       $packages->{$l} ||= {};
+                       $packages->{$l}->{$sig} ||= {};
+                       $packages->{$l}->{$sig}->{$pkg->{version}} = $pkg;
+               }
+       }
+
+    my $file_mode = (~ oct(MT->config('UploadUmask'))) & oct('666');
+       foreach my $l (keys(%$packages)) {
+               my $file = File::Spec->catfile($root, 'packages-' . $l . '.yaml.gz');
+
+               my $yaml = YAML::Tiny->new;
+               $yaml->[0] = $packages->{$l};
+
+               $yaml->write($file);
+
+               my $fh = IO::Zlib->new($file, 'wb9');
+               if (defined $fh) {
+                       print($fh $yaml->write_string);
+                       $fh->close;
+                       chmod($file_mode, $file);
+               }
+       }
+}
+
+package PluginManager::Command::MakeDistribution;
+use base qw( PluginManager::Command );
+
+use File::Basename;
+use File::Spec;
+use File::Find;
+use Cwd;
+
+sub usage {
+       <<__EOM__;
+usage: $0 make_distribution [options]
+__EOM__
+}
+
+sub process {
+       my $self = shift;
+       #PluginManager::Command::UpdateRepository::process($self, @_);
+
+       my $root = $self->repository_root;
+
+       my $cwd = getcwd();
+       chdir($root);
+
+       require Archive::Tar;
+       my $tar = Archive::Tar->new;
+       finddepth({
+               wanted => sub {
+                       if ($_ =~ m/(packages-(.*)\.yaml\.gz|\.mpm)$/) {
+                               $tar->add_files($_);
+                       }
+               },
+               no_chdir => 1,
+       }, '.');
+
+       chdir($cwd);
+
+       my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
+       $year += 1900;
+       $mon++;
+
+       my $outfile = File::Spec->catfile(
+               $root,
+               sprintf(
+                       '%04d%02d%02d%02d%02d.mpd', $year, $mon, $mday, $hour, $min
+               )
+       );
+       $tar->write($outfile, 1);
+
+    my $file_mode = (~ oct(MT->config('UploadUmask'))) & oct('666');
+       chmod($file_mode, $outfile);
+}
+
+1;
diff --git a/lib/PluginManager/Installed.pm b/lib/PluginManager/Installed.pm
new file mode 100644 (file)
index 0000000..65314a7
--- /dev/null
@@ -0,0 +1,34 @@
+package PluginManager::Installed;
+use strict;
+
+use MT::Object;
+use base qw( MT::Object );
+@PluginManager::Installed::ISA = qw( MT::Object );
+__PACKAGE__->install_properties({
+               column_defs => {
+                       'id' => 'integer not null auto_increment',
+                       'signature' => 'string(255) not null',
+                       'version' => 'string(255) not null',
+                       'files' => 'text not null',
+                       'control' => 'text not null',
+                       'script' => 'blob not null',
+               },
+               indexes => {
+                       signature => 1,
+                       version => 1,
+               },
+               primary_key => 'id',
+               datasource => 'pm_installed',
+               audit => 1,
+       });
+1;
+
+sub make_control_locale {
+       my $self = shift;
+       my ($locale) = @_;
+
+       require YAML::Tiny;
+       my $yaml = YAML::Tiny->read_string($self->control);
+
+       $yaml->[0]{$locale} || $yaml->[0]{'en-us'};
+}
diff --git a/lib/PluginManager/L10N.pm b/lib/PluginManager/L10N.pm
new file mode 100644 (file)
index 0000000..cd3506f
--- /dev/null
@@ -0,0 +1,5 @@
+package PluginManager::L10N;
+use strict;
+use base 'MT::Plugin::L10N';
+
+1;
diff --git a/lib/PluginManager/L10N/en_us.pm b/lib/PluginManager/L10N/en_us.pm
new file mode 100644 (file)
index 0000000..e1bd647
--- /dev/null
@@ -0,0 +1,9 @@
+package PluginManager::L10N::en_us;
+
+use strict;
+
+use base 'PluginManager::L10N';
+use vars qw( %Lexicon );
+%Lexicon = ();
+
+1;
diff --git a/lib/PluginManager/L10N/ja.pm b/lib/PluginManager/L10N/ja.pm
new file mode 100644 (file)
index 0000000..4c00b11
--- /dev/null
@@ -0,0 +1,90 @@
+package PluginManager::L10N::ja;
+
+use strict;
+use base 'PluginManager::L10N::en_us';
+use vars qw( %Lexicon );
+
+%Lexicon = (
+       'A plugin to manage plugins.' => 'プラグインを管理するプラグインです。',
+
+       'Status' => '状態',
+
+       'Menus' => 'メニュー',
+       'Add/Remove Plugin' => 'プラグインの追加と削除',
+       'Import Plugin' => 'プラグインのインポート',
+       'Export Plugin' => 'プラグインのエクスポート',
+       'Create Repository' => 'リポジトリの作成',
+       'Settings' => '設定',
+
+       'Not specified' => '指定しない',
+
+       'Status' => '状態',
+       'Not installed' => '未インストール',
+       'Installed' => 'インストール済み',
+       'Need upgrade' => '要更新',
+
+       'Category' => 'カテゴリ',
+       'Commenting' => 'Commenting',
+       'Template Set' => 'Template Set',
+       'Text Formatting' => 'Text Formatting',
+       'Web Services' => 'Web Services',
+       'Widgets' => 'Widgets',
+
+       'Compatiblity' => '互換性',
+
+       'License' => 'ライセンス',
+
+       'Target' => 'プラットホーム',
+
+       'Update Packages' => 'プラグイン一覧の更新',
+
+       'Install / Upgrade' => 'インストールと更新',
+
+       'Plugin Manager' => 'プラグイン管理',
+
+       'Package list has been updated.' => 'プラグイン一覧を更新しました',
+       'Are you sure you want to remove the selected plugin?' => 'プラグインを削除してもよろしいですか?',
+
+       'Complete' => '完了',
+       'Upgrade Now' => 'データベースを更新する',
+
+       'Back To List' => 'プラグインの追加と削除へ戻る',
+
+       'Download' => 'ダウンロード',
+       'Install' => 'インストール',
+       'Uninstall' => '削除',
+       'Upgrade' => '更新',
+
+       'Installation/Upgrade successful.' => 'インストールと更新が完了しました。',
+       'Removing successful.' => '削除が完了しました。',
+
+       'Plugin' => 'プラグイン',
+       'Author' => '作成者',
+
+       'Package has been created.' => 'プラグインのパッケージが作成されました。',
+       'Repository has been created.' => 'リポジトリが作成されました。',
+       'Distribution has been created.' => 'ディストリビューションが作成されました。',
+       'created package' => 'パッケージを作成',
+       'created distribution' => 'ディストリビューションを作成',
+       'Repository\'s URL' => 'このMTで作成したリポジトリのURL',
+       'Package has been imported.' => 'プラグインのパッケージがインポートされました。',
+       'Distribution has been imported.' => 'ディストリビューションがインポートされました。',
+       'Import package from file.' => 'ファイルからプラグインをインポートする',
+       'Import package from URL.' => 'URLからプラグインをインポートする',
+       'Import distribution from file.' => 'ファイルからディストリビューションをインポートする',
+       'Import distribution from URL.' => 'URLからディストリビューションをインポートする',
+       'Do Create Package' => 'パッケージを作成',
+       'Do Create Distribution' => 'ディストリビューションを作成',
+       'Do Create Repository' => 'リポジトリの作成',
+
+       'Repository' => 'リポジトリ',
+       'Host' => 'ホスト名',
+       'User' => 'ユーザー名',
+       'Installation directory for MT' => 'MTのインストール先ディレクトリ',
+       'Example: /path/to/mt' => '例: /path/to/mt',
+       'FTP access information' => 'FTPアクセス情報',
+       'Please set FTP information first.' => '最初にFTP情報を設定してください。',
+       'Settings has been updated.' => '設定を更新しました。',
+);
+
+1;
diff --git a/lib/PluginManager/Packages.pm b/lib/PluginManager/Packages.pm
new file mode 100644 (file)
index 0000000..726a69b
--- /dev/null
@@ -0,0 +1,24 @@
+package PluginManager::Packages;
+use strict;
+
+use MT::Object;
+use base qw( MT::Object );
+@PluginManager::Packages::ISA = qw( MT::Object );
+__PACKAGE__->install_properties({
+               column_defs => {
+                       'id' => 'integer not null auto_increment',
+                       'repository' => 'string(255) not null',
+            'locale' => 'string(32) not null',
+                       'packages' => 'blob not null',
+               },
+               indexes => {
+                       repository => 1,
+            locale => 1,
+                       created_on => 1,
+                       modified_on => 1,
+               },
+               primary_key => 'id',
+               datasource => 'pm_packages',
+               audit => 1,
+       });
+1;
diff --git a/lib/PluginManager/Repository.pm b/lib/PluginManager/Repository.pm
new file mode 100644 (file)
index 0000000..96a8d34
--- /dev/null
@@ -0,0 +1,72 @@
+package PluginManager::Repository;
+
+sub repository_root {
+       my ($create_if_not_exists) = @_;
+
+       my $app = MT->instance;
+    my $dir_mode = (~ oct(MT->config('DirUmask'))) & oct('777');
+       #File::Spec->catdir($app->server_path(), 'mpm');
+       my $path = File::Spec->catdir($app->support_directory_path, 'mpm');
+       if (! -d $path && $create_if_not_exists) {
+               mkdir($path);
+               chmod($dir_mode, $path);
+       }
+       $path;
+}
+
+sub repository_pool {
+       my ($create_if_not_exists) = @_;
+
+    my $dir_mode = (~ oct(MT->config('DirUmask'))) & oct('777');
+       my $path = File::Spec->catdir(repository_root(@_), 'pool');
+       if (! -d $path && $create_if_not_exists) {
+               mkdir($path);
+               chmod($dir_mode, $path);
+       }
+       $path;
+}
+
+sub repository_url {
+       my ($create_if_not_exists) = @_;
+
+       my $app = MT->instance;
+       my $root_path = repository_root;
+       
+       return '' if ! -d $root_path;
+
+       return $app->support_directory_url . 'mpm/';
+}
+
+sub available_components {
+       my @defaults = qw(
+               core
+               typepadantispam
+               markdown/smartypants.pl
+               spamlookup/spamlookup_words.pl
+               spamlookup/spamlookup.pl
+               multiblog
+               textile/textile2.pl
+               spamlookup/spamlookup_urls.pl
+               wxrimporter/wxrimporter.pl
+               stylecatcher
+               markdown/markdown.pl
+               cloner/cloner.pl
+               facebookcommenters
+               community
+               actionstreams
+               commercial
+               widgetmanager
+               motion
+               mixicomment
+               feedsapplite
+               communityactionstreams
+       );
+       my $defaults_count = scalar(@defaults);
+       my %comp = %MT::Components;
+       grep({
+               my $c = $_;
+               grep({ $_ ne $c } @defaults) == $defaults_count
+       } keys(%MT::Components));
+}
+
+1;
diff --git a/lib/PluginManager/Util.pm b/lib/PluginManager/Util.pm
new file mode 100644 (file)
index 0000000..7b2ecb6
--- /dev/null
@@ -0,0 +1,24 @@
+package PluginManager::Util;
+
+use strict;
+use warnings;
+
+use File::Temp;
+use Exporter;
+
+our @EXPORT = qw(tempdir);
+use base qw(Exporter);
+
+my $tmp_dir = undef;
+
+sub tempdir {
+       $tmp_dir ||= MT->config('TempDir');
+       File::Temp::tempdir(@_, DIR => $tmp_dir);
+}
+
+sub tempfile {
+       $tmp_dir ||= MT->config('TempDir');
+       File::Temp::tempfile(@_, DIR => $tmp_dir);
+}
+
+1;
diff --git a/tmpl/include/pm_menus.tmpl b/tmpl/include/pm_menus.tmpl
new file mode 100644 (file)
index 0000000..c1ad3cd
--- /dev/null
@@ -0,0 +1,11 @@
+    <mtapp:widget
+        id="manager_menus"
+        label="<__trans phrase="Menus">">
+        <ul>
+            <li><a href="<mt:var name="link_package_list">"><__trans phrase="Add/Remove Plugin"></a></li>
+            <li><a href="<mt:var name="link_import">"><__trans phrase="Import Plugin"></a></li>
+            <li><a href="<mt:var name="link_export">"><__trans phrase="Export Plugin"></a></li>
+            <li><a href="<mt:var name="link_repository">"><__trans phrase="Create Repository"></a></li>
+            <li><a href="<mt:var name="link_setting">"><__trans phrase="Settings"></a></li>
+        </ul>
+    </mtapp:widget>
diff --git a/tmpl/include/pm_package_list_table.tmpl b/tmpl/include/pm_package_list_table.tmpl
new file mode 100644 (file)
index 0000000..b007cc5
--- /dev/null
@@ -0,0 +1,402 @@
+<style>
+.updated img {
+       background-image:url(<mt:StaticWebPath />images/status_icons/success.gif);
+}
+.need_upgrade img {
+       background-image:url(<mt:StaticWebPath />images/status_icons/warning.gif);
+}
+.not_installed img {
+       background-image:url(<mt:StaticWebPath />images/status_icons/draft.gif);
+}
+
+.listing td.cb {
+       vertical-align: middle;
+}
+
+.listing td.description {
+       border-top: 1px dotted #999;
+}
+</style>
+
+<form id="do_upgrade_form">
+
+
+<div class="filter first-child last-child">
+       <div>
+                       <__trans phrase="Status" />
+                       <select id="status">
+                               <option value="" class="first-child"><__trans phrase="Not specified" /></option>
+                               <option value="not_installed"><__trans phrase="Not installed" /></option>
+                               <option value="installed"><__trans phrase="Installed" /></option>
+                               <option value="need_upgrade" class="last-child"><__trans phrase="Need upgrade" /></option>
+                       </select>
+       </div>
+       <div>
+                       <__trans phrase="Category" />
+                       <select id="category">
+                               <option value="" class="first-child"><__trans phrase="Not specified" /></option>
+
+                               <option value="action streams"><__trans phrase="Action Streams" /></option>
+                               <option value="administrative/user interface"><__trans phrase="Administrative/User Interface" /></option>
+                               <option value="anti-spam"><__trans phrase="Anti-spam" /></option>
+                               <option value="commenting"><__trans phrase="Commenting" /></option>
+                               <option value="community"><__trans phrase="Community" /></option>
+                               <option value="developer"><__trans phrase="Developer" /></option>
+                               <option value="organization"><__trans phrase="Organization" /></option>
+                               <option value="photos"><__trans phrase="Photos" /></option>
+                               <option value="template set"><__trans phrase="Template Set" /></option>
+                               <option value="template/tag helpers"><__trans phrase="Template/Tag Helpers" /></option>
+                               <option value="text formatting"><__trans phrase="Text Formatting" /></option>
+                               <option value="utility"><__trans phrase="Utility" /></option>
+                               <option value="web services"><__trans phrase="Web Services" /></option>
+                               <option value="widgets"><__trans phrase="Widgets" /></option>
+
+                               <option value="joke"><__trans phrase="Joke" /></option>
+                       </select>
+       </div>
+       <div>
+                       <__trans phrase="Compatiblity" />
+                       <select id="compatiblity">
+                               <option value="" class="first-child"><__trans phrase="Not specified" /></option>
+                               <option value="4">4</option>
+                               <option value="5">5</option>
+                       </select>
+       </div>
+       <div>
+                       <__trans phrase="License" />
+                       <select id="license">
+                               <option value="" class="first-child"><__trans phrase="Not specified" /></option>
+                               <option value="freeware"><__trans phrase="Freeware" /></option>
+                               <option value="donationware"><__trans phrase="Donationware" /></option>
+                               <option value="shareware"><__trans phrase="Shareware" /></option>
+                               <option value="commercial"><__trans phrase="Commercial" /></option>
+                               <option value="gpl"><__trans phrase="GPL" /></option>
+                               <option value="bsd"><__trans phrase="BSD" /></option>
+                               <option value="mit"><__trans phrase="MIT" /></option>
+                               <option value="perl artistic"><__trans phrase="Perl Artistic" /></option>
+                               <option value="multiple"><__trans phrase="Multiple" /></option>
+                       </select>
+       </div>
+       <div>
+                       <__trans phrase="Target" />
+                       <select id="target">
+                               <option value="" class="first-child"><__trans phrase="Not specified" /></option>
+                               <option value="open source"><__trans phrase="Open Source" /></option>
+                               <option value="commercial"><__trans phrase="Commercial" /></option>
+                               <option value="enterprise "><__trans phrase="Enterprise " /></option>
+                       </select>
+       </div>
+       <div>
+               <button onclick="update_table(); return false"><__trans phrase="Filter" /></button>
+       </div>
+</div>
+
+<br />
+
+<div id="actions-bar-top" class="actions-bar actions-bar-top">
+    <span class="button-actions actions">
+               <button
+                       accesskey="r"
+                       title=""
+                       id="do_update"
+                       onclick="window.location.href = '<mt:var name="link_package_update">'; return false;"
+               ><__trans phrase="Update Packages"></button>
+       </span>
+</div>
+
+<div id="actions-bar-top" class="actions-bar actions-bar-top">
+<!--
+       <div id="pagination-top" class="pagination">
+               <span class="start-disabled"><em>&lt;&lt;</em>&nbsp;</span>
+               <span class="to-start-disabled"><em>&lt;</em>&nbsp;</span>
+               <span class="current-rows">1 &ndash; 112 / 112</span>
+               <span class="to-end-disabled">&nbsp;<em>&gt;</em></span>
+               <span class="end-disabled">&nbsp;<em>&gt;&gt;</em></span>
+       </div>
+-->
+
+    <span class="button-actions actions">
+               <button
+                       accesskey="r"
+                       title=""
+                       id="do_upgrade"
+               ><__trans phrase="Install / Upgrade"></button>
+               <button
+                       accesskey="x"
+                       title=""
+                       id="do_remove"
+               ><__trans phrase="Remove"></button>
+       </span>
+
+<!--
+    <span class="plugin-actions actions">
+       <select name="plugin_action_selector" onchange="updatePluginAction(this)">
+               <option value="0">アクション...</option>
+               <option value="set_draft">ブログ記事の公開を取り消し</option>
+               <option value="add_tags">タグの追加</option>
+               <option value="remove_tags">タグの削除</option>
+       </select>
+       <button
+               class="small-button mt-entry-listing-form-action"
+       >Go</button>
+    </span>
+-->
+</div>
+
+<div class="listing">
+<!--
+<table id="package_table">
+-->
+<table id="package_table" class="entry-listing-table compact" cellspacing="0">
+        <thead>
+            <tr>
+                <th class="cb"><input type="checkbox" name="id-head" value="all" class="select" /></th>
+                <th class="status si">
+                    <img src="<mt:StaticWebPath />images/status_icons/invert-flag.gif" alt="" title="" width="9" height="9" />
+                </th>
+                <th class="title primary-col"><__trans phrase="Name" /></th>
+                               <th class="category"><__trans phrase="Category" /></th>
+                <th class="author"><__trans phrase="Author" /></th>
+                <th class="weblog"><__trans phrase="Compatiblity" /></th>
+                <th class="datetime"><__trans phrase="License" /></th>
+                <th class="view"><__trans phrase="Target" /></th>
+            </tr>
+        </thead>
+        <tfoot>
+            <tr>
+                <th class="cb"><input type="checkbox" name="id-head" value="all" class="select" /></th>
+                <th class="status si">
+                    <img src="<mt:StaticWebPath />images/status_icons/invert-flag.gif" alt="" title="" width="9" height="9" />
+                </th>
+                <th class="title primary-col"><__trans phrase="Name" /></th>
+                               <th class="category"><__trans phrase="Category" /></th>
+                <th class="author"><__trans phrase="Author" /></th>
+                <th class="weblog"><__trans phrase="Compatiblity" /></th>
+                <th class="datetime"><__trans phrase="License" /></th>
+                <th class="view"><__trans phrase="Target" /></th>
+            </tr>
+        </tfoot>
+               <tbody>
+
+<tr id="package_row_template">
+       <td rowspan="2" class="cb">
+               <input type="hidden" class="version" name="" value="" />
+               <input type="checkbox" name="packages" value="" />
+       </td>
+       <td><img width="9" height="9" alt="" src="<mt:StaticWebPath />images/spacer.gif"/></td>
+       <td class="package_name"> </td>
+       <td class="category"> </td>
+       <td class="author"> </td>
+       <td class="compatiblity"> </td>
+       <td class="license"> </td>
+       <td class="target"> </td>
+</tr>
+<tr id="package_row_template2">
+       <td class="description" colspan="8"> </td>
+</tr>
+
+</tbody>
+</table>
+</div>
+
+<script type="text/javascript">
+var update_table = function() { };
+jQuery(function() {
+       $ = jQuery;
+       var table = $('#package_table tbody');
+       var tmpl = $('#package_row_template');
+       var tmpl2 = $('#package_row_template2');
+
+       $('input[type="checkbox"].select').click(function() {
+               $('input[type="checkbox"]').attr('checked', this.checked);
+       });
+
+       var packages = {
+       <mt:loop name="packages" glue=",">
+               '<mt:var name="__key__" encode_js="1">': {
+               <mt:loop name="__value__" glue=",">
+                       '<mt:var name="__key__" encode_js="1">': {
+                               'id': '<mt:var name="__value__{id}" encode_js="1">',
+                               'name': '<mt:var name="__value__{name}" encode_js="1">',
+                               'version': '<mt:var name="__value__{version}" encode_js="1">',
+                               'author_link': '<mt:var name="__value__{author_link}" encode_js="1">',
+                               'author_name': '<mt:var name="__value__{author_name}" encode_js="1">',
+                               'description': '<mt:var name="__value__{description}" encode_js="1">',
+                               'doc_link': '<mt:var name="__value__{doc_link}" encode_js="1">',
+                               'plugin_link': '<mt:var name="__value__{plugin_link}" encode_js="1">',
+
+                               'category': '<mt:var name="__value__{category}" encode_js="1">',
+                               <mt:var name="__value__{compatiblity}" setvar="compatiblity" />
+                               'compatiblity': [<mt:loop name="compatiblity" glue=",">'<mt:var name="__value__" encode_js="1">'</mt:loop>],
+                               'license': '<mt:var name="__value__{license}" encode_js="1">',
+                               <mt:var name="__value__{target}" setvar="target" />
+                               'target': [<mt:loop name="target" glue=",">'<mt:var name="__value__" encode_js="1">'</mt:loop>],
+
+                               'installed': '<mt:var name="__value__{installed}" encode_js="1" >'
+                       }
+               </mt:loop>
+               }
+       </mt:loop>
+       };
+
+       function version_compare(a, b) {
+               var atmp = a.replace(/\D/, '.').replace(/\.+/, '.').split(/\./);
+               var btmp = b.replace(/\D/, '.').replace(/\.+/, '.').split(/\./);
+
+               var i = 0;
+               while (true) {
+                       if (! atmp[i]) {
+                               if (btmp[i]) {
+                                       return -1;
+                               }
+                               else {
+                                       return 0;
+                               }
+                       }
+                       else if (! btmp[i]) {
+                               return 1;
+                       }
+                       else if (atmp[i] != btmp[i]) {
+                               return atmp[i] - btmp[i];
+                       }
+                       i++;
+               }
+       }
+
+       update_table = function(filter) {
+               table.children().remove();
+               var index = 0;
+
+               var filters = [];
+               filters['status'] = $('#status').val().toLowerCase();
+               filters['category'] = $('#category').val().toLowerCase();
+               filters['compatiblity'] = $('#compatiblity').val().toLowerCase();
+               filters['license'] = $('#license').val().toLowerCase();;
+               filters['target'] = $('#target').val().toLowerCase();
+               var auto_filter1 = ['category', 'license'];
+               var auto_filter2 = ['compatiblity', 'target'];
+
+               $.each(packages, function(k, v) {
+                       var version = "0";
+                       var installed_version = "";
+                       var param = {};
+                       $.each(v, function(kk, vv) {
+                               if (version_compare(kk, version) > 0) {
+                                       $.each(vv, function(kkk, vvv) {
+                                               param[kkk] = vvv;
+                                       });
+                                       version = kk;
+                               }
+
+                               if (vv.installed) {
+                                       installed_version = kk;
+                               }
+                       });
+
+
+                       for (var i = 0; i < auto_filter1.length; i++) {
+                               var filter_key = auto_filter1[i];
+                               if (
+                                       (filters[filter_key] != '')
+                                       && (filters[filter_key] != param[filter_key].toLowerCase())
+                               ) {
+                                       return true;
+                               }
+                       }
+
+                       for (var i = 0; i < auto_filter2.length; i++) {
+                               var filter_key = auto_filter2[i];
+                               if (filters[filter_key] != '') {
+                                       var found = false;
+
+                                       for (var j = 0; j < param[filter_key].length; j++) {
+                                               if (filters[filter_key] == param[filter_key][j]) {
+                                                       found = true;
+                                               }
+                                       }
+
+                                       if (! found) {
+                                               return true;
+                                       }
+                               }
+                       }
+
+                       var row = tmpl.clone();
+                       if ((index % 2) == 1) {
+                               row.addClass('even');
+                       }
+
+                       if (installed_version) {
+                               if (installed_version == version) {
+                                       row.addClass('updated');
+                                       if (
+                                               (filters['status'] != '')
+                                               && (filters['status'] != 'installed') 
+                                       ) {
+                                               return true;
+                                       }
+                               }
+                               else {
+                                       row.addClass('need_upgrade');
+                                       if (
+                                               (filters['status'] != '')
+                                               && (filters['status'] != 'installed') 
+                                               && (filters['status'] != 'need_upgrade') 
+                                       ) {
+                                               return true;
+                                       }
+                               }
+                       }
+                       else {
+                               row.addClass('not_installed');
+                               if (
+                                       (filters['status'] != '')
+                                       && (filters['status'] != 'not_installed') 
+                               ) {
+                                       return true;
+                               }
+                       }
+
+                       row.find('.version').
+                               attr('name', param.id).
+                               val(param.version);
+                       row.find('[name="packages"]').val(param.id);
+                       row.find('.package_name').append(param.name);
+                       row.find('.category').append(param.category);
+                       row.find('.compatiblity').append(param.compatiblity.join(','));
+                       row.find('.license').append(param.license);
+                       row.find('.target').append(param.target.join('<br />'));
+
+                       if (param.author_link) {
+                               row.find('.author').append(
+                                       '<a href="' + param.author_link + '" target="_blank">'
+                                       + param.author_name + '</a>'
+                               );
+                       }
+                       else {
+                               row.find('.author').append(param.author_name);
+                       }
+
+                       row.show();
+
+                       table.append(row);
+
+
+                       var row2 = tmpl2.clone();
+                       if ((index % 2) == 1) {
+                               row2.addClass('even');
+                       }
+                       row2.find('.description').append(param.description);
+                       row2.show();
+                       table.append(row2);
+
+
+                       index++;
+               });
+       };
+
+       update_table();
+});
+</script>
+
+</form>
diff --git a/tmpl/pm_export.tmpl b/tmpl/pm_export.tmpl
new file mode 100644 (file)
index 0000000..7c9b0ee
--- /dev/null
@@ -0,0 +1,126 @@
+<mt:setvarblock name="page_title"><__trans phrase="Plugin Manager"> - <__trans phrase="Export Plugin" /></mt:setvarblock>
+
+<mt:setvarblock name="system_msg">
+    <div id="msg-container">
+    <mt:if name="created_package">
+               <mtapp:statusmsg
+                       id="created_package"
+                       class="success"
+               >
+                       <__trans phrase="Package has been created.">
+               </mtapp:statusmsg>
+       </mt:if>
+    <mt:if name="created_distribution">
+               <mtapp:statusmsg
+                       id="created_distribution"
+                       class="success"
+               >
+                       <__trans phrase="Distribution has been created.">
+               </mtapp:statusmsg>
+       </mt:if>
+       </div>
+</mt:setvarblock>
+
+<mt:setvarblock name="related_content">
+       <mt:include name="include/pm_menus.tmpl">
+</mt:setvarblock>
+
+<mt:setvarblock name="html_head" append="1">
+</mt:setvarblock>
+
+<mt:include name="include/header.tmpl">
+
+<div id="plugin_manager_contents">
+
+<form action="<mt:AdminCGIPath /><mt:AdminScript />" method="post">
+       <input type="hidden" name="__mode" value="pluginmanager" />
+       <input type="hidden" name="op" value="do_export" />
+
+               <mt:If name="packages">
+               <__trans phrase="created package">
+               <ul>
+               <mt:Loop name="packages">
+                       <li><a href="<mt:Var name="url" />"><mt:Var name="filename" /></a></li>
+               </mt:Loop>
+               </ul>
+               </mt:If>
+
+               <mt:If name="distributions">
+               <__trans phrase="created distribution">
+               <ul>
+               <mt:Loop name="distributions">
+                       <li><a href="<mt:Var name="url" />"><mt:Var name="filename" /></a></li>
+               </mt:Loop>
+               </ul>
+               </mt:If>
+
+<mt:if name="repository_url">
+<div id="actions-bar-top" class="actions-bar actions-bar-top">
+       <__trans phrase="Repository's URL">
+       <input type="text" value="<mt:var name="repository_url" />" readonly="readonly" style="width: 100%; background: white !important;"/>
+</div>
+</mt:if>
+
+<div id="actions-bar-top" class="actions-bar actions-bar-top">
+    <span class="button-actions actions">
+               <button
+                       type="submit"
+                       accesskey="r"
+                       title=""
+                       id="create_package"
+                       name="package"
+                       value="1"
+               ><__trans phrase="Do Create Package"></button>
+               <button
+                       type="submit"
+                       accesskey="r"
+                       title=""
+                       id="create_distribution"
+                       name="distribution"
+                       value="1"
+               ><__trans phrase="Do Create Distribution"></button>
+       </span>
+</div>
+
+<div class="listing">
+<!--
+<table id="package_table">
+-->
+<table id="package_table" class="entry-listing-table compact" cellspacing="0">
+        <thead>
+            <tr>
+                <th class="cb"><input type="checkbox" name="id-head" value="all" class="select" /></th>
+                <th class="title primary-col"><__trans phrase="Plugin" /></th>
+            </tr>
+        </thead>
+        <tfoot>
+            <tr>
+                <th class="cb"><input type="checkbox" name="id-head" value="all" class="select" /></th>
+                <th class="title primary-col"><__trans phrase="Name" /></th>
+            </tr>
+        </tfoot>
+               <tbody>
+
+               <mt:Loop name="available_components">
+               <tr>
+                       <td class="cb"><input type="checkbox" name="packages" value="<mt:Var name="id" />" /></td>
+                       <td class="package_name"><mt:Var name="name" /></td>
+               </tr>
+               </mt:Loop>
+</tbody>
+</table>
+</div>
+
+<script type="text/javascript">
+jQuery(function() {
+       $ = jQuery;
+       $('input[type="checkbox"].select').click(function() {
+               $('input[type="checkbox"]').attr('checked', this.checked);
+       });
+});
+</script>
+
+</form>
+</div>
+
+<mt:include name="include/footer.tmpl">
diff --git a/tmpl/pm_ftp_prompt.tmpl b/tmpl/pm_ftp_prompt.tmpl
new file mode 100644 (file)
index 0000000..bf7ca9d
--- /dev/null
@@ -0,0 +1,33 @@
+<mt:setvarblock name="page_title"><__trans phrase="FTP access information"></mt:setvarblock>
+
+<mt:include name="dialog/header.tmpl">
+
+<form>
+       <div class="field required field-left-label" id="name-field">
+               <div class="field-header first-child">
+                 <label for="name" id="name-label" class="first-child last-child"><__trans phrase="Password" /></label>
+               </div>
+               <div class="field-content last-child">
+                       <input type="password" id="password" name="password" style="width: 100%;" />
+               </div>
+       </div>
+    <div class="actions-bar">
+        <div class="actions-bar-inner actions">
+            <button
+                type="submit"
+                accesskey="s"
+                title="<__trans phrase="Continue (s)">"
+                class="primary-button, mt-close-dialog"
+                               onclick="window.parent.jQuery('#<mt:Var name="id" />').trigger('process', [$('#password').val()]); return false;"
+                ><__trans phrase="Continue"></button>
+                       <button
+                               type="submit"
+                               accesskey="x"
+                               title="<__trans phrase="Cancel (x)">"
+                               class="mt-close-dialog"
+                               ><__trans phrase="Cancel"></button>
+        </div>
+    </div>
+</form>
+
+<mt:include name="dialog/footer.tmpl">
diff --git a/tmpl/pm_import.tmpl b/tmpl/pm_import.tmpl
new file mode 100644 (file)
index 0000000..1c5244c
--- /dev/null
@@ -0,0 +1,142 @@
+<mt:setvarblock name="page_title"><__trans phrase="Plugin Manager"> - <__trans phrase="Import Plugin" /></mt:setvarblock>
+
+<mt:setvarblock name="system_msg">
+    <div id="msg-container">
+    <mt:if name="imported_package">
+               <mtapp:statusmsg
+                       id="imported_package"
+                       class="success"
+               >
+                       <__trans phrase="Package has been imported.">
+               </mtapp:statusmsg>
+       </mt:if>
+    <mt:if name="imported_distribution">
+               <mtapp:statusmsg
+                       id="imported_distribution"
+                       class="success"
+               >
+                       <__trans phrase="Distribution has been imported.">
+               </mtapp:statusmsg>
+       </mt:if>
+       </div>
+</mt:setvarblock>
+
+<mt:setvarblock name="related_content">
+       <mt:include name="include/pm_menus.tmpl">
+</mt:setvarblock>
+
+<mt:setvarblock name="html_head" append="1">
+<script type="text/javascript">
+jQuery.noConflict();
+jQuery(function() {
+       var $ = jQuery;
+
+       $('button[type="submit"]').click(function(ev) {
+               ev.preventDefault();
+               ev.stopPropagation();
+
+               if (<mt:Var name="writable" /> == 1) {
+                       $('#' + this.id).trigger('process');
+                       return false;
+               }
+
+               jQuery('<a />').
+                       attr(
+                               'href',
+                               ScriptURI + '?' + '__mode=pluginmanager&' +
+                               'op=ftp_prompt&blog_id=0&id=' + this.id
+                       ).
+                       insertAfter('#footer').
+                       mtDialog().
+                       trigger('click');
+       }).
+       bind('process', function(ev, ftp_pass) {
+               $(this.form).find('input[name="ftp_password"]').val(ftp_pass);
+               this.form.submit();
+               return false;
+       });
+});
+</script>
+<style type="text/css">
+#plugin_manager_contents {
+       position: relative;
+}
+
+#plugin_manager_contents ul {
+       margin: 0px 0px 0px 20px;
+}
+
+#plugin_manager_contents li.not_yet {
+       font-weight: normal;
+       color: #ccc;
+}
+#plugin_manager_contents li.doing {
+       font-weight: bold;
+       color: #000;
+}
+#plugin_manager_contents li.done {
+       font-weight: normal;
+       color: #000;
+}
+
+#upgrade_progress_loading {
+       text-align: center;
+}
+</style>
+</mt:setvarblock>
+
+<mt:include name="include/header.tmpl">
+
+<div id="plugin_manager_contents">
+
+<form action="<mt:AdminCGIPath /><mt:AdminScript />" method="post" enctype="multipart/form-data">
+       <input type="hidden" name="__mode" value="pluginmanager" />
+       <input type="hidden" name="op" value="do_import" />
+       <input type="hidden" name="ftp_password" />
+
+       <div id="actions-bar-top" class="actions-bar actions-bar-top">
+               <__trans phrase="Import package from file.">
+               <input type="file" name="import_package_file" style="width: 100%;"/>
+               <button type="submit" id="import_package_file_button"><__trans phrase="Import"></button>
+       </div>
+</form>
+
+<form action="<mt:AdminCGIPath /><mt:AdminScript />" method="post" enctype="multipart/form-data">
+       <input type="hidden" name="__mode" value="pluginmanager" />
+       <input type="hidden" name="op" value="do_import" />
+       <input type="hidden" name="ftp_password" />
+
+       <div id="actions-bar-top" class="actions-bar actions-bar-top">
+               <__trans phrase="Import package from URL.">
+               <input type="text" name="import_package_url" style="width: 100%;"/>
+               <button type="submit" id="import_package_url_button"><__trans phrase="Import"></button>
+       </div>
+</form>
+
+<form action="<mt:AdminCGIPath /><mt:AdminScript />" method="post" enctype="multipart/form-data">
+       <input type="hidden" name="__mode" value="pluginmanager" />
+       <input type="hidden" name="op" value="do_import" />
+       <input type="hidden" name="ftp_password" />
+
+       <div id="actions-bar-top" class="actions-bar actions-bar-top">
+               <__trans phrase="Import distribution from file.">
+               <input type="file" name="import_distribution_file" style="width: 100%;"/>
+               <button type="submit" id="import_distribution_file_button" ><__trans phrase="Import"></button>
+       </div>
+</form>
+
+<form action="<mt:AdminCGIPath /><mt:AdminScript />" method="post" enctype="multipart/form-data">
+       <input type="hidden" name="__mode" value="pluginmanager" />
+       <input type="hidden" name="op" value="do_import" />
+       <input type="hidden" name="ftp_password" />
+
+       <div id="actions-bar-top" class="actions-bar actions-bar-top">
+               <__trans phrase="Import distribution from URL.">
+               <input type="text" name="import_distribution_url" style="width: 100%;"/>
+               <button type="submit" id="import_distribution_url_button" ><__trans phrase="Import"></button>
+       </div>
+</form>
+
+</div>
+
+<mt:include name="include/footer.tmpl">
diff --git a/tmpl/pm_package_list.tmpl b/tmpl/pm_package_list.tmpl
new file mode 100644 (file)
index 0000000..25a89e2
--- /dev/null
@@ -0,0 +1,237 @@
+<mt:setvarblock name="page_title"><__trans phrase="Plugin Manager"> - <__trans phrase="Add/Remove Plugin" /></mt:setvarblock>
+
+<mt:setvarblock name="system_msg">
+    <div id="msg-container">
+    <mt:if name="updated">
+               <mtapp:statusmsg
+                       id="updated"
+                       class="success"
+               >
+                       <__trans phrase="Package list has been updated.">
+               </mtapp:statusmsg>
+       </mt:if>
+       </div>
+</mt:setvarblock>
+
+<mt:setvarblock name="related_content">
+       <mt:include name="include/pm_menus.tmpl">
+</mt:setvarblock>
+
+<mt:setvarblock name="html_head" append="1">
+<script type="text/javascript">
+jQuery.noConflict();
+jQuery(function() {
+       $ = jQuery;
+       var upgrade = null;
+       var upgrade_status = {};
+       var ftp_password = null;
+
+       function process(task, callback) {
+               var finish = true;
+               $.each(task, function() {
+                       var t = this;
+                       if (! t.process) {
+                               t.process = 'not_yet';
+                       }
+                       if (! finish || t.process == 'done') {
+                               return;
+                       }
+
+                       $(t.list_item).
+                               removeClass('not_yet').
+                               addClass('doing');
+                       t.process = 'doing';
+
+                       if (finish && t.tasks) {
+                               process(t.tasks, function() {
+                                       $(t.list_item).removeClass('doing').addClass('done');
+                                       t.process = 'done';
+                                       process(task, callback);
+                               });
+                       }
+
+                       if (finish && t.action) {
+                               if (ftp_password) {
+                                       t.action += '&ftp_password=' + ftp_password;
+                               }
+
+                               $.get(t.action, function(data) {
+                                       var ret = eval('(' + data + ')');
+                                       if (! ret.error) {
+                                               $(t.list_item).removeClass('doing').addClass('done');
+                                               t.process = 'done';
+                                               upgrade_status = ret;
+                                               process(task, callback);
+                                       }
+                                       else {
+                                               alert(ret.error);
+                                       }
+                               });
+                       }
+
+                       finish = false;
+               });
+
+               if (finish && callback) {
+                       callback();
+               }
+       }
+
+       $('#do_upgrade, #do_remove').click(function(ev) {
+               ev.preventDefault();
+               ev.stopPropagation();
+
+               var command = this.id;
+               if (command == 'do_remove') {
+                       var confirmed = window.confirm('<__trans phrase="Are you sure you want to remove the selected plugin?" />');
+                       if (! confirmed) {
+                               return false;
+                       }
+               }
+
+               if (<mt:Var name="writable" /> == 1) {
+                       $('#' + this.id).trigger('process');
+                       return false;
+               }
+
+               jQuery('<a />').
+                       attr(
+                               'href',
+                               ScriptURI + '?' + '__mode=pluginmanager&' +
+                               'op=ftp_prompt&blog_id=0&id=' + this.id
+                       ).
+                       insertAfter('#footer').
+                       mtDialog().
+                       trigger('click');
+       }).
+       bind('process', function(ev, ftp_pass) {
+               var command = this.id;
+
+               var param = {
+                       packages: []
+               };
+               var form = $('#do_upgrade_form');
+               form.find('input[name="packages"]:checked').each(function(m) {
+                       param.packages.push(this.value);
+                       if (command == 'do_upgrade') {
+                               param[this.value] = form.
+                                       find('input[name="' + this.value + '"]').
+                                       val();
+                       }
+               });
+               if (ftp_pass) {
+                       ftp_password = param['ftp_password'] = ftp_pass;
+               }
+
+               //$('#package_list').hide();
+               $('#package_list').remove();
+               $('#upgrade_progress').show();
+
+               $.get('<mt:var name="link_upgrade">', param, function(data) {
+                       $('#upgrade_progress_loading').hide();
+
+                       upgrade = eval('(' + data + ')');
+                       var ul0 = document.createElement('ul');
+                       $.each(upgrade.tasks, function() {
+                               var li = document.createElement('li');
+                               li.appendChild(document.createTextNode(this.name));
+                               $(li).addClass('not_yet');
+                               this.list_item = li;
+
+                               var ul = document.createElement('ul');
+                               li.appendChild(ul);
+
+                               $.each(this.tasks, function() {
+                                       var li = document.createElement('li');
+
+                                       li.innerHTML = this.name;
+                                       $(li).addClass('not_yet');
+                                       this.list_item = li;
+                                       ul.appendChild(li);
+                               });
+
+                               ul0.appendChild(li);
+                               $('#upgrade_progress_progress').append(ul0);
+                       });
+
+                       var li = document.createElement('li');
+                       li.appendChild(document.createTextNode('<__trans phrase="Complete">'));
+                       $(li).addClass('not_yet');
+                       ul0.appendChild(li);
+
+                       process(upgrade.tasks, function() {
+                               $(li).addClass('done');
+                               if (upgrade_status.upgrade_required) {
+                                       $(li).append('<ul><li><a href="' + upgrade.upgrade_script + '" target="_blank"><__trans phrase="Upgrade Now"></a></li></ul>');
+                               }
+                               setTimeout(function() {
+                                       if (command == 'do_upgrade') {
+                                               alert('<__trans phrase="Installation/Upgrade successful." />');
+                                       }
+                                       else {
+                                               alert('<__trans phrase="Removing successful." />');
+                                       }
+                               }, 0);
+                       });
+               });
+               return false;
+       });
+
+/*
+       $('#do_close_window').click(function() {
+               $('#package_list').show();
+               $('#upgrade_progress').hide();
+
+               $('#upgrade_progress_progress').empty();
+               return false;
+       });
+*/
+});
+</script>
+<style type="text/css">
+#plugin_manager_contents {
+       position: relative;
+}
+
+#plugin_manager_contents ul {
+       margin: 0px 0px 0px 20px;
+}
+
+#plugin_manager_contents li.not_yet {
+       font-weight: normal;
+       color: #ccc;
+}
+#plugin_manager_contents li.doing {
+       font-weight: bold;
+       color: #000;
+}
+#plugin_manager_contents li.done {
+       font-weight: normal;
+       color: #000;
+}
+
+#upgrade_progress_loading {
+       text-align: center;
+}
+</style>
+</mt:setvarblock>
+
+<mt:include name="include/header.tmpl">
+
+<div id="plugin_manager_contents">
+       <div id="package_list">
+               <mt:include name="include/pm_package_list_table.tmpl">
+       </div>
+       <div id="upgrade_progress" style="display: none">
+               <div id="upgrade_progress_loading">
+                       <img src="<mt:StaticWebPath />images/loadingAnimation.gif" />
+               </div>
+               <div id="upgrade_progress_progress">
+               </div>
+               <div id="upgrade_progress_buttons">
+                       <a href="<mt:var name="link_package_list">"><__trans phrase="Back To List"></a>
+               </div>
+       </div>
+</div>
+
+<mt:include name="include/footer.tmpl">
diff --git a/tmpl/pm_repository.tmpl b/tmpl/pm_repository.tmpl
new file mode 100644 (file)
index 0000000..d83c941
--- /dev/null
@@ -0,0 +1,90 @@
+<mt:setvarblock name="page_title"><__trans phrase="Plugin Manager"> - <__trans phrase="Create Repository" /></mt:setvarblock>
+
+<mt:setvarblock name="system_msg">
+    <div id="msg-container">
+    <mt:if name="created">
+               <mtapp:statusmsg
+                       id="created"
+                       class="success"
+               >
+                       <__trans phrase="Repository has been created.">
+               </mtapp:statusmsg>
+       </mt:if>
+       </div>
+</mt:setvarblock>
+
+<mt:setvarblock name="related_content">
+       <mt:include name="include/pm_menus.tmpl">
+</mt:setvarblock>
+
+<mt:setvarblock name="html_head" append="1">
+</mt:setvarblock>
+
+<mt:include name="include/header.tmpl">
+
+<div id="plugin_manager_contents">
+
+<form action="<mt:AdminCGIPath /><mt:AdminScript />" method="post">
+       <input type="hidden" name="__mode" value="pluginmanager" />
+       <input type="hidden" name="op" value="create_repository" />
+
+<mt:if name="repository_url">
+<div id="actions-bar-top" class="actions-bar actions-bar-top">
+       <__trans phrase="Repository's URL">
+       <input type="text" value="<mt:var name="repository_url" />" readonly="readonly" style="width: 100%; background: white !important;"/>
+</div>
+</mt:if>
+
+<div id="actions-bar-top" class="actions-bar actions-bar-top">
+    <span class="button-actions actions">
+               <button
+                       type="submit"
+                       accesskey="r"
+                       title=""
+                       id="create"
+               ><__trans phrase="Do Create Repository"></button>
+       </span>
+</div>
+
+<div class="listing">
+<!--
+<table id="package_table">
+-->
+<table id="package_table" class="entry-listing-table compact" cellspacing="0">
+        <thead>
+            <tr>
+                <th class="cb"><input type="checkbox" name="id-head" value="all" class="select" /></th>
+                <th class="title primary-col"><__trans phrase="Plugin" /></th>
+            </tr>
+        </thead>
+        <tfoot>
+            <tr>
+                <th class="cb"><input type="checkbox" name="id-head" value="all" class="select" /></th>
+                <th class="title primary-col"><__trans phrase="Name" /></th>
+            </tr>
+        </tfoot>
+               <tbody>
+
+               <mt:Loop name="available_components">
+               <tr>
+                       <td class="cb"><input type="checkbox" name="packages" value="<mt:Var name="id" />" /></td>
+                       <td class="package_name"><mt:Var name="name" /></td>
+               </tr>
+               </mt:Loop>
+</tbody>
+</table>
+</div>
+
+<script type="text/javascript">
+jQuery(function() {
+       $ = jQuery;
+       $('input[type="checkbox"].select').click(function() {
+               $('input[type="checkbox"]').attr('checked', this.checked);
+       });
+});
+</script>
+
+</form>
+</div>
+
+<mt:include name="include/footer.tmpl">
diff --git a/tmpl/pm_setting.tmpl b/tmpl/pm_setting.tmpl
new file mode 100644 (file)
index 0000000..2bfe370
--- /dev/null
@@ -0,0 +1,99 @@
+<mt:setvarblock name="page_title"><__trans phrase="Plugin Manager"> - <__trans phrase="Settings" /></mt:setvarblock>
+
+<mt:setvarblock name="system_msg">
+    <div id="msg-container">
+    <mt:if name="updated">
+               <mtapp:statusmsg
+                       id="updated"
+                       class="success"
+               >
+                       <__trans phrase="Settings has been updated.">
+               </mtapp:statusmsg>
+       </mt:if>
+    <mt:if name="initialize">
+               <mtapp:statusmsg
+                       id="initialize"
+                       class="success"
+               >
+                       <__trans phrase="Please set FTP information first.">
+               </mtapp:statusmsg>
+       </mt:if>
+       </div>
+</mt:setvarblock>
+
+<mt:setvarblock name="related_content">
+       <mt:include name="include/pm_menus.tmpl">
+</mt:setvarblock>
+
+<mt:setvarblock name="html_head" append="1">
+</mt:setvarblock>
+
+<mt:include name="include/header.tmpl">
+
+<div id="plugin_manager_contents">
+
+<form action="<mt:AdminCGIPath /><mt:AdminScript />" method="post">
+       <input type="hidden" name="__mode" value="pluginmanager" />
+       <input type="hidden" name="op" value="update_setting" />
+
+<fieldset>
+    <h3 class="first-child"><__trans phrase="Repository" /></h3>
+
+    <div class="field required field-left-label" id="name-field">
+               <div class="field-header first-child">
+                 <label for="name" id="name-label" class="first-child last-child"><__trans phrase="URL" /></label>
+               </div>
+               <div class="field-content last-child">
+                       <textarea name="repositories" style="width: 100%;"><mt:Var name="repositories" /></textarea>
+               </div>
+       </div>
+
+</fieldset>
+
+<fieldset>
+    <h3 class="first-child"><__trans phrase="FTP" /></h3>
+
+    <div class="field required field-left-label" id="name-field">
+               <div class="field-header first-child">
+                 <label for="name" id="name-label" class="first-child last-child"><__trans phrase="Host" /></label>
+               </div>
+               <div class="field-content last-child">
+                       <input name="ftp_host" value="<mt:Var name="ftp_host" />" style="width: 100%;" />
+               </div>
+       </div>
+    <div class="field required field-left-label" id="name-field">
+               <div class="field-header first-child">
+                 <label for="name" id="name-label" class="first-child last-child"><__trans phrase="User" /></label>
+               </div>
+               <div class="field-content last-child">
+                       <input name="ftp_user" value="<mt:Var name="ftp_user" />" style="width: 100%;" />
+               </div>
+       </div>
+    <div class="field required field-left-label" id="name-field">
+               <div class="field-header first-child">
+                 <label for="name" id="name-label" class="first-child last-child"><__trans phrase="Installation directory for MT" /></label>
+               </div>
+               <div class="field-content last-child">
+                       <input name="ftp_directory" value="<mt:Var name="ftp_directory" />" style="width: 100%;" />
+               </div>
+               <div class="hint last-child">
+                       <__trans phrase="Example: /path/to/mt" />
+               </div>
+       </div>
+
+</fieldset>
+
+<fieldset>
+    <button
+        type="submit"
+        accesskey="s"
+        title="<__trans phrase="Save Changes (s)">"
+        class="save action primary-button"
+        ><__trans phrase="Save Changes"></button>
+</fieldset>
+
+</form>
+
+</div>
+
+<mt:include name="include/footer.tmpl">
diff --git a/tools/plugin-manager b/tools/plugin-manager
new file mode 100755 (executable)
index 0000000..222757a
--- /dev/null
@@ -0,0 +1,49 @@
+#!/usr/bin/perl -w
+
+# Movable Type (r) Open Source (C) 2001-2008 Six Apart, Ltd.
+# This program is distributed under the terms of the
+# GNU General Public License, version 2.
+#
+# $Id: run-periodic-tasks 2380 2008-05-17 22:41:18Z bchoate $
+
+use strict;
+
+use lib 'lib', '../lib';
+
+require MT::Bootstrap;
+require MT;
+
+my $mt = MT->new() or die MT->errstr;
+
+$mt->{vtbl} = { };
+$mt->{is_admin} = 0;
+$mt->{template_dir} = 'cms';
+$mt->{user_class} = 'MT::Author';
+$mt->{plugin_template_path} = 'tmpl';
+$mt->run_callbacks('init_app', $mt);
+
+
+my $status = 0;
+
+require Getopt::Long;
+#Getopt::Long::GetOptions();
+
+require PluginManager::Command;
+
+my $cmd = shift || 'help';
+my $obj = PluginManager::Command->instance_for($cmd);
+
+my %opts = ();
+my %opt_def = map({
+       $_ => \$opts{$_}
+} $obj->options);
+Getopt::Long::GetOptions(%opt_def);
+
+my $result = $obj->process(\%opts, @ARGV);
+
+if (eval{ $result->isa('PluginManager::Command::Error') }) {
+       print STDERR $result->{message};
+       $status = $result->{status};
+}
+
+exit $status;