]> git.immae.eu Git - github/wallabag/wallabag.git/commitdiff
Merge branch 'dev' of github.com:skibbipl/wallabag into skibbipl-dev
authorNicolas Lœuillet <nicolas@loeuillet.org>
Mon, 21 Jul 2014 19:21:55 +0000 (21:21 +0200)
committerNicolas Lœuillet <nicolas@loeuillet.org>
Mon, 21 Jul 2014 19:21:55 +0000 (21:21 +0200)
Conflicts:
locale/pl_PL.utf8/LC_MESSAGES/pl_PL.utf8.mo
locale/pl_PL.utf8/LC_MESSAGES/pl_PL.utf8.po

147 files changed:
.gitignore
CONTRIBUTING.md
README.md
TRANSLATION.md [new file with mode: 0755]
check_setup.php
inc/3rdparty/Session.class.php
inc/3rdparty/class.messages.php
inc/3rdparty/config.php
inc/3rdparty/libraries/PHPePub/EPub.HtmlEntities.php [new file with mode: 0644]
inc/3rdparty/libraries/PHPePub/EPub.NCX.php [new file with mode: 0644]
inc/3rdparty/libraries/PHPePub/EPub.OPF.php [new file with mode: 0644]
inc/3rdparty/libraries/PHPePub/EPub.php [new file with mode: 0644]
inc/3rdparty/libraries/PHPePub/EPubChapterSplitter.php [new file with mode: 0644]
inc/3rdparty/libraries/PHPePub/Logger.php [new file with mode: 0644]
inc/3rdparty/libraries/PHPePub/Zip.php [new file with mode: 0644]
inc/3rdparty/libraries/PHPePub/lib.uuid.LICENCE.txt [new file with mode: 0644]
inc/3rdparty/libraries/PHPePub/lib.uuid.php [new file with mode: 0644]
inc/3rdparty/libraries/content-extractor/ContentExtractor.php
inc/3rdparty/libraries/content-extractor/SiteConfig.php
inc/3rdparty/libraries/feedwriter/FeedItem.php [changed mode: 0644->0755]
inc/3rdparty/libraries/feedwriter/FeedWriter.php [changed mode: 0644->0755]
inc/3rdparty/libraries/html5/TreeBuilder.php
inc/3rdparty/libraries/humble-http-agent/CookieJar.php
inc/3rdparty/libraries/humble-http-agent/HumbleHttpAgent.php
inc/3rdparty/libraries/humble-http-agent/SimplePie_HumbleHttpAgent.php
inc/3rdparty/libraries/language-detect/LanguageDetect.php
inc/3rdparty/libraries/language-detect/LanguageDetect/Exception.php [new file with mode: 0644]
inc/3rdparty/libraries/language-detect/LanguageDetect/ISO639.php [new file with mode: 0644]
inc/3rdparty/libraries/language-detect/LanguageDetect/Parser.php [moved from inc/3rdparty/libraries/language-detect/Parser.php with 94% similarity]
inc/3rdparty/libraries/readability/Readability.php [changed mode: 0644->0755]
inc/3rdparty/makefulltextfeed.php
inc/3rdparty/makefulltextfeedHelpers.php [new file with mode: 0755]
inc/3rdparty/simple_html_dom.php [changed mode: 0644->0755]
inc/3rdparty/site_config/custom/dailymotion.com.txt [new file with mode: 0755]
inc/3rdparty/site_config/custom/index.php [new file with mode: 0644]
inc/3rdparty/site_config/custom/mobile.lemondeinformatique.fr.txt [new file with mode: 0644]
inc/3rdparty/site_config/custom/ted.com.txt [new file with mode: 0755]
inc/3rdparty/site_config/index.php
inc/3rdparty/site_config/standard/.about.com.txt [new file with mode: 0644]
inc/3rdparty/site_config/standard/moo.nac.uci.edu.txt [new file with mode: 0644]
inc/3rdparty/site_config/standard/politico.com.txt [changed mode: 0644->0755]
inc/3rdparty/site_config/standard/version.txt
inc/poche/Database.class.php
inc/poche/Poche.class.php
inc/poche/Tools.class.php [changed mode: 0644->0755]
inc/poche/config.inc.default.php [new file with mode: 0755]
inc/poche/config.inc.php.new [deleted file]
inc/poche/global.inc.php [changed mode: 0644->0755]
inc/poche/pochePictures.php
index.php [changed mode: 0644->0755]
install/index.php [changed mode: 0644->0755]
install/poche.sqlite [changed mode: 0755->0644]
install/postgres.sql
locale/cs_CZ.utf8/LC_MESSAGES/cs_CZ.utf8.po
locale/de_DE.utf8/LC_MESSAGES/de_DE.utf8.mo
locale/de_DE.utf8/LC_MESSAGES/de_DE.utf8.po
locale/en_EN.utf8/LC_MESSAGES/en_EN.utf8.mo
locale/en_EN.utf8/LC_MESSAGES/en_EN.utf8.po
locale/es_ES.utf8/LC_MESSAGES/es_ES.utf8.po
locale/fa_IR.utf8/LC_MESSAGES/fa_IR.utf8.po
locale/fr_FR.utf8/LC_MESSAGES/fr_FR.utf8.mo
locale/fr_FR.utf8/LC_MESSAGES/fr_FR.utf8.po
locale/it_IT.utf8/LC_MESSAGES/it_IT.utf8.po
locale/pl_PL.utf8/LC_MESSAGES/pl_PL.utf8.mo [changed mode: 0755->0644]
locale/pt_BR.utf8/LC_MESSAGES/pt_BR.utf8.mo [new file with mode: 0644]
locale/pt_BR.utf8/LC_MESSAGES/pt_BR.utf8.po [new file with mode: 0644]
locale/ru_RU.utf8/LC_MESSAGES/ru_RU.utf8.mo
locale/ru_RU.utf8/LC_MESSAGES/ru_RU.utf8.po
locale/sl_SI.utf8/LC_MESSAGES/sl_SI.utf8.po
locale/tools/fillCache.php [new file with mode: 0755]
locale/uk_UA.utf8/LC_MESSAGES/uk_UA.utf8.mo
locale/uk_UA.utf8/LC_MESSAGES/uk_UA.utf8.po
themes/baggy/_display-mode.twig [new file with mode: 0755]
themes/baggy/_head.twig [changed mode: 0644->0755]
themes/baggy/_menu.twig
themes/baggy/_pocheit-form.twig [new file with mode: 0755]
themes/baggy/_search-form.twig [new file with mode: 0644]
themes/baggy/_top.twig [changed mode: 0644->0755]
themes/baggy/config.twig [changed mode: 0644->0755]
themes/baggy/css/main.css
themes/baggy/css/print.css
themes/baggy/edit-tags.twig [changed mode: 0644->0755]
themes/baggy/fonts/icomoon.eot [changed mode: 0755->0644]
themes/baggy/fonts/icomoon.svg [changed mode: 0755->0644]
themes/baggy/fonts/icomoon.ttf [changed mode: 0755->0644]
themes/baggy/fonts/icomoon.woff [changed mode: 0755->0644]
themes/baggy/home.twig [changed mode: 0644->0755]
themes/baggy/img/baggy/blank.png [new file with mode: 0755]
themes/baggy/img/baggy/down.png [new file with mode: 0644]
themes/baggy/img/baggy/list.png [new file with mode: 0755]
themes/baggy/img/baggy/table.png [new file with mode: 0755]
themes/baggy/img/baggy/top.png [new file with mode: 0644]
themes/baggy/js/autoClose.js [deleted file]
themes/baggy/js/init.js
themes/baggy/js/jquery-2.0.3.min.js [deleted file]
themes/baggy/js/jquery.cookie.js [new file with mode: 0755]
themes/baggy/layout.twig [changed mode: 0644->0755]
themes/baggy/tags.twig [changed mode: 0644->0755]
themes/baggy/view.twig [changed mode: 0644->0755]
themes/courgette/_head.twig
themes/courgette/_top.twig
themes/courgette/_view.twig
themes/courgette/config.twig
themes/courgette/home.twig
themes/courgette/tags.twig [changed mode: 0644->0755]
themes/dark/img/dark/rss.png [new file with mode: 0644]
themes/default/_bookmarklet.twig
themes/default/_head.twig [changed mode: 0644->0755]
themes/default/_import.twig [new file with mode: 0755]
themes/default/_menu.twig
themes/default/_pocheit-form.twig
themes/default/_search-form.twig [new file with mode: 0755]
themes/default/_sorting.twig [new file with mode: 0755]
themes/default/_top.twig [changed mode: 0644->0755]
themes/default/config.twig [changed mode: 0644->0755]
themes/default/css/images/animated-overlay.gif [new file with mode: 0644]
themes/default/css/images/ui-bg_flat_0_aaaaaa_40x100.png [new file with mode: 0644]
themes/default/css/images/ui-bg_flat_75_ffffff_40x100.png [new file with mode: 0644]
themes/default/css/images/ui-bg_glass_55_fbf9ee_1x400.png [new file with mode: 0644]
themes/default/css/images/ui-bg_glass_65_ffffff_1x400.png [new file with mode: 0644]
themes/default/css/images/ui-bg_glass_75_dadada_1x400.png [new file with mode: 0644]
themes/default/css/images/ui-bg_glass_75_e6e6e6_1x400.png [new file with mode: 0644]
themes/default/css/images/ui-bg_glass_95_fef1ec_1x400.png [new file with mode: 0644]
themes/default/css/images/ui-bg_highlight-soft_75_cccccc_1x100.png [new file with mode: 0644]
themes/default/css/images/ui-icons_222222_256x240.png [new file with mode: 0644]
themes/default/css/images/ui-icons_2e83ff_256x240.png [new file with mode: 0644]
themes/default/css/images/ui-icons_454545_256x240.png [new file with mode: 0644]
themes/default/css/images/ui-icons_888888_256x240.png [new file with mode: 0644]
themes/default/css/images/ui-icons_cd0a0a_256x240.png [new file with mode: 0644]
themes/default/css/jquery-ui-1.10.4.custom.css [new file with mode: 0644]
themes/default/css/jquery-ui-1.10.4.custom.min.css [new file with mode: 0644]
themes/default/css/style-default.css [changed mode: 0644->0755]
themes/default/css/style.css [changed mode: 0644->0755]
themes/default/edit-tags.twig [changed mode: 0644->0755]
themes/default/home.twig [changed mode: 0644->0755]
themes/default/img/default/print.png [new file with mode: 0755]
themes/default/js/autoCompleteTags.js [new file with mode: 0755]
themes/default/js/jquery-ui-1.10.4.custom.js [new file with mode: 0644]
themes/default/js/jquery-ui-1.10.4.custom.min.js [new file with mode: 0644]
themes/default/js/popupForm.js [new file with mode: 0644]
themes/default/js/saveLink.js [new file with mode: 0755]
themes/default/tags.twig [changed mode: 0644->0755]
themes/default/view.twig [changed mode: 0644->0755]
themes/dmagenta/img/dmagenta/rss.png [new file with mode: 0644]
themes/solarized-dark/img/solarized-dark/rss.png [new file with mode: 0644]
themes/solarized/img/solarized/rss.png [new file with mode: 0644]
wallabag_compatibility_test.php

index 2abed7edb59fe5fb8a62f70d06ceff7fbb4ba428..aec2e3ef5bb3f144d0b6864493901c7675c1e665 100644 (file)
@@ -3,4 +3,5 @@ cache/*
 vendor
 composer.phar
 db/poche.sqlite
-inc/poche/config.inc.php
\ No newline at end of file
+inc/poche/config.inc.php
+inc/3rdparty/htmlpurifier/HTMLPurifier/DefinitionCache/Serializer/
\ No newline at end of file
index 85c09e52cbfddca03edffb747110b4bb083fc90d..9ccb0b149d791a4c9745575e88ca8df7264ba637 100644 (file)
@@ -1,11 +1,28 @@
-# How contributing
+# How to contribute
 
 ## You found a bug
 Please [open a new issue](https://github.com/wallabag/wallabag/issues/new).
 
 To fix the bug quickly, we need some infos:
-* your wallabag version (in ./index.php)
+* your wallabag version (on top of the ./index.php file, and also on config page)
+* your webserver installation :
+  * type of hosting (shared or dedicaced)
+  * in case of a dedicaced server, the server and OS used
+  * the php version used, eventually `phpinfo()`
+* which storage system you choose at install (SQLite, MySQL/MariaDB or PostgreSQL)
+* any problem on the `wallabag_compatibility_test.php` page
+* any particular details which could be related
+
+
+If relevant :
 * the link you want to save and which causes problem
+* the file you want to import into wallabag, or just an extract
+
+If you have the skills :
+* enable DEBUG mode and look the output at cache/log.txt
+* look for errors into php and server logs
+
+Note : If you have large portions of text, use [Github's Gist service](https://gist.github.com/) or other pastebin-like.
 
 ## You want to fix a bug or to add a feature
-Please fork wallabag and work with **the dev branch** only. **Do not work on master branch**.
\ No newline at end of file
+Please fork wallabag and work with **the dev branch** only. **Do not work on master branch**.
index fe6a06b61855524c4eb4b930cb90fdea73f260c4..0b54dff45a19a639c6a64fbbef09be07fcada90b 100644 (file)
--- a/README.md
+++ b/README.md
@@ -4,7 +4,7 @@ wallabag is a self hostable application allowing you to not miss any content any
 More informations on our website: [wallabag.org](http://wallabag.org)
 
 ## License
-Copyright © 2010-2013 Nicolas Lœuillet <nicolas@loeuillet.org>
+Copyright © 2010-2014 Nicolas Lœuillet <nicolas@loeuillet.org>
 This work is free. You can redistribute it and/or modify it under the
 terms of the Do What The Fuck You Want To Public License, Version 2,
 as published by Sam Hocevar. See the COPYING file for more details.
diff --git a/TRANSLATION.md b/TRANSLATION.md
new file mode 100755 (executable)
index 0000000..2e38d5c
--- /dev/null
@@ -0,0 +1,67 @@
+# How to manage translations of wallabag
+
+This guide will describe procedure of translation management of wallabag web application.
+
+All translation are made using [gettext](http://en.wikipedia.org/wiki/Gettext) system and tools. 
+
+You will need [Poedit](http://www.poedit.net/download.php) editor to update, edit and create your translation files comfortably. In general, you can handle translations also without it: all can be done using gettext tools and your favorite plain text editor only. This guide, however, describes editing with Poedit. If you want to use gettext only, pls refer to xgettext manual page to update po files from sources (see also how it is used by Poedit below) and use msgunfmt tool to compile .mo files manually.  
+
+You need to know, that translation phrases are stored in **".po"** files (for example: `locale/pl_PL.utf8/LC_MESSAGES/pl_PL.utf8.po`), which are then complied in **".mo"** files using **msgfmt** gettext tool or by Poedit, which will run msgfmt for you in background. 
+
+**It's assumed, that you have wallabag installed locally on your computer or on the server you have access to.**
+
+## To change existing translation you will need to do:
+
+### 1. Clear cache
+You can do this using **http://your-wallabag-host.com/?empty-cache** link (replace http://your-wallabag-host.com/ with real url of your wallabag application)
+
+OR
+
+from command line:
+go to root of your installation of wallabag project and run next command:
+
+`rm -rf ./cache/*`
+
+(this may require root privileges if you run, for example Apatche web server with mod_php)
+
+### 2. Generate php files from all twig templates
+Do this using next command:
+
+`php ./locale/tools/fillCache.php`
+
+OR
+
+from your browser: **http://your-wallabag-host.com/locale/tools/fillCache.php** (this may require removal of .htacces file in locale/ directory).
+
+### 3. Configure your Poedit
+Open Poedit editor, open Edit->Preferences. Go to "Parsers" tab, click on PHP and press "Edit" button. Make sure your "Parser command:" looks like
+
+`xgettext --no-location --force-po -o %o %C %K %F`
+
+Usualy it is required to add "--no-location" to default value. 
+
+### 4. Open .po file you want to edit in Poedit and change it's settings
+Open, for example `locale/pl_PL.utf8/LC_MESSAGES/pl_PL.utf8.po` file in your Poedit.
+
+Go to "Catalog"->"Settings..." menu. Go to "Path" tab and add path to wallabag installaion in your local file system. This step can't be ommited as you will not be able to update phrases otherwise.
+
+You can also check "project into" tab to be sure, that "Language" is set correctly (this will allow you to spell check your translation).
+
+### 5. Update opened .po file from sources
+Once you have set your path correctly, you are able to update phrases from sources. Press "Update catalog - synchronize it with sources" button or go to "Catalog"->"Update from sources" menu.
+
+As a result you will see confirmation popup with two tabs: "New strings" and "Obsolete strings". Pls review and accept changes (or press "Undo" if you see too many obsolete strings, as Poedit will remove them all - in this case please make sure all previous steps are performed w/o errors).
+
+### 6. Translate and save your .po file
+If you have any dificulties on this step, please consult with Poedit manual.
+Every time you save your .po file, Poedit will also comple appropriate .mo file by default (of course, if not disabled in preferences).
+
+So, you are almost done.
+
+### 7. Clear cache again
+This step may be required if your web server runs php scripts in name of, say, www user (i.e. Apache with mod_php, not cgi).
+
+
+##To create new translation 
+Please simple create appropriate directories in locale folder and perform all steps, described above. Instead of opening an existing file just create new one.
+
index 96dd0f7d4741bd9ca6128c642cfcdeb661208806..2b84a7440d358d486e98119b2f23ee7396b076d2 100644 (file)
@@ -13,16 +13,6 @@ if (version_compare(PHP_VERSION, '5.4.0', '<')) {
     }
 }
 
-// Check PDO Sqlite
-if (! extension_loaded('pdo_sqlite')) {
-    die('PHP extension required: pdo_sqlite');
-}
-
-// Check ZIP
-if (! extension_loaded('zip')) {
-    die('PHP extension required: zip');
-}
-
 // Check if /cache is writeable
 if (! is_writable('cache')) {
     die('The directory "cache" must be writeable by your web server user');
index b30a31f3a8fef4757349dd6be1e4445f056a8a7a..59dfbe67009dd6bf7f09163f3c6eb34782ccb781 100644 (file)
@@ -31,9 +31,9 @@ class Session
     public static $sessionName = '';
     // If the user does not access any page within this time,
     // his/her session is considered expired (3600 sec. = 1 hour)
-    public static $inactivityTimeout = 86400;
+    public static $inactivityTimeout = 3600;
     // Extra timeout for long sessions (if enabled) (82800 sec. = 23 hours)
-    public static $longSessionTimeout = 31536000;
+    public static $longSessionTimeout = 7776000; // 7776000 = 90 days
     // If you get disconnected often or if your IP address changes often.
     // Let you disable session cookie hijacking protection
     public static $disableSessionProtection = false;
@@ -48,8 +48,13 @@ class Session
     /**
      * Initialize session
      */
-    public static function init()
+    public static function init($longlastingsession = false)
     {
+        //check if session name is correct
+        if ( (session_id() && !empty(self::$sessionName) && session_name()!=self::$sessionName) || $longlastingsession ) {
+            session_destroy();
+        }
+
         // Force cookie path (but do not change lifetime)
         $cookie = session_get_cookie_params();
         // Default cookie expiration and path.
@@ -61,12 +66,22 @@ class Session
         if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {
             $ssl = true;
         }
-        session_set_cookie_params($cookie['lifetime'], $cookiedir, $_SERVER['HTTP_HOST'], $ssl);
+
+        if ( $longlastingsession ) {
+            session_set_cookie_params(self::$longSessionTimeout, $cookiedir, null, $ssl, true);
+        }
+        else {
+            session_set_cookie_params(0, $cookiedir, null, $ssl, true);
+        }
+        //set server side valid session timeout
+        //WARNING! this may not work in shared session environment. See http://www.php.net/manual/en/session.configuration.php#ini.session.gc-maxlifetime about min value: it can be set in any application
+        ini_set('session.gc_maxlifetime', self::$longSessionTimeout);
+
         // Use cookies to store session.
         ini_set('session.use_cookies', 1);
         // Force cookies for session  (phpsessionID forbidden in URL)
         ini_set('session.use_only_cookies', 1);
-        if (!session_id()) {
+        if ( !session_id() ) {
             // Prevent php to use sessionID in URL if cookies are disabled.
             ini_set('session.use_trans_sid', false);
             if (!empty(self::$sessionName)) {
@@ -115,6 +130,9 @@ class Session
         if (self::banCanLogin()) {
             if ($login === $loginTest && $password === $passwordTest) {
                 self::banLoginOk();
+
+                self::init($longlastingsession);
+
                 // Generate unique random number to sign forms (HMAC)
                 $_SESSION['uid'] = sha1(uniqid('', true).'_'.mt_rand());
                 $_SESSION['ip'] = self::_allIPs();
@@ -135,6 +153,7 @@ class Session
             self::banLoginFailed();
         }
 
+        self::init();
         return false;
     }
 
@@ -143,7 +162,14 @@ class Session
      */
     public static function logout()
     {
-        unset($_SESSION['uid'],$_SESSION['ip'],$_SESSION['expires_on'],$_SESSION['tokens'], $_SESSION['login'], $_SESSION['pass'], $_SESSION['longlastingsession'], $_SESSION['poche_user']);
+        // unset($_SESSION['uid'],$_SESSION['ip'],$_SESSION['expires_on'],$_SESSION['tokens'], $_SESSION['login'], $_SESSION['pass'], $_SESSION['longlastingsession'], $_SESSION['poche_user']);
+        
+        // Destruction du cookie (le code peut paraître complexe mais c'est pour être certain de reprendre les mêmes paramètres)
+        $args = array_merge(array(session_name(), ''), array_values(session_get_cookie_params()));
+        $args[2] = time() - 3600;
+        call_user_func_array('setcookie', $args);
+        // Suppression physique de la session
+        session_destroy();
     }
 
     /**
@@ -157,7 +183,7 @@ class Session
             || (self::$disableSessionProtection === false
                 && $_SESSION['ip'] !== self::_allIPs())
             || time() >= $_SESSION['expires_on']) {
-            self::logout();
+            //self::logout();
 
             return false;
         }
index e60bd3a19c3e1db9e914ed3c10a7e3e1a2e74d4a..27c28f43f4efefb6e34579652d12bb8908037a57 100644 (file)
@@ -59,6 +59,7 @@ class Messages {
                $this->msgId = md5(uniqid());\r
                \r
                // Create the session array if it doesnt already exist\r
+               settype($_SESSION, 'array');
                if( !array_key_exists('flash_messages', $_SESSION) ) $_SESSION['flash_messages'] = array();\r
                \r
        }\r
@@ -228,4 +229,4 @@ class Messages {
 \r
 \r
 } // end class\r
-?>
\ No newline at end of file
+?>
index e618117b7190da886aa40731fba02896f4521664..ec680d8659cbc3f3b84dad4d678bf58ff7bae760 100755 (executable)
@@ -19,7 +19,7 @@ if (!isset($options)) $options = new stdClass();
 // Enable service\r
 // ----------------------\r
 // Set this to false if you want to disable the service.\r
-// If set to false, no feed is produced and users will \r
+// If set to false, no feed is produced and users will\r
 // be told that the service is disabled.\r
 $options->enabled = true;\r
 \r
@@ -43,10 +43,64 @@ $options->default_entries = 5;
 // ----------------------\r
 // The maximum number of feed items to process when no access key is supplied.\r
 // This limits the user-supplied &max=x value. For example, if the user\r
-// asks for 20 items to be processed (&max=20), if max_entries is set to \r
+// asks for 20 items to be processed (&max=20), if max_entries is set to\r
 // 10, only 10 will be processed.\r
 $options->max_entries = 10;\r
 \r
+// Full content\r
+// ----------------------\r
+// By default Full-Text RSS includes the extracted content in the output.\r
+// You can exclude this from the output by passing '&content=0' in the querystring.\r
+//\r
+// Possible values...\r
+// Always include: true\r
+// Never include: false\r
+// Include unless user overrides (&content=0): 'user' (default)\r
+//\r
+// Note: currently this does not disable full content extraction. It simply omits it\r
+// from the output.\r
+$options->content = 'user';\r
+\r
+// Excerpts\r
+// ----------------------\r
+// By default Full-Text RSS does not include excerpts in the output.\r
+// You can enable this by passing '&summary=1' in the querystring.\r
+// This will include a plain text excerpt from the extracted content.\r
+//\r
+// Possible values...\r
+// Always include: true (recommended for new users)\r
+// Never include: false\r
+// Don't include unless user overrides (&summary=1): 'user' (default)\r
+//\r
+// Important: if both content and excerpts are requested, the excerpt will be\r
+// placed in the description element and the full content inside content:encoded.\r
+// If excerpts are not requested, the full content will go inside the description element.\r
+//\r
+// Why are we not returning both excerpts and content by default?\r
+// Mainly for backward compatibility.\r
+// Excerpts should appear in the feed item's description element. Previous versions\r
+// of Full-Text RSS did not return excerpts, so the description element was always\r
+// used for the full content (as recommended by the RSS advisory). When returning both,\r
+// we need somewhere else to place the content (content:encoded).\r
+// Having both enabled should not create any problems for news readers, but it may create\r
+// problems for developers upgrading from one of our earlier versions who may now find\r
+// their applications are returning excerpts instead of the full content they were\r
+// expecting. To avoid such surprises for users who are upgrading Full-Text RSS,\r
+// excerpts must be explicitly requested in the querystring by default.\r
+//\r
+// Why not use a different element name for excerpts?\r
+// According to the RSS advisory:\r
+// "Publishers who employ summaries should store the summary in description and\r
+// the full content in content:encoded, ordering description first within the item.\r
+// On items with no summary, the full content should be stored in description."\r
+// See: http://www.rssboard.org/rss-profile#namespace-elements-content-encoded\r
+//\r
+// For more consistent element naming, we recommend new users set this option to true.\r
+// The full content can still be excluded via the querystring, but the element names\r
+// will not change: when $options->summary = true, the description element will always\r
+// be reserved for the excerpt and content:encoded always for full content.\r
+$options->summary = 'user';\r
+\r
 // Rewrite relative URLs\r
 // ----------------------\r
 // With this enabled relative URLs found in the extracted content\r
@@ -67,7 +121,7 @@ $options->exclude_items_on_fail = 'user';
 // Enable multi-page support\r
 // -------------------------\r
 // If enabled, we will try to follow next page links on multi-page articles.\r
-// Currently this only happens for sites where next_page_link has been defined \r
+// Currently this only happens for sites where next_page_link has been defined\r
 // in a site config file.\r
 $options->multipage = true;\r
 \r
@@ -125,10 +179,10 @@ $options->detect_language = 1;
 \r
 // Registration key\r
 // ---------------\r
-// The registration key is optional. It is not required to use Full-Text RSS, \r
-// and does not affect the normal operation of Full-Text RSS. It is currently \r
-// only used on admin pages which help you update site patterns with the \r
-// latest version offered by FiveFilters.org. For these admin-related \r
+// The registration key is optional. It is not required to use Full-Text RSS,\r
+// and does not affect the normal operation of Full-Text RSS. It is currently\r
+// only used on admin pages which help you update site patterns with the\r
+// latest version offered by FiveFilters.org. For these admin-related\r
 // tasks to complete, we will require a valid registration key.\r
 // If you would like one, you can purchase the latest version of Full-Text RSS\r
 // at http://fivefilters.org/content-only/\r
@@ -144,12 +198,12 @@ $options->registration_key = '';
 // ----------------------\r
 // Certain pages/actions, e.g. updating site patterns with our online tool, will require admin credentials.\r
 // To use these pages, enter a password here and you'll be prompted for it when you try to access those pages.\r
-// If no password or username is set, pages requiring admin privelages will be inaccessible. \r
+// If no password or username is set, pages requiring admin privelages will be inaccessible.\r
 // The default username is 'admin'.\r
 // If overriding with an environment variable, separate username and password with a colon, e.g.:\r
 // ftr_admin_credentials: admin:my-secret-password\r
 // Example: $options->admin_credentials = array('username'=>'admin', 'password'=>'my-secret-password');\r
-$options->admin_credentials = array('username'=>'admin', 'password'=>'admin');\r
+$options->admin_credentials = array('username'=>'admin', 'password'=>'');\r
 \r
 // URLs to allow\r
 // ----------------------\r
@@ -178,12 +232,12 @@ $options->key_required = false;
 // ----------------------\r
 // By default, when processing feeds, we assume item titles in the feed\r
 // have not been truncated. So after processing web pages, the extracted titles\r
-// are not used in the generated feed. If you prefer to have extracted titles in \r
-// the feed you can either set this to false, in which case we will always favour \r
-// extracted titles. Alternatively, if set to 'user' (default) we'll use the \r
+// are not used in the generated feed. If you prefer to have extracted titles in\r
+// the feed you can either set this to false, in which case we will always favour\r
+// extracted titles. Alternatively, if set to 'user' (default) we'll use the\r
 // extracted title if you pass '&use_extracted_title' in the querystring.\r
 // Possible values:\r
-// * Favour feed titles: true \r
+// * Favour feed titles: true\r
 // * Favour extracted titles: false\r
 // * Favour feed titles with user override: 'user' (default)\r
 // Note: this has no effect when the input URL is to a web page - in these cases\r
@@ -192,17 +246,17 @@ $options->favour_feed_titles = 'user';
 \r
 // Access keys (password protected access)\r
 // ------------------------------------\r
-// NOTE: You do not need an API key from fivefilters.org to run your own \r
+// NOTE: You do not need an API key from fivefilters.org to run your own\r
 // copy of the code. This is here if you'd like to restrict access to\r
 // _your_ copy.\r
 // Keys let you group users - those with a key and those without - and\r
 // restrict access to the service to those without a key.\r
 // If you want everyone to access the service in the same way, you can\r
 // leave the array below empty and ignore the access key options further down.\r
-// The options further down let you control how the service should behave \r
+// The options further down let you control how the service should behave\r
 // in each mode.\r
-// Note: Explicitly including the index number (1 and 2 in the examples below) \r
-// is highly recommended (when generating feeds, we encode the key and \r
+// Note: Explicitly including the index number (1 and 2 in the examples below)\r
+// is highly recommended (when generating feeds, we encode the key and\r
 // refer to it by index number and hash).\r
 $options->api_keys = array();\r
 // Example:\r
@@ -232,13 +286,13 @@ $options->max_entries_with_key = 10;
 // filter the resulting HTML for XSS attacks, making it redundant for\r
 // Full-Text RSS do the same. Similarly with frameworks/CMS which display\r
 // feed content - the content should be treated like any other user-submitted content.\r
-// \r
+//\r
 // If you are writing an application yourself which is processing feeds generated by\r
 // Full-Text RSS, you can either filter the HTML yourself to remove potential XSS attacks\r
 // or enable this option. This might be useful if you are processing our generated\r
 // feeds with JavaScript on the client side - although there's client side xss\r
 // filtering available too, e.g. https://code.google.com/p/google-caja/wiki/JsHtmlSanitizer\r
-// \r
+//\r
 // If enabled, we'll pass retrieved HTML content through htmLawed with\r
 // safe flag on and style attributes denied, see\r
 // http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed/htmLawed_README.htm#s3.6\r
@@ -253,8 +307,8 @@ $options->xss_filter = 'user';
 // Allowed parsers\r
 // ----------------------\r
 // Full-Text RSS attempts to use PHP's libxml extension to process HTML.\r
-// While fast, on some sites it may not always produce good results. \r
-// For these sites, you can specify an alternative HTML parser: \r
+// While fast, on some sites it may not always produce good results.\r
+// For these sites, you can specify an alternative HTML parser:\r
 // parser: html5lib\r
 // The html5lib parser is bundled with Full-Text RSS.\r
 // see http://code.google.com/p/html5lib/\r
@@ -273,7 +327,7 @@ $options->cors = false;
 \r
 // Use APC user cache?\r
 // ----------------------\r
-// If enabled we will store site config files (when requested \r
+// If enabled we will store site config files (when requested\r
 // for the first time) in APC's user cache. Keys prefixed with 'sc.'\r
 // This improves performance by reducing disk access.\r
 // Note: this has no effect if APC is unavailable on your server.\r
@@ -346,7 +400,7 @@ $options->rewrite_url = array(
 // Valid actions:\r
 // * 'exclude' - exclude this item from the result\r
 // * 'link' - create HTML link to the item\r
-$options->content_type_exc = array( \r
+$options->content_type_exc = array(\r
                                                           'application/pdf' => array('action'=>'link', 'name'=>'PDF'),\r
                                                           'image' => array('action'=>'link', 'name'=>'Image'),\r
                                                           'audio' => array('action'=>'link', 'name'=>'Audio'),\r
@@ -375,13 +429,13 @@ $options->cache_cleanup = 100;
 /// DO NOT CHANGE ANYTHING BELOW THIS ///////////\r
 /////////////////////////////////////////////////\r
 \r
-if (!defined('_FF_FTR_VERSION')) define('_FF_FTR_VERSION', '3.1');\r
+if (!defined('_FF_FTR_VERSION')) define('_FF_FTR_VERSION', '3.2');\r
 \r
 if (basename(__FILE__) == 'config.php') {\r
        if (file_exists(dirname(__FILE__).'/custom_config.php')) {\r
                require_once dirname(__FILE__).'/custom_config.php';\r
        }\r
-       \r
+\r
        // check for environment variables - often used on cloud platforms\r
        // environment variables should be prefixed with 'ftr_', e.g.\r
        // ftr_max_entries: 1\r
diff --git a/inc/3rdparty/libraries/PHPePub/EPub.HtmlEntities.php b/inc/3rdparty/libraries/PHPePub/EPub.HtmlEntities.php
new file mode 100644 (file)
index 0000000..376b613
--- /dev/null
@@ -0,0 +1,266 @@
+<?php
+/**
+ * This should be a complete list of all HTML entities, mapped to their UTF-8 character codes.
+ *
+ * @author A. Grandt
+ * @copyright A. Grandt 2009-2013
+ * @license GNU LGPL, Attribution required for commercial implementations, requested for everything else.
+ * @version 3.00
+ */
+global $htmlEntities;
+$htmlEntities = array();
+
+$htmlEntities["&quot;"]     ="\x22"; // &#34; ((double) quotation mark)
+$htmlEntities["&amp;"]      ="\x26"; // &#38; (ampersand)
+$htmlEntities["&apos;"]     ="\x27"; // &#39; (apostrophe  = apostrophe-quote)
+$htmlEntities["&lt;"]       ="\x3C"; // &#60; (less-than sign)
+$htmlEntities["&gt;"]       ="\x3E"; // &#62; (greater-than sign)
+$htmlEntities["&nbsp;"]     ="\xC2\xA0"; // &#160; (non-breaking space)
+$htmlEntities["&iexcl;"]    ="\xC2\xA1"; // &#161; (inverted exclamation mark)
+$htmlEntities["&cent;"]     ="\xC2\xA2"; // &#162; (cent)
+$htmlEntities["&pound;"]    ="\xC2\xA3"; // &#163; (pound)
+$htmlEntities["&curren;"]   ="\xC2\xA4"; // &#164; (currency)
+$htmlEntities["&yen;"]      ="\xC2\xA5"; // &#165; (yen)
+$htmlEntities["&brvbar;"]   ="\xC2\xA6"; // &#166; (broken vertical bar)
+$htmlEntities["&sect;"]     ="\xC2\xA7"; // &#167; (section)
+$htmlEntities["&uml;"]      ="\xC2\xA8"; // &#168; (spacing diaeresis)
+$htmlEntities["&copy;"]     ="\xC2\xA9"; // &#169; (copyright)
+$htmlEntities["&ordf;"]     ="\xC2\xAA"; // &#170; (feminine ordinal indicator)
+$htmlEntities["&laquo;"]    ="\xC2\xAB"; // &#171; (angle quotation mark (left))
+$htmlEntities["&not;"]      ="\xC2\xAC"; // &#172; (negation)
+$htmlEntities["&shy;"]      ="\xC2\xAD"; // &#173; (soft hyphen)
+$htmlEntities["&reg;"]      ="\xC2\xAE"; // &#174; (registered trademark)
+$htmlEntities["&macr;"]     ="\xC2\xAF"; // &#175; (spacing macron)
+$htmlEntities["&deg;"]      ="\xC2\xB0"; // &#176; (degree)
+$htmlEntities["&plusmn;"]   ="\xC2\xB1"; // &#177; (plus-or-minus)
+$htmlEntities["&sup2;"]     ="\xC2\xB2"; // &#178; (superscript 2)
+$htmlEntities["&sup3;"]     ="\xC2\xB3"; // &#179; (superscript 3)
+$htmlEntities["&acute;"]    ="\xC2\xB4"; // &#180; (spacing acute)
+$htmlEntities["&micro;"]    ="\xC2\xB5"; // &#181; (micro)
+$htmlEntities["&para;"]     ="\xC2\xB6"; // &#182; (paragraph)
+$htmlEntities["&middot;"]   ="\xC2\xB7"; // &#183; (middle dot)
+$htmlEntities["&cedil;"]    ="\xC2\xB8"; // &#184; (spacing cedilla)
+$htmlEntities["&sup1;"]     ="\xC2\xB9"; // &#185; (superscript 1)
+$htmlEntities["&ordm;"]     ="\xC2\xBA"; // &#186; (masculine ordinal indicator)
+$htmlEntities["&raquo;"]    ="\xC2\xBB"; // &#187; (angle quotation mark (right))
+$htmlEntities["&frac14;"]   ="\xC2\xBC"; // &#188; (fraction 1/4)
+$htmlEntities["&frac12;"]   ="\xC2\xBD"; // &#189; (fraction 1/2)
+$htmlEntities["&frac34;"]   ="\xC2\xBE"; // &#190; (fraction 3/4)
+$htmlEntities["&iquest;"]   ="\xC2\xBF"; // &#191; (inverted question mark)
+$htmlEntities["&Agrave;"]   ="\xC3\x80"; // &#192; (capital a, grave accent)
+$htmlEntities["&Aacute;"]   ="\xC3\x81"; // &#193; (capital a, acute accent)
+$htmlEntities["&Acirc;"]    ="\xC3\x82"; // &#194; (capital a, circumflex accent)
+$htmlEntities["&Atilde;"]   ="\xC3\x83"; // &#195; (capital a, tilde)
+$htmlEntities["&Auml;"]     ="\xC3\x84"; // &#196; (capital a, umlaut mark)
+$htmlEntities["&Aring;"]    ="\xC3\x85"; // &#197; (capital a, ring)
+$htmlEntities["&AElig;"]    ="\xC3\x86"; // &#198; (capital ae)
+$htmlEntities["&Ccedil;"]   ="\xC3\x87"; // &#199; (capital c, cedilla)
+$htmlEntities["&Egrave;"]   ="\xC3\x88"; // &#200; (capital e, grave accent)
+$htmlEntities["&Eacute;"]   ="\xC3\x89"; // &#201; (capital e, acute accent)
+$htmlEntities["&Ecirc;"]    ="\xC3\x8A"; // &#202; (capital e, circumflex accent)
+$htmlEntities["&Euml;"]     ="\xC3\x8B"; // &#203; (capital e, umlaut mark)
+$htmlEntities["&Igrave;"]   ="\xC3\x8C"; // &#204; (capital i, grave accent)
+$htmlEntities["&Iacute;"]   ="\xC3\x8D"; // &#205; (capital i, acute accent)
+$htmlEntities["&Icirc;"]    ="\xC3\x8E"; // &#206; (capital i, circumflex accent)
+$htmlEntities["&Iuml;"]     ="\xC3\x8F"; // &#207; (capital i, umlaut mark)
+$htmlEntities["&ETH;"]      ="\xC3\x90"; // &#208; (capital eth, Icelandic)
+$htmlEntities["&Ntilde;"]   ="\xC3\x91"; // &#209; (capital n, tilde)
+$htmlEntities["&Ograve;"]   ="\xC3\x92"; // &#210; (capital o, grave accent)
+$htmlEntities["&Oacute;"]   ="\xC3\x93"; // &#211; (capital o, acute accent)
+$htmlEntities["&Ocirc;"]    ="\xC3\x94"; // &#212; (capital o, circumflex accent)
+$htmlEntities["&Otilde;"]   ="\xC3\x95"; // &#213; (capital o, tilde)
+$htmlEntities["&Ouml;"]     ="\xC3\x96"; // &#214; (capital o, umlaut mark)
+$htmlEntities["&times;"]    ="\xC3\x97"; // &#215; (multiplication)
+$htmlEntities["&Oslash;"]   ="\xC3\x98"; // &#216; (capital o, slash)
+$htmlEntities["&Ugrave;"]   ="\xC3\x99"; // &#217; (capital u, grave accent)
+$htmlEntities["&Uacute;"]   ="\xC3\x9A"; // &#218; (capital u, acute accent)
+$htmlEntities["&Ucirc;"]    ="\xC3\x9B"; // &#219; (capital u, circumflex accent)
+$htmlEntities["&Uuml;"]     ="\xC3\x9C"; // &#220; (capital u, umlaut mark)
+$htmlEntities["&Yacute;"]   ="\xC3\x9D"; // &#221; (capital y, acute accent)
+$htmlEntities["&THORN;"]    ="\xC3\x9E"; // &#222; (capital THORN, Icelandic)
+$htmlEntities["&szlig;"]    ="\xC3\x9F"; // &#223; (small sharp s, German)
+$htmlEntities["&agrave;"]   ="\xC3\xA0"; // &#224; (small a, grave accent)
+$htmlEntities["&aacute;"]   ="\xC3\xA1"; // &#225; (small a, acute accent)
+$htmlEntities["&acirc;"]    ="\xC3\xA2"; // &#226; (small a, circumflex accent)
+$htmlEntities["&atilde;"]   ="\xC3\xA3"; // &#227; (small a, tilde)
+$htmlEntities["&auml;"]     ="\xC3\xA4"; // &#228; (small a, umlaut mark)
+$htmlEntities["&aring;"]    ="\xC3\xA5"; // &#229; (small a, ring)
+$htmlEntities["&aelig;"]    ="\xC3\xA6"; // &#230; (small ae)
+$htmlEntities["&ccedil;"]   ="\xC3\xA7"; // &#231; (small c, cedilla)
+$htmlEntities["&egrave;"]   ="\xC3\xA8"; // &#232; (small e, grave accent)
+$htmlEntities["&eacute;"]   ="\xC3\xA9"; // &#233; (small e, acute accent)
+$htmlEntities["&ecirc;"]    ="\xC3\xAA"; // &#234; (small e, circumflex accent)
+$htmlEntities["&euml;"]     ="\xC3\xAB"; // &#235; (small e, umlaut mark)
+$htmlEntities["&igrave;"]   ="\xC3\xAC"; // &#236; (small i, grave accent)
+$htmlEntities["&iacute;"]   ="\xC3\xAD"; // &#237; (small i, acute accent)
+$htmlEntities["&icirc;"]    ="\xC3\xAE"; // &#238; (small i, circumflex accent)
+$htmlEntities["&iuml;"]     ="\xC3\xAF"; // &#239; (small i, umlaut mark)
+$htmlEntities["&eth;"]      ="\xC3\xB0"; // &#240; (small eth, Icelandic)
+$htmlEntities["&ntilde;"]   ="\xC3\xB1"; // &#241; (small n, tilde)
+$htmlEntities["&ograve;"]   ="\xC3\xB2"; // &#242; (small o, grave accent)
+$htmlEntities["&oacute;"]   ="\xC3\xB3"; // &#243; (small o, acute accent)
+$htmlEntities["&ocirc;"]    ="\xC3\xB4"; // &#244; (small o, circumflex accent)
+$htmlEntities["&otilde;"]   ="\xC3\xB5"; // &#245; (small o, tilde)
+$htmlEntities["&ouml;"]     ="\xC3\xB6"; // &#246; (small o, umlaut mark)
+$htmlEntities["&divide;"]   ="\xC3\xB7"; // &#247; (division)
+$htmlEntities["&oslash;"]   ="\xC3\xB8"; // &#248; (small o, slash)
+$htmlEntities["&ugrave;"]   ="\xC3\xB9"; // &#249; (small u, grave accent)
+$htmlEntities["&uacute;"]   ="\xC3\xBA"; // &#250; (small u, acute accent)
+$htmlEntities["&ucirc;"]    ="\xC3\xBB"; // &#251; (small u, circumflex accent)
+$htmlEntities["&uuml;"]     ="\xC3\xBC"; // &#252; (small u, umlaut mark)
+$htmlEntities["&yacute;"]   ="\xC3\xBD"; // &#253; (small y, acute accent)
+$htmlEntities["&thorn;"]    ="\xC3\xBE"; // &#254; (small thorn, Icelandic)
+$htmlEntities["&yuml;"]     ="\xC3\xBF"; // &#255; (small y, umlaut mark)
+$htmlEntities["&OElig;"]    ="\xC5\x92"; // &#338; (capital ligature OE)
+$htmlEntities["&oelig;"]    ="\xC5\x93"; // &#339; (small ligature oe)
+$htmlEntities["&Scaron;"]   ="\xC5\xA0"; // &#352; (capital S with caron)
+$htmlEntities["&scaron;"]   ="\xC5\xA1"; // &#353; (small S with caron)
+$htmlEntities["&Yuml;"]     ="\xC5\xB8"; // &#376; (capital Y with diaeres)
+$htmlEntities["&fnof;"]     ="\xC6\x92"; // &#402; (f with hook)
+$htmlEntities["&circ;"]     ="\xCB\x86"; // &#710; (modifier letter circumflex accent)
+$htmlEntities["&tilde;"]    ="\xCB\x9C"; // &#732; (small tilde)
+$htmlEntities["&Alpha;"]    ="\xCE\x91"; // &#913; (Alpha)
+$htmlEntities["&Beta;"]     ="\xCE\x92"; // &#914; (Beta)
+$htmlEntities["&Gamma;"]    ="\xCE\x93"; // &#915; (Gamma)
+$htmlEntities["&Delta;"]    ="\xCE\x94"; // &#916; (Delta)
+$htmlEntities["&Epsilon;"]  ="\xCE\x95"; // &#917; (Epsilon)
+$htmlEntities["&Zeta;"]     ="\xCE\x96"; // &#918; (Zeta)
+$htmlEntities["&Eta;"]      ="\xCE\x97"; // &#919; (Eta)
+$htmlEntities["&Theta;"]    ="\xCE\x98"; // &#920; (Theta)
+$htmlEntities["&Iota;"]     ="\xCE\x99"; // &#921; (Iota)
+$htmlEntities["&Kappa;"]    ="\xCE\x9A"; // &#922; (Kappa)
+$htmlEntities["&Lambda;"]   ="\xCE\x9B"; // &#923; (Lambda)
+$htmlEntities["&Mu;"]       ="\xCE\x9C"; // &#924; (Mu)
+$htmlEntities["&Nu;"]       ="\xCE\x9D"; // &#925; (Nu)
+$htmlEntities["&Xi;"]       ="\xCE\x9E"; // &#926; (Xi)
+$htmlEntities["&Omicron;"]  ="\xCE\x9F"; // &#927; (Omicron)
+$htmlEntities["&Pi;"]       ="\xCE\xA0"; // &#928; (Pi)
+$htmlEntities["&Rho;"]      ="\xCE\xA1"; // &#929; (Rho)
+$htmlEntities["&Sigma;"]    ="\xCE\xA3"; // &#931; (Sigma)
+$htmlEntities["&Tau;"]      ="\xCE\xA4"; // &#932; (Tau)
+$htmlEntities["&Upsilon;"]  ="\xCE\xA5"; // &#933; (Upsilon)
+$htmlEntities["&Phi;"]      ="\xCE\xA6"; // &#934; (Phi)
+$htmlEntities["&Chi;"]      ="\xCE\xA7"; // &#935; (Chi)
+$htmlEntities["&Psi;"]      ="\xCE\xA8"; // &#936; (Psi)
+$htmlEntities["&Omega;"]    ="\xCE\xA9"; // &#937; (Omega)
+$htmlEntities["&alpha;"]    ="\xCE\xB1"; // &#945; (alpha)
+$htmlEntities["&beta;"]     ="\xCE\xB2"; // &#946; (beta)
+$htmlEntities["&gamma;"]    ="\xCE\xB3"; // &#947; (gamma)
+$htmlEntities["&delta;"]    ="\xCE\xB4"; // &#948; (delta)
+$htmlEntities["&epsilon;"]  ="\xCE\xB5"; // &#949; (epsilon)
+$htmlEntities["&zeta;"]     ="\xCE\xB6"; // &#950; (zeta)
+$htmlEntities["&eta;"]      ="\xCE\xB7"; // &#951; (eta)
+$htmlEntities["&theta;"]    ="\xCE\xB8"; // &#952; (theta)
+$htmlEntities["&iota;"]     ="\xCE\xB9"; // &#953; (iota)
+$htmlEntities["&kappa;"]    ="\xCE\xBA"; // &#954; (kappa)
+$htmlEntities["&lambda;"]   ="\xCE\xBB"; // &#955; (lambda)
+$htmlEntities["&mu;"]       ="\xCE\xBC"; // &#956; (mu)
+$htmlEntities["&nu;"]       ="\xCE\xBD"; // &#957; (nu)
+$htmlEntities["&xi;"]       ="\xCE\xBE"; // &#958; (xi)
+$htmlEntities["&omicron;"]  ="\xCE\xBF"; // &#959; (omicron)
+$htmlEntities["&pi;"]       ="\xCF\x80"; // &#960; (pi)
+$htmlEntities["&rho;"]      ="\xCF\x81"; // &#961; (rho)
+$htmlEntities["&sigmaf;"]   ="\xCF\x82"; // &#962; (sigmaf)
+$htmlEntities["&sigma;"]    ="\xCF\x83"; // &#963; (sigma)
+$htmlEntities["&tau;"]      ="\xCF\x84"; // &#964; (tau)
+$htmlEntities["&upsilon;"]  ="\xCF\x85"; // &#965; (upsilon)
+$htmlEntities["&phi;"]      ="\xCF\x86"; // &#966; (phi)
+$htmlEntities["&chi;"]      ="\xCF\x87"; // &#967; (chi)
+$htmlEntities["&psi;"]      ="\xCF\x88"; // &#968; (psi)
+$htmlEntities["&omega;"]    ="\xCF\x89"; // &#969; (omega)
+$htmlEntities["&thetasym;"] ="\xCF\x91"; // &#977; (theta symbol)
+$htmlEntities["&upsih;"]    ="\xCF\x92"; // &#978; (upsilon symbol)
+$htmlEntities["&piv;"]      ="\xCF\x96"; // &#982; (pi symbol)
+$htmlEntities["&ensp;"]     ="\xE2\x80\x82"; // &#8194; (en space)
+$htmlEntities["&emsp;"]     ="\xE2\x80\x83"; // &#8195; (em space)
+$htmlEntities["&thinsp;"]   ="\xE2\x80\x89"; // &#8201; (thin space)
+$htmlEntities["&zwnj;"]     ="‌\xE2\x80\x8C"; // &#8204; (zero width non-joiner)
+$htmlEntities["&zwj;"]      ="\xE2\x80\x8D‍"; // &#8205; (zero width joiner)
+$htmlEntities["&lrm;"]      ="‎\xE2\x80\x8E"; // &#8206; (left-to-right mark)
+$htmlEntities["&rlm;"]      ="\xE2\x80\x8F"; // &#8207; (right-to-left mark)
+$htmlEntities["&ndash;"]    ="\xE2\x80\x93"; // &#8211; (en dash)
+$htmlEntities["&mdash;"]    ="\xE2\x80\x94"; // &#8212; (em dash)
+$htmlEntities["&lsquo;"]    ="\xE2\x80\x98"; // &#8216; (left single quotation mark)
+$htmlEntities["&rsquo;"]    ="\xE2\x80\x99"; // &#8217; (right single quotation mark)
+$htmlEntities["&sbquo;"]    ="\xE2\x80\x9A"; // &#8218; (single low-9 quotation mark)
+$htmlEntities["&ldquo;"]    ="\xE2\x80\x9C"; // &#8220; (left double quotation mark)
+$htmlEntities["&rdquo;"]    ="\xE2\x80\x9D"; // &#8221; (right double quotation mark)
+$htmlEntities["&bdquo;"]    ="\xE2\x80\x9E"; // &#8222; (double low-9 quotation mark)
+$htmlEntities["&dagger;"]   ="\xE2\x80\xA0"; // &#8224; (dagger)
+$htmlEntities["&Dagger;"]   ="\xE2\x80\xA1"; // &#8225; (double dagger)
+$htmlEntities["&bull;"]     ="\xE2\x80\xA2"; // &#8226; (bullet)
+$htmlEntities["&hellip;"]   ="\xE2\x80\xA6"; // &#8230; (horizontal ellipsis)
+$htmlEntities["&permil;"]   ="\xE2\x80\xB0"; // &#8240; (per mille)
+$htmlEntities["&prime;"]    ="\xE2\x80\xB2"; // &#8242; (minutes or prime)
+$htmlEntities["&Prime;"]    ="\xE2\x80\xB3"; // &#8243; (seconds or Double Prime)
+$htmlEntities["&lsaquo;"]   ="\xE2\x80\xB9"; // &#8249; (single left angle quotation)
+$htmlEntities["&rsaquo;"]   ="\xE2\x80\xBA"; // &#8250; (single right angle quotation)
+$htmlEntities["&oline;"]    ="\xE2\x80\xBE"; // &#8254; (overline)
+$htmlEntities["&frasl;"]    ="\xE2\x81\x84"; // &#8260; (fraction slash)
+$htmlEntities["&euro;"]     ="\xE2\x82\xAC"; // &#8364; (euro)
+$htmlEntities["&image;"]    ="\xE2\x84\x91"; // &#8465; (blackletter capital I)
+$htmlEntities["&weierp;"]   ="\xE2\x84\x98"; // &#8472; (script capital P)
+$htmlEntities["&real;"]     ="\xE2\x84\x9C"; // &#8476; (blackletter capital R)
+$htmlEntities["&trade;"]    ="\xE2\x84\xA2"; // &#8482; (trademark)
+$htmlEntities["&alefsym;"]  ="\xE2\x84\xB5"; // &#8501; (alef)
+$htmlEntities["&larr;"]     ="\xE2\x86\x90"; // &#8592; (left arrow)
+$htmlEntities["&uarr;"]     ="\xE2\x86\x91"; // &#8593; (up arrow)
+$htmlEntities["&rarr;"]     ="\xE2\x86\x92"; // &#8594; (right arrow)
+$htmlEntities["&darr;"]     ="\xE2\x86\x93"; // &#8595; (down arrow)
+$htmlEntities["&harr;"]     ="\xE2\x86\x94"; // &#8596; (left right arrow)
+$htmlEntities["&crarr;"]    ="\xE2\x86\xB5"; // &#8629; (carriage return arrow)
+$htmlEntities["&lArr;"]     ="\xE2\x87\x90"; // &#8656; (left double arrow)
+$htmlEntities["&uArr;"]     ="\xE2\x87\x91"; // &#8657; (up double arrow)
+$htmlEntities["&rArr;"]     ="\xE2\x87\x92"; // &#8658; (right double arrow)
+$htmlEntities["&dArr;"]     ="\xE2\x87\x93"; // &#8659; (down double arrow)
+$htmlEntities["&hArr;"]     ="\xE2\x87\x94"; // &#8660; (left right double arrow)
+$htmlEntities["&forall;"]   ="\xE2\x88\x80"; // &#8704; (for all)
+$htmlEntities["&part;"]     ="\xE2\x88\x82"; // &#8706; (partial differential)
+$htmlEntities["&exist;"]    ="\xE2\x88\x83"; // &#8707; (there exists)
+$htmlEntities["&empty;"]    ="\xE2\x88\x85"; // &#8709; (empty set)
+$htmlEntities["&nabla;"]    ="\xE2\x88\x87"; // &#8711; (backward difference)
+$htmlEntities["&isin;"]     ="\xE2\x88\x88"; // &#8712; (element of)
+$htmlEntities["&notin;"]    ="\xE2\x88\x89"; // &#8713; (not an element of)
+$htmlEntities["&ni;"]       ="\xE2\x88\x8B"; // &#8715; (ni = contains as member)
+$htmlEntities["&prod;"]     ="\xE2\x88\x8F"; // &#8719; (n-ary product)
+$htmlEntities["&sum;"]      ="\xE2\x88\x91"; // &#8721; (n-ary sumation)
+$htmlEntities["&minus;"]    ="\xE2\x88\x92"; // &#8722; (minus)
+$htmlEntities["&lowast;"]   ="\xE2\x88\x97"; // &#8727; (asterisk operator)
+$htmlEntities["&radic;"]    ="\xE2\x88\x9A"; // &#8730; (square root)
+$htmlEntities["&prop;"]     ="\xE2\x88\x9D"; // &#8733; (proportional to)
+$htmlEntities["&infin;"]    ="\xE2\x88\x9E"; // &#8734; (infinity)
+$htmlEntities["&ang;"]      ="\xE2\x88\xA0"; // &#8736; (angle)
+$htmlEntities["&and;"]      ="\xE2\x88\xA7"; // &#8743; (logical and)
+$htmlEntities["&or;"]       ="\xE2\x88\xA8"; // &#8744; (logical or)
+$htmlEntities["&cap;"]      ="\xE2\x88\xA9"; // &#8745; (intersection)
+$htmlEntities["&cup;"]      ="\xE2\x88\xAA"; // &#8746; (union)
+$htmlEntities["&int;"]      ="\xE2\x88\xAB"; // &#8747; (integral)
+$htmlEntities["&there4;"]   ="\xE2\x88\xB4"; // &#8756; (therefore)
+$htmlEntities["&sim;"]      ="\xE2\x88\xBC"; // &#8764; (similar to)
+$htmlEntities["&cong;"]     ="\xE2\x89\x85"; // &#8773; (congruent to)
+$htmlEntities["&asymp;"]    ="\xE2\x89\x88"; // &#8776; (approximately equal)
+$htmlEntities["&ne;"]       ="\xE2\x89\xA0"; // &#8800; (not equal)
+$htmlEntities["&equiv;"]    ="\xE2\x89\xA1"; // &#8801; (equivalent)
+$htmlEntities["&le;"]       ="\xE2\x89\xA4"; // &#8804; (less or equal)
+$htmlEntities["&ge;"]       ="\xE2\x89\xA5"; // &#8805; (greater or equal)
+$htmlEntities["&sub;"]      ="\xE2\x8A\x82"; // &#8834; (subset of)
+$htmlEntities["&sup;"]      ="\xE2\x8A\x83"; // &#8835; (superset of)
+$htmlEntities["&nsub;"]     ="\xE2\x8A\x84"; // &#8836; (not subset of)
+$htmlEntities["&sube;"]     ="\xE2\x8A\x86"; // &#8838; (subset or equal)
+$htmlEntities["&supe;"]     ="\xE2\x8A\x87"; // &#8839; (superset or equal)
+$htmlEntities["&oplus;"]    ="\xE2\x8A\x95"; // &#8853; (circled plus)
+$htmlEntities["&otimes;"]   ="\xE2\x8A\x87"; // &#8855; (circled times)
+$htmlEntities["&perp;"]     ="\xE2\x8A\xA5"; // &#8869; (perpendicular)
+$htmlEntities["&sdot;"]     ="\xE2\x8C\x85"; // &#8901; (dot operator)
+$htmlEntities["&lceil;"]    ="\xE2\x8C\x88"; // &#8968; (left ceiling)
+$htmlEntities["&rceil;"]    ="\xE2\x8C\x89"; // &#8969; (right ceiling)
+$htmlEntities["&lfloor;"]   ="\xE2\x8C\x8A"; // &#8970; (left floor)
+$htmlEntities["&rfloor;"]   ="\xE2\x8C\x8B"; // &#8971; (right floor)
+$htmlEntities["&lang;"]     ="\xE2\x8C\xA9"; // &#9001; (left angle bracket = bra)
+$htmlEntities["&rang;"]     ="\xE2\x8C\xAA"; // &#9002; (right angle bracket = ket)
+$htmlEntities["&loz;"]      ="\xE2\x97\x8A"; // &#9674; (lozenge)
+$htmlEntities["&spades;"]   ="\xE2\x99\xA0"; // &#9824; (spade)
+$htmlEntities["&clubs;"]    ="\xE2\x99\xA3"; // &#9827; (club)
+$htmlEntities["&hearts;"]   ="\xE2\x99\xA5"; // &#9829; (heart)
+$htmlEntities["&diams;"]    ="\xE2\x99\xA6"; // &#9830; (diamond)
+?>
\ No newline at end of file
diff --git a/inc/3rdparty/libraries/PHPePub/EPub.NCX.php b/inc/3rdparty/libraries/PHPePub/EPub.NCX.php
new file mode 100644 (file)
index 0000000..e5da05c
--- /dev/null
@@ -0,0 +1,782 @@
+<?php
+/**
+ * ePub NCX file structure
+ *
+ * @author A. Grandt <php@grandt.com>
+ * @copyright 2009-2014 A. Grandt
+ * @license GNU LGPL, Attribution required for commercial implementations, requested for everything else.
+ * @version 3.20
+ */
+class Ncx {
+    const _VERSION = 3.20;
+
+    const MIMETYPE = "application/x-dtbncx+xml";
+
+    private $bookVersion = EPub::BOOK_VERSION_EPUB2;
+
+    private $navMap = NULL;
+    private $uid = NULL;
+    private $meta = array();
+    private $docTitle = NULL;
+    private $docAuthor = NULL;
+
+    private $currentLevel = NULL;
+    private $lastLevel = NULL;
+
+    private $languageCode = "en";
+    private $writingDirection = EPub::DIRECTION_LEFT_TO_RIGHT;
+
+    public $chapterList = array();
+    public $referencesTitle = "Guide";
+    public $referencesClass = "references";
+       public $referencesId = "references";
+       public $referencesList = array();
+    public $referencesName = array();
+    public $referencesOrder = NULL;
+
+    /**
+     * Class constructor.
+        *
+        * @param string $uid
+        * @param string $docTitle
+        * @param string $docAuthor
+        * @param string $languageCode
+        * @param string $writingDirection
+        */
+    function __construct($uid = NULL, $docTitle = NULL, $docAuthor = NULL, $languageCode = "en", $writingDirection = EPub::DIRECTION_LEFT_TO_RIGHT) {
+        $this->navMap = new NavMap($writingDirection);
+        $this->currentLevel = $this->navMap;
+        $this->setUid($uid);
+        $this->setDocTitle($docTitle);
+        $this->setDocAuthor($docAuthor);
+               $this->setLanguageCode($languageCode);
+               $this->setWritingDirection($writingDirection);
+    }
+
+    /**
+     * Class destructor
+     *
+     * @return void
+     */
+    function __destruct() {
+        unset($this->bookVersion, $this->navMap, $this->uid, $this->meta);
+        unset($this->docTitle, $this->docAuthor, $this->currentLevel, $this->lastLevel);
+               unset($this->languageCode, $this->writingDirection, $this->chapterList, $this->referencesTitle);
+               unset($this->referencesClass, $this->referencesId, $this->referencesList, $this->referencesName);
+               unset($this->referencesOrder);
+       }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $bookVersion
+     */
+    function setVersion($bookVersion) {
+        $this->bookVersion = is_string($bookVersion) ? trim($bookVersion) : EPub::BOOK_VERSION_EPUB2;
+    }
+
+       /**
+        *
+        * @return bool TRUE if the book is set to type ePub 2
+        */
+    function isEPubVersion2() {
+        return $this->bookVersion === EPub::BOOK_VERSION_EPUB2;
+   }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $uid
+     */
+    function setUid($uid) {
+        $this->uid = is_string($uid) ? trim($uid) : NULL;
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $docTitle
+     */
+    function setDocTitle($docTitle) {
+        $this->docTitle = is_string($docTitle) ? trim($docTitle) : NULL;
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $docAuthor
+     */
+    function setDocAuthor($docAuthor) {
+        $this->docAuthor = is_string($docAuthor) ? trim($docAuthor) : NULL;
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $languageCode
+     */
+    function setLanguageCode($languageCode) {
+        $this->languageCode = is_string($languageCode) ? trim($languageCode) : "en";
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $writingDirection
+     */
+    function setWritingDirection($writingDirection) {
+        $this->writingDirection = is_string($writingDirection) ? trim($writingDirection) : EPub::DIRECTION_LEFT_TO_RIGHT;
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param NavMap $navMap
+     */
+    function setNavMap($navMap) {
+        if ($navMap != NULL && is_object($navMap) && get_class($navMap) === "NavMap") {
+            $this->navMap = $navMap;
+        }
+    }
+
+    /**
+     * Add one chapter level.
+     *
+     * Subsequent chapters will be added to this level.
+        *
+        * @param string $navTitle
+        * @param string $navId
+        * @param string $navClass
+        * @param string $isNavHidden
+        * @param string $writingDirection
+        * @return NavPoint
+        */
+    function subLevel($navTitle = NULL, $navId = NULL, $navClass = NULL, $isNavHidden = FALSE, $writingDirection = NULL) {
+               $navPoint = FALSE;
+               if (isset($navTitle) && isset($navClass)) {
+                       $navPoint = new NavPoint($navTitle, NULL, $navId, $navClass, $isNavHidden, $writingDirection);
+                       $this->addNavPoint($navPoint);
+               }
+        if ($this->lastLevel !== NULL) {
+            $this->currentLevel = $this->lastLevel;
+        }
+               return $navPoint;
+    }
+
+    /**
+     * Step back one chapter level.
+     *
+     * Subsequent chapters will be added to this chapters parent level.
+     */
+    function backLevel() {
+        $this->lastLevel = $this->currentLevel;
+        $this->currentLevel = $this->currentLevel->getParent();
+    }
+
+    /**
+     * Step back to the root level.
+     *
+     * Subsequent chapters will be added to the rooot NavMap.
+     */
+    function rootLevel() {
+        $this->lastLevel = $this->currentLevel;
+        $this->currentLevel = $this->navMap;
+    }
+
+    /**
+     * Step back to the given level.
+     * Useful for returning to a previous level from deep within the structure.
+     * Values below 2 will have the same effect as rootLevel()
+     *
+     * @param int $newLevel
+     */
+    function setCurrentLevel($newLevel) {
+        if ($newLevel <= 1) {
+            $this->rootLevel();
+        } else {
+            while ($this->currentLevel->getLevel() > $newLevel) {
+                $this->backLevel();
+            }
+        }
+    }
+
+    /**
+     * Get current level count.
+     * The indentation of the current structure point.
+     *
+     * @return current level count;
+     */
+    function getCurrentLevel() {
+        return $this->currentLevel->getLevel();
+    }
+
+    /**
+     * Add child NavPoints to current level.
+     *
+     * @param NavPoint $navPoint
+     */
+    function addNavPoint($navPoint) {
+        $this->lastLevel = $this->currentLevel->addNavPoint($navPoint);
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @return NavMap
+     */
+    function getNavMap() {
+        return $this->navMap;
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $name
+     * @param string $content
+     */
+    function addMetaEntry($name, $content) {
+        $name = is_string($name) ? trim($name) : NULL;
+        $content = is_string($content) ? trim($content) : NULL;
+
+        if ($name != NULL && $content != NULL) {
+            $this->meta[] = array($name => $content);
+        }
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @return string
+     */
+    function finalize() {
+        $nav = $this->navMap->finalize();
+
+        $ncx = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
+        if ($this->isEPubVersion2()) {
+            $ncx .= "<!DOCTYPE ncx PUBLIC \"-//NISO//DTD ncx 2005-1//EN\"\n"
+            . "  \"http://www.daisy.org/z3986/2005/ncx-2005-1.dtd\">\n";
+        }
+        $ncx .= "<ncx xmlns=\"http://www.daisy.org/z3986/2005/ncx/\" version=\"2005-1\" xml:lang=\"" . $this->languageCode . "\" dir=\"" . $this->writingDirection . "\">\n"
+        . "\t<head>\n"
+        . "\t\t<meta name=\"dtb:uid\" content=\"" . $this->uid . "\" />\n"
+        . "\t\t<meta name=\"dtb:depth\" content=\"" . $this->navMap->getNavLevels() . "\" />\n"
+        . "\t\t<meta name=\"dtb:totalPageCount\" content=\"0\" />\n"
+        . "\t\t<meta name=\"dtb:maxPageNumber\" content=\"0\" />\n";
+
+        if (sizeof($this->meta)) {
+            foreach ($this->meta as $metaEntry) {
+                list($name, $content) = each($metaEntry);
+                $ncx .= "\t\t<meta name=\"" . $name . "\" content=\"" . $content . "\" />\n";
+            }
+        }
+
+        $ncx .= "\t</head>\n\n\t<docTitle>\n\t\t<text>"
+        . $this->docTitle
+        . "</text>\n\t</docTitle>\n\n\t<docAuthor>\n\t\t<text>"
+        . $this->docAuthor
+        . "</text>\n\t</docAuthor>\n\n"
+        . $nav;
+
+        return $ncx . "</ncx>\n";
+    }
+
+       /**
+        *
+        * @param string $title
+        * @param string $cssFileName
+        * @return string
+        */
+    function finalizeEPub3($title = "Table of Contents", $cssFileName = NULL) {
+               $end = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+            . "<html xmlns=\"http://www.w3.org/1999/xhtml\"\n"
+            . "      xmlns:epub=\"http://www.idpf.org/2007/ops\"\n"
+            . "      xml:lang=\"" . $this->languageCode . "\" lang=\"" . $this->languageCode . "\" dir=\"" . $this->writingDirection . "\">\n"
+            . "\t<head>\n"
+            . "\t\t<title>" . $this->docTitle . "</title>\n"
+            . "\t\t<meta http-equiv=\"default-style\" content=\"text/html; charset=utf-8\"/>\n";
+        if ($cssFileName !== NULL) {
+            $end .= "\t\t<link rel=\"stylesheet\" href=\"" . $cssFileName . "\" type=\"text/css\"/>\n";
+        }
+        $end .= "\t</head>\n"
+            . "\t<body epub:type=\"frontmatter toc\">\n"
+            . "\t\t<header>\n"
+            . "\t\t\t<h1>" . $title . "</h1>\n"
+            . "\t\t</header>\n"
+            . $this->navMap->finalizeEPub3()
+            . $this->finalizeEPub3Landmarks()
+            . "\t</body>\n"
+            . "</html>\n";
+
+        return $end;
+    }
+
+       /**
+        * Build the references for the ePub 2 toc.
+        * These are merely reference pages added to the end of the navMap though.
+        *
+        * @return string
+        */
+       function finalizeReferences() {
+               if (isset($this->referencesList) && sizeof($this->referencesList) > 0) {
+                       $this->rootLevel();
+                       $this->subLevel($this->referencesTitle, $this->referencesId, $this->referencesClass);
+                       $refId = 1;
+                       while (list($item, $descriptive) = each($this->referencesOrder)) {
+                               if (array_key_exists($item, $this->referencesList)) {
+                                       $name = (empty($this->referencesName[$item]) ? $descriptive : $this->referencesName[$item]);
+                                       $navPoint = new NavPoint($name, $this->referencesList[$item], "ref-" . $refId++);
+                                       $this->addNavPoint($navPoint);
+                               }
+                       }
+               }
+       }
+
+       /**
+        * Build the landmarks for the ePub 3 toc.
+        * @return string
+        */
+       function finalizeEPub3Landmarks() {
+               $lm = "";
+               if (isset($this->referencesList) && sizeof($this->referencesList) > 0) {
+                       $lm = "\t\t\t<nav epub:type=\"landmarks\">\n"
+                                       . "\t\t\t\t<h2"
+                                       . ($this->writingDirection === EPub::DIRECTION_RIGHT_TO_LEFT ? " dir=\"rtl\"" : "")
+                                       . ">" . $this->referencesTitle . "</h2>\n"
+                                       . "\t\t\t\t<ol>\n";
+
+                       $li = "";
+                       while (list($item, $descriptive) = each($this->referencesOrder)) {
+                               if (array_key_exists($item, $this->referencesList)) {
+                                       $li .= "\t\t\t\t\t<li><a epub:type=\""
+                                                       . $item
+                                                       . "\" href=\"" . $this->referencesList[$item] . "\">"
+                                                       . (empty($this->referencesName[$item]) ? $descriptive : $this->referencesName[$item])
+                                                       . "</a></li>\n";
+                               }
+                       }
+                       if (empty($li)) {
+                               return "";
+                       }
+
+                       $lm .= $li
+                                       . "\t\t\t\t</ol>\n"
+                                       . "\t\t\t</nav>\n";
+               }
+               return $lm;
+       }
+}
+
+/**
+ * ePub NavMap class
+ */
+class NavMap {
+    const _VERSION = 3.00;
+
+    private $navPoints = array();
+    private $navLevels = 0;
+       private $writingDirection = NULL;
+
+    /**
+     * Class constructor.
+     *
+     * @return void
+     */
+    function __construct($writingDirection = NULL) {
+               $this->setWritingDirection($writingDirection);
+    }
+
+    /**
+     * Class destructor
+     *
+     * @return void
+     */
+    function __destruct() {
+        unset($this->navPoints, $this->navLevels, $this->writingDirection);
+    }
+
+    /**
+     * Set the writing direction to be used for this NavPoint.
+     *
+     * @param string $writingDirection
+     */
+    function setWritingDirection($writingDirection) {
+        $this->writingDirection = isset($writingDirection) && is_string($writingDirection) ? trim($writingDirection) : NULL;
+    }
+
+    function getWritingDirection() {
+        return $this->writingDirection;
+    }
+
+    /**
+     * Add a navPoint to the root of the NavMap.
+     *
+     * @param NavPoint $navPoint
+     * @return NavMap
+     */
+    function addNavPoint($navPoint) {
+        if ($navPoint != NULL && is_object($navPoint) && get_class($navPoint) === "NavPoint") {
+            $navPoint->setParent($this);
+                       if ($navPoint->getWritingDirection() == NULL) {
+                               $navPoint->setWritingDirection($this->writingDirection);
+                       }
+            $this->navPoints[] = $navPoint;
+            return $navPoint;
+        }
+        return $this;
+    }
+
+    /**
+     * The final max depth for the "dtb:depth" meta attribute
+     * Only available after finalize have been called.
+     *
+     * @return number
+     */
+    function getNavLevels() {
+        return $this->navLevels+1;
+    }
+
+    function getLevel() {
+        return 1;
+    }
+
+    function getParent() {
+        return $this;
+    }
+
+    /**
+     * Finalize the navMap, the final max depth for the "dtb:depth" meta attribute can be retrieved with getNavLevels after finalization
+     *
+     */
+    function finalize() {
+        $playOrder = 0;
+        $this->navLevels = 0;
+
+        $nav = "\t<navMap>\n";
+        if (sizeof($this->navPoints) > 0) {
+            $this->navLevels++;
+            foreach ($this->navPoints as $navPoint) {
+                $retLevel = $navPoint->finalize($nav, $playOrder, 0);
+                if ($retLevel > $this->navLevels) {
+                    $this->navLevels = $retLevel;
+                }
+            }
+        }
+        return $nav . "\t</navMap>\n";
+    }
+
+    /**
+     * Finalize the navMap, the final max depth for the "dtb:depth" meta attribute can be retrieved with getNavLevels after finalization
+     *
+     */
+    function finalizeEPub3() {
+        $playOrder = 0;
+        $level = 0;
+        $this->navLevels = 0;
+
+        $nav = "\t\t<nav epub:type=\"toc\" id=\"toc\">\n";
+
+        if (sizeof($this->navPoints) > 0) {
+            $this->navLevels++;
+
+            $nav .= str_repeat("\t", $level) . "\t\t\t<ol epub:type=\"list\">\n";
+            foreach ($this->navPoints as $navPoint) {
+                $retLevel = $navPoint->finalizeEPub3($nav, $playOrder, 0);
+                if ($retLevel > $this->navLevels) {
+                    $this->navLevels = $retLevel;
+                }
+            }
+            $nav .= str_repeat("\t", $level) . "\t\t\t</ol>\n";
+        }
+
+        return $nav . "\t\t</nav>\n";
+    }
+}
+
+/**
+ * ePub NavPoint class
+ */
+class NavPoint {
+    const _VERSION = 3.00;
+
+    private $label = NULL;
+    private $contentSrc = NULL;
+    private $id = NULL;
+    private $navClass = NULL;
+    private $isNavHidden = FALSE;
+       private $navPoints = array();
+       private $parent = NULL;
+
+    /**
+     * Class constructor.
+     *
+     * All three attributes are mandatory, though if ID is set to null (default) the value will be generated.
+     *
+     * @param string $label
+     * @param string $contentSrc
+     * @param string $id
+        * @param string $navClass
+        * @param bool   $isNavHidden
+        * @param string $writingDirection
+        */
+    function __construct($label, $contentSrc = NULL, $id = NULL, $navClass = NULL, $isNavHidden = FALSE, $writingDirection = NULL) {
+        $this->setLabel($label);
+        $this->setContentSrc($contentSrc);
+        $this->setId($id);
+        $this->setNavClass($navClass);
+        $this->setNavHidden($isNavHidden);
+               $this->setWritingDirection($writingDirection);
+    }
+
+    /**
+     * Class destructor
+     *
+     * @return void
+     */
+    function __destruct() {
+        unset($this->label, $this->contentSrc, $this->id, $this->navClass);
+        unset($this->isNavHidden, $this->navPoints, $this->parent);
+    }
+
+    /**
+     * Set the Text label for the NavPoint.
+     *
+     * The label is mandatory.
+     *
+     * @param string $label
+     */
+    function setLabel($label) {
+        $this->label = is_string($label) ? trim($label) : NULL;
+    }
+
+    /**
+     * Get the Text label for the NavPoint.
+     *
+     * @return string Label
+     */
+    function getLabel() {
+        return $this->label;
+    }
+
+    /**
+     * Set the src reference for the NavPoint.
+     *
+     * The src is mandatory for ePub 2.
+     *
+     * @param string $contentSrc
+     */
+    function setContentSrc($contentSrc) {
+        $this->contentSrc =  isset($contentSrc) && is_string($contentSrc) ? trim($contentSrc) : NULL;
+    }
+
+    /**
+     * Get the src reference for the NavPoint.
+     *
+     * @return string content src url.
+     */
+    function getContentSrc() {
+        return $this->contentSrc;
+    }
+    /**
+     * Set the parent for this NavPoint.
+     *
+     * @param NavPoint or NavMap $parent
+     */
+    function setParent($parent) {
+        if ($parent != NULL && is_object($parent) &&
+                (get_class($parent) === "NavPoint" || get_class($parent) === "NavMap") ) {
+            $this->parent = $parent;
+        }
+    }
+
+    /**
+     * Get the parent to this NavPoint.
+     *
+     * @return NavPoint, or NavMap if the parent is the root.
+     */
+    function getParent() {
+        return $this->parent;
+    }
+
+    /**
+     * Get the current level. 1 = document root.
+     *
+     * @return int level
+     */
+    function getLevel() {
+        return $this->parent === NULL ? 1 : $this->parent->getLevel()+1;
+    }
+
+    /**
+     * Set the id for the NavPoint.
+     *
+     * The id must be unique, and is mandatory.
+     *
+     * @param string $id
+     */
+    function setId($id) {
+        $this->id = is_string($id) ? trim($id) : NULL;
+    }
+
+    /**
+     * Set the class to be used for this NavPoint.
+     *
+     * @param string $navClass
+     */
+    function setNavClass($navClass) {
+        $this->navClass = isset($navClass) && is_string($navClass) ? trim($navClass) : NULL;
+    }
+
+    /**
+     * Set the class to be used for this NavPoint.
+     *
+     * @param string $navClass
+     */
+    function setNavHidden($isNavHidden) {
+        $this->isNavHidden = $isNavHidden === TRUE;
+    }
+
+    /**
+     * Set the writing direction to be used for this NavPoint.
+     *
+     * @param string $writingDirection
+     */
+    function setWritingDirection($writingDirection) {
+        $this->writingDirection = isset($writingDirection) && is_string($writingDirection) ? trim($writingDirection) : NULL;
+    }
+
+    function getWritingDirection() {
+        return $this->writingDirection;
+    }
+
+       /**
+     * Add child NavPoints for multi level NavMaps.
+     *
+     * @param NavPoint $navPoint
+     */
+    function addNavPoint($navPoint) {
+        if ($navPoint != NULL && is_object($navPoint) && get_class($navPoint) === "NavPoint") {
+            $navPoint->setParent($this);
+                       if ($navPoint->getWritingDirection() == NULL) {
+                               $navPoint->setWritingDirection($this->writingDirection);
+                       }
+            $this->navPoints[] = $navPoint;
+            return $navPoint;
+        }
+        return $this;
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $nav
+     * @param int    $playOrder
+     * @param int    $level
+     * @return int
+     */
+    function finalize(&$nav = "", &$playOrder = 0, $level = 0) {
+        $maxLevel = $level;
+        $levelAdjust = 0;
+
+               if ($this->isNavHidden) {
+                       return $maxLevel;
+               }
+
+               if (isset($this->contentSrc)) {
+                       $playOrder++;
+
+                       if ($this->id == NULL) {
+                               $this->id = "navpoint-" . $playOrder;
+                       }
+                       $nav .= str_repeat("\t", $level) . "\t\t<navPoint id=\"" . $this->id . "\" playOrder=\"" . $playOrder . "\">\n"
+                       . str_repeat("\t", $level) . "\t\t\t<navLabel>\n"
+                       . str_repeat("\t", $level) . "\t\t\t\t<text>" . $this->label . "</text>\n"
+                       . str_repeat("\t", $level) . "\t\t\t</navLabel>\n"
+                       . str_repeat("\t", $level) . "\t\t\t<content src=\"" . $this->contentSrc . "\" />\n";
+               } else {
+                       $levelAdjust++;
+               }
+
+        if (sizeof($this->navPoints) > 0) {
+            $maxLevel++;
+            foreach ($this->navPoints as $navPoint) {
+                $retLevel = $navPoint->finalize($nav, $playOrder, ($level+1+$levelAdjust));
+                if ($retLevel > $maxLevel) {
+                    $maxLevel = $retLevel;
+                }
+            }
+        }
+
+               if (isset($this->contentSrc)) {
+               $nav .= str_repeat("\t", $level) . "\t\t</navPoint>\n";
+               }
+
+        return $maxLevel;
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $nav
+     * @param int    $playOrder
+     * @param int    $level
+     * @return int
+     */
+    function finalizeEPub3(&$nav = "", &$playOrder = 0, $level = 0, $subLevelClass = NULL, $subLevelHidden = FALSE) {
+        $maxLevel = $level;
+
+        if ($this->id == NULL) {
+            $this->id = "navpoint-" . $playOrder;
+        }
+               $indent = str_repeat("\t", $level) . "\t\t\t\t";
+
+        $nav .= $indent . "<li id=\"" . $this->id . "\"";
+               if (isset($this->writingDirection)) {
+                       $nav .= " dir=\"" . $this->writingDirection . "\"";
+               }
+               $nav .=  ">\n";
+
+               if (isset($this->contentSrc)) {
+                       $nav .= $indent . "\t<a href=\"" . $this->contentSrc . "\">" . $this->label . "</a>\n";
+               } else {
+                       $nav .= $indent . "\t<span>" . $this->label . "</span>\n";
+               }
+
+        if (sizeof($this->navPoints) > 0) {
+            $maxLevel++;
+
+                       $nav .= $indent . "\t<ol epub:type=\"list\"";
+            if (isset($subLevelClass)) {
+                               $nav .= " class=\"" . $subLevelClass . "\"";
+                       }
+            if ($subLevelHidden) {
+                               $nav .= " hidden=\"hidden\"";
+                       }
+            $nav .= ">\n";
+
+            foreach ($this->navPoints as $navPoint) {
+                $retLevel = $navPoint->finalizeEPub3($nav, $playOrder, ($level+2), $subLevelClass, $subLevelHidden);
+                if ($retLevel > $maxLevel) {
+                    $maxLevel = $retLevel;
+                }
+            }
+            $nav .= $indent . "\t</ol>\n";
+        }
+
+        $nav .= $indent . "</li>\n";
+
+        return $maxLevel;
+    }
+}
+?>
\ No newline at end of file
diff --git a/inc/3rdparty/libraries/PHPePub/EPub.OPF.php b/inc/3rdparty/libraries/PHPePub/EPub.OPF.php
new file mode 100644 (file)
index 0000000..803a210
--- /dev/null
@@ -0,0 +1,1226 @@
+<?php
+/**
+ * ePub OPF file structure
+ *
+ * @author A. Grandt <php@grandt.com>
+ * @copyright 2009-2014 A. Grandt
+ * @license GNU LGPL, Attribution required for commercial implementations, requested for everything else.
+ * @version 3.20
+ */
+class Opf {
+    const _VERSION = 3.20;
+
+    /* Core Media types.
+     * These types are the only guaranteed mime types any ePub reader must understand.
+    * Any other type muse define a fall back whose fallback chain will end in one of these.
+    */
+    const TYPE_GIF = "image/gif";
+    const TYPE_JPEG = "image/jpeg";
+    const TYPE_PNG = "image/png";
+    const TYPE_SVG = "image/svg+xml";
+    const TYPE_XHTML = "application/xhtml+xml";
+    const TYPE_DTBOOK = "application/x-dtbook+xml";
+    const TYPE_CSS = "text/css";
+    const TYPE_XML = "application/xml";
+    const TYPE_OEB1_DOC = "text/x-oeb1-document"; // Deprecated
+    const TYPE_OEB1_CSS = "text/x-oeb1-css"; // Deprecated
+    const TYPE_NCX = "application/x-dtbncx+xml";
+
+    private $bookVersion = EPub::BOOK_VERSION_EPUB2;
+       private $ident = "BookId";
+
+    public $date = NULL;
+    public $metadata = NULL;
+    public $manifest = NULL;
+    public $spine = NULL;
+    public $guide = NULL;
+
+    /**
+     * Class constructor.
+     *
+     * @return void
+     */
+    function __construct($ident = "BookId", $bookVersion = EPub::BOOK_VERSION_EPUB2) {
+        $this->setIdent($ident);
+        $this->setVersion($bookVersion);
+        $this->metadata = new Metadata();
+        $this->manifest = new Manifest();
+        $this->spine = new Spine();
+        $this->guide = new Guide();
+    }
+
+    /**
+     * Class destructor
+     *
+     * @return void
+     */
+    function __destruct() {
+        unset ($this->bookVersion, $this->ident, $this->date, $this->metadata, $this->manifest, $this->spine, $this->guide);
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $ident
+     */
+    function setVersion($bookVersion) {
+        $this->bookVersion = is_string($bookVersion) ? trim($bookVersion) : EPub::BOOK_VERSION_EPUB2;
+    }
+
+       function isEPubVersion2() {
+               return $this->bookVersion === EPub::BOOK_VERSION_EPUB2;
+       }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $ident
+     */
+    function setIdent($ident = "BookId") {
+        $this->ident = is_string($ident) ? trim($ident) : "BookId";
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @return string
+     */
+    function finalize() {
+        $opf = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
+                               . "<package xmlns=\"http://www.idpf.org/2007/opf\" unique-identifier=\"" . $this->ident . "\" version=\"" . $this->bookVersion . "\">\n";
+
+               $opf .= $this->metadata->finalize($this->bookVersion, $this->date);
+        $opf .= $this->manifest->finalize($this->bookVersion);
+        $opf .= $this->spine->finalize();
+
+        if ($this->guide->length() > 0) {
+            $opf .= $this->guide->finalize();
+        }
+
+        return $opf . "</package>\n";
+    }
+
+    // Convenience functions:
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $title
+     * @param string $language
+     * @param string $identifier
+     * @param string $identifierScheme
+     */
+    function initialize($title, $language, $identifier, $identifierScheme) {
+        $this->metadata->addDublinCore(new DublinCore("title", $title));
+        $this->metadata->addDublinCore(new DublinCore("language", $language));
+
+        $dc = new DublinCore("identifier", $identifier);
+        $dc->addAttr("id", $this->ident);
+        $dc->addOpfAttr("scheme", $identifierScheme);
+        $this->metadata->addDublinCore($dc);
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $id
+     * @param string $href
+     * @param string $mediaType
+     */
+    function addItem($id, $href, $mediaType, $properties = NULL) {
+        $this->manifest->addItem(new Item($id, $href, $mediaType, $properties));
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $idref
+     * @param bool   $linear
+     */
+    function addItemRef($idref, $linear = TRUE) {
+        $this->spine->addItemref(new Itemref($idref, $linear));
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $type
+     * @param string $title
+     * @param string $href
+     */
+    function addReference($type, $title, $href) {
+        $this->guide->addReference(new Reference($type, $title, $href));
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $name
+     * @param string $value
+     */
+    function addDCMeta($name, $value) {
+        $this->metadata->addDublinCore(new DublinCore($name, $value));
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $name
+     * @param string $content
+     */
+    function addMeta($name, $content) {
+        $this->metadata->addMeta($name, $content);
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $name
+     * @param string $fileAs
+     * @param string $role Use the MarcCode constants
+     */
+    function addCreator($name, $fileAs = NULL, $role = NULL) {
+        $dc = new DublinCore(DublinCore::CREATOR, trim($name));
+
+        if ($fileAs !== NULL) {
+            $dc->addOpfAttr("file-as", trim($fileAs));
+        }
+
+        if ($role !== NULL) {
+            $dc->addOpfAttr("role", trim($role));
+        }
+
+        $this->metadata->addDublinCore($dc);
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $name
+     * @param string $fileAs
+     * @param string $role Use the MarcCode constants
+     */
+    function addColaborator($name, $fileAs = NULL, $role = NULL) {
+        $dc = new DublinCore(DublinCore::CONTRIBUTOR, trim($name));
+
+        if ($fileAs !== NULL) {
+            $dc->addOpfAttr("file-as", trim($fileAs));
+        }
+
+        if ($role !== NULL) {
+            $dc->addOpfAttr("role", trim($role));
+        }
+
+        $this->metadata->addDublinCore($dc);
+    }
+}
+
+/**
+ * ePub OPF Metadata structures
+ */
+class Metadata {
+    const _VERSION = 3.00;
+
+    private $dc = array();
+    private $meta = array();
+
+    /**
+     * Class constructor.
+     *
+     * @return void
+     */
+    function __construct() {
+    }
+
+    /**
+     * Class destructor
+     *
+     * @return void
+     */
+    function __destruct() {
+        unset ($this->dc, $this->meta);
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param DublinCore $dc
+     */
+    function addDublinCore($dc) {
+        if ($dc != NULL && is_object($dc) && get_class($dc) === "DublinCore") {
+            $this->dc[] = $dc;
+        }
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $name
+     * @param string $content
+     */
+    function addMeta($name, $content) {
+        $name = is_string($name) ? trim($name) : NULL;
+        if (isset($name)) {
+            $content = is_string($content) ? trim($content) : NULL;
+        }
+        if (isset($content)) {
+            $this->meta[] = array ($name => $content);
+        }
+    }
+
+       /**
+        *
+        * @param string $bookVersion
+        * @param int    $date
+        * @return string
+        */
+    function finalize($bookVersion = EPub::BOOK_VERSION_EPUB2, $date = NULL) {
+        $metadata = "\t<metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n";
+               if ($bookVersion === EPub::BOOK_VERSION_EPUB2) {
+                       $metadata .= "\t\txmlns:opf=\"http://www.idpf.org/2007/opf\"\n\t\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n";
+               } else {
+                       $metadata .= "\t\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n";
+                       if (!isset($date)) {
+                               $date = time();
+                       }
+                       $metadata .= "\t\t<meta property=\"dcterms:modified\">" . gmdate("Y-m-d\TH:i:s\Z", $date) . "</meta>\n";
+               }
+
+        foreach ($this->dc as $dc) {
+            $metadata .= $dc->finalize($bookVersion);
+        }
+
+        foreach ($this->meta as $data) {
+            list($name, $content) = each($data);
+            $metadata .= "\t\t<meta name=\"" . $name . "\" content=\"" . $content . "\" />\n";
+        }
+
+        return $metadata . "\t</metadata>\n";
+    }
+}
+
+/**
+ * ePub OPF Dublin Core (dc:) Metadata structures
+ */
+class DublinCore {
+    const _VERSION = 3.00;
+
+    const CONTRIBUTOR = "contributor";
+    const COVERAGE = "coverage";
+    const CREATOR = "creator";
+    const DATE = "date";
+    const DESCRIPTION = "description";
+    const FORMAT = "format";
+    const IDENTIFIER = "identifier";
+    const LANGUAGE = "language";
+    const PUBLISHER = "publisher";
+    const RELATION = "relation";
+    const RIGHTS = "rights";
+    const SOURCE = "source";
+    const SUBJECT = "subject";
+    const TITLE = "title";
+    const TYPE = "type";
+
+    private $dcName = NULL;
+    private $dcValue = NULL;
+    private $attr = array();
+    private $opfAttr = array();
+
+    /**
+     * Class constructor.
+     *
+     * @return void
+     */
+    function __construct($name, $value) {
+        $this->setDc($name, $value);
+    }
+
+    /**
+     * Class destructor
+     *
+     * @return void
+     */
+    function __destruct() {
+        unset ($this->dcName, $this->dcValue, $this->attr, $this->opfAttr);
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $name
+     * @param string $value
+     */
+    function setDc($name, $value) {
+        $this->dcName = is_string($name) ? trim($name) : NULL;
+        if (isset($this->dcName)) {
+            $this->dcValue = isset($value) ? (string)$value : NULL;
+        }
+        if (! isset($this->dcValue)) {
+            $this->dcName = NULL;
+        }
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $attrName
+     * @param string $attrValue
+     */
+    function addAttr($attrName, $attrValue) {
+        $attrName = is_string($attrName) ? trim($attrName) : NULL;
+        if (isset($attrName)) {
+            $attrValue = is_string($attrValue) ? trim($attrValue) : NULL;
+        }
+        if (isset($attrValue)) {
+            $this->attr[$attrName] = $attrValue;
+        }
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $opfAttrName
+     * @param string $opfAttrValue
+     */
+    function addOpfAttr($opfAttrName, $opfAttrValue) {
+        $opfAttrName = is_string($opfAttrName) ? trim($opfAttrName) : NULL;
+        if (isset($opfAttrName)) {
+            $opfAttrValue = is_string($opfAttrValue) ? trim($opfAttrValue) : NULL;
+        }
+        if (isset($opfAttrValue)) {
+            $this->opfAttr[$opfAttrName] = $opfAttrValue;
+        }
+    }
+
+
+       /**
+        *
+        * @param string $bookVersion
+        * @return string
+        */
+    function finalize($bookVersion = EPub::BOOK_VERSION_EPUB2) {
+        $dc = "\t\t<dc:" . $this->dcName;
+
+        if (sizeof($this->attr) > 0) {
+            while (list($name, $content) = each($this->attr)) {
+                $dc .= " " . $name . "=\"" . $content . "\"";
+            }
+        }
+
+        if ($bookVersion === EPub::BOOK_VERSION_EPUB2 && sizeof($this->opfAttr) > 0) {
+            while (list($name, $content) = each($this->opfAttr)) {
+                $dc .= " opf:" . $name . "=\"" . $content . "\"";
+            }
+        }
+
+        return $dc . ">" . $this->dcValue . "</dc:" . $this->dcName . ">\n";
+    }
+}
+
+/**
+ * ePub OPF Manifest structure
+ */
+class Manifest {
+    const _VERSION = 3.00;
+
+    private $items = array();
+
+    /**
+     * Class constructor.
+     *
+     * @return void
+     */
+    function __construct() {
+    }
+
+    /**
+     * Class destructor
+     *
+     * @return void
+     */
+    function __destruct() {
+        unset ($this->items);
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param Item $item
+     */
+    function addItem($item) {
+        if ($item != NULL && is_object($item) && get_class($item) === "Item") {
+            $this->items[] = $item;
+        }
+    }
+
+       /**
+        *
+        * @param string $bookVersion
+        * @return string
+        */
+       function finalize($bookVersion = EPub::BOOK_VERSION_EPUB2) {
+        $manifest = "\n\t<manifest>\n";
+        foreach ($this->items as $item) {
+            $manifest .= $item->finalize($bookVersion);
+        }
+        return $manifest . "\t</manifest>\n";
+    }
+}
+
+/**
+ * ePub OPF Item structure
+ */
+class Item {
+    const _VERSION = 3.00;
+
+    private $id = NULL;
+    private $href = NULL;
+    private $mediaType = NULL;
+       private $properties = NULL;
+    private $requiredNamespace = NULL;
+    private $requiredModules = NULL;
+    private $fallback = NULL;
+    private $fallbackStyle = NULL;
+
+    /**
+     * Class constructor.
+     *
+     * @return void
+     */
+    function __construct($id, $href, $mediaType, $properties = NULL) {
+        $this->setId($id);
+        $this->setHref($href);
+        $this->setMediaType($mediaType);
+        $this->setProperties($properties);
+    }
+
+    /**
+     * Class destructor
+     *
+     * @return void
+     */
+    function __destruct() {
+        unset ($this->id, $this->href, $this->mediaType);
+        unset ($this->properties, $this->requiredNamespace, $this->requiredModules, $this->fallback, $this->fallbackStyle);
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $id
+     */
+    function setId($id) {
+        $this->id = is_string($id) ? trim($id) : NULL;
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $href
+     */
+    function setHref($href) {
+        $this->href = is_string($href) ? trim($href) : NULL;
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $mediaType
+     */
+    function setMediaType($mediaType) {
+        $this->mediaType = is_string($mediaType) ? trim($mediaType) : NULL;
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $properties
+     */
+    function setProperties($properties) {
+        $this->properties = is_string($properties) ? trim($properties) : NULL;
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $requiredNamespace
+     */
+    function setRequiredNamespace($requiredNamespace) {
+        $this->requiredNamespace = is_string($requiredNamespace) ? trim($requiredNamespace) : NULL;
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $requiredModules
+     */
+    function setRequiredModules($requiredModules) {
+        $this->requiredModules = is_string($requiredModules) ? trim($requiredModules) : NULL;
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $fallback
+     */
+    function setfallback($fallback) {
+        $this->fallback = is_string($fallback) ? trim($fallback) : NULL;
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $fallbackStyle
+     */
+    function setFallbackStyle($fallbackStyle) {
+        $this->fallbackStyle = is_string($fallbackStyle) ? trim($fallbackStyle) : NULL;
+    }
+
+       /**
+        *
+        * @param string $bookVersion
+        * @return string
+        */
+    function finalize($bookVersion = EPub::BOOK_VERSION_EPUB2) {
+        $item = "\t\t<item id=\"" . $this->id . "\" href=\"" . $this->href . "\" media-type=\"" . $this->mediaType . "\" ";
+               if ($bookVersion === EPub::BOOK_VERSION_EPUB3 && isset($this->properties)) {
+            $item .= "properties=\"" . $this->properties . "\" ";
+        }
+        if (isset($this->requiredNamespace)) {
+            $item .= "\n\t\t\trequired-namespace=\"" . $this->requiredNamespace . "\" ";
+            if (isset($this->requiredModules)) {
+                $item .= "required-modules=\"" . $this->requiredModules . "\" ";
+            }
+        }
+        if (isset($this->fallback)) {
+            $item .= "\n\t\t\tfallback=\"" . $this->fallback . "\" ";
+        }
+        if (isset($this->fallbackStyle)) {
+            $item .= "\n\t\t\tfallback-style=\"" . $this->fallbackStyle . "\" ";
+        }
+        return $item . "/>\n";
+    }
+}
+
+/**
+ * ePub OPF Spine structure
+ */
+class Spine {
+    const _VERSION = 1.00;
+
+    private $itemrefs = array();
+    private $toc = NULL;
+
+    /**
+     * Class constructor.
+     *
+     * @return void
+     */
+    function __construct($toc = "ncx") {
+        $this->setToc($toc);
+    }
+
+    /**
+     * Class destructor
+     *
+     * @return void
+     */
+    function __destruct() {
+        unset ($this->itemrefs, $this->toc);
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $toc
+     */
+    function setToc($toc) {
+        $this->toc = is_string($toc) ? trim($toc) : NULL;
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param Itemref $itemref
+     */
+    function addItemref($itemref) {
+        if ($itemref != NULL 
+                               && is_object($itemref) 
+                               && get_class($itemref) === "Itemref" 
+                               && !isset($this->itemrefs[$itemref->getIdref()])) {
+            $this->itemrefs[$itemref->getIdref()] = $itemref;
+        }
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @return string
+     */
+    function finalize() {
+        $spine = "\n\t<spine toc=\"" . $this->toc . "\">\n";
+        foreach ($this->itemrefs as $itemref) {
+            $spine .= $itemref->finalize();
+        }
+        return $spine . "\t</spine>\n";
+    }
+}
+
+/**
+ * ePub OPF ItemRef structure
+ */
+class Itemref {
+    const _VERSION = 3.00;
+
+    private $idref = NULL;
+    private $linear = TRUE;
+
+    /**
+     * Class constructor.
+     *
+     * @return void
+     */
+    function __construct($idref, $linear = TRUE) {
+        $this->setIdref($idref);
+        $this->setLinear($linear);
+    }
+
+    /**
+     * Class destructor
+     *
+     * @return void
+     */
+    function __destruct() {
+        unset ($this->idref, $this->linear);
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $idref
+     */
+    function setIdref($idref) {
+        $this->idref = is_string($idref) ? trim($idref) : NULL;
+    }
+
+       /**
+     *
+     * Enter description here ...
+     *
+     * @return string $idref
+     */
+    function getIdref() {
+        return $this->idref;
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param bool $linear
+     */
+    function setLinear($linear = TRUE) {
+        $this->linear = $linear === TRUE;
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @return string
+     */
+    function finalize() {
+        $itemref = "\t\t<itemref idref=\"" . $this->idref . "\"";
+        if ($this->linear == FALSE) {
+            return $itemref .= " linear=\"no\" />\n";
+        }
+        return $itemref . " />\n";
+    }
+}
+
+/**
+ * ePub OPF Guide structure
+ */
+class Guide {
+    const _VERSION = 3.00;
+
+    private $references = array();
+
+    /**
+     * Class constructor.
+     *
+     * @return void
+     */
+    function __construct() {
+    }
+
+    /**
+     * Class destructor
+     *
+     * @return void
+     */
+    function __destruct() {
+        unset ($this->references);
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     */
+    function length() {
+        return sizeof($this->references);
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param Reference $reference
+     */
+    function addReference($reference) {
+        if ($reference != NULL && is_object($reference) && get_class($reference) === "Reference") {
+            $this->references[] = $reference;
+        }
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @return string
+     */
+    function finalize() {
+        $ref = "";
+        if (sizeof($this->references) > 0) {
+            $ref = "\n\t<guide>\n";
+            foreach ($this->references as $reference) {
+                $ref .= $reference->finalize();
+            }
+            $ref .= "\t</guide>\n";
+        }
+        return $ref;
+    }
+}
+
+/**
+ * Reference constants
+ */
+class Reference {
+    const _VERSION = 1.00;
+
+    /* REFERENCE types are derived from the "Chicago Manual of Style"
+     */
+
+    /** Acknowledgements page */
+    const ACKNOWLEDGEMENTS = "acknowledgements";
+
+    /** Bibliography page */
+    const BIBLIOGRAPHY = "bibliography";
+
+    /** Colophon page */
+    const COLOPHON = "colophon";
+
+    /** Copyright page */
+    const COPYRIGHT_PAGE = "copyright-page";
+
+    /** Dedication */
+    const DEDICATION = "dedication";
+
+    /** Epigraph */
+    const EPIGRAPH = "epigraph";
+
+    /** Foreword */
+    const FOREWORD = "foreword";
+
+    /** Glossary page */
+    const GLOSSARY = "glossary";
+
+    /** back-of-book style index */
+    const INDEX = "index";
+
+    /** List of illustrations */
+    const LIST_OF_ILLUSTRATIONS = "loi";
+
+    /** List of tables */
+    const LIST_OF_TABLES = "lot";
+
+    /** Notes page */
+    const NOTES = "notes";
+
+    /** Preface page */
+    const PREFACE = "preface";
+
+    /** Table of contents */
+    const TABLE_OF_CONTENTS = "toc";
+
+    /** Page with possibly title, author, publisher, and other metadata */
+    const TITLE_PAGE = "titlepage";
+
+    /** First page of the book, ie. first page of the first chapter */
+    const TEXT = "text";
+
+       // ******************
+       // ePub3 constants
+       // ******************
+
+       // Document partitions
+       /** The publications cover(s), jacket information, etc. This is officially in ePub3, but works for ePub 2 as well */
+       const COVER = "cover";
+
+       /** Preliminary material to the content body, such as tables of contents, dedications, etc. */
+       const FRONTMATTER = "frontmatter";
+
+       /** The main (body) content of a document. */
+       const BODYMATTER = "bodymatter";
+
+       /** Ancillary material occurring after the document body, such as indices, appendices, etc. */
+       const BACKMATTER = "backmatter";
+
+
+       private $type = NULL;
+    private $title = NULL;
+    private $href = NULL;
+
+    /**
+     * Class constructor.
+        *
+        * @param string $type
+        * @param string $title
+        * @param string $href
+        */
+    function __construct($type, $title, $href) {
+        $this->setType($type);
+        $this->setTitle($title);
+        $this->setHref($href);
+    }
+
+    /**
+     * Class destructor
+     *
+     * @return void
+     */
+    function __destruct() {
+        unset ($this->type, $this->title, $this->href);
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $type
+     */
+    function setType($type) {
+        $this->type = is_string($type) ? trim($type) : NULL;
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $title
+     */
+    function setTitle($title) {
+        $this->title = is_string($title) ? trim($title) : NULL;
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param string $href
+     */
+    function setHref($href) {
+        $this->href = is_string($href) ? trim($href) : NULL;
+    }
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @return string
+     */
+    function finalize() {
+        return "\t\t<reference type=\"" . $this->type . "\" title=\"" . $this->title . "\" href=\"" . $this->href . "\" />\n";
+    }
+}
+
+/**
+ * Common Marc codes.
+ * Ref: http://www.loc.gov/marc/relators/
+ */
+class MarcCode {
+    const _VERSION = 3.00;
+
+    /**
+     * Adapter
+     *
+     * Use for a person who
+     * 1) reworks a musical composition, usually for a different medium, or
+     * 2) rewrites novels or stories for motion pictures or other audiovisual medium.
+     */
+    const ADAPTER = "adp";
+
+    /**
+     * Annotator
+     *
+     * Use for a person who writes manuscript annotations on a printed item.
+     */
+    const ANNOTATOR = "ann";
+
+    /**
+     * Arranger
+     *
+     * Use for a person who transcribes a musical composition, usually for a different
+     *  medium from that of the original; in an arrangement the musical substance remains
+     *  essentially unchanged.
+     */
+    const ARRANGER = "arr";
+
+    /**
+     * Artist
+     *
+     * Use for a person (e.g., a painter) who conceives, and perhaps also implements,
+     *  an original graphic design or work of art, if specific codes (e.g., [egr],
+     *  [etr]) are not desired. For book illustrators, prefer Illustrator [ill].
+     */
+    const ARTIST = "art";
+
+    /**
+     * Associated name
+     *
+     * Use as a general relator for a name associated with or found in an item or
+     *  collection, or which cannot be determined to be that of a Former owner [fmo]
+     *  or other designated relator indicative of provenance.
+     */
+    const ASSOCIATED_NAME = "asn";
+
+    /**
+     * Author
+     *
+     * Use for a person or corporate body chiefly responsible for the intellectual
+     *  or artistic content of a work. This term may also be used when more than one
+     *  person or body bears such responsibility.
+     */
+    const AUTHOR = "aut";
+
+    /**
+     * Author in quotations or text extracts
+     *
+     * Use for a person whose work is largely quoted or extracted in a works to which
+     *  he or she did not contribute directly. Such quotations are found particularly
+     *  in exhibition catalogs, collections of photographs, etc.
+     */
+    const AUTHOR_IN_QUOTES = "aqt";
+
+    /**
+     * Author of afterword, colophon, etc.
+     *
+     * Use for a person or corporate body responsible for an afterword, postface,
+     *  colophon, etc. but who is not the chief author of a work.
+     */
+    const AUTHOR_OF_AFTERWORD = "aft";
+
+    /**
+     * Author of introduction, etc.
+     *
+     * Use for a person or corporate body responsible for an introduction, preface,
+     *  foreword, or other critical matter, but who is not the chief author.
+     */
+    const AUTHOR_OF_INTRO = "aui";
+
+    /**
+     * Bibliographic antecedent
+     *
+     * Use for the author responsible for a work upon which the work represented by
+     *  the catalog record is based. This can be appropriate for adaptations, sequels,
+     *  continuations, indexes, etc.
+     */
+    const BIB_ANTECEDENT = "ant";
+
+    /**
+     * Book producer
+     *
+     * Use for the person or firm responsible for the production of books and other
+     *  print media, if specific codes (e.g., [bkd], [egr], [tyd], [prt]) are not desired.
+     */
+    const BOOK_PRODUCER = "bkp";
+
+    /**
+     * Collaborator
+     *
+     * Use for a person or corporate body that takes a limited part in the elaboration
+     *  of a work of another author or that brings complements (e.g., appendices, notes)
+     *  to the work of another author.
+     */
+    const COLABORATOR = "clb";
+
+    /**
+     * Commentator
+     *
+     * Use for a person who provides interpretation, analysis, or a discussion of the
+     *  subject matter on a recording, motion picture, or other audiovisual medium.
+     *  Compiler [com] Use for a person who produces a work or publication by selecting
+     *  and putting together material from the works of various persons or bodies.
+     */
+    const COMMENTATOR = "cmm";
+
+    /**
+     * Designer
+     *
+     * Use for a person or organization responsible for design if specific codes (e.g.,
+     *  [bkd], [tyd]) are not desired.
+     */
+    const DESIGNER = "dsr";
+
+    /**
+     * Editor
+     *
+     * Use for a person who prepares for publication a work not primarily his/her own,
+     *  such as by elucidating text, adding introductory or other critical matter, or
+     *  technically directing an editorial staff.
+     */
+    const EDITORT = "edt";
+
+    /**
+     * Illustrator
+     *
+     * Use for the person who conceives, and perhaps also implements, a design or
+     *  illustration, usually to accompany a written text.
+     */
+    const ILLUSTRATOR = "ill";
+
+    /**
+     * Lyricist
+     *
+     * Use for the writer of the text of a song.
+     */
+    const LYRICIST = "lyr";
+
+    /**
+     * Metadata contact
+     *
+     * Use for the person or organization primarily responsible for compiling and
+     *  maintaining the original description of a metadata set (e.g., geospatial
+     *  metadata set).
+     */
+    const METADATA_CONTACT = "mdc";
+
+    /**
+     * Musician
+     *
+     * Use for the person who performs music or contributes to the musical content
+     *  of a work when it is not possible or desirable to identify the function more
+     *  precisely.
+     */
+    const MUSICIAN = "mus";
+
+    /**
+     * Narrator
+     *
+     * Use for the speaker who relates the particulars of an act, occurrence, or
+     *  course of events.
+     */
+    const NARRATOR = "nrt";
+
+    /**
+     * Other
+     *
+     * Use for relator codes from other lists which have no equivalent in the MARC
+     *  list or for terms which have not been assigned a code.
+     */
+    const OTHER = "oth";
+
+    /**
+     * Photographer
+     *
+     * Use for the person or organization responsible for taking photographs, whether
+     *  they are used in their original form or as reproductions.
+     */
+    const PHOTOGRAPHER = "pht";
+
+    /**
+     * Printer
+     *
+     * Use for the person or organization who prints texts, whether from type or plates.
+     */
+    const PRINTER = "prt";
+
+    /**
+     * Redactor
+     *
+     * Use for a person who writes or develops the framework for an item without
+     *  being intellectually responsible for its content.
+     */
+    const REDACTOR = "red";
+
+    /**
+     * Reviewer
+     *
+     * Use for a person or corporate body responsible for the review of book, motion
+     *  picture, performance, etc.
+     */
+    const REVIEWER = "rev";
+
+    /**
+     * Sponsor
+     *
+     * Use for the person or agency that issued a contract, or under whose auspices
+     *  a work has been written, printed, published, etc.
+     */
+    const SPONSOR = "spn";
+
+    /**
+     * Thesis advisor
+     *
+     * Use for the person under whose supervision a degree candidate develops and
+     *  presents a thesis, memoir, or text of a dissertation.
+     */
+    const THESIS_ADVISOR = "ths";
+
+    /**
+     * Transcriber
+     *
+     * Use for a person who prepares a handwritten or typewritten copy from original
+     *  material, including from dictated or orally recorded material.
+     */
+    const TRANSCRIBER = "trc";
+
+    /**
+     * Translator
+     *
+     * Use for a person who renders a text from one language into another, or from
+     *  an older form of a language into the modern form.
+     */
+    const TRANSLATOR = "trl";
+}
+?>
diff --git a/inc/3rdparty/libraries/PHPePub/EPub.php b/inc/3rdparty/libraries/PHPePub/EPub.php
new file mode 100644 (file)
index 0000000..d9b990b
--- /dev/null
@@ -0,0 +1,2438 @@
+<?php
+/**
+ * Create an ePub compatible book file.
+ *
+ * Please note, once finalized a book can no longer have chapters of data added or changed.
+ *
+ * License: GNU LGPL, Attribution required for commercial implementations, requested for everything else.
+ *
+ * Thanks to: Adam Schmalhofer and Kirstyn Fox for invaluable input and for "nudging" me in the right direction :)
+ *
+ * @author A. Grandt <php@grandt.com>
+ * @copyright 2009-2014 A. Grandt
+ * @license GNU LGPL 2.1
+ * @version 3.20
+ * @link http://www.phpclasses.org/package/6115
+ * @link https://github.com/Grandt/PHPePub
+ * @uses Zip.php version 1.50; http://www.phpclasses.org/browse/package/6110.html or https://github.com/Grandt/PHPZip
+ */
+class EPub {
+    const VERSION = 3.20;
+    const REQ_ZIP_VERSION = 1.60;
+
+    const IDENTIFIER_UUID = 'UUID';
+    const IDENTIFIER_URI = 'URI';
+    const IDENTIFIER_ISBN = 'ISBN';
+
+    /** Ignore all external references, and do not process the file for these */
+    const EXTERNAL_REF_IGNORE = 0;
+    /** Process the file for external references and add them to the book */
+    const EXTERNAL_REF_ADD = 1;
+    /** Process the file for external references and add them to the book, but remove images, and img tags */
+    const EXTERNAL_REF_REMOVE_IMAGES = 2;
+    /** Process the file for external references and add them to the book, but replace images, and img tags with [image] */
+    const EXTERNAL_REF_REPLACE_IMAGES = 3;
+
+    const DIRECTION_LEFT_TO_RIGHT = "ltr";
+    const DIRECTION_RIGHT_TO_LEFT = "rtl";
+
+       const BOOK_VERSION_EPUB2 = "2.0";
+    const BOOK_VERSION_EPUB3 = "3.0";
+
+    private $bookVersion = EPub::BOOK_VERSION_EPUB2;
+
+    private $debugInside = FALSE;
+
+       public $maxImageWidth = 768;
+    public $maxImageHeight = 1024;
+
+    public $splitDefaultSize = 250000;
+       /** Gifs can crash some early ADE based readers, and are disabled by default.
+        * getImage will convert these if it can, unless this is set to TRUE.
+        */
+    public $isGifImagesEnabled = FALSE;
+       public $isReferencesAddedToToc = TRUE;
+
+    private $zip;
+
+    private $title = "";
+    private $language = "en";
+    private $identifier = "";
+    private $identifierType = "";
+    private $description = "";
+    private $author = "";
+    private $authorSortKey = "";
+    private $publisherName = "";
+    private $publisherURL = "";
+    private $date = 0;
+    private $rights = "";
+    private $coverage = "";
+    private $relation = "";
+    private $sourceURL = "";
+
+    private $chapterCount = 0;
+    private $opf = NULL;
+    private $ncx = NULL;
+    private $isFinalized = FALSE;
+    private $isCoverImageSet = FALSE;
+    private $buildTOC = FALSE;
+       private $tocTitle = NULL;
+       private $tocFileName = NULL;
+       private $tocCSSClass = NULL;
+       private $tocAddReferences = FALSE;
+       private $tocCssFileName = NULL;
+
+    private $fileList = array();
+    private $writingDirection = EPub::DIRECTION_LEFT_TO_RIGHT;
+    private $languageCode = "en";
+
+    /**
+     * Used for building the TOC.
+     * If this list is overwritten it MUST contain at least "text" as an element.
+     */
+    public $referencesOrder = NULL;
+
+    private $dateformat = 'Y-m-d\TH:i:s.000000P'; // ISO 8601 long
+    private $dateformatShort = 'Y-m-d'; // short date format to placate ePubChecker.
+    private $headerDateFormat = "D, d M Y H:i:s T";
+
+    protected $isCurlInstalled;
+    protected $isGdInstalled;
+    protected $isExifInstalled;
+    protected $isFileGetContentsInstalled;
+    protected $isFileGetContentsExtInstalled;
+
+    private $bookRoot = "OEBPS/";
+    private $docRoot = NULL;
+    private $EPubMark = TRUE;
+    private $generator = "";
+
+    private $log = NULL;
+    public $isLogging = TRUE;
+
+    public $encodeHTML = FALSE;
+
+    private $mimetypes = array(
+        "js" => "application/x-javascript", "swf" => "application/x-shockwave-flash", "xht" => "application/xhtml+xml", "xhtml" => "application/xhtml+xml", "zip" => "application/zip",
+        "aif" => "audio/x-aiff", "aifc" => "audio/x-aiff", "aiff" => "audio/x-aiff", "au" => "audio/basic", "kar" => "audio/midi", "m3u" => "audio/x-mpegurl", "mid" => "audio/midi", "midi" => "audio/midi", "mp2" => "audio/mpeg", "mp3" => "audio/mpeg", "mpga" => "audio/mpeg", "oga" => "audio/ogg", "ogg" => "audio/ogg", "ra" => "audio/x-realaudio", "ram" => "audio/x-pn-realaudio", "rm" => "audio/x-pn-realaudio", "rpm" => "audio/x-pn-realaudio-plugin", "snd" => "audio/basic", "wav" => "audio/x-wav",
+        "bmp" => "image/bmp", "djv" => "image/vnd.djvu", "djvu" => "image/vnd.djvu", "gif" => "image/gif", "ief" => "image/ief", "jpe" => "image/jpeg", "jpeg" => "image/jpeg", "jpg" => "image/jpeg", "pbm" => "image/x-portable-bitmap", "pgm" => "image/x-portable-graymap", "png" => "image/png", "pnm" => "image/x-portable-anymap", "ppm" => "image/x-portable-pixmap", "ras" => "image/x-cmu-raster", "rgb" => "image/x-rgb", "tif" => "image/tif", "tiff" => "image/tiff", "wbmp" => "image/vnd.wap.wbmp", "xbm" => "image/x-xbitmap", "xpm" => "image/x-xpixmap", "xwd" => "image/x-windowdump",
+        "asc" => "text/plain", "css" => "text/css", "etx" => "text/x-setext", "htm" => "text/html", "html" => "text/html", "rtf" => "text/rtf", "rtx" => "text/richtext", "sgm" => "text/sgml", "sgml" => "text/sgml", "tsv" => "text/tab-seperated-values", "txt" => "text/plain", "wml" => "text/vnd.wap.wml", "wmls" => "text/vnd.wap.wmlscript", "xml" => "text/xml", "xsl" => "text/xml",
+        "avi" => "video/x-msvideo", "mov" => "video/quicktime", "movie" => "video/x-sgi-movie", "mp4" => "video/mp4", "mpe" => "video/mpeg", "mpeg" => "video/mpeg", "mpg" => "video/mpeg", "mxu" => "video/vnd.mpegurl", "ogv" => "video/ogg", "qt" => "video/quicktime", "webm" => "video/webm");
+
+    // These are the ONLY allowed types in that these are the ones ANY reader must support, any other MUST have the fallback attribute pointing to one of these.
+    private $coreMediaTypes = array("image/gif", "image/jpeg", "image/png", "image/svg+xml", "application/xhtml+xml", "application/x-dtbook+xml", "application/xml", "application/x-dtbncx+xml", "text/css", "text/x-oeb1-css", "text/x-oeb1-document");
+
+    private $opsContentTypes = array("application/xhtml+xml", "application/x-dtbook+xml", "application/xml", "application/x-dtbncx+xml", "text/x-oeb1-document");
+
+    private $forbiddenCharacters = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", "%");
+
+       private $htmlContentHeader = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"\n    \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n<title></title>\n</head>\n<body>\n";
+       private $htmlContentFooter = "</body>\n</html>\n";
+
+    /**
+     * Class constructor.
+     *
+     * @return void
+     */
+    function __construct($bookVersion = EPub::BOOK_VERSION_EPUB2, $debugInside = FALSE, $languageCode = "en", $writingDirection = EPub::DIRECTION_LEFT_TO_RIGHT) {
+        include_once("Zip.php");
+               include_once("Logger.php");
+
+        if (!$debugInside) {
+            error_reporting(E_ERROR | E_PARSE);
+        }
+
+               $this->bookVersion = $bookVersion;
+               $this->writingDirection = $writingDirection;
+               $this->languageCode = $languageCode;
+
+        $this->log = new Logger("EPub", $this->isLogging);
+
+        /* Prepare Logging. Just in case it's used. later */
+        if ($this->isLogging) {
+            $this->log->logLine("EPub class version....: " . self::VERSION);
+            $this->log->logLine("EPub req. Zip version.: " . self::REQ_ZIP_VERSION);
+            $this->log->logLine("Zip version...........: " . Zip::VERSION);
+            $this->log->dumpInstalledModules();
+        }
+
+        if (!defined("Zip::VERSION") || Zip::VERSION < self::REQ_ZIP_VERSION) {
+            die("<p>EPub version " . self::VERSION . " requires Zip.php at version " . self::REQ_ZIP_VERSION . " or higher.<br />You can obtain the latest version from <a href=\"http://www.phpclasses.org/browse/package/6110.html\">http://www.phpclasses.org/browse/package/6110.html</a>.</p>");
+        }
+
+        include_once("EPubChapterSplitter.php");
+        include_once("EPub.HtmlEntities.php");
+        include_once("EPub.NCX.php");
+        include_once("EPub.OPF.php");
+
+        $this->initialize();
+    }
+
+    /**
+     * Class destructor
+     *
+     * @return void
+     * @TODO make sure elements in the destructor match the current class elements
+     */
+    function __destruct() {
+               unset($this->bookVersion, $this->maxImageWidth, $this->maxImageHeight);
+               unset($this->splitDefaultSize, $this->isGifImagesEnabled, $this->isReferencesAddedToToc);
+               unset($this->zip, $this->title, $this->language, $this->identifier, $this->identifierType);
+               unset($this->description, $this->author, $this->authorSortKey, $this->publisherName);
+               unset($this->publisherURL, $this->date, $this->rights, $this->coverage, $this->relation);
+               unset($this->sourceURL, $this->chapterCount, $this->opf, $this->ncx, $this->isFinalized);
+               unset($this->isCoverImageSet, $this->fileList, $this->writingDirection, $this->languageCode);
+               unset($this->referencesOrder, $this->dateformat, $this->dateformatShort, $this->headerDateFormat);
+               unset($this->isCurlInstalled, $this->isGdInstalled, $this->isExifInstalled);
+               unset($this->isFileGetContentsInstalled, $this->isFileGetContentsExtInstalled, $this->bookRoot);
+               unset($this->docRoot, $this->EPubMark, $this->generator, $this->log, $this->isLogging);
+               unset($this->encodeHTML, $this->mimetypes, $this->coreMediaTypes, $this->opsContentTypes);
+               unset($this->forbiddenCharacters, $this->htmlContentHeader, $this->htmlContentFooter);
+               unset($this->buildTOC, $this->tocTitle, $this->tocCSSClass, $this->tocAddReferences);
+               unset($this->tocFileName, $this->tocCssFileName);
+    }
+
+       /**
+        * initialize defaults.
+        */
+    private function initialize() {
+        $this->referencesOrder = array(
+                       Reference::COVER => "Cover Page",
+                       Reference::TITLE_PAGE => "Title Page",
+                       Reference::ACKNOWLEDGEMENTS => "Acknowledgements",
+                       Reference::BIBLIOGRAPHY => "Bibliography",
+                       Reference::COLOPHON => "Colophon",
+                       Reference::COPYRIGHT_PAGE => "Copyright",
+                       Reference::DEDICATION => "Dedication",
+                       Reference::EPIGRAPH => "Epigraph",
+                       Reference::FOREWORD => "Foreword",
+                       Reference::TABLE_OF_CONTENTS => "Table of Contents",
+                       Reference::NOTES => "Notes",
+                       Reference::PREFACE => "Preface",
+                       Reference::TEXT => "First Page",
+                       Reference::LIST_OF_ILLUSTRATIONS => "List of Illustrations",
+                       Reference::LIST_OF_TABLES => "List of Tables",
+                       Reference::GLOSSARY => "Glossary",
+                       Reference::INDEX => "Index");
+
+        $this->docRoot = filter_input(INPUT_SERVER, "DOCUMENT_ROOT") . "/";
+
+        $this->isCurlInstalled = extension_loaded('curl') && function_exists('curl_version');
+        $this->isGdInstalled = extension_loaded('gd') && function_exists('gd_info');
+        $this->isExifInstalled = extension_loaded('exif') && function_exists('exif_imagetype');
+        $this->isFileGetContentsInstalled = function_exists('file_get_contents');
+        $this->isFileGetContentsExtInstalled = $this->isFileGetContentsInstalled && ini_get('allow_url_fopen');
+
+        $this->zip = new Zip();
+        $this->zip->setExtraField(FALSE);
+        $this->zip->addFile("application/epub+zip", "mimetype");
+        $this->zip->setExtraField(TRUE);
+        $this->zip->addDirectory("META-INF");
+
+        $this->content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<container version=\"1.0\" xmlns=\"urn:oasis:names:tc:opendocument:xmlns:container\">\n\t<rootfiles>\n\t\t<rootfile full-path=\"" . $this->bookRoot . "book.opf\" media-type=\"application/oebps-package+xml\" />\n\t</rootfiles>\n</container>\n";
+
+               if (!$this->isEPubVersion2()) {
+                       $this->htmlContentHeader = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
+                       . "<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\">\n"
+                       . "<head>"
+                       . "<meta http-equiv=\"Default-Style\" content=\"text/html; charset=utf-8\" />\n"
+                       . "<title></title>\n"
+                       . "</head>\n"
+                       . "<body>\n";
+               }
+
+        $this->zip->addFile($this->content, "META-INF/container.xml", 0, NULL, FALSE);
+        $this->content = NULL;
+        $this->ncx = new Ncx(NULL, NULL, NULL, $this->languageCode, $this->writingDirection);
+        $this->opf = new Opf();
+               $this->ncx->setVersion($this->bookVersion);
+               $this->opf->setVersion($this->bookVersion);
+        $this->opf->addItem("ncx", "book.ncx", Ncx::MIMETYPE);
+        $this->chapterCount = 0;
+    }
+
+    /**
+     * Add dynamically generated data as a file to the book.
+        *
+     * @param string $fileName Filename to use for the file, must be unique for the book.
+     * @param string $fileId Unique identifier for the file.
+     * @param string $fileData File data
+     * @param string $mimetype file mime type
+     * @return bool $success
+     */
+    function addFile($fileName, $fileId,  $fileData, $mimetype) {
+        if ($this->isFinalized || array_key_exists($fileName, $this->fileList)) {
+            return FALSE;
+        }
+
+        $fileName = $this->normalizeFileName($fileName);
+
+        $compress = (strpos($mimetype, "image/") !== 0);
+
+               $this->zip->addFile($fileData, $this->bookRoot.$fileName, 0, NULL, $compress);
+        $this->fileList[$fileName] = $fileName;
+        $this->opf->addItem($fileId, $fileName, $mimetype);
+        return TRUE;
+    }
+
+    /**
+     * Add a large file directly from the filestystem to the book.
+        *
+     * @param string $fileName Filename to use for the file, must be unique for the book.
+     * @param string $fileId Unique identifier for the file.
+     * @param string $filePath File path
+     * @param string $mimetype file mime type
+     * @return bool $success
+     */
+    function addLargeFile($fileName, $fileId,  $filePath, $mimetype) {
+        if ($this->isFinalized || array_key_exists($fileName, $this->fileList)) {
+            return FALSE;
+        }
+        $fileName = $this->normalizeFileName($fileName);
+
+        if ($this->zip->addLargeFile($filePath, $this->bookRoot.$fileName)) {
+            $this->fileList[$fileName] = $fileName;
+            $this->opf->addItem($fileId, $fileName, $mimetype);
+            return TRUE;
+        }
+        return FALSE;
+    }
+
+    /**
+     * Add a CSS file to the book.
+     *
+     * @param string $fileName Filename to use for the CSS file, must be unique for the book.
+     * @param string $fileId Unique identifier for the file.
+     * @param string $fileData CSS data
+     * @param int    $externalReferences How to handle external references, EPub::EXTERNAL_REF_IGNORE, EPub::EXTERNAL_REF_ADD or EPub::EXTERNAL_REF_REMOVE_IMAGES? See documentation for <code>processCSSExternalReferences</code> for explanation. Default is EPub::EXTERNAL_REF_IGNORE.
+     * @param string $baseDir Default is "", meaning it is pointing to the document root. NOT used if $externalReferences is set to EPub::EXTERNAL_REF_IGNORE.
+     *
+     * @return bool $success
+     */
+    function addCSSFile($fileName, $fileId,  $fileData, $externalReferences = EPub::EXTERNAL_REF_IGNORE, $baseDir = "") {
+        if ($this->isFinalized || array_key_exists($fileName, $this->fileList)) {
+            return FALSE;
+        }
+        $fileName = Zip::getRelativePath($fileName);
+        $fileName = preg_replace('#^[/\.]+#i', "", $fileName);
+
+        if ($externalReferences !== EPub::EXTERNAL_REF_IGNORE) {
+            $cssDir = pathinfo($fileName);
+            $cssDir = preg_replace('#^[/\.]+#i', "", $cssDir["dirname"] . "/");
+            if (!empty($cssDir)) {
+                $cssDir = preg_replace('#[^/]+/#i', "../", $cssDir);
+            }
+
+            $this->processCSSExternalReferences($fileData, $externalReferences, $baseDir, $cssDir);
+        }
+
+        $this->addFile($fileName, "css_" . $fileId, $fileData, "text/css");
+
+        return TRUE;
+    }
+
+    /**
+     * Add a chapter to the book, as a chapter should not exceed 250kB, you can parse an array with multiple parts as $chapterData.
+     * These will still only show up as a single chapter in the book TOC.
+     *
+     * @param string $chapterName Name of the chapter, will be use din the TOC
+     * @param string $fileName Filename to use for the chapter, must be unique for the book.
+     * @param string $chapter Chapter text in XHTML or array $chapterData valid XHTML data for the chapter. File should NOT exceed 250kB.
+     * @param bool   $autoSplit Should the chapter be split if it exceeds the default split size? Default=FALSE, only used if $chapterData is a string.
+     * @param int    $externalReferences How to handle external references, EPub::EXTERNAL_REF_IGNORE, EPub::EXTERNAL_REF_ADD or EPub::EXTERNAL_REF_REMOVE_IMAGES? See documentation for <code>processChapterExternalReferences</code> for explanation. Default is EPub::EXTERNAL_REF_IGNORE.
+     * @param string $baseDir Default is "", meaning it is pointing to the document root. NOT used if $externalReferences is set to EPub::EXTERNAL_REF_IGNORE.
+     * @return mixed $success FALSE if the addition failed, else the new NavPoint.
+     */
+    function addChapter($chapterName, $fileName, $chapterData = NULL, $autoSplit = FALSE, $externalReferences = EPub::EXTERNAL_REF_IGNORE, $baseDir = "") {
+        if ($this->isFinalized) {
+            return FALSE;
+        }
+        $fileName = Zip::getRelativePath($fileName);
+        $fileName = preg_replace('#^[/\.]+#i', "", $fileName);
+        $fileName = $this->sanitizeFileName($fileName);
+
+        $chapter = $chapterData;
+        if ($autoSplit && is_string($chapterData) && mb_strlen($chapterData) > $this->splitDefaultSize) {
+            $splitter = new EPubChapterSplitter();
+
+            $chapterArray = $splitter->splitChapter($chapterData);
+            if (count($chapterArray) > 1) {
+                $chapter = $chapterArray;
+            }
+        }
+
+        if (!empty($chapter) && is_string($chapter)) {
+            if ($externalReferences !== EPub::EXTERNAL_REF_IGNORE) {
+                $htmlDirInfo = pathinfo($fileName);
+                $htmlDir = preg_replace('#^[/\.]+#i', "", $htmlDirInfo["dirname"] . "/");
+                $this->processChapterExternalReferences($chapter, $externalReferences, $baseDir, $htmlDir);
+            }
+
+            if ($this->encodeHTML === TRUE) {
+                $chapter = $this->encodeHtml($chapter);
+            }
+
+            $this->chapterCount++;
+            $this->addFile($fileName, "chapter" . $this->chapterCount, $chapter, "application/xhtml+xml");
+            $this->opf->addItemRef("chapter" . $this->chapterCount);
+
+            $navPoint = new NavPoint($this->decodeHtmlEntities($chapterName), $fileName, "chapter" . $this->chapterCount);
+            $this->ncx->addNavPoint($navPoint);
+            $this->ncx->chapterList[$chapterName] = $navPoint;
+        } else if (is_array($chapter)) {
+            $fileNameParts = pathinfo($fileName);
+            $extension = $fileNameParts['extension'];
+            $name = $fileNameParts['filename'];
+
+            $partCount = 0;
+            $this->chapterCount++;
+
+            $oneChapter = each($chapter);
+            while ($oneChapter) {
+                list($k, $v) = $oneChapter;
+                if ($this->encodeHTML === TRUE) {
+                    $v = $this->encodeHtml($v);
+                }
+
+                if ($externalReferences !== EPub::EXTERNAL_REF_IGNORE) {
+                    $this->processChapterExternalReferences($v, $externalReferences, $baseDir);
+                }
+                $partCount++;
+                               $partName = $name . "_" . $partCount;
+                $this->addFile($partName . "." . $extension, $partName, $v, "application/xhtml+xml");
+                $this->opf->addItemRef($partName);
+
+                $oneChapter = each($chapter);
+            }
+                       $partName = $name . "_1." . $extension;
+            $navPoint = new NavPoint($this->decodeHtmlEntities($chapterName), $partName, $partName);
+            $this->ncx->addNavPoint($navPoint);
+
+            $this->ncx->chapterList[$chapterName] = $navPoint;
+        } else if (!isset($chapterData) && strpos($fileName, "#") > 0) {
+            $this->chapterCount++;
+            //$this->opf->addItemRef("chapter" . $this->chapterCount);
+
+            $navPoint = new NavPoint($this->decodeHtmlEntities($chapterName), $fileName, "chapter" . $this->chapterCount);
+            $this->ncx->addNavPoint($navPoint);
+            $this->ncx->chapterList[$chapterName] = $navPoint;
+               } else if (!isset($chapterData) && $fileName=="TOC.xhtml") {
+            $this->chapterCount++;
+            $this->opf->addItemRef("toc");
+
+            $navPoint = new NavPoint($this->decodeHtmlEntities($chapterName), $fileName, "chapter" . $this->chapterCount);
+            $this->ncx->addNavPoint($navPoint);
+            $this->ncx->chapterList[$chapterName] = $navPoint;
+               }
+        return $navPoint;
+    }
+
+       /**
+        * Add one chapter level.
+        *
+        * Subsequent chapters will be added to this level.
+        *
+        * @param string $navTitle
+        * @param string $navId
+        * @param string $navClass
+        * @param int    $isNavHidden
+        * @param string $writingDirection
+        * @return NavPoint The new NavPoint for that level.
+        */
+       function subLevel($navTitle = NULL, $navId = NULL, $navClass = NULL, $isNavHidden = FALSE, $writingDirection = NULL) {
+               return $this->ncx->subLevel($this->decodeHtmlEntities($navTitle), $navId, $navClass, $isNavHidden, $writingDirection);
+       }
+
+       /**
+        * Step back one chapter level.
+        *
+        * Subsequent chapters will be added to this chapters parent level.
+        */
+       function backLevel() {
+               $this->ncx->backLevel();
+       }
+
+       /**
+        * Step back to the root level.
+        *
+        * Subsequent chapters will be added to the rooot NavMap.
+        */
+       function rootLevel() {
+               $this->ncx->rootLevel();
+       }
+
+       /**
+        * Step back to the given level.
+        * Useful for returning to a previous level from deep within the structure.
+        * Values below 2 will have the same effect as rootLevel()
+        *
+        * @param int $newLevel
+        */
+       function setCurrentLevel($newLevel) {
+               $this->ncx->setCurrentLevel($newLevel);
+       }
+
+       /**
+        * Get current level count.
+        * The indentation of the current structure point.
+        *
+        * @return current level count;
+        */
+       function getCurrentLevel() {
+               return $this->ncx->getCurrentLevel();
+       }
+
+    /**
+     * Wrap ChapterContent with Head and Footer
+     *
+     * @param $content
+     * @return string $content
+     */
+    private function wrapChapter($content) {
+        return $this->htmlContentHeader . "\n" . $content . "\n" . $this->htmlContentFooter;
+    }
+
+       /**
+     * Reference pages is usually one or two pages for items such as Table of Contents, reference lists, Author notes or Acknowledgements.
+     * These do not show up in the regular navigation list.
+     *
+     * As they are supposed to be short.
+     *
+     * @param string $pageName Name of the chapter, will be use din the TOC
+     * @param string $fileName Filename to use for the chapter, must be unique for the book.
+     * @param string $pageData Page content in XHTML. File should NOT exceed 250kB.
+     * @param string $reference Reference key
+     * @param int    $externalReferences How to handle external references. See documentation for <code>processChapterExternalReferences</code> for explanation. Default is EPub::EXTERNAL_REF_IGNORE.
+     * @param string $baseDir Default is "", meaning it is pointing to the document root. NOT used if $externalReferences is set to EPub::EXTERNAL_REF_IGNORE.
+     * @return bool $success
+     */
+    function addReferencePage($pageName, $fileName, $pageData, $reference, $externalReferences = EPub::EXTERNAL_REF_IGNORE, $baseDir = "") {
+        if ($this->isFinalized) {
+            return FALSE;
+        }
+        $fileName = Zip::getRelativePath($fileName);
+        $fileName = preg_replace('#^[/\.]+#i', "", $fileName);
+
+
+        if (!empty($pageData) && is_string($pageData)) {
+                       if ($this->encodeHTML === TRUE) {
+                               $pageData = $this->encodeHtml($pageData);
+                       }
+                       
+            $this->wrapChapter($pageData);
+
+            if ($externalReferences !== EPub::EXTERNAL_REF_IGNORE) {
+                $htmlDirInfo = pathinfo($fileName);
+                $htmlDir = preg_replace('#^[/\.]+#i', "", $htmlDirInfo["dirname"] . "/");
+                $this->processChapterExternalReferences($pageData, $externalReferences, $baseDir, $htmlDir);
+            }
+
+            $this->addFile($fileName, "ref_" . $reference, $pageData, "application/xhtml+xml");
+                       
+                       if ($reference !== Reference::TABLE_OF_CONTENTS || !isset($this->ncx->referencesList[$reference])) {
+                               $this->opf->addItemRef("ref_" . $reference, FALSE);
+                               $this->opf->addReference($reference, $pageName, $fileName);
+
+                               $this->ncx->referencesList[$reference] = $fileName;
+                               $this->ncx->referencesName[$reference] = $pageName;
+                       }
+                       return TRUE;
+               }
+               return TRUE;
+    }
+
+       /**
+     * Add custom metadata to the book.
+        *
+        * It is up to the builder to make sure there are no collisions. Metadata are just key value pairs.
+     *
+     * @param string $name
+     * @param string $content
+     */
+       function addCustomMetadata($name, $content) {
+               $this->opf->addMeta($name, $content);
+       }
+
+    /**
+        * Add DublinCore metadata to the book
+        *
+        * Use the DublinCore constants included in EPub, ie DublinCore::DATE
+        *
+        * @param string $dublinCore name
+        * @param string $value
+        */
+    function addDublinCoreMetadata($dublinCoreConstant, $value) {
+        if ($this->isFinalized) {
+            return;
+        }
+
+               $this->opf->addDCMeta($dublinCoreConstant, $this->decodeHtmlEntities($value));
+    }
+
+    /**
+     * Add a cover image to the book.
+     * If the $imageData is not set, the function assumes the $fileName is the path to the image file.
+     *
+     * The styling and structure of the generated XHTML is heavily inspired by the XHTML generated by Calibre.
+     *
+     * @param string $fileName Filename to use for the image, must be unique for the book.
+     * @param string $imageData Binary image data
+     * @param string $mimetype Image mimetype, such as "image/jpeg" or "image/png".
+     * @return bool $success
+     */
+    function setCoverImage($fileName, $imageData = NULL, $mimetype = NULL,$bookTitle) {
+        if ($this->isFinalized || $this->isCoverImageSet || array_key_exists("CoverPage.html", $this->fileList)) {
+            return FALSE;
+        }
+
+        if ($imageData == NULL) {
+            // assume $fileName is the valid file path.
+            if (!file_exists($fileName)) {
+                // Attempt to locate the file using the doc root.
+                $rp = realpath($this->docRoot . "/" . $fileName);
+
+               if ($rp !== FALSE) {
+                    // only assign the docroot path if it actually exists there.
+                    $fileName = $rp;
+                }
+            }
+            $image = $this->getImage($fileName);
+                       $imageData = $image['image'];
+            $mimetype = $image['mime'];
+            $fileName = preg_replace("#\.[^\.]+$#", "." . $image['ext'], $fileName);
+        }
+
+
+        $path = pathinfo($fileName);
+        $imgPath = "images/" . $path["basename"];
+
+        if (empty($mimetype) && file_exists($fileName)) {
+            list($width, $height, $type, $attr) = getimagesize($fileName);
+            $mimetype = image_type_to_mime_type($type);
+        }
+        if (empty($mimetype)) {
+            $ext = strtolower($path['extension']);
+            if ($ext == "jpg") {
+                $ext = "jpeg";
+            }
+            $mimetype = "image/" . $ext;
+        }
+
+               $coverPage = "";
+
+               if ($this->isEPubVersion2()) {
+                       $coverPage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
+                               . "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"\n"
+                               . "  \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n"
+                               . "<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\" xml:lang=\"en\">\n"
+                               . "\t<head>\n"
+                               . "\t\t<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/>\n"
+                               . "\t\t<title>Cover Image</title>\n"
+                               . "\t\t<link type=\"text/css\" rel=\"stylesheet\" href=\"Styles/CoverPage.css\" />\n"
+                               . "\t</head>\n"
+                               . "\t<body>\n"
+                . "\t" . $bookTitle . "\n"
+                               . "\t\t<div>\n"
+                               . "\t\t\t<img src=\"" . $imgPath . "\" alt=\"Cover image\" style=\"height: 100%\"/>\n"
+                               . "\t\t</div>\n"
+                               . "\t</body>\n"
+                               . "</html>\n";
+               } else {
+                   $coverPage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
+                               . "<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\">\n"
+                               . "<head>"
+                               . "\t<meta http-equiv=\"Default-Style\" content=\"text/html; charset=utf-8\" />\n"
+                               . "\t\t<title>Cover Image</title>\n"
+                               . "\t\t<link type=\"text/css\" rel=\"stylesheet\" href=\"Styles/CoverPage.css\" />\n"
+                               . "\t</head>\n"
+                               . "\t<body>\n"
+                               . "\t\t<section epub:type=\"cover\">\n"
+                . "\t" . $bookTitle . "\n"
+                               . "\t\t\t<img src=\"" . $imgPath . "\" alt=\"Cover image\" style=\"height: 30%\"/>\n"
+                               . "\t\t</section>\n"
+                               . "\t</body>\n"
+                               . "</html>\n";
+               }
+               $coverPageCss = "@page, body, div, img {\n"
+                               . "\tpadding: 0pt;\n"
+                               . "\tmargin:0pt;\n"
+                               . "}\n\nbody {\n"
+                               . "\ttext-align: center;\n"
+                               . "}\n";
+
+               $this->addCSSFile("Styles/CoverPage.css", "CoverPageCss", $coverPageCss);
+        $this->addFile($imgPath, "CoverImage", $imageData, $mimetype);
+               $this->addReferencePage("CoverPage", "CoverPage.xhtml", $coverPage, "cover");
+        $this->isCoverImageSet = TRUE;
+        return TRUE;
+    }
+
+    /**
+     * Process external references from a HTML to the book. The chapter itself is not stored.
+     * the HTML is scanned for &lt;link..., &lt;style..., and &lt;img tags.
+     * Embedded CSS styles and links will also be processed.
+     * Script tags are not processed, as scripting should be avoided in e-books.
+     *
+     * EPub keeps track of added files, and duplicate files referenced across multiple
+     *  chapters, are only added once.
+     *
+     * If the $doc is a string, it is assumed to be the content of an HTML file,
+     *  else is it assumes to be a DOMDocument.
+     *
+     * Basedir is the root dir the HTML is supposed to "live" in, used to resolve
+     *  relative references such as <code>&lt;img src="../images/image.png"/&gt;</code>
+     *
+     * $externalReferences determines how the function will handle external references.
+     *
+     * @param mixed  &$doc (referenced)
+     * @param int    $externalReferences How to handle external references, EPub::EXTERNAL_REF_IGNORE, EPub::EXTERNAL_REF_ADD or EPub::EXTERNAL_REF_REMOVE_IMAGES? Default is EPub::EXTERNAL_REF_ADD.
+     * @param string $baseDir Default is "", meaning it is pointing to the document root.
+     * @param string $htmlDir The path to the parent HTML file's directory from the root of the archive.
+     *
+     * @return bool  FALSE if uncuccessful (book is finalized or $externalReferences == EXTERNAL_REF_IGNORE).
+     */
+    protected function processChapterExternalReferences(&$doc, $externalReferences = EPub::EXTERNAL_REF_ADD, $baseDir = "", $htmlDir = "") {
+        if ($this->isFinalized || $externalReferences === EPub::EXTERNAL_REF_IGNORE) {
+            return FALSE;
+        }
+
+        $backPath = preg_replace('#[^/]+/#i', "../", $htmlDir);
+        $isDocAString = is_string($doc);
+        $xmlDoc = NULL;
+
+        if ($isDocAString) {
+            $xmlDoc = new DOMDocument();
+            @$xmlDoc->loadHTML($doc);
+        } else {
+            $xmlDoc = $doc;
+        }
+
+        $this->processChapterStyles($xmlDoc, $externalReferences, $baseDir, $htmlDir);
+        $this->processChapterLinks($xmlDoc, $externalReferences, $baseDir, $htmlDir, $backPath);
+        $this->processChapterImages($xmlDoc, $externalReferences, $baseDir, $htmlDir, $backPath);
+        $this->processChapterSources($xmlDoc, $externalReferences, $baseDir, $htmlDir, $backPath);
+
+        if ($isDocAString) {
+            //$html = $xmlDoc->saveXML();
+
+            $htmlNode = $xmlDoc->getElementsByTagName("html");
+            $headNode = $xmlDoc->getElementsByTagName("head");
+            $bodyNode = $xmlDoc->getElementsByTagName("body");
+
+                       $htmlNS = "";
+                       for ($index = 0; $index < $htmlNode->item(0)->attributes->length; $index++) {
+                               $nodeName = $htmlNode->item(0)->attributes->item($index)->nodeName;
+                               $nodeValue = $htmlNode->item(0)->attributes->item($index)->nodeValue;
+
+                               if ($nodeName != "xmlns") {
+                                       $htmlNS .= " $nodeName=\"$nodeValue\"";
+                               }
+                       }
+
+            $xml = new DOMDocument('1.0', "utf-8");
+            $xml->lookupPrefix("http://www.w3.org/1999/xhtml");
+            $xml->preserveWhiteSpace = FALSE;
+            $xml->formatOutput = TRUE;
+
+            $xml2Doc = new DOMDocument('1.0', "utf-8");
+            $xml2Doc->lookupPrefix("http://www.w3.org/1999/xhtml");
+            $xml2Doc->loadXML("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"\n    \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\"$htmlNS>\n</html>\n");
+            $html = $xml2Doc->getElementsByTagName("html")->item(0);
+            $html->appendChild($xml2Doc->importNode($headNode->item(0), TRUE));
+            $html->appendChild($xml2Doc->importNode($bodyNode->item(0), TRUE));
+
+            // force pretty printing and correct formatting, should not be needed, but it is.
+            $xml->loadXML($xml2Doc->saveXML());
+            $doc = $xml->saveXML();
+
+                       if (!$this->isEPubVersion2()) {
+                               $doc = preg_replace('#^\s*<!DOCTYPE\ .+?>\s*#im', '', $doc);
+                       }
+        }
+               return TRUE;
+    }
+
+    /**
+     * Process images referenced from an CSS file to the book.
+     *
+     * $externalReferences determins how the function will handle external references.
+     *
+     * @param string &$cssFile (referenced)
+     * @param int    $externalReferences How to handle external references, EPub::EXTERNAL_REF_IGNORE, EPub::EXTERNAL_REF_ADD or EPub::EXTERNAL_REF_REMOVE_IMAGES? Default is EPub::EXTERNAL_REF_ADD.
+     * @param string $baseDir Default is "", meaning it is pointing to the document root.
+     * @param string $cssDir The of the CSS file's directory from the root of the archive.
+     *
+     * @return bool  FALSE if unsuccessful (book is finalized or $externalReferences == EXTERNAL_REF_IGNORE).
+     */
+    protected function processCSSExternalReferences(&$cssFile, $externalReferences = EPub::EXTERNAL_REF_ADD, $baseDir = "", $cssDir = "") {
+        if ($this->isFinalized || $externalReferences === EPub::EXTERNAL_REF_IGNORE) {
+            return FALSE;
+        }
+
+        $backPath = preg_replace('#[^/]+/#i', "../", $cssDir);
+        $imgs = null;
+        preg_match_all('#url\s*\([\'\"\s]*(.+?)[\'\"\s]*\)#im', $cssFile, $imgs, PREG_SET_ORDER);
+
+        $itemCount = count($imgs);
+        for ($idx = 0; $idx < $itemCount; $idx++) {
+            $img = $imgs[$idx];
+            if ($externalReferences === EPub::EXTERNAL_REF_REMOVE_IMAGES || $externalReferences === EPub::EXTERNAL_REF_REPLACE_IMAGES) {
+                $cssFile = str_replace($img[0], "", $cssFile);
+            } else {
+                $source = $img[1];
+
+                $pathData = pathinfo($source);
+                $internalSrc = $pathData['basename'];
+                $internalPath = "";
+                $isSourceExternal = FALSE;
+
+                if ($this->resolveImage($source, $internalPath, $internalSrc, $isSourceExternal, $baseDir, $cssDir, $backPath)) {
+                    $cssFile = str_replace($img[0], "url('" . $backPath . $internalPath . "')", $cssFile);
+                } else if ($isSourceExternal) {
+                    $cssFile = str_replace($img[0], "", $cssFile); // External image is missing
+                } // else do nothing, if the image is local, and missing, assume it's been generated.
+            }
+        }
+        return TRUE;
+    }
+
+    /**
+     * Process style tags in a DOMDocument. Styles will be passed as CSS files and reinserted into the document.
+     *
+     * @param DOMDocument &$xmlDoc (referenced)
+     * @param int    $externalReferences How to handle external references, EPub::EXTERNAL_REF_IGNORE, EPub::EXTERNAL_REF_ADD or EPub::EXTERNAL_REF_REMOVE_IMAGES? Default is EPub::EXTERNAL_REF_ADD.
+     * @param string $baseDir  Default is "", meaning it is pointing to the document root.
+     * @param string $htmlDir  The path to the parent HTML file's directory from the root of the archive.
+     *
+     * @return bool  FALSE if uncuccessful (book is finalized or $externalReferences == EXTERNAL_REF_IGNORE).
+     */
+    protected function processChapterStyles(&$xmlDoc, $externalReferences = EPub::EXTERNAL_REF_ADD, $baseDir = "", $htmlDir = "") {
+        if ($this->isFinalized || $externalReferences === EPub::EXTERNAL_REF_IGNORE) {
+            return FALSE;
+        }
+        // process inlined CSS styles in style tags.
+        $styles = $xmlDoc->getElementsByTagName("style");
+        $styleCount = $styles->length;
+        for ($styleIdx = 0; $styleIdx < $styleCount; $styleIdx++) {
+            $style = $styles->item($styleIdx);
+
+            $styleData = preg_replace('#[/\*\s]*\<\!\[CDATA\[[\s\*/]*#im', "", $style->nodeValue);
+            $styleData = preg_replace('#[/\*\s]*\]\]\>[\s\*/]*#im', "", $styleData);
+
+            $this->processCSSExternalReferences($styleData, $externalReferences, $baseDir, $htmlDir);
+            $style->nodeValue  = "\n" . trim($styleData) . "\n";
+        }
+        return TRUE;
+    }
+
+    /**
+     * Process link tags in a DOMDocument. Linked files will be loaded into the archive, and the link src will be rewritten to point to that location.
+     * Link types text/css will be passed as CSS files.
+     *
+     * @param DOMDocument &$xmlDoc (referenced)
+     * @param int    $externalReferences How to handle external references, EPub::EXTERNAL_REF_IGNORE, EPub::EXTERNAL_REF_ADD or EPub::EXTERNAL_REF_REMOVE_IMAGES? Default is EPub::EXTERNAL_REF_ADD.
+     * @param string $baseDir  Default is "", meaning it is pointing to the document root.
+     * @param string $htmlDir  The path to the parent HTML file's directory from the root of the archive.
+     * @param string $backPath The path to get back to the root of the archive from $htmlDir.
+     *
+     * @return bool  FALSE if uncuccessful (book is finalized or $externalReferences == EXTERNAL_REF_IGNORE).
+     */
+    protected function processChapterLinks(&$xmlDoc, $externalReferences = EPub::EXTERNAL_REF_ADD, $baseDir = "", $htmlDir = "", $backPath = "") {
+        if ($this->isFinalized || $externalReferences === EPub::EXTERNAL_REF_IGNORE) {
+            return FALSE;
+        }
+        // process link tags.
+        $links = $xmlDoc->getElementsByTagName("link");
+        $linkCount = $links->length;
+        for ($linkIdx = 0; $linkIdx < $linkCount; $linkIdx++) {
+            $link = $links->item($linkIdx);
+            $source = $link->attributes->getNamedItem("href")->nodeValue;
+            $sourceData = NULL;
+
+            $pathData = pathinfo($source);
+            $internalSrc = $pathData['basename'];
+
+            if (preg_match('#^(http|ftp)s?://#i', $source) == 1) {
+                $urlinfo = parse_url($source);
+
+                if (strpos($urlinfo['path'], $baseDir."/") !== FALSE) {
+                    $internalSrc = substr($urlinfo['path'], strpos($urlinfo['path'], $baseDir."/") + strlen($baseDir) + 1);
+                }
+
+                @$sourceData = getFileContents($source);
+            } else if (strpos($source, "/") === 0) {
+                @$sourceData = file_get_contents($this->docRoot . $source);
+            } else {
+                @$sourceData = file_get_contents($this->docRoot . $baseDir . "/" . $source);
+            }
+
+            if (!empty($sourceData)) {
+                if (!array_key_exists($internalSrc, $this->fileList)) {
+                    $mime = $link->attributes->getNamedItem("type")->nodeValue;
+                    if (empty($mime)) {
+                        $mime = "text/plain";
+                    }
+                    if ($mime == "text/css") {
+                        $this->processCSSExternalReferences($sourceData, $externalReferences, $baseDir, $htmlDir);
+                        $this->addCSSFile($internalSrc, $internalSrc, $sourceData, EPub::EXTERNAL_REF_IGNORE, $baseDir);
+                        $link->setAttribute("href", $backPath . $internalSrc);
+                    } else {
+                        $this->addFile($internalSrc, $internalSrc, $sourceData, $mime);
+                    }
+                    $this->fileList[$internalSrc] = $source;
+                } else {
+                    $link->setAttribute("href", $backPath . $internalSrc);
+                }
+            } // else do nothing, if the link is local, and missing, assume it's been generated.
+        }
+        return TRUE;
+    }
+
+    /**
+     * Process img tags in a DOMDocument.
+     * $externalReferences will determine what will happen to these images, and the img src will be rewritten accordingly.
+     *
+     * @param DOMDocument &$xmlDoc             (referenced)
+     * @param int          $externalReferences How to handle external references, EPub::EXTERNAL_REF_IGNORE, EPub::EXTERNAL_REF_ADD or EPub::EXTERNAL_REF_REMOVE_IMAGES? Default is EPub::EXTERNAL_REF_ADD.
+     * @param string       $baseDir            Default is "", meaning it is pointing to the document root.
+     * @param string       $htmlDir            The path to the parent HTML file's directory from the root of the archive.
+     * @param string       $backPath           The path to get back to the root of the archive from $htmlDir.
+     *
+     * @return bool  FALSE if uncuccessful (book is finalized or $externalReferences == EXTERNAL_REF_IGNORE).
+     */
+    protected function processChapterImages(&$xmlDoc, $externalReferences = EPub::EXTERNAL_REF_ADD, $baseDir = "", $htmlDir = "", $backPath = "") {
+        if ($this->isFinalized || $externalReferences === EPub::EXTERNAL_REF_IGNORE) {
+            return FALSE;
+        }
+        // process img tags.
+        $postProcDomElememts = array();
+        $images = $xmlDoc->getElementsByTagName("img");
+        $itemCount = $images->length;
+               
+        for ($idx = 0; $idx < $itemCount; $idx++) {
+            $img = $images->item($idx);
+
+                       if ($externalReferences === EPub::EXTERNAL_REF_REMOVE_IMAGES) {
+                $postProcDomElememts[] = $img;
+            } else if ($externalReferences === EPub::EXTERNAL_REF_REPLACE_IMAGES) {
+                $altNode = $img->attributes->getNamedItem("alt");
+                               $alt = "image";
+                               if ($altNode !== NULL && strlen($altNode->nodeValue) > 0) {
+                                       $alt = $altNode->nodeValue;
+                               }
+                $postProcDomElememts[] = array($img, $this->createDomFragment($xmlDoc, "<em>[" . $alt . "]</em>"));
+            } else {
+                $source = $img->attributes->getNamedItem("src")->nodeValue;
+
+                $parsedSource = parse_url($source);
+                $internalSrc = $this->sanitizeFileName(urldecode(pathinfo($parsedSource['path'], PATHINFO_BASENAME)));
+                $internalPath = "";
+                $isSourceExternal = FALSE;
+
+                if ($this->resolveImage($source, $internalPath, $internalSrc, $isSourceExternal, $baseDir, $htmlDir, $backPath)) {
+                    $img->setAttribute("src", $backPath . $internalPath);
+                } else if ($isSourceExternal) {
+                    $postProcDomElememts[] = $img; // External image is missing
+                } // else do nothing, if the image is local, and missing, assume it's been generated.
+            }
+        }
+
+        foreach ($postProcDomElememts as $target) {
+            if (is_array($target)) {
+                $target[0]->parentNode->replaceChild($target[1], $target[0]);
+            } else {
+                $target->parentNode->removeChild($target);
+            }
+        }
+        return TRUE;
+    }
+       
+    /**
+     * Process source tags in a DOMDocument.
+     * $externalReferences will determine what will happen to these images, and the img src will be rewritten accordingly.
+     *
+     * @param DOMDocument &$xmlDoc             (referenced)
+     * @param int          $externalReferences How to handle external references, EPub::EXTERNAL_REF_IGNORE, EPub::EXTERNAL_REF_ADD or EPub::EXTERNAL_REF_REMOVE_IMAGES? Default is EPub::EXTERNAL_REF_ADD.
+     * @param string       $baseDir            Default is "", meaning it is pointing to the document root.
+     * @param string       $htmlDir            The path to the parent HTML file's directory from the root of the archive.
+     * @param string       $backPath           The path to get back to the root of the archive from $htmlDir.
+     *
+     * @return bool  FALSE if uncuccessful (book is finalized or $externalReferences == EXTERNAL_REF_IGNORE).
+     */
+       protected function processChapterSources(&$xmlDoc, $externalReferences = EPub::EXTERNAL_REF_ADD, $baseDir = "", $htmlDir = "", $backPath = "") {
+               if ($this->isFinalized || $externalReferences === EPub::EXTERNAL_REF_IGNORE) {
+                       return FALSE;
+               }
+
+               if ($this->bookVersion !== EPub::BOOK_VERSION_EPUB3) {
+                       // ePub 2 does not support multimedia formats, and they must be removed.
+                       $externalReferences = EPub::EXTERNAL_REF_REMOVE_IMAGES;
+               }
+               
+               $postProcDomElememts = array();
+               $images = $xmlDoc->getElementsByTagName("source");
+               $itemCount = $images->length;
+               for ($idx = 0; $idx < $itemCount; $idx++) {
+                       $img = $images->item($idx);
+                       if ($externalReferences === EPub::EXTERNAL_REF_REMOVE_IMAGES) {
+                               $postProcDomElememts[] = $img;
+                       } else if ($externalReferences === EPub::EXTERNAL_REF_REPLACE_IMAGES) {
+                               $altNode = $img->attributes->getNamedItem("alt");
+                               $alt = "image";
+                               if ($altNode !== NULL && strlen($altNode->nodeValue) > 0) {
+                                       $alt = $altNode->nodeValue;
+                               }
+                               $postProcDomElememts[] = array($img, $this->createDomFragment($xmlDoc, "[" . $alt . "]"));
+                       } else {
+                               $source = $img->attributes->getNamedItem("src")->nodeValue;
+
+                               $parsedSource = parse_url($source);
+                               $internalSrc = $this->sanitizeFileName(urldecode(pathinfo($parsedSource['path'], PATHINFO_BASENAME)));
+                               $internalPath = "";
+                               $isSourceExternal = FALSE;
+
+                               if ($this->resolveMedia($source, $internalPath, $internalSrc, $isSourceExternal, $baseDir, $htmlDir, $backPath)) {
+                                       $img->setAttribute("src", $backPath . $internalPath);
+                               } else if ($isSourceExternal) {
+                                       $postProcDomElememts[] = $img; // External image is missing
+                               } // else do nothing, if the image is local, and missing, assume it's been generated.
+                       }
+               }
+       }
+
+    /**
+     * Resolve an image src and determine it's target location and add it to the book.
+     *
+     * @param string  $source Image Source link.
+     * @param string &$internalPath (referenced) Return value, will be set to the target path and name in the book.
+     * @param string &$internalSrc (referenced) Return value, will be set to the target name in the book.
+     * @param string &$isSourceExternal (referenced) Return value, will be set to TRUE if the image originated from a full URL.
+     * @param string  $baseDir  Default is "", meaning it is pointing to the document root.
+     * @param string  $htmlDir  The path to the parent HTML file's directory from the root of the archive.
+     * @param string  $backPath The path to get back to the root of the archive from $htmlDir.
+     */
+    protected function resolveImage($source, &$internalPath, &$internalSrc, &$isSourceExternal, $baseDir = "", $htmlDir = "", $backPath = "") {
+        if ($this->isFinalized) {
+            return FALSE;
+        }
+        $imageData  = NULL;
+               
+        if (preg_match('#^(http|ftp)s?://#i', $source) == 1) {
+            $urlinfo = parse_url($source);
+                       $urlPath = pathinfo($urlinfo['path']);
+
+            if (strpos($urlinfo['path'], $baseDir."/") !== FALSE) {
+                $internalSrc = $this->sanitizeFileName(urldecode(substr($urlinfo['path'], strpos($urlinfo['path'], $baseDir."/") + strlen($baseDir) + 1)));
+            }
+            $internalPath = $urlinfo["scheme"] . "/" . $urlinfo["host"] . "/" . pathinfo($urlinfo["path"], PATHINFO_DIRNAME);
+            $isSourceExternal = TRUE;
+            $imageData = $this->getImage($source);
+        } else if (strpos($source, "/") === 0) {
+            $internalPath = pathinfo($source, PATHINFO_DIRNAME);
+
+                       $path = $source;
+                       if (!file_exists($path)) {
+                               $path = $this->docRoot . $path;
+                       }
+
+                       $imageData = $this->getImage($path);
+        } else {
+            $internalPath = $htmlDir . "/" . preg_replace('#^[/\.]+#', '', pathinfo($source, PATHINFO_DIRNAME));
+                       
+                       $path = $baseDir . "/" . $source;
+                       if (!file_exists($path)) {
+                               $path = $this->docRoot . $path;
+                       }
+                       
+            $imageData = $this->getImage($path);
+        }
+        if ($imageData !== FALSE) {
+                       $iSrcInfo = pathinfo($internalSrc);
+                       if (!empty($imageData['ext']) && $imageData['ext'] != $iSrcInfo['extension']) {
+                               $internalSrc = $iSrcInfo['filename'] . "." . $imageData['ext'];
+               }
+            $internalPath = Zip::getRelativePath("images/" . $internalPath . "/" . $internalSrc);
+        if (!array_key_exists($internalPath, $this->fileList)) {
+                $this->addFile($internalPath, "i_" . $internalSrc, $imageData['image'], $imageData['mime']);
+                $this->fileList[$internalPath] = $source;
+            }
+            return TRUE;
+        }
+        return FALSE;
+    }
+
+    /**
+     * Resolve a media src and determine it's target location and add it to the book.
+     *
+     * @param string $source Source link.
+     * @param string $internalPath (referenced) Return value, will be set to the target path and name in the book.
+     * @param string $internalSrc (referenced) Return value, will be set to the target name in the book.
+     * @param string $isSourceExternal (referenced) Return value, will be set to TRUE if the image originated from a full URL.
+     * @param string $baseDir  Default is "", meaning it is pointing to the document root.
+     * @param string $htmlDir  The path to the parent HTML file's directory from the root of the archive.
+     * @param string $backPath The path to get back to the root of the archive from $htmlDir.
+     */
+    protected function resolveMedia($source, &$internalPath, &$internalSrc, &$isSourceExternal, $baseDir = "", $htmlDir = "", $backPath = "") {
+        if ($this->isFinalized) {
+            return FALSE;
+        }
+        $mediaPath = NULL;
+               $tmpFile;
+
+        if (preg_match('#^(http|ftp)s?://#i', $source) == 1) {
+            $urlinfo = parse_url($source);
+
+            if (strpos($urlinfo['path'], $baseDir."/") !== FALSE) {
+                $internalSrc = substr($urlinfo['path'], strpos($urlinfo['path'], $baseDir."/") + strlen($baseDir) + 1);
+            }
+            $internalPath = $urlinfo["scheme"] . "/" . $urlinfo["host"] . "/" . pathinfo($urlinfo["path"], PATHINFO_DIRNAME);
+            $isSourceExternal = TRUE;
+            $mediaPath = $this->getFileContents($source, true);
+                       $tmpFile = $mediaPath;
+               } else if (strpos($source, "/") === 0) {
+            $internalPath = pathinfo($source, PATHINFO_DIRNAME);
+                       
+                       $mediaPath = $source;
+                       if (!file_exists($mediaPath)) {
+                               $mediaPath = $this->docRoot . $mediaPath;
+                       }
+        } else {
+            $internalPath = $htmlDir . "/" . preg_replace('#^[/\.]+#', '', pathinfo($source, PATHINFO_DIRNAME));
+                       
+                       $mediaPath = $baseDir . "/" . $source;
+                       if (!file_exists($mediaPath)) {
+                               $mediaPath = $this->docRoot . $mediaPath;
+                       }
+        }
+
+        if ($mediaPath !== FALSE) {
+            $mime = $this->getMime($source);
+            $internalPath = Zip::getRelativePath("media/" . $internalPath . "/" . $internalSrc);
+                       
+            if (!array_key_exists($internalPath, $this->fileList) &&
+                                       $this->addLargeFile($internalPath, "m_" . $internalSrc, $mediaPath, $mime)) {
+                $this->fileList[$internalPath] = $source;
+            }
+                       if (isset($tmpFile)) {
+                               unlink($tmpFile);
+                       }
+            return TRUE;
+        }
+        return FALSE;
+    }
+
+    /**
+     * Get Book Chapter count.
+     *
+     * @access public
+     * @return number of chapters
+     */
+    function getChapterCount() {
+        return $this->chapterCount;
+    }
+
+    /**
+     * Book title, mandatory.
+     *
+     * Used for the dc:title metadata parameter in the OPF file as well as the DocTitle attribute in the NCX file.
+     *
+     * @param string $title
+     * @access public
+     * @return bool $success
+     */
+    function setTitle($title) {
+        if ($this->isFinalized) {
+            return FALSE;
+        }
+        $this->title = $title;
+        return TRUE;
+    }
+
+    /**
+     * Get Book title.
+     *
+     * @access public
+     * @return $title
+     */
+    function getTitle() {
+        return $this->title;
+    }
+
+    /**
+     * Book language, mandatory
+     *
+     * Use the RFC3066 Language codes, such as "en", "da", "fr" etc.
+     * Defaults to "en".
+     *
+     * Used for the dc:language metadata parameter in the OPF file.
+     *
+     * @param string $language
+     * @access public
+     * @return bool $success
+     */
+    function setLanguage($language) {
+        if ($this->isFinalized || mb_strlen($language) != 2) {
+            return FALSE;
+        }
+        $this->language = $language;
+        return TRUE;
+    }
+
+    /**
+     * Get Book language.
+     *
+     * @access public
+     * @return $language
+     */
+    function getLanguage() {
+        return $this->language;
+    }
+
+    /**
+     * Unique book identifier, mandatory.
+     * Use the URI, or ISBN if available.
+     *
+     * An unambiguous reference to the resource within a given context.
+     *
+     * Recommended best practice is to identify the resource by means of a
+     *  string conforming to a formal identification system.
+     *
+     * Used for the dc:identifier metadata parameter in the OPF file, as well
+     *  as dtb:uid in the NCX file.
+     *
+     * Identifier type should only be:
+     *  EPub::IDENTIFIER_URI
+     *  EPub::IDENTIFIER_ISBN
+     *  EPub::IDENTIFIER_UUID
+     *
+     * @param string $identifier
+     * @param string $identifierType
+     * @access public
+     * @return bool $success
+     */
+    function setIdentifier($identifier, $identifierType) {
+        if ($this->isFinalized || ($identifierType !== EPub::IDENTIFIER_URI && $identifierType !== EPub::IDENTIFIER_ISBN && $identifierType !== EPub::IDENTIFIER_UUID)) {
+            return FALSE;
+        }
+        $this->identifier = $identifier;
+        $this->identifierType = $identifierType;
+        return TRUE;
+    }
+
+    /**
+     * Get Book identifier.
+     *
+     * @access public
+     * @return $identifier
+     */
+    function getIdentifier() {
+        return $this->identifier;
+    }
+
+    /**
+     * Get Book identifierType.
+     *
+     * @access public
+     * @return $identifierType
+     */
+    function getIdentifierType() {
+        return $this->identifierType;
+    }
+
+    /**
+     * Book description, optional.
+     *
+     * An account of the resource.
+     *
+     * Description may include but is not limited to: an abstract, a table of
+     *  contents, a graphical representation, or a free-text account of the
+     *  resource.
+     *
+     * Used for the dc:source metadata parameter in the OPF file
+     *
+     * @param string $description
+     * @access public
+     * @return bool $success
+     */
+    function setDescription($description) {
+        if ($this->isFinalized) {
+            return FALSE;
+        }
+        $this->description = $description;
+        return TRUE;
+    }
+
+    /**
+     * Get Book description.
+     *
+     * @access public
+     * @return $description
+     */
+    function getDescription() {
+        return $this->description;
+    }
+
+    /**
+     * Book author or creator, optional.
+     * The $authorSortKey is basically how the name is to be sorted, usually
+     *  it's "Lastname, First names" where the $author is the straight
+     *  "Firstnames Lastname"
+     *
+     * An entity primarily responsible for making the resource.
+     *
+     * Examples of a Creator include a person, an organization, or a service.
+     *  Typically, the name of a Creator should be used to indicate the entity.
+     *
+     * Used for the dc:creator metadata parameter in the OPF file and the
+     *  docAuthor attribure in the NCX file.
+     * The sort key is used for the opf:file-as attribute in dc:creator.
+     *
+     * @param string $author
+     * @param string $authorSortKey
+     * @access public
+     * @return bool $success
+     */
+    function setAuthor($author, $authorSortKey) {
+        if ($this->isFinalized) {
+            return FALSE;
+        }
+        $this->author = $author;
+        $this->authorSortKey = $authorSortKey;
+        return TRUE;
+    }
+
+    /**
+     * Get Book author.
+     *
+     * @access public
+     * @return $author
+     */
+    function getAuthor() {
+        return $this->author;
+    }
+
+    /**
+     * Publisher Information, optional.
+     *
+     * An entity responsible for making the resource available.
+     *
+     * Examples of a Publisher include a person, an organization, or a service.
+     *  Typically, the name of a Publisher should be used to indicate the entity.
+     *
+     * Used for the dc:publisher and dc:relation metadata parameters in the OPF file.
+     *
+     * @param string $publisherName
+     * @param string $publisherURL
+     * @access public
+     * @return bool $success
+     */
+    function setPublisher($publisherName, $publisherURL) {
+        if ($this->isFinalized) {
+            return FALSE;
+        }
+        $this->publisherName = $publisherName;
+        $this->publisherURL = $publisherURL;
+        return TRUE;
+    }
+
+    /**
+     * Get Book publisherName.
+     *
+     * @access public
+     * @return $publisherName
+     */
+    function getPublisherName() {
+        return $this->publisherName;
+    }
+
+    /**
+     * Get Book publisherURL.
+     *
+     * @access public
+     * @return $publisherURL
+     */
+    function getPublisherURL() {
+        return $this->publisherURL;
+    }
+
+    /**
+     * Release date, optional. If left blank, the time of the finalization will
+     *  be used.
+     *
+     * A point or period of time associated with an event in the lifecycle of
+     *  the resource.
+     *
+     * Date may be used to express temporal information at any level of
+     *  granularity.  Recommended best practice is to use an encoding scheme,
+     *  such as the W3CDTF profile of ISO 8601 [W3CDTF].
+     *
+     * Used for the dc:date metadata parameter in the OPF file
+     *
+     * @param long $timestamp
+     * @access public
+     * @return bool $success
+     */
+    function setDate($timestamp) {
+        if ($this->isFinalized) {
+            return FALSE;
+        }
+        $this->date = $timestamp;
+        $this->opf->date = $timestamp;
+        return TRUE;
+    }
+
+    /**
+     * Get Book date.
+     *
+     * @access public
+     * @return $date
+     */
+    function getDate() {
+        return $this->date;
+    }
+
+    /**
+     * Book (copy)rights, optional.
+     *
+     * Information about rights held in and over the resource.
+     *
+     * Typically, rights information includes a statement about various
+     *  property rights associated with the resource, including intellectual
+     *  property rights.
+     *
+     * Used for the dc:rights metadata parameter in the OPF file
+     *
+     * @param string $rightsText
+     * @access public
+     * @return bool $success
+     */
+    function setRights($rightsText) {
+        if ($this->isFinalized) {
+            return FALSE;
+        }
+        $this->rights = $rightsText;
+        return TRUE;
+    }
+
+    /**
+     * Get Book rights.
+     *
+     * @access public
+     * @return $rights
+     */
+    function getRights() {
+        return $this->rights;
+    }
+
+    /**
+     * Add book Subject.
+     *
+     * The topic of the resource.
+     *
+     * Typically, the subject will be represented using keywords, key phrases,
+     *  or classification codes. Recommended best practice is to use a
+     *  controlled vocabulary. To describe the spatial or temporal topic of the
+     *  resource, use the Coverage element.
+     *
+     * @param string $subject
+     */
+    function setSubject($subject) {
+        if ($this->isFinalized) {
+            return;
+        }
+               $this->opf->addDCMeta(DublinCore::SUBJECT, $this->decodeHtmlEntities($subject));
+    }
+
+       /**
+     * Book source URL, optional.
+     *
+     * A related resource from which the described resource is derived.
+     *
+     * The described resource may be derived from the related resource in whole
+     *  or in part. Recommended best practice is to identify the related
+     *  resource by means of a string conforming to a formal identification system.
+     *
+     * Used for the dc:source metadata parameter in the OPF file
+     *
+     * @param string $sourceURL
+     * @access public
+     * @return bool $success
+     */
+    function setSourceURL($sourceURL) {
+        if ($this->isFinalized) {
+            return FALSE;
+        }
+        $this->sourceURL = $sourceURL;
+        return TRUE;
+    }
+
+    /**
+     * Get Book sourceURL.
+     *
+     * @access public
+     * @return $sourceURL
+     */
+    function getSourceURL() {
+        return $this->sourceURL;
+    }
+
+    /**
+     * Coverage, optional.
+     *
+     * The spatial or temporal topic of the resource, the spatial applicability
+     *  of the resource, or the jurisdiction under which the resource is relevant.
+     *
+     * Spatial topic and spatial applicability may be a named place or a location
+     *  specified by its geographic coordinates. Temporal topic may be a named
+     *  period, date, or date range. A jurisdiction may be a named administrative
+     *  entity or a geographic place to which the resource applies. Recommended
+     *  best practice is to use a controlled vocabulary such as the Thesaurus of
+     *  Geographic Names [TGN]. Where appropriate, named places or time periods
+     *  can be used in preference to numeric identifiers such as sets of
+     *  coordinates or date ranges.
+     *
+     * Used for the dc:coverage metadata parameter in the OPF file
+     *
+        * Same as ->addDublinCoreMetadata(DublinCore::COVERAGE, $coverage);
+        *
+     * @param string $coverage
+     * @access public
+     * @return bool $success
+     */
+    function setCoverage($coverage) {
+        if ($this->isFinalized) {
+            return FALSE;
+        }
+        $this->coverage = $coverage;
+        return TRUE;
+    }
+
+    /**
+     * Get Book coverage.
+     *
+     * @access public
+     * @return $coverage
+     */
+    function getCoverage() {
+        return $this->coverage;
+    }
+
+    /**
+     * Set book Relation.
+     *
+     * A related resource.
+     *
+     * Recommended best practice is to identify the related resource by means
+     *  of a string conforming to a formal identification system.
+     *
+     * @param string $relation
+     */
+    function setRelation($relation) {
+        if ($this->isFinalized) {
+            return;
+        }
+        $this->relation = $relation;
+    }
+
+    /**
+     * Get the book relation.
+     *
+     * @return string The relation.
+     */
+    function getRelation() {
+        return $this->relation;
+    }
+
+    /**
+     * Set book Generator.
+     *
+     * The generator is a meta tag added to the ncx file, it is not visible
+     *  from within the book, but is a kind of electronic watermark.
+     *
+     * @param string $generator
+     */
+    function setGenerator($generator) {
+        if ($this->isFinalized) {
+            return;
+        }
+        $this->generator = $generator;
+    }
+
+    /**
+     * Get the book relation.
+     *
+     * @return string The generator identity string.
+     */
+    function getGenerator() {
+        return $this->generator;
+    }
+
+    /**
+     * Set ePub date formate to the short yyyy-mm-dd form, for compliance with
+     *  a bug in EpubCheck, prior to its version 1.1.
+     *
+     * The latest version of ePubCheck can be obtained here:
+     *  http://code.google.com/p/epubcheck/
+     *
+     * @access public
+     * @return bool $success
+     */
+    function setShortDateFormat() {
+        if ($this->isFinalized) {
+            return FALSE;
+        }
+        $this->dateformat = $this->dateformatShort;
+        return TRUE;
+    }
+
+    /**
+     * @Deprecated
+     */
+    function setIgnoreEmptyBuffer($ignoreEmptyBuffer = TRUE) {
+        die ("Function was deprecated, functionality is no longer needed.");
+    }
+
+       /**
+        * Set the references title for the ePub 3 landmarks section
+        *
+        * @param string $referencesTitle
+        * @param string $referencesId
+        * @param string $referencesClass
+        * @return bool
+        */
+       function setReferencesTitle($referencesTitle = "Guide", $referencesId = "", $referencesClass = "references") {
+        if ($this->isFinalized) {
+            return FALSE;
+        }
+               $this->ncx->referencesTitle = is_string($referencesTitle) ? trim($referencesTitle) : "Guide";
+               $this->ncx->referencesId = is_string($referencesId) ? trim($referencesId) : "references";
+               $this->ncx->referencesClass = is_string($referencesClass) ? trim($referencesClass) : "references";
+               return TRUE;
+       }
+
+       /**
+        * Set the references title for the ePub 3 landmarks section
+        *
+        * @param bool $referencesTitle
+        */
+       function setisReferencesAddedToToc($isReferencesAddedToToc = TRUE) {
+        if ($this->isFinalized) {
+            return FALSE;
+        }
+               $this->isReferencesAddedToToc = $isReferencesAddedToToc === TRUE;
+               return TRUE;
+       }
+
+       /**
+     * Get Book status.
+     *
+     * @access public
+     * @return bool
+     */
+    function isFinalized() {
+        return $this->isFinalized;
+    }
+
+    /**
+     * Build the Table of Contents. This is not strictly necessary, as most eReaders will build it from the navigation structure in the .ncx file.
+     *
+     * @param string $cssFileName Include a link to this css file in the TOC html.
+     * @param string $tocCSSClass The TOC is a <div>, if you need special formatting, you can add a css class for that div. Default is "toc".
+     * @param string $title Title of the Table of contents. Default is "Table of Contents". Use this for ie. languages other than English.
+     * @param bool   $addReferences include reference pages in the TOC, using the $referencesOrder array to determine the order of the pages in the TOC. Default is TRUE.
+        * @param bool   $addToIndex Add the TOC to the NCX index at the current leve/position. Default is FALSE
+        * @param string $tocFileName Change teh default name of the TOC file. The default is "TOC.xhtml"
+     */
+    function buildTOC($cssFileName = NULL, $tocCSSClass = "toc", $title = "Table of Contents", $addReferences = TRUE, $addToIndex = FALSE, $tocFileName = "TOC.xhtml") {
+        if ($this->isFinalized) {
+            return FALSE;
+        }
+               $this->buildTOC = TRUE;
+               $this->tocTitle = $title;
+               $this->tocFileName = $this->normalizeFileName($tocFileName);
+               if (!empty($cssFileName)) {
+                       $this->tocCSSFileName = $this->normalizeFileName($cssFileName);
+               }
+               $this->tocCSSClass = $tocCSSClass;
+               $this->tocAddReferences = $addReferences;
+
+               $this->opf->addItemRef("ref_" . Reference::TABLE_OF_CONTENTS, FALSE);
+               $this->opf->addReference(Reference::TABLE_OF_CONTENTS, $title, $this->tocFileName);
+
+               if ($addToIndex) {
+            $navPoint = new NavPoint($this->decodeHtmlEntities($title), $this->tocFileName, "ref_" . Reference::TABLE_OF_CONTENTS);
+            $this->ncx->addNavPoint($navPoint);
+               } else {
+                       $this->ncx->referencesList[Reference::TABLE_OF_CONTENTS] = $this->tocFileName;
+                       $this->ncx->referencesName[Reference::TABLE_OF_CONTENTS] = $title;
+               }
+       }
+       
+       private function finalizeTOC() {
+        if (!$this->buildTOC) {
+            return FALSE;
+        }
+
+        if (empty($this->tocTitle)) {
+            $this->tocTitle = "Table of Contents";
+        }
+
+               $tocData = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
+
+               if ($this->isEPubVersion2()) {
+                       $tocData .= "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"\n"
+                       . "    \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n"
+                       . "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
+                   . "<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n";
+               } else {
+                       $tocData .= "<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\">\n"
+                   . "<head>\n<meta http-equiv=\"Default-Style\" content=\"text/html; charset=utf-8\" />\n";
+               }
+
+        if (!empty($this->tocCssFileName)) {
+            $tocData .= "<link rel=\"stylesheet\" type=\"text/css\" href=\"" . $this->tocCssFileName . "\" />\n";
+        }
+
+               $tocData .= "<title>" . $this->tocTitle . "</title>\n"
+        . "</head>\n"
+        . "<body>\n"
+        . "<h3>" . $this->tocTitle . "</h3>\n<div";
+
+        if (!empty($this->tocCSSClass)) {
+            $tocData .= " class=\"" . $this->tocCSSClass . "\"";
+        }
+        $tocData .= ">\n";
+
+        while (list($item, $descriptive) = each($this->referencesOrder)) {
+            if ($item === "text") {
+                while (list($chapterName, $navPoint) = each($this->ncx->chapterList)) {
+                                       $fileName = $navPoint->getContentSrc();
+                                       $level = $navPoint->getLevel() -2;
+                                       $tocData .= "\t<p>" . str_repeat(" &#160;  &#160;  &#160;", $level) . "<a href=\"" . $this->sanitizeFileName($fileName) . "\">" . $chapterName . "</a></p>\n";
+                }
+            } else if ($this->tocAddReferences === TRUE) {
+                if (array_key_exists($item, $this->ncx->referencesList)) {
+                    $tocData .= "\t<p><a href=\"" . $this->ncx->referencesList[$item] . "\">" . $descriptive . "</a></p>\n";
+                } else if ($item === "toc") {
+                    $tocData .= "\t<p><a href=\"TOC.xhtml\">" . $this->tocTitle . "</a></p>\n";
+                } else if ($item === "cover" && $this->isCoverImageSet) {
+                    $tocData .= "\t<p><a href=\"CoverPage.xhtml\">" . $descriptive . "</a></p>\n";
+                }
+            }
+        }
+        $tocData .= "</div>\n</body>\n</html>\n";
+
+               $this->addReferencePage($this->tocTitle, $this->tocFileName, $tocData, Reference::TABLE_OF_CONTENTS);
+               
+    }
+
+       /**
+        * @return bool
+        */
+       function isEPubVersion2() {
+               return $this->bookVersion === EPub::BOOK_VERSION_EPUB2;
+       }
+
+       /**
+        * @param string $cssFileName
+        * @param string $title
+        * @return string
+        */
+       function buildEPub3TOC($cssFileName = NULL, $title = "Table of Contents") {
+               $this->ncx->referencesOrder = $this->referencesOrder;
+               $this->ncx->setDocTitle($this->decodeHtmlEntities($this->title));
+               return $this->ncx->finalizeEPub3($title, $cssFileName);
+       }
+
+       /**
+        * @param string $fileName
+        * @param string $tocData
+        * @return bool
+        */
+       function addEPub3TOC($fileName, $tocData) {
+               if ($this->isEPubVersion2() || $this->isFinalized || array_key_exists($fileName, $this->fileList)) {
+            return FALSE;
+        }
+        $fileName = Zip::getRelativePath($fileName);
+        $fileName = preg_replace('#^[/\.]+#i', "", $fileName);
+
+        $this->zip->addFile($tocData, $this->bookRoot.$fileName);
+
+        $this->fileList[$fileName] = $fileName;
+        $this->opf->addItem("toc", $fileName, "application/xhtml+xml", "nav");
+        return TRUE;
+       }
+
+       /**
+     * Check for mandatory parameters and finalize the e-book.
+     * Once finalized, the book is locked for further additions.
+     *
+     * @return bool $success
+     */
+    function finalize() {
+        if ($this->isFinalized || $this->chapterCount == 0 || empty($this->title) || empty($this->language)) {
+            return FALSE;
+        }
+
+        if (empty($this->identifier) || empty($this->identifierType)) {
+            $this->setIdentifier($this->createUUID(4), EPub::IDENTIFIER_UUID);
+        }
+
+        if ($this->date == 0) {
+            $this->date = time();
+        }
+
+        if (empty($this->sourceURL)) {
+            $this->sourceURL = $this->getCurrentPageURL();
+        }
+
+        if (empty($this->publisherURL)) {
+            $this->sourceURL = $this->getCurrentServerURL();
+        }
+
+        // Generate OPF data:
+        $this->opf->setIdent("BookId");
+        $this->opf->initialize($this->title, $this->language, $this->identifier, $this->identifierType);
+               
+        $DCdate = new DublinCore(DublinCore::DATE, gmdate($this->dateformat, $this->date));
+        $DCdate->addOpfAttr("event", "publication");
+        $this->opf->metadata->addDublinCore($DCdate);
+
+        if (!empty($this->description)) {
+            $this->opf->addDCMeta(DublinCore::DESCRIPTION, $this->decodeHtmlEntities($this->description));
+        }
+
+        if (!empty($this->publisherName)) {
+            $this->opf->addDCMeta(DublinCore::PUBLISHER, $this->decodeHtmlEntities($this->publisherName));
+        }
+
+        if (!empty($this->publisherURL)) {
+            $this->opf->addDCMeta(DublinCore::RELATION, $this->decodeHtmlEntities($this->publisherURL));
+        }
+
+        if (!empty($this->author)) {
+                       $author = $this->decodeHtmlEntities($this->author);
+            $this->opf->addCreator($author, $this->decodeHtmlEntities($this->authorSortKey), MarcCode::AUTHOR);
+            $this->ncx->setDocAuthor($author);
+        }
+
+        if (!empty($this->rights)) {
+            $this->opf->addDCMeta(DublinCore::RIGHTS, $this->decodeHtmlEntities($this->rights));
+        }
+
+        if (!empty($this->coverage)) {
+            $this->opf->addDCMeta(DublinCore::COVERAGE, $this->decodeHtmlEntities($this->coverage));
+        }
+
+        if (!empty($this->sourceURL)) {
+            $this->opf->addDCMeta(DublinCore::SOURCE, $this->sourceURL);
+        }
+
+        if (!empty($this->relation)) {
+            $this->opf->addDCMeta(DublinCore::RELATION, $this->decodeHtmlEntities($this->relation));
+        }
+
+        if ($this->isCoverImageSet) {
+            $this->opf->addMeta("cover", "coverImage");
+        }
+
+        if (!empty($this->generator)) {
+                       $gen = $this->decodeHtmlEntities($this->generator);
+            $this->opf->addMeta("generator", $gen);
+            $this->ncx->addMetaEntry("dtb:generator", $gen);
+        }
+
+        if ($this->EPubMark) {
+            $this->opf->addMeta("generator", "EPub (Version " . self::VERSION . ") by A. Grandt, http://www.phpclasses.org/package/6115");
+        }
+
+               reset($this->ncx->chapterList);
+        list($firstChapterName, $firstChapterNavPoint) = each($this->ncx->chapterList);
+               $firstChapterFileName = $firstChapterNavPoint->getContentSrc();
+        $this->opf->addReference(Reference::TEXT, $this->decodeHtmlEntities($firstChapterName), $firstChapterFileName);
+
+        $this->ncx->setUid($this->identifier);
+
+        $this->ncx->setDocTitle($this->decodeHtmlEntities($this->title));
+
+               $this->ncx->referencesOrder = $this->referencesOrder;
+               if ($this->isReferencesAddedToToc) {
+                       $this->ncx->finalizeReferences();
+               }
+
+               $this->finalizeTOC();
+
+               if (!$this->isEPubVersion2()) {
+                       $this->addEPub3TOC("epub3toc.xhtml", $this->buildEPub3TOC());
+               }
+
+        $opfFinal = $this->fixEncoding($this->opf->finalize());
+        $ncxFinal = $this->fixEncoding($this->ncx->finalize());
+
+        if (mb_detect_encoding($opfFinal, 'UTF-8', true) === "UTF-8") {
+            $this->zip->addFile($opfFinal, $this->bookRoot."book.opf");
+        } else {
+            $this->zip->addFile(mb_convert_encoding($opfFinal, "UTF-8"), $this->bookRoot."book.opf");
+        }
+
+        if (mb_detect_encoding($ncxFinal, 'UTF-8', true) === "UTF-8") {
+            $this->zip->addFile($ncxFinal, $this->bookRoot."book.ncx");
+        } else {
+            $this->zip->addFile(mb_convert_encoding($ncxFinal, "UTF-8"), $this->bookRoot."book.ncx");
+        }
+
+        $this->opf = NULL;
+        $this->ncx = NULL;
+
+        $this->isFinalized = TRUE;
+        return TRUE;
+    }
+
+    /**
+     * Ensure the encoded string is a valid UTF-8 string.
+     *
+     * Note, that a mb_detect_encoding on the returned string will still return ASCII if the entire string is comprized of characters in the 1-127 range.
+     *
+     * @link: http://snippetdb.com/php/convert-string-to-utf-8-for-mysql
+     * @param string $in_str
+     * @return string converted string.
+     */
+    function fixEncoding($in_str) {
+        if (mb_detect_encoding($in_str) == "UTF-8" && mb_check_encoding($in_str,"UTF-8")) {
+            return $in_str;
+        } else {
+            return utf8_encode($in_str);
+        }
+    }
+
+    /**
+     * Return the finalized book.
+     *
+     * @return string with the book in binary form.
+     */
+    function getBook() {
+        if (!$this->isFinalized) {
+            $this->finalize();
+        }
+
+        return $this->zip->getZipData();
+    }
+
+    /**
+     * Remove disallowed characters from string to get a nearly safe filename
+     *
+     * @param string $fileName
+     * @return mixed|string
+     */
+    function sanitizeFileName($fileName) {
+        $fileName1 = str_replace($this->forbiddenCharacters, '', $fileName);
+        $fileName2 = preg_replace('/[\s-]+/', '-', $fileName1);
+        return trim($fileName2, '.-_');
+
+    }
+
+       /**
+        * Cleanup the filepath, and remove leading . and / characters.
+        * 
+        * Sometimes, when a path is generated from multiple fragments, 
+        *  you can get something like "../data/html/../images/image.jpeg"
+        * ePub files don't work well with that, this will normalize that 
+        *  example path to "data/images/image.jpeg"
+        *
+        * @param string $fileName
+        * @return string normalized filename
+        */
+       function normalizeFileName($fileName) {
+        return preg_replace('#^[/\.]+#i', "", Zip::getRelativePath($fileName));
+       }
+
+    /**
+     * Save the ePub file to local disk.
+     *
+     * @param string $fileName
+     * @param string $baseDir If empty baseDir is absolute to server path, if omitted it's relative to script path
+     * @return The sent file name if successfull, FALSE if it failed.
+     */
+    function saveBook($fileName, $baseDir = '.') {
+
+        // Make fileName safe
+        $fileName = $this->sanitizeFileName($fileName);
+
+        // Finalize book, if it's not done already
+        if (!$this->isFinalized) {
+            $this->finalize();
+        }
+
+               if (stripos(strrev($fileName), "bupe.") !== 0) {
+            $fileName .= ".epub";
+        }
+
+        // Try to open file access
+        $fh = fopen($baseDir.'/'.$fileName, "w");
+
+        if ($fh) {
+            fputs($fh, $this->getBook());
+            fclose($fh);
+
+            // if file is written return TRUE
+            return $fileName;
+        }
+
+        // return FALSE by default
+        return FALSE;
+    }
+
+    /**
+     * Return the finalized book size.
+     *
+     * @return string
+     */
+    function getBookSize() {
+        if (!$this->isFinalized) {
+            $this->finalize();
+        }
+
+        return $this->zip->getArchiveSize();
+    }
+
+    /**
+     * Send the book as a zip download
+     *
+     * Sending will fail if the output buffer is in use. You can override this limit by
+     *  calling setIgnoreEmptyBuffer(TRUE), though the function will still fail if that
+     *  buffer is not empty.
+     *
+     * @param string $fileName The name of the book without the .epub at the end.
+     * @return The sent file name if successfull, FALSE if it failed.
+     */
+    function sendBook($fileName) {
+        if (!$this->isFinalized) {
+            $this->finalize();
+        }
+
+        if (stripos(strrev($fileName), "bupe.") !== 0) {
+            $fileName .= ".epub";
+        }
+
+        if (TRUE === $this->zip->sendZip($fileName, "application/epub+zip")) {
+                       return $fileName;
+               }
+        return FALSE;
+    }
+
+    /**
+     * Generates an UUID.
+     *
+     * Default version (4) will generate a random UUID, version 3 will URL based UUID.
+     *
+     * Added for convinience
+     *
+     * @param int    $bookVersion UUID version to retrieve, See lib.uuid.manual.html for details.
+     * @param string $url
+        * @return string The formatted uuid
+     */
+    function createUUID($bookVersion = 4, $url = NULL) {
+        include_once("lib.uuid.php");
+        return UUID::mint($bookVersion, $url, UUID::nsURL);
+    }
+
+    /**
+     * Get the url of the current page.
+     * Example use: Default Source URL
+     *
+     * $return string Page URL.
+     */
+    function getCurrentPageURL() {
+        $pageURL = $this->getCurrentServerURL() . filter_input(INPUT_SERVER, "REQUEST_URI");
+        return $pageURL;
+    }
+
+    /**
+     * Get the url of the server.
+     * Example use: Default Publisher URL
+     *
+     * $return string Server URL.
+     */
+    function getCurrentServerURL() {
+        $serverURL = 'http';
+               $https = filter_input(INPUT_SERVER, "HTTPS");
+               $port = filter_input(INPUT_SERVER, "SERVER_PORT");
+
+               if ($https === "on") {
+            $serverURL .= "s";
+        }
+        $serverURL .= "://" . filter_input(INPUT_SERVER, "SERVER_NAME");
+        if ($port != "80") {
+            $serverURL .= ":" . $port;
+        }
+        return $serverURL . '/';
+    }
+
+    /**
+     * Try to determine the mimetype of the file path.
+     *
+     * @param string $source Path
+     * @return string mimetype, or FALSE.
+     */
+    function getMime($source) {
+        return $this->mimetypes[pathinfo($source, PATHINFO_EXTENSION)];
+    }
+
+    /**
+     * Get an image from a file or url, return it resized if the image exceeds the $maxImageWidth or $maxImageHeight directives.
+     *
+     * The return value is an array.
+     * ['width'] is the width of the image.
+     * ['height'] is the height of the image.
+     * ['mime'] is the mime type of the image. Resized images are always in jpeg format.
+     * ['image'] is the image data.
+     * ['ext'] is the extension of the image file.
+     *
+     * @param string $source path or url to file.
+     * $return array
+     */
+    function getImage($source) {
+        $width = -1;
+        $height = -1;
+        $mime = "application/octet-stream";
+        $type = FALSE;
+               $ext = "";
+
+
+        $image = $this->getFileContents($source);
+
+        if ($image !== FALSE && strlen($image) > 0) {
+            $imageFile = imagecreatefromstring($image);
+            if ($imageFile !== false) {
+                $width = ImageSX($imageFile);
+                $height = ImageSY($imageFile);
+            }
+            if ($this->isExifInstalled) {
+                @$type = exif_imagetype($source);
+                $mime = image_type_to_mime_type($type);
+            }
+            if ($mime === "application/octet-stream") {
+                $mime = $this->image_file_type_from_binary($image);
+            }
+            if ($mime === "application/octet-stream") {
+                $mime = $this->getMimeTypeFromUrl($source);
+            }
+        } else {
+            return FALSE;
+        }
+
+        if ($width <= 0 || $height <= 0) {
+            return FALSE;
+        }
+
+        $ratio = 1;
+
+        if ($this->isGdInstalled) {
+            if ($width > $this->maxImageWidth) {
+                $ratio = $this->maxImageWidth/$width;
+            }
+            if ($height*$ratio > $this->maxImageHeight) {
+                $ratio = $this->maxImageHeight/$height;
+            }
+
+                       if ($ratio < 1 || empty($mime) || ($this->isGifImagesEnabled !== FALSE && $mime == "image/gif")) {
+                               $image_o = imagecreatefromstring($image);
+                               $image_p = imagecreatetruecolor($width*$ratio, $height*$ratio);
+                               
+                               if ($mime == "image/png") {
+                                       imagealphablending($image_p, false);
+                                       imagesavealpha($image_p, true);  
+                                       imagealphablending($image_o, true);
+                                       
+                                       imagecopyresampled($image_p, $image_o, 0, 0, 0, 0, ($width*$ratio), ($height*$ratio), $width, $height);
+                                       ob_start();
+                                       imagepng($image_p, NULL, 9);
+                                       $image = ob_get_contents();
+                                       ob_end_clean();
+
+                                       $ext = "png";
+                               } else {
+                                       imagecopyresampled($image_p, $image_o, 0, 0, 0, 0, ($width*$ratio), ($height*$ratio), $width, $height);
+                                       ob_start();
+                                       imagejpeg($image_p, NULL, 80);
+                                       $image = ob_get_contents();
+                                       ob_end_clean();
+
+                                       $mime = "image/jpeg";
+                                       $ext = "jpg";
+                               }
+                               imagedestroy($image_o);
+                               imagedestroy($image_p);
+                       }
+        }
+
+               if ($ext === "") {
+                       static $mimeToExt = array (
+                               'image/jpeg' => 'jpg',
+                               'image/gif' => 'gif',
+                               'image/png' => 'png'
+            );
+
+                       if (isset($mimeToExt[$mime])) {
+                               $ext = $mimeToExt[$mime];
+                       }
+               }
+
+        $rv = array();
+        $rv['width'] = $width*$ratio;
+        $rv['height'] = $height*$ratio;
+        $rv['mime'] = $mime;
+        $rv['image'] = $image;
+        $rv['ext'] = $ext;
+
+        return $rv;
+    }
+
+    /**
+     * Get file contents, using curl if available, else file_get_contents
+     *
+     * @param string $source
+     * @return bool
+     */
+    function getFileContents($source, $toTempFile = FALSE) {
+        $isExternal = preg_match('#^(http|ftp)s?://#i', $source) == 1;
+
+        if ($isExternal && $this->isCurlInstalled) {
+            $ch = curl_init();
+                       $outFile = NULL;
+                       $fp = NULL;
+                       $res = FALSE;
+                       $info = array('http_code' => 500);
+                       
+                   curl_setopt($ch, CURLOPT_HEADER, 0); 
+            curl_setopt($ch, CURLOPT_URL, str_replace(" ","%20",$source));
+            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+                       curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
+                       curl_setopt($ch, CURLOPT_BUFFERSIZE, 4096);
+                       
+                       if ($toTempFile) {
+                               $outFile = tempnam(sys_get_temp_dir(), "EPub_v" . EPub::VERSION . "_");
+                               $fp = fopen($outFile, "w+b");
+                               curl_setopt($ch, CURLOPT_FILE, $fp); 
+
+                               $res = curl_exec($ch);
+                               $info = curl_getinfo($ch);
+                               
+                               curl_close($ch);
+                               fclose($fp);
+                       } else {
+                               $res = curl_exec($ch);
+                               $info = curl_getinfo($ch);
+                               
+                               curl_close($ch);
+                       }
+
+            if ($info['http_code'] == 200 && $res != false) {
+                               if ($toTempFile) {
+                                       return $outFile;
+                               }
+                return $res;
+            }
+                       return FALSE;
+        }
+
+        if ($this->isFileGetContentsInstalled && (!$isExternal || $this->isFileGetContentsExtInstalled)) {
+            @$data = file_get_contents($source);
+            return $data;
+        }
+        return FALSE;
+    }
+
+    /**
+    * get mime type from image data
+    *
+    * By fireweasel found on http://stackoverflow.com/questions/2207095/get-image-mimetype-from-resource-in-php-gd
+    * @staticvar array $type
+    * @param object $binary
+    * @return string
+    */
+    function image_file_type_from_binary($binary) {
+        $hits = 0;
+        if (!preg_match(
+                '/\A(?:(\xff\xd8\xff)|(GIF8[79]a)|(\x89PNG\x0d\x0a)|(BM)|(\x49\x49(?:\x2a\x00|\x00\x4a))|(FORM.{4}ILBM))/',
+                $binary, $hits)) {
+            return 'application/octet-stream';
+        }
+        static $type = array (
+            1 => 'image/jpeg',
+            2 => 'image/gif',
+            3 => 'image/png',
+            4 => 'image/x-windows-bmp',
+            5 => 'image/tiff',
+            6 => 'image/x-ilbm',
+        );
+        return $type[count($hits) - 1];
+    }
+
+       /**
+        * @param string $source URL Source
+        * @return string MimeType
+        */
+    function getMimeTypeFromUrl($source) {
+        $ext = FALSE;
+
+        $srev = strrev($source);
+        $pos = strpos($srev, "?");
+        if ($pos !== FALSE) {
+            $srev = substr($srev, $pos+1);
+        }
+
+        $pos = strpos($srev, ".");
+        if ($pos !== FALSE) {
+            $ext = strtolower(strrev(substr($srev, 0, $pos)));
+        }
+
+        if ($ext !== FALSE) {
+            return $this->getMimeTypeFromExtension($ext);
+        }
+        return "application/octet-stream";
+    }
+
+       /**
+        * @param string $ext Extension
+        * @return string MimeType
+        */
+       function getMimeTypeFromExtension($ext) {
+               switch ($ext) {
+                       case "jpg":
+                       case "jpe":
+                       case "jpeg":
+                               return 'image/jpeg';
+                       case "gif":
+                               return 'image/gif';
+                       case "png":
+                               return 'image/png';
+                       case "bmp":
+                               return 'image/x-windows-bmp';
+                       case "tif":
+                       case "tiff":
+                       case "cpt":
+                               return 'image/tiff';
+                       case "lbm":
+                       case "ilbm":
+                               return 'image/x-ilbm';
+                       default:
+                               return "application/octet-stream";
+               }
+       }
+
+    /**
+     * Encode html code to use html entities, safeguarding it from potential character encoding peoblems
+     * This function is a bit different from the vanilla htmlentities function in that it does not encode html tags.
+     *
+     * The regexp is taken from the PHP Manual discussion, it was written by user "busbyjon".
+     * http://www.php.net/manual/en/function.htmlentities.php#90111
+     *
+     * @param string $string string to encode.
+     */
+    public function encodeHtml($string) {
+        $string = strtr($string, $this->html_encoding_characters);
+
+        //return preg_replace("/&amp;(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,5};)/", "&\\1", $string);
+        //return preg_replace("/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,5};)/", "&amp;", $string);
+        return $string;
+    }
+
+    /**
+     * Helper function to create a DOM fragment with given markup.
+     *
+     * @author Adam Schmalhofer
+     *
+     * @param DOMDocument $dom
+     * @param string $markup
+     * @return DOMNode fragment in a node.
+     */
+    protected function createDomFragment($dom, $markup) {
+        $node = $dom->createDocumentFragment();
+        $node->appendXML($markup);
+        return $node;
+    }
+
+    /**
+     * Retrieve an array of file names currently added to the book.
+     * $key is the filename used in the book
+     * $value is the original filename, will be the same as $key for most entries
+     *
+     * @return array file list
+     */
+    function getFileList() {
+        return $this->fileList;
+    }
+
+    /**
+     * @deprecated Use Zip::getRelativePath($relPath) instead.
+     */
+    function relPath($relPath) {
+        die ("Function was deprecated, use Zip::getRelativePath(\$relPath); instead");
+    }
+
+    /**
+     * Set default chapter target size.
+     * Default is 250000 bytes, and minimum is 10240 bytes.
+     *
+     * @param int $size segment size in bytes
+     * @return void
+     */
+    function setSplitSize($size) {
+        $this->splitDefaultSize = (int)$size;
+        if ($size < 10240) {
+            $this->splitDefaultSize = 10240; // Making the file smaller than 10k is not a good idea.
+        }
+    }
+
+    /**
+     * Get the chapter target size.
+     *
+     * @return $size
+     */
+    function getSplitSize() {
+        return $this->splitDefaultSize;
+    }
+
+    /**
+     * Remove all non essential html tags and entities.
+     *
+        * @global type $htmlEntities
+        * @param string $string
+        * @return string with the stripped entities.
+        */
+    function decodeHtmlEntities($string) {
+        global $htmlEntities;
+
+        $string = preg_replace('~\s*<br\s*/*\s*>\s*~i', "\n", $string);
+        $string = preg_replace('~\s*</(p|div)\s*>\s*~i', "\n\n", $string);
+        $string = preg_replace('~<[^>]*>~', '', $string);
+
+        $string = strtr($string, $htmlEntities);
+
+        $string = str_replace('&', '&amp;', $string);
+        $string = str_replace('&amp;amp;', '&amp;', $string);
+        $string = preg_replace('~&amp;(#x*[a-fA-F0-9]+;)~', '&\1', $string);
+        $string = str_replace('<', '&lt;', $string);
+        $string = str_replace('>', '&gt;', $string);
+
+        return $string;
+       }
+
+    /**
+     * Simply remove all HTML tags, brute force and no finesse.
+     *
+     * @param string $string html
+     * @return string
+     */
+    function html2text($string) {
+        return preg_replace('~<[^>]*>~', '', $string);
+    }
+
+       /**
+        * @return string
+        */
+       function getLog() {
+        return $this->log->getLog();
+    }
+}
diff --git a/inc/3rdparty/libraries/PHPePub/EPubChapterSplitter.php b/inc/3rdparty/libraries/PHPePub/EPubChapterSplitter.php
new file mode 100644 (file)
index 0000000..1d44f23
--- /dev/null
@@ -0,0 +1,201 @@
+<?php
+/**
+ * Split an HTML file into smaller html files, retaining the formatting and structure for the individual parts.
+ * What this splitter does is using DOM to try and retain any formatting in the file, including rebuilding the DOM tree for subsequent parts.
+ * Split size is considered max target size. The actual size is the result of an even split across the resulting files.
+ *
+ * @author A. Grandt <php@grandt.com>
+ * @copyright 2009-2014 A. Grandt
+ * @license GNU LGPL 2.1
+ * @link http://www.phpclasses.org/package/6115
+ * @link https://github.com/Grandt/PHPePub
+ * @version 3.20
+ */
+class EPubChapterSplitter {
+    const VERSION = 3.20;
+
+    private $splitDefaultSize = 250000;
+    private $bookVersion = EPub::BOOK_VERSION_EPUB2;
+
+    /**
+     *
+     * Enter description here ...
+     *
+     * @param unknown_type $ident
+     */
+    function setVersion($bookVersion) {
+        $this->bookVersion = is_string($bookVersion) ? trim($bookVersion) : EPub::BOOK_VERSION_EPUB2;
+    }
+
+       /**
+     * Set default chapter target size.
+     * Default is 250000 bytes, and minimum is 10240 bytes.
+     *
+     * @param $size segment size in bytes
+     * @return void
+     */
+    function setSplitSize($size) {
+        $this->splitDefaultSize = (int)$size;
+        if ($size < 10240) {
+            $this->splitDefaultSize = 10240; // Making the file smaller than 10k is not a good idea.
+        }
+    }
+
+    /**
+     * Get the chapter target size.
+     *
+     * @return $size
+     */
+    function getSplitSize() {
+        return $this->splitDefaultSize;
+    }
+
+    /**
+     * Split $chapter into multiple parts.
+     *
+     * The search string can either be a regular string or a PHP PECL Regular Expression pattern as defined here: http://www.php.net/manual/en/pcre.pattern.php
+     * If the search string is a regular string, the matching will be for lines in the HTML starting with the string given
+     *
+     * @param String $chapter XHTML file
+     * @param Bool   $splitOnSearchString Split on chapter boundaries, Splitting on search strings disables the split size check.
+     * @param String $searchString Chapter string to search for can be fixed text, or a regular expression pattern.
+     *
+     * @return array with 1 or more parts
+     */
+    function splitChapter($chapter, $splitOnSearchString = false, $searchString = '/^Chapter\\ /i') {
+        $chapterData = array();
+        $isSearchRegexp = $splitOnSearchString && (preg_match('#^(\D|\S|\W).+\1[imsxeADSUXJu]*$#m', $searchString) == 1);
+        if ($splitOnSearchString && !$isSearchRegexp) {
+            $searchString = '#^<.+?>' . preg_quote($searchString, '#') . "#";
+        }
+
+        if (!$splitOnSearchString && strlen($chapter) <= $this->splitDefaultSize) {
+            return array($chapter);
+        }
+
+        $xmlDoc = new DOMDocument();
+        @$xmlDoc->loadHTML($chapter);
+
+        $head = $xmlDoc->getElementsByTagName("head");
+        $body = $xmlDoc->getElementsByTagName("body");
+
+        $htmlPos = stripos($chapter, "<html");
+        $htmlEndPos = stripos($chapter, ">", $htmlPos);
+        $newXML = substr($chapter, 0, $htmlEndPos+1) . "\n</html>";
+        if (strpos(trim($newXML), "<?xml ") === FALSE) {
+            $newXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" . $newXML;
+        }
+        $headerLength = strlen($newXML);
+
+        $files = array();
+        $chapterNames = array();
+        $domDepth = 0;
+        $domPath = array();
+        $domClonedPath = array();
+
+        $curFile = $xmlDoc->createDocumentFragment();
+        $files[] = $curFile;
+        $curParent = $curFile;
+        $curSize = 0;
+
+        $bodyLen = strlen($xmlDoc->saveXML($body->item(0)));
+        $headLen = strlen($xmlDoc->saveXML($head->item(0))) + $headerLength;
+
+        $partSize = $this->splitDefaultSize - $headLen;
+
+        if ($bodyLen > $partSize) {
+            $parts = ceil($bodyLen / $partSize);
+            $partSize = ($bodyLen / $parts)  - $headLen;
+        }
+
+        $node = $body->item(0)->firstChild;
+
+        do {
+            $nodeData = $xmlDoc->saveXML($node);
+            $nodeLen = strlen($nodeData);
+
+            if ($nodeLen > $partSize && $node->hasChildNodes()) {
+                $domPath[] = $node;
+                $domClonedPath[] = $node->cloneNode(false);
+                $domDepth++;
+
+                $node = $node->firstChild;
+            }
+
+            $node2 = $node->nextSibling;
+
+            if ($node != null && $node->nodeName != "#text") {
+                $doSplit = false;
+                if ($splitOnSearchString) {
+                    $doSplit = preg_match($searchString, $nodeData) == 1;
+                    if ($doSplit) {
+                        $chapterNames[] = trim($nodeData);
+                    }
+                }
+
+                if ($curSize > 0 && ($doSplit || (!$splitOnSearchString && $curSize + $nodeLen > $partSize))) {
+                    $curFile = $xmlDoc->createDocumentFragment();
+                    $files[] = $curFile;
+                    $curParent = $curFile;
+                    if ($domDepth > 0) {
+                        reset($domPath);
+                        reset($domClonedPath);
+                        $oneDomClonedPath = each($domClonedPath);
+                        while ($oneDomClonedPath) {
+                            list($k, $v) = $oneDomClonedPath;
+                            $newParent = $v->cloneNode(false);
+                            $curParent->appendChild($newParent);
+                            $curParent = $newParent;
+                            $oneDomClonedPath = each($domClonedPath);
+                        }
+                    }
+                    $curSize = strlen($xmlDoc->saveXML($curFile));
+                }
+                $curParent->appendChild($node->cloneNode(true));
+                $curSize += $nodeLen;
+            }
+
+            $node = $node2;
+            while ($node == null && $domDepth > 0) {
+                $domDepth--;
+                $node = end($domPath)->nextSibling;
+                array_pop($domPath);
+                array_pop($domClonedPath);
+                $curParent = $curParent->parentNode;
+            }
+        } while ($node != null);
+
+        $curFile = null;
+        $curSize = 0;
+
+        $xml = new DOMDocument('1.0', $xmlDoc->xmlEncoding);
+        $xml->lookupPrefix("http://www.w3.org/1999/xhtml");
+        $xml->preserveWhiteSpace = false;
+        $xml->formatOutput = true;
+
+        for ($idx = 0; $idx < count($files); $idx++) {
+            $xml2Doc = new DOMDocument('1.0', $xmlDoc->xmlEncoding);
+            $xml2Doc->lookupPrefix("http://www.w3.org/1999/xhtml");
+            $xml2Doc->loadXML($newXML);
+            $html = $xml2Doc->getElementsByTagName("html")->item(0);
+            $html->appendChild($xml2Doc->importNode($head->item(0), true));
+            $body = $xml2Doc->createElement("body");
+            $html->appendChild($body);
+            $body->appendChild($xml2Doc->importNode($files[$idx], true));
+
+            // force pretty printing and correct formatting, should not be needed, but it is.
+            $xml->loadXML($xml2Doc->saveXML());
+
+                       $doc = $xml->saveXML();
+
+                       if ($this->bookVersion === EPub::BOOK_VERSION_EPUB3) {
+                               $doc = preg_replace('#^\s*<!DOCTYPE\ .+?>\s*#im', '', $doc);
+                       }
+
+            $chapterData[$splitOnSearchString ? $chapterNames[$idx] : $idx] = $doc;
+        }
+
+        return $chapterData;
+    }
+}
+?>
diff --git a/inc/3rdparty/libraries/PHPePub/Logger.php b/inc/3rdparty/libraries/PHPePub/Logger.php
new file mode 100644 (file)
index 0000000..314019c
--- /dev/null
@@ -0,0 +1,92 @@
+<?php
+/**
+ * Simple log line aggregator.
+ *
+ * @author A. Grandt <php@grandt.com>
+ * @copyright 2012-2013 A. Grandt
+ * @license GNU LGPL, Attribution required for commercial implementations, requested for everything else.
+ * @version 1.00
+ */
+class Logger {
+    const VERSION = 1.00;
+
+    private $log = "";
+    private $tStart;
+    private $tLast;
+    private $name = NULL;
+    private $isLogging = FALSE;
+    private $isDebugging = FALSE;
+
+    /**
+     * Class constructor.
+     *
+     * @return void
+     */
+    function __construct($name = NULL, $isLogging = FALSE) {
+               if ($name === NULL) {
+                       $this->name = "";
+               } else {
+                       $this->name = $name . " : ";
+               }
+        $this->isLogging = $isLogging;
+        $this->start();
+    }
+
+    /**
+     * Class destructor
+     *
+     * @return void
+     * @TODO make sure elements in the destructor match the current class elements
+     */
+    function __destruct() {
+        unset($this->log);
+    }
+
+    function start() {
+        /* Prepare Logging. Just in case it's used. later */
+        if ($this->isLogging) {
+            $this->tStart = gettimeofday();
+            $this->tLast = $this->tStart;
+            $this->log = "<h1>Log: " . $this->name . "</h1>\n<pre>Started: " . gmdate("D, d M Y H:i:s T", $this->tStart['sec']) . "\n &#916; Start ;  &#916; Last  ;";
+                       $this->logLine("Start");
+               }
+    }
+
+    function dumpInstalledModules() {
+        if ($this->isLogging) {
+            $isCurlInstalled = extension_loaded('curl') && function_exists('curl_version');
+            $isGdInstalled = extension_loaded('gd') && function_exists('gd_info');
+            $isExifInstalled = extension_loaded('exif') && function_exists('exif_imagetype');
+            $isFileGetContentsInstalled = function_exists('file_get_contents');
+            $isFileGetContentsExtInstalled = $isFileGetContentsInstalled && ini_get('allow_url_fopen');
+
+            $this->logLine("isCurlInstalled...............: " . ($isCurlInstalled ? "Yes" : "No"));
+            $this->logLine("isGdInstalled.................: " . ($isGdInstalled ? "Yes" : "No"));
+            $this->logLine("isExifInstalled...............: " . ($isExifInstalled ? "Yes" : "No"));
+            $this->logLine("isFileGetContentsInstalled....: " . ($isFileGetContentsInstalled ? "Yes" : "No"));
+            $this->logLine("isFileGetContentsExtInstalled.: " . ($isFileGetContentsExtInstalled ? "Yes" : "No"));
+        }
+    }
+
+    function logLine($line) {
+        if ($this->isLogging) {
+            $tTemp = gettimeofday();
+            $tS = $this->tStart['sec'] + (((int)($this->tStart['usec']/100))/10000);
+            $tL = $this->tLast['sec'] + (((int)($this->tLast['usec']/100))/10000);
+            $tT = $tTemp['sec'] + (((int)($tTemp['usec']/100))/10000);
+
+                       $logline = sprintf("\n+%08.04f; +%08.04f; ", ($tT-$tS), ($tT-$tL)) . $this->name . $line;
+            $this->log .= $logline;
+            $this->tLast = $tTemp;
+
+                   if ($this->isDebugging) {
+                               echo "<pre>" . $logline . "\n</pre>\n";
+                       }
+        }
+    }
+
+    function getLog() {
+        return $this->log;
+    }
+}
+?>
\ No newline at end of file
diff --git a/inc/3rdparty/libraries/PHPePub/Zip.php b/inc/3rdparty/libraries/PHPePub/Zip.php
new file mode 100644 (file)
index 0000000..01e0356
--- /dev/null
@@ -0,0 +1,818 @@
+<?php
+/**
+ * Class to create and manage a Zip file.
+ *
+ * Initially inspired by CreateZipFile by Rochak Chauhan  www.rochakchauhan.com (http://www.phpclasses.org/browse/package/2322.html)
+ * and
+ * http://www.pkware.com/documents/casestudies/APPNOTE.TXT Zip file specification.
+ *
+ * License: GNU LGPL, Attribution required for commercial implementations, requested for everything else.
+ *
+ * @author A. Grandt <php@grandt.com>
+ * @copyright 2009-2014 A. Grandt
+ * @license GNU LGPL 2.1
+ * @link http://www.phpclasses.org/package/6110
+ * @link https://github.com/Grandt/PHPZip
+ * @version 1.60
+ */
+class Zip {
+    const VERSION = 1.60;
+
+    const ZIP_LOCAL_FILE_HEADER = "\x50\x4b\x03\x04"; // Local file header signature
+    const ZIP_CENTRAL_FILE_HEADER = "\x50\x4b\x01\x02"; // Central file header signature
+    const ZIP_END_OF_CENTRAL_DIRECTORY = "\x50\x4b\x05\x06\x00\x00\x00\x00"; //end of Central directory record
+
+    const EXT_FILE_ATTR_DIR = 010173200020;  // Permission 755 drwxr-xr-x = (((S_IFDIR | 0755) << 16) | S_DOS_D);
+    const EXT_FILE_ATTR_FILE = 020151000040; // Permission 644 -rw-r--r-- = (((S_IFREG | 0644) << 16) | S_DOS_A);
+
+    const ATTR_VERSION_TO_EXTRACT = "\x14\x00"; // Version needed to extract
+    const ATTR_MADE_BY_VERSION = "\x1E\x03"; // Made By Version
+
+       // Unix file types
+       const S_IFIFO  = 0010000; // named pipe (fifo)
+       const S_IFCHR  = 0020000; // character special
+       const S_IFDIR  = 0040000; // directory
+       const S_IFBLK  = 0060000; // block special
+       const S_IFREG  = 0100000; // regular
+       const S_IFLNK  = 0120000; // symbolic link
+       const S_IFSOCK = 0140000; // socket
+
+       // setuid/setgid/sticky bits, the same as for chmod:
+
+       const S_ISUID  = 0004000; // set user id on execution
+       const S_ISGID  = 0002000; // set group id on execution
+       const S_ISTXT  = 0001000; // sticky bit
+
+       // And of course, the other 12 bits are for the permissions, the same as for chmod:
+       // When addding these up, you can also just write the permissions as a simgle octal number
+       // ie. 0755. The leading 0 specifies octal notation.
+       const S_IRWXU  = 0000700; // RWX mask for owner
+       const S_IRUSR  = 0000400; // R for owner
+       const S_IWUSR  = 0000200; // W for owner
+       const S_IXUSR  = 0000100; // X for owner
+       const S_IRWXG  = 0000070; // RWX mask for group
+       const S_IRGRP  = 0000040; // R for group
+       const S_IWGRP  = 0000020; // W for group
+       const S_IXGRP  = 0000010; // X for group
+       const S_IRWXO  = 0000007; // RWX mask for other
+       const S_IROTH  = 0000004; // R for other
+       const S_IWOTH  = 0000002; // W for other
+       const S_IXOTH  = 0000001; // X for other
+       const S_ISVTX  = 0001000; // save swapped text even after use
+
+       // Filetype, sticky and permissions are added up, and shifted 16 bits left BEFORE adding the DOS flags.
+
+       // DOS file type flags, we really only use the S_DOS_D flag.
+
+       const S_DOS_A  = 0000040; // DOS flag for Archive
+       const S_DOS_D  = 0000020; // DOS flag for Directory
+       const S_DOS_V  = 0000010; // DOS flag for Volume
+       const S_DOS_S  = 0000004; // DOS flag for System
+       const S_DOS_H  = 0000002; // DOS flag for Hidden
+       const S_DOS_R  = 0000001; // DOS flag for Read Only
+
+    private $zipMemoryThreshold = 1048576; // Autocreate tempfile if the zip data exceeds 1048576 bytes (1 MB)
+
+    private $zipData = NULL;
+    private $zipFile = NULL;
+    private $zipComment = NULL;
+    private $cdRec = array(); // central directory
+    private $offset = 0;
+    private $isFinalized = FALSE;
+    private $addExtraField = TRUE;
+
+    private $streamChunkSize = 65536;
+    private $streamFilePath = NULL;
+    private $streamTimestamp = NULL;
+    private $streamFileComment = NULL;
+    private $streamFile = NULL;
+    private $streamData = NULL;
+    private $streamFileLength = 0;
+       private $streamExtFileAttr = null;
+
+    /**
+     * Constructor.
+     *
+     * @param boolean $useZipFile Write temp zip data to tempFile? Default FALSE
+     */
+    function __construct($useZipFile = FALSE) {
+        if ($useZipFile) {
+            $this->zipFile = tmpfile();
+        } else {
+            $this->zipData = "";
+        }
+    }
+
+    function __destruct() {
+        if (is_resource($this->zipFile)) {
+            fclose($this->zipFile);
+        }
+        $this->zipData = NULL;
+    }
+
+    /**
+     * Extra fields on the Zip directory records are Unix time codes needed for compatibility on the default Mac zip archive tool.
+     * These are enabled as default, as they do no harm elsewhere and only add 26 bytes per file added.
+     *
+     * @param bool $setExtraField TRUE (default) will enable adding of extra fields, anything else will disable it.
+     */
+    function setExtraField($setExtraField = TRUE) {
+        $this->addExtraField = ($setExtraField === TRUE);
+    }
+
+    /**
+     * Set Zip archive comment.
+     *
+     * @param string $newComment New comment. NULL to clear.
+     * @return bool $success
+     */
+    public function setComment($newComment = NULL) {
+        if ($this->isFinalized) {
+            return FALSE;
+        }
+        $this->zipComment = $newComment;
+
+        return TRUE;
+    }
+
+    /**
+     * Set zip file to write zip data to.
+     * This will cause all present and future data written to this class to be written to this file.
+     * This can be used at any time, even after the Zip Archive have been finalized. Any previous file will be closed.
+     * Warning: If the given file already exists, it will be overwritten.
+     *
+     * @param string $fileName
+     * @return bool $success
+     */
+    public function setZipFile($fileName) {
+        if (is_file($fileName)) {
+            unlink($fileName);
+        }
+        $fd=fopen($fileName, "x+b");
+        if (is_resource($this->zipFile)) {
+            rewind($this->zipFile);
+            while (!feof($this->zipFile)) {
+                fwrite($fd, fread($this->zipFile, $this->streamChunkSize));
+            }
+
+            fclose($this->zipFile);
+        } else {
+            fwrite($fd, $this->zipData);
+            $this->zipData = NULL;
+        }
+        $this->zipFile = $fd;
+
+        return TRUE;
+    }
+
+    /**
+     * Add an empty directory entry to the zip archive.
+     * Basically this is only used if an empty directory is added.
+     *
+     * @param string $directoryPath Directory Path and name to be added to the archive.
+     * @param int    $timestamp     (Optional) Timestamp for the added directory, if omitted or set to 0, the current time will be used.
+     * @param string $fileComment   (Optional) Comment to be added to the archive for this directory. To use fileComment, timestamp must be given.
+        * @param int    $extFileAttr   (Optional) The external file reference, use generateExtAttr to generate this.
+     * @return bool $success
+     */
+    public function addDirectory($directoryPath, $timestamp = 0, $fileComment = NULL, $extFileAttr = self::EXT_FILE_ATTR_DIR) {
+        if ($this->isFinalized) {
+            return FALSE;
+        }
+        $directoryPath = str_replace("\\", "/", $directoryPath);
+        $directoryPath = rtrim($directoryPath, "/");
+
+        if (strlen($directoryPath) > 0) {
+            $this->buildZipEntry($directoryPath.'/', $fileComment, "\x00\x00", "\x00\x00", $timestamp, "\x00\x00\x00\x00", 0, 0, $extFileAttr);
+            return TRUE;
+        }
+        return FALSE;
+    }
+
+    /**
+     * Add a file to the archive at the specified location and file name.
+     *
+     * @param string $data        File data.
+     * @param string $filePath    Filepath and name to be used in the archive.
+     * @param int    $timestamp   (Optional) Timestamp for the added file, if omitted or set to 0, the current time will be used.
+     * @param string $fileComment (Optional) Comment to be added to the archive for this file. To use fileComment, timestamp must be given.
+     * @param bool   $compress    (Optional) Compress file, if set to FALSE the file will only be stored. Default TRUE.
+        * @param int    $extFileAttr (Optional) The external file reference, use generateExtAttr to generate this.
+     * @return bool $success
+     */
+    public function addFile($data, $filePath, $timestamp = 0, $fileComment = NULL, $compress = TRUE, $extFileAttr = self::EXT_FILE_ATTR_FILE) {
+        if ($this->isFinalized) {
+            return FALSE;
+        }
+
+        if (is_resource($data) && get_resource_type($data) == "stream") {
+            $this->addLargeFile($data, $filePath, $timestamp, $fileComment, $extFileAttr);
+            return FALSE;
+        }
+
+        $gzData = "";
+        $gzType = "\x08\x00"; // Compression type 8 = deflate
+        $gpFlags = "\x00\x00"; // General Purpose bit flags for compression type 8 it is: 0=Normal, 1=Maximum, 2=Fast, 3=super fast compression.
+        $dataLength = strlen($data);
+        $fileCRC32 = pack("V", crc32($data));
+
+        if ($compress) {
+            $gzTmp = gzcompress($data);
+            $gzData = substr(substr($gzTmp, 0, strlen($gzTmp) - 4), 2); // gzcompress adds a 2 byte header and 4 byte CRC we can't use.
+            // The 2 byte header does contain useful data, though in this case the 2 parameters we'd be interrested in will always be 8 for compression type, and 2 for General purpose flag.
+            $gzLength = strlen($gzData);
+        } else {
+            $gzLength = $dataLength;
+        }
+
+        if ($gzLength >= $dataLength) {
+            $gzLength = $dataLength;
+            $gzData = $data;
+            $gzType = "\x00\x00"; // Compression type 0 = stored
+            $gpFlags = "\x00\x00"; // Compression type 0 = stored
+        }
+
+        if (!is_resource($this->zipFile) && ($this->offset + $gzLength) > $this->zipMemoryThreshold) {
+            $this->zipflush();
+        }
+
+        $this->buildZipEntry($filePath, $fileComment, $gpFlags, $gzType, $timestamp, $fileCRC32, $gzLength, $dataLength, $extFileAttr);
+
+        $this->zipwrite($gzData);
+
+        return TRUE;
+    }
+
+    /**
+     * Add the content to a directory.
+     *
+     * @author Adam Schmalhofer <Adam.Schmalhofer@gmx.de>
+     * @author A. Grandt
+     *
+     * @param string $realPath       Path on the file system.
+     * @param string $zipPath        Filepath and name to be used in the archive.
+     * @param bool   $recursive      Add content recursively, default is TRUE.
+     * @param bool   $followSymlinks Follow and add symbolic links, if they are accessible, default is TRUE.
+     * @param array &$addedFiles     Reference to the added files, this is used to prevent duplicates, efault is an empty array.
+     *                               If you start the function by parsing an array, the array will be populated with the realPath
+     *                               and zipPath kay/value pairs added to the archive by the function.
+        * @param bool   $overrideFilePermissions Force the use of the file/dir permissions set in the $extDirAttr
+        *                                                           and $extFileAttr parameters.
+        * @param int    $extDirAttr     Permissions for directories.
+        * @param int    $extFileAttr    Permissions for files.
+     */
+    public function addDirectoryContent($realPath, $zipPath, $recursive = TRUE, $followSymlinks = TRUE, &$addedFiles = array(),
+                                       $overrideFilePermissions = FALSE, $extDirAttr = self::EXT_FILE_ATTR_DIR, $extFileAttr = self::EXT_FILE_ATTR_FILE) {
+        if (file_exists($realPath) && !isset($addedFiles[realpath($realPath)])) {
+            if (is_dir($realPath)) {
+                               if ($overrideFilePermissions) {
+                       $this->addDirectory($zipPath, 0, null, $extDirAttr);
+                               } else {
+                                       $this->addDirectory($zipPath, 0, null, self::getFileExtAttr($realPath));
+                               }
+            }
+
+            $addedFiles[realpath($realPath)] = $zipPath;
+
+            $iter = new DirectoryIterator($realPath);
+            foreach ($iter as $file) {
+                if ($file->isDot()) {
+                    continue;
+                }
+                $newRealPath = $file->getPathname();
+                $newZipPath = self::pathJoin($zipPath, $file->getFilename());
+
+                if (file_exists($newRealPath) && ($followSymlinks === TRUE || !is_link($newRealPath))) {
+                    if ($file->isFile()) {
+                        $addedFiles[realpath($newRealPath)] = $newZipPath;
+                                               if ($overrideFilePermissions) {
+                                                       $this->addLargeFile($newRealPath, $newZipPath, 0, null, $extFileAttr);
+                                               } else {
+                                                       $this->addLargeFile($newRealPath, $newZipPath, 0, null, self::getFileExtAttr($newRealPath));
+                                               }
+                    } else if ($recursive === TRUE) {
+                        $this->addDirectoryContent($newRealPath, $newZipPath, $recursive, $followSymlinks, $addedFiles, $overrideFilePermissions, $extDirAttr, $extFileAttr);
+                    } else {
+                                               if ($overrideFilePermissions) {
+                                                       $this->addDirectory($zipPath, 0, null, $extDirAttr);
+                                               } else {
+                                                       $this->addDirectory($zipPath, 0, null, self::getFileExtAttr($newRealPath));
+                                               }
+                    }
+                }
+            }
+        }
+    }
+
+    /**
+     * Add a file to the archive at the specified location and file name.
+     *
+     * @param string $dataFile    File name/path.
+     * @param string $filePath    Filepath and name to be used in the archive.
+     * @param int    $timestamp   (Optional) Timestamp for the added file, if omitted or set to 0, the current time will be used.
+     * @param string $fileComment (Optional) Comment to be added to the archive for this file. To use fileComment, timestamp must be given.
+        * @param int    $extFileAttr (Optional) The external file reference, use generateExtAttr to generate this.
+     * @return bool $success
+     */
+    public function addLargeFile($dataFile, $filePath, $timestamp = 0, $fileComment = NULL, $extFileAttr = self::EXT_FILE_ATTR_FILE)   {
+        if ($this->isFinalized) {
+            return FALSE;
+        }
+
+        if (is_string($dataFile) && is_file($dataFile)) {
+            $this->processFile($dataFile, $filePath, $timestamp, $fileComment, $extFileAttr);
+        } else if (is_resource($dataFile) && get_resource_type($dataFile) == "stream") {
+            $fh = $dataFile;
+            $this->openStream($filePath, $timestamp, $fileComment, $extFileAttr);
+
+            while (!feof($fh)) {
+                $this->addStreamData(fread($fh, $this->streamChunkSize));
+            }
+            $this->closeStream($this->addExtraField);
+        }
+        return TRUE;
+    }
+
+    /**
+     * Create a stream to be used for large entries.
+     *
+     * @param string $filePath    Filepath and name to be used in the archive.
+     * @param int    $timestamp   (Optional) Timestamp for the added file, if omitted or set to 0, the current time will be used.
+     * @param string $fileComment (Optional) Comment to be added to the archive for this file. To use fileComment, timestamp must be given.
+        * @param int    $extFileAttr (Optional) The external file reference, use generateExtAttr to generate this.
+     * @return bool $success
+     */
+    public function openStream($filePath, $timestamp = 0, $fileComment = null, $extFileAttr = self::EXT_FILE_ATTR_FILE)   {
+        if (!function_exists('sys_get_temp_dir')) {
+            die ("ERROR: Zip " . self::VERSION . " requires PHP version 5.2.1 or above if large files are used.");
+        }
+
+        if ($this->isFinalized) {
+            return FALSE;
+        }
+
+        $this->zipflush();
+
+        if (strlen($this->streamFilePath) > 0) {
+            $this->closeStream();
+        }
+
+        $this->streamFile = tempnam(sys_get_temp_dir(), 'Zip');
+        $this->streamData = fopen($this->streamFile, "wb");
+        $this->streamFilePath = $filePath;
+        $this->streamTimestamp = $timestamp;
+        $this->streamFileComment = $fileComment;
+        $this->streamFileLength = 0;
+               $this->streamExtFileAttr = $extFileAttr;
+
+        return TRUE;
+    }
+
+    /**
+     * Add data to the open stream.
+     *
+     * @param string $data
+     * @return mixed length in bytes added or FALSE if the archive is finalized or there are no open stream.
+     */
+    public function addStreamData($data) {
+        if ($this->isFinalized || strlen($this->streamFilePath) == 0) {
+            return FALSE;
+        }
+
+        $length = fwrite($this->streamData, $data, strlen($data));
+        if ($length != strlen($data)) {
+            die ("<p>Length mismatch</p>\n");
+        }
+        $this->streamFileLength += $length;
+
+        return $length;
+    }
+
+    /**
+     * Close the current stream.
+     *
+     * @return bool $success
+     */
+    public function closeStream() {
+        if ($this->isFinalized || strlen($this->streamFilePath) == 0) {
+            return FALSE;
+        }
+
+        fflush($this->streamData);
+        fclose($this->streamData);
+
+        $this->processFile($this->streamFile, $this->streamFilePath, $this->streamTimestamp, $this->streamFileComment, $this->streamExtFileAttr);
+
+        $this->streamData = null;
+        $this->streamFilePath = null;
+        $this->streamTimestamp = null;
+        $this->streamFileComment = null;
+        $this->streamFileLength = 0;
+               $this->streamExtFileAttr = null;
+
+        // Windows is a little slow at times, so a millisecond later, we can unlink this.
+        unlink($this->streamFile);
+
+        $this->streamFile = null;
+
+        return TRUE;
+    }
+
+    private function processFile($dataFile, $filePath, $timestamp = 0, $fileComment = null, $extFileAttr = self::EXT_FILE_ATTR_FILE) {
+        if ($this->isFinalized) {
+            return FALSE;
+        }
+
+        $tempzip = tempnam(sys_get_temp_dir(), 'ZipStream');
+
+        $zip = new ZipArchive;
+        if ($zip->open($tempzip) === TRUE) {
+            $zip->addFile($dataFile, 'file');
+            $zip->close();
+        }
+
+        $file_handle = fopen($tempzip, "rb");
+        $stats = fstat($file_handle);
+        $eof = $stats['size']-72;
+
+        fseek($file_handle, 6);
+
+        $gpFlags = fread($file_handle, 2);
+        $gzType = fread($file_handle, 2);
+        fread($file_handle, 4);
+        $fileCRC32 = fread($file_handle, 4);
+        $v = unpack("Vval", fread($file_handle, 4));
+        $gzLength = $v['val'];
+        $v = unpack("Vval", fread($file_handle, 4));
+        $dataLength = $v['val'];
+
+        $this->buildZipEntry($filePath, $fileComment, $gpFlags, $gzType, $timestamp, $fileCRC32, $gzLength, $dataLength, $extFileAttr);
+
+        fseek($file_handle, 34);
+        $pos = 34;
+
+        while (!feof($file_handle) && $pos < $eof) {
+            $datalen = $this->streamChunkSize;
+            if ($pos + $this->streamChunkSize > $eof) {
+                $datalen = $eof-$pos;
+            }
+            $data = fread($file_handle, $datalen);
+            $pos += $datalen;
+
+            $this->zipwrite($data);
+        }
+
+        fclose($file_handle);
+
+        unlink($tempzip);
+    }
+
+    /**
+     * Close the archive.
+     * A closed archive can no longer have new files added to it.
+     *
+     * @return bool $success
+     */
+    public function finalize() {
+        if (!$this->isFinalized) {
+            if (strlen($this->streamFilePath) > 0) {
+                $this->closeStream();
+            }
+            $cd = implode("", $this->cdRec);
+
+            $cdRecSize = pack("v", sizeof($this->cdRec));
+            $cdRec = $cd . self::ZIP_END_OF_CENTRAL_DIRECTORY
+            . $cdRecSize . $cdRecSize
+            . pack("VV", strlen($cd), $this->offset);
+            if (!empty($this->zipComment)) {
+                $cdRec .= pack("v", strlen($this->zipComment)) . $this->zipComment;
+            } else {
+                $cdRec .= "\x00\x00";
+            }
+
+            $this->zipwrite($cdRec);
+
+            $this->isFinalized = TRUE;
+            $this->cdRec = NULL;
+
+            return TRUE;
+        }
+        return FALSE;
+    }
+
+    /**
+     * Get the handle ressource for the archive zip file.
+     * If the zip haven't been finalized yet, this will cause it to become finalized
+     *
+     * @return zip file handle
+     */
+    public function getZipFile() {
+        if (!$this->isFinalized) {
+            $this->finalize();
+        }
+
+        $this->zipflush();
+
+        rewind($this->zipFile);
+
+        return $this->zipFile;
+    }
+
+    /**
+     * Get the zip file contents
+     * If the zip haven't been finalized yet, this will cause it to become finalized
+     *
+     * @return zip data
+     */
+    public function getZipData() {
+        if (!$this->isFinalized) {
+            $this->finalize();
+        }
+        if (!is_resource($this->zipFile)) {
+            return $this->zipData;
+        } else {
+            rewind($this->zipFile);
+            $filestat = fstat($this->zipFile);
+            return fread($this->zipFile, $filestat['size']);
+        }
+    }
+
+    /**
+     * Send the archive as a zip download
+     *
+     * @param String $fileName The name of the Zip archive, in ISO-8859-1 (or ASCII) encoding, ie. "archive.zip". Optional, defaults to NULL, which means that no ISO-8859-1 encoded file name will be specified.
+     * @param String $contentType Content mime type. Optional, defaults to "application/zip".
+     * @param String $utf8FileName The name of the Zip archive, in UTF-8 encoding. Optional, defaults to NULL, which means that no UTF-8 encoded file name will be specified.
+     * @param bool $inline Use Content-Disposition with "inline" instead of "attached". Optional, defaults to FALSE.
+     * @return bool $success
+     */
+    function sendZip($fileName = null, $contentType = "application/zip", $utf8FileName = null, $inline = false) {
+        if (!$this->isFinalized) {
+            $this->finalize();
+        }
+
+        $headerFile = null;
+        $headerLine = null;
+        if (!headers_sent($headerFile, $headerLine) or die("<p><strong>Error:</strong> Unable to send file $fileName. HTML Headers have already been sent from <strong>$headerFile</strong> in line <strong>$headerLine</strong></p>")) {
+            if ((ob_get_contents() === FALSE || ob_get_contents() == '') or die("\n<p><strong>Error:</strong> Unable to send file <strong>$fileName</strong>. Output buffer contains the following text (typically warnings or errors):<br>" . htmlentities(ob_get_contents()) . "</p>")) {
+                if (ini_get('zlib.output_compression')) {
+                    ini_set('zlib.output_compression', 'Off');
+                }
+
+                header("Pragma: public");
+                header("Last-Modified: " . gmdate("D, d M Y H:i:s T"));
+                header("Expires: 0");
+                header("Accept-Ranges: bytes");
+                header("Connection: close");
+                header("Content-Type: " . $contentType);
+                $cd = "Content-Disposition: ";
+                if ($inline) {
+                    $cd .= "inline";
+                               } else{
+                    $cd .= "attached";
+                               }
+                if ($fileName) {
+                    $cd .= '; filename="' . $fileName . '"';
+                               }
+                if ($utf8FileName) {
+                    $cd .= "; filename*=UTF-8''" . rawurlencode($utf8FileName);
+                               }
+                header($cd);
+                header("Content-Length: ". $this->getArchiveSize());
+
+                if (!is_resource($this->zipFile)) {
+                    echo $this->zipData;
+                } else {
+                    rewind($this->zipFile);
+
+                    while (!feof($this->zipFile)) {
+                        echo fread($this->zipFile, $this->streamChunkSize);
+                    }
+                }
+            }
+            return TRUE;
+        }
+        return FALSE;
+    }
+
+    /**
+     * Return the current size of the archive
+     *
+     * @return $size Size of the archive
+     */
+    public function getArchiveSize() {
+        if (!is_resource($this->zipFile)) {
+            return strlen($this->zipData);
+        }
+        $filestat = fstat($this->zipFile);
+
+        return $filestat['size'];
+    }
+
+    /**
+     * Calculate the 2 byte dostime used in the zip entries.
+     *
+     * @param int $timestamp
+     * @return 2-byte encoded DOS Date
+     */
+    private function getDosTime($timestamp = 0) {
+        $timestamp = (int)$timestamp;
+        $oldTZ = @date_default_timezone_get();
+        date_default_timezone_set('UTC');
+        $date = ($timestamp == 0 ? getdate() : getdate($timestamp));
+        date_default_timezone_set($oldTZ);
+        if ($date["year"] >= 1980) {
+            return pack("V", (($date["mday"] + ($date["mon"] << 5) + (($date["year"]-1980) << 9)) << 16) |
+                    (($date["seconds"] >> 1) + ($date["minutes"] << 5) + ($date["hours"] << 11)));
+        }
+        return "\x00\x00\x00\x00";
+    }
+
+    /**
+     * Build the Zip file structures
+     *
+     * @param string $filePath
+     * @param string $fileComment
+     * @param string $gpFlags
+     * @param string $gzType
+     * @param int    $timestamp
+     * @param string $fileCRC32
+     * @param int    $gzLength
+     * @param int    $dataLength
+     * @param int    $extFileAttr Use self::EXT_FILE_ATTR_FILE for files, self::EXT_FILE_ATTR_DIR for Directories.
+     */
+    private function buildZipEntry($filePath, $fileComment, $gpFlags, $gzType, $timestamp, $fileCRC32, $gzLength, $dataLength, $extFileAttr) {
+        $filePath = str_replace("\\", "/", $filePath);
+        $fileCommentLength = (empty($fileComment) ? 0 : strlen($fileComment));
+        $timestamp = (int)$timestamp;
+        $timestamp = ($timestamp == 0 ? time() : $timestamp);
+
+        $dosTime = $this->getDosTime($timestamp);
+        $tsPack = pack("V", $timestamp);
+
+        $ux = "\x75\x78\x0B\x00\x01\x04\xE8\x03\x00\x00\x04\x00\x00\x00\x00";
+
+        if (!isset($gpFlags) || strlen($gpFlags) != 2) {
+            $gpFlags = "\x00\x00";
+        }
+
+        $isFileUTF8 = mb_check_encoding($filePath, "UTF-8") && !mb_check_encoding($filePath, "ASCII");
+        $isCommentUTF8 = !empty($fileComment) && mb_check_encoding($fileComment, "UTF-8") && !mb_check_encoding($fileComment, "ASCII");
+        if ($isFileUTF8 || $isCommentUTF8) {
+            $flag = 0;
+            $gpFlagsV = unpack("vflags", $gpFlags);
+            if (isset($gpFlagsV['flags'])) {
+                $flag = $gpFlagsV['flags'];
+            }
+            $gpFlags = pack("v", $flag | (1 << 11));
+        }
+
+        $header = $gpFlags . $gzType . $dosTime. $fileCRC32
+        . pack("VVv", $gzLength, $dataLength, strlen($filePath)); // File name length
+
+        $zipEntry  = self::ZIP_LOCAL_FILE_HEADER;
+        $zipEntry .= self::ATTR_VERSION_TO_EXTRACT;
+        $zipEntry .= $header;
+        $zipEntry .= pack("v", ($this->addExtraField ? 28 : 0)); // Extra field length
+        $zipEntry .= $filePath; // FileName
+        // Extra fields
+        if ($this->addExtraField) {
+            $zipEntry .= "\x55\x54\x09\x00\x03" . $tsPack . $tsPack . $ux;
+        }
+        $this->zipwrite($zipEntry);
+
+        $cdEntry  = self::ZIP_CENTRAL_FILE_HEADER;
+        $cdEntry .= self::ATTR_MADE_BY_VERSION;
+        $cdEntry .= ($dataLength === 0 ? "\x0A\x00" : self::ATTR_VERSION_TO_EXTRACT);
+        $cdEntry .= $header;
+        $cdEntry .= pack("v", ($this->addExtraField ? 24 : 0)); // Extra field length
+        $cdEntry .= pack("v", $fileCommentLength); // File comment length
+        $cdEntry .= "\x00\x00"; // Disk number start
+        $cdEntry .= "\x00\x00"; // internal file attributes
+        $cdEntry .= pack("V", $extFileAttr); // External file attributes
+        $cdEntry .= pack("V", $this->offset); // Relative offset of local header
+        $cdEntry .= $filePath; // FileName
+        // Extra fields
+        if ($this->addExtraField) {
+            $cdEntry .= "\x55\x54\x05\x00\x03" . $tsPack . $ux;
+        }
+        if (!empty($fileComment)) {
+            $cdEntry .= $fileComment; // Comment
+        }
+
+        $this->cdRec[] = $cdEntry;
+        $this->offset += strlen($zipEntry) + $gzLength;
+    }
+
+    private function zipwrite($data) {
+        if (!is_resource($this->zipFile)) {
+            $this->zipData .= $data;
+        } else {
+            fwrite($this->zipFile, $data);
+            fflush($this->zipFile);
+        }
+    }
+
+    private function zipflush() {
+        if (!is_resource($this->zipFile)) {
+            $this->zipFile = tmpfile();
+            fwrite($this->zipFile, $this->zipData);
+            $this->zipData = NULL;
+        }
+    }
+
+    /**
+     * Join $file to $dir path, and clean up any excess slashes.
+     *
+     * @param string $dir
+     * @param string $file
+     */
+    public static function pathJoin($dir, $file) {
+        if (empty($dir) || empty($file)) {
+            return self::getRelativePath($dir . $file);
+        }
+        return self::getRelativePath($dir . '/' . $file);
+    }
+
+    /**
+     * Clean up a path, removing any unnecessary elements such as /./, // or redundant ../ segments.
+     * If the path starts with a "/", it is deemed an absolute path and any /../ in the beginning is stripped off.
+     * The returned path will not end in a "/".
+        *
+        * Sometimes, when a path is generated from multiple fragments, 
+        *  you can get something like "../data/html/../images/image.jpeg"
+        * This will normalize that example path to "../data/images/image.jpeg"
+     *
+     * @param string $path The path to clean up
+     * @return string the clean path
+     */
+    public static function getRelativePath($path) {
+        $path = preg_replace("#/+\.?/+#", "/", str_replace("\\", "/", $path));
+        $dirs = explode("/", rtrim(preg_replace('#^(?:\./)+#', '', $path), '/'));
+
+        $offset = 0;
+        $sub = 0;
+        $subOffset = 0;
+        $root = "";
+
+        if (empty($dirs[0])) {
+            $root = "/";
+            $dirs = array_splice($dirs, 1);
+        } else if (preg_match("#[A-Za-z]:#", $dirs[0])) {
+            $root = strtoupper($dirs[0]) . "/";
+            $dirs = array_splice($dirs, 1);
+        }
+
+        $newDirs = array();
+        foreach ($dirs as $dir) {
+            if ($dir !== "..") {
+                $subOffset--;
+                $newDirs[++$offset] = $dir;
+            } else {
+                $subOffset++;
+                if (--$offset < 0) {
+                    $offset = 0;
+                    if ($subOffset > $sub) {
+                        $sub++;
+                    }
+                }
+            }
+        }
+
+        if (empty($root)) {
+            $root = str_repeat("../", $sub);
+        }
+        return $root . implode("/", array_slice($newDirs, 0, $offset));
+    }
+
+       /**
+        * Create the file permissions for a file or directory, for use in the extFileAttr parameters.
+        *
+        * @param int   $owner Unix permisions for owner (octal from 00 to 07)
+        * @param int   $group Unix permisions for group (octal from 00 to 07)
+        * @param int   $other Unix permisions for others (octal from 00 to 07)
+        * @param bool  $isFile
+        * @return EXTRERNAL_REF field.
+        */
+       public static function generateExtAttr($owner = 07, $group = 05, $other = 05, $isFile = true) {
+               $fp = $isFile ? self::S_IFREG : self::S_IFDIR;
+               $fp |= (($owner & 07) << 6) | (($group & 07) << 3) | ($other & 07);
+
+               return ($fp << 16) | ($isFile ? self::S_DOS_A : self::S_DOS_D);
+       }
+
+       /**
+        * Get the file permissions for a file or directory, for use in the extFileAttr parameters.
+        *
+        * @param string $filename
+        * @return external ref field, or FALSE if the file is not found.
+        */
+       public static function getFileExtAttr($filename) {
+               if (file_exists($filename)) {
+                       $fp = fileperms($filename) << 16;
+                       return $fp | (is_dir($filename) ? self::S_DOS_D : self::S_DOS_A);
+               }
+               return FALSE;
+       }
+}
+?>
diff --git a/inc/3rdparty/libraries/PHPePub/lib.uuid.LICENCE.txt b/inc/3rdparty/libraries/PHPePub/lib.uuid.LICENCE.txt
new file mode 100644 (file)
index 0000000..9424a83
--- /dev/null
@@ -0,0 +1,31 @@
+   DrUUID RFC4122 library for PHP5
+    by J. King (http://jkingweb.ca/)
+   Licensed under MIT license
+
+   See http://jkingweb.ca/code/php/lib.uuid/
+    for documentation
+    
+   Last revised 2010-02-15
+
+Copyright (c) 2009 J. King
+
+Permission is hereby granted, free of charge, to any person
+obtaining a copy of this software and associated documentation
+files (the "Software"), to deal in the Software without
+restriction, including without limitation the rights to use,
+copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the
+Software is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
diff --git a/inc/3rdparty/libraries/PHPePub/lib.uuid.php b/inc/3rdparty/libraries/PHPePub/lib.uuid.php
new file mode 100644 (file)
index 0000000..c6a8de5
--- /dev/null
@@ -0,0 +1,314 @@
+<?php
+/*
+ DrUUID RFC4122 library for PHP5
+by J. King (http://jkingweb.ca/)
+Licensed under MIT license
+
+See http://jkingweb.ca/code/php/lib.uuid/
+for documentation
+
+Last revised 2010-02-15
+*/
+
+/*
+ Copyright (c) 2009 J. King
+
+Permission is hereby granted, free of charge, to any person
+obtaining a copy of this software and associated documentation
+files (the "Software"), to deal in the Software without
+restriction, including without limitation the rights to use,
+copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the
+Software is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
+*/
+
+
+class UUID {
+       const MD5  = 3;
+       const SHA1 = 5;
+       const clearVer = 15;  // 00001111  Clears all bits of version byte with AND
+       const clearVar = 63;  // 00111111  Clears all relevant bits of variant byte with AND
+       const varRes   = 224; // 11100000  Variant reserved for future use
+       const varMS    = 192; // 11000000  Microsft GUID variant
+       const varRFC   = 128; // 10000000  The RFC 4122 variant (this variant)
+       const varNCS   = 0;   // 00000000  The NCS compatibility variant
+       const version1 = 16;  // 00010000
+       const version3 = 48;  // 00110000
+       const version4 = 64;  // 01000000
+       const version5 = 80;  // 01010000
+       const interval = 0x01b21dd213814000; // Time (in 100ns steps) between the start of the UTC and Unix epochs
+       const nsDNS  = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
+       const nsURL  = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
+       const nsOID  = '6ba7b812-9dad-11d1-80b4-00c04fd430c8';
+       const nsX500 = '6ba7b814-9dad-11d1-80b4-00c04fd430c8';
+       protected static $randomFunc = 'randomTwister';
+       protected static $randomSource = NULL;
+       //instance properties
+       protected $bytes;
+       protected $hex;
+       protected $string;
+       protected $urn;
+       protected $version;
+       protected $variant;
+       protected $node;
+       protected $time;
+
+       public static function mint($ver = 1, $node = NULL, $ns = NULL) {
+               /* Create a new UUID based on provided data. */
+               switch((int) $ver) {
+                       case 1:
+                               return new self(self::mintTime($node));
+                       case 2:
+                               // Version 2 is not supported
+                               throw new UUIDException("Version 2 is unsupported.");
+                       case 3:
+                               return new self(self::mintName(self::MD5, $node, $ns));
+                       case 4:
+                               return new self(self::mintRand());
+                       case 5:
+                               return new self(self::mintName(self::SHA1, $node, $ns));
+                       default:
+                               throw new UUIDException("Selected version is invalid or unsupported.");
+               }
+       }
+
+       public static function import($uuid) {
+               /* Import an existing UUID. */
+               return new self(self::makeBin($uuid, 16));
+       }
+
+       public static function compare($a, $b) {
+               /* Compares the binary representations of two UUIDs.
+                The comparison will return true if they are bit-exact,
+               or if neither is valid. */
+               if (self::makeBin($a, 16)==self::makeBin($b, 16)) {
+                       return TRUE;
+               } else {
+                       return FALSE;
+               }
+       }
+
+       public function __toString() {
+               return $this->string;
+       }
+
+       public function __get($var) {
+               switch($var) {
+                       case "bytes":
+                               return $this->bytes;
+                       case "hex":
+                               return bin2hex($this->bytes);
+                       case "string":
+                               return $this->__toString();
+                       case "urn":
+                               return "urn:uuid:".$this->__toString();
+                       case "version":
+                               return ord($this->bytes[6]) >> 4;
+                       case "variant":
+                               $byte = ord($this->bytes[8]);
+                               if ($byte >= self::varRes) {
+                                       return 3;
+                               }
+                               if ($byte >= self::varMS) {
+                                       return 2;
+                               }
+                               if ($byte >= self::varRFC) {
+                                       return 1;
+                               }
+                               return 0;
+                       case "node":
+                               if (ord($this->bytes[6])>>4==1) {
+                                       return bin2hex(substr($this->bytes,10));
+                               } else {
+                                       return NULL;
+                               }
+                       case "time":
+                               if (ord($this->bytes[6])>>4==1) {
+                                       // Restore contiguous big-endian byte order
+                                       $time = bin2hex($this->bytes[6].$this->bytes[7].$this->bytes[4].$this->bytes[5].$this->bytes[0].$this->bytes[1].$this->bytes[2].$this->bytes[3]);
+                                       // Clear version flag
+                                       $time[0] = "0";
+                                       // Do some reverse arithmetic to get a Unix timestamp
+                                       $time = (hexdec($time) - self::interval) / 10000000;
+                                       return $time;
+                               } else {
+                                       return NULL;
+                               }
+                       default:
+                               return NULL;
+               }
+       }
+
+       protected function __construct($uuid) {
+               if (strlen($uuid) != 16) {
+                       throw new UUIDException("Input must be a 128-bit integer.");
+               }
+               $this->bytes  = $uuid;
+               // Optimize the most common use
+               $this->string =
+               bin2hex(substr($uuid,0,4))."-".
+               bin2hex(substr($uuid,4,2))."-".
+               bin2hex(substr($uuid,6,2))."-".
+               bin2hex(substr($uuid,8,2))."-".
+               bin2hex(substr($uuid,10,6));
+       }
+
+       protected static function mintTime($node = NULL) {
+               /* Generates a Version 1 UUID.
+                These are derived from the time at which they were generated. */
+               // Get time since Gregorian calendar reform in 100ns intervals
+               // This is exceedingly difficult because of PHP's (and pack()'s)
+               //  integer size limits.
+               // Note that this will never be more accurate than to the microsecond.
+               $time = microtime(1) * 10000000 + self::interval;
+               // Convert to a string representation
+               $time = sprintf("%F", $time);
+               preg_match("/^\d+/", $time, $time); //strip decimal point
+               // And now to a 64-bit binary representation
+               $time = base_convert($time[0], 10, 16);
+               $time = pack("H*", str_pad($time, 16, "0", STR_PAD_LEFT));
+               // Reorder bytes to their proper locations in the UUID
+               $uuid  = $time[4].$time[5].$time[6].$time[7].$time[2].$time[3].$time[0].$time[1];
+               // Generate a random clock sequence
+               $uuid .= self::randomBytes(2);
+               // set variant
+               $uuid[8] = chr(ord($uuid[8]) & self::clearVar | self::varRFC);
+               // set version
+               $uuid[6] = chr(ord($uuid[6]) & self::clearVer | self::version1);
+               // Set the final 'node' parameter, a MAC address
+               if ($node) {
+                       $node = self::makeBin($node, 6);
+               }
+               if (!$node) {
+                       // If no node was provided or if the node was invalid,
+                       //  generate a random MAC address and set the multicast bit
+                       $node = self::randomBytes(6);
+                       $node[0] = pack("C", ord($node[0]) | 1);
+               }
+               $uuid .= $node;
+               return $uuid;
+       }
+
+       protected static function mintRand() {
+               /* Generate a Version 4 UUID.
+                These are derived soly from random numbers. */
+               // generate random fields
+               $uuid = self::randomBytes(16);
+               // set variant
+               $uuid[8] = chr(ord($uuid[8]) & self::clearVar | self::varRFC);
+               // set version
+               $uuid[6] = chr(ord($uuid[6]) & self::clearVer | self::version4);
+               return $uuid;
+       }
+
+       protected static function mintName($ver, $node, $ns) {
+               /* Generates a Version 3 or Version 5 UUID.
+                These are derived from a hash of a name and its namespace, in binary form. */
+               if (!$node) {
+                       throw new UUIDException("A name-string is required for Version 3 or 5 UUIDs.");
+               }
+               // if the namespace UUID isn't binary, make it so
+               $ns = self::makeBin($ns, 16);
+               if (!$ns) {
+                       throw new UUIDException("A binary namespace is required for Version 3 or 5 UUIDs.");
+               }
+               $uuid = null;
+               $version =  self::version3;
+               switch($ver) {
+                       case self::MD5:
+                               $version = self::version3;
+                               $uuid = md5($ns.$node,1);
+                               break;
+                       case self::SHA1:
+                               $version = self::version5;
+                               $uuid = substr(sha1($ns.$node,1),0, 16);
+                               break;
+               }
+               // set variant
+               $uuid[8] = chr(ord($uuid[8]) & self::clearVar | self::varRFC);
+               // set version
+               $uuid[6] = chr(ord($uuid[6]) & self::clearVer | $version);
+               return ($uuid);
+       }
+
+       protected static function makeBin($str, $len) {
+               /* Insure that an input string is either binary or hexadecimal.
+                Returns binary representation, or false on failure. */
+               if ($str instanceof self) {
+                       return $str->bytes;
+               }
+               if (strlen($str)==$len) {
+                       return $str;
+               } else {
+                       $str = preg_replace("/^urn:uuid:/is", "", $str); // strip URN scheme and namespace
+               }
+               $str = preg_replace("/[^a-f0-9]/is", "", $str);  // strip non-hex characters
+               if (strlen($str) != ($len * 2)) {
+                       return FALSE;
+               } else {
+                       return pack("H*", $str);
+               }
+       }
+
+       public static function initRandom() {
+               /* Look for a system-provided source of randomness, which is usually crytographically secure.
+                /dev/urandom is tried first simply out of bias for Linux systems. */
+               if (is_readable('/dev/urandom')) {
+                       self::$randomSource = fopen('/dev/urandom', 'rb');
+                       self::$randomFunc = 'randomFRead';
+               }
+               else if (class_exists('COM', 0)) {
+                       try {
+                               self::$randomSource = new COM('CAPICOM.Utilities.1');  // See http://msdn.microsoft.com/en-us/library/aa388182(VS.85).aspx
+                               self::$randomFunc = 'randomCOM';
+                       }
+                       catch(Exception $e) {
+                       }
+               }
+               return self::$randomFunc;
+       }
+
+       public static function randomBytes($bytes) {
+               return call_user_func(array('self', self::$randomFunc), $bytes);
+       }
+
+       protected static function randomTwister($bytes) {
+               /* Get the specified number of random bytes, using mt_rand().
+                Randomness is returned as a string of bytes. */
+               $rand = "";
+               for ($a = 0; $a < $bytes; $a++) {
+                       $rand .= chr(mt_rand(0, 255));
+               }
+               return $rand;
+       }
+
+       protected static function randomFRead($bytes) {
+               /* Get the specified number of random bytes using a file handle
+                previously opened with UUID::initRandom().
+               Randomness is returned as a string of bytes. */
+               return fread(self::$randomSource, $bytes);
+       }
+
+       protected static function randomCOM($bytes) {
+               /* Get the specified number of random bytes using Windows'
+                randomness source via a COM object previously created by UUID::initRandom().
+               Randomness is returned as a string of bytes. */
+               return base64_decode(self::$randomSource->GetRandom($bytes,0)); // straight binary mysteriously doesn't work, hence the base64
+       }
+}
+
+class UUIDException extends Exception {
+}
index ddd33bb5a8859908509d4281520aa56e9f978b2c..21e693e7db6ed0c7bbb30f6a0ba885c79ebe1f9d 100644 (file)
-<?php\r
-/**\r
- * Content Extractor\r
- * \r
- * Uses patterns specified in site config files and auto detection (hNews/PHP Readability) \r
- * to extract content from HTML files.\r
- * \r
- * @version 1.0\r
- * @date 2013-02-05\r
- * @author Keyvan Minoukadeh\r
- * @copyright 2013 Keyvan Minoukadeh\r
- * @license http://www.gnu.org/licenses/agpl-3.0.html AGPL v3\r
- */\r
-\r
-class ContentExtractor\r
-{\r
-       protected static $tidy_config = array(\r
-                                'clean' => true,\r
-                                'output-xhtml' => true,\r
-                                'logical-emphasis' => true,\r
-                                'show-body-only' => false,\r
-                                'new-blocklevel-tags' => 'article, aside, footer, header, hgroup, menu, nav, section, details, datagrid',\r
-                                'new-inline-tags' => 'mark, time, meter, progress, data',\r
-                                'wrap' => 0,\r
-                                'drop-empty-paras' => true,\r
-                                'drop-proprietary-attributes' => false,\r
-                                'enclose-text' => true,\r
-                                'enclose-block-text' => true,\r
-                                'merge-divs' => true,\r
-                                'merge-spans' => true,\r
-                                'char-encoding' => 'utf8',\r
-                                'hide-comments' => true\r
-                                );\r
-       protected $html;\r
-       protected $config;\r
-       protected $title;\r
-       protected $author = array();\r
-       protected $language;\r
-       protected $date;\r
-       protected $body;\r
-       protected $success = false;\r
-       protected $nextPageUrl;\r
-       public $allowedParsers = array('libxml', 'html5lib');\r
-       public $fingerprints = array();\r
-       public $readability;\r
-       public $debug = false;\r
-       public $debugVerbose = false;\r
-\r
-       function __construct($path, $fallback=null) {\r
-               SiteConfig::set_config_path($path, $fallback);  \r
-       }\r
-       \r
-       protected function debug($msg) {\r
-               if ($this->debug) {\r
-                       $mem = round(memory_get_usage()/1024, 2);\r
-                       $memPeak = round(memory_get_peak_usage()/1024, 2);\r
-                       echo '* ',$msg;\r
-                       if ($this->debugVerbose) echo ' - mem used: ',$mem," (peak: $memPeak)";\r
-                       echo "\n";\r
-                       ob_flush();\r
-                       flush();\r
-               }\r
-       }\r
-       \r
-       public function reset() {\r
-               $this->html = null;\r
-               $this->readability = null;\r
-               $this->config = null;\r
-               $this->title = null;\r
-               $this->body = null;\r
-               $this->author = array();\r
-               $this->language = null;\r
-               $this->date = null;\r
-               $this->nextPageUrl = null;\r
-               $this->success = false;\r
-       }\r
-\r
-       public function findHostUsingFingerprints($html) {\r
-               $this->debug('Checking fingerprints...');\r
-               $head = substr($html, 0, 8000);\r
-               foreach ($this->fingerprints as $_fp => $_fphost) {\r
-                       $lookin = 'html';\r
-                       if (is_array($_fphost)) {\r
-                               if (isset($_fphost['head']) && $_fphost['head']) {\r
-                                       $lookin = 'head';\r
-                               }\r
-                               $_fphost = $_fphost['hostname'];\r
-                       }\r
-                       if (strpos($$lookin, $_fp) !== false) {\r
-                               $this->debug("Found match: $_fphost");\r
-                               return $_fphost;\r
-                       }\r
-               }\r
-               $this->debug('No fingerprint matches');\r
-               return false;\r
-       }\r
-       \r
-       // returns SiteConfig instance (joined in order: exact match, wildcard, fingerprint, global, default)\r
-       public function buildSiteConfig($url, $html='', $add_to_cache=true) {\r
-               // extract host name\r
-               $host = @parse_url($url, PHP_URL_HOST);\r
-               $host = strtolower($host);\r
-               if (substr($host, 0, 4) == 'www.') $host = substr($host, 4);\r
-               // is merged version already cached?\r
-               if (SiteConfig::is_cached("$host.merged")) {\r
-                       $this->debug("Returning cached and merged site config for $host");\r
-                       return SiteConfig::build("$host.merged");\r
-               }\r
-               // let's build from site_config/custom/ and standard/\r
-               $config = SiteConfig::build($host);\r
-               if ($add_to_cache && $config && !SiteConfig::is_cached("$host")) {\r
-                       SiteConfig::add_to_cache($host, $config);\r
-               }\r
-               // if no match, use defaults\r
-               if (!$config) $config = new SiteConfig();\r
-               // load fingerprint config?\r
-               if ($config->autodetect_on_failure()) {\r
-                       // check HTML for fingerprints\r
-                       if (!empty($this->fingerprints) && ($_fphost = $this->findHostUsingFingerprints($html))) {\r
-                               if ($config_fingerprint = SiteConfig::build($_fphost)) {\r
-                                       $this->debug("Appending site config settings from $_fphost (fingerprint match)");\r
-                                       $config->append($config_fingerprint);\r
-                                       if ($add_to_cache && !SiteConfig::is_cached($_fphost)) {\r
-                                               //$config_fingerprint->cache_in_apc = true;\r
-                                               SiteConfig::add_to_cache($_fphost, $config_fingerprint);\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-               // load global config?\r
-               if ($config->autodetect_on_failure()) {\r
-                       if ($config_global = SiteConfig::build('global', true)) {\r
-                               $this->debug('Appending site config settings from global.txt');\r
-                               $config->append($config_global);\r
-                               if ($add_to_cache && !SiteConfig::is_cached('global')) {\r
-                                       //$config_global->cache_in_apc = true;\r
-                                       SiteConfig::add_to_cache('global', $config_global);\r
-                               }\r
-                       }\r
-               }\r
-               // store copy of merged config\r
-               if ($add_to_cache) {\r
-                       // do not store in APC if wildcard match\r
-                       $use_apc = ($host == $config->cache_key);\r
-                       $config->cache_key = null;\r
-                       SiteConfig::add_to_cache("$host.merged", $config, $use_apc);\r
-               }\r
-               return $config;\r
-       }\r
-       \r
-       // returns true on success, false on failure\r
-       // $smart_tidy indicates that if tidy is used and no results are produced, we will\r
-       // try again without it. Tidy helps us deal with PHP's patchy HTML parsing most of the time\r
-       // but it has problems of its own which we try to avoid with this option.\r
-       public function process($html, $url, $smart_tidy=true) {\r
-               $this->reset();\r
-               $this->config = $this->buildSiteConfig($url, $html);\r
-               \r
-               // do string replacements\r
-               if (!empty($this->config->find_string)) {\r
-                       if (count($this->config->find_string) == count($this->config->replace_string)) {\r
-                               $html = str_replace($this->config->find_string, $this->config->replace_string, $html, $_count);\r
-                               $this->debug("Strings replaced: $_count (find_string and/or replace_string)");\r
-                       } else {\r
-                               $this->debug('Skipped string replacement - incorrect number of find-replace strings in site config');\r
-                       }\r
-                       unset($_count);\r
-               }\r
-               \r
-               // use tidy (if it exists)?\r
-               // This fixes problems with some sites which would otherwise\r
-               // trouble DOMDocument's HTML parsing. (Although sometimes it\r
-               // makes matters worse, which is why you can override it in site config files.)\r
-               $tidied = false;\r
-               if ($this->config->tidy() && function_exists('tidy_parse_string') && $smart_tidy) {\r
-                       $this->debug('Using Tidy');\r
-                       $tidy = tidy_parse_string($html, self::$tidy_config, 'UTF8');\r
-                       if (tidy_clean_repair($tidy)) {\r
-                               $original_html = $html;\r
-                               $tidied = true;\r
-                               $html = $tidy->value;\r
-                       }\r
-                       unset($tidy);\r
-               }\r
-               \r
-               // load and parse html\r
-               $_parser = $this->config->parser();\r
-               if (!in_array($_parser, $this->allowedParsers)) {\r
-                       $this->debug("HTML parser $_parser not listed, using libxml instead");\r
-                       $_parser = 'libxml';\r
-               }\r
-               $this->debug("Attempting to parse HTML with $_parser");\r
-               $this->readability = new Readability($html, $url, $_parser);\r
-               \r
-               // we use xpath to find elements in the given HTML document\r
-               // see http://en.wikipedia.org/wiki/XPath_1.0\r
-               $xpath = new DOMXPath($this->readability->dom);\r
-\r
-               // try to get next page link\r
-               foreach ($this->config->next_page_link as $pattern) {\r
-                       $elems = @$xpath->evaluate($pattern, $this->readability->dom);\r
-                       if (is_string($elems)) {\r
-                               $this->nextPageUrl = trim($elems);\r
-                               break;\r
-                       } elseif ($elems instanceof DOMNodeList && $elems->length > 0) {\r
-                               foreach ($elems as $item) {\r
-                                       if ($item instanceof DOMElement && $item->hasAttribute('href')) {\r
-                                               $this->nextPageUrl = $item->getAttribute('href');\r
-                                               break 2;\r
-                                       } elseif ($item instanceof DOMAttr && $item->value) {\r
-                                               $this->nextPageUrl = $item->value;\r
-                                               break 2;\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-               \r
-               // try to get title\r
-               foreach ($this->config->title as $pattern) {\r
-                       // $this->debug("Trying $pattern");\r
-                       $elems = @$xpath->evaluate($pattern, $this->readability->dom);\r
-                       if (is_string($elems)) {\r
-                               $this->title = trim($elems);\r
-                               $this->debug('Title expression evaluated as string: '.$this->title);\r
-                               $this->debug("...XPath match: $pattern");\r
-                               break;\r
-                       } elseif ($elems instanceof DOMNodeList && $elems->length > 0) {\r
-                               $this->title = $elems->item(0)->textContent;\r
-                               $this->debug('Title matched: '.$this->title);\r
-                               $this->debug("...XPath match: $pattern");\r
-                               // remove title from document\r
-                               try {\r
-                                       $elems->item(0)->parentNode->removeChild($elems->item(0));\r
-                               } catch (DOMException $e) {\r
-                                       // do nothing\r
-                               }\r
-                               break;\r
-                       }\r
-               }\r
-               \r
-               // try to get author (if it hasn't already been set)\r
-               if (empty($this->author)) {\r
-                       foreach ($this->config->author as $pattern) {\r
-                               $elems = @$xpath->evaluate($pattern, $this->readability->dom);\r
-                               if (is_string($elems)) {\r
-                                       if (trim($elems) != '') {\r
-                                               $this->author[] = trim($elems);\r
-                                               $this->debug('Author expression evaluated as string: '.trim($elems));\r
-                                               $this->debug("...XPath match: $pattern");\r
-                                               break;\r
-                                       }\r
-                               } elseif ($elems instanceof DOMNodeList && $elems->length > 0) {\r
-                                       foreach ($elems as $elem) {\r
-                                               if (!isset($elem->parentNode)) continue;\r
-                                               $this->author[] = trim($elem->textContent);\r
-                                               $this->debug('Author matched: '.trim($elem->textContent));\r
-                                       }\r
-                                       if (!empty($this->author)) {\r
-                                               $this->debug("...XPath match: $pattern");\r
-                                               break;\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-               \r
-               // try to get language\r
-               $_lang_xpath = array('//html[@lang]/@lang', '//meta[@name="DC.language"]/@content');\r
-               foreach ($_lang_xpath as $pattern) {\r
-                       $elems = @$xpath->evaluate($pattern, $this->readability->dom);\r
-                       if (is_string($elems)) {\r
-                               if (trim($elems) != '') {\r
-                                       $this->language = trim($elems);\r
-                                       $this->debug('Language matched: '.$this->language);\r
-                                       break;\r
-                               }\r
-                       } elseif ($elems instanceof DOMNodeList && $elems->length > 0) {\r
-                               foreach ($elems as $elem) {\r
-                                       if (!isset($elem->parentNode)) continue;\r
-                                       $this->language = trim($elem->textContent);\r
-                                       $this->debug('Language matched: '.$this->language);                                     \r
-                               }\r
-                               if ($this->language) break;\r
-                       }\r
-               }\r
-               \r
-               // try to get date\r
-               foreach ($this->config->date as $pattern) {\r
-                       $elems = @$xpath->evaluate($pattern, $this->readability->dom);\r
-                       if (is_string($elems)) {\r
-                               $this->date = strtotime(trim($elems, "; \t\n\r\0\x0B"));                                \r
-                       } elseif ($elems instanceof DOMNodeList && $elems->length > 0) {\r
-                               $this->date = $elems->item(0)->textContent;\r
-                               $this->date = strtotime(trim($this->date, "; \t\n\r\0\x0B"));\r
-                               // remove date from document\r
-                               // $elems->item(0)->parentNode->removeChild($elems->item(0));\r
-                       }\r
-                       if (!$this->date) {\r
-                               $this->date = null;\r
-                       } else {\r
-                               $this->debug('Date matched: '.date('Y-m-d H:i:s', $this->date));\r
-                               $this->debug("...XPath match: $pattern");\r
-                               break;\r
-                       }\r
-               }\r
-\r
-               // strip elements (using xpath expressions)\r
-               foreach ($this->config->strip as $pattern) {\r
-                       $elems = @$xpath->query($pattern, $this->readability->dom);\r
-                       // check for matches\r
-                       if ($elems && $elems->length > 0) {\r
-                               $this->debug('Stripping '.$elems->length.' elements (strip)');\r
-                               for ($i=$elems->length-1; $i >= 0; $i--) {\r
-                                       $elems->item($i)->parentNode->removeChild($elems->item($i));\r
-                               }\r
-                       }\r
-               }\r
-               \r
-               // strip elements (using id and class attribute values)\r
-               foreach ($this->config->strip_id_or_class as $string) {\r
-                       $string = strtr($string, array("'"=>'', '"'=>''));\r
-                       $elems = @$xpath->query("//*[contains(@class, '$string') or contains(@id, '$string')]", $this->readability->dom);\r
-                       // check for matches\r
-                       if ($elems && $elems->length > 0) {\r
-                               $this->debug('Stripping '.$elems->length.' elements (strip_id_or_class)');\r
-                               for ($i=$elems->length-1; $i >= 0; $i--) {\r
-                                       $elems->item($i)->parentNode->removeChild($elems->item($i));\r
-                               }\r
-                       }\r
-               }\r
-               \r
-               // strip images (using src attribute values)\r
-               foreach ($this->config->strip_image_src as $string) {\r
-                       $string = strtr($string, array("'"=>'', '"'=>''));\r
-                       $elems = @$xpath->query("//img[contains(@src, '$string')]", $this->readability->dom);\r
-                       // check for matches\r
-                       if ($elems && $elems->length > 0) {\r
-                               $this->debug('Stripping '.$elems->length.' image elements');\r
-                               for ($i=$elems->length-1; $i >= 0; $i--) {\r
-                                       $elems->item($i)->parentNode->removeChild($elems->item($i));\r
-                               }\r
-                       }\r
-               }\r
-               // strip elements using Readability.com and Instapaper.com ignore class names\r
-               // .entry-unrelated and .instapaper_ignore\r
-               // See https://www.readability.com/publishers/guidelines/#view-plainGuidelines\r
-               // and http://blog.instapaper.com/post/730281947\r
-               $elems = @$xpath->query("//*[contains(concat(' ',normalize-space(@class),' '),' entry-unrelated ') or contains(concat(' ',normalize-space(@class),' '),' instapaper_ignore ')]", $this->readability->dom);\r
-               // check for matches\r
-               if ($elems && $elems->length > 0) {\r
-                       $this->debug('Stripping '.$elems->length.' .entry-unrelated,.instapaper_ignore elements');\r
-                       for ($i=$elems->length-1; $i >= 0; $i--) {\r
-                               $elems->item($i)->parentNode->removeChild($elems->item($i));\r
-                       }\r
-               }\r
-               \r
-               // strip elements that contain style="display: none;"\r
-               $elems = @$xpath->query("//*[contains(@style,'display:none')]", $this->readability->dom);\r
-               // check for matches\r
-               if ($elems && $elems->length > 0) {\r
-                       $this->debug('Stripping '.$elems->length.' elements with inline display:none style');\r
-                       for ($i=$elems->length-1; $i >= 0; $i--) {\r
-                               $elems->item($i)->parentNode->removeChild($elems->item($i));\r
-                       }\r
-               }\r
-               \r
-               // try to get body\r
-               foreach ($this->config->body as $pattern) {\r
-                       $elems = @$xpath->query($pattern, $this->readability->dom);\r
-                       // check for matches\r
-                       if ($elems && $elems->length > 0) {\r
-                               $this->debug('Body matched');\r
-                               $this->debug("...XPath match: $pattern");\r
-                               if ($elems->length == 1) {                              \r
-                                       $this->body = $elems->item(0);\r
-                                       // prune (clean up elements that may not be content)\r
-                                       if ($this->config->prune()) {\r
-                                               $this->debug('...pruning content');\r
-                                               $this->readability->prepArticle($this->body);\r
-                                       }\r
-                                       break;\r
-                               } else {\r
-                                       $this->body = $this->readability->dom->createElement('div');\r
-                                       $this->debug($elems->length.' body elems found');\r
-                                       foreach ($elems as $elem) {\r
-                                               if (!isset($elem->parentNode)) continue;\r
-                                               $isDescendant = false;\r
-                                               foreach ($this->body->childNodes as $parent) {\r
-                                                       if ($this->isDescendant($parent, $elem)) {\r
-                                                               $isDescendant = true;\r
-                                                               break;\r
-                                                       }\r
-                                               }\r
-                                               if ($isDescendant) {\r
-                                                       $this->debug('...element is child of another body element, skipping.');\r
-                                               } else {\r
-                                                       // prune (clean up elements that may not be content)\r
-                                                       if ($this->config->prune()) {\r
-                                                               $this->debug('Pruning content');\r
-                                                               $this->readability->prepArticle($elem);\r
-                                                       }\r
-                                                       $this->debug('...element added to body');\r
-                                                       $this->body->appendChild($elem);\r
-                                               }\r
-                                       }\r
-                                       if ($this->body->hasChildNodes()) break;\r
-                               }\r
-                       }\r
-               }               \r
-               \r
-               // auto detect?\r
-               $detect_title = $detect_body = $detect_author = $detect_date = false;\r
-               // detect title?\r
-               if (!isset($this->title)) {\r
-                       if (empty($this->config->title) || $this->config->autodetect_on_failure()) {\r
-                               $detect_title = true;\r
-                       }\r
-               }\r
-               // detect body?\r
-               if (!isset($this->body)) {\r
-                       if (empty($this->config->body) || $this->config->autodetect_on_failure()) {\r
-                               $detect_body = true;\r
-                       }\r
-               }\r
-               // detect author?\r
-               if (empty($this->author)) {\r
-                       if (empty($this->config->author) || $this->config->autodetect_on_failure()) {\r
-                               $detect_author = true;\r
-                       }\r
-               }\r
-               // detect date?\r
-               if (!isset($this->date)) {\r
-                       if (empty($this->config->date) || $this->config->autodetect_on_failure()) {\r
-                               $detect_date = true;\r
-                       }\r
-               }\r
-\r
-               // check for hNews\r
-               if ($detect_title || $detect_body) {\r
-                       // check for hentry\r
-                       $elems = @$xpath->query("//*[contains(concat(' ',normalize-space(@class),' '),' hentry ')]", $this->readability->dom);\r
-                       if ($elems && $elems->length > 0) {\r
-                               $this->debug('hNews: found hentry');\r
-                               $hentry = $elems->item(0);\r
-                               \r
-                               if ($detect_title) {\r
-                                       // check for entry-title\r
-                                       $elems = @$xpath->query(".//*[contains(concat(' ',normalize-space(@class),' '),' entry-title ')]", $hentry);\r
-                                       if ($elems && $elems->length > 0) {\r
-                                               $this->title = $elems->item(0)->textContent;\r
-                                               $this->debug('hNews: found entry-title: '.$this->title);\r
-                                               // remove title from document\r
-                                               $elems->item(0)->parentNode->removeChild($elems->item(0));\r
-                                               $detect_title = false;\r
-                                       }\r
-                               }\r
-                               \r
-                               if ($detect_date) {\r
-                                       // check for time element with pubdate attribute\r
-                                       $elems = @$xpath->query(".//time[@pubdate] | .//abbr[contains(concat(' ',normalize-space(@class),' '),' published ')]", $hentry);\r
-                                       if ($elems && $elems->length > 0) {\r
-                                               $this->date = strtotime(trim($elems->item(0)->textContent));\r
-                                               // remove date from document\r
-                                               //$elems->item(0)->parentNode->removeChild($elems->item(0));\r
-                                               if ($this->date) {\r
-                                                       $this->debug('hNews: found publication date: '.date('Y-m-d H:i:s', $this->date));\r
-                                                       $detect_date = false;\r
-                                               } else {\r
-                                                       $this->date = null;\r
-                                               }\r
-                                       }\r
-                               }\r
-\r
-                               if ($detect_author) {\r
-                                       // check for time element with pubdate attribute\r
-                                       $elems = @$xpath->query(".//*[contains(concat(' ',normalize-space(@class),' '),' vcard ') and (contains(concat(' ',normalize-space(@class),' '),' author ') or contains(concat(' ',normalize-space(@class),' '),' byline '))]", $hentry);\r
-                                       if ($elems && $elems->length > 0) {\r
-                                               $author = $elems->item(0);\r
-                                               $fn = @$xpath->query(".//*[contains(concat(' ',normalize-space(@class),' '),' fn ')]", $author);\r
-                                               if ($fn && $fn->length > 0) {\r
-                                                       foreach ($fn as $_fn) {\r
-                                                               if (trim($_fn->textContent) != '') {\r
-                                                                       $this->author[] = trim($_fn->textContent);\r
-                                                                       $this->debug('hNews: found author: '.trim($_fn->textContent));\r
-                                                               }\r
-                                                       }\r
-                                               } else {\r
-                                                       if (trim($author->textContent) != '') {\r
-                                                               $this->author[] = trim($author->textContent);\r
-                                                               $this->debug('hNews: found author: '.trim($author->textContent));\r
-                                                       }\r
-                                               }\r
-                                               $detect_author = empty($this->author);\r
-                                       }\r
-                               }\r
-                               \r
-                               // check for entry-content.\r
-                               // according to hAtom spec, if there are multiple elements marked entry-content,\r
-                               // we include all of these in the order they appear - see http://microformats.org/wiki/hatom#Entry_Content\r
-                               if ($detect_body) {\r
-                                       $elems = @$xpath->query(".//*[contains(concat(' ',normalize-space(@class),' '),' entry-content ')]", $hentry);\r
-                                       if ($elems && $elems->length > 0) {\r
-                                               $this->debug('hNews: found entry-content');\r
-                                               if ($elems->length == 1) {\r
-                                                       // what if it's empty? (some sites misuse hNews - place their content outside an empty entry-content element)\r
-                                                       $e = $elems->item(0);\r
-                                                       if (($e->tagName == 'img') || (trim($e->textContent) != '')) {\r
-                                                               $this->body = $elems->item(0);\r
-                                                               // prune (clean up elements that may not be content)\r
-                                                               if ($this->config->prune()) {\r
-                                                                       $this->debug('Pruning content');\r
-                                                                       $this->readability->prepArticle($this->body);\r
-                                                               }\r
-                                                               $detect_body = false;\r
-                                                       } else {\r
-                                                               $this->debug('hNews: skipping entry-content - appears not to contain content');\r
-                                                       }\r
-                                                       unset($e);\r
-                                               } else {\r
-                                                       $this->body = $this->readability->dom->createElement('div');\r
-                                                       $this->debug($elems->length.' entry-content elems found');\r
-                                                       foreach ($elems as $elem) {\r
-                                                               if (!isset($elem->parentNode)) continue;\r
-                                                               $isDescendant = false;\r
-                                                               foreach ($this->body->childNodes as $parent) {\r
-                                                                       if ($this->isDescendant($parent, $elem)) {\r
-                                                                               $isDescendant = true;\r
-                                                                               break;\r
-                                                                       }\r
-                                                               }\r
-                                                               if ($isDescendant) {\r
-                                                                       $this->debug('Element is child of another body element, skipping.');\r
-                                                               } else {\r
-                                                                       // prune (clean up elements that may not be content)\r
-                                                                       if ($this->config->prune()) {\r
-                                                                               $this->debug('Pruning content');\r
-                                                                               $this->readability->prepArticle($elem);\r
-                                                                       }                                                               \r
-                                                                       $this->debug('Element added to body');                                                                  \r
-                                                                       $this->body->appendChild($elem);\r
-                                                               }\r
-                                                       }\r
-                                                       $detect_body = false;\r
-                                               }\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-               // check for elements marked with instapaper_title\r
-               if ($detect_title) {\r
-                       // check for instapaper_title\r
-                       $elems = @$xpath->query("//*[contains(concat(' ',normalize-space(@class),' '),' instapaper_title ')]", $this->readability->dom);\r
-                       if ($elems && $elems->length > 0) {\r
-                               $this->title = $elems->item(0)->textContent;\r
-                               $this->debug('Title found (.instapaper_title): '.$this->title);\r
-                               // remove title from document\r
-                               $elems->item(0)->parentNode->removeChild($elems->item(0));\r
-                               $detect_title = false;\r
-                       }\r
-               }\r
-               // check for elements marked with instapaper_body\r
-               if ($detect_body) {\r
-                       $elems = @$xpath->query("//*[contains(concat(' ',normalize-space(@class),' '),' instapaper_body ')]", $this->readability->dom);\r
-                       if ($elems && $elems->length > 0) {\r
-                               $this->debug('body found (.instapaper_body)');\r
-                               $this->body = $elems->item(0);\r
-                               // prune (clean up elements that may not be content)\r
-                               if ($this->config->prune()) {\r
-                                       $this->debug('Pruning content');\r
-                                       $this->readability->prepArticle($this->body);\r
-                               }\r
-                               $detect_body = false;\r
-                       }\r
-               }\r
-               \r
-               // Find author in rel="author" marked element\r
-               // We only use this if there's exactly one.\r
-               // If there's more than one, it could indicate more than\r
-               // one author, but it could also indicate that we're processing\r
-               // a page listing different articles with different authors.\r
-               if ($detect_author) {\r
-                       $elems = @$xpath->query("//a[contains(concat(' ',normalize-space(@rel),' '),' author ')]", $this->readability->dom);\r
-                       if ($elems && $elems->length == 1) {\r
-                               $author = trim($elems->item(0)->textContent);\r
-                               if ($author != '') {\r
-                                       $this->debug("Author found (rel=\"author\"): $author");\r
-                                       $this->author[] = $author;\r
-                                       $detect_author = false;\r
-                               }\r
-                       }\r
-               }\r
-\r
-               // Find date in pubdate marked time element\r
-               // For the same reason given above, we only use this\r
-               // if there's exactly one element.\r
-               if ($detect_date) {\r
-                       $elems = @$xpath->query("//time[@pubdate]", $this->readability->dom);\r
-                       if ($elems && $elems->length == 1) {\r
-                               $this->date = strtotime(trim($elems->item(0)->textContent));\r
-                               // remove date from document\r
-                               //$elems->item(0)->parentNode->removeChild($elems->item(0));\r
-                               if ($this->date) {\r
-                                       $this->debug('Date found (pubdate marked time element): '.date('Y-m-d H:i:s', $this->date));\r
-                                       $detect_date = false;\r
-                               } else {\r
-                                       $this->date = null;\r
-                               }\r
-                       }\r
-               }\r
-\r
-               // still missing title or body, so we detect using Readability\r
-               if ($detect_title || $detect_body) {\r
-                       $this->debug('Using Readability');\r
-                       // clone body if we're only using Readability for title (otherwise it may interfere with body element)\r
-                       if (isset($this->body)) $this->body = $this->body->cloneNode(true);\r
-                       $success = $this->readability->init();\r
-               }\r
-               if ($detect_title) {\r
-                       $this->debug('Detecting title');\r
-                       $this->title = $this->readability->getTitle()->textContent;\r
-               }\r
-               if ($detect_body && $success) {\r
-                       $this->debug('Detecting body');\r
-                       $this->body = $this->readability->getContent();\r
-                       if ($this->body->childNodes->length == 1 && $this->body->firstChild->nodeType === XML_ELEMENT_NODE) {\r
-                               $this->body = $this->body->firstChild;\r
-                       }\r
-                       // prune (clean up elements that may not be content)\r
-                       if ($this->config->prune()) {\r
-                               $this->debug('Pruning content');\r
-                               $this->readability->prepArticle($this->body);\r
-                       }\r
-               }\r
-               if (isset($this->body)) {\r
-                       // remove scripts\r
-                       $this->readability->removeScripts($this->body);\r
-                       // remove any h1-h6 elements that appear as first thing in the body\r
-                       // and which match our title\r
-                       if (isset($this->title) && ($this->title != '')) {\r
-                               $firstChild = $this->body->firstChild;\r
-                               while ($firstChild->nodeType && ($firstChild->nodeType !== XML_ELEMENT_NODE)) {\r
-                                       $firstChild = $firstChild->nextSibling;\r
-                               }\r
-                               if (($firstChild->nodeType === XML_ELEMENT_NODE)\r
-                                       && in_array(strtolower($firstChild->tagName), array('h1', 'h2', 'h3', 'h4', 'h5', 'h6'))\r
-                                       && (strtolower(trim($firstChild->textContent)) == strtolower(trim($this->title)))) {\r
-                                               $this->body->removeChild($firstChild);\r
-                               }\r
-                       }\r
-                       // prevent self-closing iframes\r
-                       $elems = $this->body->getElementsByTagName('iframe');\r
-                       for ($i = $elems->length-1; $i >= 0; $i--) {\r
-                               $e = $elems->item($i);\r
-                               if (!$e->hasChildNodes()) {\r
-                                       $e->appendChild($this->body->ownerDocument->createTextNode('[embedded content]'));\r
-                               }\r
-                       }\r
-                       // remove image lazy loading - WordPress plugin http://wordpress.org/extend/plugins/lazy-load/\r
-                       // the plugin replaces the src attribute to point to a 1x1 gif and puts the original src\r
-                       // inside the data-lazy-src attribute. It also places the original image inside a noscript element \r
-                       // next to the amended one.\r
-                       $elems = @$xpath->query("//img[@data-lazy-src]", $this->body);\r
-                       for ($i = $elems->length-1; $i >= 0; $i--) {\r
-                               $e = $elems->item($i);\r
-                               // let's see if we can grab image from noscript\r
-                               if ($e->nextSibling !== null && $e->nextSibling->nodeName === 'noscript') {\r
-                                       $_new_elem = $e->ownerDocument->createDocumentFragment();\r
-                                       @$_new_elem->appendXML($e->nextSibling->innerHTML);\r
-                                       $e->nextSibling->parentNode->replaceChild($_new_elem, $e->nextSibling);\r
-                                       $e->parentNode->removeChild($e);\r
-                               } else {\r
-                                       // Use data-lazy-src as src value\r
-                                       $e->setAttribute('src', $e->getAttribute('data-lazy-src'));\r
-                                       $e->removeAttribute('data-lazy-src');\r
-                               }\r
-                       }\r
-               \r
-                       $this->success = true;\r
-               }\r
-               \r
-               // if we've had no success and we've used tidy, there's a chance\r
-               // that tidy has messed up. So let's try again without tidy...\r
-               if (!$this->success && $tidied && $smart_tidy) {\r
-                       $this->debug('Trying again without tidy');\r
-                       $this->process($original_html, $url, false);\r
-               }\r
-\r
-               return $this->success;\r
-       }\r
-       \r
-       private function isDescendant(DOMElement $parent, DOMElement $child) {\r
-               $node = $child->parentNode;\r
-               while ($node != null) {\r
-                       if ($node->isSameNode($parent)) return true;\r
-                       $node = $node->parentNode;\r
-               }\r
-               return false;\r
-       }\r
-\r
-       public function getContent() {\r
-               return $this->body;\r
-       }\r
-       \r
-       public function getTitle() {\r
-               return $this->title;\r
-       }\r
-       \r
-       public function getAuthors() {\r
-               return $this->author;\r
-       }\r
-       \r
-       public function getLanguage() {\r
-               return $this->language;\r
-       }\r
-       \r
-       public function getDate() {\r
-               return $this->date;\r
-       }\r
-       \r
-       public function getSiteConfig() {\r
-               return $this->config;\r
-       }\r
-       \r
-       public function getNextPageUrl() {\r
-               return $this->nextPageUrl;\r
-       }\r
-}\r
-?>
\ No newline at end of file
+<?php
+/**
+ * Content Extractor
+ * 
+ * Uses patterns specified in site config files and auto detection (hNews/PHP Readability) 
+ * to extract content from HTML files.
+ * 
+ * @version 1.0
+ * @date 2013-02-05
+ * @author Keyvan Minoukadeh
+ * @copyright 2013 Keyvan Minoukadeh
+ * @license http://www.gnu.org/licenses/agpl-3.0.html AGPL v3
+ */
+
+class ContentExtractor
+{
+       protected static $tidy_config = array(
+                                'clean' => true,
+                                'output-xhtml' => true,
+                                'logical-emphasis' => true,
+                                'show-body-only' => false,
+                                'new-blocklevel-tags' => 'article, aside, footer, header, hgroup, menu, nav, section, details, datagrid',
+                                'new-inline-tags' => 'mark, time, meter, progress, data',
+                                'wrap' => 0,
+                                'drop-empty-paras' => true,
+                                'drop-proprietary-attributes' => false,
+                                'enclose-text' => true,
+                                'enclose-block-text' => true,
+                                'merge-divs' => true,
+                                'merge-spans' => true,
+                                'char-encoding' => 'utf8',
+                                'hide-comments' => true
+                                );
+       protected $html;
+       protected $config;
+       protected $title;
+       protected $author = array();
+       protected $language;
+       protected $date;
+       protected $body;
+       protected $success = false;
+       protected $nextPageUrl;
+       public $allowedParsers = array('libxml', 'html5lib');
+       public $fingerprints = array();
+       public $readability;
+       public $debug = false;
+       public $debugVerbose = false;
+
+       function __construct($path, $fallback=null) {
+               SiteConfig::set_config_path($path, $fallback);  
+       }
+       
+       protected function debug($msg) {
+               if ($this->debug) {
+                       $mem = round(memory_get_usage()/1024, 2);
+                       $memPeak = round(memory_get_peak_usage()/1024, 2);
+                       echo '* ',$msg;
+                       if ($this->debugVerbose) echo ' - mem used: ',$mem," (peak: $memPeak)";
+                       echo "\n";
+                       ob_flush();
+                       flush();
+               }
+       }
+       
+       public function reset() {
+               $this->html = null;
+               $this->readability = null;
+               $this->config = null;
+               $this->title = null;
+               $this->body = null;
+               $this->author = array();
+               $this->language = null;
+               $this->date = null;
+               $this->nextPageUrl = null;
+               $this->success = false;
+       }
+
+       public function findHostUsingFingerprints($html) {
+               $this->debug('Checking fingerprints...');
+               $head = substr($html, 0, 8000);
+               foreach ($this->fingerprints as $_fp => $_fphost) {
+                       $lookin = 'html';
+                       if (is_array($_fphost)) {
+                               if (isset($_fphost['head']) && $_fphost['head']) {
+                                       $lookin = 'head';
+                               }
+                               $_fphost = $_fphost['hostname'];
+                       }
+                       if (strpos($$lookin, $_fp) !== false) {
+                               $this->debug("Found match: $_fphost");
+                               return $_fphost;
+                       }
+               }
+               $this->debug('No fingerprint matches');
+               return false;
+       }
+       
+       // returns SiteConfig instance (joined in order: exact match, wildcard, fingerprint, global, default)
+       public function buildSiteConfig($url, $html='', $add_to_cache=true) {
+               // extract host name
+               $host = @parse_url($url, PHP_URL_HOST);
+               $host = strtolower($host);
+               if (substr($host, 0, 4) == 'www.') $host = substr($host, 4);
+               // is merged version already cached?
+               if (SiteConfig::is_cached("$host.merged")) {
+                       $this->debug("Returning cached and merged site config for $host");
+                       return SiteConfig::build("$host.merged");
+               }
+               // let's build from site_config/custom/ and standard/
+               $config = SiteConfig::build($host);
+               if ($add_to_cache && $config && !SiteConfig::is_cached("$host")) {
+                       SiteConfig::add_to_cache($host, $config);
+               }
+               // if no match, use defaults
+               if (!$config) $config = new SiteConfig();
+               // load fingerprint config?
+               if ($config->autodetect_on_failure()) {
+                       // check HTML for fingerprints
+                       if (!empty($this->fingerprints) && ($_fphost = $this->findHostUsingFingerprints($html))) {
+                               if ($config_fingerprint = SiteConfig::build($_fphost)) {
+                                       $this->debug("Appending site config settings from $_fphost (fingerprint match)");
+                                       $config->append($config_fingerprint);
+                                       if ($add_to_cache && !SiteConfig::is_cached($_fphost)) {
+                                               //$config_fingerprint->cache_in_apc = true;
+                                               SiteConfig::add_to_cache($_fphost, $config_fingerprint);
+                                       }
+                               }
+                       }
+               }
+               // load global config?
+               if ($config->autodetect_on_failure()) {
+                       if ($config_global = SiteConfig::build('global', true)) {
+                               $this->debug('Appending site config settings from global.txt');
+                               $config->append($config_global);
+                               if ($add_to_cache && !SiteConfig::is_cached('global')) {
+                                       //$config_global->cache_in_apc = true;
+                                       SiteConfig::add_to_cache('global', $config_global);
+                               }
+                       }
+               }
+               // store copy of merged config
+               if ($add_to_cache) {
+                       // do not store in APC if wildcard match
+                       $use_apc = ($host == $config->cache_key);
+                       $config->cache_key = null;
+                       SiteConfig::add_to_cache("$host.merged", $config, $use_apc);
+               }
+               return $config;
+       }
+       
+       // returns true on success, false on failure
+       // $smart_tidy indicates that if tidy is used and no results are produced, we will
+       // try again without it. Tidy helps us deal with PHP's patchy HTML parsing most of the time
+       // but it has problems of its own which we try to avoid with this option.
+       public function process($html, $url, $smart_tidy=true) {
+               $this->reset();
+               $this->config = $this->buildSiteConfig($url, $html);
+               
+               // do string replacements
+               if (!empty($this->config->find_string)) {
+                       if (count($this->config->find_string) == count($this->config->replace_string)) {
+                               $html = str_replace($this->config->find_string, $this->config->replace_string, $html, $_count);
+                               $this->debug("Strings replaced: $_count (find_string and/or replace_string)");
+                       } else {
+                               $this->debug('Skipped string replacement - incorrect number of find-replace strings in site config');
+                       }
+                       unset($_count);
+               }
+               
+               // use tidy (if it exists)?
+               // This fixes problems with some sites which would otherwise
+               // trouble DOMDocument's HTML parsing. (Although sometimes it
+               // makes matters worse, which is why you can override it in site config files.)
+               $tidied = false;
+               if ($this->config->tidy() && function_exists('tidy_parse_string') && $smart_tidy) {
+                       $this->debug('Using Tidy');
+                       $tidy = tidy_parse_string($html, self::$tidy_config, 'UTF8');
+                       if (tidy_clean_repair($tidy)) {
+                               $original_html = $html;
+                               $tidied = true;
+                               $html = $tidy->value;
+                       }
+                       unset($tidy);
+               }
+               
+               // load and parse html
+               $_parser = $this->config->parser();
+               if (!in_array($_parser, $this->allowedParsers)) {
+                       $this->debug("HTML parser $_parser not listed, using libxml instead");
+                       $_parser = 'libxml';
+               }
+               $this->debug("Attempting to parse HTML with $_parser");
+               $this->readability = new Readability($html, $url, $_parser);
+               
+               // we use xpath to find elements in the given HTML document
+               // see http://en.wikipedia.org/wiki/XPath_1.0
+               $xpath = new DOMXPath($this->readability->dom);
+
+               // try to get next page link
+               foreach ($this->config->next_page_link as $pattern) {
+                       $elems = @$xpath->evaluate($pattern, $this->readability->dom);
+                       if (is_string($elems)) {
+                               $this->nextPageUrl = trim($elems);
+                               break;
+                       } elseif ($elems instanceof DOMNodeList && $elems->length > 0) {
+                               foreach ($elems as $item) {
+                                       if ($item instanceof DOMElement && $item->hasAttribute('href')) {
+                                               $this->nextPageUrl = $item->getAttribute('href');
+                                               break 2;
+                                       } elseif ($item instanceof DOMAttr && $item->value) {
+                                               $this->nextPageUrl = $item->value;
+                                               break 2;
+                                       }
+                               }
+                       }
+               }
+               
+               // try to get title
+               foreach ($this->config->title as $pattern) {
+                       // $this->debug("Trying $pattern");
+                       $elems = @$xpath->evaluate($pattern, $this->readability->dom);
+                       if (is_string($elems)) {
+                               $this->title = trim($elems);
+                               $this->debug('Title expression evaluated as string: '.$this->title);
+                               $this->debug("...XPath match: $pattern");
+                               break;
+                       } elseif ($elems instanceof DOMNodeList && $elems->length > 0) {
+                               $this->title = $elems->item(0)->textContent;
+                               $this->debug('Title matched: '.$this->title);
+                               $this->debug("...XPath match: $pattern");
+                               // remove title from document
+                               try {
+                                       @$elems->item(0)->parentNode->removeChild($elems->item(0));
+                               } catch (DOMException $e) {
+                                       // do nothing
+                               }
+                               break;
+                       }
+               }
+               
+               // try to get author (if it hasn't already been set)
+               if (empty($this->author)) {
+                       foreach ($this->config->author as $pattern) {
+                               $elems = @$xpath->evaluate($pattern, $this->readability->dom);
+                               if (is_string($elems)) {
+                                       if (trim($elems) != '') {
+                                               $this->author[] = trim($elems);
+                                               $this->debug('Author expression evaluated as string: '.trim($elems));
+                                               $this->debug("...XPath match: $pattern");
+                                               break;
+                                       }
+                               } elseif ($elems instanceof DOMNodeList && $elems->length > 0) {
+                                       foreach ($elems as $elem) {
+                                               if (!isset($elem->parentNode)) continue;
+                                               $this->author[] = trim($elem->textContent);
+                                               $this->debug('Author matched: '.trim($elem->textContent));
+                                       }
+                                       if (!empty($this->author)) {
+                                               $this->debug("...XPath match: $pattern");
+                                               break;
+                                       }
+                               }
+                       }
+               }
+               
+               // try to get language
+               $_lang_xpath = array('//html[@lang]/@lang', '//meta[@name="DC.language"]/@content');
+               foreach ($_lang_xpath as $pattern) {
+                       $elems = @$xpath->evaluate($pattern, $this->readability->dom);
+                       if (is_string($elems)) {
+                               if (trim($elems) != '') {
+                                       $this->language = trim($elems);
+                                       $this->debug('Language matched: '.$this->language);
+                                       break;
+                               }
+                       } elseif ($elems instanceof DOMNodeList && $elems->length > 0) {
+                               foreach ($elems as $elem) {
+                                       if (!isset($elem->parentNode)) continue;
+                                       $this->language = trim($elem->textContent);
+                                       $this->debug('Language matched: '.$this->language);                                     
+                               }
+                               if ($this->language) break;
+                       }
+               }
+               
+               // try to get date
+               foreach ($this->config->date as $pattern) {
+                       $elems = @$xpath->evaluate($pattern, $this->readability->dom);
+                       if (is_string($elems)) {
+                               $this->date = strtotime(trim($elems, "; \t\n\r\0\x0B"));                                
+                       } elseif ($elems instanceof DOMNodeList && $elems->length > 0) {
+                               $this->date = $elems->item(0)->textContent;
+                               $this->date = strtotime(trim($this->date, "; \t\n\r\0\x0B"));
+                               // remove date from document
+                               // $elems->item(0)->parentNode->removeChild($elems->item(0));
+                       }
+                       if (!$this->date) {
+                               $this->date = null;
+                       } else {
+                               $this->debug('Date matched: '.date('Y-m-d H:i:s', $this->date));
+                               $this->debug("...XPath match: $pattern");
+                               break;
+                       }
+               }
+
+               // strip elements (using xpath expressions)
+               foreach ($this->config->strip as $pattern) {
+                       $elems = @$xpath->query($pattern, $this->readability->dom);
+                       // check for matches
+                       if ($elems && $elems->length > 0) {
+                               $this->debug('Stripping '.$elems->length.' elements (strip)');
+                               for ($i=$elems->length-1; $i >= 0; $i--) {
+                                       $elems->item($i)->parentNode->removeChild($elems->item($i));
+                               }
+                       }
+               }
+               
+               // strip elements (using id and class attribute values)
+               foreach ($this->config->strip_id_or_class as $string) {
+                       $string = strtr($string, array("'"=>'', '"'=>''));
+                       $elems = @$xpath->query("//*[contains(@class, '$string') or contains(@id, '$string')]", $this->readability->dom);
+                       // check for matches
+                       if ($elems && $elems->length > 0) {
+                               $this->debug('Stripping '.$elems->length.' elements (strip_id_or_class)');
+                               for ($i=$elems->length-1; $i >= 0; $i--) {
+                                       $elems->item($i)->parentNode->removeChild($elems->item($i));
+                               }
+                       }
+               }
+               
+               // strip images (using src attribute values)
+               foreach ($this->config->strip_image_src as $string) {
+                       $string = strtr($string, array("'"=>'', '"'=>''));
+                       $elems = @$xpath->query("//img[contains(@src, '$string')]", $this->readability->dom);
+                       // check for matches
+                       if ($elems && $elems->length > 0) {
+                               $this->debug('Stripping '.$elems->length.' image elements');
+                               for ($i=$elems->length-1; $i >= 0; $i--) {
+                                       $elems->item($i)->parentNode->removeChild($elems->item($i));
+                               }
+                       }
+               }
+               // strip elements using Readability.com and Instapaper.com ignore class names
+               // .entry-unrelated and .instapaper_ignore
+               // See https://www.readability.com/publishers/guidelines/#view-plainGuidelines
+               // and http://blog.instapaper.com/post/730281947
+               $elems = @$xpath->query("//*[contains(concat(' ',normalize-space(@class),' '),' entry-unrelated ') or contains(concat(' ',normalize-space(@class),' '),' instapaper_ignore ')]", $this->readability->dom);
+               // check for matches
+               if ($elems && $elems->length > 0) {
+                       $this->debug('Stripping '.$elems->length.' .entry-unrelated,.instapaper_ignore elements');
+                       for ($i=$elems->length-1; $i >= 0; $i--) {
+                               $elems->item($i)->parentNode->removeChild($elems->item($i));
+                       }
+               }
+               
+               // strip elements that contain style="display: none;"
+               $elems = @$xpath->query("//*[contains(@style,'display:none')]", $this->readability->dom);
+               // check for matches
+               if ($elems && $elems->length > 0) {
+                       $this->debug('Stripping '.$elems->length.' elements with inline display:none style');
+                       for ($i=$elems->length-1; $i >= 0; $i--) {
+                               $elems->item($i)->parentNode->removeChild($elems->item($i));
+                       }
+               }
+               
+               // try to get body
+               foreach ($this->config->body as $pattern) {
+                       $elems = @$xpath->query($pattern, $this->readability->dom);
+                       // check for matches
+                       if ($elems && $elems->length > 0) {
+                               $this->debug('Body matched');
+                               $this->debug("...XPath match: $pattern");
+                               if ($elems->length == 1) {                              
+                                       $this->body = $elems->item(0);
+                                       // prune (clean up elements that may not be content)
+                                       if ($this->config->prune()) {
+                                               $this->debug('...pruning content');
+                                               $this->readability->prepArticle($this->body);
+                                       }
+                                       break;
+                               } else {
+                                       $this->body = $this->readability->dom->createElement('div');
+                                       $this->debug($elems->length.' body elems found');
+                                       foreach ($elems as $elem) {
+                                               if (!isset($elem->parentNode)) continue;
+                                               $isDescendant = false;
+                                               foreach ($this->body->childNodes as $parent) {
+                                                       if ($this->isDescendant($parent, $elem)) {
+                                                               $isDescendant = true;
+                                                               break;
+                                                       }
+                                               }
+                                               if ($isDescendant) {
+                                                       $this->debug('...element is child of another body element, skipping.');
+                                               } else {
+                                                       // prune (clean up elements that may not be content)
+                                                       if ($this->config->prune()) {
+                                                               $this->debug('Pruning content');
+                                                               $this->readability->prepArticle($elem);
+                                                       }
+                                                       $this->debug('...element added to body');
+                                                       $this->body->appendChild($elem);
+                                               }
+                                       }
+                                       if ($this->body->hasChildNodes()) break;
+                               }
+                       }
+               }               
+               
+               // auto detect?
+               $detect_title = $detect_body = $detect_author = $detect_date = false;
+               // detect title?
+               if (!isset($this->title)) {
+                       if (empty($this->config->title) || $this->config->autodetect_on_failure()) {
+                               $detect_title = true;
+                       }
+               }
+               // detect body?
+               if (!isset($this->body)) {
+                       if (empty($this->config->body) || $this->config->autodetect_on_failure()) {
+                               $detect_body = true;
+                       }
+               }
+               // detect author?
+               if (empty($this->author)) {
+                       if (empty($this->config->author) || $this->config->autodetect_on_failure()) {
+                               $detect_author = true;
+                       }
+               }
+               // detect date?
+               if (!isset($this->date)) {
+                       if (empty($this->config->date) || $this->config->autodetect_on_failure()) {
+                               $detect_date = true;
+                       }
+               }
+
+               // check for hNews
+               if ($detect_title || $detect_body) {
+                       // check for hentry
+                       $elems = @$xpath->query("//*[contains(concat(' ',normalize-space(@class),' '),' hentry ')]", $this->readability->dom);
+                       if ($elems && $elems->length > 0) {
+                               $this->debug('hNews: found hentry');
+                               $hentry = $elems->item(0);
+                               
+                               if ($detect_title) {
+                                       // check for entry-title
+                                       $elems = @$xpath->query(".//*[contains(concat(' ',normalize-space(@class),' '),' entry-title ')]", $hentry);
+                                       if ($elems && $elems->length > 0) {
+                                               $this->title = $elems->item(0)->textContent;
+                                               $this->debug('hNews: found entry-title: '.$this->title);
+                                               // remove title from document
+                                               $elems->item(0)->parentNode->removeChild($elems->item(0));
+                                               $detect_title = false;
+                                       }
+                               }
+                               
+                               if ($detect_date) {
+                                       // check for time element with pubdate attribute
+                                       $elems = @$xpath->query(".//time[@pubdate] | .//abbr[contains(concat(' ',normalize-space(@class),' '),' published ')]", $hentry);
+                                       if ($elems && $elems->length > 0) {
+                                               $this->date = strtotime(trim($elems->item(0)->textContent));
+                                               // remove date from document
+                                               //$elems->item(0)->parentNode->removeChild($elems->item(0));
+                                               if ($this->date) {
+                                                       $this->debug('hNews: found publication date: '.date('Y-m-d H:i:s', $this->date));
+                                                       $detect_date = false;
+                                               } else {
+                                                       $this->date = null;
+                                               }
+                                       }
+                               }
+
+                               if ($detect_author) {
+                                       // check for time element with pubdate attribute
+                                       $elems = @$xpath->query(".//*[contains(concat(' ',normalize-space(@class),' '),' vcard ') and (contains(concat(' ',normalize-space(@class),' '),' author ') or contains(concat(' ',normalize-space(@class),' '),' byline '))]", $hentry);
+                                       if ($elems && $elems->length > 0) {
+                                               $author = $elems->item(0);
+                                               $fn = @$xpath->query(".//*[contains(concat(' ',normalize-space(@class),' '),' fn ')]", $author);
+                                               if ($fn && $fn->length > 0) {
+                                                       foreach ($fn as $_fn) {
+                                                               if (trim($_fn->textContent) != '') {
+                                                                       $this->author[] = trim($_fn->textContent);
+                                                                       $this->debug('hNews: found author: '.trim($_fn->textContent));
+                                                               }
+                                                       }
+                                               } else {
+                                                       if (trim($author->textContent) != '') {
+                                                               $this->author[] = trim($author->textContent);
+                                                               $this->debug('hNews: found author: '.trim($author->textContent));
+                                                       }
+                                               }
+                                               $detect_author = empty($this->author);
+                                       }
+                               }
+                               
+                               // check for entry-content.
+                               // according to hAtom spec, if there are multiple elements marked entry-content,
+                               // we include all of these in the order they appear - see http://microformats.org/wiki/hatom#Entry_Content
+                               if ($detect_body) {
+                                       $elems = @$xpath->query(".//*[contains(concat(' ',normalize-space(@class),' '),' entry-content ')]", $hentry);
+                                       if ($elems && $elems->length > 0) {
+                                               $this->debug('hNews: found entry-content');
+                                               if ($elems->length == 1) {
+                                                       // what if it's empty? (some sites misuse hNews - place their content outside an empty entry-content element)
+                                                       $e = $elems->item(0);
+                                                       if (($e->tagName == 'img') || (trim($e->textContent) != '')) {
+                                                               $this->body = $elems->item(0);
+                                                               // prune (clean up elements that may not be content)
+                                                               if ($this->config->prune()) {
+                                                                       $this->debug('Pruning content');
+                                                                       $this->readability->prepArticle($this->body);
+                                                               }
+                                                               $detect_body = false;
+                                                       } else {
+                                                               $this->debug('hNews: skipping entry-content - appears not to contain content');
+                                                       }
+                                                       unset($e);
+                                               } else {
+                                                       $this->body = $this->readability->dom->createElement('div');
+                                                       $this->debug($elems->length.' entry-content elems found');
+                                                       foreach ($elems as $elem) {
+                                                               if (!isset($elem->parentNode)) continue;
+                                                               $isDescendant = false;
+                                                               foreach ($this->body->childNodes as $parent) {
+                                                                       if ($this->isDescendant($parent, $elem)) {
+                                                                               $isDescendant = true;
+                                                                               break;
+                                                                       }
+                                                               }
+                                                               if ($isDescendant) {
+                                                                       $this->debug('Element is child of another body element, skipping.');
+                                                               } else {
+                                                                       // prune (clean up elements that may not be content)
+                                                                       if ($this->config->prune()) {
+                                                                               $this->debug('Pruning content');
+                                                                               $this->readability->prepArticle($elem);
+                                                                       }                                                               
+                                                                       $this->debug('Element added to body');                                                                  
+                                                                       $this->body->appendChild($elem);
+                                                               }
+                                                       }
+                                                       $detect_body = false;
+                                               }
+                                       }
+                               }
+                       }
+               }
+
+               // check for elements marked with instapaper_title
+               if ($detect_title) {
+                       // check for instapaper_title
+                       $elems = @$xpath->query("//*[contains(concat(' ',normalize-space(@class),' '),' instapaper_title ')]", $this->readability->dom);
+                       if ($elems && $elems->length > 0) {
+                               $this->title = $elems->item(0)->textContent;
+                               $this->debug('Title found (.instapaper_title): '.$this->title);
+                               // remove title from document
+                               $elems->item(0)->parentNode->removeChild($elems->item(0));
+                               $detect_title = false;
+                       }
+               }
+               // check for elements marked with instapaper_body
+               if ($detect_body) {
+                       $elems = @$xpath->query("//*[contains(concat(' ',normalize-space(@class),' '),' instapaper_body ')]", $this->readability->dom);
+                       if ($elems && $elems->length > 0) {
+                               $this->debug('body found (.instapaper_body)');
+                               $this->body = $elems->item(0);
+                               // prune (clean up elements that may not be content)
+                               if ($this->config->prune()) {
+                                       $this->debug('Pruning content');
+                                       $this->readability->prepArticle($this->body);
+                               }
+                               $detect_body = false;
+                       }
+               }
+               
+               // Find author in rel="author" marked element
+               // We only use this if there's exactly one.
+               // If there's more than one, it could indicate more than
+               // one author, but it could also indicate that we're processing
+               // a page listing different articles with different authors.
+               if ($detect_author) {
+                       $elems = @$xpath->query("//a[contains(concat(' ',normalize-space(@rel),' '),' author ')]", $this->readability->dom);
+                       if ($elems && $elems->length == 1) {
+                               $author = trim($elems->item(0)->textContent);
+                               if ($author != '') {
+                                       $this->debug("Author found (rel=\"author\"): $author");
+                                       $this->author[] = $author;
+                                       $detect_author = false;
+                               }
+                       }
+               }
+
+               // Find date in pubdate marked time element
+               // For the same reason given above, we only use this
+               // if there's exactly one element.
+               if ($detect_date) {
+                       $elems = @$xpath->query("//time[@pubdate]", $this->readability->dom);
+                       if ($elems && $elems->length == 1) {
+                               $this->date = strtotime(trim($elems->item(0)->textContent));
+                               // remove date from document
+                               //$elems->item(0)->parentNode->removeChild($elems->item(0));
+                               if ($this->date) {
+                                       $this->debug('Date found (pubdate marked time element): '.date('Y-m-d H:i:s', $this->date));
+                                       $detect_date = false;
+                               } else {
+                                       $this->date = null;
+                               }
+                       }
+               }
+
+               // still missing title or body, so we detect using Readability
+               if ($detect_title || $detect_body) {
+                       $this->debug('Using Readability');
+                       // clone body if we're only using Readability for title (otherwise it may interfere with body element)
+                       if (isset($this->body)) $this->body = $this->body->cloneNode(true);
+                       $success = $this->readability->init();
+               }
+               if ($detect_title) {
+                       $this->debug('Detecting title');
+                       $this->title = $this->readability->getTitle()->textContent;
+               }
+               if ($detect_body && $success) {
+                       $this->debug('Detecting body');
+                       $this->body = $this->readability->getContent();
+                       if ($this->body->childNodes->length == 1 && $this->body->firstChild->nodeType === XML_ELEMENT_NODE) {
+                               $this->body = $this->body->firstChild;
+                       }
+                       // prune (clean up elements that may not be content)
+                       if ($this->config->prune()) {
+                               $this->debug('Pruning content');
+                               $this->readability->prepArticle($this->body);
+                       }
+               }
+               if (isset($this->body)) {
+                       // remove scripts
+                       $this->readability->removeScripts($this->body);
+                       // remove any h1-h6 elements that appear as first thing in the body
+                       // and which match our title
+                       if (isset($this->title) && ($this->title != '')) {
+                               $firstChild = $this->body->firstChild;
+                               while ($firstChild->nodeType && ($firstChild->nodeType !== XML_ELEMENT_NODE)) {
+                                       $firstChild = $firstChild->nextSibling;
+                               }
+                               if (($firstChild->nodeType === XML_ELEMENT_NODE)
+                                       && in_array(strtolower($firstChild->tagName), array('h1', 'h2', 'h3', 'h4', 'h5', 'h6'))
+                                       && (strtolower(trim($firstChild->textContent)) == strtolower(trim($this->title)))) {
+                                               $this->body->removeChild($firstChild);
+                               }
+                       }
+                       // prevent self-closing iframes
+                       $elems = $this->body->getElementsByTagName('iframe');
+                       for ($i = $elems->length-1; $i >= 0; $i--) {
+                               $e = $elems->item($i);
+                               if (!$e->hasChildNodes()) {
+                                       $e->appendChild($this->body->ownerDocument->createTextNode('[embedded content]'));
+                               }
+                       }
+                       // remove image lazy loading - WordPress plugin http://wordpress.org/extend/plugins/lazy-load/
+                       // the plugin replaces the src attribute to point to a 1x1 gif and puts the original src
+                       // inside the data-lazy-src attribute. It also places the original image inside a noscript element 
+                       // next to the amended one.
+                       $elems = @$xpath->query("//img[@data-lazy-src]", $this->body);
+                       for ($i = $elems->length-1; $i >= 0; $i--) {
+                               $e = $elems->item($i);
+                               // let's see if we can grab image from noscript
+                               if ($e->nextSibling !== null && $e->nextSibling->nodeName === 'noscript') {
+                                       $_new_elem = $e->ownerDocument->createDocumentFragment();
+                                       @$_new_elem->appendXML($e->nextSibling->innerHTML);
+                                       $e->nextSibling->parentNode->replaceChild($_new_elem, $e->nextSibling);
+                                       $e->parentNode->removeChild($e);
+                               } else {
+                                       // Use data-lazy-src as src value
+                                       $e->setAttribute('src', $e->getAttribute('data-lazy-src'));
+                                       $e->removeAttribute('data-lazy-src');
+                               }
+                       }
+               
+                       $this->success = true;
+               }
+               
+               // if we've had no success and we've used tidy, there's a chance
+               // that tidy has messed up. So let's try again without tidy...
+               if (!$this->success && $tidied && $smart_tidy) {
+                       $this->debug('Trying again without tidy');
+                       $this->process($original_html, $url, false);
+               }
+
+               return $this->success;
+       }
+       
+       private function isDescendant(DOMElement $parent, DOMElement $child) {
+               $node = $child->parentNode;
+               while ($node != null) {
+                       if ($node->isSameNode($parent)) return true;
+                       $node = $node->parentNode;
+               }
+               return false;
+       }
+
+       public function getContent() {
+               return $this->body;
+       }
+       
+       public function getTitle() {
+               return $this->title;
+       }
+       
+       public function getAuthors() {
+               return $this->author;
+       }
+       
+       public function getLanguage() {
+               return $this->language;
+       }
+       
+       public function getDate() {
+               return $this->date;
+       }
+       
+       public function getSiteConfig() {
+               return $this->config;
+       }
+       
+       public function getNextPageUrl() {
+               return $this->nextPageUrl;
+       }
+}
\ No newline at end of file
index c5e300d7a1e5d0ff7bdf175fe94a91e2796f2bcb..1f6a7603bd2b0b3d9dcdd14d6fb04b37fac1d887 100644 (file)
-<?php\r
-/**\r
- * Site Config\r
- * \r
- * Each instance of this class should hold extraction patterns and other directives\r
- * for a website. See ContentExtractor class to see how it's used.\r
- * \r
- * @version 0.7\r
- * @date 2012-08-27\r
- * @author Keyvan Minoukadeh\r
- * @copyright 2012 Keyvan Minoukadeh\r
- * @license http://www.gnu.org/licenses/agpl-3.0.html AGPL v3\r
- */\r
-\r
-class SiteConfig\r
-{\r
-       // Use first matching element as title (0 or more xpath expressions)\r
-       public $title = array();\r
-       \r
-       // Use first matching element as body (0 or more xpath expressions)\r
-       public $body = array();\r
-       \r
-       // Use first matching element as author (0 or more xpath expressions)\r
-       public $author = array();\r
-       \r
-       // Use first matching element as date (0 or more xpath expressions)\r
-       public $date = array();\r
-       \r
-       // Strip elements matching these xpath expressions (0 or more)\r
-       public $strip = array();\r
-       \r
-       // Strip elements which contain these strings (0 or more) in the id or class attribute \r
-       public $strip_id_or_class = array();\r
-       \r
-       // Strip images which contain these strings (0 or more) in the src attribute \r
-       public $strip_image_src = array();\r
-       \r
-       // Additional HTTP headers to send\r
-       // NOT YET USED\r
-       public $http_header = array();\r
-       \r
-       // Process HTML with tidy before creating DOM (bool or null if undeclared)\r
-       public $tidy = null;\r
-       \r
-       protected $default_tidy = true; // used if undeclared\r
-       \r
-       // Autodetect title/body if xpath expressions fail to produce results.\r
-       // Note that this applies to title and body separately, ie. \r
-       //   * if we get a body match but no title match, this option will determine whether we autodetect title \r
-       //   * if neither match, this determines whether we autodetect title and body.\r
-       // Also note that this only applies when there is at least one xpath expression in title or body, ie.\r
-       //   * if title and body are both empty (no xpath expressions), this option has no effect (both title and body will be auto-detected)\r
-       //   * if there's an xpath expression for title and none for body, body will be auto-detected and this option will determine whether we auto-detect title if the xpath expression for it fails to produce results.\r
-       // Usage scenario: you want to extract something specific from a set of URLs, e.g. a table, and if the table is not found, you want to ignore the entry completely. Auto-detection is unlikely to succeed here, so you construct your patterns and set this option to false. Another scenario may be a site where auto-detection has proven to fail (or worse, picked up the wrong content).\r
-       // bool or null if undeclared\r
-       public $autodetect_on_failure = null;\r
-       protected $default_autodetect_on_failure = true; // used if undeclared\r
-       \r
-       // Clean up content block - attempt to remove elements that appear to be superfluous\r
-       // bool or null if undeclared\r
-       public $prune = null;\r
-       protected $default_prune = true; // used if undeclared\r
-       \r
-       // Test URL - if present, can be used to test the config above\r
-       public $test_url = array();\r
-       \r
-       // Single-page link - should identify a link element or URL pointing to the page holding the entire article\r
-       // This is useful for sites which split their articles across multiple pages. Links to such pages tend to \r
-       // display the first page with links to the other pages at the bottom. Often there is also a link to a page\r
-       // which displays the entire article on one page (e.g. 'print view').\r
-       // This should be an XPath expression identifying the link to that page. If present and we find a match,\r
-       // we will retrieve that page and the rest of the options in this config will be applied to the new page.\r
-       public $single_page_link = array();\r
-       \r
-       public $next_page_link = array();\r
-       \r
-       // Single-page link in feed? - same as above, but patterns applied to item description HTML taken from feed\r
-       public $single_page_link_in_feed = array();\r
-       \r
-       // Which parser to use for turning raw HTML into a DOMDocument (either 'libxml' or 'html5lib')\r
-       // string or null if undeclared\r
-       public $parser = null;\r
-       protected $default_parser = 'libxml'; // used if undeclared\r
-       \r
-       // Strings to search for in HTML before processing begins (used with $replace_string)\r
-       public $find_string = array();\r
-       // Strings to replace those found in $find_string before HTML processing begins\r
-       public $replace_string = array();\r
-       \r
-       // the options below cannot be set in the config files which this class represents\r
-       \r
-       //public $cache_in_apc = false; // used to decide if we should cache in apc or not\r
-       public $cache_key = null;\r
-       public static $debug = false;\r
-       protected static $apc = false;\r
-       protected static $config_path;\r
-       protected static $config_path_fallback;\r
-       protected static $config_cache = array();\r
-       const HOSTNAME_REGEX = '/^(([a-zA-Z0-9-]*[a-zA-Z0-9])\.)*([A-Za-z0-9-]*[A-Za-z0-9])$/';\r
-       \r
-       protected static function debug($msg) {\r
-               if (self::$debug) {\r
-                       //$mem = round(memory_get_usage()/1024, 2);\r
-                       //$memPeak = round(memory_get_peak_usage()/1024, 2);\r
-                       echo '* ',$msg;\r
-                       //echo ' - mem used: ',$mem," (peak: $memPeak)\n";\r
-                       echo "\n";\r
-                       ob_flush();\r
-                       flush();\r
-               }\r
-       }\r
-       \r
-       // enable APC caching of certain site config files?\r
-       // If enabled the following site config files will be \r
-       // cached in APC cache (when requested for first time):\r
-       // * anything in site_config/custom/ and its corresponding file in site_config/standard/\r
-       // * the site config files associated with HTML fingerprints\r
-       // * the global site config file\r
-       // returns true if enabled, false otherwise\r
-       public static function use_apc($apc=true) {\r
-               if (!function_exists('apc_add')) {\r
-                       if ($apc) self::debug('APC will not be used (function apc_add does not exist)');\r
-                       return false;\r
-               }\r
-               self::$apc = $apc;\r
-               return $apc;\r
-       }\r
-       \r
-       // return bool or null\r
-       public function tidy($use_default=true) {\r
-               if ($use_default) return (isset($this->tidy)) ? $this->tidy : $this->default_tidy;\r
-               return $this->tidy;\r
-       }\r
-       \r
-       // return bool or null\r
-       public function prune($use_default=true) {\r
-               if ($use_default) return (isset($this->prune)) ? $this->prune : $this->default_prune;\r
-               return $this->prune;\r
-       }\r
-       \r
-       // return string or null\r
-       public function parser($use_default=true) {\r
-               if ($use_default) return (isset($this->parser)) ? $this->parser : $this->default_parser;\r
-               return $this->parser;\r
-       }\r
-\r
-       // return bool or null\r
-       public function autodetect_on_failure($use_default=true) {\r
-               if ($use_default) return (isset($this->autodetect_on_failure)) ? $this->autodetect_on_failure : $this->default_autodetect_on_failure;\r
-               return $this->autodetect_on_failure;\r
-       }\r
-       \r
-       public static function set_config_path($path, $fallback=null) {\r
-               self::$config_path = $path;\r
-               self::$config_path_fallback = $fallback;\r
-       }\r
-       \r
-       public static function add_to_cache($key, SiteConfig $config, $use_apc=true) {\r
-               $key = strtolower($key);\r
-               if (substr($key, 0, 4) == 'www.') $key = substr($key, 4);\r
-               if ($config->cache_key) $key = $config->cache_key;\r
-               self::$config_cache[$key] = $config;\r
-               if (self::$apc && $use_apc) {\r
-                       self::debug("Adding site config to APC cache with key sc.$key");\r
-                       apc_add("sc.$key", $config);\r
-               }\r
-               self::debug("Cached site config with key $key");\r
-       }\r
-       \r
-       public static function is_cached($key) {\r
-               $key = strtolower($key);\r
-               if (substr($key, 0, 4) == 'www.') $key = substr($key, 4);\r
-               if (array_key_exists($key, self::$config_cache)) {\r
-                       return true;\r
-               } elseif (self::$apc && (bool)apc_fetch("sc.$key")) {\r
-                       return true;\r
-               }\r
-               return false;\r
-       }\r
-       \r
-       public function append(SiteConfig $newconfig) {\r
-               // check for commands where we accept multiple statements (no test_url)\r
-               foreach (array('title', 'body', 'author', 'date', 'strip', 'strip_id_or_class', 'strip_image_src', 'single_page_link', 'single_page_link_in_feed', 'next_page_link', 'http_header', 'find_string', 'replace_string') as $var) {\r
-                       // append array elements for this config variable from $newconfig to this config\r
-                       //$this->$var = $this->$var + $newconfig->$var;\r
-                       $this->$var = array_unique(array_merge($this->$var, $newconfig->$var));\r
-               }\r
-               // check for single statement commands\r
-               // we do not overwrite existing non null values\r
-               foreach (array('tidy', 'prune', 'parser', 'autodetect_on_failure') as $var) {\r
-                       if ($this->$var === null) $this->$var = $newconfig->$var;\r
-               }\r
-       }\r
-       \r
-       // returns SiteConfig instance if an appropriate one is found, false otherwise\r
-       // if $exact_host_match is true, we will not look for wildcard config matches\r
-       // by default if host is 'test.example.org' we will look for and load '.example.org.txt' if it exists\r
-       public static function build($host, $exact_host_match=false) {\r
-               $host = strtolower($host);\r
-               if (substr($host, 0, 4) == 'www.') $host = substr($host, 4);\r
-               if (!$host || (strlen($host) > 200) || !preg_match(self::HOSTNAME_REGEX, ltrim($host, '.'))) return false;\r
-               // check for site configuration\r
-               $try = array($host);\r
-               // should we look for wildcard matches \r
-               if (!$exact_host_match) {\r
-                       $split = explode('.', $host);\r
-                       if (count($split) > 1) {\r
-                               array_shift($split);\r
-                               $try[] = '.'.implode('.', $split);\r
-                       }\r
-               }\r
-               \r
-               // look for site config file in primary folder\r
-               self::debug(". looking for site config for $host in primary folder");\r
-               foreach ($try as $h) {\r
-                       if (array_key_exists($h, self::$config_cache)) {\r
-                               self::debug("... site config for $h already loaded in this request");\r
-                               return self::$config_cache[$h];\r
-                       } elseif (self::$apc && ($sconfig = apc_fetch("sc.$h"))) {\r
-                               self::debug("... site config for $h in APC cache");\r
-                               return $sconfig;\r
-                       } elseif (file_exists(self::$config_path."/$h.txt")) {\r
-                               self::debug("... found site config ($h.txt)");\r
-                               $file_primary = self::$config_path."/$h.txt";\r
-                               $matched_name = $h;\r
-                               break;\r
-                       }\r
-               }\r
-               \r
-               // if we found site config, process it\r
-               if (isset($file_primary)) {\r
-                       $config_lines = file($file_primary, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);\r
-                       if (!$config_lines || !is_array($config_lines)) return false;\r
-                       $config = self::build_from_array($config_lines);\r
-                       // if APC caching is available and enabled, mark this for cache\r
-                       //$config->cache_in_apc = true;\r
-                       $config->cache_key = $matched_name;\r
-                       \r
-                       // if autodetec on failure is off (on by default) we do not need to look\r
-                       // in secondary folder\r
-                       if (!$config->autodetect_on_failure()) {\r
-                               self::debug('... autodetect on failure is disabled (no other site config files will be loaded)');\r
-                               return $config;\r
-                       }\r
-               }\r
-               \r
-               // look for site config file in secondary folder\r
-               if (isset(self::$config_path_fallback)) {\r
-                       self::debug(". looking for site config for $host in secondary folder");\r
-                       foreach ($try as $h) {\r
-                               if (file_exists(self::$config_path_fallback."/$h.txt")) {\r
-                                       self::debug("... found site config in secondary folder ($h.txt)");\r
-                                       $file_secondary = self::$config_path_fallback."/$h.txt";\r
-                                       $matched_name = $h;\r
-                                       break;\r
-                               }\r
-                       }\r
-                       if (!isset($file_secondary)) {\r
-                               self::debug("... no site config match in secondary folder");\r
-                       }\r
-               }\r
-               \r
-               // return false if no config file found\r
-               if (!isset($file_primary) && !isset($file_secondary)) {\r
-                       self::debug("... no site config match for $host");\r
-                       return false;\r
-               }\r
-               \r
-               // return primary config if secondary not found\r
-               if (!isset($file_secondary) && isset($config)) {\r
-                       return $config;\r
-               }\r
-               \r
-               // process secondary config file\r
-               $config_lines = file($file_secondary, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);\r
-               if (!$config_lines || !is_array($config_lines)) {\r
-                       // failed to process secondary\r
-                       if (isset($config)) {\r
-                               // return primary config\r
-                               return $config;\r
-                       } else {\r
-                               return false;\r
-                       }\r
-               }\r
-               \r
-               // merge with primary and return\r
-               if (isset($config)) {\r
-                       self::debug('. merging config files');\r
-                       $config->append(self::build_from_array($config_lines));\r
-                       return $config;\r
-               } else {\r
-                       // return just secondary\r
-                       $config = self::build_from_array($config_lines);\r
-                       // if APC caching is available and enabled, mark this for cache\r
-                       //$config->cache_in_apc = true;\r
-                       $config->cache_key = $matched_name;\r
-                       return $config;\r
-               }\r
-       }\r
-       \r
-       public static function build_from_array(array $lines) {\r
-               $config = new SiteConfig();\r
-               foreach ($lines as $line) {\r
-                       $line = trim($line);\r
-                       \r
-                       // skip comments, empty lines\r
-                       if ($line == '' || $line[0] == '#') continue;\r
-                       \r
-                       // get command\r
-                       $command = explode(':', $line, 2);\r
-                       // if there's no colon ':', skip this line\r
-                       if (count($command) != 2) continue;\r
-                       $val = trim($command[1]);\r
-                       $command = trim($command[0]);\r
-                       if ($command == '' || $val == '') continue;\r
-                       \r
-                       // check for commands where we accept multiple statements\r
-                       if (in_array($command, array('title', 'body', 'author', 'date', 'strip', 'strip_id_or_class', 'strip_image_src', 'single_page_link', 'single_page_link_in_feed', 'next_page_link', 'http_header', 'test_url', 'find_string', 'replace_string'))) {\r
-                               array_push($config->$command, $val);\r
-                       // check for single statement commands that evaluate to true or false\r
-                       } elseif (in_array($command, array('tidy', 'prune', 'autodetect_on_failure'))) {\r
-                               $config->$command = ($val == 'yes');\r
-                       // check for single statement commands stored as strings\r
-                       } elseif (in_array($command, array('parser'))) {\r
-                               $config->$command = $val;\r
-                       // check for replace_string(find): replace\r
-                       } elseif ((substr($command, -1) == ')') && preg_match('!^([a-z0-9_]+)\((.*?)\)$!i', $command, $match)) {\r
-                               if (in_array($match[1], array('replace_string'))) {\r
-                                       $command = $match[1];\r
-                                       array_push($config->find_string, $match[2]);\r
-                                       array_push($config->$command, $val);\r
-                               }\r
-                       }\r
-               }\r
-               return $config;\r
-       }\r
-}\r
-?>
\ No newline at end of file
+<?php
+/**
+ * Site Config
+ * 
+ * Each instance of this class should hold extraction patterns and other directives
+ * for a website. See ContentExtractor class to see how it's used.
+ * 
+ * @version 0.8
+ * @date 2013-04-16
+ * @author Keyvan Minoukadeh
+ * @copyright 2013 Keyvan Minoukadeh
+ * @license http://www.gnu.org/licenses/agpl-3.0.html AGPL v3
+ */
+
+class SiteConfig
+{
+       // Use first matching element as title (0 or more xpath expressions)
+       public $title = array();
+       
+       // Use first matching element as body (0 or more xpath expressions)
+       public $body = array();
+       
+       // Use first matching element as author (0 or more xpath expressions)
+       public $author = array();
+       
+       // Use first matching element as date (0 or more xpath expressions)
+       public $date = array();
+       
+       // Strip elements matching these xpath expressions (0 or more)
+       public $strip = array();
+       
+       // Strip elements which contain these strings (0 or more) in the id or class attribute 
+       public $strip_id_or_class = array();
+       
+       // Strip images which contain these strings (0 or more) in the src attribute 
+       public $strip_image_src = array();
+       
+       // Additional HTTP headers to send
+       // NOT YET USED
+       public $http_header = array();
+       
+       // Process HTML with tidy before creating DOM (bool or null if undeclared)
+       public $tidy = null;
+       
+       protected $default_tidy = true; // used if undeclared
+       
+       // Autodetect title/body if xpath expressions fail to produce results.
+       // Note that this applies to title and body separately, ie. 
+       //   * if we get a body match but no title match, this option will determine whether we autodetect title 
+       //   * if neither match, this determines whether we autodetect title and body.
+       // Also note that this only applies when there is at least one xpath expression in title or body, ie.
+       //   * if title and body are both empty (no xpath expressions), this option has no effect (both title and body will be auto-detected)
+       //   * if there's an xpath expression for title and none for body, body will be auto-detected and this option will determine whether we auto-detect title if the xpath expression for it fails to produce results.
+       // Usage scenario: you want to extract something specific from a set of URLs, e.g. a table, and if the table is not found, you want to ignore the entry completely. Auto-detection is unlikely to succeed here, so you construct your patterns and set this option to false. Another scenario may be a site where auto-detection has proven to fail (or worse, picked up the wrong content).
+       // bool or null if undeclared
+       public $autodetect_on_failure = null;
+       protected $default_autodetect_on_failure = true; // used if undeclared
+       
+       // Clean up content block - attempt to remove elements that appear to be superfluous
+       // bool or null if undeclared
+       public $prune = null;
+       protected $default_prune = true; // used if undeclared
+       
+       // Test URL - if present, can be used to test the config above
+       public $test_url = array();
+       
+       // Single-page link - should identify a link element or URL pointing to the page holding the entire article
+       // This is useful for sites which split their articles across multiple pages. Links to such pages tend to 
+       // display the first page with links to the other pages at the bottom. Often there is also a link to a page
+       // which displays the entire article on one page (e.g. 'print view').
+       // This should be an XPath expression identifying the link to that page. If present and we find a match,
+       // we will retrieve that page and the rest of the options in this config will be applied to the new page.
+       public $single_page_link = array();
+       
+       public $next_page_link = array();
+       
+       // Single-page link in feed? - same as above, but patterns applied to item description HTML taken from feed
+       public $single_page_link_in_feed = array();
+       
+       // Which parser to use for turning raw HTML into a DOMDocument (either 'libxml' or 'html5lib')
+       // string or null if undeclared
+       public $parser = null;
+       protected $default_parser = 'libxml'; // used if undeclared
+       
+       // Strings to search for in HTML before processing begins (used with $replace_string)
+       public $find_string = array();
+       // Strings to replace those found in $find_string before HTML processing begins
+       public $replace_string = array();
+       
+       // the options below cannot be set in the config files which this class represents
+       
+       //public $cache_in_apc = false; // used to decide if we should cache in apc or not
+       public $cache_key = null;
+       public static $debug = false;
+       protected static $apc = false;
+       protected static $config_path;
+       protected static $config_path_fallback;
+       protected static $config_cache = array();
+       const HOSTNAME_REGEX = '/^(([a-zA-Z0-9-]*[a-zA-Z0-9])\.)*([A-Za-z0-9-]*[A-Za-z0-9])$/';
+       
+       protected static function debug($msg) {
+               if (self::$debug) {
+                       //$mem = round(memory_get_usage()/1024, 2);
+                       //$memPeak = round(memory_get_peak_usage()/1024, 2);
+                       echo '* ',$msg;
+                       //echo ' - mem used: ',$mem," (peak: $memPeak)\n";
+                       echo "\n";
+                       ob_flush();
+                       flush();
+               }
+       }
+       
+       // enable APC caching of certain site config files?
+       // If enabled the following site config files will be 
+       // cached in APC cache (when requested for first time):
+       // * anything in site_config/custom/ and its corresponding file in site_config/standard/
+       // * the site config files associated with HTML fingerprints
+       // * the global site config file
+       // returns true if enabled, false otherwise
+       public static function use_apc($apc=true) {
+               if (!function_exists('apc_add')) {
+                       if ($apc) self::debug('APC will not be used (function apc_add does not exist)');
+                       return false;
+               }
+               self::$apc = $apc;
+               return $apc;
+       }
+       
+       // return bool or null
+       public function tidy($use_default=true) {
+               if ($use_default) return (isset($this->tidy)) ? $this->tidy : $this->default_tidy;
+               return $this->tidy;
+       }
+       
+       // return bool or null
+       public function prune($use_default=true) {
+               if ($use_default) return (isset($this->prune)) ? $this->prune : $this->default_prune;
+               return $this->prune;
+       }
+       
+       // return string or null
+       public function parser($use_default=true) {
+               if ($use_default) return (isset($this->parser)) ? $this->parser : $this->default_parser;
+               return $this->parser;
+       }
+
+       // return bool or null
+       public function autodetect_on_failure($use_default=true) {
+               if ($use_default) return (isset($this->autodetect_on_failure)) ? $this->autodetect_on_failure : $this->default_autodetect_on_failure;
+               return $this->autodetect_on_failure;
+       }
+       
+       public static function set_config_path($path, $fallback=null) {
+               self::$config_path = $path;
+               self::$config_path_fallback = $fallback;
+       }
+       
+       public static function add_to_cache($key, SiteConfig $config, $use_apc=true) {
+               $key = strtolower($key);
+               if (substr($key, 0, 4) == 'www.') $key = substr($key, 4);
+               if ($config->cache_key) $key = $config->cache_key;
+               self::$config_cache[$key] = $config;
+               if (self::$apc && $use_apc) {
+                       self::debug("Adding site config to APC cache with key sc.$key");
+                       apc_add("sc.$key", $config);
+               }
+               self::debug("Cached site config with key $key");
+       }
+       
+       public static function is_cached($key) {
+               $key = strtolower($key);
+               if (substr($key, 0, 4) == 'www.') $key = substr($key, 4);
+               if (array_key_exists($key, self::$config_cache)) {
+                       return true;
+               } elseif (self::$apc && (bool)apc_fetch("sc.$key")) {
+                       return true;
+               }
+               return false;
+       }
+       
+       public function append(SiteConfig $newconfig) {
+               // check for commands where we accept multiple statements (no test_url)
+               foreach (array('title', 'body', 'author', 'date', 'strip', 'strip_id_or_class', 'strip_image_src', 'single_page_link', 'single_page_link_in_feed', 'next_page_link', 'http_header') as $var) {
+                       // append array elements for this config variable from $newconfig to this config
+                       //$this->$var = $this->$var + $newconfig->$var;
+                       $this->$var = array_unique(array_merge($this->$var, $newconfig->$var));
+               }
+               // check for single statement commands
+               // we do not overwrite existing non null values
+               foreach (array('tidy', 'prune', 'parser', 'autodetect_on_failure') as $var) {
+                       if ($this->$var === null) $this->$var = $newconfig->$var;
+               }
+               // treat find_string and replace_string separately (don't apply array_unique) (thanks fabrizio!)
+               foreach (array('find_string', 'replace_string') as $var) {
+                       // append array elements for this config variable from $newconfig to this config
+                       //$this->$var = $this->$var + $newconfig->$var;
+                       $this->$var = array_merge($this->$var, $newconfig->$var);
+               }
+       }
+       
+       // returns SiteConfig instance if an appropriate one is found, false otherwise
+       // if $exact_host_match is true, we will not look for wildcard config matches
+       // by default if host is 'test.example.org' we will look for and load '.example.org.txt' if it exists
+       public static function build($host, $exact_host_match=false) {
+               $host = strtolower($host);
+               if (substr($host, 0, 4) == 'www.') $host = substr($host, 4);
+               if (!$host || (strlen($host) > 200) || !preg_match(self::HOSTNAME_REGEX, ltrim($host, '.'))) return false;
+               // check for site configuration
+               $try = array($host);
+               // should we look for wildcard matches 
+               if (!$exact_host_match) {
+                       $split = explode('.', $host);
+                       if (count($split) > 1) {
+                               array_shift($split);
+                               $try[] = '.'.implode('.', $split);
+                       }
+               }
+               
+               // look for site config file in primary folder
+               self::debug(". looking for site config for $host in primary folder");
+               foreach ($try as $h) {
+                       if (array_key_exists($h, self::$config_cache)) {
+                               self::debug("... site config for $h already loaded in this request");
+                               return self::$config_cache[$h];
+                       } elseif (self::$apc && ($sconfig = apc_fetch("sc.$h"))) {
+                               self::debug("... site config for $h in APC cache");
+                               return $sconfig;
+                       } elseif (file_exists(self::$config_path."/$h.txt")) {
+                               self::debug("... found site config ($h.txt)");
+                               $file_primary = self::$config_path."/$h.txt";
+                               $matched_name = $h;
+                               break;
+                       }
+               }
+               
+               // if we found site config, process it
+               if (isset($file_primary)) {
+                       $config_lines = file($file_primary, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
+                       if (!$config_lines || !is_array($config_lines)) return false;
+                       $config = self::build_from_array($config_lines);
+                       // if APC caching is available and enabled, mark this for cache
+                       //$config->cache_in_apc = true;
+                       $config->cache_key = $matched_name;
+                       
+                       // if autodetec on failure is off (on by default) we do not need to look
+                       // in secondary folder
+                       if (!$config->autodetect_on_failure()) {
+                               self::debug('... autodetect on failure is disabled (no other site config files will be loaded)');
+                               return $config;
+                       }
+               }
+               
+               // look for site config file in secondary folder
+               if (isset(self::$config_path_fallback)) {
+                       self::debug(". looking for site config for $host in secondary folder");
+                       foreach ($try as $h) {
+                               if (file_exists(self::$config_path_fallback."/$h.txt")) {
+                                       self::debug("... found site config in secondary folder ($h.txt)");
+                                       $file_secondary = self::$config_path_fallback."/$h.txt";
+                                       $matched_name = $h;
+                                       break;
+                               }
+                       }
+                       if (!isset($file_secondary)) {
+                               self::debug("... no site config match in secondary folder");
+                       }
+               }
+               
+               // return false if no config file found
+               if (!isset($file_primary) && !isset($file_secondary)) {
+                       self::debug("... no site config match for $host");
+                       return false;
+               }
+               
+               // return primary config if secondary not found
+               if (!isset($file_secondary) && isset($config)) {
+                       return $config;
+               }
+               
+               // process secondary config file
+               $config_lines = file($file_secondary, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
+               if (!$config_lines || !is_array($config_lines)) {
+                       // failed to process secondary
+                       if (isset($config)) {
+                               // return primary config
+                               return $config;
+                       } else {
+                               return false;
+                       }
+               }
+               
+               // merge with primary and return
+               if (isset($config)) {
+                       self::debug('. merging config files');
+                       $config->append(self::build_from_array($config_lines));
+                       return $config;
+               } else {
+                       // return just secondary
+                       $config = self::build_from_array($config_lines);
+                       // if APC caching is available and enabled, mark this for cache
+                       //$config->cache_in_apc = true;
+                       $config->cache_key = $matched_name;
+                       return $config;
+               }
+       }
+       
+       public static function build_from_array(array $lines) {
+               $config = new SiteConfig();
+               foreach ($lines as $line) {
+                       $line = trim($line);
+                       
+                       // skip comments, empty lines
+                       if ($line == '' || $line[0] == '#') continue;
+                       
+                       // get command
+                       $command = explode(':', $line, 2);
+                       // if there's no colon ':', skip this line
+                       if (count($command) != 2) continue;
+                       $val = trim($command[1]);
+                       $command = trim($command[0]);
+                       if ($command == '' || $val == '') continue;
+                       
+                       // check for commands where we accept multiple statements
+                       if (in_array($command, array('title', 'body', 'author', 'date', 'strip', 'strip_id_or_class', 'strip_image_src', 'single_page_link', 'single_page_link_in_feed', 'next_page_link', 'http_header', 'test_url', 'find_string', 'replace_string'))) {
+                               array_push($config->$command, $val);
+                       // check for single statement commands that evaluate to true or false
+                       } elseif (in_array($command, array('tidy', 'prune', 'autodetect_on_failure'))) {
+                               $config->$command = ($val == 'yes');
+                       // check for single statement commands stored as strings
+                       } elseif (in_array($command, array('parser'))) {
+                               $config->$command = $val;
+                       // check for replace_string(find): replace
+                       } elseif ((substr($command, -1) == ')') && preg_match('!^([a-z0-9_]+)\((.*?)\)$!i', $command, $match)) {
+                               if (in_array($match[1], array('replace_string'))) {
+                                       $command = $match[1];
+                                       array_push($config->find_string, $match[2]);
+                                       array_push($config->$command, $val);
+                               }
+                       }
+               }
+               return $config;
+       }
+}
\ No newline at end of file
old mode 100644 (file)
new mode 100755 (executable)
index 9373dee..4078659
@@ -1,7 +1,7 @@
 <?php\r
  /**\r
  * Univarsel Feed Writer\r
- * \r
+ *\r
  * FeedItem class - Used as feed element in FeedWriter class\r
  *\r
  * @package         UnivarselFeedWriter\r
  */\r
  class FeedItem\r
  {\r
-       private $elements = array();    //Collection of feed elements\r
-       private $version;\r
-       \r
-       /**\r
-       * Constructor \r
-       * \r
-       * @param    contant     (RSS1/RSS2/ATOM) RSS2 is default. \r
-       */ \r
-       function __construct($version = RSS2)\r
-       {    \r
-               $this->version = $version;\r
-       }\r
-\r
-       /**\r
-       * Set element (overwrites existing elements with $elementName)\r
-       * \r
-       * @access   public\r
-       * @param    srting  The tag name of an element\r
-       * @param    srting  The content of tag\r
-       * @param    array   Attributes(if any) in 'attrName' => 'attrValue' format\r
-       * @return   void\r
-       */\r
-       public function setElement($elementName, $content, $attributes = null)\r
-       {\r
-               if (isset($this->elements[$elementName])) {\r
-                       unset($this->elements[$elementName]);\r
-               }\r
-               $this->addElement($elementName, $content, $attributes);\r
-       }       \r
-       \r
-       /**\r
-       * Add an element to elements array\r
-       * \r
-       * @access   public\r
-       * @param    srting  The tag name of an element\r
-       * @param    srting  The content of tag\r
-       * @param    array   Attributes(if any) in 'attrName' => 'attrValue' format\r
-       * @return   void\r
-       */\r
-       public function addElement($elementName, $content, $attributes = null)\r
-       {\r
-               $i = 0;\r
-               if (isset($this->elements[$elementName])) {\r
-                       $i = count($this->elements[$elementName]);\r
-               } else {\r
-                       $this->elements[$elementName] = array();\r
-               }\r
-               $this->elements[$elementName][$i]['name']       = $elementName;\r
-               $this->elements[$elementName][$i]['content']    = $content;\r
-               $this->elements[$elementName][$i]['attributes'] = $attributes;\r
-       }\r
-       \r
-       /**\r
-       * Set multiple feed elements from an array. \r
-       * Elements which have attributes cannot be added by this method\r
-       * \r
-       * @access   public\r
-       * @param    array   array of elements in 'tagName' => 'tagContent' format.\r
-       * @return   void\r
-       */\r
-       public function addElementArray($elementArray)\r
-       {\r
-               if(! is_array($elementArray)) return;\r
-               foreach ($elementArray as $elementName => $content) \r
-               {\r
-                       $this->addElement($elementName, $content);\r
-               }\r
-       }\r
-       \r
-       /**\r
-       * Return the collection of elements in this feed item\r
-       * \r
-       * @access   public\r
-       * @return   array\r
-       */\r
-       public function getElements()\r
-       {\r
-               return $this->elements;\r
-       }\r
-       \r
-       // Wrapper functions ------------------------------------------------------\r
-       \r
-       /**\r
-       * Set the 'dscription' element of feed item\r
-       * \r
-       * @access   public\r
-       * @param    string  The content of 'description' element\r
-       * @return   void\r
-       */\r
-       public function setDescription($description) \r
-       {\r
-               $tag = 'description'; \r
-               $this->setElement($tag, $description);\r
-       }\r
-       \r
-       /**\r
-       * @desc     Set the 'title' element of feed item\r
-       * @access   public\r
-       * @param    string  The content of 'title' element\r
-       * @return   void\r
-       */\r
-       public function setTitle($title) \r
-       {\r
-               $this->setElement('title', $title);     \r
-       }\r
-       \r
-       /**\r
-       * Set the 'date' element of feed item\r
-       * \r
-       * @access   public\r
-       * @param    string  The content of 'date' element\r
-       * @return   void\r
-       */\r
-       public function setDate($date) \r
-       {\r
-               if(! is_numeric($date))\r
-               {\r
-                       $date = strtotime($date);\r
-               }\r
-      \r
-               if($this->version == RSS2) \r
-               {\r
-                       $tag    = 'pubDate';\r
-                       $value  = date(DATE_RSS, $date);\r
-               }\r
-               else                                \r
-               {\r
-                       $tag    = 'dc:date';\r
-                       $value  = date("Y-m-d", $date);\r
-               }\r
-               \r
-               $this->setElement($tag, $value);    \r
-       }\r
-       \r
-       /**\r
-       * Set the 'link' element of feed item\r
-       * \r
-       * @access   public\r
-       * @param    string  The content of 'link' element\r
-       * @return   void\r
-       */\r
-       public function setLink($link) \r
-       {\r
-               if($this->version == RSS2 || $this->version == RSS1)\r
-               {\r
-                       $this->setElement('link', $link);\r
-               }\r
-               else\r
-               {\r
-                       $this->setElement('link','',array('href'=>$link));\r
-                       $this->setElement('id', FeedWriter::uuid($link,'urn:uuid:'));\r
-               } \r
-               \r
-       }\r
-       \r
-       /**\r
-       * Set the 'encloser' element of feed item\r
-       * For RSS 2.0 only\r
-       * \r
-       * @access   public\r
-       * @param    string  The url attribute of encloser tag\r
-       * @param    string  The length attribute of encloser tag\r
-       * @param    string  The type attribute of encloser tag\r
-       * @return   void\r
-       */\r
-       public function setEncloser($url, $length, $type)\r
-       {\r
-               $attributes = array('url'=>$url, 'length'=>$length, 'type'=>$type);\r
-               $this->setElement('enclosure','',$attributes);\r
-       }\r
-       \r
+    private $elements = array();    //Collection of feed elements\r
+    private $version;\r
+\r
+    /**\r
+    * Constructor\r
+    *\r
+    * @param    contant     (RSS1/RSS2/ATOM) RSS2 is default.\r
+    */\r
+    function __construct($version = RSS2)\r
+    {\r
+        $this->version = $version;\r
+    }\r
+\r
+    /**\r
+    * Set element (overwrites existing elements with $elementName)\r
+    *\r
+    * @access   public\r
+    * @param    srting  The tag name of an element\r
+    * @param    srting  The content of tag\r
+    * @param    array   Attributes(if any) in 'attrName' => 'attrValue' format\r
+    * @return   void\r
+    */\r
+    public function setElement($elementName, $content, $attributes = null)\r
+    {\r
+        if (isset($this->elements[$elementName])) {\r
+            unset($this->elements[$elementName]);\r
+        }\r
+        $this->addElement($elementName, $content, $attributes);\r
+    }\r
+\r
+    /**\r
+    * Add an element to elements array\r
+    *\r
+    * @access   public\r
+    * @param    srting  The tag name of an element\r
+    * @param    srting  The content of tag\r
+    * @param    array   Attributes(if any) in 'attrName' => 'attrValue' format\r
+    * @return   void\r
+    */\r
+    public function addElement($elementName, $content, $attributes = null)\r
+    {\r
+        $i = 0;\r
+        if (isset($this->elements[$elementName])) {\r
+            $i = count($this->elements[$elementName]);\r
+        } else {\r
+            $this->elements[$elementName] = array();\r
+        }\r
+        $this->elements[$elementName][$i]['name']       = $elementName;\r
+        $this->elements[$elementName][$i]['content']    = $content;\r
+        $this->elements[$elementName][$i]['attributes'] = $attributes;\r
+    }\r
+\r
+    /**\r
+    * Set multiple feed elements from an array.\r
+    * Elements which have attributes cannot be added by this method\r
+    *\r
+    * @access   public\r
+    * @param    array   array of elements in 'tagName' => 'tagContent' format.\r
+    * @return   void\r
+    */\r
+    public function addElementArray($elementArray)\r
+    {\r
+        if(! is_array($elementArray)) return;\r
+        foreach ($elementArray as $elementName => $content)\r
+        {\r
+            $this->addElement($elementName, $content);\r
+        }\r
+    }\r
+\r
+    /**\r
+    * Return the collection of elements in this feed item\r
+    *\r
+    * @access   public\r
+    * @return   array\r
+    */\r
+    public function getElements()\r
+    {\r
+        return $this->elements;\r
+    }\r
+\r
+    // Wrapper functions ------------------------------------------------------\r
+\r
+    /**\r
+    * Set the 'dscription' element of feed item\r
+    *\r
+    * @access   public\r
+    * @param    string  The content of 'description' element\r
+    * @return   void\r
+    */\r
+    public function setDescription($description)\r
+    {\r
+        $tag = ($this->version == ATOM)? 'summary' : 'description';\r
+        $this->setElement($tag, $description);\r
+    }\r
+\r
+    /**\r
+    * @desc     Set the 'title' element of feed item\r
+    * @access   public\r
+    * @param    string  The content of 'title' element\r
+    * @return   void\r
+    */\r
+    public function setTitle($title)\r
+    {\r
+        $this->setElement('title', $title);\r
+    }\r
+\r
+    /**\r
+    * Set the 'date' element of feed item\r
+    *\r
+    * @access   public\r
+    * @param    string  The content of 'date' element\r
+    * @return   void\r
+    */\r
+    public function setDate($date)\r
+    {\r
+        if(! is_numeric($date))\r
+        {\r
+            $date = strtotime($date);\r
+        }\r
+\r
+        if($this->version == ATOM)\r
+        {\r
+               $tag    = 'updated';\r
+               $value  = date(DATE_ATOM, $date);\r
+        }\r
+        elseif($this->version == RSS2)\r
+        {\r
+               $tag    = 'pubDate';\r
+               $value  = date(DATE_RSS, $date);\r
+        }\r
+        else\r
+        {\r
+               $tag    = 'dc:date';\r
+               $value  = date("Y-m-d", $date);\r
+        }\r
+\r
+        $this->setElement($tag, $value);\r
+    }\r
+\r
+    /**\r
+    * Set the 'link' element of feed item\r
+    *\r
+    * @access   public\r
+    * @param    string  The content of 'link' element\r
+    * @return   void\r
+    */\r
+    public function setLink($link)\r
+    {\r
+        if($this->version == RSS2 || $this->version == RSS1)\r
+        {\r
+            $this->setElement('link', $link);\r
+            $this->setElement('guid', $link);\r
+        }\r
+        else\r
+        {\r
+            $this->setElement('link','',array('href'=>$link));\r
+            $this->setElement('id', FeedWriter::uuid($link,'urn:uuid:'));\r
+        }\r
+\r
+    }\r
+\r
+    /**\r
+    * Set the 'source' element of feed item\r
+    *\r
+    * @access   public\r
+    * @param    string  The content of 'source' element\r
+    * @return   void\r
+    */\r
+    public function setSource($link)\r
+    {\r
+        $attributes = array('url'=>$link);\r
+        $this->setElement('source', "wallabag",$attributes);\r
+    }\r
+\r
+    /**\r
+    * Set the 'encloser' element of feed item\r
+    * For RSS 2.0 only\r
+    *\r
+    * @access   public\r
+    * @param    string  The url attribute of encloser tag\r
+    * @param    string  The length attribute of encloser tag\r
+    * @param    string  The type attribute of encloser tag\r
+    * @return   void\r
+    */\r
+    public function setEncloser($url, $length, $type)\r
+    {\r
+        $attributes = array('url'=>$url, 'length'=>$length, 'type'=>$type);\r
+        $this->setElement('enclosure','',$attributes);\r
+    }\r
+\r
  } // end of class FeedItem\r
-?>\r
+?>
\ No newline at end of file
old mode 100644 (file)
new mode 100755 (executable)
index adb2526..9446cdd
@@ -2,6 +2,7 @@
 define('RSS2', 1, true);\r
 define('JSON', 2, true);\r
 define('JSONP', 3, true);\r
+define('ATOM', 4, true);\r
 \r
  /**\r
  * Univarsel Feed Writer class\r
@@ -9,433 +10,444 @@ define('JSONP', 3, true);
  * Genarate RSS2 or JSON (original: RSS 1.0, RSS2.0 and ATOM Feed)\r
  *\r
  * Modified for FiveFilters.org's Full-Text RSS project\r
- * to allow for inclusion of hubs, JSON output. \r
+ * to allow for inclusion of hubs, JSON output.\r
  * Stripped RSS1 and ATOM support.\r
- *                             \r
+ *\r
  * @package     UnivarselFeedWriter\r
  * @author      Anis uddin Ahmad <anisniit@gmail.com>\r
  * @link        http://www.ajaxray.com/projects/rss\r
  */\r
  class FeedWriter\r
  {\r
-        private $self          = null;     // self URL - http://feed2.w3.org/docs/warning/MissingAtomSelfLink.html\r
-        private $hubs          = array();  // PubSubHubbub hubs\r
-        private $channels      = array();  // Collection of channel elements\r
-        private $items         = array();  // Collection of items as object of FeedItem class.\r
-        private $data          = array();  // Store some other version wise data\r
-        private $CDATAEncoding = array();  // The tag names which have to encoded as CDATA\r
-        private $xsl                   = null;         // stylesheet to render RSS (used by Chrome)\r
-        private $json                  = null;         // JSON object\r
-        \r
-        private $version   = null; \r
-       \r
-       /**\r
-       * Constructor\r
-       * \r
-       * @param    constant    the version constant (RSS2 or JSON).       \r
-       */ \r
-       function __construct($version = RSS2)\r
-       {       \r
-               $this->version = $version;\r
-                       \r
-               // Setting default value for assential channel elements\r
-               $this->channels['title']        = $version . ' Feed';\r
-               $this->channels['link']         = 'http://www.ajaxray.com/blog';\r
-                               \r
-               //Tag names to encode in CDATA\r
-               $this->CDATAEncoding = array('description', 'content:encoded', 'content', 'subtitle', 'summary');\r
-       }\r
-       \r
-       public function setFormat($format) {\r
-               $this->version = $format;\r
-       }\r
-\r
-       // Start # public functions ---------------------------------------------\r
-       \r
-       /**\r
-       * Set a channel element\r
-       * @access   public\r
-       * @param    srting  name of the channel tag\r
-       * @param    string  content of the channel tag\r
-       * @return   void\r
-       */\r
-       public function setChannelElement($elementName, $content)\r
-       {\r
-               $this->channels[$elementName] = $content ;\r
-       }\r
-       \r
-       /**\r
-       * Set multiple channel elements from an array. Array elements \r
-       * should be 'channelName' => 'channelContent' format.\r
-       * \r
-       * @access   public\r
-       * @param    array   array of channels\r
-       * @return   void\r
-       */\r
-       public function setChannelElementsFromArray($elementArray)\r
-       {\r
-               if(! is_array($elementArray)) return;\r
-               foreach ($elementArray as $elementName => $content) \r
-               {\r
-                       $this->setChannelElement($elementName, $content);\r
-               }\r
-       }\r
-       \r
-       /**\r
-       * Genarate the actual RSS/JSON file\r
-       * \r
-       * @access   public\r
-       * @return   void\r
-       */ \r
-       public function genarateFeed()\r
-       {\r
-               if ($this->version == RSS2) {\r
-                       header('Content-type: text/xml; charset=UTF-8');\r
-                       // this line prevents Chrome 20 from prompting download\r
-                       // used by Google: https://news.google.com/news/feeds?ned=us&topic=b&output=rss\r
-                       header('X-content-type-options: nosniff');\r
-               } elseif ($this->version == JSON) {\r
-                       header('Content-type: application/json; charset=UTF-8');\r
-                       $this->json = new stdClass();\r
-               } elseif ($this->version == JSONP) {\r
-                       header('Content-type: application/javascript; charset=UTF-8');\r
-                       $this->json = new stdClass();\r
-               }\r
-               $this->printHead();\r
-               $this->printChannels();\r
-               $this->printItems();\r
-               $this->printTale();\r
-               if ($this->version == JSON || $this->version == JSONP) {\r
-                       echo json_encode($this->json);\r
-               }\r
-       }\r
-       \r
-       /**\r
-       * Create a new FeedItem.\r
-       * \r
-       * @access   public\r
-       * @return   object  instance of FeedItem class\r
-       */\r
-       public function createNewItem()\r
-       {\r
-               $Item = new FeedItem($this->version);\r
-               return $Item;\r
-       }\r
-       \r
-       /**\r
-       * Add a FeedItem to the main class\r
-       * \r
-       * @access   public\r
-       * @param    object  instance of FeedItem class\r
-       * @return   void\r
-       */\r
-       public function addItem($feedItem)\r
-       {\r
-               $this->items[] = $feedItem;    \r
-       }\r
-       \r
-       // Wrapper functions -------------------------------------------------------------------\r
-       \r
-       /**\r
-       * Set the 'title' channel element\r
-       * \r
-       * @access   public\r
-       * @param    srting  value of 'title' channel tag\r
-       * @return   void\r
-       */\r
-       public function setTitle($title)\r
-       {\r
-               $this->setChannelElement('title', $title);\r
-       }\r
-       \r
-       /**\r
-       * Add a hub to the channel element\r
-       * \r
-       * @access   public\r
-       * @param    string URL\r
-       * @return   void\r
-       */\r
-       public function addHub($hub)\r
-       {\r
-               $this->hubs[] = $hub;    \r
-       }\r
-       \r
-       /**\r
-       * Set XSL URL\r
-       * \r
-       * @access   public\r
-       * @param    string URL\r
-       * @return   void\r
-       */\r
-       public function setXsl($xsl)\r
-       {\r
-               $this->xsl = $xsl;    \r
-       }       \r
-       \r
-       /**\r
-       * Set self URL\r
-       * \r
-       * @access   public\r
-       * @param    string URL\r
-       * @return   void\r
-       */\r
-       public function setSelf($self)\r
-       {\r
-               $this->self = $self;    \r
-       }       \r
-       \r
-       /**\r
-       * Set the 'description' channel element\r
-       * \r
-       * @access   public\r
-       * @param    srting  value of 'description' channel tag\r
-       * @return   void\r
-       */\r
-       public function setDescription($desciption)\r
-       {\r
-               $tag = ($this->version == ATOM)? 'subtitle' : 'description'; \r
-               $this->setChannelElement($tag, $desciption);\r
-       }\r
-       \r
-       /**\r
-       * Set the 'link' channel element\r
-       * \r
-       * @access   public\r
-       * @param    srting  value of 'link' channel tag\r
-       * @return   void\r
-       */\r
-       public function setLink($link)\r
-       {\r
-               $this->setChannelElement('link', $link);\r
-       }\r
-       \r
-       /**\r
-       * Set the 'image' channel element\r
-       * \r
-       * @access   public\r
-       * @param    srting  title of image\r
-       * @param    srting  link url of the imahe\r
-       * @param    srting  path url of the image\r
-       * @return   void\r
-       */\r
-       public function setImage($title, $link, $url)\r
-       {\r
-               $this->setChannelElement('image', array('title'=>$title, 'link'=>$link, 'url'=>$url));\r
-       }\r
-       \r
-       // End # public functions ----------------------------------------------\r
-       \r
-       // Start # private functions ----------------------------------------------\r
-       \r
-       /**\r
-       * Prints the xml and rss namespace\r
-       * \r
-       * @access   private\r
-       * @return   void\r
-       */\r
-       private function printHead()\r
-       {\r
-               if ($this->version == RSS2)\r
-               {\r
-                       $out  = '<?xml version="1.0" encoding="utf-8"?>'."\n";\r
-                       if ($this->xsl) $out .= '<?xml-stylesheet type="text/xsl" href="'.htmlspecialchars($this->xsl).'"?>' . PHP_EOL;\r
-                       $out .= '<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:media="http://search.yahoo.com/mrss/">' . PHP_EOL;\r
-                       echo $out;\r
-               }\r
-               elseif ($this->version == JSON || $this->version == JSONP)\r
-               {\r
-                       $this->json->rss = array('@attributes' => array('version' => '2.0'));\r
-               }\r
-       }\r
-       \r
-       /**\r
-       * Closes the open tags at the end of file\r
-       * \r
-       * @access   private\r
-       * @return   void\r
-       */\r
-       private function printTale()\r
-       {\r
-               if ($this->version == RSS2)\r
-               {\r
-                       echo '</channel>',PHP_EOL,'</rss>'; \r
-               }    \r
-               // do nothing for JSON\r
-       }\r
-\r
-       /**\r
-       * Creates a single node as xml format\r
-       * \r
-       * @access   private\r
-       * @param    string  name of the tag\r
-       * @param    mixed   tag value as string or array of nested tags in 'tagName' => 'tagValue' format\r
-       * @param    array   Attributes(if any) in 'attrName' => 'attrValue' format\r
-       * @return   string  formatted xml tag\r
-       */\r
-       private function makeNode($tagName, $tagContent, $attributes = null)\r
-       {        \r
-               if ($this->version == RSS2)\r
-               {\r
-                       $nodeText = '';\r
-                       $attrText = '';\r
-                       if (is_array($attributes))\r
-                       {\r
-                               foreach ($attributes as $key => $value) \r
-                               {\r
-                                       $attrText .= " $key=\"$value\" ";\r
-                               }\r
-                       }\r
-                       $nodeText .= "<{$tagName}{$attrText}>";\r
-                       if (is_array($tagContent))\r
-                       { \r
-                               foreach ($tagContent as $key => $value) \r
-                               {\r
-                                       $nodeText .= $this->makeNode($key, $value);\r
-                               }\r
-                       }\r
-                       else\r
-                       {\r
-                               //$nodeText .= (in_array($tagName, $this->CDATAEncoding))? $tagContent : htmlentities($tagContent);\r
-                               $nodeText .= htmlspecialchars($tagContent);\r
-                       }           \r
-                       //$nodeText .= (in_array($tagName, $this->CDATAEncoding))? "]]></$tagName>" : "</$tagName>";\r
-                       $nodeText .= "</$tagName>";\r
-                       return $nodeText . PHP_EOL;\r
-               }\r
-               elseif ($this->version == JSON || $this->version == JSONP)\r
-               {\r
-                       $tagName = (string)$tagName;\r
-                       $tagName = strtr($tagName, ':', '_');\r
-                       $node = null;\r
-                       if (!$tagContent && is_array($attributes) && count($attributes))\r
-                       {\r
-                               $node = array('@attributes' => $this->json_keys($attributes));\r
-                       } else {\r
-                               if (is_array($tagContent)) {\r
-                                       $node = $this->json_keys($tagContent);\r
-                               } else {\r
-                                       $node = $tagContent;\r
-                               }\r
-                       }\r
-                       return $node;\r
-               }\r
-               return ''; // should not get here\r
-       }\r
-       \r
-       private function json_keys(array $array) {\r
-               $new = array();\r
-               foreach ($array as $key => $val) {\r
-                       if (is_string($key)) $key = strtr($key, ':', '_');\r
-                       if (is_array($val)) {\r
-                               $new[$key] = $this->json_keys($val);\r
-                       } else {\r
-                               $new[$key] = $val;\r
-                       }\r
-               }\r
-               return $new;\r
-       }\r
-       \r
-       /**\r
-       * @desc     Print channels\r
-       * @access   private\r
-       * @return   void\r
-       */\r
-       private function printChannels()\r
-       {\r
-               //Start channel tag\r
-               if ($this->version == RSS2) {\r
-                       echo '<channel>' . PHP_EOL;    \r
-                       // add hubs\r
-                       foreach ($this->hubs as $hub) {\r
-                               //echo $this->makeNode('link', '', array('rel'=>'hub', 'href'=>$hub, 'xmlns'=>'http://www.w3.org/2005/Atom'));\r
-                               echo '<link rel="hub"  href="'.htmlspecialchars($hub).'" xmlns="http://www.w3.org/2005/Atom" />' . PHP_EOL;\r
-                       }\r
-                       // add self\r
-                       if (isset($this->self)) {\r
-                               //echo $this->makeNode('link', '', array('rel'=>'self', 'href'=>$this->self, 'xmlns'=>'http://www.w3.org/2005/Atom'));\r
-                               echo '<link rel="self" href="'.htmlspecialchars($this->self).'" xmlns="http://www.w3.org/2005/Atom" />' . PHP_EOL;\r
-                       }\r
-                       //Print Items of channel\r
-                       foreach ($this->channels as $key => $value) \r
-                       {\r
-                               echo $this->makeNode($key, $value);\r
-                       }\r
-               } elseif ($this->version == JSON || $this->version == JSONP) {\r
-                       $this->json->rss['channel'] = (object)$this->json_keys($this->channels);\r
-               }\r
-       }\r
-       \r
-       /**\r
-       * Prints formatted feed items\r
-       * \r
-       * @access   private\r
-       * @return   void\r
-       */\r
-       private function printItems()\r
-       {    \r
-               foreach ($this->items as $item) {\r
-                       $itemElements = $item->getElements();\r
-                       \r
-                       echo $this->startItem();\r
-                       \r
-                       if ($this->version == JSON || $this->version == JSONP) {\r
-                               $json_item = array();\r
-                       }\r
-                       \r
-                       foreach ($itemElements as $thisElement) {\r
-                               foreach ($thisElement as $instance) {                   \r
-                                       if ($this->version == RSS2) {\r
-                                               echo $this->makeNode($instance['name'], $instance['content'], $instance['attributes']);\r
-                                       } elseif ($this->version == JSON || $this->version == JSONP) {\r
-                                               $_json_node = $this->makeNode($instance['name'], $instance['content'], $instance['attributes']);\r
-                                               if (count($thisElement) > 1) {\r
-                                                       $json_item[strtr($instance['name'], ':', '_')][] = $_json_node;\r
-                                               } else {\r
-                                                       $json_item[strtr($instance['name'], ':', '_')] = $_json_node;\r
-                                               }\r
-                                       }\r
-                               }\r
-                       }\r
-                       echo $this->endItem();\r
-                       if ($this->version == JSON || $this->version == JSONP) {\r
-                               if (count($this->items) > 1) {\r
-                                       $this->json->rss['channel']->item[] = $json_item;\r
-                               } else {\r
-                                       $this->json->rss['channel']->item = $json_item;\r
-                               }\r
-                       }\r
-               }\r
-       }\r
-       \r
-       /**\r
-       * Make the starting tag of channels\r
-       * \r
-       * @access   private\r
-       * @return   void\r
-       */\r
-       private function startItem()\r
-       {\r
-               if ($this->version == RSS2)\r
-               {\r
-                       echo '<item>' . PHP_EOL; \r
-               }    \r
-               // nothing for JSON\r
-       }\r
-       \r
-       /**\r
-       * Closes feed item tag\r
-       * \r
-       * @access   private\r
-       * @return   void\r
-       */\r
-       private function endItem()\r
-       {\r
-               if ($this->version == RSS2)\r
-               {\r
-                       echo '</item>' . PHP_EOL; \r
-               }    \r
-               // nothing for JSON\r
-       }\r
-       \r
-       // End # private functions ----------------------------------------------\r
+     private $self          = null;     // self URL - http://feed2.w3.org/docs/warning/MissingAtomSelfLink.html\r
+     private $hubs          = array();  // PubSubHubbub hubs\r
+     private $channels      = array();  // Collection of channel elements\r
+     private $items         = array();  // Collection of items as object of FeedItem class.\r
+     private $data          = array();  // Store some other version wise data\r
+     private $CDATAEncoding = array();  // The tag names which have to encoded as CDATA\r
+     private $xsl            = null;        // stylesheet to render RSS (used by Chrome)\r
+     private $json            = null;        // JSON object\r
+\r
+     private $version   = null;\r
+\r
+    /**\r
+    * Constructor\r
+    *\r
+    * @param    constant    the version constant (RSS2 or JSON).\r
+    */\r
+    function __construct($version = RSS2)\r
+    {\r
+        $this->version = $version;\r
+\r
+        // Setting default value for assential channel elements\r
+        $this->channels['title']        = $version . ' Feed';\r
+        $this->channels['link']         = 'http://www.ajaxray.com/blog';\r
+\r
+        //Tag names to encode in CDATA\r
+        $this->CDATAEncoding = array('description', 'content:encoded', 'content', 'subtitle', 'summary');\r
+    }\r
+\r
+    public function setFormat($format) {\r
+        $this->version = $format;\r
+    }\r
+\r
+    // Start # public functions ---------------------------------------------\r
+\r
+    /**\r
+    * Set a channel element\r
+    * @access   public\r
+    * @param    srting  name of the channel tag\r
+    * @param    string  content of the channel tag\r
+    * @return   void\r
+    */\r
+    public function setChannelElement($elementName, $content)\r
+    {\r
+        $this->channels[$elementName] = $content ;\r
+    }\r
+\r
+    /**\r
+    * Set multiple channel elements from an array. Array elements\r
+    * should be 'channelName' => 'channelContent' format.\r
+    *\r
+    * @access   public\r
+    * @param    array   array of channels\r
+    * @return   void\r
+    */\r
+    public function setChannelElementsFromArray($elementArray)\r
+    {\r
+        if(! is_array($elementArray)) return;\r
+        foreach ($elementArray as $elementName => $content)\r
+        {\r
+            $this->setChannelElement($elementName, $content);\r
+        }\r
+    }\r
+\r
+    /**\r
+    * Genarate the actual RSS/JSON file\r
+    *\r
+    * @access   public\r
+    * @return   void\r
+    */\r
+    public function genarateFeed($withHeaders = true)\r
+    {\r
+        if ($withHeaders) {\r
+          if ($this->version == RSS2) {\r
+              header('Content-type: text/xml; charset=UTF-8');\r
+              // this line prevents Chrome 20 from prompting download\r
+              // used by Google: https://news.google.com/news/feeds?ned=us&topic=b&output=rss\r
+              header('X-content-type-options: nosniff');\r
+          } elseif ($this->version == JSON) {\r
+              header('Content-type: application/json; charset=UTF-8');\r
+          } elseif ($this->version == JSONP) {\r
+              header('Content-type: application/javascript; charset=UTF-8');\r
+          }\r
+        }\r
+\r
+        if ($this->version == JSON || $this->version == JSONP) {\r
+          $this->json = new stdClass();\r
+        }\r
+\r
+\r
+        $this->printHead();\r
+        $this->printChannels();\r
+        $this->printItems();\r
+        $this->printTale();\r
+        if ($this->version == JSON || $this->version == JSONP) {\r
+            echo json_encode($this->json);\r
+        }\r
+    }\r
+\r
+    public function &getItems()\r
+    {\r
+       return $this->items;\r
+    }\r
+\r
+    /**\r
+    * Create a new FeedItem.\r
+    *\r
+    * @access   public\r
+    * @return   object  instance of FeedItem class\r
+    */\r
+    public function createNewItem()\r
+    {\r
+        $Item = new FeedItem($this->version);\r
+        return $Item;\r
+    }\r
+\r
+    /**\r
+    * Add a FeedItem to the main class\r
+    *\r
+    * @access   public\r
+    * @param    object  instance of FeedItem class\r
+    * @return   void\r
+    */\r
+    public function addItem($feedItem)\r
+    {\r
+        $this->items[] = $feedItem;\r
+    }\r
+\r
+    // Wrapper functions -------------------------------------------------------------------\r
+\r
+    /**\r
+    * Set the 'title' channel element\r
+    *\r
+    * @access   public\r
+    * @param    srting  value of 'title' channel tag\r
+    * @return   void\r
+    */\r
+    public function setTitle($title)\r
+    {\r
+        $this->setChannelElement('title', $title);\r
+    }\r
+\r
+    /**\r
+    * Add a hub to the channel element\r
+    *\r
+    * @access   public\r
+    * @param    string URL\r
+    * @return   void\r
+    */\r
+    public function addHub($hub)\r
+    {\r
+        $this->hubs[] = $hub;\r
+    }\r
+\r
+    /**\r
+    * Set XSL URL\r
+    *\r
+    * @access   public\r
+    * @param    string URL\r
+    * @return   void\r
+    */\r
+    public function setXsl($xsl)\r
+    {\r
+        $this->xsl = $xsl;\r
+    }\r
+\r
+    /**\r
+    * Set self URL\r
+    *\r
+    * @access   public\r
+    * @param    string URL\r
+    * @return   void\r
+    */\r
+    public function setSelf($self)\r
+    {\r
+        $this->self = $self;\r
+    }\r
+\r
+    /**\r
+    * Set the 'description' channel element\r
+    *\r
+    * @access   public\r
+    * @param    srting  value of 'description' channel tag\r
+    * @return   void\r
+    */\r
+    public function setDescription($description)\r
+    {\r
+        $tag = ($this->version == ATOM)? 'subtitle' : 'description';\r
+        $this->setChannelElement($tag, $description);\r
+    }\r
+\r
+    /**\r
+    * Set the 'link' channel element\r
+    *\r
+    * @access   public\r
+    * @param    srting  value of 'link' channel tag\r
+    * @return   void\r
+    */\r
+    public function setLink($link)\r
+    {\r
+        $this->setChannelElement('link', $link);\r
+    }\r
+\r
+    /**\r
+    * Set the 'image' channel element\r
+    *\r
+    * @access   public\r
+    * @param    srting  title of image\r
+    * @param    srting  link url of the imahe\r
+    * @param    srting  path url of the image\r
+    * @return   void\r
+    */\r
+    public function setImage($title, $link, $url)\r
+    {\r
+        $this->setChannelElement('image', array('title'=>$title, 'link'=>$link, 'url'=>$url));\r
+    }\r
+\r
+    // End # public functions ----------------------------------------------\r
+\r
+    // Start # private functions ----------------------------------------------\r
+\r
+    /**\r
+    * Prints the xml and rss namespace\r
+    *\r
+    * @access   private\r
+    * @return   void\r
+    */\r
+    private function printHead()\r
+    {\r
+        if ($this->version == RSS2)\r
+        {\r
+            $out  = '<?xml version="1.0" encoding="utf-8"?>'."\n";\r
+            if ($this->xsl) $out .= '<?xml-stylesheet type="text/xsl" href="'.htmlspecialchars($this->xsl).'"?>' . PHP_EOL;\r
+            $out .= '<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:media="http://search.yahoo.com/mrss/">' . PHP_EOL;\r
+            echo $out;\r
+        }\r
+        elseif ($this->version == JSON || $this->version == JSONP)\r
+        {\r
+            $this->json->rss = array('@attributes' => array('version' => '2.0'));\r
+        }\r
+    }\r
+\r
+    /**\r
+    * Closes the open tags at the end of file\r
+    *\r
+    * @access   private\r
+    * @return   void\r
+    */\r
+    private function printTale()\r
+    {\r
+        if ($this->version == RSS2)\r
+        {\r
+            echo '</channel>',PHP_EOL,'</rss>';\r
+        }\r
+        // do nothing for JSON\r
+    }\r
+\r
+    /**\r
+    * Creates a single node as xml format\r
+    *\r
+    * @access   private\r
+    * @param    string  name of the tag\r
+    * @param    mixed   tag value as string or array of nested tags in 'tagName' => 'tagValue' format\r
+    * @param    array   Attributes(if any) in 'attrName' => 'attrValue' format\r
+    * @return   string  formatted xml tag\r
+    */\r
+    private function makeNode($tagName, $tagContent, $attributes = null)\r
+    {\r
+        if ($this->version == RSS2)\r
+        {\r
+            $nodeText = '';\r
+            $attrText = '';\r
+            if (is_array($attributes))\r
+            {\r
+                foreach ($attributes as $key => $value)\r
+                {\r
+                    $attrText .= " $key=\"$value\" ";\r
+                }\r
+            }\r
+            $nodeText .= "<{$tagName}{$attrText}>";\r
+            if (is_array($tagContent))\r
+            {\r
+                foreach ($tagContent as $key => $value)\r
+                {\r
+                    $nodeText .= $this->makeNode($key, $value);\r
+                }\r
+            }\r
+            else\r
+            {\r
+                //$nodeText .= (in_array($tagName, $this->CDATAEncoding))? $tagContent : htmlentities($tagContent);\r
+                $nodeText .= htmlspecialchars($tagContent);\r
+            }\r
+            //$nodeText .= (in_array($tagName, $this->CDATAEncoding))? "]]></$tagName>" : "</$tagName>";\r
+            $nodeText .= "</$tagName>";\r
+            return $nodeText . PHP_EOL;\r
+        }\r
+        elseif ($this->version == JSON || $this->version == JSONP)\r
+        {\r
+            $tagName = (string)$tagName;\r
+            $tagName = strtr($tagName, ':', '_');\r
+            $node = null;\r
+            if (!$tagContent && is_array($attributes) && count($attributes))\r
+            {\r
+                $node = array('@attributes' => $this->json_keys($attributes));\r
+            } else {\r
+                if (is_array($tagContent)) {\r
+                    $node = $this->json_keys($tagContent);\r
+                } else {\r
+                    $node = $tagContent;\r
+                }\r
+            }\r
+            return $node;\r
+        }\r
+        return ''; // should not get here\r
+    }\r
+\r
+    private function json_keys(array $array) {\r
+        $new = array();\r
+        foreach ($array as $key => $val) {\r
+            if (is_string($key)) $key = strtr($key, ':', '_');\r
+            if (is_array($val)) {\r
+                $new[$key] = $this->json_keys($val);\r
+            } else {\r
+                $new[$key] = $val;\r
+            }\r
+        }\r
+        return $new;\r
+    }\r
+\r
+    /**\r
+    * @desc     Print channels\r
+    * @access   private\r
+    * @return   void\r
+    */\r
+    private function printChannels()\r
+    {\r
+        //Start channel tag\r
+        if ($this->version == RSS2) {\r
+            echo '<channel>' . PHP_EOL;\r
+            // add hubs\r
+            foreach ($this->hubs as $hub) {\r
+                //echo $this->makeNode('link', '', array('rel'=>'hub', 'href'=>$hub, 'xmlns'=>'http://www.w3.org/2005/Atom'));\r
+                echo '<link rel="hub"  href="'.htmlspecialchars($hub).'" xmlns="http://www.w3.org/2005/Atom" />' . PHP_EOL;\r
+            }\r
+            // add self\r
+            if (isset($this->self)) {\r
+                //echo $this->makeNode('link', '', array('rel'=>'self', 'href'=>$this->self, 'xmlns'=>'http://www.w3.org/2005/Atom'));\r
+                echo '<link rel="self" href="'.htmlspecialchars($this->self).'" xmlns="http://www.w3.org/2005/Atom" />' . PHP_EOL;\r
+            }\r
+            //Print Items of channel\r
+            foreach ($this->channels as $key => $value)\r
+            {\r
+                echo $this->makeNode($key, $value);\r
+            }\r
+        } elseif ($this->version == JSON || $this->version == JSONP) {\r
+            $this->json->rss['channel'] = (object)$this->json_keys($this->channels);\r
+        }\r
+    }\r
+\r
+    /**\r
+    * Prints formatted feed items\r
+    *\r
+    * @access   private\r
+    * @return   void\r
+    */\r
+    private function printItems()\r
+    {\r
+        foreach ($this->items as $item) {\r
+            $itemElements = $item->getElements();\r
+\r
+            echo $this->startItem();\r
+\r
+            if ($this->version == JSON || $this->version == JSONP) {\r
+                $json_item = array();\r
+            }\r
+\r
+            foreach ($itemElements as $thisElement) {\r
+                foreach ($thisElement as $instance) {\r
+                    if ($this->version == RSS2) {\r
+                        echo $this->makeNode($instance['name'], $instance['content'], $instance['attributes']);\r
+                    } elseif ($this->version == JSON || $this->version == JSONP) {\r
+                        $_json_node = $this->makeNode($instance['name'], $instance['content'], $instance['attributes']);\r
+                        if (count($thisElement) > 1) {\r
+                            $json_item[strtr($instance['name'], ':', '_')][] = $_json_node;\r
+                        } else {\r
+                            $json_item[strtr($instance['name'], ':', '_')] = $_json_node;\r
+                        }\r
+                    }\r
+                }\r
+            }\r
+            echo $this->endItem();\r
+            if ($this->version == JSON || $this->version == JSONP) {\r
+                if (count($this->items) > 1) {\r
+                    $this->json->rss['channel']->item[] = $json_item;\r
+                } else {\r
+                    $this->json->rss['channel']->item = $json_item;\r
+                }\r
+            }\r
+        }\r
+    }\r
+\r
+    /**\r
+    * Make the starting tag of channels\r
+    *\r
+    * @access   private\r
+    * @return   void\r
+    */\r
+    private function startItem()\r
+    {\r
+        if ($this->version == RSS2)\r
+        {\r
+            echo '<item>' . PHP_EOL;\r
+        }\r
+        // nothing for JSON\r
+    }\r
+\r
+    /**\r
+    * Closes feed item tag\r
+    *\r
+    * @access   private\r
+    * @return   void\r
+    */\r
+    private function endItem()\r
+    {\r
+        if ($this->version == RSS2)\r
+        {\r
+            echo '</item>' . PHP_EOL;\r
+        }\r
+        // nothing for JSON\r
+    }\r
+\r
+    // End # private functions ----------------------------------------------\r
  }
\ No newline at end of file
index 2f5244f9fd744d1543fa83d4c5432dc7a7ff8773..c4a48b2152d09778c264b0864253371e65fd91b3 100644 (file)
@@ -134,6 +134,7 @@ class HTML5_TreeBuilder {
 
     // Namespaces for foreign content
     const NS_HTML   = null; // to prevent DOM from requiring NS on everything
+    const NS_XHTML  = 'http://www.w3.org/1999/xhtml';
     const NS_MATHML = 'http://www.w3.org/1998/Math/MathML';
     const NS_SVG    = 'http://www.w3.org/2000/svg';
     const NS_XLINK  = 'http://www.w3.org/1999/xlink';
@@ -3157,11 +3158,19 @@ class HTML5_TreeBuilder {
         }
 
     private function insertElement($token, $append = true) {
-        $el = $this->dom->createElementNS(self::NS_HTML, $token['name']);
+        //$el = $this->dom->createElementNS(self::NS_HTML, $token['name']);
+        $namespaceURI = strpos($token['name'], ':') ? self::NS_XHTML : self::NS_HTML;
+        $el = $this->dom->createElementNS($namespaceURI, $token['name']);
 
         if (!empty($token['attr'])) {
             foreach($token['attr'] as $attr) {
-                if(!$el->hasAttribute($attr['name'])) {
+
+                               // mike@macgirvin.com 2011-11-17, check attribute name for
+                               // validity (ignoring extenders and combiners) as illegal chars in names
+                               // causes everything to abort
+
+                               $valid = preg_match('/^[a-zA-Z\_\:]([\-a-zA-Z0-9\_\:\.]+$)/',$attr['name']);
+                if($attr['name'] && (!$el->hasAttribute($attr['name'])) && ($valid)) {
                     $el->setAttribute($attr['name'], $attr['value']);
                 }
             }
index 83e94f14035c5dd9053bb4150592a6807fa77f39..e4d5f495b355a1dc2dc5e4079266cd654cea7f42 100644 (file)
-<?php\r
-/**\r
- * Cookie Jar\r
- * \r
- * PHP class for handling cookies, as defined by the Netscape spec: \r
- * <http://curl.haxx.se/rfc/cookie_spec.html>\r
- *\r
- * This class should be used to handle cookies (storing cookies from HTTP response messages, and\r
- * sending out cookies in HTTP request messages). This has been adapted for FiveFilters.org \r
- * from the original version used in HTTP Navigator. See http://www.keyvan.net/code/http-navigator/\r
- * \r
- * This class is mainly based on Cookies.pm <http://search.cpan.org/author/GAAS/libwww-perl-5.65/\r
- * lib/HTTP/Cookies.pm> from the libwww-perl collection <http://www.linpro.no/lwp/>.\r
- * Unlike Cookies.pm, this class only supports the Netscape cookie spec, not RFC 2965.\r
- * \r
- * @version 0.5\r
- * @date 2011-03-15\r
- * @see http://php.net/HttpRequestPool\r
- * @author Keyvan Minoukadeh\r
- * @copyright 2011 Keyvan Minoukadeh\r
- * @license http://www.gnu.org/licenses/agpl-3.0.html AGPL v3\r
- */\r
-\r
-class CookieJar\r
-{\r
-    /**\r
-    * Cookies - array containing all cookies.\r
-    *\r
-    * <pre>\r
-    * Cookies are stored like this:\r
-    *   [domain][path][name] = array\r
-    * where array is:\r
-    *   0 => value, 1 => secure, 2 => expires\r
-    * </pre>\r
-    * @var array\r
-    * @access private\r
-    */\r
-    public $cookies = array();\r
-       public $debug = false;\r
-\r
-    /**\r
-    * Constructor\r
-    */\r
-    function __construct() {\r
-    }\r
-\r
-       protected function debug($msg, $file=null, $line=null) {\r
-               if ($this->debug) {\r
-                       $mem = round(memory_get_usage()/1024, 2);\r
-                       $memPeak = round(memory_get_peak_usage()/1024, 2);\r
-                       echo '* ',$msg;\r
-                       if (isset($file, $line)) echo " ($file line $line)";\r
-                       echo ' - mem used: ',$mem," (peak: $memPeak)\n";        \r
-                       ob_flush();\r
-                       flush();\r
-               }\r
-       }       \r
-       \r
-    /**\r
-    * Get matching cookies\r
-    *\r
-    * Only use this method if you cannot use add_cookie_header(), for example, if you want to use\r
-    * this cookie jar class without using the request class.\r
-    *\r
-    * @param array $param associative array containing 'domain', 'path', 'secure' keys\r
-    * @return string\r
-    * @see add_cookie_header()\r
-    */\r
-    public function getMatchingCookies($url)\r
-    {\r
-               if (($parts = @parse_url($url)) && isset($parts['scheme'], $parts['host'], $parts['path'])) {\r
-                       $param['domain'] = $parts['host'];\r
-                       $param['path'] = $parts['path'];\r
-                       $param['secure'] = (strtolower($parts['scheme']) == 'https');\r
-                       unset($parts);\r
-               } else {\r
-                       return false;\r
-               }\r
-        // RFC 2965 notes:\r
-        //  If multiple cookies satisfy the criteria above, they are ordered in\r
-        //  the Cookie header such that those with more specific Path attributes\r
-        //  precede those with less specific.  Ordering with respect to other\r
-        //  attributes (e.g., Domain) is unspecified.\r
-        $domain = $param['domain'];\r
-        if (strpos($domain, '.') === false) $domain .= '.local';\r
-        $request_path = $param['path'];\r
-        if ($request_path == '') $request_path = '/';\r
-        $request_secure = $param['secure'];\r
-        $now = time();\r
-        $matched_cookies = array();\r
-        // domain - find matching domains\r
-        $this->debug('Finding matching domains for '.$domain, __FILE__, __LINE__);\r
-        while (strpos($domain, '.') !== false) {\r
-            if (isset($this->cookies[$domain])) {\r
-                $this->debug(' domain match found: '.$domain);\r
-                $cookies =& $this->cookies[$domain];\r
-            } else {\r
-                $domain = $this->_reduce_domain($domain);\r
-                continue;\r
-            }\r
-            // paths - find matching paths starting from most specific\r
-            $this->debug('  - Finding matching paths for '.$request_path);\r
-            $paths = array_keys($cookies);\r
-            usort($paths, array($this, '_cmp_length'));\r
-            foreach ($paths as $path) {\r
-                // continue to next cookie if request path does not path-match cookie path\r
-                if (!$this->_path_match($request_path, $path)) continue;\r
-                // loop through cookie names\r
-                $this->debug('     path match found: '.$path);\r
-                foreach ($cookies[$path] as $name => $values) {\r
-                    // if this cookie is secure but request isn't, continue to next cookie\r
-                    if ($values[1] && !$request_secure) continue;\r
-                    // if cookie is not a session cookie and has expired, continue to next cookie\r
-                    if (is_int($values[2]) && ($values[2] < $now)) continue;\r
-                    // cookie matches request\r
-                    $this->debug('      cookie match: '.$name.'='.$values[0]);\r
-                    $matched_cookies[] = $name.'='.$values[0];\r
-                }\r
-            }\r
-            $domain = $this->_reduce_domain($domain);\r
-        }\r
-        // return cookies\r
-        return implode('; ', $matched_cookies);\r
-    }\r
-\r
-    /**\r
-    * Parse Set-Cookie values.\r
-    *\r
-    * Only use this method if you cannot use extract_cookies(), for example, if you want to use\r
-    * this cookie jar class without using the response class.\r
-    *\r
-    * @param array $set_cookies array holding 1 or more "Set-Cookie" header values\r
-    * @param array $param associative array containing 'host', 'path' keys\r
-    * @return void\r
-    * @see extract_cookies()\r
-    */\r
-    public function storeCookies($url, $set_cookies)\r
-    {\r
-        if (count($set_cookies) == 0) return;\r
-               $param = @parse_url($url);\r
-               if (!is_array($param) || !isset($param['host'])) return;\r
-        $request_host = $param['host'];\r
-        if (strpos($request_host, '.') === false) $request_host .= '.local';\r
-        $request_path = @$param['path'];\r
-        if ($request_path == '') $request_path = '/';\r
-        //\r
-        // loop through set-cookie headers\r
-        //\r
-        foreach ($set_cookies as $set_cookie) {\r
-            $this->debug('Parsing: '.$set_cookie);\r
-            // temporary cookie store (before adding to jar)\r
-            $tmp_cookie = array();\r
-            $param = explode(';', $set_cookie);\r
-            // loop through params\r
-            for ($x=0; $x<count($param); $x++) {\r
-                $key_val = explode('=', $param[$x], 2);\r
-                if (count($key_val) != 2) {\r
-                    // if the first param isn't a name=value pair, continue to the next set-cookie\r
-                    // header\r
-                    if ($x == 0) continue 2;\r
-                    // check for secure flag\r
-                    if (strtolower(trim($key_val[0])) == 'secure') $tmp_cookie['secure'] = true;\r
-                    // continue to next param\r
-                    continue;\r
-                }\r
-                list($key, $val) = array_map('trim', $key_val);\r
-                // first name=value pair is the cookie name and value\r
-                // the name and value are stored under 'name' and 'value' to avoid conflicts\r
-                // with later parameters.\r
-                if ($x == 0) {\r
-                    $tmp_cookie = array('name'=>$key, 'value'=>$val);\r
-                    continue;\r
-                }\r
-                $key = strtolower($key);\r
-                if (in_array($key, array('expires', 'path', 'domain', 'secure'))) {\r
-                    $tmp_cookie[$key] = $val;\r
-                }\r
-            }\r
-            //\r
-            // set cookie\r
-            //\r
-            // check domain\r
-            if (isset($tmp_cookie['domain']) && ($tmp_cookie['domain'] != $request_host) &&\r
-                    ($tmp_cookie['domain'] != ".$request_host")) {\r
-                $domain = $tmp_cookie['domain'];\r
-                if ((strpos($domain, '.') === false) && ($domain != 'local')) {\r
-                    $this->debug(' - domain "'.$domain.'" has no dot and is not a local domain');\r
-                    continue;\r
-                }\r
-                if (preg_match('/\.[0-9]+$/', $domain)) {\r
-                    $this->debug(' - domain "'.$domain.'" appears to be an ip address');\r
-                    continue;\r
-                }\r
-                if (substr($domain, 0, 1) != '.') $domain = ".$domain";\r
-                if (!$this->_domain_match($request_host, $domain)) {\r
-                    $this->debug(' - request host "'.$request_host.'" does not domain-match "'.$domain.'"');\r
-                    continue;\r
-                }\r
-            } else {\r
-                // if domain is not specified in the set-cookie header, domain will default to\r
-                // the request host\r
-                $domain = $request_host;\r
-            }\r
-            // check path\r
-            if (isset($tmp_cookie['path']) && ($tmp_cookie['path'] != '')) {\r
-                $path = urldecode($tmp_cookie['path']);\r
-                if (!$this->_path_match($request_path, $path)) {\r
-                    $this->debug(' - request path "'.$request_path.'" does not path-match "'.$path.'"');\r
-                    continue;\r
-                }\r
-            } else {\r
-                $path = $request_path;\r
-                $path = substr($path, 0, strrpos($path, '/'));\r
-                if ($path == '') $path = '/';\r
-            }\r
-            // check if secure\r
-            $secure = (isset($tmp_cookie['secure'])) ? true : false;\r
-            // check expiry\r
-            if (isset($tmp_cookie['expires'])) {\r
-                if (($expires = strtotime($tmp_cookie['expires'])) < 0) {\r
-                    $expires = null;\r
-                }\r
-            } else {\r
-                $expires = null;\r
-            }\r
-            // set cookie\r
-            $this->set_cookie($domain, $path, $tmp_cookie['name'], $tmp_cookie['value'], $secure, $expires);\r
-        }\r
-    }\r
-       \r
-       // return array of set-cookie values extracted from HTTP response headers (string $h)\r
-       public function extractCookies($h) {\r
-        $x = 0;\r
-        $lines = 0;\r
-        $headers = array();\r
-        $last_match = false;\r
-               $h = explode("\n", $h);\r
-        foreach ($h as $line) {\r
-                       $line = rtrim($line);\r
-            $lines++;\r
-\r
-            $trimmed_line = trim($line);\r
-            if (isset($line_last)) {\r
-                // check if we have \r\n\r\n (indicating the end of headers)\r
-                // some servers will not use CRLF (\r\n), so we make CR (\r) optional.\r
-                // if (preg_match('/\015?\012\015?\012/', $line_last.$line)) {\r
-                //     break;\r
-                // }\r
-                // As an alternative, we can check if the current trimmed line is empty\r
-                if ($trimmed_line == '') {\r
-                    break;\r
-                }\r
-\r
-                // check for continuation line...\r
-                // RFC 2616 Section 2.2 "Basic Rules":\r
-                // HTTP/1.1 header field values can be folded onto multiple lines if the\r
-                // continuation line begins with a space or horizontal tab. All linear\r
-                // white space, including folding, has the same semantics as SP. A\r
-                // recipient MAY replace any linear white space with a single SP before\r
-                // interpreting the field value or forwarding the message downstream.\r
-                if ($last_match && preg_match('/^\s+(.*)/', $line, $match)) {\r
-                    // append to previous header value\r
-                    $headers[$x-1] .= ' '.rtrim($match[1]);\r
-                    continue;\r
-                }\r
-            }\r
-            $line_last = $line;\r
-\r
-            // split header name and value\r
-            if (preg_match('/^Set-Cookie\s*:\s*(.*)/i', $line, $match)) {\r
-                $headers[$x++] = rtrim($match[1]);\r
-                $last_match = true;\r
-            } else {\r
-                $last_match = false;\r
-            }\r
-        }\r
-        return $headers;\r
-       }\r
-\r
-    /**\r
-    * Set Cookie\r
-    * @param string $domain\r
-    * @param string $path\r
-    * @param string $name cookie name\r
-    * @param string $value cookie value\r
-    * @param bool $secure\r
-    * @param int $expires expiry time (null if session cookie, <= 0 will delete cookie)\r
-    * @return void\r
-    */\r
-    function set_cookie($domain, $path, $name, $value, $secure=false, $expires=null)\r
-    {\r
-        if ($domain == '') return;\r
-        if ($path == '') return;\r
-        if ($name == '') return;\r
-        // check if cookie needs to go\r
-        if (isset($expires) && ($expires <= 0)) {\r
-            if (isset($this->cookies[$domain][$path][$name])) unset($this->cookies[$domain][$path][$name]);\r
-            return;\r
-        }\r
-        if ($value == '') return;\r
-        $this->cookies[$domain][$path][$name] = array($value, $secure, $expires);\r
-        return;\r
-    }\r
-\r
-    /**\r
-    * Clear cookies - [domain [,path [,name]]] - call method with no arguments to clear all cookies.\r
-    * @param string $domain\r
-    * @param string $path\r
-    * @param string $name\r
-    * @return void\r
-    */\r
-    function clear($domain=null, $path=null, $name=null)\r
-    {\r
-        if (!isset($domain)) {\r
-            $this->cookies = array();\r
-        } elseif (!isset($path)) {\r
-            if (isset($this->cookies[$domain])) unset($this->cookies[$domain]);\r
-        } elseif (!isset($name)) {\r
-            if (isset($this->cookies[$domain][$path])) unset($this->cookies[$domain][$path]);\r
-        } elseif (isset($name)) {\r
-            if (isset($this->cookies[$domain][$path][$name])) unset($this->cookies[$domain][$path][$name]);\r
-        }\r
-    }\r
-\r
-    /**\r
-    * Compare string length - used for sorting\r
-    * @access private\r
-    * @return int\r
-    */\r
-    function _cmp_length($a, $b)\r
-    {\r
-        $la = strlen($a); $lb = strlen($b);\r
-        if ($la == $lb) return 0;\r
-        return ($la > $lb) ? -1 : 1;\r
-    }\r
-\r
-    /**\r
-    * Reduce domain\r
-    * @param string $domain\r
-    * @return string\r
-    * @access private\r
-    */\r
-    function _reduce_domain($domain)\r
-    {\r
-        if ($domain == '') return '';\r
-        if (substr($domain, 0, 1) == '.') return substr($domain, 1);\r
-        return substr($domain, strpos($domain, '.'));\r
-    }\r
-\r
-    /**\r
-    * Path match - check if path1 path-matches path2\r
-    *\r
-    * From RFC 2965: \r
-    *   <i>For two strings that represent paths, P1 and P2, P1 path-matches P2\r
-    *   if P2 is a prefix of P1 (including the case where P1 and P2 string-\r
-    *   compare equal).  Thus, the string /tec/waldo path-matches /tec.</i>\r
-    * @param string $path1\r
-    * @param string $path2\r
-    * @return bool\r
-    * @access private\r
-    */\r
-    function _path_match($path1, $path2)\r
-    {\r
-        return (substr($path1, 0, strlen($path2)) == $path2);\r
-    }\r
-\r
-    /**\r
-    * Domain match - check if domain1 domain-matches domain2\r
-    *\r
-    * A few extracts from RFC 2965: \r
-    *  -  A Set-Cookie2 from request-host y.x.foo.com for Domain=.foo.com\r
-    *     would be rejected, because H is y.x and contains a dot.\r
-    *\r
-    *  -  A Set-Cookie2 from request-host x.foo.com for Domain=.foo.com\r
-    *     would be accepted.\r
-    *\r
-    *  -  A Set-Cookie2 with Domain=.com or Domain=.com., will always be\r
-    *     rejected, because there is no embedded dot.\r
-    *\r
-    *  -  A Set-Cookie2 from request-host example for Domain=.local will\r
-    *     be accepted, because the effective host name for the request-\r
-    *     host is example.local, and example.local domain-matches .local.\r
-    *\r
-    * I'm ignoring the first point for now (must check to see how other browsers handle\r
-    * this rule for Set-Cookie headers)\r
-    *\r
-    * @param string $domain1\r
-    * @param string $domain2\r
-    * @return bool\r
-    * @access private\r
-    */\r
-    function _domain_match($domain1, $domain2)\r
-    {\r
-        $domain1 = strtolower($domain1);\r
-        $domain2 = strtolower($domain2);\r
-        while (strpos($domain1, '.') !== false) {\r
-            if ($domain1 == $domain2) return true;\r
-            $domain1 = $this->_reduce_domain($domain1);\r
-            continue;\r
-        }\r
-        return false;\r
-    }\r
-}\r
-?>
\ No newline at end of file
+<?php
+/**
+ * Cookie Jar
+ * 
+ * PHP class for handling cookies, as defined by the Netscape spec: 
+ * <http://curl.haxx.se/rfc/cookie_spec.html>
+ *
+ * This class should be used to handle cookies (storing cookies from HTTP response messages, and
+ * sending out cookies in HTTP request messages). This has been adapted for FiveFilters.org 
+ * from the original version used in HTTP Navigator. See http://www.keyvan.net/code/http-navigator/
+ * 
+ * This class is mainly based on Cookies.pm <http://search.cpan.org/author/GAAS/libwww-perl-5.65/
+ * lib/HTTP/Cookies.pm> from the libwww-perl collection <http://www.linpro.no/lwp/>.
+ * Unlike Cookies.pm, this class only supports the Netscape cookie spec, not RFC 2965.
+ * 
+ * @version 0.5
+ * @date 2011-03-15
+ * @see http://php.net/HttpRequestPool
+ * @author Keyvan Minoukadeh
+ * @copyright 2011 Keyvan Minoukadeh
+ * @license http://www.gnu.org/licenses/agpl-3.0.html AGPL v3
+ */
+
+class CookieJar
+{
+    /**
+    * Cookies - array containing all cookies.
+    *
+    * <pre>
+    * Cookies are stored like this:
+    *   [domain][path][name] = array
+    * where array is:
+    *   0 => value, 1 => secure, 2 => expires
+    * </pre>
+    * @var array
+    * @access private
+    */
+    public $cookies = array();
+       public $debug = false;
+
+    /**
+    * Constructor
+    */
+    function __construct() {
+    }
+
+       protected function debug($msg, $file=null, $line=null) {
+               if ($this->debug) {
+                       $mem = round(memory_get_usage()/1024, 2);
+                       $memPeak = round(memory_get_peak_usage()/1024, 2);
+                       echo '* ',$msg;
+                       if (isset($file, $line)) echo " ($file line $line)";
+                       echo ' - mem used: ',$mem," (peak: $memPeak)\n";        
+                       ob_flush();
+                       flush();
+               }
+       }       
+       
+    /**
+    * Get matching cookies
+    *
+    * Only use this method if you cannot use add_cookie_header(), for example, if you want to use
+    * this cookie jar class without using the request class.
+    *
+    * @param array $param associative array containing 'domain', 'path', 'secure' keys
+    * @return string
+    * @see add_cookie_header()
+    */
+    public function getMatchingCookies($url)
+    {
+               if (($parts = @parse_url($url)) && isset($parts['scheme'], $parts['host'], $parts['path'])) {
+                       $param['domain'] = $parts['host'];
+                       $param['path'] = $parts['path'];
+                       $param['secure'] = (strtolower($parts['scheme']) == 'https');
+                       unset($parts);
+               } else {
+                       return false;
+               }
+        // RFC 2965 notes:
+        //  If multiple cookies satisfy the criteria above, they are ordered in
+        //  the Cookie header such that those with more specific Path attributes
+        //  precede those with less specific.  Ordering with respect to other
+        //  attributes (e.g., Domain) is unspecified.
+        $domain = $param['domain'];
+        if (strpos($domain, '.') === false) $domain .= '.local';
+        $request_path = $param['path'];
+        if ($request_path == '') $request_path = '/';
+        $request_secure = $param['secure'];
+        $now = time();
+        $matched_cookies = array();
+        // domain - find matching domains
+        $this->debug('Finding matching domains for '.$domain, __FILE__, __LINE__);
+        while (strpos($domain, '.') !== false) {
+            if (isset($this->cookies[$domain])) {
+                $this->debug(' domain match found: '.$domain);
+                $cookies =& $this->cookies[$domain];
+            } else {
+                $domain = $this->_reduce_domain($domain);
+                continue;
+            }
+            // paths - find matching paths starting from most specific
+            $this->debug('  - Finding matching paths for '.$request_path);
+            $paths = array_keys($cookies);
+            usort($paths, array($this, '_cmp_length'));
+            foreach ($paths as $path) {
+                // continue to next cookie if request path does not path-match cookie path
+                if (!$this->_path_match($request_path, $path)) continue;
+                // loop through cookie names
+                $this->debug('     path match found: '.$path);
+                foreach ($cookies[$path] as $name => $values) {
+                    // if this cookie is secure but request isn't, continue to next cookie
+                    if ($values[1] && !$request_secure) continue;
+                    // if cookie is not a session cookie and has expired, continue to next cookie
+                    if (is_int($values[2]) && ($values[2] < $now)) continue;
+                    // cookie matches request
+                    $this->debug('      cookie match: '.$name.'='.$values[0]);
+                    $matched_cookies[] = $name.'='.$values[0];
+                }
+            }
+            $domain = $this->_reduce_domain($domain);
+        }
+        // return cookies
+        return implode('; ', $matched_cookies);
+    }
+
+    /**
+    * Parse Set-Cookie values.
+    *
+    * Only use this method if you cannot use extract_cookies(), for example, if you want to use
+    * this cookie jar class without using the response class.
+    *
+    * @param array $set_cookies array holding 1 or more "Set-Cookie" header values
+    * @param array $param associative array containing 'host', 'path' keys
+    * @return void
+    * @see extract_cookies()
+    */
+    public function storeCookies($url, $set_cookies)
+    {
+        if (count($set_cookies) == 0) return;
+               $param = @parse_url($url);
+               if (!is_array($param) || !isset($param['host'])) return;
+        $request_host = $param['host'];
+        if (strpos($request_host, '.') === false) $request_host .= '.local';
+        $request_path = @$param['path'];
+        if ($request_path == '') $request_path = '/';
+        //
+        // loop through set-cookie headers
+        //
+        foreach ($set_cookies as $set_cookie) {
+            $this->debug('Parsing: '.$set_cookie);
+            // temporary cookie store (before adding to jar)
+            $tmp_cookie = array();
+            $param = explode(';', $set_cookie);
+            // loop through params
+            for ($x=0; $x<count($param); $x++) {
+                $key_val = explode('=', $param[$x], 2);
+                if (count($key_val) != 2) {
+                    // if the first param isn't a name=value pair, continue to the next set-cookie
+                    // header
+                    if ($x == 0) continue 2;
+                    // check for secure flag
+                    if (strtolower(trim($key_val[0])) == 'secure') $tmp_cookie['secure'] = true;
+                    // continue to next param
+                    continue;
+                }
+                list($key, $val) = array_map('trim', $key_val);
+                // first name=value pair is the cookie name and value
+                // the name and value are stored under 'name' and 'value' to avoid conflicts
+                // with later parameters.
+                if ($x == 0) {
+                    $tmp_cookie = array('name'=>$key, 'value'=>$val);
+                    continue;
+                }
+                $key = strtolower($key);
+                if (in_array($key, array('expires', 'path', 'domain', 'secure'))) {
+                    $tmp_cookie[$key] = $val;
+                }
+            }
+            //
+            // set cookie
+            //
+            // check domain
+            if (isset($tmp_cookie['domain']) && ($tmp_cookie['domain'] != $request_host) &&
+                    ($tmp_cookie['domain'] != ".$request_host")) {
+                $domain = $tmp_cookie['domain'];
+                if ((strpos($domain, '.') === false) && ($domain != 'local')) {
+                    $this->debug(' - domain "'.$domain.'" has no dot and is not a local domain');
+                    continue;
+                }
+                if (preg_match('/\.[0-9]+$/', $domain)) {
+                    $this->debug(' - domain "'.$domain.'" appears to be an ip address');
+                    continue;
+                }
+                if (substr($domain, 0, 1) != '.') $domain = ".$domain";
+                if (!$this->_domain_match($request_host, $domain)) {
+                    $this->debug(' - request host "'.$request_host.'" does not domain-match "'.$domain.'"');
+                    continue;
+                }
+            } else {
+                // if domain is not specified in the set-cookie header, domain will default to
+                // the request host
+                $domain = $request_host;
+            }
+            // check path
+            if (isset($tmp_cookie['path']) && ($tmp_cookie['path'] != '')) {
+                $path = urldecode($tmp_cookie['path']);
+                if (!$this->_path_match($request_path, $path)) {
+                    $this->debug(' - request path "'.$request_path.'" does not path-match "'.$path.'"');
+                    continue;
+                }
+            } else {
+                $path = $request_path;
+                $path = substr($path, 0, strrpos($path, '/'));
+                if ($path == '') $path = '/';
+            }
+            // check if secure
+            $secure = (isset($tmp_cookie['secure'])) ? true : false;
+            // check expiry
+            if (isset($tmp_cookie['expires'])) {
+                if (($expires = strtotime($tmp_cookie['expires'])) < 0) {
+                    $expires = null;
+                }
+            } else {
+                $expires = null;
+            }
+            // set cookie
+            $this->set_cookie($domain, $path, $tmp_cookie['name'], $tmp_cookie['value'], $secure, $expires);
+        }
+    }
+       
+       // return array of set-cookie values extracted from HTTP response headers (string $h)
+       public function extractCookies($h) {
+        $x = 0;
+        $lines = 0;
+        $headers = array();
+        $last_match = false;
+               $h = explode("\n", $h);
+        foreach ($h as $line) {
+                       $line = rtrim($line);
+            $lines++;
+
+            $trimmed_line = trim($line);
+            if (isset($line_last)) {
+                // check if we have \r\n\r\n (indicating the end of headers)
+                // some servers will not use CRLF (\r\n), so we make CR (\r) optional.
+                // if (preg_match('/\015?\012\015?\012/', $line_last.$line)) {
+                //     break;
+                // }
+                // As an alternative, we can check if the current trimmed line is empty
+                if ($trimmed_line == '') {
+                    break;
+                }
+
+                // check for continuation line...
+                // RFC 2616 Section 2.2 "Basic Rules":
+                // HTTP/1.1 header field values can be folded onto multiple lines if the
+                // continuation line begins with a space or horizontal tab. All linear
+                // white space, including folding, has the same semantics as SP. A
+                // recipient MAY replace any linear white space with a single SP before
+                // interpreting the field value or forwarding the message downstream.
+                if ($last_match && preg_match('/^\s+(.*)/', $line, $match)) {
+                    // append to previous header value
+                    $headers[$x-1] .= ' '.rtrim($match[1]);
+                    continue;
+                }
+            }
+            $line_last = $line;
+
+            // split header name and value
+            if (preg_match('/^Set-Cookie\s*:\s*(.*)/i', $line, $match)) {
+                $headers[$x++] = rtrim($match[1]);
+                $last_match = true;
+            } else {
+                $last_match = false;
+            }
+        }
+        return $headers;
+       }
+
+    /**
+    * Set Cookie
+    * @param string $domain
+    * @param string $path
+    * @param string $name cookie name
+    * @param string $value cookie value
+    * @param bool $secure
+    * @param int $expires expiry time (null if session cookie, <= 0 will delete cookie)
+    * @return void
+    */
+    function set_cookie($domain, $path, $name, $value, $secure=false, $expires=null)
+    {
+        if ($domain == '') return;
+        if ($path == '') return;
+        if ($name == '') return;
+        // check if cookie needs to go
+        if (isset($expires) && ($expires <= 0)) {
+            if (isset($this->cookies[$domain][$path][$name])) unset($this->cookies[$domain][$path][$name]);
+            return;
+        }
+        if ($value == '') return;
+        $this->cookies[$domain][$path][$name] = array($value, $secure, $expires);
+        return;
+    }
+
+    /**
+    * Clear cookies - [domain [,path [,name]]] - call method with no arguments to clear all cookies.
+    * @param string $domain
+    * @param string $path
+    * @param string $name
+    * @return void
+    */
+    function clear($domain=null, $path=null, $name=null)
+    {
+        if (!isset($domain)) {
+            $this->cookies = array();
+        } elseif (!isset($path)) {
+            if (isset($this->cookies[$domain])) unset($this->cookies[$domain]);
+        } elseif (!isset($name)) {
+            if (isset($this->cookies[$domain][$path])) unset($this->cookies[$domain][$path]);
+        } elseif (isset($name)) {
+            if (isset($this->cookies[$domain][$path][$name])) unset($this->cookies[$domain][$path][$name]);
+        }
+    }
+
+    /**
+    * Compare string length - used for sorting
+    * @access private
+    * @return int
+    */
+    function _cmp_length($a, $b)
+    {
+        $la = strlen($a); $lb = strlen($b);
+        if ($la == $lb) return 0;
+        return ($la > $lb) ? -1 : 1;
+    }
+
+    /**
+    * Reduce domain
+    * @param string $domain
+    * @return string
+    * @access private
+    */
+    function _reduce_domain($domain)
+    {
+        if ($domain == '') return '';
+        if (substr($domain, 0, 1) == '.') return substr($domain, 1);
+        return substr($domain, strpos($domain, '.'));
+    }
+
+    /**
+    * Path match - check if path1 path-matches path2
+    *
+    * From RFC 2965: 
+    *   <i>For two strings that represent paths, P1 and P2, P1 path-matches P2
+    *   if P2 is a prefix of P1 (including the case where P1 and P2 string-
+    *   compare equal).  Thus, the string /tec/waldo path-matches /tec.</i>
+    * @param string $path1
+    * @param string $path2
+    * @return bool
+    * @access private
+    */
+    function _path_match($path1, $path2)
+    {
+        return (substr($path1, 0, strlen($path2)) == $path2);
+    }
+
+    /**
+    * Domain match - check if domain1 domain-matches domain2
+    *
+    * A few extracts from RFC 2965: 
+    *  -  A Set-Cookie2 from request-host y.x.foo.com for Domain=.foo.com
+    *     would be rejected, because H is y.x and contains a dot.
+    *
+    *  -  A Set-Cookie2 from request-host x.foo.com for Domain=.foo.com
+    *     would be accepted.
+    *
+    *  -  A Set-Cookie2 with Domain=.com or Domain=.com., will always be
+    *     rejected, because there is no embedded dot.
+    *
+    *  -  A Set-Cookie2 from request-host example for Domain=.local will
+    *     be accepted, because the effective host name for the request-
+    *     host is example.local, and example.local domain-matches .local.
+    *
+    * I'm ignoring the first point for now (must check to see how other browsers handle
+    * this rule for Set-Cookie headers)
+    *
+    * @param string $domain1
+    * @param string $domain2
+    * @return bool
+    * @access private
+    */
+    function _domain_match($domain1, $domain2)
+    {
+        $domain1 = strtolower($domain1);
+        $domain2 = strtolower($domain2);
+        while (strpos($domain1, '.') !== false) {
+            if ($domain1 == $domain2) return true;
+            $domain1 = $this->_reduce_domain($domain1);
+            continue;
+        }
+        return false;
+    }
+}
\ No newline at end of file
index e4f1b3b3834c989cb22925fc17e14b4e6b70891a..963f0c05296e00f8bc9d38ef8aac9e5b950ea2b3 100644 (file)
-<?php\r
-/**\r
- * Humble HTTP Agent\r
- * \r
- * This class is designed to take advantage of parallel HTTP requests\r
- * offered by PHP's PECL HTTP extension or the curl_multi_* functions. \r
- * For environments which do not have these options, it reverts to standard sequential \r
- * requests (using file_get_contents())\r
- * \r
- * @version 1.1\r
- * @date 2012-08-20\r
- * @see http://php.net/HttpRequestPool\r
- * @author Keyvan Minoukadeh\r
- * @copyright 2011-2012 Keyvan Minoukadeh\r
- * @license http://www.gnu.org/licenses/agpl-3.0.html AGPL v3\r
- */\r
-\r
-class HumbleHttpAgent\r
-{\r
-       const METHOD_REQUEST_POOL = 1;\r
-       const METHOD_CURL_MULTI = 2;\r
-       const METHOD_FILE_GET_CONTENTS = 4;\r
-       //const UA_BROWSER = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0.1) Gecko/20100101 Firefox/4.0.1';\r
-       const UA_BROWSER = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.92 Safari/535.2';\r
-       const UA_PHP = 'PHP/5.2';\r
-       const REF_GOOGLE = 'http://www.google.co.uk/url?sa=t&source=web&cd=1';\r
-       \r
-       protected $requests = array();\r
-       protected $redirectQueue = array();\r
-       protected $requestOptions;\r
-       protected $maxParallelRequests = 5;\r
-       protected $cache = null; //TODO\r
-       protected $httpContext;\r
-       protected $minimiseMemoryUse = false; //TODO\r
-       protected $method;\r
-       protected $cookieJar;\r
-       public $debug = false;\r
-       public $debugVerbose = false;\r
-       public $rewriteHashbangFragment = true; // see http://code.google.com/web/ajaxcrawling/docs/specification.html\r
-       public $maxRedirects = 5;\r
-       public $userAgentMap = array();\r
-       public $rewriteUrls = array();\r
-       public $userAgentDefault;\r
-       public $referer;\r
-       //public $userAgent = 'Mozilla/5.0';\r
-       \r
-       // Prevent certain file/mime types\r
-       // HTTP responses which match these content types will\r
-       // be returned without body.\r
-       public $headerOnlyTypes = array();\r
-       // URLs ending with one of these extensions will\r
-       // prompt Humble HTTP Agent to send a HEAD request first\r
-       // to see if returned content type matches $headerOnlyTypes.\r
-       public $headerOnlyClues = array('pdf','mp3','zip','exe','gif','gzip','gz','jpeg','jpg','mpg','mpeg','png','ppt','mov');\r
-       // AJAX triggers to search for.\r
-       // for AJAX sites, e.g. Blogger with its dynamic views templates.\r
-       public $ajaxTriggers = array("<meta name='fragment' content='!'",'<meta name="fragment" content="!"',"<meta content='!' name='fragment'",'<meta content="!" name="fragment"');\r
-       \r
-       //TODO: set max file size\r
-       //TODO: normalise headers\r
-       \r
-       function __construct($requestOptions=null, $method=null) {\r
-               $this->userAgentDefault = self::UA_BROWSER;\r
-               $this->referer = self::REF_GOOGLE;\r
-               // set the request method\r
-               if (in_array($method, array(1,2,4))) {\r
-                       $this->method = $method;\r
-               } else {\r
-                       if (class_exists('HttpRequestPool')) {\r
-                               $this->method = self::METHOD_REQUEST_POOL;\r
-                       } elseif (function_exists('curl_multi_init')) {\r
-                               $this->method = self::METHOD_CURL_MULTI;\r
-                       } else {\r
-                               $this->method = self::METHOD_FILE_GET_CONTENTS;\r
-                       }\r
-               }\r
-               if ($this->method == self::METHOD_CURL_MULTI) {\r
-                       require_once(dirname(__FILE__).'/RollingCurl.php');\r
-               }\r
-               // create cookie jar\r
-               $this->cookieJar = new CookieJar();\r
-               // set request options (redirect must be 0)\r
-               $this->requestOptions = array(\r
-                       'timeout' => 15,\r
-                       'redirect' => 0 // we handle redirects manually so we can rewrite the new hashbang URLs that are creeping up over the web\r
-                       // TODO: test onprogress?\r
-               );\r
-               if (is_array($requestOptions)) {\r
-                       $this->requestOptions = array_merge($this->requestOptions, $requestOptions);\r
-               }\r
-               $this->httpContext = array(\r
-                       'http' => array(\r
-                               'ignore_errors' => true,\r
-                               'timeout' => $this->requestOptions['timeout'],\r
-                               'max_redirects' => $this->requestOptions['redirect'],\r
-                               'header' => "Accept: */*\r\n"\r
-                               )\r
-                       );\r
-       }\r
-       \r
-       protected function debug($msg) {\r
-               if ($this->debug) {\r
-                       $mem = round(memory_get_usage()/1024, 2);\r
-                       $memPeak = round(memory_get_peak_usage()/1024, 2);\r
-                       echo '* ',$msg;\r
-                       if ($this->debugVerbose) echo ' - mem used: ',$mem," (peak: $memPeak)";\r
-                       echo "\n";\r
-                       ob_flush();\r
-                       flush();\r
-               }\r
-       }\r
-       \r
-       protected function getUserAgent($url, $asArray=false) {\r
-               $host = @parse_url($url, PHP_URL_HOST);\r
-               if (strtolower(substr($host, 0, 4)) == 'www.') {\r
-                       $host = substr($host, 4);\r
-               }\r
-               if ($host) {\r
-                       $try = array($host);\r
-                       $split = explode('.', $host);\r
-                       if (count($split) > 1) {\r
-                               array_shift($split);\r
-                               $try[] = '.'.implode('.', $split);\r
-                       }\r
-                       foreach ($try as $h) {\r
-                               if (isset($this->userAgentMap[$h])) {\r
-                                       $ua = $this->userAgentMap[$h];\r
-                                       break;\r
-                               }\r
-                       }\r
-               }\r
-               if (!isset($ua)) $ua = $this->userAgentDefault;\r
-               if ($asArray) {\r
-                       return array('User-Agent' => $ua);\r
-               } else {\r
-                       return 'User-Agent: '.$ua;\r
-               }\r
-       }\r
-       \r
-       public function rewriteHashbangFragment($url) {\r
-               // return $url if there's no '#!'\r
-               if (strpos($url, '#!') === false) return $url;\r
-               // split $url and rewrite\r
-               // TODO: is SimplePie_IRI included?\r
-               $iri = new SimplePie_IRI($url);\r
-               $fragment = substr($iri->fragment, 1); // strip '!'\r
-               $iri->fragment = null;\r
-               if (isset($iri->query)) {\r
-                       parse_str($iri->query, $query);\r
-               } else {\r
-                       $query = array();\r
-               }\r
-               $query['_escaped_fragment_'] = (string)$fragment;\r
-               $iri->query = str_replace('%2F', '/', http_build_query($query)); // needed for some sites\r
-               return $iri->get_iri();\r
-       }\r
-       \r
-       public function getUglyURL($url, $html) {\r
-               if ($html == '') return false;\r
-               $found = false;\r
-               foreach ($this->ajaxTriggers as $string) {\r
-                       if (stripos($html, $string)) {\r
-                               $found = true;\r
-                               break;\r
-                       }\r
-               }\r
-               if (!$found) return false;\r
-               $iri = new SimplePie_IRI($url);\r
-               if (isset($iri->query)) {\r
-                       parse_str($iri->query, $query);\r
-               } else {\r
-                       $query = array();\r
-               }\r
-               $query['_escaped_fragment_'] = '';\r
-               $iri->query = str_replace('%2F', '/', http_build_query($query)); // needed for some sites\r
-               return $iri->get_iri();\r
-       }\r
-       \r
-       public function removeFragment($url) {\r
-               $pos = strpos($url, '#');\r
-               if ($pos === false) {\r
-                       return $url;\r
-               } else {\r
-                       return substr($url, 0, $pos);\r
-               }\r
-       }\r
-       \r
-       public function rewriteUrls($url) {\r
-               foreach ($this->rewriteUrls as $find => $action) {\r
-                       if (strpos($url, $find) !== false) {\r
-                               if (is_array($action)) {\r
-                                       return strtr($url, $action);\r
-                               }\r
-                       }\r
-               }\r
-               return $url;\r
-       }\r
-       \r
-       public function enableDebug($bool=true) {\r
-               $this->debug = (bool)$bool;\r
-       }\r
-       \r
-       public function minimiseMemoryUse($bool = true) {\r
-               $this->minimiseMemoryUse = $bool;\r
-       }\r
-       \r
-       public function setMaxParallelRequests($max) {\r
-               $this->maxParallelRequests = $max;\r
-       }\r
-       \r
-       public function validateUrl($url) {\r
-               $url = filter_var($url, FILTER_SANITIZE_URL);\r
-               $test = filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED);\r
-               // deal with bug http://bugs.php.net/51192 (present in PHP 5.2.13 and PHP 5.3.2)\r
-               if ($test === false) {\r
-                       $test = filter_var(strtr($url, '-', '_'), FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED);\r
-               }\r
-               if ($test !== false && $test !== null && preg_match('!^https?://!', $url)) {\r
-                       return $url;\r
-               } else {\r
-                       return false;\r
-               }\r
-       }\r
-       \r
-       public function fetchAll(array $urls) {\r
-               $this->fetchAllOnce($urls, $isRedirect=false);\r
-               $redirects = 0;\r
-               while (!empty($this->redirectQueue) && ++$redirects <= $this->maxRedirects) {\r
-                       $this->debug("Following redirects #$redirects...");\r
-                       $this->fetchAllOnce($this->redirectQueue, $isRedirect=true);\r
-               }\r
-       }\r
-       \r
-       // fetch all URLs without following redirects\r
-       public function fetchAllOnce(array $urls, $isRedirect=false) {\r
-               if (!$isRedirect) $urls = array_unique($urls);\r
-               if (empty($urls)) return;\r
-               \r
-               //////////////////////////////////////////////////////\r
-               // parallel (HttpRequestPool)\r
-               if ($this->method == self::METHOD_REQUEST_POOL) {\r
-                       $this->debug('Starting parallel fetch (HttpRequestPool)');\r
-                       try {\r
-                               while (count($urls) > 0) {\r
-                                       $this->debug('Processing set of '.min($this->maxParallelRequests, count($urls)));\r
-                                       $subset = array_splice($urls, 0, $this->maxParallelRequests);\r
-                                       $pool = new HttpRequestPool();\r
-                                       foreach ($subset as $orig => $url) {\r
-                                               if (!$isRedirect) $orig = $url;\r
-                                               unset($this->redirectQueue[$orig]);\r
-                                               $this->debug("...$url");\r
-                                               if (!$isRedirect && isset($this->requests[$url])) {\r
-                                                       $this->debug("......in memory");\r
-                                               /*\r
-                                               } elseif ($this->isCached($url)) {\r
-                                                       $this->debug("......is cached");\r
-                                                       if (!$this->minimiseMemoryUse) {\r
-                                                               $this->requests[$url] = $this->getCached($url);\r
-                                                       }\r
-                                               */\r
-                                               } else {\r
-                                                       $this->debug("......adding to pool");\r
-                                                       $req_url = $this->rewriteUrls($url);\r
-                                                       $req_url = ($this->rewriteHashbangFragment) ? $this->rewriteHashbangFragment($req_url) : $req_url;\r
-                                                       $req_url = $this->removeFragment($req_url);\r
-                                                       if (!empty($this->headerOnlyTypes) && !isset($this->requests[$orig]['wrongGuess']) && $this->possibleUnsupportedType($req_url)) {\r
-                                                               $_meth = HttpRequest::METH_HEAD;\r
-                                                       } else {\r
-                                                               $_meth = HttpRequest::METH_GET;\r
-                                                               unset($this->requests[$orig]['wrongGuess']);\r
-                                                       }\r
-                                                       $httpRequest = new HttpRequest($req_url, $_meth, $this->requestOptions);\r
-                                                       // send cookies, if we have any\r
-                                                       if ($cookies = $this->cookieJar->getMatchingCookies($req_url)) {\r
-                                                               $this->debug("......sending cookies: $cookies");\r
-                                                               $httpRequest->addHeaders(array('Cookie' => $cookies));\r
-                                                       }\r
-                                                       //$httpRequest->addHeaders(array('User-Agent' => $this->userAgent));\r
-                                                       $httpRequest->addHeaders($this->getUserAgent($req_url, true));\r
-                                                       // add referer for picky sites\r
-                                                       $httpRequest->addheaders(array('Referer' => $this->referer));\r
-                                                       $this->requests[$orig] = array('headers'=>null, 'body'=>null, 'httpRequest'=>$httpRequest);\r
-                                                       $this->requests[$orig]['original_url'] = $orig;\r
-                                                       $pool->attach($httpRequest);\r
-                                               }\r
-                                       }\r
-                                       // did we get anything into the pool?\r
-                                       if (count($pool) > 0) {\r
-                                               $this->debug('Sending request...');\r
-                                               try {\r
-                                                       $pool->send();\r
-                                               } catch (HttpRequestPoolException $e) {\r
-                                                       // do nothing\r
-                                               }\r
-                                               $this->debug('Received responses');\r
-                                               foreach($subset as $orig => $url) {\r
-                                                       if (!$isRedirect) $orig = $url;\r
-                                                       $request = $this->requests[$orig]['httpRequest'];\r
-                                                       //$this->requests[$orig]['headers'] = $this->headersToString($request->getResponseHeader());\r
-                                                       // getResponseHeader() doesn't return status line, so, for consistency...\r
-                                                       $this->requests[$orig]['headers'] = substr($request->getRawResponseMessage(), 0, $request->getResponseInfo('header_size'));\r
-                                                       // check content type\r
-                                                       // TODO: use getResponseHeader('content-type') or getResponseInfo()\r
-                                                       if ($this->headerOnlyType($this->requests[$orig]['headers'])) {\r
-                                                               $this->requests[$orig]['body'] = '';\r
-                                                               $_header_only_type = true;\r
-                                                               $this->debug('Header only type returned');\r
-                                                       } else {\r
-                                                               $this->requests[$orig]['body'] = $request->getResponseBody();\r
-                                                               $_header_only_type = false;\r
-                                                       }\r
-                                                       $this->requests[$orig]['effective_url'] = $request->getResponseInfo('effective_url');\r
-                                                       $this->requests[$orig]['status_code'] = $status_code = $request->getResponseCode();\r
-                                                       // is redirect?\r
-                                                       if ((in_array($status_code, array(300, 301, 302, 303, 307)) || $status_code > 307 && $status_code < 400) && $request->getResponseHeader('location')) {\r
-                                                               $redirectURL = $request->getResponseHeader('location');\r
-                                                               if (!preg_match('!^https?://!i', $redirectURL)) {\r
-                                                                       $redirectURL = SimplePie_Misc::absolutize_url($redirectURL, $url);\r
-                                                               }\r
-                                                               if ($this->validateURL($redirectURL)) {\r
-                                                                       $this->debug('Redirect detected. Valid URL: '.$redirectURL);\r
-                                                                       // store any cookies\r
-                                                                       $cookies = $request->getResponseHeader('set-cookie');\r
-                                                                       if ($cookies && !is_array($cookies)) $cookies = array($cookies);\r
-                                                                       if ($cookies) $this->cookieJar->storeCookies($url, $cookies);\r
-                                                                       $this->redirectQueue[$orig] = $redirectURL;\r
-                                                               } else {\r
-                                                                       $this->debug('Redirect detected. Invalid URL: '.$redirectURL);\r
-                                                               }\r
-                                                       } elseif (!$_header_only_type && $request->getMethod() === HttpRequest::METH_HEAD) {\r
-                                                               // the response content-type did not match our 'header only' types, \r
-                                                               // but we'd issues a HEAD request because we assumed it would. So\r
-                                                               // let's queue a proper GET request for this item...\r
-                                                               $this->debug('Wrong guess at content-type, queing GET request');\r
-                                                               $this->requests[$orig]['wrongGuess'] = true;\r
-                                                               $this->redirectQueue[$orig] = $this->requests[$orig]['effective_url'];\r
-                                                       } elseif (strpos($this->requests[$orig]['effective_url'], '_escaped_fragment_') === false) {\r
-                                                               // check for <meta name='fragment' content='!'/>\r
-                                                               // for AJAX sites, e.g. Blogger with its dynamic views templates.\r
-                                                               // Based on Google's spec: https://developers.google.com/webmasters/ajax-crawling/docs/specification\r
-                                                               if (isset($this->requests[$orig]['body'])) {\r
-                                                                       $redirectURL = $this->getUglyURL($this->requests[$orig]['effective_url'], substr($this->requests[$orig]['body'], 0, 4000));\r
-                                                                       if ($redirectURL) {\r
-                                                                               $this->debug('AJAX trigger (meta name="fragment" content="!") found. Queueing '.$redirectURL);\r
-                                                                               $this->redirectQueue[$orig] = $redirectURL;\r
-                                                                       }\r
-                                                               }\r
-                                                       }\r
-                                                       //die($url.' -multi- '.$request->getResponseInfo('effective_url'));\r
-                                                       $pool->detach($request);\r
-                                                       unset($this->requests[$orig]['httpRequest'], $request);\r
-                                                       /*\r
-                                                       if ($this->minimiseMemoryUse) {\r
-                                                               if ($this->cache($url)) {\r
-                                                                       unset($this->requests[$url]);\r
-                                                               }\r
-                                                       }\r
-                                                       */\r
-                                               }\r
-                                       }\r
-                               }\r
-                       } catch (HttpException $e) {\r
-                               $this->debug($e);\r
-                               return false;\r
-                       }\r
-               }\r
-               \r
-               //////////////////////////////////////////////////////////\r
-               // parallel (curl_multi_*)\r
-               elseif ($this->method == self::METHOD_CURL_MULTI) {\r
-                       $this->debug('Starting parallel fetch (curl_multi_*)');\r
-                       while (count($urls) > 0) {\r
-                               $this->debug('Processing set of '.min($this->maxParallelRequests, count($urls)));\r
-                               $subset = array_splice($urls, 0, $this->maxParallelRequests);\r
-                               $pool = new RollingCurl(array($this, 'handleCurlResponse'));\r
-                               $pool->window_size = count($subset);            \r
-                               \r
-                               foreach ($subset as $orig => $url) {\r
-                                       if (!$isRedirect) $orig = $url;\r
-                                       unset($this->redirectQueue[$orig]);\r
-                                       $this->debug("...$url");\r
-                                       if (!$isRedirect && isset($this->requests[$url])) {\r
-                                               $this->debug("......in memory");\r
-                                       /*\r
-                                       } elseif ($this->isCached($url)) {\r
-                                               $this->debug("......is cached");\r
-                                               if (!$this->minimiseMemoryUse) {\r
-                                                       $this->requests[$url] = $this->getCached($url);\r
-                                               }\r
-                                       */\r
-                                       } else {\r
-                                               $this->debug("......adding to pool");\r
-                                               $req_url = $this->rewriteUrls($url);\r
-                                               $req_url = ($this->rewriteHashbangFragment) ? $this->rewriteHashbangFragment($req_url) : $req_url;\r
-                                               $req_url = $this->removeFragment($req_url);\r
-                                               if (!empty($this->headerOnlyTypes) && !isset($this->requests[$orig]['wrongGuess']) && $this->possibleUnsupportedType($req_url)) {\r
-                                                       $_meth = 'HEAD';\r
-                                               } else {\r
-                                                       $_meth = 'GET';\r
-                                                       unset($this->requests[$orig]['wrongGuess']);\r
-                                               }                                               \r
-                                               $headers = array();\r
-                                               //$headers[] = 'User-Agent: '.$this->userAgent;\r
-                                               $headers[] = $this->getUserAgent($req_url);\r
-                                               // add referer for picky sites\r
-                                               $headers[] = 'Referer: '.$this->referer;\r
-                                               // send cookies, if we have any\r
-                                               if ($cookies = $this->cookieJar->getMatchingCookies($req_url)) {\r
-                                                       $this->debug("......sending cookies: $cookies");\r
-                                                       $headers[] = 'Cookie: '.$cookies;\r
-                                               }\r
-                                               $httpRequest = new RollingCurlRequest($req_url, $_meth, null, $headers, array(\r
-                                                       CURLOPT_CONNECTTIMEOUT => $this->requestOptions['timeout'],\r
-                                                       CURLOPT_TIMEOUT => $this->requestOptions['timeout']\r
-                                                       ));\r
-                                               $httpRequest->set_original_url($orig);\r
-                                               $this->requests[$orig] = array('headers'=>null, 'body'=>null, 'httpRequest'=>$httpRequest);\r
-                                               $this->requests[$orig]['original_url'] = $orig; // TODO: is this needed anymore?\r
-                                               $pool->add($httpRequest);\r
-                                       }\r
-                               }\r
-                               // did we get anything into the pool?\r
-                               if (count($pool) > 0) {\r
-                                       $this->debug('Sending request...');\r
-                                       $pool->execute(); // this will call handleCurlResponse() and populate $this->requests[$orig]\r
-                                       $this->debug('Received responses');\r
-                                       foreach($subset as $orig => $url) {\r
-                                               if (!$isRedirect) $orig = $url;\r
-                                               // $this->requests[$orig]['headers']\r
-                                               // $this->requests[$orig]['body']\r
-                                               // $this->requests[$orig]['effective_url']\r
-                                               // check content type\r
-                                               if ($this->headerOnlyType($this->requests[$orig]['headers'])) {\r
-                                                       $this->requests[$orig]['body'] = '';\r
-                                                       $_header_only_type = true;\r
-                                                       $this->debug('Header only type returned');\r
-                                               } else {\r
-                                                       $_header_only_type = false;\r
-                                               }\r
-                                               $status_code = $this->requests[$orig]['status_code'];\r
-                                               if ((in_array($status_code, array(300, 301, 302, 303, 307)) || $status_code > 307 && $status_code < 400) && isset($this->requests[$orig]['location'])) {\r
-                                                       $redirectURL = $this->requests[$orig]['location'];\r
-                                                       if (!preg_match('!^https?://!i', $redirectURL)) {\r
-                                                               $redirectURL = SimplePie_Misc::absolutize_url($redirectURL, $url);\r
-                                                       }\r
-                                                       if ($this->validateURL($redirectURL)) {\r
-                                                               $this->debug('Redirect detected. Valid URL: '.$redirectURL);\r
-                                                               // store any cookies\r
-                                                               $cookies = $this->cookieJar->extractCookies($this->requests[$orig]['headers']);\r
-                                                               if (!empty($cookies)) $this->cookieJar->storeCookies($url, $cookies);                                                   \r
-                                                               $this->redirectQueue[$orig] = $redirectURL;\r
-                                                       } else {\r
-                                                               $this->debug('Redirect detected. Invalid URL: '.$redirectURL);\r
-                                                       }\r
-                                               } elseif (!$_header_only_type && $this->requests[$orig]['method'] == 'HEAD') {\r
-                                                       // the response content-type did not match our 'header only' types, \r
-                                                       // but we'd issues a HEAD request because we assumed it would. So\r
-                                                       // let's queue a proper GET request for this item...\r
-                                                       $this->debug('Wrong guess at content-type, queing GET request');\r
-                                                       $this->requests[$orig]['wrongGuess'] = true;\r
-                                                       $this->redirectQueue[$orig] = $this->requests[$orig]['effective_url'];\r
-                                               } elseif (strpos($this->requests[$orig]['effective_url'], '_escaped_fragment_') === false) {\r
-                                                       // check for <meta name='fragment' content='!'/>\r
-                                                       // for AJAX sites, e.g. Blogger with its dynamic views templates.\r
-                                                       // Based on Google's spec: https://developers.google.com/webmasters/ajax-crawling/docs/specification\r
-                                                       if (isset($this->requests[$orig]['body'])) {\r
-                                                               $redirectURL = $this->getUglyURL($this->requests[$orig]['effective_url'], substr($this->requests[$orig]['body'], 0, 4000));\r
-                                                               if ($redirectURL) {\r
-                                                                       $this->debug('AJAX trigger (meta name="fragment" content="!") found. Queueing '.$redirectURL);\r
-                                                                       $this->redirectQueue[$orig] = $redirectURL;\r
-                                                               }\r
-                                                       }\r
-                                               }\r
-                                               // die($url.' -multi- '.$request->getResponseInfo('effective_url'));\r
-                                               unset($this->requests[$orig]['httpRequest'], $this->requests[$orig]['method']);\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-               //////////////////////////////////////////////////////\r
-               // sequential (file_get_contents)\r
-               else {\r
-                       $this->debug('Starting sequential fetch (file_get_contents)');\r
-                       $this->debug('Processing set of '.count($urls));\r
-                       foreach ($urls as $orig => $url) {\r
-                               if (!$isRedirect) $orig = $url;\r
-                               unset($this->redirectQueue[$orig]);\r
-                               $this->debug("...$url");\r
-                               if (!$isRedirect && isset($this->requests[$url])) {\r
-                                       $this->debug("......in memory");\r
-                               /*\r
-                               } elseif ($this->isCached($url)) {\r
-                                       $this->debug("......is cached");\r
-                                       if (!$this->minimiseMemoryUse) {\r
-                                               $this->requests[$url] = $this->getCached($url);\r
-                                       }\r
-                               */\r
-                               } else {\r
-                                       $this->debug("Sending request for $url");\r
-                                       $this->requests[$orig]['original_url'] = $orig;\r
-                                       $req_url = $this->rewriteUrls($url);\r
-                                       $req_url = ($this->rewriteHashbangFragment) ? $this->rewriteHashbangFragment($req_url) : $req_url;\r
-                                       $req_url = $this->removeFragment($req_url);\r
-                                       // send cookies, if we have any\r
-                                       $httpContext = $this->httpContext;\r
-                                       $httpContext['http']['header'] .= $this->getUserAgent($req_url)."\r\n";\r
-                                       // add referer for picky sites\r
-                                       $httpContext['http']['header'] .= 'Referer: '.$this->referer."\r\n";\r
-                                       if ($cookies = $this->cookieJar->getMatchingCookies($req_url)) {\r
-                                               $this->debug("......sending cookies: $cookies");\r
-                                               $httpContext['http']['header'] .= 'Cookie: '.$cookies."\r\n";\r
-                                       }\r
-                                       if (false !== ($html = @file_get_contents($req_url, false, stream_context_create($httpContext)))) {\r
-                                               $this->debug('Received response');\r
-                                               // get status code\r
-                                               if (!isset($http_response_header[0]) || !preg_match('!^HTTP/\d+\.\d+\s+(\d+)!', trim($http_response_header[0]), $match)) {\r
-                                                       $this->debug('Error: no status code found');\r
-                                                       // TODO: handle error - no status code\r
-                                               } else {\r
-                                                       $this->requests[$orig]['headers'] = $this->headersToString($http_response_header, false);\r
-                                                       // check content type\r
-                                                       if ($this->headerOnlyType($this->requests[$orig]['headers'])) {\r
-                                                               $this->requests[$orig]['body'] = '';\r
-                                                       } else {\r
-                                                               $this->requests[$orig]['body'] = $html;\r
-                                                       }\r
-                                                       $this->requests[$orig]['effective_url'] = $req_url;\r
-                                                       $this->requests[$orig]['status_code'] = $status_code = (int)$match[1];\r
-                                                       unset($match);\r
-                                                       // handle redirect\r
-                                                       if (preg_match('/^Location:(.*?)$/mi', $this->requests[$orig]['headers'], $match)) {\r
-                                                               $this->requests[$orig]['location'] =  trim($match[1]);\r
-                                                       }\r
-                                                       if ((in_array($status_code, array(300, 301, 302, 303, 307)) || $status_code > 307 && $status_code < 400) && isset($this->requests[$orig]['location'])) {\r
-                                                               $redirectURL = $this->requests[$orig]['location'];\r
-                                                               if (!preg_match('!^https?://!i', $redirectURL)) {\r
-                                                                       $redirectURL = SimplePie_Misc::absolutize_url($redirectURL, $url);\r
-                                                               }\r
-                                                               if ($this->validateURL($redirectURL)) {\r
-                                                                       $this->debug('Redirect detected. Valid URL: '.$redirectURL);\r
-                                                                       // store any cookies\r
-                                                                       $cookies = $this->cookieJar->extractCookies($this->requests[$orig]['headers']);\r
-                                                                       if (!empty($cookies)) $this->cookieJar->storeCookies($url, $cookies);\r
-                                                                       $this->redirectQueue[$orig] = $redirectURL;\r
-                                                               } else {\r
-                                                                       $this->debug('Redirect detected. Invalid URL: '.$redirectURL);\r
-                                                               }\r
-                                                       } elseif (strpos($this->requests[$orig]['effective_url'], '_escaped_fragment_') === false) {\r
-                                                               // check for <meta name='fragment' content='!'/>\r
-                                                               // for AJAX sites, e.g. Blogger with its dynamic views templates.\r
-                                                               // Based on Google's spec: https://developers.google.com/webmasters/ajax-crawling/docs/specification\r
-                                                               if (isset($this->requests[$orig]['body'])) {\r
-                                                                       $redirectURL = $this->getUglyURL($this->requests[$orig]['effective_url'], substr($this->requests[$orig]['body'], 0, 4000));\r
-                                                                       if ($redirectURL) {\r
-                                                                               $this->debug('AJAX trigger (meta name="fragment" content="!") found. Queueing '.$redirectURL);\r
-                                                                               $this->redirectQueue[$orig] = $redirectURL;\r
-                                                                       }\r
-                                                               }\r
-                                                       }\r
-                                               }\r
-                                       } else {\r
-                                               $this->debug('Error retrieving URL');\r
-                                               //print_r($req_url);\r
-                                               //print_r($http_response_header);\r
-                                               //print_r($html);\r
-                                               \r
-                                               // TODO: handle error - failed to retrieve URL\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-       }\r
-       \r
-       public function handleCurlResponse($response, $info, $request) {\r
-               $orig = $request->url_original;\r
-               $this->requests[$orig]['headers'] = substr($response, 0, $info['header_size']);\r
-               $this->requests[$orig]['body'] = substr($response, $info['header_size']);\r
-               $this->requests[$orig]['method'] = $request->method;\r
-               $this->requests[$orig]['effective_url'] = $info['url'];\r
-               $this->requests[$orig]['status_code'] = (int)$info['http_code'];\r
-               if (preg_match('/^Location:(.*?)$/mi', $this->requests[$orig]['headers'], $match)) {\r
-                       $this->requests[$orig]['location'] =  trim($match[1]);\r
-               }\r
-       }\r
-       \r
-       protected function headersToString(array $headers, $associative=true) {\r
-               if (!$associative) {\r
-                       return implode("\n", $headers);\r
-               } else {\r
-                       $str = '';\r
-                       foreach ($headers as $key => $val) {\r
-                               if (is_array($val)) {\r
-                                       foreach ($val as $v) $str .= "$key: $v\n";\r
-                               } else {\r
-                                       $str .= "$key: $val\n";\r
-                               }\r
-                       }\r
-                       return rtrim($str);\r
-               }\r
-       }\r
-       \r
-       public function get($url, $remove=false, $gzdecode=true) {\r
-               $url = "$url";\r
-               if (isset($this->requests[$url]) && isset($this->requests[$url]['body'])) {\r
-                       $this->debug("URL already fetched - in memory ($url, effective: {$this->requests[$url]['effective_url']})");\r
-                       $response = $this->requests[$url];\r
-               /*\r
-               } elseif ($this->isCached($url)) {\r
-                       $this->debug("URL already fetched - in disk cache ($url)");\r
-                       $response = $this->getCached($url);\r
-                       $this->requests[$url] = $response;\r
-               */\r
-               } else {\r
-                       $this->debug("Fetching URL ($url)");\r
-                       $this->fetchAll(array($url));\r
-                       if (isset($this->requests[$url]) && isset($this->requests[$url]['body'])) {\r
-                               $response = $this->requests[$url];\r
-                       } else {\r
-                               $this->debug("Request failed");\r
-                               $response = false;\r
-                       }\r
-               }\r
-               /*\r
-               if ($this->minimiseMemoryUse && $response) {\r
-                       $this->cache($url);\r
-                       unset($this->requests[$url]);\r
-               }\r
-               */\r
-               if ($remove && $response) unset($this->requests[$url]);\r
-               if ($gzdecode && stripos($response['headers'], 'Content-Encoding: gzip')) {\r
-                       if ($html = gzdecode($response['body'])) {\r
-                               $response['body'] = $html;\r
-                       }\r
-               }\r
-               return $response;\r
-       }\r
-       \r
-       public function parallelSupport() {\r
-               return class_exists('HttpRequestPool') || function_exists('curl_multi_init');\r
-       }\r
-       \r
-       private function headerOnlyType($headers) {\r
-               if (preg_match('!^Content-Type:\s*(([a-z-]+)/([^;\r\n ]+))!im', $headers, $match)) {\r
-                       // look for full mime type (e.g. image/jpeg) or just type (e.g. image)\r
-                       $match[1] = strtolower(trim($match[1]));\r
-                       $match[2] = strtolower(trim($match[2]));\r
-                       foreach (array($match[1], $match[2]) as $mime) {\r
-                               if (in_array($mime, $this->headerOnlyTypes)) return true;\r
-                       }\r
-               }\r
-               return false;\r
-       }\r
-       \r
-       private function possibleUnsupportedType($url) {\r
-               $path = @parse_url($url, PHP_URL_PATH);\r
-               if ($path && strpos($path, '.') !== false) {\r
-                       $ext = strtolower(trim(pathinfo($path, PATHINFO_EXTENSION)));\r
-                       return in_array($ext, $this->headerOnlyClues);\r
-               }\r
-               return false;\r
-       }\r
-}\r
-\r
-// gzdecode from http://www.php.net/manual/en/function.gzdecode.php#82930\r
-if (!function_exists('gzdecode')) {\r
-       function gzdecode($data,&$filename='',&$error='',$maxlength=null) \r
-       {\r
-               $len = strlen($data);\r
-               if ($len < 18 || strcmp(substr($data,0,2),"\x1f\x8b")) {\r
-                       $error = "Not in GZIP format.";\r
-                       return null;  // Not GZIP format (See RFC 1952)\r
-               }\r
-               $method = ord(substr($data,2,1));  // Compression method\r
-               $flags  = ord(substr($data,3,1));  // Flags\r
-               if ($flags & 31 != $flags) {\r
-                       $error = "Reserved bits not allowed.";\r
-                       return null;\r
-               }\r
-               // NOTE: $mtime may be negative (PHP integer limitations)\r
-               $mtime = unpack("V", substr($data,4,4));\r
-               $mtime = $mtime[1];\r
-               $xfl   = substr($data,8,1);\r
-               $os    = substr($data,8,1);\r
-               $headerlen = 10;\r
-               $extralen  = 0;\r
-               $extra     = "";\r
-               if ($flags & 4) {\r
-                       // 2-byte length prefixed EXTRA data in header\r
-                       if ($len - $headerlen - 2 < 8) {\r
-                               return false;  // invalid\r
-                       }\r
-                       $extralen = unpack("v",substr($data,8,2));\r
-                       $extralen = $extralen[1];\r
-                       if ($len - $headerlen - 2 - $extralen < 8) {\r
-                               return false;  // invalid\r
-                       }\r
-                       $extra = substr($data,10,$extralen);\r
-                       $headerlen += 2 + $extralen;\r
-               }\r
-               $filenamelen = 0;\r
-               $filename = "";\r
-               if ($flags & 8) {\r
-                       // C-style string\r
-                       if ($len - $headerlen - 1 < 8) {\r
-                               return false; // invalid\r
-                       }\r
-                       $filenamelen = strpos(substr($data,$headerlen),chr(0));\r
-                       if ($filenamelen === false || $len - $headerlen - $filenamelen - 1 < 8) {\r
-                               return false; // invalid\r
-                       }\r
-                       $filename = substr($data,$headerlen,$filenamelen);\r
-                       $headerlen += $filenamelen + 1;\r
-               }\r
-               $commentlen = 0;\r
-               $comment = "";\r
-               if ($flags & 16) {\r
-                       // C-style string COMMENT data in header\r
-                       if ($len - $headerlen - 1 < 8) {\r
-                               return false;    // invalid\r
-                       }\r
-                       $commentlen = strpos(substr($data,$headerlen),chr(0));\r
-                       if ($commentlen === false || $len - $headerlen - $commentlen - 1 < 8) {\r
-                               return false;    // Invalid header format\r
-                       }\r
-                       $comment = substr($data,$headerlen,$commentlen);\r
-                       $headerlen += $commentlen + 1;\r
-               }\r
-               $headercrc = "";\r
-               if ($flags & 2) {\r
-                       // 2-bytes (lowest order) of CRC32 on header present\r
-                       if ($len - $headerlen - 2 < 8) {\r
-                               return false;    // invalid\r
-                       }\r
-                       $calccrc = crc32(substr($data,0,$headerlen)) & 0xffff;\r
-                       $headercrc = unpack("v", substr($data,$headerlen,2));\r
-                       $headercrc = $headercrc[1];\r
-                       if ($headercrc != $calccrc) {\r
-                               $error = "Header checksum failed.";\r
-                               return false;    // Bad header CRC\r
-                       }\r
-                       $headerlen += 2;\r
-               }\r
-               // GZIP FOOTER\r
-               $datacrc = unpack("V",substr($data,-8,4));\r
-               $datacrc = sprintf('%u',$datacrc[1] & 0xFFFFFFFF);\r
-               $isize = unpack("V",substr($data,-4));\r
-               $isize = $isize[1];\r
-               // decompression:\r
-               $bodylen = $len-$headerlen-8;\r
-               if ($bodylen < 1) {\r
-                       // IMPLEMENTATION BUG!\r
-                       return null;\r
-               }\r
-               $body = substr($data,$headerlen,$bodylen);\r
-               $data = "";\r
-               if ($bodylen > 0) {\r
-                       switch ($method) {\r
-                       case 8:\r
-                               // Currently the only supported compression method:\r
-                               $data = gzinflate($body,$maxlength);\r
-                               break;\r
-                       default:\r
-                               $error = "Unknown compression method.";\r
-                               return false;\r
-                       }\r
-               }  // zero-byte body content is allowed\r
-               // Verifiy CRC32\r
-               $crc   = sprintf("%u",crc32($data));\r
-               $crcOK = $crc == $datacrc;\r
-               $lenOK = $isize == strlen($data);\r
-               if (!$lenOK || !$crcOK) {\r
-                       $error = ( $lenOK ? '' : 'Length check FAILED. ') . ( $crcOK ? '' : 'Checksum FAILED.');\r
-                       return false;\r
-               }\r
-               return $data;\r
-       }\r
-}\r
-?>
\ No newline at end of file
+<?php
+/**
+ * Humble HTTP Agent
+ * 
+ * This class is designed to take advantage of parallel HTTP requests
+ * offered by PHP's PECL HTTP extension or the curl_multi_* functions. 
+ * For environments which do not have these options, it reverts to standard sequential 
+ * requests (using file_get_contents())
+ * 
+ * @version 1.4
+ * @date 2013-05-10
+ * @see http://php.net/HttpRequestPool
+ * @author Keyvan Minoukadeh
+ * @copyright 2011-2013 Keyvan Minoukadeh
+ * @license http://www.gnu.org/licenses/agpl-3.0.html AGPL v3
+ */
+
+class HumbleHttpAgent
+{
+       const METHOD_REQUEST_POOL = 1;
+       const METHOD_CURL_MULTI = 2;
+       const METHOD_FILE_GET_CONTENTS = 4;
+       //const UA_BROWSER = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0.1) Gecko/20100101 Firefox/4.0.1';
+       const UA_BROWSER = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.92 Safari/535.2';
+       const UA_PHP = 'PHP/5.4';
+       const REF_GOOGLE = 'http://www.google.co.uk/url?sa=t&source=web&cd=1';
+       
+       protected $requests = array();
+       protected $redirectQueue = array();
+       protected $requestOptions;
+       protected $maxParallelRequests = 5;
+       protected $cache = null; //TODO
+       protected $httpContext;
+       protected $minimiseMemoryUse = false; //TODO
+       protected $method;
+       protected $cookieJar;
+       public $debug = false;
+       public $debugVerbose = false;
+       public $rewriteHashbangFragment = true; // see http://code.google.com/web/ajaxcrawling/docs/specification.html
+       public $maxRedirects = 5;
+       public $userAgentMap = array();
+       public $rewriteUrls = array();
+       public $userAgentDefault;
+       public $referer;
+       //public $userAgent = 'Mozilla/5.0';
+       
+       // Prevent certain file/mime types
+       // HTTP responses which match these content types will
+       // be returned without body.
+       public $headerOnlyTypes = array();
+       // URLs ending with one of these extensions will
+       // prompt Humble HTTP Agent to send a HEAD request first
+       // to see if returned content type matches $headerOnlyTypes.
+       public $headerOnlyClues = array('pdf','mp3','zip','exe','gif','gzip','gz','jpeg','jpg','mpg','mpeg','png','ppt','mov');
+       // AJAX triggers to search for.
+       // for AJAX sites, e.g. Blogger with its dynamic views templates.
+       public $ajaxTriggers = array("<meta name='fragment' content='!'",'<meta name="fragment" content="!"',"<meta content='!' name='fragment'",'<meta content="!" name="fragment"');
+       
+       //TODO: set max file size
+       //TODO: normalise headers
+       
+       function __construct($requestOptions=null, $method=null) {
+               $this->userAgentDefault = self::UA_BROWSER;
+               $this->referer = self::REF_GOOGLE;
+               // set the request method
+               if (in_array($method, array(1,2,4))) {
+                       $this->method = $method;
+               } else {
+                       if (class_exists('HttpRequestPool')) {
+                               $this->method = self::METHOD_REQUEST_POOL;
+                       } elseif (function_exists('curl_multi_init')) {
+                               $this->method = self::METHOD_CURL_MULTI;
+                       } else {
+                               $this->method = self::METHOD_FILE_GET_CONTENTS;
+                       }
+               }
+               if ($this->method == self::METHOD_CURL_MULTI) {
+                       require_once(dirname(__FILE__).'/RollingCurl.php');
+               }
+               // create cookie jar
+               $this->cookieJar = new CookieJar();
+               // set request options (redirect must be 0)
+               $this->requestOptions = array(
+                       'timeout' => 15,
+                       'connecttimeout' => 15,
+                       'dns_cache_timeout' => 300,
+                       'redirect' => 0 // we handle redirects manually so we can rewrite the new hashbang URLs that are creeping up over the web
+                       // TODO: test onprogress?
+               );
+               if (is_array($requestOptions)) {
+                       $this->requestOptions = array_merge($this->requestOptions, $requestOptions);
+               }
+               $this->httpContext = array(
+                       'http' => array(
+                               'ignore_errors' => true,
+                               'timeout' => $this->requestOptions['timeout'],
+                               'max_redirects' => $this->requestOptions['redirect'],
+                               'header' => "Accept: */*\r\n"
+                               )
+                       );
+       }
+       
+       protected function debug($msg) {
+               if ($this->debug) {
+                       $mem = round(memory_get_usage()/1024, 2);
+                       $memPeak = round(memory_get_peak_usage()/1024, 2);
+                       echo '* ',$msg;
+                       if ($this->debugVerbose) echo ' - mem used: ',$mem," (peak: $memPeak)";
+                       echo "\n";
+                       ob_flush();
+                       flush();
+               }
+       }
+       
+       protected function getUserAgent($url, $asArray=false) {
+               $host = @parse_url($url, PHP_URL_HOST);
+               if (strtolower(substr($host, 0, 4)) == 'www.') {
+                       $host = substr($host, 4);
+               }
+               if ($host) {
+                       $try = array($host);
+                       $split = explode('.', $host);
+                       if (count($split) > 1) {
+                               array_shift($split);
+                               $try[] = '.'.implode('.', $split);
+                       }
+                       foreach ($try as $h) {
+                               if (isset($this->userAgentMap[$h])) {
+                                       $ua = $this->userAgentMap[$h];
+                                       break;
+                               }
+                       }
+               }
+               if (!isset($ua)) $ua = $this->userAgentDefault;
+               if ($asArray) {
+                       return array('User-Agent' => $ua);
+               } else {
+                       return 'User-Agent: '.$ua;
+               }
+       }
+       
+       public function rewriteHashbangFragment($url) {
+               // return $url if there's no '#!'
+               if (strpos($url, '#!') === false) return $url;
+               // split $url and rewrite
+               // TODO: is SimplePie_IRI included?
+               $iri = new SimplePie_IRI($url);
+               $fragment = substr($iri->fragment, 1); // strip '!'
+               $iri->fragment = null;
+               if (isset($iri->query)) {
+                       parse_str($iri->query, $query);
+               } else {
+                       $query = array();
+               }
+               $query['_escaped_fragment_'] = (string)$fragment;
+               $iri->query = str_replace('%2F', '/', http_build_query($query)); // needed for some sites
+               return $iri->get_iri();
+       }
+       
+       public function getRedirectURLfromHTML($url, $html) {
+               $redirect_url = $this->getMetaRefreshURL($url, $html);
+               if (!$redirect_url) {
+                       $redirect_url = $this->getUglyURL($url, $html);
+               }
+               return $redirect_url;
+       }
+       
+       public function getMetaRefreshURL($url, $html) {
+               if ($html == '') return false;
+               // <meta HTTP-EQUIV="REFRESH" content="0; url=http://www.bernama.com/bernama/v6/newsindex.php?id=943513">
+               if (!preg_match('!<meta http-equiv=["\']?refresh["\']? content=["\']?[0-9];\s*url=["\']?([^"\'>]+)["\']*>!i', $html, $match)) {
+                       return false;
+               }
+               $redirect_url = $match[1];
+               if (preg_match('!^https?://!i', $redirect_url)) {
+                       // already absolute
+                       $this->debug('Meta refresh redirect found (http-equiv="refresh"), new URL: '.$redirect_url);
+                       return $redirect_url;
+               }
+               // absolutize redirect URL
+               $base = new SimplePie_IRI($url);
+               // remove '//' in URL path (causes URLs not to resolve properly)
+               if (isset($base->path)) $base->path = preg_replace('!//+!', '/', $base->path);
+               if ($absolute = SimplePie_IRI::absolutize($base, $redirect_url)) {
+                       $this->debug('Meta refresh redirect found (http-equiv="refresh"), new URL: '.$absolute);
+                       return $absolute;
+               }
+               return false;
+       }       
+       
+       public function getUglyURL($url, $html) {
+               if ($html == '') return false;
+               $found = false;
+               foreach ($this->ajaxTriggers as $string) {
+                       if (stripos($html, $string)) {
+                               $found = true;
+                               break;
+                       }
+               }
+               if (!$found) return false;
+               $iri = new SimplePie_IRI($url);
+               if (isset($iri->query)) {
+                       parse_str($iri->query, $query);
+               } else {
+                       $query = array();
+               }
+               $query['_escaped_fragment_'] = '';
+               $iri->query = str_replace('%2F', '/', http_build_query($query)); // needed for some sites
+               $ugly_url = $iri->get_iri();
+               $this->debug('AJAX trigger (meta name="fragment" content="!") found, new URL: '.$ugly_url);
+               return $ugly_url;
+       }
+       
+       public function removeFragment($url) {
+               $pos = strpos($url, '#');
+               if ($pos === false) {
+                       return $url;
+               } else {
+                       return substr($url, 0, $pos);
+               }
+       }
+       
+       public function rewriteUrls($url) {
+               foreach ($this->rewriteUrls as $find => $action) {
+                       if (strpos($url, $find) !== false) {
+                               if (is_array($action)) {
+                                       return strtr($url, $action);
+                               }
+                       }
+               }
+               return $url;
+       }
+       
+       public function enableDebug($bool=true) {
+               $this->debug = (bool)$bool;
+       }
+       
+       public function minimiseMemoryUse($bool = true) {
+               $this->minimiseMemoryUse = $bool;
+       }
+       
+       public function setMaxParallelRequests($max) {
+               $this->maxParallelRequests = $max;
+       }
+       
+       public function validateUrl($url) {
+               $url = filter_var($url, FILTER_SANITIZE_URL);
+               $test = filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED);
+               // deal with bug http://bugs.php.net/51192 (present in PHP 5.2.13 and PHP 5.3.2)
+               if ($test === false) {
+                       $test = filter_var(strtr($url, '-', '_'), FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED);
+               }
+               if ($test !== false && $test !== null && preg_match('!^https?://!', $url)) {
+                       return $url;
+               } else {
+                       return false;
+               }
+       }
+       
+       public function fetchAll(array $urls) {
+               $this->fetchAllOnce($urls, $isRedirect=false);
+               $redirects = 0;
+               while (!empty($this->redirectQueue) && ++$redirects <= $this->maxRedirects) {
+                       $this->debug("Following redirects #$redirects...");
+                       $this->fetchAllOnce($this->redirectQueue, $isRedirect=true);
+               }
+       }
+       
+       // fetch all URLs without following redirects
+       public function fetchAllOnce(array $urls, $isRedirect=false) {
+               if (!$isRedirect) $urls = array_unique($urls);
+               if (empty($urls)) return;
+               
+               //////////////////////////////////////////////////////
+               // parallel (HttpRequestPool)
+               if ($this->method == self::METHOD_REQUEST_POOL) {
+                       $this->debug('Starting parallel fetch (HttpRequestPool)');
+                       try {
+                               while (count($urls) > 0) {
+                                       $this->debug('Processing set of '.min($this->maxParallelRequests, count($urls)));
+                                       $subset = array_splice($urls, 0, $this->maxParallelRequests);
+                                       $pool = new HttpRequestPool();
+                                       foreach ($subset as $orig => $url) {
+                                               if (!$isRedirect) $orig = $url;
+                                               unset($this->redirectQueue[$orig]);
+                                               $this->debug("...$url");
+                                               if (!$isRedirect && isset($this->requests[$url])) {
+                                                       $this->debug("......in memory");
+                                               /*
+                                               } elseif ($this->isCached($url)) {
+                                                       $this->debug("......is cached");
+                                                       if (!$this->minimiseMemoryUse) {
+                                                               $this->requests[$url] = $this->getCached($url);
+                                                       }
+                                               */
+                                               } else {
+                                                       $this->debug("......adding to pool");
+                                                       $req_url = $this->rewriteUrls($url);
+                                                       $req_url = ($this->rewriteHashbangFragment) ? $this->rewriteHashbangFragment($req_url) : $req_url;
+                                                       $req_url = $this->removeFragment($req_url);
+                                                       if (!empty($this->headerOnlyTypes) && !isset($this->requests[$orig]['wrongGuess']) && $this->possibleUnsupportedType($req_url)) {
+                                                               $_meth = HttpRequest::METH_HEAD;
+                                                       } else {
+                                                               $_meth = HttpRequest::METH_GET;
+                                                               unset($this->requests[$orig]['wrongGuess']);
+                                                       }
+                                                       $httpRequest = new HttpRequest($req_url, $_meth, $this->requestOptions);
+                                                       // send cookies, if we have any
+                                                       if ($cookies = $this->cookieJar->getMatchingCookies($req_url)) {
+                                                               $this->debug("......sending cookies: $cookies");
+                                                               $httpRequest->addHeaders(array('Cookie' => $cookies));
+                                                       }
+                                                       //$httpRequest->addHeaders(array('User-Agent' => $this->userAgent));
+                                                       $httpRequest->addHeaders($this->getUserAgent($req_url, true));
+                                                       // add referer for picky sites
+                                                       $httpRequest->addheaders(array('Referer' => $this->referer));
+                                                       $this->requests[$orig] = array('headers'=>null, 'body'=>null, 'httpRequest'=>$httpRequest);
+                                                       $this->requests[$orig]['original_url'] = $orig;
+                                                       $pool->attach($httpRequest);
+                                               }
+                                       }
+                                       // did we get anything into the pool?
+                                       if (count($pool) > 0) {
+                                               $this->debug('Sending request...');
+                                               try {
+                                                       $pool->send();
+                                               } catch (HttpRequestPoolException $e) {
+                                                       // do nothing
+                                               }
+                                               $this->debug('Received responses');
+                                               foreach($subset as $orig => $url) {
+                                                       if (!$isRedirect) $orig = $url;
+                                                       $request = $this->requests[$orig]['httpRequest'];
+                                                       //$this->requests[$orig]['headers'] = $this->headersToString($request->getResponseHeader());
+                                                       // getResponseHeader() doesn't return status line, so, for consistency...
+                                                       $this->requests[$orig]['headers'] = substr($request->getRawResponseMessage(), 0, $request->getResponseInfo('header_size'));
+                                                       // check content type
+                                                       // TODO: use getResponseHeader('content-type') or getResponseInfo()
+                                                       if ($this->headerOnlyType($this->requests[$orig]['headers'])) {
+                                                               $this->requests[$orig]['body'] = '';
+                                                               $_header_only_type = true;
+                                                               $this->debug('Header only type returned');
+                                                       } else {
+                                                               $this->requests[$orig]['body'] = $request->getResponseBody();
+                                                               $_header_only_type = false;
+                                                       }
+                                                       $this->requests[$orig]['effective_url'] = $request->getResponseInfo('effective_url');
+                                                       $this->requests[$orig]['status_code'] = $status_code = $request->getResponseCode();
+                                                       // is redirect?
+                                                       if ((in_array($status_code, array(300, 301, 302, 303, 307)) || $status_code > 307 && $status_code < 400) && $request->getResponseHeader('location')) {
+                                                               $redirectURL = $request->getResponseHeader('location');
+                                                               if (!preg_match('!^https?://!i', $redirectURL)) {
+                                                                       $redirectURL = SimplePie_Misc::absolutize_url($redirectURL, $url);
+                                                               }
+                                                               if ($this->validateURL($redirectURL)) {
+                                                                       $this->debug('Redirect detected. Valid URL: '.$redirectURL);
+                                                                       // store any cookies
+                                                                       $cookies = $request->getResponseHeader('set-cookie');
+                                                                       if ($cookies && !is_array($cookies)) $cookies = array($cookies);
+                                                                       if ($cookies) $this->cookieJar->storeCookies($url, $cookies);
+                                                                       $this->redirectQueue[$orig] = $redirectURL;
+                                                               } else {
+                                                                       $this->debug('Redirect detected. Invalid URL: '.$redirectURL);
+                                                               }
+                                                       } elseif (!$_header_only_type && $request->getMethod() === HttpRequest::METH_HEAD) {
+                                                               // the response content-type did not match our 'header only' types, 
+                                                               // but we'd issues a HEAD request because we assumed it would. So
+                                                               // let's queue a proper GET request for this item...
+                                                               $this->debug('Wrong guess at content-type, queing GET request');
+                                                               $this->requests[$orig]['wrongGuess'] = true;
+                                                               $this->redirectQueue[$orig] = $this->requests[$orig]['effective_url'];
+                                                       } elseif (strpos($this->requests[$orig]['effective_url'], '_escaped_fragment_') === false) {
+                                                               // check for <meta name='fragment' content='!'/>
+                                                               // for AJAX sites, e.g. Blogger with its dynamic views templates.
+                                                               // Based on Google's spec: https://developers.google.com/webmasters/ajax-crawling/docs/specification
+                                                               if (isset($this->requests[$orig]['body'])) {
+                                                                       $redirectURL = $this->getRedirectURLfromHTML($this->requests[$orig]['effective_url'], substr($this->requests[$orig]['body'], 0, 4000));
+                                                                       if ($redirectURL) {
+                                                                               $this->redirectQueue[$orig] = $redirectURL;
+                                                                       }
+                                                               }
+                                                       }
+                                                       //die($url.' -multi- '.$request->getResponseInfo('effective_url'));
+                                                       $pool->detach($request);
+                                                       unset($this->requests[$orig]['httpRequest'], $request);
+                                                       /*
+                                                       if ($this->minimiseMemoryUse) {
+                                                               if ($this->cache($url)) {
+                                                                       unset($this->requests[$url]);
+                                                               }
+                                                       }
+                                                       */
+                                               }
+                                       }
+                               }
+                       } catch (HttpException $e) {
+                               $this->debug($e);
+                               return false;
+                       }
+               }
+               
+               //////////////////////////////////////////////////////////
+               // parallel (curl_multi_*)
+               elseif ($this->method == self::METHOD_CURL_MULTI) {
+                       $this->debug('Starting parallel fetch (curl_multi_*)');
+                       while (count($urls) > 0) {
+                               $this->debug('Processing set of '.min($this->maxParallelRequests, count($urls)));
+                               $subset = array_splice($urls, 0, $this->maxParallelRequests);
+                               $pool = new RollingCurl(array($this, 'handleCurlResponse'));
+                               $pool->window_size = count($subset);            
+                               
+                               foreach ($subset as $orig => $url) {
+                                       if (!$isRedirect) $orig = $url;
+                                       unset($this->redirectQueue[$orig]);
+                                       $this->debug("...$url");
+                                       if (!$isRedirect && isset($this->requests[$url])) {
+                                               $this->debug("......in memory");
+                                       /*
+                                       } elseif ($this->isCached($url)) {
+                                               $this->debug("......is cached");
+                                               if (!$this->minimiseMemoryUse) {
+                                                       $this->requests[$url] = $this->getCached($url);
+                                               }
+                                       */
+                                       } else {
+                                               $this->debug("......adding to pool");
+                                               $req_url = $this->rewriteUrls($url);
+                                               $req_url = ($this->rewriteHashbangFragment) ? $this->rewriteHashbangFragment($req_url) : $req_url;
+                                               $req_url = $this->removeFragment($req_url);
+                                               if (!empty($this->headerOnlyTypes) && !isset($this->requests[$orig]['wrongGuess']) && $this->possibleUnsupportedType($req_url)) {
+                                                       $_meth = 'HEAD';
+                                               } else {
+                                                       $_meth = 'GET';
+                                                       unset($this->requests[$orig]['wrongGuess']);
+                                               }                                               
+                                               $headers = array();
+                                               //$headers[] = 'User-Agent: '.$this->userAgent;
+                                               $headers[] = $this->getUserAgent($req_url);
+                                               // add referer for picky sites
+                                               $headers[] = 'Referer: '.$this->referer;
+                                               // send cookies, if we have any
+                                               if ($cookies = $this->cookieJar->getMatchingCookies($req_url)) {
+                                                       $this->debug("......sending cookies: $cookies");
+                                                       $headers[] = 'Cookie: '.$cookies;
+                                               }
+                                               $httpRequest = new RollingCurlRequest($req_url, $_meth, null, $headers, array(
+                                                       CURLOPT_CONNECTTIMEOUT => $this->requestOptions['timeout'],
+                                                       CURLOPT_TIMEOUT => $this->requestOptions['timeout']
+                                                       ));
+                                               $httpRequest->set_original_url($orig);
+                                               $this->requests[$orig] = array('headers'=>null, 'body'=>null, 'httpRequest'=>$httpRequest);
+                                               $this->requests[$orig]['original_url'] = $orig; // TODO: is this needed anymore?
+                                               $pool->add($httpRequest);
+                                       }
+                               }
+                               // did we get anything into the pool?
+                               if (count($pool) > 0) {
+                                       $this->debug('Sending request...');
+                                       $pool->execute(); // this will call handleCurlResponse() and populate $this->requests[$orig]
+                                       $this->debug('Received responses');
+                                       foreach($subset as $orig => $url) {
+                                               if (!$isRedirect) $orig = $url;
+                                               // $this->requests[$orig]['headers']
+                                               // $this->requests[$orig]['body']
+                                               // $this->requests[$orig]['effective_url']
+                                               // check content type
+                                               if ($this->headerOnlyType($this->requests[$orig]['headers'])) {
+                                                       $this->requests[$orig]['body'] = '';
+                                                       $_header_only_type = true;
+                                                       $this->debug('Header only type returned');
+                                               } else {
+                                                       $_header_only_type = false;
+                                               }
+                                               $status_code = $this->requests[$orig]['status_code'];
+                                               if ((in_array($status_code, array(300, 301, 302, 303, 307)) || $status_code > 307 && $status_code < 400) && isset($this->requests[$orig]['location'])) {
+                                                       $redirectURL = $this->requests[$orig]['location'];
+                                                       if (!preg_match('!^https?://!i', $redirectURL)) {
+                                                               $redirectURL = SimplePie_Misc::absolutize_url($redirectURL, $url);
+                                                       }
+                                                       if ($this->validateURL($redirectURL)) {
+                                                               $this->debug('Redirect detected. Valid URL: '.$redirectURL);
+                                                               // store any cookies
+                                                               $cookies = $this->cookieJar->extractCookies($this->requests[$orig]['headers']);
+                                                               if (!empty($cookies)) $this->cookieJar->storeCookies($url, $cookies);                                                   
+                                                               $this->redirectQueue[$orig] = $redirectURL;
+                                                       } else {
+                                                               $this->debug('Redirect detected. Invalid URL: '.$redirectURL);
+                                                       }
+                                               } elseif (!$_header_only_type && $this->requests[$orig]['method'] == 'HEAD') {
+                                                       // the response content-type did not match our 'header only' types, 
+                                                       // but we'd issues a HEAD request because we assumed it would. So
+                                                       // let's queue a proper GET request for this item...
+                                                       $this->debug('Wrong guess at content-type, queing GET request');
+                                                       $this->requests[$orig]['wrongGuess'] = true;
+                                                       $this->redirectQueue[$orig] = $this->requests[$orig]['effective_url'];
+                                               } elseif (strpos($this->requests[$orig]['effective_url'], '_escaped_fragment_') === false) {
+                                                       // check for <meta name='fragment' content='!'/>
+                                                       // for AJAX sites, e.g. Blogger with its dynamic views templates.
+                                                       // Based on Google's spec: https://developers.google.com/webmasters/ajax-crawling/docs/specification
+                                                       if (isset($this->requests[$orig]['body'])) {
+                                                               $redirectURL = $this->getRedirectURLfromHTML($this->requests[$orig]['effective_url'], substr($this->requests[$orig]['body'], 0, 4000));
+                                                               if ($redirectURL) {
+                                                                       $this->redirectQueue[$orig] = $redirectURL;
+                                                               }
+                                                       }
+                                               }
+                                               // die($url.' -multi- '.$request->getResponseInfo('effective_url'));
+                                               unset($this->requests[$orig]['httpRequest'], $this->requests[$orig]['method']);
+                                       }
+                               }
+                       }
+               }
+
+               //////////////////////////////////////////////////////
+               // sequential (file_get_contents)
+               else {
+                       $this->debug('Starting sequential fetch (file_get_contents)');
+                       $this->debug('Processing set of '.count($urls));
+                       foreach ($urls as $orig => $url) {
+                               if (!$isRedirect) $orig = $url;
+                               unset($this->redirectQueue[$orig]);
+                               $this->debug("...$url");
+                               if (!$isRedirect && isset($this->requests[$url])) {
+                                       $this->debug("......in memory");
+                               /*
+                               } elseif ($this->isCached($url)) {
+                                       $this->debug("......is cached");
+                                       if (!$this->minimiseMemoryUse) {
+                                               $this->requests[$url] = $this->getCached($url);
+                                       }
+                               */
+                               } else {
+                                       $this->debug("Sending request for $url");
+                                       $this->requests[$orig]['original_url'] = $orig;
+                                       $req_url = $this->rewriteUrls($url);
+                                       $req_url = ($this->rewriteHashbangFragment) ? $this->rewriteHashbangFragment($req_url) : $req_url;
+                                       $req_url = $this->removeFragment($req_url);
+                                       // send cookies, if we have any
+                                       $httpContext = $this->httpContext;
+                                       $httpContext['http']['header'] .= $this->getUserAgent($req_url)."\r\n";
+                                       // add referer for picky sites
+                                       $httpContext['http']['header'] .= 'Referer: '.$this->referer."\r\n";
+                                       if ($cookies = $this->cookieJar->getMatchingCookies($req_url)) {
+                                               $this->debug("......sending cookies: $cookies");
+                                               $httpContext['http']['header'] .= 'Cookie: '.$cookies."\r\n";
+                                       }
+                                       if (false !== ($html = @file_get_contents($req_url, false, stream_context_create($httpContext)))) {
+                                               $this->debug('Received response');
+                                               // get status code
+                                               if (!isset($http_response_header[0]) || !preg_match('!^HTTP/\d+\.\d+\s+(\d+)!', trim($http_response_header[0]), $match)) {
+                                                       $this->debug('Error: no status code found');
+                                                       // TODO: handle error - no status code
+                                               } else {
+                                                       $this->requests[$orig]['headers'] = $this->headersToString($http_response_header, false);
+                                                       // check content type
+                                                       if ($this->headerOnlyType($this->requests[$orig]['headers'])) {
+                                                               $this->requests[$orig]['body'] = '';
+                                                       } else {
+                                                               $this->requests[$orig]['body'] = $html;
+                                                       }
+                                                       $this->requests[$orig]['effective_url'] = $req_url;
+                                                       $this->requests[$orig]['status_code'] = $status_code = (int)$match[1];
+                                                       unset($match);
+                                                       // handle redirect
+                                                       if (preg_match('/^Location:(.*?)$/mi', $this->requests[$orig]['headers'], $match)) {
+                                                               $this->requests[$orig]['location'] =  trim($match[1]);
+                                                       }
+                                                       if ((in_array($status_code, array(300, 301, 302, 303, 307)) || $status_code > 307 && $status_code < 400) && isset($this->requests[$orig]['location'])) {
+                                                               $redirectURL = $this->requests[$orig]['location'];
+                                                               if (!preg_match('!^https?://!i', $redirectURL)) {
+                                                                       $redirectURL = SimplePie_Misc::absolutize_url($redirectURL, $url);
+                                                               }
+                                                               if ($this->validateURL($redirectURL)) {
+                                                                       $this->debug('Redirect detected. Valid URL: '.$redirectURL);
+                                                                       // store any cookies
+                                                                       $cookies = $this->cookieJar->extractCookies($this->requests[$orig]['headers']);
+                                                                       if (!empty($cookies)) $this->cookieJar->storeCookies($url, $cookies);
+                                                                       $this->redirectQueue[$orig] = $redirectURL;
+                                                               } else {
+                                                                       $this->debug('Redirect detected. Invalid URL: '.$redirectURL);
+                                                               }
+                                                       } elseif (strpos($this->requests[$orig]['effective_url'], '_escaped_fragment_') === false) {
+                                                               // check for <meta name='fragment' content='!'/>
+                                                               // for AJAX sites, e.g. Blogger with its dynamic views templates.
+                                                               // Based on Google's spec: https://developers.google.com/webmasters/ajax-crawling/docs/specification
+                                                               if (isset($this->requests[$orig]['body'])) {
+                                                                       $redirectURL = $this->getRedirectURLfromHTML($this->requests[$orig]['effective_url'], substr($this->requests[$orig]['body'], 0, 4000));
+                                                                       if ($redirectURL) {
+                                                                               $this->redirectQueue[$orig] = $redirectURL;
+                                                                       }
+                                                               }
+                                                       }
+                                               }
+                                       } else {
+                                               $this->debug('Error retrieving URL');
+                                               //print_r($req_url);
+                                               //print_r($http_response_header);
+                                               //print_r($html);
+                                               
+                                               // TODO: handle error - failed to retrieve URL
+                                       }
+                               }
+                       }
+               }
+       }
+       
+       public function handleCurlResponse($response, $info, $request) {
+               $orig = $request->url_original;
+               $this->requests[$orig]['headers'] = substr($response, 0, $info['header_size']);
+               $this->requests[$orig]['body'] = substr($response, $info['header_size']);
+               $this->requests[$orig]['method'] = $request->method;
+               $this->requests[$orig]['effective_url'] = $info['url'];
+               $this->requests[$orig]['status_code'] = (int)$info['http_code'];
+               if (preg_match('/^Location:(.*?)$/mi', $this->requests[$orig]['headers'], $match)) {
+                       $this->requests[$orig]['location'] =  trim($match[1]);
+               }
+       }
+       
+       protected function headersToString(array $headers, $associative=true) {
+               if (!$associative) {
+                       return implode("\n", $headers);
+               } else {
+                       $str = '';
+                       foreach ($headers as $key => $val) {
+                               if (is_array($val)) {
+                                       foreach ($val as $v) $str .= "$key: $v\n";
+                               } else {
+                                       $str .= "$key: $val\n";
+                               }
+                       }
+                       return rtrim($str);
+               }
+       }
+       
+       public function get($url, $remove=false, $gzdecode=true) {
+               $url = "$url";
+               if (isset($this->requests[$url]) && isset($this->requests[$url]['body'])) {
+                       $this->debug("URL already fetched - in memory ($url, effective: {$this->requests[$url]['effective_url']})");
+                       $response = $this->requests[$url];
+               /*
+               } elseif ($this->isCached($url)) {
+                       $this->debug("URL already fetched - in disk cache ($url)");
+                       $response = $this->getCached($url);
+                       $this->requests[$url] = $response;
+               */
+               } else {
+                       $this->debug("Fetching URL ($url)");
+                       $this->fetchAll(array($url));
+                       if (isset($this->requests[$url]) && isset($this->requests[$url]['body'])) {
+                               $response = $this->requests[$url];
+                       } else {
+                               $this->debug("Request failed");
+                               $response = false;
+                       }
+               }
+               /*
+               if ($this->minimiseMemoryUse && $response) {
+                       $this->cache($url);
+                       unset($this->requests[$url]);
+               }
+               */
+               if ($remove && $response) unset($this->requests[$url]);
+               if ($gzdecode && stripos($response['headers'], 'Content-Encoding: gzip')) {
+                       if ($html = gzdecode($response['body'])) {
+                               $response['body'] = $html;
+                       }
+               }
+               return $response;
+       }
+       
+       public function parallelSupport() {
+               return class_exists('HttpRequestPool') || function_exists('curl_multi_init');
+       }
+       
+       private function headerOnlyType($headers) {
+               if (preg_match('!^Content-Type:\s*(([a-z-]+)/([^;\r\n ]+))!im', $headers, $match)) {
+                       // look for full mime type (e.g. image/jpeg) or just type (e.g. image)
+                       $match[1] = strtolower(trim($match[1]));
+                       $match[2] = strtolower(trim($match[2]));
+                       foreach (array($match[1], $match[2]) as $mime) {
+                               if (in_array($mime, $this->headerOnlyTypes)) return true;
+                       }
+               }
+               return false;
+       }
+       
+       private function possibleUnsupportedType($url) {
+               $path = @parse_url($url, PHP_URL_PATH);
+               if ($path && strpos($path, '.') !== false) {
+                       $ext = strtolower(trim(pathinfo($path, PATHINFO_EXTENSION)));
+                       return in_array($ext, $this->headerOnlyClues);
+               }
+               return false;
+       }
+}
+
+// gzdecode from http://www.php.net/manual/en/function.gzdecode.php#82930
+if (!function_exists('gzdecode')) {
+       function gzdecode($data,&$filename='',&$error='',$maxlength=null) 
+       {
+               $len = strlen($data);
+               if ($len < 18 || strcmp(substr($data,0,2),"\x1f\x8b")) {
+                       $error = "Not in GZIP format.";
+                       return null;  // Not GZIP format (See RFC 1952)
+               }
+               $method = ord(substr($data,2,1));  // Compression method
+               $flags  = ord(substr($data,3,1));  // Flags
+               if ($flags & 31 != $flags) {
+                       $error = "Reserved bits not allowed.";
+                       return null;
+               }
+               // NOTE: $mtime may be negative (PHP integer limitations)
+               $mtime = unpack("V", substr($data,4,4));
+               $mtime = $mtime[1];
+               $xfl   = substr($data,8,1);
+               $os    = substr($data,8,1);
+               $headerlen = 10;
+               $extralen  = 0;
+               $extra     = "";
+               if ($flags & 4) {
+                       // 2-byte length prefixed EXTRA data in header
+                       if ($len - $headerlen - 2 < 8) {
+                               return false;  // invalid
+                       }
+                       $extralen = unpack("v",substr($data,8,2));
+                       $extralen = $extralen[1];
+                       if ($len - $headerlen - 2 - $extralen < 8) {
+                               return false;  // invalid
+                       }
+                       $extra = substr($data,10,$extralen);
+                       $headerlen += 2 + $extralen;
+               }
+               $filenamelen = 0;
+               $filename = "";
+               if ($flags & 8) {
+                       // C-style string
+                       if ($len - $headerlen - 1 < 8) {
+                               return false; // invalid
+                       }
+                       $filenamelen = strpos(substr($data,$headerlen),chr(0));
+                       if ($filenamelen === false || $len - $headerlen - $filenamelen - 1 < 8) {
+                               return false; // invalid
+                       }
+                       $filename = substr($data,$headerlen,$filenamelen);
+                       $headerlen += $filenamelen + 1;
+               }
+               $commentlen = 0;
+               $comment = "";
+               if ($flags & 16) {
+                       // C-style string COMMENT data in header
+                       if ($len - $headerlen - 1 < 8) {
+                               return false;    // invalid
+                       }
+                       $commentlen = strpos(substr($data,$headerlen),chr(0));
+                       if ($commentlen === false || $len - $headerlen - $commentlen - 1 < 8) {
+                               return false;    // Invalid header format
+                       }
+                       $comment = substr($data,$headerlen,$commentlen);
+                       $headerlen += $commentlen + 1;
+               }
+               $headercrc = "";
+               if ($flags & 2) {
+                       // 2-bytes (lowest order) of CRC32 on header present
+                       if ($len - $headerlen - 2 < 8) {
+                               return false;    // invalid
+                       }
+                       $calccrc = crc32(substr($data,0,$headerlen)) & 0xffff;
+                       $headercrc = unpack("v", substr($data,$headerlen,2));
+                       $headercrc = $headercrc[1];
+                       if ($headercrc != $calccrc) {
+                               $error = "Header checksum failed.";
+                               return false;    // Bad header CRC
+                       }
+                       $headerlen += 2;
+               }
+               // GZIP FOOTER
+               $datacrc = unpack("V",substr($data,-8,4));
+               $datacrc = sprintf('%u',$datacrc[1] & 0xFFFFFFFF);
+               $isize = unpack("V",substr($data,-4));
+               $isize = $isize[1];
+               // decompression:
+               $bodylen = $len-$headerlen-8;
+               if ($bodylen < 1) {
+                       // IMPLEMENTATION BUG!
+                       return null;
+               }
+               $body = substr($data,$headerlen,$bodylen);
+               $data = "";
+               if ($bodylen > 0) {
+                       switch ($method) {
+                       case 8:
+                               // Currently the only supported compression method:
+                               $data = gzinflate($body,$maxlength);
+                               break;
+                       default:
+                               $error = "Unknown compression method.";
+                               return false;
+                       }
+               }  // zero-byte body content is allowed
+               // Verifiy CRC32
+               $crc   = sprintf("%u",crc32($data));
+               $crcOK = $crc == $datacrc;
+               $lenOK = $isize == strlen($data);
+               if (!$lenOK || !$crcOK) {
+                       $error = ( $lenOK ? '' : 'Length check FAILED. ') . ( $crcOK ? '' : 'Checksum FAILED.');
+                       return false;
+               }
+               return $data;
+       }
+}
\ No newline at end of file
index ecd46d5f8af37f38f56bdd23d7b23a0a945fd090..c524a1ee11edef33a5424b914cd3423638ce41db 100644 (file)
@@ -1,79 +1,78 @@
-<?php\r
-/**\r
- * Humble HTTP Agent extension for SimplePie_File\r
- * \r
- * This class is designed to extend and override SimplePie_File\r
- * in order to prevent duplicate HTTP requests being sent out.\r
- * The idea is to initialise an instance of Humble HTTP Agent\r
- * and attach it, to a static class variable, of this class.\r
- * SimplePie will then automatically initialise this class\r
- * \r
- * @date 2011-02-28\r
- */\r
-\r
-class SimplePie_HumbleHttpAgent extends SimplePie_File\r
-{\r
-       protected static $agent;\r
-       var $url;\r
-       var $useragent;\r
-       var $success = true;\r
-       var $headers = array();\r
-       var $body;\r
-       var $status_code;\r
-       var $redirects = 0;\r
-       var $error;\r
-       var $method = SIMPLEPIE_FILE_SOURCE_NONE;\r
-\r
-       public static function set_agent(HumbleHttpAgent $agent) {\r
-               self::$agent = $agent;\r
-       }\r
-       \r
-       public function __construct($url, $timeout = 10, $redirects = 5, $headers = null, $useragent = null, $force_fsockopen = false) {\r
-               if (class_exists('idna_convert'))\r
-               {\r
-                       $idn = new idna_convert();\r
-                       $parsed = SimplePie_Misc::parse_url($url);\r
-                       $url = SimplePie_Misc::compress_parse_url($parsed['scheme'], $idn->encode($parsed['authority']), $parsed['path'], $parsed['query'], $parsed['fragment']);\r
-               }\r
-               $this->url = $url;\r
-               $this->useragent = $useragent;\r
-               if (preg_match('/^http(s)?:\/\//i', $url))\r
-               {\r
-                       if (!is_array($headers))\r
-                       {\r
-                               $headers = array();\r
-                       }\r
-                       $this->method = SIMPLEPIE_FILE_SOURCE_REMOTE | SIMPLEPIE_FILE_SOURCE_CURL;\r
-                       $headers2 = array();\r
-                       foreach ($headers as $key => $value) {\r
-                               $headers2[] = "$key: $value";\r
-                       }\r
-                       //TODO: allow for HTTP headers\r
-                       // curl_setopt($fp, CURLOPT_HTTPHEADER, $headers2);\r
-\r
-                       $response = self::$agent->get($url);\r
-                       \r
-                       if ($response === false || !isset($response['status_code'])) {\r
-                               $this->error = 'failed to fetch URL';\r
-                               $this->success = false;\r
-                       } else {\r
-                               // The extra lines at the end are there to satisfy SimplePie's HTTP parser.\r
-                               // The class expects a full HTTP message, whereas we're giving it only\r
-                               // headers - the new lines indicate the start of the body.\r
-                               $parser = new SimplePie_HTTP_Parser($response['headers']."\r\n\r\n");\r
-                               if ($parser->parse()) {\r
-                                       $this->headers = $parser->headers;\r
-                                       //$this->body = $parser->body;\r
-                                       $this->body = $response['body'];\r
-                                       $this->status_code = $parser->status_code;\r
-                               }\r
-                       }\r
-               }\r
-               else\r
-               {\r
-                       $this->error = 'invalid URL';\r
-                       $this->success = false;\r
-               }\r
-       }\r
-}\r
-?>
\ No newline at end of file
+<?php
+/**
+ * Humble HTTP Agent extension for SimplePie_File
+ * 
+ * This class is designed to extend and override SimplePie_File
+ * in order to prevent duplicate HTTP requests being sent out.
+ * The idea is to initialise an instance of Humble HTTP Agent
+ * and attach it, to a static class variable, of this class.
+ * SimplePie will then automatically initialise this class
+ * 
+ * @date 2011-02-28
+ */
+
+class SimplePie_HumbleHttpAgent extends SimplePie_File
+{
+       protected static $agent;
+       var $url;
+       var $useragent;
+       var $success = true;
+       var $headers = array();
+       var $body;
+       var $status_code;
+       var $redirects = 0;
+       var $error;
+       var $method = SIMPLEPIE_FILE_SOURCE_NONE;
+
+       public static function set_agent(HumbleHttpAgent $agent) {
+               self::$agent = $agent;
+       }
+       
+       public function __construct($url, $timeout = 10, $redirects = 5, $headers = null, $useragent = null, $force_fsockopen = false) {
+               if (class_exists('idna_convert'))
+               {
+                       $idn = new idna_convert();
+                       $parsed = SimplePie_Misc::parse_url($url);
+                       $url = SimplePie_Misc::compress_parse_url($parsed['scheme'], $idn->encode($parsed['authority']), $parsed['path'], $parsed['query'], $parsed['fragment']);
+               }
+               $this->url = $url;
+               $this->useragent = $useragent;
+               if (preg_match('/^http(s)?:\/\//i', $url))
+               {
+                       if (!is_array($headers))
+                       {
+                               $headers = array();
+                       }
+                       $this->method = SIMPLEPIE_FILE_SOURCE_REMOTE | SIMPLEPIE_FILE_SOURCE_CURL;
+                       $headers2 = array();
+                       foreach ($headers as $key => $value) {
+                               $headers2[] = "$key: $value";
+                       }
+                       //TODO: allow for HTTP headers
+                       // curl_setopt($fp, CURLOPT_HTTPHEADER, $headers2);
+
+                       $response = self::$agent->get($url);
+                       
+                       if ($response === false || !isset($response['status_code'])) {
+                               $this->error = 'failed to fetch URL';
+                               $this->success = false;
+                       } else {
+                               // The extra lines at the end are there to satisfy SimplePie's HTTP parser.
+                               // The class expects a full HTTP message, whereas we're giving it only
+                               // headers - the new lines indicate the start of the body.
+                               $parser = new SimplePie_HTTP_Parser($response['headers']."\r\n\r\n");
+                               if ($parser->parse()) {
+                                       $this->headers = $parser->headers;
+                                       //$this->body = $parser->body;
+                                       $this->body = $response['body'];
+                                       $this->status_code = $parser->status_code;
+                               }
+                       }
+               }
+               else
+               {
+                       $this->error = 'invalid URL';
+                       $this->success = false;
+               }
+       }
+}
\ No newline at end of file
index 09b115467121eb3e2ad79d022772a1290118b92e..382d869c4432fdff55b2315796b2fb636f95726c 100644 (file)
@@ -6,23 +6,24 @@
  * Attempts to detect the language of a sample of text by correlating ranked
  * 3-gram frequencies to a table of 3-gram frequencies of known languages.
  *
- * Implements a version of a technique originally proposed by Cavnar & Trenkle 
- * (1994): "N-Gram-Based Text Categorization" 
+ * Implements a version of a technique originally proposed by Cavnar & Trenkle
+ * (1994): "N-Gram-Based Text Categorization"
  *
- * PHP versions 4 and 5
+ * PHP version 5
  *
- * @category   Text
- * @package    Text_LanguageDetect
- * @author     Nicholas Pisarro <infinityminusnine+pear@gmail.com>
- * @copyright  2005-2006 Nicholas Pisarro
- * @license    http://www.debian.org/misc/bsd.license BSD
- * @version    CVS: $Id: LanguageDetect.php,v 1.20 2008/07/01 02:09:15 taak Exp $
- * @link       http://pear.php.net/package/Text_LanguageDetect/
- * @link       http://langdetect.blogspot.com/
+ * @category  Text
+ * @package   Text_LanguageDetect
+ * @author    Nicholas Pisarro <infinityminusnine+pear@gmail.com>
+ * @copyright 2005-2006 Nicholas Pisarro
+ * @license   http://www.debian.org/misc/bsd.license BSD
+ * @version   SVN: $Id: LanguageDetect.php 322353 2012-01-16 08:41:43Z cweiske $
+ * @link      http://pear.php.net/package/Text_LanguageDetect/
+ * @link      http://langdetect.blogspot.com/
  */
 
-//require_once 'PEAR.php';
-require_once 'Parser.php';
+require_once 'LanguageDetect/Exception.php';
+require_once 'LanguageDetect/Parser.php';
+require_once 'LanguageDetect/ISO639.php';
 
 /**
  * Language detection class
@@ -41,9 +42,10 @@ require_once 'Parser.php';
  *
  * echo "Supported languages:\n";
  *
- * $langs = $l->getLanguages();
- * if (PEAR::isError($langs)) {
- *     die($langs->getMessage());
+ * try {
+ *     $langs = $l->getLanguages();
+ * } catch (Text_LanguageDetect_Exception $e) {
+ *     die($e->getMessage());
  * }
  *
  * sort($langs);
@@ -54,38 +56,38 @@ require_once 'Parser.php';
  * }
  * </code>
  *
- * @category   Text
- * @package    Text_LanguageDetect
- * @author     Nicholas Pisarro <infinityminusnine+pear@gmail.com>
- * @copyright  2005 Nicholas Pisarro
- * @license    http://www.debian.org/misc/bsd.license BSD
- * @version    Release: @package_version@
- * @todo       allow users to generate their own language models
+ * @category  Text
+ * @package   Text_LanguageDetect
+ * @author    Nicholas Pisarro <infinityminusnine+pear@gmail.com>
+ * @copyright 2005 Nicholas Pisarro
+ * @license   http://www.debian.org/misc/bsd.license BSD
+ * @version   Release: @package_version@
+ * @link      http://pear.php.net/package/Text_LanguageDetect/
+ * @todo      allow users to generate their own language models
  */
 class Text_LanguageDetect
 {
-    /** 
+    /**
      * The filename that stores the trigram data for the detector
      *
-     * If this value starts with a slash (/) or a dot (.) the value of 
+     * If this value starts with a slash (/) or a dot (.) the value of
      * $this->_data_dir will be ignored
-     * 
+     *
      * @var      string
      * @access   private
      */
-    var $_db_filename = './lang.dat';
+    var $_db_filename = 'lang.dat';
 
     /**
      * The filename that stores the unicode block definitions
      *
-     * If this value starts with a slash (/) or a dot (.) the value of 
+     * If this value starts with a slash (/) or a dot (.) the value of
      * $this->_data_dir will be ignored
-     * 
+     *
      * @var string
      * @access private
      */
-    var $_unicode_db_filename = './unicode_blocks.dat';
+    var $_unicode_db_filename = 'unicode_blocks.dat';
 
     /**
      * The data directory
@@ -99,11 +101,8 @@ class Text_LanguageDetect
 
     /**
      * The trigram data for comparison
-     * 
-     * Will be loaded on start from $this->_db_filename
      *
-     * May be set to a PEAR_Error object if there is an error during its 
-     * initialization
+     * Will be loaded on start from $this->_db_filename
      *
      * @var      array
      * @access   private
@@ -120,7 +119,7 @@ class Text_LanguageDetect
 
     /**
      * The size of the trigram data arrays
-     * 
+     *
      * @var      int
      * @access   private
      */
@@ -140,7 +139,7 @@ class Text_LanguageDetect
 
     /**
      * Whether or not to simulate perl's Language::Guess exactly
-     * 
+     *
      * @access  private
      * @var     bool
      * @see     setPerlCompatible()
@@ -164,19 +163,25 @@ class Text_LanguageDetect
      */
     var $_clusters;
 
+    /**
+     * Which type of "language names" are accepted and returned:
+     *
+     * 0 - language name ("english")
+     * 2 - 2-letter ISO 639-1 code ("en")
+     * 3 - 3-letter ISO 639-2 code ("eng")
+     */
+    var $_name_mode = 0;
+
     /**
      * Constructor
      *
      * Will attempt to load the language database. If it fails, you will get
-     * a PEAR_Error object returned when you try to use detect()
-     *
+     * an exception.
      */
-    function Text_LanguageDetect($db=null, $unicode_db=null)
+    function __construct()
     {
-               if (isset($db)) $this->_db_filename = $db;
-               if (isset($unicode_db)) $this->_unicode_db_filename = $unicode_db;
-               
         $data = $this->_readdb($this->_db_filename);
+        $this->_checkTrigram($data['trigram']);
         $this->_lang_db = $data['trigram'];
 
         if (isset($data['trigram-unicodemap'])) {
@@ -186,29 +191,32 @@ class Text_LanguageDetect
         // Not yet implemented:
         if (isset($data['trigram-clusters'])) {
             $this->_clusters = $data['trigram-clusters'];
-        }              
+        }
     }
 
     /**
      * Returns the path to the location of the database
      *
-     * @access    private
-     * @return    string    expected path to the language model database
+     * @param string $fname File name to load
+     *
+     * @return string expected path to the language model database
+     * @access private
      */
     function _get_data_loc($fname)
     {
-        return $fname;
+        return dirname(__FILE__).'/'.$fname;
     }
 
     /**
      * Loads the language trigram database from filename
      *
      * Trigram datbase should be a serialize()'d array
-     * 
-     * @access    private
-     * @param     string      $fname   the filename where the data is stored
-     * @return    array                the language model data
-     * @throws    PEAR_Error
+     *
+     * @param string $fname the filename where the data is stored
+     *
+     * @return array the language model data
+     * @throws Text_LanguageDetect_Exception
+     * @access private
      */
     function _readdb($fname)
     {
@@ -217,79 +225,74 @@ class Text_LanguageDetect
 
         // input check
         if (!file_exists($fname)) {
-            throw new Exception('Language database does not exist.');
+            throw new Text_LanguageDetect_Exception(
+                'Language database does not exist: ' . $fname,
+                Text_LanguageDetect_Exception::DB_NOT_FOUND
+            );
         } elseif (!is_readable($fname)) {
-            throw new Exception('Language database is not readable.');
+            throw new Text_LanguageDetect_Exception(
+                'Language database is not readable: ' . $fname,
+                Text_LanguageDetect_Exception::DB_NOT_READABLE
+            );
         }
 
-        if (function_exists('file_get_contents')) {
-            return unserialize(file_get_contents($fname));
-        } else {
-            // if you don't have file_get_contents(), 
-            // then this is the next fastest way
-            ob_start();
-            readfile($fname);
-            $contents = ob_get_contents();
-            ob_end_clean();
-            return unserialize($contents);
-        }
+        return unserialize(file_get_contents($fname));
     }
 
 
     /**
      * Checks if this object is ready to detect languages
-     * 
-     * @access   private
-     * @param    mixed   &$err  error object to be returned by reference, if any
-     * @return   bool           true if no errors
+     *
+     * @param array $trigram Trigram data from database
+     *
+     * @return void
+     * @access private
      */
-    function _setup_ok(&$err)
+    function _checkTrigram($trigram)
     {
-        if (!is_array($this->_lang_db)) {
+        if (!is_array($trigram)) {
             if (ini_get('magic_quotes_runtime')) {
-                throw new Exception('Error loading database. Try turning magic_quotes_runtime off.');
-            } else {
-                throw new Exception('Language database is not an array.');
+                throw new Text_LanguageDetect_Exception(
+                    'Error loading database. Try turning magic_quotes_runtime off.',
+                    Text_LanguageDetect_Exception::MAGIC_QUOTES
+                );
             }
-            return false;
-
-        } elseif (empty($this->_lang_db)) {
-            throw new Exception('Language database has no elements.');
-            return false;
-
-        } else {
-            return true;
+            throw new Text_LanguageDetect_Exception(
+                'Language database is not an array.',
+                Text_LanguageDetect_Exception::DB_NOT_ARRAY
+            );
+        } elseif (empty($trigram)) {
+            throw new Text_LanguageDetect_Exception(
+                'Language database has no elements.',
+                Text_LanguageDetect_Exception::DB_EMPTY
+            );
         }
     }
 
     /**
      * Omits languages
      *
-     * Pass this function the name of or an array of names of 
+     * Pass this function the name of or an array of names of
      * languages that you don't want considered
      *
-     * If you're only expecting a limited set of languages, this can greatly 
+     * If you're only expecting a limited set of languages, this can greatly
      * speed up processing
      *
-     * @access   public
-     * @param    mixed  $omit_list      language name or array of names to omit
-     * @param    bool   $include_only   if true will include (rather than 
-     *                                  exclude) only those in the list
-     * @return   int                    number of languages successfully deleted
-     * @throws   PEAR_Error
+     * @param mixed $omit_list    language name or array of names to omit
+     * @param bool  $include_only if true will include (rather than
+     *                            exclude) only those in the list
+     *
+     * @return int number of languages successfully deleted
+     * @throws Text_LanguageDetect_Exception
      */
-    function omitLanguages($omit_list, $include_only = false)
+    public function omitLanguages($omit_list, $include_only = false)
     {
-
-        // setup check
-        if (!$this->_setup_ok($err)) {
-            return $err;
-        }
-
         $deleted = 0;
 
-        // deleting the given languages
+        $omit_list = $this->_convertFromNameMode($omit_list);
+
         if (!$include_only) {
+            // deleting the given languages
             if (!is_array($omit_list)) {
                 $omit_list = strtolower($omit_list); // case desensitize
                 if (isset($this->_lang_db[$omit_list])) {
@@ -301,12 +304,12 @@ class Text_LanguageDetect
                     if (isset($this->_lang_db[$omit_lang])) {
                         unset($this->_lang_db[$omit_lang]);
                         $deleted++;
-                    } 
+                    }
                 }
             }
 
-        // deleting all except the given languages
         } else {
+            // deleting all except the given languages
             if (!is_array($omit_list)) {
                 $omit_list = array($omit_list);
             }
@@ -327,7 +330,7 @@ class Text_LanguageDetect
         // reset the cluster cache if the number of languages changes
         // this will then have to be recalculated
         if (isset($this->_clusters) && $deleted > 0) {
-            unset($this->_clusters);
+            $this->_clusters = null;
         }
 
         return $deleted;
@@ -339,49 +342,40 @@ class Text_LanguageDetect
      *
      * @access public
      * @return int            the number of languages
-     * @throws PEAR_Error
+     * @throws   Text_LanguageDetect_Exception
      */
     function getLanguageCount()
     {
-        if (!$this->_setup_ok($err)) {
-            return $err;
-        } else {
-            return count($this->_lang_db);
-        }
+        return count($this->_lang_db);
     }
 
     /**
-     * Returns true if a given language exists
+     * Checks if the language with the given name exists in the database
      *
-     * If passed an array of names, will return true only if all exist
+     * @param mixed $lang Language name or array of language names
      *
-     * @access    public
-     * @param     mixed       $lang    language name or array of language names
-     * @return    bool                 true if language model exists
-     * @throws    PEAR_Error
+     * @return bool true if language model exists
      */
-    function languageExists($lang)
+    public function languageExists($lang)
     {
-        if (!$this->_setup_ok($err)) {
-            return $err;
-        } else {
-            // string
-            if (is_string($lang)) {
-                return isset($this->_lang_db[strtolower($lang)]);
-
-            // array
-            } elseif (is_array($lang)) {
-                foreach ($lang as $test_lang) {
-                    if (!isset($this->_lang_db[strtolower($test_lang)])) {
-                        return false;
-                    } 
-                }
-                return true;
+        $lang = $this->_convertFromNameMode($lang);
 
-            // other (error)
-            } else {
-                throw new Exception('Unknown type passed to languageExists()');
+        if (is_string($lang)) {
+            return isset($this->_lang_db[strtolower($lang)]);
+
+        } elseif (is_array($lang)) {
+            foreach ($lang as $test_lang) {
+                if (!isset($this->_lang_db[strtolower($test_lang)])) {
+                    return false;
+                }
             }
+            return true;
+
+        } else {
+            throw new Text_LanguageDetect_Exception(
+                'Unsupported parameter type passed to languageExists()',
+                Text_LanguageDetect_Exception::PARAM_TYPE
+            );
         }
     }
 
@@ -389,25 +383,24 @@ class Text_LanguageDetect
      * Returns the list of detectable languages
      *
      * @access public
-     * @return array        the names of the languages known to this object
-     * @throws PEAR_Error
+     * @return array        the names of the languages known to this object<<<<<<<
+     * @throws   Text_LanguageDetect_Exception
      */
     function getLanguages()
     {
-        if (!$this->_setup_ok($err)) {
-            return $err;
-        } else {
-            return array_keys($this->_lang_db);
-        }
+        return $this->_convertToNameMode(
+            array_keys($this->_lang_db)
+        );
     }
 
     /**
      * Make this object behave like Language::Guess
-     * 
-     * @access    public
-     * @param     bool     $setting     false to turn off perl compatibility
+     *
+     * @param bool $setting false to turn off perl compatibility
+     *
+     * @return void
      */
-    function setPerlCompatible($setting = true)
+    public function setPerlCompatible($setting = true)
     {
         if (is_bool($setting)) { // input check
             $this->_perl_compatible = $setting;
@@ -421,6 +414,21 @@ class Text_LanguageDetect
 
     }
 
+    /**
+     * Sets the way how language names are accepted and returned.
+     *
+     * @param integer $name_mode One of the following modes:
+     *                           0 - language name ("english")
+     *                           2 - 2-letter ISO 639-1 code ("en")
+     *                           3 - 3-letter ISO 639-2 code ("eng")
+     *
+     * @return void
+     */
+    function setNameMode($name_mode)
+    {
+        $this->_name_mode = $name_mode;
+    }
+
     /**
      * Whether to use unicode block ranges in detection
      *
@@ -429,10 +437,11 @@ class Text_LanguageDetect
      * in languages that use latin scripts. In other cases it should speed up
      * detection noticeably.
      *
-     * @access  public
-     * @param   bool    $setting    false to turn off
+     * @param bool $setting false to turn off
+     *
+     * @return void
      */
-    function useUnicodeBlocks($setting = true)
+    public function useUnicodeBlocks($setting = true)
     {
         if (is_bool($setting)) {
             $this->_use_unicode_narrowing = $setting;
@@ -442,15 +451,15 @@ class Text_LanguageDetect
     /**
      * Converts a piece of text into trigrams
      *
-     * Superceded by the Text_LanguageDetect_Parser class 
+     * @param string $text text to convert
      *
-     * @access    private
-     * @param     string    $text    text to convert
-     * @return    array              array of trigram frequencies
+     * @return     array array of trigram frequencies
+     * @access     private
+     * @deprecated Superceded by the Text_LanguageDetect_Parser class
      */
     function _trigram($text)
     {
-        $s = new Text_LanguageDetect_Parser($text, $this->_db_filename, $this->_unicode_db_filename);
+        $s = new Text_LanguageDetect_Parser($text);
         $s->prepareTrigram();
         $s->prepareUnicode(false);
         $s->setPadStart(!$this->_perl_compatible);
@@ -463,11 +472,12 @@ class Text_LanguageDetect
      *
      * Thresholds (cuts off) the list at $this->_threshold
      *
-     * @access    protected
-     * @param     array     $arr     array of trgram 
-     * @return    array              ranks of trigrams
+     * @param array $arr array of trigram
+     *
+     * @return array ranks of trigrams
+     * @access protected
      */
-    function _arr_rank(&$arr)
+    function _arr_rank($arr)
     {
 
         // sorts alphabetically first as a standard way of breaking rank ties
@@ -494,14 +504,17 @@ class Text_LanguageDetect
 
     /**
      * Sorts an array by value breaking ties alphabetically
-     * 
-     * @access   private
-     * @param    array     &$arr     the array to sort
+     *
+     * @param array &$arr the array to sort
+     *
+     * @return void
+     * @access private
      */
     function _bub_sort(&$arr)
     {
         // should do the same as this perl statement:
-        // sort { $trigrams{$b} == $trigrams{$a} ?  $a cmp $b : $trigrams{$b} <=> $trigrams{$a} }
+        // sort { $trigrams{$b} == $trigrams{$a}
+        //   ?  $a cmp $b : $trigrams{$b} <=> $trigrams{$a} }
 
         // needs to sort by both key and value at once
         // using the key to break ties for the value
@@ -528,13 +541,14 @@ class Text_LanguageDetect
     /**
      * Sort function used by bubble sort
      *
-     * Callback function for usort(). 
+     * Callback function for usort().
      *
-     * @access   private
-     * @param    array        first param passed by usort()
-     * @param    array        second param passed by usort()
-     * @return   int          1 if $a is greater, -1 if not
-     * @see      _bub_sort()
+     * @param array $a first param passed by usort()
+     * @param array $b second param passed by usort()
+     *
+     * @return int 1 if $a is greater, -1 if not
+     * @see    _bub_sort()
+     * @access private
      */
     function _sort_func($a, $b)
     {
@@ -542,12 +556,12 @@ class Text_LanguageDetect
         list($a_key, $a_value) = $a;
         list($b_key, $b_value) = $b;
 
-        // if the values are the same, break ties using the key
         if ($a_value == $b_value) {
+            // if the values are the same, break ties using the key
             return strcmp($a_key, $b_key);
 
-        // if not, just sort normally
         } else {
+            // if not, just sort normally
             if ($a_value > $b_value) {
                 return -1;
             } else {
@@ -559,23 +573,24 @@ class Text_LanguageDetect
     }
 
     /**
-     * Calculates a linear rank-order distance statistic between two sets of 
+     * Calculates a linear rank-order distance statistic between two sets of
      * ranked trigrams
      *
-     * Sums the differences in rank for each trigram. If the trigram does not 
+     * Sums the differences in rank for each trigram. If the trigram does not
      * appear in both, consider it a difference of $this->_threshold.
      *
      * This distance measure was proposed by Cavnar & Trenkle (1994). Despite
      * its simplicity it has been shown to be highly accurate for language
      * identification tasks.
      *
-     * @access  private
-     * @param   array    $arr1  the reference set of trigram ranks
-     * @param   array    $arr2  the target set of trigram ranks
-     * @return  int             the sum of the differences between the ranks of
-     *                          the two trigram sets
+     * @param array $arr1 the reference set of trigram ranks
+     * @param array $arr2 the target set of trigram ranks
+     *
+     * @return int the sum of the differences between the ranks of
+     *             the two trigram sets
+     * @access private
      */
-    function _distance(&$arr1, &$arr2)
+    function _distance($arr1, $arr2)
     {
         $sumdist = 0;
 
@@ -598,14 +613,15 @@ class Text_LanguageDetect
 
     /**
      * Normalizes the score returned by _distance()
-     * 
+     *
      * Different if perl compatible or not
      *
-     * @access    private
-     * @param     int    $score          the score from _distance()
-     * @param     int    $base_count     the number of trigrams being considered
-     * @return    float                  the normalized score
-     * @see       _distance()
+     * @param int $score      the score from _distance()
+     * @param int $base_count the number of trigrams being considered
+     *
+     * @return float the normalized score
+     * @see    _distance()
+     * @access private
      */
     function _normalize_score($score, $base_count = null)
     {
@@ -630,29 +646,24 @@ class Text_LanguageDetect
      *
      * If perl compatible, the score is 300-0, 0 being most similar.
      * Otherwise, it's 0-1 with 1 being most similar.
-     * 
+     *
      * The $sample text should be at least a few sentences in length;
      * should be ascii-7 or utf8 encoded, if another and the mbstring extension
      * is present it will try to detect and convert. However, experience has
-     * shown that mb_detect_encoding() *does not work very well* with at least 
+     * shown that mb_detect_encoding() *does not work very well* with at least
      * some types of encoding.
      *
-     * @access  public
-     * @param   string  $sample a sample of text to compare.
-     * @param   int     $limit  if specified, return an array of the most likely
-     *                           $limit languages and their scores.
-     * @return  mixed       sorted array of language scores, blank array if no 
-     *                      useable text was found, or PEAR_Error if error 
-     *                      with the object setup
-     * @see     _distance()
-     * @throws  PEAR_Error
+     * @param string $sample a sample of text to compare.
+     * @param int    $limit  if specified, return an array of the most likely
+     *                       $limit languages and their scores.
+     *
+     * @return mixed sorted array of language scores, blank array if no
+     *               useable text was found
+     * @see    _distance()
+     * @throws Text_LanguageDetect_Exception
      */
-    function detect($sample, $limit = 0)
+    public function detect($sample, $limit = 0)
     {
-        if (!$this->_setup_ok($err)) {
-            return $err;
-        }
-
         // input check
         if (!Text_LanguageDetect_Parser::validateString($sample)) {
             return array();
@@ -660,36 +671,27 @@ class Text_LanguageDetect
 
         // check char encoding
         // (only if mbstring extension is compiled and PHP > 4.0.6)
-        if (function_exists('mb_detect_encoding') 
-            && function_exists('mb_convert_encoding')) {
-
+        if (function_exists('mb_detect_encoding')
+            && function_exists('mb_convert_encoding')
+        ) {
             // mb_detect_encoding isn't very reliable, to say the least
-            // detection should still work with a sufficient sample of ascii characters
+            // detection should still work with a sufficient sample
+            //  of ascii characters
             $encoding = mb_detect_encoding($sample);
 
             // mb_detect_encoding() will return FALSE if detection fails
             // don't attempt conversion if that's the case
-            if ($encoding != 'ASCII' && $encoding != 'UTF-8' && $encoding !== false) {
-            
-                if (function_exists('mb_list_encodings')) {
-                    // verify the encoding exists in mb_list_encodings
-                    if (in_array($encoding, mb_list_encodings())) {
-                        $sample = mb_convert_encoding($sample, 'UTF-8', $encoding);
-                    }
-
-                    // if the previous condition failed:
-                    // somehow we detected an encoding that also we don't support
-
-                } else {
-                    // php 4 doesnt have mb_list_encodings()
-                    // so attempt with error suppression
-                    $sample = @mb_convert_encoding($sample, 'UTF-8', $encoding);
+            if ($encoding != 'ASCII' && $encoding != 'UTF-8'
+                && $encoding !== false
+            ) {
+                // verify the encoding exists in mb_list_encodings
+                if (in_array($encoding, mb_list_encodings())) {
+                    $sample = mb_convert_encoding($sample, 'UTF-8', $encoding);
                 }
             }
         }
 
-        $sample_obj = new Text_LanguageDetect_Parser($sample, $this->_db_filename, $this->_unicode_db_filename);
+        $sample_obj = new Text_LanguageDetect_Parser($sample);
         $sample_obj->prepareTrigram();
         if ($this->_use_unicode_narrowing) {
             $sample_obj->prepareUnicode();
@@ -713,7 +715,10 @@ class Text_LanguageDetect
             if (is_array($blocks)) {
                 $present_blocks = array_keys($blocks);
             } else {
-                throw new Exception('Error during block detection');
+                throw new Text_LanguageDetect_Exception(
+                    'Error during block detection',
+                    Text_LanguageDetect_Exception::BLOCK_DETECTION
+                );
             }
 
             $possible_langs = array();
@@ -731,30 +736,30 @@ class Text_LanguageDetect
             }
 
             // could also try an intersect operation rather than a union
-            // in other words, choose languages whose trigrams contain 
+            // in other words, choose languages whose trigrams contain
             // ALL of the unicode blocks found in this sample
             // would improve speed but would be completely thrown off by an
             // unexpected character, like an umlaut appearing in english text
 
             $possible_langs = array_intersect(
-                        array_keys($this->_lang_db),
-                        array_unique($possible_langs)
+                array_keys($this->_lang_db),
+                array_unique($possible_langs)
             );
 
-            // needs to intersect it with the keys of _lang_db in case 
+            // needs to intersect it with the keys of _lang_db in case
             // languages have been omitted
 
-        // or just try 'em all
         } else {
+            // or just try 'em all
             $possible_langs = array_keys($this->_lang_db);
         }
 
 
         foreach ($possible_langs as $lang) {
-            $scores[$lang] =
-                $this->_normalize_score(
-                        $this->_distance($this->_lang_db[$lang], $trigram_freqs),
-                        $trigram_count);
+            $scores[$lang] = $this->_normalize_score(
+                $this->_distance($this->_lang_db[$lang], $trigram_freqs),
+                $trigram_count
+            );
         }
 
         unset($sample_obj);
@@ -772,7 +777,6 @@ class Text_LanguageDetect
             $limited_scores = array();
 
             $i = 0;
-
             foreach ($scores as $key => $value) {
                 if ($i++ >= $limit) {
                     break;
@@ -781,9 +785,9 @@ class Text_LanguageDetect
                 $limited_scores[$key] = $value;
             }
 
-            return $limited_scores;
+            return $this->_convertToNameMode($limited_scores, true);
         } else {
-            return $scores;
+            return $this->_convertToNameMode($scores, true);
         }
     }
 
@@ -791,35 +795,33 @@ class Text_LanguageDetect
      * Returns only the most similar language to the text sample
      *
      * Calls $this->detect() and returns only the top result
-     * 
-     * @access   public
-     * @param    string    $sample    text to detect the language of
-     * @return   string               the name of the most likely language
-     *                                or null if no language is similar
-     * @see      detect()
-     * @throws   PEAR_Error
+     *
+     * @param string $sample text to detect the language of
+     *
+     * @return string the name of the most likely language
+     *                or null if no language is similar
+     * @see    detect()
+     * @throws Text_LanguageDetect_Exception
      */
-    function detectSimple($sample)
+    public function detectSimple($sample)
     {
         $scores = $this->detect($sample, 1);
 
         // if top language has the maximum possible score,
         // then the top score will have been picked at random
-        if (    !is_array($scores) 
-                || empty($scores) 
-                || current($scores) == $this->_max_score) {
-
+        if (!is_array($scores) || empty($scores)
+            || current($scores) == $this->_max_score
+        ) {
             return null;
-
         } else {
-            return ucfirst(key($scores));
+            return key($scores);
         }
     }
 
     /**
      * Returns an array containing the most similar language and a confidence
      * rating
-     * 
+     *
      * Confidence is a simple measure calculated from the similarity score
      * minus the similarity score from the next most similar language
      * divided by the highest possible score. Languages that have closely
@@ -827,46 +829,43 @@ class Text_LanguageDetect
      * confidence scores.
      *
      * The similarity score answers the question "How likely is the text the
-     * returned language regardless of the other languages considered?" The 
+     * returned language regardless of the other languages considered?" The
      * confidence score is one way of answering the question "how likely is the
      * text the detected language relative to the rest of the language model
      * set?"
      *
      * To see how similar languages are a priori, see languageSimilarity()
-     * 
-     * @access   public
-     * @param    string    $sample    text for which language will be detected
-     * @return   array     most similar language, score and confidence rating
-     *                     or null if no language is similar
-     * @see      detect()
-     * @throws   PEAR_Error
+     *
+     * @param string $sample text for which language will be detected
+     *
+     * @return array most similar language, score and confidence rating
+     *               or null if no language is similar
+     * @see    detect()
+     * @throws Text_LanguageDetect_Exception
      */
-    function detectConfidence($sample)
+    public function detectConfidence($sample)
     {
         $scores = $this->detect($sample, 2);
 
-        // if most similar language has the max score, it 
+        // if most similar language has the max score, it
         // will have been picked at random
-        if (    !is_array($scores) 
-                || empty($scores) 
-                || current($scores) == $this->_max_score) {
-
+        if (!is_array($scores) || empty($scores)
+            || current($scores) == $this->_max_score
+        ) {
             return null;
         }
 
-        $arr['language'] = ucfirst(key($scores));
+        $arr['language'] = key($scores);
         $arr['similarity'] = current($scores);
         if (next($scores) !== false) { // if false then no next element
             // the goal is to return a higher value if the distance between
             // the similarity of the first score and the second score is high
 
             if ($this->_perl_compatible) {
-
-                $arr['confidence'] =
-                    (current($scores) - $arr['similarity']) / $this->_max_score;
+                $arr['confidence'] = (current($scores) - $arr['similarity'])
+                    / $this->_max_score;
 
             } else {
-
                 $arr['confidence'] = $arr['similarity'] - current($scores);
 
             }
@@ -882,32 +881,26 @@ class Text_LanguageDetect
      * Returns the distribution of unicode blocks in a given utf8 string
      *
      * For the block name of a single char, use unicodeBlockName()
-     * 
-     * @access public
-     * @param string $str input string. Must be ascii or utf8
-     * @param bool $skip_symbols if true, skip ascii digits, symbols and 
-     *                           non-printing characters. Includes spaces,
-     *                           newlines and common punctutation characters.
+     *
+     * @param string $str          input string. Must be ascii or utf8
+     * @param bool   $skip_symbols if true, skip ascii digits, symbols and
+     *                             non-printing characters. Includes spaces,
+     *                             newlines and common punctutation characters.
+     *
      * @return array
-     * @throws PEAR_Error
+     * @throws Text_LanguageDetect_Exception
      */
-    function detectUnicodeBlocks($str, $skip_symbols)
+    public function detectUnicodeBlocks($str, $skip_symbols)
     {
-        // input check
-        if (!is_bool($skip_symbols)) {
-            throw new Exception('Second parameter must be boolean');
-        } 
-
-        if (!is_string($str)) {
-            throw new Exception('First parameter was not a string');
-        }
+        $skip_symbols = (bool)$skip_symbols;
+        $str          = (string)$str;
 
-        $sample_obj = new Text_LanguageDetect_Parser($str, $this->_db_filename, $this->_unicode_db_filename);
+        $sample_obj = new Text_LanguageDetect_Parser($str);
         $sample_obj->prepareUnicode();
         $sample_obj->prepareTrigram(false);
         $sample_obj->setUnicodeSkipSymbols($skip_symbols);
         $sample_obj->analyze();
-        $blocks =& $sample_obj->getUnicodeBlocks();
+        $blocks = $sample_obj->getUnicodeBlocks();
         unset($sample_obj);
         return $blocks;
     }
@@ -915,38 +908,37 @@ class Text_LanguageDetect
     /**
      * Returns the block name for a given unicode value
      *
-     * If passed a string, will assume it is being passed a UTF8-formatted 
+     * If passed a string, will assume it is being passed a UTF8-formatted
      * character and will automatically convert. Otherwise it will assume it
      * is being passed a numeric unicode value.
      *
      * Make sure input is of the correct type!
      *
-     * @access public
      * @param mixed $unicode unicode value or utf8 char
+     *
      * @return mixed the block name string or false if not found
-     * @throws PEAR_Error
+     * @throws Text_LanguageDetect_Exception
      */
-    function unicodeBlockName($unicode) {
+    public function unicodeBlockName($unicode)
+    {
         if (is_string($unicode)) {
             // assume it is being passed a utf8 char, so convert it
-
-            // input check
-            if ($this->utf8strlen($unicode) > 1) {
-                throw new Exception('Pass this function only a single char');
+            if (self::utf8strlen($unicode) > 1) {
+                throw new Text_LanguageDetect_Exception(
+                    'Pass a single char only to this method',
+                    Text_LanguageDetect_Exception::PARAM_TYPE
+                );
             }
-
             $unicode = $this->_utf8char2unicode($unicode);
 
-            if ($unicode == -1) {
-                throw new Exception('Malformatted char');
-            }
-
-        // input check
         } elseif (!is_int($unicode)) {
-            throw new Exception('Input must be of type string or int.');
+            throw new Text_LanguageDetect_Exception(
+                'Input must be of type string or int.',
+                Text_LanguageDetect_Exception::PARAM_TYPE
+            );
         }
 
-        $blocks =& $this->_read_unicode_block_db();
+        $blocks = $this->_read_unicode_block_db();
 
         $result = $this->_unicode_block_name($unicode, $blocks);
 
@@ -964,14 +956,17 @@ class Text_LanguageDetect
      * the public interface for this function, which does input checks which
      * this function omits for speed.
      *
-     * @access  protected
-     * @param   int     $unicode the unicode value
-     * @param   array   &$blocks the block database
-     * @param   int     $block_count the number of defined blocks in the database
-     * @see     unicodeBlockName()
+     * @param int   $unicode     the unicode value
+     * @param array $blocks      the block database
+     * @param int   $block_count the number of defined blocks in the database
+     *
+     * @return mixed Block name, -1 if it failed
+     * @see    unicodeBlockName()
+     * @access protected
      */
-    function _unicode_block_name($unicode, &$blocks, $block_count = -1) {
-        // for a reference, see 
+    function _unicode_block_name($unicode, $blocks, $block_count = -1)
+    {
+        // for a reference, see
         // http://www.unicode.org/Public/UNIDATA/Blocks.txt
 
         // assume that ascii characters are the most common
@@ -994,35 +989,36 @@ class Text_LanguageDetect
         while ($low <= $high) {
             $mid = floor(($low + $high) / 2);
 
-            // if it's lower than the lower bound
             if ($unicode < $blocks[$mid][0]) {
+                // if it's lower than the lower bound
                 $high = $mid - 1;
 
-            // if it's higher than the upper bound
             } elseif ($unicode > $blocks[$mid][1]) {
+                // if it's higher than the upper bound
                 $low = $mid + 1;
 
-            // found it
             } else {
+                // found it
                 return $blocks[$mid];
             }
         }
 
-        // failed to find the block 
+        // failed to find the block
         return -1;
 
-        // todo: differentiate when it's out of range or when it falls 
+        // todo: differentiate when it's out of range or when it falls
         //       into an unassigned range?
     }
 
     /**
      * Brings up the unicode block database
      *
-     * @access protected
      * @return array the database of unicode block definitions
-     * @throws PEAR_Error
+     * @throws Text_LanguageDetect_Exception
+     * @access protected
      */
-    function &_read_unicode_block_db() {
+    function _read_unicode_block_db()
+    {
         // since the unicode definitions are always going to be the same,
         // might as well share the memory for the db with all other instances
         // of this class
@@ -1037,29 +1033,27 @@ class Text_LanguageDetect
 
     /**
      * Calculate the similarities between the language models
-     * 
+     *
      * Use this function to see how similar languages are to each other.
      *
      * If passed 2 language names, will return just those languages compared.
      * If passed 1 language name, will return that language compared to
      * all others.
-     * If passed none, will return an array of every language model compared 
+     * If passed none, will return an array of every language model compared
      * to every other one.
      *
-     * @access  public
-     * @param   string   $lang1   the name of the first language to be compared
-     * @param   string   $lang2   the name of the second language to be compared
-     * @return  array    scores of every language compared
-     *                   or the score of just the provided languages
-     *                   or null if one of the supplied languages does not exist
-     * @throws  PEAR_Error
+     * @param string $lang1 the name of the first language to be compared
+     * @param string $lang2 the name of the second language to be compared
+     *
+     * @return array scores of every language compared
+     *               or the score of just the provided languages
+     *               or null if one of the supplied languages does not exist
+     * @throws Text_LanguageDetect_Exception
      */
-    function languageSimilarity($lang1 = null, $lang2 = null)
+    public function languageSimilarity($lang1 = null, $lang2 = null)
     {
-        if (!$this->_setup_ok($err)) {
-            return $err;
-        }
-
+        $lang1 = $this->_convertFromNameMode($lang1);
+        $lang2 = $this->_convertFromNameMode($lang2);
         if ($lang1 != null) {
             $lang1 = strtolower($lang1);
 
@@ -1069,12 +1063,8 @@ class Text_LanguageDetect
             }
 
             if ($lang2 != null) {
-
-                // can't only set the second param
-                if ($lang1 == null) {
-                    return null;
-                // check if language model exists
-                } elseif (!isset($this->_lang_db[$lang2])) {
+                if (!isset($this->_lang_db[$lang2])) {
+                    // check if language model exists
                     return null;
                 }
 
@@ -1088,14 +1078,15 @@ class Text_LanguageDetect
                     )
                 );
 
-
-            // compare just $lang1 to all languages
             } else {
+                // compare just $lang1 to all languages
                 $return_arr = array();
                 foreach ($this->_lang_db as $key => $value) {
-                    if ($key != $lang1) { // don't compare a language to itself
+                    if ($key != $lang1) {
+                        // don't compare a language to itself
                         $return_arr[$key] = $this->_normalize_score(
-                            $this->_distance($this->_lang_db[$lang1], $value));
+                            $this->_distance($this->_lang_db[$lang1], $value)
+                        );
                     }
                 }
                 asort($return_arr);
@@ -1104,30 +1095,27 @@ class Text_LanguageDetect
             }
 
 
-        // compare all languages to each other
         } else {
+            // compare all languages to each other
             $return_arr = array();
             foreach (array_keys($this->_lang_db) as $lang1) {
                 foreach (array_keys($this->_lang_db) as $lang2) {
-
                     // skip comparing languages to themselves
-                    if ($lang1 != $lang2) { 
-                    
-                        // don't re-calculate what's already been done
-                        if (isset($return_arr[$lang2][$lang1])) {
+                    if ($lang1 != $lang2) {
 
-                            $return_arr[$lang1][$lang2] =
-                                $return_arr[$lang2][$lang1];
+                        if (isset($return_arr[$lang2][$lang1])) {
+                            // don't re-calculate what's already been done
+                            $return_arr[$lang1][$lang2]
+                                = $return_arr[$lang2][$lang1];
 
-                        // calculate
                         } else {
-
-                            $return_arr[$lang1][$lang2] = 
-                                $this->_normalize_score(
-                                        $this->_distance(
-                                            $this->_lang_db[$lang1],
-                                            $this->_lang_db[$lang2]
-                                        )
+                            // calculate
+                            $return_arr[$lang1][$lang2]
+                                $this->_normalize_score(
+                                    $this->_distance(
+                                        $this->_lang_db[$lang1],
+                                        $this->_lang_db[$lang2]
+                                    )
                                 );
 
                         }
@@ -1150,20 +1138,14 @@ class Text_LanguageDetect
      *
      * @access      public
      * @return      array language cluster data
-     * @throws      PEAR_Error
+     * @throws      Text_LanguageDetect_Exception
      * @see         languageSimilarity()
-     * @deprecated  this function will eventually be removed and placed into 
+     * @deprecated  this function will eventually be removed and placed into
      *              the model generation class
      */
     function clusterLanguages()
     {
         // todo: set the maximum number of clusters
-
-        // setup check
-        if (!$this->_setup_ok($err)) {
-            return $err;
-        }
-
         // return cached result, if any
         if (isset($this->_clusters)) {
             return $this->_clusters;
@@ -1177,7 +1159,10 @@ class Text_LanguageDetect
 
         foreach ($langs as $lang) {
             if (!isset($this->_lang_db[$lang])) {
-                throw new Exception("missing $lang!\n");
+                throw new Text_LanguageDetect_Exception(
+                    "missing $lang!",
+                    Text_LanguageDetect_Exception::UNKNOWN_LANGUAGE
+                );
             }
         }
 
@@ -1186,7 +1171,9 @@ class Text_LanguageDetect
             $langs[$lang1] = $lang1;
             unset($langs[$old_key]);
         }
-        
+
+        $result_data = $really_map = array();
+
         $i = 0;
         while (count($langs) > 2 && $i++ < 200) {
             $highest_score = -1;
@@ -1194,18 +1181,22 @@ class Text_LanguageDetect
             $highest_key2 = '';
             foreach ($langs as $lang1) {
                 foreach ($langs as $lang2) {
-                    if (    $lang1 != $lang2 
-                            && $arr[$lang1][$lang2] > $highest_score) {
+                    if ($lang1 != $lang2
+                        && $arr[$lang1][$lang2] > $highest_score
+                    ) {
                         $highest_score = $arr[$lang1][$lang2];
                         $highest_key1 = $lang1;
                         $highest_key2 = $lang2;
                     }
                 }
             }
-            
+
             if (!$highest_key1) {
                 // should not ever happen
-                throw new Exception("no highest key? (step: $i)");
+                throw new Text_LanguageDetect_Exception(
+                    "no highest key? (step: $i)",
+                    Text_LanguageDetect_Exception::NO_HIGHEST_KEY
+                );
             }
 
             if ($highest_score == 0) {
@@ -1217,7 +1208,7 @@ class Text_LanguageDetect
             $sum1 = array_sum($arr[$highest_key1]);
             $sum2 = array_sum($arr[$highest_key2]);
 
-            // use the score for the one that is most similar to the rest of 
+            // use the score for the one that is most similar to the rest of
             // the field as the score for the group
             // todo: could try averaging or "centroid" method instead
             // seems like that might make more sense
@@ -1248,7 +1239,7 @@ class Text_LanguageDetect
             $really_lang = $replaceme;
             while (isset($really_map[$really_lang])) {
                 $really_lang = $really_map[$really_lang];
-            } 
+            }
             $really_map[$newkey] = $really_lang;
 
 
@@ -1259,8 +1250,8 @@ class Text_LanguageDetect
                         $arr[$key1][$newkey] = $arr[$key1][$key2];
                         unset($arr[$key1][$key2]);
                         // replacing $arr[$key1][$key2] with $arr[$key1][$newkey]
-                    } 
-                    
+                    }
+
                     if ($key1 == $replaceme) {
                         $arr[$newkey][$key2] = $arr[$key1][$key2];
                         unset($arr[$key1][$key2]);
@@ -1273,7 +1264,7 @@ class Text_LanguageDetect
                     }
                 }
             }
-                        
+
 
             unset($langs[$highest_key1]);
             unset($langs[$highest_key2]);
@@ -1293,7 +1284,7 @@ class Text_LanguageDetect
         }
 
         $return_val = array(
-                'open_forks' => $langs, 
+                'open_forks' => $langs,
                         // the top level of clusters
                         // clusters that are mutually exclusive
                         // or specified by a specific maximum
@@ -1323,11 +1314,11 @@ class Text_LanguageDetect
      * use, and it may disappear or its functionality may change in future
      * releases without notice.
      *
-     * This compares the sample text to top the top level of clusters. If the 
+     * This compares the sample text to top the top level of clusters. If the
      * sample is similar to the cluster it will drop down and compare it to the
      * languages in the cluster, and so on until it hits a leaf node.
      *
-     * this should find the language in considerably fewer compares 
+     * this should find the language in considerably fewer compares
      * (the equivalent of a binary search), however clusterLanguages() is costly
      * and the loss of accuracy from this technique is significant.
      *
@@ -1337,15 +1328,14 @@ class Text_LanguageDetect
      * was very large, however in such cases some method of Bayesian inference
      * might be more helpful.
      *
-     * @see     clusterLanguages()
-     * @access  public
-     * @param   string $str input string
-     * @return  array language scores (only those compared)
-     * @throws  PEAR_Error
+     * @param string $str input string
+     *
+     * @return array language scores (only those compared)
+     * @throws Text_LanguageDetect_Exception
+     * @see    clusterLanguages()
      */
-    function clusteredSearch($str)
+    public function clusteredSearch($str)
     {
-
         // input check
         if (!Text_LanguageDetect_Parser::validateString($str)) {
             return array();
@@ -1359,7 +1349,7 @@ class Text_LanguageDetect
         $dendogram_data  = $result['fork_data'];
         $dendogram_alias = $result['name_map'];
 
-        $sample_obj = new Text_LanguageDetect_Parser($str, $this->_db_filename, $this->_unicode_db_filename);
+        $sample_obj = new Text_LanguageDetect_Parser($str);
         $sample_obj->prepareTrigram();
         $sample_obj->setPadStart(!$this->_perl_compatible);
         $sample_obj->analyze();
@@ -1372,7 +1362,7 @@ class Text_LanguageDetect
         }
 
         $i = 0; // counts the number of steps
-        
+
         foreach ($dendogram_start as $lang) {
             if (isset($dendogram_alias[$lang])) {
                 $lang_key = $dendogram_alias[$lang];
@@ -1382,7 +1372,8 @@ class Text_LanguageDetect
 
             $scores[$lang] = $this->_normalize_score(
                 $this->_distance($this->_lang_db[$lang_key], $sample_result),
-                $sample_count);
+                $sample_count
+            );
 
             $i++;
         }
@@ -1411,7 +1402,8 @@ class Text_LanguageDetect
 
                 $scores[$lang] = $this->_normalize_score(
                     $this->_distance($this->_lang_db[$lang_key], $sample_result),
-                    $sample_count);
+                    $sample_count
+                );
 
                 //todo: does not need to do same comparison again
             }
@@ -1428,8 +1420,8 @@ class Text_LanguageDetect
 
             $diff = $scores[$cur_key] - $scores[$loser_key];
 
-            // $cur_key ({$dendogram_alias[$cur_key]}) wins 
-            // over $loser_key ({$dendogram_alias[$loser_key]}) 
+            // $cur_key ({$dendogram_alias[$cur_key]}) wins
+            // over $loser_key ({$dendogram_alias[$loser_key]})
             // with a difference of $diff
         }
 
@@ -1439,9 +1431,9 @@ class Text_LanguageDetect
         // which paths the algorithm decided to take along the tree
 
         // but sometimes the last item is only the second highest
-        if (   ($this->_perl_compatible  && (end($scores) > prev($scores)))
-            || (!$this->_perl_compatible && (end($scores) < prev($scores)))) {
-
+        if (($this->_perl_compatible  && (end($scores) > prev($scores)))
+            || (!$this->_perl_compatible && (end($scores) < prev($scores)))
+        ) {
             $real_last_score = current($scores);
             $real_last_key = key($scores);
 
@@ -1449,7 +1441,7 @@ class Text_LanguageDetect
             unset($scores[$real_last_key]);
             $scores[$real_last_key] = $real_last_score;
         }
-            
+
 
         if (!$this->_perl_compatible) {
             $scores = array_reverse($scores, true);
@@ -1464,12 +1456,11 @@ class Text_LanguageDetect
      *
      * Returns the numbers of characters (not bytes) in a utf8 string
      *
-     * @static
-     * @access  public
-     * @param   string $str string to get the length of
-     * @return  int         number of chars
+     * @param string $str string to get the length of
+     *
+     * @return int number of chars
      */
-    function utf8strlen($str)
+    public static function utf8strlen($str)
     {
         // utf8_decode() will convert unknown chars to '?', which is actually
         // ideal for counting.
@@ -1482,53 +1473,45 @@ class Text_LanguageDetect
     /**
      * Returns the unicode value of a utf8 char
      *
-     * @access  protected
-     * @param   string $char a utf8 (possibly multi-byte) char
-     * @return  int          unicode value or -1 if malformatted
+     * @param string $char a utf8 (possibly multi-byte) char
+     *
+     * @return int unicode value
+     * @access protected
+     * @link   http://en.wikipedia.org/wiki/UTF-8
      */
-    function _utf8char2unicode($char) {
-
+    function _utf8char2unicode($char)
+    {
         // strlen() here will actually get the binary length of a single char
         switch (strlen($char)) {
-
-            // for a reference, see http://en.wikipedia.org/wiki/UTF-8
-
-            case 1:
-                // normal ASCII-7 byte
-                // 0xxxxxxx -->  0xxxxxxx
-                return ord($char{0});
-
-            case 2:
-                // 2 byte unicode
-                // 110zzzzx 10xxxxxx --> 00000zzz zxxxxxxx
-                $z = (ord($char{0}) & 0x000001F) << 6;
-                $x = (ord($char{1}) & 0x0000003F);
-
-                return ($z | $x);
-
-            case 3:
-                // 3 byte unicode
-                // 1110zzzz 10zxxxxx 10xxxxxx --> zzzzzxxx xxxxxxxx 
-                $z =  (ord($char{0}) & 0x0000000F) << 12;
-                $x1 = (ord($char{1}) & 0x0000003F) << 6;
-                $x2 = (ord($char{2}) & 0x0000003F);
-
-                return ($z | $x1 | $x2);
-
-            case 4:
-                // 4 byte unicode
-                // 11110zzz 10zzxxxx 10xxxxxx 10xxxxxx -->
-                // 000zzzzz xxxxxxxx xxxxxxxx
-                $z1 = (ord($char{0}) & 0x00000007) << 18;
-                $z2 = (ord($char{1}) & 0x0000003F) << 12;
-                $x1 = (ord($char{2}) & 0x0000003F) << 6;
-                $x2 = (ord($char{3}) & 0x0000003F);
-
-                return ($z1 | $z2 | $x1 | $x2);
-
-            default:
-                // error: malformatted char?
-                return -1;
+        case 1:
+            // normal ASCII-7 byte
+            // 0xxxxxxx -->  0xxxxxxx
+            return ord($char{0});
+
+        case 2:
+            // 2 byte unicode
+            // 110zzzzx 10xxxxxx --> 00000zzz zxxxxxxx
+            $z = (ord($char{0}) & 0x000001F) << 6;
+            $x = (ord($char{1}) & 0x0000003F);
+            return ($z | $x);
+
+        case 3:
+            // 3 byte unicode
+            // 1110zzzz 10zxxxxx 10xxxxxx --> zzzzzxxx xxxxxxxx
+            $z =  (ord($char{0}) & 0x0000000F) << 12;
+            $x1 = (ord($char{1}) & 0x0000003F) << 6;
+            $x2 = (ord($char{2}) & 0x0000003F);
+            return ($z | $x1 | $x2);
+
+        case 4:
+            // 4 byte unicode
+            // 11110zzz 10zzxxxx 10xxxxxx 10xxxxxx -->
+            // 000zzzzz xxxxxxxx xxxxxxxx
+            $z1 = (ord($char{0}) & 0x00000007) << 18;
+            $z2 = (ord($char{1}) & 0x0000003F) << 12;
+            $x1 = (ord($char{2}) & 0x0000003F) << 6;
+            $x2 = (ord($char{3}) & 0x0000003F);
+            return ($z1 | $z2 | $x1 | $x2);
         }
     }
 
@@ -1536,18 +1519,18 @@ class Text_LanguageDetect
      * utf8-safe fast character iterator
      *
      * Will get the next character starting from $counter, which will then be
-     * incremented. If a multi-byte char the bytes will be concatenated and 
+     * incremented. If a multi-byte char the bytes will be concatenated and
      * $counter will be incremeted by the number of bytes in the char.
      *
-     * @access  private
-     * @param   string  &$str        the string being iterated over
-     * @param   int     &$counter    the iterator, will increment by reference
-     * @param   bool    $special_convert whether to do special conversions
-     * @return  char    the next (possibly multi-byte) char from $counter
+     * @param string $str             the string being iterated over
+     * @param int    &$counter        the iterator, will increment by reference
+     * @param bool   $special_convert whether to do special conversions
+     *
+     * @return char the next (possibly multi-byte) char from $counter
+     * @access private
      */
-    function _next_char(&$str, &$counter, $special_convert = false)
+    static function _next_char($str, &$counter, $special_convert = false)
     {
-
         $char = $str{$counter++};
         $ord = ord($char);
 
@@ -1556,7 +1539,6 @@ class Text_LanguageDetect
 
         // normal ascii one byte char
         if ($ord <= 127) {
-
             // special conversions needed for this package
             // (that only apply to regular ascii characters)
             // lower case, and convert all non-alphanumeric characters
@@ -1571,8 +1553,8 @@ class Text_LanguageDetect
 
             return $char;
 
-        // multi-byte chars
         } elseif ($ord >> 5 == 6) { // two-byte char
+            // multi-byte chars
             $nextchar = $str{$counter++}; // get next byte
 
             // lower-casing of non-ascii characters is still incomplete
@@ -1582,27 +1564,27 @@ class Text_LanguageDetect
                 if ($ord == 195) {
                     $nextord = ord($nextchar);
                     $nextord_adj = $nextord + 64;
-                    // for a reference, see 
+                    // for a reference, see
                     // http://www.ramsch.org/martin/uni/fmi-hp/iso8859-1.html
 
                     // &Agrave; - &THORN; but not &times;
-                    if (    $nextord_adj >= 192
-                            && $nextord_adj <= 222 
-                            && $nextord_adj != 215) {
-
-                        $nextchar = chr($nextord + 32); 
+                    if ($nextord_adj >= 192
+                        && $nextord_adj <= 222
+                        && $nextord_adj != 215
+                    ) {
+                        $nextchar = chr($nextord + 32);
                     }
 
-                // lower case cyrillic alphabet
                 } elseif ($ord == 208) {
+                    // lower case cyrillic alphabet
                     $nextord = ord($nextchar);
                     // if A - Pe
                     if ($nextord >= 144 && $nextord <= 159) {
                         // lower case
                         $nextchar = chr($nextord + 32);
 
-                    // if Er - Ya
                     } elseif ($nextord >= 160 && $nextord <= 175) {
+                        // if Er - Ya
                         // lower case
                         $char = chr(209); // == $ord++
                         $nextchar = chr($nextord - 32);
@@ -1611,12 +1593,11 @@ class Text_LanguageDetect
             }
 
             // tag on next byte
-            return $char . $nextchar; 
-
+            return $char . $nextchar;
         } elseif ($ord >> 4  == 14) { // three-byte char
-            
+
             // tag on next 2 bytes
-            return $char . $str{$counter++} . $str{$counter++}; 
+            return $char . $str{$counter++} . $str{$counter++};
 
         } elseif ($ord >> 3 == 30) { // four-byte char
 
@@ -1628,8 +1609,85 @@ class Text_LanguageDetect
         }
     }
 
-}
+    /**
+     * Converts an $language input parameter from the configured mode
+     * to the language name that is used internally.
+     *
+     * Works for strings and arrays.
+     *
+     * @param string|array $lang       A language description ("english"/"en"/"eng")
+     * @param boolean      $convertKey If $lang is an array, setting $key
+     *                                 converts the keys to the language name.
+     *
+     * @return string|array Language name
+     */
+    function _convertFromNameMode($lang, $convertKey = false)
+    {
+        if ($this->_name_mode == 0) {
+            return $lang;
+        }
+
+        if ($this->_name_mode == 2) {
+            $method = 'code2ToName';
+        } else {
+            $method = 'code3ToName';
+        }
+
+        if (is_string($lang)) {
+            return (string)Text_LanguageDetect_ISO639::$method($lang);
+        }
+
+        $newlang = array();
+        foreach ($lang as $key => $val) {
+            if ($convertKey) {
+                $newkey = (string)Text_LanguageDetect_ISO639::$method($key);
+                $newlang[$newkey] = $val;
+            } else {
+                $newlang[$key] = (string)Text_LanguageDetect_ISO639::$method($val);
+            }
+        }
+        return $newlang;
+    }
 
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
+    /**
+     * Converts an $language output parameter from the language name that is
+     * used internally to the configured mode.
+     *
+     * Works for strings and arrays.
+     *
+     * @param string|array $lang       A language description ("english"/"en"/"eng")
+     * @param boolean      $convertKey If $lang is an array, setting $key
+     *                                 converts the keys to the language name.
+     *
+     * @return string|array Language name
+     */
+    function _convertToNameMode($lang, $convertKey = false)
+    {
+        if ($this->_name_mode == 0) {
+            return $lang;
+        }
+
+        if ($this->_name_mode == 2) {
+            $method = 'nameToCode2';
+        } else {
+            $method = 'nameToCode3';
+        }
+
+        if (is_string($lang)) {
+            return Text_LanguageDetect_ISO639::$method($lang);
+        }
+
+        $newlang = array();
+        foreach ($lang as $key => $val) {
+            if ($convertKey) {
+                $newkey = Text_LanguageDetect_ISO639::$method($key);
+                $newlang[$newkey] = $val;
+            } else {
+                $newlang[$key] = Text_LanguageDetect_ISO639::$method($val);
+            }
+        }
+        return $newlang;
+    }
+}
 
-?>
+/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
\ No newline at end of file
diff --git a/inc/3rdparty/libraries/language-detect/LanguageDetect/Exception.php b/inc/3rdparty/libraries/language-detect/LanguageDetect/Exception.php
new file mode 100644 (file)
index 0000000..196d994
--- /dev/null
@@ -0,0 +1,57 @@
+<?php
+class Text_LanguageDetect_Exception extends Exception
+{
+    /**
+     * Database file could not be found
+     */
+    const DB_NOT_FOUND = 10;
+
+    /**
+     * Database file found, but not readable
+     */
+    const DB_NOT_READABLE = 11;
+
+    /**
+     * Database file is empty
+     */
+    const DB_EMPTY = 12;
+
+    /**
+     * Database contents is not a PHP array
+     */
+    const DB_NOT_ARRAY = 13;
+
+    /**
+     * Magic quotes are activated
+     */
+    const MAGIC_QUOTES = 14;
+
+
+    /**
+     * Parameter of invalid type passed to method
+     */
+    const PARAM_TYPE = 20;
+
+    /**
+     * Character in parameter is invalid
+     */
+    const INVALID_CHAR = 21;
+
+
+    /**
+     * Language is not in the database
+     */
+    const UNKNOWN_LANGUAGE = 30;
+
+
+    /**
+     * Error during block detection
+     */
+    const BLOCK_DETECTION = 40;
+
+
+    /**
+     * Error while clustering languages
+     */
+    const NO_HIGHEST_KEY = 50;
+}
diff --git a/inc/3rdparty/libraries/language-detect/LanguageDetect/ISO639.php b/inc/3rdparty/libraries/language-detect/LanguageDetect/ISO639.php
new file mode 100644 (file)
index 0000000..05b0590
--- /dev/null
@@ -0,0 +1,339 @@
+<?php
+/**
+ * Part of Text_LanguageDetect
+ *
+ * PHP version 5
+ *
+ * @category  Text
+ * @package   Text_LanguageDetect
+ * @author    Christian Weiske <cweiske@php.net>
+ * @copyright 2011 Christian Weiske <cweiske@php.net>
+ * @license   http://www.debian.org/misc/bsd.license BSD
+ * @version   SVN: $Id$
+ * @link      http://pear.php.net/package/Text_LanguageDetect/
+ */
+
+/**
+ * Provides a mapping between the languages from lang.dat and the
+ * ISO 639-1 and ISO-639-2 codes.
+ *
+ * Note that this class contains only languages that exist in lang.dat.
+ *
+ * @category  Text
+ * @package   Text_LanguageDetect
+ * @author    Christian Weiske <cweiske@php.net>
+ * @copyright 2011 Christian Weiske <cweiske@php.net>
+ * @license   http://www.debian.org/misc/bsd.license BSD
+ * @link      http://www.loc.gov/standards/iso639-2/php/code_list.php
+ */
+class Text_LanguageDetect_ISO639
+{
+    /**
+     * Maps all language names from the language database to the
+     * ISO 639-1 2-letter language code.
+     *
+     * NULL indicates that there is no 2-letter code.
+     *
+     * @var array
+     */
+    public static $nameToCode2 = array(
+        'albanian'   => 'sq',
+        'arabic'     => 'ar',
+        'azeri'      => 'az',
+        'bengali'    => 'bn',
+        'bulgarian'  => 'bg',
+        'cebuano'    => null,
+        'croatian'   => 'hr',
+        'czech'      => 'cs',
+        'danish'     => 'da',
+        'dutch'      => 'nl',
+        'english'    => 'en',
+        'estonian'   => 'et',
+        'farsi'      => 'fa',
+        'finnish'    => 'fi',
+        'french'     => 'fr',
+        'german'     => 'de',
+        'hausa'      => 'ha',
+        'hawaiian'   => null,
+        'hindi'      => 'hi',
+        'hungarian'  => 'hu',
+        'icelandic'  => 'is',
+        'indonesian' => 'id',
+        'italian'    => 'it',
+        'kazakh'     => 'kk',
+        'kyrgyz'     => 'ky',
+        'latin'      => 'la',
+        'latvian'    => 'lv',
+        'lithuanian' => 'lt',
+        'macedonian' => 'mk',
+        'mongolian'  => 'mn',
+        'nepali'     => 'ne',
+        'norwegian'  => 'no',
+        'pashto'     => 'ps',
+        'pidgin'     => null,
+        'polish'     => 'pl',
+        'portuguese' => 'pt',
+        'romanian'   => 'ro',
+        'russian'    => 'ru',
+        'serbian'    => 'sr',
+        'slovak'     => 'sk',
+        'slovene'    => 'sl',
+        'somali'     => 'so',
+        'spanish'    => 'es',
+        'swahili'    => 'sw',
+        'swedish'    => 'sv',
+        'tagalog'    => 'tl',
+        'turkish'    => 'tr',
+        'ukrainian'  => 'uk',
+        'urdu'       => 'ur',
+        'uzbek'      => 'uz',
+        'vietnamese' => 'vi',
+        'welsh'      => 'cy',
+    );
+
+    /**
+     * Maps all language names from the language database to the
+     * ISO 639-2 3-letter language code.
+     *
+     * @var array
+     */
+    public static $nameToCode3 = array(
+        'albanian'   => 'sqi',
+        'arabic'     => 'ara',
+        'azeri'      => 'aze',
+        'bengali'    => 'ben',
+        'bulgarian'  => 'bul',
+        'cebuano'    => 'ceb',
+        'croatian'   => 'hrv',
+        'czech'      => 'ces',
+        'danish'     => 'dan',
+        'dutch'      => 'nld',
+        'english'    => 'eng',
+        'estonian'   => 'est',
+        'farsi'      => 'fas',
+        'finnish'    => 'fin',
+        'french'     => 'fra',
+        'german'     => 'deu',
+        'hausa'      => 'hau',
+        'hawaiian'   => 'haw',
+        'hindi'      => 'hin',
+        'hungarian'  => 'hun',
+        'icelandic'  => 'isl',
+        'indonesian' => 'ind',
+        'italian'    => 'ita',
+        'kazakh'     => 'kaz',
+        'kyrgyz'     => 'kir',
+        'latin'      => 'lat',
+        'latvian'    => 'lav',
+        'lithuanian' => 'lit',
+        'macedonian' => 'mkd',
+        'mongolian'  => 'mon',
+        'nepali'     => 'nep',
+        'norwegian'  => 'nor',
+        'pashto'     => 'pus',
+        'pidgin'     => 'crp',
+        'polish'     => 'pol',
+        'portuguese' => 'por',
+        'romanian'   => 'ron',
+        'russian'    => 'rus',
+        'serbian'    => 'srp',
+        'slovak'     => 'slk',
+        'slovene'    => 'slv',
+        'somali'     => 'som',
+        'spanish'    => 'spa',
+        'swahili'    => 'swa',
+        'swedish'    => 'swe',
+        'tagalog'    => 'tgl',
+        'turkish'    => 'tur',
+        'ukrainian'  => 'ukr',
+        'urdu'       => 'urd',
+        'uzbek'      => 'uzb',
+        'vietnamese' => 'vie',
+        'welsh'      => 'cym',
+    );
+
+    /**
+     * Maps ISO 639-1 2-letter language codes to the language names
+     * in the language database
+     *
+     * Not all languages have a 2 letter code, so some are missing
+     *
+     * @var array
+     */
+    public static $code2ToName = array(
+        'ar' => 'arabic',
+        'az' => 'azeri',
+        'bg' => 'bulgarian',
+        'bn' => 'bengali',
+        'cs' => 'czech',
+        'cy' => 'welsh',
+        'da' => 'danish',
+        'de' => 'german',
+        'en' => 'english',
+        'es' => 'spanish',
+        'et' => 'estonian',
+        'fa' => 'farsi',
+        'fi' => 'finnish',
+        'fr' => 'french',
+        'ha' => 'hausa',
+        'hi' => 'hindi',
+        'hr' => 'croatian',
+        'hu' => 'hungarian',
+        'id' => 'indonesian',
+        'is' => 'icelandic',
+        'it' => 'italian',
+        'kk' => 'kazakh',
+        'ky' => 'kyrgyz',
+        'la' => 'latin',
+        'lt' => 'lithuanian',
+        'lv' => 'latvian',
+        'mk' => 'macedonian',
+        'mn' => 'mongolian',
+        'ne' => 'nepali',
+        'nl' => 'dutch',
+        'no' => 'norwegian',
+        'pl' => 'polish',
+        'ps' => 'pashto',
+        'pt' => 'portuguese',
+        'ro' => 'romanian',
+        'ru' => 'russian',
+        'sk' => 'slovak',
+        'sl' => 'slovene',
+        'so' => 'somali',
+        'sq' => 'albanian',
+        'sr' => 'serbian',
+        'sv' => 'swedish',
+        'sw' => 'swahili',
+        'tl' => 'tagalog',
+        'tr' => 'turkish',
+        'uk' => 'ukrainian',
+        'ur' => 'urdu',
+        'uz' => 'uzbek',
+        'vi' => 'vietnamese',
+    );
+
+    /**
+     * Maps ISO 639-2 3-letter language codes to the language names
+     * in the language database.
+     *
+     * @var array
+     */
+    public static $code3ToName = array(
+        'ara' => 'arabic',
+        'aze' => 'azeri',
+        'ben' => 'bengali',
+        'bul' => 'bulgarian',
+        'ceb' => 'cebuano',
+        'ces' => 'czech',
+        'crp' => 'pidgin',
+        'cym' => 'welsh',
+        'dan' => 'danish',
+        'deu' => 'german',
+        'eng' => 'english',
+        'est' => 'estonian',
+        'fas' => 'farsi',
+        'fin' => 'finnish',
+        'fra' => 'french',
+        'hau' => 'hausa',
+        'haw' => 'hawaiian',
+        'hin' => 'hindi',
+        'hrv' => 'croatian',
+        'hun' => 'hungarian',
+        'ind' => 'indonesian',
+        'isl' => 'icelandic',
+        'ita' => 'italian',
+        'kaz' => 'kazakh',
+        'kir' => 'kyrgyz',
+        'lat' => 'latin',
+        'lav' => 'latvian',
+        'lit' => 'lithuanian',
+        'mkd' => 'macedonian',
+        'mon' => 'mongolian',
+        'nep' => 'nepali',
+        'nld' => 'dutch',
+        'nor' => 'norwegian',
+        'pol' => 'polish',
+        'por' => 'portuguese',
+        'pus' => 'pashto',
+        'rom' => 'romanian',
+        'rus' => 'russian',
+        'slk' => 'slovak',
+        'slv' => 'slovene',
+        'som' => 'somali',
+        'spa' => 'spanish',
+        'sqi' => 'albanian',
+        'srp' => 'serbian',
+        'swa' => 'swahili',
+        'swe' => 'swedish',
+        'tgl' => 'tagalog',
+        'tur' => 'turkish',
+        'ukr' => 'ukrainian',
+        'urd' => 'urdu',
+        'uzb' => 'uzbek',
+        'vie' => 'vietnamese',
+    );
+
+    /**
+     * Returns the 2-letter ISO 639-1 code for the given language name.
+     *
+     * @param string $lang English language name like "swedish"
+     *
+     * @return string Two-letter language code (e.g. "sv") or NULL if not found
+     */
+    public static function nameToCode2($lang)
+    {
+        $lang = strtolower($lang);
+        if (!isset(self::$nameToCode2[$lang])) {
+            return null;
+        }
+        return self::$nameToCode2[$lang];
+    }
+
+    /**
+     * Returns the 3-letter ISO 639-2 code for the given language name.
+     *
+     * @param string $lang English language name like "swedish"
+     *
+     * @return string Three-letter language code (e.g. "swe") or NULL if not found
+     */
+    public static function nameToCode3($lang)
+    {
+        $lang = strtolower($lang);
+        if (!isset(self::$nameToCode3[$lang])) {
+            return null;
+        }
+        return self::$nameToCode3[$lang];
+    }
+
+    /**
+     * Returns the language name for the given 2-letter ISO 639-1 code.
+     *
+     * @param string $code Two-letter language code (e.g. "sv")
+     *
+     * @return string English language name like "swedish"
+     */
+    public static function code2ToName($code)
+    {
+        $lang = strtolower($code);
+        if (!isset(self::$code2ToName[$code])) {
+            return null;
+        }
+        return self::$code2ToName[$code];
+    }
+
+    /**
+     * Returns the language name for the given 3-letter ISO 639-2 code.
+     *
+     * @param string $code Three-letter language code (e.g. "swe")
+     *
+     * @return string English language name like "swedish"
+     */
+    public static function code3ToName($code)
+    {
+        $lang = strtolower($code);
+        if (!isset(self::$code3ToName[$code])) {
+            return null;
+        }
+        return self::$code3ToName[$code];
+    }
+}
\ No newline at end of file
similarity index 94%
rename from inc/3rdparty/libraries/language-detect/Parser.php
rename to inc/3rdparty/libraries/language-detect/LanguageDetect/Parser.php
index 7f15fa988aa820031ab8aa0b902cd625dde09e1a..fb0e1e2044b2fcb8b918394b858d95f007ebd81e 100644 (file)
@@ -8,7 +8,7 @@
  * @author      Nicholas Pisarro
  * @copyright   2006
  * @license     BSD
- * @version     CVS: $Id: Parser.php,v 1.5 2006/03/11 05:45:05 taak Exp $
+ * @version     CVS: $Id: Parser.php 322327 2012-01-15 17:55:59Z cweiske $
  * @link        http://pear.php.net/package/Text_LanguageDetect/
  * @link        http://langdetect.blogspot.com/
  */
@@ -28,7 +28,7 @@
  * @author      Nicholas Pisarro
  * @copyright   2006
  * @license     BSD
- * @version     release: 0.2.3
+ * @version     release: 0.3.0
  */
 class Text_LanguageDetect_Parser extends Text_LanguageDetect
 {
@@ -102,21 +102,17 @@ class Text_LanguageDetect_Parser extends Text_LanguageDetect
      * @access  private
      * @param   string  $string     string to be parsed
      */
-    function Text_LanguageDetect_Parser($string, $db=null, $unicode_db=null) {
-               if (isset($db)) $this->_db_filename = $db;
-               if (isset($unicode_db)) $this->_unicode_db_filename = $unicode_db;      
+    function Text_LanguageDetect_Parser($string) {
         $this->_string = $string;
     }
 
     /**
      * Returns true if a string is suitable for parsing
      *
-     * @static
-     * @access  public
      * @param   string  $str    input string to test
      * @return  bool            true if acceptable, false if not
      */
-    function validateString($str) {
+    public static function validateString($str) {
         if (!empty($str) && strlen($str) > 3 && preg_match('/\S/', $str)) {
             return true;
         } else {
@@ -222,8 +218,7 @@ class Text_LanguageDetect_Parser extends Text_LanguageDetect
 
         // unicode startup
         if ($this->_compile_unicode) {
-            $blocks =& $this->_read_unicode_block_db();
-
+            $blocks = $this->_read_unicode_block_db();
             $block_count = count($blocks);
 
             $skipped_count = 0;
@@ -349,6 +344,4 @@ class Text_LanguageDetect_Parser extends Text_LanguageDetect
     }
 }
 
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-?>
+/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
\ No newline at end of file
old mode 100644 (file)
new mode 100755 (executable)
index 2e8991c..4fa3ba6
-<?php\r
-/** \r
-* Arc90's Readability ported to PHP for FiveFilters.org\r
-* Based on readability.js version 1.7.1 (without multi-page support)\r
-* Updated to allow HTML5 parsing with html5lib\r
-* Updated with lightClean mode to preserve more images and youtube/vimeo/viddler embeds\r
-* ------------------------------------------------------\r
-* Original URL: http://lab.arc90.com/experiments/readability/js/readability.js\r
-* Arc90's project URL: http://lab.arc90.com/experiments/readability/\r
-* JS Source: http://code.google.com/p/arc90labs-readability\r
-* Ported by: Keyvan Minoukadeh, http://www.keyvan.net\r
-* More information: http://fivefilters.org/content-only/\r
-* License: Apache License, Version 2.0\r
-* Requires: PHP5\r
-* Date: 2012-09-19\r
-* \r
-* Differences between the PHP port and the original\r
-* ------------------------------------------------------\r
-* Arc90's Readability is designed to run in the browser. It works on the DOM \r
-* tree (the parsed HTML) after the page's CSS styles have been applied and \r
-* Javascript code executed. This PHP port does not run inside a browser. \r
-* We use PHP's ability to parse HTML to build our DOM tree, but we cannot \r
-* rely on CSS or Javascript support. As such, the results will not always \r
-* match Arc90's Readability. (For example, if a web page contains CSS style \r
-* rules or Javascript code which hide certain HTML elements from display, \r
-* Arc90's Readability will dismiss those from consideration but our PHP port, \r
-* unable to understand CSS or Javascript, will not know any better.)\r
-* \r
-* Another significant difference is that the aim of Arc90's Readability is \r
-* to re-present the main content block of a given web page so users can \r
-* read it more easily in their browsers. Correct identification, clean up, \r
-* and separation of the content block is only a part of this process. \r
-* This PHP port is only concerned with this part, it does not include code \r
-* that relates to presentation in the browser - Arc90 already do \r
-* that extremely well, and for PDF output there's FiveFilters.org's \r
-* PDF Newspaper: http://fivefilters.org/pdf-newspaper/.\r
-* \r
-* Finally, this class contains methods that might be useful for developers \r
-* working on HTML document fragments. So without deviating too much from \r
-* the original code (which I don't want to do because it makes debugging \r
-* and updating more difficult), I've tried to make it a little more \r
-* developer friendly. You should be able to use the methods here on \r
-* existing DOMElement objects without passing an entire HTML document to \r
-* be parsed.\r
-*/\r
-\r
-// This class allows us to do JavaScript like assignements to innerHTML\r
-require_once(dirname(__FILE__).'/JSLikeHTMLElement.php');\r
-\r
-// Alternative usage (for testing only!)\r
-// uncomment the lines below and call Readability.php in your browser \r
-// passing it the URL of the page you'd like content from, e.g.:\r
-// Readability.php?url=http://medialens.org/alerts/09/090615_the_guardian_climate.php\r
-\r
-/*\r
-if (!isset($_GET['url']) || $_GET['url'] == '') {\r
-       die('Please pass a URL to the script. E.g. Readability.php?url=bla.com/story.html');\r
-}\r
-$url = $_GET['url'];\r
-if (!preg_match('!^https?://!i', $url)) $url = 'http://'.$url;\r
-$html = file_get_contents($url);\r
-$r = new Readability($html, $url);\r
-$r->init();\r
-echo $r->articleContent->innerHTML;\r
-*/\r
-\r
-class Readability\r
-{\r
-       public $version = '1.7.1-without-multi-page';\r
-       public $convertLinksToFootnotes = false;\r
-       public $revertForcedParagraphElements = true;\r
-       public $articleTitle;\r
-       public $articleContent;\r
-       public $dom;\r
-       public $url = null; // optional - URL where HTML was retrieved\r
-       public $debug = false;\r
-       public $lightClean = true; // preserves more content (experimental) added 2012-09-19\r
-       protected $body = null; // \r
-       protected $bodyCache = null; // Cache the body HTML in case we need to re-use it later\r
-       protected $flags = 7; // 1 | 2 | 4;   // Start with all flags set.\r
-       protected $success = false; // indicates whether we were able to extract or not\r
-       \r
+<?php
+/** 
+* Arc90's Readability ported to PHP for FiveFilters.org
+* Based on readability.js version 1.7.1 (without multi-page support)
+* Updated to allow HTML5 parsing with html5lib
+* Updated with lightClean mode to preserve more images and youtube/vimeo/viddler embeds
+* ------------------------------------------------------
+* Original URL: http://lab.arc90.com/experiments/readability/js/readability.js
+* Arc90's project URL: http://lab.arc90.com/experiments/readability/
+* JS Source: http://code.google.com/p/arc90labs-readability
+* Ported by: Keyvan Minoukadeh, http://www.keyvan.net
+* More information: http://fivefilters.org/content-only/
+* License: Apache License, Version 2.0
+* Requires: PHP5
+* Date: 2012-09-19
+* 
+* Differences between the PHP port and the original
+* ------------------------------------------------------
+* Arc90's Readability is designed to run in the browser. It works on the DOM 
+* tree (the parsed HTML) after the page's CSS styles have been applied and 
+* Javascript code executed. This PHP port does not run inside a browser. 
+* We use PHP's ability to parse HTML to build our DOM tree, but we cannot 
+* rely on CSS or Javascript support. As such, the results will not always 
+* match Arc90's Readability. (For example, if a web page contains CSS style 
+* rules or Javascript code which hide certain HTML elements from display, 
+* Arc90's Readability will dismiss those from consideration but our PHP port, 
+* unable to understand CSS or Javascript, will not know any better.)
+* 
+* Another significant difference is that the aim of Arc90's Readability is 
+* to re-present the main content block of a given web page so users can 
+* read it more easily in their browsers. Correct identification, clean up, 
+* and separation of the content block is only a part of this process. 
+* This PHP port is only concerned with this part, it does not include code 
+* that relates to presentation in the browser - Arc90 already do 
+* that extremely well, and for PDF output there's FiveFilters.org's 
+* PDF Newspaper: http://fivefilters.org/pdf-newspaper/.
+* 
+* Finally, this class contains methods that might be useful for developers 
+* working on HTML document fragments. So without deviating too much from 
+* the original code (which I don't want to do because it makes debugging 
+* and updating more difficult), I've tried to make it a little more 
+* developer friendly. You should be able to use the methods here on 
+* existing DOMElement objects without passing an entire HTML document to 
+* be parsed.
+*/
+
+// This class allows us to do JavaScript like assignements to innerHTML
+require_once(dirname(__FILE__).'/JSLikeHTMLElement.php');
+
+// Alternative usage (for testing only!)
+// uncomment the lines below and call Readability.php in your browser 
+// passing it the URL of the page you'd like content from, e.g.:
+// Readability.php?url=http://medialens.org/alerts/09/090615_the_guardian_climate.php
+
+/*
+if (!isset($_GET['url']) || $_GET['url'] == '') {
+       die('Please pass a URL to the script. E.g. Readability.php?url=bla.com/story.html');
+}
+$url = $_GET['url'];
+if (!preg_match('!^https?://!i', $url)) $url = 'http://'.$url;
+$html = file_get_contents($url);
+$r = new Readability($html, $url);
+$r->init();
+echo $r->articleContent->innerHTML;
+*/
+
+class Readability
+{
+       public $version = '1.7.1-without-multi-page';
+       public $convertLinksToFootnotes = false;
+       public $revertForcedParagraphElements = true;
+       public $articleTitle;
+       public $articleContent;
+       public $dom;
+       public $url = null; // optional - URL where HTML was retrieved
+       public $debug = false;
+       public $lightClean = true; // preserves more content (experimental) added 2012-09-19
+       protected $body = null; // 
+       protected $bodyCache = null; // Cache the body HTML in case we need to re-use it later
+       protected $flags = 7; // 1 | 2 | 4;   // Start with all flags set.
+       protected $success = false; // indicates whether we were able to extract or not
+       
+       /**
+       * All of the regular expressions in use within readability.
+       * Defined up here so we don't instantiate them repeatedly in loops.
+       **/
+       public $regexps = array(
+               'unlikelyCandidates' => '/combx|comment|community|disqus|extra|foot|header|menu|remark|rss|shoutbox|sidebar|sponsor|ad-break|agegate|pagination|pager|popup/i',
+               'okMaybeItsACandidate' => '/and|article|body|column|main|shadow/i',
+               'positive' => '/article|body|content|entry|hentry|main|page|attachment|pagination|post|text|blog|story/i',
+               'negative' => '/combx|comment|com-|contact|foot|footer|_nav|footnote|masthead|media|meta|outbrain|promo|related|scroll|shoutbox|sidebar|sponsor|shopping|tags|tool|widget/i',
+               'divToPElements' => '/<(a|blockquote|dl|div|img|ol|p|pre|table|ul)/i',
+               'replaceBrs' => '/(<br[^>]*>[ \n\r\t]*){2,}/i',
+               'replaceFonts' => '/<(\/?)font[^>]*>/i',
+               // 'trimRe' => '/^\s+|\s+$/g', // PHP has trim()
+               'normalize' => '/\s{2,}/',
+               'killBreaks' => '/(<br\s*\/?>(\s|&nbsp;?)*){1,}/',
+               'video' => '!//(player\.|www\.)?(youtube|vimeo|viddler)\.com!i',
+               'skipFootnoteLink' => '/^\s*(\[?[a-z0-9]{1,2}\]?|^|edit|citation needed)\s*$/i'
+       );      
+       
+       /* constants */
+       const FLAG_STRIP_UNLIKELYS = 1;
+       const FLAG_WEIGHT_CLASSES = 2;
+       const FLAG_CLEAN_CONDITIONALLY = 4;
+       
+       /**
+       * Create instance of Readability
+       * @param string UTF-8 encoded string
+       * @param string (optional) URL associated with HTML (used for footnotes)
+       * @param string which parser to use for turning raw HTML into a DOMDocument (either 'libxml' or 'html5lib')
+       */      
+       function __construct($html, $url=null, $parser='libxml')
+       {
+               $this->url = $url;
+               /* Turn all double br's into p's */
+               $html = preg_replace($this->regexps['replaceBrs'], '</p><p>', $html);
+               $html = preg_replace($this->regexps['replaceFonts'], '<$1span>', $html);
+               $html = mb_convert_encoding($html, 'HTML-ENTITIES', "UTF-8");
+               if (trim($html) == '') $html = '<html></html>';
+               if ($parser=='html5lib' && ($this->dom = HTML5_Parser::parse($html))) {
+                       // all good
+               } else {
+                       $this->dom = new DOMDocument();
+                       $this->dom->preserveWhiteSpace = false;
+                       @$this->dom->loadHTML($html);
+               }
+               $this->dom->registerNodeClass('DOMElement', 'JSLikeHTMLElement');
+       }
+
+       /**
+       * Get article title element
+       * @return DOMElement
+       */
+       public function getTitle() {
+               return $this->articleTitle;
+       }
+       
+       /**
+       * Get article content element
+       * @return DOMElement
+       */
+       public function getContent() {
+               return $this->articleContent;
+       }       
+       
+       /**
+       * Runs readability.
+       * 
+       * Workflow:
+       *  1. Prep the document by removing script tags, css, etc.
+       *  2. Build readability's DOM tree.
+       *  3. Grab the article content from the current dom tree.
+       *  4. Replace the current DOM tree with the new one.
+       *  5. Read peacefully.
+       *
+       * @return boolean true if we found content, false otherwise
+       **/
+       public function init()
+       {
+               if (!isset($this->dom->documentElement)) return false;
+               $this->removeScripts($this->dom);
+               //die($this->getInnerHTML($this->dom->documentElement));
+               
+               // Assume successful outcome
+               $this->success = true;
+
+               $bodyElems = $this->dom->getElementsByTagName('body');
+               if ($bodyElems->length > 0) {
+                       if ($this->bodyCache == null) {
+                               $this->bodyCache = $bodyElems->item(0)->innerHTML;
+                       }
+                       if ($this->body == null) {
+                               $this->body = $bodyElems->item(0);
+                       }
+               }
+
+               $this->prepDocument();
+               
+               //die($this->dom->documentElement->parentNode->nodeType);
+               //$this->setInnerHTML($this->dom->documentElement, $this->getInnerHTML($this->dom->documentElement));
+               //die($this->getInnerHTML($this->dom->documentElement));
+
+               /* Build readability's DOM tree */
+               $overlay        = $this->dom->createElement('div');
+               $innerDiv       = $this->dom->createElement('div');
+               $articleTitle   = $this->getArticleTitle();
+               $articleContent = $this->grabArticle();
+
+               if (!$articleContent) {
+                       $this->success = false;
+                       $articleContent = $this->dom->createElement('div');
+                       $articleContent->setAttribute('id', 'readability-content');
+                       $articleContent->innerHTML = '<p>Sorry, Readability was unable to parse this page for content.</p>';            
+               }
+               
+               $overlay->setAttribute('id', 'readOverlay');
+               $innerDiv->setAttribute('id', 'readInner');
+
+               /* Glue the structure of our document together. */
+               $innerDiv->appendChild($articleTitle);
+               $innerDiv->appendChild($articleContent);
+               $overlay->appendChild($innerDiv);
+               
+               /* Clear the old HTML, insert the new content. */
+               $this->body->innerHTML = '';
+               $this->body->appendChild($overlay);
+               //document.body.insertBefore(overlay, document.body.firstChild);
+               $this->body->removeAttribute('style');
+
+               $this->postProcessContent($articleContent);
+               
+               // Set title and content instance variables
+               $this->articleTitle = $articleTitle;
+               $this->articleContent = $articleContent;
+               
+               return $this->success;
+       }
+       
+       /**
+       * Debug
+       */
+       protected function dbg($msg) {
+               if ($this->debug) echo '* ',$msg, "\n";
+       }
+       
+       /**
+       * Run any post-process modifications to article content as necessary.
+       *
+       * @param DOMElement
+       * @return void
+       */
+       public function postProcessContent($articleContent) {
+               if ($this->convertLinksToFootnotes && !preg_match('/wikipedia\.org/', @$this->url)) { 
+                       $this->addFootnotes($articleContent);
+               }
+       }
+       
+       /**
+       * Get the article title as an H1.
+       *
+       * @return DOMElement
+       */
+       protected function getArticleTitle() {
+               $curTitle = '';
+               $origTitle = '';
+
+               try {
+                       $curTitle = $origTitle = $this->getInnerText($this->dom->getElementsByTagName('title')->item(0));
+               } catch(Exception $e) {}
+               
+               if (preg_match('/ [\|\-] /', $curTitle))
+               {
+                       $curTitle = preg_replace('/(.*)[\|\-] .*/i', '$1', $origTitle);
+                       
+                       if (count(explode(' ', $curTitle)) < 3) {
+                               $curTitle = preg_replace('/[^\|\-]*[\|\-](.*)/i', '$1', $origTitle);
+                       }
+               }
+               else if (strpos($curTitle, ': ') !== false)
+               {
+                       $curTitle = preg_replace('/.*:(.*)/i', '$1', $origTitle);
+
+                       if (count(explode(' ', $curTitle)) < 3) {
+                               $curTitle = preg_replace('/[^:]*[:](.*)/i','$1', $origTitle);
+                       }
+               }
+               else if(strlen($curTitle) > 150 || strlen($curTitle) < 15)
+               {
+                       $hOnes = $this->dom->getElementsByTagName('h1');
+                       if($hOnes->length == 1)
+                       {
+                               $curTitle = $this->getInnerText($hOnes->item(0));
+                       }
+               }
+
+               $curTitle = trim($curTitle);
+
+               if (count(explode(' ', $curTitle)) <= 4) {
+                       $curTitle = $origTitle;
+               }
+               
+               $articleTitle = $this->dom->createElement('h1');
+               $articleTitle->innerHTML = $curTitle;
+               
+               return $articleTitle;
+       }
+       
+       /**
+       * Prepare the HTML document for readability to scrape it.
+       * This includes things like stripping javascript, CSS, and handling terrible markup.
+       * 
+       * @return void
+       **/
+       protected function prepDocument() {
+               /**
+               * In some cases a body element can't be found (if the HTML is totally hosed for example)
+               * so we create a new body node and append it to the document.
+               */
+               if ($this->body == null)
+               {
+                       $this->body = $this->dom->createElement('body');
+                       $this->dom->documentElement->appendChild($this->body);
+               }
+               $this->body->setAttribute('id', 'readabilityBody');
+
+               /* Remove all style tags in head */
+               $styleTags = $this->dom->getElementsByTagName('style');
+               for ($i = $styleTags->length-1; $i >= 0; $i--)
+               {
+                       $styleTags->item($i)->parentNode->removeChild($styleTags->item($i));
+               }
+
+               /* Turn all double br's into p's */
+               /* Note, this is pretty costly as far as processing goes. Maybe optimize later. */
+               //document.body.innerHTML = document.body.innerHTML.replace(readability.regexps.replaceBrs, '</p><p>').replace(readability.regexps.replaceFonts, '<$1span>');
+               // We do this in the constructor for PHP as that's when we have raw HTML - before parsing it into a DOM tree.
+               // Manipulating innerHTML as it's done in JS is not possible in PHP.
+       }
+
+       /**
+       * For easier reading, convert this document to have footnotes at the bottom rather than inline links.
+       * @see http://www.roughtype.com/archives/2010/05/experiments_in.php
+       *
+       * @return void
+       **/
+       public function addFootnotes($articleContent) {
+               $footnotesWrapper = $this->dom->createElement('div');
+               $footnotesWrapper->setAttribute('id', 'readability-footnotes');
+               $footnotesWrapper->innerHTML = '<h3>References</h3>';
+               
+               $articleFootnotes = $this->dom->createElement('ol');
+               $articleFootnotes->setAttribute('id', 'readability-footnotes-list');
+               $footnotesWrapper->appendChild($articleFootnotes);
+               
+               $articleLinks = $articleContent->getElementsByTagName('a');
+               
+               $linkCount = 0;
+               for ($i = 0; $i < $articleLinks->length; $i++)
+               {
+                       $articleLink  = $articleLinks->item($i);
+                       $footnoteLink = $articleLink->cloneNode(true);
+                       $refLink      = $this->dom->createElement('a');
+                       $footnote     = $this->dom->createElement('li');
+                       $linkDomain   = @parse_url($footnoteLink->getAttribute('href'), PHP_URL_HOST);
+                       if (!$linkDomain && isset($this->url)) $linkDomain = @parse_url($this->url, PHP_URL_HOST);
+                       //linkDomain   = footnoteLink.host ? footnoteLink.host : document.location.host,
+                       $linkText     = $this->getInnerText($articleLink);
+                       
+                       if ((strpos($articleLink->getAttribute('class'), 'readability-DoNotFootnote') !== false) || preg_match($this->regexps['skipFootnoteLink'], $linkText)) {
+                               continue;
+                       }
+                       
+                       $linkCount++;
+
+                       /** Add a superscript reference after the article link */
+                       $refLink->setAttribute('href', '#readabilityFootnoteLink-' . $linkCount);
+                       $refLink->innerHTML = '<small><sup>[' . $linkCount . ']</sup></small>';
+                       $refLink->setAttribute('class', 'readability-DoNotFootnote');
+                       $refLink->setAttribute('style', 'color: inherit;');
+                       
+                       //TODO: does this work or should we use DOMNode.isSameNode()?
+                       if ($articleLink->parentNode->lastChild == $articleLink) {
+                               $articleLink->parentNode->appendChild($refLink);
+                       } else {
+                               $articleLink->parentNode->insertBefore($refLink, $articleLink->nextSibling);
+                       }
+
+                       $articleLink->setAttribute('style', 'color: inherit; text-decoration: none;');
+                       $articleLink->setAttribute('name', 'readabilityLink-' . $linkCount);
+
+                       $footnote->innerHTML = '<small><sup><a href="#readabilityLink-' . $linkCount . '" title="Jump to Link in Article">^</a></sup></small> ';
+
+                       $footnoteLink->innerHTML = ($footnoteLink->getAttribute('title') != '' ? $footnoteLink->getAttribute('title') : $linkText);
+                       $footnoteLink->setAttribute('name', 'readabilityFootnoteLink-' . $linkCount);
+                       
+                       $footnote->appendChild($footnoteLink);
+                       if ($linkDomain) $footnote->innerHTML = $footnote->innerHTML . '<small> (' . $linkDomain . ')</small>';
+                       
+                       $articleFootnotes->appendChild($footnote);
+               }
+
+               if ($linkCount > 0) {
+                       $articleContent->appendChild($footnotesWrapper);           
+               }
+       }
+
+       /**
+       * Reverts P elements with class 'readability-styled'
+       * to text nodes - which is what they were before.
+       *
+       * @param DOMElement
+       * @return void
+       */
+       function revertReadabilityStyledElements($articleContent) {
+               $xpath = new DOMXPath($articleContent->ownerDocument);
+               $elems = $xpath->query('.//p[@class="readability-styled"]', $articleContent);
+               //$elems = $articleContent->getElementsByTagName('p');
+               for ($i = $elems->length-1; $i >= 0; $i--) {
+                       $e = $elems->item($i);
+                       $e->parentNode->replaceChild($articleContent->ownerDocument->createTextNode($e->textContent), $e);
+                       //if ($e->hasAttribute('class') && $e->getAttribute('class') == 'readability-styled') {
+                       //      $e->parentNode->replaceChild($this->dom->createTextNode($e->textContent), $e);
+                       //}
+               }
+       }
+       
+       /**
+       * Prepare the article node for display. Clean out any inline styles,
+       * iframes, forms, strip extraneous <p> tags, etc.
+       *
+       * @param DOMElement
+       * @return void
+       */
+       function prepArticle($articleContent) {
+               $this->cleanStyles($articleContent);
+               $this->killBreaks($articleContent);
+               if ($this->revertForcedParagraphElements) {
+                       $this->revertReadabilityStyledElements($articleContent);
+               }
+
+               /* Clean out junk from the article content */
+               $this->cleanConditionally($articleContent, 'form');
+               $this->clean($articleContent, 'object');
+               $this->clean($articleContent, 'h1');
+
+               /**
+               * If there is only one h2, they are probably using it
+               * as a header and not a subheader, so remove it since we already have a header.
+               ***/
+               if (!$this->lightClean && ($articleContent->getElementsByTagName('h2')->length == 1)) {
+                       $this->clean($articleContent, 'h2'); 
+               }
+               $this->clean($articleContent, 'iframe');
+
+               $this->cleanHeaders($articleContent);
+
+               /* Do these last as the previous stuff may have removed junk that will affect these */
+               $this->cleanConditionally($articleContent, 'table');
+               $this->cleanConditionally($articleContent, 'ul');
+               $this->cleanConditionally($articleContent, 'div');
+
+               /* Remove extra paragraphs */
+               $articleParagraphs = $articleContent->getElementsByTagName('p');
+               for ($i = $articleParagraphs->length-1; $i >= 0; $i--)
+               {
+                       $imgCount    = $articleParagraphs->item($i)->getElementsByTagName('img')->length;
+                       $embedCount  = $articleParagraphs->item($i)->getElementsByTagName('embed')->length;
+                       $objectCount = $articleParagraphs->item($i)->getElementsByTagName('object')->length;
+                       $iframeCount = $articleParagraphs->item($i)->getElementsByTagName('iframe')->length;
+                       
+                       if ($imgCount === 0 && $embedCount === 0 && $objectCount === 0 && $iframeCount === 0 && $this->getInnerText($articleParagraphs->item($i), false) == '')
+                       {
+                               $articleParagraphs->item($i)->parentNode->removeChild($articleParagraphs->item($i));
+                       }
+               }
+
+               try {
+                       $articleContent->innerHTML = preg_replace('/<br[^>]*>\s*<p/i', '<p', $articleContent->innerHTML);
+                       //articleContent.innerHTML = articleContent.innerHTML.replace(/<br[^>]*>\s*<p/gi, '<p');      
+               }
+               catch (Exception $e) {
+                       $this->dbg("Cleaning innerHTML of breaks failed. This is an IE strict-block-elements bug. Ignoring.: " . $e);
+               }
+       }
+       
+       /**
+       * Initialize a node with the readability object. Also checks the
+       * className/id for special names to add to its score.
+       *
+       * @param Element
+       * @return void
+       **/
+       protected function initializeNode($node) {
+               $readability = $this->dom->createAttribute('readability');
+               $readability->value = 0; // this is our contentScore
+               $node->setAttributeNode($readability);                   
+
+               switch (strtoupper($node->tagName)) { // unsure if strtoupper is needed, but using it just in case
+                       case 'DIV':
+                               $readability->value += 5;
+                               break;
+
+                       case 'PRE':
+                       case 'TD':
+                       case 'BLOCKQUOTE':
+                               $readability->value += 3;
+                               break;
+                               
+                       case 'ADDRESS':
+                       case 'OL':
+                       case 'UL':
+                       case 'DL':
+                       case 'DD':
+                       case 'DT':
+                       case 'LI':
+                       case 'FORM':
+                               $readability->value -= 3;
+                               break;
+
+                       case 'H1':
+                       case 'H2':
+                       case 'H3':
+                       case 'H4':
+                       case 'H5':
+                       case 'H6':
+                       case 'TH':
+                               $readability->value -= 5;
+                               break;
+               }
+               $readability->value += $this->getClassWeight($node);
+       }
+       
+       /***
+       * grabArticle - Using a variety of metrics (content score, classname, element types), find the content that is
+       *               most likely to be the stuff a user wants to read. Then return it wrapped up in a div.
+       *
+       * @return DOMElement
+       **/
+       protected function grabArticle($page=null) {
+               $stripUnlikelyCandidates = $this->flagIsActive(self::FLAG_STRIP_UNLIKELYS);
+               if (!$page) $page = $this->dom;
+               $allElements = $page->getElementsByTagName('*');
+               /**
+               * First, node prepping. Trash nodes that look cruddy (like ones with the class name "comment", etc), and turn divs
+               * into P tags where they have been used inappropriately (as in, where they contain no other block level elements.)
+               *
+               * Note: Assignment from index for performance. See http://www.peachpit.com/articles/article.aspx?p=31567&seqNum=5
+               * TODO: Shouldn't this be a reverse traversal?
+               **/
+               $node = null;
+               $nodesToScore = array();
+               for ($nodeIndex = 0; ($node = $allElements->item($nodeIndex)); $nodeIndex++) {
+               //for ($nodeIndex=$targetList->length-1; $nodeIndex >= 0; $nodeIndex--) {
+                       //$node = $targetList->item($nodeIndex);
+                       $tagName = strtoupper($node->tagName);
+                       /* Remove unlikely candidates */
+                       if ($stripUnlikelyCandidates) {
+                               $unlikelyMatchString = $node->getAttribute('class') . $node->getAttribute('id');
+                               if (
+                                       preg_match($this->regexps['unlikelyCandidates'], $unlikelyMatchString) &&
+                                       !preg_match($this->regexps['okMaybeItsACandidate'], $unlikelyMatchString) &&
+                                       $tagName != 'BODY'
+                               )
+                               {
+                                       $this->dbg('Removing unlikely candidate - ' . $unlikelyMatchString);
+                                       //$nodesToRemove[] = $node;
+                                       $node->parentNode->removeChild($node);
+                                       $nodeIndex--;
+                                       continue;
+                               }               
+                       }
+
+                       if ($tagName == 'P' || $tagName == 'TD' || $tagName == 'PRE') {
+                               $nodesToScore[] = $node;
+                       }
+
+                       /* Turn all divs that don't have children block level elements into p's */
+                       if ($tagName == 'DIV') {
+                               if (!preg_match($this->regexps['divToPElements'], $node->innerHTML)) {
+                                       //$this->dbg('Altering div to p');
+                                       $newNode = $this->dom->createElement('p');
+                                       try {
+                                               $newNode->innerHTML = $node->innerHTML;
+                                               //$nodesToReplace[] = array('new'=>$newNode, 'old'=>$node);
+                                               $node->parentNode->replaceChild($newNode, $node);
+                                               $nodeIndex--;
+                                               $nodesToScore[] = $node; // or $newNode?
+                                       }
+                                       catch(Exception $e) {
+                                               $this->dbg('Could not alter div to p, reverting back to div.: ' . $e);
+                                       }
+                               }
+                               else
+                               {
+                                       /* EXPERIMENTAL */
+                                       // TODO: change these p elements back to text nodes after processing
+                                       for ($i = 0, $il = $node->childNodes->length; $i < $il; $i++) {
+                                               $childNode = $node->childNodes->item($i);
+                                               if ($childNode->nodeType == 3) { // XML_TEXT_NODE
+                                                       //$this->dbg('replacing text node with a p tag with the same content.');
+                                                       $p = $this->dom->createElement('p');
+                                                       $p->innerHTML = $childNode->nodeValue;
+                                                       $p->setAttribute('style', 'display: inline;');
+                                                       $p->setAttribute('class', 'readability-styled');
+                                                       $childNode->parentNode->replaceChild($p, $childNode);
+                                               }
+                                       }
+                               }
+                       }
+               }
+               
+               /**
+               * Loop through all paragraphs, and assign a score to them based on how content-y they look.
+               * Then add their score to their parent node.
+               *
+               * A score is determined by things like number of commas, class names, etc. Maybe eventually link density.
+               **/
+               $candidates = array();
+               for ($pt=0; $pt < count($nodesToScore); $pt++) {
+                       $parentNode      = $nodesToScore[$pt]->parentNode;
+                       // $grandParentNode = $parentNode ? $parentNode->parentNode : null;
+                       $grandParentNode = !$parentNode ? null : (($parentNode->parentNode instanceof DOMElement) ? $parentNode->parentNode : null);
+                       $innerText       = $this->getInnerText($nodesToScore[$pt]);
+
+                       if (!$parentNode || !isset($parentNode->tagName)) {
+                               continue;
+                       }
+
+                       /* If this paragraph is less than 25 characters, don't even count it. */
+                       if(strlen($innerText) < 25) {
+                               continue;
+                       }
+
+                       /* Initialize readability data for the parent. */
+                       if (!$parentNode->hasAttribute('readability')) 
+                       {
+                               $this->initializeNode($parentNode);
+                               $candidates[] = $parentNode;
+                       }
+
+                       /* Initialize readability data for the grandparent. */
+                       if ($grandParentNode && !$grandParentNode->hasAttribute('readability') && isset($grandParentNode->tagName))
+                       {
+                               $this->initializeNode($grandParentNode);
+                               $candidates[] = $grandParentNode;
+                       }
+
+                       $contentScore = 0;
+
+                       /* Add a point for the paragraph itself as a base. */
+                       $contentScore++;
+
+                       /* Add points for any commas within this paragraph */
+                       $contentScore += count(explode(',', $innerText));
+                       
+                       /* For every 100 characters in this paragraph, add another point. Up to 3 points. */
+                       $contentScore += min(floor(strlen($innerText) / 100), 3);
+                       
+                       /* Add the score to the parent. The grandparent gets half. */
+                       $parentNode->getAttributeNode('readability')->value += $contentScore;
+
+                       if ($grandParentNode) {
+                               $grandParentNode->getAttributeNode('readability')->value += $contentScore/2;             
+                       }
+               }
+
+               /**
+               * After we've calculated scores, loop through all of the possible candidate nodes we found
+               * and find the one with the highest score.
+               **/
+               $topCandidate = null;
+               for ($c=0, $cl=count($candidates); $c < $cl; $c++)
+               {
+                       /**
+                       * Scale the final candidates score based on link density. Good content should have a
+                       * relatively small link density (5% or less) and be mostly unaffected by this operation.
+                       **/
+                       $readability = $candidates[$c]->getAttributeNode('readability');
+                       $readability->value = $readability->value * (1-$this->getLinkDensity($candidates[$c]));
+
+                       $this->dbg('Candidate: ' . $candidates[$c]->tagName . ' (' . $candidates[$c]->getAttribute('class') . ':' . $candidates[$c]->getAttribute('id') . ') with score ' . $readability->value);
+
+                       if (!$topCandidate || $readability->value > (int)$topCandidate->getAttribute('readability')) {
+                               $topCandidate = $candidates[$c];
+                       }
+               }
+
+               /**
+               * If we still have no top candidate, just use the body as a last resort.
+               * We also have to copy the body node so it is something we can modify.
+               **/
+               if ($topCandidate === null || strtoupper($topCandidate->tagName) == 'BODY')
+               {
+                       $topCandidate = $this->dom->createElement('div');
+                       if ($page instanceof DOMDocument) {
+                               if (!isset($page->documentElement)) {
+                                       // we don't have a body either? what a mess! :)
+                               } else {
+                                       $topCandidate->innerHTML = $page->documentElement->innerHTML;
+                                       $page->documentElement->innerHTML = '';
+                                       $this->reinitBody();
+                                       $page->documentElement->appendChild($topCandidate);
+                               }
+                       } else {
+                               $topCandidate->innerHTML = $page->innerHTML;
+                               $page->innerHTML = '';
+                               $page->appendChild($topCandidate);
+                       }
+                       $this->initializeNode($topCandidate);
+               }
+
+               /**
+               * Now that we have the top candidate, look through its siblings for content that might also be related.
+               * Things like preambles, content split by ads that we removed, etc.
+               **/
+               $articleContent        = $this->dom->createElement('div');
+               $articleContent->setAttribute('id', 'readability-content');
+               $siblingScoreThreshold = max(10, ((int)$topCandidate->getAttribute('readability')) * 0.2);
+               $siblingNodes          = $topCandidate->parentNode->childNodes;
+               if (!isset($siblingNodes)) {
+                       $siblingNodes = new stdClass;
+                       $siblingNodes->length = 0;
+               }
+
+               for ($s=0, $sl=$siblingNodes->length; $s < $sl; $s++)
+               {
+                       $siblingNode = $siblingNodes->item($s);
+                       $append      = false;
+
+                       $this->dbg('Looking at sibling node: ' . $siblingNode->nodeName . (($siblingNode->nodeType === XML_ELEMENT_NODE && $siblingNode->hasAttribute('readability')) ? (' with score ' . $siblingNode->getAttribute('readability')) : ''));
+
+                       //dbg('Sibling has score ' . ($siblingNode->readability ? siblingNode.readability.contentScore : 'Unknown'));
+
+                       if ($siblingNode === $topCandidate)
+                       // or if ($siblingNode->isSameNode($topCandidate))
+                       {
+                               $append = true;
+                       }
+
+                       $contentBonus = 0;
+                       /* Give a bonus if sibling nodes and top candidates have the example same classname */
+                       if ($siblingNode->nodeType === XML_ELEMENT_NODE && $siblingNode->getAttribute('class') == $topCandidate->getAttribute('class') && $topCandidate->getAttribute('class') != '') {
+                               $contentBonus += ((int)$topCandidate->getAttribute('readability')) * 0.2;
+                       }
+
+                       if ($siblingNode->nodeType === XML_ELEMENT_NODE && $siblingNode->hasAttribute('readability') && (((int)$siblingNode->getAttribute('readability')) + $contentBonus) >= $siblingScoreThreshold)
+                       {
+                               $append = true;
+                       }
+                       
+                       if (strtoupper($siblingNode->nodeName) == 'P') {
+                               $linkDensity = $this->getLinkDensity($siblingNode);
+                               $nodeContent = $this->getInnerText($siblingNode);
+                               $nodeLength  = strlen($nodeContent);
+                               
+                               if ($nodeLength > 80 && $linkDensity < 0.25)
+                               {
+                                       $append = true;
+                               }
+                               else if ($nodeLength < 80 && $linkDensity === 0 && preg_match('/\.( |$)/', $nodeContent))
+                               {
+                                       $append = true;
+                               }
+                       }
+
+                       if ($append)
+                       {
+                               $this->dbg('Appending node: ' . $siblingNode->nodeName);
+
+                               $nodeToAppend = null;
+                               $sibNodeName = strtoupper($siblingNode->nodeName);
+                               if ($sibNodeName != 'DIV' && $sibNodeName != 'P') {
+                                       /* We have a node that isn't a common block level element, like a form or td tag. Turn it into a div so it doesn't get filtered out later by accident. */
+                                       
+                                       $this->dbg('Altering siblingNode of ' . $sibNodeName . ' to div.');
+                                       $nodeToAppend = $this->dom->createElement('div');
+                                       try {
+                                               $nodeToAppend->setAttribute('id', $siblingNode->getAttribute('id'));
+                                               $nodeToAppend->innerHTML = $siblingNode->innerHTML;
+                                       }
+                                       catch(Exception $e)
+                                       {
+                                               $this->dbg('Could not alter siblingNode to div, reverting back to original.');
+                                               $nodeToAppend = $siblingNode;
+                                               $s--;
+                                               $sl--;
+                                       }
+                               } else {
+                                       $nodeToAppend = $siblingNode;
+                                       $s--;
+                                       $sl--;
+                               }
+                               
+                               /* To ensure a node does not interfere with readability styles, remove its classnames */
+                               $nodeToAppend->removeAttribute('class');
+
+                               /* Append sibling and subtract from our list because it removes the node when you append to another node */
+                               $articleContent->appendChild($nodeToAppend);
+                       }
+               }
+
+               /**
+               * So we have all of the content that we need. Now we clean it up for presentation.
+               **/
+               $this->prepArticle($articleContent);
+
+               /**
+               * Now that we've gone through the full algorithm, check to see if we got any meaningful content.
+               * If we didn't, we may need to re-run grabArticle with different flags set. This gives us a higher
+               * likelihood of finding the content, and the sieve approach gives us a higher likelihood of
+               * finding the -right- content.
+               **/
+               if (strlen($this->getInnerText($articleContent, false)) < 250)
+               {
+                       // TODO: find out why element disappears sometimes, e.g. for this URL http://www.businessinsider.com/6-hedge-fund-etfs-for-average-investors-2011-7
+                       // in the meantime, we check and create an empty element if it's not there.
+                       $this->reinitBody();
+                       
+                       if ($this->flagIsActive(self::FLAG_STRIP_UNLIKELYS)) {
+                               $this->removeFlag(self::FLAG_STRIP_UNLIKELYS);
+                               return $this->grabArticle($this->body);
+                       }
+                       else if ($this->flagIsActive(self::FLAG_WEIGHT_CLASSES)) {
+                               $this->removeFlag(self::FLAG_WEIGHT_CLASSES);
+                               return $this->grabArticle($this->body);              
+                       }
+                       else if ($this->flagIsActive(self::FLAG_CLEAN_CONDITIONALLY)) {
+                               $this->removeFlag(self::FLAG_CLEAN_CONDITIONALLY);
+                               return $this->grabArticle($this->body);
+                       }
+                       else {
+                               return false;
+                       }
+               }
+               return $articleContent;
+       }
+       
+       /**
+       * Remove script tags from document
+       *
+       * @param DOMElement
+       * @return void
+       */
+       public function removeScripts($doc) {
+               $scripts = $doc->getElementsByTagName('script');
+               for($i = $scripts->length-1; $i >= 0; $i--)
+               {
+                       $scripts->item($i)->parentNode->removeChild($scripts->item($i));
+               }
+       }
+       
+       /**
+       * Get the inner text of a node.
+       * This also strips out any excess whitespace to be found.
+       *
+       * @param DOMElement $
+       * @param boolean $normalizeSpaces (default: true)
+       * @return string
+       **/
+       public function getInnerText($e, $normalizeSpaces=true) {
+               $textContent = '';
+
+               if (!isset($e->textContent) || $e->textContent == '') {
+                       return '';
+               }
+
+               $textContent = trim($e->textContent);
+
+               if ($normalizeSpaces) {
+                       return preg_replace($this->regexps['normalize'], ' ', $textContent);
+               } else {
+                       return $textContent;
+               }
+       }
+
+       /**
+       * Get the number of times a string $s appears in the node $e.
+       *
+       * @param DOMElement $e
+       * @param string - what to count. Default is ","
+       * @return number (integer)
+       **/
+       public function getCharCount($e, $s=',') {
+               return substr_count($this->getInnerText($e), $s);
+       }
+
+       /**
+       * Remove the style attribute on every $e and under.
+       *
+       * @param DOMElement $e
+       * @return void
+       */
+       public function cleanStyles($e) {
+               if (!is_object($e)) return;
+               $elems = $e->getElementsByTagName('*');
+               foreach ($elems as $elem) {
+                       $elem->removeAttribute('style');
+               }
+       }
+       
+       /**
+       * Get the density of links as a percentage of the content
+       * This is the amount of text that is inside a link divided by the total text in the node.
+       * 
+       * @param DOMElement $e
+       * @return number (float)
+       */
+       public function getLinkDensity($e) {
+               $links      = $e->getElementsByTagName('a');
+               $textLength = strlen($this->getInnerText($e));
+               $linkLength = 0;
+               for ($i=0, $il=$links->length; $i < $il; $i++)
+               {
+                       $linkLength += strlen($this->getInnerText($links->item($i)));
+               }
+               if ($textLength > 0) {
+                       return $linkLength / $textLength;
+               } else {
+                       return 0;
+               }
+       }
+       
+       /**
+       * Get an elements class/id weight. Uses regular expressions to tell if this 
+       * element looks good or bad.
+       *
+       * @param DOMElement $e
+       * @return number (Integer)
+       */
+       public function getClassWeight($e) {
+               if(!$this->flagIsActive(self::FLAG_WEIGHT_CLASSES)) {
+                       return 0;
+               }
+
+               $weight = 0;
+
+               /* Look for a special classname */
+               if ($e->hasAttribute('class') && $e->getAttribute('class') != '')
+               {
+                       if (preg_match($this->regexps['negative'], $e->getAttribute('class'))) {
+                               $weight -= 25;
+                       }
+                       if (preg_match($this->regexps['positive'], $e->getAttribute('class'))) {
+                               $weight += 25;
+                       }
+               }
+
+               /* Look for a special ID */
+               if ($e->hasAttribute('id') && $e->getAttribute('id') != '')
+               {
+                       if (preg_match($this->regexps['negative'], $e->getAttribute('id'))) {
+                               $weight -= 25;
+                       }
+                       if (preg_match($this->regexps['positive'], $e->getAttribute('id'))) {
+                               $weight += 25;
+                       }
+               }
+               return $weight;
+       }
+
+       /**
+       * Remove extraneous break tags from a node.
+       *
+       * @param DOMElement $node
+       * @return void
+       */
+       public function killBreaks($node) {
+               $html = $node->innerHTML;
+               $html = preg_replace($this->regexps['killBreaks'], '<br />', $html);
+               $node->innerHTML = $html;
+       }
+
+       /**
+       * Clean a node of all elements of type "tag".
+       * (Unless it's a youtube/vimeo video. People love movies.)
+       *
+       * Updated 2012-09-18 to preserve youtube/vimeo iframes
+       *
+       * @param DOMElement $e
+       * @param string $tag
+       * @return void
+       */
+       public function clean($e, $tag) {
+               $targetList = $e->getElementsByTagName($tag);
+               $isEmbed = ($tag == 'iframe' || $tag == 'object' || $tag == 'embed');
+               
+               for ($y=$targetList->length-1; $y >= 0; $y--) {
+                       /* Allow youtube and vimeo videos through as people usually want to see those. */
+                       if ($isEmbed) {
+                               $attributeValues = '';
+                               for ($i=0, $il=$targetList->item($y)->attributes->length; $i < $il; $i++) {
+                                       $attributeValues .= $targetList->item($y)->attributes->item($i)->value . '|'; // DOMAttr? (TODO: test)
+                               }
+                               
+                               /* First, check the elements attributes to see if any of them contain youtube or vimeo */
+                               if (preg_match($this->regexps['video'], $attributeValues)) {
+                                       continue;
+                               }
+
+                               /* Then check the elements inside this element for the same. */
+                               if (preg_match($this->regexps['video'], $targetList->item($y)->innerHTML)) {
+                                       continue;
+                               }
+                       }
+                       $targetList->item($y)->parentNode->removeChild($targetList->item($y));
+               }
+       }
+       
+       /**
+       * Clean an element of all tags of type "tag" if they look fishy.
+       * "Fishy" is an algorithm based on content length, classnames, 
+       * link density, number of images & embeds, etc.
+       *
+       * @param DOMElement $e
+       * @param string $tag
+       * @return void
+       */
+       public function cleanConditionally($e, $tag) {
+               if (!$this->flagIsActive(self::FLAG_CLEAN_CONDITIONALLY)) {
+                       return;
+               }
+
+               $tagsList = $e->getElementsByTagName($tag);
+               $curTagsLength = $tagsList->length;
+
+               /**
+               * Gather counts for other typical elements embedded within.
+               * Traverse backwards so we can remove nodes at the same time without effecting the traversal.
+               *
+               * TODO: Consider taking into account original contentScore here.
+               */
+               for ($i=$curTagsLength-1; $i >= 0; $i--) {
+                       $weight = $this->getClassWeight($tagsList->item($i));
+                       $contentScore = ($tagsList->item($i)->hasAttribute('readability')) ? (int)$tagsList->item($i)->getAttribute('readability') : 0;
+                       
+                       $this->dbg('Cleaning Conditionally ' . $tagsList->item($i)->tagName . ' (' . $tagsList->item($i)->getAttribute('class') . ':' . $tagsList->item($i)->getAttribute('id') . ')' . (($tagsList->item($i)->hasAttribute('readability')) ? (' with score ' . $tagsList->item($i)->getAttribute('readability')) : ''));
+
+                       if ($weight + $contentScore < 0) {
+                               $tagsList->item($i)->parentNode->removeChild($tagsList->item($i));
+                       }
+                       else if ( $this->getCharCount($tagsList->item($i), ',') < 10) {
+                               /**
+                               * If there are not very many commas, and the number of
+                               * non-paragraph elements is more than paragraphs or other ominous signs, remove the element.
+                               **/
+                               $p      = $tagsList->item($i)->getElementsByTagName('p')->length;
+                               $img    = $tagsList->item($i)->getElementsByTagName('img')->length;
+                               $li     = $tagsList->item($i)->getElementsByTagName('li')->length-100;
+                               $input  = $tagsList->item($i)->getElementsByTagName('input')->length;
+                               $a              = $tagsList->item($i)->getElementsByTagName('a')->length;
+
+                               $embedCount = 0;
+                               $embeds = $tagsList->item($i)->getElementsByTagName('embed');
+                               for ($ei=0, $il=$embeds->length; $ei < $il; $ei++) {
+                                       if (preg_match($this->regexps['video'], $embeds->item($ei)->getAttribute('src'))) {
+                                               $embedCount++; 
+                                       }
+                               }
+                               $embeds = $tagsList->item($i)->getElementsByTagName('iframe');
+                               for ($ei=0, $il=$embeds->length; $ei < $il; $ei++) {
+                                       if (preg_match($this->regexps['video'], $embeds->item($ei)->getAttribute('src'))) {
+                                               $embedCount++; 
+                                       }
+                               }
+
+                               $linkDensity   = $this->getLinkDensity($tagsList->item($i));
+                               $contentLength = strlen($this->getInnerText($tagsList->item($i)));
+                               $toRemove      = false;
+
+                               if ($this->lightClean) {
+                                       $this->dbg('Light clean...');
+                                       if ( ($img > $p) && ($img > 4) ) {
+                                               $this->dbg(' more than 4 images and more image elements than paragraph elements');
+                                               $toRemove = true;
+                                       } else if ($li > $p && $tag != 'ul' && $tag != 'ol') {
+                                               $this->dbg(' too many <li> elements, and parent is not <ul> or <ol>');
+                                               $toRemove = true;
+                                       } else if ( $input > floor($p/3) ) {
+                                               $this->dbg(' too many <input> elements');
+                                               $toRemove = true; 
+                                       } else if ($contentLength < 10 && ($embedCount === 0 && ($img === 0 || $img > 2))) {
+                                               $this->dbg(' content length less than 10 chars, 0 embeds and either 0 images or more than 2 images');
+                                               $toRemove = true;
+                                       } else if($weight < 25 && $linkDensity > 0.2) {
+                                               $this->dbg(' weight smaller than 25 and link density above 0.2');
+                                               $toRemove = true;
+                                       } else if($a > 2 && ($weight >= 25 && $linkDensity > 0.5)) {
+                                               $this->dbg(' more than 2 links and weight above 25 but link density greater than 0.5');
+                                               $toRemove = true;
+                                       } else if($embedCount > 3) {
+                                               $this->dbg(' more than 3 embeds');
+                                               $toRemove = true;
+                                       }
+                               } else {
+                                       $this->dbg('Standard clean...');
+                                       if ( $img > $p ) {
+                                               $this->dbg(' more image elements than paragraph elements');
+                                               $toRemove = true;
+                                       } else if ($li > $p && $tag != 'ul' && $tag != 'ol') {
+                                               $this->dbg(' too many <li> elements, and parent is not <ul> or <ol>');
+                                               $toRemove = true;
+                                       } else if ( $input > floor($p/3) ) {
+                                               $this->dbg(' too many <input> elements');
+                                               $toRemove = true; 
+                                       } else if ($contentLength < 25 && ($img === 0 || $img > 2) ) {
+                                               $this->dbg(' content length less than 25 chars and 0 images, or more than 2 images');
+                                               $toRemove = true;
+                                       } else if($weight < 25 && $linkDensity > 0.2) {
+                                               $this->dbg(' weight smaller than 25 and link density above 0.2');
+                                               $toRemove = true;
+                                       } else if($weight >= 25 && $linkDensity > 0.5) {
+                                               $this->dbg(' weight above 25 but link density greater than 0.5');
+                                               $toRemove = true;
+                                       } else if(($embedCount == 1 && $contentLength < 75) || $embedCount > 1) {
+                                               $this->dbg(' 1 embed and content length smaller than 75 chars, or more than one embed');
+                                               $toRemove = true;
+                                       }
+                               }
+
+                               if ($toRemove) {
+                                       //$this->dbg('Removing: '.$tagsList->item($i)->innerHTML);
+                                       $tagsList->item($i)->parentNode->removeChild($tagsList->item($i));
+                               }
+                       }
+               }
+       }
+
+       /**
+       * Clean out spurious headers from an Element. Checks things like classnames and link density.
+       *
+       * @param DOMElement $e
+       * @return void
+       */
+       public function cleanHeaders($e) {
+               for ($headerIndex = 1; $headerIndex < 3; $headerIndex++) {
+                       $headers = $e->getElementsByTagName('h' . $headerIndex);
+                       for ($i=$headers->length-1; $i >=0; $i--) {
+                               if ($this->getClassWeight($headers->item($i)) < 0 || $this->getLinkDensity($headers->item($i)) > 0.33) {
+                                       $headers->item($i)->parentNode->removeChild($headers->item($i));
+                               }
+                       }
+               }
+       }
+
+       public function flagIsActive($flag) {
+               return ($this->flags & $flag) > 0;
+       }
+       
+       public function addFlag($flag) {
+               $this->flags = $this->flags | $flag;
+       }
+       
+       public function removeFlag($flag) {
+               $this->flags = $this->flags & ~$flag;
+       }
+       
        /**\r
-       * All of the regular expressions in use within readability.\r
-       * Defined up here so we don't instantiate them repeatedly in loops.\r
-       **/\r
-       public $regexps = array(\r
-               'unlikelyCandidates' => '/combx|comment|community|disqus|extra|foot|header|menu|remark|rss|shoutbox|sidebar|sponsor|ad-break|agegate|pagination|pager|popup/i',\r
-               'okMaybeItsACandidate' => '/and|article|body|column|main|shadow/i',\r
-               'positive' => '/article|body|content|entry|hentry|main|page|attachment|pagination|post|text|blog|story/i',\r
-               'negative' => '/combx|comment|com-|contact|foot|footer|_nav|footnote|masthead|media|meta|outbrain|promo|related|scroll|shoutbox|sidebar|sponsor|shopping|tags|tool|widget/i',\r
-               'divToPElements' => '/<(a|blockquote|dl|div|img|ol|p|pre|table|ul)/i',\r
-               'replaceBrs' => '/(<br[^>]*>[ \n\r\t]*){2,}/i',\r
-               'replaceFonts' => '/<(\/?)font[^>]*>/i',\r
-               // 'trimRe' => '/^\s+|\s+$/g', // PHP has trim()\r
-               'normalize' => '/\s{2,}/',\r
-               'killBreaks' => '/(<br\s*\/?>(\s|&nbsp;?)*){1,}/',\r
-               'video' => '!//(player\.|www\.)?(youtube|vimeo|viddler)\.com!i',\r
-               'skipFootnoteLink' => '/^\s*(\[?[a-z0-9]{1,2}\]?|^|edit|citation needed)\s*$/i'\r
-       );      \r
-       \r
-       /* constants */\r
-       const FLAG_STRIP_UNLIKELYS = 1;\r
-       const FLAG_WEIGHT_CLASSES = 2;\r
-       const FLAG_CLEAN_CONDITIONALLY = 4;\r
-       \r
-       /**\r
-       * Create instance of Readability\r
-       * @param string UTF-8 encoded string\r
-       * @param string (optional) URL associated with HTML (used for footnotes)\r
-       * @param string which parser to use for turning raw HTML into a DOMDocument (either 'libxml' or 'html5lib')\r
-       */      \r
-       function __construct($html, $url=null, $parser='libxml')\r
-       {\r
-               $this->url = $url;\r
-               /* Turn all double br's into p's */\r
-               $html = preg_replace($this->regexps['replaceBrs'], '</p><p>', $html);\r
-               $html = preg_replace($this->regexps['replaceFonts'], '<$1span>', $html);\r
-               $html = mb_convert_encoding($html, 'HTML-ENTITIES', "UTF-8");\r
-               if (trim($html) == '') $html = '<html></html>';\r
-               if ($parser=='html5lib' && ($this->dom = HTML5_Parser::parse($html))) {\r
-                       // all good\r
-               } else {\r
-                       $this->dom = new DOMDocument();\r
-                       $this->dom->preserveWhiteSpace = false;\r
-                       @$this->dom->loadHTML($html);\r
-               }\r
-               $this->dom->registerNodeClass('DOMElement', 'JSLikeHTMLElement');\r
-       }\r
-\r
-       /**\r
-       * Get article title element\r
-       * @return DOMElement\r
-       */\r
-       public function getTitle() {\r
-               return $this->articleTitle;\r
-       }\r
-       \r
-       /**\r
-       * Get article content element\r
-       * @return DOMElement\r
-       */\r
-       public function getContent() {\r
-               return $this->articleContent;\r
-       }       \r
-       \r
-       /**\r
-       * Runs readability.\r
-       * \r
-       * Workflow:\r
-       *  1. Prep the document by removing script tags, css, etc.\r
-       *  2. Build readability's DOM tree.\r
-       *  3. Grab the article content from the current dom tree.\r
-       *  4. Replace the current DOM tree with the new one.\r
-       *  5. Read peacefully.\r
-       *\r
-       * @return boolean true if we found content, false otherwise\r
-       **/\r
-       public function init()\r
-       {\r
-               if (!isset($this->dom->documentElement)) return false;\r
-               $this->removeScripts($this->dom);\r
-               //die($this->getInnerHTML($this->dom->documentElement));\r
-               \r
-               // Assume successful outcome\r
-               $this->success = true;\r
-\r
-               $bodyElems = $this->dom->getElementsByTagName('body');\r
-               if ($bodyElems->length > 0) {\r
-                       if ($this->bodyCache == null) {\r
-                               $this->bodyCache = $bodyElems->item(0)->innerHTML;\r
-                       }\r
-                       if ($this->body == null) {\r
-                               $this->body = $bodyElems->item(0);\r
-                       }\r
-               }\r
-\r
-               $this->prepDocument();\r
-               \r
-               //die($this->dom->documentElement->parentNode->nodeType);\r
-               //$this->setInnerHTML($this->dom->documentElement, $this->getInnerHTML($this->dom->documentElement));\r
-               //die($this->getInnerHTML($this->dom->documentElement));\r
-\r
-               /* Build readability's DOM tree */\r
-               $overlay        = $this->dom->createElement('div');\r
-               $innerDiv       = $this->dom->createElement('div');\r
-               $articleTitle   = $this->getArticleTitle();\r
-               $articleContent = $this->grabArticle();\r
-\r
-               if (!$articleContent) {\r
-                       $this->success = false;\r
-                       $articleContent = $this->dom->createElement('div');\r
-                       $articleContent->setAttribute('id', 'readability-content');\r
-                       $articleContent->innerHTML = '<p>Sorry, Readability was unable to parse this page for content.</p>';            \r
-               }\r
-               \r
-               $overlay->setAttribute('id', 'readOverlay');\r
-               $innerDiv->setAttribute('id', 'readInner');\r
-\r
-               /* Glue the structure of our document together. */\r
-               $innerDiv->appendChild($articleTitle);\r
-               $innerDiv->appendChild($articleContent);\r
-               $overlay->appendChild($innerDiv);\r
-               \r
-               /* Clear the old HTML, insert the new content. */\r
-               $this->body->innerHTML = '';\r
-               $this->body->appendChild($overlay);\r
-               //document.body.insertBefore(overlay, document.body.firstChild);\r
-               $this->body->removeAttribute('style');\r
-\r
-               $this->postProcessContent($articleContent);\r
-               \r
-               // Set title and content instance variables\r
-               $this->articleTitle = $articleTitle;\r
-               $this->articleContent = $articleContent;\r
-               \r
-               return $this->success;\r
-       }\r
-       \r
-       /**\r
-       * Debug\r
-       */\r
-       protected function dbg($msg) {\r
-               if ($this->debug) echo '* ',$msg, "\n";\r
-       }\r
-       \r
-       /**\r
-       * Run any post-process modifications to article content as necessary.\r
-       *\r
-       * @param DOMElement\r
-       * @return void\r
-       */\r
-       public function postProcessContent($articleContent) {\r
-               if ($this->convertLinksToFootnotes && !preg_match('/wikipedia\.org/', @$this->url)) { \r
-                       $this->addFootnotes($articleContent);\r
-               }\r
-       }\r
-       \r
-       /**\r
-       * Get the article title as an H1.\r
-       *\r
-       * @return DOMElement\r
-       */\r
-       protected function getArticleTitle() {\r
-               $curTitle = '';\r
-               $origTitle = '';\r
-\r
-               try {\r
-                       $curTitle = $origTitle = $this->getInnerText($this->dom->getElementsByTagName('title')->item(0));\r
-               } catch(Exception $e) {}\r
-               \r
-               if (preg_match('/ [\|\-] /', $curTitle))\r
-               {\r
-                       $curTitle = preg_replace('/(.*)[\|\-] .*/i', '$1', $origTitle);\r
-                       \r
-                       if (count(explode(' ', $curTitle)) < 3) {\r
-                               $curTitle = preg_replace('/[^\|\-]*[\|\-](.*)/i', '$1', $origTitle);\r
-                       }\r
-               }\r
-               else if (strpos($curTitle, ': ') !== false)\r
-               {\r
-                       $curTitle = preg_replace('/.*:(.*)/i', '$1', $origTitle);\r
-\r
-                       if (count(explode(' ', $curTitle)) < 3) {\r
-                               $curTitle = preg_replace('/[^:]*[:](.*)/i','$1', $origTitle);\r
-                       }\r
-               }\r
-               else if(strlen($curTitle) > 150 || strlen($curTitle) < 15)\r
-               {\r
-                       $hOnes = $this->dom->getElementsByTagName('h1');\r
-                       if($hOnes->length == 1)\r
-                       {\r
-                               $curTitle = $this->getInnerText($hOnes->item(0));\r
-                       }\r
-               }\r
-\r
-               $curTitle = trim($curTitle);\r
-\r
-               if (count(explode(' ', $curTitle)) <= 4) {\r
-                       $curTitle = $origTitle;\r
-               }\r
-               \r
-               $articleTitle = $this->dom->createElement('h1');\r
-               $articleTitle->innerHTML = $curTitle;\r
-               \r
-               return $articleTitle;\r
-       }\r
-       \r
-       /**\r
-       * Prepare the HTML document for readability to scrape it.\r
-       * This includes things like stripping javascript, CSS, and handling terrible markup.\r
-       * \r
-       * @return void\r
-       **/\r
-       protected function prepDocument() {\r
-               /**\r
-               * In some cases a body element can't be found (if the HTML is totally hosed for example)\r
-               * so we create a new body node and append it to the document.\r
-               */\r
-               if ($this->body == null)\r
-               {\r
-                       $this->body = $this->dom->createElement('body');\r
-                       $this->dom->documentElement->appendChild($this->body);\r
-               }\r
-               $this->body->setAttribute('id', 'readabilityBody');\r
-\r
-               /* Remove all style tags in head */\r
-               $styleTags = $this->dom->getElementsByTagName('style');\r
-               for ($i = $styleTags->length-1; $i >= 0; $i--)\r
-               {\r
-                       $styleTags->item($i)->parentNode->removeChild($styleTags->item($i));\r
-               }\r
-\r
-               /* Turn all double br's into p's */\r
-               /* Note, this is pretty costly as far as processing goes. Maybe optimize later. */\r
-               //document.body.innerHTML = document.body.innerHTML.replace(readability.regexps.replaceBrs, '</p><p>').replace(readability.regexps.replaceFonts, '<$1span>');\r
-               // We do this in the constructor for PHP as that's when we have raw HTML - before parsing it into a DOM tree.\r
-               // Manipulating innerHTML as it's done in JS is not possible in PHP.\r
-       }\r
-\r
-       /**\r
-       * For easier reading, convert this document to have footnotes at the bottom rather than inline links.\r
-       * @see http://www.roughtype.com/archives/2010/05/experiments_in.php\r
-       *\r
-       * @return void\r
-       **/\r
-       public function addFootnotes($articleContent) {\r
-               $footnotesWrapper = $this->dom->createElement('div');\r
-               $footnotesWrapper->setAttribute('id', 'readability-footnotes');\r
-               $footnotesWrapper->innerHTML = '<h3>References</h3>';\r
-               \r
-               $articleFootnotes = $this->dom->createElement('ol');\r
-               $articleFootnotes->setAttribute('id', 'readability-footnotes-list');\r
-               $footnotesWrapper->appendChild($articleFootnotes);\r
-               \r
-               $articleLinks = $articleContent->getElementsByTagName('a');\r
-               \r
-               $linkCount = 0;\r
-               for ($i = 0; $i < $articleLinks->length; $i++)\r
-               {\r
-                       $articleLink  = $articleLinks->item($i);\r
-                       $footnoteLink = $articleLink->cloneNode(true);\r
-                       $refLink      = $this->dom->createElement('a');\r
-                       $footnote     = $this->dom->createElement('li');\r
-                       $linkDomain   = @parse_url($footnoteLink->getAttribute('href'), PHP_URL_HOST);\r
-                       if (!$linkDomain && isset($this->url)) $linkDomain = @parse_url($this->url, PHP_URL_HOST);\r
-                       //linkDomain   = footnoteLink.host ? footnoteLink.host : document.location.host,\r
-                       $linkText     = $this->getInnerText($articleLink);\r
-                       \r
-                       if ((strpos($articleLink->getAttribute('class'), 'readability-DoNotFootnote') !== false) || preg_match($this->regexps['skipFootnoteLink'], $linkText)) {\r
-                               continue;\r
-                       }\r
-                       \r
-                       $linkCount++;\r
-\r
-                       /** Add a superscript reference after the article link */\r
-                       $refLink->setAttribute('href', '#readabilityFootnoteLink-' . $linkCount);\r
-                       $refLink->innerHTML = '<small><sup>[' . $linkCount . ']</sup></small>';\r
-                       $refLink->setAttribute('class', 'readability-DoNotFootnote');\r
-                       $refLink->setAttribute('style', 'color: inherit;');\r
-                       \r
-                       //TODO: does this work or should we use DOMNode.isSameNode()?\r
-                       if ($articleLink->parentNode->lastChild == $articleLink) {\r
-                               $articleLink->parentNode->appendChild($refLink);\r
-                       } else {\r
-                               $articleLink->parentNode->insertBefore($refLink, $articleLink->nextSibling);\r
-                       }\r
-\r
-                       $articleLink->setAttribute('style', 'color: inherit; text-decoration: none;');\r
-                       $articleLink->setAttribute('name', 'readabilityLink-' . $linkCount);\r
-\r
-                       $footnote->innerHTML = '<small><sup><a href="#readabilityLink-' . $linkCount . '" title="Jump to Link in Article">^</a></sup></small> ';\r
-\r
-                       $footnoteLink->innerHTML = ($footnoteLink->getAttribute('title') != '' ? $footnoteLink->getAttribute('title') : $linkText);\r
-                       $footnoteLink->setAttribute('name', 'readabilityFootnoteLink-' . $linkCount);\r
-                       \r
-                       $footnote->appendChild($footnoteLink);\r
-                       if ($linkDomain) $footnote->innerHTML = $footnote->innerHTML . '<small> (' . $linkDomain . ')</small>';\r
-                       \r
-                       $articleFootnotes->appendChild($footnote);\r
-               }\r
-\r
-               if ($linkCount > 0) {\r
-                       $articleContent->appendChild($footnotesWrapper);           \r
-               }\r
-       }\r
-\r
-       /**\r
-       * Reverts P elements with class 'readability-styled'\r
-       * to text nodes - which is what they were before.\r
-       *\r
-       * @param DOMElement\r
-       * @return void\r
-       */\r
-       function revertReadabilityStyledElements($articleContent) {\r
-               $xpath = new DOMXPath($articleContent->ownerDocument);\r
-               $elems = $xpath->query('.//p[@class="readability-styled"]', $articleContent);\r
-               //$elems = $articleContent->getElementsByTagName('p');\r
-               for ($i = $elems->length-1; $i >= 0; $i--) {\r
-                       $e = $elems->item($i);\r
-                       $e->parentNode->replaceChild($articleContent->ownerDocument->createTextNode($e->textContent), $e);\r
-                       //if ($e->hasAttribute('class') && $e->getAttribute('class') == 'readability-styled') {\r
-                       //      $e->parentNode->replaceChild($this->dom->createTextNode($e->textContent), $e);\r
-                       //}\r
-               }\r
-       }\r
-       \r
-       /**\r
-       * Prepare the article node for display. Clean out any inline styles,\r
-       * iframes, forms, strip extraneous <p> tags, etc.\r
-       *\r
-       * @param DOMElement\r
-       * @return void\r
-       */\r
-       function prepArticle($articleContent) {\r
-               $this->cleanStyles($articleContent);\r
-               $this->killBreaks($articleContent);\r
-               if ($this->revertForcedParagraphElements) {\r
-                       $this->revertReadabilityStyledElements($articleContent);\r
-               }\r
-\r
-               /* Clean out junk from the article content */\r
-               $this->cleanConditionally($articleContent, 'form');\r
-               $this->clean($articleContent, 'object');\r
-               $this->clean($articleContent, 'h1');\r
-\r
-               /**\r
-               * If there is only one h2, they are probably using it\r
-               * as a header and not a subheader, so remove it since we already have a header.\r
-               ***/\r
-               if (!$this->lightClean && ($articleContent->getElementsByTagName('h2')->length == 1)) {\r
-                       $this->clean($articleContent, 'h2'); \r
-               }\r
-               $this->clean($articleContent, 'iframe');\r
-\r
-               $this->cleanHeaders($articleContent);\r
-\r
-               /* Do these last as the previous stuff may have removed junk that will affect these */\r
-               $this->cleanConditionally($articleContent, 'table');\r
-               $this->cleanConditionally($articleContent, 'ul');\r
-               $this->cleanConditionally($articleContent, 'div');\r
-\r
-               /* Remove extra paragraphs */\r
-               $articleParagraphs = $articleContent->getElementsByTagName('p');\r
-               for ($i = $articleParagraphs->length-1; $i >= 0; $i--)\r
-               {\r
-                       $imgCount    = $articleParagraphs->item($i)->getElementsByTagName('img')->length;\r
-                       $embedCount  = $articleParagraphs->item($i)->getElementsByTagName('embed')->length;\r
-                       $objectCount = $articleParagraphs->item($i)->getElementsByTagName('object')->length;\r
-                       $iframeCount = $articleParagraphs->item($i)->getElementsByTagName('iframe')->length;\r
-                       \r
-                       if ($imgCount === 0 && $embedCount === 0 && $objectCount === 0 && $iframeCount === 0 && $this->getInnerText($articleParagraphs->item($i), false) == '')\r
-                       {\r
-                               $articleParagraphs->item($i)->parentNode->removeChild($articleParagraphs->item($i));\r
-                       }\r
-               }\r
-\r
-               try {\r
-                       $articleContent->innerHTML = preg_replace('/<br[^>]*>\s*<p/i', '<p', $articleContent->innerHTML);\r
-                       //articleContent.innerHTML = articleContent.innerHTML.replace(/<br[^>]*>\s*<p/gi, '<p');      \r
-               }\r
-               catch (Exception $e) {\r
-                       $this->dbg("Cleaning innerHTML of breaks failed. This is an IE strict-block-elements bug. Ignoring.: " . $e);\r
-               }\r
-       }\r
-       \r
-       /**\r
-       * Initialize a node with the readability object. Also checks the\r
-       * className/id for special names to add to its score.\r
-       *\r
-       * @param Element\r
-       * @return void\r
-       **/\r
-       protected function initializeNode($node) {\r
-               $readability = $this->dom->createAttribute('readability');\r
-               $readability->value = 0; // this is our contentScore\r
-               $node->setAttributeNode($readability);                   \r
-\r
-               switch (strtoupper($node->tagName)) { // unsure if strtoupper is needed, but using it just in case\r
-                       case 'DIV':\r
-                               $readability->value += 5;\r
-                               break;\r
-\r
-                       case 'PRE':\r
-                       case 'TD':\r
-                       case 'BLOCKQUOTE':\r
-                               $readability->value += 3;\r
-                               break;\r
-                               \r
-                       case 'ADDRESS':\r
-                       case 'OL':\r
-                       case 'UL':\r
-                       case 'DL':\r
-                       case 'DD':\r
-                       case 'DT':\r
-                       case 'LI':\r
-                       case 'FORM':\r
-                               $readability->value -= 3;\r
-                               break;\r
-\r
-                       case 'H1':\r
-                       case 'H2':\r
-                       case 'H3':\r
-                       case 'H4':\r
-                       case 'H5':\r
-                       case 'H6':\r
-                       case 'TH':\r
-                               $readability->value -= 5;\r
-                               break;\r
-               }\r
-               $readability->value += $this->getClassWeight($node);\r
-       }\r
-       \r
-       /***\r
-       * grabArticle - Using a variety of metrics (content score, classname, element types), find the content that is\r
-       *               most likely to be the stuff a user wants to read. Then return it wrapped up in a div.\r
-       *\r
-       * @return DOMElement\r
-       **/\r
-       protected function grabArticle($page=null) {\r
-               $stripUnlikelyCandidates = $this->flagIsActive(self::FLAG_STRIP_UNLIKELYS);\r
-               if (!$page) $page = $this->dom;\r
-               $allElements = $page->getElementsByTagName('*');\r
-               /**\r
-               * First, node prepping. Trash nodes that look cruddy (like ones with the class name "comment", etc), and turn divs\r
-               * into P tags where they have been used inappropriately (as in, where they contain no other block level elements.)\r
-               *\r
-               * Note: Assignment from index for performance. See http://www.peachpit.com/articles/article.aspx?p=31567&seqNum=5\r
-               * TODO: Shouldn't this be a reverse traversal?\r
-               **/\r
-               $node = null;\r
-               $nodesToScore = array();\r
-               for ($nodeIndex = 0; ($node = $allElements->item($nodeIndex)); $nodeIndex++) {\r
-               //for ($nodeIndex=$targetList->length-1; $nodeIndex >= 0; $nodeIndex--) {\r
-                       //$node = $targetList->item($nodeIndex);\r
-                       $tagName = strtoupper($node->tagName);\r
-                       /* Remove unlikely candidates */\r
-                       if ($stripUnlikelyCandidates) {\r
-                               $unlikelyMatchString = $node->getAttribute('class') . $node->getAttribute('id');\r
-                               if (\r
-                                       preg_match($this->regexps['unlikelyCandidates'], $unlikelyMatchString) &&\r
-                                       !preg_match($this->regexps['okMaybeItsACandidate'], $unlikelyMatchString) &&\r
-                                       $tagName != 'BODY'\r
-                               )\r
-                               {\r
-                                       $this->dbg('Removing unlikely candidate - ' . $unlikelyMatchString);\r
-                                       //$nodesToRemove[] = $node;\r
-                                       $node->parentNode->removeChild($node);\r
-                                       $nodeIndex--;\r
-                                       continue;\r
-                               }               \r
-                       }\r
-\r
-                       if ($tagName == 'P' || $tagName == 'TD' || $tagName == 'PRE') {\r
-                               $nodesToScore[] = $node;\r
-                       }\r
-\r
-                       /* Turn all divs that don't have children block level elements into p's */\r
-                       if ($tagName == 'DIV') {\r
-                               if (!preg_match($this->regexps['divToPElements'], $node->innerHTML)) {\r
-                                       //$this->dbg('Altering div to p');\r
-                                       $newNode = $this->dom->createElement('p');\r
-                                       try {\r
-                                               $newNode->innerHTML = $node->innerHTML;\r
-                                               //$nodesToReplace[] = array('new'=>$newNode, 'old'=>$node);\r
-                                               $node->parentNode->replaceChild($newNode, $node);\r
-                                               $nodeIndex--;\r
-                                               $nodesToScore[] = $node; // or $newNode?\r
-                                       }\r
-                                       catch(Exception $e) {\r
-                                               $this->dbg('Could not alter div to p, reverting back to div.: ' . $e);\r
-                                       }\r
-                               }\r
-                               else\r
-                               {\r
-                                       /* EXPERIMENTAL */\r
-                                       // TODO: change these p elements back to text nodes after processing\r
-                                       for ($i = 0, $il = $node->childNodes->length; $i < $il; $i++) {\r
-                                               $childNode = $node->childNodes->item($i);\r
-                                               if ($childNode->nodeType == 3) { // XML_TEXT_NODE\r
-                                                       //$this->dbg('replacing text node with a p tag with the same content.');\r
-                                                       $p = $this->dom->createElement('p');\r
-                                                       $p->innerHTML = $childNode->nodeValue;\r
-                                                       $p->setAttribute('style', 'display: inline;');\r
-                                                       $p->setAttribute('class', 'readability-styled');\r
-                                                       $childNode->parentNode->replaceChild($p, $childNode);\r
-                                               }\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-               \r
-               /**\r
-               * Loop through all paragraphs, and assign a score to them based on how content-y they look.\r
-               * Then add their score to their parent node.\r
-               *\r
-               * A score is determined by things like number of commas, class names, etc. Maybe eventually link density.\r
-               **/\r
-               $candidates = array();\r
-               for ($pt=0; $pt < count($nodesToScore); $pt++) {\r
-                       $parentNode      = $nodesToScore[$pt]->parentNode;\r
-                       // $grandParentNode = $parentNode ? $parentNode->parentNode : null;\r
-                       $grandParentNode = !$parentNode ? null : (($parentNode->parentNode instanceof DOMElement) ? $parentNode->parentNode : null);\r
-                       $innerText       = $this->getInnerText($nodesToScore[$pt]);\r
-\r
-                       if (!$parentNode || !isset($parentNode->tagName)) {\r
-                               continue;\r
-                       }\r
-\r
-                       /* If this paragraph is less than 25 characters, don't even count it. */\r
-                       if(strlen($innerText) < 25) {\r
-                               continue;\r
-                       }\r
-\r
-                       /* Initialize readability data for the parent. */\r
-                       if (!$parentNode->hasAttribute('readability')) \r
-                       {\r
-                               $this->initializeNode($parentNode);\r
-                               $candidates[] = $parentNode;\r
-                       }\r
-\r
-                       /* Initialize readability data for the grandparent. */\r
-                       if ($grandParentNode && !$grandParentNode->hasAttribute('readability') && isset($grandParentNode->tagName))\r
-                       {\r
-                               $this->initializeNode($grandParentNode);\r
-                               $candidates[] = $grandParentNode;\r
-                       }\r
-\r
-                       $contentScore = 0;\r
-\r
-                       /* Add a point for the paragraph itself as a base. */\r
-                       $contentScore++;\r
-\r
-                       /* Add points for any commas within this paragraph */\r
-                       $contentScore += count(explode(',', $innerText));\r
-                       \r
-                       /* For every 100 characters in this paragraph, add another point. Up to 3 points. */\r
-                       $contentScore += min(floor(strlen($innerText) / 100), 3);\r
-                       \r
-                       /* Add the score to the parent. The grandparent gets half. */\r
-                       $parentNode->getAttributeNode('readability')->value += $contentScore;\r
-\r
-                       if ($grandParentNode) {\r
-                               $grandParentNode->getAttributeNode('readability')->value += $contentScore/2;             \r
-                       }\r
-               }\r
-\r
-               /**\r
-               * After we've calculated scores, loop through all of the possible candidate nodes we found\r
-               * and find the one with the highest score.\r
-               **/\r
-               $topCandidate = null;\r
-               for ($c=0, $cl=count($candidates); $c < $cl; $c++)\r
-               {\r
-                       /**\r
-                       * Scale the final candidates score based on link density. Good content should have a\r
-                       * relatively small link density (5% or less) and be mostly unaffected by this operation.\r
-                       **/\r
-                       $readability = $candidates[$c]->getAttributeNode('readability');\r
-                       $readability->value = $readability->value * (1-$this->getLinkDensity($candidates[$c]));\r
-\r
-                       $this->dbg('Candidate: ' . $candidates[$c]->tagName . ' (' . $candidates[$c]->getAttribute('class') . ':' . $candidates[$c]->getAttribute('id') . ') with score ' . $readability->value);\r
-\r
-                       if (!$topCandidate || $readability->value > (int)$topCandidate->getAttribute('readability')) {\r
-                               $topCandidate = $candidates[$c];\r
-                       }\r
-               }\r
-\r
-               /**\r
-               * If we still have no top candidate, just use the body as a last resort.\r
-               * We also have to copy the body node so it is something we can modify.\r
-               **/\r
-               if ($topCandidate === null || strtoupper($topCandidate->tagName) == 'BODY')\r
-               {\r
-                       $topCandidate = $this->dom->createElement('div');\r
-                       if ($page instanceof DOMDocument) {\r
-                               if (!isset($page->documentElement)) {\r
-                                       // we don't have a body either? what a mess! :)\r
-                               } else {\r
-                                       $topCandidate->innerHTML = $page->documentElement->innerHTML;\r
-                                       $page->documentElement->innerHTML = '';\r
-                                       $page->documentElement->appendChild($topCandidate);\r
-                               }\r
-                       } else {\r
-                               $topCandidate->innerHTML = $page->innerHTML;\r
-                               $page->innerHTML = '';\r
-                               $page->appendChild($topCandidate);\r
-                       }\r
-                       $this->initializeNode($topCandidate);\r
-               }\r
-\r
-               /**\r
-               * Now that we have the top candidate, look through its siblings for content that might also be related.\r
-               * Things like preambles, content split by ads that we removed, etc.\r
-               **/\r
-               $articleContent        = $this->dom->createElement('div');\r
-               $articleContent->setAttribute('id', 'readability-content');\r
-               $siblingScoreThreshold = max(10, ((int)$topCandidate->getAttribute('readability')) * 0.2);\r
-               $siblingNodes          = $topCandidate->parentNode->childNodes;\r
-               if (!isset($siblingNodes)) {\r
-                       $siblingNodes = new stdClass;\r
-                       $siblingNodes->length = 0;\r
-               }\r
-\r
-               for ($s=0, $sl=$siblingNodes->length; $s < $sl; $s++)\r
-               {\r
-                       $siblingNode = $siblingNodes->item($s);\r
-                       $append      = false;\r
-\r
-                       $this->dbg('Looking at sibling node: ' . $siblingNode->nodeName . (($siblingNode->nodeType === XML_ELEMENT_NODE && $siblingNode->hasAttribute('readability')) ? (' with score ' . $siblingNode->getAttribute('readability')) : ''));\r
-\r
-                       //dbg('Sibling has score ' . ($siblingNode->readability ? siblingNode.readability.contentScore : 'Unknown'));\r
-\r
-                       if ($siblingNode === $topCandidate)\r
-                       // or if ($siblingNode->isSameNode($topCandidate))\r
-                       {\r
-                               $append = true;\r
-                       }\r
-\r
-                       $contentBonus = 0;\r
-                       /* Give a bonus if sibling nodes and top candidates have the example same classname */\r
-                       if ($siblingNode->nodeType === XML_ELEMENT_NODE && $siblingNode->getAttribute('class') == $topCandidate->getAttribute('class') && $topCandidate->getAttribute('class') != '') {\r
-                               $contentBonus += ((int)$topCandidate->getAttribute('readability')) * 0.2;\r
-                       }\r
-\r
-                       if ($siblingNode->nodeType === XML_ELEMENT_NODE && $siblingNode->hasAttribute('readability') && (((int)$siblingNode->getAttribute('readability')) + $contentBonus) >= $siblingScoreThreshold)\r
-                       {\r
-                               $append = true;\r
-                       }\r
-                       \r
-                       if (strtoupper($siblingNode->nodeName) == 'P') {\r
-                               $linkDensity = $this->getLinkDensity($siblingNode);\r
-                               $nodeContent = $this->getInnerText($siblingNode);\r
-                               $nodeLength  = strlen($nodeContent);\r
-                               \r
-                               if ($nodeLength > 80 && $linkDensity < 0.25)\r
-                               {\r
-                                       $append = true;\r
-                               }\r
-                               else if ($nodeLength < 80 && $linkDensity === 0 && preg_match('/\.( |$)/', $nodeContent))\r
-                               {\r
-                                       $append = true;\r
-                               }\r
-                       }\r
-\r
-                       if ($append)\r
-                       {\r
-                               $this->dbg('Appending node: ' . $siblingNode->nodeName);\r
-\r
-                               $nodeToAppend = null;\r
-                               $sibNodeName = strtoupper($siblingNode->nodeName);\r
-                               if ($sibNodeName != 'DIV' && $sibNodeName != 'P') {\r
-                                       /* We have a node that isn't a common block level element, like a form or td tag. Turn it into a div so it doesn't get filtered out later by accident. */\r
-                                       \r
-                                       $this->dbg('Altering siblingNode of ' . $sibNodeName . ' to div.');\r
-                                       $nodeToAppend = $this->dom->createElement('div');\r
-                                       try {\r
-                                               $nodeToAppend->setAttribute('id', $siblingNode->getAttribute('id'));\r
-                                               $nodeToAppend->innerHTML = $siblingNode->innerHTML;\r
-                                       }\r
-                                       catch(Exception $e)\r
-                                       {\r
-                                               $this->dbg('Could not alter siblingNode to div, reverting back to original.');\r
-                                               $nodeToAppend = $siblingNode;\r
-                                               $s--;\r
-                                               $sl--;\r
-                                       }\r
-                               } else {\r
-                                       $nodeToAppend = $siblingNode;\r
-                                       $s--;\r
-                                       $sl--;\r
-                               }\r
-                               \r
-                               /* To ensure a node does not interfere with readability styles, remove its classnames */\r
-                               $nodeToAppend->removeAttribute('class');\r
-\r
-                               /* Append sibling and subtract from our list because it removes the node when you append to another node */\r
-                               $articleContent->appendChild($nodeToAppend);\r
-                       }\r
-               }\r
-\r
-               /**\r
-               * So we have all of the content that we need. Now we clean it up for presentation.\r
-               **/\r
-               $this->prepArticle($articleContent);\r
-\r
-               /**\r
-               * Now that we've gone through the full algorithm, check to see if we got any meaningful content.\r
-               * If we didn't, we may need to re-run grabArticle with different flags set. This gives us a higher\r
-               * likelihood of finding the content, and the sieve approach gives us a higher likelihood of\r
-               * finding the -right- content.\r
-               **/\r
-               if (strlen($this->getInnerText($articleContent, false)) < 250)\r
-               {\r
-                       // TODO: find out why element disappears sometimes, e.g. for this URL http://www.businessinsider.com/6-hedge-fund-etfs-for-average-investors-2011-7\r
-                       // in the meantime, we check and create an empty element if it's not there.\r
-                       if (!isset($this->body->childNodes)) $this->body = $this->dom->createElement('body');\r
+        * Will recreate previously deleted body property\r
+        *\r
+        * @return void\r
+        */\r
+       protected function reinitBody() {\r
+               if (!isset($this->body->childNodes)) {\r
+                       $this->body = $this->dom->createElement('body');
                        $this->body->innerHTML = $this->bodyCache;\r
-                       \r
-                       if ($this->flagIsActive(self::FLAG_STRIP_UNLIKELYS)) {\r
-                               $this->removeFlag(self::FLAG_STRIP_UNLIKELYS);\r
-                               return $this->grabArticle($this->body);\r
-                       }\r
-                       else if ($this->flagIsActive(self::FLAG_WEIGHT_CLASSES)) {\r
-                               $this->removeFlag(self::FLAG_WEIGHT_CLASSES);\r
-                               return $this->grabArticle($this->body);              \r
-                       }\r
-                       else if ($this->flagIsActive(self::FLAG_CLEAN_CONDITIONALLY)) {\r
-                               $this->removeFlag(self::FLAG_CLEAN_CONDITIONALLY);\r
-                               return $this->grabArticle($this->body);\r
-                       }\r
-                       else {\r
-                               return false;\r
-                       }\r
-               }\r
-               return $articleContent;\r
-       }\r
-       \r
-       /**\r
-       * Remove script tags from document\r
-       *\r
-       * @param DOMElement\r
-       * @return void\r
-       */\r
-       public function removeScripts($doc) {\r
-               $scripts = $doc->getElementsByTagName('script');\r
-               for($i = $scripts->length-1; $i >= 0; $i--)\r
-               {\r
-                       $scripts->item($i)->parentNode->removeChild($scripts->item($i));\r
-               }\r
-       }\r
-       \r
-       /**\r
-       * Get the inner text of a node.\r
-       * This also strips out any excess whitespace to be found.\r
-       *\r
-       * @param DOMElement $\r
-       * @param boolean $normalizeSpaces (default: true)\r
-       * @return string\r
-       **/\r
-       public function getInnerText($e, $normalizeSpaces=true) {\r
-               $textContent = '';\r
-\r
-               if (!isset($e->textContent) || $e->textContent == '') {\r
-                       return '';\r
-               }\r
-\r
-               $textContent = trim($e->textContent);\r
-\r
-               if ($normalizeSpaces) {\r
-                       return preg_replace($this->regexps['normalize'], ' ', $textContent);\r
-               } else {\r
-                       return $textContent;\r
-               }\r
-       }\r
-\r
-       /**\r
-       * Get the number of times a string $s appears in the node $e.\r
-       *\r
-       * @param DOMElement $e\r
-       * @param string - what to count. Default is ","\r
-       * @return number (integer)\r
-       **/\r
-       public function getCharCount($e, $s=',') {\r
-               return substr_count($this->getInnerText($e), $s);\r
-       }\r
-\r
-       /**\r
-       * Remove the style attribute on every $e and under.\r
-       *\r
-       * @param DOMElement $e\r
-       * @return void\r
-       */\r
-       public function cleanStyles($e) {\r
-               if (!is_object($e)) return;\r
-               $elems = $e->getElementsByTagName('*');\r
-               foreach ($elems as $elem) {\r
-                       $elem->removeAttribute('style');\r
-               }\r
-       }\r
-       \r
-       /**\r
-       * Get the density of links as a percentage of the content\r
-       * This is the amount of text that is inside a link divided by the total text in the node.\r
-       * \r
-       * @param DOMElement $e\r
-       * @return number (float)\r
-       */\r
-       public function getLinkDensity($e) {\r
-               $links      = $e->getElementsByTagName('a');\r
-               $textLength = strlen($this->getInnerText($e));\r
-               $linkLength = 0;\r
-               for ($i=0, $il=$links->length; $i < $il; $i++)\r
-               {\r
-                       $linkLength += strlen($this->getInnerText($links->item($i)));\r
-               }\r
-               if ($textLength > 0) {\r
-                       return $linkLength / $textLength;\r
-               } else {\r
-                       return 0;\r
-               }\r
-       }\r
-       \r
-       /**\r
-       * Get an elements class/id weight. Uses regular expressions to tell if this \r
-       * element looks good or bad.\r
-       *\r
-       * @param DOMElement $e\r
-       * @return number (Integer)\r
-       */\r
-       public function getClassWeight($e) {\r
-               if(!$this->flagIsActive(self::FLAG_WEIGHT_CLASSES)) {\r
-                       return 0;\r
-               }\r
-\r
-               $weight = 0;\r
-\r
-               /* Look for a special classname */\r
-               if ($e->hasAttribute('class') && $e->getAttribute('class') != '')\r
-               {\r
-                       if (preg_match($this->regexps['negative'], $e->getAttribute('class'))) {\r
-                               $weight -= 25;\r
-                       }\r
-                       if (preg_match($this->regexps['positive'], $e->getAttribute('class'))) {\r
-                               $weight += 25;\r
-                       }\r
-               }\r
-\r
-               /* Look for a special ID */\r
-               if ($e->hasAttribute('id') && $e->getAttribute('id') != '')\r
-               {\r
-                       if (preg_match($this->regexps['negative'], $e->getAttribute('id'))) {\r
-                               $weight -= 25;\r
-                       }\r
-                       if (preg_match($this->regexps['positive'], $e->getAttribute('id'))) {\r
-                               $weight += 25;\r
-                       }\r
-               }\r
-               return $weight;\r
-       }\r
-\r
-       /**\r
-       * Remove extraneous break tags from a node.\r
-       *\r
-       * @param DOMElement $node\r
-       * @return void\r
-       */\r
-       public function killBreaks($node) {\r
-               $html = $node->innerHTML;\r
-               $html = preg_replace($this->regexps['killBreaks'], '<br />', $html);\r
-               $node->innerHTML = $html;\r
-       }\r
-\r
-       /**\r
-       * Clean a node of all elements of type "tag".\r
-       * (Unless it's a youtube/vimeo video. People love movies.)\r
-       *\r
-       * Updated 2012-09-18 to preserve youtube/vimeo iframes\r
-       *\r
-       * @param DOMElement $e\r
-       * @param string $tag\r
-       * @return void\r
-       */\r
-       public function clean($e, $tag) {\r
-               $targetList = $e->getElementsByTagName($tag);\r
-               $isEmbed = ($tag == 'iframe' || $tag == 'object' || $tag == 'embed');\r
-               \r
-               for ($y=$targetList->length-1; $y >= 0; $y--) {\r
-                       /* Allow youtube and vimeo videos through as people usually want to see those. */\r
-                       if ($isEmbed) {\r
-                               $attributeValues = '';\r
-                               for ($i=0, $il=$targetList->item($y)->attributes->length; $i < $il; $i++) {\r
-                                       $attributeValues .= $targetList->item($y)->attributes->item($i)->value . '|'; // DOMAttr? (TODO: test)\r
-                               }\r
-                               \r
-                               /* First, check the elements attributes to see if any of them contain youtube or vimeo */\r
-                               if (preg_match($this->regexps['video'], $attributeValues)) {\r
-                                       continue;\r
-                               }\r
-\r
-                               /* Then check the elements inside this element for the same. */\r
-                               if (preg_match($this->regexps['video'], $targetList->item($y)->innerHTML)) {\r
-                                       continue;\r
-                               }\r
-                       }\r
-                       $targetList->item($y)->parentNode->removeChild($targetList->item($y));\r
-               }\r
-       }\r
-       \r
-       /**\r
-       * Clean an element of all tags of type "tag" if they look fishy.\r
-       * "Fishy" is an algorithm based on content length, classnames, \r
-       * link density, number of images & embeds, etc.\r
-       *\r
-       * @param DOMElement $e\r
-       * @param string $tag\r
-       * @return void\r
-       */\r
-       public function cleanConditionally($e, $tag) {\r
-               if (!$this->flagIsActive(self::FLAG_CLEAN_CONDITIONALLY)) {\r
-                       return;\r
-               }\r
-\r
-               $tagsList = $e->getElementsByTagName($tag);\r
-               $curTagsLength = $tagsList->length;\r
-\r
-               /**\r
-               * Gather counts for other typical elements embedded within.\r
-               * Traverse backwards so we can remove nodes at the same time without effecting the traversal.\r
-               *\r
-               * TODO: Consider taking into account original contentScore here.\r
-               */\r
-               for ($i=$curTagsLength-1; $i >= 0; $i--) {\r
-                       $weight = $this->getClassWeight($tagsList->item($i));\r
-                       $contentScore = ($tagsList->item($i)->hasAttribute('readability')) ? (int)$tagsList->item($i)->getAttribute('readability') : 0;\r
-                       \r
-                       $this->dbg('Cleaning Conditionally ' . $tagsList->item($i)->tagName . ' (' . $tagsList->item($i)->getAttribute('class') . ':' . $tagsList->item($i)->getAttribute('id') . ')' . (($tagsList->item($i)->hasAttribute('readability')) ? (' with score ' . $tagsList->item($i)->getAttribute('readability')) : ''));\r
-\r
-                       if ($weight + $contentScore < 0) {\r
-                               $tagsList->item($i)->parentNode->removeChild($tagsList->item($i));\r
-                       }\r
-                       else if ( $this->getCharCount($tagsList->item($i), ',') < 10) {\r
-                               /**\r
-                               * If there are not very many commas, and the number of\r
-                               * non-paragraph elements is more than paragraphs or other ominous signs, remove the element.\r
-                               **/\r
-                               $p      = $tagsList->item($i)->getElementsByTagName('p')->length;\r
-                               $img    = $tagsList->item($i)->getElementsByTagName('img')->length;\r
-                               $li     = $tagsList->item($i)->getElementsByTagName('li')->length-100;\r
-                               $input  = $tagsList->item($i)->getElementsByTagName('input')->length;\r
-                               $a              = $tagsList->item($i)->getElementsByTagName('a')->length;\r
-\r
-                               $embedCount = 0;\r
-                               $embeds = $tagsList->item($i)->getElementsByTagName('embed');\r
-                               for ($ei=0, $il=$embeds->length; $ei < $il; $ei++) {\r
-                                       if (preg_match($this->regexps['video'], $embeds->item($ei)->getAttribute('src'))) {\r
-                                               $embedCount++; \r
-                                       }\r
-                               }\r
-                               $embeds = $tagsList->item($i)->getElementsByTagName('iframe');\r
-                               for ($ei=0, $il=$embeds->length; $ei < $il; $ei++) {\r
-                                       if (preg_match($this->regexps['video'], $embeds->item($ei)->getAttribute('src'))) {\r
-                                               $embedCount++; \r
-                                       }\r
-                               }\r
-\r
-                               $linkDensity   = $this->getLinkDensity($tagsList->item($i));\r
-                               $contentLength = strlen($this->getInnerText($tagsList->item($i)));\r
-                               $toRemove      = false;\r
-\r
-                               if ($this->lightClean) {\r
-                                       $this->dbg('Light clean...');\r
-                                       if ( ($img > $p) && ($img > 4) ) {\r
-                                               $this->dbg(' more than 4 images and more image elements than paragraph elements');\r
-                                               $toRemove = true;\r
-                                       } else if ($li > $p && $tag != 'ul' && $tag != 'ol') {\r
-                                               $this->dbg(' too many <li> elements, and parent is not <ul> or <ol>');\r
-                                               $toRemove = true;\r
-                                       } else if ( $input > floor($p/3) ) {\r
-                                               $this->dbg(' too many <input> elements');\r
-                                               $toRemove = true; \r
-                                       } else if ($contentLength < 25 && ($embedCount === 0 && ($img === 0 || $img > 2))) {\r
-                                               $this->dbg(' content length less than 25 chars, 0 embeds and either 0 images or more than 2 images');\r
-                                               $toRemove = true;\r
-                                       } else if($weight < 25 && $linkDensity > 0.2) {\r
-                                               $this->dbg(' weight smaller than 25 and link density above 0.2');\r
-                                               $toRemove = true;\r
-                                       } else if($a > 2 && ($weight >= 25 && $linkDensity > 0.5)) {\r
-                                               $this->dbg(' more than 2 links and weight above 25 but link density greater than 0.5');\r
-                                               $toRemove = true;\r
-                                       } else if($embedCount > 3) {\r
-                                               $this->dbg(' more than 3 embeds');\r
-                                               $toRemove = true;\r
-                                       }\r
-                               } else {\r
-                                       $this->dbg('Standard clean...');\r
-                                       if ( $img > $p ) {\r
-                                               $this->dbg(' more image elements than paragraph elements');\r
-                                               $toRemove = true;\r
-                                       } else if ($li > $p && $tag != 'ul' && $tag != 'ol') {\r
-                                               $this->dbg(' too many <li> elements, and parent is not <ul> or <ol>');\r
-                                               $toRemove = true;\r
-                                       } else if ( $input > floor($p/3) ) {\r
-                                               $this->dbg(' too many <input> elements');\r
-                                               $toRemove = true; \r
-                                       } else if ($contentLength < 25 && ($img === 0 || $img > 2) ) {\r
-                                               $this->dbg(' content length less than 25 chars and 0 images, or more than 2 images');\r
-                                               $toRemove = true;\r
-                                       } else if($weight < 25 && $linkDensity > 0.2) {\r
-                                               $this->dbg(' weight smaller than 25 and link density above 0.2');\r
-                                               $toRemove = true;\r
-                                       } else if($weight >= 25 && $linkDensity > 0.5) {\r
-                                               $this->dbg(' weight above 25 but link density greater than 0.5');\r
-                                               $toRemove = true;\r
-                                       } else if(($embedCount == 1 && $contentLength < 75) || $embedCount > 1) {\r
-                                               $this->dbg(' 1 embed and content length smaller than 75 chars, or more than one embed');\r
-                                               $toRemove = true;\r
-                                       }\r
-                               }\r
-\r
-                               if ($toRemove) {\r
-                                       //$this->dbg('Removing: '.$tagsList->item($i)->innerHTML);\r
-                                       $tagsList->item($i)->parentNode->removeChild($tagsList->item($i));\r
-                               }\r
-                       }\r
-               }\r
-       }\r
-\r
-       /**\r
-       * Clean out spurious headers from an Element. Checks things like classnames and link density.\r
-       *\r
-       * @param DOMElement $e\r
-       * @return void\r
-       */\r
-       public function cleanHeaders($e) {\r
-               for ($headerIndex = 1; $headerIndex < 3; $headerIndex++) {\r
-                       $headers = $e->getElementsByTagName('h' . $headerIndex);\r
-                       for ($i=$headers->length-1; $i >=0; $i--) {\r
-                               if ($this->getClassWeight($headers->item($i)) < 0 || $this->getLinkDensity($headers->item($i)) > 0.33) {\r
-                                       $headers->item($i)->parentNode->removeChild($headers->item($i));\r
-                               }\r
-                       }\r
                }\r
-       }\r
-\r
-       public function flagIsActive($flag) {\r
-               return ($this->flags & $flag) > 0;\r
-       }\r
-       \r
-       public function addFlag($flag) {\r
-               $this->flags = $this->flags | $flag;\r
-       }\r
-       \r
-       public function removeFlag($flag) {\r
-               $this->flags = $this->flags & ~$flag;\r
-       }\r
-}\r
+       }
+               
+}
 ?>
\ No newline at end of file
index 2852c4c2a76fbda3e902de30aea99873abb87d2e..a081f88b29f6800dab4cd2249366e35d45cd33dd 100755 (executable)
@@ -3,8 +3,8 @@
 // Author: Keyvan Minoukadeh\r
 // Copyright (c) 2013 Keyvan Minoukadeh\r
 // License: AGPLv3\r
-// Version: 3.1\r
-// Date: 2013-03-05\r
+// Version: 3.2\r
+// Date: 2013-05-13\r
 // More info: http://fivefilters.org/content-only/\r
 // Help: http://help.fivefilters.org\r
 \r
@@ -25,14 +25,10 @@ along with this program.  If not, see <http://www.gnu.org/licenses/>.
 \r
 // Usage\r
 // -----\r
-// Request this file passing it your feed in the querystring: makefulltextfeed.php?url=mysite.org\r
-// The following options can be passed in the querystring:\r
-// * URL: url=[feed or website url] (required, should be URL-encoded - in php: urlencode($url))\r
-// * URL points to HTML (not feed): html=true (optional, by default it's automatically detected)\r
-// * API key: key=[api key] (optional, refer to config.php)\r
-// * Max entries to process: max=[max number of items] (optional)\r
+// Request this file passing it a web page or feed URL in the querystring: makefulltextfeed.php?url=example.org/article\r
+// For more request parameters, see http://help.fivefilters.org/customer/portal/articles/226660-usage\r
 \r
-error_reporting(E_ALL ^ E_NOTICE);\r
+//error_reporting(E_ALL ^ E_NOTICE);\r
 ini_set("display_errors", 1);\r
 @set_time_limit(120);\r
 \r
@@ -55,42 +51,8 @@ if (get_magic_quotes_gpc()) {
 \r
 // set include path\r
 set_include_path(realpath(dirname(__FILE__).'/libraries').PATH_SEPARATOR.get_include_path());\r
-// Autoloading of classes allows us to include files only when they're\r
-// needed. If we've got a cached copy, for example, only Zend_Cache is loaded.\r
-function autoload($class_name) {\r
-       static $dir = null;\r
-       if ($dir === null) $dir = dirname(__FILE__).'/libraries/';\r
-       static $mapping = array(\r
-               // Include FeedCreator for RSS/Atom creation\r
-               'FeedWriter' => 'feedwriter/FeedWriter.php',\r
-               'FeedItem' => 'feedwriter/FeedItem.php',\r
-               // Include ContentExtractor and Readability for identifying and extracting content from URLs\r
-               'ContentExtractor' => 'content-extractor/ContentExtractor.php',\r
-               'SiteConfig' => 'content-extractor/SiteConfig.php',\r
-               'Readability' => 'readability/Readability.php',\r
-               // Include Humble HTTP Agent to allow parallel requests and response caching\r
-               'HumbleHttpAgent' => 'humble-http-agent/HumbleHttpAgent.php',\r
-               'SimplePie_HumbleHttpAgent' => 'humble-http-agent/SimplePie_HumbleHttpAgent.php',\r
-               'CookieJar' => 'humble-http-agent/CookieJar.php',\r
-               // Include Zend Cache to improve performance (cache results)\r
-               'Zend_Cache' => 'Zend/Cache.php',\r
-               // Language detect\r
-               'Text_LanguageDetect' => 'language-detect/LanguageDetect.php',\r
-               // HTML5 Lib\r
-               'HTML5_Parser' => 'html5/Parser.php',\r
-               // htmLawed - used if XSS filter is enabled (xss_filter)\r
-               'htmLawed' => 'htmLawed/htmLawed.php'\r
-       );\r
-       if (isset($mapping[$class_name])) {\r
-               debug("** Loading class $class_name ({$mapping[$class_name]})");\r
-               require $dir.$mapping[$class_name];\r
-               return true;\r
-       } else {\r
-               return false;\r
-       }\r
-}\r
-spl_autoload_register('autoload');\r
-require dirname(__FILE__).'/libraries/simplepie/autoloader.php';\r
+\r
+require_once dirname(__FILE__).'/makefulltextfeedHelpers.php';\r
 \r
 ////////////////////////////////\r
 // Load config file\r
@@ -110,8 +72,8 @@ header('X-Robots-Tag: noindex, nofollow');
 ////////////////////////////////\r
 // Check if service is enabled\r
 ////////////////////////////////\r
-if (!$options->enabled) { \r
-       die('The full-text RSS service is currently disabled'); \r
+if (!$options->enabled) {\r
+       die('The full-text RSS service is currently disabled');\r
 }\r
 \r
 ////////////////////////////////\r
@@ -155,8 +117,8 @@ $options->smart_cache = $options->smart_cache && function_exists('apc_inc');
 ////////////////////////////////\r
 // Check for feed URL\r
 ////////////////////////////////\r
-if (!isset($_GET['url'])) { \r
-       die('No URL supplied'); \r
+if (!isset($_GET['url'])) {\r
+       die('No URL supplied');\r
 }\r
 $url = trim($_GET['url']);\r
 if (strtolower(substr($url, 0, 7)) == 'feed://') {\r
@@ -195,10 +157,12 @@ if (isset($_GET['key']) && ($key_index = array_search($_GET['key'], $options->ap
        if (isset($_GET['links'])) $redirect .= '&links='.urlencode($_GET['links']);\r
        if (isset($_GET['exc'])) $redirect .= '&exc='.urlencode($_GET['exc']);\r
        if (isset($_GET['format'])) $redirect .= '&format='.urlencode($_GET['format']);\r
-       if (isset($_GET['callback'])) $redirect .= '&callback='.urlencode($_GET['callback']);   \r
+       if (isset($_GET['callback'])) $redirect .= '&callback='.urlencode($_GET['callback']);\r
        if (isset($_GET['l'])) $redirect .= '&l='.urlencode($_GET['l']);\r
        if (isset($_GET['xss'])) $redirect .= '&xss';\r
        if (isset($_GET['use_extracted_title'])) $redirect .= '&use_extracted_title';\r
+       if (isset($_GET['content'])) $redirect .= '&content='.urlencode($_GET['content']);\r
+       if (isset($_GET['summary'])) $redirect .= '&summary='.urlencode($_GET['summary']);\r
        if (isset($_GET['debug'])) $redirect .= '&debug';\r
        if ($debug_mode) {\r
                debug('Redirecting to hide access key, follow URL below to continue');\r
@@ -211,7 +175,7 @@ if (isset($_GET['key']) && ($key_index = array_search($_GET['key'], $options->ap
 \r
 ///////////////////////////////////////////////\r
 // Set timezone.\r
-// Prevents warnings, but needs more testing - \r
+// Prevents warnings, but needs more testing -\r
 // perhaps if timezone is set in php.ini we\r
 // don't need to set it at all...\r
 ///////////////////////////////////////////////\r
@@ -233,7 +197,7 @@ if (isset($_GET['key']) && isset($_GET['hash']) && isset($options->api_keys[(int
 }\r
 $key_index = ($valid_key) ? (int)$_GET['key'] : 0;\r
 if (!$valid_key && $options->key_required) {\r
-       die('A valid key must be supplied'); \r
+       die('A valid key must be supplied');\r
 }\r
 if (!$valid_key && isset($_GET['key']) && $_GET['key'] != '') {\r
        die('The entered key is invalid');\r
@@ -284,6 +248,28 @@ if ($options->favour_feed_titles == 'user') {
        $favour_feed_titles = $options->favour_feed_titles;\r
 }\r
 \r
+///////////////////////////////////////////////\r
+// Include full content in output?\r
+///////////////////////////////////////////////\r
+if ($options->content === 'user') {\r
+       if (isset($_GET['content']) && $_GET['content'] === '0') {\r
+               $options->content = false;\r
+       } else {\r
+               $options->content = true;\r
+       }\r
+}\r
+\r
+///////////////////////////////////////////////\r
+// Include summaries in output?\r
+///////////////////////////////////////////////\r
+if ($options->summary === 'user') {\r
+       if (isset($_GET['summary']) && $_GET['summary'] === '1') {\r
+               $options->summary = true;\r
+       } else {\r
+               $options->summary = false;\r
+       }\r
+}\r
+\r
 ///////////////////////////////////////////////\r
 // Exclude items if extraction fails\r
 ///////////////////////////////////////////////\r
@@ -306,15 +292,6 @@ if ($options->detect_language === 'user') {
        $detect_language = $options->detect_language;\r
 }\r
 \r
-if ($detect_language >= 2) {\r
-       $language_codes = array('albanian' => 'sq','arabic' => 'ar','azeri' => 'az','bengali' => 'bn','bulgarian' => 'bg',\r
-       'cebuano' => 'ceb', // ISO 639-2\r
-       'croatian' => 'hr','czech' => 'cs','danish' => 'da','dutch' => 'nl','english' => 'en','estonian' => 'et','farsi' => 'fa','finnish' => 'fi','french' => 'fr','german' => 'de','hausa' => 'ha',\r
-       'hawaiian' => 'haw', // ISO 639-2 \r
-       'hindi' => 'hi','hungarian' => 'hu','icelandic' => 'is','indonesian' => 'id','italian' => 'it','kazakh' => 'kk','kyrgyz' => 'ky','latin' => 'la','latvian' => 'lv','lithuanian' => 'lt','macedonian' => 'mk','mongolian' => 'mn','nepali' => 'ne','norwegian' => 'no','pashto' => 'ps',\r
-       'pidgin' => 'cpe', // ISO 639-2  \r
-       'polish' => 'pl','portuguese' => 'pt','romanian' => 'ro','russian' => 'ru','serbian' => 'sr','slovak' => 'sk','slovene' => 'sl','somali' => 'so','spanish' => 'es','swahili' => 'sw','swedish' => 'sv','tagalog' => 'tl','turkish' => 'tr','ukrainian' => 'uk','urdu' => 'ur','uzbek' => 'uz','vietnamese' => 'vi','welsh' => 'cy');\r
-}\r
 $use_cld = extension_loaded('cld') && (version_compare(PHP_VERSION, '5.3.0') >= 0);\r
 \r
 /////////////////////////////////////\r
@@ -364,7 +341,7 @@ if ($options->cors) header('Access-Control-Allow-Origin: *');
 //////////////////////////////////\r
 if ($options->caching) {\r
        debug('Caching is enabled...');\r
-       $cache_id = md5($max.$url.$valid_key.$links.$favour_feed_titles.$xss_filter.$exclude_on_fail.$format.$detect_language.(int)isset($_GET['pubsub']));\r
+       $cache_id = md5($max.$url.(int)$valid_key.$links.(int)$favour_feed_titles.(int)$options->content.(int)$options->summary.(int)$xss_filter.(int)$exclude_on_fail.$format.$detect_language.(int)isset($_GET['pubsub']));\r
        $check_cache = true;\r
        if ($options->apc && $options->smart_cache) {\r
                apc_add("cache.$cache_id", 0, 10*60);\r
@@ -415,6 +392,7 @@ if (!$debug_mode) {
 //////////////////////////////////\r
 // Set up HTTP agent\r
 //////////////////////////////////\r
+global $http;\r
 $http = new HumbleHttpAgent();\r
 $http->debug = $debug_mode;\r
 $http->userAgentMap = $options->user_agents;\r
@@ -478,29 +456,6 @@ if ($html_only || !$result) {
        $isDummyFeed = true;\r
        unset($feed, $result);\r
        // create single item dummy feed object\r
-       class DummySingleItemFeed {\r
-               public $item;\r
-               function __construct($url) { $this->item = new DummySingleItem($url); }\r
-               public function get_title() { return ''; }\r
-               public function get_description() { return 'Content extracted from '.$this->item->url; }\r
-               public function get_link() { return $this->item->url; }\r
-               public function get_language() { return false; }\r
-               public function get_image_url() { return false; }\r
-               public function get_items($start=0, $max=1) { return array(0=>$this->item); }\r
-       }\r
-       class DummySingleItem {\r
-               public $url;\r
-               function __construct($url) { $this->url = $url; }\r
-               public function get_permalink() { return $this->url; }\r
-               public function get_title() { return null; }\r
-               public function get_date($format='') { return false; }\r
-               public function get_author($key=0) { return null; }\r
-               public function get_authors() { return null; }\r
-               public function get_description() { return ''; }\r
-               public function get_enclosure($key=0, $prefer=null) { return null; }\r
-               public function get_enclosures() { return null; }\r
-               public function get_categories() { return null; }\r
-       }\r
        $feed = new DummySingleItemFeed($url);\r
 }\r
 \r
@@ -524,7 +479,7 @@ if ($img_url = $feed->get_image_url()) {
 ////////////////////////////////////////////\r
 // Loop through feed items\r
 ////////////////////////////////////////////\r
-$items = $feed->get_items(0, $max);    \r
+$items = $feed->get_items(0, $max);\r
 // Request all feed items in parallel (if supported)\r
 $urls_sanitized = array();\r
 $urls = array();\r
@@ -606,24 +561,43 @@ foreach ($items as $key => $item) {
                        $is_single_page = false;\r
                        if ($single_page_response = getSinglePage($item, $html, $effective_url)) {\r
                                $is_single_page = true;\r
-                               $html = $single_page_response['body'];\r
-                               // remove strange things\r
-                               $html = str_replace('</[>', '', $html); \r
-                               $html = convert_to_utf8($html, $single_page_response['headers']);\r
                                $effective_url = $single_page_response['effective_url'];\r
-                               debug("Retrieved single-page view from $effective_url");\r
+                               // check if action defined for returned Content-Type\r
+                               $mime_info = get_mime_action_info($single_page_response['headers']);\r
+                               if (isset($mime_info['action'])) {\r
+                                       if ($mime_info['action'] == 'exclude') {\r
+                                               continue; // skip this feed item entry\r
+                                       } elseif ($mime_info['action'] == 'link') {\r
+                                               if ($mime_info['type'] == 'image') {\r
+                                                       $html = "<a href=\"$effective_url\"><img src=\"$effective_url\" alt=\"{$mime_info['name']}\" /></a>";\r
+                                               } else {\r
+                                                       $html = "<a href=\"$effective_url\">Download {$mime_info['name']}</a>";\r
+                                               }\r
+                                               $extracted_title = $mime_info['name'];\r
+                                               $do_content_extraction = false;\r
+                                       }\r
+                               }\r
+                               if ($do_content_extraction) {\r
+                                       $html = $single_page_response['body'];\r
+                                       // remove strange things\r
+                                       $html = str_replace('</[>', '', $html);\r
+                                       $html = convert_to_utf8($html, $single_page_response['headers']);\r
+                                       debug("Retrieved single-page view from $effective_url");\r
+                               }\r
                                unset($single_page_response);\r
                        }\r
+               }\r
+               if ($do_content_extraction) {\r
                        debug('--------');\r
                        debug('Attempting to extract content');\r
                        $extract_result = $extractor->process($html, $effective_url);\r
                        $readability = $extractor->readability;\r
-                       $content_block = ($extract_result) ? $extractor->getContent() : null;                   \r
+                       $content_block = ($extract_result) ? $extractor->getContent() : null;\r
                        $extracted_title = ($extract_result) ? $extractor->getTitle() : '';\r
                        // Deal with multi-page articles\r
                        //die('Next: '.$extractor->getNextPageUrl());\r
                        $is_multi_page = (!$is_single_page && $extract_result && $extractor->getNextPageUrl());\r
-                       if ($options->multipage && $is_multi_page) {\r
+                       if ($options->multipage && $is_multi_page && $options->content) {\r
                                debug('--------');\r
                                debug('Attempting to process multi-page article');\r
                                $multi_page_urls = array();\r
@@ -636,7 +610,7 @@ foreach ($items as $key => $item) {
                                                // check it's not what we have already!\r
                                                if (!in_array($next_page_url, $multi_page_urls)) {\r
                                                        // it's not, so let's attempt to fetch it\r
-                                                       $multi_page_urls[] = $next_page_url;                                            \r
+                                                       $multi_page_urls[] = $next_page_url;\r
                                                        $_prev_ref = $http->referer;\r
                                                        if (($response = $http->get($next_page_url, true)) && $response['status_code'] < 300) {\r
                                                                // make sure mime type is not something with a different action associated\r
@@ -661,13 +635,15 @@ foreach ($items as $key => $item) {
                                // did we successfully deal with this multi-page article?\r
                                if (empty($multi_page_content)) {\r
                                        debug('Failed to extract all parts of multi-page article, so not going to include them');\r
-                                       $multi_page_content[] = $readability->dom->createElement('p')->innerHTML = '<em>This article appears to continue on subsequent pages which we could not extract</em>';\r
+                                       $_page = $readability->dom->createElement('p');\r
+                                       $_page->innerHTML = '<em>This article appears to continue on subsequent pages which we could not extract</em>';\r
+                                       $multi_page_content[] = $_page;\r
                                }\r
                                foreach ($multi_page_content as $_page) {\r
                                        $_page = $content_block->ownerDocument->importNode($_page, true);\r
                                        $content_block->appendChild($_page);\r
                                }\r
-                               unset($multi_page_urls, $multi_page_content, $page_mime_info, $next_page_url);\r
+                               unset($multi_page_urls, $multi_page_content, $page_mime_info, $next_page_url, $_page);\r
                        }\r
                }\r
                // use extracted title for both feed and item title if we're using single-item dummy feed\r
@@ -695,7 +671,11 @@ foreach ($items as $key => $item) {
                        $html .= $item->get_description();\r
                } else {\r
                        $readability->clean($content_block, 'select');\r
-                       if ($options->rewrite_relative_urls) makeAbsolute($effective_url, $content_block);\r
+                       // get base URL\r
+                       $base_url = get_base_url($readability->dom);\r
+                       if (!$base_url) $base_url = $effective_url;\r
+                       // rewrite URLs\r
+                       if ($options->rewrite_relative_urls) makeAbsolute($base_url, $content_block);\r
                        // footnotes\r
                        if (($links == 'footnotes') && (strpos($effective_url, 'wikipedia.org') === false)) {\r
                                $readability->addFootnotes($content_block);\r
@@ -714,7 +694,7 @@ foreach ($items as $key => $item) {
                        } else {\r
                                $html = $content_block->ownerDocument->saveXML($content_block); // essentially outerHTML\r
                        }\r
-                       unset($content_block);\r
+                       //unset($content_block);\r
                        // post-processing cleanup\r
                        $html = preg_replace('!<p>[\s\h\v]*</p>!u', '', $html);\r
                        if ($links == 'remove') {\r
@@ -727,130 +707,155 @@ foreach ($items as $key => $item) {
                }\r
        }\r
 \r
-               if ($valid_key && isset($_GET['pubsub'])) { // used only on fivefilters.org at the moment\r
-                       $newitem->addElement('guid', 'http://fivefilters.org/content-only/redirect.php?url='.urlencode($item->get_permalink()), array('isPermaLink'=>'false'));\r
+       if ($valid_key && isset($_GET['pubsub'])) { // used only on fivefilters.org at the moment\r
+               $newitem->addElement('guid', 'http://fivefilters.org/content-only/redirect.php?url='.urlencode($item->get_permalink()), array('isPermaLink'=>'false'));\r
+       } else {\r
+               $newitem->addElement('guid', $item->get_permalink(), array('isPermaLink'=>'true'));\r
+       }\r
+       // filter xss?\r
+       if ($xss_filter) {\r
+               debug('Filtering HTML to remove XSS');\r
+               $html = htmLawed::hl($html, array('safe'=>1, 'deny_attribute'=>'style', 'comment'=>1, 'cdata'=>1));\r
+       }\r
+\r
+       // add content\r
+       if ($options->summary === true) {\r
+               // get summary\r
+               $summary = '';\r
+               if (!$do_content_extraction) {\r
+                       $summary = $html;\r
                } else {\r
-                       $newitem->addElement('guid', $item->get_permalink(), array('isPermaLink'=>'true'));\r
-               }\r
-               // filter xss?\r
-               if ($xss_filter) {\r
-                       debug('Filtering HTML to remove XSS');\r
-                       $html = htmLawed::hl($html, array('safe'=>1, 'deny_attribute'=>'style', 'comment'=>1, 'cdata'=>1));\r
-               }\r
-               $newitem->setDescription($html);\r
-               \r
-               // set date\r
-               if ((int)$item->get_date('U') > 0) {\r
-                       $newitem->setDate((int)$item->get_date('U'));\r
-               } elseif ($extractor->getDate()) {\r
-                       $newitem->setDate($extractor->getDate());\r
-               }\r
-               \r
-               // add authors\r
-               if ($authors = $item->get_authors()) {\r
-                       foreach ($authors as $author) {\r
-                               // for some feeds, SimplePie stores author's name as email, e.g. http://feeds.feedburner.com/nymag/intel\r
-                               if ($author->get_name() !== null) {\r
-                                       $newitem->addElement('dc:creator', $author->get_name());\r
-                               } elseif ($author->get_email() !== null) {\r
-                                       $newitem->addElement('dc:creator', $author->get_email());\r
+                       // Try to get first few paragraphs\r
+                       if (isset($content_block) && ($content_block instanceof DOMElement)) {\r
+                               $_paras = $content_block->getElementsByTagName('p');\r
+                               foreach ($_paras as $_para) {\r
+                                       $summary .= preg_replace("/[\n\r\t ]+/", ' ', $_para->textContent).' ';\r
+                                       if (strlen($summary) > 200) break;\r
                                }\r
+                       } else {\r
+                               $summary = $html;\r
                        }\r
-               } elseif ($authors = $extractor->getAuthors()) {\r
-                       //TODO: make sure the list size is reasonable\r
-                       foreach ($authors as $author) {\r
-                               // TODO: xpath often selects authors from other articles linked from the page.\r
-                               // for now choose first item\r
-                               $newitem->addElement('dc:creator', $author);\r
-                               break;\r
+               }\r
+               unset($_paras, $_para);\r
+               $summary = get_excerpt($summary);\r
+               $newitem->setDescription($summary);\r
+               if ($options->content) $newitem->setElement('content:encoded', $html);\r
+       } else {\r
+               if ($options->content) $newitem->setDescription($html);\r
+       }\r
+\r
+       // set date\r
+       if ((int)$item->get_date('U') > 0) {\r
+               $newitem->setDate((int)$item->get_date('U'));\r
+       } elseif ($extractor->getDate()) {\r
+               $newitem->setDate($extractor->getDate());\r
+       }\r
+\r
+       // add authors\r
+       if ($authors = $item->get_authors()) {\r
+               foreach ($authors as $author) {\r
+                       // for some feeds, SimplePie stores author's name as email, e.g. http://feeds.feedburner.com/nymag/intel\r
+                       if ($author->get_name() !== null) {\r
+                               $newitem->addElement('dc:creator', $author->get_name());\r
+                       } elseif ($author->get_email() !== null) {\r
+                               $newitem->addElement('dc:creator', $author->get_email());\r
                        }\r
                }\r
-               \r
-               // add language\r
-               if ($detect_language) {\r
-                       $language = $extractor->getLanguage();\r
-                       if (!$language) $language = $feed->get_language();\r
-                       if (($detect_language == 3 || (!$language && $detect_language == 2)) && $text_sample) {\r
-                               try {\r
-                                       if ($use_cld) {\r
-                                               // Use PHP-CLD extension\r
-                                               $php_cld = 'CLD\detect'; // in quotes to prevent PHP 5.2 parse error\r
-                                               $res = $php_cld($text_sample);\r
-                                               if (is_array($res) && count($res) > 0) {\r
-                                                       $language = $res[0]['code'];\r
-                                               }       \r
-                                       } else {\r
-                                               //die('what');\r
-                                               // Use PEAR's Text_LanguageDetect\r
-                                               if (!isset($l)) {\r
-                                                       $l = new Text_LanguageDetect('libraries/language-detect/lang.dat', 'libraries/language-detect/unicode_blocks.dat');\r
-                                               }\r
-                                               $l_result = $l->detect($text_sample, 1);\r
-                                               if (count($l_result) > 0) {\r
-                                                       $language = $language_codes[key($l_result)];\r
-                                               }\r
+       } elseif ($authors = $extractor->getAuthors()) {\r
+               //TODO: make sure the list size is reasonable\r
+               foreach ($authors as $author) {\r
+                       // TODO: xpath often selects authors from other articles linked from the page.\r
+                       // for now choose first item\r
+                       $newitem->addElement('dc:creator', $author);\r
+                       break;\r
+               }\r
+       }\r
+\r
+       // add language\r
+       if ($detect_language) {\r
+               $language = $extractor->getLanguage();\r
+               if (!$language) $language = $feed->get_language();\r
+               if (($detect_language == 3 || (!$language && $detect_language == 2)) && $text_sample) {\r
+                       try {\r
+                               if ($use_cld) {\r
+                                       // Use PHP-CLD extension\r
+                                       $php_cld = 'CLD\detect'; // in quotes to prevent PHP 5.2 parse error\r
+                                       $res = $php_cld($text_sample);\r
+                                       if (is_array($res) && count($res) > 0) {\r
+                                               $language = $res[0]['code'];\r
+                                       }\r
+                               } else {\r
+                                       //die('what');\r
+                                       // Use PEAR's Text_LanguageDetect\r
+                                       if (!isset($l)) {\r
+                                         $l = new Text_LanguageDetect();\r
+                                         $l->setNameMode(2); // return ISO 639-1 codes (e.g. "en")\r
+                                       }\r
+                                       $l_result = $l->detect($text_sample, 1);\r
+                                       if (count($l_result) > 0) {\r
+                                               $language = key($l_result);\r
                                        }\r
-                               } catch (Exception $e) {\r
-                                       //die('error: '.$e);    \r
-                                       // do nothing\r
                                }\r
-                       }\r
-                       if ($language && (strlen($language) < 7)) {     \r
-                               $newitem->addElement('dc:language', $language);\r
+                       } catch (Exception $e) {\r
+                               //die('error: '.$e);\r
+                               // do nothing\r
                        }\r
                }\r
-               \r
-               // add MIME type (if it appeared in our exclusions lists)\r
-               if (isset($mime_info['mime'])) $newitem->addElement('dc:format', $mime_info['mime']);\r
-               // add effective URL (URL after redirects)\r
-               if (isset($effective_url)) {\r
-                       //TODO: ensure $effective_url is valid witout - sometimes it causes problems, e.g.\r
-                       //http://www.siasat.pk/forum/showthread.php?108883-Pakistan-Chowk-by-Rana-Mubashir-\96-25th-March-2012-Special-Program-from-Liari-(Karachi)\r
-                       //temporary measure: use utf8_encode()\r
-                       $newitem->addElement('dc:identifier', remove_url_cruft(utf8_encode($effective_url)));\r
-               } else {\r
-                       $newitem->addElement('dc:identifier', remove_url_cruft($item->get_permalink()));\r
+               if ($language && (strlen($language) < 7)) {\r
+                       $newitem->addElement('dc:language', $language);\r
                }\r
-               \r
-               // add categories\r
-               if ($categories = $item->get_categories()) {\r
-                       foreach ($categories as $category) {\r
-                               if ($category->get_label() !== null) {\r
-                                       $newitem->addElement('category', $category->get_label());\r
-                               }\r
+       }\r
+\r
+       // add MIME type (if it appeared in our exclusions lists)\r
+       if (isset($mime_info['mime'])) $newitem->addElement('dc:format', $mime_info['mime']);\r
+       // add effective URL (URL after redirects)\r
+       if (isset($effective_url)) {\r
+               //TODO: ensure $effective_url is valid witout - sometimes it causes problems, e.g.\r
+               //http://www.siasat.pk/forum/showthread.php?108883-Pakistan-Chowk-by-Rana-Mubashir-�-25th-March-2012-Special-Program-from-Liari-(Karachi)\r
+               //temporary measure: use utf8_encode()\r
+               $newitem->addElement('dc:identifier', remove_url_cruft(utf8_encode($effective_url)));\r
+       } else {\r
+               $newitem->addElement('dc:identifier', remove_url_cruft($item->get_permalink()));\r
+       }\r
+\r
+       // add categories\r
+       if ($categories = $item->get_categories()) {\r
+               foreach ($categories as $category) {\r
+                       if ($category->get_label() !== null) {\r
+                               $newitem->addElement('category', $category->get_label());\r
                        }\r
                }\r
-               \r
-               // check for enclosures\r
-               if ($options->keep_enclosures) {\r
-                       if ($enclosures = $item->get_enclosures()) {\r
-                               foreach ($enclosures as $enclosure) {\r
-                                       // thumbnails\r
-                                       foreach ((array)$enclosure->get_thumbnails() as $thumbnail) {\r
-                                               $newitem->addElement('media:thumbnail', '', array('url'=>$thumbnail));\r
-                                       }\r
-                                       if (!$enclosure->get_link()) continue;\r
-                                       $enc = array();\r
-                                       // Media RSS spec ($enc): http://search.yahoo.com/mrss\r
-                                       // SimplePie methods ($enclosure): http://simplepie.org/wiki/reference/start#methods4\r
-                                       $enc['url'] = $enclosure->get_link();\r
-                                       if ($enclosure->get_length()) $enc['fileSize'] = $enclosure->get_length();\r
-                                       if ($enclosure->get_type()) $enc['type'] = $enclosure->get_type();\r
-                                       if ($enclosure->get_medium()) $enc['medium'] = $enclosure->get_medium();\r
-                                       if ($enclosure->get_expression()) $enc['expression'] = $enclosure->get_expression();\r
-                                       if ($enclosure->get_bitrate()) $enc['bitrate'] = $enclosure->get_bitrate();\r
-                                       if ($enclosure->get_framerate()) $enc['framerate'] = $enclosure->get_framerate();\r
-                                       if ($enclosure->get_sampling_rate()) $enc['samplingrate'] = $enclosure->get_sampling_rate();\r
-                                       if ($enclosure->get_channels()) $enc['channels'] = $enclosure->get_channels();\r
-                                       if ($enclosure->get_duration()) $enc['duration'] = $enclosure->get_duration();\r
-                                       if ($enclosure->get_height()) $enc['height'] = $enclosure->get_height();\r
-                                       if ($enclosure->get_width()) $enc['width'] = $enclosure->get_width();\r
-                                       if ($enclosure->get_language()) $enc['lang'] = $enclosure->get_language();\r
-                                       $newitem->addElement('media:content', '', $enc);\r
+       }\r
+\r
+       // check for enclosures\r
+       if ($options->keep_enclosures) {\r
+               if ($enclosures = $item->get_enclosures()) {\r
+                       foreach ($enclosures as $enclosure) {\r
+                               // thumbnails\r
+                               foreach ((array)$enclosure->get_thumbnails() as $thumbnail) {\r
+                                       $newitem->addElement('media:thumbnail', '', array('url'=>$thumbnail));\r
                                }\r
+                               if (!$enclosure->get_link()) continue;\r
+                               $enc = array();\r
+                               // Media RSS spec ($enc): http://search.yahoo.com/mrss\r
+                               // SimplePie methods ($enclosure): http://simplepie.org/wiki/reference/start#methods4\r
+                               $enc['url'] = $enclosure->get_link();\r
+                               if ($enclosure->get_length()) $enc['fileSize'] = $enclosure->get_length();\r
+                               if ($enclosure->get_type()) $enc['type'] = $enclosure->get_type();\r
+                               if ($enclosure->get_medium()) $enc['medium'] = $enclosure->get_medium();\r
+                               if ($enclosure->get_expression()) $enc['expression'] = $enclosure->get_expression();\r
+                               if ($enclosure->get_bitrate()) $enc['bitrate'] = $enclosure->get_bitrate();\r
+                               if ($enclosure->get_framerate()) $enc['framerate'] = $enclosure->get_framerate();\r
+                               if ($enclosure->get_sampling_rate()) $enc['samplingrate'] = $enclosure->get_sampling_rate();\r
+                               if ($enclosure->get_channels()) $enc['channels'] = $enclosure->get_channels();\r
+                               if ($enclosure->get_duration()) $enc['duration'] = $enclosure->get_duration();\r
+                               if ($enclosure->get_height()) $enc['height'] = $enclosure->get_height();\r
+                               if ($enclosure->get_width()) $enc['width'] = $enclosure->get_width();\r
+                               if ($enclosure->get_language()) $enc['lang'] = $enclosure->get_language();\r
+                               $newitem->addElement('media:content', '', $enc);\r
                        }\r
                }\r
-       /* } */\r
+       }\r
        $output->addItem($newitem);\r
        unset($html);\r
        $item_count++;\r
@@ -887,7 +892,7 @@ if (!$debug_mode) {
        }\r
        if ($add_to_cache) {\r
                ob_start();\r
-               $output->genarateFeed();\r
+               $output->genarateFeed(false);\r
                $output = ob_get_contents();\r
                ob_end_clean();\r
                if ($html_only && $item_count == 0) {\r
@@ -898,299 +903,8 @@ if (!$debug_mode) {
                }\r
                echo $output;\r
        } else {\r
-               $output->genarateFeed();\r
+               $output->genarateFeed(false);\r
        }\r
        if ($callback) echo ');';\r
 }\r
 \r
-///////////////////////////////\r
-// HELPER FUNCTIONS\r
-///////////////////////////////\r
-\r
-function url_allowed($url) {\r
-       global $options;\r
-       if (!empty($options->allowed_urls)) {\r
-               $allowed = false;\r
-               foreach ($options->allowed_urls as $allowurl) {\r
-                       if (stristr($url, $allowurl) !== false) {\r
-                               $allowed = true;\r
-                               break;\r
-                       }\r
-               }\r
-               if (!$allowed) return false;\r
-       } else {\r
-               foreach ($options->blocked_urls as $blockurl) {\r
-                       if (stristr($url, $blockurl) !== false) {\r
-                               return false;\r
-                       }\r
-               }\r
-       }\r
-       return true;\r
-}\r
-\r
-//////////////////////////////////////////////\r
-// Convert $html to UTF8\r
-// (uses HTTP headers and HTML to find encoding)\r
-// adapted from http://stackoverflow.com/questions/910793/php-detect-encoding-and-make-everything-utf-8\r
-//////////////////////////////////////////////\r
-function convert_to_utf8($html, $header=null)\r
-{\r
-       $encoding = null;\r
-       if ($html || $header) {\r
-               if (is_array($header)) $header = implode("\n", $header);\r
-               if (!$header || !preg_match_all('/^Content-Type:\s+([^;]+)(?:;\s*charset=["\']?([^;"\'\n]*))?/im', $header, $match, PREG_SET_ORDER)) {\r
-                       // error parsing the response\r
-                       debug('Could not find Content-Type header in HTTP response');\r
-               } else {\r
-                       $match = end($match); // get last matched element (in case of redirects)\r
-                       if (isset($match[2])) $encoding = trim($match[2], "\"' \r\n\0\x0B\t");\r
-               }\r
-               // TODO: check to see if encoding is supported (can we convert it?)\r
-               // If it's not, result will be empty string.\r
-               // For now we'll check for invalid encoding types returned by some sites, e.g. 'none'\r
-               // Problem URL: http://facta.co.jp/blog/archives/20111026001026.html\r
-               if (!$encoding || $encoding == 'none') {\r
-                       // search for encoding in HTML - only look at the first 50000 characters\r
-                       // Why 50000? See, for example, http://www.lemonde.fr/festival-de-cannes/article/2012/05/23/deux-cretes-en-goguette-sur-la-croisette_1705732_766360.html\r
-                       // TODO: improve this so it looks at smaller chunks first\r
-                       $html_head = substr($html, 0, 50000);\r
-                       if (preg_match('/^<\?xml\s+version=(?:"[^"]*"|\'[^\']*\')\s+encoding=("[^"]*"|\'[^\']*\')/s', $html_head, $match)) {\r
-                               $encoding = trim($match[1], '"\'');\r
-                       } elseif (preg_match('/<meta\s+http-equiv=["\']?Content-Type["\']? content=["\'][^;]+;\s*charset=["\']?([^;"\'>]+)/i', $html_head, $match)) {\r
-                               $encoding = trim($match[1]);\r
-                       } elseif (preg_match_all('/<meta\s+([^>]+)>/i', $html_head, $match)) {\r
-                               foreach ($match[1] as $_test) {\r
-                                       if (preg_match('/charset=["\']?([^"\']+)/i', $_test, $_m)) {\r
-                                               $encoding = trim($_m[1]);\r
-                                               break;\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-               if (isset($encoding)) $encoding = trim($encoding);\r
-               // trim is important here!\r
-               if (!$encoding || (strtolower($encoding) == 'iso-8859-1')) {\r
-                       // replace MS Word smart qutoes\r
-                       $trans = array();\r
-                       $trans[chr(130)] = '&sbquo;';    // Single Low-9 Quotation Mark\r
-                       $trans[chr(131)] = '&fnof;';    // Latin Small Letter F With Hook\r
-                       $trans[chr(132)] = '&bdquo;';    // Double Low-9 Quotation Mark\r
-                       $trans[chr(133)] = '&hellip;';    // Horizontal Ellipsis\r
-                       $trans[chr(134)] = '&dagger;';    // Dagger\r
-                       $trans[chr(135)] = '&Dagger;';    // Double Dagger\r
-                       $trans[chr(136)] = '&circ;';    // Modifier Letter Circumflex Accent\r
-                       $trans[chr(137)] = '&permil;';    // Per Mille Sign\r
-                       $trans[chr(138)] = '&Scaron;';    // Latin Capital Letter S With Caron\r
-                       $trans[chr(139)] = '&lsaquo;';    // Single Left-Pointing Angle Quotation Mark\r
-                       $trans[chr(140)] = '&OElig;';    // Latin Capital Ligature OE\r
-                       $trans[chr(145)] = '&lsquo;';    // Left Single Quotation Mark\r
-                       $trans[chr(146)] = '&rsquo;';    // Right Single Quotation Mark\r
-                       $trans[chr(147)] = '&ldquo;';    // Left Double Quotation Mark\r
-                       $trans[chr(148)] = '&rdquo;';    // Right Double Quotation Mark\r
-                       $trans[chr(149)] = '&bull;';    // Bullet\r
-                       $trans[chr(150)] = '&ndash;';    // En Dash\r
-                       $trans[chr(151)] = '&mdash;';    // Em Dash\r
-                       $trans[chr(152)] = '&tilde;';    // Small Tilde\r
-                       $trans[chr(153)] = '&trade;';    // Trade Mark Sign\r
-                       $trans[chr(154)] = '&scaron;';    // Latin Small Letter S With Caron\r
-                       $trans[chr(155)] = '&rsaquo;';    // Single Right-Pointing Angle Quotation Mark\r
-                       $trans[chr(156)] = '&oelig;';    // Latin Small Ligature OE\r
-                       $trans[chr(159)] = '&Yuml;';    // Latin Capital Letter Y With Diaeresis\r
-                       $html = strtr($html, $trans);\r
-               }\r
-               if (!$encoding) {\r
-                       debug('No character encoding found, so treating as UTF-8');\r
-                       $encoding = 'utf-8';\r
-               } else {\r
-                       debug('Character encoding: '.$encoding);\r
-                       if (strtolower($encoding) != 'utf-8') {\r
-                               debug('Converting to UTF-8');\r
-                               $html = SimplePie_Misc::change_encoding($html, $encoding, 'utf-8');\r
-                               /*\r
-                               if (function_exists('iconv')) {\r
-                                       // iconv appears to handle certain character encodings better than mb_convert_encoding\r
-                                       $html = iconv($encoding, 'utf-8', $html);\r
-                               } else {\r
-                                       $html = mb_convert_encoding($html, 'utf-8', $encoding);\r
-                               }\r
-                               */\r
-                       }\r
-               }\r
-       }\r
-       return $html;\r
-}\r
-\r
-function makeAbsolute($base, $elem) {\r
-       $base = new SimplePie_IRI($base);\r
-       // remove '//' in URL path (used to prevent URLs from resolving properly)\r
-       // TODO: check if this is still the case\r
-       if (isset($base->path)) $base->path = preg_replace('!//+!', '/', $base->path);\r
-       foreach(array('a'=>'href', 'img'=>'src') as $tag => $attr) {\r
-               $elems = $elem->getElementsByTagName($tag);\r
-               for ($i = $elems->length-1; $i >= 0; $i--) {\r
-                       $e = $elems->item($i);\r
-                       //$e->parentNode->replaceChild($articleContent->ownerDocument->createTextNode($e->textContent), $e);\r
-                       makeAbsoluteAttr($base, $e, $attr);\r
-               }\r
-               if (strtolower($elem->tagName) == $tag) makeAbsoluteAttr($base, $elem, $attr);\r
-       }\r
-}\r
-function makeAbsoluteAttr($base, $e, $attr) {\r
-       if ($e->hasAttribute($attr)) {\r
-               // Trim leading and trailing white space. I don't really like this but \r
-               // unfortunately it does appear on some sites. e.g.  <img src=" /path/to/image.jpg" />\r
-               $url = trim(str_replace('%20', ' ', $e->getAttribute($attr)));\r
-               $url = str_replace(' ', '%20', $url);\r
-               if (!preg_match('!https?://!i', $url)) {\r
-                       if ($absolute = SimplePie_IRI::absolutize($base, $url)) {\r
-                               $e->setAttribute($attr, $absolute);\r
-                       }\r
-               }\r
-       }\r
-}\r
-function makeAbsoluteStr($base, $url) {\r
-       $base = new SimplePie_IRI($base);\r
-       // remove '//' in URL path (causes URLs not to resolve properly)\r
-       if (isset($base->path)) $base->path = preg_replace('!//+!', '/', $base->path);\r
-       if (preg_match('!^https?://!i', $url)) {\r
-               // already absolute\r
-               return $url;\r
-       } else {\r
-               if ($absolute = SimplePie_IRI::absolutize($base, $url)) {\r
-                       return $absolute;\r
-               }\r
-               return false;\r
-       }\r
-}\r
-// returns single page response, or false if not found\r
-function getSinglePage($item, $html, $url) {\r
-       global $http, $extractor;\r
-       debug('Looking for site config files to see if single page link exists');\r
-       $site_config = $extractor->buildSiteConfig($url, $html);\r
-       $splink = null;\r
-       if (!empty($site_config->single_page_link)) {\r
-               $splink = $site_config->single_page_link;\r
-       } elseif (!empty($site_config->single_page_link_in_feed)) {\r
-               // single page link xpath is targeted at feed\r
-               $splink = $site_config->single_page_link_in_feed;\r
-               // so let's replace HTML with feed item description\r
-               $html = $item->get_description();\r
-       }\r
-       if (isset($splink)) {\r
-               // Build DOM tree from HTML\r
-               $readability = new Readability($html, $url);\r
-               $xpath = new DOMXPath($readability->dom);\r
-               // Loop through single_page_link xpath expressions\r
-               $single_page_url = null;\r
-               foreach ($splink as $pattern) {\r
-                       $elems = @$xpath->evaluate($pattern, $readability->dom);\r
-                       if (is_string($elems)) {\r
-                               $single_page_url = trim($elems);\r
-                               break;\r
-                       } elseif ($elems instanceof DOMNodeList && $elems->length > 0) {\r
-                               foreach ($elems as $item) {\r
-                                       if ($item instanceof DOMElement && $item->hasAttribute('href')) {\r
-                                               $single_page_url = $item->getAttribute('href');\r
-                                               break 2;\r
-                                       } elseif ($item instanceof DOMAttr && $item->value) {\r
-                                               $single_page_url = $item->value;\r
-                                               break 2;\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-               // If we've got URL, resolve against $url\r
-               if (isset($single_page_url) && ($single_page_url = makeAbsoluteStr($url, $single_page_url))) {\r
-                       // check it's not what we have already!\r
-                       if ($single_page_url != $url) {\r
-                               // it's not, so let's try to fetch it...\r
-                               $_prev_ref = $http->referer;\r
-                               $http->referer = $single_page_url;\r
-                               if (($response = $http->get($single_page_url, true)) && $response['status_code'] < 300) {\r
-                                       $http->referer = $_prev_ref;\r
-                                       return $response;\r
-                               }\r
-                               $http->referer = $_prev_ref;\r
-                       }\r
-               }\r
-       }\r
-       return false;\r
-}\r
-\r
-// based on content-type http header, decide what to do\r
-// param: HTTP headers string\r
-// return: array with keys: 'mime', 'type', 'subtype', 'action', 'name'\r
-// e.g. array('mime'=>'image/jpeg', 'type'=>'image', 'subtype'=>'jpeg', 'action'=>'link', 'name'=>'Image')\r
-function get_mime_action_info($headers) {\r
-       global $options;\r
-       // check if action defined for returned Content-Type\r
-       $info = array();\r
-       if (preg_match('!^Content-Type:\s*(([-\w]+)/([-\w\+]+))!im', $headers, $match)) {\r
-               // look for full mime type (e.g. image/jpeg) or just type (e.g. image)\r
-               // match[1] = full mime type, e.g. image/jpeg\r
-               // match[2] = first part, e.g. image\r
-               // match[3] = last part, e.g. jpeg\r
-               $info['mime'] = strtolower(trim($match[1]));\r
-               $info['type'] = strtolower(trim($match[2]));\r
-               $info['subtype'] = strtolower(trim($match[3]));\r
-               foreach (array($info['mime'], $info['type']) as $_mime) {\r
-                       if (isset($options->content_type_exc[$_mime])) {\r
-                               $info['action'] = $options->content_type_exc[$_mime]['action'];\r
-                               $info['name'] = $options->content_type_exc[$_mime]['name'];\r
-                               break;\r
-                       }\r
-               }\r
-       }\r
-       return $info;\r
-}\r
-\r
-function remove_url_cruft($url) {\r
-       // remove google analytics for the time being\r
-       // regex adapted from http://navitronic.co.uk/2010/12/removing-google-analytics-cruft-from-urls/\r
-       // https://gist.github.com/758177\r
-       return preg_replace('/(\?|\&)utm_[a-z]+=[^\&]+/', '', $url);\r
-}\r
-\r
-function make_substitutions($string) {\r
-       if ($string == '') return $string;\r
-       global $item, $effective_url;\r
-       $string = str_replace('{url}', htmlspecialchars($item->get_permalink()), $string);\r
-       $string = str_replace('{effective-url}', htmlspecialchars($effective_url), $string);\r
-       return $string;\r
-}\r
-\r
-function get_cache() {\r
-       global $options, $valid_key;\r
-       static $cache = null;\r
-       if ($cache === null) {\r
-               $frontendOptions = array(\r
-                       'lifetime' => 10*60, // cache lifetime of 10 minutes\r
-                       'automatic_serialization' => false,\r
-                       'write_control' => false,\r
-                       'automatic_cleaning_factor' => $options->cache_cleanup,\r
-                       'ignore_user_abort' => false\r
-               );\r
-               $backendOptions = array(\r
-                       'cache_dir' => ($valid_key) ? $options->cache_dir.'/rss-with-key/' : $options->cache_dir.'/rss/', // directory where to put the cache files\r
-                       'file_locking' => false,\r
-                       'read_control' => true,\r
-                       'read_control_type' => 'strlen',\r
-                       'hashed_directory_level' => $options->cache_directory_level,\r
-                       'hashed_directory_perm' => 0777,\r
-                       'cache_file_perm' => 0664,\r
-                       'file_name_prefix' => 'ff'\r
-               );\r
-               // getting a Zend_Cache_Core object\r
-               $cache = Zend_Cache::factory('Core', 'File', $frontendOptions, $backendOptions);\r
-       }\r
-       return $cache;\r
-}\r
-\r
-function debug($msg) {\r
-       global $debug_mode;\r
-       if ($debug_mode) {\r
-               echo '* ',$msg,"\n";\r
-               ob_flush();\r
-               flush();\r
-       }\r
-}
\ No newline at end of file
diff --git a/inc/3rdparty/makefulltextfeedHelpers.php b/inc/3rdparty/makefulltextfeedHelpers.php
new file mode 100755 (executable)
index 0000000..ac872ab
--- /dev/null
@@ -0,0 +1,389 @@
+<?php
+
+// Autoloading of classes allows us to include files only when they're
+// needed. If we've got a cached copy, for example, only Zend_Cache is loaded.
+function autoload($class_name) {
+       static $dir = null;
+       if ($dir === null) $dir = dirname(__FILE__).'/libraries/';
+       static $mapping = array(
+               // Include FeedCreator for RSS/Atom creation
+               'FeedWriter' => 'feedwriter/FeedWriter.php',
+               'FeedItem' => 'feedwriter/FeedItem.php',
+               // Include ContentExtractor and Readability for identifying and extracting content from URLs
+               'ContentExtractor' => 'content-extractor/ContentExtractor.php',
+               'SiteConfig' => 'content-extractor/SiteConfig.php',
+               'Readability' => 'readability/Readability.php',
+               // Include Humble HTTP Agent to allow parallel requests and response caching
+               'HumbleHttpAgent' => 'humble-http-agent/HumbleHttpAgent.php',
+               'SimplePie_HumbleHttpAgent' => 'humble-http-agent/SimplePie_HumbleHttpAgent.php',
+               'CookieJar' => 'humble-http-agent/CookieJar.php',
+               // Include Zend Cache to improve performance (cache results)
+               'Zend_Cache' => 'Zend/Cache.php',
+               // Language detect
+               'Text_LanguageDetect' => 'language-detect/LanguageDetect.php',
+               // HTML5 Lib
+               'HTML5_Parser' => 'html5/Parser.php',
+               // htmLawed - used if XSS filter is enabled (xss_filter)
+               'htmLawed' => 'htmLawed/htmLawed.php'
+       );
+       if (isset($mapping[$class_name])) {
+               debug("** Loading class $class_name ({$mapping[$class_name]})");
+               require $dir.$mapping[$class_name];
+               return true;
+       } else {
+               return false;
+       }
+}
+spl_autoload_register('autoload');
+require dirname(__FILE__).'/libraries/simplepie/autoloader.php';
+
+
+class DummySingleItemFeed {
+       public $item;
+       function __construct($url) { $this->item = new DummySingleItem($url); }
+       public function get_title() { return ''; }
+       public function get_description() { return 'Content extracted from '.$this->item->url; }
+       public function get_link() { return $this->item->url; }
+       public function get_language() { return false; }
+       public function get_image_url() { return false; }
+       public function get_items($start=0, $max=1) { return array(0=>$this->item); }
+}
+class DummySingleItem {
+       public $url;
+       function __construct($url) { $this->url = $url; }
+       public function get_permalink() { return $this->url; }
+       public function get_title() { return null; }
+       public function get_date($format='') { return false; }
+       public function get_author($key=0) { return null; }
+       public function get_authors() { return null; }
+       public function get_description() { return ''; }
+       public function get_enclosure($key=0, $prefer=null) { return null; }
+       public function get_enclosures() { return null; }
+       public function get_categories() { return null; }
+}
+
+///////////////////////////////
+// HELPER FUNCTIONS
+///////////////////////////////
+
+// Adapted from WordPress\r
+// http://core.trac.wordpress.org/browser/tags/3.5.1/wp-includes/formatting.php#L2173\r
+function get_excerpt($text, $num_words=55, $more=null) {\r
+       if (null === $more) $more = '&hellip;';\r
+       $text = strip_tags($text);\r
+       //TODO: Check if word count is based on single characters (East Asian characters)\r
+       /*\r
+       if (1==2) {\r
+       $text = trim(preg_replace("/[\n\r\t ]+/", ' ', $text), ' ');\r
+       preg_match_all('/./u', $text, $words_array);\r
+       $words_array = array_slice($words_array[0], 0, $num_words + 1);\r
+       $sep = '';\r
+       } else {\r
+       $words_array = preg_split("/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY);\r
+       $sep = ' ';\r
+       }\r
+       */\r
+       $words_array = preg_split("/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY);\r
+       $sep = ' ';\r
+       if (count($words_array) > $num_words) {\r
+               array_pop($words_array);\r
+               $text = implode($sep, $words_array);\r
+               $text = $text.$more;\r
+       } else {\r
+               $text = implode($sep, $words_array);\r
+       }\r
+       // trim whitespace at beginning or end of string\r
+       // See: http://stackoverflow.com/questions/4166896/trim-unicode-whitespace-in-php-5-2\r
+       $text = preg_replace('/^[\pZ\pC]+|[\pZ\pC]+$/u', '', $text);\r
+       return $text;\r
+}\r
+\r
+function url_allowed($url) {
+       global $options;
+       if (!empty($options->allowed_urls)) {
+               $allowed = false;
+               foreach ($options->allowed_urls as $allowurl) {
+                       if (stristr($url, $allowurl) !== false) {
+                               $allowed = true;
+                               break;
+                       }
+               }
+               if (!$allowed) return false;
+       } else {
+               foreach ($options->blocked_urls as $blockurl) {
+                       if (stristr($url, $blockurl) !== false) {
+                               return false;
+                       }
+               }
+       }
+       return true;
+}
+
+//////////////////////////////////////////////
+// Convert $html to UTF8
+// (uses HTTP headers and HTML to find encoding)
+// adapted from http://stackoverflow.com/questions/910793/php-detect-encoding-and-make-everything-utf-8
+//////////////////////////////////////////////
+function convert_to_utf8($html, $header=null)
+{
+       $encoding = null;
+       if ($html || $header) {
+               if (is_array($header)) $header = implode("\n", $header);
+               if (!$header || !preg_match_all('/^Content-Type:\s+([^;]+)(?:;\s*charset=["\']?([^;"\'\n]*))?/im', $header, $match, PREG_SET_ORDER)) {
+                       // error parsing the response
+                       debug('Could not find Content-Type header in HTTP response');
+               } else {
+                       $match = end($match); // get last matched element (in case of redirects)
+                       if (isset($match[2])) $encoding = trim($match[2], "\"' \r\n\0\x0B\t");
+               }
+               // TODO: check to see if encoding is supported (can we convert it?)
+               // If it's not, result will be empty string.
+               // For now we'll check for invalid encoding types returned by some sites, e.g. 'none'
+               // Problem URL: http://facta.co.jp/blog/archives/20111026001026.html
+               if (!$encoding || $encoding == 'none') {
+                       // search for encoding in HTML - only look at the first 50000 characters
+                       // Why 50000? See, for example, http://www.lemonde.fr/festival-de-cannes/article/2012/05/23/deux-cretes-en-goguette-sur-la-croisette_1705732_766360.html
+                       // TODO: improve this so it looks at smaller chunks first
+                       $html_head = substr($html, 0, 50000);
+                       if (preg_match('/^<\?xml\s+version=(?:"[^"]*"|\'[^\']*\')\s+encoding=("[^"]*"|\'[^\']*\')/s', $html_head, $match)) {
+                               $encoding = trim($match[1], '"\'');
+                       } elseif (preg_match('/<meta\s+http-equiv=["\']?Content-Type["\']? content=["\'][^;]+;\s*charset=["\']?([^;"\'>]+)/i', $html_head, $match)) {
+                               $encoding = trim($match[1]);
+                       } elseif (preg_match_all('/<meta\s+([^>]+)>/i', $html_head, $match)) {
+                               foreach ($match[1] as $_test) {
+                                       if (preg_match('/charset=["\']?([^"\']+)/i', $_test, $_m)) {
+                                               $encoding = trim($_m[1]);
+                                               break;
+                                       }
+                               }
+                       }
+               }
+               if (isset($encoding)) $encoding = trim($encoding);
+               // trim is important here!
+               if (!$encoding || (strtolower($encoding) == 'iso-8859-1')) {
+                       // replace MS Word smart qutoes
+                       $trans = array();
+                       $trans[chr(130)] = '&sbquo;';    // Single Low-9 Quotation Mark
+                       $trans[chr(131)] = '&fnof;';    // Latin Small Letter F With Hook
+                       $trans[chr(132)] = '&bdquo;';    // Double Low-9 Quotation Mark
+                       $trans[chr(133)] = '&hellip;';    // Horizontal Ellipsis
+                       $trans[chr(134)] = '&dagger;';    // Dagger
+                       $trans[chr(135)] = '&Dagger;';    // Double Dagger
+                       $trans[chr(136)] = '&circ;';    // Modifier Letter Circumflex Accent
+                       $trans[chr(137)] = '&permil;';    // Per Mille Sign
+                       $trans[chr(138)] = '&Scaron;';    // Latin Capital Letter S With Caron
+                       $trans[chr(139)] = '&lsaquo;';    // Single Left-Pointing Angle Quotation Mark
+                       $trans[chr(140)] = '&OElig;';    // Latin Capital Ligature OE
+                       $trans[chr(145)] = '&lsquo;';    // Left Single Quotation Mark
+                       $trans[chr(146)] = '&rsquo;';    // Right Single Quotation Mark
+                       $trans[chr(147)] = '&ldquo;';    // Left Double Quotation Mark
+                       $trans[chr(148)] = '&rdquo;';    // Right Double Quotation Mark
+                       $trans[chr(149)] = '&bull;';    // Bullet
+                       $trans[chr(150)] = '&ndash;';    // En Dash
+                       $trans[chr(151)] = '&mdash;';    // Em Dash
+                       $trans[chr(152)] = '&tilde;';    // Small Tilde
+                       $trans[chr(153)] = '&trade;';    // Trade Mark Sign
+                       $trans[chr(154)] = '&scaron;';    // Latin Small Letter S With Caron
+                       $trans[chr(155)] = '&rsaquo;';    // Single Right-Pointing Angle Quotation Mark
+                       $trans[chr(156)] = '&oelig;';    // Latin Small Ligature OE
+                       $trans[chr(159)] = '&Yuml;';    // Latin Capital Letter Y With Diaeresis
+                       $html = strtr($html, $trans);
+               }
+               if (!$encoding) {
+                       debug('No character encoding found, so treating as UTF-8');
+                       $encoding = 'utf-8';
+               } else {
+                       debug('Character encoding: '.$encoding);
+                       if (strtolower($encoding) != 'utf-8') {
+                               debug('Converting to UTF-8');
+                               $html = SimplePie_Misc::change_encoding($html, $encoding, 'utf-8');
+                       }
+               }
+       }
+       return $html;
+}
+
+function makeAbsolute($base, $elem) {
+       $base = new SimplePie_IRI($base);
+       // remove '//' in URL path (used to prevent URLs from resolving properly)
+       // TODO: check if this is still the case
+       if (isset($base->path)) $base->path = preg_replace('!//+!', '/', $base->path);
+       foreach(array('a'=>'href', 'img'=>'src') as $tag => $attr) {
+               $elems = $elem->getElementsByTagName($tag);
+               for ($i = $elems->length-1; $i >= 0; $i--) {
+                       $e = $elems->item($i);
+                       //$e->parentNode->replaceChild($articleContent->ownerDocument->createTextNode($e->textContent), $e);
+                       makeAbsoluteAttr($base, $e, $attr);
+               }
+               if (strtolower($elem->tagName) == $tag) makeAbsoluteAttr($base, $elem, $attr);
+       }
+}
+function makeAbsoluteAttr($base, $e, $attr) {
+       if ($e->hasAttribute($attr)) {
+               // Trim leading and trailing white space. I don't really like this but
+               // unfortunately it does appear on some sites. e.g.  <img src=" /path/to/image.jpg" />
+               $url = trim(str_replace('%20', ' ', $e->getAttribute($attr)));
+               $url = str_replace(' ', '%20', $url);
+               if (!preg_match('!https?://!i', $url)) {
+                       if ($absolute = SimplePie_IRI::absolutize($base, $url)) {
+                               $e->setAttribute($attr, $absolute);
+                       }
+               }
+       }
+}
+function makeAbsoluteStr($base, $url) {
+       $base = new SimplePie_IRI($base);
+       // remove '//' in URL path (causes URLs not to resolve properly)
+       if (isset($base->path)) $base->path = preg_replace('!//+!', '/', $base->path);
+       if (preg_match('!^https?://!i', $url)) {
+               // already absolute
+               return $url;
+       } else {
+               if ($absolute = SimplePie_IRI::absolutize($base, $url)) {
+                       return $absolute;
+               }
+               return false;
+       }
+}
+// returns single page response, or false if not found
+function getSinglePage($item, $html, $url) {
+       global $http, $extractor;
+       debug('Looking for site config files to see if single page link exists');
+       $site_config = $extractor->buildSiteConfig($url, $html);
+       $splink = null;
+       if (!empty($site_config->single_page_link)) {
+               $splink = $site_config->single_page_link;
+       } elseif (!empty($site_config->single_page_link_in_feed)) {
+               // single page link xpath is targeted at feed
+               $splink = $site_config->single_page_link_in_feed;
+               // so let's replace HTML with feed item description
+               $html = $item->get_description();
+       }
+       if (isset($splink)) {
+               // Build DOM tree from HTML
+               $readability = new Readability($html, $url);
+               $xpath = new DOMXPath($readability->dom);
+               // Loop through single_page_link xpath expressions
+               $single_page_url = null;
+               foreach ($splink as $pattern) {
+                       $elems = @$xpath->evaluate($pattern, $readability->dom);
+                       if (is_string($elems)) {
+                               $single_page_url = trim($elems);
+                               break;
+                       } elseif ($elems instanceof DOMNodeList && $elems->length > 0) {
+                               foreach ($elems as $item) {
+                                       if ($item instanceof DOMElement && $item->hasAttribute('href')) {
+                                               $single_page_url = $item->getAttribute('href');
+                                               break 2;
+                                       } elseif ($item instanceof DOMAttr && $item->value) {
+                                               $single_page_url = $item->value;
+                                               break 2;
+                                       }
+                               }
+                       }
+               }
+               // If we've got URL, resolve against $url
+               if (isset($single_page_url) && ($single_page_url = makeAbsoluteStr($url, $single_page_url))) {
+                       // check it's not what we have already!
+                       if ($single_page_url != $url) {
+                               // it's not, so let's try to fetch it...
+                               $_prev_ref = $http->referer;
+                               $http->referer = $single_page_url;
+                               if (($response = $http->get($single_page_url, true)) && $response['status_code'] < 300) {
+                                       $http->referer = $_prev_ref;
+                                       return $response;
+                               }
+                               $http->referer = $_prev_ref;
+                       }
+               }
+       }
+       return false;
+}
+
+// based on content-type http header, decide what to do
+// param: HTTP headers string
+// return: array with keys: 'mime', 'type', 'subtype', 'action', 'name'
+// e.g. array('mime'=>'image/jpeg', 'type'=>'image', 'subtype'=>'jpeg', 'action'=>'link', 'name'=>'Image')
+function get_mime_action_info($headers) {
+       global $options;
+       // check if action defined for returned Content-Type
+       $info = array();
+       if (preg_match('!^Content-Type:\s*(([-\w]+)/([-\w\+]+))!im', $headers, $match)) {
+               // look for full mime type (e.g. image/jpeg) or just type (e.g. image)
+               // match[1] = full mime type, e.g. image/jpeg
+               // match[2] = first part, e.g. image
+               // match[3] = last part, e.g. jpeg
+               $info['mime'] = strtolower(trim($match[1]));
+               $info['type'] = strtolower(trim($match[2]));
+               $info['subtype'] = strtolower(trim($match[3]));
+               foreach (array($info['mime'], $info['type']) as $_mime) {
+                       if (isset($options->content_type_exc[$_mime])) {
+                               $info['action'] = $options->content_type_exc[$_mime]['action'];
+                               $info['name'] = $options->content_type_exc[$_mime]['name'];
+                               break;
+                       }
+               }
+       }
+       return $info;
+}
+
+function remove_url_cruft($url) {
+       // remove google analytics for the time being
+       // regex adapted from http://navitronic.co.uk/2010/12/removing-google-analytics-cruft-from-urls/
+       // https://gist.github.com/758177
+       return preg_replace('/(\?|\&)utm_[a-z]+=[^\&]+/', '', $url);
+}
+
+function make_substitutions($string) {
+       if ($string == '') return $string;
+       global $item, $effective_url;
+       $string = str_replace('{url}', htmlspecialchars($item->get_permalink()), $string);
+       $string = str_replace('{effective-url}', htmlspecialchars($effective_url), $string);
+       return $string;
+}
+
+function get_cache() {
+       global $options, $valid_key;
+       static $cache = null;
+       if ($cache === null) {
+               $frontendOptions = array(
+                       'lifetime' => 10*60, // cache lifetime of 10 minutes
+                       'automatic_serialization' => false,
+                       'write_control' => false,
+                       'automatic_cleaning_factor' => $options->cache_cleanup,
+                       'ignore_user_abort' => false
+               );
+               $backendOptions = array(
+                       'cache_dir' => ($valid_key) ? $options->cache_dir.'/rss-with-key/' : $options->cache_dir.'/rss/', // directory where to put the cache files
+                       'file_locking' => false,
+                       'read_control' => true,
+                       'read_control_type' => 'strlen',
+                       'hashed_directory_level' => $options->cache_directory_level,
+                       'hashed_directory_perm' => 0777,
+                       'cache_file_perm' => 0664,
+                       'file_name_prefix' => 'ff'
+               );
+               // getting a Zend_Cache_Core object
+               $cache = Zend_Cache::factory('Core', 'File', $frontendOptions, $backendOptions);
+       }
+       return $cache;
+}
+
+function debug($msg) {
+       global $debug_mode;
+       if ($debug_mode) {
+               echo '* ',$msg,"\n";
+               ob_flush();
+               flush();
+       }
+}
+
+function get_base_url($dom) {\r
+       $xpath = new DOMXPath($dom);\r
+       $base_url = @$xpath->evaluate('string(//head/base/@href)', $dom);\r
+       if ($base_url !== '') {\r
+               return $base_url;\r
+       } else {\r
+               return false;\r
+       }\r
+}
old mode 100644 (file)
new mode 100755 (executable)
index 43b94e5..9b73b10
@@ -34,7 +34,7 @@
  * @author S.C. Chen <me578022@gmail.com>\r
  * @author John Schlick\r
  * @author Rus Carroll\r
- * @version 1.5 ($Rev: 202 $)\r
+ * @version 1.5 ($Rev: 210 $)\r
  * @package PlaceLocalInclude\r
  * @subpackage simple_html_dom\r
  */\r
@@ -269,7 +269,10 @@ class simple_html_dom_node
                {\r
                        return $this->children;\r
                }\r
-               if (isset($this->children[$idx])) return $this->children[$idx];\r
+               if (isset($this->children[$idx]))\r
+               {\r
+                       return $this->children[$idx];\r
+               }\r
                return null;\r
        }\r
 \r
@@ -330,14 +333,14 @@ class simple_html_dom_node
        function find_ancestor_tag($tag)\r
        {\r
                global $debug_object;\r
-               if (is_object($debug_object)) { $debug_object->debugLogEntry(1); }\r
+               if (is_object($debug_object)) { $debug_object->debug_log_entry(1); }\r
 \r
                // Start by including ourselves in the comparison.\r
                $returnDom = $this;\r
 \r
                while (!is_null($returnDom))\r
                {\r
-                       if (is_object($debug_object)) { $debug_object->debugLog(2, "Current tag is: " . $returnDom->tag); }\r
+                       if (is_object($debug_object)) { $debug_object->debug_log(2, "Current tag is: " . $returnDom->tag); }\r
 \r
                        if ($returnDom->tag == $tag)\r
                        {\r
@@ -374,7 +377,7 @@ class simple_html_dom_node
                                        $text = " with text: " . $this->text;\r
                                }\r
                        }\r
-                       $debug_object->debugLog(1, 'Innertext of tag: ' . $this->tag . $text);\r
+                       $debug_object->debug_log(1, 'Innertext of tag: ' . $this->tag . $text);\r
                }\r
 \r
                if ($this->tag==='root') return $this->innertext();\r
@@ -532,7 +535,9 @@ class simple_html_dom_node
                        foreach ($head as $k=>$v)\r
                        {\r
                                if (!isset($found_keys[$k]))\r
+                               {\r
                                        $found_keys[$k] = 1;\r
+                               }\r
                        }\r
                }\r
 \r
@@ -554,7 +559,7 @@ class simple_html_dom_node
        protected function seek($selector, &$ret, $lowercase=false)\r
        {\r
                global $debug_object;\r
-               if (is_object($debug_object)) { $debug_object->debugLogEntry(1); }\r
+               if (is_object($debug_object)) { $debug_object->debug_log_entry(1); }\r
 \r
                list($tag, $key, $val, $exp, $no_key) = $selector;\r
 \r
@@ -615,7 +620,7 @@ class simple_html_dom_node
                                        // this is a normal search, we want the value of that attribute of the tag.\r
                                        $nodeKeyValue = $node->attr[$key];\r
                                }\r
-                               if (is_object($debug_object)) {$debug_object->debugLog(2, "testing node: " . $node->tag . " for attribute: " . $key . $exp . $val . " where nodes value is: " . $nodeKeyValue);}\r
+                               if (is_object($debug_object)) {$debug_object->debug_log(2, "testing node: " . $node->tag . " for attribute: " . $key . $exp . $val . " where nodes value is: " . $nodeKeyValue);}\r
 \r
                                //PaperG - If lowercase is set, do a case insensitive test of the value of the selector.\r
                                if ($lowercase) {\r
@@ -623,7 +628,7 @@ class simple_html_dom_node
                                } else {\r
                                        $check = $this->match($exp, $val, $nodeKeyValue);\r
                                }\r
-                               if (is_object($debug_object)) {$debug_object->debugLog(2, "after match: " . ($check ? "true" : "false"));}\r
+                               if (is_object($debug_object)) {$debug_object->debug_log(2, "after match: " . ($check ? "true" : "false"));}\r
 \r
                                // handle multiple class\r
                                if (!$check && strcasecmp($key, 'class')===0) {\r
@@ -645,12 +650,12 @@ class simple_html_dom_node
                        unset($node);\r
                }\r
                // It's passed by reference so this is actually what this function returns.\r
-               if (is_object($debug_object)) {$debug_object->debugLog(1, "EXIT - ret: ", $ret);}\r
+               if (is_object($debug_object)) {$debug_object->debug_log(1, "EXIT - ret: ", $ret);}\r
        }\r
 \r
        protected function match($exp, $pattern, $value) {\r
                global $debug_object;\r
-               if (is_object($debug_object)) {$debug_object->debugLogEntry(1);}\r
+               if (is_object($debug_object)) {$debug_object->debug_log_entry(1);}\r
 \r
                switch ($exp) {\r
                        case '=':\r
@@ -672,7 +677,7 @@ class simple_html_dom_node
 \r
        protected function parse_selector($selector_string) {\r
                global $debug_object;\r
-               if (is_object($debug_object)) {$debug_object->debugLogEntry(1);}\r
+               if (is_object($debug_object)) {$debug_object->debug_log_entry(1);}\r
 \r
                // pattern of CSS selectors, modified from mootools\r
                // Paperg: Add the colon to the attrbute, so that it properly finds <tag attr:ibute="something" > like google does.\r
@@ -683,7 +688,7 @@ class simple_html_dom_node
 //             $pattern = "/([\w-:\*]*)(?:\#([\w-]+)|\.([\w-]+))?(?:\[@?(!?[\w-]+)(?:([!*^$]?=)[\"']?(.*?)[\"']?)?\])?([\/, ]+)/is";\r
                $pattern = "/([\w-:\*]*)(?:\#([\w-]+)|\.([\w-]+))?(?:\[@?(!?[\w-:]+)(?:([!*^$]?=)[\"']?(.*?)[\"']?)?\])?([\/, ]+)/is";\r
                preg_match_all($pattern, trim($selector_string).' ', $matches, PREG_SET_ORDER);\r
-               if (is_object($debug_object)) {$debug_object->debugLog(2, "Matches Array: ", $matches);}\r
+               if (is_object($debug_object)) {$debug_object->debug_log(2, "Matches Array: ", $matches);}\r
 \r
                $selectors = array();\r
                $result = array();\r
@@ -718,12 +723,14 @@ class simple_html_dom_node
                return $selectors;\r
        }\r
 \r
-       function __get($name) {\r
+       function __get($name)\r
+       {\r
                if (isset($this->attr[$name]))\r
                {\r
                        return $this->convert_text($this->attr[$name]);\r
                }\r
-               switch ($name) {\r
+               switch ($name)\r
+               {\r
                        case 'outertext': return $this->outertext();\r
                        case 'innertext': return $this->innertext();\r
                        case 'plaintext': return $this->text();\r
@@ -732,22 +739,30 @@ class simple_html_dom_node
                }\r
        }\r
 \r
-       function __set($name, $value) {\r
-               switch ($name) {\r
+       function __set($name, $value)\r
+       {\r
+               global $debug_object;\r
+               if (is_object($debug_object)) {$debug_object->debug_log_entry(1);}\r
+\r
+               switch ($name)\r
+               {\r
                        case 'outertext': return $this->_[HDOM_INFO_OUTER] = $value;\r
                        case 'innertext':\r
                                if (isset($this->_[HDOM_INFO_TEXT])) return $this->_[HDOM_INFO_TEXT] = $value;\r
                                return $this->_[HDOM_INFO_INNER] = $value;\r
                }\r
-               if (!isset($this->attr[$name])) {\r
+               if (!isset($this->attr[$name]))\r
+               {\r
                        $this->_[HDOM_INFO_SPACE][] = array(' ', '', '');\r
                        $this->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_DOUBLE;\r
                }\r
                $this->attr[$name] = $value;\r
        }\r
 \r
-       function __isset($name) {\r
-               switch ($name) {\r
+       function __isset($name)\r
+       {\r
+               switch ($name)\r
+               {\r
                        case 'outertext': return true;\r
                        case 'innertext': return true;\r
                        case 'plaintext': return true;\r
@@ -765,7 +780,7 @@ class simple_html_dom_node
        function convert_text($text)\r
        {\r
                global $debug_object;\r
-               if (is_object($debug_object)) {$debug_object->debugLogEntry(1);}\r
+               if (is_object($debug_object)) {$debug_object->debug_log_entry(1);}\r
 \r
                $converted_text = $text;\r
 \r
@@ -777,7 +792,7 @@ class simple_html_dom_node
                        $sourceCharset = strtoupper($this->dom->_charset);\r
                        $targetCharset = strtoupper($this->dom->_target_charset);\r
                }\r
-               if (is_object($debug_object)) {$debug_object->debugLog(3, "source charset: " . $sourceCharset . " target charaset: " . $targetCharset);}\r
+               if (is_object($debug_object)) {$debug_object->debug_log(3, "source charset: " . $sourceCharset . " target charaset: " . $targetCharset);}\r
 \r
                if (!empty($sourceCharset) && !empty($targetCharset) && (strcasecmp($sourceCharset, $targetCharset) != 0))\r
                {\r
@@ -1045,10 +1060,10 @@ class simple_html_dom
 \r
                // prepare\r
                $this->prepare($str, $lowercase, $stripRN, $defaultBRText, $defaultSpanText);\r
-               // strip out comments\r
-               $this->remove_noise("'<!--(.*?)-->'is");\r
                // strip out cdata\r
                $this->remove_noise("'<!\[CDATA\[(.*?)\]\]>'is", true);\r
+               // strip out comments\r
+               $this->remove_noise("'<!--(.*?)-->'is");\r
                // Per sourceforge http://sourceforge.net/tracker/?func=detail&aid=2949097&group_id=218559&atid=1044037\r
                // Script tags removal now preceeds style tag removal.\r
                // strip out <script> tags\r
@@ -1078,10 +1093,15 @@ class simple_html_dom
        // load html from file\r
        function load_file()\r
        {\r
+         //external error: NOT related to dom loading\r
+         $extError=error_get_last();\r
+\r
                $args = func_get_args();\r
                $this->load(call_user_func_array('file_get_contents', $args), true);\r
+\r
                // Throw an error if we can't properly load the dom.\r
-               if (($error=error_get_last())!==null) {\r
+               $error=error_get_last();\r
+               if ($error!==$extError) {\r
                        $this->clear();\r
                        return false;\r
                }\r
@@ -1198,22 +1218,22 @@ class simple_html_dom
                        if ($success)\r
                        {\r
                                $charset = $matches[1];\r
-                               if (is_object($debug_object)) {$debug_object->debugLog(2, 'header content-type found charset of: ' . $charset);}\r
+                               if (is_object($debug_object)) {$debug_object->debug_log(2, 'header content-type found charset of: ' . $charset);}\r
                        }\r
 \r
                }\r
 \r
                if (empty($charset))\r
                {\r
-                       $el = $this->root->find('meta[http-equiv=Content-Type]',0);\r
+                       $el = $this->root->find('meta[http-equiv=Content-Type]',0, true);\r
                        if (!empty($el))\r
                        {\r
                                $fullvalue = $el->content;\r
-                               if (is_object($debug_object)) {$debug_object->debugLog(2, 'meta content-type tag found' . $fullvalue);}\r
+                               if (is_object($debug_object)) {$debug_object->debug_log(2, 'meta content-type tag found' . $fullvalue);}\r
 \r
                                if (!empty($fullvalue))\r
                                {\r
-                                       $success = preg_match('/charset=(.+)/', $fullvalue, $matches);\r
+                                       $success = preg_match('/charset=(.+)/i', $fullvalue, $matches);\r
                                        if ($success)\r
                                        {\r
                                                $charset = $matches[1];\r
@@ -1221,7 +1241,7 @@ class simple_html_dom
                                        else\r
                                        {\r
                                                // If there is a meta tag, and they don't specify the character set, research says that it's typically ISO-8859-1\r
-                                               if (is_object($debug_object)) {$debug_object->debugLog(2, 'meta content-type tag couldn\'t be parsed. using iso-8859 default.');}\r
+                                               if (is_object($debug_object)) {$debug_object->debug_log(2, 'meta content-type tag couldn\'t be parsed. using iso-8859 default.');}\r
                                                $charset = 'ISO-8859-1';\r
                                        }\r
                                }\r
@@ -1231,14 +1251,19 @@ class simple_html_dom
                // If we couldn't find a charset above, then lets try to detect one based on the text we got...\r
                if (empty($charset))\r
                {\r
-                       // Have php try to detect the encoding from the text given to us.\r
-                       $charset = mb_detect_encoding($this->root->plaintext . "ascii", $encoding_list = array( "UTF-8", "CP1252" ) );\r
-                       if (is_object($debug_object)) {$debug_object->debugLog(2, 'mb_detect found: ' . $charset);}\r
+                       // Use this in case mb_detect_charset isn't installed/loaded on this machine.\r
+                       $charset = false;\r
+                       if (function_exists('mb_detect_encoding'))\r
+                       {\r
+                               // Have php try to detect the encoding from the text given to us.\r
+                               $charset = mb_detect_encoding($this->root->plaintext . "ascii", $encoding_list = array( "UTF-8", "CP1252" ) );\r
+                               if (is_object($debug_object)) {$debug_object->debug_log(2, 'mb_detect found: ' . $charset);}\r
+                       }\r
 \r
                        // and if this doesn't work...  then we need to just wrongheadedly assume it's UTF-8 so that we can move on - cause this will usually give us most of what we need...\r
                        if ($charset === false)\r
                        {\r
-                               if (is_object($debug_object)) {$debug_object->debugLog(2, 'since mb_detect failed - using default of utf-8');}\r
+                               if (is_object($debug_object)) {$debug_object->debug_log(2, 'since mb_detect failed - using default of utf-8');}\r
                                $charset = 'UTF-8';\r
                        }\r
                }\r
@@ -1246,11 +1271,11 @@ class simple_html_dom
                // Since CP1252 is a superset, if we get one of it's subsets, we want it instead.\r
                if ((strtolower($charset) == strtolower('ISO-8859-1')) || (strtolower($charset) == strtolower('Latin1')) || (strtolower($charset) == strtolower('Latin-1')))\r
                {\r
-                       if (is_object($debug_object)) {$debug_object->debugLog(2, 'replacing ' . $charset . ' with CP1252 as its a superset');}\r
+                       if (is_object($debug_object)) {$debug_object->debug_log(2, 'replacing ' . $charset . ' with CP1252 as its a superset');}\r
                        $charset = 'CP1252';\r
                }\r
 \r
-               if (is_object($debug_object)) {$debug_object->debugLog(1, 'EXIT - ' . $charset);}\r
+               if (is_object($debug_object)) {$debug_object->debug_log(1, 'EXIT - ' . $charset);}\r
 \r
                return $this->_charset = $charset;\r
        }\r
@@ -1616,14 +1641,14 @@ class simple_html_dom
        protected function remove_noise($pattern, $remove_tag=false)\r
        {\r
                global $debug_object;\r
-               if (is_object($debug_object)) { $debug_object->debugLogEntry(1); }\r
+               if (is_object($debug_object)) { $debug_object->debug_log_entry(1); }\r
 \r
                $count = preg_match_all($pattern, $this->doc, $matches, PREG_SET_ORDER|PREG_OFFSET_CAPTURE);\r
 \r
                for ($i=$count-1; $i>-1; --$i)\r
                {\r
                        $key = '___noise___'.sprintf('% 5d', count($this->noise)+1000);\r
-                       if (is_object($debug_object)) { $debug_object->debugLog(2, 'key is: ' . $key); }\r
+                       if (is_object($debug_object)) { $debug_object->debug_log(2, 'key is: ' . $key); }\r
                        $idx = ($remove_tag) ? 0 : 1;\r
                        $this->noise[$key] = $matches[$i][$idx][0];\r
                        $this->doc = substr_replace($this->doc, $key, $matches[$i][$idx][1], strlen($matches[$i][$idx][0]));\r
@@ -1641,7 +1666,7 @@ class simple_html_dom
        function restore_noise($text)\r
        {\r
                global $debug_object;\r
-               if (is_object($debug_object)) { $debug_object->debugLogEntry(1); }\r
+               if (is_object($debug_object)) { $debug_object->debug_log_entry(1); }\r
 \r
                while (($pos=strpos($text, '___noise___'))!==false)\r
                {\r
@@ -1649,7 +1674,7 @@ class simple_html_dom
                        if (strlen($text) > $pos+15)\r
                        {\r
                                $key = '___noise___'.$text[$pos+11].$text[$pos+12].$text[$pos+13].$text[$pos+14].$text[$pos+15];\r
-                               if (is_object($debug_object)) { $debug_object->debugLog(2, 'located key of: ' . $key); }\r
+                               if (is_object($debug_object)) { $debug_object->debug_log(2, 'located key of: ' . $key); }\r
 \r
                                if (isset($this->noise[$key]))\r
                                {\r
@@ -1674,7 +1699,7 @@ class simple_html_dom
        function search_noise($text)\r
        {\r
                global $debug_object;\r
-               if (is_object($debug_object)) { $debug_object->debugLogEntry(1); }\r
+               if (is_object($debug_object)) { $debug_object->debug_log_entry(1); }\r
 \r
                foreach($this->noise as $noiseElement)\r
                {\r
diff --git a/inc/3rdparty/site_config/custom/dailymotion.com.txt b/inc/3rdparty/site_config/custom/dailymotion.com.txt
new file mode 100755 (executable)
index 0000000..0cad808
--- /dev/null
@@ -0,0 +1,12 @@
+title: //title
+body: //iframe
+
+replace_string(<![CDATA[): _
+replace_string(]]>): _
+
+single_page_link: //link[@type='application/xml+oembed']
+
+prune: no
+tidy: no
+
+http://www.dailymotion.com/video/x1vk5oh_before-they-were-on-game-of-thrones_people
diff --git a/inc/3rdparty/site_config/custom/index.php b/inc/3rdparty/site_config/custom/index.php
new file mode 100644 (file)
index 0000000..a3d5f73
--- /dev/null
@@ -0,0 +1,3 @@
+<?php
+// this is here to prevent directory listing over the web
+?>
\ No newline at end of file
diff --git a/inc/3rdparty/site_config/custom/mobile.lemondeinformatique.fr.txt b/inc/3rdparty/site_config/custom/mobile.lemondeinformatique.fr.txt
new file mode 100644 (file)
index 0000000..24aec5c
--- /dev/null
@@ -0,0 +1,6 @@
+title: //h2
+body: div[@id='illustration'] | //p
+prune: no
+tidy: no
+
+test_url: http://mobile.lemondeinformatique.fr/actualites/lire-les-datacenters-d-apple-google-et-facebook-eco-responsables-selon-greenpeace-le-monde-informatique-57122.html
diff --git a/inc/3rdparty/site_config/custom/ted.com.txt b/inc/3rdparty/site_config/custom/ted.com.txt
new file mode 100755 (executable)
index 0000000..4940d2b
--- /dev/null
@@ -0,0 +1,11 @@
+title: //title\r
+body: //div[@class='talk-article__body talk-transcript__body'] | //div[@class='media__image media__image--thumb talk-link__image']\r
+\r
+strip_id_or_class: talk-transcript__para__time\r
+\r
+single_page_link: //a[@id='hero-transcript-link']\r
+\r
+#prune: no\r
+tidy: no\r
+\r
+test_url: http://www.ted.com/talks/andrew_solomon_how_the_worst_moments_in_our_lives_make_us_who_we_are\r
index a1b767fd5af66ae62087ced67fdfe7218c221f28..76ca8b3cba6e57b99a95e0dff108bd5cebb97ab0 100644 (file)
@@ -1,3 +1,2 @@
-<?php\r
-// this is here to prevent directory listing over the web\r
-?>
\ No newline at end of file
+<?php
+// this is here to prevent directory listing over the web
\ No newline at end of file
diff --git a/inc/3rdparty/site_config/standard/.about.com.txt b/inc/3rdparty/site_config/standard/.about.com.txt
new file mode 100644 (file)
index 0000000..e1ebaee
--- /dev/null
@@ -0,0 +1,14 @@
+body: //div[@id='articlebody']
+title: //h1
+author: //p[@id='by']//a
+
+next_page_link: //span[@class='next']/a
+# Not the same as below!
+
+prune: yes
+tidy: no
+
+# Annoying 'next' links plainly inside the article body
+strip: //*[text()[contains(.,'Next: ')]]
+
+test_url: http://psychology.about.com/od/theoriesofpersonality/ss/defensemech.htm
diff --git a/inc/3rdparty/site_config/standard/moo.nac.uci.edu.txt b/inc/3rdparty/site_config/standard/moo.nac.uci.edu.txt
new file mode 100644 (file)
index 0000000..24c949e
--- /dev/null
@@ -0,0 +1,9 @@
+title: //div[@id='header']//h1[1]
+
+body: //div[@id='content']
+
+strip_id_or_class: toc
+
+prune: no
+
+test_url: http://moo.nac.uci.edu/~hjm/HOWTO_move_data.html
old mode 100644 (file)
new mode 100755 (executable)
index 121fd5b..c5302d1
@@ -4,10 +4,14 @@ body://div[contains(@class,"story-text")]
 # Why doesn't this work? next_page_link://ul[contains(@class,"pagination")]/li/a[@rel="next"]\r
 \r
 next_page_link://ul[contains(@class,"pagination")]/li[contains(@class, "current")]/following-sibling::node()/a\r
+next_page_link://div[contains(@class,"pagination")]/ol/li[contains(@class, "current")]/following-sibling::node()/a\r
 date://meta[@name="publish_date"]/@content\r
 \r
 strip://div[contains(@class, "breadcrumbs")]\r
 strip://a[contains(@class, "hidden")]\r
 strip://div[contains(@class, "story-embed")]\r
 strip://div[contains(@class, "story-text")]//p/a[contains(text(), "Also on POLITICO:")]/..
+strip://div[contains(@class, "story-interrupt")]\r
+strip://footer[contains(@class, "author-bio")]\r
+\r
 test_url: http://www.politico.com/news/stories/0712/78105.html
\ No newline at end of file
index bf0d87ab1b2b0ec1a11a3973d2845b42413d9767..eaf01ebdb46bd0ae40dc572aa883350d1360131d 100644 (file)
@@ -1 +1 @@
-4
\ No newline at end of file
+2013-05-12T22:53:07Z
\ No newline at end of file
index c998fe14db5fcd40dd79a9ab9c22501633c39139..11cccb7238d9d6a6e16695386152a25fc6789fa8 100755 (executable)
@@ -18,7 +18,7 @@ class Database {
       'default' => 'ORDER BY entries.id'
     );
 
-    function __construct() 
+    function __construct()
     {
         switch (STORAGE) {
             case 'sqlite':
@@ -27,12 +27,14 @@ class Database {
                 break;
             case 'mysql':
                 $db_path = 'mysql:host=' . STORAGE_SERVER . ';dbname=' . STORAGE_DB;
-                $this->handle = new PDO($db_path, STORAGE_USER, STORAGE_PASSWORD); 
+                $this->handle = new PDO($db_path, STORAGE_USER, STORAGE_PASSWORD);
                 break;
             case 'postgres':
                 $db_path = 'pgsql:host=' . STORAGE_SERVER . ';dbname=' . STORAGE_DB;
-                $this->handle = new PDO($db_path, STORAGE_USER, STORAGE_PASSWORD); 
+                $this->handle = new PDO($db_path, STORAGE_USER, STORAGE_PASSWORD);
                 break;
+            default:
+                die(STORAGE . ' is not a recognised database system !');
         }
 
         $this->handle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
@@ -51,7 +53,7 @@ class Database {
         }
         $hasAdmin = count($query->fetchAll());
 
-        if ($hasAdmin == 0) 
+        if ($hasAdmin == 0)
             return false;
 
         return true;
@@ -77,7 +79,7 @@ class Database {
         }
         else {
             $sql = '
-                CREATE TABLE tags (
+                CREATE TABLE IF NOT EXISTS tags (
                   id bigserial primary key,
                   value varchar(255) NOT NULL
                 );
@@ -110,7 +112,7 @@ class Database {
         }
         else {
             $sql = '
-                CREATE TABLE tags_entries (
+                CREATE TABLE IF NOT EXISTS tags_entries (
                   id bigserial primary key,
                   entry_id integer NOT NULL,
                   tag_id integer NOT NULL
@@ -140,7 +142,7 @@ class Database {
         $sql = 'INSERT INTO users_config ( user_id, name, value ) VALUES (?, ?, ?)';
         $params = array($id_user, 'language', LANG);
         $query = $this->executeQuery($sql, $params);
-        
+
         $sql = 'INSERT INTO users_config ( user_id, name, value ) VALUES (?, ?, ?)';
         $params = array($id_user, 'theme', DEFAULT_THEME);
         $query = $this->executeQuery($sql, $params);
@@ -153,7 +155,7 @@ class Database {
         $query = $this->executeQuery($sql, array($id));
         $result = $query->fetchAll();
         $user_config = array();
-        
+
         foreach ($result as $key => $value) {
             $user_config[$value['name']] = $value['value'];
         }
@@ -201,10 +203,10 @@ class Database {
         $params_update = array($password, $userId);
         $query = $this->executeQuery($sql_update, $params_update);
     }
-    
+
     public function updateUserConfig($userId, $key, $value) {
         $config = $this->getConfigUser($userId);
-        
+
         if (! isset($config[$key])) {
             $sql = "INSERT INTO users_config (value, user_id, name) VALUES (?, ?, ?)";
         }
@@ -229,6 +231,73 @@ class Database {
             return FALSE;
         }
     }
+    
+    public function listUsers($username=null) {
+        $sql = 'SELECT count(*) FROM users'.( $username ? ' WHERE username=?' : '');
+        $query = $this->executeQuery($sql, ( $username ? array($username) : array()));
+        list($count) = $query->fetch();
+        return $count;
+    }
+    
+    public function getUserPassword($userID) {
+        $sql = "SELECT * FROM users WHERE id=?";
+        $query = $this->executeQuery($sql, array($userID));
+        $password = $query->fetchAll();
+        return isset($password[0]['password']) ? $password[0]['password'] : null;
+    }
+    
+    public function deleteUserConfig($userID) {
+        $sql_action = 'DELETE from users_config WHERE user_id=?';
+        $params_action = array($userID);
+        $query = $this->executeQuery($sql_action, $params_action);
+        return $query;
+    }
+    
+    public function deleteTagsEntriesAndEntries($userID) {
+        $entries = $this->retrieveAll($userID);
+        foreach($entries as $entryid) {
+            $tags = $this->retrieveTagsByEntry($entryid);
+            foreach($tags as $tag) {
+                $this->removeTagForEntry($entryid,$tags);
+            }
+            $this->deleteById($entryid,$userID);
+        }
+    }
+    
+    public function deleteUser($userID) {
+        $sql_action = 'DELETE from users WHERE id=?';
+        $params_action = array($userID);
+        $query = $this->executeQuery($sql_action, $params_action);
+    }
+
+    public function updateContentAndTitle($id, $title, $body, $user_id) {
+        $sql_action = 'UPDATE entries SET content = ?, title = ? WHERE id=? AND user_id=?';
+        $params_action = array($body, $title, $id, $user_id);
+        $query = $this->executeQuery($sql_action, $params_action);
+        return $query;
+    }
+
+    public function retrieveUnfetchedEntries($user_id, $limit) {
+
+        $sql_limit = "LIMIT 0,".$limit;
+        if (STORAGE == 'postgres') {
+            $sql_limit = "LIMIT ".$limit." OFFSET 0";
+        }
+
+        $sql        = "SELECT * FROM entries WHERE (content = '' OR content IS NULL) AND title LIKE 'Untitled - Import%' AND user_id=? ORDER BY id " . $sql_limit;
+        $query      = $this->executeQuery($sql, array($user_id));
+        $entries    = $query->fetchAll();
+
+        return $entries;
+    }
+
+    public function retrieveUnfetchedEntriesCount($user_id) {
+      $sql        = "SELECT count(*) FROM entries WHERE (content = '' OR content IS NULL) AND title LIKE 'Untitled - Import%' AND user_id=?";
+      $query      = $this->executeQuery($sql, array($user_id));
+      list($count) = $query->fetch();
+
+      return $count;
+    }
 
     public function retrieveAll($user_id) {
         $sql        = "SELECT * FROM entries WHERE user_id=? ORDER BY id";
@@ -294,24 +363,24 @@ class Database {
                 return $entries;
         }
 
-    public function getEntriesByViewCount($view, $user_id, $tag_id = 0) {\r
-        switch ($view) {\r
+    public function getEntriesByViewCount($view, $user_id, $tag_id = 0) {
+        switch ($view) {
             case 'archive':
-                    $sql    = "SELECT count(*) FROM entries WHERE user_id=? AND is_read=? ";\r
+                    $sql    = "SELECT count(*) FROM entries WHERE user_id=? AND is_read=? ";
                 $params = array($user_id, 1);
                 break;
             case 'fav' :
-                    $sql    = "SELECT count(*) FROM entries WHERE user_id=? AND is_fav=? ";\r
+                    $sql    = "SELECT count(*) FROM entries WHERE user_id=? AND is_fav=? ";
                 $params = array($user_id, 1);
                 break;
-            case 'tag' :\r
-                $sql    = "SELECT count(*) FROM entries\r
-                    LEFT JOIN tags_entries ON tags_entries.entry_id=entries.id\r
-                    WHERE entries.user_id=? AND tags_entries.tag_id = ? ";\r
-                $params = array($user_id, $tag_id);\r
-                break;\r
+            case 'tag' :
+                $sql    = "SELECT count(*) FROM entries
+                    LEFT JOIN tags_entries ON tags_entries.entry_id=entries.id
+                    WHERE entries.user_id=? AND tags_entries.tag_id = ? ";
+                $params = array($user_id, $tag_id);
+                break;
             default:
-                $sql    = "SELECT count(*) FROM entries WHERE user_id=? AND is_read=? ";\r
+                $sql    = "SELECT count(*) FROM entries WHERE user_id=? AND is_read=? ";
                 $params = array($user_id, 0);
                 break;
         }
@@ -319,7 +388,7 @@ class Database {
         $query = $this->executeQuery($sql, $params);
         list($count) = $query->fetch();
 
-        return $count;\r
+        return $count;
     }
 
     public function updateContent($id, $content, $user_id) {
@@ -329,11 +398,25 @@ class Database {
         return $query;
     }
 
-    public function add($url, $title, $content, $user_id) {
-        $sql_action = 'INSERT INTO entries ( url, title, content, user_id ) VALUES (?, ?, ?, ?)';
-        $params_action = array($url, $title, $content, $user_id);
-        $query = $this->executeQuery($sql_action, $params_action);
-        return $query;
+    /**
+     *
+     * @param string $url
+     * @param string $title
+     * @param string $content
+     * @param integer $user_id
+     * @return integer $id of inserted record
+     */
+    public function add($url, $title, $content, $user_id, $isFavorite=0, $isRead=0) {
+        $sql_action = 'INSERT INTO entries ( url, title, content, user_id, is_fav, is_read ) VALUES (?, ?, ?, ?, ?, ?)';
+        $params_action = array($url, $title, $content, $user_id, $isFavorite, $isRead);
+
+        if ( !$this->executeQuery($sql_action, $params_action) ) {
+          $id = null;
+        }
+        else {
+          $id = intval($this->getLastId( (STORAGE == 'postgres') ? 'entries_id_seq' : '') );
+        }
+        return $id;
     }
 
     public function deleteById($id, $user_id) {
@@ -365,12 +448,24 @@ class Database {
         return $this->getHandle()->lastInsertId($column);
     }
 
-    public function retrieveAllTags($user_id) {
-        $sql = "SELECT DISTINCT tags.* FROM tags
+    public function search($term, $user_id, $limit = '') {
+        $search = '%'.$term.'%';
+        $sql_action = "SELECT * FROM entries WHERE user_id=? AND (content LIKE ? OR title LIKE ? OR url LIKE ?) "; //searches in content, title and URL
+        $sql_action .= $this->getEntriesOrder().' ' . $limit;
+        $params_action = array($user_id, $search, $search, $search);
+        $query = $this->executeQuery($sql_action, $params_action);
+        return $query->fetchAll();
+       }
+
+    public function retrieveAllTags($user_id, $term = null) {
+        $sql = "SELECT DISTINCT tags.*, count(entries.id) AS entriescount FROM tags
           LEFT JOIN tags_entries ON tags_entries.tag_id=tags.id
           LEFT JOIN entries ON tags_entries.entry_id=entries.id
-          WHERE entries.user_id=?";
-        $query = $this->executeQuery($sql, array($user_id));
+          WHERE entries.user_id=?
+            ". (($term) ? "AND lower(tags.value) LIKE ?" : '') ."
+          GROUP BY tags.id, tags.value
+          ORDER BY tags.value";
+        $query = $this->executeQuery($sql, (($term)? array($user_id, strtolower('%'.$term.'%')) : array($user_id) ));
         $tags = $query->fetchAll();
 
         return $tags;
@@ -390,10 +485,10 @@ class Database {
     }
 
     public function retrieveEntriesByTag($tag_id, $user_id) {
-        $sql = 
+        $sql =
             "SELECT entries.* FROM entries
             LEFT JOIN tags_entries ON tags_entries.entry_id=entries.id
-            WHERE tags_entries.tag_id = ? AND entries.user_id=?";
+            WHERE tags_entries.tag_id = ? AND entries.user_id=? ORDER by entries.id DESC";
         $query = $this->executeQuery($sql, array($tag_id, $user_id));
         $entries = $query->fetchAll();
 
@@ -401,7 +496,7 @@ class Database {
     }
 
     public function retrieveTagsByEntry($entry_id) {
-        $sql = 
+        $sql =
             "SELECT tags.* FROM tags
             LEFT JOIN tags_entries ON tags_entries.tag_id=tags.id
             WHERE tags_entries.entry_id = ?";
@@ -417,6 +512,25 @@ class Database {
         $query          = $this->executeQuery($sql_action, $params_action);
         return $query;
     }
+    
+    public function cleanUnusedTag($tag_id) {
+        $sql_action = "SELECT tags.* FROM tags JOIN tags_entries ON tags_entries.tag_id=tags.id WHERE tags.id=?";
+        $query = $this->executeQuery($sql_action,array($tag_id));
+        $tagstokeep = $query->fetchAll();
+        $sql_action = "SELECT tags.* FROM tags LEFT JOIN tags_entries ON tags_entries.tag_id=tags.id WHERE tags.id=?";
+        $query = $this->executeQuery($sql_action,array($tag_id));
+        $alltags = $query->fetchAll();
+        
+        foreach ($alltags as $tag) {
+            if ($tag && !in_array($tag,$tagstokeep)) {
+                $sql_action = "DELETE FROM tags WHERE id=?";
+                $params_action = array($tag[0]);
+                $this->executeQuery($sql_action, $params_action);
+                return true;
+            }
+        }
+        
+    }
 
     public function retrieveTagByValue($value) {
         $tag  = NULL;
index 8a9de488d732576c7a8cb4df66390d3a011cad33..09a9f5ff85276423a29b505312d2f1cec66ead8a 100755 (executable)
@@ -18,7 +18,7 @@ class Poche
     public $tpl;
     public $messages;
     public $pagination;
-    
+
     private $currentTheme = '';
     private $currentLanguage = '';
     private $notInstalledMessage = array();
@@ -32,20 +32,21 @@ class Poche
       'fr_FR.utf8' => 'Français',
       'it_IT.utf8' => 'Italiano',
       'pl_PL.utf8' => 'Polski',
+      'pt_BR.utf8' => 'Português (Brasil)',
       'ru_RU.utf8' => 'Pусский',
       'sl_SI.utf8' => 'Slovenščina',
-      'uk_UA.utf8' => 'УкÑ\80аÑ\97нÑ\81Ñ\8cкий',
+      'uk_UA.utf8' => 'УкÑ\80аÑ\97нÑ\81Ñ\8cка',
     );
     public function __construct()
     {
         if ($this->configFileIsAvailable()) {
             $this->init();
         }
-        
+
         if ($this->themeIsInstalled()) {
             $this->initTpl();
         }
-        
+
         if ($this->systemIsInstalled()) {
             $this->store = new Database();
             $this->messages = new Messages();
@@ -56,12 +57,10 @@ class Poche
             $this->store->checkTags();
         }
     }
-    
-    private function init() 
+
+    private function init()
     {
         Tools::initPhp();
-        Session::$sessionName = 'poche'; 
-        Session::init();
 
         if (isset($_SESSION['poche_user']) && $_SESSION['poche_user'] != array()) {
             $this->user = $_SESSION['poche_user'];
@@ -73,43 +72,43 @@ class Poche
 
         # l10n
         $language = $this->user->getConfigValue('language');
-        putenv('LC_ALL=' . $language);
+        @putenv('LC_ALL=' . $language);
         setlocale(LC_ALL, $language);
-        bindtextdomain($language, LOCALE); 
-        textdomain($language); 
+        bindtextdomain($language, LOCALE);
+        textdomain($language);
 
         # Pagination
         $this->pagination = new Paginator($this->user->getConfigValue('pager'), 'p');
-        
+
         # Set up theme
         $themeDirectory = $this->user->getConfigValue('theme');
-        
+
         if ($themeDirectory === false) {
             $themeDirectory = DEFAULT_THEME;
         }
-        
+
         $this->currentTheme = $themeDirectory;
 
         # Set up language
         $languageDirectory = $this->user->getConfigValue('language');
-        
+
         if ($languageDirectory === false) {
             $languageDirectory = DEFAULT_THEME;
         }
-        
+
         $this->currentLanguage = $languageDirectory;
     }
 
     public function configFileIsAvailable() {
         if (! self::$configFileAvailable) {
-            $this->notInstalledMessage[] = 'You have to rename inc/poche/config.inc.php.new to inc/poche/config.inc.php.';
+            $this->notInstalledMessage[] = 'You have to copy (don\'t just rename!) inc/poche/config.inc.default.php to inc/poche/config.inc.php.';
 
             return false;
         }
 
         return true;
     }
-    
+
     public function themeIsInstalled() {
         $passTheme = TRUE;
         # Twig is an absolute requirement for Poche to function. Abort immediately if the Composer installer hasn't been run yet
@@ -124,27 +123,27 @@ class Poche
             self::$canRenderTemplates = false;
 
             $passTheme = FALSE;
-        } 
-        
+        }
+
         # Check if the selected theme and its requirements are present
         $theme = $this->getTheme();
 
         if ($theme != '' && ! is_dir(THEME . '/' . $theme)) {
             $this->notInstalledMessage[] = 'The currently selected theme (' . $theme . ') does not seem to be properly installed (Missing directory: ' . THEME . '/' . $theme . ')';
-            
+
             self::$canRenderTemplates = false;
-            
+
             $passTheme = FALSE;
         }
-        
+
         $themeInfo = $this->getThemeInfo($theme);
         if (isset($themeInfo['requirements']) && is_array($themeInfo['requirements'])) {
             foreach ($themeInfo['requirements'] as $requiredTheme) {
                 if (! is_dir(THEME . '/' . $requiredTheme)) {
                     $this->notInstalledMessage[] = 'The required "' . $requiredTheme . '" theme is missing for the current theme (' . $theme . ')';
-                
+
                     self::$canRenderTemplates = false;
-                
+
                     $passTheme = FALSE;
                 }
             }
@@ -154,21 +153,21 @@ class Poche
             return FALSE;
         }
 
-        
+
         return true;
     }
-    
+
     /**
      * all checks before installation.
      * @todo move HTML to template
-     * @return boolean 
+     * @return boolean
      */
     public function systemIsInstalled()
     {
         $msg = TRUE;
-        
+
         $configSalt = defined('SALT') ? constant('SALT') : '';
-        
+
         if (empty($configSalt)) {
             $this->notInstalledMessage[] = 'You have not yet filled in the SALT value in the config.inc.php file.';
             $msg = FALSE;
@@ -194,7 +193,7 @@ class Poche
 
         return true;
     }
-    
+
     public function getNotInstalledMessage() {
         return $this->notInstalledMessage;
     }
@@ -203,7 +202,7 @@ class Poche
     {
         $loaderChain = new Twig_Loader_Chain();
         $theme = $this->getTheme();
-       
+
         # add the current theme as first to the loader chain so Twig will look there first for overridden template files
         try {
             $loaderChain->addLoader(new Twig_Loader_Filesystem(THEME . '/' . $theme));
@@ -211,7 +210,7 @@ class Poche
             # @todo isInstalled() should catch this, inject Twig later
             die('The currently selected theme (' . $theme . ') does not seem to be properly installed (' . THEME . '/' . $theme .' is missing)');
         }
-        
+
         # add all required themes to the loader chain
         $themeInfo = $this->getThemeInfo($theme);
         if (isset($themeInfo['requirements']) && is_array($themeInfo['requirements'])) {
@@ -224,16 +223,16 @@ class Poche
                 }
             }
         }
-        
+
         if (DEBUG_POCHE) {
             $twigParams = array();
         } else {
             $twigParams = array('cache' => CACHE);
         }
-        
+
         $this->tpl = new Twig_Environment($loaderChain, $twigParams);
         $this->tpl->addExtension(new Twig_Extensions_Extension_I18n());
-        
+
         # filter to display domain name of an url
         $filter = new Twig_SimpleFilter('getDomain', 'Tools::getDomain');
         $this->tpl->addFilter($filter);
@@ -243,6 +242,58 @@ class Poche
         $this->tpl->addFilter($filter);
     }
 
+    public function createNewUser() {
+        if (isset($_GET['newuser'])){
+            if ($_POST['newusername'] != "" && $_POST['password4newuser'] != ""){
+                $newusername = filter_var($_POST['newusername'], FILTER_SANITIZE_STRING);
+                if (!$this->store->userExists($newusername)){
+                    if ($this->store->install($newusername, Tools::encodeString($_POST['password4newuser'] . $newusername))) {
+                        Tools::logm('The new user '.$newusername.' has been installed');
+                        $this->messages->add('s', sprintf(_('The new user %s has been installed. Do you want to <a href="?logout">logout ?</a>'),$newusername));
+                        Tools::redirect();
+                    }
+                    else {
+                        Tools::logm('error during adding new user');
+                        Tools::redirect();
+                    }
+                }
+                else {
+                    $this->messages->add('e', sprintf(_('Error : An user with the name %s already exists !'),$newusername));
+                    Tools::logm('An user with the name '.$newusername.' already exists !');
+                    Tools::redirect();
+                }
+            }
+        }
+    }
+
+    public function deleteUser(){
+        if (isset($_GET['deluser'])){
+            if ($this->store->listUsers() > 1) {
+                if (Tools::encodeString($_POST['password4deletinguser'].$this->user->getUsername()) == $this->store->getUserPassword($this->user->getId())) {
+                    $username = $this->user->getUsername();
+                    $this->store->deleteUserConfig($this->user->getId());
+                    Tools::logm('The configuration for user '. $username .' has been deleted !');
+                    $this->store->deleteTagsEntriesAndEntries($this->user->getId());
+                    Tools::logm('The entries for user '. $username .' has been deleted !');
+                    $this->store->deleteUser($this->user->getId());
+                    Tools::logm('User '. $username .' has been completely deleted !');
+                    Session::logout();
+                    Tools::logm('logout');
+                    Tools::redirect();
+                    $this->messages->add('s', sprintf(_('User %s has been successfully deleted !'),$newusername));
+                }
+                else {
+                    Tools::logm('Bad password !');
+                    $this->messages->add('e', _('Error : The password is wrong !'));
+                }
+            }
+            else {
+                Tools::logm('Only user !');
+                $this->messages->add('e', _('Error : You are the only user, you cannot delete your account !'));
+            }
+        }
+    }
+
     private function install()
     {
         Tools::logm('poche still not installed');
@@ -252,7 +303,7 @@ class Poche
             'poche_url' => Tools::getPocheUrl()
         ));
         if (isset($_GET['install'])) {
-            if (($_POST['password'] == $_POST['password_repeat']) 
+            if (($_POST['password'] == $_POST['password_repeat'])
                 && $_POST['password'] != "" && $_POST['login'] != "") {
                 # let's rock, install poche baby !
                 if ($this->store->install($_POST['login'], Tools::encodeString($_POST['password'] . $_POST['login'])))
@@ -269,7 +320,7 @@ class Poche
         }
         exit();
     }
-    
+
     public function getTheme() {
         return $this->currentTheme;
     }
@@ -294,7 +345,7 @@ class Poche
         if (is_file($themeIniFile) && is_readable($themeIniFile)) {
             $themeInfo = parse_ini_file($themeIniFile);
         }
-        
+
         if ($themeInfo === false) {
             $themeInfo = array();
         }
@@ -305,7 +356,7 @@ class Poche
 
         return $themeInfo;
     }
-    
+
     public function getInstalledThemes() {
         $handle = opendir(THEME);
         $themes = array();
@@ -332,28 +383,28 @@ class Poche
     public function getInstalledLanguages() {
         $handle = opendir(LOCALE);
         $languages = array();
-        
+
         while (($language = readdir($handle)) !== false) {
             # Languages are stored in a directory, so all directory names are languages
             # @todo move language installation data to database
-            if (! is_dir(LOCALE . '/' . $language) || in_array($language, array('..', '.'))) {
+            if (! is_dir(LOCALE . '/' . $language) || in_array($language, array('..', '.', 'tools'))) {
                 continue;
             }
-            
+
             $current = false;
-            
+
             if ($language === $this->getLanguage()) {
                 $current = true;
             }
-            
-            $languages[] = array('name' => $this->language_names[$language], 'value' => $language, 'current' => $current);
+
+            $languages[] = array('name' => (isset($this->language_names[$language]) ? $this->language_names[$language] : $language), 'value' => $language, 'current' => $current);
         }
-        
+
         return $languages;
     }
 
     public function getDefaultConfig()
-    {   
+    {
         return array(
             'pager' => PAGINATION,
             'language' => LANG,
@@ -361,60 +412,6 @@ class Poche
         );
     }
 
-    protected function getPageContent(Url $url)
-    {
-        // Saving and clearing context
-        $REAL = array();
-        foreach( $GLOBALS as $key => $value ) {
-            if( $key != "GLOBALS" && $key != "_SESSION" ) {
-                $GLOBALS[$key] = array();
-                $REAL[$key] = $value;
-            }
-        }
-        // Saving and clearing session
-        $REAL_SESSION = array();
-        foreach( $_SESSION as $key => $value ) {
-            $REAL_SESSION[$key] = $value;
-            unset($_SESSION[$key]);
-        }
-
-        // Running code in different context
-        $scope = function() {
-            extract( func_get_arg(1) );
-            $_GET = $_REQUEST = array(
-                        "url" => $url->getUrl(),
-                        "max" => 5,
-                        "links" => "preserve",
-                        "exc" => "",
-                        "format" => "json",
-                        "submit" => "Create Feed"
-            );
-            ob_start();
-            require func_get_arg(0);
-            $json = ob_get_flush();
-            return $json;
-        };
-        $json = $scope( "inc/3rdparty/makefulltextfeed.php", array("url" => $url) );
-
-        // Clearing and restoring context
-        foreach( $GLOBALS as $key => $value ) {
-            if( $key != "GLOBALS" && $key != "_SESSION" ) {
-                unset($GLOBALS[$key]);
-            }
-        }
-        foreach( $REAL as $key => $value ) {
-            $GLOBALS[$key] = $value;
-        }
-        // Clearing and restoring session
-        foreach( $_SESSION as $key => $value ) {
-            unset($_SESSION[$key]);
-        }
-        foreach( $REAL_SESSION as $key => $value ) {
-            $_SESSION[$key] = $value;
-        }
-        return json_decode($json, true);
-    }
-
     /**
      * Call action (mark as fav, archive, delete, etc.)
      */
@@ -423,28 +420,22 @@ class Poche
         switch ($action)
         {
             case 'add':
-                $content = $this->getPageContent($url);
+                $content = Tools::getPageContent($url);
                 $title = ($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled');
                 $body = $content['rss']['channel']['item']['description'];
 
                 // clean content from prevent xss attack
-                $config = HTMLPurifier_Config::createDefault();
-                $purifier = new HTMLPurifier($config);
+                $purifier = $this->getPurifier();
                 $title = $purifier->purify($title);
                 $body = $purifier->purify($body);
 
-                //search for possible duplicate if not in import mode
-                if (!$import) {
-                    $duplicate = $this->store->retrieveOneByURL($url->getUrl(), $this->user->getId());
-                }
+                //search for possible duplicate
+                $duplicate = NULL;
+                $duplicate = $this->store->retrieveOneByURL($url->getUrl(), $this->user->getId());
 
-                if ($this->store->add($url->getUrl(), $title, $body, $this->user->getId())) {
+                $last_id = $this->store->add($url->getUrl(), $title, $body, $this->user->getId());
+                if ( $last_id ) {
                     Tools::logm('add link ' . $url->getUrl());
-                    $sequence = '';
-                    if (STORAGE == 'postgres') {
-                        $sequence = 'entries_id_seq';
-                    }
-                    $last_id = $this->store->getLastId($sequence);
                     if (DOWNLOAD_PICTURES) {
                         $content = filtre_picture($body, $url->getUrl(), $last_id);
                         Tools::logm('updating content article');
@@ -464,23 +455,17 @@ class Poche
                         }
                     }
 
-                    if (!$import) {
-                        $this->messages->add('s', _('the link has been added successfully'));
-                    }
+                    $this->messages->add('s', _('the link has been added successfully'));
                 }
                 else {
-                    if (!$import) {
-                        $this->messages->add('e', _('error during insertion : the link wasn\'t added'));
-                        Tools::logm('error during insertion : the link wasn\'t added ' . $url->getUrl());
-                    }
+                    $this->messages->add('e', _('error during insertion : the link wasn\'t added'));
+                    Tools::logm('error during insertion : the link wasn\'t added ' . $url->getUrl());
                 }
 
-                if (!$import) {
-                    if ($autoclose == TRUE) {
-                      Tools::redirect('?view=home');
-                    } else {
-                      Tools::redirect('?view=home&closewin=true');
-                    }
+                if ($autoclose == TRUE) {
+                  Tools::redirect('?view=home');
+                } else {
+                  Tools::redirect('?view=home&closewin=true');
                 }
                 break;
             case 'delete':
@@ -501,62 +486,81 @@ class Poche
             case 'toggle_fav' :
                 $this->store->favoriteById($id, $this->user->getId());
                 Tools::logm('mark as favorite link #' . $id);
-                if (!$import) {
-                    Tools::redirect();
+                if ( Tools::isAjaxRequest() ) {
+                  echo 1;
+                  exit;
+                }
+                else {
+                  Tools::redirect();
                 }
                 break;
             case 'toggle_archive' :
                 $this->store->archiveById($id, $this->user->getId());
                 Tools::logm('archive link #' . $id);
-                if (!$import) {
-                    Tools::redirect();
+                if ( Tools::isAjaxRequest() ) {
+                  echo 1;
+                  exit;
+                }
+                else {
+                  Tools::redirect();
                 }
                 break;
             case 'archive_all' :
                 $this->store->archiveAll($this->user->getId());
                 Tools::logm('archive all links');
-                if (!$import) {
-                    Tools::redirect();
-                }
+                Tools::redirect();
                 break;
             case 'add_tag' :
-                if($import){
-                    $entry_id = $id;
-                    $tags = explode(',', $tags);
-                }
-                else{
+                if (isset($_GET['search'])) {
+                    //when we want to apply a tag to a search
+                    $tags = array($_GET['search']);
+                    $allentry_ids = $this->store->search($tags[0], $this->user->getId());
+                    $entry_ids = array();
+                    foreach ($allentry_ids as $eachentry) {
+                        $entry_ids[] = $eachentry[0];
+                    }
+                } else { //add a tag to a single article
                     $tags = explode(',', $_POST['value']);
-                    $entry_id = $_POST['entry_id'];
+                    $entry_ids = array($_POST['entry_id']);
                 }
-                $entry = $this->store->retrieveOneById($entry_id, $this->user->getId());
-                if (!$entry) {
-                    $this->messages->add('e', _('Article not found!'));
-                    Tools::logm('error : article not found');
-                    Tools::redirect();
-                }
-                foreach($tags as $key => $tag_value) {
-                    $value = trim($tag_value);
-                    $tag = $this->store->retrieveTagByValue($value);
-
-                    if (is_null($tag)) {
-                        # we create the tag
-                        $tag = $this->store->createTag($value);
-                        $sequence = '';
-                        if (STORAGE == 'postgres') {
-                            $sequence = 'tags_id_seq';
-                        }
-                        $tag_id = $this->store->getLastId($sequence);
+                foreach($entry_ids as $entry_id) {
+                    $entry = $this->store->retrieveOneById($entry_id, $this->user->getId());
+                    if (!$entry) {
+                        $this->messages->add('e', _('Article not found!'));
+                        Tools::logm('error : article not found');
+                        Tools::redirect();
                     }
-                    else {
-                        $tag_id = $tag['id'];
+                    //get all already set tags to preven duplicates
+                    $already_set_tags = array();
+                    $entry_tags = $this->store->retrieveTagsByEntry($entry_id);
+                    foreach ($entry_tags as $tag) {
+                      $already_set_tags[] = $tag['value'];
+                    }
+                    foreach($tags as $key => $tag_value) {
+                        $value = trim($tag_value);
+                        if ($value && !in_array($value, $already_set_tags)) {
+                          $tag = $this->store->retrieveTagByValue($value);
+                          if (is_null($tag)) {
+                              # we create the tag
+                              $tag = $this->store->createTag($value);
+                              $sequence = '';
+                              if (STORAGE == 'postgres') {
+                                  $sequence = 'tags_id_seq';
+                              }
+                              $tag_id = $this->store->getLastId($sequence);
+                          }
+                          else {
+                              $tag_id = $tag['id'];
+                          }
+
+                          # we assign the tag to the article
+                          $this->store->setTagToEntry($tag_id, $entry_id);
+                        }
                     }
-
-                    # we assign the tag to the article
-                    $this->store->setTagToEntry($tag_id, $entry_id);
-                }
-                if(!$import) {
-                    Tools::redirect();
                 }
+                $this->messages->add('s', _('The tag has been applied successfully'));
+                Tools::logm('The tag has been applied successfully');
+                Tools::redirect();
                 break;
             case 'remove_tag' :
                 $tag_id = $_GET['tag_id'];
@@ -567,6 +571,11 @@ class Poche
                     Tools::redirect();
                 }
                 $this->store->removeTagForEntry($id, $tag_id);
+                Tools::logm('tag entry deleted');
+                if ($this->store->cleanUnusedTag($tag_id)) {
+                    Tools::logm('tag deleted');
+                }
+                $this->messages->add('s', _('The tag has been successfully deleted'));
                 Tools::redirect();
                 break;
             default:
@@ -581,24 +590,32 @@ class Poche
         switch ($view)
         {
             case 'config':
-                $dev = trim($this->getPocheVersion('dev'));
-                $prod = trim($this->getPocheVersion('prod'));
+                $dev_infos = $this->getPocheVersion('dev');
+                $dev = trim($dev_infos[0]);
+                $check_time_dev = date('d-M-Y H:i', $dev_infos[1]);
+                $prod_infos = $this->getPocheVersion('prod');
+                $prod = trim($prod_infos[0]);
+                $check_time_prod = date('d-M-Y H:i', $prod_infos[1]);
                 $compare_dev = version_compare(POCHE, $dev);
                 $compare_prod = version_compare(POCHE, $prod);
                 $themes = $this->getInstalledThemes();
                 $languages = $this->getInstalledLanguages();
                 $token = $this->user->getConfigValue('token');
                 $http_auth = (isset($_SERVER['PHP_AUTH_USER']) || isset($_SERVER['REMOTE_USER'])) ? true : false;
+                $only_user = ($this->store->listUsers() > 1) ? false : true;
                 $tpl_vars = array(
                     'themes' => $themes,
                     'languages' => $languages,
                     'dev' => $dev,
                     'prod' => $prod,
+                    'check_time_dev' => $check_time_dev,
+                    'check_time_prod' => $check_time_prod,
                     'compare_dev' => $compare_dev,
                     'compare_prod' => $compare_prod,
                     'token' => $token,
                     'user_id' => $this->user->getId(),
                     'http_auth' => $http_auth,
+                    'only_user' => $only_user
                 );
                 Tools::logm('config view');
                 break;
@@ -619,13 +636,36 @@ class Poche
                 break;
             case 'tags':
                 $token = $this->user->getConfigValue('token');
-                $tags = $this->store->retrieveAllTags($this->user->getId());
+                //if term is set - search tags for this term
+                $term = Tools::checkVar('term');
+                $tags = $this->store->retrieveAllTags($this->user->getId(), $term);
+                if (Tools::isAjaxRequest()) {
+                  $result = array();
+                  foreach ($tags as $tag) {
+                    $result[] = $tag['value'];
+                  }
+                  echo json_encode($result);
+                  exit;
+                }
                 $tpl_vars = array(
                     'token' => $token,
                     'user_id' => $this->user->getId(),
                     'tags' => $tags,
                 );
                 break;
+            case 'search':
+                if (isset($_GET['search'])) {
+                   $search = filter_var($_GET['search'], FILTER_SANITIZE_STRING);
+                   $tpl_vars['entries'] = $this->store->search($search, $this->user->getId());
+                   $count = count($tpl_vars['entries']);
+                   $this->pagination->set_total($count);
+                   $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')),
+                            $this->pagination->page_links('?view=' . $view . '?search=' . $search . '&sort=' . $_SESSION['sort'] . '&' ));
+                   $tpl_vars['page_links'] = $page_links;
+                   $tpl_vars['nb_results'] = $count;
+                   $tpl_vars['search_term'] = $search;
+                }
+                break;
             case 'view':
                 $entry = $this->store->retrieveOneById($id, $this->user->getId());
                 if ($entry != NULL) {
@@ -660,8 +700,9 @@ class Poche
                     'entries' => '',
                     'page_links' => '',
                     'nb_results' => '',
+                    'listmode' => (isset($_COOKIE['listmode']) ? true : false),
                 );
-                
+
                 //if id is given - we retrive entries by tag: id is tag id
                 if ($id) {
                   $tpl_vars['tag'] = $this->store->retrieveTag($id, $this->user->getId());
@@ -686,8 +727,8 @@ class Poche
     }
 
     /**
-     * update the password of the current user. 
-     * if MODE_DEMO is TRUE, the password can't be updated. 
+     * update the password of the current user.
+     * if MODE_DEMO is TRUE, the password can't be updated.
      * @todo add the return value
      * @todo set the new password in function header like this updatePassword($newPassword)
      * @return boolean
@@ -715,42 +756,44 @@ class Poche
             }
         }
     }
-    
+
     public function updateTheme()
     {
         # no data
         if (empty($_POST['theme'])) {
         }
-        
+
         # we are not going to change it to the current theme...
         if ($_POST['theme'] == $this->getTheme()) {
             $this->messages->add('w', _('still using the "' . $this->getTheme() . '" theme!'));
             Tools::redirect('?view=config');
         }
-        
+
         $themes = $this->getInstalledThemes();
         $actualTheme = false;
-        
+
         foreach (array_keys($themes) as $theme) {
             if ($theme == $_POST['theme']) {
                 $actualTheme = true;
                 break;
             }
         }
-        
+
         if (! $actualTheme) {
             $this->messages->add('e', _('that theme does not seem to be installed'));
             Tools::redirect('?view=config');
         }
-        
+
         $this->store->updateUserConfig($this->user->getId(), 'theme', $_POST['theme']);
         $this->messages->add('s', _('you have changed your theme preferences'));
-        
+
         $currentConfig = $_SESSION['poche_user']->config;
         $currentConfig['theme'] = $_POST['theme'];
-        
+
         $_SESSION['poche_user']->setConfig($currentConfig);
-        
+
+        $this->emptyCache();
+
         Tools::redirect('?view=config');
     }
 
@@ -759,39 +802,40 @@ class Poche
         # no data
         if (empty($_POST['language'])) {
         }
-        
+
         # we are not going to change it to the current language...
         if ($_POST['language'] == $this->getLanguage()) {
             $this->messages->add('w', _('still using the "' . $this->getLanguage() . '" language!'));
             Tools::redirect('?view=config');
         }
-        
+
         $languages = $this->getInstalledLanguages();
         $actualLanguage = false;
-        
+
         foreach ($languages as $language) {
             if ($language['value'] == $_POST['language']) {
                 $actualLanguage = true;
                 break;
             }
         }
-        
+
         if (! $actualLanguage) {
             $this->messages->add('e', _('that language does not seem to be installed'));
             Tools::redirect('?view=config');
         }
-        
+
         $this->store->updateUserConfig($this->user->getId(), 'language', $_POST['language']);
         $this->messages->add('s', _('you have changed your language preferences'));
-        
+
         $currentConfig = $_SESSION['poche_user']->config;
         $currentConfig['language'] = $_POST['language'];
-        
+
         $_SESSION['poche_user']->setConfig($currentConfig);
-        
+
+        $this->emptyCache();
+
         Tools::redirect('?view=config');
     }
-
     /**
      * get credentials from differents sources
      * it redirects the user to the $referer link
@@ -846,7 +890,7 @@ class Poche
     /**
      * log out the poche user. It cleans the session.
      * @todo add the return value
-     * @return boolean 
+     * @return boolean
      */
     public function logout()
     {
@@ -857,238 +901,137 @@ class Poche
     }
 
     /**
-     * import from Instapaper. poche needs a ./instapaper-export.html file
-     * @todo add the return value
-     * @param string $targetFile the file used for importing
+     * import datas into your poche
      * @return boolean
      */
-    private function importFromInstapaper($targetFile)
-    {
-        # TODO gestion des articles favs
-        $html = new simple_html_dom();
-        $html->load_file($targetFile);
-        Tools::logm('starting import from instapaper');
-
-        $read = 0;
-        $errors = array();
-        foreach($html->find('ol') as $ul)
-        {
-            foreach($ul->find('li') as $li)
-            {
-                $a = $li->find('a');
-                $url = new Url(base64_encode($a[0]->href));
-                $this->action('add', $url, 0, TRUE);
-                if ($read == '1') {
-                    $sequence = '';
-                    if (STORAGE == 'postgres') {
-                        $sequence = 'entries_id_seq';
-                    }
-                    $last_id = $this->store->getLastId($sequence);
-                    $this->action('toggle_archive', $url, $last_id, TRUE);
-                }
+    public function import() {
+
+      if ( isset($_FILES['file']) ) {
+        Tools::logm('Import stated: parsing file');
+
+        // assume, that file is in json format
+        $str_data = file_get_contents($_FILES['file']['tmp_name']);
+        $data = json_decode($str_data, true);
+
+        if ( $data === null ) {
+          //not json - assume html
+          $html = new simple_html_dom();
+          $html->load_file($_FILES['file']['tmp_name']);
+          $data = array();
+          $read = 0;
+          foreach (array('ol','ul') as $list) {
+            foreach ($html->find($list) as $ul) {
+              foreach ($ul->find('li') as $li) {
+                $tmpEntry = array();
+                  $a = $li->find('a');
+                  $tmpEntry['url'] = $a[0]->href;
+                  $tmpEntry['tags'] = $a[0]->tags;
+                  $tmpEntry['is_read'] = $read;
+                  if ($tmpEntry['url']) {
+                    $data[] = $tmpEntry;
+                  }
+              }
+              # the second <ol/ul> is for read links
+              $read = ((sizeof($data) && $read)?0:1);
             }
-
-            # the second <ol> is for read links
-            $read = 1;
+          }
         }
-        $this->messages->add('s', _('import from instapaper completed'));
-        Tools::logm('import from instapaper completed');
-        Tools::redirect();
-    }
 
-    /**
-     * import from Pocket. poche needs a ./ril_export.html file
-     * @todo add the return value
-     * @param string $targetFile the file used for importing
-     * @return boolean 
-     */
-    private function importFromPocket($targetFile)
-    {
-        # TODO gestion des articles favs
-        $html = new simple_html_dom();
-        $html->load_file($targetFile);
-        Tools::logm('starting import from pocket');
-
-        $read = 0;
-        $errors = array();
-        foreach($html->find('ul') as $ul)
-        {
-            foreach($ul->find('li') as $li)
-            {
-                $a = $li->find('a');
-                $url = new Url(base64_encode($a[0]->href));
-                $this->action('add', $url, 0, TRUE);
-                $sequence = '';
-                if (STORAGE == 'postgres') {
-                    $sequence = 'entries_id_seq';
-                }
-                $last_id = $this->store->getLastId($sequence);
-                if ($read == '1') {
-                    $this->action('toggle_archive', $url, $last_id, TRUE);
-                }
-                $tags = $a[0]->tags;
-                if(!empty($tags)) {
-                    $this->action('add_tag',$url,$last_id,true,false,$tags);
-                }
+        //for readability structure
+        foreach ($data as $record) {
+          if (is_array($record)) {
+            $data[] = $record;
+            foreach ($record as $record2) {
+              if (is_array($record2)) {
+                $data[] = $record2;
+              }
+            }
+          }
+        }
+
+        $urlsInserted = array(); //urls of articles inserted
+        foreach ($data as $record) {
+          $url = trim( isset($record['article__url']) ? $record['article__url'] : (isset($record['url']) ? $record['url'] : '') );
+          if ( $url and !in_array($url, $urlsInserted) ) {
+            $title = (isset($record['title']) ? $record['title'] :  _('Untitled - Import - ').'</a> <a href="./?import">'._('click to finish import').'</a><a>');
+            $body = (isset($record['content']) ? $record['content'] : '');
+            $isRead = (isset($record['is_read']) ? intval($record['is_read']) : (isset($record['archive'])?intval($record['archive']):0));
+            $isFavorite = (isset($record['is_fav']) ? intval($record['is_fav']) : (isset($record['favorite'])?intval($record['favorite']):0) );
+            //insert new record
+            $id = $this->store->add($url, $title, $body, $this->user->getId(), $isFavorite, $isRead);
+            if ( $id ) {
+              $urlsInserted[] = $url; //add
+
+              if ( isset($record['tags']) && trim($record['tags']) ) {
+                //@TODO: set tags
+
+              }
             }
-            
-            # the second <ul> is for read links
-            $read = 1;
+          }
         }
-        $this->messages->add('s', _('import from pocket completed'));
-        Tools::logm('import from pocket completed');
-        Tools::redirect();
-    }
-
-    /**
-     * import from Readability. poche needs a ./readability file
-     * @todo add the return value
-     * @param string $targetFile the file used for importing
-     * @return boolean 
-     */
-    private function importFromReadability($targetFile)
-    {
-        # TODO gestion des articles lus / favs
-        $str_data = file_get_contents($targetFile);
-        $data = json_decode($str_data,true);
-        Tools::logm('starting import from Readability');
-        $count = 0;
-        foreach ($data as $key => $value) {
-            $url = NULL;
-            $favorite = FALSE;
-            $archive = FALSE;
-            foreach ($value as $item) {
-                foreach ($item as $attr => $value) {
-                    if ($attr == 'article__url') {
-                        $url = new Url(base64_encode($value));
-                    }
-                    $sequence = '';
-                    if (STORAGE == 'postgres') {
-                        $sequence = 'entries_id_seq';
-                    }
-                    if ($value == 'true') {
-                        if ($attr == 'favorite') {
-                            $favorite = TRUE;
-                        }
-                        if ($attr == 'archive') {
-                            $archive = TRUE;
-                        }
-                    }
-                }
 
-                # we can add the url
-                if (!is_null($url) && $url->isCorrect()) {
-                    $this->action('add', $url, 0, TRUE);
-                    $count++;
-                    if ($favorite) {
-                        $last_id = $this->store->getLastId($sequence);
-                        $this->action('toggle_fav', $url, $last_id, TRUE);
-                    }
-                    if ($archive) {
-                        $last_id = $this->store->getLastId($sequence);
-                        $this->action('toggle_archive', $url, $last_id, TRUE);
-                    }
-                }
-            }
+        $i = sizeof($urlsInserted);
+        if ( $i > 0 ) {
+          $this->messages->add('s', _('Articles inserted: ').$i._('. Please note, that some may be marked as "read".'));
         }
-        $this->messages->add('s', _('import from Readability completed. ' . $count . ' new links.'));
-        Tools::logm('import from Readability completed');
+        Tools::logm('Import of articles finished: '.$i.' articles added (w/o content if not provided).');
+      }
+      //file parsing finished here
+
+      //now download article contents if any
+
+      //check if we need to download any content
+      $recordsDownloadRequired = $this->store->retrieveUnfetchedEntriesCount($this->user->getId());
+      if ( $recordsDownloadRequired == 0 ) {
+        //nothing to download
+        $this->messages->add('s', _('Import finished.'));
+        Tools::logm('Import finished completely');
         Tools::redirect();
-    }
+      }
+      else {
+        //if just inserted - don't download anything, download will start in next reload
+        if ( !isset($_FILES['file']) ) {
+          //download next batch
+          Tools::logm('Fetching next batch of articles...');
+          $items = $this->store->retrieveUnfetchedEntries($this->user->getId(), IMPORT_LIMIT);
 
-    /**
-     * import from Poche exported file
-     * @param string $targetFile the file used for importing
-     * @return boolean 
-     */
-    private function importFromPoche($targetFile)
-    {
-        $str_data = file_get_contents($targetFile);
-        $data = json_decode($str_data,true);
-        Tools::logm('starting import from Poche');
+          $purifier = $this->getPurifier();
 
+          foreach ($items as $item) {
+            $url = new Url(base64_encode($item['url']));
+            Tools::logm('Fetching article '.$item['id']);
+            $content = Tools::getPageContent($url);
 
-        $sequence = '';
-        if (STORAGE == 'postgres') {
-            $sequence = 'entries_id_seq';
-        }
+            $title = (($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled'));
+            $body = (($content['rss']['channel']['item']['description'] != '') ? $content['rss']['channel']['item']['description'] : _('Undefined'));
 
-        $count = 0;
-        foreach ($data as $value) {
-
-            $url = new Url(base64_encode($value['url']));
-            $favorite = ($value['is_fav'] == -1);
-            $archive = ($value['is_read'] == -1);
-    
-            # we can add the url
-            if (!is_null($url) && $url->isCorrect()) {
-                
-                $this->action('add', $url, 0, TRUE);
-                
-                $count++;
-                if ($favorite) {
-                    $last_id = $this->store->getLastId($sequence);
-                    $this->action('toggle_fav', $url, $last_id, TRUE);
-                }
-                if ($archive) {
-                    $last_id = $this->store->getLastId($sequence);
-                    $this->action('toggle_archive', $url, $last_id, TRUE);
-                }
-            }
-            
-        }
-        $this->messages->add('s', _('import from Poche completed. ' . $count . ' new links.'));
-        Tools::logm('import from Poche completed');
-        Tools::redirect();
-    }
+            //clean content to prevent xss attack
+            $title = $purifier->purify($title);
+            $body = $purifier->purify($body);
+
+            $this->store->updateContentAndTitle($item['id'], $title, $body, $this->user->getId());
+            Tools::logm('Article '.$item['id'].' updated.');
+          }
 
-    /**
-     * import datas into your poche
-     * @param  string $from name of the service to import : pocket, instapaper or readability
-     * @todo add the return value
-     * @return boolean       
-     */
-    public function import($from)
-    {
-        $providers = array(
-            'pocket' => 'importFromPocket',
-            'readability' => 'importFromReadability',
-            'instapaper' => 'importFromInstapaper',
-            'poche' => 'importFromPoche',
-        );
-        
-        if (! isset($providers[$from])) {
-            $this->messages->add('e', _('Unknown import provider.'));
-            Tools::redirect();
-        }
-        
-        $targetDefinition = 'IMPORT_' . strtoupper($from) . '_FILE';
-        $targetFile = constant($targetDefinition);
-        
-        if (! defined($targetDefinition)) {
-            $this->messages->add('e', _('Incomplete inc/poche/define.inc.php file, please define "' . $targetDefinition . '".'));
-            Tools::redirect();
-        }
-        
-        if (! file_exists($targetFile)) {
-            $this->messages->add('e', _('Could not find required "' . $targetFile . '" import file.'));
-            Tools::redirect();
         }
-        
-        $this->$providers[$from]($targetFile);
+      }
+
+      return array('includeImport'=>true, 'import'=>array('recordsDownloadRequired'=>$recordsDownloadRequired, 'recordsUnderDownload'=> IMPORT_LIMIT, 'delay'=> IMPORT_DELAY * 1000) );
     }
 
     /**
      * export poche entries in json
      * @return json all poche entries
      */
-    public function export()
-    {
-        $entries = $this->store->retrieveAll($this->user->getId());
-        echo $this->tpl->render('export.twig', array(
-            'export' => Tools::renderJson($entries),
-        ));
-        Tools::logm('export view');
+    public function export() {
+      $filename = "wallabag-export-".$this->user->getId()."-".date("Y-m-d").".json";
+      header('Content-Disposition: attachment; filename='.$filename);
+
+      $entries = $this->store->retrieveAll($this->user->getId());
+      echo $this->tpl->render('export.twig', array(
+          'export' => Tools::renderJson($entries),
+      ));
+      Tools::logm('export view');
     }
 
     /**
@@ -1096,35 +1039,42 @@ class Poche
      * @param  string $which 'prod' or 'dev'
      * @return string        latest $which version
      */
-    private function getPocheVersion($which = 'prod')
-    {
-        $cache_file = CACHE . '/' . $which;
-
-        # checks if the cached version file exists
-        if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
-           $version = file_get_contents($cache_file);
-        } else {
-           $version = file_get_contents('http://static.wallabag.org/versions/' . $which);
-           file_put_contents($cache_file, $version, LOCK_EX);
-        }
-        return $version;
+    private function getPocheVersion($which = 'prod') {
+      $cache_file = CACHE . '/' . $which;
+      $check_time = time();
+
+      # checks if the cached version file exists
+      if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
+         $version = file_get_contents($cache_file);
+         $check_time = filemtime($cache_file);
+      } else {
+         $version = file_get_contents('http://static.wallabag.org/versions/' . $which);
+         file_put_contents($cache_file, $version, LOCK_EX);
+      }
+      return array($version, $check_time);
     }
 
     public function generateToken()
     {
-        if (ini_get('open_basedir') === '') {
-            $token = substr(base64_encode(file_get_contents('/dev/urandom', false, null, 0, 20)), 0, 15);
-        }
-        else {
-            $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
-        }
-
-        $token = str_replace('+', '', $token);
-        $this->store->updateUserConfig($this->user->getId(), 'token', $token);
-        $currentConfig = $_SESSION['poche_user']->config;
-        $currentConfig['token'] = $token;
-        $_SESSION['poche_user']->setConfig($currentConfig);
-        Tools::redirect();
+      if (ini_get('open_basedir') === '') {
+        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
+          echo 'This is a server using Windows!';
+          // alternative to /dev/urandom for Windows
+          $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
+        } else {
+          $token = substr(base64_encode(file_get_contents('/dev/urandom', false, null, 0, 20)), 0, 15);
+        }
+      }
+      else {
+        $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
+      }
+
+      $token = str_replace('+', '', $token);
+      $this->store->updateUserConfig($this->user->getId(), 'token', $token);
+      $currentConfig = $_SESSION['poche_user']->config;
+      $currentConfig['token'] = $token;
+      $_SESSION['poche_user']->setConfig($currentConfig);
+      Tools::redirect();
     }
 
     public function generateFeeds($token, $user_id, $tag_id, $type = 'home')
@@ -1132,8 +1082,11 @@ class Poche
         $allowed_types = array('home', 'fav', 'archive', 'tag');
         $config = $this->store->getConfigUser($user_id);
 
-        if (!in_array($type, $allowed_types) ||
-            $token != $config['token']) {
+        if ($config == null) {
+            die(sprintf(_('User with this id (%d) does not exist.'), $user_id));
+        }
+
+        if (!in_array($type, $allowed_types) || $token != $config['token']) {
             die(_('Uh, there is a problem while generating feeds.'));
         }
         // Check the token
@@ -1141,8 +1094,9 @@ class Poche
         $feed = new FeedWriter(RSS2);
         $feed->setTitle('wallabag — ' . $type . ' feed');
         $feed->setLink(Tools::getPocheUrl());
-        $feed->setChannelElement('updated', date(DATE_RSS , time()));
-        $feed->setChannelElement('author', 'wallabag');
+        $feed->setChannelElement('pubDate', date(DATE_RSS , time()));
+        $feed->setChannelElement('generator', 'wallabag');
+        $feed->setDescription('wallabag ' . $type . ' elements');
 
         if ($type == 'tag') {
             $entries = $this->store->retrieveEntriesByTag($tag_id, $user_id);
@@ -1155,7 +1109,8 @@ class Poche
             foreach ($entries as $entry) {
                 $newItem = $feed->createNewItem();
                 $newItem->setTitle($entry['title']);
-                $newItem->setLink(Tools::getPocheUrl() . '?view=view&amp;id=' . $entry['id']);
+                $newItem->setSource(Tools::getPocheUrl() . '?view=view&amp;id=' . $entry['id']);
+                $newItem->setLink($entry['url']);
                 $newItem->setDate(time());
                 $newItem->setDescription($entry['content']);
                 $feed->addItem($newItem);
@@ -1181,4 +1136,132 @@ class Poche
         $this->messages->add('s', _('Cache deleted.'));
         Tools::redirect();
     }
+
+    /**
+     * return new purifier object with actual config
+     */
+    protected function getPurifier() {
+      $config = HTMLPurifier_Config::createDefault();
+      $config->set('Cache.SerializerPath', CACHE);
+      $config->set('HTML.SafeIframe', true);
+
+      //allow YouTube, Vimeo and dailymotion videos
+      $config->set('URI.SafeIframeRegexp', '%^(https?:)?//(www\.youtube(?:-nocookie)?\.com/embed/|player\.vimeo\.com/video/|www\.dailymotion\.com/embed/video/)%');
+
+      return new HTMLPurifier($config);
+    }
+
+    /**
+     * handle epub
+     */
+    public function createEpub() {
+
+        switch ($_GET['method']) {
+            case 'id':
+                $entryID = filter_var($_GET['id'],FILTER_SANITIZE_NUMBER_INT);
+                $entry = $this->store->retrieveOneById($entryID, $this->user->getId());
+                $entries = array($entry);
+                $bookTitle = $entry['title'];
+                $bookFileName = substr($bookTitle, 0, 200);
+                break;
+            case 'all':
+                $entries = $this->store->retrieveAll($this->user->getId());
+                $bookTitle = sprintf(_('All my articles on '), date(_('d.m.y'))); #translatable because each country has it's own date format system
+                $bookFileName = _('Allarticles') . date(_('dmY'));
+                break;
+            case 'tag':
+                $tag = filter_var($_GET['tag'],FILTER_SANITIZE_STRING);
+                $tags_id = $this->store->retrieveAllTags($this->user->getId(),$tag);
+                $tag_id = $tags_id[0]["id"]; // we take the first result, which is supposed to match perfectly. There must be a workaround.
+                $entries = $this->store->retrieveEntriesByTag($tag_id,$this->user->getId());
+                $bookTitle = sprintf(_('Articles tagged %s'),$tag);
+                $bookFileName = substr(sprintf(_('Tag %s'),$tag), 0, 200);
+                break;
+            case 'category':
+                $category = filter_var($_GET['category'],FILTER_SANITIZE_STRING);
+                $entries = $this->store->getEntriesByView($category,$this->user->getId());
+                $bookTitle = sprintf(_('All articles in category %s'), $category);
+                $bookFileName = substr(sprintf(_('Category %s'),$category), 0, 200);
+                break;
+            case 'search':
+                $search = filter_var($_GET['search'],FILTER_SANITIZE_STRING);
+                $entries = $this->store->search($search,$this->user->getId());
+                $bookTitle = sprintf(_('All articles for search %s'), $search);
+                $bookFileName = substr(sprintf(_('Search %s'), $search), 0, 200);
+                break;
+            case 'default':
+                die(_('Uh, there is a problem while generating epub.'));
+
+        }
+
+        $content_start =
+        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+        . "<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\">\n"
+        . "<head>"
+        . "<meta http-equiv=\"Default-Style\" content=\"text/html; charset=utf-8\" />\n"
+        . "<title>wallabag articles book</title>\n"
+        . "</head>\n"
+        . "<body>\n";
+
+        $bookEnd = "</body>\n</html>\n";
+
+        $log = new Logger("wallabag", TRUE);
+        $fileDir = CACHE;
+        
+        $book = new EPub(EPub::BOOK_VERSION_EPUB3, DEBUG_POCHE);
+        $log->logLine("new EPub()");
+        $log->logLine("EPub class version: " . EPub::VERSION);
+        $log->logLine("EPub Req. Zip version: " . EPub::REQ_ZIP_VERSION);
+        $log->logLine("Zip version: " . Zip::VERSION);
+        $log->logLine("getCurrentServerURL: " . $book->getCurrentServerURL());
+        $log->logLine("getCurrentPageURL..: " . $book->getCurrentPageURL());
+
+        $book->setTitle(_('wallabag\'s articles'));
+        $book->setIdentifier("http://$_SERVER[HTTP_HOST]", EPub::IDENTIFIER_URI); // Could also be the ISBN number, prefered for published books, or a UUID.
+        //$book->setLanguage("en"); // Not needed, but included for the example, Language is mandatory, but EPub defaults to "en". Use RFC3066 Language codes, such as "en", "da", "fr" etc.
+        $book->setDescription(_("Some articles saved on my wallabag"));
+        $book->setAuthor("wallabag","wallabag");
+        $book->setPublisher("wallabag","wallabag"); // I hope this is a non existant address :)
+        $book->setDate(time()); // Strictly not needed as the book date defaults to time().
+        //$book->setRights("Copyright and licence information specific for the book."); // As this is generated, this _could_ contain the name or licence information of the user who purchased the book, if needed. If this is used that way, the identifier must also be made unique for the book.
+        $book->setSourceURL("http://$_SERVER[HTTP_HOST]");
+
+        $book->addDublinCoreMetadata(DublinCore::CONTRIBUTOR, "PHP");
+        $book->addDublinCoreMetadata(DublinCore::CONTRIBUTOR, "wallabag");
+
+        $cssData = "body {\n margin-left: .5em;\n margin-right: .5em;\n text-align: justify;\n}\n\np {\n font-family: serif;\n font-size: 10pt;\n text-align: justify;\n text-indent: 1em;\n margin-top: 0px;\n margin-bottom: 1ex;\n}\n\nh1, h2 {\n font-family: sans-serif;\n font-style: italic;\n text-align: center;\n background-color: #6b879c;\n color: white;\n width: 100%;\n}\n\nh1 {\n margin-bottom: 2px;\n}\n\nh2 {\n margin-top: -2px;\n margin-bottom: 2px;\n}\n";
+
+        $log->logLine("Add Cover");
+
+        $fullTitle = "<h1> " . $bookTitle . "</h1>\n";
+
+        $book->setCoverImage("Cover.png", file_get_contents("themes/baggy/img/apple-touch-icon-152.png"), "image/png", $fullTitle);
+
+        $cover = $content_start . '<div style="text-align:center;"><p>' . _('Produced by wallabag with PHPePub') . '</p><p>'. _('Please open <a href="https://github.com/wallabag/wallabag/issues" >an issue</a> if you have trouble with the display of this E-Book on your device.') . '</p></div>' . $bookEnd;
+
+        //$book->addChapter("Table of Contents", "TOC.xhtml", NULL, false, EPub::EXTERNAL_REF_IGNORE);
+        $book->addChapter("Notices", "Cover2.html", $cover);
+
+        $book->buildTOC();
+
+        foreach ($entries as $entry) { //set tags as subjects
+            $tags = $this->store->retrieveTagsByEntry($entry['id']);
+            foreach ($tags as $tag) {
+                $book->setSubject($tag['value']);
+            }
+
+            $log->logLine("Set up parameters");
+
+            $chapter = $content_start . $entry['content'] . $bookEnd;
+            $book->addChapter($entry['title'], htmlspecialchars($entry['title']) . ".html", $chapter, true, EPub::EXTERNAL_REF_ADD);
+            $log->logLine("Added chapter " . $entry['title']);
+        }
+
+        if (DEBUG_POCHE) {
+            $epuplog = $book->getLog();
+            $book->addChapter("Log", "Log.html", $content_start . $log->getLog() . "\n</pre>" . $bookEnd); // log generation
+        }
+        $book->finalize();
+        $zipData = $book->sendBook($bookFileName);
+    }
 }
old mode 100644 (file)
new mode 100755 (executable)
index 4ed28ed..cc01f40
@@ -7,7 +7,7 @@
  * @copyright  2013
  * @license    http://www.wtfpl.net/ see COPYING file
  */
+
 class Tools
 {
     public static function initPhp()
@@ -18,8 +18,6 @@ class Tools
             die(_('Oops, it seems you don\'t have PHP 5.'));
         }
 
-        error_reporting(E_ALL);
-
         function stripslashesDeep($value) {
             return is_array($value)
                 ? array_map('stripslashesDeep', $value)
@@ -42,7 +40,7 @@ class Tools
                     && (strtolower($_SERVER['HTTPS']) == 'on'))
             || (isset($_SERVER["SERVER_PORT"])
                     && $_SERVER["SERVER_PORT"] == '443') // HTTPS detection.
-            || (isset($_SERVER["SERVER_PORT"]) //Custom HTTPS port detection 
+            || (isset($_SERVER["SERVER_PORT"]) //Custom HTTPS port detection
                     && $_SERVER["SERVER_PORT"] == SSL_PORT)
              || (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])
                     && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https');
@@ -59,8 +57,14 @@ class Tools
             return $scriptname;
         }
 
+        $host = (isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME']));
+
+        if (strpos($host, ':') !== false) {
+            $serverport = '';
+        }
+
         return 'http' . ($https ? 's' : '') . '://'
-            . $_SERVER["HTTP_HOST"] . $serverport . $scriptname;
+            . $host . $serverport . $scriptname;
     }
 
     public static function redirect($url = '')
@@ -148,7 +152,7 @@ class Tools
             );
 
             # only download page lesser than 4MB
-            $data = @file_get_contents($url, false, $context, -1, 4000000); 
+            $data = @file_get_contents($url, false, $context, -1, 4000000);
 
             if (isset($http_response_header) and isset($http_response_header[0])) {
                 $httpcodeOK = isset($http_response_header) and isset($http_response_header[0]) and ((strpos($http_response_header[0], '200 OK') !== FALSE) or (strpos($http_response_header[0], '301 Moved Permanently') !== FALSE));
@@ -193,14 +197,14 @@ class Tools
 
     public static function logm($message)
     {
-        if (DEBUG_POCHE) {
+        if (DEBUG_POCHE && php_sapi_name() != 'cli') {
             $t = strval(date('Y/m/d_H:i:s')) . ' - ' . $_SERVER["REMOTE_ADDR"] . ' - ' . strval($message) . "\n";
             file_put_contents(CACHE . '/log.txt', $t, FILE_APPEND);
             error_log('DEBUG POCHE : ' . $message);
         }
     }
 
-    public static function encodeString($string) 
+    public static function encodeString($string)
     {
         return sha1($string . SALT);
     }
@@ -212,7 +216,7 @@ class Tools
 
     public static function getDomain($url)
     {
-      return parse_url($url, PHP_URL_HOST);
+        return parse_url($url, PHP_URL_HOST);
     }
 
     public static function getReadingTime($text) {
@@ -241,7 +245,6 @@ class Tools
         }
     }
 
-
     public static function download_db() {
         header('Content-Disposition: attachment; filename="poche.sqlite.gz"');
         self::status(200);
@@ -252,4 +255,74 @@ class Tools
 
         exit;
     }
+
+    public static function getPageContent(Url $url)
+    {
+        // Saving and clearing context
+        $REAL = array();
+        foreach( $GLOBALS as $key => $value ) {
+            if( $key != 'GLOBALS' && $key != '_SESSION' && $key != 'HTTP_SESSION_VARS' ) {
+                $GLOBALS[$key] = array();
+                $REAL[$key] = $value;
+            }
+        }
+        // Saving and clearing session
+        if ( isset($_SESSION) ) {
+            $REAL_SESSION = array();
+            foreach( $_SESSION as $key => $value ) {
+                $REAL_SESSION[$key] = $value;
+                unset($_SESSION[$key]);
+            }
+        }
+
+        // Running code in different context
+        $scope = function() {
+            extract( func_get_arg(1) );
+            $_GET = $_REQUEST = array(
+                        "url" => $url->getUrl(),
+                        "max" => 5,
+                        "links" => "preserve",
+                        "exc" => "",
+                        "format" => "json",
+                        "submit" => "Create Feed"
+            );
+            ob_start();
+            require func_get_arg(0);
+            $json = ob_get_contents();
+            ob_end_clean();
+            return $json;
+        };
+        $json = $scope( "inc/3rdparty/makefulltextfeed.php", array("url" => $url) );
+
+        // Clearing and restoring context
+        foreach( $GLOBALS as $key => $value ) {
+            if( $key != "GLOBALS" && $key != "_SESSION" ) {
+                unset($GLOBALS[$key]);
+            }
+        }
+        foreach( $REAL as $key => $value ) {
+            $GLOBALS[$key] = $value;
+        }
+        // Clearing and restoring session
+        if ( isset($REAL_SESSION) ) {
+            foreach( $_SESSION as $key => $value ) {
+                unset($_SESSION[$key]);
+            }
+            foreach( $REAL_SESSION as $key => $value ) {
+                $_SESSION[$key] = $value;
+            }
+        }
+
+        return json_decode($json, true);
+    }
+
+    /**
+     * Returns whether we handle an AJAX (XMLHttpRequest) request.
+     * @return boolean whether we handle an AJAX (XMLHttpRequest) request.
+     */
+    public static function isAjaxRequest()
+    {
+      return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
+    }
+
 }
diff --git a/inc/poche/config.inc.default.php b/inc/poche/config.inc.default.php
new file mode 100755 (executable)
index 0000000..95f727c
--- /dev/null
@@ -0,0 +1,68 @@
+<?php
+/**
+ * wallabag, self hostable application allowing you to not miss any content anymore
+ *
+ * @category   wallabag
+ * @author     Nicolas Lœuillet <nicolas@loeuillet.org>
+ * @copyright  2013
+ * @license    http://www.wtfpl.net/ see COPYING file
+ */
+
+@define ('SALT', ''); # put a strong string here
+@define ('LANG', 'en_EN.utf8');
+
+@define ('STORAGE', 'sqlite'); # postgres, mysql or sqlite
+
+@define ('STORAGE_SQLITE', ROOT . '/db/poche.sqlite'); # if you are using sqlite, where the database file is located
+
+# only for postgres & mysql
+@define ('STORAGE_SERVER', 'localhost');
+@define ('STORAGE_DB', 'poche');
+@define ('STORAGE_USER', 'poche');
+@define ('STORAGE_PASSWORD', 'poche');
+
+#################################################################################
+# Do not trespass unless you know what you are doing
+#################################################################################
+
+// Change this if not using the standart port for SSL - i.e you server is behind sslh
+@define ('SSL_PORT', 443);
+
+@define ('MODE_DEMO', FALSE);
+@define ('DEBUG_POCHE', FALSE);
+
+//default level of error reporting in application. Developers should override it in their config.inc.php: set to E_ALL.
+@define ('ERROR_REPORTING', E_ALL & ~E_NOTICE);
+
+@define ('DOWNLOAD_PICTURES', FALSE); # This can slow down the process of adding articles
+@define ('REGENERATE_PICTURES_QUALITY', 75);
+@define ('CONVERT_LINKS_FOOTNOTES', FALSE);
+@define ('REVERT_FORCED_PARAGRAPH_ELEMENTS', FALSE);
+@define ('SHARE_TWITTER', TRUE);
+@define ('SHARE_MAIL', TRUE);
+@define ('SHARE_SHAARLI', FALSE);
+@define ('SHAARLI_URL', 'http://myshaarliurl.com');
+@define ('FLATTR', TRUE);
+@define ('FLATTR_API', 'https://api.flattr.com/rest/v2/things/lookup/?url=');
+@define ('NOT_FLATTRABLE', '0');
+@define ('FLATTRABLE', '1');
+@define ('FLATTRED', '2');
+// display or not print link in article view
+@define ('SHOW_PRINTLINK', '1');
+// display or not percent of read in article view. Affects only default theme.
+@define ('SHOW_READPERCENT', '1');
+@define ('ABS_PATH', 'assets/');
+
+@define ('DEFAULT_THEME', 'baggy');
+
+@define ('THEME', ROOT . '/themes');
+@define ('LOCALE', ROOT . '/locale');
+@define ('CACHE', ROOT . '/cache');
+
+@define ('PAGINATION', '10');
+
+//limit for download of articles during import
+@define ('IMPORT_LIMIT', 5);
+//delay between downloads (in sec)
+@define ('IMPORT_DELAY', 5);
+
diff --git a/inc/poche/config.inc.php.new b/inc/poche/config.inc.php.new
deleted file mode 100755 (executable)
index 8d52497..0000000
+++ /dev/null
@@ -1,63 +0,0 @@
-<?php
-/**
- * wallabag, self hostable application allowing you to not miss any content anymore
- *
- * @category   wallabag
- * @author     Nicolas Lœuillet <nicolas@loeuillet.org>
- * @copyright  2013
- * @license    http://www.wtfpl.net/ see COPYING file
- */
-
-define ('SALT', ''); # put a strong string here
-define ('LANG', 'en_EN.utf8');
-
-define ('STORAGE', 'sqlite'); # postgres, mysql or sqlite
-
-define ('STORAGE_SQLITE', ROOT . '/db/poche.sqlite'); # if you are using sqlite, where the database file is located
-
-# only for postgres & mysql
-define ('STORAGE_SERVER', 'localhost');
-define ('STORAGE_DB', 'poche');
-define ('STORAGE_USER', 'poche');
-define ('STORAGE_PASSWORD', 'poche');
-
-#################################################################################
-# Do not trespass unless you know what you are doing
-#################################################################################
-
-// Change this if not using the standart port for SSL - i.e you server is behind sslh
-define ('SSL_PORT', 443); 
-
-define ('MODE_DEMO', FALSE);
-define ('DEBUG_POCHE', FALSE);
-define ('DOWNLOAD_PICTURES', FALSE);
-define ('CONVERT_LINKS_FOOTNOTES', FALSE);
-define ('REVERT_FORCED_PARAGRAPH_ELEMENTS', FALSE);
-define ('SHARE_TWITTER', TRUE);
-define ('SHARE_MAIL', TRUE);
-define ('SHARE_SHAARLI', FALSE);
-define ('SHAARLI_URL', 'http://myshaarliurl.com');
-define ('FLATTR', TRUE);
-define ('FLATTR_API', 'https://api.flattr.com/rest/v2/things/lookup/?url=');
-define ('NOT_FLATTRABLE', '0');
-define ('FLATTRABLE', '1');
-define ('FLATTRED', '2');
-define ('ABS_PATH', 'assets/');
-
-define ('DEFAULT_THEME', 'baggy');
-
-define ('THEME', ROOT . '/themes');
-define ('LOCALE', ROOT . '/locale');
-define ('CACHE', ROOT . '/cache');
-
-define ('PAGINATION', '10');
-
-define ('POCKET_FILE', '/ril_export.html');
-define ('READABILITY_FILE', '/readability');
-define ('INSTAPAPER_FILE', '/instapaper-export.html');
-define ('POCHE_FILE', '/poche-export');
-
-define ('IMPORT_POCKET_FILE', ROOT . POCKET_FILE);
-define ('IMPORT_READABILITY_FILE', ROOT . READABILITY_FILE);
-define ('IMPORT_INSTAPAPER_FILE', ROOT . INSTAPAPER_FILE);
-define ('IMPORT_POCHE_FILE', ROOT . POCHE_FILE);
\ No newline at end of file
old mode 100644 (file)
new mode 100755 (executable)
index d22b058..8cf86d0
@@ -31,6 +31,11 @@ require_once INCLUDES . '/3rdparty/FlattrItem.class.php';
 
 require_once INCLUDES . '/3rdparty/htmlpurifier/HTMLPurifier.auto.php';
 
+# epub library
+require_once INCLUDES . '/3rdparty/libraries/PHPePub/Logger.php';
+require_once INCLUDES . '/3rdparty/libraries/PHPePub/EPub.php';
+require_once INCLUDES . '/3rdparty/libraries/PHPePub/EPubChapterSplitter.php';
+
 # Composer its autoloader for automatically loading Twig
 if (! file_exists(ROOT . '/vendor/autoload.php')) {
     Poche::$canRenderTemplates = false;
@@ -38,11 +43,12 @@ if (! file_exists(ROOT . '/vendor/autoload.php')) {
     require_once ROOT . '/vendor/autoload.php';
 }
 
-# system configuration; database credentials et cetera
+# system configuration; database credentials et caetera
 if (! file_exists(INCLUDES . '/poche/config.inc.php')) {
     Poche::$configFileAvailable = false;
 } else {
     require_once INCLUDES . '/poche/config.inc.php';
+    require_once INCLUDES . '/poche/config.inc.default.php';
 }
 
 if (Poche::$configFileAvailable && DOWNLOAD_PICTURES) {
index e4b0b1608843b0ec8d0a81642a44fb8c2e55d161..7c319a857659862c7484afa365fad176a143bfbd 100644 (file)
@@ -14,6 +14,7 @@
 function filtre_picture($content, $url, $id)
 {
     $matches = array();
+    $processing_pictures = array(); // list of processing image to avoid processing the same pictures twice
     preg_match_all('#<\s*(img)[^>]+src="([^"]*)"[^>]*>#Si', $content, $matches, PREG_SET_ORDER);
     foreach($matches as $i => $link) {
         $link[1] = trim($link[1]);
@@ -22,8 +23,17 @@ function filtre_picture($content, $url, $id)
             $filename = basename(parse_url($absolute_path, PHP_URL_PATH));
             $directory = create_assets_directory($id);
             $fullpath = $directory . '/' . $filename;
-            download_pictures($absolute_path, $fullpath);
-            $content = str_replace($matches[$i][2], $fullpath, $content);
+            
+            if (in_array($absolute_path, $processing_pictures) === true) {
+                // replace picture's URL only if processing is OK : already processing -> go to next picture
+                continue;
+            }
+            
+            if (download_pictures($absolute_path, $fullpath) === true) {
+                $content = str_replace($matches[$i][2], $fullpath, $content);
+            }
+            
+            $processing_pictures[] = $absolute_path;
         }
 
     }
@@ -64,17 +74,55 @@ function get_absolute_link($relative_link, $url) {
 
 /**
  * Téléchargement des images
+ * 
+ * @return bool true if the download and processing is OK, false else
  */
 function download_pictures($absolute_path, $fullpath)
 {
     $rawdata = Tools::getFile($absolute_path);
+    $fullpath = urldecode($fullpath);
 
     if(file_exists($fullpath)) {
         unlink($fullpath);
     }
-    $fp = fopen($fullpath, 'x');
-    fwrite($fp, $rawdata);
-    fclose($fp);
+    
+    // check extension
+    $file_ext = strrchr($fullpath, '.');
+    $whitelist = array(".jpg",".jpeg",".gif",".png"); 
+    if (!(in_array($file_ext, $whitelist))) {
+        Tools::logm('processed image with not allowed extension. Skipping ' . $fullpath);
+        return false;
+    }
+    
+    // check headers
+    $imageinfo = getimagesize($absolute_path);
+    if ($imageinfo['mime'] != 'image/gif' && $imageinfo['mime'] != 'image/jpeg'&& $imageinfo['mime'] != 'image/jpg'&& $imageinfo['mime'] != 'image/png') {
+        Tools::logm('processed image with bad header. Skipping ' . $fullpath);
+        return false;
+    }
+    
+    // regenerate image
+    $im = imagecreatefromstring($rawdata);
+    if ($im === false) {
+        Tools::logm('error while regenerating image ' . $fullpath);
+        return false;
+    }
+    
+    switch ($imageinfo['mime']) {
+        case 'image/gif':
+            $result = imagegif($im, $fullpath);
+            break;
+        case 'image/jpeg':
+        case 'image/jpg':
+            $result = imagejpeg($im, $fullpath, REGENERATE_PICTURES_QUALITY);
+            break;
+        case 'image/png':
+            $result = imagepng($im, $fullpath, ceil(REGENERATE_PICTURES_QUALITY / 100 * 9));
+            break;
+    }
+    imagedestroy($im);
+    
+    return $result;
 }
 
 /**
old mode 100644 (file)
new mode 100755 (executable)
index a26c42e..481841e
--- a/index.php
+++ b/index.php
@@ -8,10 +8,18 @@
  * @license    http://www.wtfpl.net/ see COPYING file
  */
 
-define ('POCHE', '1.5.2');
+define ('POCHE', '1.7.1');
 require 'check_setup.php';
 require_once 'inc/poche/global.inc.php';
-session_start(); 
+
+# Set error reporting level
+if (defined('ERROR_REPORTING')) {
+       error_reporting(ERROR_REPORTING);
+}
+
+# Start session
+Session::$sessionName = 'poche';
+Session::init();
 
 # Start Poche
 $poche = new Poche();
@@ -30,14 +38,14 @@ $tpl_vars = array(
     'referer' => $referer,
     'view' => $view,
     'poche_url' => Tools::getPocheUrl(),
-    'title' => _('poche, a read it later open source system'),
+    'title' => _('wallabag, a read it later open source system'),
     'token' => Session::getToken(),
     'theme' => $poche->getTheme()
 );
 
 if (! empty($notInstalledMessage)) {
     if (! Poche::$canRenderTemplates || ! Poche::$configFileAvailable) {
-        # We cannot use Twig to display the error message 
+        # We cannot use Twig to display the error message
         echo '<h1>Errors</h1><ol>';
         foreach ($notInstalledMessage as $message) {
             echo '<li>' . $message . '</li>';
@@ -63,8 +71,15 @@ if (isset($_GET['login'])) {
 } elseif (isset($_GET['config'])) {
     # Update password
     $poche->updatePassword();
+} elseif (isset($_GET['newuser'])) {
+    $poche->createNewUser();
+} elseif (isset($_GET['deluser'])) {
+    $poche->deleteUser();
+} elseif (isset($_GET['epub'])) {
+    $poche->createEpub();
 } elseif (isset($_GET['import'])) {
-    $import = $poche->import($_GET['from']);
+    $import = $poche->import();
+    $tpl_vars = array_merge($tpl_vars, $import);
 } elseif (isset($_GET['download'])) {
     Tools::download_db();
 } elseif (isset($_GET['empty-cache'])) {
@@ -75,13 +90,15 @@ if (isset($_GET['login'])) {
     $poche->updateTheme();
 } elseif (isset($_GET['updatelanguage'])) {
     $poche->updateLanguage();
+} elseif (isset($_GET['uploadfile'])) {
+    $poche->uploadFile();
 } elseif (isset($_GET['feed'])) {
     if (isset($_GET['action']) && $_GET['action'] == 'generate') {
         $poche->generateToken();
     }
     else {
         $tag_id = (isset($_GET['tag_id']) ? intval($_GET['tag_id']) : 0);
-        $poche->generateFeeds($_GET['token'], $_GET['user_id'], $tag_id, $_GET['type']);
+        $poche->generateFeeds($_GET['token'], filter_var($_GET['user_id'],FILTER_SANITIZE_NUMBER_INT), $tag_id, $_GET['type']);
     }
 }
 
@@ -115,6 +132,7 @@ if (Session::isLogged()) {
 } else {
     $tpl_file = Tools::getTplFile('login');
     $tpl_vars['http_auth'] = 0;
+    Session::logout();
 }
 
 # because messages can be added in $poche->action(), we have to add this entry now (we can add it before)
old mode 100644 (file)
new mode 100755 (executable)
index 975b997..e702891
@@ -1,9 +1,30 @@
 <?php
 $errors = array();
 $successes = array();
-if ($_POST['download']) {
+
+/* Function taken from at http://php.net/manual/en/function.rmdir.php#110489
+ * Idea : nbari at dalmp dot com
+ * Rights unknown
+ * Here in case of .gitignore files
+ */
+function delTree($dir) {
+    $files = array_diff(scandir($dir), array('.','..'));
+    foreach ($files as $file) {
+      (is_dir("$dir/$file")) ? delTree("$dir/$file") : unlink("$dir/$file");
+    }
+    return rmdir($dir);
+  }
+
+if (isset($_GET['clean'])) {
+    if (is_dir('install')){
+    delTree('install');
+    header('Location: index.php');      
+    }
+}
+
+if (isset($_POST['download'])) {
     if (!file_put_contents("cache/vendor.zip", fopen("http://static.wallabag.org/files/vendor.zip", 'r'))) {
-        $errors[] = 'Impossible to download vendor.zip. Please <a href="http://wllbg.org/vendor">download it manually<a> and unzip it in your wallabag folder.';
+        $errors[] = 'Impossible to download vendor.zip. Please <a href="http://wllbg.org/vendor">download it manually</a> and unzip it in your wallabag folder.';
     }
     else {
         if (extension_loaded('zip')) {
@@ -25,14 +46,14 @@ if ($_POST['download']) {
         }
     }
 }
-else if ($_POST['install']) {
+else if (isset($_POST['install'])) {
     if (!is_dir('vendor')) {
         $errors[] = 'You must install twig before.';
     }
     else {
         $continue = true;
         // Create config.inc.php
-        if (!copy('inc/poche/config.inc.php.new', 'inc/poche/config.inc.php')) {
+        if (!copy('inc/poche/config.inc.default.php', 'inc/poche/config.inc.php')) {
             $errors[] = 'Installation aborted, impossible to create inc/poche/config.inc.php file. Maybe you don\'t have write access to create it.';
             $continue = false;
         }
@@ -64,6 +85,7 @@ else if ($_POST['install']) {
                 else {
                     $db_path = 'sqlite:' . realpath('') . '/db/poche.sqlite';
                     $handle = new PDO($db_path);
+                    $sql_structure = "";
                 }
             }
             else {
@@ -79,7 +101,7 @@ else if ($_POST['install']) {
 
                     $sql_structure = file_get_contents('install/mysql.sql');
                 }
-                else if ($_POST['db_engine'] == 'postgresql') {
+                else if ($_POST['db_engine'] == 'postgres') {
                     $db_path = 'pgsql:host=' . $_POST['pg_server'] . ';dbname=' . $_POST['pg_database'];
                     $content = str_replace("define ('STORAGE_SERVER', 'localhost');", "define ('STORAGE_SERVER', '".$_POST['pg_server']."');", $content);
                     $content = str_replace("define ('STORAGE_DB', 'poche');", "define ('STORAGE_DB', '".$_POST['pg_database']."');", $content);
@@ -129,7 +151,7 @@ else if ($_POST['install']) {
                 $params = array($id_user, 'language', 'en_EN.UTF8');
                 $query = executeQuery($handle, $sql, $params);
 
-                $successes[] = 'wallabag is now installed. Don\'t forget to delete install folder. Then, <a href="index.php">reload this page</a>.';
+                $successes[] = 'wallabag is now installed. You can now <a href="index.php?clean=0">access it !</a>';
             }
         }
     }
@@ -143,7 +165,7 @@ else if ($_POST['install']) {
         <!--[if IE]>
         <meta http-equiv="X-UA-Compatible" content="IE=10">
         <![endif]-->
-        <title>wallabag  installation</title>
+        <title>wallabag - installation</title>
         <link rel="shortcut icon" type="image/x-icon" href="themes/baggy/img/favicon.ico" />
         <link rel="apple-touch-icon-precomposed" sizes="144x144" href="themes/baggy/img/apple-touch-icon-144x144-precomposed.png">
         <link rel="apple-touch-icon-precomposed" sizes="72x72" href="themes/baggy/img/apple-touch-icon-72x72-precomposed.png">
@@ -154,7 +176,7 @@ else if ($_POST['install']) {
         <link rel="stylesheet" href="themes/baggy/css/main.css" media="all">
         <link rel="stylesheet" href="themes/baggy/css/messages.css" media="all">
         <link rel="stylesheet" href="themes/baggy/css/print.css" media="print">
-        <script src="themes/baggy/js/jquery-2.0.3.min.js"></script>
+        <script src="themes/default/js/jquery-2.0.3.min.js"></script>
         <script src="themes/baggy/js/init.js"></script>
     </head>
     <body>
@@ -198,18 +220,18 @@ else if ($_POST['install']) {
                 <?php if (file_exists('inc/poche/config.inc.php') && is_dir('vendor')) : ?>
                 <div class='messages success install'>
                     <p>
-                        wallabag seems already installed. If you want to update it, you only have to delete install folder.
+                        wallabag seems already installed. If you want to update it, you only have to delete install folder, then <a href="index.php">reload this page</a>.
                     </p>
                 </div>
                 <?php endif; ?>    
             <?php endif; ?>
             <p>To install wallabag, you just have to fill the following fields. That's all.</p>
-            <p>Don't forget to check your server compatibility <a href="wallabag_compatibility_test.php">here</a>.</p>
+            <p>Don't forget to check your server compatibility <a href="wallabag_compatibility_test.php?from=install">here</a>.</p>
             <form method="post">
                 <fieldset>
                     <legend><strong>Technical settings</strong></legend>
                     <?php if (!is_dir('vendor')) : ?>
-                        <div class='messages notice install'>wallabag needs twig, a template engine (<a href="http://twig.sensiolabs.org/">?</a>). Two ways to install it: 
+                        <div class='messages notice install'>wallabag needs twig, a template engine (<a href="http://twig.sensiolabs.org/">?</a>). Two ways to install it:<br />
                         <ul>
                             <li>automatically download and extract vendor.zip into your wallabag folder. 
                             <p><input type="submit" name="download" value="Download vendor.zip" /></p>
@@ -225,7 +247,11 @@ php composer.phar install</code></pre></li>
                     <p>
                         Database engine:
                         <ul>
-                            <li><label for="sqlite">SQLite</label> <input name="db_engine" type="radio" checked="" id="sqlite" value="sqlite" /></li>
+                            <li><label for="sqlite">SQLite</label> <input name="db_engine" type="radio" checked="" id="sqlite" value="sqlite" />
+                            <div id="pdo_sqlite" class='messages error install'>
+                                <p>You have to enable <a href="http://php.net/manual/ref.pdo-sqlite.php">pdo_sqlite extension</a>.</p>
+                            </div>
+                            </li>
                             <li>
                                 <label for="mysql">MySQL</label> <input name="db_engine" type="radio" id="mysql" value="mysql" />
                                 <ul id="mysql_infos">
@@ -236,12 +262,12 @@ php composer.phar install</code></pre></li>
                                 </ul>
                             </li>
                             <li>
-                                <label for="postgresql">PostgreSQL</label> <input name="db_engine" type="radio" id="postgresql" value="postgresql" />
+                                <label for="postgres">PostgreSQL</label> <input name="db_engine" type="radio" id="postgres" value="postgres" />
                                 <ul id="pg_infos">
                                     <li><label for="pg_server">Server</label> <input type="text" placeholder="localhost" id="pg_server" name="pg_server" /></li>
                                     <li><label for="pg_database">Database</label> <input type="text" placeholder="wallabag" id="pg_database" name="pg_database" /></li>
                                     <li><label for="pg_user">User</label> <input type="text" placeholder="user" id="pg_user" name="pg_user" /></li>
-                                  id  <li><label for="pg_password">Password</label> <input type="text" placeholder="p4ssw0rd" id="pg_password" name="pg_password" /></li>
+                                    <li><label for="pg_password">Password</label> <input type="text" placeholder="p4ssw0rd" id="pg_password" name="pg_password" /></li>
                                 </ul>
                             </li>
                         </ul>
@@ -263,26 +289,49 @@ php composer.phar install</code></pre></li>
                     </p>
                 </fieldset>
 
-                <input type="submit" value="Install wallabag" name="install" />
+                <input type="submit" id="install_button" value="Install wallabag" name="install" />
             </form>
         </div>
         <script>
             $("#mysql_infos").hide();
             $("#pg_infos").hide();
+
+            <?php
+            if (!extension_loaded('pdo_sqlite')) : ?>
+            $("#install_button").hide();
+            <?php
+            else :
+            ?>
+            $("#pdo_sqlite").hide();
+            <?php
+            endif;
+            ?>
+
             $("input[name=db_engine]").click(function() 
                 {
                     if ( $("#mysql").prop('checked')) {
                         $("#mysql_infos").show();
                         $("#pg_infos").hide();
+                        $("#pdo_sqlite").hide();
+                        $("#install_button").show();
                     }
                     else {
-                        if ( $("#postgresql").prop('checked')) {
+                        if ( $("#postgres").prop('checked')) {
                             $("#mysql_infos").hide();
                             $("#pg_infos").show();
+                            $("#pdo_sqlite").hide();
+                            $("#install_button").show();
                         }
                         else {
                             $("#mysql_infos").hide();
                             $("#pg_infos").hide();
+                            <?php
+                            if (!extension_loaded('pdo_sqlite')) : ?>
+                            $("#pdo_sqlite").show();
+                            $("#install_button").hide();
+                            <?php
+                            endif;
+                            ?>
                         }
                     }
                 });
old mode 100755 (executable)
new mode 100644 (file)
index fe8f559ca29c31925a69b88d0d2cab5d815f117a..1d73dfcba2f294d46ecb25e20f0ce1190fb192e8 100644 (file)
@@ -1,10 +1,10 @@
-CREATE TABLE config (
+CREATE TABLE IF NOT EXISTS config (
     id bigserial primary key,
     name varchar(255) NOT NULL,
     value varchar(255) NOT NULL
 );
 
-CREATE TABLE entries (
+CREATE TABLE IF NOT EXISTS entries (
     id bigserial primary key,
     title varchar(255) NOT NULL,
     url varchar(255) NOT NULL,
@@ -14,7 +14,7 @@ CREATE TABLE entries (
     user_id integer NOT NULL
 );
 
-CREATE TABLE users (
+CREATE TABLE IF NOT EXISTS users (
     id bigserial primary key,
     username varchar(255) NOT NULL,
     password varchar(255) NOT NULL,
@@ -22,20 +22,20 @@ CREATE TABLE users (
     email varchar(255) NOT NULL
 );
 
-CREATE TABLE users_config (
+CREATE TABLE IF NOT EXISTS users_config (
     id bigserial primary key,
     user_id integer NOT NULL,
     name varchar(255) NOT NULL,
     value varchar(255) NOT NULL
 );
 
-CREATE TABLE tags (
+CREATE TABLE IF NOT EXISTS tags (
   id bigserial primary key,
   value varchar(255) NOT NULL
 );
 
-CREATE TABLE tags_entries (
+CREATE TABLE IF NOT EXISTS tags_entries (
   id bigserial primary key,
   entry_id integer NOT NULL,
   tag_id integer NOT NULL
-)
\ No newline at end of file
+)
index 8209a9cddfa711012ebf75bbfda242b69f3a2a4b..cf727432b27c658c9761fcecbc3056105cb36245 100644 (file)
 msgid ""
 msgstr ""
 "Project-Id-Version: poche\n"
-"POT-Creation-Date: \n"
-"PO-Revision-Date: 2013-10-08 13:25+0100\n"
-"Last-Translator: Nicolas Lœuillet <nicolas.loeuillet@gmail.com>\n"
-"Language-Team: Czech (http://www.transifex.com/projects/p/poche/language/"
-"cs/)\n"
+"Report-Msgid-Bugs-To: \n"
+"POT-Creation-Date: 2014-02-25 15:28+0300\n"
+"PO-Revision-Date: 2014-02-25 15:29+0300\n"
+"Last-Translator: Maryana <mariroz@mr.lviv.ua>\n"
+"Language-Team: Czech (http://www.transifex.com/projects/p/poche/language/cs/)\n"
+"Language: cs\n"
 "MIME-Version: 1.0\n"
 "Content-Type: text/plain; charset=UTF-8\n"
 "Content-Transfer-Encoding: 8bit\n"
-"Language: cs\n"
 "Plural-Forms: nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;\n"
 "X-Generator: Poedit 1.5.4\n"
+"X-Poedit-Language: Czech\n"
+"X-Poedit-Basepath: .\n"
+"X-Poedit-SearchPath-0: /home/mariroz/_DEV/web/wallabag/wallabag-master-testing\n"
+
+msgid "wallabag, a read it later open source system"
+msgstr ""
+
+msgid "login failed: user doesn't exist"
+msgstr ""
+
+msgid "return home"
+msgstr ""
 
 msgid "config"
 msgstr "nastavení"
 
-msgid "Poching a link"
-msgstr "Odkaz se ukládá"
+msgid "Saving articles"
+msgstr ""
+
+msgid "There are several ways to save an article:"
+msgstr ""
 
 msgid "read the documentation"
 msgstr "číst dokumentaci"
 
-msgid "by filling this field"
+msgid "download the extension"
+msgstr ""
+
+msgid "via F-Droid"
+msgstr ""
+
+msgid " or "
+msgstr ""
+
+msgid "via Google Play"
+msgstr ""
+
+msgid "download the application"
+msgstr ""
+
+#, fuzzy
+msgid "By filling this field"
 msgstr "vyplněním tohoto pole"
 
-msgid "poche it!"
-msgstr "uložit!"
+msgid "bag it!"
+msgstr ""
 
-msgid "Updating poche"
-msgstr "Poche se aktualizuje"
+msgid "Bookmarklet: drag & drop this link to your bookmarks bar"
+msgstr ""
 
-msgid "your version"
-msgstr "vaše verze"
+msgid "Upgrading wallabag"
+msgstr ""
 
-msgid "latest stable version"
+#, fuzzy
+msgid "Installed version"
 msgstr "poslední stabilní verze"
 
-msgid "a more recent stable version is available."
+#, fuzzy
+msgid "Latest stable version"
+msgstr "poslední stabilní verze"
+
+#, fuzzy
+msgid "A more recent stable version is available."
 msgstr "je k dispozici novější stabilní verze."
 
-msgid "you are up to date."
+#, fuzzy
+msgid "You are up to date."
 msgstr "je aktuální"
 
-msgid "latest dev version"
+#, fuzzy
+msgid "Latest dev version"
 msgstr "poslední vývojová verze"
 
-msgid "a more recent development version is available."
+#, fuzzy
+msgid "A more recent development version is available."
 msgstr "je k dispozici novější vývojová verze."
 
+msgid "Feeds"
+msgstr ""
+
+msgid "Your feed token is currently empty and must first be generated to enable feeds. Click <a href='?feed&amp;action=generate'>here to generate it</a>."
+msgstr ""
+
+msgid "Unread feed"
+msgstr ""
+
+#, fuzzy
+msgid "Favorites feed"
+msgstr "oblíbené"
+
+#, fuzzy
+msgid "Archive feed"
+msgstr "archív"
+
+msgid "Your token:"
+msgstr ""
+
+msgid "Your user id:"
+msgstr ""
+
+msgid "You can regenerate your token: <a href='?feed&amp;action=generate'>generate!</a>."
+msgstr ""
+
+#, fuzzy
+msgid "Change your theme"
+msgstr "Změnit heslo"
+
+msgid "Theme:"
+msgstr ""
+
+msgid "Update"
+msgstr "Aktualizovat"
+
+#, fuzzy
+msgid "Change your language"
+msgstr "Změnit heslo"
+
+msgid "Language:"
+msgstr ""
+
 msgid "Change your password"
 msgstr "Změnit heslo"
 
@@ -64,65 +147,68 @@ msgstr "Heslo"
 msgid "Repeat your new password:"
 msgstr "Znovu nové heslo:"
 
-msgid "Update"
-msgstr "Aktualizovat"
-
 msgid "Import"
 msgstr "Importovat"
 
-msgid "Please execute the import script locally, it can take a very long time."
+#, fuzzy
+msgid "Please execute the import script locally as it can take a very long time."
 msgstr "Spusťte importní skript lokálně, může to dlouho trvat."
 
-msgid "More info in the official doc:"
+#, fuzzy
+msgid "More info in the official documentation:"
 msgstr "Více informací v oficiální dokumentaci:"
 
-msgid "import from Pocket"
+#, fuzzy
+msgid "Import from Pocket"
 msgstr "importovat z Pocket"
 
-msgid "import from Readability"
+#, php-format
+msgid "(you must have a %s file on your server)"
+msgstr ""
+
+#, fuzzy
+msgid "Import from Readability"
 msgstr "importovat z Readability"
 
-msgid "import from Instapaper"
+#, fuzzy
+msgid "Import from Instapaper"
 msgstr "importovat z Instapaper"
 
-msgid "Export your poche data"
+#, fuzzy
+msgid "Import from wallabag"
+msgstr "importovat z Readability"
+
+#, fuzzy
+msgid "Export your wallabag data"
 msgstr "Export dat"
 
 msgid "Click here"
 msgstr "Klikněte zde"
 
-msgid "to export your poche data."
-msgstr "pro export vašich dat."
-
-msgid "back to home"
-msgstr "zpět na úvod"
+msgid "to download your database."
+msgstr ""
 
-msgid "installation"
-msgstr "instalace"
+#, fuzzy
+msgid "to export your wallabag data."
+msgstr "pro export vašich dat."
 
-msgid "install your poche"
-msgstr "instalovat"
+msgid "Cache"
+msgstr ""
 
-msgid ""
-"poche is still not installed. Please fill the below form to install it. "
-"Don't hesitate to <a href='http://doc.inthepoche.com'>read the documentation "
-"on poche website</a>."
+msgid "to delete cache."
 msgstr ""
-"poche ještě není nainstalováno. Pro instalaci vyplňte níže uvedený formulář. "
-"Nezapomeňte <a href='http://doc.inthepoche.com'>si přečíst dokumentaci</a> "
-"na stránkách programu."
 
-msgid "Login"
-msgstr "Jméno"
+msgid "You can enter multiple tags, separated by commas."
+msgstr ""
 
-msgid "Repeat your password"
-msgstr "Zopakujte heslo"
+msgid "return to article"
+msgstr ""
 
-msgid "Install"
-msgstr "Instalovat"
+msgid "plop"
+msgstr ""
 
-msgid "back to top"
-msgstr "zpět na začátek"
+msgid "You can <a href='wallabag_compatibility_test.php'>check your configuration here</a>."
+msgstr ""
 
 msgid "favoris"
 msgstr "oblíbené"
@@ -151,10 +237,14 @@ msgstr "podle nadpisu"
 msgid "by title desc"
 msgstr "podle nadpisu sestupně"
 
-msgid "No link available here!"
-msgstr "Není k dispozici žádný odkaz!"
+msgid "Tag"
+msgstr ""
 
-msgid "toggle mark as read"
+msgid "No articles found."
+msgstr ""
+
+#, fuzzy
+msgid "Toggle mark as read"
 msgstr "označit jako přečtené"
 
 msgid "toggle favorite"
@@ -166,13 +256,95 @@ msgstr "smazat"
 msgid "original"
 msgstr "originál"
 
+msgid "estimated reading time:"
+msgstr ""
+
+msgid "mark all the entries as read"
+msgstr ""
+
 msgid "results"
 msgstr "výsledky"
 
-msgid "tweet"
+msgid "installation"
+msgstr "instalace"
+
+#, fuzzy
+msgid "install your wallabag"
+msgstr "instalovat"
+
+#, fuzzy
+msgid "wallabag is still not installed. Please fill the below form to install it. Don't hesitate to <a href='http://doc.wallabag.org/'>read the documentation on wallabag website</a>."
+msgstr "poche ještě není nainstalováno. Pro instalaci vyplňte níže uvedený formulář. Nezapomeňte <a href='http://doc.inthepoche.com'>si přečíst dokumentaci</a> na stránkách programu."
+
+msgid "Login"
+msgstr "Jméno"
+
+msgid "Repeat your password"
+msgstr "Zopakujte heslo"
+
+msgid "Install"
+msgstr "Instalovat"
+
+#, fuzzy
+msgid "login to your wallabag"
+msgstr "přihlásit se k poche"
+
+msgid "Login to wallabag"
+msgstr ""
+
+msgid "you are in demo mode, some features may be disabled."
+msgstr "používáte ukázkový mód, některé funkce jsou zakázány."
+
+msgid "Username"
+msgstr ""
+
+msgid "Stay signed in"
+msgstr "Zůstat přihlášen(a)"
+
+msgid "(Do not check on public computers)"
+msgstr "(Nezaškrtávejte na veřejně dostupných počítačích)"
+
+msgid "Sign in"
+msgstr "Přihlásit se"
+
+msgid "favorites"
+msgstr "oblíbené"
+
+msgid "estimated reading time :"
+msgstr ""
+
+msgid "Mark all the entries as read"
+msgstr ""
+
+msgid "Return home"
+msgstr ""
+
+#, fuzzy
+msgid "Back to top"
+msgstr "zpět na začátek"
+
+#, fuzzy
+msgid "Mark as read"
+msgstr "označit jako přečtené"
+
+#, fuzzy
+msgid "Favorite"
+msgstr "oblíbené"
+
+#, fuzzy
+msgid "Toggle favorite"
+msgstr "označit jako oblíbené"
+
+#, fuzzy
+msgid "Delete"
+msgstr "smazat"
+
+#, fuzzy
+msgid "Tweet"
 msgstr "tweetnout"
 
-msgid "email"
+#, fuzzy
+msgid "Email"
 msgstr "email"
 
 msgid "shaarli"
@@ -181,26 +353,24 @@ msgstr "shaarli"
 msgid "flattr"
 msgstr "flattr"
 
-msgid "this article appears wrong?"
+#, fuzzy
+msgid "Does this article appear wrong?"
 msgstr "vypadá tento článek špatně?"
 
-msgid "create an issue"
-msgstr "odeslat požadavek"
-
-msgid "or"
-msgstr "nebo"
+msgid "tags:"
+msgstr ""
 
-msgid "contact us by mail"
-msgstr "kontaktovat e-mailem"
+msgid "Edit tags"
+msgstr ""
 
-msgid "plop"
+msgid "save link!"
 msgstr ""
 
 msgid "home"
 msgstr "domů"
 
-msgid "favorites"
-msgstr "oblíbené"
+msgid "tags"
+msgstr ""
 
 msgid "logout"
 msgstr "odhlásit se"
@@ -211,23 +381,187 @@ msgstr "běží na"
 msgid "debug mode is on so cache is off."
 msgstr "je zapnut ladicí mód, proto je keš vypnuta."
 
-msgid "your poche version:"
-msgstr "verze:"
+#, fuzzy
+msgid "your wallabag version:"
+msgstr "vaše verze"
 
 msgid "storage:"
 msgstr "úložiště:"
 
-msgid "login to your poche"
-msgstr "přihlásit se k poche"
+msgid "save a link"
+msgstr ""
 
-msgid "you are in demo mode, some features may be disabled."
-msgstr "používáte ukázkový mód, některé funkce jsou zakázány."
+msgid "back to home"
+msgstr "zpět na úvod"
 
-msgid "Stay signed in"
-msgstr "Zůstat přihlášen(a)"
+msgid "toggle mark as read"
+msgstr "označit jako přečtené"
 
-msgid "(Do not check on public computers)"
-msgstr "(Nezaškrtávejte na veřejně dostupných počítačích)"
+msgid "tweet"
+msgstr "tweetnout"
 
-msgid "Sign in"
-msgstr "Přihlásit se"
+msgid "email"
+msgstr "email"
+
+msgid "this article appears wrong?"
+msgstr "vypadá tento článek špatně?"
+
+msgid "No link available here!"
+msgstr "Není k dispozici žádný odkaz!"
+
+msgid "Poching a link"
+msgstr "Odkaz se ukládá"
+
+msgid "by filling this field"
+msgstr "vyplněním tohoto pole"
+
+msgid "bookmarklet: drag & drop this link to your bookmarks bar"
+msgstr ""
+
+msgid "your version"
+msgstr "vaše verze"
+
+msgid "latest stable version"
+msgstr "poslední stabilní verze"
+
+msgid "a more recent stable version is available."
+msgstr "je k dispozici novější stabilní verze."
+
+msgid "you are up to date."
+msgstr "je aktuální"
+
+msgid "latest dev version"
+msgstr "poslední vývojová verze"
+
+msgid "a more recent development version is available."
+msgstr "je k dispozici novější vývojová verze."
+
+msgid "Please execute the import script locally, it can take a very long time."
+msgstr "Spusťte importní skript lokálně, může to dlouho trvat."
+
+#, fuzzy
+msgid "More infos in the official doc:"
+msgstr "Více informací v oficiální dokumentaci:"
+
+msgid "import from Pocket"
+msgstr "importovat z Pocket"
+
+msgid "import from Readability"
+msgstr "importovat z Readability"
+
+msgid "import from Instapaper"
+msgstr "importovat z Instapaper"
+
+msgid "Tags"
+msgstr ""
+
+#, fuzzy
+msgid "Untitled"
+msgstr "podle nadpisu"
+
+msgid "the link has been added successfully"
+msgstr ""
+
+msgid "error during insertion : the link wasn't added"
+msgstr ""
+
+msgid "the link has been deleted successfully"
+msgstr ""
+
+msgid "the link wasn't deleted"
+msgstr ""
+
+msgid "Article not found!"
+msgstr ""
+
+msgid "previous"
+msgstr ""
+
+msgid "next"
+msgstr ""
+
+msgid "in demo mode, you can't update your password"
+msgstr ""
+
+msgid "your password has been updated"
+msgstr ""
+
+msgid "the two fields have to be filled & the password must be the same in the two fields"
+msgstr ""
+
+msgid "still using the \""
+msgstr ""
+
+msgid "that theme does not seem to be installed"
+msgstr ""
+
+msgid "you have changed your theme preferences"
+msgstr ""
+
+msgid "that language does not seem to be installed"
+msgstr ""
+
+msgid "you have changed your language preferences"
+msgstr ""
+
+msgid "login failed: you have to fill all fields"
+msgstr ""
+
+msgid "welcome to your wallabag"
+msgstr ""
+
+msgid "login failed: bad login or password"
+msgstr ""
+
+#, fuzzy
+msgid "import from instapaper completed"
+msgstr "importovat z Instapaper"
+
+#, fuzzy
+msgid "import from pocket completed"
+msgstr "importovat z Pocket"
+
+#, fuzzy
+msgid "import from Readability completed. "
+msgstr "importovat z Readability"
+
+#, fuzzy
+msgid "import from Poche completed. "
+msgstr "importovat z Pocket"
+
+msgid "Unknown import provider."
+msgstr ""
+
+msgid "Incomplete inc/poche/define.inc.php file, please define \""
+msgstr ""
+
+msgid "Could not find required \""
+msgstr ""
+
+msgid "Uh, there is a problem while generating feeds."
+msgstr ""
+
+#, fuzzy
+msgid "Cache deleted."
+msgstr "smazat"
+
+msgid "Oops, it seems you don't have PHP 5."
+msgstr ""
+
+#~ msgid "poche it!"
+#~ msgstr "uložit!"
+
+#~ msgid "Updating poche"
+#~ msgstr "Poche se aktualizuje"
+
+#~ msgid "create an issue"
+#~ msgstr "odeslat požadavek"
+
+#~ msgid "or"
+#~ msgstr "nebo"
+
+#~ msgid "contact us by mail"
+#~ msgstr "kontaktovat e-mailem"
+
+#~ msgid "your poche version:"
+#~ msgstr "verze:"
index 375e923f98912ccd7228ea06fc5ae27c965fa13d..bd18817fbc80bb572c1e7e0808680b94eaac6af7 100644 (file)
Binary files a/locale/de_DE.utf8/LC_MESSAGES/de_DE.utf8.mo and b/locale/de_DE.utf8/LC_MESSAGES/de_DE.utf8.mo differ
index 5b30d3d711431c6953821f264aa062493f4ea7f0..8b82721d95da7f530bdb342dd2a30e53dba109e2 100644 (file)
 msgid ""
 msgstr ""
-"Project-Id-Version: \n"
-"POT-Creation-Date: \n"
+"Project-Id-Version: Wallabag\n"
+"Report-Msgid-Bugs-To: \n"
+"POT-Creation-Date: 2014-03-27 13:41+0100\n"
 "PO-Revision-Date: \n"
-"Last-Translator: Square252\n"
+"Last-Translator: Kevin Meyer <wallabag@kevin-meyer.de>\n"
 "Language-Team: \n"
+"Language: de\n"
 "MIME-Version: 1.0\n"
 "Content-Type: text/plain; charset=UTF-8\n"
 "Content-Transfer-Encoding: 8bit\n"
-"X-Generator: Poedit 1.5.7\n"
+"X-Generator: Poedit 1.6.4\n"
+"X-Poedit-Basepath: .\n"
+"X-Poedit-SearchPath-0: /Users/kevinmeyer/Dropbox/dev_web/wallabag-dev\n"
 
 msgid "config"
 msgstr "Konfiguration"
 
-msgid "Poching a link"
-msgstr "Poche einen Link"
+msgid "Saving articles"
+msgstr "Artikel speichern"
+
+msgid "There are several ways to save an article:"
+msgstr "Es gibt viele Methoden um Artikel zu speichern:"
 
 msgid "read the documentation"
 msgstr "Die Dokumentation lesen"
 
-msgid "by filling this field"
-msgstr "durch das ausfüllen dieses Feldes:"
+msgid "download the extension"
+msgstr "installiere die Erweiterung"
+
+msgid "via F-Droid"
+msgstr "via F-Droid"
+
+msgid " or "
+msgstr " oder "
+
+msgid "via Google Play"
+msgstr "via Google Play"
+
+msgid "download the application"
+msgstr "lade die App"
+
+msgid "By filling this field"
+msgstr "Durch Ausfüllen dieses Feldes"
 
-msgid "poche it!"
-msgstr "Poche es!"
+msgid "bag it!"
+msgstr "bag it!"
 
-msgid "Updating poche"
-msgstr "Poche aktualisieren"
+msgid "Bookmarklet: drag & drop this link to your bookmarks bar"
+msgstr "Bookmarklet: Ziehe diesen Link in deine Lesezeichen-Leiste"
 
-msgid "your version"
-msgstr "Deine Version"
+msgid "Upgrading wallabag"
+msgstr "wallabag aktualisieren"
 
-msgid "latest stable version"
+msgid "Installed version"
+msgstr "Installierte Version"
+
+msgid "Latest stable version"
 msgstr "Neuste stabile Version"
 
-msgid "a more recent stable version is available."
+msgid "A more recent stable version is available."
 msgstr "Eine neuere stabile Version ist verfügbar."
 
-msgid "you are up to date."
+msgid "You are up to date."
 msgstr "Du bist auf den neuesten Stand."
 
-msgid "latest dev version"
+msgid "Last check:"
+msgstr "Zuletzt geprüft:"
+
+msgid "Latest dev version"
 msgstr "Neuste Entwicklungsversion"
 
-msgid "a more recent development version is available."
+msgid "A more recent development version is available."
 msgstr "Eine neuere Entwicklungsversion ist verfügbar."
 
+msgid "You can clear cache to check the latest release."
+msgstr "Leere den Cache um die neueste Version zu prüfen."
+
+msgid "Feeds"
+msgstr "Feeds"
+
+msgid ""
+"Your feed token is currently empty and must first be generated to enable "
+"feeds. Click <a href='?feed&amp;action=generate'>here to generate it</a>."
+msgstr ""
+"Dein Feed Token ist noch nicht vorhanden und muss zunächst generiert werden, "
+"um deine Feeds zu aktivieren. Klicke <a href='?feed&amp;"
+"action=generate'>hier um ihn zu generieren</a>."
+
+msgid "Unread feed"
+msgstr "Ungelesen Feed"
+
+msgid "Favorites feed"
+msgstr "Favoriten Feed"
+
+msgid "Archive feed"
+msgstr "Archiv Feed"
+
+msgid "Your token:"
+msgstr "Dein Token:"
+
+msgid "Your user id:"
+msgstr "Deine User ID:"
+
+msgid ""
+"You can regenerate your token: <a href='?feed&amp;action=generate'>generate!"
+"</a>."
+msgstr ""
+"Hier kannst du dein Token erzeugen: <a href='?feed&amp;"
+"action=generate'>Generieren!</a>."
+
+msgid "Change your theme"
+msgstr "Theme ändern"
+
+msgid "Theme:"
+msgstr "Theme:"
+
+msgid "Update"
+msgstr "Aktualisieren"
+
+msgid "Change your language"
+msgstr "Sprache ändern"
+
+msgid "Language:"
+msgstr "Sprache:"
+
 msgid "Change your password"
 msgstr "Passwort ändern"
 
@@ -58,75 +137,86 @@ msgstr "Passwort"
 msgid "Repeat your new password:"
 msgstr "Neues Passwort wiederholen:"
 
-msgid "Update"
-msgstr "Aktualisieren"
-
 msgid "Import"
 msgstr "Import"
 
-msgid "Please execute the import script locally, it can take a very long time."
-msgstr "Bitte führe das Import Script lokal aus, dies kann eine Weile dauern."
+msgid ""
+"Importing from other services can be quite long, and webservers default "
+"configuration often prevents long scripts execution time, so it must be done "
+"in multiple parts."
+msgstr ""
+"Der Import von anderen Diensten kann sehr lange dauern. Deswegen bricht der "
+"Webserver diesen in vielen Konfigurationen ab. Daher muss der Import in "
+"mehrere Teile aufgeteilt werden."
+
+msgid "First, select the export file on your computer and upload it."
+msgstr "Wähle eine Datei von deinem Computer aus und lade sie hoch."
+
+msgid "File:"
+msgstr "Datei:"
+
+msgid "Upload"
+msgstr "Hochladen"
 
-msgid "More info in the official doc:"
-msgstr "Mehr Informationen in der offiziellen Dokumentation:"
+msgid "Then, click on the right link below."
+msgstr "Klicke dann unten auf den entsprechenden Link."
 
-msgid "import from Pocket"
+msgid "Import from Pocket"
 msgstr "Import aus Pocket"
 
-msgid "import from Readability"
+#, php-format
+msgid "(after uploaded %s file)"
+msgstr "(nach Upload der Datei %s)"
+
+msgid "Import from Readability"
 msgstr "Import aus Readability"
 
-msgid "import from Instapaper"
+msgid "Import from Instapaper"
 msgstr "Import aus Instapaper"
 
-msgid "Export your poche data"
-msgstr "Exportieren Sie Ihre Poche Daten."
-
-msgid "Click here"
-msgstr "Klicke hier"
+msgid "Import from wallabag"
+msgstr "Import aus Readability"
 
-msgid "to export your poche data."
-msgstr "um deine Daten aus Poche zu exportieren."
+msgid ""
+"3. Your feed token is currently empty and must first be generated to fetch "
+"content. Click <a href='?feed&amp;action=generate'>here to generate it</a>."
+msgstr ""
+"3. Dein Feed Token ist noch nicht vorhanden und muss zunächst generiert "
+"werden, um Inhalt abrufen zu können. Klicke <a href='?feed&amp;"
+"action=generate'>hier um ihn zu generieren</a>."
 
-msgid "back to home"
-msgstr "züruck zur Hauptseite"
+msgid "Finally, you have to fetch content for imported items."
+msgstr "Jetzt musst du den Inhalt der importierten Artikel abrufen."
 
-msgid "installation"
-msgstr "Installieren"
+msgid "Click here"
+msgstr "Klicke hier"
 
-msgid "install your poche"
-msgstr "Installiere dein Poche"
+msgid "to fetch content for 10 articles"
+msgstr "um den Inhalt von 10 Artikeln abzurufen"
 
 msgid ""
-"poche is still not installed. Please fill the below form to install it. "
-"Don't hesitate to <a href='http://doc.inthepoche.com'>read the documentation "
-"on poche website</a>."
+"If you have console access to your server, you can also create a cron task:"
 msgstr ""
-"Poche ist noch nicht installiert. Bitte fülle die Felder unten aus, um die "
-"Installation durchzuführen. Zögere nicht, <a href='http://inthepoche.com/"
-"doc'>die Dokumentation auf der Website von Poche zu lesen falls du Probleme "
-"haben solltest."
+"Wenn du Konsolenzugang zu deinem Server hast kannst du auch einen cron "
+"erstellen:"
 
-msgid "Login"
-msgstr "Benutzername"
+msgid "Export your wallabag data"
+msgstr "Exportieren deine wallabag Daten"
 
-msgid "Repeat your password"
-msgstr "Wiederhole dein Passwort"
+msgid "to download your database."
+msgstr "um deine Datenbank herunterzuladen"
 
-msgid "Install"
-msgstr "Installieren"
+msgid "to export your wallabag data."
+msgstr "um deine Daten aus wallabag zu exportieren."
 
-msgid "back to top"
-msgstr "Nach Oben"
+msgid "Cache"
+msgstr "Cache"
 
-msgid "favoris"
-msgstr ""
-
-msgid "archive"
-msgstr "Archiv"
+msgid "to delete cache."
+msgstr "um den Cache zu löschen."
 
-msgid "unread"
-msgstr "ungelesen"
+msgid "Tags"
+msgstr "Tags"
 
 msgid "by date asc"
 msgstr "nach Datum aufsteigend"
@@ -146,10 +236,72 @@ msgstr "nach Titel"
 msgid "by title desc"
 msgstr "nach Titel absteigend"
 
-msgid "No link available here!"
-msgstr "Kein Link verfügbar!"
+#, fuzzy
+msgid "toggle view mode"
+msgstr "Favorit"
+
+msgid "home"
+msgstr "Start"
+
+msgid "favorites"
+msgstr "Favoriten"
+
+msgid "archive"
+msgstr "Archiv"
+
+msgid "tags"
+msgstr "Tags"
+
+msgid "save a link"
+msgstr "Speichere einen Link"
+
+msgid "search"
+msgstr "Suche"
+
+msgid "logout"
+msgstr "Logout"
+
+msgid "return home"
+msgstr "Zurück zum Start"
+
+#, fuzzy
+msgid "Search"
+msgstr "Archiv"
+
+msgid "powered by"
+msgstr "bereitgestellt von"
+
+msgid "debug mode is on so cache is off."
+msgstr "Debug Modus ist aktiviert, das Caching ist somit deaktiviert"
+
+msgid "your wallabag version:"
+msgstr "Deine wallabag Version"
+
+msgid "storage:"
+msgstr "Speicher:"
+
+msgid "Save a link"
+msgstr "Speichere einen Link"
+
+msgid "save link!"
+msgstr "Link speichern!"
+
+msgid "unread"
+msgstr "ungelesen"
+
+msgid "Tag"
+msgstr "Tag"
+
+msgid "No articles found."
+msgstr "Keine Artikel gefunden."
 
-msgid "toggle mark as read"
+msgid "estimated reading time:"
+msgstr "geschätzte Lesezeit:"
+
+msgid "estimated reading time :"
+msgstr "geschätzte Lesezeit:"
+
+msgid "Toggle mark as read"
 msgstr "Als gelesen markieren"
 
 msgid "toggle favorite"
@@ -161,69 +313,346 @@ msgstr "Löschen"
 msgid "original"
 msgstr "Original"
 
+msgid "Mark all the entries as read"
+msgstr "Markiere alle als gelesen"
+
 msgid "results"
 msgstr "Ergebnisse"
 
-msgid "tweet"
-msgstr "Twittern"
+msgid "Uh, there is a problem with the cron."
+msgstr "Oh, es gab ein Problem mit dem cron."
 
-msgid "email"
-msgstr "senden per E-Mail"
+msgid "Untitled"
+msgstr "Ohne Titel"
 
-msgid "shaarli"
-msgstr "Shaarli"
+msgid "the link has been added successfully"
+msgstr "Speichern des Links erfolgreich"
 
-msgid "flattr"
-msgstr "flattr"
+msgid "error during insertion : the link wasn't added"
+msgstr "Fehler beim Einfügen: Der Link wurde nicht hinzugefügt"
 
-msgid "this article appears wrong?"
-msgstr "dieser Artikel erscheint falsch?"
+msgid "the link has been deleted successfully"
+msgstr "Löschen des Links erfolgreich"
 
-msgid "create an issue"
-msgstr "ein Ticket erstellen"
+msgid "the link wasn't deleted"
+msgstr "Der Link wurde nicht entfernt"
 
-msgid "or"
-msgstr "oder"
+msgid "Article not found!"
+msgstr "Artikel nicht gefunden!"
 
-msgid "contact us by mail"
-msgstr "kontaktieren Sie uns per E-Mail"
+msgid "previous"
+msgstr "vorherige"
 
-msgid "plop"
-msgstr "plop"
+msgid "next"
+msgstr "nächste"
 
-msgid "home"
-msgstr "Start"
+msgid "in demo mode, you can't update your password"
+msgstr "im Demo-Modus kann das Passwort nicht geändert werden"
 
-msgid "favorites"
-msgstr "Favoriten"
+msgid "your password has been updated"
+msgstr "Dein Passwort wurde geändert"
 
-msgid "logout"
-msgstr "Logout"
+msgid ""
+"the two fields have to be filled & the password must be the same in the two "
+"fields"
+msgstr "Beide Felder müssen mit selbem Inhalt ausgefüllt sein"
 
-msgid "powered by"
-msgstr "bereitgestellt von"
+msgid "still using the \""
+msgstr "nutze immernoch die \""
 
-msgid "debug mode is on so cache is off."
-msgstr "Debug Modus ist aktiviert, das Caching ist somit deaktiviert"
+msgid "that theme does not seem to be installed"
+msgstr "dieses Theme scheint nicht installiert zu sein"
 
-msgid "your poche version:"
-msgstr "Deine Poche Version"
+msgid "you have changed your theme preferences"
+msgstr "Du hast deine Theme Einstellungen geändert"
 
-msgid "storage:"
-msgstr "Speicher:"
+msgid "that language does not seem to be installed"
+msgstr "Diese Sprache scheint nicht installiert zu sein"
+
+msgid "you have changed your language preferences"
+msgstr "Du hast deine Spracheinstellungen geändert"
+
+msgid "login failed: you have to fill all fields"
+msgstr "Anmeldung fehlgeschlagen: Alle Felder müssen ausgefüllt werden"
+
+msgid "welcome to your wallabag"
+msgstr "Willkommen bei deiner wallabag"
+
+msgid "login failed: bad login or password"
+msgstr "Anmeldung fehlgeschlagen: Falscher Benutzername oder Passwort"
+
+msgid ""
+"import from instapaper completed. You have to execute the cron to fetch "
+"content."
+msgstr ""
+"Import aus Instapaper vollständig. Führe den cronjob aus um den Inhalt "
+"abzurufen."
+
+msgid ""
+"import from pocket completed. You have to execute the cron to fetch content."
+msgstr ""
+"Import aus Pocket vollständig. Führe den cronjob aus um den Inhalt abzurufen."
 
-msgid "login to your poche"
-msgstr "Bei Poche anmelden"
+msgid ""
+"import from Readability completed. You have to execute the cron to fetch "
+"content."
+msgstr ""
+"Import aus Readability vollständig. Führe den cronjob aus um den Inhalt "
+"abzurufen."
 
-msgid "you are in demo mode, some features may be disabled."
+msgid ""
+"import from Poche completed. You have to execute the cron to fetch content."
 msgstr ""
-"Du befindest dich im Demomodus, einige Funktionen könnten deaktiviert sein."
+"Import aus Poche vollständig. Führe den cronjob aus um den Inhalt abzurufen."
+
+msgid "Unknown import provider."
+msgstr "Unbekannter Import Anbieter."
+
+msgid "Could not find required \""
+msgstr "Nicht gefunden: \""
+
+msgid "File uploaded. You can now execute import."
+msgstr "Datei hochgeladen. Du kannst nun importieren."
+
+msgid "Error while importing file. Do you have access to upload it?"
+msgstr "Fehler beim Importieren. Hast du das Recht zum Hochladen?"
+
+msgid "User with this id ("
+msgstr "Nutzer mit dieser id ("
+
+msgid "Uh, there is a problem while generating feeds."
+msgstr "Oh, es gab ein Problem beim Erstellen des Feeds."
+
+msgid "Cache deleted."
+msgstr "Cache gelöscht"
+
+msgid "Oops, it seems you don't have PHP 5."
+msgstr "Oops, es scheint als würde PHP 5 fehlen."
+
+msgid "wallabag, a read it later open source system"
+msgstr "wallabag, ein Später-Lesen Open Source System"
+
+msgid "login failed: user doesn't exist"
+msgstr "Anmeldung fehlgeschlagen: Benutzer existiert nicht"
+
+#~ msgid "You can enter multiple tags, separated by commas."
+#~ msgstr "Du kannst mehrere Tags, durch Kommata getrennt, eingeben."
+
+#~ msgid "return to article"
+#~ msgstr "zurück zum Artikel"
+
+#, fuzzy
+#~ msgid "favoris"
+#~ msgstr "Favoriten"
+
+#~ msgid "mark all the entries as read"
+#~ msgstr "Markiere alle als gelesen"
+
+#~ msgid "Back to top"
+#~ msgstr "Nach Oben"
+
+#~ msgid "Mark as read"
+#~ msgstr "Als gelesen markieren"
+
+#~ msgid "Favorite"
+#~ msgstr "Favoriten"
+
+#~ msgid "Toggle favorite"
+#~ msgstr "Favorit"
+
+#~ msgid "Delete"
+#~ msgstr "Löschen"
+
+#~ msgid "Tweet"
+#~ msgstr "Twittern"
+
+#~ msgid "Email"
+#~ msgstr "per E-Mail senden"
+
+#~ msgid "shaarli"
+#~ msgstr "Shaarli"
+
+#~ msgid "flattr"
+#~ msgstr "flattr"
+
+#~ msgid "Does this article appear wrong?"
+#~ msgstr "Erscheint dieser Artikel falsch?"
+
+#~ msgid "Edit tags"
+#~ msgstr "Tags bearbeiten"
+
+#~ msgid "Start typing for auto complete."
+#~ msgstr "Beginne zu tippen für die Autovervollständigung."
+
+#~ msgid "Return home"
+#~ msgstr "Zurück zum Start"
+
+#~ msgid "tags:"
+#~ msgstr "Tags:"
+
+#~ msgid "login to your wallabag"
+#~ msgstr "Bei wallabag anmelden"
+
+#~ msgid "you are in demo mode, some features may be disabled."
+#~ msgstr ""
+#~ "Du befindest dich im Demomodus, einige Funktionen könnten deaktiviert "
+#~ "sein."
+
+#~ msgid "Login"
+#~ msgstr "Benutzername"
+
+#~ msgid "Stay signed in"
+#~ msgstr "Angemeldet bleiben"
+
+#~ msgid "(Do not check on public computers)"
+#~ msgstr "(nicht auf einem öffentlichen Computer anhaken)"
+
+#~ msgid "plop"
+#~ msgstr "plop"
+
+#~ msgid "Login to wallabag"
+#~ msgstr "Bei wallabag anmelden"
+
+#~ msgid "Username"
+#~ msgstr "Benutzername"
+
+#~ msgid "Sign in"
+#~ msgstr "Einloggen"
+
+#~ msgid "Enter your search here"
+#~ msgstr "Gib hier deine Suchanfrage ein"
+
+#~ msgid "installation"
+#~ msgstr "Installieren"
+
+#~ msgid "install your wallabag"
+#~ msgstr "Installiere deine wallabag"
+
+#~ msgid ""
+#~ "wallabag is still not installed. Please fill the below form to install "
+#~ "it. Don't hesitate to <a href='http://doc.wallabag.org/'>read the "
+#~ "documentation on wallabag website</a>."
+#~ msgstr ""
+#~ "wallabag ist noch nicht installiert. Bitte fülle die Felder unten aus, um "
+#~ "die Installation durchzuführen. Zögere nicht, <a href='http://doc."
+#~ "wallabag.org/'>die Dokumentation auf der Website von wallabag zu lesen, "
+#~ "falls du Probleme haben solltest."
+
+#~ msgid "Repeat your password"
+#~ msgstr "Wiederhole dein Passwort"
+
+#~ msgid "Install"
+#~ msgstr "Installieren"
+
+#~ msgid "No link available here!"
+#~ msgstr "Kein Link verfügbar!"
+
+#~ msgid "toggle mark as read"
+#~ msgstr "Als gelesen markieren"
+
+#~ msgid ""
+#~ "You can <a href='wallabag_compatibility_test.php'>check your "
+#~ "configuration here</a>."
+#~ msgstr ""
+#~ "Du kannst deine Konfiguration <a href='wallabag_compatibility_test."
+#~ "php'>hier testen</a>."
+
+#~ msgid "back to home"
+#~ msgstr "züruck zur Hauptseite"
+
+#~ msgid "tweet"
+#~ msgstr "Twittern"
+
+#~ msgid "email"
+#~ msgstr "senden per E-Mail"
+
+#~ msgid "this article appears wrong?"
+#~ msgstr "dieser Artikel erscheint falsch?"
+
+#~ msgid "Poching a link"
+#~ msgstr "Poche einen Link"
+
+#~ msgid "by filling this field"
+#~ msgstr "durch das ausfüllen dieses Feldes:"
+
+#~ msgid "bookmarklet: drag & drop this link to your bookmarks bar"
+#~ msgstr "Bookmarklet: Ziehe diesen Link in deine Lesezeichen-Leiste"
+
+#~ msgid "your version"
+#~ msgstr "Deine Version"
+
+#~ msgid "latest stable version"
+#~ msgstr "Neuste stabile Version"
+
+#~ msgid "a more recent stable version is available."
+#~ msgstr "Eine neuere stabile Version ist verfügbar."
+
+#~ msgid "you are up to date."
+#~ msgstr "Du bist auf den neuesten Stand."
+
+#~ msgid "latest dev version"
+#~ msgstr "Neuste Entwicklungsversion"
+
+#~ msgid "a more recent development version is available."
+#~ msgstr "Eine neuere Entwicklungsversion ist verfügbar."
+
+#~ msgid ""
+#~ "Please execute the import script locally, it can take a very long time."
+#~ msgstr ""
+#~ "Bitte führe das Import Script lokal aus, dies kann eine Weile dauern."
+
+#~ msgid "More infos in the official doc:"
+#~ msgstr "Mehr Informationen in der offiziellen Dokumentation:"
+
+#~ msgid "import from Pocket"
+#~ msgstr "Import aus Pocket"
+
+#~ msgid "(you must have a %s file on your server)"
+#~ msgstr "(du brauchst eine %s Datei auf deinem Server)"
+
+#~ msgid "import from Readability"
+#~ msgstr "Import aus Readability"
+
+#~ msgid "import from Instapaper"
+#~ msgstr "Import aus Instapaper"
+
+#~ msgid "You can also create a cron task:"
+#~ msgstr "Du kannst auch einen cronjob anlegen:"
+
+#~ msgid ""
+#~ "Please execute the import script locally as it can take a very long time."
+#~ msgstr ""
+#~ "Bitte führe das Import Script lokal aus, da dies eine Weile dauern kann."
+
+#~ msgid "More info in the official documentation:"
+#~ msgstr "Mehr Informationen in der offiziellen Dokumentation:"
+
+#~ msgid "import from instapaper completed"
+#~ msgstr "Import aus Instapaper erfolgreich"
+
+#~ msgid "import from pocket completed"
+#~ msgstr "Import aus Pocket erfolgreich"
+
+#~ msgid "import from Poche completed. "
+#~ msgstr "Import aus Poche erfolgreich"
+
+#~ msgid "Incomplete inc/poche/define.inc.php file, please define \""
+#~ msgstr "Unvollständige inc/poche/define.inc.php Datei, bitte setze \""
+
+#~ msgid "poche it!"
+#~ msgstr "Poche es!"
+
+#~ msgid "Updating poche"
+#~ msgstr "Poche aktualisieren"
+
+#~ msgid "create an issue"
+#~ msgstr "ein Ticket erstellen"
 
-msgid "Stay signed in"
-msgstr "Angemeldet bleiben"
+#~ msgid "or"
+#~ msgstr "oder"
 
-msgid "(Do not check on public computers)"
-msgstr "(nicht auf einem öffentlichen Computer anhaken)"
+#~ msgid "contact us by mail"
+#~ msgstr "kontaktieren Sie uns per E-Mail"
 
-msgid "Sign in"
-msgstr "Einloggen"
+#~ msgid "your poche version:"
+#~ msgstr "Deine Poche Version"
index 83d0a85f208ebc0fb5c619bd740a2fdda7d7d531..bf5f69e7286a149f8f2646d2fba934698e3d5ce3 100644 (file)
Binary files a/locale/en_EN.utf8/LC_MESSAGES/en_EN.utf8.mo and b/locale/en_EN.utf8/LC_MESSAGES/en_EN.utf8.mo differ
index b78759f53fa31678576f6a2cae9eeddfe88a1d54..119fb0601819b1ebfc93521760eee9f1ab73cab6 100644 (file)
 msgid ""
 msgstr ""
 "Project-Id-Version: \n"
-"POT-Creation-Date: \n"
+"Report-Msgid-Bugs-To: \n"
+"POT-Creation-Date: 2014-02-25 15:17+0300\n"
 "PO-Revision-Date: \n"
-"Last-Translator: Nicolas Lœuillet <nicolas.loeuillet@gmail.com>\n"
+"Last-Translator: Maryana <mariroz@mr.lviv.ua>\n"
 "Language-Team: \n"
+"Language: \n"
 "MIME-Version: 1.0\n"
 "Content-Type: text/plain; charset=UTF-8\n"
 "Content-Transfer-Encoding: 8bit\n"
 "X-Generator: Poedit 1.5.4\n"
+"X-Poedit-Language: English\n"
+"X-Poedit-Basepath: .\n"
+"X-Poedit-SearchPath-0: /home/mariroz/_DEV/web/wallabag/wallabag-master-testing\n"
+
+msgid "wallabag, a read it later open source system"
+msgstr "wallabag, a read it later open source system"
+
+msgid "login failed: user doesn't exist"
+msgstr "login failed: user doesn't exist"
+
+msgid "return home"
+msgstr "return home"
 
 msgid "config"
 msgstr "config"
 
-msgid "Poching a link"
-msgstr "Poching a link"
+msgid "Saving articles"
+msgstr "Saving articles"
+
+msgid "There are several ways to save an article:"
+msgstr "There are several ways to save an article:"
 
 msgid "read the documentation"
 msgstr "read the documentation"
 
-msgid "by filling this field"
-msgstr "by filling this field"
+msgid "download the extension"
+msgstr "download the extension"
 
-msgid "poche it!"
-msgstr "poche it!"
+msgid "via F-Droid"
+msgstr "via F-Droid"
 
-msgid "Updating poche"
-msgstr "Updating poche"
+msgid " or "
+msgstr " or "
 
-msgid "your version"
-msgstr "your version"
+msgid "via Google Play"
+msgstr "via Google Play"
 
-msgid "latest stable version"
-msgstr "latest stable version"
+msgid "download the application"
+msgstr "download the application"
 
-msgid "a more recent stable version is available."
-msgstr "a more recent stable version is available."
+msgid "By filling this field"
+msgstr "By filling this field"
 
-msgid "you are up to date."
-msgstr "you are up to date."
+msgid "bag it!"
+msgstr "bag it!"
 
-msgid "latest dev version"
-msgstr "latest dev version"
+msgid "Bookmarklet: drag & drop this link to your bookmarks bar"
+msgstr "Bookmarklet: drag & drop this link to your bookmarks bar"
 
-msgid "a more recent development version is available."
-msgstr "a more recent development version is available."
+msgid "Upgrading wallabag"
+msgstr "Upgrading wallabag"
+
+msgid "Installed version"
+msgstr "Installed version"
+
+msgid "Latest stable version"
+msgstr "Latest stable version"
+
+msgid "A more recent stable version is available."
+msgstr "A more recent stable version is available."
+
+msgid "You are up to date."
+msgstr "You are up to date."
+
+msgid "Latest dev version"
+msgstr "Latest dev version"
+
+msgid "A more recent development version is available."
+msgstr "A more recent development version is available."
+
+msgid "Feeds"
+msgstr "Feeds"
+
+msgid "Your feed token is currently empty and must first be generated to enable feeds. Click <a href='?feed&amp;action=generate'>here to generate it</a>."
+msgstr "Your feed token is currently empty and must first be generated to enable feeds. Click <a href='?feed&amp;action=generate'>here to generate it</a>."
+
+msgid "Unread feed"
+msgstr "Unread feed"
+
+msgid "Favorites feed"
+msgstr "Favorites feed"
+
+msgid "Archive feed"
+msgstr "Archive feed"
+
+msgid "Your token:"
+msgstr "Your token:"
+
+msgid "Your user id:"
+msgstr "Your user id:"
+
+msgid "You can regenerate your token: <a href='?feed&amp;action=generate'>generate!</a>."
+msgstr "You can regenerate your token: <a href='?feed&amp;action=generate'>generate!</a>."
+
+msgid "Change your theme"
+msgstr "Change your theme"
+
+msgid "Theme:"
+msgstr "Theme:"
+
+msgid "Update"
+msgstr "Update"
+
+msgid "Change your language"
+msgstr "Change your language"
+
+msgid "Language:"
+msgstr "Language:"
 
 msgid "Change your password"
 msgstr "Change your password"
@@ -58,66 +132,60 @@ msgstr "Password"
 msgid "Repeat your new password:"
 msgstr "Repeat your new password:"
 
-msgid "Update"
-msgstr "Update"
-
 msgid "Import"
 msgstr "Import"
 
-msgid "Please execute the import script locally, it can take a very long time."
-msgstr ""
-"Please execute the import script locally, it can take a very long time."
+msgid "Please execute the import script locally as it can take a very long time."
+msgstr "Please execute the import script locally as it can take a very long time."
 
-msgid "More info in the official doc:"
-msgstr "More info in the official doc:"
+msgid "More info in the official documentation:"
+msgstr "More info in the official documentation:"
 
-msgid "import from Pocket"
-msgstr "import from Pocket"
+msgid "Import from Pocket"
+msgstr "Import from Pocket"
 
-msgid "import from Readability"
-msgstr "import from Readability"
+#, php-format
+msgid "(you must have a %s file on your server)"
+msgstr "(you must have a %s file on your server)"
 
-msgid "import from Instapaper"
-msgstr "import from Instapaper"
+msgid "Import from Readability"
+msgstr "Import from Readability"
+
+msgid "Import from Instapaper"
+msgstr "Import from Instapaper"
 
-msgid "Export your poche data"
-msgstr "Export your poche data"
+msgid "Import from wallabag"
+msgstr "Import from wallabag"
+
+msgid "Export your wallabag data"
+msgstr "Export your wallabag data"
 
 msgid "Click here"
 msgstr "Click here"
 
-msgid "to export your poche data."
-msgstr "to export your poche data."
+msgid "to download your database."
+msgstr "to download your database."
 
-msgid "back to home"
-msgstr "back to home"
+msgid "to export your wallabag data."
+msgstr "to export your wallabag data."
 
-msgid "installation"
-msgstr "installation"
+msgid "Cache"
+msgstr "Cache"
 
-msgid "install your poche"
-msgstr "install your poche"
+msgid "to delete cache."
+msgstr "to delete cache."
 
-msgid ""
-"poche is still not installed. Please fill the below form to install it. "
-"Don't hesitate to <a href='http://doc.inthepoche.com'>read the documentation "
-"on poche website</a>."
-msgstr ""
-"poche is still not installed. Please fill the below form to install it. "
-"Don't hesitate to <a href='http://doc.inthepoche.com'>read the documentation "
-"on poche website</a>."
-
-msgid "Login"
-msgstr "Login"
+msgid "You can enter multiple tags, separated by commas."
+msgstr "You can enter multiple tags, separated by commas."
 
-msgid "Repeat your password"
-msgstr "Repeat your password"
+msgid "return to article"
+msgstr "return to article"
 
-msgid "Install"
-msgstr "Install"
+msgid "plop"
+msgstr "plop"
 
-msgid "back to top"
-msgstr "back to top"
+msgid "You can <a href='wallabag_compatibility_test.php'>check your configuration here</a>."
+msgstr "You can <a href='wallabag_compatibility_test.php'>check your configuration here</a>."
 
 msgid "favoris"
 msgstr "favoris"
@@ -146,11 +214,14 @@ msgstr "by title"
 msgid "by title desc"
 msgstr "by title desc"
 
-msgid "No link available here!"
-msgstr "No link available here!"
+msgid "Tag"
+msgstr "Tag"
 
-msgid "toggle mark as read"
-msgstr "toggle mark as read"
+msgid "No articles found."
+msgstr "No articles found."
+
+msgid "Toggle mark as read"
+msgstr "Toggle mark as read"
 
 msgid "toggle favorite"
 msgstr "toggle favorite"
@@ -161,14 +232,86 @@ msgstr "delete"
 msgid "original"
 msgstr "original"
 
+msgid "estimated reading time:"
+msgstr "estimated reading time:"
+
+msgid "mark all the entries as read"
+msgstr "mark all the entries as read"
+
 msgid "results"
 msgstr "results"
 
-msgid "tweet"
-msgstr "tweet"
+msgid "installation"
+msgstr "installation"
 
-msgid "email"
-msgstr "email"
+msgid "install your wallabag"
+msgstr "install your wallabag"
+
+msgid "wallabag is still not installed. Please fill the below form to install it. Don't hesitate to <a href='http://doc.wallabag.org/'>read the documentation on wallabag website</a>."
+msgstr "wallabag is still not installed. Please fill the below form to install it. Don't hesitate to <a href='http://doc.wallabag.org/'>read the documentation on wallabag website</a>."
+
+msgid "Login"
+msgstr "Login"
+
+msgid "Repeat your password"
+msgstr "Repeat your password"
+
+msgid "Install"
+msgstr "Install"
+
+msgid "login to your wallabag"
+msgstr "login to your wallabag"
+
+msgid "Login to wallabag"
+msgstr "Login to wallabag"
+
+msgid "you are in demo mode, some features may be disabled."
+msgstr "you are in demo mode, some features may be disabled."
+
+msgid "Username"
+msgstr "Username"
+
+msgid "Stay signed in"
+msgstr "Stay signed in"
+
+msgid "(Do not check on public computers)"
+msgstr "(Do not check on public computers)"
+
+msgid "Sign in"
+msgstr "Sign in"
+
+msgid "favorites"
+msgstr "favorites"
+
+msgid "estimated reading time :"
+msgstr "estimated reading time :"
+
+msgid "Mark all the entries as read"
+msgstr "Mark all the entries as read"
+
+msgid "Return home"
+msgstr "Return home"
+
+msgid "Back to top"
+msgstr "Back to top"
+
+msgid "Mark as read"
+msgstr "Mark as read"
+
+msgid "Favorite"
+msgstr "Favorite"
+
+msgid "Toggle favorite"
+msgstr "Toggle favorite"
+
+msgid "Delete"
+msgstr "Delete"
+
+msgid "Tweet"
+msgstr "Tweet"
+
+msgid "Email"
+msgstr "Email"
 
 msgid "shaarli"
 msgstr "shaarli"
@@ -176,26 +319,23 @@ msgstr "shaarli"
 msgid "flattr"
 msgstr "flattr"
 
-msgid "this article appears wrong?"
-msgstr "this article appears wrong?"
+msgid "Does this article appear wrong?"
+msgstr "Does this article appear wrong?"
 
-msgid "create an issue"
-msgstr "create an issue"
+msgid "tags:"
+msgstr "tags:"
 
-msgid "or"
-msgstr "or"
+msgid "Edit tags"
+msgstr "Edit tags"
 
-msgid "contact us by mail"
-msgstr "contact us by mail"
-
-msgid "plop"
-msgstr "plop"
+msgid "save link!"
+msgstr "save link!"
 
 msgid "home"
 msgstr "home"
 
-msgid "favorites"
-msgstr "favorites"
+msgid "tags"
+msgstr "tags"
 
 msgid "logout"
 msgstr "logout"
@@ -206,23 +346,179 @@ msgstr "powered by"
 msgid "debug mode is on so cache is off."
 msgstr "debug mode is on so cache is off."
 
-msgid "your poche version:"
-msgstr "your poche version:"
+msgid "your wallabag version:"
+msgstr "your wallabag version:"
 
 msgid "storage:"
 msgstr "storage:"
 
-msgid "login to your poche"
-msgstr "login to your poche"
+msgid "save a link"
+msgstr "save a link"
 
-msgid "you are in demo mode, some features may be disabled."
-msgstr "you are in demo mode, some features may be disabled."
+msgid "back to home"
+msgstr "back to home"
 
-msgid "Stay signed in"
-msgstr "Stay signed in"
+msgid "toggle mark as read"
+msgstr "toggle mark as read"
 
-msgid "(Do not check on public computers)"
-msgstr "(Do not check on public computers)"
+msgid "tweet"
+msgstr "tweet"
 
-msgid "Sign in"
-msgstr "Sign in"
+msgid "email"
+msgstr "email"
+
+msgid "this article appears wrong?"
+msgstr "this article appears wrong?"
+
+msgid "No link available here!"
+msgstr "No link available here!"
+
+msgid "Poching a link"
+msgstr "Poching a link"
+
+msgid "by filling this field"
+msgstr "by filling this field"
+
+msgid "bookmarklet: drag & drop this link to your bookmarks bar"
+msgstr "bookmarklet: drag & drop this link to your bookmarks bar"
+
+msgid "your version"
+msgstr "your version"
+
+msgid "latest stable version"
+msgstr "latest stable version"
+
+msgid "a more recent stable version is available."
+msgstr "a more recent stable version is available."
+
+msgid "you are up to date."
+msgstr "you are up to date."
+
+msgid "latest dev version"
+msgstr "latest dev version"
+
+msgid "a more recent development version is available."
+msgstr "a more recent development version is available."
+
+msgid "Please execute the import script locally, it can take a very long time."
+msgstr "Please execute the import script locally, it can take a very long time."
+
+msgid "More infos in the official doc:"
+msgstr "More infos in the official doc:"
+
+msgid "import from Pocket"
+msgstr "import from Pocket"
+
+msgid "import from Readability"
+msgstr "import from Readability"
+
+msgid "import from Instapaper"
+msgstr "import from Instapaper"
+
+msgid "Tags"
+msgstr "Tags"
+
+msgid "Untitled"
+msgstr "Untitled"
+
+msgid "the link has been added successfully"
+msgstr "the link has been added successfully"
+
+msgid "error during insertion : the link wasn't added"
+msgstr "error during insertion : the link wasn't added"
+
+msgid "the link has been deleted successfully"
+msgstr "the link has been deleted successfully"
+
+msgid "the link wasn't deleted"
+msgstr "the link wasn't deleted"
+
+msgid "Article not found!"
+msgstr "Article not found!"
+
+msgid "previous"
+msgstr "previous"
+
+msgid "next"
+msgstr "next"
+
+msgid "in demo mode, you can't update your password"
+msgstr "in demo mode, you can't update your password"
+
+msgid "your password has been updated"
+msgstr "your password has been updated"
+
+msgid "the two fields have to be filled & the password must be the same in the two fields"
+msgstr "the two fields have to be filled & the password must be the same in the two fields"
+
+msgid "still using the \""
+msgstr "still using the \""
+
+msgid "that theme does not seem to be installed"
+msgstr "that theme does not seem to be installed"
+
+msgid "you have changed your theme preferences"
+msgstr "you have changed your theme preferences"
+
+msgid "that language does not seem to be installed"
+msgstr "that language does not seem to be installed"
+
+msgid "you have changed your language preferences"
+msgstr "you have changed your language preferences"
+
+msgid "login failed: you have to fill all fields"
+msgstr "login failed: you have to fill all fields"
+
+msgid "welcome to your wallabag"
+msgstr "welcome to your wallabag"
+
+msgid "login failed: bad login or password"
+msgstr "login failed: bad login or password"
+
+msgid "import from instapaper completed"
+msgstr "import from instapaper completed"
+
+msgid "import from pocket completed"
+msgstr "import from pocket completed"
+
+msgid "import from Readability completed. "
+msgstr "import from Readability completed. "
+
+msgid "import from Poche completed. "
+msgstr "import from Poche completed. "
+
+msgid "Unknown import provider."
+msgstr "Unknown import provider."
+
+msgid "Incomplete inc/poche/define.inc.php file, please define \""
+msgstr "Incomplete inc/poche/define.inc.php file, please define \""
+
+msgid "Could not find required \""
+msgstr "Could not find required \""
+
+msgid "Uh, there is a problem while generating feeds."
+msgstr "Uh, there is a problem while generating feeds."
+
+msgid "Cache deleted."
+msgstr "Cache deleted."
+
+msgid "Oops, it seems you don't have PHP 5."
+msgstr "Oops, it seems you don't have PHP 5."
+
+#~ msgid "poche it!"
+#~ msgstr "poche it!"
+
+#~ msgid "Updating poche"
+#~ msgstr "Updating poche"
+
+#~ msgid "create an issue"
+#~ msgstr "create an issue"
+
+#~ msgid "or"
+#~ msgstr "or"
+
+#~ msgid "contact us by mail"
+#~ msgstr "contact us by mail"
+
+#~ msgid "your poche version:"
+#~ msgstr "your poche version:"
index afe0595def4bfd63841b6bcbbdbec874cb5b64df..c08decfe2ca27665b81f23ba8c5e41806b0573b6 100644 (file)
 msgid ""
 msgstr ""
 "Project-Id-Version: \n"
-"POT-Creation-Date: \n"
+"Report-Msgid-Bugs-To: \n"
+"POT-Creation-Date: 2014-02-25 15:16+0300\n"
 "PO-Revision-Date: \n"
-"Last-Translator: Nicolas Lœuillet <nicolas.loeuillet@gmail.com>\n"
+"Last-Translator: Maryana <mariroz@mr.lviv.ua>\n"
 "Language-Team: \n"
+"Language: \n"
 "MIME-Version: 1.0\n"
 "Content-Type: text/plain; charset=UTF-8\n"
 "Content-Transfer-Encoding: 8bit\n"
 "X-Generator: Poedit 1.5.4\n"
+"X-Poedit-Language: Spanish\n"
+"X-Poedit-Basepath: .\n"
+"X-Poedit-SearchPath-0: /home/mariroz/_DEV/web/wallabag/wallabag-master-testing\n"
+
+msgid "wallabag, a read it later open source system"
+msgstr ""
+
+msgid "login failed: user doesn't exist"
+msgstr ""
+
+msgid "return home"
+msgstr ""
 
 msgid "config"
 msgstr "configuración"
 
-msgid "Poching a link"
-msgstr "Pochear un enlace"
+msgid "Saving articles"
+msgstr ""
+
+msgid "There are several ways to save an article:"
+msgstr ""
 
 msgid "read the documentation"
 msgstr "leer la documentación"
 
-msgid "by filling this field"
+msgid "download the extension"
+msgstr ""
+
+msgid "via F-Droid"
+msgstr ""
+
+msgid " or "
+msgstr ""
+
+msgid "via Google Play"
+msgstr ""
+
+msgid "download the application"
+msgstr ""
+
+#, fuzzy
+msgid "By filling this field"
 msgstr "rellenando este campo"
 
-msgid "poche it!"
-msgstr "pochéalo!"
+msgid "bag it!"
+msgstr ""
 
-msgid "Updating poche"
-msgstr "Actualizar"
+msgid "Bookmarklet: drag & drop this link to your bookmarks bar"
+msgstr ""
 
-msgid "your version"
-msgstr "su versión"
+msgid "Upgrading wallabag"
+msgstr ""
 
-msgid "latest stable version"
+#, fuzzy
+msgid "Installed version"
 msgstr "ultima versión estable"
 
-msgid "a more recent stable version is available."
+#, fuzzy
+msgid "Latest stable version"
+msgstr "ultima versión estable"
+
+#, fuzzy
+msgid "A more recent stable version is available."
 msgstr "una versión estable más reciente está disponible."
 
-msgid "you are up to date."
+#, fuzzy
+msgid "You are up to date."
 msgstr "estás actualizado."
 
-msgid "latest dev version"
+#, fuzzy
+msgid "Latest dev version"
 msgstr "ultima versión de desarollo"
 
-msgid "a more recent development version is available."
+#, fuzzy
+msgid "A more recent development version is available."
 msgstr "una versión de desarollo más reciente está disponible."
 
+msgid "Feeds"
+msgstr ""
+
+msgid "Your feed token is currently empty and must first be generated to enable feeds. Click <a href='?feed&amp;action=generate'>here to generate it</a>."
+msgstr ""
+
+msgid "Unread feed"
+msgstr ""
+
+#, fuzzy
+msgid "Favorites feed"
+msgstr "preferidos"
+
+#, fuzzy
+msgid "Archive feed"
+msgstr "archivos"
+
+msgid "Your token:"
+msgstr ""
+
+msgid "Your user id:"
+msgstr ""
+
+msgid "You can regenerate your token: <a href='?feed&amp;action=generate'>generate!</a>."
+msgstr ""
+
+#, fuzzy
+msgid "Change your theme"
+msgstr "Modificar tu contraseña"
+
+msgid "Theme:"
+msgstr ""
+
+msgid "Update"
+msgstr "Actualizar"
+
+#, fuzzy
+msgid "Change your language"
+msgstr "Modificar tu contraseña"
+
+msgid "Language:"
+msgstr ""
+
 msgid "Change your password"
 msgstr "Modificar tu contraseña"
 
@@ -58,66 +143,68 @@ msgstr "Contraseña"
 msgid "Repeat your new password:"
 msgstr "Repetir la nueva contraseña :"
 
-msgid "Update"
-msgstr "Actualizar"
-
 msgid "Import"
 msgstr "Importar"
 
-msgid "Please execute the import script locally, it can take a very long time."
-msgstr ""
-"Por favor, ejecute la importación en local, esto puede demorar un tiempo."
+#, fuzzy
+msgid "Please execute the import script locally as it can take a very long time."
+msgstr "Por favor, ejecute la importación en local, esto puede demorar un tiempo."
 
-msgid "More info in the official doc:"
+#, fuzzy
+msgid "More info in the official documentation:"
 msgstr "Más información en la documentación oficial :"
 
-msgid "import from Pocket"
+#, fuzzy
+msgid "Import from Pocket"
 msgstr "importación desde Pocket"
 
-msgid "import from Readability"
+#, php-format
+msgid "(you must have a %s file on your server)"
+msgstr ""
+
+#, fuzzy
+msgid "Import from Readability"
 msgstr "importación desde Readability"
 
-msgid "import from Instapaper"
+#, fuzzy
+msgid "Import from Instapaper"
 msgstr "importación desde Instapaper"
 
-msgid "Export your poche data"
+#, fuzzy
+msgid "Import from wallabag"
+msgstr "importación desde Readability"
+
+#, fuzzy
+msgid "Export your wallabag data"
 msgstr "Exportar sus datos de poche"
 
 msgid "Click here"
 msgstr "Haga clic aquí"
 
-msgid "to export your poche data."
-msgstr "para exportar sus datos de poche."
-
-msgid "back to home"
-msgstr "volver a la página de inicio"
+msgid "to download your database."
+msgstr ""
 
-msgid "installation"
-msgstr "instalación"
+#, fuzzy
+msgid "to export your wallabag data."
+msgstr "para exportar sus datos de poche."
 
-msgid "install your poche"
-msgstr "instala tu Poche"
+msgid "Cache"
+msgstr ""
 
-msgid ""
-"Poche is still not installed. Please fill the below form to install it. "
-"Don't hesitate to <a href='http://doc.inthepoche.com'>read the documentation "
-"on poche website</a>."
+msgid "to delete cache."
 msgstr ""
-"Poche todavia no està instalado. Por favor, completa los campos siguientes "
-"para instalarlo. No dudes de <a href='http://doc.inthepoche.com'>leer la "
-"documentación en el sitio de Poche</a>."
 
-msgid "Login"
-msgstr "Nombre de usuario"
+msgid "You can enter multiple tags, separated by commas."
+msgstr ""
 
-msgid "Repeat your password"
-msgstr "Repita su contraseña"
+msgid "return to article"
+msgstr ""
 
-msgid "Install"
-msgstr "Instalar"
+msgid "plop"
+msgstr "plop"
 
-msgid "back to top"
-msgstr "volver arriba"
+msgid "You can <a href='wallabag_compatibility_test.php'>check your configuration here</a>."
+msgstr ""
 
 msgid "favoris"
 msgstr "preferidos"
@@ -146,10 +233,14 @@ msgstr "por título"
 msgid "by title desc"
 msgstr "por título descendiente"
 
-msgid "No link available here!"
-msgstr "¡No hay ningún enlace disponible por aquí!"
+msgid "Tag"
+msgstr ""
 
-msgid "toggle mark as read"
+msgid "No articles found."
+msgstr ""
+
+#, fuzzy
+msgid "Toggle mark as read"
 msgstr "marcar como leído"
 
 msgid "toggle favorite"
@@ -161,13 +252,95 @@ msgstr "eliminar"
 msgid "original"
 msgstr "original"
 
+msgid "estimated reading time:"
+msgstr ""
+
+msgid "mark all the entries as read"
+msgstr ""
+
 msgid "results"
 msgstr "resultados"
 
-msgid "tweet"
+msgid "installation"
+msgstr "instalación"
+
+#, fuzzy
+msgid "install your wallabag"
+msgstr "instala tu Poche"
+
+#, fuzzy
+msgid "wallabag is still not installed. Please fill the below form to install it. Don't hesitate to <a href='http://doc.wallabag.org/'>read the documentation on wallabag website</a>."
+msgstr "Poche todavia no està instalado. Por favor, completa los campos siguientes para instalarlo. No dudes de <a href='http://doc.inthepoche.com'>leer la documentación en el sitio de Poche</a>."
+
+msgid "Login"
+msgstr "Nombre de usuario"
+
+msgid "Repeat your password"
+msgstr "Repita su contraseña"
+
+msgid "Install"
+msgstr "Instalar"
+
+#, fuzzy
+msgid "login to your wallabag"
+msgstr "conectarse a tu Poche"
+
+msgid "Login to wallabag"
+msgstr ""
+
+msgid "you are in demo mode, some features may be disabled."
+msgstr "este es el modo de demostración, algunas funcionalidades pueden estar desactivadas."
+
+msgid "Username"
+msgstr ""
+
+msgid "Stay signed in"
+msgstr "Seguir conectado"
+
+msgid "(Do not check on public computers)"
+msgstr "(no marcar en un ordenador público)"
+
+msgid "Sign in"
+msgstr "Iniciar sesión"
+
+msgid "favorites"
+msgstr "preferidos"
+
+msgid "estimated reading time :"
+msgstr ""
+
+msgid "Mark all the entries as read"
+msgstr ""
+
+msgid "Return home"
+msgstr ""
+
+#, fuzzy
+msgid "Back to top"
+msgstr "volver arriba"
+
+#, fuzzy
+msgid "Mark as read"
+msgstr "marcar como leído"
+
+#, fuzzy
+msgid "Favorite"
+msgstr "preferidos"
+
+#, fuzzy
+msgid "Toggle favorite"
+msgstr "preferido"
+
+#, fuzzy
+msgid "Delete"
+msgstr "eliminar"
+
+#, fuzzy
+msgid "Tweet"
 msgstr "tweetear"
 
-msgid "email"
+#, fuzzy
+msgid "Email"
 msgstr "enviar por mail"
 
 msgid "shaarli"
@@ -176,26 +349,24 @@ msgstr "shaarli"
 msgid "flattr"
 msgstr "flattr"
 
-msgid "this article appears wrong?"
+#, fuzzy
+msgid "Does this article appear wrong?"
 msgstr "este articulo no se ve bien?"
 
-msgid "create an issue"
-msgstr "crear un ticket"
-
-msgid "or"
-msgstr "o"
+msgid "tags:"
+msgstr ""
 
-msgid "contact us by mail"
-msgstr "contactarnos por mail"
+msgid "Edit tags"
+msgstr ""
 
-msgid "plop"
-msgstr "plop"
+msgid "save link!"
+msgstr ""
 
 msgid "home"
 msgstr "inicio"
 
-msgid "favorites"
-msgstr "preferidos"
+msgid "tags"
+msgstr ""
 
 msgid "logout"
 msgstr "cerrar sesión"
@@ -206,25 +377,187 @@ msgstr "hecho con"
 msgid "debug mode is on so cache is off."
 msgstr "el modo de depuración está activado, así que la cache está desactivada."
 
-msgid "your poche version:"
-msgstr "tu versión de Poche:"
+#, fuzzy
+msgid "your wallabag version:"
+msgstr "su versión"
 
 msgid "storage:"
 msgstr "almacenamiento:"
 
-msgid "login to your poche"
-msgstr "conectarse a tu Poche"
+msgid "save a link"
+msgstr ""
 
-msgid "you are in demo mode, some features may be disabled."
+msgid "back to home"
+msgstr "volver a la página de inicio"
+
+msgid "toggle mark as read"
+msgstr "marcar como leído"
+
+msgid "tweet"
+msgstr "tweetear"
+
+msgid "email"
+msgstr "enviar por mail"
+
+msgid "this article appears wrong?"
+msgstr "este articulo no se ve bien?"
+
+msgid "No link available here!"
+msgstr "¡No hay ningún enlace disponible por aquí!"
+
+msgid "Poching a link"
+msgstr "Pochear un enlace"
+
+msgid "by filling this field"
+msgstr "rellenando este campo"
+
+msgid "bookmarklet: drag & drop this link to your bookmarks bar"
 msgstr ""
-"este es el modo de demostración, algunas funcionalidades pueden estar "
-"desactivadas."
 
-msgid "Stay signed in"
-msgstr "Seguir conectado"
+msgid "your version"
+msgstr "su versión"
 
-msgid "(Do not check on public computers)"
-msgstr "(no marcar en un ordenador público)"
+msgid "latest stable version"
+msgstr "ultima versión estable"
 
-msgid "Sign in"
-msgstr "Iniciar sesión"
+msgid "a more recent stable version is available."
+msgstr "una versión estable más reciente está disponible."
+
+msgid "you are up to date."
+msgstr "estás actualizado."
+
+msgid "latest dev version"
+msgstr "ultima versión de desarollo"
+
+msgid "a more recent development version is available."
+msgstr "una versión de desarollo más reciente está disponible."
+
+msgid "Please execute the import script locally, it can take a very long time."
+msgstr "Por favor, ejecute la importación en local, esto puede demorar un tiempo."
+
+#, fuzzy
+msgid "More infos in the official doc:"
+msgstr "Más información en la documentación oficial :"
+
+msgid "import from Pocket"
+msgstr "importación desde Pocket"
+
+msgid "import from Readability"
+msgstr "importación desde Readability"
+
+msgid "import from Instapaper"
+msgstr "importación desde Instapaper"
+
+msgid "Tags"
+msgstr ""
+
+#, fuzzy
+msgid "Untitled"
+msgstr "por título"
+
+msgid "the link has been added successfully"
+msgstr ""
+
+msgid "error during insertion : the link wasn't added"
+msgstr ""
+
+msgid "the link has been deleted successfully"
+msgstr ""
+
+msgid "the link wasn't deleted"
+msgstr ""
+
+msgid "Article not found!"
+msgstr ""
+
+msgid "previous"
+msgstr ""
+
+msgid "next"
+msgstr ""
+
+msgid "in demo mode, you can't update your password"
+msgstr ""
+
+msgid "your password has been updated"
+msgstr ""
+
+msgid "the two fields have to be filled & the password must be the same in the two fields"
+msgstr ""
+
+msgid "still using the \""
+msgstr ""
+
+msgid "that theme does not seem to be installed"
+msgstr ""
+
+msgid "you have changed your theme preferences"
+msgstr ""
+
+msgid "that language does not seem to be installed"
+msgstr ""
+
+msgid "you have changed your language preferences"
+msgstr ""
+
+msgid "login failed: you have to fill all fields"
+msgstr ""
+
+msgid "welcome to your wallabag"
+msgstr ""
+
+msgid "login failed: bad login or password"
+msgstr ""
+
+#, fuzzy
+msgid "import from instapaper completed"
+msgstr "importación desde Instapaper"
+
+#, fuzzy
+msgid "import from pocket completed"
+msgstr "importación desde Pocket"
+
+#, fuzzy
+msgid "import from Readability completed. "
+msgstr "importación desde Readability"
+
+#, fuzzy
+msgid "import from Poche completed. "
+msgstr "importación desde Pocket"
+
+msgid "Unknown import provider."
+msgstr ""
+
+msgid "Incomplete inc/poche/define.inc.php file, please define \""
+msgstr ""
+
+msgid "Could not find required \""
+msgstr ""
+
+msgid "Uh, there is a problem while generating feeds."
+msgstr ""
+
+#, fuzzy
+msgid "Cache deleted."
+msgstr "eliminar"
+
+msgid "Oops, it seems you don't have PHP 5."
+msgstr ""
+
+#~ msgid "poche it!"
+#~ msgstr "pochéalo!"
+
+#~ msgid "Updating poche"
+#~ msgstr "Actualizar"
+
+#~ msgid "create an issue"
+#~ msgstr "crear un ticket"
+
+#~ msgid "or"
+#~ msgstr "o"
+
+#~ msgid "contact us by mail"
+#~ msgstr "contactarnos por mail"
+
+#~ msgid "your poche version:"
+#~ msgstr "tu versión de Poche:"
index 74a763c6238086f5bf489f302b2e3fc2f15eb19a..f24814d5846fcb55a6348821fefba99ef391ab4e 100644 (file)
 msgid ""
 msgstr ""
 "Project-Id-Version: \n"
-"POT-Creation-Date: \n"
+"Report-Msgid-Bugs-To: \n"
+"POT-Creation-Date: 2014-02-25 15:15+0300\n"
 "PO-Revision-Date: \n"
-"Last-Translator: Nicolas Lœuillet <nicolas.loeuillet@gmail.com>\n"
+"Last-Translator: Maryana <mariroz@mr.lviv.ua>\n"
 "Language-Team: \n"
+"Language: \n"
 "MIME-Version: 1.0\n"
 "Content-Type: text/plain; charset=UTF-8\n"
 "Content-Transfer-Encoding: 8bit\n"
 "X-Generator: Poedit 1.5.4\n"
+"X-Poedit-Language: Persian\n"
+"X-Poedit-Basepath: .\n"
+"X-Poedit-SearchPath-0: /home/mariroz/_DEV/web/wallabag/wallabag-master-testing\n"
+
+msgid "wallabag, a read it later open source system"
+msgstr ""
+
+msgid "login failed: user doesn't exist"
+msgstr ""
+
+msgid "return home"
+msgstr ""
 
 msgid "config"
 msgstr "تنظیمات"
 
-msgid "Poching a link"
-msgstr "پیوندی را poche کنید"
+msgid "Saving articles"
+msgstr ""
+
+msgid "There are several ways to save an article:"
+msgstr ""
 
 msgid "read the documentation"
 msgstr "راهنما را بخوانید"
 
-msgid "by filling this field"
+msgid "download the extension"
+msgstr ""
+
+msgid "via F-Droid"
+msgstr ""
+
+msgid " or "
+msgstr ""
+
+msgid "via Google Play"
+msgstr ""
+
+msgid "download the application"
+msgstr ""
+
+#, fuzzy
+msgid "By filling this field"
 msgstr "با پرکردن این بخش"
 
-msgid "poche it!"
-msgstr "poche کنید!"
+msgid "bag it!"
+msgstr ""
 
-msgid "Updating poche"
-msgstr "به‌روزرسانی poche"
+msgid "Bookmarklet: drag & drop this link to your bookmarks bar"
+msgstr ""
 
-msgid "your version"
-msgstr "نسخهٔ شما"
+msgid "Upgrading wallabag"
+msgstr ""
 
-msgid "latest stable version"
+#, fuzzy
+msgid "Installed version"
 msgstr "آخرین نسخهٔ پایدار"
 
-msgid "a more recent stable version is available."
+#, fuzzy
+msgid "Latest stable version"
+msgstr "آخرین نسخهٔ پایدار"
+
+#, fuzzy
+msgid "A more recent stable version is available."
 msgstr "نسخهٔ پایدار تازه‌ای منتشر شده است."
 
-msgid "you are up to date."
+#, fuzzy
+msgid "You are up to date."
 msgstr "شما به‌روز هستید."
 
-msgid "latest dev version"
+#, fuzzy
+msgid "Latest dev version"
 msgstr "آخرین نسخهٔ آزمایشی"
 
-msgid "a more recent development version is available."
+#, fuzzy
+msgid "A more recent development version is available."
 msgstr "نسخهٔ آزمایشی تازه‌ای منتشر شده است."
 
+msgid "Feeds"
+msgstr ""
+
+msgid "Your feed token is currently empty and must first be generated to enable feeds. Click <a href='?feed&amp;action=generate'>here to generate it</a>."
+msgstr ""
+
+msgid "Unread feed"
+msgstr ""
+
+#, fuzzy
+msgid "Favorites feed"
+msgstr "بهترین‌ها"
+
+#, fuzzy
+msgid "Archive feed"
+msgstr "بایگانی"
+
+msgid "Your token:"
+msgstr ""
+
+msgid "Your user id:"
+msgstr ""
+
+msgid "You can regenerate your token: <a href='?feed&amp;action=generate'>generate!</a>."
+msgstr ""
+
+#, fuzzy
+msgid "Change your theme"
+msgstr "گذرواژهٔ خود را تغییر دهید"
+
+msgid "Theme:"
+msgstr ""
+
+msgid "Update"
+msgstr "به‌روزرسانی"
+
+#, fuzzy
+msgid "Change your language"
+msgstr "گذرواژهٔ خود را تغییر دهید"
+
+msgid "Language:"
+msgstr ""
+
 msgid "Change your password"
 msgstr "گذرواژهٔ خود را تغییر دهید"
 
@@ -58,64 +143,68 @@ msgstr "گذرواژه"
 msgid "Repeat your new password:"
 msgstr "گذرواژهٔ تازه را دوباره وارد کنید"
 
-msgid "Update"
-msgstr "به‌روزرسانی"
-
 msgid "Import"
 msgstr "درون‌ریزی"
 
-msgid "Please execute the import script locally, it can take a very long time."
+#, fuzzy
+msgid "Please execute the import script locally as it can take a very long time."
 msgstr "لطفاً برنامهٔ درون‌ریزی را به‌طور محلی اجرا کنید، شاید خیلی طول بکشد."
 
-msgid "More info in the official doc:"
+#, fuzzy
+msgid "More info in the official documentation:"
 msgstr "اطلاعات بیشتر در راهنمای رسمی:"
 
-msgid "import from Pocket"
+#, fuzzy
+msgid "Import from Pocket"
 msgstr "درون‌ریزی از Pocket"
 
-msgid "import from Readability"
+#, php-format
+msgid "(you must have a %s file on your server)"
+msgstr ""
+
+#, fuzzy
+msgid "Import from Readability"
 msgstr "درون‌ریزی از Readability"
 
-msgid "import from Instapaper"
+#, fuzzy
+msgid "Import from Instapaper"
 msgstr "درون‌ریزی از Instapaper"
 
-msgid "Export your poche data"
+#, fuzzy
+msgid "Import from wallabag"
+msgstr "درون‌ریزی از Readability"
+
+#, fuzzy
+msgid "Export your wallabag data"
 msgstr "داده‌های poche خود را برون‌بری کنید"
 
 msgid "Click here"
 msgstr "اینجا را کلیک کنید"
 
-msgid "to export your poche data."
-msgstr "برای برون‌بری داده‌های poche شما"
-
-msgid "back to home"
-msgstr "بازگشت به خانه"
+msgid "to download your database."
+msgstr ""
 
-msgid "installation"
-msgstr "نصب"
+#, fuzzy
+msgid "to export your wallabag data."
+msgstr "برای برون‌بری داده‌های poche شما"
 
-msgid "install your poche"
-msgstr "poche خود را نصب کنید"
+msgid "Cache"
+msgstr ""
 
-msgid ""
-"poche is still not installed. Please fill the below form to install it. "
-"Don't hesitate to <a href='http://doc.inthepoche.com'>read the documentation "
-"on poche website</a>."
+msgid "to delete cache."
 msgstr ""
-"poche هنوز نصب نیست. برای نصب لطفاً فرم زیر را پر کنید. خواندن <a "
-"href='http://doc.inthepoche.com'>راهنما در وبگاه poche</a> را از یاد نبرید."
 
-msgid "Login"
-msgstr "ورود"
+msgid "You can enter multiple tags, separated by commas."
+msgstr ""
 
-msgid "Repeat your password"
-msgstr "گذرواژه را دوباره وارد کنید"
+msgid "return to article"
+msgstr ""
 
-msgid "Install"
-msgstr "نصب"
+msgid "plop"
+msgstr "plop"
 
-msgid "back to top"
-msgstr "بازگشت به بالای صفحه"
+msgid "You can <a href='wallabag_compatibility_test.php'>check your configuration here</a>."
+msgstr ""
 
 msgid "favoris"
 msgstr "بهترین‌ها"
@@ -144,10 +233,14 @@ msgstr "با عنوان"
 msgid "by title desc"
 msgstr "با عنوان (الفبایی معکوس)"
 
-msgid "No link available here!"
-msgstr "اینجا پیوندی موجود نیست!"
+msgid "Tag"
+msgstr ""
 
-msgid "toggle mark as read"
+msgid "No articles found."
+msgstr ""
+
+#, fuzzy
+msgid "Toggle mark as read"
 msgstr "خوانده‌شده/خوانده‌نشده"
 
 msgid "toggle favorite"
@@ -159,13 +252,95 @@ msgstr "پاک‌کردن"
 msgid "original"
 msgstr "اصلی"
 
+msgid "estimated reading time:"
+msgstr ""
+
+msgid "mark all the entries as read"
+msgstr ""
+
 msgid "results"
 msgstr "نتایج"
 
-msgid "tweet"
+msgid "installation"
+msgstr "نصب"
+
+#, fuzzy
+msgid "install your wallabag"
+msgstr "poche خود را نصب کنید"
+
+#, fuzzy
+msgid "wallabag is still not installed. Please fill the below form to install it. Don't hesitate to <a href='http://doc.wallabag.org/'>read the documentation on wallabag website</a>."
+msgstr "poche هنوز نصب نیست. برای نصب لطفاً فرم زیر را پر کنید. خواندن <a href='http://doc.inthepoche.com'>راهنما در وبگاه poche</a> را از یاد نبرید."
+
+msgid "Login"
+msgstr "ورود"
+
+msgid "Repeat your password"
+msgstr "گذرواژه را دوباره وارد کنید"
+
+msgid "Install"
+msgstr "نصب"
+
+#, fuzzy
+msgid "login to your wallabag"
+msgstr "به poche خود وارد شوید"
+
+msgid "Login to wallabag"
+msgstr ""
+
+msgid "you are in demo mode, some features may be disabled."
+msgstr "این تنها نسخهٔ نمایشی است، برخی از ویژگی‌ها کار نمی‌کنند."
+
+msgid "Username"
+msgstr ""
+
+msgid "Stay signed in"
+msgstr "مرا به خاطر بسپار"
+
+msgid "(Do not check on public computers)"
+msgstr "(روی رایانه‌های عمومی این کار را نکنید)"
+
+msgid "Sign in"
+msgstr "ورود"
+
+msgid "favorites"
+msgstr "بهترین‌ها"
+
+msgid "estimated reading time :"
+msgstr ""
+
+msgid "Mark all the entries as read"
+msgstr ""
+
+msgid "Return home"
+msgstr ""
+
+#, fuzzy
+msgid "Back to top"
+msgstr "بازگشت به بالای صفحه"
+
+#, fuzzy
+msgid "Mark as read"
+msgstr "خوانده‌شده/خوانده‌نشده"
+
+#, fuzzy
+msgid "Favorite"
+msgstr "بهترین‌ها"
+
+#, fuzzy
+msgid "Toggle favorite"
+msgstr "جزء بهترین‌ها هست/نیست"
+
+#, fuzzy
+msgid "Delete"
+msgstr "پاک‌کردن"
+
+#, fuzzy
+msgid "Tweet"
 msgstr "توییت"
 
-msgid "email"
+#, fuzzy
+msgid "Email"
 msgstr "ایمیل"
 
 msgid "shaarli"
@@ -174,26 +349,24 @@ msgstr "shaarli"
 msgid "flattr"
 msgstr "flattr"
 
-msgid "this article appears wrong?"
+#, fuzzy
+msgid "Does this article appear wrong?"
 msgstr "این مطلب اشتباه نمایش داده شده؟"
 
-msgid "create an issue"
-msgstr "یک درخواست رفع‌مشکل بنویسید"
-
-msgid "or"
-msgstr "یا"
+msgid "tags:"
+msgstr ""
 
-msgid "contact us by mail"
-msgstr "به ما ایمیل بزنید"
+msgid "Edit tags"
+msgstr ""
 
-msgid "plop"
-msgstr "plop"
+msgid "save link!"
+msgstr ""
 
 msgid "home"
 msgstr "خانه"
 
-msgid "favorites"
-msgstr "بهترین‌ها"
+msgid "tags"
+msgstr ""
 
 msgid "logout"
 msgstr "بیرون رفتن"
@@ -204,23 +377,187 @@ msgstr "نیروگرفته از"
 msgid "debug mode is on so cache is off."
 msgstr "حالت عیب‌یابی فعال است، پس کاشه خاموش است."
 
-msgid "your poche version:"
-msgstr "نسخهٔ poche شما:"
+#, fuzzy
+msgid "your wallabag version:"
+msgstr "نسخهٔ شما"
 
 msgid "storage:"
 msgstr "ذخیره‌سازی:"
 
-msgid "login to your poche"
-msgstr "به poche خود وارد شوید"
+msgid "save a link"
+msgstr ""
 
-msgid "you are in demo mode, some features may be disabled."
-msgstr "اÛ\8cÙ\86 ØªÙ\86Ù\87ا Ù\86سخÙ\87Ù\94 Ù\86Ù\85اÛ\8cØ´Û\8c Ø§Ø³ØªØ\8c Ø¨Ø±Ø®Û\8c Ø§Ø² Ù\88Û\8cÚ\98Ú¯Û\8câ\80\8cÙ\87ا Ú©Ø§Ø± Ù\86Ù\85Û\8câ\80\8cÚ©Ù\86Ù\86د."
+msgid "back to home"
+msgstr "بازگشت Ø¨Ù\87 Ø®Ø§Ù\86Ù\87"
 
-msgid "Stay signed in"
-msgstr "مرا به خاطر بسپار"
+msgid "toggle mark as read"
+msgstr "خوانده‌شده/خوانده‌نشده"
 
-msgid "(Do not check on public computers)"
-msgstr "(روی رایانه‌های عمومی این کار را نکنید)"
+msgid "tweet"
+msgstr "توییت"
 
-msgid "Sign in"
-msgstr "ورود"
+msgid "email"
+msgstr "ایمیل"
+
+msgid "this article appears wrong?"
+msgstr "این مطلب اشتباه نمایش داده شده؟"
+
+msgid "No link available here!"
+msgstr "اینجا پیوندی موجود نیست!"
+
+msgid "Poching a link"
+msgstr "پیوندی را poche کنید"
+
+msgid "by filling this field"
+msgstr "با پرکردن این بخش"
+
+msgid "bookmarklet: drag & drop this link to your bookmarks bar"
+msgstr ""
+
+msgid "your version"
+msgstr "نسخهٔ شما"
+
+msgid "latest stable version"
+msgstr "آخرین نسخهٔ پایدار"
+
+msgid "a more recent stable version is available."
+msgstr "نسخهٔ پایدار تازه‌ای منتشر شده است."
+
+msgid "you are up to date."
+msgstr "شما به‌روز هستید."
+
+msgid "latest dev version"
+msgstr "آخرین نسخهٔ آزمایشی"
+
+msgid "a more recent development version is available."
+msgstr "نسخهٔ آزمایشی تازه‌ای منتشر شده است."
+
+msgid "Please execute the import script locally, it can take a very long time."
+msgstr "لطفاً برنامهٔ درون‌ریزی را به‌طور محلی اجرا کنید، شاید خیلی طول بکشد."
+
+#, fuzzy
+msgid "More infos in the official doc:"
+msgstr "اطلاعات بیشتر در راهنمای رسمی:"
+
+msgid "import from Pocket"
+msgstr "درون‌ریزی از Pocket"
+
+msgid "import from Readability"
+msgstr "درون‌ریزی از Readability"
+
+msgid "import from Instapaper"
+msgstr "درون‌ریزی از Instapaper"
+
+msgid "Tags"
+msgstr ""
+
+#, fuzzy
+msgid "Untitled"
+msgstr "با عنوان"
+
+msgid "the link has been added successfully"
+msgstr ""
+
+msgid "error during insertion : the link wasn't added"
+msgstr ""
+
+msgid "the link has been deleted successfully"
+msgstr ""
+
+msgid "the link wasn't deleted"
+msgstr ""
+
+msgid "Article not found!"
+msgstr ""
+
+msgid "previous"
+msgstr ""
+
+msgid "next"
+msgstr ""
+
+msgid "in demo mode, you can't update your password"
+msgstr ""
+
+msgid "your password has been updated"
+msgstr ""
+
+msgid "the two fields have to be filled & the password must be the same in the two fields"
+msgstr ""
+
+msgid "still using the \""
+msgstr ""
+
+msgid "that theme does not seem to be installed"
+msgstr ""
+
+msgid "you have changed your theme preferences"
+msgstr ""
+
+msgid "that language does not seem to be installed"
+msgstr ""
+
+msgid "you have changed your language preferences"
+msgstr ""
+
+msgid "login failed: you have to fill all fields"
+msgstr ""
+
+msgid "welcome to your wallabag"
+msgstr ""
+
+msgid "login failed: bad login or password"
+msgstr ""
+
+#, fuzzy
+msgid "import from instapaper completed"
+msgstr "درون‌ریزی از Instapaper"
+
+#, fuzzy
+msgid "import from pocket completed"
+msgstr "درون‌ریزی از Pocket"
+
+#, fuzzy
+msgid "import from Readability completed. "
+msgstr "درون‌ریزی از Readability"
+
+#, fuzzy
+msgid "import from Poche completed. "
+msgstr "درون‌ریزی از Pocket"
+
+msgid "Unknown import provider."
+msgstr ""
+
+msgid "Incomplete inc/poche/define.inc.php file, please define \""
+msgstr ""
+
+msgid "Could not find required \""
+msgstr ""
+
+msgid "Uh, there is a problem while generating feeds."
+msgstr ""
+
+#, fuzzy
+msgid "Cache deleted."
+msgstr "پاک‌کردن"
+
+msgid "Oops, it seems you don't have PHP 5."
+msgstr ""
+
+#~ msgid "poche it!"
+#~ msgstr "poche کنید!"
+
+#~ msgid "Updating poche"
+#~ msgstr "به‌روزرسانی poche"
+
+#~ msgid "create an issue"
+#~ msgstr "یک درخواست رفع‌مشکل بنویسید"
+
+#~ msgid "or"
+#~ msgstr "یا"
+
+#~ msgid "contact us by mail"
+#~ msgstr "به ما ایمیل بزنید"
+
+#~ msgid "your poche version:"
+#~ msgstr "نسخهٔ poche شما:"
index 76872b5a0fe47c51d05e0f65221616214ce72e28..b625e346c7ea82c3760705371100a4d25a5d10ac 100644 (file)
Binary files a/locale/fr_FR.utf8/LC_MESSAGES/fr_FR.utf8.mo and b/locale/fr_FR.utf8/LC_MESSAGES/fr_FR.utf8.mo differ
index f105d1801298d578aa884514f65afcb3c8a083c4..0343bfec63fe6e54b6758f0591bcad57462362d3 100644 (file)
 msgid ""
 msgstr ""
-"Project-Id-Version: \n"
-"POT-Creation-Date: \n"
+"Project-Id-Version: wallabag 1.7\n"
+"Report-Msgid-Bugs-To: \n"
+"POT-Creation-Date: 2014-05-10 20:09+0100\n"
 "PO-Revision-Date: \n"
-"Last-Translator: Nicolas Lœuillet <nicolas.loeuillet@gmail.com>\n"
+"Last-Translator: Gilles Wittezaële <gilles.wittezaele@laposte.net>\n"
 "Language-Team: \n"
+"Language: fr_FR\n"
 "MIME-Version: 1.0\n"
 "Content-Type: text/plain; charset=UTF-8\n"
 "Content-Transfer-Encoding: 8bit\n"
+"X-Poedit-KeywordsList: _;gettext;gettext_noop\n"
+"X-Poedit-SourceCharset: UTF-8\n"
 "X-Generator: Poedit 1.5.4\n"
+"Plural-Forms: nplurals=2; plural=(n != 1);\n"
+
+msgid "wallabag, a read it later open source system"
+msgstr "wallabag, un système open source de lecture différé"
+
+msgid "login failed: user doesn't exist"
+msgstr "échec de l'identification : cet utilisateur n'existe pas"
+
+msgid "save link!"
+msgstr "enregistrer le lien !"
+
+msgid "plop"
+msgstr "plop"
+
+msgid "powered by"
+msgstr "propulsé par"
+
+msgid "debug mode is on so cache is off."
+msgstr "le mode de debug est actif, le cache est donc désactivé."
+
+msgid "your wallabag version:"
+msgstr "votre version de wallabag :"
+
+msgid "storage:"
+msgstr "stockage :"
+
+msgid "login to your wallabag"
+msgstr "se connecter à votre wallabag"
+
+msgid "Login to wallabag"
+msgstr "Se connecter à wallabag"
+
+msgid "you are in demo mode, some features may be disabled."
+msgstr ""
+"vous êtes en mode démo, certaines fonctionnalités peuvent être désactivées."
+
+msgid "Username"
+msgstr "Nom d'utilisateur"
+
+msgid "Password"
+msgstr "Mot de passe"
+
+msgid "Stay signed in"
+msgstr "Rester connecté"
+
+msgid "(Do not check on public computers)"
+msgstr "(Ne pas cocher sur un ordinateur public)"
+
+msgid "Sign in"
+msgstr "Se connecter"
+
+msgid "back to home"
+msgstr "retour à l'accueil"
+
+msgid "favorites"
+msgstr "favoris"
+
+msgid "archive"
+msgstr "archive"
+
+msgid "unread"
+msgstr "non lus"
+
+msgid "Tag"
+msgstr "Tag"
+
+msgid "No articles found."
+msgstr "Aucun article trouvé."
+
+msgid "estimated reading time:"
+msgstr "temps de lecture estimé :"
+
+msgid "estimated reading time :"
+msgstr "temps de lecture estimé :"
+
+msgid "Toggle mark as read"
+msgstr "Marquer comme lu / non lu"
+
+msgid "toggle favorite"
+msgstr "marquer / enlever comme favori"
+
+msgid "delete"
+msgstr "supprimer"
+
+msgid "original"
+msgstr "original"
+
+msgid "Mark all the entries as read"
+msgstr "Marquer tous les articles comme lus"
+
+msgid "results"
+msgstr "résultats"
+
+msgid " found for « "
+msgstr "trouvé pour « "
+
+msgid "Only one result found for "
+msgstr "Seulement un résultat trouvé pour "
 
 msgid "config"
 msgstr "configuration"
 
-msgid "Poching a link"
-msgstr "Pocher un lien"
+msgid "Saving articles"
+msgstr "Sauvegarde des articles"
+
+msgid "There are several ways to save an article:"
+msgstr "Il y a plusieurs façons d'enregistrer un article :"
 
 msgid "read the documentation"
 msgstr "lisez la documentation"
 
-msgid "by filling this field"
-msgstr "en remplissant ce champ"
+msgid "download the extension"
+msgstr "téléchargez l'extension"
 
-msgid "poche it!"
-msgstr "pochez-le !"
+msgid "via F-Droid"
+msgstr "via F-Droid"
 
-msgid "Updating poche"
-msgstr "Mettre à jour poche"
+msgid " or "
+msgstr " ou "
 
-msgid "your version"
-msgstr "votre version"
+msgid "via Google Play"
+msgstr "via Google PlayStore"
 
-msgid "latest stable version"
-msgstr "dernière version stable"
+msgid "download the application"
+msgstr "téléchargez l'application"
 
-msgid "a more recent stable version is available."
-msgstr "une version stable plus récente est disponible."
+msgid "By filling this field"
+msgstr "En remplissant ce champ"
 
-msgid "you are up to date."
-msgstr "vous êtes à jour."
+msgid "bag it!"
+msgstr "bag it !"
 
-msgid "latest dev version"
-msgstr "dernière version de développement"
+msgid "Bookmarklet: drag & drop this link to your bookmarks bar"
+msgstr "Bookmarklet : glissez-déposez ce lien dans votre barre de favoris"
 
-msgid "a more recent development version is available."
-msgstr "une version de développement plus récente est disponible."
+msgid "Upgrading wallabag"
+msgstr "Mise à jour de wallabag"
+
+msgid "Installed version"
+msgstr "Version installée"
+
+msgid "Latest stable version"
+msgstr "Dernière version stable"
+
+msgid "A more recent stable version is available."
+msgstr "Une version stable plus récente est disponible."
+
+msgid "You are up to date."
+msgstr "Vous êtes à jour."
+
+msgid "Last check:"
+msgstr "Dernière vérification: "
+
+msgid "Latest dev version"
+msgstr "Dernière version de développement"
+
+msgid "A more recent development version is available."
+msgstr "Une version de développement plus récente est disponible."
+
+msgid "You can clear cache to check the latest release."
+msgstr ""
+"Vous pouvez vider le cache pour vérifier que vous avez la dernière version."
+
+msgid "Feeds"
+msgstr "Flux"
+
+msgid ""
+"Your feed token is currently empty and must first be generated to enable "
+"feeds. Click <a href='?feed&amp;action=generate'>here to generate it</a>."
+msgstr ""
+"Votre jeton de flux est actuellement vide et doit d'abord être généré pour "
+"activer les flux. Cliquez <a href='?feed&amp;action=generate'>ici</a> pour "
+"le générer."
+
+msgid "Unread feed"
+msgstr "Flux des non lus"
+
+msgid "Favorites feed"
+msgstr "Flux des favoris"
+
+msgid "Archive feed"
+msgstr "Flux des archives"
+
+msgid "Your token:"
+msgstr "Votre jeton :"
+
+msgid "Your user id:"
+msgstr "Votre ID utilisateur :"
+
+msgid ""
+"You can regenerate your token: <a href='?feed&amp;action=generate'>generate!"
+"</a>."
+msgstr ""
+"Vous pouvez regénérer votre jeton : <a href='?feed&amp;"
+"action=generate'>génération !</a>."
+
+msgid "Change your theme"
+msgstr "Changer votre thème"
+
+msgid "Theme:"
+msgstr "Thème :"
+
+msgid "Update"
+msgstr "Mettre à jour"
+
+msgid "Change your language"
+msgstr "Changer votre langue"
+
+msgid "Language:"
+msgstr "Langue :"
 
 msgid "Change your password"
 msgstr "Modifier votre mot de passe"
@@ -52,80 +230,214 @@ msgstr "Modifier votre mot de passe"
 msgid "New password:"
 msgstr "Nouveau mot de passe :"
 
-msgid "Password"
-msgstr "Mot de passe"
-
 msgid "Repeat your new password:"
 msgstr "Répétez votre nouveau mot de passe :"
 
-msgid "Update"
-msgstr "Mettre à jour"
-
 msgid "Import"
 msgstr "Importer"
 
-msgid "Please execute the import script locally, it can take a very long time."
-msgstr "Merci d'exécuter l'import en local, cela peut prendre du temps."
+msgid ""
+"You can import your Pocket, Readability, Instapaper, Wallabag or any data in "
+"appropriate json or html format."
+msgstr ""
+"Vous pouvez importer depuis Pocket, Readability, Instapaper, wallabag, ou "
+"n'importe quel fichier au format JSON ou HTML approprié."
 
-msgid "More info in the official doc:"
-msgstr "Plus d'infos sur la documentation officielle"
+msgid ""
+"Please select export file on your computer and press \"Import\" button below."
+"<br>Wallabag will parse your file, insert all URLs and start fetching of "
+"articles if required.<br>Fetching process is controlled by two constants in "
+"your config file: IMPORT_LIMIT (how many articles are fetched at once) and "
+"IMPORT_DELAY (delay between fetch of next batch of articles)."
+msgstr ""
+"Sélectionner le fichier à importer sur votre disque dur, et pressez la "
+"bouton « Importer » ci-dessous.<br />wallabag analysera votre fichier, "
+"ajoutera toutes les URL trouvées et commencera à télécharger les contenus si "
+"nécessaire.<br />Le processus de téléchargement est contrôlé par deux "
+"constantes dans votre fichier de configuration:<wbr /><code>IMPORT_LIMIT</"
+"code> (nombre d'éléments téléchargés à la fois) et <code>IMPORT_DELAY</code> "
+"(le délai d'attente entre deux séquences de téléchargement)."
+
+msgid "File:"
+msgstr "Fichier : "
+
+msgid "You can click here to fetch content for articles with no content."
+msgstr ""
+"Vous pouvez cliquer ici pour télécharger le contenu des articles vides."
 
-msgid "import from Pocket"
-msgstr "import depuis Pocket"
+msgid "Export your wallabag data"
+msgstr "Exporter vos données de wallabag"
 
-msgid "import from Readability"
-msgstr "import depuis Readability"
+msgid "Click here"
+msgstr "Cliquez ici"
 
-msgid "import from Instapaper"
-msgstr "import depuis Instapaper"
+msgid "to download your database."
+msgstr "pour télécharger votre base de données."
 
-msgid "Export your poche data"
-msgstr "Exporter vos données de poche"
+msgid "to export your wallabag data."
+msgstr "pour exporter vos données de wallabag."
 
-msgid "Click here"
-msgstr "Cliquez-ici"
+msgid "Cache"
+msgstr "Cache"
 
-msgid "to export your poche data."
-msgstr "pour exporter vos données de poche."
+msgid "to delete cache."
+msgstr "pour effacer le cache."
 
-msgid "back to home"
-msgstr "retour à l'accueil"
+msgid "Add user"
+msgstr "Ajouter un utilisateur"
 
-msgid "installation"
-msgstr "installation"
+msgid "Add a new user :"
+msgstr "Ajouter un nouvel utilisateur : "
+
+msgid "Login for new user"
+msgstr "Identifiant du nouvel utilisateur"
+
+msgid "Login"
+msgstr "Nom d'utilisateur"
+
+msgid "Password for new user"
+msgstr "Mot de passe du nouvel utilisateur"
+
+msgid "Send"
+msgstr "Envoyer"
+
+msgid "Delete account"
+msgstr "Supprimer le compte"
 
-msgid "install your poche"
-msgstr "installez votre poche"
+msgid "You can delete your account by entering your password and validating."
+msgstr ""
+"Vous pouvez supprimer votre compte en entrant votre mot de passe et en "
+"validant."
+
+msgid "Be careful, data will be erased forever (that is a very long time)."
+msgstr "Attention, les données seront perdues pour toujours."
+
+msgid "Type here your password"
+msgstr "Entrez votre mot de passe ici"
+
+msgid "You are the only user, you cannot delete your own account."
+msgstr ""
+"Vous êtes l'unique utilisateur, vous ne pouvez pas supprimer votre compte."
 
 msgid ""
-"poche is still not installed. Please fill the below form to install it. "
-"Don't hesitate to <a href='http://doc.inthepoche.com'>read the documentation "
-"on poche website</a>."
+"To completely remove wallabag, delete the wallabag folder on your web server."
 msgstr ""
-"poche n'est pas encore installé. Merci de remplir le formulaire suivant pour "
-"l'installer. N'hésitez pas à <a href='http://doc.inthepoche.com'>lire la "
-"documentation sur le site de poche</a>."
+"Pour désinstaller complètement wallabag, supprimez le répertoire "
+"<code>wallabag</code> de votre serveur Web."
 
-msgid "Login"
-msgstr "Nom d'utilisateur"
+msgid "Save a link"
+msgstr "Ajouter un lien"
 
-msgid "Repeat your password"
-msgstr "Répétez votre mot de passe"
+msgid "Return home"
+msgstr "Retour accueil"
 
-msgid "Install"
-msgstr "Installer"
+msgid "Back to top"
+msgstr "Haut de page"
+
+msgid "Mark as read"
+msgstr "Marquer comme lu"
+
+msgid "Favorite"
+msgstr "Favoris"
+
+msgid "Toggle favorite"
+msgstr "Marquer / enlever comme favori"
 
-msgid "back to top"
-msgstr "retour en haut de page"
+msgid "Delete"
+msgstr "Effacer"
+
+msgid "Tweet"
+msgstr "Tweet"
+
+msgid "Email"
+msgstr "E-mail"
+
+msgid "shaarli"
+msgstr "Shaarli"
+
+msgid "flattr"
+msgstr "Flattr"
+
+msgid "Print"
+msgstr "Imprimer"
+
+msgid "Does this article appear wrong?"
+msgstr "Cet article s'affiche mal ?"
+
+msgid "tags:"
+msgstr "tags :"
+
+msgid "Edit tags"
+msgstr "Modifier les tags"
 
 msgid "favoris"
 msgstr "favoris"
 
-msgid "archive"
-msgstr "archive"
+msgid "mark all the entries as read"
+msgstr "marquer tous les articles comme lus"
 
-msgid "unread"
-msgstr "non lus"
+msgid "toggle view mode"
+msgstr "changer de mode de visualisation"
+
+msgid "return home"
+msgstr "retour à l'accueil"
+
+msgid "Poching a link"
+msgstr "Enregistrer un lien"
+
+msgid "by filling this field"
+msgstr "en remplissant ce champ"
+
+msgid "bookmarklet: drag & drop this link to your bookmarks bar"
+msgstr "bookmarklet : glissez-déposez ce lien dans votre barre de favoris"
+
+msgid "your version"
+msgstr "votre version"
+
+msgid "latest stable version"
+msgstr "dernière version stable"
+
+msgid "a more recent stable version is available."
+msgstr "une version stable plus récente est disponible."
+
+msgid "you are up to date."
+msgstr "vous êtes à jour."
+
+msgid "latest dev version"
+msgstr "dernière version de développement"
+
+msgid "a more recent development version is available."
+msgstr "une version de développement plus récente est disponible."
+
+msgid "Please execute the import script locally, it can take a very long time."
+msgstr ""
+"Merci d'exécuter le script d'importation en local car cela peut prendre du "
+"temps."
+
+msgid "More infos in the official doc:"
+msgstr "Plus d'infos dans la documentation officielle :"
+
+msgid "import from Pocket"
+msgstr "importer depuis Pocket"
+
+#, php-format
+msgid "(you must have a %s file on your server)"
+msgstr "(le fichier %s doit être présent sur le serveur)"
+
+msgid "import from Readability"
+msgstr "importer depuis Readability"
+
+msgid "import from Instapaper"
+msgstr "importer depuis Instapaper"
+
+msgid "Start typing for auto complete."
+msgstr "Commencez à taper pour activer l'auto-complétion."
+
+msgid "You can enter multiple tags, separated by commas."
+msgstr "Vous pouvez entrer plusieurs tags, séparés par des virgules."
+
+msgid "return to article"
+msgstr "retourner à l'article"
 
 msgid "by date asc"
 msgstr "par date asc"
@@ -145,84 +457,196 @@ msgstr "par titre"
 msgid "by title desc"
 msgstr "par titre desc"
 
+msgid "home"
+msgstr "accueil"
+
+msgid "tags"
+msgstr "tags"
+
+msgid "save a link"
+msgstr "sauver un lien"
+
+msgid "search"
+msgstr "rechercher"
+
+msgid "logout"
+msgstr "déconnexion"
+
+msgid "installation"
+msgstr "installation"
+
+msgid "install your wallabag"
+msgstr "installez votre wallabag"
+
+msgid ""
+"wallabag is still not installed. Please fill the below form to install it. "
+"Don't hesitate to <a href='http://doc.wallabag.org/'>read the documentation "
+"on wallabag website</a>."
+msgstr ""
+"wallabag n'est pas encore installé. Merci de remplir le formulaire suivant "
+"pour l'installer. N'hésitez pas à <a href='http://doc.wallabag.org'>lire la "
+"documentation sur le site de wallabag</a>."
+
+msgid "Repeat your password"
+msgstr "Répétez votre mot de passe"
+
+msgid "Install"
+msgstr "Installer"
+
+msgid ""
+"You can <a href='wallabag_compatibility_test.php'>check your configuration "
+"here</a>."
+msgstr ""
+"Vous pouvez vérifier votre configuration <a "
+"href='wallabag_compatibility_test.php'>ici</a>."
+
+msgid "Tags"
+msgstr "Tags"
+
 msgid "No link available here!"
 msgstr "Aucun lien n'est disponible ici !"
 
 msgid "toggle mark as read"
 msgstr "marquer comme lu / non lu"
 
-msgid "toggle favorite"
-msgstr "marquer comme favori"
+msgid "tweet"
+msgstr "tweet"
 
-msgid "delete"
-msgstr "supprimer"
+msgid "email"
+msgstr "e-mail"
 
-msgid "original"
-msgstr "original"
+msgid "this article appears wrong?"
+msgstr "cet article s'affiche mal ?"
 
-msgid "results"
-msgstr "résultats"
+msgid "Search"
+msgstr "Rechercher"
 
-msgid "tweet"
-msgstr "tweet"
+msgid "Download required for "
+msgstr "Téléchargement requis pour "
 
-msgid "email"
-msgstr "email"
+msgid "records"
+msgstr " articles"
 
-msgid "shaarli"
-msgstr "shaarli"
+msgid "Downloading next "
+msgstr "Téléchargement des "
 
-msgid "flattr"
-msgstr "flattr"
+msgid "articles, please wait"
+msgstr " articles suivants, veuillez patienter..."
 
-msgid "this article appears wrong?"
-msgstr "cet article s'affiche mal ?"
+msgid "Enter your search here"
+msgstr "Entrez votre recherche ici"
 
-msgid "create an issue"
-msgstr "créez un ticket"
+#, php-format
+msgid ""
+"The new user %s has been installed. Do you want to <a href=\"?logout"
+"\">logout ?</a>"
+msgstr ""
+"Le nouvel utilisateur « %s » a été ajouté. Voulez-vous vous  <a href=\"?"
+"logout\">déconnecter ?</a>"
 
-msgid "or"
-msgstr "ou"
+#, php-format
+msgid "Error : An user with the name %s already exists !"
+msgstr "Erreur : Un utilisateur avec le nom « %s » existe déjà !"
 
-msgid "contact us by mail"
-msgstr "contactez-nous par email"
+#, php-format
+msgid "User %s has been successfully deleted !"
+msgstr "L'utilisateur « %s » a été supprimé avec succès !"
 
-msgid "plop"
-msgstr "plop"
+msgid "Error : The password is wrong !"
+msgstr "Erreur : le mot de passe est incorrect !"
 
-msgid "home"
-msgstr "accueil"
+msgid "Error : You are the only user, you cannot delete your account !"
+msgstr ""
+"Erreur : Vous êtes l'unique utilisateur, vous ne pouvez pas supprimer votre "
+"compte !"
 
-msgid "favorites"
-msgstr "favoris"
+msgid "Untitled"
+msgstr "Sans titre"
 
-msgid "logout"
-msgstr "déconnexion"
+msgid "the link has been added successfully"
+msgstr "le lien a été ajouté avec succès"
 
-msgid "powered by"
-msgstr "propulsé par"
+msgid "error during insertion : the link wasn't added"
+msgstr "erreur pendant l'insertion : le lien n'a pas été ajouté"
 
-msgid "debug mode is on so cache is off."
-msgstr "le mode de debug est actif, le cache est donc désactivé."
+msgid "the link has been deleted successfully"
+msgstr "le lien a été effacé avec succès"
 
-msgid "your poche version:"
-msgstr "votre version de poche :"
+msgid "the link wasn't deleted"
+msgstr "le lien n'a pas été effacé"
 
-msgid "storage:"
-msgstr "stockage :"
+msgid "Article not found!"
+msgstr "Article non trouvé !"
 
-msgid "login to your poche"
-msgstr "se connecter à votre poche"
+msgid "previous"
+msgstr "précédent"
 
-msgid "you are in demo mode, some features may be disabled."
+msgid "next"
+msgstr "suivant"
+
+msgid "in demo mode, you can't update your password"
+msgstr "en mode démo, vous ne pouvez pas mettre à jour votre mot de passe"
+
+msgid "your password has been updated"
+msgstr "votre mot de passe a été mis à jour"
+
+msgid ""
+"the two fields have to be filled & the password must be the same in the two "
+"fields"
 msgstr ""
-"vous êtes en mode démo, certaines fonctionnalités peuvent être désactivées."
+"les deux champs doivent être remplis & le mot de passe doit être le même "
+"dans les deux"
 
-msgid "Stay signed in"
-msgstr "Rester connecté"
+msgid "still using the \""
+msgstr "vous utilisez toujours \""
 
-msgid "(Do not check on public computers)"
-msgstr "(ne pas cocher sur un ordinateur public)"
+msgid "that theme does not seem to be installed"
+msgstr "ce thème ne semble pas installé"
 
-msgid "Sign in"
-msgstr "Se connecter"
+msgid "you have changed your theme preferences"
+msgstr "vous avez changé vos préférences de thème"
+
+msgid "that language does not seem to be installed"
+msgstr "cette langue ne semble pas être installée"
+
+msgid "you have changed your language preferences"
+msgstr "vous avez changé vos préférences de langue"
+
+msgid "login failed: you have to fill all fields"
+msgstr "échec de l'identification : vous devez remplir tous les champs"
+
+msgid "welcome to your wallabag"
+msgstr "bienvenue dans votre wallabag"
+
+msgid "login failed: bad login or password"
+msgstr "échec de l'identification : mauvais identifiant ou mot de passe"
+
+msgid "Untitled - Import - "
+msgstr "Sans titre - Importer - "
+
+msgid "click to finish import"
+msgstr "cliquez pour terminer l'importation"
+
+msgid "Articles inserted: "
+msgstr "Articles ajoutés : "
+
+msgid ". Please note, that some may be marked as \"read\"."
+msgstr ". Notez que certains pourraient être marqués comme \"lus\"."
+
+msgid "Import finished."
+msgstr "Importation terminée."
+
+msgid "Undefined"
+msgstr "Non défini"
+
+msgid "User with this id ("
+msgstr "Utilisateur avec cet identifiant ("
+
+msgid "Uh, there is a problem while generating feeds."
+msgstr "Hum, il y a un problème lors de la génération des flux."
+
+msgid "Cache deleted."
+msgstr "Cache effacé."
+
+msgid "Oops, it seems you don't have PHP 5."
+msgstr "Oups, vous ne semblez pas avoir PHP 5."
index 429d5d55801b398efbb267694de558e734871016..41cc01e016fb0eab5b7450bc98d59c57f51b043a 100644 (file)
 msgid ""
 msgstr ""
 "Project-Id-Version: poche\n"
-"POT-Creation-Date: \n"
-"PO-Revision-Date: 2013-11-25 09:47+0100\n"
-"Last-Translator: Nicolas Lœuillet <nicolas.loeuillet@gmail.com>\n"
-"Language-Team: Italian (http://www.transifex.com/projects/p/poche/language/"
-"it/)\n"
+"Report-Msgid-Bugs-To: \n"
+"POT-Creation-Date: 2014-02-25 15:13+0300\n"
+"PO-Revision-Date: 2014-02-25 15:13+0300\n"
+"Last-Translator: Maryana <mariroz@mr.lviv.ua>\n"
+"Language-Team: Italian (http://www.transifex.com/projects/p/poche/language/it/)\n"
+"Language: it\n"
 "MIME-Version: 1.0\n"
 "Content-Type: text/plain; charset=UTF-8\n"
 "Content-Transfer-Encoding: 8bit\n"
-"Language: it\n"
 "Plural-Forms: nplurals=2; plural=(n != 1);\n"
 "X-Generator: Poedit 1.5.4\n"
+"X-Poedit-Language: Italian\n"
+"X-Poedit-Country: ITALY\n"
+"X-Poedit-Basepath: .\n"
+"X-Poedit-SearchPath-0: /home/mariroz/_DEV/web/wallabag/wallabag-master-testing\n"
+
+msgid "wallabag, a read it later open source system"
+msgstr ""
+
+msgid "login failed: user doesn't exist"
+msgstr ""
+
+msgid "return home"
+msgstr ""
 
 msgid "config"
 msgstr "configurazione"
 
-msgid "Poching a link"
-msgstr "Pochare un link"
+msgid "Saving articles"
+msgstr ""
+
+msgid "There are several ways to save an article:"
+msgstr ""
 
 msgid "read the documentation"
 msgstr "leggi la documentazione"
 
-msgid "by filling this field"
+msgid "download the extension"
+msgstr ""
+
+msgid "via F-Droid"
+msgstr ""
+
+msgid " or "
+msgstr ""
+
+msgid "via Google Play"
+msgstr ""
+
+msgid "download the application"
+msgstr ""
+
+#, fuzzy
+msgid "By filling this field"
 msgstr "compilando questo campo"
 
-msgid "poche it!"
-msgstr "pochalo!"
+msgid "bag it!"
+msgstr ""
 
-msgid "Updating poche"
-msgstr "Aggiornamento poche"
+msgid "Bookmarklet: drag & drop this link to your bookmarks bar"
+msgstr ""
 
-msgid "your version"
-msgstr "la tua versione"
+msgid "Upgrading wallabag"
+msgstr ""
 
-msgid "latest stable version"
+#, fuzzy
+msgid "Installed version"
 msgstr "ultima versione stabile"
 
-msgid "a more recent stable version is available."
+#, fuzzy
+msgid "Latest stable version"
+msgstr "ultima versione stabile"
+
+#, fuzzy
+msgid "A more recent stable version is available."
 msgstr "è disponibile una versione stabile più recente."
 
-msgid "you are up to date."
+#, fuzzy
+msgid "You are up to date."
 msgstr "sei aggiornato."
 
-msgid "latest dev version"
+#, fuzzy
+msgid "Latest dev version"
 msgstr "ultima versione di sviluppo"
 
-msgid "a more recent development version is available."
+#, fuzzy
+msgid "A more recent development version is available."
 msgstr "è disponibile una versione di sviluppo più recente."
 
+msgid "Feeds"
+msgstr ""
+
+msgid "Your feed token is currently empty and must first be generated to enable feeds. Click <a href='?feed&amp;action=generate'>here to generate it</a>."
+msgstr ""
+
+msgid "Unread feed"
+msgstr ""
+
+#, fuzzy
+msgid "Favorites feed"
+msgstr "preferiti"
+
+#, fuzzy
+msgid "Archive feed"
+msgstr "archivio"
+
+msgid "Your token:"
+msgstr ""
+
+msgid "Your user id:"
+msgstr ""
+
+msgid "You can regenerate your token: <a href='?feed&amp;action=generate'>generate!</a>."
+msgstr ""
+
+#, fuzzy
+msgid "Change your theme"
+msgstr "Cambia la tua password"
+
+msgid "Theme:"
+msgstr ""
+
+msgid "Update"
+msgstr "Aggiorna"
+
+#, fuzzy
+msgid "Change your language"
+msgstr "Cambia la tua password"
+
+msgid "Language:"
+msgstr ""
+
 msgid "Change your password"
 msgstr "Cambia la tua password"
 
@@ -64,67 +148,68 @@ msgstr "Password"
 msgid "Repeat your new password:"
 msgstr "Ripeti la nuova password:"
 
-msgid "Update"
-msgstr "Aggiorna"
-
 msgid "Import"
 msgstr "Importa"
 
-msgid "Please execute the import script locally, it can take a very long time."
-msgstr ""
-"Si prega di eseguire lo script di importazione a livello locale, può "
-"richiedere un tempo molto lungo."
+#, fuzzy
+msgid "Please execute the import script locally as it can take a very long time."
+msgstr "Si prega di eseguire lo script di importazione a livello locale, può richiedere un tempo molto lungo."
 
-msgid "More info in the official doc:"
+#, fuzzy
+msgid "More info in the official documentation:"
 msgstr "Maggiori info nella documentazione ufficiale"
 
-msgid "import from Pocket"
+#, fuzzy
+msgid "Import from Pocket"
 msgstr "Importa da Pocket"
 
-msgid "import from Readability"
+#, php-format
+msgid "(you must have a %s file on your server)"
+msgstr ""
+
+#, fuzzy
+msgid "Import from Readability"
 msgstr "Importa da Readability"
 
-msgid "import from Instapaper"
+#, fuzzy
+msgid "Import from Instapaper"
 msgstr "Importa da Instapaper"
 
-msgid "Export your poche data"
+#, fuzzy
+msgid "Import from wallabag"
+msgstr "Importa da Readability"
+
+#, fuzzy
+msgid "Export your wallabag data"
 msgstr "Esporta i tuoi dati di poche"
 
 msgid "Click here"
 msgstr "Fai clic qui"
 
-msgid "to export your poche data."
-msgstr "per esportare i tuoi dati di poche."
-
-msgid "back to home"
-msgstr "torna alla home"
+msgid "to download your database."
+msgstr ""
 
-msgid "installation"
-msgstr "installazione"
+#, fuzzy
+msgid "to export your wallabag data."
+msgstr "per esportare i tuoi dati di poche."
 
-msgid "install your poche"
-msgstr "installa il tuo poche"
+msgid "Cache"
+msgstr ""
 
-msgid ""
-"poche is still not installed. Please fill the below form to install it. "
-"Don't hesitate to <a href='http://doc.inthepoche.com'>read the documentation "
-"on poche website</a>."
+msgid "to delete cache."
 msgstr ""
-"poche non è ancora installato. Si prega di riempire il modulo sottostante "
-"per completare l'installazione. <a href='http://doc.inthepoche.com'>Leggere "
-"la documentazione sul sito di poche</a>."
 
-msgid "Login"
-msgstr "Nome utente"
+msgid "You can enter multiple tags, separated by commas."
+msgstr ""
 
-msgid "Repeat your password"
-msgstr "Ripeti la tua password"
+msgid "return to article"
+msgstr ""
 
-msgid "Install"
-msgstr "Installa"
+msgid "plop"
+msgstr "plop"
 
-msgid "back to top"
-msgstr "torna a inizio pagina"
+msgid "You can <a href='wallabag_compatibility_test.php'>check your configuration here</a>."
+msgstr ""
 
 msgid "favoris"
 msgstr "preferiti"
@@ -153,10 +238,14 @@ msgstr "per titolo"
 msgid "by title desc"
 msgstr "per titolo decr"
 
-msgid "No link available here!"
-msgstr "Nessun link disponibile!"
+msgid "Tag"
+msgstr ""
 
-msgid "toggle mark as read"
+msgid "No articles found."
+msgstr ""
+
+#, fuzzy
+msgid "Toggle mark as read"
 msgstr "segna come letto / non letto"
 
 msgid "toggle favorite"
@@ -168,13 +257,95 @@ msgstr "elimina"
 msgid "original"
 msgstr "originale"
 
+msgid "estimated reading time:"
+msgstr ""
+
+msgid "mark all the entries as read"
+msgstr ""
+
 msgid "results"
 msgstr "risultati"
 
-msgid "tweet"
+msgid "installation"
+msgstr "installazione"
+
+#, fuzzy
+msgid "install your wallabag"
+msgstr "installa il tuo poche"
+
+#, fuzzy
+msgid "wallabag is still not installed. Please fill the below form to install it. Don't hesitate to <a href='http://doc.wallabag.org/'>read the documentation on wallabag website</a>."
+msgstr "poche non è ancora installato. Si prega di riempire il modulo sottostante per completare l'installazione. <a href='http://doc.inthepoche.com'>Leggere la documentazione sul sito di poche</a>."
+
+msgid "Login"
+msgstr "Nome utente"
+
+msgid "Repeat your password"
+msgstr "Ripeti la tua password"
+
+msgid "Install"
+msgstr "Installa"
+
+#, fuzzy
+msgid "login to your wallabag"
+msgstr "accedi al tuo poche"
+
+msgid "Login to wallabag"
+msgstr ""
+
+msgid "you are in demo mode, some features may be disabled."
+msgstr "sei in modalità dimostrazione, alcune funzionalità potrebbero essere disattivate."
+
+msgid "Username"
+msgstr ""
+
+msgid "Stay signed in"
+msgstr "Resta connesso"
+
+msgid "(Do not check on public computers)"
+msgstr "(non selezionare su computer pubblici)"
+
+msgid "Sign in"
+msgstr "Accedi"
+
+msgid "favorites"
+msgstr "preferiti"
+
+msgid "estimated reading time :"
+msgstr ""
+
+msgid "Mark all the entries as read"
+msgstr ""
+
+msgid "Return home"
+msgstr ""
+
+#, fuzzy
+msgid "Back to top"
+msgstr "torna a inizio pagina"
+
+#, fuzzy
+msgid "Mark as read"
+msgstr "segna come letto / non letto"
+
+#, fuzzy
+msgid "Favorite"
+msgstr "preferiti"
+
+#, fuzzy
+msgid "Toggle favorite"
+msgstr "segna come preferito"
+
+#, fuzzy
+msgid "Delete"
+msgstr "elimina"
+
+#, fuzzy
+msgid "Tweet"
 msgstr "twitta"
 
-msgid "email"
+#, fuzzy
+msgid "Email"
 msgstr "email"
 
 msgid "shaarli"
@@ -183,26 +354,24 @@ msgstr "shaarli"
 msgid "flattr"
 msgstr "flattr"
 
-msgid "this article appears wrong?"
+#, fuzzy
+msgid "Does this article appear wrong?"
 msgstr "articolo non visualizzato correttamente?"
 
-msgid "create an issue"
-msgstr "crea una segnalazione"
-
-msgid "or"
-msgstr "oppure"
+msgid "tags:"
+msgstr ""
 
-msgid "contact us by mail"
-msgstr "contattaci via email"
+msgid "Edit tags"
+msgstr ""
 
-msgid "plop"
-msgstr "plop"
+msgid "save link!"
+msgstr ""
 
 msgid "home"
 msgstr "home"
 
-msgid "favorites"
-msgstr "preferiti"
+msgid "tags"
+msgstr ""
 
 msgid "logout"
 msgstr "esci"
@@ -213,25 +382,187 @@ msgstr "realizzato con"
 msgid "debug mode is on so cache is off."
 msgstr "modalità di debug attiva, cache disattivata."
 
-msgid "your poche version:"
-msgstr "la tua versione di poche:"
+#, fuzzy
+msgid "your wallabag version:"
+msgstr "la tua versione"
 
 msgid "storage:"
 msgstr "memoria:"
 
-msgid "login to your poche"
-msgstr "accedi al tuo poche"
+msgid "save a link"
+msgstr ""
 
-msgid "you are in demo mode, some features may be disabled."
+msgid "back to home"
+msgstr "torna alla home"
+
+msgid "toggle mark as read"
+msgstr "segna come letto / non letto"
+
+msgid "tweet"
+msgstr "twitta"
+
+msgid "email"
+msgstr "email"
+
+msgid "this article appears wrong?"
+msgstr "articolo non visualizzato correttamente?"
+
+msgid "No link available here!"
+msgstr "Nessun link disponibile!"
+
+msgid "Poching a link"
+msgstr "Pochare un link"
+
+msgid "by filling this field"
+msgstr "compilando questo campo"
+
+msgid "bookmarklet: drag & drop this link to your bookmarks bar"
 msgstr ""
-"sei in modalità dimostrazione, alcune funzionalità potrebbero essere "
-"disattivate."
 
-msgid "Stay signed in"
-msgstr "Resta connesso"
+msgid "your version"
+msgstr "la tua versione"
 
-msgid "(Do not check on public computers)"
-msgstr "(non selezionare su computer pubblici)"
+msgid "latest stable version"
+msgstr "ultima versione stabile"
 
-msgid "Sign in"
-msgstr "Accedi"
+msgid "a more recent stable version is available."
+msgstr "è disponibile una versione stabile più recente."
+
+msgid "you are up to date."
+msgstr "sei aggiornato."
+
+msgid "latest dev version"
+msgstr "ultima versione di sviluppo"
+
+msgid "a more recent development version is available."
+msgstr "è disponibile una versione di sviluppo più recente."
+
+msgid "Please execute the import script locally, it can take a very long time."
+msgstr "Si prega di eseguire lo script di importazione a livello locale, può richiedere un tempo molto lungo."
+
+#, fuzzy
+msgid "More infos in the official doc:"
+msgstr "Maggiori info nella documentazione ufficiale"
+
+msgid "import from Pocket"
+msgstr "Importa da Pocket"
+
+msgid "import from Readability"
+msgstr "Importa da Readability"
+
+msgid "import from Instapaper"
+msgstr "Importa da Instapaper"
+
+msgid "Tags"
+msgstr ""
+
+#, fuzzy
+msgid "Untitled"
+msgstr "per titolo"
+
+msgid "the link has been added successfully"
+msgstr ""
+
+msgid "error during insertion : the link wasn't added"
+msgstr ""
+
+msgid "the link has been deleted successfully"
+msgstr ""
+
+msgid "the link wasn't deleted"
+msgstr ""
+
+msgid "Article not found!"
+msgstr ""
+
+msgid "previous"
+msgstr ""
+
+msgid "next"
+msgstr ""
+
+msgid "in demo mode, you can't update your password"
+msgstr ""
+
+msgid "your password has been updated"
+msgstr ""
+
+msgid "the two fields have to be filled & the password must be the same in the two fields"
+msgstr ""
+
+msgid "still using the \""
+msgstr ""
+
+msgid "that theme does not seem to be installed"
+msgstr ""
+
+msgid "you have changed your theme preferences"
+msgstr ""
+
+msgid "that language does not seem to be installed"
+msgstr ""
+
+msgid "you have changed your language preferences"
+msgstr ""
+
+msgid "login failed: you have to fill all fields"
+msgstr ""
+
+msgid "welcome to your wallabag"
+msgstr ""
+
+msgid "login failed: bad login or password"
+msgstr ""
+
+#, fuzzy
+msgid "import from instapaper completed"
+msgstr "Importa da Instapaper"
+
+#, fuzzy
+msgid "import from pocket completed"
+msgstr "Importa da Pocket"
+
+#, fuzzy
+msgid "import from Readability completed. "
+msgstr "Importa da Readability"
+
+#, fuzzy
+msgid "import from Poche completed. "
+msgstr "Importa da Pocket"
+
+msgid "Unknown import provider."
+msgstr ""
+
+msgid "Incomplete inc/poche/define.inc.php file, please define \""
+msgstr ""
+
+msgid "Could not find required \""
+msgstr ""
+
+msgid "Uh, there is a problem while generating feeds."
+msgstr ""
+
+#, fuzzy
+msgid "Cache deleted."
+msgstr "elimina"
+
+msgid "Oops, it seems you don't have PHP 5."
+msgstr ""
+
+#~ msgid "poche it!"
+#~ msgstr "pochalo!"
+
+#~ msgid "Updating poche"
+#~ msgstr "Aggiornamento poche"
+
+#~ msgid "create an issue"
+#~ msgstr "crea una segnalazione"
+
+#~ msgid "or"
+#~ msgstr "oppure"
+
+#~ msgid "contact us by mail"
+#~ msgstr "contattaci via email"
+
+#~ msgid "your poche version:"
+#~ msgstr "la tua versione di poche:"
old mode 100755 (executable)
new mode 100644 (file)
diff --git a/locale/pt_BR.utf8/LC_MESSAGES/pt_BR.utf8.mo b/locale/pt_BR.utf8/LC_MESSAGES/pt_BR.utf8.mo
new file mode 100644 (file)
index 0000000..c1ce317
Binary files /dev/null and b/locale/pt_BR.utf8/LC_MESSAGES/pt_BR.utf8.mo differ
diff --git a/locale/pt_BR.utf8/LC_MESSAGES/pt_BR.utf8.po b/locale/pt_BR.utf8/LC_MESSAGES/pt_BR.utf8.po
new file mode 100644 (file)
index 0000000..e145392
--- /dev/null
@@ -0,0 +1,549 @@
+msgid ""
+msgstr ""
+"Project-Id-Version: wallabag\n"
+"Report-Msgid-Bugs-To: \n"
+"POT-Creation-Date: 2014-02-25 15:17+0300\n"
+"PO-Revision-Date: \n"
+"Last-Translator: @iancamporez <ian@camporez.com>\n"
+"Language-Team: @iancamporez <ian@camporez.com>\n"
+"Language: pt_BR\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"X-Generator: Poedit 1.6.4\n"
+"X-Poedit-Basepath: .\n"
+"X-Poedit-SearchPath-0: /home/ian/Projetos/wallabag/locale/en_EN.utf8/"
+"LC_MESSAGES\n"
+
+msgid "wallabag, a read it later open source system"
+msgstr "wallabag, um \"read it later\" de código aberto"
+
+msgid "login failed: user doesn't exist"
+msgstr "falha ao entrar: o usuário não existe"
+
+msgid "return home"
+msgstr "retornar à página inicial"
+
+msgid "config"
+msgstr "configurar"
+
+msgid "Saving articles"
+msgstr "Salvando artigos"
+
+msgid "There are several ways to save an article:"
+msgstr "Existem várias maneiras de salvar um artigo:"
+
+msgid "read the documentation"
+msgstr "ler a documentação"
+
+msgid "download the extension"
+msgstr "baixar a extensão"
+
+msgid "via F-Droid"
+msgstr "via F-Droid"
+
+msgid " or "
+msgstr "ou "
+
+msgid "via Google Play"
+msgstr "via Google Play"
+
+msgid "download the application"
+msgstr "baixar o aplicativo"
+
+msgid "By filling this field"
+msgstr "Preenchendo esse campo"
+
+msgid "bag it!"
+msgstr "adicionar ao wallabag"
+
+msgid "Bookmarklet: drag & drop this link to your bookmarks bar"
+msgstr "Bookmarklet: arraste esse link para sua barra de favoritos"
+
+msgid "Upgrading wallabag"
+msgstr "Atualizando o wallabag"
+
+msgid "Installed version"
+msgstr "Versão instalada"
+
+msgid "Latest stable version"
+msgstr "Última versão estável"
+
+msgid "A more recent stable version is available."
+msgstr "Uma versão estável mais nova está disponível"
+
+msgid "You are up to date."
+msgstr "Você está atualizado."
+
+msgid "Latest dev version"
+msgstr "Última versão em desenvolvimento"
+
+msgid "A more recent development version is available."
+msgstr "Uma versão em desenvolvimento mais recente está disponível"
+
+msgid "Feeds"
+msgstr "Feeds"
+
+msgid ""
+"Your feed token is currently empty and must first be generated to enable "
+"feeds. Click <a href='?feed&amp;action=generate'>here to generate it</a>."
+msgstr ""
+"Seu token do feed e precisa ser gerado para ativar os feeds. Clique <a "
+"href='?feed&amp;action=generate'>aqui para gerar um token</a>."
+
+msgid "Unread feed"
+msgstr "Feed de artigos não lidos"
+
+msgid "Favorites feed"
+msgstr "Feed dos favoritos"
+
+msgid "Archive feed"
+msgstr "Feed de arquivados"
+
+msgid "Your token:"
+msgstr "Seu token:"
+
+msgid "Your user id:"
+msgstr "Seu código de usuário:"
+
+msgid ""
+"You can regenerate your token: <a href='?feed&amp;action=generate'>generate!"
+"</a>."
+msgstr ""
+"Você pode regerar seu token: <a href='?feed&amp;action=generate'>gerar!</a>."
+
+msgid "Change your theme"
+msgstr "Mudar seu tema"
+
+msgid "Theme:"
+msgstr "Tema:"
+
+msgid "Update"
+msgstr "Atualizar"
+
+msgid "Change your language"
+msgstr "Alterar seu idioma"
+
+msgid "Language:"
+msgstr "Idioma:"
+
+msgid "Change your password"
+msgstr "Alterar sua senha"
+
+msgid "New password:"
+msgstr "Nova senha:"
+
+msgid "Password"
+msgstr "Senha"
+
+msgid "Repeat your new password:"
+msgstr "Repetir sua nova senha:"
+
+msgid "Import"
+msgstr "Importar"
+
+msgid ""
+"Please execute the import script locally as it can take a very long time."
+msgstr ""
+"Por favor, execute o script de importação localmente, pois pode demorar "
+"muito tempo."
+
+msgid "More info in the official documentation:"
+msgstr "Mais informações na documentação oficial:"
+
+msgid "Import from Pocket"
+msgstr "Importar do Pocket"
+
+#, php-format
+msgid "(you must have a %s file on your server)"
+msgstr "(você deve ter um arquivo %s no seu servidor)"
+
+msgid "Import from Readability"
+msgstr "Importar do Readability"
+
+msgid "Import from Instapaper"
+msgstr "Importar do Instapaper"
+
+msgid "Import from wallabag"
+msgstr "Importar do wallabag"
+
+msgid "Export your wallabag data"
+msgstr "Exportar seus dados do wallabag"
+
+msgid "Click here"
+msgstr "Clique aqui"
+
+msgid "to download your database."
+msgstr "para baixar seu banco de dados."
+
+msgid "to export your wallabag data."
+msgstr "para exportar seus dados do wallabag."
+
+msgid "Cache"
+msgstr "Cache"
+
+msgid "to delete cache."
+msgstr "para apagar o cache."
+
+msgid "You can enter multiple tags, separated by commas."
+msgstr "Você pode inserir várias tags, separadas por vírgulas."
+
+msgid "return to article"
+msgstr "retornar ao artigo"
+
+msgid "plop"
+msgstr "plop"
+
+msgid ""
+"You can <a href='wallabag_compatibility_test.php'>check your configuration "
+"here</a>."
+msgstr ""
+"Você pode <a href='wallabag_compatibility_test.php'>checar suas "
+"configurações aqui</a>."
+
+msgid "favoris"
+msgstr "favoritos"
+
+msgid "archive"
+msgstr "arquivo"
+
+msgid "unread"
+msgstr "não lidos"
+
+msgid "by date asc"
+msgstr "por data (cresc.)"
+
+msgid "by date"
+msgstr "por data"
+
+msgid "by date desc"
+msgstr "por data (decr.)"
+
+msgid "by title asc"
+msgstr "por título (cresc.)"
+
+msgid "by title"
+msgstr "por título"
+
+msgid "by title desc"
+msgstr "por título (decr.)"
+
+msgid "Tag"
+msgstr "Tag"
+
+msgid "No articles found."
+msgstr "Nenhum artigo encontrado."
+
+msgid "Toggle mark as read"
+msgstr "Alterar \"marcar como lido\""
+
+msgid "toggle favorite"
+msgstr "alterar \"favorito\""
+
+msgid "delete"
+msgstr "deletar"
+
+msgid "original"
+msgstr "original"
+
+msgid "estimated reading time:"
+msgstr "tempo estimado de leitura:"
+
+msgid "mark all the entries as read"
+msgstr "marcar todas as entradas como lidas"
+
+msgid "results"
+msgstr "resultados"
+
+msgid "installation"
+msgstr "instalação"
+
+msgid "install your wallabag"
+msgstr "instalar seu wallabag"
+
+msgid ""
+"wallabag is still not installed. Please fill the below form to install it. "
+"Don't hesitate to <a href='http://doc.wallabag.org/'>read the documentation "
+"on wallabag website</a>."
+msgstr ""
+"O wallabag ainda não está instalado. Preencha o formulário abaixo para "
+"instalá-lo. Não hesite em <a href='http://doc.wallabag.org/'>ler a "
+"documentação no site do wallabag</a>."
+
+msgid "Login"
+msgstr "Login"
+
+msgid "Repeat your password"
+msgstr "Repetir sua senha"
+
+msgid "Install"
+msgstr "Instalar"
+
+msgid "login to your wallabag"
+msgstr "entrar no seu wallabag"
+
+msgid "Login to wallabag"
+msgstr "Entrar no wallabag"
+
+msgid "you are in demo mode, some features may be disabled."
+msgstr "você está no modo demo, alguns recursos podem estar desativados."
+
+msgid "Username"
+msgstr "Nome de usuário"
+
+msgid "Stay signed in"
+msgstr "Continuar conectado"
+
+msgid "(Do not check on public computers)"
+msgstr "(Não marque em computadores públicos)"
+
+msgid "Sign in"
+msgstr "Entrar"
+
+msgid "favorites"
+msgstr "favoritos"
+
+msgid "estimated reading time :"
+msgstr "tempo estimado de leitura :"
+
+msgid "Mark all the entries as read"
+msgstr "Marcar todas as entradas como lidas"
+
+msgid "Return home"
+msgstr "Retornar à página inicial"
+
+msgid "Back to top"
+msgstr "Voltar ao topo"
+
+msgid "Mark as read"
+msgstr "Marcar como lido"
+
+msgid "Favorite"
+msgstr "Favoritar"
+
+msgid "Toggle favorite"
+msgstr "Alterar \"favorito\""
+
+msgid "Delete"
+msgstr "Deletar"
+
+msgid "Tweet"
+msgstr "Tweetar"
+
+msgid "Email"
+msgstr "Email"
+
+msgid "shaarli"
+msgstr "shaarli"
+
+msgid "flattr"
+msgstr "flattr"
+
+msgid "Does this article appear wrong?"
+msgstr "Esse artigo está sendo exibido incorretamente?"
+
+msgid "tags:"
+msgstr "tags:"
+
+msgid "Edit tags"
+msgstr "Editar tags"
+
+msgid "save link!"
+msgstr "salvar link!"
+
+msgid "home"
+msgstr "início"
+
+msgid "tags"
+msgstr "tags"
+
+msgid "logout"
+msgstr "sair"
+
+msgid "powered by"
+msgstr "powered by"
+
+msgid "debug mode is on so cache is off."
+msgstr "o modo debug está ativo, então o cache foi desativado."
+
+msgid "your wallabag version:"
+msgstr "sua versão do wallabag:"
+
+msgid "storage:"
+msgstr "armazenamento:"
+
+msgid "save a link"
+msgstr "salvar link"
+
+msgid "back to home"
+msgstr "voltar à página inicial"
+
+msgid "toggle mark as read"
+msgstr "alterar \"marcar como lido\""
+
+msgid "tweet"
+msgstr "tweetar"
+
+msgid "email"
+msgstr "email"
+
+msgid "this article appears wrong?"
+msgstr "esse artigo está sendo mostrado incorretamente?"
+
+msgid "No link available here!"
+msgstr "Nenhum link disponível aqui!"
+
+msgid "Poching a link"
+msgstr "Pocheando um link"
+
+msgid "by filling this field"
+msgstr "preenchendo esse campo"
+
+msgid "bookmarklet: drag & drop this link to your bookmarks bar"
+msgstr "bookmarklet: arraste esse link para a sua barra de favoritos"
+
+msgid "your version"
+msgstr "sua versão"
+
+msgid "latest stable version"
+msgstr "última versão estável"
+
+msgid "a more recent stable version is available."
+msgstr "uma versão estável mais nova está disponível"
+
+msgid "you are up to date."
+msgstr "você está atualizado."
+
+msgid "latest dev version"
+msgstr "última versão em desenvolvimento"
+
+msgid "a more recent development version is available."
+msgstr "uma versão em desenvolvimento mais nova está disponível"
+
+msgid "Please execute the import script locally, it can take a very long time."
+msgstr ""
+"Por favor, execute o script de importação localmente, pois pode demorar "
+"muito tempo."
+
+msgid "More infos in the official doc:"
+msgstr "Mais informações na documentação oficial:"
+
+msgid "import from Pocket"
+msgstr "importar do Pocket"
+
+msgid "import from Readability"
+msgstr "importar do Readability"
+
+msgid "import from Instapaper"
+msgstr "importar do Instapaper"
+
+msgid "Tags"
+msgstr "Tags"
+
+msgid "Untitled"
+msgstr "Sem título"
+
+msgid "the link has been added successfully"
+msgstr "o link foi adicionado com sucesso"
+
+msgid "error during insertion : the link wasn't added"
+msgstr "erro durante a inserção: o link não foi adicionado"
+
+msgid "the link has been deleted successfully"
+msgstr "o link foi deletado com sucesso"
+
+msgid "the link wasn't deleted"
+msgstr "o link não foi deletado"
+
+msgid "Article not found!"
+msgstr "Artigo não encontrado!"
+
+msgid "previous"
+msgstr "anterior"
+
+msgid "next"
+msgstr "próximo"
+
+msgid "in demo mode, you can't update your password"
+msgstr "você não pode alterar a senha no modo demo"
+
+msgid "your password has been updated"
+msgstr "sua senha foi atualizada"
+
+msgid ""
+"the two fields have to be filled & the password must be the same in the two "
+"fields"
+msgstr ""
+"os dois campos devem estar preenchidos e as senhas devem ser iguais em ambos"
+
+msgid "still using the \""
+msgstr "ainda usando o \""
+
+msgid "that theme does not seem to be installed"
+msgstr "esse tema aparentemente não está instalado"
+
+msgid "you have changed your theme preferences"
+msgstr "você alterou suas preferências de tema"
+
+msgid "that language does not seem to be installed"
+msgstr "esse idioma aparentemente não está instalado"
+
+msgid "you have changed your language preferences"
+msgstr "você alterou suas preferências de idioma"
+
+msgid "login failed: you have to fill all fields"
+msgstr "falha ao entrar: você deve preencher todos os campos"
+
+msgid "welcome to your wallabag"
+msgstr "bem-vindo ao seu wallabag"
+
+msgid "login failed: bad login or password"
+msgstr "falha ao entrar: login ou senha incorretos"
+
+msgid "import from instapaper completed"
+msgstr "importação do instapaper completa"
+
+msgid "import from pocket completed"
+msgstr "importação do pocket completa"
+
+msgid "import from Readability completed. "
+msgstr "importação do Readability completa. "
+
+msgid "import from Poche completed. "
+msgstr "importação do Poche completa. "
+
+msgid "Unknown import provider."
+msgstr "Serviço de importação desconhecido."
+
+msgid "Incomplete inc/poche/define.inc.php file, please define \""
+msgstr "Arquivo inc/poche/define.inc.php incompleto, por favor defina \""
+
+msgid "Could not find required \""
+msgstr "Não foi possível encontrar o requerido \""
+
+msgid "Uh, there is a problem while generating feeds."
+msgstr "Uh, houve um problema ao gerar os feeds."
+
+msgid "Cache deleted."
+msgstr "Cache deletado."
+
+msgid "Oops, it seems you don't have PHP 5."
+msgstr "Oops, parece que você não tem o PHP 5."
+
+#~ msgid "poche it!"
+#~ msgstr "poche it!"
+
+#~ msgid "Updating poche"
+#~ msgstr "Updating poche"
+
+#~ msgid "create an issue"
+#~ msgstr "create an issue"
+
+#~ msgid "or"
+#~ msgstr "or"
+
+#~ msgid "contact us by mail"
+#~ msgstr "contact us by mail"
+
+#~ msgid "your poche version:"
+#~ msgstr "your poche version:"
index c9cf1a559907a912667bd1153854cb4e9cc8e28e..5cbfad164299132aadc7ff72992bba203b8df993 100755 (executable)
Binary files a/locale/ru_RU.utf8/LC_MESSAGES/ru_RU.utf8.mo and b/locale/ru_RU.utf8/LC_MESSAGES/ru_RU.utf8.mo differ
index aa1769cfcb5a46162590c033d928e87d205908d0..08f12b7cfdc5fc37e281eea18c49cfcc8bfbf6d2 100755 (executable)
@@ -2,7 +2,7 @@ msgid ""
 msgstr ""
 "Project-Id-Version: \n"
 "Report-Msgid-Bugs-To: \n"
-"POT-Creation-Date: 2014-02-07 12:40+0300\n"
+"POT-Creation-Date: 2014-02-25 15:09+0300\n"
 "PO-Revision-Date: \n"
 "Last-Translator: Maryana <mariroz@mr.lviv.ua>\n"
 "Language-Team: \n"
@@ -14,135 +14,25 @@ msgstr ""
 "X-Poedit-Language: Russian\n"
 "X-Poedit-Country: RUSSIA\n"
 "X-Poedit-SourceCharset: utf-8\n"
-"X-Poedit-SearchPath-0: /home/mariroz/_DEV/web/wallabag/wallabag\n"
+"X-Poedit-SearchPath-0: /home/mariroz/_DEV/web/wallabag/wallabag-master-testing\n"
 
-msgid "poche, a read it later open source system"
-msgstr "poche, сервис отложенного чтения с открытым исходным кодом"
+msgid "wallabag, a read it later open source system"
+msgstr "wallabag, сервис отложенного чтения с открытым исходным кодом"
 
 msgid "login failed: user doesn't exist"
 msgstr "войти не удалось: пользователь не существует"
 
-msgid "Return home"
-msgstr "На главную"
-
-msgid "Back to top"
-msgstr "Наверх"
-
-msgid "original"
-msgstr "источник"
-
-msgid "Mark as read"
-msgstr "Отметить как прочитанное"
-
-msgid "Toggle mark as read"
-msgstr "Изменить отметку 'прочитано'"
-
-msgid "Favorite"
-msgstr "Избранное"
-
-msgid "Toggle favorite"
-msgstr "Изменить метку избранного"
-
-msgid "Delete"
-msgstr "Удалить"
-
-msgid "Tweet"
-msgstr "Твитнуть"
-
-msgid "Email"
-msgstr "Отправить по почте"
-
-msgid "shaarli"
-msgstr "shaarli"
-
-msgid "flattr"
-msgstr "проспонсировать"
-
-msgid "Does this article appear wrong?"
-msgstr "Статья выглядит криво?"
-
-msgid "tags:"
-msgstr "теги:"
-
-msgid "Edit tags"
-msgstr "Редактировать теги"
-
 msgid "return home"
 msgstr "на главную"
 
-msgid "powered by"
-msgstr "при поддержке"
-
-msgid "debug mode is on so cache is off."
-msgstr "включён режим отладки - кеш выключен."
-
-msgid "your poche version:"
-msgstr "ваша версия poche:"
-
-msgid "storage:"
-msgstr "хранилище:"
-
-msgid "favoris"
-msgstr "избранное"
-
-msgid "archive"
-msgstr "архив"
-
-msgid "unread"
-msgstr "непрочитанное"
-
-msgid "by date asc"
-msgstr "по дате, сперва старые"
-
-msgid "by date"
-msgstr "по дате"
-
-msgid "by date desc"
-msgstr "по дате, сперва новые"
-
-msgid "by title asc"
-msgstr "по заголовку (прямой)"
-
-msgid "by title"
-msgstr "по заголовку"
-
-msgid "by title desc"
-msgstr "по заголовку (обратный)"
-
-msgid "No articles found."
-msgstr "Статей не найдено."
-
-msgid "toggle favorite"
-msgstr "изменить метку избранного"
-
-msgid "delete"
-msgstr "удалить"
-
-msgid "estimated reading time:"
-msgstr "ориентировочное время чтения:"
-
-msgid "results"
-msgstr "найдено"
-
-msgid "home"
-msgstr "главная"
-
-msgid "favorites"
-msgstr "избранное"
-
-msgid "tags"
-msgstr "теги"
-
 msgid "config"
 msgstr "настройки"
 
-msgid "logout"
-msgstr "выход"
-
-msgid "Poching links"
-msgstr "Сохранение ссылок"
+msgid "Saving articles"
+msgstr "Сохранение статей"
 
-msgid "There are several ways to poche a link:"
+#, fuzzy
+msgid "There are several ways to save an article:"
 msgstr "Существует несколько способов сохранить ссылку:"
 
 msgid "read the documentation"
@@ -166,14 +56,14 @@ msgstr "скачать приложение"
 msgid "By filling this field"
 msgstr "Заполнением этого поля"
 
-msgid "poche it!"
+msgid "bag it!"
 msgstr "прикарманить!"
 
 msgid "Bookmarklet: drag & drop this link to your bookmarks bar"
 msgstr "Закладка: перетащите и опустите ссылку на панель закладок"
 
-msgid "Updating poche"
-msgstr "Обновления poche"
+msgid "Upgrading wallabag"
+msgstr "Обновление wallabag"
 
 msgid "Installed version"
 msgstr "Установленная версия"
@@ -187,15 +77,14 @@ msgstr "Доступна новая стабильная версия."
 msgid "You are up to date."
 msgstr "У вас всё самое новое."
 
-msgid "latest dev version"
+#, fuzzy
+msgid "Latest dev version"
 msgstr "последняя версия в разработке"
 
-msgid "a more recent development version is available."
+#, fuzzy
+msgid "A more recent development version is available."
 msgstr "есть более свежая версия в разработке."
 
-msgid "you are up to date."
-msgstr "у вас всё самое новое."
-
 msgid "Feeds"
 msgstr "Ленты (feeds)"
 
@@ -253,7 +142,8 @@ msgstr "Импортировать"
 msgid "Please execute the import script locally as it can take a very long time."
 msgstr "Пожалуйста, выполните сценарий импорта локально - это может занять слишком много времени."
 
-msgid "More info in the official docs:"
+#, fuzzy
+msgid "More info in the official documentation:"
 msgstr "Больше сведений в официальной документации:"
 
 msgid "Import from Pocket"
@@ -269,11 +159,11 @@ msgstr "Импортировать из Readability"
 msgid "Import from Instapaper"
 msgstr "Импортировать из Instapaper"
 
-msgid "Import from poche"
-msgstr "Импортировать из poche"
+msgid "Import from wallabag"
+msgstr "Импортировать из wallabag"
 
-msgid "Export your poche data"
-msgstr "Экспортировать данные poche"
+msgid "Export your wallabag data"
+msgstr "Экспортировать данные wallabag"
 
 msgid "Click here"
 msgstr "Кликните здесь"
@@ -281,17 +171,14 @@ msgstr "Кликните здесь"
 msgid "to download your database."
 msgstr "чтобы скачать вашу базу данных"
 
-msgid "to export your poche data."
-msgstr "чтобы экспортировать свои записи из poche."
+msgid "to export your wallabag data."
+msgstr "чтобы экспортировать свои записи из wallabag."
 
-msgid "Tag"
-msgstr "Тег"
-
-msgid "No link available here!"
-msgstr "Здесь нет ссылки!"
+msgid "Cache"
+msgstr "Кэш"
 
-msgid "toggle mark as read"
-msgstr "изменить отметку 'прочитано'"
+msgid "to delete cache."
+msgstr "чтобы сбросить кэш."
 
 msgid "You can enter multiple tags, separated by commas."
 msgstr "Вы можете ввести несколько тегов, разделяя их запятой."
@@ -305,6 +192,60 @@ msgstr "plop"
 msgid "You can <a href='wallabag_compatibility_test.php'>check your configuration here</a>."
 msgstr "Вы можете <a href='wallabag_compatibility_test.php'>проверить конфигурацию здесь</a>."
 
+msgid "favoris"
+msgstr "избранное"
+
+msgid "archive"
+msgstr "архив"
+
+msgid "unread"
+msgstr "непрочитанное"
+
+msgid "by date asc"
+msgstr "по дате, сперва старые"
+
+msgid "by date"
+msgstr "по дате"
+
+msgid "by date desc"
+msgstr "по дате, сперва новые"
+
+msgid "by title asc"
+msgstr "по заголовку (прямой)"
+
+msgid "by title"
+msgstr "по заголовку"
+
+msgid "by title desc"
+msgstr "по заголовку (обратный)"
+
+msgid "Tag"
+msgstr "Тег"
+
+msgid "No articles found."
+msgstr "Статей не найдено."
+
+msgid "Toggle mark as read"
+msgstr "Изменить отметку 'прочитано'"
+
+msgid "toggle favorite"
+msgstr "изменить метку избранного"
+
+msgid "delete"
+msgstr "удалить"
+
+msgid "original"
+msgstr "источник"
+
+msgid "estimated reading time:"
+msgstr "ориентировочное время чтения:"
+
+msgid "mark all the entries as read"
+msgstr "отметить все статьи как прочитанные "
+
+msgid "results"
+msgstr "найдено"
+
 msgid "installation"
 msgstr "установка"
 
@@ -341,6 +282,159 @@ msgstr "Запомнить меня"
 msgid "(Do not check on public computers)"
 msgstr "(Не отмечайте на чужих компьютерах)"
 
+msgid "Sign in"
+msgstr "Зарегистрироваться"
+
+msgid "favorites"
+msgstr "избранное"
+
+#, fuzzy
+msgid "estimated reading time :"
+msgstr "ориентировочное время чтения:"
+
+msgid "Mark all the entries as read"
+msgstr "Отметить все как прочитанное"
+
+msgid "Return home"
+msgstr "На главную"
+
+msgid "Back to top"
+msgstr "Наверх"
+
+msgid "Mark as read"
+msgstr "Отметить как прочитанное"
+
+msgid "Favorite"
+msgstr "Избранное"
+
+msgid "Toggle favorite"
+msgstr "Изменить метку избранного"
+
+msgid "Delete"
+msgstr "Удалить"
+
+msgid "Tweet"
+msgstr "Твитнуть"
+
+msgid "Email"
+msgstr "Отправить по почте"
+
+msgid "shaarli"
+msgstr "shaarli"
+
+msgid "flattr"
+msgstr "проспонсировать"
+
+msgid "Does this article appear wrong?"
+msgstr "Статья выглядит криво?"
+
+msgid "tags:"
+msgstr "теги:"
+
+msgid "Edit tags"
+msgstr "Редактировать теги"
+
+msgid "save link!"
+msgstr "сохранить ссылку!"
+
+msgid "home"
+msgstr "главная"
+
+msgid "tags"
+msgstr "теги"
+
+msgid "logout"
+msgstr "выход"
+
+msgid "powered by"
+msgstr "при поддержке"
+
+msgid "debug mode is on so cache is off."
+msgstr "включён режим отладки - кеш выключен."
+
+msgid "your wallabag version:"
+msgstr "Ваша версия wallabag:"
+
+msgid "storage:"
+msgstr "хранилище:"
+
+msgid "save a link"
+msgstr "сохранить ссылку"
+
+msgid "back to home"
+msgstr "домой"
+
+msgid "toggle mark as read"
+msgstr "изменить отметку 'прочитано'"
+
+msgid "tweet"
+msgstr "твитнуть"
+
+msgid "email"
+msgstr "email"
+
+#, fuzzy
+msgid "this article appears wrong?"
+msgstr "Статья выглядит криво?"
+
+msgid "No link available here!"
+msgstr "Здесь нет ссылки!"
+
+#, fuzzy
+msgid "Poching a link"
+msgstr "Сохранение ссылок"
+
+#, fuzzy
+msgid "by filling this field"
+msgstr "Заполнением этого поля"
+
+#, fuzzy
+msgid "bookmarklet: drag & drop this link to your bookmarks bar"
+msgstr "Закладка: перетащите и опустите ссылку на панель закладок"
+
+msgid "your version"
+msgstr "Ваша версия"
+
+#, fuzzy
+msgid "latest stable version"
+msgstr "Последняя стабильная версия"
+
+#, fuzzy
+msgid "a more recent stable version is available."
+msgstr "Доступна новая стабильная версия."
+
+msgid "you are up to date."
+msgstr "у вас всё самое новое."
+
+msgid "latest dev version"
+msgstr "последняя версия в разработке"
+
+msgid "a more recent development version is available."
+msgstr "есть более свежая версия в разработке."
+
+#, fuzzy
+msgid "Please execute the import script locally, it can take a very long time."
+msgstr "Пожалуйста, выполните сценарий импорта локально - это может занять слишком много времени."
+
+#, fuzzy
+msgid "More infos in the official doc:"
+msgstr "Больше сведений в официальной документации:"
+
+#, fuzzy
+msgid "import from Pocket"
+msgstr "Импортировать из Pocket"
+
+#, fuzzy
+msgid "import from Readability"
+msgstr "Импортировать из Readability"
+
+#, fuzzy
+msgid "import from Instapaper"
+msgstr "Импортировать из Instapaper"
+
+msgid "Tags"
+msgstr "Теги"
+
 msgid "Untitled"
 msgstr "Без названия"
 
@@ -356,6 +450,9 @@ msgstr "ссылка успешно удалена"
 msgid "the link wasn't deleted"
 msgstr "ссылка не удалена"
 
+msgid "Article not found!"
+msgstr "Статью не найдено."
+
 msgid "previous"
 msgstr "предыдущая"
 
@@ -389,15 +486,12 @@ msgstr "вы изменили свои настройки языка"
 msgid "login failed: you have to fill all fields"
 msgstr "войти не удалось: вы должны заполнить все поля"
 
-msgid "welcome to your poche"
-msgstr "добро пожаловать в ваш poche"
+msgid "welcome to your wallabag"
+msgstr "добро пожаловать в wallabag"
 
 msgid "login failed: bad login or password"
 msgstr "войти не удалось: неправильное имя пользователя или пароль"
 
-msgid "see you soon!"
-msgstr "увидимся!"
-
 msgid "import from instapaper completed"
 msgstr "импорт из instapaper завершен"
 
@@ -422,14 +516,40 @@ msgstr "Не удалось найти требуемый \""
 msgid "Uh, there is a problem while generating feeds."
 msgstr "Ох, возникла проблема при создании ленты."
 
+msgid "Cache deleted."
+msgstr "Кэш очищен. "
+
 msgid "Oops, it seems you don't have PHP 5."
 msgstr "Упс, кажется у вас не установлен PHP 5."
 
-#~ msgid "your version"
-#~ msgstr "Ваша версия"
+#~ msgid "You can poche a link by several methods:"
+#~ msgstr "Вы можете сохранить ссылку несколькими путями:"
+
+#~ msgid "poche it!"
+#~ msgstr "прикарманить!"
+
+#~ msgid "Updating poche"
+#~ msgstr "Обновления poche"
+
+#, fuzzy
+#~ msgid "Export your poche datas"
+#~ msgstr "Экспортировать данные poche"
+
+#, fuzzy
+#~ msgid "to export your poche datas."
+#~ msgstr "чтобы экспортировать свои записи из poche."
 
-#~ msgid "back to home"
-#~ msgstr "домой"
+#~ msgid "your poche version:"
+#~ msgstr "ваша версия poche:"
+
+#~ msgid "Import from poche"
+#~ msgstr "Импортировать из poche"
+
+#~ msgid "welcome to your poche"
+#~ msgstr "добро пожаловать в ваш poche"
+
+#~ msgid "see you soon!"
+#~ msgstr "увидимся!"
 
 #~ msgid "create an issue"
 #~ msgstr "оповестить об ошибке"
@@ -439,6 +559,3 @@ msgstr "Упс, кажется у вас не установлен PHP 5."
 
 #~ msgid "contact us by mail"
 #~ msgstr "связаться по почте"
-
-#~ msgid "Sign in"
-#~ msgstr "Зарегистрироваться"
index 6eac8e018723f76e07666b95ab4fe74753736171..8ad2ededc2145c3b66b595dbb4af16216b47414b 100644 (file)
 msgid ""
 msgstr ""
 "Project-Id-Version: wallabag\n"
-"POT-Creation-Date: \n"
-"PO-Revision-Date: 2014-02-21 15:09+0100\n"
-"Last-Translator: Nicolas Lœuillet <nicolas.loeuillet@gmail.com>\n"
-"Language-Team: Slovenian (Slovenia) (http://www.transifex.com/projects/p/"
-"wallabag/language/sl_SI/)\n"
+"Report-Msgid-Bugs-To: \n"
+"POT-Creation-Date: 2014-02-25 15:12+0300\n"
+"PO-Revision-Date: 2014-02-25 15:12+0300\n"
+"Last-Translator: Maryana <mariroz@mr.lviv.ua>\n"
+"Language-Team: Slovenian (Slovenia) (http://www.transifex.com/projects/p/wallabag/language/sl_SI/)\n"
+"Language: sl_SI\n"
 "MIME-Version: 1.0\n"
 "Content-Type: text/plain; charset=UTF-8\n"
 "Content-Transfer-Encoding: 8bit\n"
-"Language: sl_SI\n"
-"Plural-Forms: nplurals=4; plural=(n%100==1 ? 0 : n%100==2 ? 1 : n%100==3 || n"
-"%100==4 ? 2 : 3);\n"
+"Plural-Forms: nplurals=4; plural=(n%100==1 ? 0 : n%100==2 ? 1 : n%100==3 || n%100==4 ? 2 : 3);\n"
 "X-Generator: Poedit 1.5.4\n"
+"X-Poedit-Language: Slovenian\n"
+"X-Poedit-Country: SLOVENIA\n"
+"X-Poedit-Basepath: .\n"
+"X-Poedit-SearchPath-0: /home/mariroz/_DEV/web/wallabag/wallabag-master-testing\n"
+
+msgid "wallabag, a read it later open source system"
+msgstr ""
+
+msgid "login failed: user doesn't exist"
+msgstr ""
+
+msgid "return home"
+msgstr ""
 
 msgid "config"
 msgstr "nastavitve"
 
-msgid "Poching a link"
-msgstr "Shrani povezavo"
+msgid "Saving articles"
+msgstr ""
+
+msgid "There are several ways to save an article:"
+msgstr ""
 
 msgid "read the documentation"
 msgstr "preberite dokumentacijo"
 
-msgid "by filling this field"
+msgid "download the extension"
+msgstr ""
+
+msgid "via F-Droid"
+msgstr ""
+
+msgid " or "
+msgstr ""
+
+msgid "via Google Play"
+msgstr ""
+
+msgid "download the application"
+msgstr ""
+
+#, fuzzy
+msgid "By filling this field"
 msgstr "z vnosom v to polje"
 
-msgid "poche it!"
-msgstr "shrani!"
+msgid "bag it!"
+msgstr ""
 
-msgid "Updating poche"
-msgstr "Posodabljam Poche"
+msgid "Bookmarklet: drag & drop this link to your bookmarks bar"
+msgstr ""
 
-msgid "your version"
-msgstr "vaša različica"
+msgid "Upgrading wallabag"
+msgstr ""
 
-msgid "latest stable version"
+#, fuzzy
+msgid "Installed version"
 msgstr "zadnja stabilna različica"
 
-msgid "a more recent stable version is available."
+#, fuzzy
+msgid "Latest stable version"
+msgstr "zadnja stabilna različica"
+
+#, fuzzy
+msgid "A more recent stable version is available."
 msgstr "na voljo je nova stabilna različica."
 
-msgid "you are up to date."
+#, fuzzy
+msgid "You are up to date."
 msgstr "imate najnovejšo različico."
 
-msgid "latest dev version"
+#, fuzzy
+msgid "Latest dev version"
 msgstr "zadnja razvojna različica"
 
-msgid "a more recent development version is available."
+#, fuzzy
+msgid "A more recent development version is available."
 msgstr "na voljo je nova razvojna različica."
 
+msgid "Feeds"
+msgstr ""
+
+msgid "Your feed token is currently empty and must first be generated to enable feeds. Click <a href='?feed&amp;action=generate'>here to generate it</a>."
+msgstr ""
+
+msgid "Unread feed"
+msgstr ""
+
+#, fuzzy
+msgid "Favorites feed"
+msgstr "priljubljeni"
+
+#, fuzzy
+msgid "Archive feed"
+msgstr "arhiv"
+
+msgid "Your token:"
+msgstr ""
+
+msgid "Your user id:"
+msgstr ""
+
+msgid "You can regenerate your token: <a href='?feed&amp;action=generate'>generate!</a>."
+msgstr ""
+
+#, fuzzy
+msgid "Change your theme"
+msgstr "Zamenjava gesla"
+
+msgid "Theme:"
+msgstr ""
+
+msgid "Update"
+msgstr "Posodobi"
+
+#, fuzzy
+msgid "Change your language"
+msgstr "Zamenjava gesla"
+
+msgid "Language:"
+msgstr ""
+
 msgid "Change your password"
 msgstr "Zamenjava gesla"
 
@@ -65,67 +148,69 @@ msgstr "Geslo"
 msgid "Repeat your new password:"
 msgstr "Ponovite novo geslo:"
 
-msgid "Update"
-msgstr "Posodobi"
-
 msgid "Import"
 msgstr "Uvozi"
 
-msgid "Please execute the import script locally, it can take a very long time."
-msgstr ""
-"Prosimo poženite skripto za uvoz lokalno, saj lahko postopek traja precej "
-"časa."
+#, fuzzy
+msgid "Please execute the import script locally as it can take a very long time."
+msgstr "Prosimo poženite skripto za uvoz lokalno, saj lahko postopek traja precej časa."
 
-msgid "More infos in the official doc:"
+#, fuzzy
+msgid "More info in the official documentation:"
 msgstr "Več informacij v uradni dokumentaciji:"
 
-msgid "import from Pocket"
+#, fuzzy
+msgid "Import from Pocket"
 msgstr "Uvoz iz aplikacije Pocket"
 
-msgid "import from Readability"
+#, php-format
+msgid "(you must have a %s file on your server)"
+msgstr ""
+
+#, fuzzy
+msgid "Import from Readability"
 msgstr "Uvoz iz aplikacije Readability"
 
-msgid "import from Instapaper"
+#, fuzzy
+msgid "Import from Instapaper"
 msgstr "Uvoz iz aplikacije Instapaper"
 
-msgid "Export your poche datas"
+#, fuzzy
+msgid "Import from wallabag"
+msgstr "Uvoz iz aplikacije Readability"
+
+#, fuzzy
+msgid "Export your wallabag data"
 msgstr "Izvoz vsebine"
 
 msgid "Click here"
 msgstr "Kliknite tukaj"
 
-msgid "to export your poche datas."
+#, fuzzy
+msgid "to download your database."
 msgstr "za izvoz vsebine aplikacije Poche."
 
-msgid "back to home"
-msgstr "Nazaj domov"
-
-msgid "installation"
-msgstr "Namestitev"
+#, fuzzy
+msgid "to export your wallabag data."
+msgstr "za izvoz vsebine aplikacije Poche."
 
-msgid "install your poche"
-msgstr "Namestitev aplikacije Poche"
+msgid "Cache"
+msgstr ""
 
-msgid ""
-"poche is still not installed. Please fill the below form to install it. "
-"Don't hesitate to <a href='http://inthepoche.com/doc'>read the documentation "
-"on poche website</a>."
+msgid "to delete cache."
 msgstr ""
-"Poche še vedno ni nameščen. Za namestitev izpolnite spodnji obrazec. Za več "
-"informacij <a href='http://inthepoche.com/doc'>preberite dokumentacijo na "
-"spletni strani</a>."
 
-msgid "Login"
-msgstr "Prijava"
+msgid "You can enter multiple tags, separated by commas."
+msgstr ""
 
-msgid "Repeat your password"
-msgstr "Ponovite geslo"
+msgid "return to article"
+msgstr ""
 
-msgid "Install"
-msgstr "Namesti"
+msgid "plop"
+msgstr "štrbunk"
 
-msgid "back to top"
-msgstr "nazaj na vrh"
+msgid "You can <a href='wallabag_compatibility_test.php'>check your configuration here</a>."
+msgstr ""
 
 msgid "favoris"
 msgstr "priljubljeni"
@@ -154,10 +239,14 @@ msgstr "po naslovu"
 msgid "by title desc"
 msgstr "po naslovu - padajoče"
 
-msgid "No link available here!"
-msgstr "Povezava ni na voljo!"
+msgid "Tag"
+msgstr ""
 
-msgid "toggle mark as read"
+msgid "No articles found."
+msgstr ""
+
+#, fuzzy
+msgid "Toggle mark as read"
 msgstr "označi kot prebrano"
 
 msgid "toggle favorite"
@@ -169,13 +258,95 @@ msgstr "zavrzi"
 msgid "original"
 msgstr "izvirnik"
 
+msgid "estimated reading time:"
+msgstr ""
+
+msgid "mark all the entries as read"
+msgstr ""
+
 msgid "results"
 msgstr "rezultati"
 
-msgid "tweet"
+msgid "installation"
+msgstr "Namestitev"
+
+#, fuzzy
+msgid "install your wallabag"
+msgstr "Namestitev aplikacije Poche"
+
+#, fuzzy
+msgid "wallabag is still not installed. Please fill the below form to install it. Don't hesitate to <a href='http://doc.wallabag.org/'>read the documentation on wallabag website</a>."
+msgstr "Poche še vedno ni nameščen. Za namestitev izpolnite spodnji obrazec. Za več informacij <a href='http://inthepoche.com/doc'>preberite dokumentacijo na spletni strani</a>."
+
+msgid "Login"
+msgstr "Prijava"
+
+msgid "Repeat your password"
+msgstr "Ponovite geslo"
+
+msgid "Install"
+msgstr "Namesti"
+
+#, fuzzy
+msgid "login to your wallabag"
+msgstr "prijavite se v svoj Poche"
+
+msgid "Login to wallabag"
+msgstr ""
+
+msgid "you are in demo mode, some features may be disabled."
+msgstr "uporabljate vzorčno različico programa, zato so lahko nekatere funkcije izklopljene."
+
+msgid "Username"
+msgstr ""
+
+msgid "Stay signed in"
+msgstr "Ostani prijavljen"
+
+msgid "(Do not check on public computers)"
+msgstr "(Ne označi na javnih napravah)"
+
+msgid "Sign in"
+msgstr "Prijava"
+
+msgid "favorites"
+msgstr "priljubljeni"
+
+msgid "estimated reading time :"
+msgstr ""
+
+msgid "Mark all the entries as read"
+msgstr ""
+
+msgid "Return home"
+msgstr ""
+
+#, fuzzy
+msgid "Back to top"
+msgstr "nazaj na vrh"
+
+#, fuzzy
+msgid "Mark as read"
+msgstr "označi kot prebrano"
+
+#, fuzzy
+msgid "Favorite"
+msgstr "priljubljeni"
+
+#, fuzzy
+msgid "Toggle favorite"
+msgstr "označi kot priljubljeno"
+
+#, fuzzy
+msgid "Delete"
+msgstr "zavrzi"
+
+#, fuzzy
+msgid "Tweet"
 msgstr "tvitni"
 
-msgid "email"
+#, fuzzy
+msgid "Email"
 msgstr "pošlji po e-pošti"
 
 msgid "shaarli"
@@ -184,26 +355,24 @@ msgstr "shaarli"
 msgid "flattr"
 msgstr "flattr"
 
-msgid "this article appears wrong?"
+#, fuzzy
+msgid "Does this article appear wrong?"
 msgstr "napaka?"
 
-msgid "create an issue"
-msgstr "prijavi napako"
-
-msgid "or"
-msgstr "ali"
+msgid "tags:"
+msgstr ""
 
-msgid "contact us by mail"
-msgstr "pošlji e-pošto razvijalcem"
+msgid "Edit tags"
+msgstr ""
 
-msgid "plop"
-msgstr "štrbunk"
+msgid "save link!"
+msgstr ""
 
 msgid "home"
 msgstr "domov"
 
-msgid "favorites"
-msgstr "priljubljeni"
+msgid "tags"
+msgstr ""
 
 msgid "logout"
 msgstr "odjava"
@@ -212,28 +381,188 @@ msgid "powered by"
 msgstr "stran poganja"
 
 msgid "debug mode is on so cache is off."
-msgstr ""
-"vklopljen je način odpravljanja napak, zato je predpomnilnik izključen."
+msgstr "vklopljen je način odpravljanja napak, zato je predpomnilnik izključen."
 
-msgid "your poche version:"
-msgstr "vaša verzija Poche:"
+#, fuzzy
+msgid "your wallabag version:"
+msgstr "vaša različica"
 
 msgid "storage:"
 msgstr "pomnilnik:"
 
-msgid "login to your poche"
-msgstr "prijavite se v svoj Poche"
+msgid "save a link"
+msgstr ""
 
-msgid "you are in demo mode, some features may be disabled."
+msgid "back to home"
+msgstr "Nazaj domov"
+
+msgid "toggle mark as read"
+msgstr "označi kot prebrano"
+
+msgid "tweet"
+msgstr "tvitni"
+
+msgid "email"
+msgstr "pošlji po e-pošti"
+
+msgid "this article appears wrong?"
+msgstr "napaka?"
+
+msgid "No link available here!"
+msgstr "Povezava ni na voljo!"
+
+msgid "Poching a link"
+msgstr "Shrani povezavo"
+
+msgid "by filling this field"
+msgstr "z vnosom v to polje"
+
+msgid "bookmarklet: drag & drop this link to your bookmarks bar"
 msgstr ""
-"uporabljate vzorčno različico programa, zato so lahko nekatere funkcije "
-"izklopljene."
 
-msgid "Stay signed in"
-msgstr "Ostani prijavljen"
+msgid "your version"
+msgstr "vaša različica"
 
-msgid "(Do not check on public computers)"
-msgstr "(Ne označi na javnih napravah)"
+msgid "latest stable version"
+msgstr "zadnja stabilna različica"
 
-msgid "Sign in"
-msgstr "Prijava"
+msgid "a more recent stable version is available."
+msgstr "na voljo je nova stabilna različica."
+
+msgid "you are up to date."
+msgstr "imate najnovejšo različico."
+
+msgid "latest dev version"
+msgstr "zadnja razvojna različica"
+
+msgid "a more recent development version is available."
+msgstr "na voljo je nova razvojna različica."
+
+msgid "Please execute the import script locally, it can take a very long time."
+msgstr "Prosimo poženite skripto za uvoz lokalno, saj lahko postopek traja precej časa."
+
+msgid "More infos in the official doc:"
+msgstr "Več informacij v uradni dokumentaciji:"
+
+msgid "import from Pocket"
+msgstr "Uvoz iz aplikacije Pocket"
+
+msgid "import from Readability"
+msgstr "Uvoz iz aplikacije Readability"
+
+msgid "import from Instapaper"
+msgstr "Uvoz iz aplikacije Instapaper"
+
+msgid "Tags"
+msgstr ""
+
+#, fuzzy
+msgid "Untitled"
+msgstr "po naslovu"
+
+msgid "the link has been added successfully"
+msgstr ""
+
+msgid "error during insertion : the link wasn't added"
+msgstr ""
+
+msgid "the link has been deleted successfully"
+msgstr ""
+
+msgid "the link wasn't deleted"
+msgstr ""
+
+msgid "Article not found!"
+msgstr ""
+
+msgid "previous"
+msgstr ""
+
+msgid "next"
+msgstr ""
+
+msgid "in demo mode, you can't update your password"
+msgstr ""
+
+msgid "your password has been updated"
+msgstr ""
+
+msgid "the two fields have to be filled & the password must be the same in the two fields"
+msgstr ""
+
+msgid "still using the \""
+msgstr ""
+
+msgid "that theme does not seem to be installed"
+msgstr ""
+
+msgid "you have changed your theme preferences"
+msgstr ""
+
+msgid "that language does not seem to be installed"
+msgstr ""
+
+msgid "you have changed your language preferences"
+msgstr ""
+
+msgid "login failed: you have to fill all fields"
+msgstr ""
+
+msgid "welcome to your wallabag"
+msgstr ""
+
+msgid "login failed: bad login or password"
+msgstr ""
+
+#, fuzzy
+msgid "import from instapaper completed"
+msgstr "Uvoz iz aplikacije Instapaper"
+
+#, fuzzy
+msgid "import from pocket completed"
+msgstr "Uvoz iz aplikacije Pocket"
+
+#, fuzzy
+msgid "import from Readability completed. "
+msgstr "Uvoz iz aplikacije Readability"
+
+#, fuzzy
+msgid "import from Poche completed. "
+msgstr "Uvoz iz aplikacije Pocket"
+
+msgid "Unknown import provider."
+msgstr ""
+
+msgid "Incomplete inc/poche/define.inc.php file, please define \""
+msgstr ""
+
+msgid "Could not find required \""
+msgstr ""
+
+msgid "Uh, there is a problem while generating feeds."
+msgstr ""
+
+#, fuzzy
+msgid "Cache deleted."
+msgstr "zavrzi"
+
+msgid "Oops, it seems you don't have PHP 5."
+msgstr ""
+
+#~ msgid "poche it!"
+#~ msgstr "shrani!"
+
+#~ msgid "Updating poche"
+#~ msgstr "Posodabljam Poche"
+
+#~ msgid "create an issue"
+#~ msgstr "prijavi napako"
+
+#~ msgid "or"
+#~ msgstr "ali"
+
+#~ msgid "contact us by mail"
+#~ msgstr "pošlji e-pošto razvijalcem"
+
+#~ msgid "your poche version:"
+#~ msgstr "vaša verzija Poche:"
diff --git a/locale/tools/fillCache.php b/locale/tools/fillCache.php
new file mode 100755 (executable)
index 0000000..bdd9cc5
--- /dev/null
@@ -0,0 +1,59 @@
+<?php
+
+// this script compile all twig templates and put it in cahce to get Poedit (or xgettext) to extract phrases fron chached templates.
+
+// gettext command line tools:
+// msgunfmt - get po from mo
+// msgfmt - get mo from po
+// xgettext - extract phrases from files
+
+
+               $siteRoot = dirname(__FILE__) . '/../..';
+
+               require_once  $siteRoot . '/vendor/twig/twig/lib/Twig/Autoloader.php';
+               Twig_Autoloader::register();
+
+               require_once  $siteRoot . '/vendor/twig/extensions/lib/Twig/Extensions/Autoloader.php';
+               Twig_Extensions_Autoloader::register();
+
+               //$tplDir = $siteRoot.'/themes/default';
+               $tplDirRoot = $siteRoot.'/themes/';
+               $tmpDir =  $siteRoot. '/cache/';
+
+               foreach (new IteratorIterator(new DirectoryIterator($tplDirRoot)) as $tplDir) {
+
+                       if ($tplDir->isDir() and $tplDir!='.' and $tplDir!='..') {
+                               echo "\n$tplDir\n";
+
+                               $loader = new Twig_Loader_Filesystem($tplDirRoot.$tplDir);
+
+                               // force auto-reload to always have the latest version of the template
+                               $twig = new Twig_Environment($loader, array(
+                                               'cache' => $tmpDir,
+                                               'auto_reload' => true
+                               ));
+
+                               $twig->addExtension(new Twig_Extensions_Extension_I18n());
+
+                               $filter = new Twig_SimpleFilter('getDomain', 'Tools::getDomain');
+                               $twig->addFilter($filter);
+
+                               $filter = new Twig_SimpleFilter('getReadingTime', 'Tools::getReadingTime');
+                               $twig->addFilter($filter);
+
+                               $filter = new Twig_SimpleFilter('getPrettyFilename', function($string) { return str_replace($siteRoot, '', $string); });
+                               $twig->addFilter($filter);
+
+//                             // iterate over all your templates
+                               foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($tplDirRoot.$tplDir), RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
+                                               // force compilation
+                                       if ($file->isFile() and pathinfo($file, PATHINFO_EXTENSION)=='twig') {
+                                                       echo "\t$file\n";
+                                                       $twig->loadTemplate(str_replace($tplDirRoot.$tplDir.'/', '', $file));
+                                       }
+                               }
+
+                       }
+
+               }
+
index 80972b65dc5caa2e869eaadf6611bc34bfdbf052..4884abf5c5dda633e2c8847a0be1ef162f27630a 100755 (executable)
Binary files a/locale/uk_UA.utf8/LC_MESSAGES/uk_UA.utf8.mo and b/locale/uk_UA.utf8/LC_MESSAGES/uk_UA.utf8.mo differ
index 6092cbab9ba3a0cf93c39f7277b7473d87bc7dbf..0879770562aad47a58ecf6b4d23858276f43ee74 100755 (executable)
@@ -2,8 +2,8 @@ msgid ""
 msgstr ""
 "Project-Id-Version: wballabag\n"
 "Report-Msgid-Bugs-To: \n"
-"POT-Creation-Date: 2014-02-06 19:23+0300\n"
-"PO-Revision-Date: 2014-02-06 19:24+0300\n"
+"POT-Creation-Date: 2014-02-25 15:06+0300\n"
+"PO-Revision-Date: 2014-02-25 15:08+0300\n"
 "Last-Translator: Maryana <mariroz@mr.lviv.ua>\n"
 "Language-Team: \n"
 "Language: \n"
@@ -15,52 +15,25 @@ msgstr ""
 "X-Poedit-Language: Ukrainian\n"
 "X-Poedit-Country: UKRAINE\n"
 "X-Poedit-SourceCharset: utf-8\n"
-"X-Poedit-SearchPath-0: /home/mariroz/_DEV/web/wallabag/wallabag\n"
+"X-Poedit-SearchPath-0: /home/mariroz/_DEV/web/wallabag/wallabag-master-testing\n"
 
-msgid "poche, a read it later open source system"
-msgstr "poche, сервіс відкладеного читання з відкритим кодом"
+msgid "wallabag, a read it later open source system"
+msgstr "wallabag, сервіс відкладеного читання з відкритим кодом"
 
 msgid "login failed: user doesn't exist"
 msgstr "увійти не вдалося: користувач не існує"
 
-msgid "powered by"
-msgstr "за підтримки"
-
-msgid "debug mode is on so cache is off."
-msgstr "режим відладки включено, отже кеш виключено."
-
-msgid "your poche version:"
-msgstr "версія вашої poche:"
-
-msgid "storage:"
-msgstr "сховище:"
-
-msgid "home"
-msgstr "головна"
-
-msgid "favorites"
-msgstr "вибране"
-
-msgid "archive"
-msgstr "архів"
-
-msgid "tags"
-msgstr "теги"
+msgid "return home"
+msgstr "повернутися на головну"
 
 msgid "config"
 msgstr "налаштування"
 
-msgid "logout"
-msgstr "вихід"
-
-msgid "return home"
-msgstr "повернутися на головну"
-
-msgid "Poching links"
+msgid "Saving articles"
 msgstr "Зберігання посилань"
 
-msgid "There are several ways to poche a link:"
-msgstr "Є кілька способів зберегти посилання:"
+msgid "There are several ways to save an article:"
+msgstr "Є кілька способів зберегти статтю:"
 
 msgid "read the documentation"
 msgstr "читати документацію"
@@ -83,14 +56,14 @@ msgstr "завантажити додаток"
 msgid "By filling this field"
 msgstr "Заповнивши це поле"
 
-msgid "poche it!"
+msgid "bag it!"
 msgstr "зберегти!"
 
 msgid "Bookmarklet: drag & drop this link to your bookmarks bar"
 msgstr "З допомогою закладки: перетягніть і відпустіть посилання на панель закладок"
 
-msgid "Updating poche"
-msgstr "Оновлення poche"
+msgid "Upgrading wallabag"
+msgstr "Оновлення wallabag"
 
 msgid "Installed version"
 msgstr "Встановлено ​​версію"
@@ -104,14 +77,11 @@ msgstr "Є новіша стабільна версія."
 msgid "You are up to date."
 msgstr "У вас остання версія."
 
-msgid "latest dev version"
-msgstr "остання версія в розробці"
-
-msgid "a more recent development version is available."
-msgstr "доступна новіша версія в розробці."
+msgid "Latest dev version"
+msgstr "Остання версія в розробці"
 
-msgid "you are up to date."
-msgstr "у вас остання версія."
+msgid "A more recent development version is available."
+msgstr "Доступна новіша версія в розробці."
 
 msgid "Feeds"
 msgstr "Завантаження (feeds)"
@@ -170,8 +140,8 @@ msgstr "Імпортування"
 msgid "Please execute the import script locally as it can take a very long time."
 msgstr "Будь ласка, виконайте сценарій імпорту локально, оскільки це може тривати досить довго."
 
-msgid "More info in the official docs:"
-msgstr "Більш детальна інформація в офіційній документації:"
+msgid "More info in the official documentation:"
+msgstr "Більше інформації в офіційній документації:"
 
 msgid "Import from Pocket"
 msgstr "Імпорт з Pocket-а"
@@ -186,11 +156,11 @@ msgstr "Імпорт з Readability"
 msgid "Import from Instapaper"
 msgstr "Імпорт з Instapaper"
 
-msgid "Import from poche"
-msgstr "Імпорт з poche"
+msgid "Import from wallabag"
+msgstr "Імпорт з wallabag"
 
-msgid "Export your poche data"
-msgstr "Експортувати ваші дані з poche"
+msgid "Export your wallabag data"
+msgstr "Експортувати ваші дані з wallabag"
 
 msgid "Click here"
 msgstr "Клікніть тут"
@@ -198,32 +168,14 @@ msgstr "Клікніть тут"
 msgid "to download your database."
 msgstr "щоб завантажити вашу базу даних."
 
-msgid "to export your poche data."
-msgstr "щоб експортувати ваші дані poche."
+msgid "to export your wallabag data."
+msgstr "щоб експортувати ваші дані wallabag."
 
-msgid "Tag"
-msgstr "Тег"
+msgid "Cache"
+msgstr "Ð\9aеÑ\88"
 
-msgid "No link available here!"
-msgstr "Немає доступних посилань!"
-
-msgid "toggle mark as read"
-msgstr "змінити мітку на прочитано"
-
-msgid "toggle favorite"
-msgstr "змінити мітку вибраного"
-
-msgid "delete"
-msgstr "видалити"
-
-msgid "original"
-msgstr "оригінал"
-
-msgid "estimated reading time:"
-msgstr "приблизний час читання:"
-
-msgid "results"
-msgstr "результат(ів)"
+msgid "to delete cache."
+msgstr "щоб очистити кеш."
 
 msgid "You can enter multiple tags, separated by commas."
 msgstr "Ви можете ввести декілька тегів, розділених комами."
@@ -240,6 +192,9 @@ msgstr "Ви можете <a href='wallabag_compatibility_test.php'>переві
 msgid "favoris"
 msgstr "вибране"
 
+msgid "archive"
+msgstr "архів"
+
 msgid "unread"
 msgstr "непрочитане"
 
@@ -261,12 +216,33 @@ msgstr "за назвою"
 msgid "by title desc"
 msgstr "за назвою по спаданню"
 
+msgid "Tag"
+msgstr "Тег"
+
 msgid "No articles found."
 msgstr "Статей не знайдено."
 
 msgid "Toggle mark as read"
 msgstr "змінити мітку прочитаного"
 
+msgid "toggle favorite"
+msgstr "змінити мітку вибраного"
+
+msgid "delete"
+msgstr "видалити"
+
+msgid "original"
+msgstr "оригінал"
+
+msgid "estimated reading time:"
+msgstr "приблизний час читання:"
+
+msgid "mark all the entries as read"
+msgstr "відмітити всі статті як прочитані"
+
+msgid "results"
+msgstr "результат(ів)"
+
 msgid "installation"
 msgstr "інсталяція"
 
@@ -303,6 +279,18 @@ msgstr "Запам'ятати мене"
 msgid "(Do not check on public computers)"
 msgstr "(Не відмічайте на загальнодоступних комп'ютерах)"
 
+msgid "Sign in"
+msgstr "Увійти"
+
+msgid "favorites"
+msgstr "вибране"
+
+msgid "estimated reading time :"
+msgstr "приблизний час читання:"
+
+msgid "Mark all the entries as read"
+msgstr "Відмітити все як прочитане"
+
 msgid "Return home"
 msgstr "Повернутися на головну"
 
@@ -342,11 +330,95 @@ msgstr "теги:"
 msgid "Edit tags"
 msgstr "Редагувати теги"
 
-msgid "previous"
-msgstr "попеÑ\80еднÑ\8f"
+msgid "save link!"
+msgstr "збеÑ\80егÑ\82и Ð»Ñ\96нк!"
 
-msgid "next"
-msgstr "наступна"
+msgid "home"
+msgstr "головна"
+
+msgid "tags"
+msgstr "теги"
+
+msgid "logout"
+msgstr "вихід"
+
+msgid "powered by"
+msgstr "за підтримки"
+
+msgid "debug mode is on so cache is off."
+msgstr "режим відладки включено, отже кеш виключено."
+
+msgid "your wallabag version:"
+msgstr "версія вашого wallabag:"
+
+msgid "storage:"
+msgstr "сховище:"
+
+msgid "save a link"
+msgstr "зберегти лінк"
+
+msgid "back to home"
+msgstr "назад на головну"
+
+msgid "toggle mark as read"
+msgstr "змінити мітку на прочитано"
+
+msgid "tweet"
+msgstr "твітнути"
+
+msgid "email"
+msgstr "email"
+
+msgid "this article appears wrong?"
+msgstr "ця стаття виглядає не так, як треба?"
+
+msgid "No link available here!"
+msgstr "Немає доступних посилань!"
+
+msgid "Poching a link"
+msgstr "Зберігання посилання"
+
+msgid "by filling this field"
+msgstr "заповнивши це поле"
+
+msgid "bookmarklet: drag & drop this link to your bookmarks bar"
+msgstr "з допомогою закладки: перетягніть і відпустіть посилання на панель закладок"
+
+msgid "your version"
+msgstr "ваша версія:"
+
+msgid "latest stable version"
+msgstr "остання стабільна версія"
+
+msgid "a more recent stable version is available."
+msgstr "є новіша стабільна версія."
+
+msgid "you are up to date."
+msgstr "у вас остання версія."
+
+msgid "latest dev version"
+msgstr "остання версія в розробці"
+
+msgid "a more recent development version is available."
+msgstr "доступна новіша версія в розробці."
+
+msgid "Please execute the import script locally, it can take a very long time."
+msgstr "Будь ласка, виконайте сценарій імпорту локально, оскільки це може тривати досить довго."
+
+msgid "More infos in the official doc:"
+msgstr "Більше інформації в офіційній документації:"
+
+msgid "import from Pocket"
+msgstr "імпорт з Pocket-а"
+
+msgid "import from Readability"
+msgstr "імпорт з Readability"
+
+msgid "import from Instapaper"
+msgstr "імпорт з Instapaper"
+
+msgid "Tags"
+msgstr "Теги"
 
 msgid "Untitled"
 msgstr "Без назви"
@@ -363,6 +435,15 @@ msgstr "посилання успішно видалено"
 msgid "the link wasn't deleted"
 msgstr "посилання не було видалено"
 
+msgid "Article not found!"
+msgstr "Статтю не знайдено!"
+
+msgid "previous"
+msgstr "попередня"
+
+msgid "next"
+msgstr "наступна"
+
 msgid "in demo mode, you can't update your password"
 msgstr "в демонстраційному режимі ви не можете змінювати свій пароль"
 
@@ -390,15 +471,12 @@ msgstr "ви змінили свої налаштування мови"
 msgid "login failed: you have to fill all fields"
 msgstr "увійти не вдалося: ви повинні заповнити всі поля"
 
-msgid "welcome to your poche"
-msgstr "ласкаво просимо до вашого poche"
+msgid "welcome to your wallabag"
+msgstr "ласкаво просимо до вашого wallabag"
 
 msgid "login failed: bad login or password"
 msgstr "увійти не вдалося: не вірний логін або пароль"
 
-msgid "see you soon!"
-msgstr "бувайте, ще побачимось!"
-
 msgid "import from instapaper completed"
 msgstr "імпорт з instapaper-а завершено"
 
@@ -423,6 +501,34 @@ msgstr "Не вдалося знайти потрібний \""
 msgid "Uh, there is a problem while generating feeds."
 msgstr "Ох, є проблема при створенні завантажень (feeds)."
 
+msgid "Cache deleted."
+msgstr "Кеш очищено."
+
 msgid "Oops, it seems you don't have PHP 5."
 msgstr "Упс, здається, у вас немає PHP 5."
 
+#~ msgid "You can poche a link by several methods:"
+#~ msgstr "Ви можете зберегти посилання кількома способами:"
+
+#~ msgid "poche it!"
+#~ msgstr "зберегти!"
+
+#~ msgid "Updating poche"
+#~ msgstr "Оновлення poche"
+
+#, fuzzy
+#~ msgid "Export your poche datas"
+#~ msgstr "Експортувати ваші дані з poche"
+
+#, fuzzy
+#~ msgid "to export your poche datas."
+#~ msgstr "щоб експортувати ваші дані poche."
+
+#~ msgid "Import from poche"
+#~ msgstr "Імпорт з poche"
+
+#~ msgid "welcome to your poche"
+#~ msgstr "ласкаво просимо до вашого poche"
+
+#~ msgid "see you soon!"
+#~ msgstr "бувайте, ще побачимось!"
diff --git a/themes/baggy/_display-mode.twig b/themes/baggy/_display-mode.twig
new file mode 100755 (executable)
index 0000000..382dd5f
--- /dev/null
@@ -0,0 +1,5 @@
+<div id="display-mode">
+  <a href="javascript: void(null);" id="listmode" class="listmode">
+    <img src="{{ poche_url }}themes/{{ theme }}/img/{{ theme }}/blank.png" alt="{% trans "toggle view mode" %}" title="{% trans "toggle view mode" %}" width="16" height="16">
+  </a>
+</div>
old mode 100644 (file)
new mode 100755 (executable)
index 206d5aa..be11673
@@ -1,12 +1,16 @@
-        <link rel="shortcut icon" type="image/x-icon" href="{{ poche_url }}/themes/{{theme}}/img/favicon.ico" />
-        <link rel="apple-touch-icon-precomposed" sizes="144x144" href="{{ poche_url }}/themes/{{theme}}/img/apple-touch-icon-144x144-precomposed.png">
-        <link rel="apple-touch-icon-precomposed" sizes="72x72" href="{{ poche_url }}/themes/{{theme}}/img/apple-touch-icon-72x72-precomposed.png">
-        <link rel="apple-touch-icon-precomposed" href="{{ poche_url }}/themes/{{theme}}/img/apple-touch-icon-precomposed.png">
-        <link rel="stylesheet" href="{{ poche_url }}/themes/{{theme}}/css/ratatouille.css" media="all">
-        <link rel="stylesheet" href="{{ poche_url }}/themes/{{theme}}/css/font.css" media="all">
-        <link rel="stylesheet" href="{{ poche_url }}/themes/{{theme}}/css/main.css" media="all">
-        <link rel="stylesheet" href="{{ poche_url }}/themes/{{theme}}/css/messages.css" media="all">
-        <link rel="stylesheet" href="{{ poche_url }}/themes/{{theme}}/css/print.css" media="print">
-        <script src="{{ poche_url }}/themes/{{theme}}/js/jquery-2.0.3.min.js"></script>
-        <script src="{{ poche_url }}/themes/{{theme}}/js/init.js"></script>
-        <script src="{{ poche_url }}/themes/{{ constant('DEFAULT_THEME') }}/js/closeMessage.js"></script>
+        <link rel="shortcut icon" type="image/x-icon" href="{{ poche_url }}themes/{{theme}}/img/favicon.ico" />
+        <link rel="apple-touch-icon-precomposed" sizes="144x144" href="{{ poche_url }}themes/{{theme}}/img/apple-touch-icon-144x144-precomposed.png">
+        <link rel="apple-touch-icon-precomposed" sizes="72x72" href="{{ poche_url }}themes/{{theme}}/img/apple-touch-icon-72x72-precomposed.png">
+        <link rel="apple-touch-icon-precomposed" href="{{ poche_url }}themes/{{theme}}/img/apple-touch-icon-precomposed.png">
+        <link rel="stylesheet" href="{{ poche_url }}themes/{{theme}}/css/ratatouille.css" media="all">
+        <link rel="stylesheet" href="{{ poche_url }}themes/{{theme}}/css/font.css" media="all">
+        <link rel="stylesheet" href="{{ poche_url }}themes/{{theme}}/css/main.css" media="all">
+        <link rel="stylesheet" href="{{ poche_url }}themes/{{theme}}/css/messages.css" media="all">
+        <link rel="stylesheet" href="{{ poche_url }}themes/{{theme}}/css/print.css" media="print">
+        <script src="{{ poche_url }}themes/default/js/jquery-2.0.3.min.js"></script>
+        <script src="{{ poche_url }}themes/default/js/autoClose.js"></script>
+        <script src="{{ poche_url }}themes/{{theme}}/js/jquery.cookie.js"></script>
+        <script src="{{ poche_url }}themes/{{theme}}/js/init.js"></script>
+        <script src="{{ poche_url }}themes/default/js/saveLink.js"></script>
+        <script src="{{ poche_url }}themes/default/js/popupForm.js"></script>
+        <script src="{{ poche_url }}themes/{{theme}}/js/closeMessage.js"></script>
index e9cd9d4ad8affb7718730e2b1ae61bb8c9bf62b9..f1b75cd50056099c333fe48970ca90c8479a7b48 100644 (file)
@@ -4,9 +4,13 @@
                 <li><a href="./?view=fav" {% if view == 'fav' %}class="current"{% endif %}>{% trans "favorites" %}</a></li>
                 <li><a href="./?view=archive" {% if view == 'archive' %}class="current"{% endif %}>{% trans "archive" %}</a></li>
                 <li><a href="./?view=tags" {% if view == 'tags' %}class="current"{% endif %}>{% trans "tags" %}</a></li>
-                <li><a href="javascript: void(null);" id="pocheit">{% trans "save a link" %}</a></li>
+                <li style="position: relative;"><a href="javascript: void(null);" id="bagit">{% trans "save a link" %}</a>
+                    {% include '_pocheit-form.twig' %}
+                </li>
+                               <li style="position: relative;"><a href="javascript: void(null);" id="search">{% trans "search" %}</a>
+                    {% include '_search-form.twig' %}
+                </li>
                 <li><a href="./?view=config" {% if view == 'config' %}class="current"{% endif %}>{% trans "config" %}</a></li>
                 <li><a class="icon icon-power" href="./?logout" title="{% trans "logout" %}">{% trans "logout" %}</a></li>
             </ul>
 
-            {% include '_pocheit-form.twig' %}
diff --git a/themes/baggy/_pocheit-form.twig b/themes/baggy/_pocheit-form.twig
new file mode 100755 (executable)
index 0000000..505ec36
--- /dev/null
@@ -0,0 +1,10 @@
+<div id="bagit-form" class="messages info">
+    <form method="get" action="index.php" target="_blank" id="bagit-form-form">
+        <h2><a href="javascript: void(null);" id="bagit-form-close">X</a>
+        {% trans "Save a link" %}</h2>
+        <input type="hidden" name="autoclose" value="1" />
+        <input required placeholder="example.com/article" class="addurl" id="plainurl" name="plainurl" type="url" />
+        <input type="submit" value="{% trans "save link!" %}" />
+        <div id="add-link-result"></div>
+    </form>
+</div>
diff --git a/themes/baggy/_search-form.twig b/themes/baggy/_search-form.twig
new file mode 100644 (file)
index 0000000..b8ac3bf
--- /dev/null
@@ -0,0 +1,7 @@
+<div id="search-form" class="messages info">
+<form method="get" action="index.php">
+        <input type="hidden" name="view" value="search"></input>
+        <label><a href="javascript: void(null);" id="search-form-close">X</a>{% trans "Search" %}</label> : <input type="text" name="search" />
+        <input id="submit-search" type="submit" value="{% trans "Search" %} !"></input>
+</form>
+</div>
\ No newline at end of file
old mode 100644 (file)
new mode 100755 (executable)
index 4f476a3..a31c092
@@ -1,6 +1,6 @@
         <header class="w600p center mbm">
             <h1 class="logo">
-                {% if view == 'home' %}{% block logo %}<img width="100" height="100" src="{{ poche_url }}/themes/{{theme}}/img/logo-w.png" alt="logo poche" />{% endblock %}
+                {% if view == 'home' %}{% block logo %}<img width="100" height="100" src="{{ poche_url }}themes/{{theme}}/img/logo-w.png" alt="wallabag logo" />{% endblock %}
                 {% else %}<a href="./" title="{% trans "return home" %}" >{{ block('logo') }}</a>
                 {% endif %}
             </h1>
old mode 100644 (file)
new mode 100755 (executable)
index b37ac11..46735f0
@@ -8,10 +8,11 @@
             <h2>{% trans "Saving articles" %}</h2>
             <p>{% trans "There are several ways to save an article:" %} (<a href="http://doc.wallabag.org/" title="{% trans "read the documentation" %}">?</a>)</p>
             <ul>
-                <li>Firefox: <a href="https://addons.mozilla.org/firefox/addon/poche/" title="download the firefox extension">{% trans "download the extension" %}</a></li>
+                <li>Firefox: <a href="https://addons.mozilla.org/firefox/addon/wallabag/" title="download the firefox extension">{% trans "download the extension" %}</a></li>
                 <li>Chrome: <a href="http://doc.wallabag.org/doku.php?id=users:chrome_extension" title="download the chrome extension">{% trans "download the extension" %}</a></li>
-                <li>Android: <a href="https://f-droid.org/repository/browse/?fdid=fr.gaulupeau.apps.Poche" title="download the application">{% trans "via F-Droid" %}</a> {% trans " or " %} <a href="https://play.google.com/store/apps/details?id=fr.gaulupeau.apps.InThePoche" title="download the application">{% trans "via Google Play" %}</a></li>
-                <li>Windows Phone: <a href="https://www.windowsphone.com/en-us/store/app/poche/334de2f0-51b5-4826-8549-a3d805a37e83" title="download the window phone application">{% trans "download the application" %}</a></li>
+                <li>Android: <a href="https://f-droid.org/app/fr.gaulupeau.apps.InThePoche" title="download the application">{% trans "via F-Droid" %}</a> {% trans " or " %} <a href="https://play.google.com/store/apps/details?id=fr.gaulupeau.apps.InThePoche" title="download the application">{% trans "via Google Play" %}</a></li>
+                <li>iOS: <a href="https://itunes.apple.com/app/wallabag/id828331015?mt=8" title="download the iOS application">{% trans "download the application" %}</a></li>
+                <li>Windows Phone: <a href="http://www.windowsphone.com/en-us/store/app/wallabag/ff890514-348c-4d0b-9b43-153fff3f7450" title="download the window phone application">{% trans "download the application" %}</a></li>
                 <li>
                     <form method="get" action="index.php">
                         <label class="addurl" for="config_plainurl">{% trans "By filling this field" %}:</label>
             <h2>{% trans "Upgrading wallabag" %}</h2>
             <ul>
                 <li>{% trans "Installed version" %} : <strong>{{ constant('POCHE') }}</strong></li>
-                <li>{% trans "Latest stable version" %} : {{ prod }}. {% if compare_prod == -1 %}<strong><a href="http://wallabag.org/">{% trans "A more recent stable version is available." %}</a></strong>{% else %}{% trans "You are up to date." %}{% endif %}</li>
-                {% if constant('DEBUG_POCHE') == 1 %}<li>{% trans "Latest dev version" %} : {{ dev }}. {% if compare_dev == -1 %}<strong><a href="http://wallabag.org/">{% trans "A more recent development version is available." %}</a></strong>{% else %}{% trans "You are up to date." %}{% endif %}</li>{% endif %}
+                <li>{% trans "Latest stable version" %} : {{ prod }}. {% if compare_prod == -1 %}<strong><a href="http://wallabag.org/">{% trans "A more recent stable version is available." %}</a></strong>{% else %}{% trans "You are up to date." %}{% endif %} ({% trans "Last check:" %} {{ check_time_prod }})</li>
+                {% if constant('DEBUG_POCHE') == 1 %}<li>{% trans "Latest dev version" %} : {{ dev }}. {% if compare_dev == -1 %}<strong><a href="http://wallabag.org/">{% trans "A more recent development version is available." %}</a></strong>{% else %}{% trans "You are up to date." %}{% endif %} ({% trans "Last check:" %} {{ check_time_dev }}){% endif %}</li>
             </ul>
+            <p>{% trans "You can clear cache to check the latest release." %}</p>
 
             <h2>{% trans "Feeds" %}</h2>
             {% if token == '' %}
@@ -42,7 +44,7 @@
             <p>{% trans "Your user id:" %} <strong>{{user_id}}</strong></p>
             <p>{% trans "You can regenerate your token: <a href='?feed&amp;action=generate'>generate!</a>." %}</p>
             {% endif %}
-            
+
             <h2>{% trans "Change your theme" %}</h2>
             <form method="post" action="?updatetheme" name="changethemeform">
                 <fieldset class="w500p inline">
             {% endif %}
 
             <h2>{% trans "Import" %}</h2>
-            <p>{% trans "Please execute the import script locally as it can take a very long time." %}</p>
-            <p>{% trans "More info in the official documentation:" %} <a href="http://doc.wallabag.org/doku.php?id=users:migrate">wallabag.org</a></p>
-            <ul>
-                <li><a href="./?import&amp;from=pocket">{% trans "Import from Pocket" %}</a> {{ '(you must have a %s file on your server)'|trans|format(constant('POCKET_FILE')) }}</li>
-                <li><a href="./?import&amp;from=readability">{% trans "Import from Readability" %}</a> {{ '(you must have a %s file on your server)'|trans|format(constant('READABILITY_FILE')) }}</li>
-                <li><a href="./?import&amp;from=instapaper">{% trans "Import from Instapaper" %}</a> {{ '(you must have a %s file on your server)'|trans|format(constant('INSTAPAPER_FILE')) }}</li>
-                <li><a href="./?import&amp;from=poche">{% trans "Import from wallabag" %}</a> {{ '(you must have a %s file on your server)'|trans|format(constant('POCHE_FILE')) }}</li>
-            </ul>
-
+            <p>{% trans "You can import your Pocket, Readability, Instapaper, Wallabag or any data in appropriate json or html format." %}</p>
+            <p>{% trans "Please select export file on your computer and press \"Import\" button below.<br>Wallabag will parse your file, insert all URLs and start fetching of articles if required.<br>Fetching process is controlled by two constants in your config file: IMPORT_LIMIT (how many articles are fetched at once) and IMPORT_DELAY (delay between fetch of next batch of articles)." %}</p>
+            <form method="post" action="?import" name="uploadfile" enctype="multipart/form-data">
+                <fieldset class="w500p">
+                    <div class="row">
+                        <label class="col w150p" for="file">{% trans "File:" %}</label>
+                        <input class="col" type="file" id="file" name="file" tabindex="4">
+                    </div>
+                    <div class="row mts txtcenter">
+                        <button class="bouton" type="submit" tabindex="4">{% trans "Import" %}</button>
+                    </div>
+                </fieldset>
+            </form>
+            <p><a href="?import">{% trans "You can click here to fetch content for articles with no content." %}</a></p>
+            
             <h2>{% trans "Export your wallabag data" %}</h2>
             {% if constant('STORAGE') == 'sqlite' %}
             <p><a href="?download" target="_blank">{% trans "Click here" %}</a> {% trans "to download your database." %}</p>{% endif %}
             <p><a href="?export" target="_blank">{% trans "Click here" %}</a> {% trans "to export your wallabag data." %}</p>
+            
+            <h2>{% trans "Fancy an E-Book ?" %}</h2>
+            <p>{% trans "Click on <a href=\"./?epub&amp;method=all\" title=\"Generate ePub\">this link</a> to get all your articles in one ebook (ePub 3 format)." %}
+            <br>{% trans "This can <b>take a while</b> and can <b>even fail</b> if you have too many articles, depending on your server configuration." %}</p>
 
             <h2>{% trans "Cache" %}</h2>
             <p><a href="?empty-cache">{% trans "Click here" %}</a> {% trans "to delete cache." %}</p>
 
+            <h2>{% trans 'Add user' %}</h2>
+            <p>{% trans 'Add a new user :' %}</p>
+            <form method="post" action="?newuser">
+                <fieldset class="w500p">
+                <div class="row">
+                    <label class="col w150p" for="newusername">{% trans 'Login for new user' %}</label>
+                    <input class="col" type="text" id="newusername" name="newusername" placeholder="{% trans 'Login' %}">
+                </div>
+                <div class="row">
+                    <label class="col w150p" for="password4newuser">{% trans "Password for new user" %}</label>
+                    <input class="col" type="password" id="password4newuser" name="password4newuser" placeholder="{% trans "Password" %}">
+                </div>
+                <div class="row mts txtcenter">
+                    <button type="submit">{% trans "Send" %}</button>  
+                </div>
+                </fieldset>
+            </form>
+            
+            <h2>{% trans "Delete account" %}</h2>
+            {% if not only_user %}<form method="post" action="?deluser">
+            <p>{% trans "You can delete your account by entering your password and validating." %}<br /><b>{% trans "Be careful, data will be erased forever (that is a very long time)." %}</b></p>
+            <fieldset class="w500p">
+                <div class="row">
+                    <label class="col w150p" for="password4deletinguser">{% trans "Type here your password" %}</label>
+                    <input class="col" type="password" id="password4deletinguser" name="password4deletinguser" placeholder="{% trans "Password" %}">
+                </div>
+            <div class="row mts txtcenter">
+                <button type="submit">{% trans "Send" %}</button>
+            </div>
+            </form>
+            {% else %}<p>{% trans "You are the only user, you cannot delete your own account." %}<br />
+            {% trans "To completely remove wallabag, delete the wallabag folder on your web server." %}</p>{% endif %}
 {% endblock %}
index 3e128b08d5a568851aeb7d6fd89bcc472702afbc..6d320cd2d657b6a108faa4a6213a5500fd97f37d 100755 (executable)
@@ -173,21 +173,22 @@ h2:after {
 #links {
   position: fixed;
   top: 0;
-  width: 9em;
+  width: 10em;
   left: 0;
   text-align: right;
   background: #333;
-  padding-top: 9em;
+  padding-top: 9.5em;
   height: 100%;
   box-shadow:inset -4px 0 20px rgba(0,0,0,0.6);
   z-index: 10;
 }
 
 #main {
-  margin-left: 12em;
+  margin-left: 13em;
   position: relative;
   z-index: 10;
   padding-right: 5%;
+  padding-bottom: 1em;
 }
 
   #links a {
@@ -227,7 +228,7 @@ h2:after {
   #links li:last-child {
     position: fixed;
     bottom: 1em;
-    width: 10%;
+    width: 10em;
   }
 
   #links li:last-child a:before {
@@ -237,6 +238,61 @@ h2:after {
   }
 
 
+#sort {
+    padding: 0;
+    list-style-type: none;
+    opacity: 0.5;
+    display: inline-block;
+}
+
+#sort li {
+    display: inline;
+    font-size: 0.9em;
+}
+
+#sort li + li {
+    margin-left: 10px;
+}
+
+#sort a {
+    padding: 2px 2px 0;
+    vertical-align: middle;
+}
+
+#sort img {
+    vertical-align: baseline;
+}
+#sort img:hover {
+    cursor: pointer;
+}
+
+#display-mode {
+  float: right;
+  vertical-align: middle;
+  margin-top: 10px;
+  margin-bottom: 10px;
+  opacity: 0.5;
+}
+#listmode {
+  width: 16px;
+  display: inline-block;
+  text-decoration: none;
+}
+#listmode a:hover {
+  opacity: 1;
+}
+.tablemode {
+  background-image: url("../img/baggy/table.png");
+  background-repeat: no-repeat;
+  background-position: bottom;
+}
+.listmode {
+  background-image: url("../img/baggy/list.png");
+  background-repeat: no-repeat;
+  background-position: bottom;
+}
+
+
 /* ==========================================================================
    2 = Layout
    ========================================================================== */
@@ -248,7 +304,7 @@ h2:after {
 
 footer {
   text-align: right;
-  position: fixed;
+  position: relative;
   bottom: 0;
   right: 5em;
   color: #999;
@@ -266,6 +322,15 @@ footer a {
   letter-spacing:-5px;
 }
 
+.listmode .entrie {
+  width: 100%!important;
+  margin-left: 0!important;
+}
+
+.listmode .entrie p {
+  display: none;
+}
+
 .list-entries + .results {
   margin-bottom: 2em;
 }
@@ -359,6 +424,7 @@ footer a {
     content: none;
   }
 
+
 .entrie h2 a {
   display: block;
   text-decoration: none;
@@ -370,7 +436,7 @@ footer a {
        -o-transition: all 0.5s ease;
           transition: all 0.5s ease;
 }
-
+/*
 .entrie h2 a:after {
   content: "";
   position: absolute;
@@ -379,6 +445,7 @@ footer a {
   height: 100%;
   left: 0;
 }
+*/
 
 .entrie p {
   color: #666;
@@ -442,6 +509,7 @@ footer a {
 
 .pagination {
   text-align: right;
+  margin-bottom:50px;
 }
 
 .nb-results {
@@ -468,6 +536,153 @@ footer a {
   display: none;
 }
 
+/* ==========================================================================
+  2.1 = "save a link" related styles
+  ========================================================================== */
+
+#bagit-form, #search-form {
+  background: rgba(0,0,0,0.5);
+  position: absolute;
+  top: 0;
+  left: 10em;
+  z-index: 20;
+  height: 100%;
+  width: 100%;
+  margin: 0;
+  margin-top: -30%;
+  padding: 2em;
+  display: none;
+  border-left: 1px #EEE solid;
+}
+
+#bagit-form form, #search-form form {
+  background: #FFF;
+  position: absolute;
+  top: 0;
+  left: 0;
+  z-index: 20;
+  border: 10px solid #000;
+  width: 400px;
+  height: 200px;
+  /* margin: -150px 0 0 -300px; */
+  padding: 2em;
+}
+
+a#bagit-form-close, a#search-form-close {
+  background: #000;
+  color: #FFF;
+  padding: 0.2em 0.5em;
+  text-decoration: none;
+  display: inline-block;
+  float: right;
+  font-size: 0.6em;
+}
+a#bagit-form-close:hover, a#search-form-close:hover {
+  background: #999;
+  color: #000;
+}
+
+.active-current {
+  background-color: #999;
+}
+
+.active-current:after {
+  content: "";
+  width: 0;
+  height: 0;
+  position: absolute;
+  border-style: solid;
+  border-width: 10px;
+  border-color:  transparent #EEE transparent transparent;
+  right: 0;
+  top: 50%;
+  margin-top: -10px;
+}
+
+.opacity03 {
+  opacity: 0.3;
+}
+
+.add-to-wallabag-link-after {
+  background-color: #000;
+  color: #fff;
+  padding: 0 3px 2px 3px;
+}
+
+a.add-to-wallabag-link-after {
+    visibility: hidden;
+    position: absolute;
+    opacity: 0;
+    transition-duration: 2s;
+    transition-timing-function: ease-out;
+}
+
+#article article a:hover + a.add-to-wallabag-link-after, a.add-to-wallabag-link-after:hover {
+    opacity: 1;
+    visibility: visible;
+    transition-duration: .3s;
+    transition-timing-function: ease-in;
+}
+
+a.add-to-wallabag-link-after:after {
+     content: "w";
+}
+
+#add-link-result {
+  font-weight: bold;
+  margin-top: 10px;
+}
+
+/* ==========================================================================
+  2.2 = "search for articles" popup div related styles
+  ========================================================================== */
+#search-form {
+  background: rgba(0,0,0,0.5);
+  position: absolute;
+  top: 0;
+  left: 10em;
+  z-index: 20;
+  height: 100%;
+  width: 100%;
+  margin: 0;
+  margin-top: -30%;
+  padding: 2em;
+  display: none;
+  border-left: 1px #EEE solid;
+}
+
+#search-form form {
+  background: #FFF;
+  position: absolute;
+  top: 0;
+  left: 0;
+  z-index: 20;
+  border: 10px solid #000;
+  width: 400px;
+  height: 200px;
+  /* margin: -150px 0 0 -300px; */
+  padding: 2em;
+}
+
+a#search-form-close {
+  background: #000;
+  color: #FFF;
+  padding: 0.2em 0.5em;
+  text-decoration: none;
+  display: inline-block;
+  float: right;
+  font-size: 1.2em;
+}
+a#search-form-close:hover {
+  background: #999;
+  color: #000;
+}
+
+#submit-search{
+margin-left: 4em;
+margin-top:1em;
+}
+
 /* ==========================================================================
    3 = Pictos
    ========================================================================== */
@@ -550,6 +765,9 @@ footer a {
 .icon-rss:before {
   content: "\e808";
 }
+.icon-print:before {
+  content: "\e80d";
+}
 
 /* ==========================================================================
    Icon selected
@@ -583,7 +801,7 @@ footer a {
   }
 
 .warning {
-  font-size: 3em;
+  /* font-size: 3em;
   color: #999;
   font-style: italic;
   position: absolute;
@@ -592,7 +810,10 @@ footer a {
   width: 100%;
   text-align: center;
   padding-right: 5%;
-  margin-top: -2em;
+  margin-top: -2em;*/
+  font-weight: bold;
+  display: block;
+  width: 100%;
 }
 
 /* ==========================================================================
@@ -602,6 +823,7 @@ footer a {
 #article {
   width: 70%;
   margin-bottom: 3em;
+  text-align: justify;
 }
 
 #article .tags {
@@ -731,6 +953,9 @@ blockquote {
     width: 100%;
     margin-left: 0;
   }
+  #display-mode {
+    display: none;
+  }
 }
 
 @media screen and (max-width: 500px) {
@@ -754,8 +979,8 @@ blockquote {
     content: none;
   }
   .logo {
-    width: 1.5em;
-    height: 1.5em;
+    width: 1.25em;
+    height: 1.25em;
     left: 0;
     top: 0;
   }
@@ -805,6 +1030,7 @@ blockquote {
     margin-left: 1.5em;
     padding-right: 1.5em;
     position: static;
+    margin-top: 3em;
   }
   #article_toolbar .topPosF {
     display: none;
@@ -820,4 +1046,12 @@ blockquote {
   #article_toolbar a {
     padding: 0.3em 0.4em 0.2em;
   }
+  
+  #display-mode {
+    display: none;
+  }
+
+  #bagit-form, #search-form {
+    left: 0;
+  }
 }
index 9aefa779e76bdac3e7e72d84c0ff65edb4aa56ed..9dd6d295cf27c3c2f47f431d875660cf120f98d5 100755 (executable)
@@ -17,6 +17,7 @@ img {
 
 /* Hide useless blocks */
 body > header,
+#article_toolbar,
 #links,
 #sort,
 body > footer,
@@ -46,3 +47,16 @@ abbr[title]:after {
 .pagination span.current {
     border-style: dashed;
 }
+
+#main {
+               width: 100%;
+               padding: 0;
+               margin: 0;
+               margin-left: 0;
+         padding-right: 0;
+       padding-bottom: 0;
+}
+
+#article {
+               width: 100%;
+}
old mode 100644 (file)
new mode 100755 (executable)
index 9e9012e..2113e96
@@ -4,6 +4,11 @@
 {% include '_menu.twig' %}
 {% endblock %}
 {% block content %}
+
+<script src="{{ poche_url }}themes/default/js/jquery-ui-1.10.4.custom.min.js"></script>
+<script src="{{ poche_url }}themes/default/js/autoCompleteTags.js"></script>
+<link rel="stylesheet" href="{{ poche_url }}themes/default/css/jquery-ui-1.10.4.custom.min.css" media="all">
+
 <div id="article">
   <h2>{{ entry.title|raw }}</21>
 </div>
@@ -17,7 +22,8 @@
     <input type="hidden" name="entry_id" value="{{ entry_id }}" />
     <label for="value">Add tags: </label><input type="text" placeholder="interview, editorial, video" id="value" name="value" required="required" />
     <input type="submit" value="Tag" />
-    <p>{% trans "You can enter multiple tags, separated by commas." %}</p>
+    <p>{% trans "Start typing for auto complete." %}<br>
+    {% trans "You can enter multiple tags, separated by commas." %}</p>
 </form>
 <a class="icon icon-reply return" href="./?view=view&id={{ entry_id }}">{% trans "return to article" %}</a>
 {% endblock %}
old mode 100755 (executable)
new mode 100644 (file)
index 02f53b3..5632351
Binary files a/themes/baggy/fonts/icomoon.eot and b/themes/baggy/fonts/icomoon.eot differ
old mode 100755 (executable)
new mode 100644 (file)
index d9c35b9..b458613
@@ -1,7 +1,21 @@
 <?xml version="1.0" standalone="no"?>
 <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" >
 <svg xmlns="http://www.w3.org/2000/svg">
-<metadata>Generated by IcoMoon</metadata>
+<metadata>
+<json>
+{
+       "fontFamily": "icomoon",
+       "majorVersion": 1,
+       "minorVersion": 0,
+       "version": "Version 1.0",
+       "fontId": "icomoon",
+       "psName": "icomoon",
+       "subFamily": "Regular",
+       "fullName": "icomoon",
+       "description": "Generated by IcoMoon"
+}
+</json>
+</metadata>
 <defs>
 <font id="icomoon" horiz-adv-x="512">
 <font-face units-per-em="512" ascent="480" descent="-32" />
@@ -23,4 +37,5 @@
 <glyph unicode="&#xe80a;" d="M475.648 50.432v219.136q-9.216-10.24-19.968-18.944-76.288-58.368-121.856-96.256-14.336-12.288-23.552-19.456t-24.576-13.824-29.184-6.656h-1.024q-13.312 0-29.184 6.656t-24.576 13.824-23.552 19.456q-45.056 37.888-121.856 96.256-10.752 8.704-19.968 18.944v-219.136q0-4.096 3.072-6.656t6.144-2.56h420.864q3.584 0 6.144 2.56t3.072 6.656zM475.648 350.464v7.168t-0.512 3.584-0.512 3.584-1.536 2.56-2.56 2.048-4.096 1.024h-420.864q-3.584 0-6.144-3.072t-3.072-6.144q0-48.128 41.984-81.408 55.296-43.52 114.688-90.624 2.048-1.024 10.24-8.192t12.8-10.752 12.8-9.216 14.336-7.68 12.288-2.56h1.024q5.632 0 12.288 2.56t14.336 7.68 12.8 9.216 12.8 10.752 10.24 8.192q59.392 47.104 114.688 90.624 15.36 12.288 28.672 33.28t13.312 37.376zM512 361.216v-310.784q0-18.944-13.312-32.256t-32.256-13.824h-420.864q-18.432 0-32.256 13.824t-13.312 32.256v310.784q0 18.944 13.312 32.256t32.256 13.312h420.864q18.944 0 32.256-13.312t13.312-32.256z" />
 <glyph unicode="&#xe80b;" d="M0 133.888l256 256 256-256-75.776-75.776-180.224 179.712-180.224-179.712z" />
 <glyph unicode="&#xe80c;" d="M25.6 279.296q62.464-35.84 168.96-35.84t168.96 35.84l-27.648-248.832q-1.024-7.168-17.92-18.432t-51.2-22.016-72.192-10.752-71.68 10.752-51.2 22.016-18.432 18.432zM275.456 432.896q48.128-9.216 80.896-28.16t32.768-36.352v-5.12q0-29.696-57.344-50.688t-137.216-20.992-137.216 20.992-57.344 50.688v5.12q0 17.408 32.768 36.352t80.896 28.16l21.504 24.576q11.264 13.312 35.84 13.312h47.104q26.624 0 35.84-13.312zM247.808 375.552h43.008q-47.104 56.32-53.248 64.512-7.168 8.192-16.384 8.192h-52.224q-11.264 0-16.384-8.192l-54.272-64.512h43.008l32.768 33.792h41.984z" horiz-adv-x="389" />
+<glyph unicode="&#xe80d;" d="M128 448h256v-64h-256zM480 352h-448c-17.6 0-32-14.4-32-32v-160c0-17.6 14.398-32 32-32h96v-128h256v128h96c17.6 0 32 14.4 32 32v160c0 17.6-14.4 32-32 32zM352 32h-192v160h192v-160zM487.2 304c0-12.813-10.387-23.2-23.199-23.2-12.813 0-23.201 10.387-23.201 23.2s10.388 23.2 23.201 23.2c12.813 0 23.199-10.387 23.199-23.2z" />
 </font></defs></svg>
\ No newline at end of file
old mode 100755 (executable)
new mode 100644 (file)
index 3860dd0..bb1f21f
Binary files a/themes/baggy/fonts/icomoon.ttf and b/themes/baggy/fonts/icomoon.ttf differ
old mode 100755 (executable)
new mode 100644 (file)
index c3a91ed..bab1377
Binary files a/themes/baggy/fonts/icomoon.woff and b/themes/baggy/fonts/icomoon.woff differ
old mode 100644 (file)
new mode 100755 (executable)
index 4f9db06..3942d3b
             {% if entries is empty %}
             <div class="messages warning"><p>{% trans "No articles found." %}</p></div>
             {% else %}
+                 <div>
+                     {% include '_display-mode.twig' %}
+                     {% include '_sorting.twig' %}
+                 </div>
                 {% block pager %}
                     {% if nb_results > 1 %}
                 <div class="results">
-                    <div class="nb-results">{{ nb_results }} {% trans "results" %}</div>
+                    <div class="nb-results">{{ nb_results }} {% trans "results" %}{% if search_term is defined %} {% trans %}found for « {{ search_term }} »{% endtrans %}{% endif %}</div>
                         {{ page_links | raw }}
                 </div>
+                    {% elseif nb_results == 1 %}
+                        {% if search_term is defined %}
+                     <div class="results">
+                        <div class="nb-results">{% trans "Only one result found for " %} « {{ search_term }} »</div>
+                     </div>
+                        {% endif %}
                     {% endif %}
                 {% endblock %}
-            <div class="list-entries">
+            <div id="list-entries" class="list-entries">
                     {% for entry in entries %}
-                <div id="entry-{{ entry.id|e }}" class="entrie">
+                <div id="entry-{{ entry.id|e }}" class="entrie"{% if listmode %} style="width:100%; margin-left:0;"{% endif %}>
                     <h2><a href="index.php?view=view&amp;id={{ entry.id|e }}">{{ entry.title|raw }}</a></h2>
                     {% if entry.content| getReadingTime > 0 %}
                         <div class="estimatedTime"><a target="_blank" title="{% trans "estimated reading time:" %} {{ entry.content| getReadingTime }} min" class="tool reading-time"><span>{% trans "estimated reading time :" %} {{ entry.content| getReadingTime }} min</span></div>
 
                 {% endfor %}
             </div>
+            {{ block('pager') }}
             {% if view == 'home' %}{% if nb_results > 1 %}<a title="{% trans "Mark all the entries as read" %}"  href="./?action=archive_all">{{ "Mark all the entries as read" }}</a>{% endif %}{% endif %}
+
+            {% if search_term is defined %}<a title="{% trans %} Apply the tag {{ search_term }} to this search {% endtrans %}" href="./?action=add_tag&search={{ search_term }}">{% trans %} Apply the tag {{ search_term }} to this search {% endtrans %}</a>{% endif %}
+            
+            {% if tag %}<a title="{% trans "Download the articles from this tag in an epub" %}" href="./?epub&amp;method=tag&amp;tag={{ tag.value }}">{% trans "Download the articles from this tag in an epub" %}</a>
+            {% elseif search_term is defined %}<a title="{% trans "Download the articles from this search in an epub" %}" href="./?epub&amp;method=search&amp;search={{ search_term }}">{% trans "Download the articles from this search in an epub" %}</a>
+            {% else %}<a title="{% trans "Download the articles from this category in an epub" %}" href="./?epub&amp;method=category&amp;category={{ view }}">{% trans "Download the articles from this category in an epub" %}</a>{% endif %}
+            
             {% endif %}
-            {{ block('pager') }}
 {% endblock %}
diff --git a/themes/baggy/img/baggy/blank.png b/themes/baggy/img/baggy/blank.png
new file mode 100755 (executable)
index 0000000..63e0984
Binary files /dev/null and b/themes/baggy/img/baggy/blank.png differ
diff --git a/themes/baggy/img/baggy/down.png b/themes/baggy/img/baggy/down.png
new file mode 100644 (file)
index 0000000..b9d536a
Binary files /dev/null and b/themes/baggy/img/baggy/down.png differ
diff --git a/themes/baggy/img/baggy/list.png b/themes/baggy/img/baggy/list.png
new file mode 100755 (executable)
index 0000000..bd5aff5
Binary files /dev/null and b/themes/baggy/img/baggy/list.png differ
diff --git a/themes/baggy/img/baggy/table.png b/themes/baggy/img/baggy/table.png
new file mode 100755 (executable)
index 0000000..859c4cd
Binary files /dev/null and b/themes/baggy/img/baggy/table.png differ
diff --git a/themes/baggy/img/baggy/top.png b/themes/baggy/img/baggy/top.png
new file mode 100644 (file)
index 0000000..954a8c0
Binary files /dev/null and b/themes/baggy/img/baggy/top.png differ
diff --git a/themes/baggy/js/autoClose.js b/themes/baggy/js/autoClose.js
deleted file mode 100644 (file)
index e9145b7..0000000
+++ /dev/null
@@ -1,6 +0,0 @@
-$(document).ready(function() {
-       current_url = window.location.href
-       if (current_url.match("&closewin=true")) {
-               window.close();
-       }
-});
index c1d3c0ec01c6476e144462f664145a0e4bfdd2df..00470fbfd734fdebe270ff24c20c11069599e147 100755 (executable)
@@ -1,12 +1,48 @@
-document.addEventListener('DOMContentLoaded', function() {
-  var menu = document.getElementById('menu');
-
-  menu.addEventListener('click', function(){
-    if(this.nextElementSibling.style.display === "block") {
-      this.nextElementSibling.style.display = "none";
-    }else {
-      this.nextElementSibling.style.display = "block";  
+$.fn.ready(function() {
+
+  var $listmode = $('#listmode'),
+      $listentries = $("#list-entries");
+
+  /* ==========================================================================
+     Menu
+     ========================================================================== */
+
+  $("#menu").click(function(){
+    $("#links").toggle();
+  });
+
+  /* ==========================================================================
+     List mode or Table Mode
+     ========================================================================== */
+
+  $listmode.click(function(){
+    if ( $.cookie("listmode") == 1 ) {
+      // Cookie
+      $.removeCookie("listmode");
+
+      $listentries.removeClass("listmode");
+      $listmode.removeClass("tablemode");
+      $listmode.addClass("listmode");
     }
-    
+    else {
+      // Cookie
+      $.cookie("listmode", 1, {expires: 365});
+
+      $listentries.addClass("listmode");
+      $listmode.removeClass("listmode");
+      $listmode.addClass("tablemode");
+    }
+
   });
-});
\ No newline at end of file
+
+  /* ==========================================================================
+     Cookie listmode
+     ========================================================================== */
+
+  if ( $.cookie("listmode") == 1 ) {
+    $listentries.addClass("listmode");
+    $listmode.removeClass("listmode");
+    $listmode.addClass("tablemode");
+  }
+
+});
diff --git a/themes/baggy/js/jquery-2.0.3.min.js b/themes/baggy/js/jquery-2.0.3.min.js
deleted file mode 100644 (file)
index a4dd0a2..0000000
+++ /dev/null
@@ -1 +0,0 @@
-(function(e,undefined){var t,n,r=typeof undefined,i=e.location,o=e.document,s=o.documentElement,a=e.jQuery,u=e.$,l={},c=[],p="2.0.3",f=c.concat,h=c.push,d=c.slice,g=c.indexOf,m=l.toString,y=l.hasOwnProperty,v=p.trim,x=function(e,n){return new x.fn.init(e,n,t)},b=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,w=/\S+/g,T=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,k=/^-ms-/,N=/-([\da-z])/gi,E=function(e,t){return t.toUpperCase()},S=function(){o.removeEventListener("DOMContentLoaded",S,!1),e.removeEventListener("load",S,!1),x.ready()};x.fn=x.prototype={jquery:p,constructor:x,init:function(e,t,n){var r,i;if(!e)return this;if("string"==typeof e){if(r="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:T.exec(e),!r||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof x?t[0]:t,x.merge(this,x.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:o,!0)),C.test(r[1])&&x.isPlainObject(t))for(r in t)x.isFunction(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return i=o.getElementById(r[2]),i&&i.parentNode&&(this.length=1,this[0]=i),this.context=o,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):x.isFunction(e)?n.ready(e):(e.selector!==undefined&&(this.selector=e.selector,this.context=e.context),x.makeArray(e,this))},selector:"",length:0,toArray:function(){return d.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=x.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return x.each(this,e,t)},ready:function(e){return x.ready.promise().done(e),this},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(x.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:h,sort:[].sort,splice:[].splice},x.fn.init.prototype=x.fn,x.extend=x.fn.extend=function(){var e,t,n,r,i,o,s=arguments[0]||{},a=1,u=arguments.length,l=!1;for("boolean"==typeof s&&(l=s,s=arguments[1]||{},a=2),"object"==typeof s||x.isFunction(s)||(s={}),u===a&&(s=this,--a);u>a;a++)if(null!=(e=arguments[a]))for(t in e)n=s[t],r=e[t],s!==r&&(l&&r&&(x.isPlainObject(r)||(i=x.isArray(r)))?(i?(i=!1,o=n&&x.isArray(n)?n:[]):o=n&&x.isPlainObject(n)?n:{},s[t]=x.extend(l,o,r)):r!==undefined&&(s[t]=r));return s},x.extend({expando:"jQuery"+(p+Math.random()).replace(/\D/g,""),noConflict:function(t){return e.$===x&&(e.$=u),t&&e.jQuery===x&&(e.jQuery=a),x},isReady:!1,readyWait:1,holdReady:function(e){e?x.readyWait++:x.ready(!0)},ready:function(e){(e===!0?--x.readyWait:x.isReady)||(x.isReady=!0,e!==!0&&--x.readyWait>0||(n.resolveWith(o,[x]),x.fn.trigger&&x(o).trigger("ready").off("ready")))},isFunction:function(e){return"function"===x.type(e)},isArray:Array.isArray,isWindow:function(e){return null!=e&&e===e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[m.call(e)]||"object":typeof e},isPlainObject:function(e){if("object"!==x.type(e)||e.nodeType||x.isWindow(e))return!1;try{if(e.constructor&&!y.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(t){return!1}return!0},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||o;var r=C.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=x.buildFragment([e],t,i),i&&x(i).remove(),x.merge([],r.childNodes))},parseJSON:JSON.parse,parseXML:function(e){var t,n;if(!e||"string"!=typeof e)return null;try{n=new DOMParser,t=n.parseFromString(e,"text/xml")}catch(r){t=undefined}return(!t||t.getElementsByTagName("parsererror").length)&&x.error("Invalid XML: "+e),t},noop:function(){},globalEval:function(e){var t,n=eval;e=x.trim(e),e&&(1===e.indexOf("use strict")?(t=o.createElement("script"),t.text=e,o.head.appendChild(t).parentNode.removeChild(t)):n(e))},camelCase:function(e){return e.replace(k,"ms-").replace(N,E)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,s=j(e);if(n){if(s){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(s){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:function(e){return null==e?"":v.call(e)},makeArray:function(e,t){var n=t||[];return null!=e&&(j(Object(e))?x.merge(n,"string"==typeof e?[e]:e):h.call(n,e)),n},inArray:function(e,t,n){return null==t?-1:g.call(t,e,n)},merge:function(e,t){var n=t.length,r=e.length,i=0;if("number"==typeof n)for(;n>i;i++)e[r++]=t[i];else while(t[i]!==undefined)e[r++]=t[i++];return e.length=r,e},grep:function(e,t,n){var r,i=[],o=0,s=e.length;for(n=!!n;s>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,s=j(e),a=[];if(s)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(a[a.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(a[a.length]=r);return f.apply([],a)},guid:1,proxy:function(e,t){var n,r,i;return"string"==typeof t&&(n=e[t],t=e,e=n),x.isFunction(e)?(r=d.call(arguments,2),i=function(){return e.apply(t||this,r.concat(d.call(arguments)))},i.guid=e.guid=e.guid||x.guid++,i):undefined},access:function(e,t,n,r,i,o,s){var a=0,u=e.length,l=null==n;if("object"===x.type(n)){i=!0;for(a in n)x.access(e,t,a,n[a],!0,o,s)}else if(r!==undefined&&(i=!0,x.isFunction(r)||(s=!0),l&&(s?(t.call(e,r),t=null):(l=t,t=function(e,t,n){return l.call(x(e),n)})),t))for(;u>a;a++)t(e[a],n,s?r:r.call(e[a],a,t(e[a],n)));return i?e:l?t.call(e):u?t(e[0],n):o},now:Date.now,swap:function(e,t,n,r){var i,o,s={};for(o in t)s[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=s[o];return i}}),x.ready.promise=function(t){return n||(n=x.Deferred(),"complete"===o.readyState?setTimeout(x.ready):(o.addEventListener("DOMContentLoaded",S,!1),e.addEventListener("load",S,!1))),n.promise(t)},x.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function j(e){var t=e.length,n=x.type(e);return x.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}t=x(o),function(e,undefined){var t,n,r,i,o,s,a,u,l,c,p,f,h,d,g,m,y,v="sizzle"+-new Date,b=e.document,w=0,T=0,C=st(),k=st(),N=st(),E=!1,S=function(e,t){return e===t?(E=!0,0):0},j=typeof undefined,D=1<<31,A={}.hasOwnProperty,L=[],q=L.pop,H=L.push,O=L.push,F=L.slice,P=L.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},R="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",W="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",$=W.replace("w","w#"),B="\\["+M+"*("+W+")"+M+"*(?:([*^$|!~]?=)"+M+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+$+")|)|)"+M+"*\\]",I=":("+W+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+B.replace(3,8)+")*)|.*)\\)|)",z=RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),_=RegExp("^"+M+"*,"+M+"*"),X=RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=RegExp(M+"*[+~]"),Y=RegExp("="+M+"*([^\\]'\"]*)"+M+"*\\]","g"),V=RegExp(I),G=RegExp("^"+$+"$"),J={ID:RegExp("^#("+W+")"),CLASS:RegExp("^\\.("+W+")"),TAG:RegExp("^("+W.replace("w","w*")+")"),ATTR:RegExp("^"+B),PSEUDO:RegExp("^"+I),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:RegExp("^(?:"+R+")$","i"),needsContext:RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Q=/^[^{]+\{\s*\[native \w/,K=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,Z=/^(?:input|select|textarea|button)$/i,et=/^h\d$/i,tt=/'|\\/g,nt=RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),rt=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(55296|r>>10,56320|1023&r)};try{O.apply(L=F.call(b.childNodes),b.childNodes),L[b.childNodes.length].nodeType}catch(it){O={apply:L.length?function(e,t){H.apply(e,F.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function ot(e,t,r,i){var o,s,a,u,l,f,g,m,x,w;if((t?t.ownerDocument||t:b)!==p&&c(t),t=t||p,r=r||[],!e||"string"!=typeof e)return r;if(1!==(u=t.nodeType)&&9!==u)return[];if(h&&!i){if(o=K.exec(e))if(a=o[1]){if(9===u){if(s=t.getElementById(a),!s||!s.parentNode)return r;if(s.id===a)return r.push(s),r}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(a))&&y(t,s)&&s.id===a)return r.push(s),r}else{if(o[2])return O.apply(r,t.getElementsByTagName(e)),r;if((a=o[3])&&n.getElementsByClassName&&t.getElementsByClassName)return O.apply(r,t.getElementsByClassName(a)),r}if(n.qsa&&(!d||!d.test(e))){if(m=g=v,x=t,w=9===u&&e,1===u&&"object"!==t.nodeName.toLowerCase()){f=gt(e),(g=t.getAttribute("id"))?m=g.replace(tt,"\\$&"):t.setAttribute("id",m),m="[id='"+m+"'] ",l=f.length;while(l--)f[l]=m+mt(f[l]);x=U.test(e)&&t.parentNode||t,w=f.join(",")}if(w)try{return O.apply(r,x.querySelectorAll(w)),r}catch(T){}finally{g||t.removeAttribute("id")}}}return kt(e.replace(z,"$1"),t,r,i)}function st(){var e=[];function t(n,r){return e.push(n+=" ")>i.cacheLength&&delete t[e.shift()],t[n]=r}return t}function at(e){return e[v]=!0,e}function ut(e){var t=p.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function lt(e,t){var n=e.split("|"),r=e.length;while(r--)i.attrHandle[n[r]]=t}function ct(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||D)-(~e.sourceIndex||D);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function pt(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function ft(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function ht(e){return at(function(t){return t=+t,at(function(n,r){var i,o=e([],n.length,t),s=o.length;while(s--)n[i=o[s]]&&(n[i]=!(r[i]=n[i]))})})}s=ot.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},n=ot.support={},c=ot.setDocument=function(e){var t=e?e.ownerDocument||e:b,r=t.defaultView;return t!==p&&9===t.nodeType&&t.documentElement?(p=t,f=t.documentElement,h=!s(t),r&&r.attachEvent&&r!==r.top&&r.attachEvent("onbeforeunload",function(){c()}),n.attributes=ut(function(e){return e.className="i",!e.getAttribute("className")}),n.getElementsByTagName=ut(function(e){return e.appendChild(t.createComment("")),!e.getElementsByTagName("*").length}),n.getElementsByClassName=ut(function(e){return e.innerHTML="<div class='a'></div><div class='a i'></div>",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),n.getById=ut(function(e){return f.appendChild(e).id=v,!t.getElementsByName||!t.getElementsByName(v).length}),n.getById?(i.find.ID=function(e,t){if(typeof t.getElementById!==j&&h){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},i.filter.ID=function(e){var t=e.replace(nt,rt);return function(e){return e.getAttribute("id")===t}}):(delete i.find.ID,i.filter.ID=function(e){var t=e.replace(nt,rt);return function(e){var n=typeof e.getAttributeNode!==j&&e.getAttributeNode("id");return n&&n.value===t}}),i.find.TAG=n.getElementsByTagName?function(e,t){return typeof t.getElementsByTagName!==j?t.getElementsByTagName(e):undefined}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},i.find.CLASS=n.getElementsByClassName&&function(e,t){return typeof t.getElementsByClassName!==j&&h?t.getElementsByClassName(e):undefined},g=[],d=[],(n.qsa=Q.test(t.querySelectorAll))&&(ut(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||d.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll(":checked").length||d.push(":checked")}),ut(function(e){var n=t.createElement("input");n.setAttribute("type","hidden"),e.appendChild(n).setAttribute("t",""),e.querySelectorAll("[t^='']").length&&d.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll(":enabled").length||d.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),d.push(",.*:")})),(n.matchesSelector=Q.test(m=f.webkitMatchesSelector||f.mozMatchesSelector||f.oMatchesSelector||f.msMatchesSelector))&&ut(function(e){n.disconnectedMatch=m.call(e,"div"),m.call(e,"[s!='']:x"),g.push("!=",I)}),d=d.length&&RegExp(d.join("|")),g=g.length&&RegExp(g.join("|")),y=Q.test(f.contains)||f.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},S=f.compareDocumentPosition?function(e,r){if(e===r)return E=!0,0;var i=r.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(r);return i?1&i||!n.sortDetached&&r.compareDocumentPosition(e)===i?e===t||y(b,e)?-1:r===t||y(b,r)?1:l?P.call(l,e)-P.call(l,r):0:4&i?-1:1:e.compareDocumentPosition?-1:1}:function(e,n){var r,i=0,o=e.parentNode,s=n.parentNode,a=[e],u=[n];if(e===n)return E=!0,0;if(!o||!s)return e===t?-1:n===t?1:o?-1:s?1:l?P.call(l,e)-P.call(l,n):0;if(o===s)return ct(e,n);r=e;while(r=r.parentNode)a.unshift(r);r=n;while(r=r.parentNode)u.unshift(r);while(a[i]===u[i])i++;return i?ct(a[i],u[i]):a[i]===b?-1:u[i]===b?1:0},t):p},ot.matches=function(e,t){return ot(e,null,null,t)},ot.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&c(e),t=t.replace(Y,"='$1']"),!(!n.matchesSelector||!h||g&&g.test(t)||d&&d.test(t)))try{var r=m.call(e,t);if(r||n.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(i){}return ot(t,p,null,[e]).length>0},ot.contains=function(e,t){return(e.ownerDocument||e)!==p&&c(e),y(e,t)},ot.attr=function(e,t){(e.ownerDocument||e)!==p&&c(e);var r=i.attrHandle[t.toLowerCase()],o=r&&A.call(i.attrHandle,t.toLowerCase())?r(e,t,!h):undefined;return o===undefined?n.attributes||!h?e.getAttribute(t):(o=e.getAttributeNode(t))&&o.specified?o.value:null:o},ot.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},ot.uniqueSort=function(e){var t,r=[],i=0,o=0;if(E=!n.detectDuplicates,l=!n.sortStable&&e.slice(0),e.sort(S),E){while(t=e[o++])t===e[o]&&(i=r.push(o));while(i--)e.splice(r[i],1)}return e},o=ot.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=o(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=o(t);return n},i=ot.selectors={cacheLength:50,createPseudo:at,match:J,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(nt,rt),e[3]=(e[4]||e[5]||"").replace(nt,rt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||ot.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&ot.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return J.CHILD.test(e[0])?null:(e[3]&&e[4]!==undefined?e[2]=e[4]:n&&V.test(n)&&(t=gt(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(nt,rt).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=C[e+" "];return t||(t=RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&C(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==j&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=ot.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),s="last"!==e.slice(-4),a="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,p,f,h,d,g=o!==s?"nextSibling":"previousSibling",m=t.parentNode,y=a&&t.nodeName.toLowerCase(),x=!u&&!a;if(m){if(o){while(g){p=t;while(p=p[g])if(a?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;d=g="only"===e&&!d&&"nextSibling"}return!0}if(d=[s?m.firstChild:m.lastChild],s&&x){c=m[v]||(m[v]={}),l=c[e]||[],h=l[0]===w&&l[1],f=l[0]===w&&l[2],p=h&&m.childNodes[h];while(p=++h&&p&&p[g]||(f=h=0)||d.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[w,h,f];break}}else if(x&&(l=(t[v]||(t[v]={}))[e])&&l[0]===w)f=l[1];else while(p=++h&&p&&p[g]||(f=h=0)||d.pop())if((a?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(x&&((p[v]||(p[v]={}))[e]=[w,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||ot.error("unsupported pseudo: "+e);return r[v]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?at(function(e,n){var i,o=r(e,t),s=o.length;while(s--)i=P.call(e,o[s]),e[i]=!(n[i]=o[s])}):function(e){return r(e,0,n)}):r}},pseudos:{not:at(function(e){var t=[],n=[],r=a(e.replace(z,"$1"));return r[v]?at(function(e,t,n,i){var o,s=r(e,null,i,[]),a=e.length;while(a--)(o=s[a])&&(e[a]=!(t[a]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:at(function(e){return function(t){return ot(e,t).length>0}}),contains:at(function(e){return function(t){return(t.textContent||t.innerText||o(t)).indexOf(e)>-1}}),lang:at(function(e){return G.test(e||"")||ot.error("unsupported lang: "+e),e=e.replace(nt,rt).toLowerCase(),function(t){var n;do if(n=h?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===f},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!i.pseudos.empty(e)},header:function(e){return et.test(e.nodeName)},input:function(e){return Z.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:ht(function(){return[0]}),last:ht(function(e,t){return[t-1]}),eq:ht(function(e,t,n){return[0>n?n+t:n]}),even:ht(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:ht(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:ht(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:ht(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}},i.pseudos.nth=i.pseudos.eq;for(t in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})i.pseudos[t]=pt(t);for(t in{submit:!0,reset:!0})i.pseudos[t]=ft(t);function dt(){}dt.prototype=i.filters=i.pseudos,i.setFilters=new dt;function gt(e,t){var n,r,o,s,a,u,l,c=k[e+" "];if(c)return t?0:c.slice(0);a=e,u=[],l=i.preFilter;while(a){(!n||(r=_.exec(a)))&&(r&&(a=a.slice(r[0].length)||a),u.push(o=[])),n=!1,(r=X.exec(a))&&(n=r.shift(),o.push({value:n,type:r[0].replace(z," ")}),a=a.slice(n.length));for(s in i.filter)!(r=J[s].exec(a))||l[s]&&!(r=l[s](r))||(n=r.shift(),o.push({value:n,type:s,matches:r}),a=a.slice(n.length));if(!n)break}return t?a.length:a?ot.error(e):k(e,u).slice(0)}function mt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function yt(e,t,n){var i=t.dir,o=n&&"parentNode"===i,s=T++;return t.first?function(t,n,r){while(t=t[i])if(1===t.nodeType||o)return e(t,n,r)}:function(t,n,a){var u,l,c,p=w+" "+s;if(a){while(t=t[i])if((1===t.nodeType||o)&&e(t,n,a))return!0}else while(t=t[i])if(1===t.nodeType||o)if(c=t[v]||(t[v]={}),(l=c[i])&&l[0]===p){if((u=l[1])===!0||u===r)return u===!0}else if(l=c[i]=[p],l[1]=e(t,n,a)||r,l[1]===!0)return!0}}function vt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function xt(e,t,n,r,i){var o,s=[],a=0,u=e.length,l=null!=t;for(;u>a;a++)(o=e[a])&&(!n||n(o,r,i))&&(s.push(o),l&&t.push(a));return s}function bt(e,t,n,r,i,o){return r&&!r[v]&&(r=bt(r)),i&&!i[v]&&(i=bt(i,o)),at(function(o,s,a,u){var l,c,p,f=[],h=[],d=s.length,g=o||Ct(t||"*",a.nodeType?[a]:a,[]),m=!e||!o&&t?g:xt(g,f,e,a,u),y=n?i||(o?e:d||r)?[]:s:m;if(n&&n(m,y,a,u),r){l=xt(y,h),r(l,[],a,u),c=l.length;while(c--)(p=l[c])&&(y[h[c]]=!(m[h[c]]=p))}if(o){if(i||e){if(i){l=[],c=y.length;while(c--)(p=y[c])&&l.push(m[c]=p);i(null,y=[],l,u)}c=y.length;while(c--)(p=y[c])&&(l=i?P.call(o,p):f[c])>-1&&(o[l]=!(s[l]=p))}}else y=xt(y===s?y.splice(d,y.length):y),i?i(null,s,y,u):O.apply(s,y)})}function wt(e){var t,n,r,o=e.length,s=i.relative[e[0].type],a=s||i.relative[" "],l=s?1:0,c=yt(function(e){return e===t},a,!0),p=yt(function(e){return P.call(t,e)>-1},a,!0),f=[function(e,n,r){return!s&&(r||n!==u)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;o>l;l++)if(n=i.relative[e[l].type])f=[yt(vt(f),n)];else{if(n=i.filter[e[l].type].apply(null,e[l].matches),n[v]){for(r=++l;o>r;r++)if(i.relative[e[r].type])break;return bt(l>1&&vt(f),l>1&&mt(e.slice(0,l-1).concat({value:" "===e[l-2].type?"*":""})).replace(z,"$1"),n,r>l&&wt(e.slice(l,r)),o>r&&wt(e=e.slice(r)),o>r&&mt(e))}f.push(n)}return vt(f)}function Tt(e,t){var n=0,o=t.length>0,s=e.length>0,a=function(a,l,c,f,h){var d,g,m,y=[],v=0,x="0",b=a&&[],T=null!=h,C=u,k=a||s&&i.find.TAG("*",h&&l.parentNode||l),N=w+=null==C?1:Math.random()||.1;for(T&&(u=l!==p&&l,r=n);null!=(d=k[x]);x++){if(s&&d){g=0;while(m=e[g++])if(m(d,l,c)){f.push(d);break}T&&(w=N,r=++n)}o&&((d=!m&&d)&&v--,a&&b.push(d))}if(v+=x,o&&x!==v){g=0;while(m=t[g++])m(b,y,l,c);if(a){if(v>0)while(x--)b[x]||y[x]||(y[x]=q.call(f));y=xt(y)}O.apply(f,y),T&&!a&&y.length>0&&v+t.length>1&&ot.uniqueSort(f)}return T&&(w=N,u=C),b};return o?at(a):a}a=ot.compile=function(e,t){var n,r=[],i=[],o=N[e+" "];if(!o){t||(t=gt(e)),n=t.length;while(n--)o=wt(t[n]),o[v]?r.push(o):i.push(o);o=N(e,Tt(i,r))}return o};function Ct(e,t,n){var r=0,i=t.length;for(;i>r;r++)ot(e,t[r],n);return n}function kt(e,t,r,o){var s,u,l,c,p,f=gt(e);if(!o&&1===f.length){if(u=f[0]=f[0].slice(0),u.length>2&&"ID"===(l=u[0]).type&&n.getById&&9===t.nodeType&&h&&i.relative[u[1].type]){if(t=(i.find.ID(l.matches[0].replace(nt,rt),t)||[])[0],!t)return r;e=e.slice(u.shift().value.length)}s=J.needsContext.test(e)?0:u.length;while(s--){if(l=u[s],i.relative[c=l.type])break;if((p=i.find[c])&&(o=p(l.matches[0].replace(nt,rt),U.test(u[0].type)&&t.parentNode||t))){if(u.splice(s,1),e=o.length&&mt(u),!e)return O.apply(r,o),r;break}}}return a(e,f)(o,t,!h,r,U.test(e)),r}n.sortStable=v.split("").sort(S).join("")===v,n.detectDuplicates=E,c(),n.sortDetached=ut(function(e){return 1&e.compareDocumentPosition(p.createElement("div"))}),ut(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||lt("type|href|height|width",function(e,t,n){return n?undefined:e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),n.attributes&&ut(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||lt("value",function(e,t,n){return n||"input"!==e.nodeName.toLowerCase()?undefined:e.defaultValue}),ut(function(e){return null==e.getAttribute("disabled")})||lt(R,function(e,t,n){var r;return n?undefined:(r=e.getAttributeNode(t))&&r.specified?r.value:e[t]===!0?t.toLowerCase():null}),x.find=ot,x.expr=ot.selectors,x.expr[":"]=x.expr.pseudos,x.unique=ot.uniqueSort,x.text=ot.getText,x.isXMLDoc=ot.isXML,x.contains=ot.contains}(e);var D={};function A(e){var t=D[e]={};return x.each(e.match(w)||[],function(e,n){t[n]=!0}),t}x.Callbacks=function(e){e="string"==typeof e?D[e]||A(e):x.extend({},e);var t,n,r,i,o,s,a=[],u=!e.once&&[],l=function(p){for(t=e.memory&&p,n=!0,s=i||0,i=0,o=a.length,r=!0;a&&o>s;s++)if(a[s].apply(p[0],p[1])===!1&&e.stopOnFalse){t=!1;break}r=!1,a&&(u?u.length&&l(u.shift()):t?a=[]:c.disable())},c={add:function(){if(a){var n=a.length;(function s(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&c.has(n)||a.push(n):n&&n.length&&"string"!==r&&s(n)})})(arguments),r?o=a.length:t&&(i=n,l(t))}return this},remove:function(){return a&&x.each(arguments,function(e,t){var n;while((n=x.inArray(t,a,n))>-1)a.splice(n,1),r&&(o>=n&&o--,s>=n&&s--)}),this},has:function(e){return e?x.inArray(e,a)>-1:!(!a||!a.length)},empty:function(){return a=[],o=0,this},disable:function(){return a=u=t=undefined,this},disabled:function(){return!a},lock:function(){return u=undefined,t||c.disable(),this},locked:function(){return!u},fireWith:function(e,t){return!a||n&&!u||(t=t||[],t=[e,t.slice?t.slice():t],r?u.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!n}};return c},x.extend({Deferred:function(e){var t=[["resolve","done",x.Callbacks("once memory"),"resolved"],["reject","fail",x.Callbacks("once memory"),"rejected"],["notify","progress",x.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return x.Deferred(function(n){x.each(t,function(t,o){var s=o[0],a=x.isFunction(e[t])&&e[t];i[o[1]](function(){var e=a&&a.apply(this,arguments);e&&x.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===r?n.promise():this,a?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?x.extend(e,r):r}},i={};return r.pipe=r.then,x.each(t,function(e,o){var s=o[2],a=o[3];r[o[1]]=s.add,a&&s.add(function(){n=a},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=s.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=d.call(arguments),r=n.length,i=1!==r||e&&x.isFunction(e.promise)?r:0,o=1===i?e:x.Deferred(),s=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?d.call(arguments):r,n===a?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},a,u,l;if(r>1)for(a=Array(r),u=Array(r),l=Array(r);r>t;t++)n[t]&&x.isFunction(n[t].promise)?n[t].promise().done(s(t,l,n)).fail(o.reject).progress(s(t,u,a)):--i;return i||o.resolveWith(l,n),o.promise()}}),x.support=function(t){var n=o.createElement("input"),r=o.createDocumentFragment(),i=o.createElement("div"),s=o.createElement("select"),a=s.appendChild(o.createElement("option"));return n.type?(n.type="checkbox",t.checkOn=""!==n.value,t.optSelected=a.selected,t.reliableMarginRight=!0,t.boxSizingReliable=!0,t.pixelPosition=!1,n.checked=!0,t.noCloneChecked=n.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!a.disabled,n=o.createElement("input"),n.value="t",n.type="radio",t.radioValue="t"===n.value,n.setAttribute("checked","t"),n.setAttribute("name","t"),r.appendChild(n),t.checkClone=r.cloneNode(!0).cloneNode(!0).lastChild.checked,t.focusinBubbles="onfocusin"in e,i.style.backgroundClip="content-box",i.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===i.style.backgroundClip,x(function(){var n,r,s="padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box",a=o.getElementsByTagName("body")[0];a&&(n=o.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",a.appendChild(n).appendChild(i),i.innerHTML="",i.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%",x.swap(a,null!=a.style.zoom?{zoom:1}:{},function(){t.boxSizing=4===i.offsetWidth}),e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(i,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(i,null)||{width:"4px"}).width,r=i.appendChild(o.createElement("div")),r.style.cssText=i.style.cssText=s,r.style.marginRight=r.style.width="0",i.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),a.removeChild(n))}),t):t}({});var L,q,H=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,O=/([A-Z])/g;function F(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=x.expando+Math.random()}F.uid=1,F.accepts=function(e){return e.nodeType?1===e.nodeType||9===e.nodeType:!0},F.prototype={key:function(e){if(!F.accepts(e))return 0;var t={},n=e[this.expando];if(!n){n=F.uid++;try{t[this.expando]={value:n},Object.defineProperties(e,t)}catch(r){t[this.expando]=n,x.extend(e,t)}}return this.cache[n]||(this.cache[n]={}),n},set:function(e,t,n){var r,i=this.key(e),o=this.cache[i];if("string"==typeof t)o[t]=n;else if(x.isEmptyObject(o))x.extend(this.cache[i],t);else for(r in t)o[r]=t[r];return o},get:function(e,t){var n=this.cache[this.key(e)];return t===undefined?n:n[t]},access:function(e,t,n){var r;return t===undefined||t&&"string"==typeof t&&n===undefined?(r=this.get(e,t),r!==undefined?r:this.get(e,x.camelCase(t))):(this.set(e,t,n),n!==undefined?n:t)},remove:function(e,t){var n,r,i,o=this.key(e),s=this.cache[o];if(t===undefined)this.cache[o]={};else{x.isArray(t)?r=t.concat(t.map(x.camelCase)):(i=x.camelCase(t),t in s?r=[t,i]:(r=i,r=r in s?[r]:r.match(w)||[])),n=r.length;while(n--)delete s[r[n]]}},hasData:function(e){return!x.isEmptyObject(this.cache[e[this.expando]]||{})},discard:function(e){e[this.expando]&&delete this.cache[e[this.expando]]}},L=new F,q=new F,x.extend({acceptData:F.accepts,hasData:function(e){return L.hasData(e)||q.hasData(e)},data:function(e,t,n){return L.access(e,t,n)},removeData:function(e,t){L.remove(e,t)},_data:function(e,t,n){return q.access(e,t,n)},_removeData:function(e,t){q.remove(e,t)}}),x.fn.extend({data:function(e,t){var n,r,i=this[0],o=0,s=null;if(e===undefined){if(this.length&&(s=L.get(i),1===i.nodeType&&!q.get(i,"hasDataAttrs"))){for(n=i.attributes;n.length>o;o++)r=n[o].name,0===r.indexOf("data-")&&(r=x.camelCase(r.slice(5)),P(i,r,s[r]));q.set(i,"hasDataAttrs",!0)}return s}return"object"==typeof e?this.each(function(){L.set(this,e)}):x.access(this,function(t){var n,r=x.camelCase(e);if(i&&t===undefined){if(n=L.get(i,e),n!==undefined)return n;if(n=L.get(i,r),n!==undefined)return n;if(n=P(i,r,undefined),n!==undefined)return n}else this.each(function(){var n=L.get(this,r);L.set(this,r,t),-1!==e.indexOf("-")&&n!==undefined&&L.set(this,e,t)})},null,t,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){L.remove(this,e)})}});function P(e,t,n){var r;if(n===undefined&&1===e.nodeType)if(r="data-"+t.replace(O,"-$1").toLowerCase(),n=e.getAttribute(r),"string"==typeof n){try{n="true"===n?!0:"false"===n?!1:"null"===n?null:+n+""===n?+n:H.test(n)?JSON.parse(n):n}catch(i){}L.set(e,t,n)}else n=undefined;return n}x.extend({queue:function(e,t,n){var r;return e?(t=(t||"fx")+"queue",r=q.get(e,t),n&&(!r||x.isArray(n)?r=q.access(e,t,x.makeArray(n)):r.push(n)),r||[]):undefined},dequeue:function(e,t){t=t||"fx";var n=x.queue(e,t),r=n.length,i=n.shift(),o=x._queueHooks(e,t),s=function(){x.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,s,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return q.get(e,n)||q.access(e,n,{empty:x.Callbacks("once memory").add(function(){q.remove(e,[t+"queue",n])})})}}),x.fn.extend({queue:function(e,t){var n=2;return"string"!=typeof e&&(t=e,e="fx",n--),n>arguments.length?x.queue(this[0],e):t===undefined?this:this.each(function(){var n=x.queue(this,e,t);x._queueHooks(this,e),"fx"===e&&"inprogress"!==n[0]&&x.dequeue(this,e)})},dequeue:function(e){return this.each(function(){x.dequeue(this,e)})},delay:function(e,t){return e=x.fx?x.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,r=1,i=x.Deferred(),o=this,s=this.length,a=function(){--r||i.resolveWith(o,[o])};"string"!=typeof e&&(t=e,e=undefined),e=e||"fx";while(s--)n=q.get(o[s],e+"queueHooks"),n&&n.empty&&(r++,n.empty.add(a));return a(),i.promise(t)}});var R,M,W=/[\t\r\n\f]/g,$=/\r/g,B=/^(?:input|select|textarea|button)$/i;x.fn.extend({attr:function(e,t){return x.access(this,x.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){x.removeAttr(this,e)})},prop:function(e,t){return x.access(this,x.prop,e,t,arguments.length>1)},removeProp:function(e){return this.each(function(){delete this[x.propFix[e]||e]})},addClass:function(e){var t,n,r,i,o,s=0,a=this.length,u="string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];a>s;s++)if(n=this[s],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(W," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=x.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,s=0,a=this.length,u=0===arguments.length||"string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];a>s;s++)if(n=this[s],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(W," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?x.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):x.isFunction(e)?this.each(function(n){x(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var t,i=0,o=x(this),s=e.match(w)||[];while(t=s[i++])o.hasClass(t)?o.removeClass(t):o.addClass(t)}else(n===r||"boolean"===n)&&(this.className&&q.set(this,"__className__",this.className),this.className=this.className||e===!1?"":q.get(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(W," ").indexOf(t)>=0)return!0;return!1},val:function(e){var t,n,r,i=this[0];{if(arguments.length)return r=x.isFunction(e),this.each(function(n){var i;1===this.nodeType&&(i=r?e.call(this,n,x(this).val()):e,null==i?i="":"number"==typeof i?i+="":x.isArray(i)&&(i=x.map(i,function(e){return null==e?"":e+""})),t=x.valHooks[this.type]||x.valHooks[this.nodeName.toLowerCase()],t&&"set"in t&&t.set(this,i,"value")!==undefined||(this.value=i))});if(i)return t=x.valHooks[i.type]||x.valHooks[i.nodeName.toLowerCase()],t&&"get"in t&&(n=t.get(i,"value"))!==undefined?n:(n=i.value,"string"==typeof n?n.replace($,""):null==n?"":n)}}}),x.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,s=o?null:[],a=o?i+1:r.length,u=0>i?a:o?i:0;for(;a>u;u++)if(n=r[u],!(!n.selected&&u!==i||(x.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&x.nodeName(n.parentNode,"optgroup"))){if(t=x(n).val(),o)return t;s.push(t)}return s},set:function(e,t){var n,r,i=e.options,o=x.makeArray(t),s=i.length;while(s--)r=i[s],(r.selected=x.inArray(x(r).val(),o)>=0)&&(n=!0);return n||(e.selectedIndex=-1),o}}},attr:function(e,t,n){var i,o,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return typeof e.getAttribute===r?x.prop(e,t,n):(1===s&&x.isXMLDoc(e)||(t=t.toLowerCase(),i=x.attrHooks[t]||(x.expr.match.bool.test(t)?M:R)),n===undefined?i&&"get"in i&&null!==(o=i.get(e,t))?o:(o=x.find.attr(e,t),null==o?undefined:o):null!==n?i&&"set"in i&&(o=i.set(e,n,t))!==undefined?o:(e.setAttribute(t,n+""),n):(x.removeAttr(e,t),undefined))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(w);if(o&&1===e.nodeType)while(n=o[i++])r=x.propFix[n]||n,x.expr.match.bool.test(n)&&(e[r]=!1),e.removeAttribute(n)},attrHooks:{type:{set:function(e,t){if(!x.support.radioValue&&"radio"===t&&x.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{"for":"htmlFor","class":"className"},prop:function(e,t,n){var r,i,o,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return o=1!==s||!x.isXMLDoc(e),o&&(t=x.propFix[t]||t,i=x.propHooks[t]),n!==undefined?i&&"set"in i&&(r=i.set(e,n,t))!==undefined?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){return e.hasAttribute("tabindex")||B.test(e.nodeName)||e.href?e.tabIndex:-1}}}}),M={set:function(e,t,n){return t===!1?x.removeAttr(e,n):e.setAttribute(n,n),n}},x.each(x.expr.match.bool.source.match(/\w+/g),function(e,t){var n=x.expr.attrHandle[t]||x.find.attr;x.expr.attrHandle[t]=function(e,t,r){var i=x.expr.attrHandle[t],o=r?undefined:(x.expr.attrHandle[t]=undefined)!=n(e,t,r)?t.toLowerCase():null;return x.expr.attrHandle[t]=i,o}}),x.support.optSelected||(x.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null}}),x.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){x.propFix[this.toLowerCase()]=this}),x.each(["radio","checkbox"],function(){x.valHooks[this]={set:function(e,t){return x.isArray(t)?e.checked=x.inArray(x(e).val(),t)>=0:undefined}},x.support.checkOn||(x.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var I=/^key/,z=/^(?:mouse|contextmenu)|click/,_=/^(?:focusinfocus|focusoutblur)$/,X=/^([^.]*)(?:\.(.+)|)$/;function U(){return!0}function Y(){return!1}function V(){try{return o.activeElement}catch(e){}}x.event={global:{},add:function(e,t,n,i,o){var s,a,u,l,c,p,f,h,d,g,m,y=q.get(e);if(y){n.handler&&(s=n,n=s.handler,o=s.selector),n.guid||(n.guid=x.guid++),(l=y.events)||(l=y.events={}),(a=y.handle)||(a=y.handle=function(e){return typeof x===r||e&&x.event.triggered===e.type?undefined:x.event.dispatch.apply(a.elem,arguments)},a.elem=e),t=(t||"").match(w)||[""],c=t.length;while(c--)u=X.exec(t[c])||[],d=m=u[1],g=(u[2]||"").split(".").sort(),d&&(f=x.event.special[d]||{},d=(o?f.delegateType:f.bindType)||d,f=x.event.special[d]||{},p=x.extend({type:d,origType:m,data:i,handler:n,guid:n.guid,selector:o,needsContext:o&&x.expr.match.needsContext.test(o),namespace:g.join(".")},s),(h=l[d])||(h=l[d]=[],h.delegateCount=0,f.setup&&f.setup.call(e,i,g,a)!==!1||e.addEventListener&&e.addEventListener(d,a,!1)),f.add&&(f.add.call(e,p),p.handler.guid||(p.handler.guid=n.guid)),o?h.splice(h.delegateCount++,0,p):h.push(p),x.event.global[d]=!0);e=null}},remove:function(e,t,n,r,i){var o,s,a,u,l,c,p,f,h,d,g,m=q.hasData(e)&&q.get(e);if(m&&(u=m.events)){t=(t||"").match(w)||[""],l=t.length;while(l--)if(a=X.exec(t[l])||[],h=g=a[1],d=(a[2]||"").split(".").sort(),h){p=x.event.special[h]||{},h=(r?p.delegateType:p.bindType)||h,f=u[h]||[],a=a[2]&&RegExp("(^|\\.)"+d.join("\\.(?:.*\\.|)")+"(\\.|$)"),s=o=f.length;while(o--)c=f[o],!i&&g!==c.origType||n&&n.guid!==c.guid||a&&!a.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(f.splice(o,1),c.selector&&f.delegateCount--,p.remove&&p.remove.call(e,c));s&&!f.length&&(p.teardown&&p.teardown.call(e,d,m.handle)!==!1||x.removeEvent(e,h,m.handle),delete u[h])}else for(h in u)x.event.remove(e,h+t[l],n,r,!0);x.isEmptyObject(u)&&(delete m.handle,q.remove(e,"events"))}},trigger:function(t,n,r,i){var s,a,u,l,c,p,f,h=[r||o],d=y.call(t,"type")?t.type:t,g=y.call(t,"namespace")?t.namespace.split("."):[];if(a=u=r=r||o,3!==r.nodeType&&8!==r.nodeType&&!_.test(d+x.event.triggered)&&(d.indexOf(".")>=0&&(g=d.split("."),d=g.shift(),g.sort()),c=0>d.indexOf(":")&&"on"+d,t=t[x.expando]?t:new x.Event(d,"object"==typeof t&&t),t.isTrigger=i?2:3,t.namespace=g.join("."),t.namespace_re=t.namespace?RegExp("(^|\\.)"+g.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,t.result=undefined,t.target||(t.target=r),n=null==n?[t]:x.makeArray(n,[t]),f=x.event.special[d]||{},i||!f.trigger||f.trigger.apply(r,n)!==!1)){if(!i&&!f.noBubble&&!x.isWindow(r)){for(l=f.delegateType||d,_.test(l+d)||(a=a.parentNode);a;a=a.parentNode)h.push(a),u=a;u===(r.ownerDocument||o)&&h.push(u.defaultView||u.parentWindow||e)}s=0;while((a=h[s++])&&!t.isPropagationStopped())t.type=s>1?l:f.bindType||d,p=(q.get(a,"events")||{})[t.type]&&q.get(a,"handle"),p&&p.apply(a,n),p=c&&a[c],p&&x.acceptData(a)&&p.apply&&p.apply(a,n)===!1&&t.preventDefault();return t.type=d,i||t.isDefaultPrevented()||f._default&&f._default.apply(h.pop(),n)!==!1||!x.acceptData(r)||c&&x.isFunction(r[d])&&!x.isWindow(r)&&(u=r[c],u&&(r[c]=null),x.event.triggered=d,r[d](),x.event.triggered=undefined,u&&(r[c]=u)),t.result}},dispatch:function(e){e=x.event.fix(e);var t,n,r,i,o,s=[],a=d.call(arguments),u=(q.get(this,"events")||{})[e.type]||[],l=x.event.special[e.type]||{};if(a[0]=e,e.delegateTarget=this,!l.preDispatch||l.preDispatch.call(this,e)!==!1){s=x.event.handlers.call(this,e,u),t=0;while((i=s[t++])&&!e.isPropagationStopped()){e.currentTarget=i.elem,n=0;while((o=i.handlers[n++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(o.namespace))&&(e.handleObj=o,e.data=o.data,r=((x.event.special[o.origType]||{}).handle||o.handler).apply(i.elem,a),r!==undefined&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return l.postDispatch&&l.postDispatch.call(this,e),e.result}},handlers:function(e,t){var n,r,i,o,s=[],a=t.delegateCount,u=e.target;if(a&&u.nodeType&&(!e.button||"click"!==e.type))for(;u!==this;u=u.parentNode||this)if(u.disabled!==!0||"click"!==e.type){for(r=[],n=0;a>n;n++)o=t[n],i=o.selector+" ",r[i]===undefined&&(r[i]=o.needsContext?x(i,this).index(u)>=0:x.find(i,this,null,[u]).length),r[i]&&r.push(o);r.length&&s.push({elem:u,handlers:r})}return t.length>a&&s.push({elem:this,handlers:t.slice(a)}),s},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,t){var n,r,i,s=t.button;return null==e.pageX&&null!=t.clientX&&(n=e.target.ownerDocument||o,r=n.documentElement,i=n.body,e.pageX=t.clientX+(r&&r.scrollLeft||i&&i.scrollLeft||0)-(r&&r.clientLeft||i&&i.clientLeft||0),e.pageY=t.clientY+(r&&r.scrollTop||i&&i.scrollTop||0)-(r&&r.clientTop||i&&i.clientTop||0)),e.which||s===undefined||(e.which=1&s?1:2&s?3:4&s?2:0),e}},fix:function(e){if(e[x.expando])return e;var t,n,r,i=e.type,s=e,a=this.fixHooks[i];a||(this.fixHooks[i]=a=z.test(i)?this.mouseHooks:I.test(i)?this.keyHooks:{}),r=a.props?this.props.concat(a.props):this.props,e=new x.Event(s),t=r.length;while(t--)n=r[t],e[n]=s[n];return e.target||(e.target=o),3===e.target.nodeType&&(e.target=e.target.parentNode),a.filter?a.filter(e,s):e},special:{load:{noBubble:!0},focus:{trigger:function(){return this!==V()&&this.focus?(this.focus(),!1):undefined},delegateType:"focusin"},blur:{trigger:function(){return this===V()&&this.blur?(this.blur(),!1):undefined},delegateType:"focusout"},click:{trigger:function(){return"checkbox"===this.type&&this.click&&x.nodeName(this,"input")?(this.click(),!1):undefined},_default:function(e){return x.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){e.result!==undefined&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=x.extend(new x.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?x.event.trigger(i,null,t):x.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},x.removeEvent=function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)},x.Event=function(e,t){return this instanceof x.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.getPreventDefault&&e.getPreventDefault()?U:Y):this.type=e,t&&x.extend(this,t),this.timeStamp=e&&e.timeStamp||x.now(),this[x.expando]=!0,undefined):new x.Event(e,t)},x.Event.prototype={isDefaultPrevented:Y,isPropagationStopped:Y,isImmediatePropagationStopped:Y,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=U,e&&e.preventDefault&&e.preventDefault()},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=U,e&&e.stopPropagation&&e.stopPropagation()},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=U,this.stopPropagation()}},x.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){x.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!x.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),x.support.focusinBubbles||x.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){x.event.simulate(t,e.target,x.event.fix(e),!0)};x.event.special[t]={setup:function(){0===n++&&o.addEventListener(e,r,!0)},teardown:function(){0===--n&&o.removeEventListener(e,r,!0)}}}),x.fn.extend({on:function(e,t,n,r,i){var o,s;if("object"==typeof e){"string"!=typeof t&&(n=n||t,t=undefined);for(s in e)this.on(s,t,n,e[s],i);return this}if(null==n&&null==r?(r=t,n=t=undefined):null==r&&("string"==typeof t?(r=n,n=undefined):(r=n,n=t,t=undefined)),r===!1)r=Y;else if(!r)return this;return 1===i&&(o=r,r=function(e){return x().off(e),o.apply(this,arguments)},r.guid=o.guid||(o.guid=x.guid++)),this.each(function(){x.event.add(this,e,r,n,t)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,t,n){var r,i;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,x(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof e){for(i in e)this.off(i,t,e[i]);return this}return(t===!1||"function"==typeof t)&&(n=t,t=undefined),n===!1&&(n=Y),this.each(function(){x.event.remove(this,e,n,t)})},trigger:function(e,t){return this.each(function(){x.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];return n?x.event.trigger(e,t,n,!0):undefined}});var G=/^.[^:#\[\.,]*$/,J=/^(?:parents|prev(?:Until|All))/,Q=x.expr.match.needsContext,K={children:!0,contents:!0,next:!0,prev:!0};x.fn.extend({find:function(e){var t,n=[],r=this,i=r.length;if("string"!=typeof e)return this.pushStack(x(e).filter(function(){for(t=0;i>t;t++)if(x.contains(r[t],this))return!0}));for(t=0;i>t;t++)x.find(e,r[t],n);return n=this.pushStack(i>1?x.unique(n):n),n.selector=this.selector?this.selector+" "+e:e,n},has:function(e){var t=x(e,this),n=t.length;return this.filter(function(){var e=0;for(;n>e;e++)if(x.contains(this,t[e]))return!0})},not:function(e){return this.pushStack(et(this,e||[],!0))},filter:function(e){return this.pushStack(et(this,e||[],!1))},is:function(e){return!!et(this,"string"==typeof e&&Q.test(e)?x(e):e||[],!1).length},closest:function(e,t){var n,r=0,i=this.length,o=[],s=Q.test(e)||"string"!=typeof e?x(e,t||this.context):0;for(;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(11>n.nodeType&&(s?s.index(n)>-1:1===n.nodeType&&x.find.matchesSelector(n,e))){n=o.push(n);break}return this.pushStack(o.length>1?x.unique(o):o)},index:function(e){return e?"string"==typeof e?g.call(x(e),this[0]):g.call(this,e.jquery?e[0]:e):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?x(e,t):x.makeArray(e&&e.nodeType?[e]:e),r=x.merge(this.get(),n);return this.pushStack(x.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function Z(e,t){while((e=e[t])&&1!==e.nodeType);return e}x.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return x.dir(e,"parentNode")},parentsUntil:function(e,t,n){return x.dir(e,"parentNode",n)},next:function(e){return Z(e,"nextSibling")},prev:function(e){return Z(e,"previousSibling")},nextAll:function(e){return x.dir(e,"nextSibling")},prevAll:function(e){return x.dir(e,"previousSibling")},nextUntil:function(e,t,n){return x.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return x.dir(e,"previousSibling",n)},siblings:function(e){return x.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return x.sibling(e.firstChild)},contents:function(e){return e.contentDocument||x.merge([],e.childNodes)}},function(e,t){x.fn[e]=function(n,r){var i=x.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=x.filter(r,i)),this.length>1&&(K[e]||x.unique(i),J.test(e)&&i.reverse()),this.pushStack(i)}}),x.extend({filter:function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?x.find.matchesSelector(r,e)?[r]:[]:x.find.matches(e,x.grep(t,function(e){return 1===e.nodeType}))},dir:function(e,t,n){var r=[],i=n!==undefined;while((e=e[t])&&9!==e.nodeType)if(1===e.nodeType){if(i&&x(e).is(n))break;r.push(e)}return r},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function et(e,t,n){if(x.isFunction(t))return x.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return x.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(G.test(t))return x.filter(t,e,n);t=x.filter(t,e)}return x.grep(e,function(e){return g.call(t,e)>=0!==n})}var tt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,nt=/<([\w:]+)/,rt=/<|&#?\w+;/,it=/<(?:script|style|link)/i,ot=/^(?:checkbox|radio)$/i,st=/checked\s*(?:[^=]|=\s*.checked.)/i,at=/^$|\/(?:java|ecma)script/i,ut=/^true\/(.*)/,lt=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,ct={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};ct.optgroup=ct.option,ct.tbody=ct.tfoot=ct.colgroup=ct.caption=ct.thead,ct.th=ct.td,x.fn.extend({text:function(e){return x.access(this,function(e){return e===undefined?x.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=pt(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=pt(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=e?x.filter(e,this):this,i=0;for(;null!=(n=r[i]);i++)t||1!==n.nodeType||x.cleanData(mt(n)),n.parentNode&&(t&&x.contains(n.ownerDocument,n)&&dt(mt(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++)1===e.nodeType&&(x.cleanData(mt(e,!1)),e.textContent="");return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return x.clone(this,e,t)})},html:function(e){return x.access(this,function(e){var t=this[0]||{},n=0,r=this.length;if(e===undefined&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!it.test(e)&&!ct[(nt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(tt,"<$1></$2>");try{for(;r>n;n++)t=this[n]||{},1===t.nodeType&&(x.cleanData(mt(t,!1)),t.innerHTML=e);t=0}catch(i){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=x.map(this,function(e){return[e.nextSibling,e.parentNode]}),t=0;return this.domManip(arguments,function(n){var r=e[t++],i=e[t++];i&&(r&&r.parentNode!==i&&(r=this.nextSibling),x(this).remove(),i.insertBefore(n,r))},!0),t?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t,n){e=f.apply([],e);var r,i,o,s,a,u,l=0,c=this.length,p=this,h=c-1,d=e[0],g=x.isFunction(d);if(g||!(1>=c||"string"!=typeof d||x.support.checkClone)&&st.test(d))return this.each(function(r){var i=p.eq(r);g&&(e[0]=d.call(this,r,i.html())),i.domManip(e,t,n)});if(c&&(r=x.buildFragment(e,this[0].ownerDocument,!1,!n&&this),i=r.firstChild,1===r.childNodes.length&&(r=i),i)){for(o=x.map(mt(r,"script"),ft),s=o.length;c>l;l++)a=r,l!==h&&(a=x.clone(a,!0,!0),s&&x.merge(o,mt(a,"script"))),t.call(this[l],a,l);if(s)for(u=o[o.length-1].ownerDocument,x.map(o,ht),l=0;s>l;l++)a=o[l],at.test(a.type||"")&&!q.access(a,"globalEval")&&x.contains(u,a)&&(a.src?x._evalUrl(a.src):x.globalEval(a.textContent.replace(lt,"")))}return this}}),x.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){x.fn[e]=function(e){var n,r=[],i=x(e),o=i.length-1,s=0;for(;o>=s;s++)n=s===o?this:this.clone(!0),x(i[s])[t](n),h.apply(r,n.get());return this.pushStack(r)}}),x.extend({clone:function(e,t,n){var r,i,o,s,a=e.cloneNode(!0),u=x.contains(e.ownerDocument,e);if(!(x.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||x.isXMLDoc(e)))for(s=mt(a),o=mt(e),r=0,i=o.length;i>r;r++)yt(o[r],s[r]);if(t)if(n)for(o=o||mt(e),s=s||mt(a),r=0,i=o.length;i>r;r++)gt(o[r],s[r]);else gt(e,a);return s=mt(a,"script"),s.length>0&&dt(s,!u&&mt(e,"script")),a},buildFragment:function(e,t,n,r){var i,o,s,a,u,l,c=0,p=e.length,f=t.createDocumentFragment(),h=[];for(;p>c;c++)if(i=e[c],i||0===i)if("object"===x.type(i))x.merge(h,i.nodeType?[i]:i);else if(rt.test(i)){o=o||f.appendChild(t.createElement("div")),s=(nt.exec(i)||["",""])[1].toLowerCase(),a=ct[s]||ct._default,o.innerHTML=a[1]+i.replace(tt,"<$1></$2>")+a[2],l=a[0];while(l--)o=o.lastChild;x.merge(h,o.childNodes),o=f.firstChild,o.textContent=""}else h.push(t.createTextNode(i));f.textContent="",c=0;while(i=h[c++])if((!r||-1===x.inArray(i,r))&&(u=x.contains(i.ownerDocument,i),o=mt(f.appendChild(i),"script"),u&&dt(o),n)){l=0;while(i=o[l++])at.test(i.type||"")&&n.push(i)}return f},cleanData:function(e){var t,n,r,i,o,s,a=x.event.special,u=0;for(;(n=e[u])!==undefined;u++){if(F.accepts(n)&&(o=n[q.expando],o&&(t=q.cache[o]))){if(r=Object.keys(t.events||{}),r.length)for(s=0;(i=r[s])!==undefined;s++)a[i]?x.event.remove(n,i):x.removeEvent(n,i,t.handle);q.cache[o]&&delete q.cache[o]}delete L.cache[n[L.expando]]}},_evalUrl:function(e){return x.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})}});function pt(e,t){return x.nodeName(e,"table")&&x.nodeName(1===t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function ft(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function ht(e){var t=ut.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function dt(e,t){var n=e.length,r=0;for(;n>r;r++)q.set(e[r],"globalEval",!t||q.get(t[r],"globalEval"))}function gt(e,t){var n,r,i,o,s,a,u,l;if(1===t.nodeType){if(q.hasData(e)&&(o=q.access(e),s=q.set(t,o),l=o.events)){delete s.handle,s.events={};for(i in l)for(n=0,r=l[i].length;r>n;n++)x.event.add(t,i,l[i][n])}L.hasData(e)&&(a=L.access(e),u=x.extend({},a),L.set(t,u))}}function mt(e,t){var n=e.getElementsByTagName?e.getElementsByTagName(t||"*"):e.querySelectorAll?e.querySelectorAll(t||"*"):[];return t===undefined||t&&x.nodeName(e,t)?x.merge([e],n):n}function yt(e,t){var n=t.nodeName.toLowerCase();"input"===n&&ot.test(e.type)?t.checked=e.checked:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}x.fn.extend({wrapAll:function(e){var t;return x.isFunction(e)?this.each(function(t){x(this).wrapAll(e.call(this,t))}):(this[0]&&(t=x(e,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstElementChild)e=e.firstElementChild;return e}).append(this)),this)},wrapInner:function(e){return x.isFunction(e)?this.each(function(t){x(this).wrapInner(e.call(this,t))}):this.each(function(){var t=x(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=x.isFunction(e);return this.each(function(n){x(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){x.nodeName(this,"body")||x(this).replaceWith(this.childNodes)}).end()}});var vt,xt,bt=/^(none|table(?!-c[ea]).+)/,wt=/^margin/,Tt=RegExp("^("+b+")(.*)$","i"),Ct=RegExp("^("+b+")(?!px)[a-z%]+$","i"),kt=RegExp("^([+-])=("+b+")","i"),Nt={BODY:"block"},Et={position:"absolute",visibility:"hidden",display:"block"},St={letterSpacing:0,fontWeight:400},jt=["Top","Right","Bottom","Left"],Dt=["Webkit","O","Moz","ms"];function At(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=Dt.length;while(i--)if(t=Dt[i]+n,t in e)return t;return r}function Lt(e,t){return e=t||e,"none"===x.css(e,"display")||!x.contains(e.ownerDocument,e)}function qt(t){return e.getComputedStyle(t,null)}function Ht(e,t){var n,r,i,o=[],s=0,a=e.length;for(;a>s;s++)r=e[s],r.style&&(o[s]=q.get(r,"olddisplay"),n=r.style.display,t?(o[s]||"none"!==n||(r.style.display=""),""===r.style.display&&Lt(r)&&(o[s]=q.access(r,"olddisplay",Rt(r.nodeName)))):o[s]||(i=Lt(r),(n&&"none"!==n||!i)&&q.set(r,"olddisplay",i?n:x.css(r,"display"))));for(s=0;a>s;s++)r=e[s],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[s]||"":"none"));return e}x.fn.extend({css:function(e,t){return x.access(this,function(e,t,n){var r,i,o={},s=0;if(x.isArray(t)){for(r=qt(e),i=t.length;i>s;s++)o[t[s]]=x.css(e,t[s],!1,r);return o}return n!==undefined?x.style(e,t,n):x.css(e,t)},e,t,arguments.length>1)},show:function(){return Ht(this,!0)},hide:function(){return Ht(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){Lt(this)?x(this).show():x(this).hide()})}}),x.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=vt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,s,a=x.camelCase(t),u=e.style;return t=x.cssProps[a]||(x.cssProps[a]=At(u,a)),s=x.cssHooks[t]||x.cssHooks[a],n===undefined?s&&"get"in s&&(i=s.get(e,!1,r))!==undefined?i:u[t]:(o=typeof n,"string"===o&&(i=kt.exec(n))&&(n=(i[1]+1)*i[2]+parseFloat(x.css(e,t)),o="number"),null==n||"number"===o&&isNaN(n)||("number"!==o||x.cssNumber[a]||(n+="px"),x.support.clearCloneStyle||""!==n||0!==t.indexOf("background")||(u[t]="inherit"),s&&"set"in s&&(n=s.set(e,n,r))===undefined||(u[t]=n)),undefined)}},css:function(e,t,n,r){var i,o,s,a=x.camelCase(t);return t=x.cssProps[a]||(x.cssProps[a]=At(e.style,a)),s=x.cssHooks[t]||x.cssHooks[a],s&&"get"in s&&(i=s.get(e,!0,n)),i===undefined&&(i=vt(e,t,r)),"normal"===i&&t in St&&(i=St[t]),""===n||n?(o=parseFloat(i),n===!0||x.isNumeric(o)?o||0:i):i}}),vt=function(e,t,n){var r,i,o,s=n||qt(e),a=s?s.getPropertyValue(t)||s[t]:undefined,u=e.style;return s&&(""!==a||x.contains(e.ownerDocument,e)||(a=x.style(e,t)),Ct.test(a)&&wt.test(t)&&(r=u.width,i=u.minWidth,o=u.maxWidth,u.minWidth=u.maxWidth=u.width=a,a=s.width,u.width=r,u.minWidth=i,u.maxWidth=o)),a};function Ot(e,t,n){var r=Tt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function Ft(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,s=0;for(;4>o;o+=2)"margin"===n&&(s+=x.css(e,n+jt[o],!0,i)),r?("content"===n&&(s-=x.css(e,"padding"+jt[o],!0,i)),"margin"!==n&&(s-=x.css(e,"border"+jt[o]+"Width",!0,i))):(s+=x.css(e,"padding"+jt[o],!0,i),"padding"!==n&&(s+=x.css(e,"border"+jt[o]+"Width",!0,i)));return s}function Pt(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=qt(e),s=x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=vt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Ct.test(i))return i;r=s&&(x.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+Ft(e,t,n||(s?"border":"content"),r,o)+"px"}function Rt(e){var t=o,n=Nt[e];return n||(n=Mt(e,t),"none"!==n&&n||(xt=(xt||x("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(xt[0].contentWindow||xt[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=Mt(e,t),xt.detach()),Nt[e]=n),n}function Mt(e,t){var n=x(t.createElement(e)).appendTo(t.body),r=x.css(n[0],"display");return n.remove(),r}x.each(["height","width"],function(e,t){x.cssHooks[t]={get:function(e,n,r){return n?0===e.offsetWidth&&bt.test(x.css(e,"display"))?x.swap(e,Et,function(){return Pt(e,t,r)}):Pt(e,t,r):undefined},set:function(e,n,r){var i=r&&qt(e);return Ot(e,n,r?Ft(e,t,r,x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,i),i):0)}}}),x(function(){x.support.reliableMarginRight||(x.cssHooks.marginRight={get:function(e,t){return t?x.swap(e,{display:"inline-block"},vt,[e,"marginRight"]):undefined}}),!x.support.pixelPosition&&x.fn.position&&x.each(["top","left"],function(e,t){x.cssHooks[t]={get:function(e,n){return n?(n=vt(e,t),Ct.test(n)?x(e).position()[t]+"px":n):undefined}}})}),x.expr&&x.expr.filters&&(x.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight},x.expr.filters.visible=function(e){return!x.expr.filters.hidden(e)}),x.each({margin:"",padding:"",border:"Width"},function(e,t){x.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+jt[r]+t]=o[r]||o[r-2]||o[0];return i}},wt.test(e)||(x.cssHooks[e+t].set=Ot)});var Wt=/%20/g,$t=/\[\]$/,Bt=/\r?\n/g,It=/^(?:submit|button|image|reset|file)$/i,zt=/^(?:input|select|textarea|keygen)/i;x.fn.extend({serialize:function(){return x.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=x.prop(this,"elements");return e?x.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!x(this).is(":disabled")&&zt.test(this.nodeName)&&!It.test(e)&&(this.checked||!ot.test(e))}).map(function(e,t){var n=x(this).val();return null==n?null:x.isArray(n)?x.map(n,function(e){return{name:t.name,value:e.replace(Bt,"\r\n")}}):{name:t.name,value:n.replace(Bt,"\r\n")}}).get()}}),x.param=function(e,t){var n,r=[],i=function(e,t){t=x.isFunction(t)?t():null==t?"":t,r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(t===undefined&&(t=x.ajaxSettings&&x.ajaxSettings.traditional),x.isArray(e)||e.jquery&&!x.isPlainObject(e))x.each(e,function(){i(this.name,this.value)});else for(n in e)_t(n,e[n],t,i);return r.join("&").replace(Wt,"+")};function _t(e,t,n,r){var i;if(x.isArray(t))x.each(t,function(t,i){n||$t.test(e)?r(e,i):_t(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==x.type(t))r(e,t);else for(i in t)_t(e+"["+i+"]",t[i],n,r)}x.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){x.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),x.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}});var Xt,Ut,Yt=x.now(),Vt=/\?/,Gt=/#.*$/,Jt=/([?&])_=[^&]*/,Qt=/^(.*?):[ \t]*([^\r\n]*)$/gm,Kt=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Zt=/^(?:GET|HEAD)$/,en=/^\/\//,tn=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,nn=x.fn.load,rn={},on={},sn="*/".concat("*");try{Ut=i.href}catch(an){Ut=o.createElement("a"),Ut.href="",Ut=Ut.href}Xt=tn.exec(Ut.toLowerCase())||[];function un(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(w)||[];if(x.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function ln(e,t,n,r){var i={},o=e===on;function s(a){var u;return i[a]=!0,x.each(e[a]||[],function(e,a){var l=a(t,n,r);return"string"!=typeof l||o||i[l]?o?!(u=l):undefined:(t.dataTypes.unshift(l),s(l),!1)}),u}return s(t.dataTypes[0])||!i["*"]&&s("*")}function cn(e,t){var n,r,i=x.ajaxSettings.flatOptions||{};for(n in t)t[n]!==undefined&&((i[n]?e:r||(r={}))[n]=t[n]);return r&&x.extend(!0,e,r),e}x.fn.load=function(e,t,n){if("string"!=typeof e&&nn)return nn.apply(this,arguments);var r,i,o,s=this,a=e.indexOf(" ");return a>=0&&(r=e.slice(a),e=e.slice(0,a)),x.isFunction(t)?(n=t,t=undefined):t&&"object"==typeof t&&(i="POST"),s.length>0&&x.ajax({url:e,type:i,dataType:"html",data:t}).done(function(e){o=arguments,s.html(r?x("<div>").append(x.parseHTML(e)).find(r):e)}).complete(n&&function(e,t){s.each(n,o||[e.responseText,t,e])}),this},x.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){x.fn[t]=function(e){return this.on(t,e)}}),x.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Ut,type:"GET",isLocal:Kt.test(Xt[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":sn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":x.parseJSON,"text xml":x.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?cn(cn(e,x.ajaxSettings),t):cn(x.ajaxSettings,e)},ajaxPrefilter:un(rn),ajaxTransport:un(on),ajax:function(e,t){"object"==typeof e&&(t=e,e=undefined),t=t||{};var n,r,i,o,s,a,u,l,c=x.ajaxSetup({},t),p=c.context||c,f=c.context&&(p.nodeType||p.jquery)?x(p):x.event,h=x.Deferred(),d=x.Callbacks("once memory"),g=c.statusCode||{},m={},y={},v=0,b="canceled",T={readyState:0,getResponseHeader:function(e){var t;if(2===v){if(!o){o={};while(t=Qt.exec(i))o[t[1].toLowerCase()]=t[2]}t=o[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===v?i:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return v||(e=y[n]=y[n]||e,m[e]=t),this},overrideMimeType:function(e){return v||(c.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>v)for(t in e)g[t]=[g[t],e[t]];else T.always(e[T.status]);return this},abort:function(e){var t=e||b;return n&&n.abort(t),k(0,t),this}};if(h.promise(T).complete=d.add,T.success=T.done,T.error=T.fail,c.url=((e||c.url||Ut)+"").replace(Gt,"").replace(en,Xt[1]+"//"),c.type=t.method||t.type||c.method||c.type,c.dataTypes=x.trim(c.dataType||"*").toLowerCase().match(w)||[""],null==c.crossDomain&&(a=tn.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===Xt[1]&&a[2]===Xt[2]&&(a[3]||("http:"===a[1]?"80":"443"))===(Xt[3]||("http:"===Xt[1]?"80":"443")))),c.data&&c.processData&&"string"!=typeof c.data&&(c.data=x.param(c.data,c.traditional)),ln(rn,c,t,T),2===v)return T;u=c.global,u&&0===x.active++&&x.event.trigger("ajaxStart"),c.type=c.type.toUpperCase(),c.hasContent=!Zt.test(c.type),r=c.url,c.hasContent||(c.data&&(r=c.url+=(Vt.test(r)?"&":"?")+c.data,delete c.data),c.cache===!1&&(c.url=Jt.test(r)?r.replace(Jt,"$1_="+Yt++):r+(Vt.test(r)?"&":"?")+"_="+Yt++)),c.ifModified&&(x.lastModified[r]&&T.setRequestHeader("If-Modified-Since",x.lastModified[r]),x.etag[r]&&T.setRequestHeader("If-None-Match",x.etag[r])),(c.data&&c.hasContent&&c.contentType!==!1||t.contentType)&&T.setRequestHeader("Content-Type",c.contentType),T.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+("*"!==c.dataTypes[0]?", "+sn+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)T.setRequestHeader(l,c.headers[l]);if(c.beforeSend&&(c.beforeSend.call(p,T,c)===!1||2===v))return T.abort();b="abort";for(l in{success:1,error:1,complete:1})T[l](c[l]);if(n=ln(on,c,t,T)){T.readyState=1,u&&f.trigger("ajaxSend",[T,c]),c.async&&c.timeout>0&&(s=setTimeout(function(){T.abort("timeout")},c.timeout));try{v=1,n.send(m,k)}catch(C){if(!(2>v))throw C;k(-1,C)}}else k(-1,"No Transport");function k(e,t,o,a){var l,m,y,b,w,C=t;2!==v&&(v=2,s&&clearTimeout(s),n=undefined,i=a||"",T.readyState=e>0?4:0,l=e>=200&&300>e||304===e,o&&(b=pn(c,T,o)),b=fn(c,b,T,l),l?(c.ifModified&&(w=T.getResponseHeader("Last-Modified"),w&&(x.lastModified[r]=w),w=T.getResponseHeader("etag"),w&&(x.etag[r]=w)),204===e||"HEAD"===c.type?C="nocontent":304===e?C="notmodified":(C=b.state,m=b.data,y=b.error,l=!y)):(y=C,(e||!C)&&(C="error",0>e&&(e=0))),T.status=e,T.statusText=(t||C)+"",l?h.resolveWith(p,[m,C,T]):h.rejectWith(p,[T,C,y]),T.statusCode(g),g=undefined,u&&f.trigger(l?"ajaxSuccess":"ajaxError",[T,c,l?m:y]),d.fireWith(p,[T,C]),u&&(f.trigger("ajaxComplete",[T,c]),--x.active||x.event.trigger("ajaxStop")))}return T},getJSON:function(e,t,n){return x.get(e,t,n,"json")},getScript:function(e,t){return x.get(e,undefined,t,"script")}}),x.each(["get","post"],function(e,t){x[t]=function(e,n,r,i){return x.isFunction(n)&&(i=i||r,r=n,n=undefined),x.ajax({url:e,type:t,dataType:i,data:n,success:r})}});function pn(e,t,n){var r,i,o,s,a=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),r===undefined&&(r=e.mimeType||t.getResponseHeader("Content-Type"));if(r)for(i in a)if(a[i]&&a[i].test(r)){u.unshift(i);break}if(u[0]in n)o=u[0];else{for(i in n){if(!u[0]||e.converters[i+" "+u[0]]){o=i;break}s||(s=i)}o=o||s}return o?(o!==u[0]&&u.unshift(o),n[o]):undefined}function fn(e,t,n,r){var i,o,s,a,u,l={},c=e.dataTypes.slice();if(c[1])for(s in e.converters)l[s.toLowerCase()]=e.converters[s];o=c.shift();while(o)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!u&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u=o,o=c.shift())if("*"===o)o=u;else if("*"!==u&&u!==o){if(s=l[u+" "+o]||l["* "+o],!s)for(i in l)if(a=i.split(" "),a[1]===o&&(s=l[u+" "+a[0]]||l["* "+a[0]])){s===!0?s=l[i]:l[i]!==!0&&(o=a[0],c.unshift(a[1]));break}if(s!==!0)if(s&&e["throws"])t=s(t);else try{t=s(t)}catch(p){return{state:"parsererror",error:s?p:"No conversion from "+u+" to "+o}}}return{state:"success",data:t}}x.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return x.globalEval(e),e}}}),x.ajaxPrefilter("script",function(e){e.cache===undefined&&(e.cache=!1),e.crossDomain&&(e.type="GET")}),x.ajaxTransport("script",function(e){if(e.crossDomain){var t,n;return{send:function(r,i){t=x("<script>").prop({async:!0,charset:e.scriptCharset,src:e.url}).on("load error",n=function(e){t.remove(),n=null,e&&i("error"===e.type?404:200,e.type)}),o.head.appendChild(t[0])},abort:function(){n&&n()}}}});var hn=[],dn=/(=)\?(?=&|$)|\?\?/;x.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=hn.pop()||x.expando+"_"+Yt++;return this[e]=!0,e}}),x.ajaxPrefilter("json jsonp",function(t,n,r){var i,o,s,a=t.jsonp!==!1&&(dn.test(t.url)?"url":"string"==typeof t.data&&!(t.contentType||"").indexOf("application/x-www-form-urlencoded")&&dn.test(t.data)&&"data");return a||"jsonp"===t.dataTypes[0]?(i=t.jsonpCallback=x.isFunction(t.jsonpCallback)?t.jsonpCallback():t.jsonpCallback,a?t[a]=t[a].replace(dn,"$1"+i):t.jsonp!==!1&&(t.url+=(Vt.test(t.url)?"&":"?")+t.jsonp+"="+i),t.converters["script json"]=function(){return s||x.error(i+" was not called"),s[0]},t.dataTypes[0]="json",o=e[i],e[i]=function(){s=arguments},r.always(function(){e[i]=o,t[i]&&(t.jsonpCallback=n.jsonpCallback,hn.push(i)),s&&x.isFunction(o)&&o(s[0]),s=o=undefined}),"script"):undefined}),x.ajaxSettings.xhr=function(){try{return new XMLHttpRequest}catch(e){}};var gn=x.ajaxSettings.xhr(),mn={0:200,1223:204},yn=0,vn={};e.ActiveXObject&&x(e).on("unload",function(){for(var e in vn)vn[e]();vn=undefined}),x.support.cors=!!gn&&"withCredentials"in gn,x.support.ajax=gn=!!gn,x.ajaxTransport(function(e){var t;return x.support.cors||gn&&!e.crossDomain?{send:function(n,r){var i,o,s=e.xhr();if(s.open(e.type,e.url,e.async,e.username,e.password),e.xhrFields)for(i in e.xhrFields)s[i]=e.xhrFields[i];e.mimeType&&s.overrideMimeType&&s.overrideMimeType(e.mimeType),e.crossDomain||n["X-Requested-With"]||(n["X-Requested-With"]="XMLHttpRequest");for(i in n)s.setRequestHeader(i,n[i]);t=function(e){return function(){t&&(delete vn[o],t=s.onload=s.onerror=null,"abort"===e?s.abort():"error"===e?r(s.status||404,s.statusText):r(mn[s.status]||s.status,s.statusText,"string"==typeof s.responseText?{text:s.responseText}:undefined,s.getAllResponseHeaders()))}},s.onload=t(),s.onerror=t("error"),t=vn[o=yn++]=t("abort"),s.send(e.hasContent&&e.data||null)},abort:function(){t&&t()}}:undefined});var xn,bn,wn=/^(?:toggle|show|hide)$/,Tn=RegExp("^(?:([+-])=|)("+b+")([a-z%]*)$","i"),Cn=/queueHooks$/,kn=[An],Nn={"*":[function(e,t){var n=this.createTween(e,t),r=n.cur(),i=Tn.exec(t),o=i&&i[3]||(x.cssNumber[e]?"":"px"),s=(x.cssNumber[e]||"px"!==o&&+r)&&Tn.exec(x.css(n.elem,e)),a=1,u=20;if(s&&s[3]!==o){o=o||s[3],i=i||[],s=+r||1;do a=a||".5",s/=a,x.style(n.elem,e,s+o);while(a!==(a=n.cur()/r)&&1!==a&&--u)}return i&&(s=n.start=+s||+r||0,n.unit=o,n.end=i[1]?s+(i[1]+1)*i[2]:+i[2]),n}]};function En(){return setTimeout(function(){xn=undefined}),xn=x.now()}function Sn(e,t,n){var r,i=(Nn[t]||[]).concat(Nn["*"]),o=0,s=i.length;for(;s>o;o++)if(r=i[o].call(n,t,e))return r}function jn(e,t,n){var r,i,o=0,s=kn.length,a=x.Deferred().always(function(){delete u.elem}),u=function(){if(i)return!1;var t=xn||En(),n=Math.max(0,l.startTime+l.duration-t),r=n/l.duration||0,o=1-r,s=0,u=l.tweens.length;for(;u>s;s++)l.tweens[s].run(o);return a.notifyWith(e,[l,o,n]),1>o&&u?n:(a.resolveWith(e,[l]),!1)},l=a.promise({elem:e,props:x.extend({},t),opts:x.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:xn||En(),duration:n.duration,tweens:[],createTween:function(t,n){var r=x.Tween(e,l.opts,t,n,l.opts.specialEasing[t]||l.opts.easing);return l.tweens.push(r),r},stop:function(t){var n=0,r=t?l.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)l.tweens[n].run(1);return t?a.resolveWith(e,[l,t]):a.rejectWith(e,[l,t]),this}}),c=l.props;for(Dn(c,l.opts.specialEasing);s>o;o++)if(r=kn[o].call(l,e,c,l.opts))return r;return x.map(c,Sn,l),x.isFunction(l.opts.start)&&l.opts.start.call(e,l),x.fx.timer(x.extend(u,{elem:e,anim:l,queue:l.opts.queue})),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always)}function Dn(e,t){var n,r,i,o,s;for(n in e)if(r=x.camelCase(n),i=t[r],o=e[n],x.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),s=x.cssHooks[r],s&&"expand"in s){o=s.expand(o),delete e[r];for(n in o)n in e||(e[n]=o[n],t[n]=i)}else t[r]=i}x.Animation=x.extend(jn,{tweener:function(e,t){x.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Nn[n]=Nn[n]||[],Nn[n].unshift(t)},prefilter:function(e,t){t?kn.unshift(e):kn.push(e)}});function An(e,t,n){var r,i,o,s,a,u,l=this,c={},p=e.style,f=e.nodeType&&Lt(e),h=q.get(e,"fxshow");n.queue||(a=x._queueHooks(e,"fx"),null==a.unqueued&&(a.unqueued=0,u=a.empty.fire,a.empty.fire=function(){a.unqueued||u()}),a.unqueued++,l.always(function(){l.always(function(){a.unqueued--,x.queue(e,"fx").length||a.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],"inline"===x.css(e,"display")&&"none"===x.css(e,"float")&&(p.display="inline-block")),n.overflow&&(p.overflow="hidden",l.always(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t)if(i=t[r],wn.exec(i)){if(delete t[r],o=o||"toggle"===i,i===(f?"hide":"show")){if("show"!==i||!h||h[r]===undefined)continue;f=!0}c[r]=h&&h[r]||x.style(e,r)}if(!x.isEmptyObject(c)){h?"hidden"in h&&(f=h.hidden):h=q.access(e,"fxshow",{}),o&&(h.hidden=!f),f?x(e).show():l.done(function(){x(e).hide()}),l.done(function(){var t;q.remove(e,"fxshow");for(t in c)x.style(e,t,c[t])});for(r in c)s=Sn(f?h[r]:0,r,l),r in h||(h[r]=s.start,f&&(s.end=s.start,s.start="width"===r||"height"===r?1:0))}}function Ln(e,t,n,r,i){return new Ln.prototype.init(e,t,n,r,i)}x.Tween=Ln,Ln.prototype={constructor:Ln,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(x.cssNumber[n]?"":"px")},cur:function(){var e=Ln.propHooks[this.prop];return e&&e.get?e.get(this):Ln.propHooks._default.get(this)},run:function(e){var t,n=Ln.propHooks[this.prop];return this.pos=t=this.options.duration?x.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):Ln.propHooks._default.set(this),this}},Ln.prototype.init.prototype=Ln.prototype,Ln.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=x.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){x.fx.step[e.prop]?x.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[x.cssProps[e.prop]]||x.cssHooks[e.prop])?x.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},Ln.propHooks.scrollTop=Ln.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},x.each(["toggle","show","hide"],function(e,t){var n=x.fn[t];x.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(qn(t,!0),e,r,i)}}),x.fn.extend({fadeTo:function(e,t,n,r){return this.filter(Lt).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=x.isEmptyObject(e),o=x.speed(t,n,r),s=function(){var t=jn(this,x.extend({},e),o);(i||q.get(this,"finish"))&&t.stop(!0)};return s.finish=s,i||o.queue===!1?this.each(s):this.queue(o.queue,s)},stop:function(e,t,n){var r=function(e){var t=e.stop;delete e.stop,t(n)};return"string"!=typeof e&&(n=t,t=e,e=undefined),t&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,i=null!=e&&e+"queueHooks",o=x.timers,s=q.get(this);if(i)s[i]&&s[i].stop&&r(s[i]);else for(i in s)s[i]&&s[i].stop&&Cn.test(i)&&r(s[i]);for(i=o.length;i--;)o[i].elem!==this||null!=e&&o[i].queue!==e||(o[i].anim.stop(n),t=!1,o.splice(i,1));(t||!n)&&x.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=q.get(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=x.timers,s=r?r.length:0;for(n.finish=!0,x.queue(this,e,[]),i&&i.stop&&i.stop.call(this,!0),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;s>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function qn(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=jt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}x.each({slideDown:qn("show"),slideUp:qn("hide"),slideToggle:qn("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){x.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),x.speed=function(e,t,n){var r=e&&"object"==typeof e?x.extend({},e):{complete:n||!n&&t||x.isFunction(e)&&e,duration:e,easing:n&&t||t&&!x.isFunction(t)&&t};return r.duration=x.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in x.fx.speeds?x.fx.speeds[r.duration]:x.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){x.isFunction(r.old)&&r.old.call(this),r.queue&&x.dequeue(this,r.queue)},r},x.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},x.timers=[],x.fx=Ln.prototype.init,x.fx.tick=function(){var e,t=x.timers,n=0;for(xn=x.now();t.length>n;n++)e=t[n],e()||t[n]!==e||t.splice(n--,1);t.length||x.fx.stop(),xn=undefined},x.fx.timer=function(e){e()&&x.timers.push(e)&&x.fx.start()},x.fx.interval=13,x.fx.start=function(){bn||(bn=setInterval(x.fx.tick,x.fx.interval))},x.fx.stop=function(){clearInterval(bn),bn=null},x.fx.speeds={slow:600,fast:200,_default:400},x.fx.step={},x.expr&&x.expr.filters&&(x.expr.filters.animated=function(e){return x.grep(x.timers,function(t){return e===t.elem}).length}),x.fn.offset=function(e){if(arguments.length)return e===undefined?this:this.each(function(t){x.offset.setOffset(this,e,t)});var t,n,i=this[0],o={top:0,left:0},s=i&&i.ownerDocument;if(s)return t=s.documentElement,x.contains(t,i)?(typeof i.getBoundingClientRect!==r&&(o=i.getBoundingClientRect()),n=Hn(s),{top:o.top+n.pageYOffset-t.clientTop,left:o.left+n.pageXOffset-t.clientLeft}):o},x.offset={setOffset:function(e,t,n){var r,i,o,s,a,u,l,c=x.css(e,"position"),p=x(e),f={};"static"===c&&(e.style.position="relative"),a=p.offset(),o=x.css(e,"top"),u=x.css(e,"left"),l=("absolute"===c||"fixed"===c)&&(o+u).indexOf("auto")>-1,l?(r=p.position(),s=r.top,i=r.left):(s=parseFloat(o)||0,i=parseFloat(u)||0),x.isFunction(t)&&(t=t.call(e,n,a)),null!=t.top&&(f.top=t.top-a.top+s),null!=t.left&&(f.left=t.left-a.left+i),"using"in t?t.using.call(e,f):p.css(f)}},x.fn.extend({position:function(){if(this[0]){var e,t,n=this[0],r={top:0,left:0};return"fixed"===x.css(n,"position")?t=n.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),x.nodeName(e[0],"html")||(r=e.offset()),r.top+=x.css(e[0],"borderTopWidth",!0),r.left+=x.css(e[0],"borderLeftWidth",!0)),{top:t.top-r.top-x.css(n,"marginTop",!0),left:t.left-r.left-x.css(n,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||s;while(e&&!x.nodeName(e,"html")&&"static"===x.css(e,"position"))e=e.offsetParent;return e||s})}}),x.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,n){var r="pageYOffset"===n;x.fn[t]=function(i){return x.access(this,function(t,i,o){var s=Hn(t);return o===undefined?s?s[n]:t[i]:(s?s.scrollTo(r?e.pageXOffset:o,r?o:e.pageYOffset):t[i]=o,undefined)},t,i,arguments.length,null)}});function Hn(e){return x.isWindow(e)?e:9===e.nodeType&&e.defaultView}x.each({Height:"height",Width:"width"},function(e,t){x.each({padding:"inner"+e,content:t,"":"outer"+e},function(n,r){x.fn[r]=function(r,i){var o=arguments.length&&(n||"boolean"!=typeof r),s=n||(r===!0||i===!0?"margin":"border");return x.access(this,function(t,n,r){var i;return x.isWindow(t)?t.document.documentElement["client"+e]:9===t.nodeType?(i=t.documentElement,Math.max(t.body["scroll"+e],i["scroll"+e],t.body["offset"+e],i["offset"+e],i["client"+e])):r===undefined?x.css(t,n,s):x.style(t,n,r,s)},t,o?r:undefined,o,null)}})}),x.fn.size=function(){return this.length},x.fn.andSelf=x.fn.addBack,"object"==typeof module&&module&&"object"==typeof module.exports?module.exports=x:"function"==typeof define&&define.amd&&define("jquery",[],function(){return x}),"object"==typeof e&&"object"==typeof e.document&&(e.jQuery=e.$=x)})(window);
\ No newline at end of file
diff --git a/themes/baggy/js/jquery.cookie.js b/themes/baggy/js/jquery.cookie.js
new file mode 100755 (executable)
index 0000000..9271900
--- /dev/null
@@ -0,0 +1,117 @@
+/*!
+ * jQuery Cookie Plugin v1.4.0
+ * https://github.com/carhartl/jquery-cookie
+ *
+ * Copyright 2013 Klaus Hartl
+ * Released under the MIT license
+ */
+(function (factory) {
+       if (typeof define === 'function' && define.amd) {
+               // AMD. Register as anonymous module.
+               define(['jquery'], factory);
+       } else {
+               // Browser globals.
+               factory(jQuery);
+       }
+}(function ($) {
+
+       var pluses = /\+/g;
+
+       function encode(s) {
+               return config.raw ? s : encodeURIComponent(s);
+       }
+
+       function decode(s) {
+               return config.raw ? s : decodeURIComponent(s);
+       }
+
+       function stringifyCookieValue(value) {
+               return encode(config.json ? JSON.stringify(value) : String(value));
+       }
+
+       function parseCookieValue(s) {
+               if (s.indexOf('"') === 0) {
+                       // This is a quoted cookie as according to RFC2068, unescape...
+                       s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
+               }
+
+               try {
+                       // Replace server-side written pluses with spaces.
+                       // If we can't decode the cookie, ignore it, it's unusable.
+                       s = decodeURIComponent(s.replace(pluses, ' '));
+               } catch(e) {
+                       return;
+               }
+
+               try {
+                       // If we can't parse the cookie, ignore it, it's unusable.
+                       return config.json ? JSON.parse(s) : s;
+               } catch(e) {}
+       }
+
+       function read(s, converter) {
+               var value = config.raw ? s : parseCookieValue(s);
+               return $.isFunction(converter) ? converter(value) : value;
+       }
+
+       var config = $.cookie = function (key, value, options) {
+
+               // Write
+               if (value !== undefined && !$.isFunction(value)) {
+                       options = $.extend({}, config.defaults, options);
+
+                       if (typeof options.expires === 'number') {
+                               var days = options.expires, t = options.expires = new Date();
+                               t.setDate(t.getDate() + days);
+                       }
+
+                       return (document.cookie = [
+                               encode(key), '=', stringifyCookieValue(value),
+                               options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
+                               options.path    ? '; path=' + options.path : '',
+                               options.domain  ? '; domain=' + options.domain : '',
+                               options.secure  ? '; secure' : ''
+                       ].join(''));
+               }
+
+               // Read
+
+               var result = key ? undefined : {};
+
+               // To prevent the for loop in the first place assign an empty array
+               // in case there are no cookies at all. Also prevents odd result when
+               // calling $.cookie().
+               var cookies = document.cookie ? document.cookie.split('; ') : [];
+
+               for (var i = 0, l = cookies.length; i < l; i++) {
+                       var parts = cookies[i].split('=');
+                       var name = decode(parts.shift());
+                       var cookie = parts.join('=');
+
+                       if (key && key === name) {
+                               // If second argument (value) is a function it's a converter...
+                               result = read(cookie, value);
+                               break;
+                       }
+
+                       // Prevent storing a cookie that we couldn't decode.
+                       if (!key && (cookie = read(cookie)) !== undefined) {
+                               result[name] = cookie;
+                       }
+               }
+
+               return result;
+       };
+
+       config.defaults = {};
+
+       $.removeCookie = function (key, options) {
+               if ($.cookie(key) !== undefined) {
+                       // Must not alter options, thus extending a fresh object...
+                       $.cookie(key, '', $.extend({}, options, { expires: -1 }));
+                       return true;
+               }
+               return false;
+       };
+
+}));
old mode 100644 (file)
new mode 100755 (executable)
index dfebc3e..8de1274
@@ -21,6 +21,9 @@
             {% block precontent %}{% endblock %}
             {% block messages %}
             {% include '_messages.twig' %}
+            {% if includeImport %}
+                                                               {% include '_import.twig' %}
+                                               {% endif %}
             {% endblock %}
             <div id="content" class="w600p center">
             {% block content %}{% endblock %}
old mode 100644 (file)
new mode 100755 (executable)
index 9df44bb..9bb93a4
@@ -6,7 +6,7 @@
 {% block content %}
 <h2>{% trans "Tags" %}</h2>
 <ul class="list-tags">
-{% for tag in tags %}<li>{% if token != '' %}<a class="icon icon-rss" href="?feed&amp;type=tag&amp;user_id={{ user_id }}&amp;tag_id={{ tag.id }}&amp;token={{ token }}" target="_blank"><span>rss</span></a>{% endif %} <a href="./?view=tag&amp;id={{ tag.id }}">{{ tag.value }}</a> 
+{% for tag in tags %}<li>{% if token != '' %}<a class="icon icon-rss" href="?feed&amp;type=tag&amp;user_id={{ user_id }}&amp;tag_id={{ tag.id }}&amp;token={{ token }}" target="_blank"><span>rss</span></a>{% endif %} <a href="./?view=tag&amp;id={{ tag.id }}">{{ tag.value }}</a> ({{ tag.entriescount }})
 </li>
 {% endfor %}
 </ul>
old mode 100644 (file)
new mode 100755 (executable)
index 4751c4c..af97407
@@ -8,13 +8,15 @@
             <ul class="links">
                 <li class="topPosF"><a href="#top" title="{% trans "Back to top" %}" class="tool top icon icon-arrow-up-thick"><span>{% trans "Back to top" %}</span></a></li>
                 <li><a href="{{ entry.url|e }}" target="_blank" title="{% trans "original" %} : {{ entry.title|e }}" class="tool link icon icon-link"><span>{{ entry.url | e | getDomain }}</span></a></li>
-                <li><a title="{% trans "Mark as read" %}" class="tool icon icon-check {% if entry.is_read == 0 %}archive-off{% else %}archive{% endif %}" href="./?action=toggle_archive&amp;id={{ entry.id|e }}"><span>{% trans "Toggle mark as read" %}</span></a></li>
-                <li><a title="{% trans "Favorite" %}" class="tool icon icon-star {% if entry.is_fav == 0 %}fav-off{% else %}fav{% endif %}" href="./?action=toggle_fav&amp;id={{ entry.id|e }}"><span>{% trans "Toggle favorite" %}</span></a></li>
+                <li><a title="{% trans "Mark as read" %}" class="tool icon icon-check {% if entry.is_read == 0 %}archive-off{% else %}archive{% endif %}" href="javascript: void(null);" id="markAsRead"><span>{% trans "Toggle mark as read" %}</span></a></li>
+                <li><a title="{% trans "Favorite" %}" class="tool icon icon-star {% if entry.is_fav == 0 %}fav-off{% else %}fav{% endif %}" href="javascript: void(null);" id="setFav"><span>{% trans "Toggle favorite" %}</span></a></li>
                 <li><a title="{% trans "Delete" %}" class="tool delete icon icon-trash" href="./?action=delete&amp;id={{ entry.id|e }}"><span>{% trans "Delete" %}</span></a></li>
                 {% if constant('SHARE_TWITTER') == 1 %}<li><a href="https://twitter.com/home?status={{entry.title|url_encode}}%20{{ entry.url|url_encode }}%20via%20@wallabagapp" target="_blank" class="tool twitter icon icon-twitter" title="{% trans "Tweet" %}"><span>{% trans "Tweet" %}</span></a></li>{% endif %}
                 {% if constant('SHARE_MAIL') == 1 %}<li><a href="mailto:?subject={{ entry.title|url_encode }}&amp;body={{ entry.url|url_encode }}%20via%20@wallabagapp" class="tool email icon icon-mail" title="{% trans "Email" %}"><span>{% trans "Email" %}</span></a></li>{% endif %}
                 {% if constant('SHARE_SHAARLI') == 1 %}<li><a href="{{ constant('SHAARLI_URL') }}/index.php?post={{ entry.url|url_encode }}&amp;title={{ entry.title|url_encode }}" target="_blank" class="tool shaarli" title="{% trans "shaarli" %}"><span>{% trans "shaarli" %}</span></a></li>{% endif %}
-                {% if constant('FLATTR') == 1 %}{% if flattr.status == constant('FLATTRABLE') %}<li><a href="http://flattr.com/submit/auto?url={{ entry.url }}" class="tool flattr icon icon-flattr" target="_blank" title="{% trans "flattr" %}"><span>{% trans "flattr" %}</span></a></li>{% elseif flattr.status == constant('FLATTRED') %}<li><a href="{{ flattr.flattrItemURL }}" class="tool flattr" target="_blank" title="{% trans "flattr" %}"><span>{% trans "flattr" %}</span> ({{ flattr.numflattrs }})</a></li>{% endif %}{% endif %}
+                {% if constant('FLATTR') == 1 %}{% if flattr.status == constant('FLATTRABLE') %}<li><a href="http://flattr.com/submit/auto?url={{ entry.url }}" class="tool flattr icon icon-flattr" target="_blank" title="{% trans "flattr" %}"><span>{% trans "flattr" %}</span></a></li>{% elseif flattr.status == constant('FLATTRED') %}<li><a href="{{ flattr.flattrItemURL }}" class="tool flattr icon icon-flattr" target="_blank" title="{% trans "flattr" %}"><span>{% trans "flattr" %}</span> ({{ flattr.numflattrs }})</a></li>{% endif %}{% endif %}
+                {% if constant('SHOW_PRINTLINK') == 1 %}<li><a title="{% trans "Print" %}" class="tool icon icon-print" href="javascript: window.print();"><span>{% trans "Print" %}</span></a></li>{% endif %}
+                <li><a href="./?epub&amp;method=id&amp;id={{ entry.id|e }}" title="Generate epub file">EPUB</a></li>
                 <li><a href="mailto:hello@wallabag.org?subject=Wrong%20display%20in%20wallabag&amp;body={{ entry.url|url_encode }}" title="{% trans "Does this article appear wrong?" %}" class="tool bad-display icon icon-delete"><span>{% trans "Does this article appear wrong?" %}</span></a></li>
             </ul>
         </div>
                 {{ content | raw }}
             </article>
         </div>
+        <script src="{{ poche_url }}themes/{{theme}}/js/restoreScroll.js"></script>
+        <script type="text/javascript">
+        $(document).ready(function() {
+        
+                       // toggle read property of current article
+                       $('#markAsRead').click(function(){
+                               $("body").css("cursor", "wait");
+                                           $.ajax( { url: './?action=toggle_archive&id={{ entry.id|e }}' }).done(
+                                           function( data ) {
+                                       if ( data == '1' ) {
+                                               if ( $('#markAsRead').hasClass("archive-off") ) {
+                                                       $('#markAsRead').removeClass("archive-off");    
+                                                       $('#markAsRead').addClass("archive");
+                                               }
+                                               else {
+                                                       $('#markAsRead').removeClass("archive");        
+                                                       $('#markAsRead').addClass("archive-off");
+                                               }
+                                       }
+                                       else {
+                                         alert('Error! Pls check if you are logged in.');
+                                       }
+                                     });
+                                           $("body").css("cursor", "auto");
+                                         });
+                                         
+                                         // toggle favorite property of current article
+                       $('#setFav').click(function(){
+                               $("body").css("cursor", "wait");
+                                           $.ajax( { url: './?action=toggle_fav&id={{ entry.id|e }}' }).done(
+                                           function( data ) {
+                                       if ( data == '1' ) {
+                                               if ( $('#setFav').hasClass("fav-off") ) {
+                                                       $('#setFav').removeClass("fav-off");    
+                                                       $('#setFav').addClass("fav");
+                                               }
+                                               else {
+                                                       $('#setFav').removeClass("fav");        
+                                                       $('#setFav').addClass("fav-off");
+                                               }
+                                       }
+                                       else {
+                                         alert('Error! Pls check if you are logged in.');
+                                       }
+                                     });
+                                           $("body").css("cursor", "auto");
+                                         });
+
+            $(window).scroll(function(e){
+                var scrollTop = $(window).scrollTop();
+                var docHeight = $(document).height();
+                var scrollPercent = (scrollTop) / (docHeight);
+                var scrollPercentRounded = Math.round(scrollPercent*100)/100;
+                savePercent({{ entry.id|e }}, scrollPercentRounded);
+            });
+
+            retrievePercent({{ entry.id|e }});
+
+            $(window).resize(function(){
+                retrievePercent({{ entry.id|e }});
+            });
+        });
+        </script>
 {% endblock %}
index 57b40f41cc230aa527fc8fd659be098e157a1a3c..059936d998b16a29a25d1a3323045a68856a6281 100755 (executable)
@@ -1,11 +1,11 @@
-        <link rel="shortcut icon" type="image/x-icon" href="{{ poche_url }}/themes/{{theme}}/img/favicon.ico" />
-        <link rel="apple-touch-icon-precomposed" sizes="144x144" href="{{ poche_url }}/themes/{{theme}}/img/apple-touch-icon-144x144-precomposed.png">
-        <link rel="apple-touch-icon-precomposed" sizes="72x72" href="{{ poche_url }}/themes/{{theme}}/img/apple-touch-icon-72x72-precomposed.png">
-        <link rel="apple-touch-icon-precomposed" href="{{ poche_url }}/themes/{{theme}}/img/apple-touch-icon-precomposed.png">
-        <link rel="stylesheet" href="{{ poche_url }}/themes/{{theme}}/css/font.css" media="all">
-        <link rel="stylesheet" href="{{ poche_url }}/themes/{{theme}}/css/style.css" media="all">
-        <link rel="stylesheet" href="{{ poche_url }}/themes/{{theme}}/css/messages.css" media="all">
-        <link rel="stylesheet" href="{{ poche_url }}/themes/{{theme}}/css/print.css" media="print">
+        <link rel="shortcut icon" type="image/x-icon" href="{{ poche_url }}themes/{{theme}}/img/favicon.ico" />
+        <link rel="apple-touch-icon-precomposed" sizes="144x144" href="{{ poche_url }}themes/{{theme}}/img/apple-touch-icon-144x144-precomposed.png">
+        <link rel="apple-touch-icon-precomposed" sizes="72x72" href="{{ poche_url }}themes/{{theme}}/img/apple-touch-icon-72x72-precomposed.png">
+        <link rel="apple-touch-icon-precomposed" href="{{ poche_url }}themes/{{theme}}/img/apple-touch-icon-precomposed.png">
+        <link rel="stylesheet" href="{{ poche_url }}themes/{{theme}}/css/font.css" media="all">
+        <link rel="stylesheet" href="{{ poche_url }}themes/{{theme}}/css/style.css" media="all">
+        <link rel="stylesheet" href="{{ poche_url }}themes/{{theme}}/css/messages.css" media="all">
+        <link rel="stylesheet" href="{{ poche_url }}themes/{{theme}}/css/print.css" media="print">
         <link href='//fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'>
         <script src="//codeorigin.jquery.com/jquery-2.0.3.min.js"></script>
-        <script src="{{ poche_url }}/themes/{{theme}}/js/init.js"></script>
+        <script src="{{ poche_url }}themes/{{theme}}/js/init.js"></script>
index 792687c064728ade1e600adfd9653d9508440e64..2d41db17a8cc1c39567a3819e389b51795f92fcf 100755 (executable)
@@ -1,6 +1,6 @@
         <header>
             <h1>
-                {% if view == 'home' %}{% block logo %}<img src="{{ poche_url }}/themes/{{ constant('DEFAULT_THEME') }}/img/logo.svg" alt="logo poche" />{% endblock %}
+                {% if view == 'home' %}{% block logo %}<img src="{{ poche_url }}themes/{{theme}}/img/logo.svg" alt="wallabag logo" />{% endblock %}
                 {% elseif view == 'fav' %}<a href="./" title="{% trans "back to home" %}" >{{ block('logo') }} <span>Favoris</span></a>
                 {% elseif view == 'archive' %}<a href="./" title="{% trans "back to home" %}" >{{ block('logo') }} <span>Archive</span></a>
                 {% else %}<a href="./" title="{% trans "back to home" %}" >{{ block('logo') }}</a>
index e80829eff844cc8df5c8320cd06241048fda2c22..25479a3d79d8830350ab3823685bdb1766a39253 100755 (executable)
@@ -12,6 +12,7 @@
                 {% if constant('SHARE_MAIL') == 1 %}<li><a href="mailto:?subject={{ entry.title|url_encode }}&amp;body={{ entry.url|url_encode }}%20via%20@wallabagapp" class="tool email" title="{% trans "email" %}"><span>{% trans "email" %}</span></a></li>{% endif %}
                 {% if constant('SHARE_SHAARLI') == 1 %}<li><a href="{{ constant('SHAARLI_URL') }}/index.php?post={{ entry.url|url_encode }}&amp;title={{ entry.title|url_encode }}" target="_blank" class="tool shaarli" title="{% trans "shaarli" %}"><span>{% trans "shaarli" %}</span></a></li>{% endif %}
                 {% if constant('FLATTR') == 1 %}{% if flattr.status == constant('FLATTRABLE') %}<li class="flattrli"><a href="http://flattr.com/submit/auto?url={{ entry.url }}" class="tool flattr" target="_blank" title="{% trans "flattr" %}"><span>{% trans "flattr" %}</span></a></li>{% elseif flattr.status == constant('FLATTRED') %}<li><a href="{{ flattr.flattrItemURL }}" class="tool flattr" target="_blank" title="{% trans "flattr" %}"><span>{% trans "flattr" %}</span>{{ flattr.numflattrs }}</a></li>{% endif %}{% endif %}
+                <li><a href="./?epub&amp;method=id&amp;id={{ entry.id|e }}" title="Generate epub file">EPUB</a></li>
                 <li><a href="mailto:hello@wallabag.org?subject=Wrong%20display%20in%20wallabag&amp;body={{ entry.url|url_encode }}" title="{% trans "this article appears wrong?" %}" class="tool bad-display"><span>{% trans "this article appears wrong?" %}</span></a></li>
             </ul>
         </div>
@@ -23,7 +24,7 @@
                 {{ content | raw }}
             </article>
         </div>
-        <script src="{{ poche_url }}/themes/{{ constant('DEFAULT_THEME') }}/js/restoreScroll.js"></script>
+        <script src="{{ poche_url }}themes/{{theme}}/js/restoreScroll.js"></script>
         <script type="text/javascript">
         $(document).ready(function() {
 
index 26da7289b23910b6c81ce2be36a549e9a4aa6618..9ab58461abe2dadd38722e7fe782e1904376f8ad 100755 (executable)
@@ -7,22 +7,24 @@
 {% block content %}
         <div id="config">
             <h2>{% trans "Poching a link" %}</h2>
-            <p>{% trans "You can poche a link by several methods:" %} (<a class="special" href="http://doc.wallabag.org" title="{% trans "read the documentation" %}">?</a>)</p>
+            <p>{% trans "There are several ways to save an article:" %} (<a class="special" href="http://doc.wallabag.org" title="{% trans "read the documentation" %}">?</a>)</p>
             <ul>
-                <li>firefox: <a href="https://bitbucket.org/jogaulupeau/poche/downloads/poche.xpi" title="download the firefox extension">{% trans "download the extension" %}</a></li>
-                <li>chrome: <a href="https://bitbucket.org/jogaulupeau/poche/downloads/poche.crx" title="download the chrome extension">{% trans "download the extension" %}</a></li>
-                <li>android: <a href="https://bitbucket.org/jogaulupeau/poche/downloads/Poche.apk" title="download the application">{% trans "download the application" %}</a></li>
+                <li>Firefox: <a href="https://addons.mozilla.org/firefox/addon/wallabag/" title="download the firefox extension">{% trans "download the extension" %}</a></li>
+                <li>Chrome: <a href="http://doc.wallabag.org/doku.php?id=users:chrome_extension" title="download the chrome extension">{% trans "download the extension" %}</a></li>
+                <li>Android: <a href="https://f-droid.org/app/fr.gaulupeau.apps.InThePoche" title="download the application">{% trans "via F-Droid" %}</a> {% trans " or " %} <a href="https://play.google.com/store/apps/details?id=fr.gaulupeau.apps.InThePoche" title="download the application">{% trans "via Google Play" %}</a></li>
+                <li>iOS: <a href="https://itunes.apple.com/app/wallabag/id828331015?mt=8" title="download the iOS application">{% trans "download the application" %}</a></li>
+                <li>Windows Phone: <a href="http://www.windowsphone.com/en-us/store/app/wallabag/ff890514-348c-4d0b-9b43-153fff3f7450" title="download the window phone application">{% trans "download the application" %}</a></li>
                 <li>
                     <form method="get" action="index.php">
                         <label class="addurl" for="plainurl">{% trans "by filling this field" %}:</label>
                         <input required placeholder="Ex:mywebsite.com/article" class="addurl" id="plainurl" name="plainurl" type="url" />
-                        <input type="submit" value="{% trans "poche it!" %}" />
+                        <input type="submit" value="{% trans "bag it!" %}" />
                     </form>
                 </li>
-                <li>{% trans "bookmarklet: drag & drop this link to your bookmarks bar" %} <a id="bookmarklet" ondragend="this.click();" title="i am a bookmarklet, use me !" href="javascript:if(top['bookmarklet-url@wallabag.org']){top['bookmarklet-url@wallabag.org'];}else{(function(){var%20url%20=%20location.href%20||%20url;window.open('{{ poche_url }}?action=add&url='%20+%20btoa(url),'_self');})();void(0);}">{% trans "poche it!" %}</a></li>
+                <li>{% trans "bookmarklet: drag & drop this link to your bookmarks bar" %} <a id="bookmarklet" ondragend="this.click();" title="i am a bookmarklet, use me !" href="javascript:if(top['bookmarklet-url@wallabag.org']){top['bookmarklet-url@wallabag.org'];}else{(function(){var%20url%20=%20location.href%20||%20url;window.open('{{ poche_url }}?action=add&url='%20+%20btoa(url),'_self');})();void(0);}">{% trans "bag it!" %}</a></li>
             </ul>
 
-            <h2>{% trans "Updating poche" %}</h2>
+            <h2>{% trans "Upgrading wallabag" %}</h2>
             <ul>
                 <li>{% trans "your version" %} : <strong>{{ constant('POCHE') }}</strong></li>
                 <li>{% trans "latest stable version" %} : {{ prod }}. {% if compare_prod == -1 %}<strong><a href="http://wallabag.org/">{% trans "a more recent stable version is available." %}</a></strong>{% else %}{% trans "you are up to date." %}{% endif %}</li>
             <li><a href="./?import&amp;from=instapaper">{% trans "import from Instapaper" %}</a> {{ '(you must have a %s file on your server)'|trans|format(constant('INSTAPAPER_FILE')) }}</li>
             </ul>
 
-            <h2>{% trans "Export your poche datas" %}</h2>
-            <p><a href="./?export" target="_blank">{% trans "Click here" %}</a> {% trans "to export your poche datas." %}</p>
+            <h2>{% trans "Export your wallabag data" %}</h2>
+            <p><a href="./?export" target="_blank">{% trans "Click here" %}</a> {% trans "to export your wallabag data." %}</p>
+            
+            <h2>{% trans "Fancy an E-Book ?" %}</h2>
+            <p>{% trans "Click on <a href=\"./?epub&amp;method=all\" title=\"Generate ePub\">this link</a> to get all your articles in one ebook (ePub 3 format)." %}
+            <br>{% trans "This can <b>take a while</b> and can <b>even fail</b> if you have too many articles, depending on your server configuration." %}</p>
+            
+            <h2>{% trans 'Add user' %}</h2>
+            <p>{% trans 'Add a new user :' %}</p>
+            <form method="post" action="?newuser">
+                <fieldset class="w500p">
+                <div class="row">
+                    <label class="col w150p" for="newusername">{% trans 'Login for new user' %}</label>
+                    <input class="col" type="text" id="newusername" name="newusername" placeholder="{% trans 'Login' %}">
+                </div>
+                <div class="row">
+                    <label class="col w150p" for="password4newuser">{% trans "Password for new user" %}</label>
+                    <input class="col" type="password" id="password4newuser" name="password4newuser" placeholder="{% trans "Password" %}">
+                </div>
+                <div class="row mts txtcenter">
+                    <button type="submit">{% trans "Send" %}</button>  
+                </div>
+                </fieldset>
+            </form>
+            
+            <h2>{% trans "Delete account" %}</h2>
+            {% if not only_user %}<form method="post" action="?deluser">
+            <p>{% trans "You can delete your account by entering your password and validating." %}<br /><b>{% trans "Be careful, data will be erased forever (that is a very long time)." %}</b></p>
+            <fieldset class="w500p">
+                <div class="row">
+                    <label class="col w150p" for="password4deletinguser">{% trans "Type here your password" %}</label>
+                    <input class="col" type="password" id="password4deletinguser" name="password4deletinguser" placeholder="{% trans "Password" %}">
+                </div>
+            <div class="row mts txtcenter">
+                <button type="submit">{% trans "Send" %}</button>
+            </div>
+            </form>
+            {% else %}<p>{% trans "You are the only user, you cannot delete your own account." %}<br />
+            {% trans "To completely remove wallabag, delete the wallabag folder on your web server." %}</p>{% endif %}
         </div>
-{% endblock %}
\ No newline at end of file
+{% endblock %}
index 416cfa4306109ea517cc6bb63296db9e7e11266f..401f3f20d96fc6a074c5e31689c813efdda97ba7 100755 (executable)
@@ -14,8 +14,8 @@
 {% block precontent %}
             {% if entries|length > 1 %}
             <ul id="sort">
-                <li><a href="./?sort=ia&amp;view={{ view }}&amp;id={{ id }}"><img src="{{ poche_url }}/themes/{{ theme }}/img/{{ theme }}/top.png" alt="{% trans "by date asc" %}" title="{% trans "by date asc" %}" /></a> {% trans "by date" %} <a href="./?sort=id&amp;view={{ view }}&amp;id={{ id }}"><img src="{{ poche_url }}/themes/{{ theme }}/img/{{ theme }}/down.png" alt="{% trans "by date desc" %}" title="{% trans "by date desc" %}" /></a></li>
-                <li><a href="./?sort=ta&amp;view={{ view }}&amp;id={{ id }}"><img src="{{ poche_url }}/themes/{{ theme }}/img/{{ theme }}/top.png" alt="{% trans "by title asc" %}" title="{% trans "by title asc" %}" /></a> {% trans "by title" %} <a href="./?sort=td&amp;view={{ view }}&amp;id={{ id }}"><img src="{{ poche_url }}/themes/{{ theme }}/img/{{ theme }}/down.png" alt="{% trans "by title desc" %}" title="{% trans "by title desc" %}" /></a></li>
+                <li><a href="./?sort=ia&amp;view={{ view }}&amp;id={{ id }}"><img src="{{ poche_url }}themes/{{ theme }}/img/{{ theme }}/top.png" alt="{% trans "by date asc" %}" title="{% trans "by date asc" %}" /></a> {% trans "by date" %} <a href="./?sort=id&amp;view={{ view }}&amp;id={{ id }}"><img src="{{ poche_url }}themes/{{ theme }}/img/{{ theme }}/down.png" alt="{% trans "by date desc" %}" title="{% trans "by date desc" %}" /></a></li>
+                <li><a href="./?sort=ta&amp;view={{ view }}&amp;id={{ id }}"><img src="{{ poche_url }}themes/{{ theme }}/img/{{ theme }}/top.png" alt="{% trans "by title asc" %}" title="{% trans "by title asc" %}" /></a> {% trans "by title" %} <a href="./?sort=td&amp;view={{ view }}&amp;id={{ id }}"><img src="{{ poche_url }}themes/{{ theme }}/img/{{ theme }}/down.png" alt="{% trans "by title desc" %}" title="{% trans "by title desc" %}" /></a></li>
             </ul>
             {% endif %}
 {% endblock %}
                 {% block pager %}
                     {% if nb_results > 1 %}
                 <div class="results">
-                    <div class="nb-results">{{ nb_results }} {% trans "results" %}</div>
+                    <div class="nb-results">{{ nb_results }} {% trans "results" %}{% if search_term is defined %}{% trans " found for « " %} {{ search_term }} »{% endif %}</div>
                         {{ page_links | raw }}
                 </div>
+                    {% elseif nb_results == 1 %}
+                        {% if search_term is defined %}
+                     <div class="results">
+                        <div class="nb-results">{% trans "Only one result found for " %} « {{ search_term }} »</div>
+                     </div>
+                        {% endif %}
                     {% endif %}
                 {% endblock %}
                 {% for entry in entries %}
                 <p>{{ entry.content|striptags|slice(0, 300) }}...</p>
             </div>
                 {% endfor %}
-            {% endif %}
+            
             {{ block('pager') }}
+            
+            {% if tag %}<a title="{% trans "Download the articles from this tag in an epub" %}" href="./?epub&amp;method=tag&amp;tag={{ tag.value }}">{% trans "Download the articles from this tag in an epub" %}</a>
+            {% elseif search_term is defined %}<a title="{% trans "Download the articles from this search in an epub" %}" href="./?epub&amp;method=search&amp;search={{ search_term }}">{% trans "Download the articles from this search in an epub" %}</a>
+            {% else %}<a title="{% trans "Download the articles from this category in an epub" %}" href="./?epub&amp;method=category&amp;category={{ view }}">{% trans "Download the articles from this category in an epub" %}</a>{% endif %}
+            
+            {% endif %}
+
 {% endblock %}
\ No newline at end of file
old mode 100644 (file)
new mode 100755 (executable)
index 9dfdab5..b11dce2
@@ -4,5 +4,5 @@
 {% include '_menu.twig' %}
 {% endblock %}
 {% block content %}
-{% for tag in tags %}<a class="tag" href="./?view=tag&amp;id={{ tag.id }}">{{ tag.value }}</a> {% if token != '' %}<a href="?feed&amp;type=tag&amp;user_id={{ user_id }}&amp;tag_id={{ tag.id }}&amp;token={{ token }}" target="_blank"><img src="{{ poche_url }}/themes/{{ theme }}/img/{{ theme }}/rss.png" /></a>{% endif %} {% endfor %}
+{% for tag in tags %}<a class="tag" href="./?view=tag&amp;id={{ tag.id }}">{{ tag.value }}</a> {% if token != '' %}<a href="?feed&amp;type=tag&amp;user_id={{ user_id }}&amp;tag_id={{ tag.id }}&amp;token={{ token }}" target="_blank"><img src="{{ poche_url }}themes/{{ theme }}/img/{{ theme }}/rss.png" /></a>{% endif %} {% endfor %}
 {% endblock %}
\ No newline at end of file
diff --git a/themes/dark/img/dark/rss.png b/themes/dark/img/dark/rss.png
new file mode 100644 (file)
index 0000000..21bad1a
Binary files /dev/null and b/themes/dark/img/dark/rss.png differ
index 2e3071ad60b0bcbcd0f890ff3d2169c02878c4ef..619963539c48d408c2ba8ccdf6d538105e8d6afe 100644 (file)
@@ -1,3 +1,3 @@
         <script type="text/javascript">
-          top["bookmarklet-url@wallabag.org"]=""+"<!DOCTYPE html>"+"<html>"+"<head>"+"<title>poche it !</title>"+'<link rel="icon" href="{{poche_url}}tpl/img/favicon.ico" />'+"</head>"+"<body>"+"<script>"+"window.onload=function(){"+"window.setTimeout(function(){"+"history.back();"+"},250);"+"};"+"</scr"+"ipt>"+"</body>"+"</html>"
+          top["bookmarklet-url@wallabag.org"]=""+"<!DOCTYPE html>"+"<html>"+"<head>"+"<title>bag it!</title>"+'<link rel="icon" href="{{poche_url}}tpl/img/favicon.ico" />'+"</head>"+"<body>"+"<script>"+"window.onload=function(){"+"window.setTimeout(function(){"+"history.back();"+"},250);"+"};"+"</scr"+"ipt>"+"</body>"+"</html>"
         </script>
\ No newline at end of file
old mode 100644 (file)
new mode 100755 (executable)
index f310e42..8c939e3
@@ -1,12 +1,14 @@
-        <link rel="shortcut icon" type="image/x-icon" href="{{ poche_url }}/themes/default/img/favicon.ico" />
-        <link rel="apple-touch-icon-precomposed" sizes="144x144" href="{{ poche_url }}/themes/default/img/apple-touch-icon-144x144-precomposed.png">
-        <link rel="apple-touch-icon-precomposed" sizes="72x72" href="{{ poche_url }}/themes/default/img/apple-touch-icon-72x72-precomposed.png">
-        <link rel="apple-touch-icon-precomposed" href="{{ poche_url }}/themes/default/img/apple-touch-icon-precomposed.png">
-        <link rel="stylesheet" href="{{ poche_url }}/themes/default/css/knacss.css" media="all">
-        <link rel="stylesheet" href="{{ poche_url }}/themes/default/css/style.css" media="all">
-        <link rel="stylesheet" href="{{ poche_url }}/themes/{{ theme }}/css/style-{{ theme }}.css" media="all" title="{{ theme }} theme">
-        <link rel="stylesheet" href="{{ poche_url }}/themes/default/css/messages.css" media="all">
-        <link rel="stylesheet" href="{{ poche_url }}/themes/default/css/print.css" media="print">
-        <script src="{{ poche_url }}/themes/default/js/jquery-2.0.3.min.js"></script>
-        <script src="{{ poche_url }}/themes/default/js/autoClose.js"></script>
-        <script src="{{ poche_url }}/themes/default/js/closeMessage.js"></script>
\ No newline at end of file
+        <link rel="shortcut icon" type="image/x-icon" href="{{ poche_url }}themes/default/img/favicon.ico" />
+        <link rel="apple-touch-icon-precomposed" sizes="144x144" href="{{ poche_url }}themes/default/img/apple-touch-icon-144x144-precomposed.png">
+        <link rel="apple-touch-icon-precomposed" sizes="72x72" href="{{ poche_url }}themes/default/img/apple-touch-icon-72x72-precomposed.png">
+        <link rel="apple-touch-icon-precomposed" href="{{ poche_url }}themes/default/img/apple-touch-icon-precomposed.png">
+        <link rel="stylesheet" href="{{ poche_url }}themes/default/css/knacss.css" media="all">
+        <link rel="stylesheet" href="{{ poche_url }}themes/default/css/style.css" media="all">
+        <link rel="stylesheet" href="{{ poche_url }}themes/{{ theme }}/css/style-{{ theme }}.css" media="all" title="{{ theme }} theme">
+        <link rel="stylesheet" href="{{ poche_url }}themes/default/css/messages.css" media="all">
+        <link rel="stylesheet" href="{{ poche_url }}themes/default/css/print.css" media="print">
+        <script src="{{ poche_url }}themes/default/js/jquery-2.0.3.min.js"></script>
+        <script src="{{ poche_url }}themes/default/js/autoClose.js"></script>
+        <script src="{{ poche_url }}themes/default/js/closeMessage.js"></script>
+        <script src="{{ poche_url }}themes/default/js/saveLink.js"></script>
+        <script src="{{ poche_url }}themes/default/js/popupForm.js"></script>
\ No newline at end of file
diff --git a/themes/default/_import.twig b/themes/default/_import.twig
new file mode 100755 (executable)
index 0000000..c59b7a1
--- /dev/null
@@ -0,0 +1,15 @@
+<script type="text/javascript">
+<!--
+  $(document).ready(function() {
+       $("body").css("cursor", "wait");
+       
+    setTimeout(function(){
+      window.location = './?import';
+    }, {{ import.delay }} );
+  });
+//-->
+</script>
+<div class="messages warning">
+  <p>{% trans "Download required for " %} {{ import.recordsDownloadRequired }} {% trans "records" %}.</p>
+  <p>{% trans "Downloading next " %} {{ import.recordsUnderDownload }} {% trans "articles, please wait" %}...</p>
+</div>
index 55583b3d1947769864bcdd9ad504a7ba45ea0bc1..0daa0b03d5ca8f6ef23a40e33214c2e39ee9395f 100644 (file)
@@ -3,9 +3,11 @@
                 <li><a href="./?view=fav" {% if view == 'fav' %}class="current"{% endif %}>{% trans "favorites" %}</a></li>
                 <li><a href="./?view=archive" {% if view == 'archive' %}class="current"{% endif %}>{% trans "archive" %}</a></li>
                 <li><a href="./?view=tags" {% if view == 'tags' %}class="current"{% endif %}>{% trans "tags" %}</a></li>
-                <li><a href="javascript: void(null);" id="pocheit">{% trans "save a link" %}</a><span id="pocheit-arrow"></span></li>
+                <li><a href="javascript: void(null);" id="bagit">{% trans "save a link" %}</a><span id="bagit-arrow"></span></li>
+                <li><a href="javascript: void(null);" id="search">{% trans "search" %}</a><span id="search-arrow"></span></li>
                 <li><a href="./?view=config" {% if view == 'config' %}class="current"{% endif %}>{% trans "config" %}</a></li>
                 <li><a href="./?logout" title="{% trans "logout" %}">{% trans "logout" %}</a></li>
             </ul>
             {% include '_pocheit-form.twig' %}
+            {% include '_search-form.twig' %}
 
index 130961594cd8db15ae50ac6402720aaa12a0baa6..8c982db09dae6192287d65324f1e09b36bf7e496 100755 (executable)
@@ -1,22 +1,8 @@
-<div id="pocheit-form" class="messages info">
-    <center>
-    <form method="get" action="index.php">
-        <input required placeholder="example.com/article" class="addurl" id="plainurl" name="plainurl" type="url" />
-        <input type="submit" value="{% trans "save link!" %}" />
+<div id="bagit-form" class="messages info">
+    <a href="javascript: void(null);" id="bagit-form-close">&nbsp;</a>
+    <form method="get" action="index.php" id="bagit-form-form">
+      <input required placeholder="example.com/article" class="addurl" id="plainurl" name="plainurl" type="url" />
+      <input type="submit" value="{% trans "save link!" %}" />
+      <div id="add-link-result"></div>
     </form>
-    </center>
 </div>
-<script type="text/javascript">
-    $(document).ready(function() {
-
-        $("#pocheit-form").hide();
-
-        $("#pocheit").click(function(){
-            $("#pocheit-form").toggle();
-            $("#pocheit").toggleClass("current");
-            $("#pocheit-arrow").toggleClass("arrow-down");
-        });
-
-
-    });
-</script>
diff --git a/themes/default/_search-form.twig b/themes/default/_search-form.twig
new file mode 100755 (executable)
index 0000000..33bea20
--- /dev/null
@@ -0,0 +1,9 @@
+<div id="search-form" class="messages info">                   
+<form method="get" action="index.php">
+    <p>
+               <input type="hidden" name="view" value="search"></input>
+        <label>{% trans "Search" %}</label> : <input type="text" placeholder="{% trans "Enter your search here" %}" name="search" />
+               <input type="submit" value="{% trans "Search" %} !"></input>
+    </p>
+</form>
+</div>
diff --git a/themes/default/_sorting.twig b/themes/default/_sorting.twig
new file mode 100755 (executable)
index 0000000..ce3d38b
--- /dev/null
@@ -0,0 +1,6 @@
+{% if entries|length > 1 %}
+  <ul id="sort">
+      <li><a href="./?sort=ia&amp;view={{ view }}{% if search_term is defined %}&amp;search={{ search_term }}{% endif %}&amp;id={{ id }}"><img src="{{ poche_url }}themes/{{ theme }}/img/{{ theme }}/top.png" alt="{% trans "by date asc" %}" title="{% trans "by date asc" %}" /></a> {% trans "by date" %} <a href="./?sort=id&amp;view={{ view }}{% if search_term is defined %}&amp;search={{ search_term }}{% endif %}&amp;id={{ id }}"><img src="{{ poche_url }}themes/{{ theme }}/img/{{ theme }}/down.png" alt="{% trans "by date desc" %}" title="{% trans "by date desc" %}" /></a></li>
+      <li><a href="./?sort=ta&amp;view={{ view }}{% if search_term is defined %}&amp;search={{ search_term }}{% endif %}&amp;id={{ id }}"><img src="{{ poche_url }}themes/{{ theme }}/img/{{ theme }}/top.png" alt="{% trans "by title asc" %}" title="{% trans "by title asc" %}" /></a> {% trans "by title" %} <a href="./?sort=td&amp;view={{ view }}{% if search_term is defined %}&amp;search={{ search_term }}{% endif %}&amp;id={{ id }}"><img src="{{ poche_url }}themes/{{ theme }}/img/{{ theme }}/down.png" alt="{% trans "by title desc" %}" title="{% trans "by title desc" %}" /></a></li>
+  </ul>
+{% endif %}
old mode 100644 (file)
new mode 100755 (executable)
index 0711acd..45806f0
@@ -1,6 +1,6 @@
         <header class="w600p center mbm">
             <h1>
-                {% if view == 'home' %}{% block logo %}<img width="100" height="100" src="{{ poche_url }}/themes/baggy/img/logo-other_themes.png" alt="logo poche" />{% endblock %}
+                {% if view == 'home' %}{% block logo %}<img width="100" height="100" src="{{ poche_url }}themes/baggy/img/logo-other_themes.png" alt="wallabag logo" />{% endblock %}
                 {% else %}<a href="./" title="{% trans "return home" %}" >{{ block('logo') }}</a>
                 {% endif %}
             </h1>
old mode 100644 (file)
new mode 100755 (executable)
index cd4d074..160f604
@@ -8,10 +8,11 @@
             <h2>{% trans "Saving articles" %}</h2>
             <p>{% trans "There are several ways to save an article:" %} (<a href="http://doc.wallabag.org/" title="{% trans "read the documentation" %}">?</a>)</p>
             <ul>
-                <li>Firefox: <a href="https://addons.mozilla.org/firefox/addon/poche/" title="download the firefox extension">{% trans "download the extension" %}</a></li>
+                <li>Firefox: <a href="https://addons.mozilla.org/firefox/addon/wallabag/" title="download the firefox extension">{% trans "download the extension" %}</a></li>
                 <li>Chrome: <a href="http://doc.wallabag.org/doku.php?id=users:chrome_extension" title="download the chrome extension">{% trans "download the extension" %}</a></li>
-                <li>Android: <a href="https://f-droid.org/repository/browse/?fdid=fr.gaulupeau.apps.Poche" title="download the application">{% trans "via F-Droid" %}</a> {% trans " or " %} <a href="https://play.google.com/store/apps/details?id=fr.gaulupeau.apps.InThePoche" title="download the application">{% trans "via Google Play" %}</a></li>
-                <li>Windows Phone: <a href="https://www.windowsphone.com/en-us/store/app/poche/334de2f0-51b5-4826-8549-a3d805a37e83" title="download the window phone application">{% trans "download the application" %}</a></li>
+                <li>Android: <a href="https://f-droid.org/app/fr.gaulupeau.apps.InThePoche" title="download the application">{% trans "via F-Droid" %}</a> {% trans " or " %} <a href="https://play.google.com/store/apps/details?id=fr.gaulupeau.apps.InThePoche" title="download the application">{% trans "via Google Play" %}</a></li>
+                <li>iOS: <a href="https://itunes.apple.com/app/wallabag/id828331015?mt=8" title="download the iOS application">{% trans "download the application" %}</a></li>
+                <li>Windows Phone: <a href="http://www.windowsphone.com/en-us/store/app/wallabag/ff890514-348c-4d0b-9b43-153fff3f7450" title="download the window phone application">{% trans "download the application" %}</a></li>
                 <li>
                     <form method="get" action="index.php">
                         <label class="addurl" for="config_plainurl">{% trans "By filling this field" %}:</label>
             {% endif %}
 
             <h2>{% trans "Import" %}</h2>
-            <p>{% trans "Please execute the import script locally as it can take a very long time." %}</p>
-            <p>{% trans "More info in the official documentation:" %} <a href="http://doc.wallabag.org/doku.php?id=users:migrate">wallabag.org</a></p>
-            <ul>
-                <li><a href="./?import&amp;from=pocket">{% trans "Import from Pocket" %}</a> {{ '(you must have a %s file on your server)'|trans|format(constant('POCKET_FILE')) }}</li>
-                <li><a href="./?import&amp;from=readability">{% trans "Import from Readability" %}</a> {{ '(you must have a %s file on your server)'|trans|format(constant('READABILITY_FILE')) }}</li>
-                <li><a href="./?import&amp;from=instapaper">{% trans "Import from Instapaper" %}</a> {{ '(you must have a %s file on your server)'|trans|format(constant('INSTAPAPER_FILE')) }}</li>
-                <li><a href="./?import&amp;from=poche">{% trans "Import from wallabag" %}</a> {{ '(you must have a %s file on your server)'|trans|format(constant('POCHE_FILE')) }}</li>
-            </ul>
+            <p>{% trans "You can import your Pocket, Readability, Instapaper, Wallabag or any data in appropriate json or html format." %}</p>
+            <p>{% trans "Please select export file on your computer and press \"Import\" button below.<br>Wallabag will parse your file, insert all URLs and start fetching of articles if required.<br>Fetching process is controlled by two constants in your config file: IMPORT_LIMIT (how many articles are fetched at once) and IMPORT_DELAY (delay between fetch of next batch of articles)." %}</p>
+            <form method="post" action="?import" name="uploadfile" enctype="multipart/form-data">
+                <fieldset class="w500p">
+                    <div class="row">
+                        <label class="col w150p" for="file">{% trans "File:" %}</label>
+                        <input class="col" type="file" id="file" name="file" tabindex="4">
+                    </div>
+                    <div class="row mts txtcenter">
+                        <button class="bouton" type="submit" tabindex="4">{% trans "Import" %}</button>
+                    </div>
+                </fieldset>
+            </form>
+            <p><a href="?import">{% trans "You can click here to fetch content for articles with no content." %}</a></p>
 
             <h2>{% trans "Export your wallabag data" %}</h2>
             {% if constant('STORAGE') == 'sqlite' %}
 
             <h2>{% trans "Cache" %}</h2>
             <p><a href="?empty-cache">{% trans "Click here" %}</a> {% trans "to delete cache." %}</p>
+            
+            <h2>{% trans "Fancy an E-Book ?" %}</h2>
+            <p>{% trans "Click on <a href=\"./?epub&amp;method=all\" title=\"Generate ePub\">this link</a> to get all your articles in one ebook (ePub 3 format)." %}
+            <br>{% trans "This can <b>take a while</b> and can <b>even fail</b> if you have too many articles, depending on your server configuration." %}</p>
+            
+            <h2>{% trans 'Add user' %}</h2>
+            <p>{% trans 'Add a new user :' %}</p>
+            <form method="post" action="?newuser">
+                <fieldset class="w500p">
+                <div class="row">
+                    <label class="col w150p" for="newusername">{% trans 'Login for new user' %}</label>
+                    <input class="col" type="text" id="newusername" name="newusername" placeholder="{% trans 'Login' %}">
+                </div>
+                <div class="row">
+                    <label class="col w150p" for="password4newuser">{% trans "Password for new user" %}</label>
+                    <input class="col" type="password" id="password4newuser" name="password4newuser" placeholder="{% trans "Password" %}">
+                </div>
+                <div class="row mts txtcenter">
+                    <button type="submit">{% trans "Send" %}</button>  
+                </div>
+                </fieldset>
+            </form>
+            
+            <h2>{% trans "Delete account" %}</h2>
+            {% if not only_user %}<form method="post" action="?deluser">
+            <p>{% trans "You can delete your account by entering your password and validating." %}<br /><b>{% trans "Be careful, data will be erased forever (that is a very long time)." %}</b></p>
+            <fieldset class="w500p">
+                <div class="row">
+                    <label class="col w150p" for="password4deletinguser">{% trans "Type here your password" %}</label>
+                    <input class="col" type="password" id="password4deletinguser" name="password4deletinguser" placeholder="{% trans "Password" %}">
+                </div>
+            <div class="row mts txtcenter">
+                <button type="submit">{% trans "Send" %}</button>
+            </div>
+            </form>
+            {% else %}<p>{% trans "You are the only user, you cannot delete your own account." %}<br />
+            {% trans "To completely remove wallabag, delete the wallabag folder on your web server." %}</p>{% endif %}
 {% endblock %}
diff --git a/themes/default/css/images/animated-overlay.gif b/themes/default/css/images/animated-overlay.gif
new file mode 100644 (file)
index 0000000..d441f75
Binary files /dev/null and b/themes/default/css/images/animated-overlay.gif differ
diff --git a/themes/default/css/images/ui-bg_flat_0_aaaaaa_40x100.png b/themes/default/css/images/ui-bg_flat_0_aaaaaa_40x100.png
new file mode 100644 (file)
index 0000000..9f10cb6
Binary files /dev/null and b/themes/default/css/images/ui-bg_flat_0_aaaaaa_40x100.png differ
diff --git a/themes/default/css/images/ui-bg_flat_75_ffffff_40x100.png b/themes/default/css/images/ui-bg_flat_75_ffffff_40x100.png
new file mode 100644 (file)
index 0000000..b89b914
Binary files /dev/null and b/themes/default/css/images/ui-bg_flat_75_ffffff_40x100.png differ
diff --git a/themes/default/css/images/ui-bg_glass_55_fbf9ee_1x400.png b/themes/default/css/images/ui-bg_glass_55_fbf9ee_1x400.png
new file mode 100644 (file)
index 0000000..780d3ff
Binary files /dev/null and b/themes/default/css/images/ui-bg_glass_55_fbf9ee_1x400.png differ
diff --git a/themes/default/css/images/ui-bg_glass_65_ffffff_1x400.png b/themes/default/css/images/ui-bg_glass_65_ffffff_1x400.png
new file mode 100644 (file)
index 0000000..da53255
Binary files /dev/null and b/themes/default/css/images/ui-bg_glass_65_ffffff_1x400.png differ
diff --git a/themes/default/css/images/ui-bg_glass_75_dadada_1x400.png b/themes/default/css/images/ui-bg_glass_75_dadada_1x400.png
new file mode 100644 (file)
index 0000000..f630660
Binary files /dev/null and b/themes/default/css/images/ui-bg_glass_75_dadada_1x400.png differ
diff --git a/themes/default/css/images/ui-bg_glass_75_e6e6e6_1x400.png b/themes/default/css/images/ui-bg_glass_75_e6e6e6_1x400.png
new file mode 100644 (file)
index 0000000..7d34706
Binary files /dev/null and b/themes/default/css/images/ui-bg_glass_75_e6e6e6_1x400.png differ
diff --git a/themes/default/css/images/ui-bg_glass_95_fef1ec_1x400.png b/themes/default/css/images/ui-bg_glass_95_fef1ec_1x400.png
new file mode 100644 (file)
index 0000000..533c490
Binary files /dev/null and b/themes/default/css/images/ui-bg_glass_95_fef1ec_1x400.png differ
diff --git a/themes/default/css/images/ui-bg_highlight-soft_75_cccccc_1x100.png b/themes/default/css/images/ui-bg_highlight-soft_75_cccccc_1x100.png
new file mode 100644 (file)
index 0000000..bf3a948
Binary files /dev/null and b/themes/default/css/images/ui-bg_highlight-soft_75_cccccc_1x100.png differ
diff --git a/themes/default/css/images/ui-icons_222222_256x240.png b/themes/default/css/images/ui-icons_222222_256x240.png
new file mode 100644 (file)
index 0000000..c1cb117
Binary files /dev/null and b/themes/default/css/images/ui-icons_222222_256x240.png differ
diff --git a/themes/default/css/images/ui-icons_2e83ff_256x240.png b/themes/default/css/images/ui-icons_2e83ff_256x240.png
new file mode 100644 (file)
index 0000000..84b601b
Binary files /dev/null and b/themes/default/css/images/ui-icons_2e83ff_256x240.png differ
diff --git a/themes/default/css/images/ui-icons_454545_256x240.png b/themes/default/css/images/ui-icons_454545_256x240.png
new file mode 100644 (file)
index 0000000..b6db1ac
Binary files /dev/null and b/themes/default/css/images/ui-icons_454545_256x240.png differ
diff --git a/themes/default/css/images/ui-icons_888888_256x240.png b/themes/default/css/images/ui-icons_888888_256x240.png
new file mode 100644 (file)
index 0000000..feea0e2
Binary files /dev/null and b/themes/default/css/images/ui-icons_888888_256x240.png differ
diff --git a/themes/default/css/images/ui-icons_cd0a0a_256x240.png b/themes/default/css/images/ui-icons_cd0a0a_256x240.png
new file mode 100644 (file)
index 0000000..ed5b6b0
Binary files /dev/null and b/themes/default/css/images/ui-icons_cd0a0a_256x240.png differ
diff --git a/themes/default/css/jquery-ui-1.10.4.custom.css b/themes/default/css/jquery-ui-1.10.4.custom.css
new file mode 100644 (file)
index 0000000..5690172
--- /dev/null
@@ -0,0 +1,560 @@
+/*! jQuery UI - v1.10.4 - 2014-03-09
+* http://jqueryui.com
+* Includes: jquery.ui.core.css, jquery.ui.autocomplete.css, jquery.ui.menu.css, jquery.ui.theme.css
+* To view and modify this theme, visit http://jqueryui.com/themeroller/?ffDefault=Verdana%2CArial%2Csans-serif&fwDefault=normal&fsDefault=1.1em&cornerRadius=4px&bgColorHeader=cccccc&bgTextureHeader=highlight_soft&bgImgOpacityHeader=75&borderColorHeader=aaaaaa&fcHeader=222222&iconColorHeader=222222&bgColorContent=ffffff&bgTextureContent=flat&bgImgOpacityContent=75&borderColorContent=aaaaaa&fcContent=222222&iconColorContent=222222&bgColorDefault=e6e6e6&bgTextureDefault=glass&bgImgOpacityDefault=75&borderColorDefault=d3d3d3&fcDefault=555555&iconColorDefault=888888&bgColorHover=dadada&bgTextureHover=glass&bgImgOpacityHover=75&borderColorHover=999999&fcHover=212121&iconColorHover=454545&bgColorActive=ffffff&bgTextureActive=glass&bgImgOpacityActive=65&borderColorActive=aaaaaa&fcActive=212121&iconColorActive=454545&bgColorHighlight=fbf9ee&bgTextureHighlight=glass&bgImgOpacityHighlight=55&borderColorHighlight=fcefa1&fcHighlight=363636&iconColorHighlight=2e83ff&bgColorError=fef1ec&bgTextureError=glass&bgImgOpacityError=95&borderColorError=cd0a0a&fcError=cd0a0a&iconColorError=cd0a0a&bgColorOverlay=aaaaaa&bgTextureOverlay=flat&bgImgOpacityOverlay=0&opacityOverlay=30&bgColorShadow=aaaaaa&bgTextureShadow=flat&bgImgOpacityShadow=0&opacityShadow=30&thicknessShadow=8px&offsetTopShadow=-8px&offsetLeftShadow=-8px&cornerRadiusShadow=8px
+* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */
+
+/* Layout helpers
+----------------------------------*/
+.ui-helper-hidden {
+       display: none;
+}
+.ui-helper-hidden-accessible {
+       border: 0;
+       clip: rect(0 0 0 0);
+       height: 1px;
+       margin: -1px;
+       overflow: hidden;
+       padding: 0;
+       position: absolute;
+       width: 1px;
+}
+.ui-helper-reset {
+       margin: 0;
+       padding: 0;
+       border: 0;
+       outline: 0;
+       line-height: 1.3;
+       text-decoration: none;
+       font-size: 100%;
+       list-style: none;
+}
+.ui-helper-clearfix:before,
+.ui-helper-clearfix:after {
+       content: "";
+       display: table;
+       border-collapse: collapse;
+}
+.ui-helper-clearfix:after {
+       clear: both;
+}
+.ui-helper-clearfix {
+       min-height: 0; /* support: IE7 */
+}
+.ui-helper-zfix {
+       width: 100%;
+       height: 100%;
+       top: 0;
+       left: 0;
+       position: absolute;
+       opacity: 0;
+       filter:Alpha(Opacity=0);
+}
+
+.ui-front {
+       z-index: 100;
+}
+
+
+/* Interaction Cues
+----------------------------------*/
+.ui-state-disabled {
+       cursor: default !important;
+}
+
+
+/* Icons
+----------------------------------*/
+
+/* states and images */
+.ui-icon {
+       display: block;
+       text-indent: -99999px;
+       overflow: hidden;
+       background-repeat: no-repeat;
+}
+
+
+/* Misc visuals
+----------------------------------*/
+
+/* Overlays */
+.ui-widget-overlay {
+       position: fixed;
+       top: 0;
+       left: 0;
+       width: 100%;
+       height: 100%;
+}
+.ui-autocomplete {
+       position: absolute;
+       top: 0;
+       left: 0;
+       cursor: default;
+}
+.ui-menu {
+       list-style: none;
+       padding: 2px;
+       margin: 0;
+       display: block;
+       outline: none;
+}
+.ui-menu .ui-menu {
+       margin-top: -3px;
+       position: absolute;
+}
+.ui-menu .ui-menu-item {
+       margin: 0;
+       padding: 0;
+       width: 100%;
+       /* support: IE10, see #8844 */
+       list-style-image: url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7);
+}
+.ui-menu .ui-menu-divider {
+       margin: 5px -2px 5px -2px;
+       height: 0;
+       font-size: 0;
+       line-height: 0;
+       border-width: 1px 0 0 0;
+}
+.ui-menu .ui-menu-item a {
+       text-decoration: none;
+       display: block;
+       padding: 2px .4em;
+       line-height: 1.5;
+       min-height: 0; /* support: IE7 */
+       font-weight: normal;
+}
+.ui-menu .ui-menu-item a.ui-state-focus,
+.ui-menu .ui-menu-item a.ui-state-active {
+       font-weight: normal;
+       margin: -1px;
+}
+
+.ui-menu .ui-state-disabled {
+       font-weight: normal;
+       margin: .4em 0 .2em;
+       line-height: 1.5;
+}
+.ui-menu .ui-state-disabled a {
+       cursor: default;
+}
+
+/* icon support */
+.ui-menu-icons {
+       position: relative;
+}
+.ui-menu-icons .ui-menu-item a {
+       position: relative;
+       padding-left: 2em;
+}
+
+/* left-aligned */
+.ui-menu .ui-icon {
+       position: absolute;
+       top: .2em;
+       left: .2em;
+}
+
+/* right-aligned */
+.ui-menu .ui-menu-icon {
+       position: static;
+       float: right;
+}
+
+/* Component containers
+----------------------------------*/
+.ui-widget {
+       font-family: Verdana,Arial,sans-serif;
+       font-size: 1.1em;
+}
+.ui-widget .ui-widget {
+       font-size: 1em;
+}
+.ui-widget input,
+.ui-widget select,
+.ui-widget textarea,
+.ui-widget button {
+       font-family: Verdana,Arial,sans-serif;
+       font-size: 1em;
+}
+.ui-widget-content {
+       border: 1px solid #aaaaaa;
+       background: #ffffff url(images/ui-bg_flat_75_ffffff_40x100.png) 50% 50% repeat-x;
+       color: #222222;
+}
+.ui-widget-content a {
+       color: #222222;
+}
+.ui-widget-header {
+       border: 1px solid #aaaaaa;
+       background: #cccccc url(images/ui-bg_highlight-soft_75_cccccc_1x100.png) 50% 50% repeat-x;
+       color: #222222;
+       font-weight: bold;
+}
+.ui-widget-header a {
+       color: #222222;
+}
+
+/* Interaction states
+----------------------------------*/
+.ui-state-default,
+.ui-widget-content .ui-state-default,
+.ui-widget-header .ui-state-default {
+       border: 1px solid #d3d3d3;
+       background: #e6e6e6 url(images/ui-bg_glass_75_e6e6e6_1x400.png) 50% 50% repeat-x;
+       font-weight: normal;
+       color: #555555;
+}
+.ui-state-default a,
+.ui-state-default a:link,
+.ui-state-default a:visited {
+       color: #555555;
+       text-decoration: none;
+}
+.ui-state-hover,
+.ui-widget-content .ui-state-hover,
+.ui-widget-header .ui-state-hover,
+.ui-state-focus,
+.ui-widget-content .ui-state-focus,
+.ui-widget-header .ui-state-focus {
+       border: 1px solid #999999;
+       background: #dadada url(images/ui-bg_glass_75_dadada_1x400.png) 50% 50% repeat-x;
+       font-weight: normal;
+       color: #212121;
+}
+.ui-state-hover a,
+.ui-state-hover a:hover,
+.ui-state-hover a:link,
+.ui-state-hover a:visited,
+.ui-state-focus a,
+.ui-state-focus a:hover,
+.ui-state-focus a:link,
+.ui-state-focus a:visited {
+       color: #212121;
+       text-decoration: none;
+}
+.ui-state-active,
+.ui-widget-content .ui-state-active,
+.ui-widget-header .ui-state-active {
+       border: 1px solid #aaaaaa;
+       background: #ffffff url(images/ui-bg_glass_65_ffffff_1x400.png) 50% 50% repeat-x;
+       font-weight: normal;
+       color: #212121;
+}
+.ui-state-active a,
+.ui-state-active a:link,
+.ui-state-active a:visited {
+       color: #212121;
+       text-decoration: none;
+}
+
+/* Interaction Cues
+----------------------------------*/
+.ui-state-highlight,
+.ui-widget-content .ui-state-highlight,
+.ui-widget-header .ui-state-highlight {
+       border: 1px solid #fcefa1;
+       background: #fbf9ee url(images/ui-bg_glass_55_fbf9ee_1x400.png) 50% 50% repeat-x;
+       color: #363636;
+}
+.ui-state-highlight a,
+.ui-widget-content .ui-state-highlight a,
+.ui-widget-header .ui-state-highlight a {
+       color: #363636;
+}
+.ui-state-error,
+.ui-widget-content .ui-state-error,
+.ui-widget-header .ui-state-error {
+       border: 1px solid #cd0a0a;
+       background: #fef1ec url(images/ui-bg_glass_95_fef1ec_1x400.png) 50% 50% repeat-x;
+       color: #cd0a0a;
+}
+.ui-state-error a,
+.ui-widget-content .ui-state-error a,
+.ui-widget-header .ui-state-error a {
+       color: #cd0a0a;
+}
+.ui-state-error-text,
+.ui-widget-content .ui-state-error-text,
+.ui-widget-header .ui-state-error-text {
+       color: #cd0a0a;
+}
+.ui-priority-primary,
+.ui-widget-content .ui-priority-primary,
+.ui-widget-header .ui-priority-primary {
+       font-weight: bold;
+}
+.ui-priority-secondary,
+.ui-widget-content .ui-priority-secondary,
+.ui-widget-header .ui-priority-secondary {
+       opacity: .7;
+       filter:Alpha(Opacity=70);
+       font-weight: normal;
+}
+.ui-state-disabled,
+.ui-widget-content .ui-state-disabled,
+.ui-widget-header .ui-state-disabled {
+       opacity: .35;
+       filter:Alpha(Opacity=35);
+       background-image: none;
+}
+.ui-state-disabled .ui-icon {
+       filter:Alpha(Opacity=35); /* For IE8 - See #6059 */
+}
+
+/* Icons
+----------------------------------*/
+
+/* states and images */
+.ui-icon {
+       width: 16px;
+       height: 16px;
+}
+.ui-icon,
+.ui-widget-content .ui-icon {
+       background-image: url(images/ui-icons_222222_256x240.png);
+}
+.ui-widget-header .ui-icon {
+       background-image: url(images/ui-icons_222222_256x240.png);
+}
+.ui-state-default .ui-icon {
+       background-image: url(images/ui-icons_888888_256x240.png);
+}
+.ui-state-hover .ui-icon,
+.ui-state-focus .ui-icon {
+       background-image: url(images/ui-icons_454545_256x240.png);
+}
+.ui-state-active .ui-icon {
+       background-image: url(images/ui-icons_454545_256x240.png);
+}
+.ui-state-highlight .ui-icon {
+       background-image: url(images/ui-icons_2e83ff_256x240.png);
+}
+.ui-state-error .ui-icon,
+.ui-state-error-text .ui-icon {
+       background-image: url(images/ui-icons_cd0a0a_256x240.png);
+}
+
+/* positioning */
+.ui-icon-blank { background-position: 16px 16px; }
+.ui-icon-carat-1-n { background-position: 0 0; }
+.ui-icon-carat-1-ne { background-position: -16px 0; }
+.ui-icon-carat-1-e { background-position: -32px 0; }
+.ui-icon-carat-1-se { background-position: -48px 0; }
+.ui-icon-carat-1-s { background-position: -64px 0; }
+.ui-icon-carat-1-sw { background-position: -80px 0; }
+.ui-icon-carat-1-w { background-position: -96px 0; }
+.ui-icon-carat-1-nw { background-position: -112px 0; }
+.ui-icon-carat-2-n-s { background-position: -128px 0; }
+.ui-icon-carat-2-e-w { background-position: -144px 0; }
+.ui-icon-triangle-1-n { background-position: 0 -16px; }
+.ui-icon-triangle-1-ne { background-position: -16px -16px; }
+.ui-icon-triangle-1-e { background-position: -32px -16px; }
+.ui-icon-triangle-1-se { background-position: -48px -16px; }
+.ui-icon-triangle-1-s { background-position: -64px -16px; }
+.ui-icon-triangle-1-sw { background-position: -80px -16px; }
+.ui-icon-triangle-1-w { background-position: -96px -16px; }
+.ui-icon-triangle-1-nw { background-position: -112px -16px; }
+.ui-icon-triangle-2-n-s { background-position: -128px -16px; }
+.ui-icon-triangle-2-e-w { background-position: -144px -16px; }
+.ui-icon-arrow-1-n { background-position: 0 -32px; }
+.ui-icon-arrow-1-ne { background-position: -16px -32px; }
+.ui-icon-arrow-1-e { background-position: -32px -32px; }
+.ui-icon-arrow-1-se { background-position: -48px -32px; }
+.ui-icon-arrow-1-s { background-position: -64px -32px; }
+.ui-icon-arrow-1-sw { background-position: -80px -32px; }
+.ui-icon-arrow-1-w { background-position: -96px -32px; }
+.ui-icon-arrow-1-nw { background-position: -112px -32px; }
+.ui-icon-arrow-2-n-s { background-position: -128px -32px; }
+.ui-icon-arrow-2-ne-sw { background-position: -144px -32px; }
+.ui-icon-arrow-2-e-w { background-position: -160px -32px; }
+.ui-icon-arrow-2-se-nw { background-position: -176px -32px; }
+.ui-icon-arrowstop-1-n { background-position: -192px -32px; }
+.ui-icon-arrowstop-1-e { background-position: -208px -32px; }
+.ui-icon-arrowstop-1-s { background-position: -224px -32px; }
+.ui-icon-arrowstop-1-w { background-position: -240px -32px; }
+.ui-icon-arrowthick-1-n { background-position: 0 -48px; }
+.ui-icon-arrowthick-1-ne { background-position: -16px -48px; }
+.ui-icon-arrowthick-1-e { background-position: -32px -48px; }
+.ui-icon-arrowthick-1-se { background-position: -48px -48px; }
+.ui-icon-arrowthick-1-s { background-position: -64px -48px; }
+.ui-icon-arrowthick-1-sw { background-position: -80px -48px; }
+.ui-icon-arrowthick-1-w { background-position: -96px -48px; }
+.ui-icon-arrowthick-1-nw { background-position: -112px -48px; }
+.ui-icon-arrowthick-2-n-s { background-position: -128px -48px; }
+.ui-icon-arrowthick-2-ne-sw { background-position: -144px -48px; }
+.ui-icon-arrowthick-2-e-w { background-position: -160px -48px; }
+.ui-icon-arrowthick-2-se-nw { background-position: -176px -48px; }
+.ui-icon-arrowthickstop-1-n { background-position: -192px -48px; }
+.ui-icon-arrowthickstop-1-e { background-position: -208px -48px; }
+.ui-icon-arrowthickstop-1-s { background-position: -224px -48px; }
+.ui-icon-arrowthickstop-1-w { background-position: -240px -48px; }
+.ui-icon-arrowreturnthick-1-w { background-position: 0 -64px; }
+.ui-icon-arrowreturnthick-1-n { background-position: -16px -64px; }
+.ui-icon-arrowreturnthick-1-e { background-position: -32px -64px; }
+.ui-icon-arrowreturnthick-1-s { background-position: -48px -64px; }
+.ui-icon-arrowreturn-1-w { background-position: -64px -64px; }
+.ui-icon-arrowreturn-1-n { background-position: -80px -64px; }
+.ui-icon-arrowreturn-1-e { background-position: -96px -64px; }
+.ui-icon-arrowreturn-1-s { background-position: -112px -64px; }
+.ui-icon-arrowrefresh-1-w { background-position: -128px -64px; }
+.ui-icon-arrowrefresh-1-n { background-position: -144px -64px; }
+.ui-icon-arrowrefresh-1-e { background-position: -160px -64px; }
+.ui-icon-arrowrefresh-1-s { background-position: -176px -64px; }
+.ui-icon-arrow-4 { background-position: 0 -80px; }
+.ui-icon-arrow-4-diag { background-position: -16px -80px; }
+.ui-icon-extlink { background-position: -32px -80px; }
+.ui-icon-newwin { background-position: -48px -80px; }
+.ui-icon-refresh { background-position: -64px -80px; }
+.ui-icon-shuffle { background-position: -80px -80px; }
+.ui-icon-transfer-e-w { background-position: -96px -80px; }
+.ui-icon-transferthick-e-w { background-position: -112px -80px; }
+.ui-icon-folder-collapsed { background-position: 0 -96px; }
+.ui-icon-folder-open { background-position: -16px -96px; }
+.ui-icon-document { background-position: -32px -96px; }
+.ui-icon-document-b { background-position: -48px -96px; }
+.ui-icon-note { background-position: -64px -96px; }
+.ui-icon-mail-closed { background-position: -80px -96px; }
+.ui-icon-mail-open { background-position: -96px -96px; }
+.ui-icon-suitcase { background-position: -112px -96px; }
+.ui-icon-comment { background-position: -128px -96px; }
+.ui-icon-person { background-position: -144px -96px; }
+.ui-icon-print { background-position: -160px -96px; }
+.ui-icon-trash { background-position: -176px -96px; }
+.ui-icon-locked { background-position: -192px -96px; }
+.ui-icon-unlocked { background-position: -208px -96px; }
+.ui-icon-bookmark { background-position: -224px -96px; }
+.ui-icon-tag { background-position: -240px -96px; }
+.ui-icon-home { background-position: 0 -112px; }
+.ui-icon-flag { background-position: -16px -112px; }
+.ui-icon-calendar { background-position: -32px -112px; }
+.ui-icon-cart { background-position: -48px -112px; }
+.ui-icon-pencil { background-position: -64px -112px; }
+.ui-icon-clock { background-position: -80px -112px; }
+.ui-icon-disk { background-position: -96px -112px; }
+.ui-icon-calculator { background-position: -112px -112px; }
+.ui-icon-zoomin { background-position: -128px -112px; }
+.ui-icon-zoomout { background-position: -144px -112px; }
+.ui-icon-search { background-position: -160px -112px; }
+.ui-icon-wrench { background-position: -176px -112px; }
+.ui-icon-gear { background-position: -192px -112px; }
+.ui-icon-heart { background-position: -208px -112px; }
+.ui-icon-star { background-position: -224px -112px; }
+.ui-icon-link { background-position: -240px -112px; }
+.ui-icon-cancel { background-position: 0 -128px; }
+.ui-icon-plus { background-position: -16px -128px; }
+.ui-icon-plusthick { background-position: -32px -128px; }
+.ui-icon-minus { background-position: -48px -128px; }
+.ui-icon-minusthick { background-position: -64px -128px; }
+.ui-icon-close { background-position: -80px -128px; }
+.ui-icon-closethick { background-position: -96px -128px; }
+.ui-icon-key { background-position: -112px -128px; }
+.ui-icon-lightbulb { background-position: -128px -128px; }
+.ui-icon-scissors { background-position: -144px -128px; }
+.ui-icon-clipboard { background-position: -160px -128px; }
+.ui-icon-copy { background-position: -176px -128px; }
+.ui-icon-contact { background-position: -192px -128px; }
+.ui-icon-image { background-position: -208px -128px; }
+.ui-icon-video { background-position: -224px -128px; }
+.ui-icon-script { background-position: -240px -128px; }
+.ui-icon-alert { background-position: 0 -144px; }
+.ui-icon-info { background-position: -16px -144px; }
+.ui-icon-notice { background-position: -32px -144px; }
+.ui-icon-help { background-position: -48px -144px; }
+.ui-icon-check { background-position: -64px -144px; }
+.ui-icon-bullet { background-position: -80px -144px; }
+.ui-icon-radio-on { background-position: -96px -144px; }
+.ui-icon-radio-off { background-position: -112px -144px; }
+.ui-icon-pin-w { background-position: -128px -144px; }
+.ui-icon-pin-s { background-position: -144px -144px; }
+.ui-icon-play { background-position: 0 -160px; }
+.ui-icon-pause { background-position: -16px -160px; }
+.ui-icon-seek-next { background-position: -32px -160px; }
+.ui-icon-seek-prev { background-position: -48px -160px; }
+.ui-icon-seek-end { background-position: -64px -160px; }
+.ui-icon-seek-start { background-position: -80px -160px; }
+/* ui-icon-seek-first is deprecated, use ui-icon-seek-start instead */
+.ui-icon-seek-first { background-position: -80px -160px; }
+.ui-icon-stop { background-position: -96px -160px; }
+.ui-icon-eject { background-position: -112px -160px; }
+.ui-icon-volume-off { background-position: -128px -160px; }
+.ui-icon-volume-on { background-position: -144px -160px; }
+.ui-icon-power { background-position: 0 -176px; }
+.ui-icon-signal-diag { background-position: -16px -176px; }
+.ui-icon-signal { background-position: -32px -176px; }
+.ui-icon-battery-0 { background-position: -48px -176px; }
+.ui-icon-battery-1 { background-position: -64px -176px; }
+.ui-icon-battery-2 { background-position: -80px -176px; }
+.ui-icon-battery-3 { background-position: -96px -176px; }
+.ui-icon-circle-plus { background-position: 0 -192px; }
+.ui-icon-circle-minus { background-position: -16px -192px; }
+.ui-icon-circle-close { background-position: -32px -192px; }
+.ui-icon-circle-triangle-e { background-position: -48px -192px; }
+.ui-icon-circle-triangle-s { background-position: -64px -192px; }
+.ui-icon-circle-triangle-w { background-position: -80px -192px; }
+.ui-icon-circle-triangle-n { background-position: -96px -192px; }
+.ui-icon-circle-arrow-e { background-position: -112px -192px; }
+.ui-icon-circle-arrow-s { background-position: -128px -192px; }
+.ui-icon-circle-arrow-w { background-position: -144px -192px; }
+.ui-icon-circle-arrow-n { background-position: -160px -192px; }
+.ui-icon-circle-zoomin { background-position: -176px -192px; }
+.ui-icon-circle-zoomout { background-position: -192px -192px; }
+.ui-icon-circle-check { background-position: -208px -192px; }
+.ui-icon-circlesmall-plus { background-position: 0 -208px; }
+.ui-icon-circlesmall-minus { background-position: -16px -208px; }
+.ui-icon-circlesmall-close { background-position: -32px -208px; }
+.ui-icon-squaresmall-plus { background-position: -48px -208px; }
+.ui-icon-squaresmall-minus { background-position: -64px -208px; }
+.ui-icon-squaresmall-close { background-position: -80px -208px; }
+.ui-icon-grip-dotted-vertical { background-position: 0 -224px; }
+.ui-icon-grip-dotted-horizontal { background-position: -16px -224px; }
+.ui-icon-grip-solid-vertical { background-position: -32px -224px; }
+.ui-icon-grip-solid-horizontal { background-position: -48px -224px; }
+.ui-icon-gripsmall-diagonal-se { background-position: -64px -224px; }
+.ui-icon-grip-diagonal-se { background-position: -80px -224px; }
+
+
+/* Misc visuals
+----------------------------------*/
+
+/* Corner radius */
+.ui-corner-all,
+.ui-corner-top,
+.ui-corner-left,
+.ui-corner-tl {
+       border-top-left-radius: 4px;
+}
+.ui-corner-all,
+.ui-corner-top,
+.ui-corner-right,
+.ui-corner-tr {
+       border-top-right-radius: 4px;
+}
+.ui-corner-all,
+.ui-corner-bottom,
+.ui-corner-left,
+.ui-corner-bl {
+       border-bottom-left-radius: 4px;
+}
+.ui-corner-all,
+.ui-corner-bottom,
+.ui-corner-right,
+.ui-corner-br {
+       border-bottom-right-radius: 4px;
+}
+
+/* Overlays */
+.ui-widget-overlay {
+       background: #aaaaaa url(images/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x;
+       opacity: .3;
+       filter: Alpha(Opacity=30);
+}
+.ui-widget-shadow {
+       margin: -8px 0 0 -8px;
+       padding: 8px;
+       background: #aaaaaa url(images/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x;
+       opacity: .3;
+       filter: Alpha(Opacity=30);
+       border-radius: 8px;
+}
diff --git a/themes/default/css/jquery-ui-1.10.4.custom.min.css b/themes/default/css/jquery-ui-1.10.4.custom.min.css
new file mode 100644 (file)
index 0000000..4dba92a
--- /dev/null
@@ -0,0 +1,7 @@
+/*! jQuery UI - v1.10.4 - 2014-03-09
+* http://jqueryui.com
+* Includes: jquery.ui.core.css, jquery.ui.autocomplete.css, jquery.ui.menu.css, jquery.ui.theme.css
+* To view and modify this theme, visit http://jqueryui.com/themeroller/?ffDefault=Verdana%2CArial%2Csans-serif&fwDefault=normal&fsDefault=1.1em&cornerRadius=4px&bgColorHeader=cccccc&bgTextureHeader=highlight_soft&bgImgOpacityHeader=75&borderColorHeader=aaaaaa&fcHeader=222222&iconColorHeader=222222&bgColorContent=ffffff&bgTextureContent=flat&bgImgOpacityContent=75&borderColorContent=aaaaaa&fcContent=222222&iconColorContent=222222&bgColorDefault=e6e6e6&bgTextureDefault=glass&bgImgOpacityDefault=75&borderColorDefault=d3d3d3&fcDefault=555555&iconColorDefault=888888&bgColorHover=dadada&bgTextureHover=glass&bgImgOpacityHover=75&borderColorHover=999999&fcHover=212121&iconColorHover=454545&bgColorActive=ffffff&bgTextureActive=glass&bgImgOpacityActive=65&borderColorActive=aaaaaa&fcActive=212121&iconColorActive=454545&bgColorHighlight=fbf9ee&bgTextureHighlight=glass&bgImgOpacityHighlight=55&borderColorHighlight=fcefa1&fcHighlight=363636&iconColorHighlight=2e83ff&bgColorError=fef1ec&bgTextureError=glass&bgImgOpacityError=95&borderColorError=cd0a0a&fcError=cd0a0a&iconColorError=cd0a0a&bgColorOverlay=aaaaaa&bgTextureOverlay=flat&bgImgOpacityOverlay=0&opacityOverlay=30&bgColorShadow=aaaaaa&bgTextureShadow=flat&bgImgOpacityShadow=0&opacityShadow=30&thicknessShadow=8px&offsetTopShadow=-8px&offsetLeftShadow=-8px&cornerRadiusShadow=8px
+* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */
+
+.ui-helper-hidden{display:none}.ui-helper-hidden-accessible{border:0;clip:rect(0 0 0 0);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px}.ui-helper-reset{margin:0;padding:0;border:0;outline:0;line-height:1.3;text-decoration:none;font-size:100%;list-style:none}.ui-helper-clearfix:before,.ui-helper-clearfix:after{content:"";display:table;border-collapse:collapse}.ui-helper-clearfix:after{clear:both}.ui-helper-clearfix{min-height:0}.ui-helper-zfix{width:100%;height:100%;top:0;left:0;position:absolute;opacity:0;filter:Alpha(Opacity=0)}.ui-front{z-index:100}.ui-state-disabled{cursor:default!important}.ui-icon{display:block;text-indent:-99999px;overflow:hidden;background-repeat:no-repeat}.ui-widget-overlay{position:fixed;top:0;left:0;width:100%;height:100%}.ui-autocomplete{position:absolute;top:0;left:0;cursor:default}.ui-menu{list-style:none;padding:2px;margin:0;display:block;outline:none}.ui-menu .ui-menu{margin-top:-3px;position:absolute}.ui-menu .ui-menu-item{margin:0;padding:0;width:100%;list-style-image:url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)}.ui-menu .ui-menu-divider{margin:5px -2px 5px -2px;height:0;font-size:0;line-height:0;border-width:1px 0 0 0}.ui-menu .ui-menu-item a{text-decoration:none;display:block;padding:2px .4em;line-height:1.5;min-height:0;font-weight:normal}.ui-menu .ui-menu-item a.ui-state-focus,.ui-menu .ui-menu-item a.ui-state-active{font-weight:normal;margin:-1px}.ui-menu .ui-state-disabled{font-weight:normal;margin:.4em 0 .2em;line-height:1.5}.ui-menu .ui-state-disabled a{cursor:default}.ui-menu-icons{position:relative}.ui-menu-icons .ui-menu-item a{position:relative;padding-left:2em}.ui-menu .ui-icon{position:absolute;top:.2em;left:.2em}.ui-menu .ui-menu-icon{position:static;float:right}.ui-widget{font-family:Verdana,Arial,sans-serif;font-size:1.1em}.ui-widget .ui-widget{font-size:1em}.ui-widget input,.ui-widget select,.ui-widget textarea,.ui-widget button{font-family:Verdana,Arial,sans-serif;font-size:1em}.ui-widget-content{border:1px solid #aaa;background:#fff url(images/ui-bg_flat_75_ffffff_40x100.png) 50% 50% repeat-x;color:#222}.ui-widget-content a{color:#222}.ui-widget-header{border:1px solid #aaa;background:#ccc url(images/ui-bg_highlight-soft_75_cccccc_1x100.png) 50% 50% repeat-x;color:#222;font-weight:bold}.ui-widget-header a{color:#222}.ui-state-default,.ui-widget-content .ui-state-default,.ui-widget-header .ui-state-default{border:1px solid #d3d3d3;background:#e6e6e6 url(images/ui-bg_glass_75_e6e6e6_1x400.png) 50% 50% repeat-x;font-weight:normal;color:#555}.ui-state-default a,.ui-state-default a:link,.ui-state-default a:visited{color:#555;text-decoration:none}.ui-state-hover,.ui-widget-content .ui-state-hover,.ui-widget-header .ui-state-hover,.ui-state-focus,.ui-widget-content .ui-state-focus,.ui-widget-header .ui-state-focus{border:1px solid #999;background:#dadada url(images/ui-bg_glass_75_dadada_1x400.png) 50% 50% repeat-x;font-weight:normal;color:#212121}.ui-state-hover a,.ui-state-hover a:hover,.ui-state-hover a:link,.ui-state-hover a:visited,.ui-state-focus a,.ui-state-focus a:hover,.ui-state-focus a:link,.ui-state-focus a:visited{color:#212121;text-decoration:none}.ui-state-active,.ui-widget-content .ui-state-active,.ui-widget-header .ui-state-active{border:1px solid #aaa;background:#fff url(images/ui-bg_glass_65_ffffff_1x400.png) 50% 50% repeat-x;font-weight:normal;color:#212121}.ui-state-active a,.ui-state-active a:link,.ui-state-active a:visited{color:#212121;text-decoration:none}.ui-state-highlight,.ui-widget-content .ui-state-highlight,.ui-widget-header .ui-state-highlight{border:1px solid #fcefa1;background:#fbf9ee url(images/ui-bg_glass_55_fbf9ee_1x400.png) 50% 50% repeat-x;color:#363636}.ui-state-highlight a,.ui-widget-content .ui-state-highlight a,.ui-widget-header .ui-state-highlight a{color:#363636}.ui-state-error,.ui-widget-content .ui-state-error,.ui-widget-header .ui-state-error{border:1px solid #cd0a0a;background:#fef1ec url(images/ui-bg_glass_95_fef1ec_1x400.png) 50% 50% repeat-x;color:#cd0a0a}.ui-state-error a,.ui-widget-content .ui-state-error a,.ui-widget-header .ui-state-error a{color:#cd0a0a}.ui-state-error-text,.ui-widget-content .ui-state-error-text,.ui-widget-header .ui-state-error-text{color:#cd0a0a}.ui-priority-primary,.ui-widget-content .ui-priority-primary,.ui-widget-header .ui-priority-primary{font-weight:bold}.ui-priority-secondary,.ui-widget-content .ui-priority-secondary,.ui-widget-header .ui-priority-secondary{opacity:.7;filter:Alpha(Opacity=70);font-weight:normal}.ui-state-disabled,.ui-widget-content .ui-state-disabled,.ui-widget-header .ui-state-disabled{opacity:.35;filter:Alpha(Opacity=35);background-image:none}.ui-state-disabled .ui-icon{filter:Alpha(Opacity=35)}.ui-icon{width:16px;height:16px}.ui-icon,.ui-widget-content .ui-icon{background-image:url(images/ui-icons_222222_256x240.png)}.ui-widget-header .ui-icon{background-image:url(images/ui-icons_222222_256x240.png)}.ui-state-default .ui-icon{background-image:url(images/ui-icons_888888_256x240.png)}.ui-state-hover .ui-icon,.ui-state-focus .ui-icon{background-image:url(images/ui-icons_454545_256x240.png)}.ui-state-active .ui-icon{background-image:url(images/ui-icons_454545_256x240.png)}.ui-state-highlight .ui-icon{background-image:url(images/ui-icons_2e83ff_256x240.png)}.ui-state-error .ui-icon,.ui-state-error-text .ui-icon{background-image:url(images/ui-icons_cd0a0a_256x240.png)}.ui-icon-blank{background-position:16px 16px}.ui-icon-carat-1-n{background-position:0 0}.ui-icon-carat-1-ne{background-position:-16px 0}.ui-icon-carat-1-e{background-position:-32px 0}.ui-icon-carat-1-se{background-position:-48px 0}.ui-icon-carat-1-s{background-position:-64px 0}.ui-icon-carat-1-sw{background-position:-80px 0}.ui-icon-carat-1-w{background-position:-96px 0}.ui-icon-carat-1-nw{background-position:-112px 0}.ui-icon-carat-2-n-s{background-position:-128px 0}.ui-icon-carat-2-e-w{background-position:-144px 0}.ui-icon-triangle-1-n{background-position:0 -16px}.ui-icon-triangle-1-ne{background-position:-16px -16px}.ui-icon-triangle-1-e{background-position:-32px -16px}.ui-icon-triangle-1-se{background-position:-48px -16px}.ui-icon-triangle-1-s{background-position:-64px -16px}.ui-icon-triangle-1-sw{background-position:-80px -16px}.ui-icon-triangle-1-w{background-position:-96px -16px}.ui-icon-triangle-1-nw{background-position:-112px -16px}.ui-icon-triangle-2-n-s{background-position:-128px -16px}.ui-icon-triangle-2-e-w{background-position:-144px -16px}.ui-icon-arrow-1-n{background-position:0 -32px}.ui-icon-arrow-1-ne{background-position:-16px -32px}.ui-icon-arrow-1-e{background-position:-32px -32px}.ui-icon-arrow-1-se{background-position:-48px -32px}.ui-icon-arrow-1-s{background-position:-64px -32px}.ui-icon-arrow-1-sw{background-position:-80px -32px}.ui-icon-arrow-1-w{background-position:-96px -32px}.ui-icon-arrow-1-nw{background-position:-112px -32px}.ui-icon-arrow-2-n-s{background-position:-128px -32px}.ui-icon-arrow-2-ne-sw{background-position:-144px -32px}.ui-icon-arrow-2-e-w{background-position:-160px -32px}.ui-icon-arrow-2-se-nw{background-position:-176px -32px}.ui-icon-arrowstop-1-n{background-position:-192px -32px}.ui-icon-arrowstop-1-e{background-position:-208px -32px}.ui-icon-arrowstop-1-s{background-position:-224px -32px}.ui-icon-arrowstop-1-w{background-position:-240px -32px}.ui-icon-arrowthick-1-n{background-position:0 -48px}.ui-icon-arrowthick-1-ne{background-position:-16px -48px}.ui-icon-arrowthick-1-e{background-position:-32px -48px}.ui-icon-arrowthick-1-se{background-position:-48px -48px}.ui-icon-arrowthick-1-s{background-position:-64px -48px}.ui-icon-arrowthick-1-sw{background-position:-80px -48px}.ui-icon-arrowthick-1-w{background-position:-96px -48px}.ui-icon-arrowthick-1-nw{background-position:-112px -48px}.ui-icon-arrowthick-2-n-s{background-position:-128px -48px}.ui-icon-arrowthick-2-ne-sw{background-position:-144px -48px}.ui-icon-arrowthick-2-e-w{background-position:-160px -48px}.ui-icon-arrowthick-2-se-nw{background-position:-176px -48px}.ui-icon-arrowthickstop-1-n{background-position:-192px -48px}.ui-icon-arrowthickstop-1-e{background-position:-208px -48px}.ui-icon-arrowthickstop-1-s{background-position:-224px -48px}.ui-icon-arrowthickstop-1-w{background-position:-240px -48px}.ui-icon-arrowreturnthick-1-w{background-position:0 -64px}.ui-icon-arrowreturnthick-1-n{background-position:-16px -64px}.ui-icon-arrowreturnthick-1-e{background-position:-32px -64px}.ui-icon-arrowreturnthick-1-s{background-position:-48px -64px}.ui-icon-arrowreturn-1-w{background-position:-64px -64px}.ui-icon-arrowreturn-1-n{background-position:-80px -64px}.ui-icon-arrowreturn-1-e{background-position:-96px -64px}.ui-icon-arrowreturn-1-s{background-position:-112px -64px}.ui-icon-arrowrefresh-1-w{background-position:-128px -64px}.ui-icon-arrowrefresh-1-n{background-position:-144px -64px}.ui-icon-arrowrefresh-1-e{background-position:-160px -64px}.ui-icon-arrowrefresh-1-s{background-position:-176px -64px}.ui-icon-arrow-4{background-position:0 -80px}.ui-icon-arrow-4-diag{background-position:-16px -80px}.ui-icon-extlink{background-position:-32px -80px}.ui-icon-newwin{background-position:-48px -80px}.ui-icon-refresh{background-position:-64px -80px}.ui-icon-shuffle{background-position:-80px -80px}.ui-icon-transfer-e-w{background-position:-96px -80px}.ui-icon-transferthick-e-w{background-position:-112px -80px}.ui-icon-folder-collapsed{background-position:0 -96px}.ui-icon-folder-open{background-position:-16px -96px}.ui-icon-document{background-position:-32px -96px}.ui-icon-document-b{background-position:-48px -96px}.ui-icon-note{background-position:-64px -96px}.ui-icon-mail-closed{background-position:-80px -96px}.ui-icon-mail-open{background-position:-96px -96px}.ui-icon-suitcase{background-position:-112px -96px}.ui-icon-comment{background-position:-128px -96px}.ui-icon-person{background-position:-144px -96px}.ui-icon-print{background-position:-160px -96px}.ui-icon-trash{background-position:-176px -96px}.ui-icon-locked{background-position:-192px -96px}.ui-icon-unlocked{background-position:-208px -96px}.ui-icon-bookmark{background-position:-224px -96px}.ui-icon-tag{background-position:-240px -96px}.ui-icon-home{background-position:0 -112px}.ui-icon-flag{background-position:-16px -112px}.ui-icon-calendar{background-position:-32px -112px}.ui-icon-cart{background-position:-48px -112px}.ui-icon-pencil{background-position:-64px -112px}.ui-icon-clock{background-position:-80px -112px}.ui-icon-disk{background-position:-96px -112px}.ui-icon-calculator{background-position:-112px -112px}.ui-icon-zoomin{background-position:-128px -112px}.ui-icon-zoomout{background-position:-144px -112px}.ui-icon-search{background-position:-160px -112px}.ui-icon-wrench{background-position:-176px -112px}.ui-icon-gear{background-position:-192px -112px}.ui-icon-heart{background-position:-208px -112px}.ui-icon-star{background-position:-224px -112px}.ui-icon-link{background-position:-240px -112px}.ui-icon-cancel{background-position:0 -128px}.ui-icon-plus{background-position:-16px -128px}.ui-icon-plusthick{background-position:-32px -128px}.ui-icon-minus{background-position:-48px -128px}.ui-icon-minusthick{background-position:-64px -128px}.ui-icon-close{background-position:-80px -128px}.ui-icon-closethick{background-position:-96px -128px}.ui-icon-key{background-position:-112px -128px}.ui-icon-lightbulb{background-position:-128px -128px}.ui-icon-scissors{background-position:-144px -128px}.ui-icon-clipboard{background-position:-160px -128px}.ui-icon-copy{background-position:-176px -128px}.ui-icon-contact{background-position:-192px -128px}.ui-icon-image{background-position:-208px -128px}.ui-icon-video{background-position:-224px -128px}.ui-icon-script{background-position:-240px -128px}.ui-icon-alert{background-position:0 -144px}.ui-icon-info{background-position:-16px -144px}.ui-icon-notice{background-position:-32px -144px}.ui-icon-help{background-position:-48px -144px}.ui-icon-check{background-position:-64px -144px}.ui-icon-bullet{background-position:-80px -144px}.ui-icon-radio-on{background-position:-96px -144px}.ui-icon-radio-off{background-position:-112px -144px}.ui-icon-pin-w{background-position:-128px -144px}.ui-icon-pin-s{background-position:-144px -144px}.ui-icon-play{background-position:0 -160px}.ui-icon-pause{background-position:-16px -160px}.ui-icon-seek-next{background-position:-32px -160px}.ui-icon-seek-prev{background-position:-48px -160px}.ui-icon-seek-end{background-position:-64px -160px}.ui-icon-seek-start{background-position:-80px -160px}.ui-icon-seek-first{background-position:-80px -160px}.ui-icon-stop{background-position:-96px -160px}.ui-icon-eject{background-position:-112px -160px}.ui-icon-volume-off{background-position:-128px -160px}.ui-icon-volume-on{background-position:-144px -160px}.ui-icon-power{background-position:0 -176px}.ui-icon-signal-diag{background-position:-16px -176px}.ui-icon-signal{background-position:-32px -176px}.ui-icon-battery-0{background-position:-48px -176px}.ui-icon-battery-1{background-position:-64px -176px}.ui-icon-battery-2{background-position:-80px -176px}.ui-icon-battery-3{background-position:-96px -176px}.ui-icon-circle-plus{background-position:0 -192px}.ui-icon-circle-minus{background-position:-16px -192px}.ui-icon-circle-close{background-position:-32px -192px}.ui-icon-circle-triangle-e{background-position:-48px -192px}.ui-icon-circle-triangle-s{background-position:-64px -192px}.ui-icon-circle-triangle-w{background-position:-80px -192px}.ui-icon-circle-triangle-n{background-position:-96px -192px}.ui-icon-circle-arrow-e{background-position:-112px -192px}.ui-icon-circle-arrow-s{background-position:-128px -192px}.ui-icon-circle-arrow-w{background-position:-144px -192px}.ui-icon-circle-arrow-n{background-position:-160px -192px}.ui-icon-circle-zoomin{background-position:-176px -192px}.ui-icon-circle-zoomout{background-position:-192px -192px}.ui-icon-circle-check{background-position:-208px -192px}.ui-icon-circlesmall-plus{background-position:0 -208px}.ui-icon-circlesmall-minus{background-position:-16px -208px}.ui-icon-circlesmall-close{background-position:-32px -208px}.ui-icon-squaresmall-plus{background-position:-48px -208px}.ui-icon-squaresmall-minus{background-position:-64px -208px}.ui-icon-squaresmall-close{background-position:-80px -208px}.ui-icon-grip-dotted-vertical{background-position:0 -224px}.ui-icon-grip-dotted-horizontal{background-position:-16px -224px}.ui-icon-grip-solid-vertical{background-position:-32px -224px}.ui-icon-grip-solid-horizontal{background-position:-48px -224px}.ui-icon-gripsmall-diagonal-se{background-position:-64px -224px}.ui-icon-grip-diagonal-se{background-position:-80px -224px}.ui-corner-all,.ui-corner-top,.ui-corner-left,.ui-corner-tl{border-top-left-radius:4px}.ui-corner-all,.ui-corner-top,.ui-corner-right,.ui-corner-tr{border-top-right-radius:4px}.ui-corner-all,.ui-corner-bottom,.ui-corner-left,.ui-corner-bl{border-bottom-left-radius:4px}.ui-corner-all,.ui-corner-bottom,.ui-corner-right,.ui-corner-br{border-bottom-right-radius:4px}.ui-widget-overlay{background:#aaa url(images/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x;opacity:.3;filter:Alpha(Opacity=30)}.ui-widget-shadow{margin:-8px 0 0 -8px;padding:8px;background:#aaa url(images/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x;opacity:.3;filter:Alpha(Opacity=30);border-radius:8px}
\ No newline at end of file
old mode 100644 (file)
new mode 100755 (executable)
index 9dc7c0b..889a9f5
@@ -52,4 +52,8 @@ a.link span {
 
 a.bad-display span {
     background-image: url('../img/default/bad-display.png');
+}
+
+a.print span {
+               background-image: url('../img/default/print.png');
 }
\ No newline at end of file
old mode 100644 (file)
new mode 100755 (executable)
index 2867590..e58ef81
@@ -331,7 +331,8 @@ a.email span,
 a.delete span,
 a.link span,
 a.bad-display span,
-a.reading-time span {
+a.reading-time span,
+a.print span {
     background-repeat: no-repeat;
 }
 
@@ -347,3 +348,85 @@ a.reading-time span {
     margin-left: -30px;
 }
 
+.two-column {
+  display: block;
+  width: 50%;
+  paddig-right: 20px;
+  float: left;
+  vertical-align: top;
+}
+
+
+/* ==========================================================================
+       "save a link" popup div related styles
+       ========================================================================== */
+
+#bagit-form {
+  display: none;
+  padding-left: 30px;
+  width: 450px;
+
+}
+
+a#bagit-form-close {
+  color: #FFF;
+  display: inline-block;
+  float: right;
+  background: url("../img/messages/close.png") no-repeat scroll 0 0 rgba(0, 0, 0, 0);
+  height: 16px;
+  margin: -14px -8px 0 0;
+  width: 16px;
+  text-decoration: none;
+}
+
+
+.add-to-wallabag-link-after {
+  background-color: #000;
+  color: #fff;
+  padding: 0 4px 1px 3px;
+  font-weight: bold; 
+  font-size: 0.7em; 
+  border-radius: 4px;
+}
+.add-to-wallabag-link-after:hover, .add-to-wallabag-link-after:active {
+  color: #fff;
+}
+.add-to-wallabag-link-after:visited {
+  color: #999;
+}
+a.add-to-wallabag-link-after {
+    visibility: hidden;
+    position: absolute;
+    opacity: 0;
+    transition-duration: 2s;
+    transition-timing-function: ease-out;
+}
+#article article a:hover + a.add-to-wallabag-link-after, a.add-to-wallabag-link-after:hover {
+    opacity: 1;
+    visibility: visible;
+    transition-duration: .3s;
+    transition-timing-function: ease-in;
+}
+a.add-to-wallabag-link-after:after {
+     content: "w";
+}
+
+
+#add-link-result {
+  display: inline;
+  padding-left: 10px;
+}
+
+.opacity03 {
+  /*opacity: 0.3;*/
+}
+
+#readLeftPercent {
+               display: inline-block;
+    /* Show textual content */
+    overflow: visible;
+    text-align: left;
+    text-indent: 0;
+               color: black;
+               width: 50px;
+}
\ No newline at end of file
old mode 100644 (file)
new mode 100755 (executable)
index 83f04aa..bd498d2
@@ -5,6 +5,10 @@
 {% endblock %}
 {% block content %}
 
+<script src="{{ poche_url }}themes/default/js/jquery-ui-1.10.4.custom.min.js"></script>
+<script src="{{ poche_url }}themes/default/js/autoCompleteTags.js"></script>
+<link rel="stylesheet" href="{{ poche_url }}themes/default/css/jquery-ui-1.10.4.custom.min.css" media="all">
+
 <div id="article">
   <header class="mbm">
       <h1>{{ entry.title|raw }}</h1>
@@ -17,13 +21,15 @@ no tags
 <ul>
 {% for tag in tags %}<li>{{ tag.value }} <a href="./?action=remove_tag&amp;tag_id={{ tag.id }}&amp;id={{ entry_id }}">✘</a></li>{% endfor %}
 </ul>
-<form method="post" action="./?action=add_tag">
+<form method="post" action="./?action=add_tag" id="editTags">
     <input type="hidden" name="entry_id" value="{{ entry_id }}" />
     <label for="value">Add tags: </label>
     <input type="text" placeholder="interview, editorial, video" id="value" name="value" required="required" />
     <input type="submit" value="Tag" />
-    <p>{% trans "You can enter multiple tags, separated by commas." %}</p>
+    <p>{% trans "Start typing for auto complete." %}<br>
+    {% trans "You can enter multiple tags, separated by commas." %}</p>
 
 </form>
+<br>
 <a href="./?view=view&id={{ entry_id }}">&laquo; {% trans "return to article" %}</a>
 {% endblock %}
old mode 100644 (file)
new mode 100755 (executable)
index 165fecc..e6c781f
 {% include '_menu.twig' %}
 {% endblock %}
 {% block precontent %}
-            {% if entries|length > 1 %}
-            <ul id="sort">
-                <li><a href="./?sort=ia&amp;view={{ view }}&amp;id={{ id }}"><img src="{{ poche_url }}/themes/{{ theme }}/img/{{ theme }}/top.png" alt="{% trans "by date asc" %}" title="{% trans "by date asc" %}" /></a> {% trans "by date" %} <a href="./?sort=id&amp;view={{ view }}&amp;id={{ id }}"><img src="{{ poche_url }}/themes/{{ theme }}/img/{{ theme }}/down.png" alt="{% trans "by date desc" %}" title="{% trans "by date desc" %}" /></a></li>
-                <li><a href="./?sort=ta&amp;view={{ view }}&amp;id={{ id }}"><img src="{{ poche_url }}/themes/{{ theme }}/img/{{ theme }}/top.png" alt="{% trans "by title asc" %}" title="{% trans "by title asc" %}" /></a> {% trans "by title" %} <a href="./?sort=td&amp;view={{ view }}&amp;id={{ id }}"><img src="{{ poche_url }}/themes/{{ theme }}/img/{{ theme }}/down.png" alt="{% trans "by title desc" %}" title="{% trans "by title desc" %}" /></a></li>
-            </ul>
-            {% endif %}
+
+{% include '_sorting.twig' %}
 {% endblock %}
 {% block content %}
+
+                                               {% if includeImport %}
+                                                               {% include '_import.twig' %}
+                                               {% endif %}
+
             {% if tag %}
                 <h3>{% trans "Tag" %}: <b>{{ tag.value }}</b></h3>
             {% endif %}
                 {% block pager %}
                     {% if nb_results > 1 %}
                 <div class="results">
-                    <div class="nb-results">{{ nb_results }} {% trans "results" %}</div>
+                    <div class="nb-results">{{ nb_results }} {% trans "results" %}{% if search_term is defined %}{% trans " found for « " %} {{ search_term }} »{% endif %}</div>
                         {{ page_links | raw }}
                 </div>
+                    {% elseif nb_results == 1 %}
+                        {% if search_term is defined %}
+                     <div class="results">
+                        <div class="nb-results">{% trans "Only one result found for " %} « {{ search_term }} »</div>
+                     </div>
+                        {% endif %}
                     {% endif %}
                 {% endblock %}
                 {% for entry in entries %}
                 <p>{{ entry.content|striptags|slice(0, 300) }}...</p>
             </div>
                 {% endfor %}
-            {% endif %}
+
             {{ block('pager') }}
+            
             {% if view == 'home' %}{% if nb_results > 1 %}<a title="{% trans "mark all the entries as read" %}"  href="./?action=archive_all">{% trans "mark all the entries as read" %}</a>{% endif %}{% endif %}
+            
+            {% if tag %}<a title="{% trans "Download the articles from this tag in an epub" %}" href="./?epub&amp;method=tag&amp;tag={{ tag.value }}">{% trans "Download the articles from this tag in an epub" %}</a>
+            {% elseif search_term is defined %}<a title="{% trans "Download the articles from this search in an epub" %}" href="./?epub&amp;method=search&amp;search={{ search_term }}">{% trans "Download the articles from this search in an epub" %}</a>
+            {% else %}<a title="{% trans "Download the articles from this category in an epub" %}" href="./?epub&amp;method=category&amp;category={{ view }}">{% trans "Download the articles from this category in an epub" %}</a>{% endif %}
+            
+            {% endif %}
 {% endblock %}
diff --git a/themes/default/img/default/print.png b/themes/default/img/default/print.png
new file mode 100755 (executable)
index 0000000..83d6445
Binary files /dev/null and b/themes/default/img/default/print.png differ
diff --git a/themes/default/js/autoCompleteTags.js b/themes/default/js/autoCompleteTags.js
new file mode 100755 (executable)
index 0000000..90bc982
--- /dev/null
@@ -0,0 +1,47 @@
+jQuery(function($) {
+
+  function split( val ) {
+    return val.split( /,\s*/ );
+  }
+  function extractLast( term ) {
+    return split( term ).pop();
+  }
+
+
+  $("#value").bind("keydown", function(event) {
+    if (event.keyCode === $.ui.keyCode.TAB && $(this).data("ui-autocomplete").menu.active) {
+      event.preventDefault();
+    }
+  }).autocomplete({
+    source : function(request, response) {
+      $.getJSON("./?view=tags", {
+        term : extractLast(request.term),
+        //id: $(':hidden#entry_id').val()
+      }, response);
+    },
+    search : function() {
+      // custom minLength
+      var term = extractLast(this.value);
+      if (term.length < 1) {
+        return false;
+      }
+    },
+    focus : function() {
+      // prevent value inserted on focus
+      return false;
+    },
+    select : function(event, ui) {
+      var terms = split(this.value);
+      // remove the current input
+      terms.pop();
+      // add the selected item
+      terms.push(ui.item.value);
+      // add placeholder to get the comma-and-space at the end
+      terms.push("");
+      this.value = terms.join(", ");
+      return false;
+    }
+  });
+
+
+});
diff --git a/themes/default/js/jquery-ui-1.10.4.custom.js b/themes/default/js/jquery-ui-1.10.4.custom.js
new file mode 100644 (file)
index 0000000..6f599fc
--- /dev/null
@@ -0,0 +1,2519 @@
+/*! jQuery UI - v1.10.4 - 2014-03-08
+* http://jqueryui.com
+* Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.position.js, jquery.ui.autocomplete.js, jquery.ui.menu.js
+* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */
+
+(function( $, undefined ) {
+
+var uuid = 0,
+       runiqueId = /^ui-id-\d+$/;
+
+// $.ui might exist from components with no dependencies, e.g., $.ui.position
+$.ui = $.ui || {};
+
+$.extend( $.ui, {
+       version: "1.10.4",
+
+       keyCode: {
+               BACKSPACE: 8,
+               COMMA: 188,
+               DELETE: 46,
+               DOWN: 40,
+               END: 35,
+               ENTER: 13,
+               ESCAPE: 27,
+               HOME: 36,
+               LEFT: 37,
+               NUMPAD_ADD: 107,
+               NUMPAD_DECIMAL: 110,
+               NUMPAD_DIVIDE: 111,
+               NUMPAD_ENTER: 108,
+               NUMPAD_MULTIPLY: 106,
+               NUMPAD_SUBTRACT: 109,
+               PAGE_DOWN: 34,
+               PAGE_UP: 33,
+               PERIOD: 190,
+               RIGHT: 39,
+               SPACE: 32,
+               TAB: 9,
+               UP: 38
+       }
+});
+
+// plugins
+$.fn.extend({
+       focus: (function( orig ) {
+               return function( delay, fn ) {
+                       return typeof delay === "number" ?
+                               this.each(function() {
+                                       var elem = this;
+                                       setTimeout(function() {
+                                               $( elem ).focus();
+                                               if ( fn ) {
+                                                       fn.call( elem );
+                                               }
+                                       }, delay );
+                               }) :
+                               orig.apply( this, arguments );
+               };
+       })( $.fn.focus ),
+
+       scrollParent: function() {
+               var scrollParent;
+               if (($.ui.ie && (/(static|relative)/).test(this.css("position"))) || (/absolute/).test(this.css("position"))) {
+                       scrollParent = this.parents().filter(function() {
+                               return (/(relative|absolute|fixed)/).test($.css(this,"position")) && (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x"));
+                       }).eq(0);
+               } else {
+                       scrollParent = this.parents().filter(function() {
+                               return (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x"));
+                       }).eq(0);
+               }
+
+               return (/fixed/).test(this.css("position")) || !scrollParent.length ? $(document) : scrollParent;
+       },
+
+       zIndex: function( zIndex ) {
+               if ( zIndex !== undefined ) {
+                       return this.css( "zIndex", zIndex );
+               }
+
+               if ( this.length ) {
+                       var elem = $( this[ 0 ] ), position, value;
+                       while ( elem.length && elem[ 0 ] !== document ) {
+                               // Ignore z-index if position is set to a value where z-index is ignored by the browser
+                               // This makes behavior of this function consistent across browsers
+                               // WebKit always returns auto if the element is positioned
+                               position = elem.css( "position" );
+                               if ( position === "absolute" || position === "relative" || position === "fixed" ) {
+                                       // IE returns 0 when zIndex is not specified
+                                       // other browsers return a string
+                                       // we ignore the case of nested elements with an explicit value of 0
+                                       // <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
+                                       value = parseInt( elem.css( "zIndex" ), 10 );
+                                       if ( !isNaN( value ) && value !== 0 ) {
+                                               return value;
+                                       }
+                               }
+                               elem = elem.parent();
+                       }
+               }
+
+               return 0;
+       },
+
+       uniqueId: function() {
+               return this.each(function() {
+                       if ( !this.id ) {
+                               this.id = "ui-id-" + (++uuid);
+                       }
+               });
+       },
+
+       removeUniqueId: function() {
+               return this.each(function() {
+                       if ( runiqueId.test( this.id ) ) {
+                               $( this ).removeAttr( "id" );
+                       }
+               });
+       }
+});
+
+// selectors
+function focusable( element, isTabIndexNotNaN ) {
+       var map, mapName, img,
+               nodeName = element.nodeName.toLowerCase();
+       if ( "area" === nodeName ) {
+               map = element.parentNode;
+               mapName = map.name;
+               if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
+                       return false;
+               }
+               img = $( "img[usemap=#" + mapName + "]" )[0];
+               return !!img && visible( img );
+       }
+       return ( /input|select|textarea|button|object/.test( nodeName ) ?
+               !element.disabled :
+               "a" === nodeName ?
+                       element.href || isTabIndexNotNaN :
+                       isTabIndexNotNaN) &&
+               // the element and all of its ancestors must be visible
+               visible( element );
+}
+
+function visible( element ) {
+       return $.expr.filters.visible( element ) &&
+               !$( element ).parents().addBack().filter(function() {
+                       return $.css( this, "visibility" ) === "hidden";
+               }).length;
+}
+
+$.extend( $.expr[ ":" ], {
+       data: $.expr.createPseudo ?
+               $.expr.createPseudo(function( dataName ) {
+                       return function( elem ) {
+                               return !!$.data( elem, dataName );
+                       };
+               }) :
+               // support: jQuery <1.8
+               function( elem, i, match ) {
+                       return !!$.data( elem, match[ 3 ] );
+               },
+
+       focusable: function( element ) {
+               return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) );
+       },
+
+       tabbable: function( element ) {
+               var tabIndex = $.attr( element, "tabindex" ),
+                       isTabIndexNaN = isNaN( tabIndex );
+               return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN );
+       }
+});
+
+// support: jQuery <1.8
+if ( !$( "<a>" ).outerWidth( 1 ).jquery ) {
+       $.each( [ "Width", "Height" ], function( i, name ) {
+               var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
+                       type = name.toLowerCase(),
+                       orig = {
+                               innerWidth: $.fn.innerWidth,
+                               innerHeight: $.fn.innerHeight,
+                               outerWidth: $.fn.outerWidth,
+                               outerHeight: $.fn.outerHeight
+                       };
+
+               function reduce( elem, size, border, margin ) {
+                       $.each( side, function() {
+                               size -= parseFloat( $.css( elem, "padding" + this ) ) || 0;
+                               if ( border ) {
+                                       size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0;
+                               }
+                               if ( margin ) {
+                                       size -= parseFloat( $.css( elem, "margin" + this ) ) || 0;
+                               }
+                       });
+                       return size;
+               }
+
+               $.fn[ "inner" + name ] = function( size ) {
+                       if ( size === undefined ) {
+                               return orig[ "inner" + name ].call( this );
+                       }
+
+                       return this.each(function() {
+                               $( this ).css( type, reduce( this, size ) + "px" );
+                       });
+               };
+
+               $.fn[ "outer" + name] = function( size, margin ) {
+                       if ( typeof size !== "number" ) {
+                               return orig[ "outer" + name ].call( this, size );
+                       }
+
+                       return this.each(function() {
+                               $( this).css( type, reduce( this, size, true, margin ) + "px" );
+                       });
+               };
+       });
+}
+
+// support: jQuery <1.8
+if ( !$.fn.addBack ) {
+       $.fn.addBack = function( selector ) {
+               return this.add( selector == null ?
+                       this.prevObject : this.prevObject.filter( selector )
+               );
+       };
+}
+
+// support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413)
+if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) {
+       $.fn.removeData = (function( removeData ) {
+               return function( key ) {
+                       if ( arguments.length ) {
+                               return removeData.call( this, $.camelCase( key ) );
+                       } else {
+                               return removeData.call( this );
+                       }
+               };
+       })( $.fn.removeData );
+}
+
+
+
+
+
+// deprecated
+$.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() );
+
+$.support.selectstart = "onselectstart" in document.createElement( "div" );
+$.fn.extend({
+       disableSelection: function() {
+               return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) +
+                       ".ui-disableSelection", function( event ) {
+                               event.preventDefault();
+                       });
+       },
+
+       enableSelection: function() {
+               return this.unbind( ".ui-disableSelection" );
+       }
+});
+
+$.extend( $.ui, {
+       // $.ui.plugin is deprecated. Use $.widget() extensions instead.
+       plugin: {
+               add: function( module, option, set ) {
+                       var i,
+                               proto = $.ui[ module ].prototype;
+                       for ( i in set ) {
+                               proto.plugins[ i ] = proto.plugins[ i ] || [];
+                               proto.plugins[ i ].push( [ option, set[ i ] ] );
+                       }
+               },
+               call: function( instance, name, args ) {
+                       var i,
+                               set = instance.plugins[ name ];
+                       if ( !set || !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) {
+                               return;
+                       }
+
+                       for ( i = 0; i < set.length; i++ ) {
+                               if ( instance.options[ set[ i ][ 0 ] ] ) {
+                                       set[ i ][ 1 ].apply( instance.element, args );
+                               }
+                       }
+               }
+       },
+
+       // only used by resizable
+       hasScroll: function( el, a ) {
+
+               //If overflow is hidden, the element might have extra content, but the user wants to hide it
+               if ( $( el ).css( "overflow" ) === "hidden") {
+                       return false;
+               }
+
+               var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop",
+                       has = false;
+
+               if ( el[ scroll ] > 0 ) {
+                       return true;
+               }
+
+               // TODO: determine which cases actually cause this to happen
+               // if the element doesn't have the scroll set, see if it's possible to
+               // set the scroll
+               el[ scroll ] = 1;
+               has = ( el[ scroll ] > 0 );
+               el[ scroll ] = 0;
+               return has;
+       }
+});
+
+})( jQuery );
+(function( $, undefined ) {
+
+var uuid = 0,
+       slice = Array.prototype.slice,
+       _cleanData = $.cleanData;
+$.cleanData = function( elems ) {
+       for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
+               try {
+                       $( elem ).triggerHandler( "remove" );
+               // http://bugs.jquery.com/ticket/8235
+               } catch( e ) {}
+       }
+       _cleanData( elems );
+};
+
+$.widget = function( name, base, prototype ) {
+       var fullName, existingConstructor, constructor, basePrototype,
+               // proxiedPrototype allows the provided prototype to remain unmodified
+               // so that it can be used as a mixin for multiple widgets (#8876)
+               proxiedPrototype = {},
+               namespace = name.split( "." )[ 0 ];
+
+       name = name.split( "." )[ 1 ];
+       fullName = namespace + "-" + name;
+
+       if ( !prototype ) {
+               prototype = base;
+               base = $.Widget;
+       }
+
+       // create selector for plugin
+       $.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
+               return !!$.data( elem, fullName );
+       };
+
+       $[ namespace ] = $[ namespace ] || {};
+       existingConstructor = $[ namespace ][ name ];
+       constructor = $[ namespace ][ name ] = function( options, element ) {
+               // allow instantiation without "new" keyword
+               if ( !this._createWidget ) {
+                       return new constructor( options, element );
+               }
+
+               // allow instantiation without initializing for simple inheritance
+               // must use "new" keyword (the code above always passes args)
+               if ( arguments.length ) {
+                       this._createWidget( options, element );
+               }
+       };
+       // extend with the existing constructor to carry over any static properties
+       $.extend( constructor, existingConstructor, {
+               version: prototype.version,
+               // copy the object used to create the prototype in case we need to
+               // redefine the widget later
+               _proto: $.extend( {}, prototype ),
+               // track widgets that inherit from this widget in case this widget is
+               // redefined after a widget inherits from it
+               _childConstructors: []
+       });
+
+       basePrototype = new base();
+       // we need to make the options hash a property directly on the new instance
+       // otherwise we'll modify the options hash on the prototype that we're
+       // inheriting from
+       basePrototype.options = $.widget.extend( {}, basePrototype.options );
+       $.each( prototype, function( prop, value ) {
+               if ( !$.isFunction( value ) ) {
+                       proxiedPrototype[ prop ] = value;
+                       return;
+               }
+               proxiedPrototype[ prop ] = (function() {
+                       var _super = function() {
+                                       return base.prototype[ prop ].apply( this, arguments );
+                               },
+                               _superApply = function( args ) {
+                                       return base.prototype[ prop ].apply( this, args );
+                               };
+                       return function() {
+                               var __super = this._super,
+                                       __superApply = this._superApply,
+                                       returnValue;
+
+                               this._super = _super;
+                               this._superApply = _superApply;
+
+                               returnValue = value.apply( this, arguments );
+
+                               this._super = __super;
+                               this._superApply = __superApply;
+
+                               return returnValue;
+                       };
+               })();
+       });
+       constructor.prototype = $.widget.extend( basePrototype, {
+               // TODO: remove support for widgetEventPrefix
+               // always use the name + a colon as the prefix, e.g., draggable:start
+               // don't prefix for widgets that aren't DOM-based
+               widgetEventPrefix: existingConstructor ? (basePrototype.widgetEventPrefix || name) : name
+       }, proxiedPrototype, {
+               constructor: constructor,
+               namespace: namespace,
+               widgetName: name,
+               widgetFullName: fullName
+       });
+
+       // If this widget is being redefined then we need to find all widgets that
+       // are inheriting from it and redefine all of them so that they inherit from
+       // the new version of this widget. We're essentially trying to replace one
+       // level in the prototype chain.
+       if ( existingConstructor ) {
+               $.each( existingConstructor._childConstructors, function( i, child ) {
+                       var childPrototype = child.prototype;
+
+                       // redefine the child widget using the same prototype that was
+                       // originally used, but inherit from the new version of the base
+                       $.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto );
+               });
+               // remove the list of existing child constructors from the old constructor
+               // so the old child constructors can be garbage collected
+               delete existingConstructor._childConstructors;
+       } else {
+               base._childConstructors.push( constructor );
+       }
+
+       $.widget.bridge( name, constructor );
+};
+
+$.widget.extend = function( target ) {
+       var input = slice.call( arguments, 1 ),
+               inputIndex = 0,
+               inputLength = input.length,
+               key,
+               value;
+       for ( ; inputIndex < inputLength; inputIndex++ ) {
+               for ( key in input[ inputIndex ] ) {
+                       value = input[ inputIndex ][ key ];
+                       if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {
+                               // Clone objects
+                               if ( $.isPlainObject( value ) ) {
+                                       target[ key ] = $.isPlainObject( target[ key ] ) ?
+                                               $.widget.extend( {}, target[ key ], value ) :
+                                               // Don't extend strings, arrays, etc. with objects
+                                               $.widget.extend( {}, value );
+                               // Copy everything else by reference
+                               } else {
+                                       target[ key ] = value;
+                               }
+                       }
+               }
+       }
+       return target;
+};
+
+$.widget.bridge = function( name, object ) {
+       var fullName = object.prototype.widgetFullName || name;
+       $.fn[ name ] = function( options ) {
+               var isMethodCall = typeof options === "string",
+                       args = slice.call( arguments, 1 ),
+                       returnValue = this;
+
+               // allow multiple hashes to be passed on init
+               options = !isMethodCall && args.length ?
+                       $.widget.extend.apply( null, [ options ].concat(args) ) :
+                       options;
+
+               if ( isMethodCall ) {
+                       this.each(function() {
+                               var methodValue,
+                                       instance = $.data( this, fullName );
+                               if ( !instance ) {
+                                       return $.error( "cannot call methods on " + name + " prior to initialization; " +
+                                               "attempted to call method '" + options + "'" );
+                               }
+                               if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) {
+                                       return $.error( "no such method '" + options + "' for " + name + " widget instance" );
+                               }
+                               methodValue = instance[ options ].apply( instance, args );
+                               if ( methodValue !== instance && methodValue !== undefined ) {
+                                       returnValue = methodValue && methodValue.jquery ?
+                                               returnValue.pushStack( methodValue.get() ) :
+                                               methodValue;
+                                       return false;
+                               }
+                       });
+               } else {
+                       this.each(function() {
+                               var instance = $.data( this, fullName );
+                               if ( instance ) {
+                                       instance.option( options || {} )._init();
+                               } else {
+                                       $.data( this, fullName, new object( options, this ) );
+                               }
+                       });
+               }
+
+               return returnValue;
+       };
+};
+
+$.Widget = function( /* options, element */ ) {};
+$.Widget._childConstructors = [];
+
+$.Widget.prototype = {
+       widgetName: "widget",
+       widgetEventPrefix: "",
+       defaultElement: "<div>",
+       options: {
+               disabled: false,
+
+               // callbacks
+               create: null
+       },
+       _createWidget: function( options, element ) {
+               element = $( element || this.defaultElement || this )[ 0 ];
+               this.element = $( element );
+               this.uuid = uuid++;
+               this.eventNamespace = "." + this.widgetName + this.uuid;
+               this.options = $.widget.extend( {},
+                       this.options,
+                       this._getCreateOptions(),
+                       options );
+
+               this.bindings = $();
+               this.hoverable = $();
+               this.focusable = $();
+
+               if ( element !== this ) {
+                       $.data( element, this.widgetFullName, this );
+                       this._on( true, this.element, {
+                               remove: function( event ) {
+                                       if ( event.target === element ) {
+                                               this.destroy();
+                                       }
+                               }
+                       });
+                       this.document = $( element.style ?
+                               // element within the document
+                               element.ownerDocument :
+                               // element is window or document
+                               element.document || element );
+                       this.window = $( this.document[0].defaultView || this.document[0].parentWindow );
+               }
+
+               this._create();
+               this._trigger( "create", null, this._getCreateEventData() );
+               this._init();
+       },
+       _getCreateOptions: $.noop,
+       _getCreateEventData: $.noop,
+       _create: $.noop,
+       _init: $.noop,
+
+       destroy: function() {
+               this._destroy();
+               // we can probably remove the unbind calls in 2.0
+               // all event bindings should go through this._on()
+               this.element
+                       .unbind( this.eventNamespace )
+                       // 1.9 BC for #7810
+                       // TODO remove dual storage
+                       .removeData( this.widgetName )
+                       .removeData( this.widgetFullName )
+                       // support: jquery <1.6.3
+                       // http://bugs.jquery.com/ticket/9413
+                       .removeData( $.camelCase( this.widgetFullName ) );
+               this.widget()
+                       .unbind( this.eventNamespace )
+                       .removeAttr( "aria-disabled" )
+                       .removeClass(
+                               this.widgetFullName + "-disabled " +
+                               "ui-state-disabled" );
+
+               // clean up events and states
+               this.bindings.unbind( this.eventNamespace );
+               this.hoverable.removeClass( "ui-state-hover" );
+               this.focusable.removeClass( "ui-state-focus" );
+       },
+       _destroy: $.noop,
+
+       widget: function() {
+               return this.element;
+       },
+
+       option: function( key, value ) {
+               var options = key,
+                       parts,
+                       curOption,
+                       i;
+
+               if ( arguments.length === 0 ) {
+                       // don't return a reference to the internal hash
+                       return $.widget.extend( {}, this.options );
+               }
+
+               if ( typeof key === "string" ) {
+                       // handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
+                       options = {};
+                       parts = key.split( "." );
+                       key = parts.shift();
+                       if ( parts.length ) {
+                               curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
+                               for ( i = 0; i < parts.length - 1; i++ ) {
+                                       curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
+                                       curOption = curOption[ parts[ i ] ];
+                               }
+                               key = parts.pop();
+                               if ( arguments.length === 1 ) {
+                                       return curOption[ key ] === undefined ? null : curOption[ key ];
+                               }
+                               curOption[ key ] = value;
+                       } else {
+                               if ( arguments.length === 1 ) {
+                                       return this.options[ key ] === undefined ? null : this.options[ key ];
+                               }
+                               options[ key ] = value;
+                       }
+               }
+
+               this._setOptions( options );
+
+               return this;
+       },
+       _setOptions: function( options ) {
+               var key;
+
+               for ( key in options ) {
+                       this._setOption( key, options[ key ] );
+               }
+
+               return this;
+       },
+       _setOption: function( key, value ) {
+               this.options[ key ] = value;
+
+               if ( key === "disabled" ) {
+                       this.widget()
+                               .toggleClass( this.widgetFullName + "-disabled ui-state-disabled", !!value )
+                               .attr( "aria-disabled", value );
+                       this.hoverable.removeClass( "ui-state-hover" );
+                       this.focusable.removeClass( "ui-state-focus" );
+               }
+
+               return this;
+       },
+
+       enable: function() {
+               return this._setOption( "disabled", false );
+       },
+       disable: function() {
+               return this._setOption( "disabled", true );
+       },
+
+       _on: function( suppressDisabledCheck, element, handlers ) {
+               var delegateElement,
+                       instance = this;
+
+               // no suppressDisabledCheck flag, shuffle arguments
+               if ( typeof suppressDisabledCheck !== "boolean" ) {
+                       handlers = element;
+                       element = suppressDisabledCheck;
+                       suppressDisabledCheck = false;
+               }
+
+               // no element argument, shuffle and use this.element
+               if ( !handlers ) {
+                       handlers = element;
+                       element = this.element;
+                       delegateElement = this.widget();
+               } else {
+                       // accept selectors, DOM elements
+                       element = delegateElement = $( element );
+                       this.bindings = this.bindings.add( element );
+               }
+
+               $.each( handlers, function( event, handler ) {
+                       function handlerProxy() {
+                               // allow widgets to customize the disabled handling
+                               // - disabled as an array instead of boolean
+                               // - disabled class as method for disabling individual parts
+                               if ( !suppressDisabledCheck &&
+                                               ( instance.options.disabled === true ||
+                                                       $( this ).hasClass( "ui-state-disabled" ) ) ) {
+                                       return;
+                               }
+                               return ( typeof handler === "string" ? instance[ handler ] : handler )
+                                       .apply( instance, arguments );
+                       }
+
+                       // copy the guid so direct unbinding works
+                       if ( typeof handler !== "string" ) {
+                               handlerProxy.guid = handler.guid =
+                                       handler.guid || handlerProxy.guid || $.guid++;
+                       }
+
+                       var match = event.match( /^(\w+)\s*(.*)$/ ),
+                               eventName = match[1] + instance.eventNamespace,
+                               selector = match[2];
+                       if ( selector ) {
+                               delegateElement.delegate( selector, eventName, handlerProxy );
+                       } else {
+                               element.bind( eventName, handlerProxy );
+                       }
+               });
+       },
+
+       _off: function( element, eventName ) {
+               eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace;
+               element.unbind( eventName ).undelegate( eventName );
+       },
+
+       _delay: function( handler, delay ) {
+               function handlerProxy() {
+                       return ( typeof handler === "string" ? instance[ handler ] : handler )
+                               .apply( instance, arguments );
+               }
+               var instance = this;
+               return setTimeout( handlerProxy, delay || 0 );
+       },
+
+       _hoverable: function( element ) {
+               this.hoverable = this.hoverable.add( element );
+               this._on( element, {
+                       mouseenter: function( event ) {
+                               $( event.currentTarget ).addClass( "ui-state-hover" );
+                       },
+                       mouseleave: function( event ) {
+                               $( event.currentTarget ).removeClass( "ui-state-hover" );
+                       }
+               });
+       },
+
+       _focusable: function( element ) {
+               this.focusable = this.focusable.add( element );
+               this._on( element, {
+                       focusin: function( event ) {
+                               $( event.currentTarget ).addClass( "ui-state-focus" );
+                       },
+                       focusout: function( event ) {
+                               $( event.currentTarget ).removeClass( "ui-state-focus" );
+                       }
+               });
+       },
+
+       _trigger: function( type, event, data ) {
+               var prop, orig,
+                       callback = this.options[ type ];
+
+               data = data || {};
+               event = $.Event( event );
+               event.type = ( type === this.widgetEventPrefix ?
+                       type :
+                       this.widgetEventPrefix + type ).toLowerCase();
+               // the original event may come from any element
+               // so we need to reset the target on the new event
+               event.target = this.element[ 0 ];
+
+               // copy original event properties over to the new event
+               orig = event.originalEvent;
+               if ( orig ) {
+                       for ( prop in orig ) {
+                               if ( !( prop in event ) ) {
+                                       event[ prop ] = orig[ prop ];
+                               }
+                       }
+               }
+
+               this.element.trigger( event, data );
+               return !( $.isFunction( callback ) &&
+                       callback.apply( this.element[0], [ event ].concat( data ) ) === false ||
+                       event.isDefaultPrevented() );
+       }
+};
+
+$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
+       $.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
+               if ( typeof options === "string" ) {
+                       options = { effect: options };
+               }
+               var hasOptions,
+                       effectName = !options ?
+                               method :
+                               options === true || typeof options === "number" ?
+                                       defaultEffect :
+                                       options.effect || defaultEffect;
+               options = options || {};
+               if ( typeof options === "number" ) {
+                       options = { duration: options };
+               }
+               hasOptions = !$.isEmptyObject( options );
+               options.complete = callback;
+               if ( options.delay ) {
+                       element.delay( options.delay );
+               }
+               if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
+                       element[ method ]( options );
+               } else if ( effectName !== method && element[ effectName ] ) {
+                       element[ effectName ]( options.duration, options.easing, callback );
+               } else {
+                       element.queue(function( next ) {
+                               $( this )[ method ]();
+                               if ( callback ) {
+                                       callback.call( element[ 0 ] );
+                               }
+                               next();
+                       });
+               }
+       };
+});
+
+})( jQuery );
+(function( $, undefined ) {
+
+$.ui = $.ui || {};
+
+var cachedScrollbarWidth,
+       max = Math.max,
+       abs = Math.abs,
+       round = Math.round,
+       rhorizontal = /left|center|right/,
+       rvertical = /top|center|bottom/,
+       roffset = /[\+\-]\d+(\.[\d]+)?%?/,
+       rposition = /^\w+/,
+       rpercent = /%$/,
+       _position = $.fn.position;
+
+function getOffsets( offsets, width, height ) {
+       return [
+               parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ),
+               parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 )
+       ];
+}
+
+function parseCss( element, property ) {
+       return parseInt( $.css( element, property ), 10 ) || 0;
+}
+
+function getDimensions( elem ) {
+       var raw = elem[0];
+       if ( raw.nodeType === 9 ) {
+               return {
+                       width: elem.width(),
+                       height: elem.height(),
+                       offset: { top: 0, left: 0 }
+               };
+       }
+       if ( $.isWindow( raw ) ) {
+               return {
+                       width: elem.width(),
+                       height: elem.height(),
+                       offset: { top: elem.scrollTop(), left: elem.scrollLeft() }
+               };
+       }
+       if ( raw.preventDefault ) {
+               return {
+                       width: 0,
+                       height: 0,
+                       offset: { top: raw.pageY, left: raw.pageX }
+               };
+       }
+       return {
+               width: elem.outerWidth(),
+               height: elem.outerHeight(),
+               offset: elem.offset()
+       };
+}
+
+$.position = {
+       scrollbarWidth: function() {
+               if ( cachedScrollbarWidth !== undefined ) {
+                       return cachedScrollbarWidth;
+               }
+               var w1, w2,
+                       div = $( "<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>" ),
+                       innerDiv = div.children()[0];
+
+               $( "body" ).append( div );
+               w1 = innerDiv.offsetWidth;
+               div.css( "overflow", "scroll" );
+
+               w2 = innerDiv.offsetWidth;
+
+               if ( w1 === w2 ) {
+                       w2 = div[0].clientWidth;
+               }
+
+               div.remove();
+
+               return (cachedScrollbarWidth = w1 - w2);
+       },
+       getScrollInfo: function( within ) {
+               var overflowX = within.isWindow || within.isDocument ? "" :
+                               within.element.css( "overflow-x" ),
+                       overflowY = within.isWindow || within.isDocument ? "" :
+                               within.element.css( "overflow-y" ),
+                       hasOverflowX = overflowX === "scroll" ||
+                               ( overflowX === "auto" && within.width < within.element[0].scrollWidth ),
+                       hasOverflowY = overflowY === "scroll" ||
+                               ( overflowY === "auto" && within.height < within.element[0].scrollHeight );
+               return {
+                       width: hasOverflowY ? $.position.scrollbarWidth() : 0,
+                       height: hasOverflowX ? $.position.scrollbarWidth() : 0
+               };
+       },
+       getWithinInfo: function( element ) {
+               var withinElement = $( element || window ),
+                       isWindow = $.isWindow( withinElement[0] ),
+                       isDocument = !!withinElement[ 0 ] && withinElement[ 0 ].nodeType === 9;
+               return {
+                       element: withinElement,
+                       isWindow: isWindow,
+                       isDocument: isDocument,
+                       offset: withinElement.offset() || { left: 0, top: 0 },
+                       scrollLeft: withinElement.scrollLeft(),
+                       scrollTop: withinElement.scrollTop(),
+                       width: isWindow ? withinElement.width() : withinElement.outerWidth(),
+                       height: isWindow ? withinElement.height() : withinElement.outerHeight()
+               };
+       }
+};
+
+$.fn.position = function( options ) {
+       if ( !options || !options.of ) {
+               return _position.apply( this, arguments );
+       }
+
+       // make a copy, we don't want to modify arguments
+       options = $.extend( {}, options );
+
+       var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions,
+               target = $( options.of ),
+               within = $.position.getWithinInfo( options.within ),
+               scrollInfo = $.position.getScrollInfo( within ),
+               collision = ( options.collision || "flip" ).split( " " ),
+               offsets = {};
+
+       dimensions = getDimensions( target );
+       if ( target[0].preventDefault ) {
+               // force left top to allow flipping
+               options.at = "left top";
+       }
+       targetWidth = dimensions.width;
+       targetHeight = dimensions.height;
+       targetOffset = dimensions.offset;
+       // clone to reuse original targetOffset later
+       basePosition = $.extend( {}, targetOffset );
+
+       // force my and at to have valid horizontal and vertical positions
+       // if a value is missing or invalid, it will be converted to center
+       $.each( [ "my", "at" ], function() {
+               var pos = ( options[ this ] || "" ).split( " " ),
+                       horizontalOffset,
+                       verticalOffset;
+
+               if ( pos.length === 1) {
+                       pos = rhorizontal.test( pos[ 0 ] ) ?
+                               pos.concat( [ "center" ] ) :
+                               rvertical.test( pos[ 0 ] ) ?
+                                       [ "center" ].concat( pos ) :
+                                       [ "center", "center" ];
+               }
+               pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center";
+               pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center";
+
+               // calculate offsets
+               horizontalOffset = roffset.exec( pos[ 0 ] );
+               verticalOffset = roffset.exec( pos[ 1 ] );
+               offsets[ this ] = [
+                       horizontalOffset ? horizontalOffset[ 0 ] : 0,
+                       verticalOffset ? verticalOffset[ 0 ] : 0
+               ];
+
+               // reduce to just the positions without the offsets
+               options[ this ] = [
+                       rposition.exec( pos[ 0 ] )[ 0 ],
+                       rposition.exec( pos[ 1 ] )[ 0 ]
+               ];
+       });
+
+       // normalize collision option
+       if ( collision.length === 1 ) {
+               collision[ 1 ] = collision[ 0 ];
+       }
+
+       if ( options.at[ 0 ] === "right" ) {
+               basePosition.left += targetWidth;
+       } else if ( options.at[ 0 ] === "center" ) {
+               basePosition.left += targetWidth / 2;
+       }
+
+       if ( options.at[ 1 ] === "bottom" ) {
+               basePosition.top += targetHeight;
+       } else if ( options.at[ 1 ] === "center" ) {
+               basePosition.top += targetHeight / 2;
+       }
+
+       atOffset = getOffsets( offsets.at, targetWidth, targetHeight );
+       basePosition.left += atOffset[ 0 ];
+       basePosition.top += atOffset[ 1 ];
+
+       return this.each(function() {
+               var collisionPosition, using,
+                       elem = $( this ),
+                       elemWidth = elem.outerWidth(),
+                       elemHeight = elem.outerHeight(),
+                       marginLeft = parseCss( this, "marginLeft" ),
+                       marginTop = parseCss( this, "marginTop" ),
+                       collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) + scrollInfo.width,
+                       collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) + scrollInfo.height,
+                       position = $.extend( {}, basePosition ),
+                       myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() );
+
+               if ( options.my[ 0 ] === "right" ) {
+                       position.left -= elemWidth;
+               } else if ( options.my[ 0 ] === "center" ) {
+                       position.left -= elemWidth / 2;
+               }
+
+               if ( options.my[ 1 ] === "bottom" ) {
+                       position.top -= elemHeight;
+               } else if ( options.my[ 1 ] === "center" ) {
+                       position.top -= elemHeight / 2;
+               }
+
+               position.left += myOffset[ 0 ];
+               position.top += myOffset[ 1 ];
+
+               // if the browser doesn't support fractions, then round for consistent results
+               if ( !$.support.offsetFractions ) {
+                       position.left = round( position.left );
+                       position.top = round( position.top );
+               }
+
+               collisionPosition = {
+                       marginLeft: marginLeft,
+                       marginTop: marginTop
+               };
+
+               $.each( [ "left", "top" ], function( i, dir ) {
+                       if ( $.ui.position[ collision[ i ] ] ) {
+                               $.ui.position[ collision[ i ] ][ dir ]( position, {
+                                       targetWidth: targetWidth,
+                                       targetHeight: targetHeight,
+                                       elemWidth: elemWidth,
+                                       elemHeight: elemHeight,
+                                       collisionPosition: collisionPosition,
+                                       collisionWidth: collisionWidth,
+                                       collisionHeight: collisionHeight,
+                                       offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ],
+                                       my: options.my,
+                                       at: options.at,
+                                       within: within,
+                                       elem : elem
+                               });
+                       }
+               });
+
+               if ( options.using ) {
+                       // adds feedback as second argument to using callback, if present
+                       using = function( props ) {
+                               var left = targetOffset.left - position.left,
+                                       right = left + targetWidth - elemWidth,
+                                       top = targetOffset.top - position.top,
+                                       bottom = top + targetHeight - elemHeight,
+                                       feedback = {
+                                               target: {
+                                                       element: target,
+                                                       left: targetOffset.left,
+                                                       top: targetOffset.top,
+                                                       width: targetWidth,
+                                                       height: targetHeight
+                                               },
+                                               element: {
+                                                       element: elem,
+                                                       left: position.left,
+                                                       top: position.top,
+                                                       width: elemWidth,
+                                                       height: elemHeight
+                                               },
+                                               horizontal: right < 0 ? "left" : left > 0 ? "right" : "center",
+                                               vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle"
+                                       };
+                               if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) {
+                                       feedback.horizontal = "center";
+                               }
+                               if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) {
+                                       feedback.vertical = "middle";
+                               }
+                               if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) {
+                                       feedback.important = "horizontal";
+                               } else {
+                                       feedback.important = "vertical";
+                               }
+                               options.using.call( this, props, feedback );
+                       };
+               }
+
+               elem.offset( $.extend( position, { using: using } ) );
+       });
+};
+
+$.ui.position = {
+       fit: {
+               left: function( position, data ) {
+                       var within = data.within,
+                               withinOffset = within.isWindow ? within.scrollLeft : within.offset.left,
+                               outerWidth = within.width,
+                               collisionPosLeft = position.left - data.collisionPosition.marginLeft,
+                               overLeft = withinOffset - collisionPosLeft,
+                               overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,
+                               newOverRight;
+
+                       // element is wider than within
+                       if ( data.collisionWidth > outerWidth ) {
+                               // element is initially over the left side of within
+                               if ( overLeft > 0 && overRight <= 0 ) {
+                                       newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset;
+                                       position.left += overLeft - newOverRight;
+                               // element is initially over right side of within
+                               } else if ( overRight > 0 && overLeft <= 0 ) {
+                                       position.left = withinOffset;
+                               // element is initially over both left and right sides of within
+                               } else {
+                                       if ( overLeft > overRight ) {
+                                               position.left = withinOffset + outerWidth - data.collisionWidth;
+                                       } else {
+                                               position.left = withinOffset;
+                                       }
+                               }
+                       // too far left -> align with left edge
+                       } else if ( overLeft > 0 ) {
+                               position.left += overLeft;
+                       // too far right -> align with right edge
+                       } else if ( overRight > 0 ) {
+                               position.left -= overRight;
+                       // adjust based on position and margin
+                       } else {
+                               position.left = max( position.left - collisionPosLeft, position.left );
+                       }
+               },
+               top: function( position, data ) {
+                       var within = data.within,
+                               withinOffset = within.isWindow ? within.scrollTop : within.offset.top,
+                               outerHeight = data.within.height,
+                               collisionPosTop = position.top - data.collisionPosition.marginTop,
+                               overTop = withinOffset - collisionPosTop,
+                               overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,
+                               newOverBottom;
+
+                       // element is taller than within
+                       if ( data.collisionHeight > outerHeight ) {
+                               // element is initially over the top of within
+                               if ( overTop > 0 && overBottom <= 0 ) {
+                                       newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset;
+                                       position.top += overTop - newOverBottom;
+                               // element is initially over bottom of within
+                               } else if ( overBottom > 0 && overTop <= 0 ) {
+                                       position.top = withinOffset;
+                               // element is initially over both top and bottom of within
+                               } else {
+                                       if ( overTop > overBottom ) {
+                                               position.top = withinOffset + outerHeight - data.collisionHeight;
+                                       } else {
+                                               position.top = withinOffset;
+                                       }
+                               }
+                       // too far up -> align with top
+                       } else if ( overTop > 0 ) {
+                               position.top += overTop;
+                       // too far down -> align with bottom edge
+                       } else if ( overBottom > 0 ) {
+                               position.top -= overBottom;
+                       // adjust based on position and margin
+                       } else {
+                               position.top = max( position.top - collisionPosTop, position.top );
+                       }
+               }
+       },
+       flip: {
+               left: function( position, data ) {
+                       var within = data.within,
+                               withinOffset = within.offset.left + within.scrollLeft,
+                               outerWidth = within.width,
+                               offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left,
+                               collisionPosLeft = position.left - data.collisionPosition.marginLeft,
+                               overLeft = collisionPosLeft - offsetLeft,
+                               overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft,
+                               myOffset = data.my[ 0 ] === "left" ?
+                                       -data.elemWidth :
+                                       data.my[ 0 ] === "right" ?
+                                               data.elemWidth :
+                                               0,
+                               atOffset = data.at[ 0 ] === "left" ?
+                                       data.targetWidth :
+                                       data.at[ 0 ] === "right" ?
+                                               -data.targetWidth :
+                                               0,
+                               offset = -2 * data.offset[ 0 ],
+                               newOverRight,
+                               newOverLeft;
+
+                       if ( overLeft < 0 ) {
+                               newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset;
+                               if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) {
+                                       position.left += myOffset + atOffset + offset;
+                               }
+                       }
+                       else if ( overRight > 0 ) {
+                               newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - offsetLeft;
+                               if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) {
+                                       position.left += myOffset + atOffset + offset;
+                               }
+                       }
+               },
+               top: function( position, data ) {
+                       var within = data.within,
+                               withinOffset = within.offset.top + within.scrollTop,
+                               outerHeight = within.height,
+                               offsetTop = within.isWindow ? within.scrollTop : within.offset.top,
+                               collisionPosTop = position.top - data.collisionPosition.marginTop,
+                               overTop = collisionPosTop - offsetTop,
+                               overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop,
+                               top = data.my[ 1 ] === "top",
+                               myOffset = top ?
+                                       -data.elemHeight :
+                                       data.my[ 1 ] === "bottom" ?
+                                               data.elemHeight :
+                                               0,
+                               atOffset = data.at[ 1 ] === "top" ?
+                                       data.targetHeight :
+                                       data.at[ 1 ] === "bottom" ?
+                                               -data.targetHeight :
+                                               0,
+                               offset = -2 * data.offset[ 1 ],
+                               newOverTop,
+                               newOverBottom;
+                       if ( overTop < 0 ) {
+                               newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset;
+                               if ( ( position.top + myOffset + atOffset + offset) > overTop && ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) ) {
+                                       position.top += myOffset + atOffset + offset;
+                               }
+                       }
+                       else if ( overBottom > 0 ) {
+                               newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop;
+                               if ( ( position.top + myOffset + atOffset + offset) > overBottom && ( newOverTop > 0 || abs( newOverTop ) < overBottom ) ) {
+                                       position.top += myOffset + atOffset + offset;
+                               }
+                       }
+               }
+       },
+       flipfit: {
+               left: function() {
+                       $.ui.position.flip.left.apply( this, arguments );
+                       $.ui.position.fit.left.apply( this, arguments );
+               },
+               top: function() {
+                       $.ui.position.flip.top.apply( this, arguments );
+                       $.ui.position.fit.top.apply( this, arguments );
+               }
+       }
+};
+
+// fraction support test
+(function () {
+       var testElement, testElementParent, testElementStyle, offsetLeft, i,
+               body = document.getElementsByTagName( "body" )[ 0 ],
+               div = document.createElement( "div" );
+
+       //Create a "fake body" for testing based on method used in jQuery.support
+       testElement = document.createElement( body ? "div" : "body" );
+       testElementStyle = {
+               visibility: "hidden",
+               width: 0,
+               height: 0,
+               border: 0,
+               margin: 0,
+               background: "none"
+       };
+       if ( body ) {
+               $.extend( testElementStyle, {
+                       position: "absolute",
+                       left: "-1000px",
+                       top: "-1000px"
+               });
+       }
+       for ( i in testElementStyle ) {
+               testElement.style[ i ] = testElementStyle[ i ];
+       }
+       testElement.appendChild( div );
+       testElementParent = body || document.documentElement;
+       testElementParent.insertBefore( testElement, testElementParent.firstChild );
+
+       div.style.cssText = "position: absolute; left: 10.7432222px;";
+
+       offsetLeft = $( div ).offset().left;
+       $.support.offsetFractions = offsetLeft > 10 && offsetLeft < 11;
+
+       testElement.innerHTML = "";
+       testElementParent.removeChild( testElement );
+})();
+
+}( jQuery ) );
+(function( $, undefined ) {
+
+$.widget( "ui.autocomplete", {
+       version: "1.10.4",
+       defaultElement: "<input>",
+       options: {
+               appendTo: null,
+               autoFocus: false,
+               delay: 300,
+               minLength: 1,
+               position: {
+                       my: "left top",
+                       at: "left bottom",
+                       collision: "none"
+               },
+               source: null,
+
+               // callbacks
+               change: null,
+               close: null,
+               focus: null,
+               open: null,
+               response: null,
+               search: null,
+               select: null
+       },
+
+       requestIndex: 0,
+       pending: 0,
+
+       _create: function() {
+               // Some browsers only repeat keydown events, not keypress events,
+               // so we use the suppressKeyPress flag to determine if we've already
+               // handled the keydown event. #7269
+               // Unfortunately the code for & in keypress is the same as the up arrow,
+               // so we use the suppressKeyPressRepeat flag to avoid handling keypress
+               // events when we know the keydown event was used to modify the
+               // search term. #7799
+               var suppressKeyPress, suppressKeyPressRepeat, suppressInput,
+                       nodeName = this.element[0].nodeName.toLowerCase(),
+                       isTextarea = nodeName === "textarea",
+                       isInput = nodeName === "input";
+
+               this.isMultiLine =
+                       // Textareas are always multi-line
+                       isTextarea ? true :
+                       // Inputs are always single-line, even if inside a contentEditable element
+                       // IE also treats inputs as contentEditable
+                       isInput ? false :
+                       // All other element types are determined by whether or not they're contentEditable
+                       this.element.prop( "isContentEditable" );
+
+               this.valueMethod = this.element[ isTextarea || isInput ? "val" : "text" ];
+               this.isNewMenu = true;
+
+               this.element
+                       .addClass( "ui-autocomplete-input" )
+                       .attr( "autocomplete", "off" );
+
+               this._on( this.element, {
+                       keydown: function( event ) {
+                               if ( this.element.prop( "readOnly" ) ) {
+                                       suppressKeyPress = true;
+                                       suppressInput = true;
+                                       suppressKeyPressRepeat = true;
+                                       return;
+                               }
+
+                               suppressKeyPress = false;
+                               suppressInput = false;
+                               suppressKeyPressRepeat = false;
+                               var keyCode = $.ui.keyCode;
+                               switch( event.keyCode ) {
+                               case keyCode.PAGE_UP:
+                                       suppressKeyPress = true;
+                                       this._move( "previousPage", event );
+                                       break;
+                               case keyCode.PAGE_DOWN:
+                                       suppressKeyPress = true;
+                                       this._move( "nextPage", event );
+                                       break;
+                               case keyCode.UP:
+                                       suppressKeyPress = true;
+                                       this._keyEvent( "previous", event );
+                                       break;
+                               case keyCode.DOWN:
+                                       suppressKeyPress = true;
+                                       this._keyEvent( "next", event );
+                                       break;
+                               case keyCode.ENTER:
+                               case keyCode.NUMPAD_ENTER:
+                                       // when menu is open and has focus
+                                       if ( this.menu.active ) {
+                                               // #6055 - Opera still allows the keypress to occur
+                                               // which causes forms to submit
+                                               suppressKeyPress = true;
+                                               event.preventDefault();
+                                               this.menu.select( event );
+                                       }
+                                       break;
+                               case keyCode.TAB:
+                                       if ( this.menu.active ) {
+                                               this.menu.select( event );
+                                       }
+                                       break;
+                               case keyCode.ESCAPE:
+                                       if ( this.menu.element.is( ":visible" ) ) {
+                                               this._value( this.term );
+                                               this.close( event );
+                                               // Different browsers have different default behavior for escape
+                                               // Single press can mean undo or clear
+                                               // Double press in IE means clear the whole form
+                                               event.preventDefault();
+                                       }
+                                       break;
+                               default:
+                                       suppressKeyPressRepeat = true;
+                                       // search timeout should be triggered before the input value is changed
+                                       this._searchTimeout( event );
+                                       break;
+                               }
+                       },
+                       keypress: function( event ) {
+                               if ( suppressKeyPress ) {
+                                       suppressKeyPress = false;
+                                       if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
+                                               event.preventDefault();
+                                       }
+                                       return;
+                               }
+                               if ( suppressKeyPressRepeat ) {
+                                       return;
+                               }
+
+                               // replicate some key handlers to allow them to repeat in Firefox and Opera
+                               var keyCode = $.ui.keyCode;
+                               switch( event.keyCode ) {
+                               case keyCode.PAGE_UP:
+                                       this._move( "previousPage", event );
+                                       break;
+                               case keyCode.PAGE_DOWN:
+                                       this._move( "nextPage", event );
+                                       break;
+                               case keyCode.UP:
+                                       this._keyEvent( "previous", event );
+                                       break;
+                               case keyCode.DOWN:
+                                       this._keyEvent( "next", event );
+                                       break;
+                               }
+                       },
+                       input: function( event ) {
+                               if ( suppressInput ) {
+                                       suppressInput = false;
+                                       event.preventDefault();
+                                       return;
+                               }
+                               this._searchTimeout( event );
+                       },
+                       focus: function() {
+                               this.selectedItem = null;
+                               this.previous = this._value();
+                       },
+                       blur: function( event ) {
+                               if ( this.cancelBlur ) {
+                                       delete this.cancelBlur;
+                                       return;
+                               }
+
+                               clearTimeout( this.searching );
+                               this.close( event );
+                               this._change( event );
+                       }
+               });
+
+               this._initSource();
+               this.menu = $( "<ul>" )
+                       .addClass( "ui-autocomplete ui-front" )
+                       .appendTo( this._appendTo() )
+                       .menu({
+                               // disable ARIA support, the live region takes care of that
+                               role: null
+                       })
+                       .hide()
+                       .data( "ui-menu" );
+
+               this._on( this.menu.element, {
+                       mousedown: function( event ) {
+                               // prevent moving focus out of the text field
+                               event.preventDefault();
+
+                               // IE doesn't prevent moving focus even with event.preventDefault()
+                               // so we set a flag to know when we should ignore the blur event
+                               this.cancelBlur = true;
+                               this._delay(function() {
+                                       delete this.cancelBlur;
+                               });
+
+                               // clicking on the scrollbar causes focus to shift to the body
+                               // but we can't detect a mouseup or a click immediately afterward
+                               // so we have to track the next mousedown and close the menu if
+                               // the user clicks somewhere outside of the autocomplete
+                               var menuElement = this.menu.element[ 0 ];
+                               if ( !$( event.target ).closest( ".ui-menu-item" ).length ) {
+                                       this._delay(function() {
+                                               var that = this;
+                                               this.document.one( "mousedown", function( event ) {
+                                                       if ( event.target !== that.element[ 0 ] &&
+                                                                       event.target !== menuElement &&
+                                                                       !$.contains( menuElement, event.target ) ) {
+                                                               that.close();
+                                                       }
+                                               });
+                                       });
+                               }
+                       },
+                       menufocus: function( event, ui ) {
+                               // support: Firefox
+                               // Prevent accidental activation of menu items in Firefox (#7024 #9118)
+                               if ( this.isNewMenu ) {
+                                       this.isNewMenu = false;
+                                       if ( event.originalEvent && /^mouse/.test( event.originalEvent.type ) ) {
+                                               this.menu.blur();
+
+                                               this.document.one( "mousemove", function() {
+                                                       $( event.target ).trigger( event.originalEvent );
+                                               });
+
+                                               return;
+                                       }
+                               }
+
+                               var item = ui.item.data( "ui-autocomplete-item" );
+                               if ( false !== this._trigger( "focus", event, { item: item } ) ) {
+                                       // use value to match what will end up in the input, if it was a key event
+                                       if ( event.originalEvent && /^key/.test( event.originalEvent.type ) ) {
+                                               this._value( item.value );
+                                       }
+                               } else {
+                                       // Normally the input is populated with the item's value as the
+                                       // menu is navigated, causing screen readers to notice a change and
+                                       // announce the item. Since the focus event was canceled, this doesn't
+                                       // happen, so we update the live region so that screen readers can
+                                       // still notice the change and announce it.
+                                       this.liveRegion.text( item.value );
+                               }
+                       },
+                       menuselect: function( event, ui ) {
+                               var item = ui.item.data( "ui-autocomplete-item" ),
+                                       previous = this.previous;
+
+                               // only trigger when focus was lost (click on menu)
+                               if ( this.element[0] !== this.document[0].activeElement ) {
+                                       this.element.focus();
+                                       this.previous = previous;
+                                       // #6109 - IE triggers two focus events and the second
+                                       // is asynchronous, so we need to reset the previous
+                                       // term synchronously and asynchronously :-(
+                                       this._delay(function() {
+                                               this.previous = previous;
+                                               this.selectedItem = item;
+                                       });
+                               }
+
+                               if ( false !== this._trigger( "select", event, { item: item } ) ) {
+                                       this._value( item.value );
+                               }
+                               // reset the term after the select event
+                               // this allows custom select handling to work properly
+                               this.term = this._value();
+
+                               this.close( event );
+                               this.selectedItem = item;
+                       }
+               });
+
+               this.liveRegion = $( "<span>", {
+                               role: "status",
+                               "aria-live": "polite"
+                       })
+                       .addClass( "ui-helper-hidden-accessible" )
+                       .insertBefore( this.element );
+
+               // turning off autocomplete prevents the browser from remembering the
+               // value when navigating through history, so we re-enable autocomplete
+               // if the page is unloaded before the widget is destroyed. #7790
+               this._on( this.window, {
+                       beforeunload: function() {
+                               this.element.removeAttr( "autocomplete" );
+                       }
+               });
+       },
+
+       _destroy: function() {
+               clearTimeout( this.searching );
+               this.element
+                       .removeClass( "ui-autocomplete-input" )
+                       .removeAttr( "autocomplete" );
+               this.menu.element.remove();
+               this.liveRegion.remove();
+       },
+
+       _setOption: function( key, value ) {
+               this._super( key, value );
+               if ( key === "source" ) {
+                       this._initSource();
+               }
+               if ( key === "appendTo" ) {
+                       this.menu.element.appendTo( this._appendTo() );
+               }
+               if ( key === "disabled" && value && this.xhr ) {
+                       this.xhr.abort();
+               }
+       },
+
+       _appendTo: function() {
+               var element = this.options.appendTo;
+
+               if ( element ) {
+                       element = element.jquery || element.nodeType ?
+                               $( element ) :
+                               this.document.find( element ).eq( 0 );
+               }
+
+               if ( !element ) {
+                       element = this.element.closest( ".ui-front" );
+               }
+
+               if ( !element.length ) {
+                       element = this.document[0].body;
+               }
+
+               return element;
+       },
+
+       _initSource: function() {
+               var array, url,
+                       that = this;
+               if ( $.isArray(this.options.source) ) {
+                       array = this.options.source;
+                       this.source = function( request, response ) {
+                               response( $.ui.autocomplete.filter( array, request.term ) );
+                       };
+               } else if ( typeof this.options.source === "string" ) {
+                       url = this.options.source;
+                       this.source = function( request, response ) {
+                               if ( that.xhr ) {
+                                       that.xhr.abort();
+                               }
+                               that.xhr = $.ajax({
+                                       url: url,
+                                       data: request,
+                                       dataType: "json",
+                                       success: function( data ) {
+                                               response( data );
+                                       },
+                                       error: function() {
+                                               response( [] );
+                                       }
+                               });
+                       };
+               } else {
+                       this.source = this.options.source;
+               }
+       },
+
+       _searchTimeout: function( event ) {
+               clearTimeout( this.searching );
+               this.searching = this._delay(function() {
+                       // only search if the value has changed
+                       if ( this.term !== this._value() ) {
+                               this.selectedItem = null;
+                               this.search( null, event );
+                       }
+               }, this.options.delay );
+       },
+
+       search: function( value, event ) {
+               value = value != null ? value : this._value();
+
+               // always save the actual value, not the one passed as an argument
+               this.term = this._value();
+
+               if ( value.length < this.options.minLength ) {
+                       return this.close( event );
+               }
+
+               if ( this._trigger( "search", event ) === false ) {
+                       return;
+               }
+
+               return this._search( value );
+       },
+
+       _search: function( value ) {
+               this.pending++;
+               this.element.addClass( "ui-autocomplete-loading" );
+               this.cancelSearch = false;
+
+               this.source( { term: value }, this._response() );
+       },
+
+       _response: function() {
+               var index = ++this.requestIndex;
+
+               return $.proxy(function( content ) {
+                       if ( index === this.requestIndex ) {
+                               this.__response( content );
+                       }
+
+                       this.pending--;
+                       if ( !this.pending ) {
+                               this.element.removeClass( "ui-autocomplete-loading" );
+                       }
+               }, this );
+       },
+
+       __response: function( content ) {
+               if ( content ) {
+                       content = this._normalize( content );
+               }
+               this._trigger( "response", null, { content: content } );
+               if ( !this.options.disabled && content && content.length && !this.cancelSearch ) {
+                       this._suggest( content );
+                       this._trigger( "open" );
+               } else {
+                       // use ._close() instead of .close() so we don't cancel future searches
+                       this._close();
+               }
+       },
+
+       close: function( event ) {
+               this.cancelSearch = true;
+               this._close( event );
+       },
+
+       _close: function( event ) {
+               if ( this.menu.element.is( ":visible" ) ) {
+                       this.menu.element.hide();
+                       this.menu.blur();
+                       this.isNewMenu = true;
+                       this._trigger( "close", event );
+               }
+       },
+
+       _change: function( event ) {
+               if ( this.previous !== this._value() ) {
+                       this._trigger( "change", event, { item: this.selectedItem } );
+               }
+       },
+
+       _normalize: function( items ) {
+               // assume all items have the right format when the first item is complete
+               if ( items.length && items[0].label && items[0].value ) {
+                       return items;
+               }
+               return $.map( items, function( item ) {
+                       if ( typeof item === "string" ) {
+                               return {
+                                       label: item,
+                                       value: item
+                               };
+                       }
+                       return $.extend({
+                               label: item.label || item.value,
+                               value: item.value || item.label
+                       }, item );
+               });
+       },
+
+       _suggest: function( items ) {
+               var ul = this.menu.element.empty();
+               this._renderMenu( ul, items );
+               this.isNewMenu = true;
+               this.menu.refresh();
+
+               // size and position menu
+               ul.show();
+               this._resizeMenu();
+               ul.position( $.extend({
+                       of: this.element
+               }, this.options.position ));
+
+               if ( this.options.autoFocus ) {
+                       this.menu.next();
+               }
+       },
+
+       _resizeMenu: function() {
+               var ul = this.menu.element;
+               ul.outerWidth( Math.max(
+                       // Firefox wraps long text (possibly a rounding bug)
+                       // so we add 1px to avoid the wrapping (#7513)
+                       ul.width( "" ).outerWidth() + 1,
+                       this.element.outerWidth()
+               ) );
+       },
+
+       _renderMenu: function( ul, items ) {
+               var that = this;
+               $.each( items, function( index, item ) {
+                       that._renderItemData( ul, item );
+               });
+       },
+
+       _renderItemData: function( ul, item ) {
+               return this._renderItem( ul, item ).data( "ui-autocomplete-item", item );
+       },
+
+       _renderItem: function( ul, item ) {
+               return $( "<li>" )
+                       .append( $( "<a>" ).text( item.label ) )
+                       .appendTo( ul );
+       },
+
+       _move: function( direction, event ) {
+               if ( !this.menu.element.is( ":visible" ) ) {
+                       this.search( null, event );
+                       return;
+               }
+               if ( this.menu.isFirstItem() && /^previous/.test( direction ) ||
+                               this.menu.isLastItem() && /^next/.test( direction ) ) {
+                       this._value( this.term );
+                       this.menu.blur();
+                       return;
+               }
+               this.menu[ direction ]( event );
+       },
+
+       widget: function() {
+               return this.menu.element;
+       },
+
+       _value: function() {
+               return this.valueMethod.apply( this.element, arguments );
+       },
+
+       _keyEvent: function( keyEvent, event ) {
+               if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
+                       this._move( keyEvent, event );
+
+                       // prevents moving cursor to beginning/end of the text field in some browsers
+                       event.preventDefault();
+               }
+       }
+});
+
+$.extend( $.ui.autocomplete, {
+       escapeRegex: function( value ) {
+               return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
+       },
+       filter: function(array, term) {
+               var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
+               return $.grep( array, function(value) {
+                       return matcher.test( value.label || value.value || value );
+               });
+       }
+});
+
+
+// live region extension, adding a `messages` option
+// NOTE: This is an experimental API. We are still investigating
+// a full solution for string manipulation and internationalization.
+$.widget( "ui.autocomplete", $.ui.autocomplete, {
+       options: {
+               messages: {
+                       noResults: "No search results.",
+                       results: function( amount ) {
+                               return amount + ( amount > 1 ? " results are" : " result is" ) +
+                                       " available, use up and down arrow keys to navigate.";
+                       }
+               }
+       },
+
+       __response: function( content ) {
+               var message;
+               this._superApply( arguments );
+               if ( this.options.disabled || this.cancelSearch ) {
+                       return;
+               }
+               if ( content && content.length ) {
+                       message = this.options.messages.results( content.length );
+               } else {
+                       message = this.options.messages.noResults;
+               }
+               this.liveRegion.text( message );
+       }
+});
+
+}( jQuery ));
+(function( $, undefined ) {
+
+$.widget( "ui.menu", {
+       version: "1.10.4",
+       defaultElement: "<ul>",
+       delay: 300,
+       options: {
+               icons: {
+                       submenu: "ui-icon-carat-1-e"
+               },
+               menus: "ul",
+               position: {
+                       my: "left top",
+                       at: "right top"
+               },
+               role: "menu",
+
+               // callbacks
+               blur: null,
+               focus: null,
+               select: null
+       },
+
+       _create: function() {
+               this.activeMenu = this.element;
+               // flag used to prevent firing of the click handler
+               // as the event bubbles up through nested menus
+               this.mouseHandled = false;
+               this.element
+                       .uniqueId()
+                       .addClass( "ui-menu ui-widget ui-widget-content ui-corner-all" )
+                       .toggleClass( "ui-menu-icons", !!this.element.find( ".ui-icon" ).length )
+                       .attr({
+                               role: this.options.role,
+                               tabIndex: 0
+                       })
+                       // need to catch all clicks on disabled menu
+                       // not possible through _on
+                       .bind( "click" + this.eventNamespace, $.proxy(function( event ) {
+                               if ( this.options.disabled ) {
+                                       event.preventDefault();
+                               }
+                       }, this ));
+
+               if ( this.options.disabled ) {
+                       this.element
+                               .addClass( "ui-state-disabled" )
+                               .attr( "aria-disabled", "true" );
+               }
+
+               this._on({
+                       // Prevent focus from sticking to links inside menu after clicking
+                       // them (focus should always stay on UL during navigation).
+                       "mousedown .ui-menu-item > a": function( event ) {
+                               event.preventDefault();
+                       },
+                       "click .ui-state-disabled > a": function( event ) {
+                               event.preventDefault();
+                       },
+                       "click .ui-menu-item:has(a)": function( event ) {
+                               var target = $( event.target ).closest( ".ui-menu-item" );
+                               if ( !this.mouseHandled && target.not( ".ui-state-disabled" ).length ) {
+                                       this.select( event );
+
+                                       // Only set the mouseHandled flag if the event will bubble, see #9469.
+                                       if ( !event.isPropagationStopped() ) {
+                                               this.mouseHandled = true;
+                                       }
+
+                                       // Open submenu on click
+                                       if ( target.has( ".ui-menu" ).length ) {
+                                               this.expand( event );
+                                       } else if ( !this.element.is( ":focus" ) && $( this.document[ 0 ].activeElement ).closest( ".ui-menu" ).length ) {
+
+                                               // Redirect focus to the menu
+                                               this.element.trigger( "focus", [ true ] );
+
+                                               // If the active item is on the top level, let it stay active.
+                                               // Otherwise, blur the active item since it is no longer visible.
+                                               if ( this.active && this.active.parents( ".ui-menu" ).length === 1 ) {
+                                                       clearTimeout( this.timer );
+                                               }
+                                       }
+                               }
+                       },
+                       "mouseenter .ui-menu-item": function( event ) {
+                               var target = $( event.currentTarget );
+                               // Remove ui-state-active class from siblings of the newly focused menu item
+                               // to avoid a jump caused by adjacent elements both having a class with a border
+                               target.siblings().children( ".ui-state-active" ).removeClass( "ui-state-active" );
+                               this.focus( event, target );
+                       },
+                       mouseleave: "collapseAll",
+                       "mouseleave .ui-menu": "collapseAll",
+                       focus: function( event, keepActiveItem ) {
+                               // If there's already an active item, keep it active
+                               // If not, activate the first item
+                               var item = this.active || this.element.children( ".ui-menu-item" ).eq( 0 );
+
+                               if ( !keepActiveItem ) {
+                                       this.focus( event, item );
+                               }
+                       },
+                       blur: function( event ) {
+                               this._delay(function() {
+                                       if ( !$.contains( this.element[0], this.document[0].activeElement ) ) {
+                                               this.collapseAll( event );
+                                       }
+                               });
+                       },
+                       keydown: "_keydown"
+               });
+
+               this.refresh();
+
+               // Clicks outside of a menu collapse any open menus
+               this._on( this.document, {
+                       click: function( event ) {
+                               if ( !$( event.target ).closest( ".ui-menu" ).length ) {
+                                       this.collapseAll( event );
+                               }
+
+                               // Reset the mouseHandled flag
+                               this.mouseHandled = false;
+                       }
+               });
+       },
+
+       _destroy: function() {
+               // Destroy (sub)menus
+               this.element
+                       .removeAttr( "aria-activedescendant" )
+                       .find( ".ui-menu" ).addBack()
+                               .removeClass( "ui-menu ui-widget ui-widget-content ui-corner-all ui-menu-icons" )
+                               .removeAttr( "role" )
+                               .removeAttr( "tabIndex" )
+                               .removeAttr( "aria-labelledby" )
+                               .removeAttr( "aria-expanded" )
+                               .removeAttr( "aria-hidden" )
+                               .removeAttr( "aria-disabled" )
+                               .removeUniqueId()
+                               .show();
+
+               // Destroy menu items
+               this.element.find( ".ui-menu-item" )
+                       .removeClass( "ui-menu-item" )
+                       .removeAttr( "role" )
+                       .removeAttr( "aria-disabled" )
+                       .children( "a" )
+                               .removeUniqueId()
+                               .removeClass( "ui-corner-all ui-state-hover" )
+                               .removeAttr( "tabIndex" )
+                               .removeAttr( "role" )
+                               .removeAttr( "aria-haspopup" )
+                               .children().each( function() {
+                                       var elem = $( this );
+                                       if ( elem.data( "ui-menu-submenu-carat" ) ) {
+                                               elem.remove();
+                                       }
+                               });
+
+               // Destroy menu dividers
+               this.element.find( ".ui-menu-divider" ).removeClass( "ui-menu-divider ui-widget-content" );
+       },
+
+       _keydown: function( event ) {
+               var match, prev, character, skip, regex,
+                       preventDefault = true;
+
+               function escape( value ) {
+                       return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
+               }
+
+               switch ( event.keyCode ) {
+               case $.ui.keyCode.PAGE_UP:
+                       this.previousPage( event );
+                       break;
+               case $.ui.keyCode.PAGE_DOWN:
+                       this.nextPage( event );
+                       break;
+               case $.ui.keyCode.HOME:
+                       this._move( "first", "first", event );
+                       break;
+               case $.ui.keyCode.END:
+                       this._move( "last", "last", event );
+                       break;
+               case $.ui.keyCode.UP:
+                       this.previous( event );
+                       break;
+               case $.ui.keyCode.DOWN:
+                       this.next( event );
+                       break;
+               case $.ui.keyCode.LEFT:
+                       this.collapse( event );
+                       break;
+               case $.ui.keyCode.RIGHT:
+                       if ( this.active && !this.active.is( ".ui-state-disabled" ) ) {
+                               this.expand( event );
+                       }
+                       break;
+               case $.ui.keyCode.ENTER:
+               case $.ui.keyCode.SPACE:
+                       this._activate( event );
+                       break;
+               case $.ui.keyCode.ESCAPE:
+                       this.collapse( event );
+                       break;
+               default:
+                       preventDefault = false;
+                       prev = this.previousFilter || "";
+                       character = String.fromCharCode( event.keyCode );
+                       skip = false;
+
+                       clearTimeout( this.filterTimer );
+
+                       if ( character === prev ) {
+                               skip = true;
+                       } else {
+                               character = prev + character;
+                       }
+
+                       regex = new RegExp( "^" + escape( character ), "i" );
+                       match = this.activeMenu.children( ".ui-menu-item" ).filter(function() {
+                               return regex.test( $( this ).children( "a" ).text() );
+                       });
+                       match = skip && match.index( this.active.next() ) !== -1 ?
+                               this.active.nextAll( ".ui-menu-item" ) :
+                               match;
+
+                       // If no matches on the current filter, reset to the last character pressed
+                       // to move down the menu to the first item that starts with that character
+                       if ( !match.length ) {
+                               character = String.fromCharCode( event.keyCode );
+                               regex = new RegExp( "^" + escape( character ), "i" );
+                               match = this.activeMenu.children( ".ui-menu-item" ).filter(function() {
+                                       return regex.test( $( this ).children( "a" ).text() );
+                               });
+                       }
+
+                       if ( match.length ) {
+                               this.focus( event, match );
+                               if ( match.length > 1 ) {
+                                       this.previousFilter = character;
+                                       this.filterTimer = this._delay(function() {
+                                               delete this.previousFilter;
+                                       }, 1000 );
+                               } else {
+                                       delete this.previousFilter;
+                               }
+                       } else {
+                               delete this.previousFilter;
+                       }
+               }
+
+               if ( preventDefault ) {
+                       event.preventDefault();
+               }
+       },
+
+       _activate: function( event ) {
+               if ( !this.active.is( ".ui-state-disabled" ) ) {
+                       if ( this.active.children( "a[aria-haspopup='true']" ).length ) {
+                               this.expand( event );
+                       } else {
+                               this.select( event );
+                       }
+               }
+       },
+
+       refresh: function() {
+               var menus,
+                       icon = this.options.icons.submenu,
+                       submenus = this.element.find( this.options.menus );
+
+               this.element.toggleClass( "ui-menu-icons", !!this.element.find( ".ui-icon" ).length );
+
+               // Initialize nested menus
+               submenus.filter( ":not(.ui-menu)" )
+                       .addClass( "ui-menu ui-widget ui-widget-content ui-corner-all" )
+                       .hide()
+                       .attr({
+                               role: this.options.role,
+                               "aria-hidden": "true",
+                               "aria-expanded": "false"
+                       })
+                       .each(function() {
+                               var menu = $( this ),
+                                       item = menu.prev( "a" ),
+                                       submenuCarat = $( "<span>" )
+                                               .addClass( "ui-menu-icon ui-icon " + icon )
+                                               .data( "ui-menu-submenu-carat", true );
+
+                               item
+                                       .attr( "aria-haspopup", "true" )
+                                       .prepend( submenuCarat );
+                               menu.attr( "aria-labelledby", item.attr( "id" ) );
+                       });
+
+               menus = submenus.add( this.element );
+
+               // Don't refresh list items that are already adapted
+               menus.children( ":not(.ui-menu-item):has(a)" )
+                       .addClass( "ui-menu-item" )
+                       .attr( "role", "presentation" )
+                       .children( "a" )
+                               .uniqueId()
+                               .addClass( "ui-corner-all" )
+                               .attr({
+                                       tabIndex: -1,
+                                       role: this._itemRole()
+                               });
+
+               // Initialize unlinked menu-items containing spaces and/or dashes only as dividers
+               menus.children( ":not(.ui-menu-item)" ).each(function() {
+                       var item = $( this );
+                       // hyphen, em dash, en dash
+                       if ( !/[^\-\u2014\u2013\s]/.test( item.text() ) ) {
+                               item.addClass( "ui-widget-content ui-menu-divider" );
+                       }
+               });
+
+               // Add aria-disabled attribute to any disabled menu item
+               menus.children( ".ui-state-disabled" ).attr( "aria-disabled", "true" );
+
+               // If the active item has been removed, blur the menu
+               if ( this.active && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) {
+                       this.blur();
+               }
+       },
+
+       _itemRole: function() {
+               return {
+                       menu: "menuitem",
+                       listbox: "option"
+               }[ this.options.role ];
+       },
+
+       _setOption: function( key, value ) {
+               if ( key === "icons" ) {
+                       this.element.find( ".ui-menu-icon" )
+                               .removeClass( this.options.icons.submenu )
+                               .addClass( value.submenu );
+               }
+               this._super( key, value );
+       },
+
+       focus: function( event, item ) {
+               var nested, focused;
+               this.blur( event, event && event.type === "focus" );
+
+               this._scrollIntoView( item );
+
+               this.active = item.first();
+               focused = this.active.children( "a" ).addClass( "ui-state-focus" );
+               // Only update aria-activedescendant if there's a role
+               // otherwise we assume focus is managed elsewhere
+               if ( this.options.role ) {
+                       this.element.attr( "aria-activedescendant", focused.attr( "id" ) );
+               }
+
+               // Highlight active parent menu item, if any
+               this.active
+                       .parent()
+                       .closest( ".ui-menu-item" )
+                       .children( "a:first" )
+                       .addClass( "ui-state-active" );
+
+               if ( event && event.type === "keydown" ) {
+                       this._close();
+               } else {
+                       this.timer = this._delay(function() {
+                               this._close();
+                       }, this.delay );
+               }
+
+               nested = item.children( ".ui-menu" );
+               if ( nested.length && event && ( /^mouse/.test( event.type ) ) ) {
+                       this._startOpening(nested);
+               }
+               this.activeMenu = item.parent();
+
+               this._trigger( "focus", event, { item: item } );
+       },
+
+       _scrollIntoView: function( item ) {
+               var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight;
+               if ( this._hasScroll() ) {
+                       borderTop = parseFloat( $.css( this.activeMenu[0], "borderTopWidth" ) ) || 0;
+                       paddingTop = parseFloat( $.css( this.activeMenu[0], "paddingTop" ) ) || 0;
+                       offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop;
+                       scroll = this.activeMenu.scrollTop();
+                       elementHeight = this.activeMenu.height();
+                       itemHeight = item.height();
+
+                       if ( offset < 0 ) {
+                               this.activeMenu.scrollTop( scroll + offset );
+                       } else if ( offset + itemHeight > elementHeight ) {
+                               this.activeMenu.scrollTop( scroll + offset - elementHeight + itemHeight );
+                       }
+               }
+       },
+
+       blur: function( event, fromFocus ) {
+               if ( !fromFocus ) {
+                       clearTimeout( this.timer );
+               }
+
+               if ( !this.active ) {
+                       return;
+               }
+
+               this.active.children( "a" ).removeClass( "ui-state-focus" );
+               this.active = null;
+
+               this._trigger( "blur", event, { item: this.active } );
+       },
+
+       _startOpening: function( submenu ) {
+               clearTimeout( this.timer );
+
+               // Don't open if already open fixes a Firefox bug that caused a .5 pixel
+               // shift in the submenu position when mousing over the carat icon
+               if ( submenu.attr( "aria-hidden" ) !== "true" ) {
+                       return;
+               }
+
+               this.timer = this._delay(function() {
+                       this._close();
+                       this._open( submenu );
+               }, this.delay );
+       },
+
+       _open: function( submenu ) {
+               var position = $.extend({
+                       of: this.active
+               }, this.options.position );
+
+               clearTimeout( this.timer );
+               this.element.find( ".ui-menu" ).not( submenu.parents( ".ui-menu" ) )
+                       .hide()
+                       .attr( "aria-hidden", "true" );
+
+               submenu
+                       .show()
+                       .removeAttr( "aria-hidden" )
+                       .attr( "aria-expanded", "true" )
+                       .position( position );
+       },
+
+       collapseAll: function( event, all ) {
+               clearTimeout( this.timer );
+               this.timer = this._delay(function() {
+                       // If we were passed an event, look for the submenu that contains the event
+                       var currentMenu = all ? this.element :
+                               $( event && event.target ).closest( this.element.find( ".ui-menu" ) );
+
+                       // If we found no valid submenu ancestor, use the main menu to close all sub menus anyway
+                       if ( !currentMenu.length ) {
+                               currentMenu = this.element;
+                       }
+
+                       this._close( currentMenu );
+
+                       this.blur( event );
+                       this.activeMenu = currentMenu;
+               }, this.delay );
+       },
+
+       // With no arguments, closes the currently active menu - if nothing is active
+       // it closes all menus.  If passed an argument, it will search for menus BELOW
+       _close: function( startMenu ) {
+               if ( !startMenu ) {
+                       startMenu = this.active ? this.active.parent() : this.element;
+               }
+
+               startMenu
+                       .find( ".ui-menu" )
+                               .hide()
+                               .attr( "aria-hidden", "true" )
+                               .attr( "aria-expanded", "false" )
+                       .end()
+                       .find( "a.ui-state-active" )
+                               .removeClass( "ui-state-active" );
+       },
+
+       collapse: function( event ) {
+               var newItem = this.active &&
+                       this.active.parent().closest( ".ui-menu-item", this.element );
+               if ( newItem && newItem.length ) {
+                       this._close();
+                       this.focus( event, newItem );
+               }
+       },
+
+       expand: function( event ) {
+               var newItem = this.active &&
+                       this.active
+                               .children( ".ui-menu " )
+                               .children( ".ui-menu-item" )
+                               .first();
+
+               if ( newItem && newItem.length ) {
+                       this._open( newItem.parent() );
+
+                       // Delay so Firefox will not hide activedescendant change in expanding submenu from AT
+                       this._delay(function() {
+                               this.focus( event, newItem );
+                       });
+               }
+       },
+
+       next: function( event ) {
+               this._move( "next", "first", event );
+       },
+
+       previous: function( event ) {
+               this._move( "prev", "last", event );
+       },
+
+       isFirstItem: function() {
+               return this.active && !this.active.prevAll( ".ui-menu-item" ).length;
+       },
+
+       isLastItem: function() {
+               return this.active && !this.active.nextAll( ".ui-menu-item" ).length;
+       },
+
+       _move: function( direction, filter, event ) {
+               var next;
+               if ( this.active ) {
+                       if ( direction === "first" || direction === "last" ) {
+                               next = this.active
+                                       [ direction === "first" ? "prevAll" : "nextAll" ]( ".ui-menu-item" )
+                                       .eq( -1 );
+                       } else {
+                               next = this.active
+                                       [ direction + "All" ]( ".ui-menu-item" )
+                                       .eq( 0 );
+                       }
+               }
+               if ( !next || !next.length || !this.active ) {
+                       next = this.activeMenu.children( ".ui-menu-item" )[ filter ]();
+               }
+
+               this.focus( event, next );
+       },
+
+       nextPage: function( event ) {
+               var item, base, height;
+
+               if ( !this.active ) {
+                       this.next( event );
+                       return;
+               }
+               if ( this.isLastItem() ) {
+                       return;
+               }
+               if ( this._hasScroll() ) {
+                       base = this.active.offset().top;
+                       height = this.element.height();
+                       this.active.nextAll( ".ui-menu-item" ).each(function() {
+                               item = $( this );
+                               return item.offset().top - base - height < 0;
+                       });
+
+                       this.focus( event, item );
+               } else {
+                       this.focus( event, this.activeMenu.children( ".ui-menu-item" )
+                               [ !this.active ? "first" : "last" ]() );
+               }
+       },
+
+       previousPage: function( event ) {
+               var item, base, height;
+               if ( !this.active ) {
+                       this.next( event );
+                       return;
+               }
+               if ( this.isFirstItem() ) {
+                       return;
+               }
+               if ( this._hasScroll() ) {
+                       base = this.active.offset().top;
+                       height = this.element.height();
+                       this.active.prevAll( ".ui-menu-item" ).each(function() {
+                               item = $( this );
+                               return item.offset().top - base + height > 0;
+                       });
+
+                       this.focus( event, item );
+               } else {
+                       this.focus( event, this.activeMenu.children( ".ui-menu-item" ).first() );
+               }
+       },
+
+       _hasScroll: function() {
+               return this.element.outerHeight() < this.element.prop( "scrollHeight" );
+       },
+
+       select: function( event ) {
+               // TODO: It should never be possible to not have an active item at this
+               // point, but the tests don't trigger mouseenter before click.
+               this.active = this.active || $( event.target ).closest( ".ui-menu-item" );
+               var ui = { item: this.active };
+               if ( !this.active.has( ".ui-menu" ).length ) {
+                       this.collapseAll( event, true );
+               }
+               this._trigger( "select", event, ui );
+       }
+});
+
+}( jQuery ));
diff --git a/themes/default/js/jquery-ui-1.10.4.custom.min.js b/themes/default/js/jquery-ui-1.10.4.custom.min.js
new file mode 100644 (file)
index 0000000..3163502
--- /dev/null
@@ -0,0 +1,6 @@
+/*! jQuery UI - v1.10.4 - 2014-03-08
+* http://jqueryui.com
+* Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.position.js, jquery.ui.autocomplete.js, jquery.ui.menu.js
+* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */
+
+(function(e,t){function i(t,i){var s,a,o,r=t.nodeName.toLowerCase();return"area"===r?(s=t.parentNode,a=s.name,t.href&&a&&"map"===s.nodeName.toLowerCase()?(o=e("img[usemap=#"+a+"]")[0],!!o&&n(o)):!1):(/input|select|textarea|button|object/.test(r)?!t.disabled:"a"===r?t.href||i:i)&&n(t)}function n(t){return e.expr.filters.visible(t)&&!e(t).parents().addBack().filter(function(){return"hidden"===e.css(this,"visibility")}).length}var s=0,a=/^ui-id-\d+$/;e.ui=e.ui||{},e.extend(e.ui,{version:"1.10.4",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}}),e.fn.extend({focus:function(t){return function(i,n){return"number"==typeof i?this.each(function(){var t=this;setTimeout(function(){e(t).focus(),n&&n.call(t)},i)}):t.apply(this,arguments)}}(e.fn.focus),scrollParent:function(){var t;return t=e.ui.ie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(e.css(this,"position"))&&/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0),/fixed/.test(this.css("position"))||!t.length?e(document):t},zIndex:function(i){if(i!==t)return this.css("zIndex",i);if(this.length)for(var n,s,a=e(this[0]);a.length&&a[0]!==document;){if(n=a.css("position"),("absolute"===n||"relative"===n||"fixed"===n)&&(s=parseInt(a.css("zIndex"),10),!isNaN(s)&&0!==s))return s;a=a.parent()}return 0},uniqueId:function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++s)})},removeUniqueId:function(){return this.each(function(){a.test(this.id)&&e(this).removeAttr("id")})}}),e.extend(e.expr[":"],{data:e.expr.createPseudo?e.expr.createPseudo(function(t){return function(i){return!!e.data(i,t)}}):function(t,i,n){return!!e.data(t,n[3])},focusable:function(t){return i(t,!isNaN(e.attr(t,"tabindex")))},tabbable:function(t){var n=e.attr(t,"tabindex"),s=isNaN(n);return(s||n>=0)&&i(t,!s)}}),e("<a>").outerWidth(1).jquery||e.each(["Width","Height"],function(i,n){function s(t,i,n,s){return e.each(a,function(){i-=parseFloat(e.css(t,"padding"+this))||0,n&&(i-=parseFloat(e.css(t,"border"+this+"Width"))||0),s&&(i-=parseFloat(e.css(t,"margin"+this))||0)}),i}var a="Width"===n?["Left","Right"]:["Top","Bottom"],o=n.toLowerCase(),r={innerWidth:e.fn.innerWidth,innerHeight:e.fn.innerHeight,outerWidth:e.fn.outerWidth,outerHeight:e.fn.outerHeight};e.fn["inner"+n]=function(i){return i===t?r["inner"+n].call(this):this.each(function(){e(this).css(o,s(this,i)+"px")})},e.fn["outer"+n]=function(t,i){return"number"!=typeof t?r["outer"+n].call(this,t):this.each(function(){e(this).css(o,s(this,t,!0,i)+"px")})}}),e.fn.addBack||(e.fn.addBack=function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}),e("<a>").data("a-b","a").removeData("a-b").data("a-b")&&(e.fn.removeData=function(t){return function(i){return arguments.length?t.call(this,e.camelCase(i)):t.call(this)}}(e.fn.removeData)),e.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()),e.support.selectstart="onselectstart"in document.createElement("div"),e.fn.extend({disableSelection:function(){return this.bind((e.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(e){e.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}}),e.extend(e.ui,{plugin:{add:function(t,i,n){var s,a=e.ui[t].prototype;for(s in n)a.plugins[s]=a.plugins[s]||[],a.plugins[s].push([i,n[s]])},call:function(e,t,i){var n,s=e.plugins[t];if(s&&e.element[0].parentNode&&11!==e.element[0].parentNode.nodeType)for(n=0;s.length>n;n++)e.options[s[n][0]]&&s[n][1].apply(e.element,i)}},hasScroll:function(t,i){if("hidden"===e(t).css("overflow"))return!1;var n=i&&"left"===i?"scrollLeft":"scrollTop",s=!1;return t[n]>0?!0:(t[n]=1,s=t[n]>0,t[n]=0,s)}})})(jQuery);(function(t,e){var i=0,s=Array.prototype.slice,n=t.cleanData;t.cleanData=function(e){for(var i,s=0;null!=(i=e[s]);s++)try{t(i).triggerHandler("remove")}catch(o){}n(e)},t.widget=function(i,s,n){var o,a,r,h,l={},c=i.split(".")[0];i=i.split(".")[1],o=c+"-"+i,n||(n=s,s=t.Widget),t.expr[":"][o.toLowerCase()]=function(e){return!!t.data(e,o)},t[c]=t[c]||{},a=t[c][i],r=t[c][i]=function(t,i){return this._createWidget?(arguments.length&&this._createWidget(t,i),e):new r(t,i)},t.extend(r,a,{version:n.version,_proto:t.extend({},n),_childConstructors:[]}),h=new s,h.options=t.widget.extend({},h.options),t.each(n,function(i,n){return t.isFunction(n)?(l[i]=function(){var t=function(){return s.prototype[i].apply(this,arguments)},e=function(t){return s.prototype[i].apply(this,t)};return function(){var i,s=this._super,o=this._superApply;return this._super=t,this._superApply=e,i=n.apply(this,arguments),this._super=s,this._superApply=o,i}}(),e):(l[i]=n,e)}),r.prototype=t.widget.extend(h,{widgetEventPrefix:a?h.widgetEventPrefix||i:i},l,{constructor:r,namespace:c,widgetName:i,widgetFullName:o}),a?(t.each(a._childConstructors,function(e,i){var s=i.prototype;t.widget(s.namespace+"."+s.widgetName,r,i._proto)}),delete a._childConstructors):s._childConstructors.push(r),t.widget.bridge(i,r)},t.widget.extend=function(i){for(var n,o,a=s.call(arguments,1),r=0,h=a.length;h>r;r++)for(n in a[r])o=a[r][n],a[r].hasOwnProperty(n)&&o!==e&&(i[n]=t.isPlainObject(o)?t.isPlainObject(i[n])?t.widget.extend({},i[n],o):t.widget.extend({},o):o);return i},t.widget.bridge=function(i,n){var o=n.prototype.widgetFullName||i;t.fn[i]=function(a){var r="string"==typeof a,h=s.call(arguments,1),l=this;return a=!r&&h.length?t.widget.extend.apply(null,[a].concat(h)):a,r?this.each(function(){var s,n=t.data(this,o);return n?t.isFunction(n[a])&&"_"!==a.charAt(0)?(s=n[a].apply(n,h),s!==n&&s!==e?(l=s&&s.jquery?l.pushStack(s.get()):s,!1):e):t.error("no such method '"+a+"' for "+i+" widget instance"):t.error("cannot call methods on "+i+" prior to initialization; "+"attempted to call method '"+a+"'")}):this.each(function(){var e=t.data(this,o);e?e.option(a||{})._init():t.data(this,o,new n(a,this))}),l}},t.Widget=function(){},t.Widget._childConstructors=[],t.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{disabled:!1,create:null},_createWidget:function(e,s){s=t(s||this.defaultElement||this)[0],this.element=t(s),this.uuid=i++,this.eventNamespace="."+this.widgetName+this.uuid,this.options=t.widget.extend({},this.options,this._getCreateOptions(),e),this.bindings=t(),this.hoverable=t(),this.focusable=t(),s!==this&&(t.data(s,this.widgetFullName,this),this._on(!0,this.element,{remove:function(t){t.target===s&&this.destroy()}}),this.document=t(s.style?s.ownerDocument:s.document||s),this.window=t(this.document[0].defaultView||this.document[0].parentWindow)),this._create(),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:t.noop,_getCreateEventData:t.noop,_create:t.noop,_init:t.noop,destroy:function(){this._destroy(),this.element.unbind(this.eventNamespace).removeData(this.widgetName).removeData(this.widgetFullName).removeData(t.camelCase(this.widgetFullName)),this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled "+"ui-state-disabled"),this.bindings.unbind(this.eventNamespace),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")},_destroy:t.noop,widget:function(){return this.element},option:function(i,s){var n,o,a,r=i;if(0===arguments.length)return t.widget.extend({},this.options);if("string"==typeof i)if(r={},n=i.split("."),i=n.shift(),n.length){for(o=r[i]=t.widget.extend({},this.options[i]),a=0;n.length-1>a;a++)o[n[a]]=o[n[a]]||{},o=o[n[a]];if(i=n.pop(),1===arguments.length)return o[i]===e?null:o[i];o[i]=s}else{if(1===arguments.length)return this.options[i]===e?null:this.options[i];r[i]=s}return this._setOptions(r),this},_setOptions:function(t){var e;for(e in t)this._setOption(e,t[e]);return this},_setOption:function(t,e){return this.options[t]=e,"disabled"===t&&(this.widget().toggleClass(this.widgetFullName+"-disabled ui-state-disabled",!!e).attr("aria-disabled",e),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")),this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_on:function(i,s,n){var o,a=this;"boolean"!=typeof i&&(n=s,s=i,i=!1),n?(s=o=t(s),this.bindings=this.bindings.add(s)):(n=s,s=this.element,o=this.widget()),t.each(n,function(n,r){function h(){return i||a.options.disabled!==!0&&!t(this).hasClass("ui-state-disabled")?("string"==typeof r?a[r]:r).apply(a,arguments):e}"string"!=typeof r&&(h.guid=r.guid=r.guid||h.guid||t.guid++);var l=n.match(/^(\w+)\s*(.*)$/),c=l[1]+a.eventNamespace,u=l[2];u?o.delegate(u,c,h):s.bind(c,h)})},_off:function(t,e){e=(e||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,t.unbind(e).undelegate(e)},_delay:function(t,e){function i(){return("string"==typeof t?s[t]:t).apply(s,arguments)}var s=this;return setTimeout(i,e||0)},_hoverable:function(e){this.hoverable=this.hoverable.add(e),this._on(e,{mouseenter:function(e){t(e.currentTarget).addClass("ui-state-hover")},mouseleave:function(e){t(e.currentTarget).removeClass("ui-state-hover")}})},_focusable:function(e){this.focusable=this.focusable.add(e),this._on(e,{focusin:function(e){t(e.currentTarget).addClass("ui-state-focus")},focusout:function(e){t(e.currentTarget).removeClass("ui-state-focus")}})},_trigger:function(e,i,s){var n,o,a=this.options[e];if(s=s||{},i=t.Event(i),i.type=(e===this.widgetEventPrefix?e:this.widgetEventPrefix+e).toLowerCase(),i.target=this.element[0],o=i.originalEvent)for(n in o)n in i||(i[n]=o[n]);return this.element.trigger(i,s),!(t.isFunction(a)&&a.apply(this.element[0],[i].concat(s))===!1||i.isDefaultPrevented())}},t.each({show:"fadeIn",hide:"fadeOut"},function(e,i){t.Widget.prototype["_"+e]=function(s,n,o){"string"==typeof n&&(n={effect:n});var a,r=n?n===!0||"number"==typeof n?i:n.effect||i:e;n=n||{},"number"==typeof n&&(n={duration:n}),a=!t.isEmptyObject(n),n.complete=o,n.delay&&s.delay(n.delay),a&&t.effects&&t.effects.effect[r]?s[e](n):r!==e&&s[r]?s[r](n.duration,n.easing,o):s.queue(function(i){t(this)[e](),o&&o.call(s[0]),i()})}})})(jQuery);(function(t,e){function i(t,e,i){return[parseFloat(t[0])*(p.test(t[0])?e/100:1),parseFloat(t[1])*(p.test(t[1])?i/100:1)]}function s(e,i){return parseInt(t.css(e,i),10)||0}function n(e){var i=e[0];return 9===i.nodeType?{width:e.width(),height:e.height(),offset:{top:0,left:0}}:t.isWindow(i)?{width:e.width(),height:e.height(),offset:{top:e.scrollTop(),left:e.scrollLeft()}}:i.preventDefault?{width:0,height:0,offset:{top:i.pageY,left:i.pageX}}:{width:e.outerWidth(),height:e.outerHeight(),offset:e.offset()}}t.ui=t.ui||{};var a,o=Math.max,r=Math.abs,l=Math.round,h=/left|center|right/,c=/top|center|bottom/,u=/[\+\-]\d+(\.[\d]+)?%?/,d=/^\w+/,p=/%$/,f=t.fn.position;t.position={scrollbarWidth:function(){if(a!==e)return a;var i,s,n=t("<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),o=n.children()[0];return t("body").append(n),i=o.offsetWidth,n.css("overflow","scroll"),s=o.offsetWidth,i===s&&(s=n[0].clientWidth),n.remove(),a=i-s},getScrollInfo:function(e){var i=e.isWindow||e.isDocument?"":e.element.css("overflow-x"),s=e.isWindow||e.isDocument?"":e.element.css("overflow-y"),n="scroll"===i||"auto"===i&&e.width<e.element[0].scrollWidth,a="scroll"===s||"auto"===s&&e.height<e.element[0].scrollHeight;return{width:a?t.position.scrollbarWidth():0,height:n?t.position.scrollbarWidth():0}},getWithinInfo:function(e){var i=t(e||window),s=t.isWindow(i[0]),n=!!i[0]&&9===i[0].nodeType;return{element:i,isWindow:s,isDocument:n,offset:i.offset()||{left:0,top:0},scrollLeft:i.scrollLeft(),scrollTop:i.scrollTop(),width:s?i.width():i.outerWidth(),height:s?i.height():i.outerHeight()}}},t.fn.position=function(e){if(!e||!e.of)return f.apply(this,arguments);e=t.extend({},e);var a,p,g,m,v,_,b=t(e.of),y=t.position.getWithinInfo(e.within),k=t.position.getScrollInfo(y),w=(e.collision||"flip").split(" "),D={};return _=n(b),b[0].preventDefault&&(e.at="left top"),p=_.width,g=_.height,m=_.offset,v=t.extend({},m),t.each(["my","at"],function(){var t,i,s=(e[this]||"").split(" ");1===s.length&&(s=h.test(s[0])?s.concat(["center"]):c.test(s[0])?["center"].concat(s):["center","center"]),s[0]=h.test(s[0])?s[0]:"center",s[1]=c.test(s[1])?s[1]:"center",t=u.exec(s[0]),i=u.exec(s[1]),D[this]=[t?t[0]:0,i?i[0]:0],e[this]=[d.exec(s[0])[0],d.exec(s[1])[0]]}),1===w.length&&(w[1]=w[0]),"right"===e.at[0]?v.left+=p:"center"===e.at[0]&&(v.left+=p/2),"bottom"===e.at[1]?v.top+=g:"center"===e.at[1]&&(v.top+=g/2),a=i(D.at,p,g),v.left+=a[0],v.top+=a[1],this.each(function(){var n,h,c=t(this),u=c.outerWidth(),d=c.outerHeight(),f=s(this,"marginLeft"),_=s(this,"marginTop"),x=u+f+s(this,"marginRight")+k.width,C=d+_+s(this,"marginBottom")+k.height,M=t.extend({},v),T=i(D.my,c.outerWidth(),c.outerHeight());"right"===e.my[0]?M.left-=u:"center"===e.my[0]&&(M.left-=u/2),"bottom"===e.my[1]?M.top-=d:"center"===e.my[1]&&(M.top-=d/2),M.left+=T[0],M.top+=T[1],t.support.offsetFractions||(M.left=l(M.left),M.top=l(M.top)),n={marginLeft:f,marginTop:_},t.each(["left","top"],function(i,s){t.ui.position[w[i]]&&t.ui.position[w[i]][s](M,{targetWidth:p,targetHeight:g,elemWidth:u,elemHeight:d,collisionPosition:n,collisionWidth:x,collisionHeight:C,offset:[a[0]+T[0],a[1]+T[1]],my:e.my,at:e.at,within:y,elem:c})}),e.using&&(h=function(t){var i=m.left-M.left,s=i+p-u,n=m.top-M.top,a=n+g-d,l={target:{element:b,left:m.left,top:m.top,width:p,height:g},element:{element:c,left:M.left,top:M.top,width:u,height:d},horizontal:0>s?"left":i>0?"right":"center",vertical:0>a?"top":n>0?"bottom":"middle"};u>p&&p>r(i+s)&&(l.horizontal="center"),d>g&&g>r(n+a)&&(l.vertical="middle"),l.important=o(r(i),r(s))>o(r(n),r(a))?"horizontal":"vertical",e.using.call(this,t,l)}),c.offset(t.extend(M,{using:h}))})},t.ui.position={fit:{left:function(t,e){var i,s=e.within,n=s.isWindow?s.scrollLeft:s.offset.left,a=s.width,r=t.left-e.collisionPosition.marginLeft,l=n-r,h=r+e.collisionWidth-a-n;e.collisionWidth>a?l>0&&0>=h?(i=t.left+l+e.collisionWidth-a-n,t.left+=l-i):t.left=h>0&&0>=l?n:l>h?n+a-e.collisionWidth:n:l>0?t.left+=l:h>0?t.left-=h:t.left=o(t.left-r,t.left)},top:function(t,e){var i,s=e.within,n=s.isWindow?s.scrollTop:s.offset.top,a=e.within.height,r=t.top-e.collisionPosition.marginTop,l=n-r,h=r+e.collisionHeight-a-n;e.collisionHeight>a?l>0&&0>=h?(i=t.top+l+e.collisionHeight-a-n,t.top+=l-i):t.top=h>0&&0>=l?n:l>h?n+a-e.collisionHeight:n:l>0?t.top+=l:h>0?t.top-=h:t.top=o(t.top-r,t.top)}},flip:{left:function(t,e){var i,s,n=e.within,a=n.offset.left+n.scrollLeft,o=n.width,l=n.isWindow?n.scrollLeft:n.offset.left,h=t.left-e.collisionPosition.marginLeft,c=h-l,u=h+e.collisionWidth-o-l,d="left"===e.my[0]?-e.elemWidth:"right"===e.my[0]?e.elemWidth:0,p="left"===e.at[0]?e.targetWidth:"right"===e.at[0]?-e.targetWidth:0,f=-2*e.offset[0];0>c?(i=t.left+d+p+f+e.collisionWidth-o-a,(0>i||r(c)>i)&&(t.left+=d+p+f)):u>0&&(s=t.left-e.collisionPosition.marginLeft+d+p+f-l,(s>0||u>r(s))&&(t.left+=d+p+f))},top:function(t,e){var i,s,n=e.within,a=n.offset.top+n.scrollTop,o=n.height,l=n.isWindow?n.scrollTop:n.offset.top,h=t.top-e.collisionPosition.marginTop,c=h-l,u=h+e.collisionHeight-o-l,d="top"===e.my[1],p=d?-e.elemHeight:"bottom"===e.my[1]?e.elemHeight:0,f="top"===e.at[1]?e.targetHeight:"bottom"===e.at[1]?-e.targetHeight:0,g=-2*e.offset[1];0>c?(s=t.top+p+f+g+e.collisionHeight-o-a,t.top+p+f+g>c&&(0>s||r(c)>s)&&(t.top+=p+f+g)):u>0&&(i=t.top-e.collisionPosition.marginTop+p+f+g-l,t.top+p+f+g>u&&(i>0||u>r(i))&&(t.top+=p+f+g))}},flipfit:{left:function(){t.ui.position.flip.left.apply(this,arguments),t.ui.position.fit.left.apply(this,arguments)},top:function(){t.ui.position.flip.top.apply(this,arguments),t.ui.position.fit.top.apply(this,arguments)}}},function(){var e,i,s,n,a,o=document.getElementsByTagName("body")[0],r=document.createElement("div");e=document.createElement(o?"div":"body"),s={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},o&&t.extend(s,{position:"absolute",left:"-1000px",top:"-1000px"});for(a in s)e.style[a]=s[a];e.appendChild(r),i=o||document.documentElement,i.insertBefore(e,i.firstChild),r.style.cssText="position: absolute; left: 10.7432222px;",n=t(r).offset().left,t.support.offsetFractions=n>10&&11>n,e.innerHTML="",i.removeChild(e)}()})(jQuery);(function(e){e.widget("ui.autocomplete",{version:"1.10.4",defaultElement:"<input>",options:{appendTo:null,autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null,change:null,close:null,focus:null,open:null,response:null,search:null,select:null},requestIndex:0,pending:0,_create:function(){var t,i,s,n=this.element[0].nodeName.toLowerCase(),a="textarea"===n,o="input"===n;this.isMultiLine=a?!0:o?!1:this.element.prop("isContentEditable"),this.valueMethod=this.element[a||o?"val":"text"],this.isNewMenu=!0,this.element.addClass("ui-autocomplete-input").attr("autocomplete","off"),this._on(this.element,{keydown:function(n){if(this.element.prop("readOnly"))return t=!0,s=!0,i=!0,undefined;t=!1,s=!1,i=!1;var a=e.ui.keyCode;switch(n.keyCode){case a.PAGE_UP:t=!0,this._move("previousPage",n);break;case a.PAGE_DOWN:t=!0,this._move("nextPage",n);break;case a.UP:t=!0,this._keyEvent("previous",n);break;case a.DOWN:t=!0,this._keyEvent("next",n);break;case a.ENTER:case a.NUMPAD_ENTER:this.menu.active&&(t=!0,n.preventDefault(),this.menu.select(n));break;case a.TAB:this.menu.active&&this.menu.select(n);break;case a.ESCAPE:this.menu.element.is(":visible")&&(this._value(this.term),this.close(n),n.preventDefault());break;default:i=!0,this._searchTimeout(n)}},keypress:function(s){if(t)return t=!1,(!this.isMultiLine||this.menu.element.is(":visible"))&&s.preventDefault(),undefined;if(!i){var n=e.ui.keyCode;switch(s.keyCode){case n.PAGE_UP:this._move("previousPage",s);break;case n.PAGE_DOWN:this._move("nextPage",s);break;case n.UP:this._keyEvent("previous",s);break;case n.DOWN:this._keyEvent("next",s)}}},input:function(e){return s?(s=!1,e.preventDefault(),undefined):(this._searchTimeout(e),undefined)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(e){return this.cancelBlur?(delete this.cancelBlur,undefined):(clearTimeout(this.searching),this.close(e),this._change(e),undefined)}}),this._initSource(),this.menu=e("<ul>").addClass("ui-autocomplete ui-front").appendTo(this._appendTo()).menu({role:null}).hide().data("ui-menu"),this._on(this.menu.element,{mousedown:function(t){t.preventDefault(),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur});var i=this.menu.element[0];e(t.target).closest(".ui-menu-item").length||this._delay(function(){var t=this;this.document.one("mousedown",function(s){s.target===t.element[0]||s.target===i||e.contains(i,s.target)||t.close()})})},menufocus:function(t,i){if(this.isNewMenu&&(this.isNewMenu=!1,t.originalEvent&&/^mouse/.test(t.originalEvent.type)))return this.menu.blur(),this.document.one("mousemove",function(){e(t.target).trigger(t.originalEvent)}),undefined;var s=i.item.data("ui-autocomplete-item");!1!==this._trigger("focus",t,{item:s})?t.originalEvent&&/^key/.test(t.originalEvent.type)&&this._value(s.value):this.liveRegion.text(s.value)},menuselect:function(e,t){var i=t.item.data("ui-autocomplete-item"),s=this.previous;this.element[0]!==this.document[0].activeElement&&(this.element.focus(),this.previous=s,this._delay(function(){this.previous=s,this.selectedItem=i})),!1!==this._trigger("select",e,{item:i})&&this._value(i.value),this.term=this._value(),this.close(e),this.selectedItem=i}}),this.liveRegion=e("<span>",{role:"status","aria-live":"polite"}).addClass("ui-helper-hidden-accessible").insertBefore(this.element),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_destroy:function(){clearTimeout(this.searching),this.element.removeClass("ui-autocomplete-input").removeAttr("autocomplete"),this.menu.element.remove(),this.liveRegion.remove()},_setOption:function(e,t){this._super(e,t),"source"===e&&this._initSource(),"appendTo"===e&&this.menu.element.appendTo(this._appendTo()),"disabled"===e&&t&&this.xhr&&this.xhr.abort()},_appendTo:function(){var t=this.options.appendTo;return t&&(t=t.jquery||t.nodeType?e(t):this.document.find(t).eq(0)),t||(t=this.element.closest(".ui-front")),t.length||(t=this.document[0].body),t},_initSource:function(){var t,i,s=this;e.isArray(this.options.source)?(t=this.options.source,this.source=function(i,s){s(e.ui.autocomplete.filter(t,i.term))}):"string"==typeof this.options.source?(i=this.options.source,this.source=function(t,n){s.xhr&&s.xhr.abort(),s.xhr=e.ajax({url:i,data:t,dataType:"json",success:function(e){n(e)},error:function(){n([])}})}):this.source=this.options.source},_searchTimeout:function(e){clearTimeout(this.searching),this.searching=this._delay(function(){this.term!==this._value()&&(this.selectedItem=null,this.search(null,e))},this.options.delay)},search:function(e,t){return e=null!=e?e:this._value(),this.term=this._value(),e.length<this.options.minLength?this.close(t):this._trigger("search",t)!==!1?this._search(e):undefined},_search:function(e){this.pending++,this.element.addClass("ui-autocomplete-loading"),this.cancelSearch=!1,this.source({term:e},this._response())},_response:function(){var t=++this.requestIndex;return e.proxy(function(e){t===this.requestIndex&&this.__response(e),this.pending--,this.pending||this.element.removeClass("ui-autocomplete-loading")},this)},__response:function(e){e&&(e=this._normalize(e)),this._trigger("response",null,{content:e}),!this.options.disabled&&e&&e.length&&!this.cancelSearch?(this._suggest(e),this._trigger("open")):this._close()},close:function(e){this.cancelSearch=!0,this._close(e)},_close:function(e){this.menu.element.is(":visible")&&(this.menu.element.hide(),this.menu.blur(),this.isNewMenu=!0,this._trigger("close",e))},_change:function(e){this.previous!==this._value()&&this._trigger("change",e,{item:this.selectedItem})},_normalize:function(t){return t.length&&t[0].label&&t[0].value?t:e.map(t,function(t){return"string"==typeof t?{label:t,value:t}:e.extend({label:t.label||t.value,value:t.value||t.label},t)})},_suggest:function(t){var i=this.menu.element.empty();this._renderMenu(i,t),this.isNewMenu=!0,this.menu.refresh(),i.show(),this._resizeMenu(),i.position(e.extend({of:this.element},this.options.position)),this.options.autoFocus&&this.menu.next()},_resizeMenu:function(){var e=this.menu.element;e.outerWidth(Math.max(e.width("").outerWidth()+1,this.element.outerWidth()))},_renderMenu:function(t,i){var s=this;e.each(i,function(e,i){s._renderItemData(t,i)})},_renderItemData:function(e,t){return this._renderItem(e,t).data("ui-autocomplete-item",t)},_renderItem:function(t,i){return e("<li>").append(e("<a>").text(i.label)).appendTo(t)},_move:function(e,t){return this.menu.element.is(":visible")?this.menu.isFirstItem()&&/^previous/.test(e)||this.menu.isLastItem()&&/^next/.test(e)?(this._value(this.term),this.menu.blur(),undefined):(this.menu[e](t),undefined):(this.search(null,t),undefined)},widget:function(){return this.menu.element},_value:function(){return this.valueMethod.apply(this.element,arguments)},_keyEvent:function(e,t){(!this.isMultiLine||this.menu.element.is(":visible"))&&(this._move(e,t),t.preventDefault())}}),e.extend(e.ui.autocomplete,{escapeRegex:function(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")},filter:function(t,i){var s=RegExp(e.ui.autocomplete.escapeRegex(i),"i");return e.grep(t,function(e){return s.test(e.label||e.value||e)})}}),e.widget("ui.autocomplete",e.ui.autocomplete,{options:{messages:{noResults:"No search results.",results:function(e){return e+(e>1?" results are":" result is")+" available, use up and down arrow keys to navigate."}}},__response:function(e){var t;this._superApply(arguments),this.options.disabled||this.cancelSearch||(t=e&&e.length?this.options.messages.results(e.length):this.options.messages.noResults,this.liveRegion.text(t))}})})(jQuery);(function(t){t.widget("ui.menu",{version:"1.10.4",defaultElement:"<ul>",delay:300,options:{icons:{submenu:"ui-icon-carat-1-e"},menus:"ul",position:{my:"left top",at:"right top"},role:"menu",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element,this.mouseHandled=!1,this.element.uniqueId().addClass("ui-menu ui-widget ui-widget-content ui-corner-all").toggleClass("ui-menu-icons",!!this.element.find(".ui-icon").length).attr({role:this.options.role,tabIndex:0}).bind("click"+this.eventNamespace,t.proxy(function(t){this.options.disabled&&t.preventDefault()},this)),this.options.disabled&&this.element.addClass("ui-state-disabled").attr("aria-disabled","true"),this._on({"mousedown .ui-menu-item > a":function(t){t.preventDefault()},"click .ui-state-disabled > a":function(t){t.preventDefault()},"click .ui-menu-item:has(a)":function(e){var i=t(e.target).closest(".ui-menu-item");!this.mouseHandled&&i.not(".ui-state-disabled").length&&(this.select(e),e.isPropagationStopped()||(this.mouseHandled=!0),i.has(".ui-menu").length?this.expand(e):!this.element.is(":focus")&&t(this.document[0].activeElement).closest(".ui-menu").length&&(this.element.trigger("focus",[!0]),this.active&&1===this.active.parents(".ui-menu").length&&clearTimeout(this.timer)))},"mouseenter .ui-menu-item":function(e){var i=t(e.currentTarget);i.siblings().children(".ui-state-active").removeClass("ui-state-active"),this.focus(e,i)},mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(t,e){var i=this.active||this.element.children(".ui-menu-item").eq(0);e||this.focus(t,i)},blur:function(e){this._delay(function(){t.contains(this.element[0],this.document[0].activeElement)||this.collapseAll(e)})},keydown:"_keydown"}),this.refresh(),this._on(this.document,{click:function(e){t(e.target).closest(".ui-menu").length||this.collapseAll(e),this.mouseHandled=!1}})},_destroy:function(){this.element.removeAttr("aria-activedescendant").find(".ui-menu").addBack().removeClass("ui-menu ui-widget ui-widget-content ui-corner-all ui-menu-icons").removeAttr("role").removeAttr("tabIndex").removeAttr("aria-labelledby").removeAttr("aria-expanded").removeAttr("aria-hidden").removeAttr("aria-disabled").removeUniqueId().show(),this.element.find(".ui-menu-item").removeClass("ui-menu-item").removeAttr("role").removeAttr("aria-disabled").children("a").removeUniqueId().removeClass("ui-corner-all ui-state-hover").removeAttr("tabIndex").removeAttr("role").removeAttr("aria-haspopup").children().each(function(){var e=t(this);e.data("ui-menu-submenu-carat")&&e.remove()}),this.element.find(".ui-menu-divider").removeClass("ui-menu-divider ui-widget-content")},_keydown:function(e){function i(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}var s,n,a,o,r,l=!0;switch(e.keyCode){case t.ui.keyCode.PAGE_UP:this.previousPage(e);break;case t.ui.keyCode.PAGE_DOWN:this.nextPage(e);break;case t.ui.keyCode.HOME:this._move("first","first",e);break;case t.ui.keyCode.END:this._move("last","last",e);break;case t.ui.keyCode.UP:this.previous(e);break;case t.ui.keyCode.DOWN:this.next(e);break;case t.ui.keyCode.LEFT:this.collapse(e);break;case t.ui.keyCode.RIGHT:this.active&&!this.active.is(".ui-state-disabled")&&this.expand(e);break;case t.ui.keyCode.ENTER:case t.ui.keyCode.SPACE:this._activate(e);break;case t.ui.keyCode.ESCAPE:this.collapse(e);break;default:l=!1,n=this.previousFilter||"",a=String.fromCharCode(e.keyCode),o=!1,clearTimeout(this.filterTimer),a===n?o=!0:a=n+a,r=RegExp("^"+i(a),"i"),s=this.activeMenu.children(".ui-menu-item").filter(function(){return r.test(t(this).children("a").text())}),s=o&&-1!==s.index(this.active.next())?this.active.nextAll(".ui-menu-item"):s,s.length||(a=String.fromCharCode(e.keyCode),r=RegExp("^"+i(a),"i"),s=this.activeMenu.children(".ui-menu-item").filter(function(){return r.test(t(this).children("a").text())})),s.length?(this.focus(e,s),s.length>1?(this.previousFilter=a,this.filterTimer=this._delay(function(){delete this.previousFilter},1e3)):delete this.previousFilter):delete this.previousFilter}l&&e.preventDefault()},_activate:function(t){this.active.is(".ui-state-disabled")||(this.active.children("a[aria-haspopup='true']").length?this.expand(t):this.select(t))},refresh:function(){var e,i=this.options.icons.submenu,s=this.element.find(this.options.menus);this.element.toggleClass("ui-menu-icons",!!this.element.find(".ui-icon").length),s.filter(":not(.ui-menu)").addClass("ui-menu ui-widget ui-widget-content ui-corner-all").hide().attr({role:this.options.role,"aria-hidden":"true","aria-expanded":"false"}).each(function(){var e=t(this),s=e.prev("a"),n=t("<span>").addClass("ui-menu-icon ui-icon "+i).data("ui-menu-submenu-carat",!0);s.attr("aria-haspopup","true").prepend(n),e.attr("aria-labelledby",s.attr("id"))}),e=s.add(this.element),e.children(":not(.ui-menu-item):has(a)").addClass("ui-menu-item").attr("role","presentation").children("a").uniqueId().addClass("ui-corner-all").attr({tabIndex:-1,role:this._itemRole()}),e.children(":not(.ui-menu-item)").each(function(){var e=t(this);/[^\-\u2014\u2013\s]/.test(e.text())||e.addClass("ui-widget-content ui-menu-divider")}),e.children(".ui-state-disabled").attr("aria-disabled","true"),this.active&&!t.contains(this.element[0],this.active[0])&&this.blur()},_itemRole:function(){return{menu:"menuitem",listbox:"option"}[this.options.role]},_setOption:function(t,e){"icons"===t&&this.element.find(".ui-menu-icon").removeClass(this.options.icons.submenu).addClass(e.submenu),this._super(t,e)},focus:function(t,e){var i,s;this.blur(t,t&&"focus"===t.type),this._scrollIntoView(e),this.active=e.first(),s=this.active.children("a").addClass("ui-state-focus"),this.options.role&&this.element.attr("aria-activedescendant",s.attr("id")),this.active.parent().closest(".ui-menu-item").children("a:first").addClass("ui-state-active"),t&&"keydown"===t.type?this._close():this.timer=this._delay(function(){this._close()},this.delay),i=e.children(".ui-menu"),i.length&&t&&/^mouse/.test(t.type)&&this._startOpening(i),this.activeMenu=e.parent(),this._trigger("focus",t,{item:e})},_scrollIntoView:function(e){var i,s,n,a,o,r;this._hasScroll()&&(i=parseFloat(t.css(this.activeMenu[0],"borderTopWidth"))||0,s=parseFloat(t.css(this.activeMenu[0],"paddingTop"))||0,n=e.offset().top-this.activeMenu.offset().top-i-s,a=this.activeMenu.scrollTop(),o=this.activeMenu.height(),r=e.height(),0>n?this.activeMenu.scrollTop(a+n):n+r>o&&this.activeMenu.scrollTop(a+n-o+r))},blur:function(t,e){e||clearTimeout(this.timer),this.active&&(this.active.children("a").removeClass("ui-state-focus"),this.active=null,this._trigger("blur",t,{item:this.active}))},_startOpening:function(t){clearTimeout(this.timer),"true"===t.attr("aria-hidden")&&(this.timer=this._delay(function(){this._close(),this._open(t)},this.delay))},_open:function(e){var i=t.extend({of:this.active},this.options.position);clearTimeout(this.timer),this.element.find(".ui-menu").not(e.parents(".ui-menu")).hide().attr("aria-hidden","true"),e.show().removeAttr("aria-hidden").attr("aria-expanded","true").position(i)},collapseAll:function(e,i){clearTimeout(this.timer),this.timer=this._delay(function(){var s=i?this.element:t(e&&e.target).closest(this.element.find(".ui-menu"));s.length||(s=this.element),this._close(s),this.blur(e),this.activeMenu=s},this.delay)},_close:function(t){t||(t=this.active?this.active.parent():this.element),t.find(".ui-menu").hide().attr("aria-hidden","true").attr("aria-expanded","false").end().find("a.ui-state-active").removeClass("ui-state-active")},collapse:function(t){var e=this.active&&this.active.parent().closest(".ui-menu-item",this.element);e&&e.length&&(this._close(),this.focus(t,e))},expand:function(t){var e=this.active&&this.active.children(".ui-menu ").children(".ui-menu-item").first();e&&e.length&&(this._open(e.parent()),this._delay(function(){this.focus(t,e)}))},next:function(t){this._move("next","first",t)},previous:function(t){this._move("prev","last",t)},isFirstItem:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},isLastItem:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},_move:function(t,e,i){var s;this.active&&(s="first"===t||"last"===t?this.active["first"===t?"prevAll":"nextAll"](".ui-menu-item").eq(-1):this.active[t+"All"](".ui-menu-item").eq(0)),s&&s.length&&this.active||(s=this.activeMenu.children(".ui-menu-item")[e]()),this.focus(i,s)},nextPage:function(e){var i,s,n;return this.active?(this.isLastItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.nextAll(".ui-menu-item").each(function(){return i=t(this),0>i.offset().top-s-n}),this.focus(e,i)):this.focus(e,this.activeMenu.children(".ui-menu-item")[this.active?"last":"first"]())),undefined):(this.next(e),undefined)},previousPage:function(e){var i,s,n;return this.active?(this.isFirstItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.prevAll(".ui-menu-item").each(function(){return i=t(this),i.offset().top-s+n>0}),this.focus(e,i)):this.focus(e,this.activeMenu.children(".ui-menu-item").first())),undefined):(this.next(e),undefined)},_hasScroll:function(){return this.element.outerHeight()<this.element.prop("scrollHeight")},select:function(e){this.active=this.active||t(e.target).closest(".ui-menu-item");var i={item:this.active};this.active.has(".ui-menu").length||this.collapseAll(e,!0),this._trigger("select",e,i)}})})(jQuery);
\ No newline at end of file
diff --git a/themes/default/js/popupForm.js b/themes/default/js/popupForm.js
new file mode 100644 (file)
index 0000000..06be3f0
--- /dev/null
@@ -0,0 +1,20 @@
+$(document).ready(function() {
+
+    $("#search-form").hide();
+
+    function closeSearch() {
+        $("#search-form").toggle();
+        $("#search").toggleClass("current");
+        $("#search-arrow").toggleClass("arrow-down");
+    }
+
+    $("#search").click(function(){
+        closeSearch();
+    });
+
+    $("#search-form-close").click(function(){
+        closeSearch();
+    });
+
+
+});
\ No newline at end of file
diff --git a/themes/default/js/saveLink.js b/themes/default/js/saveLink.js
new file mode 100755 (executable)
index 0000000..6dbce97
--- /dev/null
@@ -0,0 +1,101 @@
+$.fn.ready(function() {
+
+  var $bagit = $('#bagit'),
+      $bagitForm = $('#bagit-form'),
+      $bagitFormForm = $('#bagit-form-form');
+
+  /* ==========================================================================
+   bag it link and close button
+   ========================================================================== */
+
+  function toggleSaveLinkForm(url, event) {
+    $("#add-link-result").empty();
+
+    $bagit.toggleClass("active-current");
+
+    //only if bagiti link is not presented on page
+    if ( $bagit.length === 0 ) {
+      if ( event !== 'undefined' && event ) {
+        $bagitForm.css( {position:"absolute", top:event.pageY, left:event.pageX-200});
+      }
+      else {
+        $bagitForm.css( {position:"relative", top:"auto", left:"auto"});
+      }
+    }
+
+    $bagitForm.toggle();
+    $('#content').toggleClass("opacity03");
+    if (url !== 'undefined' && url) {
+      $('#plainurl').val(url);
+    }
+    $('#plainurl').focus();
+  }
+
+
+  $bagit.click(function(){
+    $bagit.toggleClass("current");
+    $("#bagit-arrow").toggleClass("arrow-down");
+    toggleSaveLinkForm();
+  });
+
+  $("#bagit-form-close").click(function(){
+    $bagit.removeClass("current");
+    $("#bagit-arrow").removeClass("arrow-down");
+    toggleSaveLinkForm();
+  });
+
+
+  //send "bag it link" form request via ajax
+  $bagitFormForm.submit( function(event) {
+    $("body").css("cursor", "wait");
+    $("#add-link-result").empty();
+
+    $.ajax({
+      type: $bagitFormForm.attr('method'),
+      url: $bagitFormForm.attr('action'),
+      data: $bagitFormForm.serialize(),
+      success: function(data) {
+        $('#add-link-result').html("Done!");
+        $('#plainurl').val('');
+        $('#plainurl').blur('');
+        $("body").css("cursor", "auto");
+        //setTimeout( function() { toggleSaveLinkForm(); }, 1000); //close form after 1000 delay
+      },
+      error: function(data) {
+        $('#add-link-result').html("Failed!");
+        $("body").css("cursor", "auto");
+      }
+    });
+
+    event.preventDefault();
+  });
+
+  /* ==========================================================================
+   Keyboard gestion
+   ========================================================================== */
+
+  $(window).keydown(function(e){
+    if ( ( e.target.tagName.toLowerCase() !== 'input' && e.keyCode == 83 ) || (e.keyCode == 27 && $bagitForm.is(':visible') ) ) {
+      $bagit.removeClass("current");
+      $("#bagit-arrow").removeClass("arrow-down");
+      toggleSaveLinkForm();
+      return false;
+    }
+  });
+
+  /* ==========================================================================
+   Process all links inside an article
+   ========================================================================== */
+
+  $("article a[href^='http']").after(function() {
+    return " <a href=\"" + $(this).attr('href') + "\" class=\"add-to-wallabag-link-after\" alt=\"add to wallabag\" title=\"add to wallabag\"></a> ";
+  });
+
+  $(".add-to-wallabag-link-after").click(function(event){
+    toggleSaveLinkForm($(this).attr('href'), event);
+    event.preventDefault();
+  });
+
+});
+
+
old mode 100644 (file)
new mode 100755 (executable)
index cff6b1d..e5be748
@@ -4,5 +4,15 @@
 {% include '_menu.twig' %}
 {% endblock %}
 {% block content %}
-{% for tag in tags %}<a href="./?view=tag&amp;id={{ tag.id }}">{{ tag.value }}</a> {% if token != '' %}<a href="?feed&amp;type=tag&amp;user_id={{ user_id }}&amp;tag_id={{ tag.id }}&amp;token={{ token }}" target="_blank"><img src="{{ poche_url }}/themes/{{ theme }}/img/{{ theme }}/rss.png" /></a>{% endif %} {% endfor %}
+  <div class="two-column">
+    {% for tag in tags %}
+      <a href="./?view=tag&amp;id={{ tag.id }}">{{ tag.value }}</a>  ({{ tag.entriescount }}) {% if token != '' %}<a href="?feed&amp;type=tag&amp;user_id={{ user_id }}&amp;tag_id={{ tag.id }}&amp;token={{ token }}" target="_blank"><img src="{{ poche_url }}themes/{{ theme }}/img/{{ theme }}/rss.png" /></a>{% endif %}
+      <br>
+
+      {% if loop.index  == '%d'|format(loop.length/2 + 0.5)  %}
+        </div><div class="two-column">
+      {% endif %}
+
+    {% endfor %}
+  </div>
 {% endblock %}
\ No newline at end of file
old mode 100644 (file)
new mode 100755 (executable)
index 916abe0..b7d48c0
@@ -1,19 +1,23 @@
 {% extends "layout.twig" %}
 {% block title %}{{ entry.title|raw }} ({{ entry.url | e | getDomain }}){% endblock %}
 {% block content %}
+        {% include '_pocheit-form.twig' %}
         <div id="article_toolbar">
             <ul>
                 <li><a href="./" title="{% trans "Return home" %}" class="tool back"><span>{% trans "Return home" %}</span></a></li>
                 <li><a href="#top" title="{% trans "Back to top" %}" class="tool top"><span>{% trans "Back to top" %}</span></a></li>
                 <li><a href="{{ entry.url|e }}" target="_blank" title="{% trans "original" %} : {{ entry.title|e }}" class="tool link"><span>{{ entry.url | e | getDomain }}</span></a></li>
-                <li><a title="{% trans "Mark as read" %}" class="tool {% if entry.is_read == 0 %}archive-off{% else %}archive{% endif %}" href="./?action=toggle_archive&amp;id={{ entry.id|e }}"><span>{% trans "Toggle mark as read" %}</span></a></li>
-                <li><a title="{% trans "Favorite" %}" class="tool {% if entry.is_fav == 0 %}fav-off{% else %}fav{% endif %}" href="./?action=toggle_fav&amp;id={{ entry.id|e }}"><span>{% trans "Toggle favorite" %}</span></a></li>
+                <li><a title="{% trans "Mark as read" %}" class="tool {% if entry.is_read == 0 %}archive-off{% else %}archive{% endif %}" href="javascript: void(null);" id="markAsRead"><span>{% trans "Toggle mark as read" %}</span></a></li>
+                <li><a title="{% trans "Favorite" %}" class="tool {% if entry.is_fav == 0 %}fav-off{% else %}fav{% endif %}" href="javascript: void(null);" id="setFav"><span>{% trans "Toggle favorite" %}</span></a></li>
                 <li><a title="{% trans "Delete" %}" class="tool delete" href="./?action=delete&amp;id={{ entry.id|e }}"><span>{% trans "Delete" %}</span></a></li>
                 {% if constant('SHARE_TWITTER') == 1 %}<li><a href="https://twitter.com/home?status={{entry.title|url_encode}}%20{{ entry.url|url_encode }}%20via%20@wallabagapp" target="_blank" class="tool twitter" title="{% trans "Tweet" %}"><span>{% trans "Tweet" %}</span></a></li>{% endif %}
                 {% if constant('SHARE_MAIL') == 1 %}<li><a href="mailto:?subject={{ entry.title|url_encode }}&amp;body={{ entry.url|url_encode }}%20via%20@wallabagapp" class="tool email" title="{% trans "Email" %}"><span>{% trans "Email" %}</span></a></li>{% endif %}
                 {% if constant('SHARE_SHAARLI') == 1 %}<li><a href="{{ constant('SHAARLI_URL') }}/index.php?post={{ entry.url|url_encode }}&amp;title={{ entry.title|url_encode }}" target="_blank" class="tool shaarli" title="{% trans "shaarli" %}"><span>{% trans "shaarli" %}</span></a></li>{% endif %}
                 {% if constant('FLATTR') == 1 %}{% if flattr.status == constant('FLATTRABLE') %}<li><a href="http://flattr.com/submit/auto?url={{ entry.url }}" class="tool flattr" target="_blank" title="{% trans "flattr" %}"><span>{% trans "flattr" %}</span></a></li>{% elseif flattr.status == constant('FLATTRED') %}<li><a href="{{ flattr.flattrItemURL }}" class="tool flattr" target="_blank" title="{% trans "flattr" %}"><span>{% trans "flattr" %}</span>{{ flattr.numflattrs }}</a></li>{% endif %}{% endif %}
+                {% if constant('SHOW_PRINTLINK') == 1 %}<li><a title="{% trans "Print" %}" class="tool print" href="javascript: window.print();"><span>{% trans "Print" %}</span></a></li>{% endif %}
+                <li><a href="./?epub&amp;method=id&amp;id={{ entry.id|e }}" title="Generate epub file">EPUB</a></li>
                 <li><a href="mailto:hello@wallabag.org?subject=Wrong%20display%20in%20wallabag&amp;body={{ entry.url|url_encode }}" title="{% trans "Does this article appear wrong?" %}" class="tool bad-display"><span>{% trans "Does this article appear wrong?" %}</span></a></li>
+                {% if constant('SHOW_READPERCENT') == 1 %}<li><div id="readLeftPercent">0%</div></li>{% endif %}
             </ul>
         </div>
         <div id="article">
             </article>
             {{ block('tags') }}
         </div>
-        <script src="{{ poche_url }}/themes/{{ constant('DEFAULT_THEME') }}/js/restoreScroll.js"></script>
+        <script src="{{ poche_url }}themes/{{theme}}/js/restoreScroll.js"></script>
         <script type="text/javascript">
         $(document).ready(function() {
+        
+                       // toggle read property of current article
+                       $('#markAsRead').click(function(){
+                               $("body").css("cursor", "wait");
+                                           $.ajax( { url: './?action=toggle_archive&id={{ entry.id|e }}' }).done(
+                                           function( data ) {
+                                       if ( data == '1' ) {
+                                               if ( $('#markAsRead').hasClass("archive-off") ) {
+                                                       $('#markAsRead').removeClass("archive-off");    
+                                                       $('#markAsRead').addClass("archive");
+                                               }
+                                               else {
+                                                       $('#markAsRead').removeClass("archive");        
+                                                       $('#markAsRead').addClass("archive-off");
+                                               }
+                                       }
+                                       else {
+                                         alert('Error! Pls check if you are logged in.');
+                                       }
+                                     });
+                                           $("body").css("cursor", "auto");
+                                         });
+                                         
+                                         // toggle favorite property of current article
+                       $('#setFav').click(function(){
+                               $("body").css("cursor", "wait");
+                                           $.ajax( { url: './?action=toggle_fav&id={{ entry.id|e }}' }).done(
+                                           function( data ) {
+                                       if ( data == '1' ) {
+                                               if ( $('#setFav').hasClass("fav-off") ) {
+                                                       $('#setFav').removeClass("fav-off");    
+                                                       $('#setFav').addClass("fav");
+                                               }
+                                               else {
+                                                       $('#setFav').removeClass("fav");        
+                                                       $('#setFav').addClass("fav-off");
+                                               }
+                                       }
+                                       else {
+                                         alert('Error! Pls check if you are logged in.');
+                                       }
+                                     });
+                                           $("body").css("cursor", "auto");
+                                         });
+        
+                                               // set percent of read on startup       
+                       if ( $(document).height() <= $(window).innerHeight() ) {
+                         pp = 100;
+                       }
+                       else {
+                               pp = 0;
+                       }
+                       $('#readLeftPercent').text( pp + '%' );
+                       
 
             $(window).scroll(function(e){
                 var scrollTop = $(window).scrollTop();
                 var scrollPercent = (scrollTop) / (docHeight);
                 var scrollPercentRounded = Math.round(scrollPercent*100)/100;
                 savePercent({{ entry.id|e }}, scrollPercentRounded);
+                
+                // change percent of read on scroll
+                pp = Math.round(scrollTop * 100 / ( docHeight - $(window).innerHeight() ));
+                $('#readLeftPercent').text( pp + '%' );
             });
 
             retrievePercent({{ entry.id|e }});
         });
         </script>
 {% endblock %}
+
diff --git a/themes/dmagenta/img/dmagenta/rss.png b/themes/dmagenta/img/dmagenta/rss.png
new file mode 100644 (file)
index 0000000..21bad1a
Binary files /dev/null and b/themes/dmagenta/img/dmagenta/rss.png differ
diff --git a/themes/solarized-dark/img/solarized-dark/rss.png b/themes/solarized-dark/img/solarized-dark/rss.png
new file mode 100644 (file)
index 0000000..21bad1a
Binary files /dev/null and b/themes/solarized-dark/img/solarized-dark/rss.png differ
diff --git a/themes/solarized/img/solarized/rss.png b/themes/solarized/img/solarized/rss.png
new file mode 100644 (file)
index 0000000..21bad1a
Binary files /dev/null and b/themes/solarized/img/solarized/rss.png differ
index 26dce018502a842796c50b6a954051fa3278a219..d6f221564c6a27550143e61f75d4f98555652b5b 100644 (file)
@@ -1,5 +1,5 @@
 <?php
-$app_name = 'wallabag 1';
+$app_name = 'wallabag';
 
 $php_ok = (function_exists('version_compare') && version_compare(phpversion(), '5.3.3', '>='));
 $pcre_ok = extension_loaded('pcre');
@@ -8,9 +8,11 @@ $mbstring_ok = extension_loaded('mbstring');
 $iconv_ok = extension_loaded('iconv');
 $tidy_ok = function_exists('tidy_parse_string');
 $curl_ok = function_exists('curl_exec');
+$parse_ini_ok = function_exists('parse_ini_file');
 $parallel_ok = ((extension_loaded('http') && class_exists('HttpRequestPool')) || ($curl_ok && function_exists('curl_multi_init')));
 $allow_url_fopen_ok = (bool)ini_get('allow_url_fopen');
 $filter_ok = extension_loaded('filter');
+$gettext_ok = function_exists("gettext");
 
 if (extension_loaded('xmlreader')) {
        $xml_ok = true;
@@ -130,8 +132,6 @@ table#chart tr.enabled td {
 
 table#chart tr.disabled td, 
 table#chart tr.disabled td a {
-       color:#999;
-       font-style:italic;
 }
 
 table#chart tr.disabled td a {
@@ -154,12 +154,31 @@ div.chunk {
        background-color:transparent;
        font-style:italic;
 }
+
+.good{
+background-color:#52CC5B;
+}
+.bad{
+background-color:#F74343;
+font-style:italic;
+font-weight: bold;
+}
+.pass{
+background-color:#FF9500;
+}
+
 </style>
 
 </head>
 
 <body>
-
+<?php
+$frominstall = false;
+if (isset($_GET['from'])){
+       if ($_GET['from'] == 'install'){
+               $frominstall = true;
+               }}
+?>
 <div id="site">
        <div id="content">
 
@@ -177,58 +196,68 @@ div.chunk {
                                        <tr class="<?php echo ($php_ok) ? 'enabled' : 'disabled'; ?>">
                                                <td>PHP</td>
                                                <td>5.3.3 or higher</td>
-                                               <td><?php echo phpversion(); ?></td>
+                                               <td class="<?php echo ($php_ok) ? 'good' : 'disabled'; ?>"><?php echo phpversion(); ?></td>
                                        </tr>
-                                       <tr class="<?php echo ($xml_ok) ? 'enabled, and sane' : 'disabled, or broken'; ?>">
+                                       <tr class="<?php echo ($xml_ok) ? 'enabled' : 'disabled'; ?>">
                                                <td><a href="http://php.net/xml">XML</a></td>
                                                <td>Enabled</td>
-                                               <td><?php echo ($xml_ok) ? 'Enabled, and sane' : 'Disabled, or broken'; ?></td>
+                                               <?php echo ($xml_ok) ? '<td class="good">Enabled, and sane</span>' : '<td class="bad">Disabled, or broken'; ?></td>
                                        </tr>
                                        <tr class="<?php echo ($pcre_ok) ? 'enabled' : 'disabled'; ?>">
                                                <td><a href="http://php.net/pcre">PCRE</a></td>
                                                <td>Enabled</td>
-                                               <td><?php echo ($pcre_ok) ? 'Enabled' : 'Disabled'; ?></td>
+                                               <?php echo ($pcre_ok) ? '<td class="good">Enabled' : '<td class="bad">Disabled'; ?></td>
                                        </tr>
 <!--                                   <tr class="<?php echo ($zlib_ok) ? 'enabled' : 'disabled'; ?>">
                                                <td><a href="http://php.net/zlib">Zlib</a></td>
                                                <td>Enabled</td>
-                                               <td><?php echo ($zlib_ok) ? 'Enabled' : 'Disabled'; ?></td>
+                                               <?php echo ($zlib_ok) ? '<td class="good">Enabled' : '<td class="bad">Disabled'; ?></td>
                                        </tr> -->
 <!--                                   <tr class="<?php echo ($mbstring_ok) ? 'enabled' : 'disabled'; ?>">
                                                <td><a href="http://php.net/mbstring">mbstring</a></td>
                                                <td>Enabled</td>
-                                               <td><?php echo ($mbstring_ok) ? 'Enabled' : 'Disabled'; ?></td>
+                                               <?php echo ($mbstring_ok) ? '<td class="good">Enabled' : '<td class="bad">Disabled'; ?></td>
                                        </tr> -->
 <!--                                   <tr class="<?php echo ($iconv_ok) ? 'enabled' : 'disabled'; ?>">
                                                <td><a href="http://php.net/iconv">iconv</a></td>
                                                <td>Enabled</td>
-                                               <td><?php echo ($iconv_ok) ? 'Enabled' : 'Disabled'; ?></td>
+                                               <?php echo ($iconv_ok) ? '<td class="good">Enabled' : '<td class="bad">Disabled'; ?></td>
                                        </tr> -->
                                        <tr class="<?php echo ($filter_ok) ? 'enabled' : 'disabled'; ?>">
                                                <td><a href="http://uk.php.net/manual/en/book.filter.php">Data filtering</a></td>
                                                <td>Enabled</td>
-                                               <td><?php echo ($filter_ok) ? 'Enabled' : 'Disabled'; ?></td>
+                                               <?php echo ($filter_ok) ? '<td class="good">Enabled' : '<td class="pass">Disabled'; ?></td>
                                        </tr>                                   
                                        <tr class="<?php echo ($tidy_ok) ? 'enabled' : 'disabled'; ?>">
                                                <td><a href="http://php.net/tidy">Tidy</a></td>
                                                <td>Enabled</td>
-                                               <td><?php echo ($tidy_ok) ? 'Enabled' : 'Disabled'; ?></td>
+                                               <?php echo ($tidy_ok) ? '<td class="good">Enabled' : '<td class="pass">Disabled'; ?></td>
                                        </tr>
                                        <tr class="<?php echo ($curl_ok) ? 'enabled' : 'disabled'; ?>">
                                                <td><a href="http://php.net/curl">cURL</a></td>
                                                <td>Enabled</td>
-                                               <td><?php echo (extension_loaded('curl')) ? 'Enabled' : 'Disabled'; ?></td>
+                                               <?php echo (extension_loaded('curl')) ? '<td class="good">Enabled' : '<td class="pass">Disabled'; ?></td>
                                        </tr>
+                    <tr class="<?php echo ($parse_ini_ok) ? 'enabled' : 'disabled'; ?>">
+                        <td><a href="http://uk.php.net/manual/en/function.parse-ini-file.php">Parse ini file</td>
+                        <td>Enabled</td>
+                        <?php echo ($parse_ini_ok) ? '<td class="good">Enabled' : '<td class="bad">Disabled'; ?></td>
+                    </tr>
                                        <tr class="<?php echo ($parallel_ok) ? 'enabled' : 'disabled'; ?>">
                                                <td>Parallel URL fetching</td>
                                                <td>Enabled</td>
-                                               <td><?php echo ($parallel_ok) ? 'Enabled' : 'Disabled'; ?></td>
+                                               <?php echo ($parallel_ok) ? '<td class="good">Enabled' : '<td class="pass">Disabled'; ?></td>
                                        </tr>
                                        <tr class="<?php echo ($allow_url_fopen_ok) ? 'enabled' : 'disabled'; ?>">
                                                <td><a href="http://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen">allow_url_fopen</a></td>
                                                <td>Enabled</td>
-                                               <td><?php echo ($allow_url_fopen_ok) ? 'Enabled' : 'Disabled'; ?></td>
-                                       </tr>                                           
+                                               <?php echo ($allow_url_fopen_ok) ? '<td class="good">Enabled' : '<td class="bad">Disabled'; ?></td>
+                                       </tr>
+                                       <tr class="<?php echo ($gettext_ok) ? 'enabled' : 'disabled'; ?>">
+                                               <td><a href="http://php.net/manual/en/book.gettext.php">gettext</a></td>
+                                               <td>Enabled</td>
+                                               <?php echo ($gettext_ok) ? '<td class="good">Enabled' : '<td class="bad">Disabled'; ?></td>
+                                       </tr>
                                </tbody>
                        </table>
                </div>
@@ -237,7 +266,7 @@ div.chunk {
                        <h3>What does this mean?</h3>
                        <ol>
                                <?php //if ($php_ok && $xml_ok && $pcre_ok && $mbstring_ok && $iconv_ok && $filter_ok && $zlib_ok && $tidy_ok && $curl_ok && $parallel_ok && $allow_url_fopen_ok): ?>
-                               <?php if ($php_ok && $xml_ok && $pcre_ok && $filter_ok && $tidy_ok && $curl_ok && $parallel_ok && $allow_url_fopen_ok): ?>
+                               <?php if ($php_ok && $xml_ok && $pcre_ok && $filter_ok && $tidy_ok && $curl_ok && $parallel_ok && $allow_url_fopen_ok && $gettext_ok && $parse_ini_ok): ?>
                                <li><em>You have everything you need to run <?php echo $app_name; ?> properly!  Congratulations!</em></li>
                                <?php else: ?>
                                        <?php if ($php_ok): ?>
@@ -250,59 +279,72 @@ div.chunk {
                                                                <?php if ($allow_url_fopen_ok): ?>
                                                                        <li><strong>allow_url_fopen:</strong> You have allow_url_fopen enabled. <em>No problems here.</em></li>
                                                                        
-                                                                       <?php if ($filter_ok): ?>
-                                                                               <li><strong>Data filtering:</strong> You have the PHP filter extension enabled. <em>No problems here.</em></li>
-       
-                                                                               <?php if ($zlib_ok): ?>
-                                                                                       <li><strong>Zlib:</strong> You have <code>Zlib</code> enabled.  This allows SimplePie to support GZIP-encoded feeds.  <em>No problems here.</em></li>
-                                                                               <?php else: ?>
-                                                                                       <li><strong>Zlib:</strong> The <code>Zlib</code> extension is not available.  SimplePie will ignore any GZIP-encoding, and instead handle feeds as uncompressed text.</li>
-                                                                               <?php endif; ?>
-                       
-                                                                               <?php if ($mbstring_ok && $iconv_ok): ?>
-                                                                                       <li><strong>mbstring and iconv:</strong> You have both <code>mbstring</code> and <code>iconv</code> installed!  This will allow <?php echo $app_name; ?> to handle the greatest number of languages. <em>No problems here.</em></li>
-                                                                               <?php elseif ($mbstring_ok): ?>
-                                                                                       <li><strong>mbstring:</strong> <code>mbstring</code> is installed, but <code>iconv</code> is not.</li>
-                                                                               <?php elseif ($iconv_ok): ?>
-                                                                                       <li><strong>iconv:</strong> <code>iconv</code> is installed, but <code>mbstring</code> is not.</li>
-                                                                               <?php else: ?>
-                                                                                       <li><strong>mbstring and iconv:</strong> <em>You do not have either of the extensions installed.</em> This will significantly impair your ability to read non-English feeds, as well as even some English ones.</li>
-                                                                               <?php endif; ?>
-
-                                                                               <?php if ($tidy_ok): ?>
-                                                                                       <li><strong>Tidy:</strong> You have <code>Tidy</code> support installed.  <em>No problems here.</em></li>
-                                                                               <?php else: ?>
-                                                                                       <li><strong>Tidy:</strong> The <code>Tidy</code> extension is not available.  <?php echo $app_name; ?> should still work with most feeds, but you may experience problems with some.</li>
-                                                                               <?php endif; ?>
+                                                                       <?php if ($gettext_ok): ?>
+                                                                               <li><strong>Gettext:</strong> You have <code>gettext</code> enabled. <em>No problems here.</em></li>
+                                        
+                                        <?php if ($parse_ini_ok): ?>
+                                        
+                                            <?php if ($filter_ok): ?>
+                                                <li><strong>Data filtering:</strong> You have the PHP filter extension enabled. <em>No problems here.</em></li>
+        
+                                                <?php if ($zlib_ok): ?>
+                                                    <li><strong>Zlib:</strong> You have <code>Zlib</code> enabled.  This allows SimplePie to support GZIP-encoded feeds.  <em>No problems here.</em></li>
+                                                <?php else: ?>
+                                                    <li><strong>Zlib:</strong> The <code>Zlib</code> extension is not available.  SimplePie will ignore any GZIP-encoding, and instead handle feeds as uncompressed text.</li>
+                                                <?php endif; ?>
+                                                
+                                                <?php if ($mbstring_ok && $iconv_ok): ?>
+                                                    <li><strong>mbstring and iconv:</strong> You have both <code>mbstring</code> and <code>iconv</code> installed!  This will allow <?php echo $app_name; ?> to handle the greatest number of languages. <em>No problems here.</em></li>
+                                                <?php elseif ($mbstring_ok): ?>
+                                                    <li><strong>mbstring:</strong> <code>mbstring</code> is installed, but <code>iconv</code> is not.</li>
+                                                <?php elseif ($iconv_ok): ?>
+                                                    <li><strong>iconv:</strong> <code>iconv</code> is installed, but <code>mbstring</code> is not.</li>
+                                                <?php else: ?>
+                                                    <li><strong>mbstring and iconv:</strong> <em>You do not have either of the extensions installed.</em> This will significantly impair your ability to read non-English feeds, as well as even some English ones.</li>
+                                                <?php endif; ?>
+
+                                                <?php if ($tidy_ok): ?>
+                                                    <li><strong>Tidy:</strong> You have <code>Tidy</code> support installed.  <em>No problems here.</em></li>
+                                                <?php else: ?>
+                                                    <li><strong>Tidy:</strong> The <code>Tidy</code> extension is not available.  <?php echo $app_name; ?> should still work with most feeds, but you may experience problems with some.</li>
+                                                <?php endif; ?>
+                                            
+                                                <?php if ($curl_ok): ?>
+                                                    <li><strong>cURL:</strong> You have <code>cURL</code> support installed.  <em>No problems here.</em></li>
+                                                <?php else: ?>
+                                                    <li><strong>cURL:</strong> The <code>cURL</code> extension is not available.  SimplePie will use <code>fsockopen()</code> instead.</li>
+                                                <?php endif; ?>
+                
+                                                <?php if ($parallel_ok): ?>
+                                                    <li><strong>Parallel URL fetching:</strong> You have <code>HttpRequestPool</code> or <code>curl_multi</code> support installed.  <em>No problems here.</em></li>
+                                                <?php else: ?>
+                                                    <li><strong>Parallel URL fetching:</strong> <code>HttpRequestPool</code> or <code>curl_multi</code> support is not available.  <?php echo $app_name; ?> will use <code>file_get_contents()</code> instead to fetch URLs sequentially rather than in parallel.</li>
+                                                <?php endif; ?>
+
+                                            <?php else: ?>
+                                                <li><strong>Data filtering:</strong> Your PHP configuration has the filter extension disabled.  <strong><?php echo $app_name; ?> will not work here.</strong></li>
+                                            <?php endif; ?>
+                                        
+                                        <?php else : ?>
+                                            <li><strong>Parse ini files function :</strong> Bad luck : your webhost has decided to block the use of the <em>parse_ini_file</em> function. <strong><?php echo $app_name; ?> will not work here.</strong>
+                                        <?php endif; ?>
                                                                                
-                                                                               <?php if ($curl_ok): ?>
-                                                                                       <li><strong>cURL:</strong> You have <code>cURL</code> support installed.  <em>No problems here.</em></li>
-                                                                               <?php else: ?>
-                                                                                       <li><strong>cURL:</strong> The <code>cURL</code> extension is not available.  SimplePie will use <code>fsockopen()</code> instead.</li>
-                                                                               <?php endif; ?>
-                       
-                                                                               <?php if ($parallel_ok): ?>
-                                                                                       <li><strong>Parallel URL fetching:</strong> You have <code>HttpRequestPool</code> or <code>curl_multi</code> support installed.  <em>No problems here.</em></li>
-                                                                               <?php else: ?>
-                                                                                       <li><strong>Parallel URL fetching:</strong> <code>HttpRequestPool</code> or <code>curl_multi</code> support is not available.  <?php echo $app_name; ?> will use <code>file_get_contents()</code> instead to fetch URLs sequentially rather than in parallel.</li>
-                                                                               <?php endif; ?>
-
                                                                        <?php else: ?>
-                                                                               <li><strong>Data filtering:</strong> Your PHP configuration has the filter extension disabled.  <em><?php echo $app_name; ?> will not work here.</em></li>
-                                                                       <?php endif; ?>                                                                         
+                                                                               <li><strong>GetText:</strong> The <code>gettext</code> extension is not available. The system we use to display wallabag in various languages is not available. <strong><?php echo $app_name; ?> will not work here.</strong></li>
+                                                                       <?php endif; ?>
                                                                                
                                                                <?php else: ?>
-                                                                       <li><strong>allow_url_fopen:</strong> Your PHP configuration has allow_url_fopen disabled.  <em><?php echo $app_name; ?> will not work here.</em></li>
+                                                                       <li><strong>allow_url_fopen:</strong> Your PHP configuration has allow_url_fopen disabled.  <strong><?php echo $app_name; ?> will not work here.</strong></li>
                                                                <?php endif; ?>
                                                                        
                                                        <?php else: ?>
-                                                               <li><strong>PCRE:</strong> Your PHP installation doesn't support Perl-Compatible Regular Expressions.  <em><?php echo $app_name; ?> will not work here.</em></li>
+                                                               <li><strong>PCRE:</strong> Your PHP installation doesn't support Perl-Compatible Regular Expressions.  <strong><?php echo $app_name; ?> will not work here.</strong></li>
                                                        <?php endif; ?>
                                                <?php else: ?>
-                                                       <li><strong>XML:</strong> Your PHP installation doesn't support XML parsing.  <em><?php echo $app_name; ?> will not work here.</em></li>
+                                                       <li><strong>XML:</strong> Your PHP installation doesn't support XML parsing.  <strong><?php echo $app_name; ?> will not work here.</strong></li>
                                                <?php endif; ?>
                                        <?php else: ?>
-                                               <li><strong>PHP:</strong> You are running an unsupported version of PHP.  <em><?php echo $app_name; ?> will not work here.</em></li>
+                                               <li><strong>PHP:</strong> You are running an unsupported version of PHP.  <strong><?php echo $app_name; ?> will not work here.</strong></li>
                                        <?php endif; ?>
                                <?php endif; ?>
                        </ol>
@@ -310,16 +352,26 @@ div.chunk {
 
                <div class="chunk">
                        <?php //if ($php_ok && $xml_ok && $pcre_ok && $mbstring_ok && $iconv_ok && $filter_ok && $allow_url_fopen_ok) { ?>
-                       <?php if ($php_ok && $xml_ok && $pcre_ok && $filter_ok && $allow_url_fopen_ok) { ?>
+                       <?php if ($php_ok && $xml_ok && $pcre_ok && $filter_ok && $allow_url_fopen_ok && $gettext_ok && $parse_ini_ok) { ?>
                                <h3>Bottom Line: Yes, you can!</h3>
                                <p><em>Your webhost has its act together!</em></p>
+                               <?php if (!$frominstall) { ?>
                                <p>You can download the latest version of <?php echo $app_name; ?> from <a href="http://wallabag.org/download">wallabag.org</a>.</p>
+                               <p>If you already have done that, you should access <a href="index.php">the index.php file</a> of your installation to configure and/or start using wallabag</p>
+                               <?php } else { ?>
+                               <p>You can now <a href="index.php">return to the installation section</a>.</p>
+                               <?php } ?>
                                <p><strong>Note</strong>: Passing this test does not guarantee that <?php echo $app_name; ?> will run on your webhost &mdash; it only ensures that the basic requirements have been addressed. If you experience any problems, please let us know.</p>
                        <?php //} else if ($php_ok && $xml_ok && $pcre_ok && $mbstring_ok && $allow_url_fopen_ok && $filter_ok) { ?>
-                       <?php } else if ($php_ok && $xml_ok && $pcre_ok && $allow_url_fopen_ok && $filter_ok) { ?>
+                       <?php } else if ($php_ok && $xml_ok && $pcre_ok && $allow_url_fopen_ok && $filter_ok && $gettext_ok && $parse_ini_ok) { ?>
                                <h3>Bottom Line: Yes, you can!</h3>
                                <p><em>For most feeds, it'll run with no problems.</em> There are certain languages that you might have a hard time with though.</p>
+                               <?php if (!$frominstall) { ?>
                                <p>You can download the latest version of <?php echo $app_name; ?> from <a href="http://wallabag.org/download">wallabag.org</a>.</p>
+                               <p>If you already have done that, you should access <a href="index.php">the index.php file</a> of your installation to configure and/or start using wallabag</p>
+                               <?php } else { ?>
+                               <p>You can now <a href="index.php">return to the installation section</a>.</p>
+                               <?php } ?>
                                <p><strong>Note</strong>: Passing this test does not guarantee that <?php echo $app_name; ?> will run on your webhost &mdash; it only ensures that the basic requirements have been addressed. If you experience any problems, please let us know.</p>
                        <?php } else { ?>
                                <h3>Bottom Line: We're sorry…</h3>