diff --git a/sources/CHANGELOG b/sources/CHANGELOG
deleted file mode 100644
index 891c85d..0000000
--- a/sources/CHANGELOG
+++ /dev/null
@@ -1,286 +0,0 @@
-1.0.1 - 201610XX
- * Fixed some type of custom column showing id instead of text - Thanks to Mike Schwörer.
- * Fixed the redirection to the OPDS catalog for Moon+ Reader.
- * Fixed the mail character encoding, now in UTF-8.
- * Fixed checkconfig.php to avoid sending content before headers. Thanks to Luke Stevenson.
- * Fixed server side rendering with custom columns.
- * Moved /icons to /images (Apache issues). Thanks to CgX.
-
-1.0.0 - 20160708
- * Updated the OPDS icons to better looking ones. Thanks to Horus68.
- * Updated the README.md.
- * Updated Brazillian, French, Hungarian, Portuguese, Russian translations.
- * Added support of language and country code. This allow to have proper Brazil Portuguese and Portugal Portuguese.
- * Added Korean translation. Thanks to Jin, Heonkyu.
- * Added Romanian translation. Thanks to mtzro2003.
- * Added Greek translation. Thanks to George Litos.
- * Added Turkish Translation. Thanks to Yunus Emre Deligöz.
- * Added Serbian Translation. Thanks to Dalibor Vinkić.
- * Added the transliteration of search text. You can enable it with $config ['cops_normalized_search']. Thanks to George Litos.
- * Added Ebookdroid, Chunky and AlReader in the know OPDS clients. Thanks to Mike Ferenduros and Horus68.
- * Added some mime types for audio books.
- * Added the rewrite rule for IIS.
- * Added a now parameter to set the style ($config['cops_style']). Thanks to Pablo Santiago Blum de Aguiar.
- * Added a directory cache ($config['cops_thumbnail_cache_directory']) to store the resized thumbnails (should help on slow NAS). Thanks to O2 Graphics.
- * Added support of all kind of custom columns (see configuration file). Thanks to Mike Schwörer.
- * Fixed COPS so that it's completely embedded (no external resources to download needed anymore).
- * Fixed a Reflected XSS vulnerability.
- * Fixed the tag filters with Bootstrap. Thanks to Klaus Broelemann.
- * Fixed some COPS path errors with reverse proxy. Thanks to Benjamin Kitt.
- * Fixed the publication date (wasn't working for date before 1901).
- * Fixed the download file name (replace + by %20 to be RFC compliant).
-
-
-1.0.0RC3 - 20141229
- * Fixed server side render with Bootstrap template (a proper unit test was also added).
- * Upgraded to latest doT-php, Typeahead 0.10.5, jquery-cookie 1.4.1, JQuery 1.11.1
- * Fixed book count with custom columns.
- * Updated Catalan, Dutch, French and Russian translations.
- * Added AZW3 to the format that can be sent to Kindle (by mail).
- * Fixed $config['cops_thumbnail_handling'] with bootstrap template.
- * Added Hungarian translation. Thanks to harunibn.
- * Added Ukrainian translation. Thanks to Anatoliy Zavalinich
- * Added full PHP password check (without any need from specific webserver configuration). Thanks to Mark Bond.
- * Added new IOS7 style with default template. Thanks to an anonymous source ;).
- * Fixed display of authors names for books with more than one author.
- * Added PHP version to checkconfig.php (will help debugging for me).
- * Added a configuration item ($config['cops_template']) to change the default template. Thanks to Shin.
- * Added a configuration item ($config['cops_language']) to force COPS language. Thanks to Sandy Pleyte.
- * Added a trick to have user based configuration, check https://github.com/seblucas/cops/wiki/User-based-config for more information. Thanks to Sandy Pleyte.
- * Changed the default sort order on books by author page to show books in a series before all other books.
-
-
-1.0.0RC2 - 20140731
- * Updated Italian, Spanish, Portuguese, Norwegian translations.
- * Added Polish translation. Thanks to macak_pl.
- * Added Haitian Creole translation. Thanks to Ian Macdonald & Jacinta.
- * Added Basque translation. Thanks to Turutarena.
- * Upgraded to JQuery 1.11.0, Magnific Popup 0.9.9, Normalize 3.0.1, Typeahead 0.10.2
- * Fixed search with accentuated characters on Internet Explorer.
- * Author can now be searched by sort or by name (Carroll, Lewis or Lewis Carroll will work).
- * Added a new bootstrap user interface.
- * Added correct mimetype for *.ibooks. Reported by Flowney.
- * Added an empty line at the end of .htaccess to make it easier to modify. Reported by Mariosipad.
- * Modified the README and checkconfig.php to check for php5-json. Reported by Mariosipad.
- * Handled properly the cancelling of a mail. Reported by coach0742.
- * Added an ugly hack to try to fix bad rendering with Kindle. Please report if it's better or not.
-
-1.0.0RC1 - 20140404
- * Updated English, Spanish, German, Italian, Portuguese, Dutch translation files. Huge thanks to all to the translators.
- * Added Swedish translation. Thanks to Bo Rosén.
- * Added Czech translation. Thanks to Zdenek Hadrava.
- * Added a lot of refactoring to simplify the code.
- * Added a lot of new unit tests.
- * Fixed a caching bug causing problems with IE.
- * Added an embedded Epub Reader based on Monocle. Thanks to all the beta testers.
- * Cleaned up a lot of stuff to prepare for bootstrap template. Note to all CSS hackers, the stylesheets are now in templates/default/styles.
- * Fixed the charset of most of the pages. Thanks to edent.
- * Added a new category : ratings. Thanks to Michael.
- * Fixed the URL rewriting in the OPDS stream, should fix file naming with FBReader. Reported by Rassie.
- * Fixed a confusion between author's name and author's sort. Reported by At_Libitum.
- * Fixed the style of the tag filters to show that they're clickable. Thanks to cycojesus.
- * Replaced | by space in author name.
-
-0.9.0 - 20131231
- * Add a lot of unit testing. I hope it will limit the risks of regression.
- * Added a "smart / autocomplete" search.
- * Updated the way locales are handled. Should be easier to add new languages.
- * Fixed display of Cyrillic characters.
- * Upgraded doT to version 1.0.1, Magnific-Popup to 0.9.8, Normalize.css to 2.1.3, Jquery-cookie to 1.4.0.
- * Fixed OPDS stream validity. Reported by Didier.
- * Added a new check in checkconfig.php to detect case problem between the actual path and the path stored in Calibre database. Try checkconfig.php?full=1. Reported by Ruud.
- * Fixed the display of the rating stars with Chrome. Thanks to At_Libitum.
- * Added a new parameter ($config['cops_titles_split_first_letter']) to avoid splitting the books by first letter. Thanks to At_Libitum.
- * Fixed non compliant OPDS search (for Stanza, Moon+ Reader, ...). Reported by At_Libitum.
- * Fixed the redirection in case the Calibre database is not found. Reported by At_Libitum
- * Changed .htaccess to allow the use of password protected catalogs with Sony's eReader (PRS-TX). Thanks to Ruud for the beta testing.
- * Updated Chinese, German, Norwegian, Portuguese, Russian translations. Huge thanks to all the translators.
- * Fixed a small problem : If a book had no summary the cover could be cut.
- * Fix COPS on Internet Explorer 9. Reported by At_Libitum.
- * Added publishers in home categories / search / autocomplete search.
- * Added a new configuration item ($config ['cops_ignored_categories']) to ignore some categories (author, tag, publisher, ...) in home screen and searches. It's also available in the "Customize UI" page.
- * Updated .htaccess to allow downloading books with a password protected COPS on a Sony PRS-TX. Reported by Ruud.
- * Changed the default search to search by categories also (should help with OPDS). Thanks to At_Libitum.
- * Fixed the tag filtering in the HTML catalog when two tags starts by the same word. Reported by Tyler.
-
-0.6.2 - 20130913
- * Added server side rendering for devices like PRS-TX / Kindle / Cybook. Thanks to all the testers.
- * Added a configuration item to tweak how thumbnail are handled.
- * Fixed the click on cog on IOS. Thanks to sb domo.
- * Added dashboard icons / standalone mode for IOS. Thanks to sb domo.
- * Fixed a regression about custom favicon.ico. Thanks to Tyler.
- * Fixed another regression about COPS's version in the about box. Reported by Ian.
- * Upgraded Magnific Popup to v0.9.5.
- * Added a style for IPhone. Thanks to sb domo.
- * Added Portuguese translation. Thanks to Pablo Aguiar.
- * Fixed rendering on Internet Explorer < 9.0.
-
-0.6.1 - 20130730
- * Properly close the lightbox when clicking in a link. Reported by le_.
- * Fix the book by languages list when the language is not found in the resources. Reported by le_.
- * Fix the string for Portuguese. Reported by le_.
- * Add again the series Index in the book list. Reported by fatzgenfatz.
-
-0.6.0 - 20130724
- * COPS HTML catalog now use templated client side rendering. You can build your own template if you want. Should be a lot faster.
- * Fancybox has been replaced by Magnific Popup, it seems faster.
- * Added a way to send book by mail (to send to Kindle or to send to your friends).
- * Added expires instruction in .htaccess (won't crash if you haven't enabled mod_expires).
- * Upgrade to JQuery 1.10.2.
- * Changed the way thumbnails are handled to offer greater visual quality (especially on high pixel density devices : Retina, Nexus, ...).
- * Changed all icon by a vectorial font (again better visual quality).
- * Added a way to filter books by tags.
- * Added a login page (login.html) to allow access to a password protected COPS on a Kobo ereader (that does not support basic auth).
- * Fixed cookie expiry date.
- * Added a default web.config for IIS installation.
- * The eink style doesn't use shadow anymore.
- * Fixed the link to the series in book detail.
-
-0.5.0 - 20130605
- * Upgrade COPS UI to HTML5 / CSS3 to hopefully make it prettier. Most of the code was contributed by Thomas Severinsen.
- * Add the number of books in each databases (when multiple database is enabled).
- * Add Norwegian Bokmål strings. Thanks to Rune Mathisen for the pull request.
- * Add a split by language of catalog. Thanks to Puiu Ionut for the pull request.
- * You can now change the theme and fancybox use on all your devices (You have to enable cookies).
- * Add an eink theme. Thanks to Gregory Bodin for the code.
-
-0.4.0 - 20130507
- * Add multiple database support. Check the documentation of $config['calibre_directory'] in config-default.php to see how to enable it.
- * Include jquery library in COPS's repository to be sure that COPS will work on LAN (without Internet access).
- * Prepare the switch to HTML5. Thanks to Thomas Severinsen for most of the code.
- * Update the locale strings to be more strict with plurals. Thanks to Tobias Ausländer for the code.
- * If Fancybox is not enabled ($config['cops_use_fancyapps'] = "0") then it's not used at all (even in the about box).
- * Fix book comments if it contains UTF8 characters. Reported by Alain.
- * Link to the book permalink was not working correctly in some cases. Reported by celta.
- * Moved some external resources to a resources directory.
- * Add chinese translation. Thanks to wogong for the pull request.
-
-0.3.4 - 20130327
- * Hopefully fix metadata update. Beware you should remove the directory php-epub-meta if you have one. Thanks to Mario for his time.
- * Fix two warnings. Reported by Goner and Mario.
-
-0.3.3 - 20130323
- * Fix catalog if book summary contains bad HTML again :(.
- * Upgrade to Fancybox 2.4.0 and JQuery 1.9.1.
- * Search is now dependant on the page you're in. For now if you're on author page it'll look for author name.
- * Update checkconfig to check if the database provided comes from Calibre.
- * Update to latest php-epub-meta should fix the metadata update with Epub.
- * Fix OPDS catalog with Ibis Reader. It didn't like empty language.
-
-0.3.2 - 20130303
- * Add dutch translation. Provided by Northguy.
- * Fix an ugly bug introduced in 0.3.1. Reported by mariosipad.
- * Small fixes/enhancement to the update metadata tools :
- * The book's name is Author - Title.epub
- * Add the Calibre uuid so that the book is automatically recognised by Calibre.
- * Update the cover
- * Fix display of the HTML catalog on Kobo's browser.
- * Enable kepub.epub download with cover fix (enable with $config['cops_provide_kepub']).
- * Hopefully fix browsing with PRS-T1. Thanks to Northguy.
- * Hopefully fix the OPDS catalog when the summary is full of HTML crap.
- * Merged 3 patches from Tyler J. Wagner :
- * Detect empty publication date set in Calibre to avoid having (0101) as publication year.
- * Don't print "Languages" if there are none defined.
- * Don't print the tag string if there's no tags.
- * If an OPDS client try to access index.php it will be automatically redirected to feed.php.
- * Move the search & sort tool box to a new line (also fix a w3c error).
-
-
-0.3.1 - 20130127
- * Add Facets to the OPDS catalog (check config item cops_books_filter).
- So far the only OPDS client that support facets are Mantano Reader and Bluefire
- * Fix book sort in some list. Patch provided by Tyler J. Wagner.
- * Update .htaccess to check if Xsendfile is available. Thanks to Gaspine for the patch.
- * Add basic support of custom columns. Check the following config item : cops_calibre_custom_column
- * Usage of X-Accel-Redirect / X-Sendfile is not necessary anymore. Warning all Nginx users
- who wants to still use X-Accel-Redirect must add
- $config['cops_x_accel_redirect'] = "X-Accel-Redirect" in their config_local.php
- * Fix COPS on IIS / Windows. Reported by Kevnancy.
- * Simplified config_default.php
- * Add a new config_local.php.example with the minimal configuration item to change.
-
-
-0.3.0 - 20130106
- * Add a config item to avoid using Fancyapps (pop-ups). Reported by mcister and Northguy.
- * Update documentation of .htaccess. Thanks to Stephane.
- * Add a config item to specify a custom icon. Based on a patch by Tyler J. Wagner.
- * Better handling of content type for book. Reported by Morg.
- * Upped the size of thumbnails for OPDS. They look way better with Mantano.
- * Add language in OPDS feed (shown in Mantano for example).
- * Update metadata on downloaded epub. Disabled by default (check config item cops_update_epub-metadata).
- * New Catalan translation provided by David Ciscar Presas.
- * Add a permalink to books, that way direct link to books can be shared. Reported by mcister and Tyler J. Wagner.
- * Add checkconfig.php that should allow to better detect the configuration problem (page in english only for now).
- * Fix some plural strings / some missing title. Reported by David Ciscar Presas.
- * Add an hint about the OPDS catalog in the HTML catalog.
-
-0.2.3 - 20121205
- * Add a .htaccess to make it easier to use with Apache
- * Fix a typo in book download. Reported by jillmess
- * Update localization (thanks to Calibre2Opds)
- * Add some missing information from Calibre (language, rating for now). Reported by mcister
- * Upgrade Fancybox to 2.1.3
-
-
-0.2.2 - 20121020
- * Changed JQuery URL to https (thanks to Dan Greve for the patch)
- * Added paging to both OPDS and HTML catalog (use new config item cops_max_item_per_page)
- * lots of code refactoring
- * Authors are now splitted by first letter, this is the new default. You can go back to the old way with the config item cops_author_split_first_letter (reported by Northguy)
- * Fix the link to books starting by special characters (reported by vinpel)
- * Upgrade to Fancyapps 2.1.0. I had to adapt the CSS so maybe it'll display better in PRS-T1
- * Add an about box on the HTML catalog which show the current version
-
-0.2.1 - 20120916
- * Fix one last error (hopefully) in link generation (thanks to gaspine)
- * Add Sony PRS-T1 to the list of E-Ink device (thanks to Northguy)
- * Fix another HTML special characters problem (thanks to NeilBryant)
- * Add an ugly config parameter to allow search in non-compliant OPDS reader (thanks to Don Caruana and David Lee)
-
-0.2.0 - 20120722
- * Fix all rewriting rule I forgot to change it in last release
- * Fix
in book comment (thanks to jillmess)
- * Fix cover zoom in HTML catalog (you can also navigate through cover with keyboard)
- * Simplify Fancybox transition for e-Ink devices (for now Kobo and Kindle)
-
-0.1.1 - 20120702
- * A lot of bug fixes in HTML catalog
- * Fixed the book comment in OPDS (broken in some rare case)
- * Fixed handling of HTML reserved characters
- * Changed book OPDS id to use an UUID (thanks to ilovejedd for the bug report)
- * Add new config item for the default timezone (thanks to gaspine)
- * Better handling of missing covers
- * Should support every book format supported by Calibre (thanks to Artem)
- * URL rewriting is off by default for the HTML catalog
- * Add some documentation about URL rewriting (thanks to gaspine and Christophe)
- * Tested and ready to use with PHP5.4
-
-0.1.0 - 20120605
- * Add localization support (thanks to Calibre2Opds)
- * Hopefully fixed an issue with & in comment
- * HTML catalog is in the sources with no support (WIP)
-
-0.0.4 - 20120523
- * More code refactoring to simplify code.
- * Changed OPDS Page id to match Calibre2Opds
- * Add icons to author, serie, tags and recent items (there is config item to disable it)
- * Fixed author URL
- * Added publishing date (works on Mantano)
- * Added Tags support
-
-0.0.3 - 20120507
- * Fixed many things blocking opensearch from working
- * There was a bug introduced in 0.0.2
- * The URL can't be relative for Mantano reader, so I added a configuration item.
- * I continued the refactoring to bring HTML to COPS
- * Thumbnails have bigger size (I'll add a configuration item later)
- * Add headers to help caching image and thumbnail to the browser
- *
-
-0.0.2 - 20120411
- * Add support for MOBI and PDF
- * Major refactoring to prepare something nice for the future ;)
- * Add a config item to make use of X-Sendfile instead of X-Accel-Redirect if needed
-
-0.0.1 - 20120302
- * First public release
diff --git a/sources/COPYING b/sources/COPYING
deleted file mode 100644
index d60c31a..0000000
--- a/sources/COPYING
+++ /dev/null
@@ -1,340 +0,0 @@
- GNU GENERAL PUBLIC LICENSE
- Version 2, June 1991
-
- Copyright (C) 1989, 1991 Free Software Foundation, Inc.
- 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
- Preamble
-
- The licenses for most software are designed to take away your
-freedom to share and change it. By contrast, the GNU General Public
-License is intended to guarantee your freedom to share and change free
-software--to make sure the software is free for all its users. This
-General Public License applies to most of the Free Software
-Foundation's software and to any other program whose authors commit to
-using it. (Some other Free Software Foundation software is covered by
-the GNU Library General Public License instead.) You can apply it to
-your programs, too.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-this service if you wish), that you receive source code or can get it
-if you want it, that you can change the software or use pieces of it
-in new free programs; and that you know you can do these things.
-
- To protect your rights, we need to make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if you
-distribute copies of the software, or if you modify it.
-
- For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must give the recipients all the rights that
-you have. You must make sure that they, too, receive or can get the
-source code. And you must show them these terms so they know their
-rights.
-
- We protect your rights with two steps: (1) copyright the software, and
-(2) offer you this license which gives you legal permission to copy,
-distribute and/or modify the software.
-
- Also, for each author's protection and ours, we want to make certain
-that everyone understands that there is no warranty for this free
-software. If the software is modified by someone else and passed on, we
-want its recipients to know that what they have is not the original, so
-that any problems introduced by others will not reflect on the original
-authors' reputations.
-
- Finally, any free program is threatened constantly by software
-patents. We wish to avoid the danger that redistributors of a free
-program will individually obtain patent licenses, in effect making the
-program proprietary. To prevent this, we have made it clear that any
-patent must be licensed for everyone's free use or not licensed at all.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- GNU GENERAL PUBLIC LICENSE
- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
- 0. This License applies to any program or other work which contains
-a notice placed by the copyright holder saying it may be distributed
-under the terms of this General Public License. The "Program", below,
-refers to any such program or work, and a "work based on the Program"
-means either the Program or any derivative work under copyright law:
-that is to say, a work containing the Program or a portion of it,
-either verbatim or with modifications and/or translated into another
-language. (Hereinafter, translation is included without limitation in
-the term "modification".) Each licensee is addressed as "you".
-
-Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope. The act of
-running the Program is not restricted, and the output from the Program
-is covered only if its contents constitute a work based on the
-Program (independent of having been made by running the Program).
-Whether that is true depends on what the Program does.
-
- 1. You may copy and distribute verbatim copies of the Program's
-source code as you receive it, in any medium, provided that you
-conspicuously and appropriately publish on each copy an appropriate
-copyright notice and disclaimer of warranty; keep intact all the
-notices that refer to this License and to the absence of any warranty;
-and give any other recipients of the Program a copy of this License
-along with the Program.
-
-You may charge a fee for the physical act of transferring a copy, and
-you may at your option offer warranty protection in exchange for a fee.
-
- 2. You may modify your copy or copies of the Program or any portion
-of it, thus forming a work based on the Program, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
- a) You must cause the modified files to carry prominent notices
- stating that you changed the files and the date of any change.
-
- b) You must cause any work that you distribute or publish, that in
- whole or in part contains or is derived from the Program or any
- part thereof, to be licensed as a whole at no charge to all third
- parties under the terms of this License.
-
- c) If the modified program normally reads commands interactively
- when run, you must cause it, when started running for such
- interactive use in the most ordinary way, to print or display an
- announcement including an appropriate copyright notice and a
- notice that there is no warranty (or else, saying that you provide
- a warranty) and that users may redistribute the program under
- these conditions, and telling the user how to view a copy of this
- License. (Exception: if the Program itself is interactive but
- does not normally print such an announcement, your work based on
- the Program is not required to print an announcement.)
-
-These requirements apply to the modified work as a whole. If
-identifiable sections of that work are not derived from the Program,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works. But when you
-distribute the same sections as part of a whole which is a work based
-on the Program, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Program.
-
-In addition, mere aggregation of another work not based on the Program
-with the Program (or with a work based on the Program) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
- 3. You may copy and distribute the Program (or a work based on it,
-under Section 2) in object code or executable form under the terms of
-Sections 1 and 2 above provided that you also do one of the following:
-
- a) Accompany it with the complete corresponding machine-readable
- source code, which must be distributed under the terms of Sections
- 1 and 2 above on a medium customarily used for software interchange; or,
-
- b) Accompany it with a written offer, valid for at least three
- years, to give any third party, for a charge no more than your
- cost of physically performing source distribution, a complete
- machine-readable copy of the corresponding source code, to be
- distributed under the terms of Sections 1 and 2 above on a medium
- customarily used for software interchange; or,
-
- c) Accompany it with the information you received as to the offer
- to distribute corresponding source code. (This alternative is
- allowed only for noncommercial distribution and only if you
- received the program in object code or executable form with such
- an offer, in accord with Subsection b above.)
-
-The source code for a work means the preferred form of the work for
-making modifications to it. For an executable work, complete source
-code means all the source code for all modules it contains, plus any
-associated interface definition files, plus the scripts used to
-control compilation and installation of the executable. However, as a
-special exception, the source code distributed need not include
-anything that is normally distributed (in either source or binary
-form) with the major components (compiler, kernel, and so on) of the
-operating system on which the executable runs, unless that component
-itself accompanies the executable.
-
-If distribution of executable or object code is made by offering
-access to copy from a designated place, then offering equivalent
-access to copy the source code from the same place counts as
-distribution of the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
- 4. You may not copy, modify, sublicense, or distribute the Program
-except as expressly provided under this License. Any attempt
-otherwise to copy, modify, sublicense or distribute the Program is
-void, and will automatically terminate your rights under this License.
-However, parties who have received copies, or rights, from you under
-this License will not have their licenses terminated so long as such
-parties remain in full compliance.
-
- 5. You are not required to accept this License, since you have not
-signed it. However, nothing else grants you permission to modify or
-distribute the Program or its derivative works. These actions are
-prohibited by law if you do not accept this License. Therefore, by
-modifying or distributing the Program (or any work based on the
-Program), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Program or works based on it.
-
- 6. Each time you redistribute the Program (or any work based on the
-Program), the recipient automatically receives a license from the
-original licensor to copy, distribute or modify the Program subject to
-these terms and conditions. You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties to
-this License.
-
- 7. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Program at all. For example, if a patent
-license would not permit royalty-free redistribution of the Program by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Program.
-
-If any portion of this section is held invalid or unenforceable under
-any particular circumstance, the balance of the section is intended to
-apply and the section as a whole is intended to apply in other
-circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system, which is
-implemented by public license practices. Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
- 8. If the distribution and/or use of the Program is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Program under this License
-may add an explicit geographical distribution limitation excluding
-those countries, so that distribution is permitted only in or among
-countries not thus excluded. In such case, this License incorporates
-the limitation as if written in the body of this License.
-
- 9. The Free Software Foundation may publish revised and/or new versions
-of the General Public License from time to time. Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
-Each version is given a distinguishing version number. If the Program
-specifies a version number of this License which applies to it and "any
-later version", you have the option of following the terms and conditions
-either of that version or of any later version published by the Free
-Software Foundation. If the Program does not specify a version number of
-this License, you may choose any version ever published by the Free Software
-Foundation.
-
- 10. If you wish to incorporate parts of the Program into other free
-programs whose distribution conditions are different, write to the author
-to ask for permission. For software which is copyrighted by the Free
-Software Foundation, write to the Free Software Foundation; we sometimes
-make exceptions for this. Our decision will be guided by the two goals
-of preserving the free status of all derivatives of our free software and
-of promoting the sharing and reuse of software generally.
-
- NO WARRANTY
-
- 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
-FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
-OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
-PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
-OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
-TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
-PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
-REPAIR OR CORRECTION.
-
- 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
-REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
-INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
-OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
-TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
-YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
-PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
-POSSIBILITY OF SUCH DAMAGES.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
-
- Copyright (C)
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-
-Also add information on how to contact you by electronic and paper mail.
-
-If the program is interactive, make it output a short notice like this
-when it starts in an interactive mode:
-
- Gnomovision version 69, Copyright (C) year name of author
- Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
- This is free software, and you are welcome to redistribute it
- under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License. Of course, the commands you use may
-be called something other than `show w' and `show c'; they could even be
-mouse-clicks or menu items--whatever suits your program.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the program, if
-necessary. Here is a sample; alter the names:
-
- Yoyodyne, Inc., hereby disclaims all copyright interest in the program
- `Gnomovision' (which makes passes at compilers) written by James Hacker.
-
- , 1 April 1989
- Ty Coon, President of Vice
-
-This General Public License does not permit incorporating your program into
-proprietary programs. If your program is a subroutine library, you may
-consider it more useful to permit linking proprietary applications with the
-library. If this is what you want to do, use the GNU Library General
-Public License instead of this License.
diff --git a/sources/JSON_renderer.php b/sources/JSON_renderer.php
deleted file mode 100644
index ecca867..0000000
--- a/sources/JSON_renderer.php
+++ /dev/null
@@ -1,255 +0,0 @@
-
- */
-
-require_once ("base.php");
-require_once ("book.php");
-
-class JSONRenderer
-{
- /**
- * @param Book $book
- * @return array
- */
- public static function getBookContentArray ($book) {
- global $config;
- $i = 0;
- $preferedData = array ();
- foreach ($config['cops_prefered_format'] as $format)
- {
- if ($i == 2) { break; }
- if ($data = $book->getDataFormat ($format)) {
- $i++;
- array_push ($preferedData, array ("url" => $data->getHtmlLink (), "name" => $format));
- }
- }
-
- $publisher = $book->getPublisher();
- if (is_null ($publisher)) {
- $pn = "";
- $pu = "";
- } else {
- $pn = $publisher->name;
- $link = new LinkNavigation ($publisher->getUri ());
- $pu = $link->hrefXhtml ();
- }
-
- $serie = $book->getSerie ();
- if (is_null ($serie)) {
- $sn = "";
- $scn = "";
- $su = "";
- } else {
- $sn = $serie->name;
- $scn = str_format (localize ("content.series.data"), $book->seriesIndex, $serie->name);
- $link = new LinkNavigation ($serie->getUri ());
- $su = $link->hrefXhtml ();
- }
- $cc = $book->getCustomColumnValues($config['cops_calibre_custom_column_list'], true);
-
- return array ("id" => $book->id,
- "hasCover" => $book->hasCover,
- "preferedData" => $preferedData,
- "rating" => $book->getRating (),
- "publisherName" => $pn,
- "publisherurl" => $pu,
- "pubDate" => $book->getPubDate (),
- "languagesName" => $book->getLanguages (),
- "authorsName" => $book->getAuthorsName (),
- "tagsName" => $book->getTagsName (),
- "seriesName" => $sn,
- "seriesIndex" => $book->seriesIndex,
- "seriesCompleteName" => $scn,
- "seriesurl" => $su,
- "customcolumns_list" => $cc);
- }
-
- /**
- * @param Book $book
- * @return array
- */
- public static function getFullBookContentArray ($book) {
- global $config;
- $out = self::getBookContentArray ($book);
- $database = GetUrlParam (DB);
-
- $out ["coverurl"] = Data::getLink ($book, "jpg", "image/jpeg", Link::OPDS_IMAGE_TYPE, "cover.jpg", NULL)->hrefXhtml ();
- $out ["thumbnailurl"] = Data::getLink ($book, "jpg", "image/jpeg", Link::OPDS_THUMBNAIL_TYPE, "cover.jpg", NULL, NULL, $config['cops_html_thumbnail_height'] * 2)->hrefXhtml ();
- $out ["content"] = $book->getComment (false);
- $out ["datas"] = array ();
- $dataKindle = $book->GetMostInterestingDataToSendToKindle ();
- foreach ($book->getDatas() as $data) {
- $tab = array ("id" => $data->id, "format" => $data->format, "url" => $data->getHtmlLink (), "mail" => 0, "readerUrl" => "");
- if (!empty ($config['cops_mail_configuration']) && !is_null ($dataKindle) && $data->id == $dataKindle->id) {
- $tab ["mail"] = 1;
- }
- if ($data->format == "EPUB") {
- $tab ["readerUrl"] = "epubreader.php?data={$data->id}&db={$database}";
- }
- array_push ($out ["datas"], $tab);
- }
- $out ["authors"] = array ();
- foreach ($book->getAuthors () as $author) {
- $link = new LinkNavigation ($author->getUri ());
- array_push ($out ["authors"], array ("name" => $author->name, "url" => $link->hrefXhtml ()));
- }
- $out ["tags"] = array ();
- foreach ($book->getTags () as $tag) {
- $link = new LinkNavigation ($tag->getUri ());
- array_push ($out ["tags"], array ("name" => $tag->name, "url" => $link->hrefXhtml ()));
- }
- $out ["customcolumns_preview"] = $book->getCustomColumnValues($config['cops_calibre_custom_column_preview'], true);
-
- return $out;
- }
-
- public static function getContentArray ($entry) {
- if ($entry instanceof EntryBook) {
- $out = array ( "title" => $entry->title);
- $out ["book"] = self::getBookContentArray ($entry->book);
- return $out;
- }
- return array ( "title" => $entry->title, "content" => $entry->content, "navlink" => $entry->getNavLink (), "number" => $entry->numberOfElement );
- }
-
- public static function getContentArrayTypeahead ($page) {
- $out = array ();
- foreach ($page->entryArray as $entry) {
- if ($entry instanceof EntryBook) {
- array_push ($out, array ("class" => $entry->className, "title" => $entry->title, "navlink" => $entry->book->getDetailUrl ()));
- } else {
- if (empty ($entry->className) xor Base::noDatabaseSelected ()) {
- array_push ($out, array ("class" => $entry->className, "title" => $entry->title, "navlink" => $entry->getNavLink ()));
- } else {
- array_push ($out, array ("class" => $entry->className, "title" => $entry->content, "navlink" => $entry->getNavLink ()));
- }
- }
- }
- return $out;
- }
-
- public static function addCompleteArray ($in) {
- global $config;
- $out = $in;
-
- $out ["c"] = array ("version" => VERSION, "i18n" => array (
- "coverAlt" => localize("i18n.coversection"),
- "authorsTitle" => localize("authors.title"),
- "bookwordTitle" => localize("bookword.title"),
- "tagsTitle" => localize("tags.title"),
- "seriesTitle" => localize("series.title"),
- "customizeTitle" => localize ("customize.title"),
- "aboutTitle" => localize ("about.title"),
- "previousAlt" => localize ("paging.previous.alternate"),
- "nextAlt" => localize ("paging.next.alternate"),
- "searchAlt" => localize ("search.alternate"),
- "sortAlt" => localize ("sort.alternate"),
- "homeAlt" => localize ("home.alternate"),
- "cogAlt" => localize ("cog.alternate"),
- "permalinkAlt" => localize ("permalink.alternate"),
- "publisherName" => localize("publisher.name"),
- "pubdateTitle" => localize("pubdate.title"),
- "languagesTitle" => localize("language.title"),
- "contentTitle" => localize("content.summary"),
- "sortorderAsc" => localize("search.sortorder.asc"),
- "sortorderDesc" => localize("search.sortorder.desc"),
- "customizeEmail" => localize("customize.email")),
- "url" => array (
- "detailUrl" => "index.php?page=13&id={0}&db={1}",
- "coverUrl" => "fetch.php?id={0}&db={1}",
- "thumbnailUrl" => "fetch.php?height=" . $config['cops_html_thumbnail_height'] . "&id={0}&db={1}"),
- "config" => array (
- "use_fancyapps" => $config ["cops_use_fancyapps"],
- "max_item_per_page" => $config['cops_max_item_per_page'],
- "kindleHack" => "",
- "server_side_rendering" => useServerSideRendering (),
- "html_tag_filter" => $config['cops_html_tag_filter']));
- if ($config['cops_thumbnail_handling'] == "1") {
- $out ["c"]["url"]["thumbnailUrl"] = $out ["c"]["url"]["coverUrl"];
- } else if (!empty ($config['cops_thumbnail_handling'])) {
- $out ["c"]["url"]["thumbnailUrl"] = $config['cops_thumbnail_handling'];
- }
- if (preg_match("/./", $_SERVER['HTTP_USER_AGENT'])) {
- $out ["c"]["config"]["kindleHack"] = 'style="text-decoration: none !important;"';
- }
- return $out;
- }
-
- public static function getJson ($complete = false) {
- global $config;
- $page = getURLParam ("page", Base::PAGE_INDEX);
- $query = getURLParam ("query");
- $search = getURLParam ("search");
- $qid = getURLParam ("id");
- $n = getURLParam ("n", "1");
- $database = GetUrlParam (DB);
-
- $currentPage = Page::getPage ($page, $qid, $query, $n);
- $currentPage->InitializeContent ();
-
- if ($search) {
- return self::getContentArrayTypeahead ($currentPage);
- }
-
- $out = array ( "title" => $currentPage->title);
- $entries = array ();
- foreach ($currentPage->entryArray as $entry) {
- array_push ($entries, self::getContentArray ($entry));
- }
- if (!is_null ($currentPage->book)) {
- $out ["book"] = self::getFullBookContentArray ($currentPage->book);
- }
- $out ["databaseId"] = GetUrlParam (DB, "");
- $out ["databaseName"] = Base::getDbName ();
- if ($out ["databaseId"] == "") {
- $out ["databaseName"] = "";
- }
- $out ["fullTitle"] = $out ["title"];
- if ($out ["databaseId"] != "" && $out ["databaseName"] != $out ["fullTitle"]) {
- $out ["fullTitle"] = $out ["databaseName"] . " > " . $out ["fullTitle"];
- }
- $out ["page"] = $page;
- $out ["multipleDatabase"] = Base::isMultipleDatabaseEnabled () ? 1 : 0;
- $out ["entries"] = $entries;
- $out ["isPaginated"] = 0;
- if ($currentPage->isPaginated ()) {
- $prevLink = $currentPage->getPrevLink ();
- $nextLink = $currentPage->getNextLink ();
- $out ["isPaginated"] = 1;
- $out ["prevLink"] = "";
- if (!is_null ($prevLink)) {
- $out ["prevLink"] = $prevLink->hrefXhtml ();
- }
- $out ["nextLink"] = "";
- if (!is_null ($nextLink)) {
- $out ["nextLink"] = $nextLink->hrefXhtml ();
- }
- $out ["maxPage"] = $currentPage->getMaxPage ();
- $out ["currentPage"] = $currentPage->n;
- }
- if (!is_null (getURLParam ("complete")) || $complete) {
- $out = self::addCompleteArray ($out);
- }
-
- $out ["containsBook"] = 0;
- if ($currentPage->containsBook ()) {
- $out ["containsBook"] = 1;
- }
-
- $out["abouturl"] = "index.php" . addURLParameter ("?page=" . Base::PAGE_ABOUT, DB, $database);
-
- if ($page == Base::PAGE_ABOUT) {
- $temp = preg_replace ("/\
About COPS\<\/h1\>/", "
About COPS " . VERSION . "
", file_get_contents('about.html'));
- $out ["fullhtml"] = $temp;
- }
-
- $out ["homeurl"] = "index.php";
- if ($page != Base::PAGE_INDEX && !is_null ($database)) $out ["homeurl"] = $out ["homeurl"] . "?" . addURLParameter ("", DB, $database);
-
- return $out;
- }
-}
\ No newline at end of file
diff --git a/sources/OPDS_renderer.php b/sources/OPDS_renderer.php
deleted file mode 100644
index 14d1f33..0000000
--- a/sources/OPDS_renderer.php
+++ /dev/null
@@ -1,278 +0,0 @@
-
- */
-
-require_once ("base.php");
-
-class OPDSRenderer
-{
- private $xmlStream = NULL;
- private $updated = NULL;
-
- private function getUpdatedTime () {
- if (is_null ($this->updated)) {
- $this->updated = time();
- }
- return date (DATE_ATOM, $this->updated);
- }
-
- private function getXmlStream () {
- if (is_null ($this->xmlStream)) {
- $this->xmlStream = new XMLWriter();
- $this->xmlStream->openMemory();
- $this->xmlStream->setIndent (true);
- }
- return $this->xmlStream;
- }
-
- public function getOpenSearch () {
- global $config;
- $xml = new XMLWriter ();
- $xml->openMemory ();
- $xml->setIndent (true);
- $xml->startDocument('1.0','UTF-8');
- $xml->startElement ("OpenSearchDescription");
- $xml->writeAttribute ("xmlns", "http://a9.com/-/spec/opensearch/1.1/");
- $xml->startElement ("ShortName");
- $xml->text ("My catalog");
- $xml->endElement ();
- $xml->startElement ("Description");
- $xml->text ("Search for ebooks");
- $xml->endElement ();
- $xml->startElement ("InputEncoding");
- $xml->text ("UTF-8");
- $xml->endElement ();
- $xml->startElement ("OutputEncoding");
- $xml->text ("UTF-8");
- $xml->endElement ();
- $xml->startElement ("Image");
- $xml->writeAttribute ("type", "image/x-icon");
- $xml->writeAttribute ("width", "16");
- $xml->writeAttribute ("height", "16");
- $xml->text ($config['cops_icon']);
- $xml->endElement ();
- $xml->startElement ("Url");
- $xml->writeAttribute ("type", 'application/atom+xml');
- $urlparam = "?query={searchTerms}";
- if (!is_null (GetUrlParam (DB))) $urlparam = addURLParameter ($urlparam, DB, GetUrlParam (DB));
- $urlparam = str_replace ("%7B", "{", $urlparam);
- $urlparam = str_replace ("%7D", "}", $urlparam);
- $xml->writeAttribute ("template", $config['cops_full_url'] . 'feed.php' . $urlparam);
- $xml->endElement ();
- $xml->startElement ("Query");
- $xml->writeAttribute ("role", "example");
- $xml->writeAttribute ("searchTerms", "robot");
- $xml->endElement ();
- $xml->endElement ();
- $xml->endDocument();
- return $xml->outputMemory(true);
- }
-
- private function startXmlDocument ($page) {
- global $config;
- self::getXmlStream ()->startDocument('1.0','UTF-8');
- self::getXmlStream ()->startElement ("feed");
- self::getXmlStream ()->writeAttribute ("xmlns", "http://www.w3.org/2005/Atom");
- self::getXmlStream ()->writeAttribute ("xmlns:xhtml", "http://www.w3.org/1999/xhtml");
- self::getXmlStream ()->writeAttribute ("xmlns:opds", "http://opds-spec.org/2010/catalog");
- self::getXmlStream ()->writeAttribute ("xmlns:opensearch", "http://a9.com/-/spec/opensearch/1.1/");
- self::getXmlStream ()->writeAttribute ("xmlns:dcterms", "http://purl.org/dc/terms/");
- self::getXmlStream ()->startElement ("title");
- self::getXmlStream ()->text ($page->title);
- self::getXmlStream ()->endElement ();
- if ($page->subtitle != "")
- {
- self::getXmlStream ()->startElement ("subtitle");
- self::getXmlStream ()->text ($page->subtitle);
- self::getXmlStream ()->endElement ();
- }
- self::getXmlStream ()->startElement ("id");
- if ($page->idPage)
- {
- $idPage = $page->idPage;
- if (!is_null (GetUrlParam (DB))) $idPage = str_replace ("cops:", "cops:" . GetUrlParam (DB) . ":", $idPage);
- self::getXmlStream ()->text ($idPage);
- }
- else
- {
- self::getXmlStream ()->text ($_SERVER['REQUEST_URI']);
- }
- self::getXmlStream ()->endElement ();
- self::getXmlStream ()->startElement ("updated");
- self::getXmlStream ()->text (self::getUpdatedTime ());
- self::getXmlStream ()->endElement ();
- self::getXmlStream ()->startElement ("icon");
- self::getXmlStream ()->text ($page->favicon);
- self::getXmlStream ()->endElement ();
- self::getXmlStream ()->startElement ("author");
- self::getXmlStream ()->startElement ("name");
- self::getXmlStream ()->text ($page->authorName);
- self::getXmlStream ()->endElement ();
- self::getXmlStream ()->startElement ("uri");
- self::getXmlStream ()->text ($page->authorUri);
- self::getXmlStream ()->endElement ();
- self::getXmlStream ()->startElement ("email");
- self::getXmlStream ()->text ($page->authorEmail);
- self::getXmlStream ()->endElement ();
- self::getXmlStream ()->endElement ();
- $link = new LinkNavigation ("", "start", "Home");
- self::renderLink ($link);
- $link = new LinkNavigation ("?" . getQueryString (), "self");
- self::renderLink ($link);
- $urlparam = "?";
- if (!is_null (GetUrlParam (DB))) $urlparam = addURLParameter ($urlparam, DB, GetUrlParam (DB));
- if ($config['cops_generate_invalid_opds_stream'] == 0 || preg_match("/(MantanoReader|FBReader)/", $_SERVER['HTTP_USER_AGENT'])) {
- // Good and compliant way of handling search
- $urlparam = addURLParameter ($urlparam, "page", Base::PAGE_OPENSEARCH);
- $link = new Link ("feed.php" . $urlparam, "application/opensearchdescription+xml", "search", "Search here");
- }
- else
- {
- // Bad way, will be removed when OPDS client are fixed
- $urlparam = addURLParameter ($urlparam, "query", "{searchTerms}");
- $urlparam = str_replace ("%7B", "{", $urlparam);
- $urlparam = str_replace ("%7D", "}", $urlparam);
- $link = new Link ($config['cops_full_url'] . 'feed.php' . $urlparam, "application/atom+xml", "search", "Search here");
- }
- self::renderLink ($link);
- if ($page->containsBook () && !is_null ($config['cops_books_filter']) && count ($config['cops_books_filter']) > 0) {
- $Urlfilter = getURLParam ("tag", "");
- foreach ($config['cops_books_filter'] as $lib => $filter) {
- $link = new LinkFacet ("?" . addURLParameter (getQueryString (), "tag", $filter), $lib, localize ("tagword.title"), $filter == $Urlfilter);
- self::renderLink ($link);
- }
- }
- }
-
- private function endXmlDocument () {
- self::getXmlStream ()->endElement ();
- self::getXmlStream ()->endDocument ();
- return self::getXmlStream ()->outputMemory(true);
- }
-
- private function renderLink ($link) {
- self::getXmlStream ()->startElement ("link");
- self::getXmlStream ()->writeAttribute ("href", $link->href);
- self::getXmlStream ()->writeAttribute ("type", $link->type);
- if (!is_null ($link->rel)) {
- self::getXmlStream ()->writeAttribute ("rel", $link->rel);
- }
- if (!is_null ($link->title)) {
- self::getXmlStream ()->writeAttribute ("title", $link->title);
- }
- if (!is_null ($link->facetGroup)) {
- self::getXmlStream ()->writeAttribute ("opds:facetGroup", $link->facetGroup);
- }
- if ($link->activeFacet) {
- self::getXmlStream ()->writeAttribute ("opds:activeFacet", "true");
- }
- self::getXmlStream ()->endElement ();
- }
-
- private function getPublicationDate($book) {
- $dateYmd = substr($book->pubdate, 0, 10);
- $pubdate = \DateTime::createFromFormat('Y-m-d', $dateYmd);
- if ($pubdate === false ||
- $pubdate->format ("Y") == "0101" ||
- $pubdate->format ("Y") == "0100") {
- return "";
- }
- return $pubdate->format("Y-m-d");
- }
-
- private function renderEntry ($entry) {
- self::getXmlStream ()->startElement ("title");
- self::getXmlStream ()->text ($entry->title);
- self::getXmlStream ()->endElement ();
- self::getXmlStream ()->startElement ("updated");
- self::getXmlStream ()->text (self::getUpdatedTime ());
- self::getXmlStream ()->endElement ();
- self::getXmlStream ()->startElement ("id");
- self::getXmlStream ()->text ($entry->id);
- self::getXmlStream ()->endElement ();
- self::getXmlStream ()->startElement ("content");
- self::getXmlStream ()->writeAttribute ("type", $entry->contentType);
- if ($entry->contentType == "text") {
- self::getXmlStream ()->text ($entry->content);
- } else {
- self::getXmlStream ()->writeRaw ($entry->content);
- }
- self::getXmlStream ()->endElement ();
- foreach ($entry->linkArray as $link) {
- self::renderLink ($link);
- }
-
- if (get_class ($entry) != "EntryBook") {
- return;
- }
-
- foreach ($entry->book->getAuthors () as $author) {
- self::getXmlStream ()->startElement ("author");
- self::getXmlStream ()->startElement ("name");
- self::getXmlStream ()->text ($author->name);
- self::getXmlStream ()->endElement ();
- self::getXmlStream ()->startElement ("uri");
- self::getXmlStream ()->text ("feed.php" . $author->getUri ());
- self::getXmlStream ()->endElement ();
- self::getXmlStream ()->endElement ();
- }
- foreach ($entry->book->getTags () as $category) {
- self::getXmlStream ()->startElement ("category");
- self::getXmlStream ()->writeAttribute ("term", $category->name);
- self::getXmlStream ()->writeAttribute ("label", $category->name);
- self::getXmlStream ()->endElement ();
- }
- if ($entry->book->getPubDate () != "") {
- self::getXmlStream ()->startElement ("dcterms:issued");
- self::getXmlStream ()->text (self::getPublicationDate($entry->book));
- self::getXmlStream ()->endElement ();
- self::getXmlStream ()->startElement ("published");
- self::getXmlStream ()->text (self::getPublicationDate($entry->book) . "T08:08:08Z");
- self::getXmlStream ()->endElement ();
- }
-
- $lang = $entry->book->getLanguages ();
- if (!empty ($lang)) {
- self::getXmlStream ()->startElement ("dcterms:language");
- self::getXmlStream ()->text ($lang);
- self::getXmlStream ()->endElement ();
- }
-
- }
-
- public function render ($page) {
- global $config;
- self::startXmlDocument ($page);
- if ($page->isPaginated ())
- {
- self::getXmlStream ()->startElement ("opensearch:totalResults");
- self::getXmlStream ()->text ($page->totalNumber);
- self::getXmlStream ()->endElement ();
- self::getXmlStream ()->startElement ("opensearch:itemsPerPage");
- self::getXmlStream ()->text ($config['cops_max_item_per_page']);
- self::getXmlStream ()->endElement ();
- self::getXmlStream ()->startElement ("opensearch:startIndex");
- self::getXmlStream ()->text (($page->n - 1) * $config['cops_max_item_per_page'] + 1);
- self::getXmlStream ()->endElement ();
- $prevLink = $page->getPrevLink ();
- $nextLink = $page->getNextLink ();
- if (!is_null ($prevLink)) {
- self::renderLink ($prevLink);
- }
- if (!is_null ($nextLink)) {
- self::renderLink ($nextLink);
- }
- }
- foreach ($page->entryArray as $entry) {
- self::getXmlStream ()->startElement ("entry");
- self::renderEntry ($entry);
- self::getXmlStream ()->endElement ();
- }
- return self::endXmlDocument ();
- }
-}
-
diff --git a/sources/README.md b/sources/README.md
deleted file mode 100644
index 526c220..0000000
--- a/sources/README.md
+++ /dev/null
@@ -1,101 +0,0 @@
-# COPS
-
-COPS stands for Calibre OPDS (and HTML) Php Server.
-
-See : [COPS's home](http://blog.slucas.fr/en/oss/calibre-opds-php-server) for more details.
-
-Don't forget to check the [Wiki](https://github.com/seblucas/cops/wiki).
-
-[![Scrutinizer Quality Score](https://scrutinizer-ci.com/g/seblucas/cops/badges/quality-score.png?s=e1c87a92ef90b8d666cd9bd4f3612bd10db84364)](https://scrutinizer-ci.com/g/seblucas/cops/)
-
-[![Code Coverage](https://scrutinizer-ci.com/g/seblucas/cops/badges/coverage.png?s=1e21d8c3bf96d7b0b7cc0e54429fa897ddea1506)](https://scrutinizer-ci.com/g/seblucas/cops/)
-
-[![Build Status](https://travis-ci.org/seblucas/cops.png)](https://travis-ci.org/seblucas/cops)
-
-[![Selenium Test Status](https://saucelabs.com/browser-matrix/seblucas.svg)](https://saucelabs.com/u/seblucas)
-
-# Why ?
-
-In my opinion Calibre is a marvelous tool but is too big and has too much
-dependencies to be used for its content server.
-
-That's the main reason why I coded this OPDS server. I needed a simple
-tool to be installed on a small server (Seagate Dockstar in my case).
-
-I initially thought of Calibre2OPDS but as it generate static file no
-search was possible.
-
-Later I added an simple HTML catalog that should be usable on my Kobo.
-
-So COPS's main advantages are :
- * No need for many dependencies.
- * No need for a lot of CPU or RAM.
- * Not much code.
- * Search is available.
- * With Dropbox / owncloud it's very easy to have an up to date OPDS server.
- * It was fun to code.
-
-If you want to use the OPDS feed don't forget to specify feed.php at the end of your URL.
-
-# Prerequisites
-
-1. PHP 5.3, 5.4, 5.5, 5.6 or hhvm with GD image processing, Libxml, Intl, Json & SQLite3 support.
-2. A web server with PHP support. I only tested with various version of Nginx.
- Other people reported it working with Apache and Cherokee. You can also use PHP
- embedded server (https://github.com/seblucas/cops/wiki/Howto---PhpEmbeddedServer)
-3. The path to a calibre library (metadata.db, format, & cover files).
-
-On any Debian base Linux you can use :
- aptitude install php5-gd php5-sqlite php5-json php5-intl
-
-On Centos you may have to add :
- yum install php-xml
-
-# Install
-
-1. Extract the zip file to a folder in web space (visible to the web server).
-2. If you're doing a first-time install, copy config_local.php.example to config_local.php
-3. Edit config_local.php to match your config.
-4. If needed add other configuration item from config_default.php
-
-If you choose to put your Calibre directory inside your web directory then you
-will have to edit /etc/nginx/mime.types to add this line :
-application/epub+zip epub;
-
-If you like Docker, you can also try [this project](https://github.com/linuxserver/docker-cops)
-
-# Known problems
-
-Not a lot, except for the bad quality of the code (first PHP project ever) ;)
-
-Please see https://github.com/seblucas/cops/issues for open issues
-
-# Need help
-
-Please read https://github.com/seblucas/cops/wiki and check the FAQ.
-
-# Credits
-
- * Locale message handling is inspired of http://www.mind-it.info/2010/02/22/a-simple-approach-to-localization-in-php/
- * str_format function come from http://tmont.com/blargh/2010/1/string-format-in-php
- * All icons come from Font Awesome : http://fontawesome.github.io/Font-Awesome/
- * The unofficial OPDS validator : http://opds-validator.appspot.com/
- * Thanks to all testers, translators and contributors.
- * Feed icons made by Freepik from Flaticon website licensed under Creative Commons BY 3.0 http://www.flaticon.com and http://www.freepik.com
-
-External libraries used :
- * JQuery : http://jquery.com/
- * Magnific Popup : http://dimsemenov.com/plugins/magnific-popup/
- * Php-epub-meta : https://github.com/splitbrain/php-epub-meta with some modification by me
- https://github.com/seblucas/php-epub-meta
- * TbsZip : http://www.tinybutstrong.com/apps/tbszip/tbszip_help.html
- * DoT.js : http://olado.github.io/doT/index.html
- * PHPMailer : https://github.com/PHPMailer/PHPMailer
- * js-lru : https://github.com/rsms/js-lru
-
-# Copyright & License
-
-COPS - 2012-2016 (c) Sbastien Lucas
-
-See COPYING and file headers for license info
-
diff --git a/sources/about.html b/sources/about.html
deleted file mode 100644
index d3369f9..0000000
--- a/sources/about.html
+++ /dev/null
@@ -1,23 +0,0 @@
-
-
About COPS
-
Authors
-
COPS is developed and maintained by Sébastien Lucas.
COPS use some external libraries, check README for the details.
-
Copyright
-
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation.
-
-
The complete content of license is provided in file COPYING within distribution and also available online.
DISCLAIMER : COPS is an open source software free to install everywhere. So if you have questions about any books available with any installation of COPS, please ask the owner of the website and not COPS's maintainer.
Check if Calibre database file can be opened with PHP
-
-
-
-
-
-
Check if Calibre database file contains at least some of the needed tables
-
- query("select count(*) FROM sqlite_master WHERE type='table' AND name in ('books', 'authors', 'tags', 'series')")->fetchColumn();
- if ($count == 4) {
- echo "{$name} OK";
- } else {
- echo "{$name} Not all Calibre tables were found. Are you sure you're using the correct database.";
- }
- } catch (Exception $e) {
- echo "{$name} If the file is readable, check your php configuration. Exception detail : " . $e;
- }
- ?>
-
-
-
-
-
Check if all Calibre books are found
-
- prepare("select books.path || '/' || data.name || '.' || lower (format) as fullpath from data join books on data.book = books.id");
- $result->execute ();
- while ($post = $result->fetchObject ())
- {
- if (!is_file (Base::getDbDirectory ($i) . $post->fullpath)) {
- echo "
-
-
diff --git a/sources/config.php b/sources/config.php
deleted file mode 100644
index 2990244..0000000
--- a/sources/config.php
+++ /dev/null
@@ -1,35 +0,0 @@
-
- */
-
-require_once 'config_default.php';
-if (file_exists(dirname(__FILE__) . '/config_local.php') && (php_sapi_name() !== 'cli')) {
- require_once 'config_local.php';
-}
-
-$remote_user = array_key_exists('PHP_AUTH_USER', $_SERVER) ? $_SERVER['PHP_AUTH_USER'] : '';
-// Clean username, only allow a-z, A-Z, 0-9, -_ chars
-$remote_user = preg_replace( "/[^a-zA-Z0-9_-]/", "", $remote_user);
-$user_config_file = 'config_local.' . $remote_user . '.php';
-if (file_exists(dirname(__FILE__) . '/' . $user_config_file) && (php_sapi_name() !== 'cli')) {
- require_once $user_config_file;
-}
-
-if(!is_null($config['cops_basic_authentication']) &&
- is_array($config['cops_basic_authentication']))
-{
- if (!isset($_SERVER['PHP_AUTH_USER']) ||
- (isset($_SERVER['PHP_AUTH_USER']) &&
- ($_SERVER['PHP_AUTH_USER']!=$config['cops_basic_authentication']['username'] ||
- $_SERVER['PHP_AUTH_PW'] != $config['cops_basic_authentication']['password'])))
- {
- header('WWW-Authenticate: Basic realm="COPS Authentication"');
- header('HTTP/1.0 401 Unauthorized');
- echo 'This site is password protected';
- exit;
- }
-}
diff --git a/sources/config_default.php b/sources/config_default.php
deleted file mode 100644
index 4b7b5f7..0000000
--- a/sources/config_default.php
+++ /dev/null
@@ -1,328 +0,0 @@
-
- */
-
- if (!isset($config))
- $config = array();
-
- /*
- * The directory containing calibre's metadata.db file, with sub-directories
- * containing all the formats.
- * BEWARE : it has to end with a /
- * You can enable multiple database with this notation instead of a simple string :
- * $config['calibre_directory'] = array ("My database name" => "/home/directory/calibre1/", "My other database name" => "/home/directory/calibre2/");
- */
- $config['calibre_directory'] = './';
-
- /*
- * SPECIFIC TO NGINX
- * The internal directory set in nginx config file
- * Leave empty if you don't know what you're doing
- */
- $config['calibre_internal_directory'] = '';
-
- /*
- * Full URL prefix (with trailing /)
- * useful especially for Opensearch where a full URL is often required
- * For example Mantano, Aldiko and Marvin require it.
- */
- $config['cops_full_url'] = '';
-
- /*
- * Number of recent books to show
- */
- $config['cops_recentbooks_limit'] = '50';
-
- /*
- * Catalog's author name
- */
- $config['cops_author_name'] = "Sébastien Lucas";
-
- /*
- * Catalog's author uri
- */
- $config['cops_author_uri'] = "http://blog.slucas.fr";
-
- /*
- * Catalog's author email
- */
- $config['cops_author_email'] = "sebastien@slucas.fr";
-
- /*
- * Catalog's title
- */
- $config['cops_title_default'] = "COPS";
-
- /*
- * Catalog's subtitle
- */
- $config['cops_subtitle_default'] = "";
-
- /*
- * Wich header to use when downloading books outside the web directory
- * Possible values are :
- * X-Accel-Redirect : For Nginx
- * X-Sendfile : For Lightttpd or Apache (with mod_xsendfile)
- * No value (default) : Let PHP handle the download
- */
- $config['cops_x_accel_redirect'] = "";
-
- /*
- * Height of thumbnail image for OPDS
- */
- $config['cops_opds_thumbnail_height'] = "164";
-
- /*
- * Height of thumbnail image for HTML
- */
- $config['cops_html_thumbnail_height'] = "164";
-
- /*
- * Icon for both OPDS and HTML catalog
- * Note that this has to be a real icon (.ico)
- */
- $config['cops_icon'] = "favicon.ico";
-
- /*
- * Show icon for authors, series, tags and books on OPDS feed
- * 1 : enable
- * 0 : disable
- */
- $config['cops_show_icons'] = "1";
-
- /*
- * Default timezone
- * Check following link for other timezones :
- * http://www.php.net/manual/en/timezones.php
- */
- $config['default_timezone'] = "Europe/Paris";
-
- /*
- * Prefered format for HTML catalog
- * The two first will be displayed in book entries
- * The other only appear in book detail
- */
- $config['cops_prefered_format'] = array ("EPUB", "PDF", "AZW3", "AZW", "MOBI", "CBR", "CBZ");
-
- /*
- * use URL rewriting for downloading of ebook in HTML catalog
- * See Github wiki for more information
- * 1 : enable
- * 0 : disable
- */
- $config['cops_use_url_rewriting'] = "0";
-
- /*
- * generate a invalid OPDS stream to allow bad OPDS client to use search
- * Example of non compliant OPDS client : Moon+ Reader
- * Example of good OPDS client : Mantano, FBReader
- * 1 : enable support for non compliant OPDS client
- * 0 : always generate valid OPDS code
- */
- $config['cops_generate_invalid_opds_stream'] = "0";
-
- /*
- * Max number of items per page
- * -1 unlimited
- */
- $config['cops_max_item_per_page'] = "-1";
-
- /*
- * split authors by first letter
- * 1 : Yes
- * 0 : No
- */
- $config['cops_author_split_first_letter'] = "1";
-
- /*
- * split titles by first letter
- * 1 : Yes
- * 0 : No
- */
- $config['cops_titles_split_first_letter'] = "1";
-
- /*
- * Enable the Lightboxes (for popups)
- * 1 : Yes (enable)
- * 0 : No
- */
- $config['cops_use_fancyapps'] = "1";
-
- /*
- * Update Epub metadata before download
- * 1 : Yes (enable)
- * 0 : No
- */
- $config['cops_update_epub-metadata'] = "0";
-
- /*
- * Filter on tags to book list
- * Only works with the OPDS catalog
- * Usage : array ("I only want to see books using the tag : Tag1" => "Tag1",
- * "I only want to see books not using the tag : Tag1" => "!Tag1",
- * "I want to see every books" => "",
- *
- * Example : array ("All" => "", "Unread" => "!Read", "Read" => "Read")
- */
- $config['cops_books_filter'] = array ();
-
- /*
- * Custom Columns for the index page
- * to add as an array containing the lookup names configured in Calibre
- *
- * For example : array ("genre", "mycolumn");
- *
- * Note that the composite custom columns are not supported
- */
- $config['cops_calibre_custom_column'] = array ();
-
- /*
- * Custom Columns for the list representation
- * to add as an array containing the lookup names configured in Calibre
- *
- * For example : array ("genre", "mycolumn");
- *
- * Note that the composite custom columns are not supported
- */
- $config['cops_calibre_custom_column_list'] = array ();
-
- /*
- * Custom Columns for the book preview panel
- * to add as an array containing the lookup names configured in Calibre
- *
- * For example : array ("genre", "mycolumn");
- *
- * Note that the composite custom columns are not supported
- */
- $config['cops_calibre_custom_column_preview'] = array ();
-
- /*
- * Rename .epub to .kepub.epub if downloaded from a Kobo eReader
- * The ebook will then be recognized a Kepub so with chaptered paging, statistics, ...
- * You have to enable URL rewriting if you want to enable kepup.epub download
- * 1 : Yes (enable)
- * 0 : No
- */
- $config['cops_provide_kepub'] = "0";
-
- /*
- * Enable and configure Send To Kindle (or Email) feature.
- *
- * Don't forget to authorize the sender email you configured in your Kindle's Approved Personal Document E-mail List.
- *
- * If you want to use a simple smtp server (provided by your ISP for example), you can configure it like that :
- * $config['cops_mail_configuration'] = array( "smtp.host" => "smtp.free.fr",
- * "smtp.username" => "",
- * "smtp.password" => "",
- * "smtp.secure" => "",
- * "address.from" => "cops@slucas.fr"
- * );
- *
- * For Gmail (ssl is mandatory) :
- * $config['cops_mail_configuration'] = array( "smtp.host" => "smtp.gmail.com",
- * "smtp.username" => "YOUR GMAIL ADRESS",
- * "smtp.password" => "YOUR GMAIL PASSWORD",
- * "smtp.secure" => "ssl",
- * "address.from" => "cops@slucas.fr"
- * );
- */
- $config['cops_mail_configuration'] = NULL;
-
- /*
- * Use filter in HTML catalog
- * 1 : Yes (enable)
- * 0 : No
- */
- $config['cops_html_tag_filter'] = "0";
-
- /*
- * Thumbnails are generated on-the-fly so it can be problematic on servers with slow CPU (Raspberry Pi, Dockstar, Piratebox, ...).
- * This configuration item allow to customize how thumbnail will be generated
- * "" : Generate thumbnail (CPU hungry)
- * "1" : always send the full size image (Network hungry)
- * any url : Send a constant image as the thumbnail (you can try "images/bookcover.png")
- */
- $config['cops_thumbnail_handling'] = "";
-
- /*
- * Directory to keep resized thumbnails: allow to resize thumbnails only on first access, then use this cache.
- * $config['cops_thumbnail_handling'] must be ""
- * "" : don't cache thumbnail
- * "/tmp/cache/" (example) : will generate thumbnails in /tmp/cache/
- * BEWARE : it has to end with a /
- */
- $config['cops_thumbnail_cache_directory'] = "";
-
- /*
- * Contains a list of user agent for browsers not compatible with client side rendering
- * For now : Kindle, Sony PRS-T1, Sony PRS-T2, All Cybook devices (maybe a little extreme).
- * This item is used as regular expression so "." will force server side rendering for all devices
- */
- $config['cops_server_side_render'] = "Kindle\/1\.0|Kindle\/2\.0|Kindle\/3\.0|EBRD1101|EBRD1201|cybook";
-
- /*
- * Specify the ignored categories for the home screen and with search
- * Meaning that if you don't want to search in publishers or tags just add them from the list
- * Only accepted values :
- * - author
- * - book
- * - series
- * - tag
- * - publisher
- * - rating
- * - language
- */
- $config ['cops_ignored_categories'] = array ();
-
- /*
- * If you use a Sony eReader or Aldiko you can't download ebooks if your catalog
- * is password protected. A simple workaround is to leave fetch.php not protected (see .htaccess).
- * But In that case your COPS installation is not completely safe.
- * Setting this parameter to "1" ensure that nobody can access fetch.php before accessing
- * index.php or feed.php first.
- * BEWARE : Do not touch this if you're not using password, not using PRS-TX or not using Aldiko.
- */
- $config ['cops_fetch_protect'] = "0";
-
- /*
- * WARNING NOT READY FOR PRODUCTION USE
- * Make the search better (don't care about diacritics, uppercase should work on Cyrillic) but slower.
- * 1 : Yes (enable)
- * 0 : No
- */
- $config ['cops_normalized_search'] = "0";
-
- /*
- * Enable PHP password protection (You can use if htpasswd is not possible for you)
- * If possible prefer htpasswd !
- * array( "username" => "xxx", "password" => "secret") : Enable PHP password protection
- * NULL : Disable PHP password protection (You can still use htpasswd)
- */
- $config['cops_basic_authentication'] = NULL;
-
- /*
- * Which template is used by default :
- * 'default'
- * 'bootstrap'
- */
- $config['cops_template'] = 'default';
-
- /*
- * Which style is used by default :
- * 'base'
- * 'default'
- * 'eink' (only available for the 'default' template)
- * 'iphone' (only available for the 'default' template)
- * 'iphone7' (only available for the 'default' template)
- */
- $config['cops_style'] = 'default';
-
- /*
- * Set language code to force a language (see lang/ directory for available languages).
- * When empty it will auto detect the language.
- */
- $config['cops_language'] = '';
diff --git a/sources/config_local.php.example b/sources/config_local.php.example
deleted file mode 100644
index 2bf34bf..0000000
--- a/sources/config_local.php.example
+++ /dev/null
@@ -1,23 +0,0 @@
-
- */
-
-require_once('base.php');
-
-/**
- * A CustomColumn with an value
- */
-class CustomColumn extends Base
-{
- /* @var string|integer the ID of the value */
- public $valueID;
- /* @var string the (string) representation of the value */
- public $value;
- /* @var CustomColumnType the custom column that contains the value */
- public $customColumnType;
- /* @var string the value encoded for HTML displaying */
- public $htmlvalue;
-
- /**
- * CustomColumn constructor.
- *
- * @param integer $pid id of the chosen value
- * @param string $pvalue string representation of the value
- * @param CustomColumnType $pcustomColumnType the CustomColumn this value lives in
- */
- public function __construct($pid, $pvalue, $pcustomColumnType)
- {
- $this->valueID = $pid;
- $this->value = $pvalue;
- $this->customColumnType = $pcustomColumnType;
- $this->htmlvalue = $this->customColumnType->encodeHTMLValue($this->value);
- }
-
- /**
- * Get the URI to show all books with this value
- *
- * @return string
- */
- public function getUri()
- {
- return $this->customColumnType->getUri($this->valueID);
- }
-
- /**
- * Get the EntryID to show all books with this value
- *
- * @return string
- */
- public function getEntryId()
- {
- return $this->customColumnType->getEntryId($this->valueID);
- }
-
- /**
- * Get the query to find all books with this value
- * the returning array has two values:
- * - first the query (string)
- * - second an array of all PreparedStatement parameters
- *
- * @return array
- */
- public function getQuery()
- {
- return $this->customColumnType->getQuery($this->valueID);
- }
-
- /**
- * Return the value of this column as an HTML snippet
- *
- * @return string
- */
- public function getHTMLEncodedValue()
- {
- return $this->htmlvalue;
- }
-
- /**
- * Craete an CustomColumn by CustomColumnID and ValueID
- *
- * @param integer $customId the id of the customColumn
- * @param integer $id the id of the chosen value
- * @return CustomColumn|null
- */
- public static function createCustom($customId, $id)
- {
- $columnType = CustomColumnType::createByCustomID($customId);
-
- return $columnType->getCustom($id);
- }
-
- /**
- * Return this object as an array
- *
- * @return array
- */
- public function toArray()
- {
- return array(
- 'valueID' => $this->valueID,
- 'value' => $this->value,
- 'customColumnType' => (array) $this->customColumnType,
- 'htmlvalue' => $this->htmlvalue);
- }
-}
-
-/**
- * A single calibre custom column
- */
-abstract class CustomColumnType extends Base
-{
- const ALL_CUSTOMS_ID = "cops:custom";
-
- const CUSTOM_TYPE_TEXT = "text"; // type 1 + 2
- const CUSTOM_TYPE_COMMENT = "comments"; // type 3
- const CUSTOM_TYPE_SERIES = "series"; // type 4
- const CUSTOM_TYPE_ENUM = "enumeration"; // type 5
- const CUSTOM_TYPE_DATE = "datetime"; // type 6
- const CUSTOM_TYPE_FLOAT = "float"; // type 7
- const CUSTOM_TYPE_INT = "int"; // type 8
- const CUSTOM_TYPE_RATING = "rating"; // type 9
- const CUSTOM_TYPE_BOOL = "bool"; // type 10
- const CUSTOM_TYPE_COMPOSITE = "composite"; // type 11 + 12
-
- /** @var array[integer]CustomColumnType */
- private static $customColumnCacheID = array();
-
- /** @var array[string]CustomColumnType */
- private static $customColumnCacheLookup = array();
-
- /** @var integer the id of this column */
- public $customId;
- /** @var string name/title of this column */
- public $columnTitle;
- /** @var string the datatype of this column (one of the CUSTOM_TYPE_* constant values) */
- public $datatype;
- /** @var null|Entry[] */
- private $customValues = NULL;
-
- protected function __construct($pcustomId, $pdatatype)
- {
- $this->columnTitle = self::getTitleByCustomID($pcustomId);
- $this->customId = $pcustomId;
- $this->datatype = $pdatatype;
- $this->customValues = NULL;
- }
-
- /**
- * The URI to show all book swith a specific value in this column
- *
- * @param string|integer $id the id of the value to show
- * @return string
- */
- public function getUri($id)
- {
- return "?page=" . parent::PAGE_CUSTOM_DETAIL . "&custom={$this->customId}&id={$id}";
- }
-
- /**
- * The URI to show all the values of this column
- *
- * @return string
- */
- public function getUriAllCustoms()
- {
- return "?page=" . parent::PAGE_ALL_CUSTOMS . "&custom={$this->customId}";
- }
-
- /**
- * The EntryID to show all book swith a specific value in this column
- *
- * @param string|integer $id the id of the value to show
- * @return string
- */
- public function getEntryId($id)
- {
- return self::ALL_CUSTOMS_ID . ":" . $this->customId . ":" . $id;
- }
-
- /**
- * The EntryID to show all the values of this column
- *
- * @return string
- */
- public function getAllCustomsId()
- {
- return self::ALL_CUSTOMS_ID . ":" . $this->customId;
- }
-
- /**
- * The title of this column
- *
- * @return string
- */
- public function getTitle()
- {
- return $this->columnTitle;
- }
-
- /**
- * The description of this column as it is definied in the database
- *
- * @return string|null
- */
- public function getDatabaseDescription()
- {
- $result = $this->getDb()->prepare('SELECT display FROM custom_columns WHERE id = ?');
- $result->execute(array($this->customId));
- if ($post = $result->fetchObject()) {
- $json = json_decode($post->display);
- return (isset($json->description) && !empty($json->description)) ? $json->description : NULL;
- }
- return NULL;
- }
-
- /**
- * Get the Entry for this column
- * This is used in the initializeContent method to display e.g. the index page
- *
- * @return Entry
- */
- public function getCount()
- {
- $ptitle = $this->getTitle();
- $pid = $this->getAllCustomsId();
- $pcontent = $this->getDescription();
- $pcontentType = $this->datatype;
- $plinkArray = array(new LinkNavigation($this->getUriAllCustoms()));
- $pclass = "";
- $pcount = $this->getDistinctValueCount();
-
- return new Entry($ptitle, $pid, $pcontent, $pcontentType, $plinkArray, $pclass, $pcount);
- }
-
- /**
- * Get the amount of distinct values for this column
- *
- * @return int
- */
- protected function getDistinctValueCount()
- {
- return count($this->getAllCustomValues());
- }
-
- /**
- * Encode a value of this column ready to be displayed in an HTML document
- *
- * @param integer|string $value
- * @return string
- */
- public function encodeHTMLValue($value)
- {
- return htmlspecialchars($value);
- }
-
- /**
- * Get the datatype of a CustomColumn by its customID
- *
- * @param integer $customId
- * @return string|null
- */
- private static function getDatatypeByCustomID($customId)
- {
- $result = parent::getDb()->prepare('SELECT datatype FROM custom_columns WHERE id = ?');
- $result->execute(array($customId));
- if ($post = $result->fetchObject()) {
- return $post->datatype;
- }
- return NULL;
- }
-
- /**
- * Create a CustomColumnType by CustomID
- *
- * @param integer $customId the id of the custom column
- * @return CustomColumnType|null
- * @throws Exception If the $customId is not found or the datatype is unknown
- */
- public static function createByCustomID($customId)
- {
- // Reuse already created CustomColumns for performance
- if (array_key_exists($customId, self::$customColumnCacheID))
- return self::$customColumnCacheID[$customId];
-
- $datatype = self::getDatatypeByCustomID($customId);
-
- switch ($datatype) {
- case self::CUSTOM_TYPE_TEXT:
- return self::$customColumnCacheID[$customId] = new CustomColumnTypeText($customId);
- case self::CUSTOM_TYPE_SERIES:
- return self::$customColumnCacheID[$customId] = new CustomColumnTypeSeries($customId);
- case self::CUSTOM_TYPE_ENUM:
- return self::$customColumnCacheID[$customId] = new CustomColumnTypeEnumeration($customId);
- case self::CUSTOM_TYPE_COMMENT:
- return self::$customColumnCacheID[$customId] = new CustomColumnTypeComment($customId);
- case self::CUSTOM_TYPE_DATE:
- return self::$customColumnCacheID[$customId] = new CustomColumnTypeDate($customId);
- case self::CUSTOM_TYPE_FLOAT:
- return self::$customColumnCacheID[$customId] = new CustomColumnTypeFloat($customId);
- case self::CUSTOM_TYPE_INT:
- return self::$customColumnCacheID[$customId] = new CustomColumnTypeInteger($customId);
- case self::CUSTOM_TYPE_RATING:
- return self::$customColumnCacheID[$customId] = new CustomColumnTypeRating($customId);
- case self::CUSTOM_TYPE_BOOL:
- return self::$customColumnCacheID[$customId] = new CustomColumnTypeBool($customId);
- case self::CUSTOM_TYPE_COMPOSITE:
- return NULL; //TODO Currently not supported
- default:
- throw new Exception("Unkown column type: " . $datatype);
- }
- }
-
- /**
- * Create a CustomColumnType by its lookup name
- *
- * @param string $lookup the lookup-name of the custom column
- * @return CustomColumnType|null
- */
- public static function createByLookup($lookup)
- {
- // Reuse already created CustomColumns for performance
- if (array_key_exists($lookup, self::$customColumnCacheLookup))
- return self::$customColumnCacheLookup[$lookup];
-
- $result = parent::getDb()->prepare('SELECT id FROM custom_columns WHERE label = ?');
- $result->execute(array($lookup));
- if ($post = $result->fetchObject()) {
- return self::$customColumnCacheLookup[$lookup] = self::createByCustomID($post->id);
- }
- return self::$customColumnCacheLookup[$lookup] = NULL;
- }
-
- /**
- * Return an entry array for all possible (in the DB used) values of this column
- * These are the values used in the getUriAllCustoms() page
- *
- * @return Entry[]
- */
- public function getAllCustomValues()
- {
- // lazy loading
- if ($this->customValues == NULL)
- $this->customValues = $this->getAllCustomValuesFromDatabase();
-
- return $this->customValues;
- }
-
- /**
- * Get the title of a CustomColumn by its customID
- *
- * @param integer $customId
- * @return string
- */
- protected static function getTitleByCustomID($customId)
- {
- $result = parent::getDb()->prepare('SELECT name FROM custom_columns WHERE id = ?');
- $result->execute(array($customId));
- if ($post = $result->fetchObject()) {
- return $post->name;
- }
- return "";
- }
-
- /**
- * Get the query to find all books with a specific value of this column
- * the returning array has two values:
- * - first the query (string)
- * - second an array of all PreparedStatement parameters
- *
- * @param string|integer $id the id of the searched value
- * @return array
- */
- abstract public function getQuery($id);
-
- /**
- * Get a CustomColumn for a specified (by ID) value
- *
- * @param string|integer $id the id of the searched value
- * @return CustomColumn
- */
- abstract public function getCustom($id);
-
- /**
- * Return an entry array for all possible (in the DB used) values of this column by querying the database
- *
- * @return Entry[]
- */
- abstract protected function getAllCustomValuesFromDatabase();
-
- /**
- * The description used in the index page
- *
- * @return string
- */
- abstract public function getDescription();
-
- /**
- * Find the value of this column for a specific book
- *
- * @param Book $book
- * @return CustomColumn
- */
- public abstract function getCustomByBook($book);
-
- /**
- * Is this column searchable by value
- * only searchable columns can be displayed on the index page
- *
- * @return bool
- */
- public abstract function isSearchable();
-}
-
-class CustomColumnTypeText extends CustomColumnType
-{
- protected function __construct($pcustomId)
- {
- parent::__construct($pcustomId, self::CUSTOM_TYPE_TEXT);
- }
-
- /**
- * Get the name of the sqlite table for this column
- *
- * @return string|null
- */
- private function getTableName()
- {
- return "custom_column_{$this->customId}";
- }
-
- /**
- * Get the name of the linking sqlite table for this column
- * (or NULL if there is no linktable)
- *
- * @return string|null
- */
- private function getTableLinkName()
- {
- return "books_custom_column_{$this->customId}_link";
- }
-
- /**
- * Get the name of the linking column in the linktable
- *
- * @return string|null
- */
- private function getTableLinkColumn()
- {
- return "value";
- }
-
- public function getQuery($id)
- {
- $query = str_format(Book::SQL_BOOKS_BY_CUSTOM, "{0}", "{1}", $this->getTableLinkName(), $this->getTableLinkColumn());
- return array($query, array($id));
- }
-
- public function getCustom($id)
- {
- $result = $this->getDb()->prepare(str_format("SELECT id, value AS name FROM {0} WHERE id = ?", $this->getTableName()));
- $result->execute(array($id));
- if ($post = $result->fetchObject()) {
- return new CustomColumn($id, $post->name, $this);
- }
- return NULL;
- }
-
- protected function getAllCustomValuesFromDatabase()
- {
- $queryFormat = "SELECT {0}.id AS id, {0}.value AS name, count(*) AS count FROM {0}, {1} WHERE {0}.id = {1}.{2} GROUP BY {0}.id, {0}.value ORDER BY {0}.value";
- $query = str_format($queryFormat, $this->getTableName(), $this->getTableLinkName(), $this->getTableLinkColumn());
-
- $result = $this->getDb()->query($query);
- $entryArray = array();
- while ($post = $result->fetchObject())
- {
- $entryPContent = str_format(localize("bookword", $post->count), $post->count);
- $entryPLinkArray = array(new LinkNavigation ($this->getUri($post->id)));
-
- $entry = new Entry($post->name, $this->getEntryId($post->id), $entryPContent, $this->datatype, $entryPLinkArray, "", $post->count);
-
- array_push($entryArray, $entry);
- }
- return $entryArray;
- }
-
- public function getDescription()
- {
- $desc = $this->getDatabaseDescription();
- if ($desc === NULL || empty($desc)) $desc = str_format(localize("customcolumn.description"), $this->getTitle());
- return $desc;
- }
-
- public function getCustomByBook($book)
- {
- $queryFormat = "SELECT {0}.id AS id, {0}.{2} AS name FROM {0}, {1} WHERE {0}.id = {1}.{2} AND {1}.book = {3} ORDER BY {0}.value";
- $query = str_format($queryFormat, $this->getTableName(), $this->getTableLinkName(), $this->getTableLinkColumn(), $book->id);
-
- $result = $this->getDb()->query($query);
- if ($post = $result->fetchObject()) {
- return new CustomColumn($post->id, $post->name, $this);
- }
- return new CustomColumn(NULL, "", $this);
- }
-
- public function isSearchable()
- {
- return true;
- }
-}
-
-class CustomColumnTypeSeries extends CustomColumnType
-{
- protected function __construct($pcustomId)
- {
- parent::__construct($pcustomId, self::CUSTOM_TYPE_SERIES);
- }
-
- /**
- * Get the name of the sqlite table for this column
- *
- * @return string|null
- */
- private function getTableName()
- {
- return "custom_column_{$this->customId}";
- }
-
- /**
- * Get the name of the linking sqlite table for this column
- * (or NULL if there is no linktable)
- *
- * @return string|null
- */
- private function getTableLinkName()
- {
- return "books_custom_column_{$this->customId}_link";
- }
-
- /**
- * Get the name of the linking column in the linktable
- *
- * @return string|null
- */
- private function getTableLinkColumn()
- {
- return "value";
- }
-
- public function getQuery($id)
- {
- $query = str_format(Book::SQL_BOOKS_BY_CUSTOM, "{0}", "{1}", $this->getTableLinkName(), $this->getTableLinkColumn());
- return array($query, array($id));
- }
-
- public function getCustom($id)
- {
- $result = $this->getDb()->prepare(str_format("SELECT id, value AS name FROM {0} WHERE id = ?", $this->getTableName()));
- $result->execute(array($id));
- if ($post = $result->fetchObject()) {
- return new CustomColumn($id, $post->name, $this);
- }
- return NULL;
- }
-
- protected function getAllCustomValuesFromDatabase()
- {
- $queryFormat = "SELECT {0}.id AS id, {0}.value AS name, count(*) AS count FROM {0}, {1} WHERE {0}.id = {1}.{2} GROUP BY {0}.id, {0}.value ORDER BY {0}.value";
- $query = str_format($queryFormat, $this->getTableName(), $this->getTableLinkName(), $this->getTableLinkColumn());
-
- $result = $this->getDb()->query($query);
- $entryArray = array();
- while ($post = $result->fetchObject()) {
- $entryPContent = str_format(localize("bookword", $post->count), $post->count);
- $entryPLinkArray = array(new LinkNavigation($this->getUri($post->id)));
-
- $entry = new Entry($post->name, $this->getEntryId($post->id), $entryPContent, $this->datatype, $entryPLinkArray, "", $post->count);
-
- array_push($entryArray, $entry);
- }
- return $entryArray;
- }
-
- public function getDescription()
- {
- return str_format(localize("customcolumn.description.series", $this->getDistinctValueCount()), $this->getDistinctValueCount());
- }
-
- public function getCustomByBook($book)
- {
- $queryFormat = "SELECT {0}.id AS id, {1}.{2} AS name, {1}.extra AS extra FROM {0}, {1} WHERE {0}.id = {1}.{2} AND {1}.book = {3}";
- $query = str_format($queryFormat, $this->getTableName(), $this->getTableLinkName(), $this->getTableLinkColumn(), $book->id);
-
- $result = $this->getDb()->query($query);
- if ($post = $result->fetchObject()) {
- return new CustomColumn($post->id, $post->name . " [" . $post->extra . "]", $this);
- }
- return new CustomColumn(NULL, "", $this);
- }
-
- public function isSearchable()
- {
- return true;
- }
-}
-
-class CustomColumnTypeEnumeration extends CustomColumnType
-{
- protected function __construct($pcustomId)
- {
- parent::__construct($pcustomId, self::CUSTOM_TYPE_ENUM);
- }
-
- /**
- * Get the name of the sqlite table for this column
- *
- * @return string|null
- */
- private function getTableName()
- {
- return "custom_column_{$this->customId}";
- }
-
- /**
- * Get the name of the linking sqlite table for this column
- * (or NULL if there is no linktable)
- *
- * @return string|null
- */
- private function getTableLinkName()
- {
- return "books_custom_column_{$this->customId}_link";
- }
-
- /**
- * Get the name of the linking column in the linktable
- *
- * @return string|null
- */
- private function getTableLinkColumn()
- {
- return "value";
- }
-
- public function getQuery($id)
- {
- $query = str_format(Book::SQL_BOOKS_BY_CUSTOM, "{0}", "{1}", $this->getTableLinkName(), $this->getTableLinkColumn());
- return array($query, array($id));
- }
-
- public function getCustom($id)
- {
- $result = $this->getDb()->prepare(str_format("SELECT id, value AS name FROM {0} WHERE id = ?", $this->getTableName()));
- $result->execute(array($id));
- if ($post = $result->fetchObject()) {
- return new CustomColumn ($id, $post->name, $this);
- }
- return NULL;
- }
-
- protected function getAllCustomValuesFromDatabase()
- {
- $queryFormat = "SELECT {0}.id AS id, {0}.value AS name, count(*) AS count FROM {0}, {1} WHERE {0}.id = {1}.{2} GROUP BY {0}.id, {0}.value ORDER BY {0}.value";
- $query = str_format($queryFormat, $this->getTableName(), $this->getTableLinkName(), $this->getTableLinkColumn());
-
- $result = $this->getDb()->query($query);
- $entryArray = array();
- while ($post = $result->fetchObject()) {
- $entryPContent = str_format(localize("bookword", $post->count), $post->count);
- $entryPLinkArray = array(new LinkNavigation ($this->getUri($post->id)));
-
- $entry = new Entry ($post->name, $this->getEntryId($post->id), $entryPContent, $this->datatype, $entryPLinkArray, "", $post->count);
-
- array_push($entryArray, $entry);
- }
- return $entryArray;
- }
-
- public function getDescription()
- {
- return str_format(localize("customcolumn.description.enum", $this->getDistinctValueCount()), $this->getDistinctValueCount());
- }
-
- public function getCustomByBook($book)
- {
- $queryFormat = "SELECT {0}.id AS id, {0}.{2} AS name FROM {0}, {1} WHERE {0}.id = {1}.{2} AND {1}.book = {3}";
- $query = str_format($queryFormat, $this->getTableName(), $this->getTableLinkName(), $this->getTableLinkColumn(), $book->id);
-
- $result = $this->getDb()->query($query);
- if ($post = $result->fetchObject()) {
- return new CustomColumn($post->id, $post->name, $this);
- }
- return new CustomColumn(NULL, localize("customcolumn.enum.unknown"), $this);
- }
-
- public function isSearchable()
- {
- return true;
- }
-}
-
-class CustomColumnTypeDate extends CustomColumnType
-{
- protected function __construct($pcustomId)
- {
- parent::__construct($pcustomId, self::CUSTOM_TYPE_DATE);
- }
-
- /**
- * Get the name of the sqlite table for this column
- *
- * @return string|null
- */
- private function getTableName()
- {
- return "custom_column_{$this->customId}";
- }
-
- public function getQuery($id)
- {
- $date = new DateTime($id);
- $query = str_format(Book::SQL_BOOKS_BY_CUSTOM_DATE, "{0}", "{1}", $this->getTableName());
- return array($query, array($date->format("Y-m-d")));
- }
-
- public function getCustom($id)
- {
- $date = new DateTime($id);
-
- return new CustomColumn($id, $date->format(localize("customcolumn.date.format")), $this);
- }
-
- protected function getAllCustomValuesFromDatabase()
- {
- $queryFormat = "SELECT date(value) AS datevalue, count(*) AS count FROM {0} GROUP BY datevalue";
- $query = str_format($queryFormat, $this->getTableName());
- $result = $this->getDb()->query($query);
-
- $entryArray = array();
- while ($post = $result->fetchObject()) {
- $date = new DateTime($post->datevalue);
- $id = $date->format("Y-m-d");
-
- $entryPContent = str_format(localize("bookword", $post->count), $post->count);
- $entryPLinkArray = array(new LinkNavigation ($this->getUri($id)));
-
- $entry = new Entry($date->format(localize("customcolumn.date.format")), $this->getEntryId($id), $entryPContent, $this->datatype, $entryPLinkArray, "", $post->count);
-
- array_push($entryArray, $entry);
- }
-
- return $entryArray;
- }
-
- public function getDescription()
- {
- $desc = $this->getDatabaseDescription();
- if ($desc === NULL || empty($desc)) $desc = str_format(localize("customcolumn.description"), $this->getTitle());
- return $desc;
- }
-
- public function getCustomByBook($book)
- {
- $queryFormat = "SELECT date({0}.value) AS datevalue FROM {0} WHERE {0}.book = {1}";
- $query = str_format($queryFormat, $this->getTableName(), $book->id);
-
- $result = $this->getDb()->query($query);
- if ($post = $result->fetchObject()) {
- $date = new DateTime($post->datevalue);
-
- return new CustomColumn($date->format("Y-m-d"), $date->format(localize("customcolumn.date.format")), $this);
- }
- return new CustomColumn(NULL, localize("customcolumn.date.unknown"), $this);
- }
-
- public function isSearchable()
- {
- return true;
- }
-}
-
-class CustomColumnTypeRating extends CustomColumnType
-{
- protected function __construct($pcustomId)
- {
- parent::__construct($pcustomId, self::CUSTOM_TYPE_RATING);
- }
-
- /**
- * Get the name of the sqlite table for this column
- *
- * @return string|null
- */
- private function getTableName()
- {
- return "custom_column_{$this->customId}";
- }
-
- /**
- * Get the name of the linking sqlite table for this column
- * (or NULL if there is no linktable)
- *
- * @return string|null
- */
- private function getTableLinkName()
- {
- return "books_custom_column_{$this->customId}_link";
- }
-
- /**
- * Get the name of the linking column in the linktable
- *
- * @return string|null
- */
- private function getTableLinkColumn()
- {
- return "value";
- }
-
- public function getQuery($id)
- {
- if ($id == 0) {
- $query = str_format(Book::SQL_BOOKS_BY_CUSTOM_RATING_NULL, "{0}", "{1}", $this->getTableLinkName(), $this->getTableName(), $this->getTableLinkColumn());
- return array($query, array());
- } else {
- $query = str_format(Book::SQL_BOOKS_BY_CUSTOM_RATING, "{0}", "{1}", $this->getTableLinkName(), $this->getTableName(), $this->getTableLinkColumn());
- return array($query, array($id));
- }
- }
-
- public function getCustom($id)
- {
- return new CustomColumn ($id, str_format(localize("customcolumn.stars", $id / 2), $id / 2), $this);
- }
-
- protected function getAllCustomValuesFromDatabase()
- {
- $queryFormat = "SELECT coalesce({0}.value, 0) AS value, count(*) AS count FROM books LEFT JOIN {1} ON books.id = {1}.book LEFT JOIN {0} ON {0}.id = {1}.value GROUP BY coalesce({0}.value, -1)";
- $query = str_format($queryFormat, $this->getTableName(), $this->getTableLinkName());
- $result = $this->getDb()->query($query);
-
- $countArray = array(0 => 0, 2 => 0, 4 => 0, 6 => 0, 8 => 0, 10 => 0);
- while ($row = $result->fetchObject()) {
- $countArray[$row->value] = $row->count;
- }
-
- $entryArray = array();
-
- for ($i = 0; $i <= 5; $i++) {
- $count = $countArray[$i * 2];
- $name = str_format(localize("customcolumn.stars", $i), $i);
- $entryid = $this->getEntryId($i * 2);
- $content = str_format(localize("bookword", $count), $count);
- $linkarray = array(new LinkNavigation($this->getUri($i * 2)));
- $entry = new Entry($name, $entryid, $content, $this->datatype, $linkarray, "", $count);
- array_push($entryArray, $entry);
- }
-
- return $entryArray;
- }
-
- public function getDescription()
- {
- return localize("customcolumn.description.rating");
- }
-
- public function getCustomByBook($book)
- {
- $queryFormat = "SELECT {0}.value AS value FROM {0}, {1} WHERE {0}.id = {1}.{2} AND {1}.book = {3}";
- $query = str_format($queryFormat, $this->getTableName(), $this->getTableLinkName(), $this->getTableLinkColumn(), $book->id);
-
- $result = $this->getDb()->query($query);
- if ($post = $result->fetchObject()) {
- return new CustomColumn($post->value, str_format(localize("customcolumn.stars", $post->value / 2), $post->value / 2), $this);
- }
- return new CustomColumn(NULL, localize("customcolumn.rating.unknown"), $this);
- }
-
- public function isSearchable()
- {
- return true;
- }
-}
-
-class CustomColumnTypeBool extends CustomColumnType
-{
- // PHP pre 5.6 does not support const arrays
- private $BOOLEAN_NAMES = array(
- -1 => "customcolumn.boolean.unknown", // localize("customcolumn.boolean.unknown")
- 00 => "customcolumn.boolean.no", // localize("customcolumn.boolean.no")
- +1 => "customcolumn.boolean.yes", // localize("customcolumn.boolean.yes")
- );
-
- protected function __construct($pcustomId)
- {
- parent::__construct($pcustomId, self::CUSTOM_TYPE_BOOL);
- }
-
- /**
- * Get the name of the sqlite table for this column
- *
- * @return string|null
- */
- private function getTableName()
- {
- return "custom_column_{$this->customId}";
- }
-
- public function getQuery($id)
- {
- if ($id == -1) {
- $query = str_format(Book::SQL_BOOKS_BY_CUSTOM_BOOL_NULL, "{0}", "{1}", $this->getTableName());
- return array($query, array());
- } else if ($id == 0) {
- $query = str_format(Book::SQL_BOOKS_BY_CUSTOM_BOOL_FALSE, "{0}", "{1}", $this->getTableName());
- return array($query, array());
- } else if ($id == 1) {
- $query = str_format(Book::SQL_BOOKS_BY_CUSTOM_BOOL_TRUE, "{0}", "{1}", $this->getTableName());
- return array($query, array());
- } else {
- return NULL;
- }
- }
-
- public function getCustom($id)
- {
- return new CustomColumn($id, localize($this->BOOLEAN_NAMES[$id]), $this);
- }
-
- protected function getAllCustomValuesFromDatabase()
- {
- $queryFormat = "SELECT coalesce({0}.value, -1) AS id, count(*) AS count FROM books LEFT JOIN {0} ON books.id = {0}.book GROUP BY {0}.value ORDER BY {0}.value";
- $query = str_format($queryFormat, $this->getTableName());
- $result = $this->getDb()->query($query);
-
- $entryArray = array();
- while ($post = $result->fetchObject()) {
- $entryPContent = str_format(localize("bookword", $post->count), $post->count);
- $entryPLinkArray = array(new LinkNavigation ($this->getUri($post->id)));
-
- $entry = new Entry(localize($this->BOOLEAN_NAMES[$post->id]), $this->getEntryId($post->id), $entryPContent, $this->datatype, $entryPLinkArray, "", $post->count);
-
- array_push($entryArray, $entry);
- }
- return $entryArray;
- }
-
- public function getDescription()
- {
- return localize("customcolumn.description.bool");
- }
-
- public function getCustomByBook($book)
- {
- $queryFormat = "SELECT {0}.value AS boolvalue FROM {0} WHERE {0}.book = {1}";
- $query = str_format($queryFormat, $this->getTableName(), $book->id);
-
- $result = $this->getDb()->query($query);
- if ($post = $result->fetchObject()) {
- return new CustomColumn($post->boolvalue, localize($this->BOOLEAN_NAMES[$post->boolvalue]), $this);
- } else {
- return new CustomColumn(-1, localize($this->BOOLEAN_NAMES[-1]), $this);
- }
- }
-
- public function isSearchable()
- {
- return true;
- }
-}
-
-class CustomColumnTypeInteger extends CustomColumnType
-{
- protected function __construct($pcustomId)
- {
- parent::__construct($pcustomId, self::CUSTOM_TYPE_INT);
- }
-
- /**
- * Get the name of the sqlite table for this column
- *
- * @return string|null
- */
- private function getTableName()
- {
- return "custom_column_{$this->customId}";
- }
-
- public function getQuery($id)
- {
- $query = str_format(Book::SQL_BOOKS_BY_CUSTOM_DIRECT, "{0}", "{1}", $this->getTableName());
- return array($query, array($id));
- }
-
- public function getCustom($id)
- {
- return new CustomColumn($id, $id, $this);
- }
-
- protected function getAllCustomValuesFromDatabase()
- {
- $queryFormat = "SELECT value AS id, count(*) AS count FROM {0} GROUP BY value";
- $query = str_format($queryFormat, $this->getTableName());
-
- $result = $this->getDb()->query($query);
- $entryArray = array();
- while ($post = $result->fetchObject()) {
- $entryPContent = str_format(localize("bookword", $post->count), $post->count);
- $entryPLinkArray = array(new LinkNavigation($this->getUri($post->id)));
-
- $entry = new Entry($post->id, $this->getEntryId($post->id), $entryPContent, $this->datatype, $entryPLinkArray, "", $post->count);
-
- array_push($entryArray, $entry);
- }
- return $entryArray;
- }
-
- public function getDescription()
- {
- $desc = $this->getDatabaseDescription();
- if ($desc === NULL || empty($desc)) $desc = str_format(localize("customcolumn.description"), $this->getTitle());
- return $desc;
- }
-
- public function getCustomByBook($book)
- {
- $queryFormat = "SELECT {0}.value AS value FROM {0} WHERE {0}.book = {1}";
- $query = str_format($queryFormat, $this->getTableName(), $book->id);
-
- $result = $this->getDb()->query($query);
- if ($post = $result->fetchObject()) {
- return new CustomColumn($post->value, $post->value, $this);
- }
- return new CustomColumn(NULL, localize("customcolumn.int.unknown"), $this);
- }
-
- public function isSearchable()
- {
- return true;
- }
-}
-
-class CustomColumnTypeFloat extends CustomColumnType
-{
- protected function __construct($pcustomId)
- {
- parent::__construct($pcustomId, self::CUSTOM_TYPE_FLOAT);
- }
-
- /**
- * Get the name of the sqlite table for this column
- *
- * @return string|null
- */
- private function getTableName()
- {
- return "custom_column_{$this->customId}";
- }
-
- public function getQuery($id)
- {
- $query = str_format(Book::SQL_BOOKS_BY_CUSTOM_DIRECT, "{0}", "{1}", $this->getTableName());
- return array($query, array($id));
- }
-
- public function getCustom($id)
- {
- return new CustomColumn($id, $id, $this);
- }
-
- protected function getAllCustomValuesFromDatabase()
- {
- $queryFormat = "SELECT value AS id, count(*) AS count FROM {0} GROUP BY value";
- $query = str_format($queryFormat, $this->getTableName());
-
- $result = $this->getDb()->query($query);
- $entryArray = array();
- while ($post = $result->fetchObject()) {
- $entryPContent = str_format(localize("bookword", $post->count), $post->count);
- $entryPLinkArray = array(new LinkNavigation($this->getUri($post->id)));
-
- $entry = new Entry($post->id, $this->getEntryId($post->id), $entryPContent, $this->datatype, $entryPLinkArray, "", $post->count);
-
- array_push($entryArray, $entry);
- }
- return $entryArray;
- }
-
- public function getDescription()
- {
- $desc = $this->getDatabaseDescription();
- if ($desc === NULL || empty($desc)) $desc = str_format(localize("customcolumn.description"), $this->getTitle());
- return $desc;
- }
-
- public function getCustomByBook($book)
- {
- $queryFormat = "SELECT {0}.value AS value FROM {0} WHERE {0}.book = {1}";
- $query = str_format($queryFormat, $this->getTableName(), $book->id);
-
- $result = $this->getDb()->query($query);
- if ($post = $result->fetchObject()) {
- return new CustomColumn($post->value, $post->value, $this);
- }
- return new CustomColumn(NULL, localize("customcolumn.float.unknown"), $this);
- }
-
- public function isSearchable()
- {
- return true;
- }
-}
-
-class CustomColumnTypeComment extends CustomColumnType
-{
- protected function __construct($pcustomId)
- {
- parent::__construct($pcustomId, self::CUSTOM_TYPE_COMMENT);
- }
-
- /**
- * Get the name of the sqlite table for this column
- *
- * @return string|null
- */
- private function getTableName()
- {
- return "custom_column_{$this->customId}";
- }
-
- public function getQuery($id)
- {
- $query = str_format(Book::SQL_BOOKS_BY_CUSTOM_DIRECT_ID, "{0}", "{1}", $this->getTableName());
- return array($query, array($id));
- }
-
- public function getCustom($id)
- {
- return new CustomColumn($id, $id, $this);
- }
-
- public function encodeHTMLValue($value)
- {
- return "
',srcAction:"iframe_src",patterns:{youtube:{index:"youtube.com",id:"v=",src:"//www.youtube.com/embed/%id%?autoplay=1"},vimeo:{index:"vimeo.com/",id:"/",src:"//player.vimeo.com/video/%id%?autoplay=1"},gmaps:{index:"//maps.google.",src:"%id%&output=embed"}}},proto:{initIframe:function(){t.types.push(Z),x("BeforeChange",function(e,t,n){t!==n&&(t===Z?D():n===Z&&D(!0))}),x(l+"."+Z,function(){D()})},getIframe:function(n,i){var o=n.src,r=t.st.iframe;e.each(r.patterns,function(){return o.indexOf(this.index)>-1?(this.id&&(o="string"==typeof this.id?o.substr(o.lastIndexOf(this.id)+this.id.length,o.length):this.id.call(this,o)),o=this.src.replace("%id%",o),!1):void 0});var a={};return r.srcAction&&(a[r.srcAction]=o),t._parseMarkup(i,a,n),t.updateStatus("ready"),i}}});var K=function(e){var n=t.items.length;return e>n-1?e-n:0>e?n+e:e},Y=function(e,t,n){return e.replace(/%curr%/gi,t+1).replace(/%total%/gi,n)};e.magnificPopup.registerModule("gallery",{options:{enabled:!1,arrowMarkup:'',preload:[0,2],navigateByImgClick:!0,arrows:!0,tPrev:"Previous (Left arrow key)",tNext:"Next (Right arrow key)",tCounter:"%curr% of %total%"},proto:{initGallery:function(){var n=t.st.gallery,i=".mfp-gallery",r=Boolean(e.fn.mfpFastClick);return t.direction=!0,n&&n.enabled?(a+=" mfp-gallery",x(f+i,function(){n.navigateByImgClick&&t.wrap.on("click"+i,".mfp-img",function(){return t.items.length>1?(t.next(),!1):void 0}),o.on("keydown"+i,function(e){37===e.keyCode?t.prev():39===e.keyCode&&t.next()})}),x("UpdateStatus"+i,function(e,n){n.text&&(n.text=Y(n.text,t.currItem.index,t.items.length))}),x(p+i,function(e,i,o,r){var a=t.items.length;o.counter=a>1?Y(n.tCounter,r.index,a):""}),x("BuildControls"+i,function(){if(t.items.length>1&&n.arrows&&!t.arrowLeft){var i=n.arrowMarkup,o=t.arrowLeft=e(i.replace(/%title%/gi,n.tPrev).replace(/%dir%/gi,"left")).addClass(y),a=t.arrowRight=e(i.replace(/%title%/gi,n.tNext).replace(/%dir%/gi,"right")).addClass(y),s=r?"mfpFastClick":"click";o[s](function(){t.prev()}),a[s](function(){t.next()}),t.isIE7&&(k("b",o[0],!1,!0),k("a",o[0],!1,!0),k("b",a[0],!1,!0),k("a",a[0],!1,!0)),t.container.append(o.add(a))}}),x(m+i,function(){t._preloadTimeout&&clearTimeout(t._preloadTimeout),t._preloadTimeout=setTimeout(function(){t.preloadNearbyImages(),t._preloadTimeout=null},16)}),x(l+i,function(){o.off(i),t.wrap.off("click"+i),t.arrowLeft&&r&&t.arrowLeft.add(t.arrowRight).destroyMfpFastClick(),t.arrowRight=t.arrowLeft=null}),void 0):!1},next:function(){t.direction=!0,t.index=K(t.index+1),t.updateItemHTML()},prev:function(){t.direction=!1,t.index=K(t.index-1),t.updateItemHTML()},goTo:function(e){t.direction=e>=t.index,t.index=e,t.updateItemHTML()},preloadNearbyImages:function(){var e,n=t.st.gallery.preload,i=Math.min(n[0],t.items.length),o=Math.min(n[1],t.items.length);for(e=1;(t.direction?o:i)>=e;e++)t._preloadItem(t.index+e);for(e=1;(t.direction?i:o)>=e;e++)t._preloadItem(t.index-e)},_preloadItem:function(n){if(n=K(n),!t.items[n].preloaded){var i=t.items[n];i.parsed||(i=t.parseEl(n)),T("LazyLoad",i),"image"===i.type&&(i.img=e('').on("load.mfploader",function(){i.hasSize=!0}).on("error.mfploader",function(){i.hasSize=!0,i.loadError=!0,T("LazyLoadError",i)}).attr("src",i.src)),i.preloaded=!0}}}});var U="retina";e.magnificPopup.registerModule(U,{options:{replaceSrc:function(e){return e.src.replace(/\.\w+$/,function(e){return"@2x"+e})},ratio:1},proto:{initRetina:function(){if(window.devicePixelRatio>1){var e=t.st.retina,n=e.ratio;n=isNaN(n)?n():n,n>1&&(x("ImageHasSize."+U,function(e,t){t.img.css({"max-width":t.img[0].naturalWidth/n,width:"100%"})}),x("ElementParse."+U,function(t,i){i.src=e.replaceSrc(i,n)}))}}}}),function(){var t=1e3,n="ontouchstart"in window,i=function(){I.off("touchmove"+r+" touchend"+r)},o="mfpFastClick",r="."+o;e.fn.mfpFastClick=function(o){return e(this).each(function(){var a,s=e(this);if(n){var l,c,d,u,p,f;s.on("touchstart"+r,function(e){u=!1,f=1,p=e.originalEvent?e.originalEvent.touches[0]:e.touches[0],c=p.clientX,d=p.clientY,I.on("touchmove"+r,function(e){p=e.originalEvent?e.originalEvent.touches:e.touches,f=p.length,p=p[0],(Math.abs(p.clientX-c)>10||Math.abs(p.clientY-d)>10)&&(u=!0,i())}).on("touchend"+r,function(e){i(),u||f>1||(a=!0,e.preventDefault(),clearTimeout(l),l=setTimeout(function(){a=!1},t),o())})})}s.on("click"+r,function(){a||o()})})},e.fn.destroyMfpFastClick=function(){e(this).off("touchstart"+r+" click"+r),n&&I.off("touchmove"+r+" touchend"+r)}}(),_()})(window.jQuery||window.Zepto);
\ No newline at end of file
diff --git a/sources/resources/Magnific-Popup/magnific-popup.css b/sources/resources/Magnific-Popup/magnific-popup.css
deleted file mode 100644
index 83a52cd..0000000
--- a/sources/resources/Magnific-Popup/magnific-popup.css
+++ /dev/null
@@ -1,363 +0,0 @@
-/* Magnific Popup CSS */
-.mfp-bg {
- top: 0;
- left: 0;
- width: 100%;
- height: 100%;
- z-index: 1042;
- overflow: hidden;
- position: fixed;
- background: #0b0b0b;
- opacity: 0.8;
- filter: alpha(opacity=80); }
-
-.mfp-wrap {
- top: 0;
- left: 0;
- width: 100%;
- height: 100%;
- z-index: 1043;
- position: fixed;
- outline: none !important;
- -webkit-backface-visibility: hidden; }
-
-.mfp-container {
- text-align: center;
- position: absolute;
- width: 100%;
- height: 100%;
- left: 0;
- top: 0;
- padding: 0 8px;
- -webkit-box-sizing: border-box;
- -moz-box-sizing: border-box;
- box-sizing: border-box; }
-
-.mfp-container:before {
- content: '';
- display: inline-block;
- height: 100%;
- vertical-align: middle; }
-
-.mfp-align-top .mfp-container:before {
- display: none; }
-
-.mfp-content {
- position: relative;
- display: inline-block;
- vertical-align: middle;
- margin: 0 auto;
- text-align: left;
- z-index: 1045; }
-
-.mfp-inline-holder .mfp-content, .mfp-ajax-holder .mfp-content {
- width: 100%;
- cursor: auto; }
-
-.mfp-ajax-cur {
- cursor: progress; }
-
-.mfp-zoom-out-cur, .mfp-zoom-out-cur .mfp-image-holder .mfp-close {
- cursor: -moz-zoom-out;
- cursor: -webkit-zoom-out;
- cursor: zoom-out; }
-
-.mfp-zoom {
- cursor: pointer;
- cursor: -webkit-zoom-in;
- cursor: -moz-zoom-in;
- cursor: zoom-in; }
-
-.mfp-auto-cursor .mfp-content {
- cursor: auto; }
-
-.mfp-close, .mfp-arrow, .mfp-preloader, .mfp-counter {
- -webkit-user-select: none;
- -moz-user-select: none;
- user-select: none; }
-
-.mfp-loading.mfp-figure {
- display: none; }
-
-.mfp-hide {
- display: none !important; }
-
-.mfp-preloader {
- color: #cccccc;
- position: absolute;
- top: 50%;
- width: auto;
- text-align: center;
- margin-top: -0.8em;
- left: 8px;
- right: 8px;
- z-index: 1044; }
- .mfp-preloader a {
- color: #cccccc; }
- .mfp-preloader a:hover {
- color: white; }
-
-.mfp-s-ready .mfp-preloader {
- display: none; }
-
-.mfp-s-error .mfp-content {
- display: none; }
-
-button.mfp-close, button.mfp-arrow {
- overflow: visible;
- cursor: pointer;
- background: transparent;
- border: 0;
- -webkit-appearance: none;
- display: block;
- outline: none;
- padding: 0;
- z-index: 1046;
- -webkit-box-shadow: none;
- box-shadow: none; }
-button::-moz-focus-inner {
- padding: 0;
- border: 0; }
-
-.mfp-close {
- width: 44px;
- height: 44px;
- line-height: 44px;
- position: absolute;
- right: 0;
- top: 0;
- text-decoration: none;
- text-align: center;
- opacity: 0.65;
- padding: 0 0 18px 10px;
- color: white;
- font-style: normal;
- font-size: 28px;
- font-family: Arial, Baskerville, monospace; }
- .mfp-close:hover, .mfp-close:focus {
- opacity: 1; }
- .mfp-close:active {
- top: 1px; }
-
-.mfp-close-btn-in .mfp-close {
- color: #333333; }
-
-.mfp-image-holder .mfp-close, .mfp-iframe-holder .mfp-close {
- color: white;
- right: -6px;
- text-align: right;
- padding-right: 6px;
- width: 100%; }
-
-.mfp-counter {
- position: absolute;
- top: 0;
- right: 0;
- color: #cccccc;
- font-size: 12px;
- line-height: 18px; }
-
-.mfp-arrow {
- position: absolute;
- opacity: 0.65;
- margin: 0;
- top: 50%;
- margin-top: -55px;
- padding: 0;
- width: 90px;
- height: 110px;
- -webkit-tap-highlight-color: rgba(0, 0, 0, 0); }
- .mfp-arrow:active {
- margin-top: -54px; }
- .mfp-arrow:hover, .mfp-arrow:focus {
- opacity: 1; }
- .mfp-arrow:before, .mfp-arrow:after, .mfp-arrow .mfp-b, .mfp-arrow .mfp-a {
- content: '';
- display: block;
- width: 0;
- height: 0;
- position: absolute;
- left: 0;
- top: 0;
- margin-top: 35px;
- margin-left: 35px;
- border: medium inset transparent; }
- .mfp-arrow:after, .mfp-arrow .mfp-a {
- border-top-width: 13px;
- border-bottom-width: 13px;
- top: 8px; }
- .mfp-arrow:before, .mfp-arrow .mfp-b {
- border-top-width: 21px;
- border-bottom-width: 21px; }
-
-.mfp-arrow-left {
- left: 0; }
- .mfp-arrow-left:after, .mfp-arrow-left .mfp-a {
- border-right: 17px solid white;
- margin-left: 31px; }
- .mfp-arrow-left:before, .mfp-arrow-left .mfp-b {
- margin-left: 25px;
- border-right: 27px solid #3f3f3f; }
-
-.mfp-arrow-right {
- right: 0; }
- .mfp-arrow-right:after, .mfp-arrow-right .mfp-a {
- border-left: 17px solid white;
- margin-left: 39px; }
- .mfp-arrow-right:before, .mfp-arrow-right .mfp-b {
- border-left: 27px solid #3f3f3f; }
-
-.mfp-iframe-holder {
- padding-top: 40px;
- padding-bottom: 40px; }
- .mfp-iframe-holder .mfp-content {
- line-height: 0;
- width: 100%;
- max-width: 900px; }
- .mfp-iframe-holder .mfp-close {
- top: -40px; }
-
-.mfp-iframe-scaler {
- width: 100%;
- height: 0;
- overflow: hidden;
- padding-top: 56.25%; }
- .mfp-iframe-scaler iframe {
- position: absolute;
- display: block;
- top: 0;
- left: 0;
- width: 100%;
- height: 100%;
- box-shadow: 0 0 8px rgba(0, 0, 0, 0.6);
- background: black; }
-
-/* Main image in popup */
-img.mfp-img {
- width: auto;
- max-width: 100%;
- height: auto;
- display: block;
- line-height: 0;
- -webkit-box-sizing: border-box;
- -moz-box-sizing: border-box;
- box-sizing: border-box;
- padding: 40px 0 40px;
- margin: 0 auto; }
-
-/* The shadow behind the image */
-.mfp-figure {
- line-height: 0; }
- .mfp-figure:after {
- content: '';
- position: absolute;
- left: 0;
- top: 40px;
- bottom: 40px;
- display: block;
- right: 0;
- width: auto;
- height: auto;
- z-index: -1;
- box-shadow: 0 0 8px rgba(0, 0, 0, 0.6);
- background: #444444; }
- .mfp-figure small {
- color: #bdbdbd;
- display: block;
- font-size: 12px;
- line-height: 14px; }
-
-.mfp-bottom-bar {
- margin-top: -36px;
- position: absolute;
- top: 100%;
- left: 0;
- width: 100%;
- cursor: auto; }
-
-.mfp-title {
- text-align: left;
- line-height: 18px;
- color: #f3f3f3;
- word-wrap: break-word;
- padding-right: 36px; }
-
-.mfp-image-holder .mfp-content {
- max-width: 100%; }
-
-.mfp-gallery .mfp-image-holder .mfp-figure {
- cursor: pointer; }
-
-@media screen and (max-width: 800px) and (orientation: landscape), screen and (max-height: 300px) {
- /**
- * Remove all paddings around the image on small screen
- */
- .mfp-img-mobile .mfp-image-holder {
- padding-left: 0;
- padding-right: 0; }
- .mfp-img-mobile img.mfp-img {
- padding: 0; }
- .mfp-img-mobile .mfp-figure {
- /* The shadow behind the image */ }
- .mfp-img-mobile .mfp-figure:after {
- top: 0;
- bottom: 0; }
- .mfp-img-mobile .mfp-figure small {
- display: inline;
- margin-left: 5px; }
- .mfp-img-mobile .mfp-bottom-bar {
- background: rgba(0, 0, 0, 0.6);
- bottom: 0;
- margin: 0;
- top: auto;
- padding: 3px 5px;
- position: fixed;
- -webkit-box-sizing: border-box;
- -moz-box-sizing: border-box;
- box-sizing: border-box; }
- .mfp-img-mobile .mfp-bottom-bar:empty {
- padding: 0; }
- .mfp-img-mobile .mfp-counter {
- right: 5px;
- top: 3px; }
- .mfp-img-mobile .mfp-close {
- top: 0;
- right: 0;
- width: 35px;
- height: 35px;
- line-height: 35px;
- background: rgba(0, 0, 0, 0.6);
- position: fixed;
- text-align: center;
- padding: 0; } }
-
-@media all and (max-width: 900px) {
- .mfp-arrow {
- -webkit-transform: scale(0.75);
- transform: scale(0.75); }
- .mfp-arrow-left {
- -webkit-transform-origin: 0;
- transform-origin: 0; }
- .mfp-arrow-right {
- -webkit-transform-origin: 100%;
- transform-origin: 100%; }
- .mfp-container {
- padding-left: 6px;
- padding-right: 6px; } }
-
-.mfp-ie7 .mfp-img {
- padding: 0; }
-.mfp-ie7 .mfp-bottom-bar {
- width: 600px;
- left: 50%;
- margin-left: -300px;
- margin-top: 5px;
- padding-bottom: 5px; }
-.mfp-ie7 .mfp-container {
- padding: 0; }
-.mfp-ie7 .mfp-content {
- padding-top: 44px; }
-.mfp-ie7 .mfp-close {
- top: 0;
- right: 0;
- padding-top: 0; }
diff --git a/sources/resources/PHPMailer/LICENSE b/sources/resources/PHPMailer/LICENSE
deleted file mode 100644
index f3f1b3b..0000000
--- a/sources/resources/PHPMailer/LICENSE
+++ /dev/null
@@ -1,504 +0,0 @@
- GNU LESSER GENERAL PUBLIC LICENSE
- Version 2.1, February 1999
-
- Copyright (C) 1991, 1999 Free Software Foundation, Inc.
- 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
-[This is the first released version of the Lesser GPL. It also counts
- as the successor of the GNU Library Public License, version 2, hence
- the version number 2.1.]
-
- Preamble
-
- The licenses for most software are designed to take away your
-freedom to share and change it. By contrast, the GNU General Public
-Licenses are intended to guarantee your freedom to share and change
-free software--to make sure the software is free for all its users.
-
- This license, the Lesser General Public License, applies to some
-specially designated software packages--typically libraries--of the
-Free Software Foundation and other authors who decide to use it. You
-can use it too, but we suggest you first think carefully about whether
-this license or the ordinary General Public License is the better
-strategy to use in any particular case, based on the explanations below.
-
- When we speak of free software, we are referring to freedom of use,
-not price. Our General Public Licenses are designed to make sure that
-you have the freedom to distribute copies of free software (and charge
-for this service if you wish); that you receive source code or can get
-it if you want it; that you can change the software and use pieces of
-it in new free programs; and that you are informed that you can do
-these things.
-
- To protect your rights, we need to make restrictions that forbid
-distributors to deny you these rights or to ask you to surrender these
-rights. These restrictions translate to certain responsibilities for
-you if you distribute copies of the library or if you modify it.
-
- For example, if you distribute copies of the library, whether gratis
-or for a fee, you must give the recipients all the rights that we gave
-you. You must make sure that they, too, receive or can get the source
-code. If you link other code with the library, you must provide
-complete object files to the recipients, so that they can relink them
-with the library after making changes to the library and recompiling
-it. And you must show them these terms so they know their rights.
-
- We protect your rights with a two-step method: (1) we copyright the
-library, and (2) we offer you this license, which gives you legal
-permission to copy, distribute and/or modify the library.
-
- To protect each distributor, we want to make it very clear that
-there is no warranty for the free library. Also, if the library is
-modified by someone else and passed on, the recipients should know
-that what they have is not the original version, so that the original
-author's reputation will not be affected by problems that might be
-introduced by others.
-
- Finally, software patents pose a constant threat to the existence of
-any free program. We wish to make sure that a company cannot
-effectively restrict the users of a free program by obtaining a
-restrictive license from a patent holder. Therefore, we insist that
-any patent license obtained for a version of the library must be
-consistent with the full freedom of use specified in this license.
-
- Most GNU software, including some libraries, is covered by the
-ordinary GNU General Public License. This license, the GNU Lesser
-General Public License, applies to certain designated libraries, and
-is quite different from the ordinary General Public License. We use
-this license for certain libraries in order to permit linking those
-libraries into non-free programs.
-
- When a program is linked with a library, whether statically or using
-a shared library, the combination of the two is legally speaking a
-combined work, a derivative of the original library. The ordinary
-General Public License therefore permits such linking only if the
-entire combination fits its criteria of freedom. The Lesser General
-Public License permits more lax criteria for linking other code with
-the library.
-
- We call this license the "Lesser" General Public License because it
-does Less to protect the user's freedom than the ordinary General
-Public License. It also provides other free software developers Less
-of an advantage over competing non-free programs. These disadvantages
-are the reason we use the ordinary General Public License for many
-libraries. However, the Lesser license provides advantages in certain
-special circumstances.
-
- For example, on rare occasions, there may be a special need to
-encourage the widest possible use of a certain library, so that it becomes
-a de-facto standard. To achieve this, non-free programs must be
-allowed to use the library. A more frequent case is that a free
-library does the same job as widely used non-free libraries. In this
-case, there is little to gain by limiting the free library to free
-software only, so we use the Lesser General Public License.
-
- In other cases, permission to use a particular library in non-free
-programs enables a greater number of people to use a large body of
-free software. For example, permission to use the GNU C Library in
-non-free programs enables many more people to use the whole GNU
-operating system, as well as its variant, the GNU/Linux operating
-system.
-
- Although the Lesser General Public License is Less protective of the
-users' freedom, it does ensure that the user of a program that is
-linked with the Library has the freedom and the wherewithal to run
-that program using a modified version of the Library.
-
- The precise terms and conditions for copying, distribution and
-modification follow. Pay close attention to the difference between a
-"work based on the library" and a "work that uses the library". The
-former contains code derived from the library, whereas the latter must
-be combined with the library in order to run.
-
- GNU LESSER GENERAL PUBLIC LICENSE
- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
- 0. This License Agreement applies to any software library or other
-program which contains a notice placed by the copyright holder or
-other authorized party saying it may be distributed under the terms of
-this Lesser General Public License (also called "this License").
-Each licensee is addressed as "you".
-
- A "library" means a collection of software functions and/or data
-prepared so as to be conveniently linked with application programs
-(which use some of those functions and data) to form executables.
-
- The "Library", below, refers to any such software library or work
-which has been distributed under these terms. A "work based on the
-Library" means either the Library or any derivative work under
-copyright law: that is to say, a work containing the Library or a
-portion of it, either verbatim or with modifications and/or translated
-straightforwardly into another language. (Hereinafter, translation is
-included without limitation in the term "modification".)
-
- "Source code" for a work means the preferred form of the work for
-making modifications to it. For a library, complete source code means
-all the source code for all modules it contains, plus any associated
-interface definition files, plus the scripts used to control compilation
-and installation of the library.
-
- Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope. The act of
-running a program using the Library is not restricted, and output from
-such a program is covered only if its contents constitute a work based
-on the Library (independent of the use of the Library in a tool for
-writing it). Whether that is true depends on what the Library does
-and what the program that uses the Library does.
-
- 1. You may copy and distribute verbatim copies of the Library's
-complete source code as you receive it, in any medium, provided that
-you conspicuously and appropriately publish on each copy an
-appropriate copyright notice and disclaimer of warranty; keep intact
-all the notices that refer to this License and to the absence of any
-warranty; and distribute a copy of this License along with the
-Library.
-
- You may charge a fee for the physical act of transferring a copy,
-and you may at your option offer warranty protection in exchange for a
-fee.
-
- 2. You may modify your copy or copies of the Library or any portion
-of it, thus forming a work based on the Library, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
- a) The modified work must itself be a software library.
-
- b) You must cause the files modified to carry prominent notices
- stating that you changed the files and the date of any change.
-
- c) You must cause the whole of the work to be licensed at no
- charge to all third parties under the terms of this License.
-
- d) If a facility in the modified Library refers to a function or a
- table of data to be supplied by an application program that uses
- the facility, other than as an argument passed when the facility
- is invoked, then you must make a good faith effort to ensure that,
- in the event an application does not supply such function or
- table, the facility still operates, and performs whatever part of
- its purpose remains meaningful.
-
- (For example, a function in a library to compute square roots has
- a purpose that is entirely well-defined independent of the
- application. Therefore, Subsection 2d requires that any
- application-supplied function or table used by this function must
- be optional: if the application does not supply it, the square
- root function must still compute square roots.)
-
-These requirements apply to the modified work as a whole. If
-identifiable sections of that work are not derived from the Library,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works. But when you
-distribute the same sections as part of a whole which is a work based
-on the Library, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote
-it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Library.
-
-In addition, mere aggregation of another work not based on the Library
-with the Library (or with a work based on the Library) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
- 3. You may opt to apply the terms of the ordinary GNU General Public
-License instead of this License to a given copy of the Library. To do
-this, you must alter all the notices that refer to this License, so
-that they refer to the ordinary GNU General Public License, version 2,
-instead of to this License. (If a newer version than version 2 of the
-ordinary GNU General Public License has appeared, then you can specify
-that version instead if you wish.) Do not make any other change in
-these notices.
-
- Once this change is made in a given copy, it is irreversible for
-that copy, so the ordinary GNU General Public License applies to all
-subsequent copies and derivative works made from that copy.
-
- This option is useful when you wish to copy part of the code of
-the Library into a program that is not a library.
-
- 4. You may copy and distribute the Library (or a portion or
-derivative of it, under Section 2) in object code or executable form
-under the terms of Sections 1 and 2 above provided that you accompany
-it with the complete corresponding machine-readable source code, which
-must be distributed under the terms of Sections 1 and 2 above on a
-medium customarily used for software interchange.
-
- If distribution of object code is made by offering access to copy
-from a designated place, then offering equivalent access to copy the
-source code from the same place satisfies the requirement to
-distribute the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
- 5. A program that contains no derivative of any portion of the
-Library, but is designed to work with the Library by being compiled or
-linked with it, is called a "work that uses the Library". Such a
-work, in isolation, is not a derivative work of the Library, and
-therefore falls outside the scope of this License.
-
- However, linking a "work that uses the Library" with the Library
-creates an executable that is a derivative of the Library (because it
-contains portions of the Library), rather than a "work that uses the
-library". The executable is therefore covered by this License.
-Section 6 states terms for distribution of such executables.
-
- When a "work that uses the Library" uses material from a header file
-that is part of the Library, the object code for the work may be a
-derivative work of the Library even though the source code is not.
-Whether this is true is especially significant if the work can be
-linked without the Library, or if the work is itself a library. The
-threshold for this to be true is not precisely defined by law.
-
- If such an object file uses only numerical parameters, data
-structure layouts and accessors, and small macros and small inline
-functions (ten lines or less in length), then the use of the object
-file is unrestricted, regardless of whether it is legally a derivative
-work. (Executables containing this object code plus portions of the
-Library will still fall under Section 6.)
-
- Otherwise, if the work is a derivative of the Library, you may
-distribute the object code for the work under the terms of Section 6.
-Any executables containing that work also fall under Section 6,
-whether or not they are linked directly with the Library itself.
-
- 6. As an exception to the Sections above, you may also combine or
-link a "work that uses the Library" with the Library to produce a
-work containing portions of the Library, and distribute that work
-under terms of your choice, provided that the terms permit
-modification of the work for the customer's own use and reverse
-engineering for debugging such modifications.
-
- You must give prominent notice with each copy of the work that the
-Library is used in it and that the Library and its use are covered by
-this License. You must supply a copy of this License. If the work
-during execution displays copyright notices, you must include the
-copyright notice for the Library among them, as well as a reference
-directing the user to the copy of this License. Also, you must do one
-of these things:
-
- a) Accompany the work with the complete corresponding
- machine-readable source code for the Library including whatever
- changes were used in the work (which must be distributed under
- Sections 1 and 2 above); and, if the work is an executable linked
- with the Library, with the complete machine-readable "work that
- uses the Library", as object code and/or source code, so that the
- user can modify the Library and then relink to produce a modified
- executable containing the modified Library. (It is understood
- that the user who changes the contents of definitions files in the
- Library will not necessarily be able to recompile the application
- to use the modified definitions.)
-
- b) Use a suitable shared library mechanism for linking with the
- Library. A suitable mechanism is one that (1) uses at run time a
- copy of the library already present on the user's computer system,
- rather than copying library functions into the executable, and (2)
- will operate properly with a modified version of the library, if
- the user installs one, as long as the modified version is
- interface-compatible with the version that the work was made with.
-
- c) Accompany the work with a written offer, valid for at
- least three years, to give the same user the materials
- specified in Subsection 6a, above, for a charge no more
- than the cost of performing this distribution.
-
- d) If distribution of the work is made by offering access to copy
- from a designated place, offer equivalent access to copy the above
- specified materials from the same place.
-
- e) Verify that the user has already received a copy of these
- materials or that you have already sent this user a copy.
-
- For an executable, the required form of the "work that uses the
-Library" must include any data and utility programs needed for
-reproducing the executable from it. However, as a special exception,
-the materials to be distributed need not include anything that is
-normally distributed (in either source or binary form) with the major
-components (compiler, kernel, and so on) of the operating system on
-which the executable runs, unless that component itself accompanies
-the executable.
-
- It may happen that this requirement contradicts the license
-restrictions of other proprietary libraries that do not normally
-accompany the operating system. Such a contradiction means you cannot
-use both them and the Library together in an executable that you
-distribute.
-
- 7. You may place library facilities that are a work based on the
-Library side-by-side in a single library together with other library
-facilities not covered by this License, and distribute such a combined
-library, provided that the separate distribution of the work based on
-the Library and of the other library facilities is otherwise
-permitted, and provided that you do these two things:
-
- a) Accompany the combined library with a copy of the same work
- based on the Library, uncombined with any other library
- facilities. This must be distributed under the terms of the
- Sections above.
-
- b) Give prominent notice with the combined library of the fact
- that part of it is a work based on the Library, and explaining
- where to find the accompanying uncombined form of the same work.
-
- 8. You may not copy, modify, sublicense, link with, or distribute
-the Library except as expressly provided under this License. Any
-attempt otherwise to copy, modify, sublicense, link with, or
-distribute the Library is void, and will automatically terminate your
-rights under this License. However, parties who have received copies,
-or rights, from you under this License will not have their licenses
-terminated so long as such parties remain in full compliance.
-
- 9. You are not required to accept this License, since you have not
-signed it. However, nothing else grants you permission to modify or
-distribute the Library or its derivative works. These actions are
-prohibited by law if you do not accept this License. Therefore, by
-modifying or distributing the Library (or any work based on the
-Library), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Library or works based on it.
-
- 10. Each time you redistribute the Library (or any work based on the
-Library), the recipient automatically receives a license from the
-original licensor to copy, distribute, link with or modify the Library
-subject to these terms and conditions. You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties with
-this License.
-
- 11. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Library at all. For example, if a patent
-license would not permit royalty-free redistribution of the Library by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Library.
-
-If any portion of this section is held invalid or unenforceable under any
-particular circumstance, the balance of the section is intended to apply,
-and the section as a whole is intended to apply in other circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system which is
-implemented by public license practices. Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
- 12. If the distribution and/or use of the Library is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Library under this License may add
-an explicit geographical distribution limitation excluding those countries,
-so that distribution is permitted only in or among countries not thus
-excluded. In such case, this License incorporates the limitation as if
-written in the body of this License.
-
- 13. The Free Software Foundation may publish revised and/or new
-versions of the Lesser General Public License from time to time.
-Such new versions will be similar in spirit to the present version,
-but may differ in detail to address new problems or concerns.
-
-Each version is given a distinguishing version number. If the Library
-specifies a version number of this License which applies to it and
-"any later version", you have the option of following the terms and
-conditions either of that version or of any later version published by
-the Free Software Foundation. If the Library does not specify a
-license version number, you may choose any version ever published by
-the Free Software Foundation.
-
- 14. If you wish to incorporate parts of the Library into other free
-programs whose distribution conditions are incompatible with these,
-write to the author to ask for permission. For software which is
-copyrighted by the Free Software Foundation, write to the Free
-Software Foundation; we sometimes make exceptions for this. Our
-decision will be guided by the two goals of preserving the free status
-of all derivatives of our free software and of promoting the sharing
-and reuse of software generally.
-
- NO WARRANTY
-
- 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
-WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
-EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
-OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
-KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
-IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
-LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
-THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
- 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
-WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
-AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
-FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
-CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
-LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
-RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
-FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
-SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
-DAMAGES.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Libraries
-
- If you develop a new library, and you want it to be of the greatest
-possible use to the public, we recommend making it free software that
-everyone can redistribute and change. You can do so by permitting
-redistribution under these terms (or, alternatively, under the terms of the
-ordinary General Public License).
-
- To apply these terms, attach the following notices to the library. It is
-safest to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least the
-"copyright" line and a pointer to where the full notice is found.
-
-
- Copyright (C)
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Lesser General Public
- License as published by the Free Software Foundation; either
- version 2.1 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public
- License along with this library; if not, write to the Free Software
- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-Also add information on how to contact you by electronic and paper mail.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the library, if
-necessary. Here is a sample; alter the names:
-
- Yoyodyne, Inc., hereby disclaims all copyright interest in the
- library `Frob' (a library for tweaking knobs) written by James Random Hacker.
-
- , 1 April 1990
- Ty Coon, President of Vice
-
-That's all there is to it!
-
-
diff --git a/sources/resources/PHPMailer/README.md b/sources/resources/PHPMailer/README.md
deleted file mode 100644
index 671141d..0000000
--- a/sources/resources/PHPMailer/README.md
+++ /dev/null
@@ -1,134 +0,0 @@
-# PHPMailer - A full-featured email creation and transfer class for PHP
-
-Build status: [![Build Status](https://travis-ci.org/Synchro/PHPMailer.png)](https://travis-ci.org/Synchro/PHPMailer)
-
-## Class Features
-
-- Probably the world's most popular code for sending email from PHP!
-- Used by many open-source projects: Drupal, SugarCRM, Yii, Joomla! and many more
-- Integrated SMTP support - send without a local mail server
-- Send emails with multiple TOs, CCs, BCCs and REPLY-TOs
-- Multipart/alternative emails for mail clients that do not read HTML email
-- Support for 8bit, base64, binary, and quoted-printable encoding
-- SMTP authentication with LOGIN, PLAIN, NTLM and CRAM-MD5 mechanisms
-- Native language support
-- Compatible with PHP 5.0 and later
-- Much more!
-
-## Why you might need it
-
-Many PHP developers utilize email in their code. The only PHP function that supports this is the mail() function. However, it does not provide any assistance for making use of popular features such as HTML-based emails and attachments.
-
-Formatting email correctly is surprisingly difficult. There are myriad overlapping RFCs, requiring tight adherence to horribly complicated formatting and encoding rules - the vast majority of code that you'll find online that uses the mail() function directly is just plain wrong!
-*Please* don't be tempted to do it yourself - if you don't use PHPMailer, there are many other excellent libraries that you should look at before rolling your own - try SwiftMailer, Zend_Mail, eZcomponents etc.
-
-The PHP mail() function usually sends via a local mail server, typically fronted by a `sendmail` binary on Linux, BSD and OS X platforms, however, Windows usually doesn't include a local mail server; PHPMailer's integrated SMTP implementation allows email sending on Windows platforms without a local mail server.
-
-## License
-
-This software is licenced under the [LGPL 2.1](http://www.gnu.org/licenses/lgpl-2.1.html). Please read LICENSE for information on the
-software availability and distribution.
-
-## Installation
-
-PHPMailer is available via [Composer/Packagist](https://packagist.org/packages/phpmailer/phpmailer). Alternatively, just copy the contents of the PHPMailer folder into somewhere that's in your PHP `include_path` setting. If you don't speak git or just want a tarball, click the 'zip' button at the top of the page in GitHub.
-
-
-## A Simple Example
-
-```php
-IsSMTP(); // Set mailer to use SMTP
-$mail->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup server
-$mail->SMTPAuth = true; // Enable SMTP authentication
-$mail->Username = 'jswan'; // SMTP username
-$mail->Password = 'secret'; // SMTP password
-$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
-
-$mail->From = 'from@example.com';
-$mail->FromName = 'Mailer';
-$mail->AddAddress('josh@example.net', 'Josh Adams'); // Add a recipient
-$mail->AddAddress('ellen@example.com'); // Name is optional
-$mail->AddReplyTo('info@example.com', 'Information');
-$mail->AddCC('cc@example.com');
-$mail->AddBCC('bcc@example.com');
-
-$mail->WordWrap = 50; // Set word wrap to 50 characters
-$mail->AddAttachment('/var/tmp/file.tar.gz'); // Add attachments
-$mail->AddAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
-$mail->IsHTML(true); // Set email format to HTML
-
-$mail->Subject = 'Here is the subject';
-$mail->Body = 'This is the HTML message body in bold!';
-$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
-
-if(!$mail->Send()) {
- echo 'Message could not be sent.';
- echo 'Mailer Error: ' . $mail->ErrorInfo;
- exit;
-}
-
-echo 'Message has been sent';
-```
-
-You'll find plenty more to play with in the `examples` folder.
-
-That's it. You should now be ready to use PHPMailer!
-
-## Localization
-PHPMailer defaults to English, but in the `languages` folder you'll find numerous translations for PHPMailer error messages that you may encounter. Their filenames contain [ISO 639-1](http://en.wikipedia.org/wiki/ISO_639-1) language code for the translations, for example `fr` for French. To specify a language, you need to tell PHPMailer which one to use, like this:
-
-```php
-// To load the French version
-$mail->SetLanguage('fr', '/optional/path/to/language/directory/');
-```
-
-## Documentation
-
-You'll find some basic user-level docs in the docs folder, and you can generate complete API-level documentation using the `generatedocs.sh` shell script in the docs folder, though you'll need to install [PHPDocumentor](http://www.phpdoc.org) first.
-
-## Tests
-
-You'll find a PHPUnit test script in the `test` folder.
-
-Build status: [![Build Status](https://travis-ci.org/PHPMailer/PHPMailer.png)](https://travis-ci.org/PHPMailer/PHPMailer)
-
-If this isn't passing, is there something you can do to help?
-
-## Contributing
-
-Please submit bug reports, suggestions and pull requests to the [GitHub issue tracker](https://github.com/PHPMailer/PHPMailer/issues).
-
-We're particularly interested in fixing edge-cases, expanding test coverage and updating translations.
-
-With the move to the PHPMailer GitHub organisation, you'll need to update any remote URLs referencing the old GitHub location with a command like this from within your clone:
-
-git remote set-url upstream https://github.com/PHPMailer/PHPMailer.git
-
-Please *don't* use the SourceForge or Google Code projects any more.
-
-## Changelog
-
-See changelog.md
-
-## History
-- PHPMailer was originally written in 2001 by Brent R. Matzelle as a [SourceForge project](http://sourceforge.net/projects/phpmailer/).
-- Marcus Bointon (coolbru on SF) and Andy Prevost (codeworxtech) took over the project in 2004.
-- Became an Apache incubator project on Google Code in 2010, managed by Jim Jagielski.
-- Marcus created his fork on [GitHub](https://github.com/Synchro/PHPMailer).
-- Jim and Marcus decide to join forces and use GitHub as the canonical and official repo for PHPMailer.
-- PHPMailer moves to the [PHPMailer organisation](https://github.com/PHPMailer) on GitHub.
-
-### What's changed since moving from SourceForge?
-- Official successor to the SourceForge and Google Code projects.
-- Test suite.
-- Continuous integration with Travis-CI.
-- Composer support.
-- Rolling releases.
-- Additional languages and language strings.
-- CRAM-MD5 authentication support.
-- Preserves full repo history of authors, commits and branches from the original SourceForge project.
diff --git a/sources/resources/PHPMailer/class.phpmailer.php b/sources/resources/PHPMailer/class.phpmailer.php
deleted file mode 100644
index 667f187..0000000
--- a/sources/resources/PHPMailer/class.phpmailer.php
+++ /dev/null
@@ -1,2810 +0,0 @@
-UseSendmailOptions) ) {
- $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header);
- } else {
- $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header, $params);
- }
- return $rt;
- }
-
- /**
- * Outputs debugging info via user-defined method
- * @param string $str
- */
- private function edebug($str) {
- if ($this->Debugoutput == "error_log") {
- error_log($str);
- } else {
- echo $str;
- }
- }
-
- /**
- * Constructor
- * @param boolean $exceptions Should we throw external exceptions?
- */
- public function __construct($exceptions = false) {
- $this->exceptions = ($exceptions == true);
- }
-
- /**
- * Destructor
- */
- public function __destruct() {
- if ($this->Mailer == 'smtp') { //Close any open SMTP connection nicely
- $this->SmtpClose();
- }
- }
-
- /**
- * Sets message type to HTML.
- * @param bool $ishtml
- * @return void
- */
- public function IsHTML($ishtml = true) {
- if ($ishtml) {
- $this->ContentType = 'text/html';
- } else {
- $this->ContentType = 'text/plain';
- }
- }
-
- /**
- * Sets Mailer to send message using SMTP.
- * @return void
- */
- public function IsSMTP() {
- $this->Mailer = 'smtp';
- }
-
- /**
- * Sets Mailer to send message using PHP mail() function.
- * @return void
- */
- public function IsMail() {
- $this->Mailer = 'mail';
- }
-
- /**
- * Sets Mailer to send message using the $Sendmail program.
- * @return void
- */
- public function IsSendmail() {
- if (!stristr(ini_get('sendmail_path'), 'sendmail')) {
- $this->Sendmail = '/var/qmail/bin/sendmail';
- }
- $this->Mailer = 'sendmail';
- }
-
- /**
- * Sets Mailer to send message using the qmail MTA.
- * @return void
- */
- public function IsQmail() {
- if (stristr(ini_get('sendmail_path'), 'qmail')) {
- $this->Sendmail = '/var/qmail/bin/sendmail';
- }
- $this->Mailer = 'sendmail';
- }
-
- /////////////////////////////////////////////////
- // METHODS, RECIPIENTS
- /////////////////////////////////////////////////
-
- /**
- * Adds a "To" address.
- * @param string $address
- * @param string $name
- * @return boolean true on success, false if address already used
- */
- public function AddAddress($address, $name = '') {
- return $this->AddAnAddress('to', $address, $name);
- }
-
- /**
- * Adds a "Cc" address.
- * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
- * @param string $address
- * @param string $name
- * @return boolean true on success, false if address already used
- */
- public function AddCC($address, $name = '') {
- return $this->AddAnAddress('cc', $address, $name);
- }
-
- /**
- * Adds a "Bcc" address.
- * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
- * @param string $address
- * @param string $name
- * @return boolean true on success, false if address already used
- */
- public function AddBCC($address, $name = '') {
- return $this->AddAnAddress('bcc', $address, $name);
- }
-
- /**
- * Adds a "Reply-to" address.
- * @param string $address
- * @param string $name
- * @return boolean
- */
- public function AddReplyTo($address, $name = '') {
- return $this->AddAnAddress('Reply-To', $address, $name);
- }
-
- /**
- * Adds an address to one of the recipient arrays
- * Addresses that have been added already return false, but do not throw exceptions
- * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo'
- * @param string $address The email address to send to
- * @param string $name
- * @throws phpmailerException
- * @return boolean true on success, false if address already used or invalid in some way
- * @access protected
- */
- protected function AddAnAddress($kind, $address, $name = '') {
- if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) {
- $this->SetError($this->Lang('Invalid recipient array').': '.$kind);
- if ($this->exceptions) {
- throw new phpmailerException('Invalid recipient array: ' . $kind);
- }
- if ($this->SMTPDebug) {
- $this->edebug($this->Lang('Invalid recipient array').': '.$kind);
- }
- return false;
- }
- $address = trim($address);
- $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
- if (!$this->ValidateAddress($address)) {
- $this->SetError($this->Lang('invalid_address').': '. $address);
- if ($this->exceptions) {
- throw new phpmailerException($this->Lang('invalid_address').': '.$address);
- }
- if ($this->SMTPDebug) {
- $this->edebug($this->Lang('invalid_address').': '.$address);
- }
- return false;
- }
- if ($kind != 'Reply-To') {
- if (!isset($this->all_recipients[strtolower($address)])) {
- array_push($this->$kind, array($address, $name));
- $this->all_recipients[strtolower($address)] = true;
- return true;
- }
- } else {
- if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
- $this->ReplyTo[strtolower($address)] = array($address, $name);
- return true;
- }
- }
- return false;
-}
-
- /**
- * Set the From and FromName properties
- * @param string $address
- * @param string $name
- * @param int $auto Also set Reply-To and Sender
- * @throws phpmailerException
- * @return boolean
- */
- public function SetFrom($address, $name = '', $auto = 1) {
- $address = trim($address);
- $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
- if (!$this->ValidateAddress($address)) {
- $this->SetError($this->Lang('invalid_address').': '. $address);
- if ($this->exceptions) {
- throw new phpmailerException($this->Lang('invalid_address').': '.$address);
- }
- if ($this->SMTPDebug) {
- $this->edebug($this->Lang('invalid_address').': '.$address);
- }
- return false;
- }
- $this->From = $address;
- $this->FromName = $name;
- if ($auto) {
- if (empty($this->ReplyTo)) {
- $this->AddAnAddress('Reply-To', $address, $name);
- }
- if (empty($this->Sender)) {
- $this->Sender = $address;
- }
- }
- return true;
- }
-
- /**
- * Check that a string looks roughly like an email address should
- * Static so it can be used without instantiation, public so people can overload
- * Conforms to RFC5322: Uses *correct* regex on which FILTER_VALIDATE_EMAIL is
- * based; So why not use FILTER_VALIDATE_EMAIL? Because it was broken to
- * not allow a@b type valid addresses :(
- * @link http://squiloople.com/2009/12/20/email-address-validation/
- * @copyright regex Copyright Michael Rushton 2009-10 | http://squiloople.com/ | Feel free to use and redistribute this code. But please keep this copyright notice.
- * @param string $address The email address to check
- * @return boolean
- * @static
- * @access public
- */
- public static function ValidateAddress($address) {
- if (defined('PCRE_VERSION')) { //Check this instead of extension_loaded so it works when that function is disabled
- if (version_compare(PCRE_VERSION, '8.0') >= 0) {
- return (boolean)preg_match('/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD', $address);
- } else {
- //Fall back to an older regex that doesn't need a recent PCRE
- return (boolean)preg_match('/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD', $address);
- }
- } else {
- //No PCRE! Do something _very_ approximate!
- //Check the address is 3 chars or longer and contains an @ that's not the first or last char
- return (strlen($address) >= 3 and strpos($address, '@') >= 1 and strpos($address, '@') != strlen($address) - 1);
- }
- }
-
- /////////////////////////////////////////////////
- // METHODS, MAIL SENDING
- /////////////////////////////////////////////////
-
- /**
- * Creates message and assigns Mailer. If the message is
- * not sent successfully then it returns false. Use the ErrorInfo
- * variable to view description of the error.
- * @throws phpmailerException
- * @return bool
- */
- public function Send() {
- try {
- if(!$this->PreSend()) return false;
- return $this->PostSend();
- } catch (phpmailerException $e) {
- $this->mailHeader = '';
- $this->SetError($e->getMessage());
- if ($this->exceptions) {
- throw $e;
- }
- return false;
- }
- }
-
- /**
- * Prep mail by constructing all message entities
- * @throws phpmailerException
- * @return bool
- */
- public function PreSend() {
- try {
- $this->mailHeader = "";
- if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
- throw new phpmailerException($this->Lang('provide_address'), self::STOP_CRITICAL);
- }
-
- // Set whether the message is multipart/alternative
- if(!empty($this->AltBody)) {
- $this->ContentType = 'multipart/alternative';
- }
-
- $this->error_count = 0; // reset errors
- $this->SetMessageType();
- //Refuse to send an empty message unless we are specifically allowing it
- if (!$this->AllowEmpty and empty($this->Body)) {
- throw new phpmailerException($this->Lang('empty_message'), self::STOP_CRITICAL);
- }
-
- $this->MIMEHeader = $this->CreateHeader();
- $this->MIMEBody = $this->CreateBody();
-
- // To capture the complete message when using mail(), create
- // an extra header list which CreateHeader() doesn't fold in
- if ($this->Mailer == 'mail') {
- if (count($this->to) > 0) {
- $this->mailHeader .= $this->AddrAppend("To", $this->to);
- } else {
- $this->mailHeader .= $this->HeaderLine("To", "undisclosed-recipients:;");
- }
- $this->mailHeader .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader(trim($this->Subject))));
- }
-
- // digitally sign with DKIM if enabled
- if (!empty($this->DKIM_domain) && !empty($this->DKIM_private) && !empty($this->DKIM_selector) && !empty($this->DKIM_domain) && file_exists($this->DKIM_private)) {
- $header_dkim = $this->DKIM_Add($this->MIMEHeader . $this->mailHeader, $this->EncodeHeader($this->SecureHeader($this->Subject)), $this->MIMEBody);
- $this->MIMEHeader = str_replace("\r\n", "\n", $header_dkim) . $this->MIMEHeader;
- }
-
- return true;
-
- } catch (phpmailerException $e) {
- $this->SetError($e->getMessage());
- if ($this->exceptions) {
- throw $e;
- }
- return false;
- }
- }
-
- /**
- * Actual Email transport function
- * Send the email via the selected mechanism
- * @throws phpmailerException
- * @return bool
- */
- public function PostSend() {
- try {
- // Choose the mailer and send through it
- switch($this->Mailer) {
- case 'sendmail':
- return $this->SendmailSend($this->MIMEHeader, $this->MIMEBody);
- case 'smtp':
- return $this->SmtpSend($this->MIMEHeader, $this->MIMEBody);
- case 'mail':
- return $this->MailSend($this->MIMEHeader, $this->MIMEBody);
- default:
- return $this->MailSend($this->MIMEHeader, $this->MIMEBody);
- }
- } catch (phpmailerException $e) {
- $this->SetError($e->getMessage());
- if ($this->exceptions) {
- throw $e;
- }
- if ($this->SMTPDebug) {
- $this->edebug($e->getMessage()."\n");
- }
- }
- return false;
- }
-
- /**
- * Sends mail using the $Sendmail program.
- * @param string $header The message headers
- * @param string $body The message body
- * @throws phpmailerException
- * @access protected
- * @return bool
- */
- protected function SendmailSend($header, $body) {
- if ($this->Sender != '') {
- $sendmail = sprintf("%s -oi -f%s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
- } else {
- $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail));
- }
- if ($this->SingleTo === true) {
- foreach ($this->SingleToArray as $val) {
- if(!@$mail = popen($sendmail, 'w')) {
- throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
- }
- fputs($mail, "To: " . $val . "\n");
- fputs($mail, $header);
- fputs($mail, $body);
- $result = pclose($mail);
- // implement call back function if it exists
- $isSent = ($result == 0) ? 1 : 0;
- $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
- if($result != 0) {
- throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
- }
- }
- } else {
- if(!@$mail = popen($sendmail, 'w')) {
- throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
- }
- fputs($mail, $header);
- fputs($mail, $body);
- $result = pclose($mail);
- // implement call back function if it exists
- $isSent = ($result == 0) ? 1 : 0;
- $this->doCallback($isSent, $this->to, $this->cc, $this->bcc, $this->Subject, $body);
- if($result != 0) {
- throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
- }
- }
- return true;
- }
-
- /**
- * Sends mail using the PHP mail() function.
- * @param string $header The message headers
- * @param string $body The message body
- * @throws phpmailerException
- * @access protected
- * @return bool
- */
- protected function MailSend($header, $body) {
- $toArr = array();
- foreach($this->to as $t) {
- $toArr[] = $this->AddrFormat($t);
- }
- $to = implode(', ', $toArr);
-
- if (empty($this->Sender)) {
- $params = " ";
- } else {
- $params = sprintf("-f%s", $this->Sender);
- }
- if ($this->Sender != '' and !ini_get('safe_mode')) {
- $old_from = ini_get('sendmail_from');
- ini_set('sendmail_from', $this->Sender);
- }
- $rt = false;
- if ($this->SingleTo === true && count($toArr) > 1) {
- foreach ($toArr as $val) {
- $rt = $this->mail_passthru($val, $this->Subject, $body, $header, $params);
- // implement call back function if it exists
- $isSent = ($rt == 1) ? 1 : 0;
- $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
- }
- } else {
- $rt = $this->mail_passthru($to, $this->Subject, $body, $header, $params);
- // implement call back function if it exists
- $isSent = ($rt == 1) ? 1 : 0;
- $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body);
- }
- if (isset($old_from)) {
- ini_set('sendmail_from', $old_from);
- }
- if(!$rt) {
- throw new phpmailerException($this->Lang('instantiate'), self::STOP_CRITICAL);
- }
- return true;
- }
-
- /**
- * Sends mail via SMTP using PhpSMTP
- * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
- * @param string $header The message headers
- * @param string $body The message body
- * @throws phpmailerException
- * @uses SMTP
- * @access protected
- * @return bool
- */
- protected function SmtpSend($header, $body) {
- require_once $this->PluginDir . 'class.smtp.php';
- $bad_rcpt = array();
-
- if(!$this->SmtpConnect()) {
- throw new phpmailerException($this->Lang('smtp_connect_failed'), self::STOP_CRITICAL);
- }
- $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender;
- if(!$this->smtp->Mail($smtp_from)) {
- $this->SetError($this->Lang('from_failed') . $smtp_from . ' : ' .implode(',', $this->smtp->getError()));
- throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL);
- }
-
- // Attempt to send attach all recipients
- foreach($this->to as $to) {
- if (!$this->smtp->Recipient($to[0])) {
- $bad_rcpt[] = $to[0];
- // implement call back function if it exists
- $isSent = 0;
- $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body);
- } else {
- // implement call back function if it exists
- $isSent = 1;
- $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body);
- }
- }
- foreach($this->cc as $cc) {
- if (!$this->smtp->Recipient($cc[0])) {
- $bad_rcpt[] = $cc[0];
- // implement call back function if it exists
- $isSent = 0;
- $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body);
- } else {
- // implement call back function if it exists
- $isSent = 1;
- $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body);
- }
- }
- foreach($this->bcc as $bcc) {
- if (!$this->smtp->Recipient($bcc[0])) {
- $bad_rcpt[] = $bcc[0];
- // implement call back function if it exists
- $isSent = 0;
- $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body);
- } else {
- // implement call back function if it exists
- $isSent = 1;
- $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body);
- }
- }
-
-
- if (count($bad_rcpt) > 0 ) { //Create error message for any bad addresses
- $badaddresses = implode(', ', $bad_rcpt);
- throw new phpmailerException($this->Lang('recipients_failed') . $badaddresses);
- }
- if(!$this->smtp->Data($header . $body)) {
- throw new phpmailerException($this->Lang('data_not_accepted'), self::STOP_CRITICAL);
- }
- if($this->SMTPKeepAlive == true) {
- $this->smtp->Reset();
- } else {
- $this->smtp->Quit();
- $this->smtp->Close();
- }
- return true;
- }
-
- /**
- * Initiates a connection to an SMTP server.
- * Returns false if the operation failed.
- * @uses SMTP
- * @access public
- * @throws phpmailerException
- * @return bool
- */
- public function SmtpConnect() {
- if(is_null($this->smtp)) {
- $this->smtp = new SMTP;
- }
-
- $this->smtp->Timeout = $this->Timeout;
- $this->smtp->do_debug = $this->SMTPDebug;
- $hosts = explode(';', $this->Host);
- $index = 0;
- $connection = $this->smtp->Connected();
-
- // Retry while there is no connection
- try {
- while($index < count($hosts) && !$connection) {
- $hostinfo = array();
- if (preg_match('/^(.+):([0-9]+)$/', $hosts[$index], $hostinfo)) {
- $host = $hostinfo[1];
- $port = $hostinfo[2];
- } else {
- $host = $hosts[$index];
- $port = $this->Port;
- }
-
- $tls = ($this->SMTPSecure == 'tls');
- $ssl = ($this->SMTPSecure == 'ssl');
-
- if ($this->smtp->Connect(($ssl ? 'ssl://':'').$host, $port, $this->Timeout)) {
-
- $hello = ($this->Helo != '' ? $this->Helo : $this->ServerHostname());
- $this->smtp->Hello($hello);
-
- if ($tls) {
- if (!$this->smtp->StartTLS()) {
- throw new phpmailerException($this->Lang('connect_host'));
- }
-
- //We must resend HELO after tls negotiation
- $this->smtp->Hello($hello);
- }
-
- $connection = true;
- if ($this->SMTPAuth) {
- if (!$this->smtp->Authenticate($this->Username, $this->Password, $this->AuthType, $this->Realm, $this->Workstation)) {
- throw new phpmailerException($this->Lang('authenticate'));
- }
- }
- }
- $index++;
- if (!$connection) {
- throw new phpmailerException($this->Lang('connect_host'));
- }
- }
- } catch (phpmailerException $e) {
- $this->smtp->Reset();
- if ($this->exceptions) {
- throw $e;
- }
- }
- return true;
- }
-
- /**
- * Closes the active SMTP session if one exists.
- * @return void
- */
- public function SmtpClose() {
- if ($this->smtp !== null) {
- if($this->smtp->Connected()) {
- $this->smtp->Quit();
- $this->smtp->Close();
- }
- }
- }
-
- /**
- * Sets the language for all class error messages.
- * Returns false if it cannot load the language file. The default language is English.
- * @param string $langcode ISO 639-1 2-character language code (e.g. Portuguese: "br")
- * @param string $lang_path Path to the language file directory
- * @return bool
- * @access public
- */
- function SetLanguage($langcode = 'en', $lang_path = 'language/') {
- //Define full set of translatable strings
- $PHPMAILER_LANG = array(
- 'authenticate' => 'SMTP Error: Could not authenticate.',
- 'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
- 'data_not_accepted' => 'SMTP Error: Data not accepted.',
- 'empty_message' => 'Message body empty',
- 'encoding' => 'Unknown encoding: ',
- 'execute' => 'Could not execute: ',
- 'file_access' => 'Could not access file: ',
- 'file_open' => 'File Error: Could not open file: ',
- 'from_failed' => 'The following From address failed: ',
- 'instantiate' => 'Could not instantiate mail function.',
- 'invalid_address' => 'Invalid address',
- 'mailer_not_supported' => ' mailer is not supported.',
- 'provide_address' => 'You must provide at least one recipient email address.',
- 'recipients_failed' => 'SMTP Error: The following recipients failed: ',
- 'signing' => 'Signing Error: ',
- 'smtp_connect_failed' => 'SMTP Connect() failed.',
- 'smtp_error' => 'SMTP server error: ',
- 'variable_set' => 'Cannot set or reset variable: '
- );
- //Overwrite language-specific strings. This way we'll never have missing translations - no more "language string failed to load"!
- $l = true;
- if ($langcode != 'en') { //There is no English translation file
- $l = @include $lang_path.'phpmailer.lang-'.$langcode.'.php';
- }
- $this->language = $PHPMAILER_LANG;
- return ($l == true); //Returns false if language not found
- }
-
- /**
- * Return the current array of language strings
- * @return array
- */
- public function GetTranslations() {
- return $this->language;
- }
-
- /////////////////////////////////////////////////
- // METHODS, MESSAGE CREATION
- /////////////////////////////////////////////////
-
- /**
- * Creates recipient headers.
- * @access public
- * @param string $type
- * @param array $addr
- * @return string
- */
- public function AddrAppend($type, $addr) {
- $addr_str = $type . ': ';
- $addresses = array();
- foreach ($addr as $a) {
- $addresses[] = $this->AddrFormat($a);
- }
- $addr_str .= implode(', ', $addresses);
- $addr_str .= $this->LE;
-
- return $addr_str;
- }
-
- /**
- * Formats an address correctly.
- * @access public
- * @param string $addr
- * @return string
- */
- public function AddrFormat($addr) {
- if (empty($addr[1])) {
- return $this->SecureHeader($addr[0]);
- } else {
- return $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">";
- }
- }
-
- /**
- * Wraps message for use with mailers that do not
- * automatically perform wrapping and for quoted-printable.
- * Original written by philippe.
- * @param string $message The message to wrap
- * @param integer $length The line length to wrap to
- * @param boolean $qp_mode Whether to run in Quoted-Printable mode
- * @access public
- * @return string
- */
- public function WrapText($message, $length, $qp_mode = false) {
- $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;
- // If utf-8 encoding is used, we will need to make sure we don't
- // split multibyte characters when we wrap
- $is_utf8 = (strtolower($this->CharSet) == "utf-8");
- $lelen = strlen($this->LE);
- $crlflen = strlen(self::CRLF);
-
- $message = $this->FixEOL($message);
- if (substr($message, -$lelen) == $this->LE) {
- $message = substr($message, 0, -$lelen);
- }
-
- $line = explode($this->LE, $message); // Magic. We know FixEOL uses $LE
- $message = '';
- for ($i = 0 ;$i < count($line); $i++) {
- $line_part = explode(' ', $line[$i]);
- $buf = '';
- for ($e = 0; $e $length)) {
- $space_left = $length - strlen($buf) - $crlflen;
- if ($e != 0) {
- if ($space_left > 20) {
- $len = $space_left;
- if ($is_utf8) {
- $len = $this->UTF8CharBoundary($word, $len);
- } elseif (substr($word, $len - 1, 1) == "=") {
- $len--;
- } elseif (substr($word, $len - 2, 1) == "=") {
- $len -= 2;
- }
- $part = substr($word, 0, $len);
- $word = substr($word, $len);
- $buf .= ' ' . $part;
- $message .= $buf . sprintf("=%s", self::CRLF);
- } else {
- $message .= $buf . $soft_break;
- }
- $buf = '';
- }
- while (strlen($word) > 0) {
- if ($length <= 0) {
- break;
- }
- $len = $length;
- if ($is_utf8) {
- $len = $this->UTF8CharBoundary($word, $len);
- } elseif (substr($word, $len - 1, 1) == "=") {
- $len--;
- } elseif (substr($word, $len - 2, 1) == "=") {
- $len -= 2;
- }
- $part = substr($word, 0, $len);
- $word = substr($word, $len);
-
- if (strlen($word) > 0) {
- $message .= $part . sprintf("=%s", self::CRLF);
- } else {
- $buf = $part;
- }
- }
- } else {
- $buf_o = $buf;
- $buf .= ($e == 0) ? $word : (' ' . $word);
-
- if (strlen($buf) > $length and $buf_o != '') {
- $message .= $buf_o . $soft_break;
- $buf = $word;
- }
- }
- }
- $message .= $buf . self::CRLF;
- }
-
- return $message;
- }
-
- /**
- * Finds last character boundary prior to maxLength in a utf-8
- * quoted (printable) encoded string.
- * Original written by Colin Brown.
- * @access public
- * @param string $encodedText utf-8 QP text
- * @param int $maxLength find last character boundary prior to this length
- * @return int
- */
- public function UTF8CharBoundary($encodedText, $maxLength) {
- $foundSplitPos = false;
- $lookBack = 3;
- while (!$foundSplitPos) {
- $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
- $encodedCharPos = strpos($lastChunk, "=");
- if ($encodedCharPos !== false) {
- // Found start of encoded character byte within $lookBack block.
- // Check the encoded byte value (the 2 chars after the '=')
- $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
- $dec = hexdec($hex);
- if ($dec < 128) { // Single byte character.
- // If the encoded char was found at pos 0, it will fit
- // otherwise reduce maxLength to start of the encoded char
- $maxLength = ($encodedCharPos == 0) ? $maxLength :
- $maxLength - ($lookBack - $encodedCharPos);
- $foundSplitPos = true;
- } elseif ($dec >= 192) { // First byte of a multi byte character
- // Reduce maxLength to split at start of character
- $maxLength = $maxLength - ($lookBack - $encodedCharPos);
- $foundSplitPos = true;
- } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back
- $lookBack += 3;
- }
- } else {
- // No encoded character found
- $foundSplitPos = true;
- }
- }
- return $maxLength;
- }
-
-
- /**
- * Set the body wrapping.
- * @access public
- * @return void
- */
- public function SetWordWrap() {
- if($this->WordWrap < 1) {
- return;
- }
-
- switch($this->message_type) {
- case 'alt':
- case 'alt_inline':
- case 'alt_attach':
- case 'alt_inline_attach':
- $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap);
- break;
- default:
- $this->Body = $this->WrapText($this->Body, $this->WordWrap);
- break;
- }
- }
-
- /**
- * Assembles message header.
- * @access public
- * @return string The assembled header
- */
- public function CreateHeader() {
- $result = '';
-
- // Set the boundaries
- $uniq_id = md5(uniqid(time()));
- $this->boundary[1] = 'b1_' . $uniq_id;
- $this->boundary[2] = 'b2_' . $uniq_id;
- $this->boundary[3] = 'b3_' . $uniq_id;
-
- if ($this->MessageDate == '') {
- $result .= $this->HeaderLine('Date', self::RFCDate());
- } else {
- $result .= $this->HeaderLine('Date', $this->MessageDate);
- }
-
- if ($this->ReturnPath) {
- $result .= $this->HeaderLine('Return-Path', '<'.trim($this->ReturnPath).'>');
- } elseif ($this->Sender == '') {
- $result .= $this->HeaderLine('Return-Path', '<'.trim($this->From).'>');
- } else {
- $result .= $this->HeaderLine('Return-Path', '<'.trim($this->Sender).'>');
- }
-
- // To be created automatically by mail()
- if($this->Mailer != 'mail') {
- if ($this->SingleTo === true) {
- foreach($this->to as $t) {
- $this->SingleToArray[] = $this->AddrFormat($t);
- }
- } else {
- if(count($this->to) > 0) {
- $result .= $this->AddrAppend('To', $this->to);
- } elseif (count($this->cc) == 0) {
- $result .= $this->HeaderLine('To', 'undisclosed-recipients:;');
- }
- }
- }
-
- $from = array();
- $from[0][0] = trim($this->From);
- $from[0][1] = $this->FromName;
- $result .= $this->AddrAppend('From', $from);
-
- // sendmail and mail() extract Cc from the header before sending
- if(count($this->cc) > 0) {
- $result .= $this->AddrAppend('Cc', $this->cc);
- }
-
- // sendmail and mail() extract Bcc from the header before sending
- if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) {
- $result .= $this->AddrAppend('Bcc', $this->bcc);
- }
-
- if(count($this->ReplyTo) > 0) {
- $result .= $this->AddrAppend('Reply-To', $this->ReplyTo);
- }
-
- // mail() sets the subject itself
- if($this->Mailer != 'mail') {
- $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject)));
- }
-
- if($this->MessageID != '') {
- $result .= $this->HeaderLine('Message-ID', $this->MessageID);
- } else {
- $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
- }
- $result .= $this->HeaderLine('X-Priority', $this->Priority);
- if ($this->XMailer == '') {
- $result .= $this->HeaderLine('X-Mailer', 'PHPMailer '.$this->Version.' (https://github.com/PHPMailer/PHPMailer/)');
- } else {
- $myXmailer = trim($this->XMailer);
- if ($myXmailer) {
- $result .= $this->HeaderLine('X-Mailer', $myXmailer);
- }
- }
-
- if($this->ConfirmReadingTo != '') {
- $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>');
- }
-
- // Add custom headers
- for($index = 0; $index < count($this->CustomHeader); $index++) {
- $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1])));
- }
- if (!$this->sign_key_file) {
- $result .= $this->HeaderLine('MIME-Version', '1.0');
- $result .= $this->GetMailMIME();
- }
-
- return $result;
- }
-
- /**
- * Returns the message MIME.
- * @access public
- * @return string
- */
- public function GetMailMIME() {
- $result = '';
- switch($this->message_type) {
- case 'inline':
- $result .= $this->HeaderLine('Content-Type', 'multipart/related;');
- $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
- break;
- case 'attach':
- case 'inline_attach':
- case 'alt_attach':
- case 'alt_inline_attach':
- $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;');
- $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
- break;
- case 'alt':
- case 'alt_inline':
- $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
- $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
- break;
- default:
- // Catches case 'plain': and case '':
- $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding);
- $result .= $this->TextLine('Content-Type: '.$this->ContentType.'; charset='.$this->CharSet);
- break;
- }
-
- if($this->Mailer != 'mail') {
- $result .= $this->LE;
- }
-
- return $result;
- }
-
- /**
- * Returns the MIME message (headers and body). Only really valid post PreSend().
- * @access public
- * @return string
- */
- public function GetSentMIMEMessage() {
- return $this->MIMEHeader . $this->mailHeader . self::CRLF . $this->MIMEBody;
- }
-
-
- /**
- * Assembles the message body. Returns an empty string on failure.
- * @access public
- * @throws phpmailerException
- * @return string The assembled message body
- */
- public function CreateBody() {
- $body = '';
-
- if ($this->sign_key_file) {
- $body .= $this->GetMailMIME().$this->LE;
- }
-
- $this->SetWordWrap();
-
- switch($this->message_type) {
- case 'inline':
- $body .= $this->GetBoundary($this->boundary[1], '', '', '');
- $body .= $this->EncodeString($this->Body, $this->Encoding);
- $body .= $this->LE.$this->LE;
- $body .= $this->AttachAll('inline', $this->boundary[1]);
- break;
- case 'attach':
- $body .= $this->GetBoundary($this->boundary[1], '', '', '');
- $body .= $this->EncodeString($this->Body, $this->Encoding);
- $body .= $this->LE.$this->LE;
- $body .= $this->AttachAll('attachment', $this->boundary[1]);
- break;
- case 'inline_attach':
- $body .= $this->TextLine('--' . $this->boundary[1]);
- $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
- $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
- $body .= $this->LE;
- $body .= $this->GetBoundary($this->boundary[2], '', '', '');
- $body .= $this->EncodeString($this->Body, $this->Encoding);
- $body .= $this->LE.$this->LE;
- $body .= $this->AttachAll('inline', $this->boundary[2]);
- $body .= $this->LE;
- $body .= $this->AttachAll('attachment', $this->boundary[1]);
- break;
- case 'alt':
- $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
- $body .= $this->EncodeString($this->AltBody, $this->Encoding);
- $body .= $this->LE.$this->LE;
- $body .= $this->GetBoundary($this->boundary[1], '', 'text/html', '');
- $body .= $this->EncodeString($this->Body, $this->Encoding);
- $body .= $this->LE.$this->LE;
- $body .= $this->EndBoundary($this->boundary[1]);
- break;
- case 'alt_inline':
- $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
- $body .= $this->EncodeString($this->AltBody, $this->Encoding);
- $body .= $this->LE.$this->LE;
- $body .= $this->TextLine('--' . $this->boundary[1]);
- $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
- $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
- $body .= $this->LE;
- $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '');
- $body .= $this->EncodeString($this->Body, $this->Encoding);
- $body .= $this->LE.$this->LE;
- $body .= $this->AttachAll('inline', $this->boundary[2]);
- $body .= $this->LE;
- $body .= $this->EndBoundary($this->boundary[1]);
- break;
- case 'alt_attach':
- $body .= $this->TextLine('--' . $this->boundary[1]);
- $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
- $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
- $body .= $this->LE;
- $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '');
- $body .= $this->EncodeString($this->AltBody, $this->Encoding);
- $body .= $this->LE.$this->LE;
- $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '');
- $body .= $this->EncodeString($this->Body, $this->Encoding);
- $body .= $this->LE.$this->LE;
- $body .= $this->EndBoundary($this->boundary[2]);
- $body .= $this->LE;
- $body .= $this->AttachAll('attachment', $this->boundary[1]);
- break;
- case 'alt_inline_attach':
- $body .= $this->TextLine('--' . $this->boundary[1]);
- $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
- $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
- $body .= $this->LE;
- $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '');
- $body .= $this->EncodeString($this->AltBody, $this->Encoding);
- $body .= $this->LE.$this->LE;
- $body .= $this->TextLine('--' . $this->boundary[2]);
- $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
- $body .= $this->TextLine("\tboundary=\"" . $this->boundary[3] . '"');
- $body .= $this->LE;
- $body .= $this->GetBoundary($this->boundary[3], '', 'text/html', '');
- $body .= $this->EncodeString($this->Body, $this->Encoding);
- $body .= $this->LE.$this->LE;
- $body .= $this->AttachAll('inline', $this->boundary[3]);
- $body .= $this->LE;
- $body .= $this->EndBoundary($this->boundary[2]);
- $body .= $this->LE;
- $body .= $this->AttachAll('attachment', $this->boundary[1]);
- break;
- default:
- // catch case 'plain' and case ''
- $body .= $this->EncodeString($this->Body, $this->Encoding);
- break;
- }
-
- if ($this->IsError()) {
- $body = '';
- } elseif ($this->sign_key_file) {
- try {
- if (!defined('PKCS7_TEXT')) {
- throw new phpmailerException($this->Lang('signing').' OpenSSL extension missing.');
- }
- $file = tempnam(sys_get_temp_dir(), 'mail');
- file_put_contents($file, $body); //TODO check this worked
- $signed = tempnam(sys_get_temp_dir(), 'signed');
- if (@openssl_pkcs7_sign($file, $signed, 'file://'.realpath($this->sign_cert_file), array('file://'.realpath($this->sign_key_file), $this->sign_key_pass), null)) {
- @unlink($file);
- $body = file_get_contents($signed);
- @unlink($signed);
- } else {
- @unlink($file);
- @unlink($signed);
- throw new phpmailerException($this->Lang('signing').openssl_error_string());
- }
- } catch (phpmailerException $e) {
- $body = '';
- if ($this->exceptions) {
- throw $e;
- }
- }
- }
- return $body;
- }
-
- /**
- * Returns the start of a message boundary.
- * @access protected
- * @param string $boundary
- * @param string $charSet
- * @param string $contentType
- * @param string $encoding
- * @return string
- */
- protected function GetBoundary($boundary, $charSet, $contentType, $encoding) {
- $result = '';
- if($charSet == '') {
- $charSet = $this->CharSet;
- }
- if($contentType == '') {
- $contentType = $this->ContentType;
- }
- if($encoding == '') {
- $encoding = $this->Encoding;
- }
- $result .= $this->TextLine('--' . $boundary);
- $result .= sprintf("Content-Type: %s; charset=%s", $contentType, $charSet);
- $result .= $this->LE;
- $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding);
- $result .= $this->LE;
-
- return $result;
- }
-
- /**
- * Returns the end of a message boundary.
- * @access protected
- * @param string $boundary
- * @return string
- */
- protected function EndBoundary($boundary) {
- return $this->LE . '--' . $boundary . '--' . $this->LE;
- }
-
- /**
- * Sets the message type.
- * @access protected
- * @return void
- */
- protected function SetMessageType() {
- $this->message_type = array();
- if($this->AlternativeExists()) $this->message_type[] = "alt";
- if($this->InlineImageExists()) $this->message_type[] = "inline";
- if($this->AttachmentExists()) $this->message_type[] = "attach";
- $this->message_type = implode("_", $this->message_type);
- if($this->message_type == "") $this->message_type = "plain";
- }
-
- /**
- * Returns a formatted header line.
- * @access public
- * @param string $name
- * @param string $value
- * @return string
- */
- public function HeaderLine($name, $value) {
- return $name . ': ' . $value . $this->LE;
- }
-
- /**
- * Returns a formatted mail line.
- * @access public
- * @param string $value
- * @return string
- */
- public function TextLine($value) {
- return $value . $this->LE;
- }
-
- /////////////////////////////////////////////////
- // CLASS METHODS, ATTACHMENTS
- /////////////////////////////////////////////////
-
- /**
- * Adds an attachment from a path on the filesystem.
- * Returns false if the file could not be found
- * or accessed.
- * @param string $path Path to the attachment.
- * @param string $name Overrides the attachment name.
- * @param string $encoding File encoding (see $Encoding).
- * @param string $type File extension (MIME) type.
- * @throws phpmailerException
- * @return bool
- */
- public function AddAttachment($path, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
- try {
- if ( !@is_file($path) ) {
- throw new phpmailerException($this->Lang('file_access') . $path, self::STOP_CONTINUE);
- }
- $filename = basename($path);
- if ( $name == '' ) {
- $name = $filename;
- }
-
- $this->attachment[] = array(
- 0 => $path,
- 1 => $filename,
- 2 => $name,
- 3 => $encoding,
- 4 => $type,
- 5 => false, // isStringAttachment
- 6 => 'attachment',
- 7 => 0
- );
-
- } catch (phpmailerException $e) {
- $this->SetError($e->getMessage());
- if ($this->exceptions) {
- throw $e;
- }
- if ($this->SMTPDebug) {
- $this->edebug($e->getMessage()."\n");
- }
- if ( $e->getCode() == self::STOP_CRITICAL ) {
- return false;
- }
- }
- return true;
- }
-
- /**
- * Return the current array of attachments
- * @return array
- */
- public function GetAttachments() {
- return $this->attachment;
- }
-
- /**
- * Attaches all fs, string, and binary attachments to the message.
- * Returns an empty string on failure.
- * @access protected
- * @param string $disposition_type
- * @param string $boundary
- * @return string
- */
- protected function AttachAll($disposition_type, $boundary) {
- // Return text of body
- $mime = array();
- $cidUniq = array();
- $incl = array();
-
- // Add all attachments
- foreach ($this->attachment as $attachment) {
- // CHECK IF IT IS A VALID DISPOSITION_FILTER
- if($attachment[6] == $disposition_type) {
- // Check for string attachment
- $string = '';
- $path = '';
- $bString = $attachment[5];
- if ($bString) {
- $string = $attachment[0];
- } else {
- $path = $attachment[0];
- }
-
- $inclhash = md5(serialize($attachment));
- if (in_array($inclhash, $incl)) { continue; }
- $incl[] = $inclhash;
- $filename = $attachment[1];
- $name = $attachment[2];
- $encoding = $attachment[3];
- $type = $attachment[4];
- $disposition = $attachment[6];
- $cid = $attachment[7];
- if ( $disposition == 'inline' && isset($cidUniq[$cid]) ) { continue; }
- $cidUniq[$cid] = true;
-
- $mime[] = sprintf("--%s%s", $boundary, $this->LE);
- $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $this->EncodeHeader($this->SecureHeader($name)), $this->LE);
- $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE);
-
- if($disposition == 'inline') {
- $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE);
- }
-
- $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE);
-
- // Encode as string attachment
- if($bString) {
- $mime[] = $this->EncodeString($string, $encoding);
- if($this->IsError()) {
- return '';
- }
- $mime[] = $this->LE.$this->LE;
- } else {
- $mime[] = $this->EncodeFile($path, $encoding);
- if($this->IsError()) {
- return '';
- }
- $mime[] = $this->LE.$this->LE;
- }
- }
- }
-
- $mime[] = sprintf("--%s--%s", $boundary, $this->LE);
-
- return implode("", $mime);
- }
-
- /**
- * Encodes attachment in requested format.
- * Returns an empty string on failure.
- * @param string $path The full path to the file
- * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
- * @throws phpmailerException
- * @see EncodeFile()
- * @access protected
- * @return string
- */
- protected function EncodeFile($path, $encoding = 'base64') {
- try {
- if (!is_readable($path)) {
- throw new phpmailerException($this->Lang('file_open') . $path, self::STOP_CONTINUE);
- }
- $magic_quotes = get_magic_quotes_runtime();
- if ($magic_quotes) {
- if (version_compare(PHP_VERSION, '5.3.0', '<')) {
- set_magic_quotes_runtime(0);
- } else {
- ini_set('magic_quotes_runtime', 0);
- }
- }
- $file_buffer = file_get_contents($path);
- $file_buffer = $this->EncodeString($file_buffer, $encoding);
- if ($magic_quotes) {
- if (version_compare(PHP_VERSION, '5.3.0', '<')) {
- set_magic_quotes_runtime($magic_quotes);
- } else {
- ini_set('magic_quotes_runtime', $magic_quotes);
- }
- }
- return $file_buffer;
- } catch (Exception $e) {
- $this->SetError($e->getMessage());
- return '';
- }
- }
-
- /**
- * Encodes string to requested format.
- * Returns an empty string on failure.
- * @param string $str The text to encode
- * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
- * @access public
- * @return string
- */
- public function EncodeString($str, $encoding = 'base64') {
- $encoded = '';
- switch(strtolower($encoding)) {
- case 'base64':
- $encoded = chunk_split(base64_encode($str), 76, $this->LE);
- break;
- case '7bit':
- case '8bit':
- $encoded = $this->FixEOL($str);
- //Make sure it ends with a line break
- if (substr($encoded, -(strlen($this->LE))) != $this->LE)
- $encoded .= $this->LE;
- break;
- case 'binary':
- $encoded = $str;
- break;
- case 'quoted-printable':
- $encoded = $this->EncodeQP($str);
- break;
- default:
- $this->SetError($this->Lang('encoding') . $encoding);
- break;
- }
- return $encoded;
- }
-
- /**
- * Encode a header string to best (shortest) of Q, B, quoted or none.
- * @access public
- * @param string $str
- * @param string $position
- * @return string
- */
- public function EncodeHeader($str, $position = 'text') {
- $x = 0;
-
- switch (strtolower($position)) {
- case 'phrase':
- if (!preg_match('/[\200-\377]/', $str)) {
- // Can't use addslashes as we don't know what value has magic_quotes_sybase
- $encoded = addcslashes($str, "\0..\37\177\\\"");
- if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
- return ($encoded);
- } else {
- return ("\"$encoded\"");
- }
- }
- $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
- break;
- case 'comment':
- $x = preg_match_all('/[()"]/', $str, $matches);
- // Fall-through
- case 'text':
- default:
- $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
- break;
- }
-
- if ($x == 0) { //There are no chars that need encoding
- return ($str);
- }
-
- $maxlen = 75 - 7 - strlen($this->CharSet);
- // Try to select the encoding which should produce the shortest output
- if ($x > strlen($str)/3) { //More than a third of the content will need encoding, so B encoding will be most efficient
- $encoding = 'B';
- if (function_exists('mb_strlen') && $this->HasMultiBytes($str)) {
- // Use a custom function which correctly encodes and wraps long
- // multibyte strings without breaking lines within a character
- $encoded = $this->Base64EncodeWrapMB($str, "\n");
- } else {
- $encoded = base64_encode($str);
- $maxlen -= $maxlen % 4;
- $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
- }
- } else {
- $encoding = 'Q';
- $encoded = $this->EncodeQ($str, $position);
- $encoded = $this->WrapText($encoded, $maxlen, true);
- $encoded = str_replace('='.self::CRLF, "\n", trim($encoded));
- }
-
- $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded);
- $encoded = trim(str_replace("\n", $this->LE, $encoded));
-
- return $encoded;
- }
-
- /**
- * Checks if a string contains multibyte characters.
- * @access public
- * @param string $str multi-byte text to wrap encode
- * @return bool
- */
- public function HasMultiBytes($str) {
- if (function_exists('mb_strlen')) {
- return (strlen($str) > mb_strlen($str, $this->CharSet));
- } else { // Assume no multibytes (we can't handle without mbstring functions anyway)
- return false;
- }
- }
-
- /**
- * Correctly encodes and wraps long multibyte strings for mail headers
- * without breaking lines within a character.
- * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php
- * @access public
- * @param string $str multi-byte text to wrap encode
- * @param string $lf string to use as linefeed/end-of-line
- * @return string
- */
- public function Base64EncodeWrapMB($str, $lf=null) {
- $start = "=?".$this->CharSet."?B?";
- $end = "?=";
- $encoded = "";
- if ($lf === null) {
- $lf = $this->LE;
- }
-
- $mb_length = mb_strlen($str, $this->CharSet);
- // Each line must have length <= 75, including $start and $end
- $length = 75 - strlen($start) - strlen($end);
- // Average multi-byte ratio
- $ratio = $mb_length / strlen($str);
- // Base64 has a 4:3 ratio
- $offset = $avgLength = floor($length * $ratio * .75);
-
- for ($i = 0; $i < $mb_length; $i += $offset) {
- $lookBack = 0;
-
- do {
- $offset = $avgLength - $lookBack;
- $chunk = mb_substr($str, $i, $offset, $this->CharSet);
- $chunk = base64_encode($chunk);
- $lookBack++;
- }
- while (strlen($chunk) > $length);
-
- $encoded .= $chunk . $lf;
- }
-
- // Chomp the last linefeed
- $encoded = substr($encoded, 0, -strlen($lf));
- return $encoded;
- }
-
- /**
- * Encode string to RFC2045 (6.7) quoted-printable format
- * @access public
- * @param string $string The text to encode
- * @param integer $line_max Number of chars allowed on a line before wrapping
- * @return string
- * @link PHP version adapted from http://www.php.net/manual/en/function.quoted-printable-decode.php#89417
- */
- public function EncodeQP($string, $line_max = 76) {
- if (function_exists('quoted_printable_encode')) { //Use native function if it's available (>= PHP5.3)
- return quoted_printable_encode($string);
- }
- //Fall back to a pure PHP implementation
- $string = str_replace(array('%20', '%0D%0A.', '%0D%0A', '%'), array(' ', "\r\n=2E", "\r\n", '='), rawurlencode($string));
- $string = preg_replace('/[^\r\n]{'.($line_max - 3).'}[^=\r\n]{2}/', "$0=\r\n", $string);
- return $string;
- }
-
- /**
- * Wrapper to preserve BC for old QP encoding function that was removed
- * @see EncodeQP()
- * @access public
- * @param string $string
- * @param integer $line_max
- * @param bool $space_conv
- * @return string
- */
- public function EncodeQPphp($string, $line_max = 76, $space_conv = false) {
- return $this->EncodeQP($string, $line_max);
- }
-
- /**
- * Encode string to q encoding.
- * @link http://tools.ietf.org/html/rfc2047
- * @param string $str the text to encode
- * @param string $position Where the text is going to be used, see the RFC for what that means
- * @access public
- * @return string
- */
- public function EncodeQ($str, $position = 'text') {
- //There should not be any EOL in the string
- $pattern="";
- $encoded = str_replace(array("\r", "\n"), '', $str);
- switch (strtolower($position)) {
- case 'phrase':
- $pattern = '^A-Za-z0-9!*+\/ -';
- break;
-
- case 'comment':
- $pattern = '\(\)"';
- //note that we don't break here!
- //for this reason we build the $pattern without including delimiters and []
-
- case 'text':
- default:
- //Replace every high ascii, control =, ? and _ characters
- //We put \075 (=) as first value to make sure it's the first one in being converted, preventing double encode
- $pattern = '\075\000-\011\013\014\016-\037\077\137\177-\377' . $pattern;
- break;
- }
-
- if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
- foreach (array_unique($matches[0]) as $char) {
- $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
- }
- }
-
- //Replace every spaces to _ (more readable than =20)
- return str_replace(' ', '_', $encoded);
-}
-
-
- /**
- * Adds a string or binary attachment (non-filesystem) to the list.
- * This method can be used to attach ascii or binary data,
- * such as a BLOB record from a database.
- * @param string $string String attachment data.
- * @param string $filename Name of the attachment.
- * @param string $encoding File encoding (see $Encoding).
- * @param string $type File extension (MIME) type.
- * @return void
- */
- public function AddStringAttachment($string, $filename, $encoding = 'base64', $type = 'application/octet-stream') {
- // Append to $attachment array
- $this->attachment[] = array(
- 0 => $string,
- 1 => $filename,
- 2 => basename($filename),
- 3 => $encoding,
- 4 => $type,
- 5 => true, // isStringAttachment
- 6 => 'attachment',
- 7 => 0
- );
- }
-
- /**
- * Add an embedded attachment from a file.
- * This can include images, sounds, and just about any other document type.
- * Be sure to set the $type to an image type for images:
- * JPEG images use 'image/jpeg', GIF uses 'image/gif', PNG uses 'image/png'.
- * @param string $path Path to the attachment.
- * @param string $cid Content ID of the attachment; Use this to reference
- * the content when using an embedded image in HTML.
- * @param string $name Overrides the attachment name.
- * @param string $encoding File encoding (see $Encoding).
- * @param string $type File MIME type.
- * @return bool True on successfully adding an attachment
- */
- public function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
-
- if ( !@is_file($path) ) {
- $this->SetError($this->Lang('file_access') . $path);
- return false;
- }
-
- $filename = basename($path);
- if ( $name == '' ) {
- $name = $filename;
- }
-
- // Append to $attachment array
- $this->attachment[] = array(
- 0 => $path,
- 1 => $filename,
- 2 => $name,
- 3 => $encoding,
- 4 => $type,
- 5 => false, // isStringAttachment
- 6 => 'inline',
- 7 => $cid
- );
- return true;
- }
-
-
- /**
- * Add an embedded stringified attachment.
- * This can include images, sounds, and just about any other document type.
- * Be sure to set the $type to an image type for images:
- * JPEG images use 'image/jpeg', GIF uses 'image/gif', PNG uses 'image/png'.
- * @param string $string The attachment binary data.
- * @param string $cid Content ID of the attachment; Use this to reference
- * the content when using an embedded image in HTML.
- * @param string $name
- * @param string $encoding File encoding (see $Encoding).
- * @param string $type MIME type.
- * @return bool True on successfully adding an attachment
- */
- public function AddStringEmbeddedImage($string, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
- // Append to $attachment array
- $this->attachment[] = array(
- 0 => $string,
- 1 => $name,
- 2 => $name,
- 3 => $encoding,
- 4 => $type,
- 5 => true, // isStringAttachment
- 6 => 'inline',
- 7 => $cid
- );
- return true;
- }
-
- /**
- * Returns true if an inline attachment is present.
- * @access public
- * @return bool
- */
- public function InlineImageExists() {
- foreach($this->attachment as $attachment) {
- if ($attachment[6] == 'inline') {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Returns true if an attachment (non-inline) is present.
- * @return bool
- */
- public function AttachmentExists() {
- foreach($this->attachment as $attachment) {
- if ($attachment[6] == 'attachment') {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Does this message have an alternative body set?
- * @return bool
- */
- public function AlternativeExists() {
- return !empty($this->AltBody);
- }
-
- /////////////////////////////////////////////////
- // CLASS METHODS, MESSAGE RESET
- /////////////////////////////////////////////////
-
- /**
- * Clears all recipients assigned in the TO array. Returns void.
- * @return void
- */
- public function ClearAddresses() {
- foreach($this->to as $to) {
- unset($this->all_recipients[strtolower($to[0])]);
- }
- $this->to = array();
- }
-
- /**
- * Clears all recipients assigned in the CC array. Returns void.
- * @return void
- */
- public function ClearCCs() {
- foreach($this->cc as $cc) {
- unset($this->all_recipients[strtolower($cc[0])]);
- }
- $this->cc = array();
- }
-
- /**
- * Clears all recipients assigned in the BCC array. Returns void.
- * @return void
- */
- public function ClearBCCs() {
- foreach($this->bcc as $bcc) {
- unset($this->all_recipients[strtolower($bcc[0])]);
- }
- $this->bcc = array();
- }
-
- /**
- * Clears all recipients assigned in the ReplyTo array. Returns void.
- * @return void
- */
- public function ClearReplyTos() {
- $this->ReplyTo = array();
- }
-
- /**
- * Clears all recipients assigned in the TO, CC and BCC
- * array. Returns void.
- * @return void
- */
- public function ClearAllRecipients() {
- $this->to = array();
- $this->cc = array();
- $this->bcc = array();
- $this->all_recipients = array();
- }
-
- /**
- * Clears all previously set filesystem, string, and binary
- * attachments. Returns void.
- * @return void
- */
- public function ClearAttachments() {
- $this->attachment = array();
- }
-
- /**
- * Clears all custom headers. Returns void.
- * @return void
- */
- public function ClearCustomHeaders() {
- $this->CustomHeader = array();
- }
-
- /////////////////////////////////////////////////
- // CLASS METHODS, MISCELLANEOUS
- /////////////////////////////////////////////////
-
- /**
- * Adds the error message to the error container.
- * @access protected
- * @param string $msg
- * @return void
- */
- protected function SetError($msg) {
- $this->error_count++;
- if ($this->Mailer == 'smtp' and !is_null($this->smtp)) {
- $lasterror = $this->smtp->getError();
- if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) {
- $msg .= '
").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cd=a.document.documentElement;function dd(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dd(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cd;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cd})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dd(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=Lb(k.pixelPosition,function(a,c){return c?(c=Jb(a,b),Hb.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ed=a.jQuery,fd=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fd),b&&a.jQuery===m&&(a.jQuery=ed),m},typeof b===K&&(a.jQuery=a.$=m),m});
diff --git a/sources/resources/jquery-cookie/jquery.cookies.js b/sources/resources/jquery-cookie/jquery.cookies.js
deleted file mode 100644
index c0f19d8..0000000
--- a/sources/resources/jquery-cookie/jquery.cookies.js
+++ /dev/null
@@ -1,2 +0,0 @@
-/*! jquery.cookie v1.4.1 | MIT */
-!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof exports?a(require("jquery")):a(jQuery)}(function(a){function b(a){return h.raw?a:encodeURIComponent(a)}function c(a){return h.raw?a:decodeURIComponent(a)}function d(a){return b(h.json?JSON.stringify(a):String(a))}function e(a){0===a.indexOf('"')&&(a=a.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\"));try{return a=decodeURIComponent(a.replace(g," ")),h.json?JSON.parse(a):a}catch(b){}}function f(b,c){var d=h.raw?b:e(b);return a.isFunction(c)?c(d):d}var g=/\+/g,h=a.cookie=function(e,g,i){if(void 0!==g&&!a.isFunction(g)){if(i=a.extend({},h.defaults,i),"number"==typeof i.expires){var j=i.expires,k=i.expires=new Date;k.setTime(+k+864e5*j)}return document.cookie=[b(e),"=",d(g),i.expires?"; expires="+i.expires.toUTCString():"",i.path?"; path="+i.path:"",i.domain?"; domain="+i.domain:"",i.secure?"; secure":""].join("")}for(var l=e?void 0:{},m=document.cookie?document.cookie.split("; "):[],n=0,o=m.length;o>n;n++){var p=m[n].split("="),q=c(p.shift()),r=p.join("=");if(e&&e===q){l=f(r,g);break}e||void 0===(r=f(r))||(l[q]=r)}return l};h.defaults={},a.removeCookie=function(b,c){return void 0===a.cookie(b)?!1:(a.cookie(b,"",a.extend({},c,{expires:-1})),!a.cookie(b))}});
\ No newline at end of file
diff --git a/sources/resources/jquery-sortelements/jquery.sortElements.js b/sources/resources/jquery-sortelements/jquery.sortElements.js
deleted file mode 100644
index bf1902d..0000000
--- a/sources/resources/jquery-sortelements/jquery.sortElements.js
+++ /dev/null
@@ -1,69 +0,0 @@
-/**
- * jQuery.fn.sortElements
- * --------------
- * @author James Padolsey (http://james.padolsey.com)
- * @version 0.11
- * @updated 18-MAR-2010
- * --------------
- * @param Function comparator:
- * Exactly the same behaviour as [1,2,3].sort(comparator)
- *
- * @param Function getSortable
- * A function that should return the element that is
- * to be sorted. The comparator will run on the
- * current collection, but you may want the actual
- * resulting sort to occur on a parent or another
- * associated element.
- *
- * E.g. $('td').sortElements(comparator, function(){
- * return this.parentNode;
- * })
- *
- * The
's parent (
) will be sorted instead
- * of the
itself.
- */
-jQuery.fn.sortElements = (function(){
-
- var sort = [].sort;
-
- return function(comparator, getSortable) {
-
- getSortable = getSortable || function(){return this;};
-
- var placements = this.map(function(){
-
- var sortElement = getSortable.call(this),
- parentNode = sortElement.parentNode,
-
- // Since the element itself will change position, we have
- // to have some way of storing it's original position in
- // the DOM. The easiest way is to have a 'flag' node:
- nextSibling = parentNode.insertBefore(
- document.createTextNode(''),
- sortElement.nextSibling
- );
-
- return function() {
-
- if (parentNode === this) {
- throw new Error(
- "You can't sort elements if any one is a descendant of another."
- );
- }
-
- // Insert before flag:
- parentNode.insertBefore(this, nextSibling);
- // Remove flag:
- parentNode.removeChild(nextSibling);
-
- };
-
- });
-
- return sort.call(this, comparator).each(function(i){
- placements[i].call(getSortable.call(this));
- });
-
- };
-
-})();
\ No newline at end of file
diff --git a/sources/resources/lru/lru.js b/sources/resources/lru/lru.js
deleted file mode 100644
index d014942..0000000
--- a/sources/resources/lru/lru.js
+++ /dev/null
@@ -1,249 +0,0 @@
-/**
- * A doubly linked list-based Least Recently Used (LRU) cache. Will keep most
- * recently used items while discarding least recently used items when its limit
- * is reached.
- *
- * Licensed under MIT. Copyright (c) 2010 Rasmus Andersson
- * See README.md for details.
- *
- * Illustration of the design:
- *
- * entry entry entry entry
- * ______ ______ ______ ______
- * | head |.newer => | |.newer => | |.newer => | tail |
- * | A | | B | | C | | D |
- * |______| <= older.|______| <= older.|______| <= older.|______|
- *
- * removed <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- added
- */
-function LRUCache (limit) {
- // Current size of the cache. (Read-only).
- this.size = 0;
- // Maximum number of items this cache can hold.
- this.limit = limit;
- this._keymap = {};
-}
-
-/**
- * Put into the cache associated with . Returns the entry which was
- * removed to make room for the new entry. Otherwise undefined is returned
- * (i.e. if there was enough room already).
- */
-LRUCache.prototype.put = function(key, value) {
- var entry = {key:key, value:value};
- // Note: No protection agains replacing, and thus orphan entries. By design.
- this._keymap[key] = entry;
- if (this.tail) {
- // link previous tail to the new tail (entry)
- this.tail.newer = entry;
- entry.older = this.tail;
- } else {
- // we're first in -- yay
- this.head = entry;
- }
- // add new entry to the end of the linked list -- it's now the freshest entry.
- this.tail = entry;
- if (this.size === this.limit) {
- // we hit the limit -- remove the head
- return this.shift();
- } else {
- // increase the size counter
- this.size++;
- }
-}
-
-/**
- * Purge the least recently used (oldest) entry from the cache. Returns the
- * removed entry or undefined if the cache was empty.
- *
- * If you need to perform any form of finalization of purged items, this is a
- * good place to do it. Simply override/replace this function:
- *
- * var c = new LRUCache(123);
- * c.shift = function() {
- * var entry = LRUCache.prototype.shift.call(this);
- * doSomethingWith(entry);
- * return entry;
- * }
- */
-LRUCache.prototype.shift = function() {
- // todo: handle special case when limit == 1
- var entry = this.head;
- if (entry) {
- if (this.head.newer) {
- this.head = this.head.newer;
- this.head.older = undefined;
- } else {
- this.head = undefined;
- }
- // Remove last strong reference to and remove links from the purged
- // entry being returned:
- entry.newer = entry.older = undefined;
- // delete is slow, but we need to do this to avoid uncontrollable growth:
- delete this._keymap[entry.key];
- }
- return entry;
-}
-
-/**
- * Get and register recent use of . Returns the value associated with
- * or undefined if not in cache.
- */
-LRUCache.prototype.get = function(key, returnEntry) {
- // First, find our cache entry
- var entry = this._keymap[key];
- if (entry === undefined) return; // Not cached. Sorry.
- // As was found in the cache, register it as being requested recently
- if (entry === this.tail) {
- // Already the most recenlty used entry, so no need to update the list
- return entry.value;
- }
- // HEAD--------------TAIL
- // <.older .newer>
- // <--- add direction --
- // A B C E
- if (entry.newer) {
- if (entry === this.head)
- this.head = entry.newer;
- entry.newer.older = entry.older; // C <-- E.
- }
- if (entry.older)
- entry.older.newer = entry.newer; // C. --> E
- entry.newer = undefined; // D --x
- entry.older = this.tail; // D. --> E
- if (this.tail)
- this.tail.newer = entry; // E. <-- D
- this.tail = entry;
- return returnEntry ? entry : entry.value;
-}
-
-// ----------------------------------------------------------------------------
-// Following code is optional and can be removed without breaking the core
-// functionality.
-
-/**
- * Check if is in the cache without registering recent use. Feasible if
- * you do not want to chage the state of the cache, but only "peek" at it.
- * Returns the entry associated with if found, or undefined if not found.
- */
-LRUCache.prototype.find = function(key) {
- return this._keymap[key];
-}
-
-/**
- * Update the value of entry with . Returns the old value, or undefined if
- * entry was not in the cache.
- */
-LRUCache.prototype.set = function(key, value) {
- var oldvalue, entry = this.get(key, true);
- if (entry) {
- oldvalue = entry.value;
- entry.value = value;
- } else {
- oldvalue = this.put(key, value);
- if (oldvalue) oldvalue = oldvalue.value;
- }
- return oldvalue;
-}
-
-/**
- * Remove entry from cache and return its value. Returns undefined if not
- * found.
- */
-LRUCache.prototype.remove = function(key) {
- var entry = this._keymap[key];
- if (!entry) return;
- delete this._keymap[entry.key]; // need to do delete unfortunately
- if (entry.newer && entry.older) {
- // relink the older entry with the newer entry
- entry.older.newer = entry.newer;
- entry.newer.older = entry.older;
- } else if (entry.newer) {
- // remove the link to us
- entry.newer.older = undefined;
- // link the newer entry to head
- this.head = entry.newer;
- } else if (entry.older) {
- // remove the link to us
- entry.older.newer = undefined;
- // link the newer entry to head
- this.tail = entry.older;
- } else {// if(entry.older === undefined && entry.newer === undefined) {
- this.head = this.tail = undefined;
- }
-
- this.size--;
- return entry.value;
-}
-
-/** Removes all entries */
-LRUCache.prototype.removeAll = function() {
- // This should be safe, as we never expose strong refrences to the outside
- this.head = this.tail = undefined;
- this.size = 0;
- this._keymap = {};
-}
-
-/**
- * Return an array containing all keys of entries stored in the cache object, in
- * arbitrary order.
- */
-if (typeof Object.keys === 'function') {
- LRUCache.prototype.keys = function() { return Object.keys(this._keymap); }
-} else {
- LRUCache.prototype.keys = function() {
- var keys = [];
- for (var k in this._keymap) keys.push(k);
- return keys;
- }
-}
-
-/**
- * Call `fun` for each entry. Starting with the newest entry if `desc` is a true
- * value, otherwise starts with the oldest (head) enrty and moves towards the
- * tail.
- *
- * `fun` is called with 3 arguments in the context `context`:
- * `fun.call(context, Object key, Object value, LRUCache self)`
- */
-LRUCache.prototype.forEach = function(fun, context, desc) {
- if (context === true) { desc = true; context = undefined; }
- else if (typeof context !== 'object') context = this;
- if (desc) {
- var entry = this.tail;
- while (entry) {
- fun.call(context, entry.key, entry.value, this);
- entry = entry.older;
- }
- } else {
- var entry = this.head;
- while (entry) {
- fun.call(context, entry.key, entry.value, this);
- entry = entry.newer;
- }
- }
-}
-
-/** Returns a JSON (array) representation */
-LRUCache.prototype.toJSON = function() {
- var s = [], entry = this.head;
- while (entry) {
- s.push({key:entry.key.toJSON(), value:entry.value.toJSON()});
- entry = entry.newer;
- }
- return s;
-}
-
-/** Returns a String representation */
-LRUCache.prototype.toString = function() {
- var s = '', entry = this.head;
- while (entry) {
- s += String(entry.key)+':'+entry.value;
- if (entry = entry.newer)
- s += ' < ';
- }
- return s;
-}
-
-// Export ourselves
-if (typeof this === 'object') this.LRUCache = LRUCache;
diff --git a/sources/resources/monocle/scripts/monocore.js b/sources/resources/monocle/scripts/monocore.js
deleted file mode 100644
index ae8b645..0000000
--- a/sources/resources/monocle/scripts/monocore.js
+++ /dev/null
@@ -1,5641 +0,0 @@
-/*!
- * Monocle - A silky, tactile browser-based ebook JavaScript library.
- *
- * Copyright 2012, Joseph Pearson
- * Licensed under the MIT license.
- */
-
-
-Monocle = {
- VERSION: "3.2.0"
-};
-
-
-Monocle.Dimensions = {};
-Monocle.Controls = {};
-Monocle.Flippers = {};
-Monocle.Panels = {};
-// A class that tests the browser environment for required capabilities and
-// known bugs (for which we have workarounds).
-//
-Monocle.Env = function () {
-
- var API = { constructor: Monocle.Env }
- var k = API.constants = API.constructor;
- var p = API.properties = {
- // Assign to a function before running survey in order to get
- // results as they come in. The function should take two arguments:
- // testName and value.
- resultCallback: null
- }
-
- // These are private variables so they don't clutter up properties.
- var css = Monocle.Browser.css;
- var activeTestName = null;
- var frameLoadCallback = null;
- var testFrame = null;
- var testFrameCntr = null;
- var testFrameSize = 100;
- var surveyCallback = null;
-
-
- function survey(cb) {
- surveyCallback = cb;
- runNextTest();
- }
-
-
- function runNextTest() {
- var test = envTests.shift();
- if (!test) { return completed(); }
- activeTestName = test[0];
- try { test[1](); } catch (e) { result(e); }
- }
-
-
- // Each test should call this to say "I'm finished, run the next test."
- //
- function result(val) {
- API[activeTestName] = val;
- if (p.resultCallback) { p.resultCallback(activeTestName, val); }
- runNextTest();
- return val;
- }
-
-
- // Invoked after all tests have run.
- //
- function completed() {
- // Remove the test frame after a slight delay (otherwise Gecko spins).
- Monocle.defer(removeTestFrame);
-
- if (typeof surveyCallback == "function") {
- fn = surveyCallback;
- surveyCallback = null;
- fn(API);
- }
- }
-
-
- // A bit of sugar for simplifying a detection pattern: does this
- // function exist?
- //
- // Pass a string snippet of JavaScript to be evaluated.
- //
- function testForFunction(str) {
- return function () { result(typeof eval(str) == "function"); }
- }
-
-
- // A bit of sugar to indicate that the detection function for this test
- // hasn't been written yet...
- //
- // Pass the value you want assigned for the test until it is implemented.
- //
- function testNotYetImplemented(rslt) {
- return function () { result(rslt); }
- }
-
-
- // Loads (or reloads) a hidden iframe so that we can test browser features.
- //
- // cb is the callback that is fired when the test frame's content is loaded.
- //
- // src is optional, in which case it defaults to 4. If provided, it can be
- // a number (specifying the number of pages of default content), or a string,
- // which will be loaded as a URL.
- //
- function loadTestFrame(cb, src) {
- if (!testFrame) { testFrame = createTestFrame(); }
- frameLoadCallback = cb;
-
- src = src || 4;
-
- if (typeof src == "number") {
- var pgs = [];
- for (var i = 1, ii = src; i <= ii; ++i) {
- pgs.push("
Page "+i+"
");
- }
- var divStyle = [
- "display:inline-block",
- "line-height:"+testFrameSize+"px",
- "width:"+testFrameSize+"px"
- ].join(";");
- src = "javascript:'"+
- ''+
- ''+
- ''+pgs.join("")+''+
- "'";
- }
-
- testFrame.src = src;
- }
-
-
- // Creates the hidden test frame and returns it.
- //
- function createTestFrame() {
- testFrameCntr = document.createElement('div');
- testFrameCntr.style.cssText = [
- "width:"+testFrameSize+"px",
- "height:"+testFrameSize+"px",
- "overflow:hidden",
- "position:absolute",
- "visibility:hidden"
- ].join(";");
- document.body.appendChild(testFrameCntr);
-
- var fr = document.createElement('iframe');
- testFrameCntr.appendChild(fr);
- fr.setAttribute("scrolling", "no");
- fr.style.cssText = [
- "width:100%",
- "height:100%",
- "border:none",
- "background:#900"
- ].join(";");
- fr.addEventListener(
- "load",
- function () {
- if (!fr.contentDocument || !fr.contentDocument.body) { return; }
- var bd = fr.contentDocument.body;
- bd.style.cssText = ([
- "margin:0",
- "padding:0",
- "position:absolute",
- "height:100%",
- "width:100%",
- "-webkit-column-width:"+testFrameSize+"px",
- "-webkit-column-gap:0",
- "-webkit-column-fill:auto",
- "-moz-column-width:"+testFrameSize+"px",
- "-moz-column-gap:0",
- "-moz-column-fill:auto",
- "-o-column-width:"+testFrameSize+"px",
- "-o-column-gap:0",
- "-o-column-fill:auto",
- "column-width:"+testFrameSize+"px",
- "column-gap:0",
- "column-fill:auto"
- ].join(";"));
- if (bd.scrollHeight > testFrameSize) {
- bd.style.cssText += ["min-width:200%", "overflow:hidden"].join(";");
- if (bd.scrollHeight <= testFrameSize) {
- bd.className = "column-force";
- } else {
- bd.className = "column-failed "+bd.scrollHeight;
- }
- }
- frameLoadCallback(fr);
- },
- false
- );
- return fr;
- }
-
-
- function removeTestFrame() {
- if (testFrameCntr && testFrameCntr.parentNode) {
- testFrameCntr.parentNode.removeChild(testFrameCntr);
- }
- }
-
-
- function columnedWidth(fr) {
- var bd = fr.contentDocument.body;
- var de = fr.contentDocument.documentElement;
- return Math.max(bd.scrollWidth, de.scrollWidth);
- }
-
-
- var envTests = [
-
- // TEST FOR REQUIRED CAPABILITIES
-
- ["supportsW3CEvents", testForFunction("window.addEventListener")],
- ["supportsCustomEvents", testForFunction("document.createEvent")],
- ["supportsColumns", function () {
- result(css.supportsPropertyWithAnyPrefix('column-width'));
- }],
- ["supportsTransform", function () {
- result(css.supportsProperty([
- 'transformProperty',
- 'WebkitTransform',
- 'MozTransform',
- 'OTransform',
- 'msTransform'
- ]));
- }],
-
-
- // TEST FOR OPTIONAL CAPABILITIES
-
- // Does it do CSS transitions?
- ["supportsTransition", function () {
- result(css.supportsPropertyWithAnyPrefix('transition'))
- }],
-
- // Can we find nodes in a document with an XPath?
- //
- ["supportsXPath", testForFunction("document.evaluate")],
-
- // Can we find nodes in a document natively with a CSS selector?
- //
- ["supportsQuerySelector", testForFunction("document.querySelector")],
-
- // Can we do 3d transforms?
- //
- ["supportsTransform3d", function () {
- result(
- css.supportsMediaQueryProperty('transform-3d') &&
- css.supportsProperty([
- 'perspectiveProperty',
- 'WebkitPerspective',
- 'MozPerspective',
- 'OPerspective',
- 'msPerspective'
- ]) &&
- !Monocle.Browser.renders.slow // Some older browsers can't be trusted.
- );
- }],
-
-
- // Commonly-used browser functionality
- ["supportsOfflineCache", function () {
- result(typeof window.applicationCache != 'undefined');
- }],
-
- ["supportsLocalStorage", function () {
- // NB: Some duplicitous early Android browsers claim to have
- // localStorage, but calls to getItem() fail.
- result(
- typeof window.localStorage != "undefined" &&
- typeof window.localStorage.getItem == "function"
- )
- }],
-
-
- // CHECK OUT OUR CONTEXT
-
- // Does the device have a MobileSafari-style touch interface?
- //
- ["touch", function () {
- result(
- ('ontouchstart' in window) ||
- css.supportsMediaQueryProperty('touch-enabled')
- );
- }],
-
- // Is the Reader embedded, or in the top-level window?
- //
- ["embedded", function () { result(top != self) }],
-
-
- // TEST FOR CERTAIN RENDERING OR INTERACTION BUGS
-
- // iOS (at least up to version 4.1) makes a complete hash of touch events
- // when an iframe is overlapped by other elements. It's a dog's breakfast.
- // See test/bugs/ios-frame-touch-bug for details.
- //
- ["brokenIframeTouchModel", function () {
- result(Monocle.Browser.iOSVersionBelow("4.2"));
- }],
-
- // Webkit-based browsers put floated elements in the wrong spot when
- // columns are used -- they appear way down where they would be if there
- // were no columns. Presumably the float positions are calculated before
- // the columns. A bug has been lodged, and it's fixed in recent WebKits.
- //
- ["floatsIgnoreColumns", function () {
- if (!Monocle.Browser.is.WebKit) { return result(false); }
- match = navigator.userAgent.match(/AppleWebKit\/([\d\.]+)/);
- if (!match) { return result(false); }
- return result(match[1] < "534.30");
- }],
-
- // The latest engines all agree that if a body is translated leftwards,
- // its scrollWidth is shortened. But some older WebKits (notably iOS4)
- // do not subtract translateX values from scrollWidth. In this case,
- // we should not add the translate back when calculating the width.
- //
- ["widthsIgnoreTranslate", function () {
- loadTestFrame(function (fr) {
- var firstWidth = columnedWidth(fr);
- var s = fr.contentDocument.body.style;
- var props = css.toDOMProps("transform");
- for (var i = 0, ii = props.length; i < ii; ++i) {
- s[props[i]] = "translateX(-600px)";
- }
- var secondWidth = columnedWidth(fr);
- for (i = 0, ii = props.length; i < ii; ++i) {
- s[props[i]] = "none";
- }
- result(secondWidth == firstWidth);
- });
- }],
-
- // On Android browsers, if the component iframe has a relative width (ie,
- // 100%), the width of the entire browser will keep expanding and expanding
- // to fit the width of the body of the iframe (which, with columns, is
- // massive). So, 100% is treated as "of the body content" rather than "of
- // the parent dimensions". In this scenario, we need to give the component
- // iframe a fixed width in pixels.
- //
- // In iOS, the frame is clipped by overflow:hidden, so this doesn't seem to
- // be a problem.
- //
- ["relativeIframeExpands", function () {
- result(navigator.userAgent.indexOf("Android 2") >= 0);
- }],
-
- // iOS3 will pause JavaScript execution if it gets a style-change + a
- // scroll change on a component body. Weirdly, this seems to break GBCR
- // in iOS4.
- //
- ["scrollToApplyStyle", function () {
- result(Monocle.Browser.iOSVersionBelow("4"));
- }],
-
-
- // TEST FOR OTHER QUIRKY BROWSER BEHAVIOUR
-
- // Older versions of WebKit (iOS3, Kindle3) need a min-width set on the
- // body of the iframe at 200%. This forces columns. But when this
- // min-width is set, it's more difficult to recognise 1 page components,
- // so we generally don't want to force it unless we have to.
- //
- ["forceColumns", function () {
- loadTestFrame(function (fr) {
- var bd = fr.contentDocument.body;
- result(bd.className ? true : false);
- });
- }],
-
- // A component iframe's body is absolutely positioned. This means that
- // the documentElement should have a height of 0, since it contains nothing
- // other than an absolutely positioned element.
- //
- // But for some browsers (Gecko and Opera), the documentElement is as
- // wide as the full columned content, and the body is only as wide as
- // the iframe element (ie, the first column).
- //
- // It gets weirder. Gecko sometimes behaves like WebKit (not clipping the
- // body) IF the component has been loaded via HTML/JS/Nodes, not URL. Still
- // can't reproduce outside Monocle.
- //
- // FIXME: If we can figure out a reliable behaviour for Gecko, we should
- // use it to precalculate the workaround. At the moment, this test isn't
- // used, but it belongs in src/dimensions/columns.js#columnedDimensions().
- //
- // ["iframeBodyWidthClipped", function () {
- // loadTestFrame(function (fr) {
- // var doc = fr.contentDocument;
- // result(
- // doc.body.scrollWidth <= testFrameSize &&
- // doc.documentElement.scrollWidth > testFrameSize
- // );
- // })
- // }],
-
- // Finding the page that a given HTML node is on is typically done by
- // calculating the offset of its rectange from the body's rectangle.
- //
- // But if this information isn't provided by the browser, we need to use
- // node.scrollIntoView and check the scrollOffset. Basically iOS3 is the
- // only target platform that doesn't give us the rectangle info.
- //
- ["findNodesByScrolling", function () {
- result(typeof document.body.getBoundingClientRect !== "function");
- }],
-
- // In MobileSafari browsers, iframes are rendered at the width and height
- // of their content, rather than having scrollbars. So in that case, it's
- // the containing element (the "sheaf") that must be scrolled, not the
- // iframe body.
- //
- ["sheafIsScroller", function () {
- loadTestFrame(function (fr) {
- result(fr.parentNode.scrollWidth > testFrameSize);
- });
- }],
-
- // For some reason, iOS MobileSafari sometimes loses track of a page after
- // slideOut -- it thinks it has an x-translation of 0, rather than -768 or
- // whatever. So the page gets "stuck" there, until it is given a non-zero
- // x-translation. The workaround is to set a non-zero duration on the jumpIn,
- // which seems to force WebKit to recalculate the x of the page. Weird, yeah.
- //
- ["stickySlideOut", function () {
- result(Monocle.Browser.is.MobileSafari);
- }],
-
-
- // Chrome and Firefox incorrectly clip text when the dimensions of
- // a page are not an integer. IE10 clips text when the page dimensions
- // are rounded.
- //
- ['roundPageDimensions', function () {
- result(!Monocle.Browser.is.IE);
- }],
-
-
-
- // In IE10, the element of the iframe's document has scrollbars,
- // unless you set its style.overflow to 'hidden'.
- //
- ['documentElementHasScrollbars', function () {
- result(Monocle.Browser.is.IE);
- }],
-
-
- // Older versions of iOS (<6) would render blank pages if they were
- // off the screen when their layout/position was updated.
- //
- ['offscreenRenderingClipped', function () {
- result(Monocle.Browser.iOSVersionBelow('6'));
- }],
-
-
- // Gecko is better at loading content with document.write than with
- // javascript: URLs. With the latter, it tends to put cruft in history,
- // and gets confused by .
- ['loadHTMLWithDocWrite', function () {
- result(Monocle.Browser.is.Gecko || Monocle.Browser.is.Opera);
- }]
-
- ];
-
-
- function isCompatible() {
- return (
- API.supportsW3CEvents &&
- API.supportsCustomEvents &&
- API.supportsColumns &&
- API.supportsTransform &&
- !API.brokenIframeTouchModel
- );
- }
-
-
- API.survey = survey;
- API.isCompatible = isCompatible;
-
- return API;
-}
-;
-// A class for manipulating CSS properties in a browser-engine-aware way.
-//
-Monocle.CSS = function () {
-
- var API = { constructor: Monocle.CSS }
- var k = API.constants = API.constructor;
- var p = API.properties = {
- guineapig: document.createElement('div')
- }
-
-
- // Returns engine-specific properties,
- //
- // eg:
- //
- // toCSSProps('transform')
- //
- // ... in WebKit, this will return:
- //
- // ['transform', '-webkit-transform']
- //
- function toCSSProps(prop) {
- var props = [prop];
- var eng = k.engines.indexOf(Monocle.Browser.engine);
- if (eng) {
- var pf = k.prefixes[eng];
- if (pf) {
- props.push(pf+prop);
- }
- }
- return props;
- }
-
-
- // Returns an engine-specific CSS string.
- //
- // eg:
- //
- // toCSSDeclaration('column-width', '300px')
- //
- // ... in Mozilla, this will return:
- //
- // "column-width: 300px; -moz-column-width: 300px;"
- //
- function toCSSDeclaration(prop, val) {
- var props = toCSSProps(prop);
- for (var i = 0, ii = props.length; i < ii; ++i) {
- props[i] += ": "+val+";";
- }
- return props.join("");
- }
-
-
- // Returns an array of DOM properties specific to this engine.
- //
- // eg:
- //
- // toDOMProps('column-width')
- //
- // ... in Opera, this will return:
- //
- // [columnWidth, OColumnWidth]
- //
- function toDOMProps(prop) {
- var parts = prop.split('-');
- for (var i = parts.length; i > 0; --i) {
- parts[i] = capStr(parts[i]);
- }
-
- var props = [parts.join('')];
- var eng = k.engines.indexOf(Monocle.Browser.engine);
- if (eng) {
- var pf = k.domprefixes[eng];
- if (pf) {
- parts[0] = capStr(parts[0]);
- props.push(pf+parts.join(''));
- }
- }
- return props;
- }
-
-
- // Is this exact property (or any in this array of properties) supported
- // by this engine?
- //
- function supportsProperty(props) {
- for (var i in props) {
- if (p.guineapig.style[props[i]] !== undefined) { return true; }
- }
- return false;
- } // Thanks modernizr!
-
-
-
- // Is this property (or a prefixed variant) supported by this engine?
- //
- function supportsPropertyWithAnyPrefix(prop) {
- return supportsProperty(toDOMProps(prop));
- }
-
-
- function supportsMediaQuery(query) {
- var gpid = "monocle_guineapig";
- p.guineapig.id = gpid;
- var st = document.createElement('style');
- st.textContent = query+'{#'+gpid+'{height:3px}}';
- (document.head || document.getElementsByTagName('head')[0]).appendChild(st);
- document.documentElement.appendChild(p.guineapig);
-
- var result = p.guineapig.offsetHeight === 3;
-
- st.parentNode.removeChild(st);
- p.guineapig.parentNode.removeChild(p.guineapig);
-
- return result;
- } // Thanks modernizr!
-
-
- function supportsMediaQueryProperty(prop) {
- return supportsMediaQuery(
- '@media (' + k.prefixes.join(prop+'),(') + 'monocle__)'
- );
- }
-
-
- function capStr(wd) {
- return wd ? wd.charAt(0).toUpperCase() + wd.substr(1) : "";
- }
-
-
- API.toCSSProps = toCSSProps;
- API.toCSSDeclaration = toCSSDeclaration;
- API.toDOMProps = toDOMProps;
- API.supportsProperty = supportsProperty;
- API.supportsPropertyWithAnyPrefix = supportsPropertyWithAnyPrefix;
- API.supportsMediaQuery = supportsMediaQuery;
- API.supportsMediaQueryProperty = supportsMediaQueryProperty;
-
- return API;
-}
-
-
-Monocle.CSS.engines = ["W3C", "WebKit", "Gecko", "Opera", "IE", "Konqueror"];
-Monocle.CSS.prefixes = ["", "-webkit-", "-moz-", "-o-", "-ms-", "-khtml-"];
-Monocle.CSS.domprefixes = ["", "Webkit", "Moz", "O", "ms", "Khtml"];
-// STUBS - simple debug functions and polyfills to normalise client
-// execution environments.
-
-
-// A little console stub if not initialized in a console-equipped browser.
-//
-if (typeof window.console == "undefined") {
- window.console = { messages: [] }
- window.console.log = function (msg) {
- this.messages.push(msg);
- }
- window.console.warn = window.console.log;
-}
-
-
-// A simple version of console.dir that works on iOS.
-//
-window.console.compatDir = function (obj) {
- var stringify = function (o) {
- var parts = [];
- for (x in o) {
- parts.push(x + ": " + o[x]);
- }
- return parts.join(";\n");
- }
-
- var out = stringify(obj);
- window.console.log(out);
- return out;
-}
-
-
-// This is called by Monocle methods and practices that are no longer
-// recommended and will soon be removed.
-//
-window.console.deprecation = function (msg) {
- console.warn("[DEPRECATION]: "+msg);
- if (typeof console.trace == "function") {
- console.trace();
- }
-}
-
-
-// A convenient alias for setTimeout that assumes 0 if no timeout is specified.
-//
-Monocle.defer = function (fn, time) {
- if (typeof fn == "function") {
- return setTimeout(fn, time || 0);
- }
-}
-;
-Monocle.Browser = {};
-
-// Compare the user-agent string to a string or regex pattern.
-//
-Monocle.Browser.uaMatch = function (test) {
- var ua = navigator.userAgent;
- if (typeof test == "string") { return ua.indexOf(test) >= 0; }
- return !!ua.match(test);
-}
-
-
-// Detect the browser engine and set boolean flags for reference.
-//
-Monocle.Browser.is = {
- IE: !!(window.attachEvent && !Monocle.Browser.uaMatch('Opera')),
- Opera: Monocle.Browser.uaMatch('Opera'),
- WebKit: Monocle.Browser.uaMatch(/Apple\s?WebKit/),
- Gecko: Monocle.Browser.uaMatch('Gecko') && !Monocle.Browser.uaMatch('KHTML'),
- MobileSafari: Monocle.Browser.uaMatch(/OS \d_.*AppleWebKit.*Mobile/)
-}
-
-
-// Set the browser engine string.
-//
-if (Monocle.Browser.is.IE) {
- Monocle.Browser.engine = "IE";
-} else if (Monocle.Browser.is.Opera) {
- Monocle.Browser.engine = "Opera";
-} else if (Monocle.Browser.is.WebKit) {
- Monocle.Browser.engine = "WebKit";
-} else if (Monocle.Browser.is.Gecko) {
- Monocle.Browser.engine = "Gecko";
-} else {
- console.warn("Unknown engine; assuming W3C compliant.");
- Monocle.Browser.engine = "W3C";
-}
-
-
-// Detect the client platform (typically device/operating system).
-//
-Monocle.Browser.on = {
- iPhone: Monocle.Browser.is.MobileSafari && screen.width == 320,
- iPad: Monocle.Browser.is.MobileSafari && screen.width == 768,
- UIWebView: (
- Monocle.Browser.is.MobileSafari &&
- !Monocle.Browser.uaMatch('Safari') &&
- !navigator.standalone
- ),
- BlackBerry: Monocle.Browser.uaMatch('BlackBerry'),
- Android: (
- Monocle.Browser.uaMatch('Android') ||
- Monocle.Browser.uaMatch(/Linux;.*EBRD/) // Sony Readers
- ),
- MacOSX: (
- Monocle.Browser.uaMatch('Mac OS X') &&
- !Monocle.Browser.is.MobileSafari
- ),
- Kindle3: Monocle.Browser.uaMatch(/Kindle\/3/)
-}
-
-
-// It is only because MobileSafari is responsible for so much anguish that
-// we special-case it here. Not a badge of honour.
-//
-if (Monocle.Browser.is.MobileSafari) {
- (function () {
- var ver = navigator.userAgent.match(/ OS ([\d_]+)/);
- if (ver) {
- Monocle.Browser.iOSVersion = ver[1].replace(/_/g, '.');
- } else {
- console.warn("Unknown MobileSafari user agent: "+navigator.userAgent);
- }
- })();
-}
-Monocle.Browser.iOSVersionBelow = function (strOrNum) {
- return !!Monocle.Browser.iOSVersion && Monocle.Browser.iOSVersion < strOrNum;
-}
-
-
-// Some browser environments are too slow or too problematic for
-// special animation effects.
-//
-// FIXME: These tests are too opinionated. Replace with more targeted tests.
-//
-Monocle.Browser.renders = (function () {
- var ua = navigator.userAgent;
- var caps = {};
- caps.eInk = Monocle.Browser.on.Kindle3;
- caps.slow = (
- caps.eInk ||
- (Monocle.Browser.on.Android && !ua.match(/Chrome/)) ||
- Monocle.Browser.on.Blackberry ||
- ua.match(/NintendoBrowser/)
- );
- return caps;
-})();
-
-
-// A helper class for sniffing CSS features and creating CSS rules
-// appropriate to the current rendering engine.
-//
-Monocle.Browser.css = new Monocle.CSS();
-
-
-// During Reader initialization, this method is called to create the
-// "environment", which tests for the existence of various browser
-// features and bugs, then invokes the callback to continue initialization.
-//
-// If the survey has already been conducted and the env exists, calls
-// callback immediately.
-//
-Monocle.Browser.survey = function (callback) {
- if (!Monocle.Browser.env) {
- Monocle.Browser.env = new Monocle.Env();
- Monocle.Browser.env.survey(callback);
- } else if (typeof callback == "function") {
- callback();
- }
-}
-;
-Gala = {}
-
-
-// Register an event listener.
-//
-Gala.listen = function (elem, evtType, fn, useCapture) {
- elem = Gala.$(elem);
- if (elem.addEventListener) {
- elem.addEventListener(evtType, fn, useCapture || false);
- } else if (elem.attachEvent) {
- if (evtType.indexOf(':') < 1) {
- elem.attachEvent('on'+evtType, fn);
- } else {
- var h = (Gala.IE_REGISTRATIONS[elem] = Gala.IE_REGISTRATIONS[elem] || {});
- var a = (h[evtType] = h[evtType] || []);
- a.push(fn);
- }
- }
-}
-
-
-// Remove an event listener.
-//
-Gala.deafen = function (elem, evtType, fn, useCapture) {
- elem = Gala.$(elem);
- if (elem.removeEventListener) {
- elem.removeEventListener(evtType, fn, useCapture || false);
- } else if (elem.detachEvent) {
- if (evtType.indexOf(':') < 1) {
- elem.detachEvent('on'+evtType, fn);
- } else {
- var h = (Gala.IE_REGISTRATIONS[elem] = Gala.IE_REGISTRATIONS[elem] || {});
- var a = (h[evtType] = h[evtType] || []);
- for (var i = 0, ii = a.length; i < ii; ++i) {
- if (a[i] == fn) { a.splice(i, 1); }
- }
- }
- }
-}
-
-
-// Fire an event on the element.
-//
-// The data supplied to this function will be available in the event object in
-// the 'm' property -- eg, alert(evt.m) --> 'foo'
-//
-Gala.dispatch = function (elem, evtType, data, cancelable) {
- elem = Gala.$(elem);
- if (elem.dispatchEvent) {
- var evt = document.createEvent('Events');
- evt.initEvent(evtType, false, cancelable || false);
- evt.m = data;
- return elem.dispatchEvent(evt);
- } else if (elem.attachEvent && evtType.indexOf(':') >= 0) {
- if (!Gala.IE_REGISTRATIONS[elem]) { return true; }
- var evtHandlers = Gala.IE_REGISTRATIONS[elem][evtType];
- if (!evtHandlers || evtHandlers.length < 1) { return true; }
- var evt = {
- type: evtType,
- currentTarget: elem,
- target: elem,
- m: data,
- defaultPrevented: false,
- preventDefault: function () { evt.defaultPrevented = true; }
- }
- var q, processQueue = Gala.IE_INVOCATION_QUEUE.length == 0;
- for (var i = 0, ii = evtHandlers.length; i < ii; ++i) {
- q = { elem: elem, evtType: evtType, handler: evtHandlers[i], evt: evt }
- Gala.IE_INVOCATION_QUEUE.push(q);
- }
- if (processQueue) {
- while (q = Gala.IE_INVOCATION_QUEUE.shift()) {
- //console.log("IE EVT on %s: '%s' with data: %s", q.elem, q.evtType, q.evt.m);
- q.handler(q.evt);
- }
- }
- return !(cancelable && evt.defaultPrevented);
- } else {
- console.warn('[GALA] Cannot dispatch non-namespaced events: '+evtType);
- return true;
- }
-}
-
-
-// Prevents the browser-default action on an event and stops it from
-// propagating up the DOM tree.
-//
-Gala.stop = function (evt) {
- evt = evt || window.event;
- if (evt.preventDefault) { evt.preventDefault(); }
- if (evt.stopPropagation) { evt.stopPropagation(); }
- evt.returnValue = false;
- evt.cancelBubble = true;
- return false;
-}
-
-
-// Add a group of listeners, which is just a hash of { evtType: callback, ... }
-//
-Gala.listenGroup = function (elem, listeners, useCapture) {
- for (evtType in listeners) {
- Gala.listen(elem, evtType, listeners[evtType], useCapture || false);
- }
-}
-
-
-// Remove a group of listeners.
-//
-Gala.deafenGroup = function (elem, listeners, useCapture) {
- for (evtType in listeners) {
- Gala.deafen(elem, evtType, listeners[evtType], useCapture || false);
- }
-}
-
-
-// Replace a group of listeners with another group, re-using the same
-// 'listeners' object -- a common pattern.
-//
-Gala.replaceGroup = function (elem, listeners, newListeners, useCapture) {
- Gala.deafenGroup(elem, listeners, useCapture || false);
- for (evtType in listeners) { delete listeners[evtType]; }
- for (evtType in newListeners) { listeners[evtType] = newListeners[evtType]; }
- Gala.listenGroup(elem, listeners, useCapture || false);
- return listeners;
-}
-
-
-// Listen for a tap or a click event.
-//
-// Returns a 'listener' object that can be passed to Gala.deafenGroup().
-//
-// If 'tapClass' is undefined, it defaults to 'tapping'. If it is a blank
-// string, no class is assigned.
-//
-Gala.onTap = function (elem, fn, tapClass) {
- elem = Gala.$(elem);
- if (typeof tapClass == 'undefined') { tapClass = Gala.TAPPING_CLASS; }
- var tapping = false;
- var fns = {
- start: function (evt) {
- tapping = true;
- if (tapClass) { elem.classList.add(tapClass); }
- },
- move: function (evt) {
- if (!tapping) { return; }
- tapping = false;
- if (tapClass) { elem.classList.remove(tapClass); }
- },
- end: function (evt) {
- if (!tapping) { return; }
- fns.move(evt);
- evt.currentTarget = evt.currentTarget || evt.srcElement;
- fn(evt);
- },
- noop: function (evt) {}
- }
- var noopOnClick = function (listeners) {
- Gala.listen(elem, 'click', listeners.click = fns.noop);
- }
- Gala.listen(window, 'gala:contact:cancel', fns.move);
- return Gala.onContact(elem, fns, false, noopOnClick);
-}
-
-
-// Register a series of functions to listen for the start, move, end
-// events of a mouse or touch interaction.
-//
-// 'fns' argument is an object like:
-//
-// {
-// 'start': function () { ... },
-// 'move': function () { ... },
-// 'end': function () { ... },
-// 'cancel': function () { ... }
-// }
-//
-// All of the functions in this object are optional.
-//
-// Returns an object that can later be passed to Gala.deafenGroup.
-//
-Gala.onContact = function (elem, fns, useCapture, initCallback) {
- elem = Gala.$(elem);
- var listeners = null;
- var inited = false;
-
- // If we see a touchstart event, register all these listeners.
- var touchListeners = function () {
- var l = {}
- if (fns.start) {
- l.touchstart = function (evt) {
- if (evt.touches.length <= 1) { fns.start(evt); }
- }
- }
- if (fns.move) {
- l.touchmove = function (evt) {
- if (evt.touches.length <= 1) { fns.move(evt); }
- }
- }
- if (fns.end) {
- l.touchend = function (evt) {
- if (evt.touches.length <= 1) { fns.end(evt); }
- }
- }
- if (fns.cancel) {
- l.touchcancel = fns.cancel;
- }
- return l;
- }
-
- // Whereas if we see a mousedown event, register all these listeners.
- var mouseListeners = function () {
- var l = {};
- if (fns.start) {
- l.mousedown = function (evt) { if (evt.button < 2) { fns.start(evt); } }
- }
- if (fns.move) {
- l.mousemove = fns.move;
- }
- if (fns.end) {
- l.mouseup = function (evt) { if (evt.button < 2) { fns.end(evt); } }
- }
- // if (fns.cancel) {
- // l.mouseout = function (evt) {
- // obj = evt.relatedTarget || evt.fromElement;
- // while (obj && (obj = obj.parentNode)) { if (obj == elem) { return; } }
- // fns.cancel(evt);
- // }
- // }
- return l;
- }
-
- if (typeof Gala.CONTACT_MODE == 'undefined') {
- var contactInit = function (evt, newListeners, mode) {
- if (inited) { return; }
- Gala.CONTACT_MODE = Gala.CONTACT_MODE || mode;
- if (Gala.CONTACT_MODE != mode) { return; }
- Gala.replaceGroup(elem, listeners, newListeners, useCapture);
- if (typeof initCallback == 'function') { initCallback(listeners); }
- if (listeners[evt.type]) { listeners[evt.type](evt); }
- inited = true;
- }
- var touchInit = function (evt) {
- contactInit(evt, touchListeners(), 'touch');
- }
- var mouseInit = function (evt) {
- contactInit(evt, mouseListeners(), 'mouse');
- }
- listeners = {
- 'touchstart': touchInit,
- 'touchmove': touchInit,
- 'touchend': touchInit,
- 'touchcancel': touchInit,
- 'mousedown': mouseInit,
- 'mousemove': mouseInit,
- 'mouseup': mouseInit,
- 'mouseout': mouseInit
- }
- } else if (Gala.CONTACT_MODE == 'touch') {
- listeners = touchListeners();
- } else if (Gala.CONTACT_MODE == 'mouse') {
- listeners = mouseListeners();
- }
-
- Gala.listenGroup(elem, listeners);
- if (typeof initCallback == 'function') { initCallback(listeners); }
- return listeners;
-}
-
-
-// The Gala.Cursor object provides more detail coordinates for the contact
-// event, and normalizes differences between touch and mouse coordinates.
-//
-// If you have a contact event listener, you can get the coordinates for it
-// with:
-//
-// var cursor = new Gala.Cursor(evt);
-//
-Gala.Cursor = function (evt) {
- var API = { constructor: Gala.Cursor }
-
-
- function initialize() {
- var ci =
- evt.type.indexOf('mouse') == 0 ? evt :
- ['touchstart', 'touchmove'].indexOf(evt.type) >= 0 ? evt.targetTouches[0] :
- ['touchend', 'touchcancel'].indexOf(evt.type) >= 0 ? evt.changedTouches[0] :
- null;
-
- // Basic coordinates (provided by the event).
- API.pageX = ci.pageX;
- API.pageY = ci.pageY;
- API.clientX = ci.clientX;
- API.clientY = ci.clientY;
- API.screenX = ci.screenX;
- API.screenY = ci.screenY;
-
- // Coordinates relative to the target element for the event.
- var tgt = API.target = evt.target || evt.srcElement;
- while (tgt.nodeType != 1 && tgt.parentNode) { tgt = tgt.parentNode; }
- assignOffsetFor(tgt, 'offset');
-
- // Coordinates relative to the element that the event was registered on.
- var registrant = evt.currentTarget;
- if (registrant && typeof registrant.offsetLeft != 'undefined') {
- assignOffsetFor(registrant, 'registrant');
- }
- }
-
-
- function assignOffsetFor(elem, attr) {
- var r;
- if (elem.getBoundingClientRect) {
- var er = elem.getBoundingClientRect();
- var dr = document.documentElement.getBoundingClientRect();
- r = { left: er.left - dr.left, top: er.top - dr.top }
- } else {
- r = { left: elem.offsetLeft, top: elem.offsetTop }
- while (elem = elem.offsetParent) {
- if (elem.offsetLeft || elem.offsetTop) {
- r.left += elem.offsetLeft;
- r.top += elem.offsetTop;
- }
- }
- }
- API[attr+'X'] = API.pageX - r.left;
- API[attr+'Y'] = API.pageY - r.top;
- }
-
-
- initialize();
-
- return API;
-}
-
-
-// A little utility to dereference ids into elements. You've seen this before.
-//
-Gala.$ = function (elem) {
- if (typeof elem == 'string') { elem = document.getElementById(elem); }
- return elem;
-}
-
-
-
-// CONSTANTS
-//
-Gala.TAPPING_CLASS = 'tapping';
-Gala.IE_REGISTRATIONS = {}
-Gala.IE_INVOCATION_QUEUE = []
-;
-// A shortcut for creating a bookdata object from a 'data' hash.
-//
-// eg:
-//
-// Monocle.bookData({ components: ['intro.html', 'ch1.html', 'ch2.html'] });
-//
-// All keys in the 'data' hash are optional:
-//
-// components: must be an array of component urls
-// chapters: must be an array of nested chapters (the usual bookdata structure)
-// metadata: must be a hash of key/values
-// getComponentFn: override the default way to fetch components via id
-//
-Monocle.bookData = function (data) {
- return {
- getComponents: function () {
- return data.components || ['anonymous'];
- },
- getContents: function () {
- return data.chapters || [];
- },
- getComponent: data.getComponent || function (id) {
- return { url: id }
- },
- getMetaData: function (key) {
- return (data.metadata || {})[key];
- },
- data: data
- }
-}
-
-
-// A shortcut for creating a bookdata object from an array of element ids.
-//
-// eg:
-//
-// Monocle.bookDataFromIds(['part1', 'part2']);
-//
-Monocle.bookDataFromIds = function (elementIds) {
- return Monocle.bookData({
- components: elementIds,
- getComponent: function (cmptId) {
- return { nodes: [document.getElementById(cmptId)] }
- }
- });
-}
-
-
-// A shortcut for creating a bookdata object from an array of nodes.
-//
-// eg:
-//
-// Monocle.bookDataFromNodes([document.getElementById('content')]);
-//
-Monocle.bookDataFromNodes = function (nodes) {
- return Monocle.bookData({
- getComponent: function (n) { return { 'nodes': nodes }; }
- });
-}
-;
-Monocle.Factory = function (element, label, index, reader) {
-
- var API = { constructor: Monocle.Factory };
- var k = API.constants = API.constructor;
- var p = API.properties = {
- element: element,
- label: label,
- index: index,
- reader: reader,
- prefix: reader.properties.classPrefix || ''
- }
-
-
- // If index is null, uses the first available slot. If index is not null and
- // the slot is not free, throws an error.
- //
- function initialize() {
- if (!p.label) { return; }
- // Append the element to the reader's graph of DOM elements.
- var node = p.reader.properties.graph;
- node[p.label] = node[p.label] || [];
- if (typeof p.index == 'undefined' && node[p.label][p.index]) {
- throw('Element already exists in graph: '+p.label+'['+p.index+']');
- } else {
- p.index = p.index || node[p.label].length;
- }
- node[p.label][p.index] = p.element;
-
- // Add the label as a class name.
- addClass(p.label);
- }
-
-
- // Finds an element that has been created in the context of the current
- // reader, with the given label. If oIndex is not provided, returns first.
- // If oIndex is provided (eg, n), returns the nth element with the label.
- //
- function find(oLabel, oIndex) {
- if (!p.reader.properties.graph[oLabel]) {
- return null;
- }
- return p.reader.properties.graph[oLabel][oIndex || 0];
- }
-
-
- // Takes an elements and assimilates it into the reader -- essentially
- // giving it a "dom" object of it's own. It will then be accessible via find.
- //
- // Note that (as per comments for initialize), if oIndex is provided and
- // there is no free slot in the array for this label at that index, an
- // error will be thrown.
- //
- function claim(oElement, oLabel, oIndex) {
- return oElement.dom = new Monocle.Factory(
- oElement,
- oLabel,
- oIndex,
- p.reader
- );
- }
-
-
- // Create an element with the given label.
- //
- // The last argument (whether third or fourth) is the options hash. Your
- // options are:
- //
- // class - the classname for the element. Must only be one name.
- // html - the innerHTML for the element.
- // text - the innerText for the element (an alternative to html, simpler).
- //
- // Returns the created element.
- //
- function make(tagName, oLabel, index_or_options, or_options) {
- var oIndex, options;
- if (arguments.length == 1) {
- oLabel = null,
- oIndex = 0;
- options = {};
- } else if (arguments.length == 2) {
- oIndex = 0;
- options = {};
- } else if (arguments.length == 4) {
- oIndex = arguments[2];
- options = arguments[3];
- } else if (arguments.length == 3) {
- var lastArg = arguments[arguments.length - 1];
- if (typeof lastArg == "number") {
- oIndex = lastArg;
- options = {};
- } else {
- oIndex = 0;
- options = lastArg;
- }
- }
-
- var oElement = document.createElement(tagName);
- claim(oElement, oLabel, oIndex);
- if (options['class']) {
- oElement.className += " "+p.prefix+options['class'];
- }
- if (options['html']) {
- oElement.innerHTML = options['html'];
- }
- if (options['text']) {
- oElement.appendChild(document.createTextNode(options['text']));
- }
-
- return oElement;
- }
-
-
- // Creates an element by passing all the given arguments to make. Then
- // appends the element as a child of the current element.
- //
- function append(tagName, oLabel, index_or_options, or_options) {
- var oElement = make.apply(this, arguments);
- p.element.appendChild(oElement);
- return oElement;
- }
-
-
- // Returns an array of [label, index, reader] for the given element.
- // A simple way to introspect the arguments required for #find, for eg.
- //
- function address() {
- return [p.label, p.index, p.reader];
- }
-
-
- // Apply a set of style rules (hash or string) to the current element.
- // See Monocle.Styles.applyRules for more info.
- //
- function setStyles(rules) {
- return Monocle.Styles.applyRules(p.element, rules);
- }
-
-
- function setBetaStyle(property, value) {
- return Monocle.Styles.affix(p.element, property, value);
- }
-
-
- // ClassName manipulation functions - with thanks to prototype.js!
-
- // Returns true if one of the current element's classnames matches name --
- // classPrefix aware (so don't concate the prefix onto it).
- //
- function hasClass(name) {
- name = p.prefix + name;
- var klass = p.element.className;
- if (!klass) { return false; }
- if (klass == name) { return true; }
- return new RegExp("(^|\\s)"+name+"(\\s|$)").test(klass);
- }
-
-
- // Adds name to the classnames of the current element (prepending the
- // reader's classPrefix first).
- //
- function addClass(name) {
- if (hasClass(name)) { return; }
- var gap = p.element.className ? ' ' : '';
- return p.element.className += gap+p.prefix+name;
- }
-
-
- // Removes (classPrefix+)name from the classnames of the current element.
- //
- function removeClass(name) {
- var reName = new RegExp("(^|\\s+)"+p.prefix+name+"(\\s+|$)");
- var reTrim = /^\s+|\s+$/g;
- var klass = p.element.className;
- p.element.className = klass.replace(reName, ' ').replace(reTrim, '');
- return p.element.className;
- }
-
-
- API.find = find;
- API.claim = claim;
- API.make = make;
- API.append = append;
- API.address = address;
-
- API.setStyles = setStyles;
- API.setBetaStyle = setBetaStyle;
- API.hasClass = hasClass;
- API.addClass = addClass;
- API.removeClass = removeClass;
-
- initialize();
-
- return API;
-}
-;
-Monocle.Events = {};
-
-
-Monocle.Events.wrapper = function (fn) {
- return function (evt) { evt.m = new Gala.Cursor(evt); fn(evt); }
-}
-
-
-Monocle.Events.listen = Gala.listen;
-
-
-Monocle.Events.deafen = Gala.deafen;
-
-
-Monocle.Events.dispatch = Gala.dispatch;
-
-
-Monocle.Events.listenForTap = function (elem, fn, tapClass) {
- return Gala.onTap(elem, Monocle.Events.wrapper(fn), tapClass);
-}
-
-
-Monocle.Events.deafenForTap = Gala.deafenGroup;
-
-
-Monocle.Events.listenForContact = function (elem, fns, options) {
- options = options || { useCapture: false };
- var wrappers = {};
- for (evtType in fns) {
- wrappers[evtType] = Monocle.Events.wrapper(fns[evtType]);
- }
- return Gala.onContact(elem, wrappers, options.useCapture);
-}
-
-
-Monocle.Events.deafenForContact = Gala.deafenGroup;
-
-
-// Listen for the next transition-end event on the given element, call
-// the function, then deafen.
-//
-// Returns a function that can be used to cancel the listen early.
-//
-Monocle.Events.afterTransition = function (elem, fn) {
- var evtName = "transitionend";
- if (Monocle.Browser.is.WebKit) {
- evtName = 'webkitTransitionEnd';
- } else if (Monocle.Browser.is.Opera) {
- evtName = 'oTransitionEnd';
- }
- var l = null, cancel = null;
- l = function () { fn(); cancel(); }
- cancel = function () { Monocle.Events.deafen(elem, evtName, l); }
- Monocle.Events.listen(elem, evtName, l);
- return cancel;
-}
-;
-Monocle.Styles = {
-
- // Takes a hash and returns a string.
- rulesToString: function (rules) {
- if (typeof rules != 'string') {
- var parts = [];
- for (var declaration in rules) {
- parts.push(declaration+": "+rules[declaration]+";")
- }
- rules = parts.join(" ");
- }
- return rules;
- },
-
-
- // Takes a hash or string of CSS property assignments and applies them
- // to the element.
- //
- applyRules: function (elem, rules) {
- rules = Monocle.Styles.rulesToString(rules);
- elem.style.cssText += ';'+rules;
- return elem.style.cssText;
- },
-
-
- // Generates cross-browser properties for a given property.
- // ie, affix(, 'transition', 'linear 100ms') would apply that value
- // to webkitTransition for WebKit browsers, and to MozTransition for Gecko.
- //
- affix: function (elem, property, value) {
- var target = elem.style ? elem.style : elem;
- var props = Monocle.Browser.css.toDOMProps(property);
- while (props.length) { target[props.shift()] = value; }
- },
-
-
- setX: function (elem, x) {
- var s = elem.style;
- if (typeof x == "number") { x += "px"; }
- var val = Monocle.Browser.env.supportsTransform3d ?
- 'translate3d('+x+', 0, 0)' :
- 'translateX('+x+')';
- val = (x == '0px') ? 'none' : val;
- s.webkitTransform = s.MozTransform = s.OTransform = s.transform = val;
- return x;
- },
-
-
- setY: function (elem, y) {
- var s = elem.style;
- if (typeof y == "number") { y += "px"; }
- var val = Monocle.Browser.env.supportsTransform3d ?
- 'translate3d(0, '+y+', 0)' :
- 'translateY('+y+')';
- val = (y == '0px') ? 'none' : val;
- s.webkitTransform = s.MozTransform = s.OTransform = s.transform = val;
- return y;
- },
-
-
- getX: function (elem) {
- var currStyle = document.defaultView.getComputedStyle(elem, null);
- var re = /matrix\([^,]+,[^,]+,[^,]+,[^,]+,\s*([^,]+),[^\)]+\)/;
- var props = Monocle.Browser.css.toDOMProps('transform');
- var matrix = null;
- while (props.length && !matrix) {
- matrix = currStyle[props.shift()];
- }
- return parseInt(matrix.match(re)[1]);
- },
-
-
- transitionFor: function (elem, prop, duration, timing, delay) {
- var tProps = Monocle.Browser.css.toDOMProps('transition');
- var pProps = Monocle.Browser.css.toCSSProps(prop);
- timing = timing || "linear";
- delay = (delay || 0)+"ms";
- for (var i = 0, ii = tProps.length; i < ii; ++i) {
- var t = "none";
- if (duration) {
- t = [pProps[i], duration+"ms", timing, delay].join(" ");
- }
- elem.style[tProps[i]] = t;
- }
- }
-
-}
-
-
-// These rule definitions are more or less compulsory for Monocle to behave
-// as expected. Which is why they appear here and not in the stylesheet.
-// Adjust them if you know what you're doing.
-//
-Monocle.Styles.container = {
- "position": "absolute",
- "overflow": "hidden",
- "top": "0",
- "left": "0",
- "bottom": "0",
- "right": "0"
-}
-
-Monocle.Styles.page = {
- "position": "absolute",
- "z-index": "1",
- "-webkit-user-select": "none",
- "-moz-user-select": "none",
- "-ms-user-select": "none",
- "user-select": "none",
- "-webkit-transform": "translate3d(0,0,0)",
- "visibility": "visible"
-
- /*
- "background": "white",
- "top": "0",
- "left": "0",
- "bottom": "0",
- "right": "0"
- */
-}
-
-Monocle.Styles.sheaf = {
- "position": "absolute",
- "overflow": "hidden"
-
- /*
- "top": "0",
- "left": "0",
- "bottom": "0",
- "right": "0"
- */
-}
-
-Monocle.Styles.component = {
- "width": "100%",
- "height": "100%",
- "border": "none",
- "-webkit-user-select": "none",
- "-moz-user-select": "none",
- "-ms-user-select": "none",
- "user-select": "none"
-}
-
-Monocle.Styles.control = {
- "z-index": "100",
- "cursor": "pointer"
-}
-
-Monocle.Styles.overlay = {
- "position": "absolute",
- "display": "none",
- "width": "100%",
- "height": "100%",
- "z-index": "1000"
-}
-;
-Monocle.Formatting = function (reader, optStyles, optScale) {
- var API = { constructor: Monocle.Formatting };
- var k = API.constants = API.constructor;
- var p = API.properties = {
- reader: reader,
-
- // An array of style rules that are automatically applied to every page.
- stylesheets: [],
-
- // A multiplier on the default font-size of each element in every
- // component. If null, the multiplier is not applied (or it is removed).
- fontScale: null
- }
-
-
- function initialize() {
- p.fontScale = optScale;
- clampStylesheets(optStyles);
- p.reader.listen('monocle:componentmodify', persistOnComponentChange);
- }
-
-
- // Clamp page frames to a set of styles that reduce Monocle breakage.
- //
- function clampStylesheets(implStyles) {
- var defCSS = k.DEFAULT_STYLE_RULES;
- if (Monocle.Browser.env.floatsIgnoreColumns) {
- defCSS.push("html#RS\\:monocle * { float: none !important; }");
- }
- p.defaultStyles = addPageStyles(defCSS, false);
- if (implStyles) {
- p.initialStyles = addPageStyles(implStyles, false);
- }
- }
-
-
- function persistOnComponentChange(evt) {
- var doc = evt.m['document'];
- doc.documentElement.id = p.reader.properties.systemId;
- adjustFontScaleForDoc(doc, p.fontScale);
- for (var i = 0; i < p.stylesheets.length; ++i) {
- if (p.stylesheets[i]) {
- addPageStylesheet(doc, i);
- }
- }
- }
-
-
- /* PAGE STYLESHEETS */
-
- // API for adding a new stylesheet to all components. styleRules should be
- // a string of CSS rules. restorePlace defaults to true.
- //
- // Returns a sheet index value that can be used with updatePageStyles
- // and removePageStyles.
- //
- function addPageStyles(styleRules, restorePlace) {
- return changingStylesheet(function () {
- p.stylesheets.push(styleRules);
- var sheetIndex = p.stylesheets.length - 1;
-
- var i = 0, cmpt = null;
- while (cmpt = p.reader.dom.find('component', i++)) {
- addPageStylesheet(cmpt.contentDocument, sheetIndex);
- }
- return sheetIndex;
- }, restorePlace);
- }
-
-
- // API for updating the styleRules in an existing page stylesheet across
- // all components. Takes a sheet index value obtained via addPageStyles.
- //
- function updatePageStyles(sheetIndex, styleRules, restorePlace) {
- return changingStylesheet(function () {
- p.stylesheets[sheetIndex] = styleRules;
- if (typeof styleRules.join == "function") {
- styleRules = styleRules.join("\n");
- }
-
- var i = 0, cmpt = null;
- while (cmpt = p.reader.dom.find('component', i++)) {
- var doc = cmpt.contentDocument;
- var styleTag = doc.getElementById('monStylesheet'+sheetIndex);
- if (!styleTag) {
- console.warn('No such stylesheet: ' + sheetIndex);
- return;
- }
- if (styleTag.styleSheet) {
- styleTag.styleSheet.cssText = styleRules;
- } else {
- styleTag.replaceChild(
- doc.createTextNode(styleRules),
- styleTag.firstChild
- );
- }
- }
- }, restorePlace);
- }
-
-
- // API for removing a page stylesheet from all components. Takes a sheet
- // index value obtained via addPageStyles.
- //
- function removePageStyles(sheetIndex, restorePlace) {
- return changingStylesheet(function () {
- p.stylesheets[sheetIndex] = null;
- var i = 0, cmpt = null;
- while (cmpt = p.reader.dom.find('component', i++)) {
- var doc = cmpt.contentDocument;
- var styleTag = doc.getElementById('monStylesheet'+sheetIndex);
- styleTag.parentNode.removeChild(styleTag);
- }
- }, restorePlace);
- }
-
-
- // Wraps all API-based stylesheet changes (add, update, remove) in a
- // brace of custom events (stylesheetchanging/stylesheetchange), and
- // recalculates component dimensions if specified (default to true).
- //
- function changingStylesheet(callback, restorePlace) {
- restorePlace = (restorePlace === false) ? false : true;
- if (restorePlace) {
- dispatchChanging();
- }
- var result = callback();
- if (restorePlace) {
- p.reader.recalculateDimensions(true);
- Monocle.defer(dispatchChange);
- } else {
- p.reader.recalculateDimensions(false);
- }
- return result;
- }
-
-
- function dispatchChanging() {
- p.reader.dispatchEvent("monocle:stylesheetchanging", {});
- }
-
-
- function dispatchChange() {
- p.reader.dispatchEvent("monocle:stylesheetchange", {});
- }
-
-
- // Private method for adding a stylesheet to a component. Used by
- // addPageStyles.
- //
- function addPageStylesheet(doc, sheetIndex) {
- var styleRules = p.stylesheets[sheetIndex];
-
- if (!styleRules) {
- return;
- }
-
- if (!doc || !doc.documentElement) {
- return;
- }
-
- var head = doc.getElementsByTagName('head')[0];
- if (!head) {
- head = doc.createElement('head');
- doc.documentElement.appendChild(head);
- }
-
- if (typeof styleRules.join == "function") {
- styleRules = styleRules.join("\n");
- }
-
- var styleTag = doc.createElement('style');
- styleTag.type = 'text/css';
- styleTag.id = "monStylesheet"+sheetIndex;
- if (styleTag.styleSheet) {
- styleTag.styleSheet.cssText = styleRules;
- } else {
- styleTag.appendChild(doc.createTextNode(styleRules));
- }
-
- head.appendChild(styleTag);
-
- return styleTag;
- }
-
-
- /* FONT SCALING */
-
- function setFontScale(scale, restorePlace) {
- p.fontScale = scale;
- if (restorePlace) {
- dispatchChanging();
- }
- var i = 0, cmpt = null;
- while (cmpt = p.reader.dom.find('component', i++)) {
- adjustFontScaleForDoc(cmpt.contentDocument, scale);
- }
- if (restorePlace) {
- p.reader.recalculateDimensions(true);
- dispatchChange();
- } else {
- p.reader.recalculateDimensions(false);
- }
- }
-
-
- function adjustFontScaleForDoc(doc, scale) {
- var elems = doc.getElementsByTagName('*');
- if (scale) {
- scale = parseFloat(scale);
- if (!doc.body.pfsSwept) {
- sweepElements(doc, elems);
- }
-
- // Iterate over each element, applying scale to the original
- // font-size. If a proportional font sizing is already applied to
- // the element, update existing cssText, otherwise append new cssText.
- //
- for (var j = 0, jj = elems.length; j < jj; ++j) {
- var newFs = fsProperty(elems[j].pfsOriginal, scale);
- if (elems[j].pfsApplied) {
- replaceFontSizeInStyle(elems[j], newFs);
- } else {
- elems[j].style.cssText += newFs;
- }
- elems[j].pfsApplied = scale;
- }
- } else if (doc.body.pfsSwept) {
- // Iterate over each element, removing proportional font-sizing flag
- // and property from cssText.
- for (var j = 0, jj = elems.length; j < jj; ++j) {
- if (elems[j].pfsApplied) {
- var oprop = elems[j].pfsOriginalProp;
- var opropDec = oprop ? 'font-size: '+oprop+' ! important;' : '';
- replaceFontSizeInStyle(elems[j], opropDec);
- elems[j].pfsApplied = null;
- }
- }
-
- // Establish new baselines in case classes have changed.
- sweepElements(doc, elems);
- }
- }
-
-
- function sweepElements(doc, elems) {
- // Iterate over each element, looking at its font size and storing
- // the original value against the element.
- for (var i = 0, ii = elems.length; i < ii; ++i) {
- var currStyle = doc.defaultView.getComputedStyle(elems[i], null);
- var fs = parseFloat(currStyle.getPropertyValue('font-size'));
- elems[i].pfsOriginal = fs;
- elems[i].pfsOriginalProp = elems[i].style.fontSize;
- }
- doc.body.pfsSwept = true;
- }
-
-
- function fsProperty(orig, scale) {
- return 'font-size: '+(orig*scale)+'px ! important;';
- }
-
-
- function replaceFontSizeInStyle(elem, newProp) {
- var lastFs = /font-size:[^;]/
- elem.style.cssText = elem.style.cssText.replace(lastFs, newProp);
- }
-
-
- API.addPageStyles = addPageStyles;
- API.updatePageStyles = updatePageStyles;
- API.removePageStyles = removePageStyles;
- API.setFontScale = setFontScale;
-
- initialize();
-
- return API;
-}
-
-
-
-Monocle.Formatting.DEFAULT_STYLE_RULES = [
- "html#RS\\:monocle * {" +
- "-webkit-font-smoothing: subpixel-antialiased;" +
- "text-rendering: auto !important;" +
- "word-wrap: break-word !important;" +
- "overflow: visible !important;" +
- "}",
- "html#RS\\:monocle body {" +
- "margin: 0 !important;"+
- "border: none !important;" +
- "padding: 0 !important;" +
- "width: 100% !important;" +
- "position: absolute !important;" +
- "-webkit-text-size-adjust: none;" +
- "}",
- "html#RS\\:monocle body * {" +
- "max-width: 100% !important;" +
- "}",
- "html#RS\\:monocle img, html#RS\\:monocle video, html#RS\\:monocle object, html#RS\\:monocle svg {" +
- "max-height: 95% !important;" +
- "height: auto !important;" +
- "}"
-]
-;
-// READER
-//
-//
-// The full DOM hierarchy created by Reader is:
-//
-// box
-// -> container
-// -> pages (the number of page elements is determined by the flipper)
-// -> sheaf (basically just sets the margins)
-// -> component (an iframe created by the current component)
-// -> body (the document.body of the iframe)
-// -> page controls
-// -> standard controls
-// -> overlay
-// -> modal/popover controls
-//
-//
-// Options:
-//
-// flipper: The class of page flipper to use.
-//
-// panels: The class of panels to use
-//
-// stylesheet: A string of CSS rules to apply to the contents of each
-// component loaded into the reader.
-//
-// fontScale: a float to multiply against the default font-size of each
-// element in each component.
-//
-// place: A book locus for the page to open to when the reader is
-// initialized. (See comments at Book#pageNumberAt for more about
-// the locus option).
-//
-// systemId: the id for root elements of components, defaults to "RS:monocle"
-//
-Monocle.Reader = function (node, bookData, options, onLoadCallback) {
-
- var API = { constructor: Monocle.Reader }
- var k = API.constants = API.constructor;
- var p = API.properties = {
- // Initialization-completed flag.
- initialized: false,
-
- // The active book.
- book: null,
-
- // DOM graph of factory-generated objects.
- graph: {},
-
- // Id applied to the HTML element of each component, can be used to scope
- // CSS rules.
- systemId: (options ? options.systemId : null) || k.DEFAULT_SYSTEM_ID,
-
- // Prefix for classnames for any created element.
- classPrefix: k.DEFAULT_CLASS_PREFIX,
-
- // Registered control objects (see addControl). Hashes of the form:
- // {
- // control: ,
- // elements: ,
- // controlType:
- // }
- controls: [],
-
- // After the reader has been resized, this resettable timer must expire
- // the place is restored.
- resizeTimer: null
- }
-
- var dom;
-
-
- // Inspects the browser environment and kicks off preparing the container.
- //
- function initialize() {
- options = options || {}
-
- Monocle.Browser.survey(prepareBox);
- }
-
-
- // Sets up the container and internal elements.
- //
- function prepareBox() {
- var box = node;
- if (typeof box == "string") { box = document.getElementById(box); }
- dom = API.dom = box.dom = new Monocle.Factory(box, 'box', 0, API);
-
- API.billboard = new Monocle.Billboard(API);
-
- if (!Monocle.Browser.env.isCompatible()) {
- if (dispatchEvent("monocle:incompatible", {}, true)) {
- fatalSystemMessage(k.COMPATIBILITY_INFO);
- }
- return;
- }
-
- dispatchEvent("monocle:initializing", API);
-
- bookData = bookData || Monocle.bookDataFromNodes([box.cloneNode(true)]);
- var bk = new Monocle.Book(bookData, options.preloadWindow || 1);
-
- box.innerHTML = "";
-
- // Make sure the box div is absolutely or relatively positioned.
- positionBox();
-
- // Attach the page-flipping gadget.
- attachFlipper(options.flipper);
-
- // Create the essential DOM elements.
- createReaderElements();
-
- // Create the selection object.
- API.selection = new Monocle.Selection(API);
-
- // Create the formatting object.
- API.formatting = new Monocle.Formatting(
- API,
- options.stylesheet,
- options.fontScale
- );
-
- primeFrames(options.primeURL, function () {
- // Make the reader elements look pretty.
- applyStyles();
-
- p.flipper.listenForInteraction(options.panels);
-
- setBook(bk, options.place, function () {
- if (onLoadCallback) { onLoadCallback(API); }
- dispatchEvent("monocle:loaded", API);
- });
- });
- }
-
-
- function positionBox() {
- var currPosVal;
- var box = dom.find('box');
- if (document.defaultView) {
- var currStyle = document.defaultView.getComputedStyle(box, null);
- currPosVal = currStyle.getPropertyValue('position');
- } else if (box.currentStyle) {
- currPosVal = box.currentStyle.position
- }
- if (["absolute", "relative"].indexOf(currPosVal) == -1) {
- box.style.position = "relative";
- }
- }
-
-
- function attachFlipper(flipperClass) {
- if (!flipperClass) {
- if (Monocle.Browser.renders.slow) {
- flipperClass = Monocle.Flippers.Instant;
- } else {
- flipperClass = Monocle.Flippers.Slider;
- }
- }
-
- p.flipper = new flipperClass(API, null, p.readerOptions);
- }
-
-
- function createReaderElements() {
- var cntr = dom.append('div', 'container');
- for (var i = 0; i < p.flipper.pageCount; ++i) {
- var page = cntr.dom.append('div', 'page', i);
- page.style.visibility = "hidden";
- page.m = { reader: API, pageIndex: i, place: null }
- page.m.sheafDiv = page.dom.append('div', 'sheaf', i);
- page.m.activeFrame = page.m.sheafDiv.dom.append('iframe', 'component', i);
- page.m.activeFrame.m = { 'pageDiv': page };
- page.m.activeFrame.setAttribute('frameBorder', 0);
- page.m.activeFrame.setAttribute('scrolling', 'no');
- p.flipper.addPage(page);
- }
- dom.append('div', 'overlay');
- dispatchEvent("monocle:loading", API);
- }
-
-
- // Opens the frame to a particular URL (usually 'about:blank').
- //
- function primeFrames(url, callback) {
- url = url || (Monocle.Browser.on.UIWebView ? "blank.html" : "about:blank");
-
- var pageCount = 0;
-
- var cb = function (evt) {
- var frame = evt.target || evt.srcElement;
- Monocle.Events.deafen(frame, 'load', cb);
- dispatchEvent(
- 'monocle:frameprimed',
- { frame: frame, pageIndex: pageCount }
- );
- if ((pageCount += 1) == p.flipper.pageCount) {
- Monocle.defer(callback);
- }
- }
-
- forEachPage(function (page) {
- Monocle.Events.listen(page.m.activeFrame, 'load', cb);
- page.m.activeFrame.src = url;
- });
- }
-
-
- function applyStyles() {
- dom.find('container').dom.setStyles(Monocle.Styles.container);
- forEachPage(function (page, i) {
- page.dom.setStyles(Monocle.Styles.page);
- dom.find('sheaf', i).dom.setStyles(Monocle.Styles.sheaf);
- var cmpt = dom.find('component', i)
- cmpt.dom.setStyles(Monocle.Styles.component);
- });
- lockFrameWidths();
- dom.find('overlay').dom.setStyles(Monocle.Styles.overlay);
- dispatchEvent('monocle:styles');
- }
-
-
- function lockingFrameWidths() {
- if (!Monocle.Browser.env.relativeIframeExpands) { return; }
- for (var i = 0, cmpt; cmpt = dom.find('component', i); ++i) {
- cmpt.style.display = "none";
- }
- }
-
-
- function lockFrameWidths() {
- if (!Monocle.Browser.env.relativeIframeExpands) { return; }
- for (var i = 0, cmpt; cmpt = dom.find('component', i); ++i) {
- cmpt.style.width = cmpt.parentNode.offsetWidth+"px";
- cmpt.style.display = "block";
- }
- }
-
-
- // Apply the book, move to a particular place or just the first page, wait
- // for everything to complete, then fire the callback.
- //
- function setBook(bk, place, callback) {
- p.book = bk;
- var pageCount = 0;
- if (typeof callback == 'function') {
- var watchers = {
- 'monocle:componentchange': function (evt) {
- dispatchEvent('monocle:firstcomponentchange', evt.m);
- return (pageCount += 1) == p.flipper.pageCount;
- },
- 'monocle:componentfailed': function (evt) {
- fatalSystemMessage(k.LOAD_FAILURE_INFO);
- return true;
- },
- 'monocle:turn': function (evt) {
- deafen('monocle:componentfailed', listener);
- callback();
- return true;
- }
- }
- var listener = function (evt) {
- if (watchers[evt.type](evt)) { deafen(evt.type, listener); }
- }
- for (evtType in watchers) { listen(evtType, listener) }
- }
- p.flipper.moveTo(place || { page: 1 }, initialized);
- }
-
-
- function getBook() {
- return p.book;
- }
-
-
- function initialized() {
- p.initialized = true;
- }
-
-
- // Attempts to restore the place we were up to in the book before the
- // reader was resized.
- //
- // The delay ensures that if we get multiple calls to this function in
- // a short period, we don't do lots of expensive recalculations.
- //
- function resized() {
- if (!p.initialized) {
- console.warn('Attempt to resize book before initialization.');
- }
- lockingFrameWidths();
- if (!dispatchEvent("monocle:resizing", {}, true)) {
- return;
- }
- clearTimeout(p.resizeTimer);
- p.resizeTimer = Monocle.defer(performResize, k.RESIZE_DELAY);
- }
-
-
- function performResize() {
- lockFrameWidths();
- recalculateDimensions(true, afterResized);
- }
-
-
- function afterResized() {
- dispatchEvent('monocle:resize');
- }
-
-
- function recalculateDimensions(andRestorePlace, callback) {
- if (!p.book) { return; }
- dispatchEvent("monocle:recalculating");
-
- var place, locus;
- if (andRestorePlace !== false) {
- var place = getPlace();
- var locus = { percent: place ? place.percentageThrough() : 0 };
- }
-
- forEachPage(function (pageDiv) {
- pageDiv.m.activeFrame.m.component.updateDimensions(pageDiv);
- });
-
- var cb = function () {
- dispatchEvent("monocle:recalculated");
- Monocle.defer(callback);
- }
- Monocle.defer(function () { locus ? p.flipper.moveTo(locus, cb) : cb; });
- }
-
-
- // Returns the current page number in the book.
- //
- // The pageDiv argument is optional - typically defaults to whatever the
- // flipper thinks is the "active" page.
- //
- function pageNumber(pageDiv) {
- var place = getPlace(pageDiv);
- return place ? (place.pageNumber() || 1) : 1;
- }
-
-
- // Returns the current "place" in the book -- ie, the page number, chapter
- // title, etc.
- //
- // The pageDiv argument is optional - typically defaults to whatever the
- // flipper thinks is the "active" page.
- //
- function getPlace(pageDiv) {
- if (!p.initialized) {
- console.warn('Attempt to access place before initialization.');
- }
- return p.flipper.getPlace(pageDiv);
- }
-
-
- // Moves the current page as specified by the locus. See
- // Monocle.Book#pageNumberAt for documentation on the locus argument.
- //
- // The callback argument is optional.
- //
- function moveTo(locus, callback) {
- if (!p.initialized) {
- console.warn('Attempt to move place before initialization.');
- }
- if (!p.book.isValidLocus(locus)) {
- dispatchEvent(
- "monocle:notfound",
- { href: locus ? locus.componentId : "anonymous" }
- );
- return false;
- }
- var fn = callback;
- if (!locus.direction) {
- dispatchEvent('monocle:jumping', { locus: locus });
- fn = function () {
- dispatchEvent('monocle:jump', { locus: locus });
- if (callback) { callback(); }
- }
- }
- p.flipper.moveTo(locus, fn);
- return true;
- }
-
-
- // Moves to the relevant element in the relevant component.
- //
- function skipToChapter(src) {
- var locus = p.book.locusOfChapter(src);
- return moveTo(locus);
- }
-
-
- // Valid types:
- // - standard (an overlay above the pages)
- // - page (within the page)
- // - modal (overlay where click-away does nothing, for a single control)
- // - hud (overlay that multiple controls can share)
- // - popover (overlay where click-away removes the ctrl elements)
- // - invisible
- //
- // Options:
- // - hidden -- creates and hides the ctrl elements;
- // use showControl to show them
- // - container -- specify an existing DOM element to contain the control.
- //
- function addControl(ctrl, cType, options) {
- for (var i = 0; i < p.controls.length; ++i) {
- if (p.controls[i].control == ctrl) {
- console.warn("Already added control: %o", ctrl);
- return;
- }
- }
-
- options = options || {};
-
- var ctrlData = { control: ctrl, elements: [], controlType: cType }
- p.controls.push(ctrlData);
-
- var addControlTo = function (cntr) {
- if (cntr == 'container') {
- cntr = options.container || dom.find('container');
- if (typeof cntr == 'string') { cntr = document.getElementById(cntr); }
- if (!cntr.dom) { dom.claim(cntr, 'controlContainer'); }
- } else if (cntr == 'overlay') {
- cntr = dom.find('overlay');
- }
- if (typeof ctrl.createControlElements != 'function') { return; }
- var ctrlElem = ctrl.createControlElements(cntr);
- if (!ctrlElem) { return; }
- cntr.appendChild(ctrlElem);
- ctrlData.elements.push(ctrlElem);
- Monocle.Styles.applyRules(ctrlElem, Monocle.Styles.control);
- return ctrlElem;
- }
-
- if (!cType || cType == 'standard' || cType == 'invisible') {
- addControlTo('container');
- } else if (cType == 'page') {
- forEachPage(addControlTo);
- } else if (cType == 'modal' || cType == 'popover' || cType == 'hud') {
- addControlTo('overlay');
- ctrlData.usesOverlay = true;
- } else if (cType == 'invisible') {
- addControlTo('container');
- } else {
- console.warn('Unknown control type: ' + cType);
- }
-
- if (options.hidden) {
- hideControl(ctrl);
- } else {
- showControl(ctrl);
- }
-
- if (typeof ctrl.assignToReader == 'function') {
- ctrl.assignToReader(API);
- }
-
- return ctrl;
- }
-
-
- function dataForControl(ctrl) {
- for (var i = 0; i < p.controls.length; ++i) {
- if (p.controls[i].control == ctrl) {
- return p.controls[i];
- }
- }
- }
-
-
- function hideControl(ctrl) {
- var controlData = dataForControl(ctrl);
- if (!controlData) {
- console.warn("No data for control: " + ctrl);
- return;
- }
- if (controlData.hidden) {
- return;
- }
- for (var i = 0; i < controlData.elements.length; ++i) {
- controlData.elements[i].style.display = "none";
- }
- if (controlData.usesOverlay) {
- var overlay = dom.find('overlay');
- overlay.style.display = "none";
- Monocle.Events.deafenForContact(overlay, overlay.listeners);
- if (controlData.controlType != 'hud') {
- dispatchEvent('monocle:modal:off');
- }
- }
- controlData.hidden = true;
- if (ctrl.properties) {
- ctrl.properties.hidden = true;
- }
- dispatchEvent('monocle:controlhide', { control: ctrl }, false);
- }
-
-
- function showControl(ctrl) {
- var controlData = dataForControl(ctrl);
- if (!controlData) {
- console.warn("No data for control: " + ctrl);
- return false;
- }
-
- if (showingControl(ctrl)) {
- return false;
- }
-
- var overlay = dom.find('overlay');
- if (controlData.usesOverlay && controlData.controlType != "hud") {
- for (var i = 0, ii = p.controls.length; i < ii; ++i) {
- if (p.controls[i].usesOverlay && !p.controls[i].hidden) {
- return false;
- }
- }
- overlay.style.display = "block";
- dispatchEvent('monocle:modal:on');
- }
-
- for (var i = 0; i < controlData.elements.length; ++i) {
- controlData.elements[i].style.display = "block";
- }
-
- if (controlData.controlType == "popover") {
- var onControl = function (evt) {
- var obj = evt.target;
- do {
- if (obj == controlData.elements[0]) { return true; }
- } while (obj && (obj = obj.parentNode));
- return false;
- }
- overlay.listeners = Monocle.Events.listenForContact(
- overlay,
- {
- start: function (evt) { if (!onControl(evt)) { hideControl(ctrl); } },
- move: function (evt) { if (!onControl(evt)) { evt.preventDefault(); } }
- }
- );
- }
- controlData.hidden = false;
- if (ctrl.properties) {
- ctrl.properties.hidden = false;
- }
- dispatchEvent('monocle:controlshow', { control: ctrl }, false);
- return true;
- }
-
-
- function showingControl(ctrl) {
- var controlData = dataForControl(ctrl);
- return controlData.hidden == false;
- }
-
-
- function dispatchEvent(evtType, data, cancelable) {
- return Monocle.Events.dispatch(dom.find('box'), evtType, data, cancelable);
- }
-
-
- function listen(evtType, fn, useCapture) {
- Monocle.Events.listen(dom.find('box'), evtType, fn, useCapture);
- }
-
-
- function deafen(evtType, fn) {
- Monocle.Events.deafen(dom.find('box'), evtType, fn);
- }
-
-
- function visiblePages() {
- return p.flipper.visiblePages ?
- p.flipper.visiblePages() :
- [dom.find('page')];
- }
-
-
- function forEachPage(callback) {
- for (var i = 0, ii = p.flipper.pageCount; i < ii; ++i) {
- var page = dom.find('page', i);
- callback(page, i);
- }
- }
-
-
- /* The Reader PageStyles API is deprecated - it has moved to Formatting */
-
- function addPageStyles(styleRules, restorePlace) {
- console.deprecation("Use reader.formatting.addPageStyles instead.");
- return API.formatting.addPageStyles(styleRules, restorePlace);
- }
-
-
- function updatePageStyles(sheetIndex, styleRules, restorePlace) {
- console.deprecation("Use reader.formatting.updatePageStyles instead.");
- return API.formatting.updatePageStyles(sheetIndex, styleRules, restorePlace);
- }
-
-
- function removePageStyles(sheetIndex, restorePlace) {
- console.deprecation("Use reader.formatting.removePageStyles instead.");
- return API.formatting.removePageStyles(sheetIndex, restorePlace);
- }
-
-
- function fatalSystemMessage(msg) {
- var info = dom.make('div', 'book_fatality', { html: msg });
- var box = dom.find('box');
- var bbOrigin = [box.offsetWidth / 2, box.offsetHeight / 2];
- API.billboard.show(info, { closeButton: false, from: bbOrigin });
- }
-
-
- API.getBook = getBook;
- API.getPlace = getPlace;
- API.moveTo = moveTo;
- API.skipToChapter = skipToChapter;
- API.resized = resized;
- API.recalculateDimensions = recalculateDimensions;
- API.addControl = addControl;
- API.hideControl = hideControl;
- API.showControl = showControl;
- API.showingControl = showingControl;
- API.dispatchEvent = dispatchEvent;
- API.listen = listen;
- API.deafen = deafen;
- API.visiblePages = visiblePages;
-
- // Deprecated!
- API.addPageStyles = addPageStyles;
- API.updatePageStyles = updatePageStyles;
- API.removePageStyles = removePageStyles;
-
- initialize();
-
- return API;
-}
-
-
-Monocle.Reader.RESIZE_DELAY = Monocle.Browser.renders.slow ? 500 : 100;
-Monocle.Reader.DEFAULT_SYSTEM_ID = 'RS:monocle'
-Monocle.Reader.DEFAULT_CLASS_PREFIX = 'monelem_'
-Monocle.Reader.DEFAULT_STYLE_RULES = Monocle.Formatting.DEFAULT_STYLE_RULES;
-Monocle.Reader.COMPATIBILITY_INFO =
- "
Incompatible browser
"+
- "
Unfortunately, your browser isn't able to display this book. "+
- "If possible, try again in another browser or on another device.
";
-Monocle.Reader.LOAD_FAILURE_INFO =
- "
Book could not be loaded
"+
- "
Sorry, parts of the book could not be retrieved. "+
- "Please check your connection and refresh to try again.