aboutsummaryrefslogtreecommitdiffstats
path: root/library
diff options
context:
space:
mode:
Diffstat (limited to 'library')
-rw-r--r--library/fullcalendar/GPL-LICENSE.txt278
-rw-r--r--library/fullcalendar/MIT-LICENSE.txt20
-rw-r--r--library/fullcalendar/changelog.txt318
-rw-r--r--library/fullcalendar/fullcalendar.css618
-rw-r--r--library/fullcalendar/fullcalendar.js5224
-rw-r--r--library/fullcalendar/fullcalendar.min.js114
-rw-r--r--library/fullcalendar/fullcalendar.print.css61
-rw-r--r--library/fullcalendar/gcal.js112
-rwxr-xr-xlibrary/slinky.php32
-rw-r--r--library/spam/README12
-rw-r--r--library/spam/b8/b8.php503
-rw-r--r--library/spam/b8/b8.php.ORIG503
-rw-r--r--library/spam/b8/degenerator/degenerator_default.php127
-rw-r--r--library/spam/b8/lexer/lexer_default.php205
-rw-r--r--library/spam/b8/storage/storage_base.php396
-rw-r--r--library/spam/b8/storage/storage_base.php.ORIG395
-rw-r--r--library/spam/b8/storage/storage_dba.php198
-rw-r--r--library/spam/b8/storage/storage_frndc.php344
-rw-r--r--library/spam/b8/storage/storage_mysql.php351
-rw-r--r--library/spam/doc/COPYING504
-rw-r--r--library/spam/doc/ChangeLog179
-rw-r--r--library/spam/doc/readme.htm707
-rw-r--r--library/spam/doc/readme.rst371
-rw-r--r--library/spam/example/index.php241
-rw-r--r--library/spam/install/setup_berkeleydb.php240
-rw-r--r--library/spam/install/setup_mysql.sql27
-rwxr-xr-xlibrary/tinymce/jscripts/tiny_mce/plugins/bbcode/editor_plugin_src.js2
27 files changed, 12081 insertions, 1 deletions
diff --git a/library/fullcalendar/GPL-LICENSE.txt b/library/fullcalendar/GPL-LICENSE.txt
new file mode 100644
index 000000000..11dddd00e
--- /dev/null
+++ b/library/fullcalendar/GPL-LICENSE.txt
@@ -0,0 +1,278 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
diff --git a/library/fullcalendar/MIT-LICENSE.txt b/library/fullcalendar/MIT-LICENSE.txt
new file mode 100644
index 000000000..46d475449
--- /dev/null
+++ b/library/fullcalendar/MIT-LICENSE.txt
@@ -0,0 +1,20 @@
+Copyright (c) 2009 Adam Shaw
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/library/fullcalendar/changelog.txt b/library/fullcalendar/changelog.txt
new file mode 100644
index 000000000..17b31f862
--- /dev/null
+++ b/library/fullcalendar/changelog.txt
@@ -0,0 +1,318 @@
+
+version 1.5.3 (2/6/12)
+ - fixed dragging issue with jQuery UI 1.8.16 (issue 1168)
+ - bundled with jQuery 1.7.1 and jQuery UI 1.8.17
+
+version 1.5.2 (8/21/11)
+ - correctly process UTC "Z" ISO8601 date strings (issue 750)
+
+version 1.5.1 (4/9/11)
+ - more flexible ISO8601 date parsing (issue 814)
+ - more flexible parsing of UNIX timestamps (issue 826)
+ - FullCalendar now buildable from source on a Mac (issue 795)
+ - FullCalendar QA'd in FF4 (issue 883)
+ - upgraded to jQuery 1.5.2 (which supports IE9) and jQuery UI 1.8.11
+
+version 1.5 (3/19/11)
+ - slicker default styling for buttons
+ - reworked a lot of the calendar's HTML and accompanying CSS
+ (solves issues 327 and 395)
+ - more printer-friendly (fullcalendar-print.css)
+ - fullcalendar now inherits styles from jquery-ui themes differently.
+ styles for buttons are distinct from styles for calendar cells.
+ (solves issue 299)
+ - can now color events through FullCalendar options and Event-Object properties (issue 117)
+ THIS IS NOW THE PREFERRED METHOD OF COLORING EVENTS (as opposed to using className and CSS)
+ - FullCalendar options:
+ - eventColor (changes both background and border)
+ - eventBackgroundColor
+ - eventBorderColor
+ - eventTextColor
+ - Event-Object options:
+ - color (changes both background and border)
+ - backgroundColor
+ - borderColor
+ - textColor
+ - can now specify an event source as an *object* with a `url` property (json feed) or
+ an `events` property (function or array) with additional properties that will
+ be applied to the entire event source:
+ - color (changes both background and border)
+ - backgroudColor
+ - borderColor
+ - textColor
+ - className
+ - editable
+ - allDayDefault
+ - ignoreTimezone
+ - startParam (for a feed)
+ - endParam (for a feed)
+ - ANY OF THE JQUERY $.ajax OPTIONS
+ allows for easily changing from GET to POST and sending additional parameters (issue 386)
+ allows for easily attaching ajax handlers such as `error` (issue 754)
+ allows for turning caching on (issue 355)
+ - Google Calendar feeds are now specified differently:
+ - specify a simple string of your feed's URL
+ - specify an *object* with a `url` property of your feed's URL.
+ you can include any of the new Event-Source options in this object.
+ - the old `$.fullCalendar.gcalFeed` method still works
+ - no more IE7 SSL popup (issue 504)
+ - remove `cacheParam` - use json event source `cache` option instead
+ - latest jquery/jquery-ui
+
+version 1.4.11 (2/22/11)
+ - fixed rerenderEvents bug (issue 790)
+ - fixed bug with faulty dragging of events from all-day slot in agenda views
+ - bundled with jquery 1.5 and jquery-ui 1.8.9
+
+version 1.4.10 (1/2/11)
+ - fixed bug with resizing event to different week in 5-day month view (issue 740)
+ - fixed bug with events not sticking after a removeEvents call (issue 757)
+ - fixed bug with underlying parseTime method, and other uses of parseInt (issue 688)
+
+version 1.4.9 (11/16/10)
+ - new algorithm for vertically stacking events (issue 111)
+ - resizing an event to a different week (issue 306)
+ - bug: some events not rendered with consecutive calls to addEventSource (issue 679)
+
+version 1.4.8 (10/16/10)
+ - ignoreTimezone option (set to `false` to process UTC offsets in ISO8601 dates)
+ - bugfixes
+ - event refetching not being called under certain conditions (issues 417, 554)
+ - event refetching being called multiple times under certain conditions (issues 586, 616)
+ - selection cannot be triggered by right mouse button (issue 558)
+ - agenda view left axis sized incorrectly (issue 465)
+ - IE js error when calendar is too narrow (issue 517)
+ - agenda view looks strange when no scrollbars (issue 235)
+ - improved parsing of ISO8601 dates with UTC offsets
+ - $.fullCalendar.version
+ - an internal refactor of the code, for easier future development and modularity
+
+version 1.4.7 (7/5/10)
+ - "dropping" external objects onto the calendar
+ - droppable (boolean, to turn on/off)
+ - dropAccept (to filter which events the calendar will accept)
+ - drop (trigger)
+ - selectable options can now be specified with a View Option Hash
+ - bugfixes
+ - dragged & reverted events having wrong time text (issue 406)
+ - bug rendering events that have an endtime with seconds, but no hours/minutes (issue 477)
+ - gotoDate date overflow bug (issue 429)
+ - wrong date reported when clicking on edge of last column in agenda views (412)
+ - support newlines in event titles
+ - select/unselect callbacks now passes native js event
+
+version 1.4.6 (5/31/10)
+ - "selecting" days or timeslots
+ - options: selectable, selectHelper, unselectAuto, unselectCancel
+ - callbacks: select, unselect
+ - methods: select, unselect
+ - when dragging an event, the highlighting reflects the duration of the event
+ - code compressing by Google Closure Compiler
+ - bundled with jQuery 1.4.2 and jQuery UI 1.8.1
+
+version 1.4.5 (2/21/10)
+ - lazyFetching option, which can force the calendar to fetch events on every view/date change
+ - scroll state of agenda views are preserved when switching back to view
+ - bugfixes
+ - calling methods on an uninitialized fullcalendar throws error
+ - IE6/7 bug where an entire view becomes invisible (issue 320)
+ - error when rendering a hidden calendar (in jquery ui tabs for example) in IE (issue 340)
+ - interconnected bugs related to calendar resizing and scrollbars
+ - when switching views or clicking prev/next, calendar would "blink" (issue 333)
+ - liquid-width calendar's events shifted (depending on initial height of browser) (issue 341)
+ - more robust underlying algorithm for calendar resizing
+
+version 1.4.4 (2/3/10)
+ - optimized event rendering in all views (events render in 1/10 the time)
+ - gotoDate() does not force the calendar to unnecessarily rerender
+ - render() method now correctly readjusts height
+
+version 1.4.3 (12/22/09)
+ - added destroy method
+ - Google Calendar event pages respect currentTimezone
+ - caching now handled by jQuery's ajax
+ - protection from setting aspectRatio to zero
+ - bugfixes
+ - parseISO8601 and DST caused certain events to display day before
+ - button positioning problem in IE6
+ - ajax event source removed after recently being added, events still displayed
+ - event not displayed when end is an empty string
+ - dynamically setting calendar height when no events have been fetched, throws error
+
+version 1.4.2 (12/02/09)
+ - eventAfterRender trigger
+ - getDate & getView methods
+ - height & contentHeight options (explicitly sets the pixel height)
+ - minTime & maxTime options (restricts shown hours in agenda view)
+ - getters [for all options] and setters [for height, contentHeight, and aspectRatio ONLY! stay tuned..]
+ - render method now readjusts calendar's size
+ - bugfixes
+ - lightbox scripts that use iframes (like fancybox)
+ - day-of-week classNames were off when firstDay=1
+ - guaranteed space on right side of agenda events (even when stacked)
+ - accepts ISO8601 dates with a space (instead of 'T')
+
+version 1.4.1 (10/31/09)
+ - can exclude weekends with new 'weekends' option
+ - gcal feed 'currentTimezone' option
+ - bugfixes
+ - year/month/date option sometimes wouldn't set correctly (depending on current date)
+ - daylight savings issue caused agenda views to start at 1am (for BST users)
+ - cleanup of gcal.js code
+
+version 1.4 (10/19/09)
+ - agendaWeek and agendaDay views
+ - added some options for agenda views:
+ - allDaySlot
+ - allDayText
+ - firstHour
+ - slotMinutes
+ - defaultEventMinutes
+ - axisFormat
+ - modified some existing options/triggers to work with agenda views:
+ - dragOpacity and timeFormat can now accept a "View Hash" (a new concept)
+ - dayClick now has an allDay parameter
+ - eventDrop now has an an allDay parameter
+ (this will affect those who use revertFunc, adjust parameter list)
+ - added 'prevYear' and 'nextYear' for buttons in header
+ - minor change for theme users, ui-state-hover not applied to active/inactive buttons
+ - added event-color-changing example in docs
+ - better defaults for right-to-left themed button icons
+
+version 1.3.2 (10/13/09)
+ - Bugfixes (please upgrade from 1.3.1!)
+ - squashed potential infinite loop when addMonths and addDays
+ is called with an invalid date
+ - $.fullCalendar.parseDate() now correctly parses IETF format
+ - when switching views, the 'today' button sticks inactive, fixed
+ - gotoDate now can accept a single Date argument
+ - documentation for changes in 1.3.1 and 1.3.2 now on website
+
+version 1.3.1 (9/30/09)
+ - Important Bugfixes (please upgrade from 1.3!)
+ - When current date was late in the month, for long months, and prev/next buttons
+ were clicked in month-view, some months would be skipped/repeated
+ - In certain time zones, daylight savings time would cause certain days
+ to be misnumbered in month-view
+ - Subtle change in way week interval is chosen when switching from month to basicWeek/basicDay view
+ - Added 'allDayDefault' option
+ - Added 'changeView' and 'render' methods
+
+version 1.3 (9/21/09)
+ - different 'views': month/basicWeek/basicDay
+ - more flexible 'header' system for buttons
+ - themable by jQuery UI themes
+ - resizable events (require jQuery UI resizable plugin)
+ - rescoped & rewritten CSS, enhanced default look
+ - cleaner css & rendering techniques for right-to-left
+ - reworked options & API to support multiple views / be consistent with jQuery UI
+ - refactoring of entire codebase
+ - broken into different JS & CSS files, assembled w/ build scripts
+ - new test suite for new features, uses firebug-lite
+ - refactored docs
+ - Options
+ + date
+ + defaultView
+ + aspectRatio
+ + disableResizing
+ + monthNames (use instead of $.fullCalendar.monthNames)
+ + monthNamesShort (use instead of $.fullCalendar.monthAbbrevs)
+ + dayNames (use instead of $.fullCalendar.dayNames)
+ + dayNamesShort (use instead of $.fullCalendar.dayAbbrevs)
+ + theme
+ + buttonText
+ + buttonIcons
+ x draggable -> editable/disableDragging
+ x fixedWeeks -> weekMode
+ x abbrevDayHeadings -> columnFormat
+ x buttons/title -> header
+ x eventDragOpacity -> dragOpacity
+ x eventRevertDuration -> dragRevertDuration
+ x weekStart -> firstDay
+ x rightToLeft -> isRTL
+ x showTime (use 'allDay' CalEvent property instead)
+ - Triggered Actions
+ + eventResizeStart
+ + eventResizeStop
+ + eventResize
+ x monthDisplay -> viewDisplay
+ x resize -> windowResize
+ 'eventDrop' params changed, can revert if ajax cuts out
+ - CalEvent Properties
+ x showTime -> allDay
+ x draggable -> editable
+ 'end' is now INCLUSIVE when allDay=true
+ 'url' now produces a real <a> tag, more native clicking/tab behavior
+ - Methods:
+ + renderEvent
+ x prevMonth -> prev
+ x nextMonth -> next
+ x prevYear/nextYear -> moveDate
+ x refresh -> rerenderEvents/refetchEvents
+ x removeEvent -> removeEvents
+ x getEventsByID -> clientEvents
+ - Utilities:
+ 'formatDate' format string completely changed (inspired by jQuery UI datepicker + datejs)
+ 'formatDates' added to support date-ranges
+ - Google Calendar Options:
+ x draggable -> editable
+ - Bugfixes
+ - gcal extension fetched 25 results max, now fetches all
+
+version 1.2.1 (6/29/09)
+ - bugfixes
+ - allows and corrects invalid end dates for events
+ - doesn't throw an error in IE while rendering when display:none
+ - fixed 'loading' callback when used w/ multiple addEventSource calls
+ - gcal className can now be an array
+
+version 1.2 (5/31/09)
+ - expanded API
+ - 'className' CalEvent attribute
+ - 'source' CalEvent attribute
+ - dynamically get/add/remove/update events of current month
+ - locale improvements: change month/day name text
+ - better date formatting ($.fullCalendar.formatDate)
+ - multiple 'event sources' allowed
+ - dynamically add/remove event sources
+ - options for prevYear and nextYear buttons
+ - docs have been reworked (include addition of Google Calendar docs)
+ - changed behavior of parseDate for number strings
+ (now interpets as unix timestamp, not MS times)
+ - bugfixes
+ - rightToLeft month start bug
+ - off-by-one errors with month formatting commands
+ - events from previous months sticking when clicking prev/next quickly
+ - Google Calendar API changed to work w/ multiple event sources
+ - can also provide 'className' and 'draggable' options
+ - date utilties moved from $ to $.fullCalendar
+ - more documentation in source code
+ - minified version of fullcalendar.js
+ - test suit (available from svn)
+ - top buttons now use <button> w/ an inner <span> for better css cusomization
+ - thus CSS has changed. IF UPGRADING FROM PREVIOUS VERSIONS,
+ UPGRADE YOUR FULLCALENDAR.CSS FILE!!!
+
+version 1.1 (5/10/09)
+ - Added the following options:
+ - weekStart
+ - rightToLeft
+ - titleFormat
+ - timeFormat
+ - cacheParam
+ - resize
+ - Fixed rendering bugs
+ - Opera 9.25 (events placement & window resizing)
+ - IE6 (window resizing)
+ - Optimized window resizing for ALL browsers
+ - Events on same day now sorted by start time (but first by timespan)
+ - Correct z-index when dragging
+ - Dragging contained in overflow DIV for IE6
+ - Modified fullcalendar.css
+ - for right-to-left support
+ - for variable start-of-week
+ - for IE6 resizing bug
+ - for THEAD and TBODY (in 1.0, just used TBODY, restructured in 1.1)
+ - IF UPGRADING FROM FULLCALENDAR 1.0, YOU MUST UPGRADE FULLCALENDAR.CSS
+ !!!!!!!!!!!
+
diff --git a/library/fullcalendar/fullcalendar.css b/library/fullcalendar/fullcalendar.css
new file mode 100644
index 000000000..04f118493
--- /dev/null
+++ b/library/fullcalendar/fullcalendar.css
@@ -0,0 +1,618 @@
+/*
+ * FullCalendar v1.5.3 Stylesheet
+ *
+ * Copyright (c) 2011 Adam Shaw
+ * Dual licensed under the MIT and GPL licenses, located in
+ * MIT-LICENSE.txt and GPL-LICENSE.txt respectively.
+ *
+ * Date: Mon Feb 6 22:40:40 2012 -0800
+ *
+ */
+
+
+.fc {
+ direction: ltr;
+ text-align: left;
+ }
+
+.fc table {
+ border-collapse: collapse;
+ border-spacing: 0;
+ }
+
+html .fc,
+.fc table {
+ font-size: 1em;
+ }
+
+.fc td,
+.fc th {
+ padding: 0;
+ vertical-align: top;
+ }
+
+
+
+/* Header
+------------------------------------------------------------------------*/
+
+.fc-header td {
+ white-space: nowrap;
+ }
+
+.fc-header-left {
+ width: 25%;
+ text-align: left;
+ }
+
+.fc-header-center {
+ text-align: center;
+ }
+
+.fc-header-right {
+ width: 25%;
+ text-align: right;
+ }
+
+.fc-header-title {
+ display: inline-block;
+ vertical-align: top;
+ }
+
+.fc-header-title h2 {
+ margin-top: 0;
+ white-space: nowrap;
+ }
+
+.fc .fc-header-space {
+ padding-left: 10px;
+ }
+
+.fc-header .fc-button {
+ margin-bottom: 1em;
+ vertical-align: top;
+ }
+
+/* buttons edges butting together */
+
+.fc-header .fc-button {
+ margin-right: -1px;
+ }
+
+.fc-header .fc-corner-right {
+ margin-right: 1px; /* back to normal */
+ }
+
+.fc-header .ui-corner-right {
+ margin-right: 0; /* back to normal */
+ }
+
+/* button layering (for border precedence) */
+
+.fc-header .fc-state-hover,
+.fc-header .ui-state-hover {
+ z-index: 2;
+ }
+
+.fc-header .fc-state-down {
+ z-index: 3;
+ }
+
+.fc-header .fc-state-active,
+.fc-header .ui-state-active {
+ z-index: 4;
+ }
+
+
+
+/* Content
+------------------------------------------------------------------------*/
+
+.fc-content {
+ clear: both;
+ }
+
+.fc-view {
+ width: 100%; /* needed for view switching (when view is absolute) */
+ overflow: hidden;
+ }
+
+
+
+/* Cell Styles
+------------------------------------------------------------------------*/
+
+.fc-widget-header, /* <th>, usually */
+.fc-widget-content { /* <td>, usually */
+ border: 1px solid #ccc;
+ }
+
+.fc-state-highlight { /* <td> today cell */ /* TODO: add .fc-today to <th> */
+ background: #ffc;
+ }
+
+.fc-cell-overlay { /* semi-transparent rectangle while dragging */
+ background: #9cf;
+ opacity: .2;
+ filter: alpha(opacity=20); /* for IE */
+ }
+
+
+
+/* Buttons
+------------------------------------------------------------------------*/
+
+.fc-button {
+ position: relative;
+ display: inline-block;
+ cursor: pointer;
+ }
+
+.fc-state-default { /* non-theme */
+ border-style: solid;
+ border-width: 1px 0;
+ }
+
+.fc-button-inner {
+ position: relative;
+ float: left;
+ overflow: hidden;
+ }
+
+.fc-state-default .fc-button-inner { /* non-theme */
+ border-style: solid;
+ border-width: 0 1px;
+ }
+
+.fc-button-content {
+ position: relative;
+ float: left;
+ height: 1.9em;
+ line-height: 1.9em;
+ padding: 0 .6em;
+ white-space: nowrap;
+ }
+
+/* icon (for jquery ui) */
+
+.fc-button-content .fc-icon-wrap {
+ position: relative;
+ float: left;
+ top: 50%;
+ }
+
+.fc-button-content .ui-icon {
+ position: relative;
+ float: left;
+ margin-top: -50%;
+ *margin-top: 0;
+ *top: -50%;
+ }
+
+/* gloss effect */
+
+.fc-state-default .fc-button-effect {
+ position: absolute;
+ top: 50%;
+ left: 0;
+ }
+
+.fc-state-default .fc-button-effect span {
+ position: absolute;
+ top: -100px;
+ left: 0;
+ width: 500px;
+ height: 100px;
+ border-width: 100px 0 0 1px;
+ border-style: solid;
+ border-color: #fff;
+ background: #444;
+ opacity: .09;
+ filter: alpha(opacity=9);
+ }
+
+/* button states (determines colors) */
+
+.fc-state-default,
+.fc-state-default .fc-button-inner {
+ border-style: solid;
+ border-color: #ccc #bbb #aaa;
+ background: #F3F3F3;
+ color: #000;
+ }
+
+.fc-state-hover,
+.fc-state-hover .fc-button-inner {
+ border-color: #999;
+ }
+
+.fc-state-down,
+.fc-state-down .fc-button-inner {
+ border-color: #555;
+ background: #777;
+ }
+
+.fc-state-active,
+.fc-state-active .fc-button-inner {
+ border-color: #555;
+ background: #777;
+ color: #fff;
+ }
+
+.fc-state-disabled,
+.fc-state-disabled .fc-button-inner {
+ color: #999;
+ border-color: #ddd;
+ }
+
+.fc-state-disabled {
+ cursor: default;
+ }
+
+.fc-state-disabled .fc-button-effect {
+ display: none;
+ }
+
+
+
+/* Global Event Styles
+------------------------------------------------------------------------*/
+
+.fc-event {
+ border-style: solid;
+ border-width: 0;
+ font-size: .85em;
+ cursor: default;
+ }
+
+a.fc-event,
+.fc-event-draggable {
+ cursor: pointer;
+ }
+
+a.fc-event {
+ text-decoration: none;
+ }
+
+.fc-rtl .fc-event {
+ text-align: right;
+ }
+
+.fc-event-skin {
+ border-color: #36c; /* default BORDER color */
+ background-color: #36c; /* default BACKGROUND color */
+ color: #fff; /* default TEXT color */
+ }
+
+.fc-event-inner {
+ position: relative;
+ width: 100%;
+ height: 100%;
+ border-style: solid;
+ border-width: 0;
+ overflow: hidden;
+ }
+
+.fc-event-time,
+.fc-event-title {
+ padding: 0 1px;
+ }
+
+.fc .ui-resizable-handle { /*** TODO: don't use ui-resizable anymore, change class ***/
+ display: block;
+ position: absolute;
+ z-index: 99999;
+ overflow: hidden; /* hacky spaces (IE6/7) */
+ font-size: 300%; /* */
+ line-height: 50%; /* */
+ }
+
+
+
+/* Horizontal Events
+------------------------------------------------------------------------*/
+
+.fc-event-hori {
+ border-width: 1px 0;
+ margin-bottom: 1px;
+ }
+
+/* resizable */
+
+.fc-event-hori .ui-resizable-e {
+ top: 0 !important; /* importants override pre jquery ui 1.7 styles */
+ right: -3px !important;
+ width: 7px !important;
+ height: 100% !important;
+ cursor: e-resize;
+ }
+
+.fc-event-hori .ui-resizable-w {
+ top: 0 !important;
+ left: -3px !important;
+ width: 7px !important;
+ height: 100% !important;
+ cursor: w-resize;
+ }
+
+.fc-event-hori .ui-resizable-handle {
+ _padding-bottom: 14px; /* IE6 had 0 height */
+ }
+
+
+
+/* Fake Rounded Corners (for buttons and events)
+------------------------------------------------------------*/
+
+.fc-corner-left {
+ margin-left: 1px;
+ }
+
+.fc-corner-left .fc-button-inner,
+.fc-corner-left .fc-event-inner {
+ margin-left: -1px;
+ }
+
+.fc-corner-right {
+ margin-right: 1px;
+ }
+
+.fc-corner-right .fc-button-inner,
+.fc-corner-right .fc-event-inner {
+ margin-right: -1px;
+ }
+
+.fc-corner-top {
+ margin-top: 1px;
+ }
+
+.fc-corner-top .fc-event-inner {
+ margin-top: -1px;
+ }
+
+.fc-corner-bottom {
+ margin-bottom: 1px;
+ }
+
+.fc-corner-bottom .fc-event-inner {
+ margin-bottom: -1px;
+ }
+
+
+
+/* Fake Rounded Corners SPECIFICALLY FOR EVENTS
+-----------------------------------------------------------------*/
+
+.fc-corner-left .fc-event-inner {
+ border-left-width: 1px;
+ }
+
+.fc-corner-right .fc-event-inner {
+ border-right-width: 1px;
+ }
+
+.fc-corner-top .fc-event-inner {
+ border-top-width: 1px;
+ }
+
+.fc-corner-bottom .fc-event-inner {
+ border-bottom-width: 1px;
+ }
+
+
+
+/* Reusable Separate-border Table
+------------------------------------------------------------*/
+
+table.fc-border-separate {
+ border-collapse: separate;
+ }
+
+.fc-border-separate th,
+.fc-border-separate td {
+ border-width: 1px 0 0 1px;
+ }
+
+.fc-border-separate th.fc-last,
+.fc-border-separate td.fc-last {
+ border-right-width: 1px;
+ }
+
+.fc-border-separate tr.fc-last th,
+.fc-border-separate tr.fc-last td {
+ border-bottom-width: 1px;
+ }
+
+.fc-border-separate tbody tr.fc-first td,
+.fc-border-separate tbody tr.fc-first th {
+ border-top-width: 0;
+ }
+
+
+
+/* Month View, Basic Week View, Basic Day View
+------------------------------------------------------------------------*/
+
+.fc-grid th {
+ text-align: center;
+ }
+
+.fc-grid .fc-day-number {
+ float: right;
+ padding: 0 2px;
+ }
+
+.fc-grid .fc-other-month .fc-day-number {
+ opacity: 0.3;
+ filter: alpha(opacity=30); /* for IE */
+ /* opacity with small font can sometimes look too faded
+ might want to set the 'color' property instead
+ making day-numbers bold also fixes the problem */
+ }
+
+.fc-grid .fc-day-content {
+ clear: both;
+ padding: 2px 2px 1px; /* distance between events and day edges */
+ }
+
+/* event styles */
+
+.fc-grid .fc-event-time {
+ font-weight: bold;
+ }
+
+/* right-to-left */
+
+.fc-rtl .fc-grid .fc-day-number {
+ float: left;
+ }
+
+.fc-rtl .fc-grid .fc-event-time {
+ float: right;
+ }
+
+
+
+/* Agenda Week View, Agenda Day View
+------------------------------------------------------------------------*/
+
+.fc-agenda table {
+ border-collapse: separate;
+ }
+
+.fc-agenda-days th {
+ text-align: center;
+ }
+
+.fc-agenda .fc-agenda-axis {
+ width: 50px;
+ padding: 0 4px;
+ vertical-align: middle;
+ text-align: right;
+ white-space: nowrap;
+ font-weight: normal;
+ }
+
+.fc-agenda .fc-day-content {
+ padding: 2px 2px 1px;
+ }
+
+/* make axis border take precedence */
+
+.fc-agenda-days .fc-agenda-axis {
+ border-right-width: 1px;
+ }
+
+.fc-agenda-days .fc-col0 {
+ border-left-width: 0;
+ }
+
+/* all-day area */
+
+.fc-agenda-allday th {
+ border-width: 0 1px;
+ }
+
+.fc-agenda-allday .fc-day-content {
+ min-height: 34px; /* TODO: doesnt work well in quirksmode */
+ _height: 34px;
+ }
+
+/* divider (between all-day and slots) */
+
+.fc-agenda-divider-inner {
+ height: 2px;
+ overflow: hidden;
+ }
+
+.fc-widget-header .fc-agenda-divider-inner {
+ background: #eee;
+ }
+
+/* slot rows */
+
+.fc-agenda-slots th {
+ border-width: 1px 1px 0;
+ }
+
+.fc-agenda-slots td {
+ border-width: 1px 0 0;
+ background: none;
+ }
+
+.fc-agenda-slots td div {
+ height: 20px;
+ }
+
+.fc-agenda-slots tr.fc-slot0 th,
+.fc-agenda-slots tr.fc-slot0 td {
+ border-top-width: 0;
+ }
+
+.fc-agenda-slots tr.fc-minor th,
+.fc-agenda-slots tr.fc-minor td {
+ border-top-style: dotted;
+ }
+
+.fc-agenda-slots tr.fc-minor th.ui-widget-header {
+ *border-top-style: solid; /* doesn't work with background in IE6/7 */
+ }
+
+
+
+/* Vertical Events
+------------------------------------------------------------------------*/
+
+.fc-event-vert {
+ border-width: 0 1px;
+ }
+
+.fc-event-vert .fc-event-head,
+.fc-event-vert .fc-event-content {
+ position: relative;
+ z-index: 2;
+ width: 100%;
+ overflow: hidden;
+ }
+
+.fc-event-vert .fc-event-time {
+ white-space: nowrap;
+ font-size: 10px;
+ }
+
+.fc-event-vert .fc-event-bg { /* makes the event lighter w/ a semi-transparent overlay */
+ position: absolute;
+ z-index: 1;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ background: #fff;
+ opacity: .3;
+ filter: alpha(opacity=30);
+ }
+
+.fc .ui-draggable-dragging .fc-event-bg, /* TODO: something nicer like .fc-opacity */
+.fc-select-helper .fc-event-bg {
+ display: none\9; /* for IE6/7/8. nested opacity filters while dragging don't work */
+ }
+
+/* resizable */
+
+.fc-event-vert .ui-resizable-s {
+ bottom: 0 !important; /* importants override pre jquery ui 1.7 styles */
+ width: 100% !important;
+ height: 8px !important;
+ overflow: hidden !important;
+ line-height: 8px !important;
+ font-size: 11px !important;
+ font-family: monospace;
+ text-align: center;
+ cursor: s-resize;
+ }
+
+.fc-agenda .ui-resizable-resizing { /* TODO: better selector */
+ _overflow: hidden;
+ }
+
+
diff --git a/library/fullcalendar/fullcalendar.js b/library/fullcalendar/fullcalendar.js
new file mode 100644
index 000000000..779a313c7
--- /dev/null
+++ b/library/fullcalendar/fullcalendar.js
@@ -0,0 +1,5224 @@
+/**
+ * @preserve
+ * FullCalendar v1.5.3
+ * http://arshaw.com/fullcalendar/
+ *
+ * Use fullcalendar.css for basic styling.
+ * For event drag & drop, requires jQuery UI draggable.
+ * For event resizing, requires jQuery UI resizable.
+ *
+ * Copyright (c) 2011 Adam Shaw
+ * Dual licensed under the MIT and GPL licenses, located in
+ * MIT-LICENSE.txt and GPL-LICENSE.txt respectively.
+ *
+ * Date: Mon Feb 6 22:40:40 2012 -0800
+ *
+ */
+
+(function($, undefined) {
+
+
+var defaults = {
+
+ // display
+ defaultView: 'month',
+ aspectRatio: 1.35,
+ header: {
+ left: 'title',
+ center: '',
+ right: 'today prev,next'
+ },
+ weekends: true,
+
+ // editing
+ //editable: false,
+ //disableDragging: false,
+ //disableResizing: false,
+
+ allDayDefault: true,
+ ignoreTimezone: true,
+
+ // event ajax
+ lazyFetching: true,
+ startParam: 'start',
+ endParam: 'end',
+
+ // time formats
+ titleFormat: {
+ month: 'MMMM yyyy',
+ week: "MMM d[ yyyy]{ '&#8212;'[ MMM] d yyyy}",
+ day: 'dddd, MMM d, yyyy'
+ },
+ columnFormat: {
+ month: 'ddd',
+ week: 'ddd M/d',
+ day: 'dddd M/d'
+ },
+ timeFormat: { // for event elements
+ '': 'h(:mm)t' // default
+ },
+
+ // locale
+ isRTL: false,
+ firstDay: 0,
+ monthNames: ['January','February','March','April','May','June','July','August','September','October','November','December'],
+ monthNamesShort: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
+ dayNames: ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
+ dayNamesShort: ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],
+ buttonText: {
+ prev: '&nbsp;&#9668;&nbsp;',
+ next: '&nbsp;&#9658;&nbsp;',
+ prevYear: '&nbsp;&lt;&lt;&nbsp;',
+ nextYear: '&nbsp;&gt;&gt;&nbsp;',
+ today: 'today',
+ month: 'month',
+ week: 'week',
+ day: 'day'
+ },
+
+ // jquery-ui theming
+ theme: false,
+ buttonIcons: {
+ prev: 'circle-triangle-w',
+ next: 'circle-triangle-e'
+ },
+
+ //selectable: false,
+ unselectAuto: true,
+
+ dropAccept: '*'
+
+};
+
+// right-to-left defaults
+var rtlDefaults = {
+ header: {
+ left: 'next,prev today',
+ center: '',
+ right: 'title'
+ },
+ buttonText: {
+ prev: '&nbsp;&#9658;&nbsp;',
+ next: '&nbsp;&#9668;&nbsp;',
+ prevYear: '&nbsp;&gt;&gt;&nbsp;',
+ nextYear: '&nbsp;&lt;&lt;&nbsp;'
+ },
+ buttonIcons: {
+ prev: 'circle-triangle-e',
+ next: 'circle-triangle-w'
+ }
+};
+
+
+
+var fc = $.fullCalendar = { version: "1.5.3" };
+var fcViews = fc.views = {};
+
+
+$.fn.fullCalendar = function(options) {
+
+
+ // method calling
+ if (typeof options == 'string') {
+ var args = Array.prototype.slice.call(arguments, 1);
+ var res;
+ this.each(function() {
+ var calendar = $.data(this, 'fullCalendar');
+ if (calendar && $.isFunction(calendar[options])) {
+ var r = calendar[options].apply(calendar, args);
+ if (res === undefined) {
+ res = r;
+ }
+ if (options == 'destroy') {
+ $.removeData(this, 'fullCalendar');
+ }
+ }
+ });
+ if (res !== undefined) {
+ return res;
+ }
+ return this;
+ }
+
+
+ // would like to have this logic in EventManager, but needs to happen before options are recursively extended
+ var eventSources = options.eventSources || [];
+ delete options.eventSources;
+ if (options.events) {
+ eventSources.push(options.events);
+ delete options.events;
+ }
+
+
+ options = $.extend(true, {},
+ defaults,
+ (options.isRTL || options.isRTL===undefined && defaults.isRTL) ? rtlDefaults : {},
+ options
+ );
+
+
+ this.each(function(i, _element) {
+ var element = $(_element);
+ var calendar = new Calendar(element, options, eventSources);
+ element.data('fullCalendar', calendar); // TODO: look into memory leak implications
+ calendar.render();
+ });
+
+
+ return this;
+
+};
+
+
+// function for adding/overriding defaults
+function setDefaults(d) {
+ $.extend(true, defaults, d);
+}
+
+
+
+
+function Calendar(element, options, eventSources) {
+ var t = this;
+
+
+ // exports
+ t.options = options;
+ t.render = render;
+ t.destroy = destroy;
+ t.refetchEvents = refetchEvents;
+ t.reportEvents = reportEvents;
+ t.reportEventChange = reportEventChange;
+ t.rerenderEvents = rerenderEvents;
+ t.changeView = changeView;
+ t.select = select;
+ t.unselect = unselect;
+ t.prev = prev;
+ t.next = next;
+ t.prevYear = prevYear;
+ t.nextYear = nextYear;
+ t.today = today;
+ t.gotoDate = gotoDate;
+ t.incrementDate = incrementDate;
+ t.formatDate = function(format, date) { return formatDate(format, date, options) };
+ t.formatDates = function(format, date1, date2) { return formatDates(format, date1, date2, options) };
+ t.getDate = getDate;
+ t.getView = getView;
+ t.option = option;
+ t.trigger = trigger;
+
+
+ // imports
+ EventManager.call(t, options, eventSources);
+ var isFetchNeeded = t.isFetchNeeded;
+ var fetchEvents = t.fetchEvents;
+
+
+ // locals
+ var _element = element[0];
+ var header;
+ var headerElement;
+ var content;
+ var tm; // for making theme classes
+ var currentView;
+ var viewInstances = {};
+ var elementOuterWidth;
+ var suggestedViewHeight;
+ var absoluteViewElement;
+ var resizeUID = 0;
+ var ignoreWindowResize = 0;
+ var date = new Date();
+ var events = [];
+ var _dragElement;
+
+
+
+ /* Main Rendering
+ -----------------------------------------------------------------------------*/
+
+
+ setYMD(date, options.year, options.month, options.date);
+
+
+ function render(inc) {
+ if (!content) {
+ initialRender();
+ }else{
+ calcSize();
+ markSizesDirty();
+ markEventsDirty();
+ renderView(inc);
+ }
+ }
+
+
+ function initialRender() {
+ tm = options.theme ? 'ui' : 'fc';
+ element.addClass('fc');
+ if (options.isRTL) {
+ element.addClass('fc-rtl');
+ }
+ if (options.theme) {
+ element.addClass('ui-widget');
+ }
+ content = $("<div class='fc-content' style='position:relative'/>")
+ .prependTo(element);
+ header = new Header(t, options);
+ headerElement = header.render();
+ if (headerElement) {
+ element.prepend(headerElement);
+ }
+ changeView(options.defaultView);
+ $(window).resize(windowResize);
+ // needed for IE in a 0x0 iframe, b/c when it is resized, never triggers a windowResize
+ if (!bodyVisible()) {
+ lateRender();
+ }
+ }
+
+
+ // called when we know the calendar couldn't be rendered when it was initialized,
+ // but we think it's ready now
+ function lateRender() {
+ setTimeout(function() { // IE7 needs this so dimensions are calculated correctly
+ if (!currentView.start && bodyVisible()) { // !currentView.start makes sure this never happens more than once
+ renderView();
+ }
+ },0);
+ }
+
+
+ function destroy() {
+ $(window).unbind('resize', windowResize);
+ header.destroy();
+ content.remove();
+ element.removeClass('fc fc-rtl ui-widget');
+ }
+
+
+
+ function elementVisible() {
+ return _element.offsetWidth !== 0;
+ }
+
+
+ function bodyVisible() {
+ return $('body')[0].offsetWidth !== 0;
+ }
+
+
+
+ /* View Rendering
+ -----------------------------------------------------------------------------*/
+
+ // TODO: improve view switching (still weird transition in IE, and FF has whiteout problem)
+
+ function changeView(newViewName) {
+ if (!currentView || newViewName != currentView.name) {
+ ignoreWindowResize++; // because setMinHeight might change the height before render (and subsequently setSize) is reached
+
+ unselect();
+
+ var oldView = currentView;
+ var newViewElement;
+
+ if (oldView) {
+ (oldView.beforeHide || noop)(); // called before changing min-height. if called after, scroll state is reset (in Opera)
+ setMinHeight(content, content.height());
+ oldView.element.hide();
+ }else{
+ setMinHeight(content, 1); // needs to be 1 (not 0) for IE7, or else view dimensions miscalculated
+ }
+ content.css('overflow', 'hidden');
+
+ currentView = viewInstances[newViewName];
+ if (currentView) {
+ currentView.element.show();
+ }else{
+ currentView = viewInstances[newViewName] = new fcViews[newViewName](
+ newViewElement = absoluteViewElement =
+ $("<div class='fc-view fc-view-" + newViewName + "' style='position:absolute'/>")
+ .appendTo(content),
+ t // the calendar object
+ );
+ }
+
+ if (oldView) {
+ header.deactivateButton(oldView.name);
+ }
+ header.activateButton(newViewName);
+
+ renderView(); // after height has been set, will make absoluteViewElement's position=relative, then set to null
+
+ content.css('overflow', '');
+ if (oldView) {
+ setMinHeight(content, 1);
+ }
+
+ if (!newViewElement) {
+ (currentView.afterShow || noop)(); // called after setting min-height/overflow, so in final scroll state (for Opera)
+ }
+
+ ignoreWindowResize--;
+ }
+ }
+
+
+
+ function renderView(inc) {
+ if (elementVisible()) {
+ ignoreWindowResize++; // because renderEvents might temporarily change the height before setSize is reached
+
+ unselect();
+
+ if (suggestedViewHeight === undefined) {
+ calcSize();
+ }
+
+ var forceEventRender = false;
+ if (!currentView.start || inc || date < currentView.start || date >= currentView.end) {
+ // view must render an entire new date range (and refetch/render events)
+ currentView.render(date, inc || 0); // responsible for clearing events
+ setSize(true);
+ forceEventRender = true;
+ }
+ else if (currentView.sizeDirty) {
+ // view must resize (and rerender events)
+ currentView.clearEvents();
+ setSize();
+ forceEventRender = true;
+ }
+ else if (currentView.eventsDirty) {
+ currentView.clearEvents();
+ forceEventRender = true;
+ }
+ currentView.sizeDirty = false;
+ currentView.eventsDirty = false;
+ updateEvents(forceEventRender);
+
+ elementOuterWidth = element.outerWidth();
+
+ header.updateTitle(currentView.title);
+ var today = new Date();
+ if (today >= currentView.start && today < currentView.end) {
+ header.disableButton('today');
+ }else{
+ header.enableButton('today');
+ }
+
+ ignoreWindowResize--;
+ currentView.trigger('viewDisplay', _element);
+ }
+ }
+
+
+
+ /* Resizing
+ -----------------------------------------------------------------------------*/
+
+
+ function updateSize() {
+ markSizesDirty();
+ if (elementVisible()) {
+ calcSize();
+ setSize();
+ unselect();
+ currentView.clearEvents();
+ currentView.renderEvents(events);
+ currentView.sizeDirty = false;
+ }
+ }
+
+
+ function markSizesDirty() {
+ $.each(viewInstances, function(i, inst) {
+ inst.sizeDirty = true;
+ });
+ }
+
+
+ function calcSize() {
+ if (options.contentHeight) {
+ suggestedViewHeight = options.contentHeight;
+ }
+ else if (options.height) {
+ suggestedViewHeight = options.height - (headerElement ? headerElement.height() : 0) - vsides(content);
+ }
+ else {
+ suggestedViewHeight = Math.round(content.width() / Math.max(options.aspectRatio, .5));
+ }
+ }
+
+
+ function setSize(dateChanged) { // todo: dateChanged?
+ ignoreWindowResize++;
+ currentView.setHeight(suggestedViewHeight, dateChanged);
+ if (absoluteViewElement) {
+ absoluteViewElement.css('position', 'relative');
+ absoluteViewElement = null;
+ }
+ currentView.setWidth(content.width(), dateChanged);
+ ignoreWindowResize--;
+ }
+
+
+ function windowResize() {
+ if (!ignoreWindowResize) {
+ if (currentView.start) { // view has already been rendered
+ var uid = ++resizeUID;
+ setTimeout(function() { // add a delay
+ if (uid == resizeUID && !ignoreWindowResize && elementVisible()) {
+ if (elementOuterWidth != (elementOuterWidth = element.outerWidth())) {
+ ignoreWindowResize++; // in case the windowResize callback changes the height
+ updateSize();
+ currentView.trigger('windowResize', _element);
+ ignoreWindowResize--;
+ }
+ }
+ }, 200);
+ }else{
+ // calendar must have been initialized in a 0x0 iframe that has just been resized
+ lateRender();
+ }
+ }
+ }
+
+
+
+ /* Event Fetching/Rendering
+ -----------------------------------------------------------------------------*/
+
+
+ // fetches events if necessary, rerenders events if necessary (or if forced)
+ function updateEvents(forceRender) {
+ if (!options.lazyFetching || isFetchNeeded(currentView.visStart, currentView.visEnd)) {
+ refetchEvents();
+ }
+ else if (forceRender) {
+ rerenderEvents();
+ }
+ }
+
+
+ function refetchEvents() {
+ fetchEvents(currentView.visStart, currentView.visEnd); // will call reportEvents
+ }
+
+
+ // called when event data arrives
+ function reportEvents(_events) {
+ events = _events;
+ rerenderEvents();
+ }
+
+
+ // called when a single event's data has been changed
+ function reportEventChange(eventID) {
+ rerenderEvents(eventID);
+ }
+
+
+ // attempts to rerenderEvents
+ function rerenderEvents(modifiedEventID) {
+ markEventsDirty();
+ if (elementVisible()) {
+ currentView.clearEvents();
+ currentView.renderEvents(events, modifiedEventID);
+ currentView.eventsDirty = false;
+ }
+ }
+
+
+ function markEventsDirty() {
+ $.each(viewInstances, function(i, inst) {
+ inst.eventsDirty = true;
+ });
+ }
+
+
+
+ /* Selection
+ -----------------------------------------------------------------------------*/
+
+
+ function select(start, end, allDay) {
+ currentView.select(start, end, allDay===undefined ? true : allDay);
+ }
+
+
+ function unselect() { // safe to be called before renderView
+ if (currentView) {
+ currentView.unselect();
+ }
+ }
+
+
+
+ /* Date
+ -----------------------------------------------------------------------------*/
+
+
+ function prev() {
+ renderView(-1);
+ }
+
+
+ function next() {
+ renderView(1);
+ }
+
+
+ function prevYear() {
+ addYears(date, -1);
+ renderView();
+ }
+
+
+ function nextYear() {
+ addYears(date, 1);
+ renderView();
+ }
+
+
+ function today() {
+ date = new Date();
+ renderView();
+ }
+
+
+ function gotoDate(year, month, dateOfMonth) {
+ if (year instanceof Date) {
+ date = cloneDate(year); // provided 1 argument, a Date
+ }else{
+ setYMD(date, year, month, dateOfMonth);
+ }
+ renderView();
+ }
+
+
+ function incrementDate(years, months, days) {
+ if (years !== undefined) {
+ addYears(date, years);
+ }
+ if (months !== undefined) {
+ addMonths(date, months);
+ }
+ if (days !== undefined) {
+ addDays(date, days);
+ }
+ renderView();
+ }
+
+
+ function getDate() {
+ return cloneDate(date);
+ }
+
+
+
+ /* Misc
+ -----------------------------------------------------------------------------*/
+
+
+ function getView() {
+ return currentView;
+ }
+
+
+ function option(name, value) {
+ if (value === undefined) {
+ return options[name];
+ }
+ if (name == 'height' || name == 'contentHeight' || name == 'aspectRatio') {
+ options[name] = value;
+ updateSize();
+ }
+ }
+
+
+ function trigger(name, thisObj) {
+ if (options[name]) {
+ return options[name].apply(
+ thisObj || _element,
+ Array.prototype.slice.call(arguments, 2)
+ );
+ }
+ }
+
+
+
+ /* External Dragging
+ ------------------------------------------------------------------------*/
+
+ if (options.droppable) {
+ $(document)
+ .bind('dragstart', function(ev, ui) {
+ var _e = ev.target;
+ var e = $(_e);
+ if (!e.parents('.fc').length) { // not already inside a calendar
+ var accept = options.dropAccept;
+ if ($.isFunction(accept) ? accept.call(_e, e) : e.is(accept)) {
+ _dragElement = _e;
+ currentView.dragStart(_dragElement, ev, ui);
+ }
+ }
+ })
+ .bind('dragstop', function(ev, ui) {
+ if (_dragElement) {
+ currentView.dragStop(_dragElement, ev, ui);
+ _dragElement = null;
+ }
+ });
+ }
+
+
+}
+
+function Header(calendar, options) {
+ var t = this;
+
+
+ // exports
+ t.render = render;
+ t.destroy = destroy;
+ t.updateTitle = updateTitle;
+ t.activateButton = activateButton;
+ t.deactivateButton = deactivateButton;
+ t.disableButton = disableButton;
+ t.enableButton = enableButton;
+
+
+ // locals
+ var element = $([]);
+ var tm;
+
+
+
+ function render() {
+ tm = options.theme ? 'ui' : 'fc';
+ var sections = options.header;
+ if (sections) {
+ element = $("<table class='fc-header' style='width:100%'/>")
+ .append(
+ $("<tr/>")
+ .append(renderSection('left'))
+ .append(renderSection('center'))
+ .append(renderSection('right'))
+ );
+ return element;
+ }
+ }
+
+
+ function destroy() {
+ element.remove();
+ }
+
+
+ function renderSection(position) {
+ var e = $("<td class='fc-header-" + position + "'/>");
+ var buttonStr = options.header[position];
+ if (buttonStr) {
+ $.each(buttonStr.split(' '), function(i) {
+ if (i > 0) {
+ e.append("<span class='fc-header-space'/>");
+ }
+ var prevButton;
+ $.each(this.split(','), function(j, buttonName) {
+ if (buttonName == 'title') {
+ e.append("<span class='fc-header-title'><h2>&nbsp;</h2></span>");
+ if (prevButton) {
+ prevButton.addClass(tm + '-corner-right');
+ }
+ prevButton = null;
+ }else{
+ var buttonClick;
+ if (calendar[buttonName]) {
+ buttonClick = calendar[buttonName]; // calendar method
+ }
+ else if (fcViews[buttonName]) {
+ buttonClick = function() {
+ button.removeClass(tm + '-state-hover'); // forget why
+ calendar.changeView(buttonName);
+ };
+ }
+ if (buttonClick) {
+ var icon = options.theme ? smartProperty(options.buttonIcons, buttonName) : null; // why are we using smartProperty here?
+ var text = smartProperty(options.buttonText, buttonName); // why are we using smartProperty here?
+ var button = $(
+ "<span class='fc-button fc-button-" + buttonName + " " + tm + "-state-default'>" +
+ "<span class='fc-button-inner'>" +
+ "<span class='fc-button-content'>" +
+ (icon ?
+ "<span class='fc-icon-wrap'>" +
+ "<span class='ui-icon ui-icon-" + icon + "'/>" +
+ "</span>" :
+ text
+ ) +
+ "</span>" +
+ "<span class='fc-button-effect'><span></span></span>" +
+ "</span>" +
+ "</span>"
+ );
+ if (button) {
+ button
+ .click(function() {
+ if (!button.hasClass(tm + '-state-disabled')) {
+ buttonClick();
+ }
+ })
+ .mousedown(function() {
+ button
+ .not('.' + tm + '-state-active')
+ .not('.' + tm + '-state-disabled')
+ .addClass(tm + '-state-down');
+ })
+ .mouseup(function() {
+ button.removeClass(tm + '-state-down');
+ })
+ .hover(
+ function() {
+ button
+ .not('.' + tm + '-state-active')
+ .not('.' + tm + '-state-disabled')
+ .addClass(tm + '-state-hover');
+ },
+ function() {
+ button
+ .removeClass(tm + '-state-hover')
+ .removeClass(tm + '-state-down');
+ }
+ )
+ .appendTo(e);
+ if (!prevButton) {
+ button.addClass(tm + '-corner-left');
+ }
+ prevButton = button;
+ }
+ }
+ }
+ });
+ if (prevButton) {
+ prevButton.addClass(tm + '-corner-right');
+ }
+ });
+ }
+ return e;
+ }
+
+
+ function updateTitle(html) {
+ element.find('h2')
+ .html(html);
+ }
+
+
+ function activateButton(buttonName) {
+ element.find('span.fc-button-' + buttonName)
+ .addClass(tm + '-state-active');
+ }
+
+
+ function deactivateButton(buttonName) {
+ element.find('span.fc-button-' + buttonName)
+ .removeClass(tm + '-state-active');
+ }
+
+
+ function disableButton(buttonName) {
+ element.find('span.fc-button-' + buttonName)
+ .addClass(tm + '-state-disabled');
+ }
+
+
+ function enableButton(buttonName) {
+ element.find('span.fc-button-' + buttonName)
+ .removeClass(tm + '-state-disabled');
+ }
+
+
+}
+
+fc.sourceNormalizers = [];
+fc.sourceFetchers = [];
+
+var ajaxDefaults = {
+ dataType: 'json',
+ cache: false
+};
+
+var eventGUID = 1;
+
+
+function EventManager(options, _sources) {
+ var t = this;
+
+
+ // exports
+ t.isFetchNeeded = isFetchNeeded;
+ t.fetchEvents = fetchEvents;
+ t.addEventSource = addEventSource;
+ t.removeEventSource = removeEventSource;
+ t.updateEvent = updateEvent;
+ t.renderEvent = renderEvent;
+ t.removeEvents = removeEvents;
+ t.clientEvents = clientEvents;
+ t.normalizeEvent = normalizeEvent;
+
+
+ // imports
+ var trigger = t.trigger;
+ var getView = t.getView;
+ var reportEvents = t.reportEvents;
+
+
+ // locals
+ var stickySource = { events: [] };
+ var sources = [ stickySource ];
+ var rangeStart, rangeEnd;
+ var currentFetchID = 0;
+ var pendingSourceCnt = 0;
+ var loadingLevel = 0;
+ var cache = [];
+
+
+ for (var i=0; i<_sources.length; i++) {
+ _addEventSource(_sources[i]);
+ }
+
+
+
+ /* Fetching
+ -----------------------------------------------------------------------------*/
+
+
+ function isFetchNeeded(start, end) {
+ return !rangeStart || start < rangeStart || end > rangeEnd;
+ }
+
+
+ function fetchEvents(start, end) {
+ rangeStart = start;
+ rangeEnd = end;
+ cache = [];
+ var fetchID = ++currentFetchID;
+ var len = sources.length;
+ pendingSourceCnt = len;
+ for (var i=0; i<len; i++) {
+ fetchEventSource(sources[i], fetchID);
+ }
+ }
+
+
+ function fetchEventSource(source, fetchID) {
+ _fetchEventSource(source, function(events) {
+ if (fetchID == currentFetchID) {
+ if (events) {
+ for (var i=0; i<events.length; i++) {
+ events[i].source = source;
+ normalizeEvent(events[i]);
+ }
+ cache = cache.concat(events);
+ }
+ pendingSourceCnt--;
+ if (!pendingSourceCnt) {
+ reportEvents(cache);
+ }
+ }
+ });
+ }
+
+
+ function _fetchEventSource(source, callback) {
+ var i;
+ var fetchers = fc.sourceFetchers;
+ var res;
+ for (i=0; i<fetchers.length; i++) {
+ res = fetchers[i](source, rangeStart, rangeEnd, callback);
+ if (res === true) {
+ // the fetcher is in charge. made its own async request
+ return;
+ }
+ else if (typeof res == 'object') {
+ // the fetcher returned a new source. process it
+ _fetchEventSource(res, callback);
+ return;
+ }
+ }
+ var events = source.events;
+ if (events) {
+ if ($.isFunction(events)) {
+ pushLoading();
+ events(cloneDate(rangeStart), cloneDate(rangeEnd), function(events) {
+ callback(events);
+ popLoading();
+ });
+ }
+ else if ($.isArray(events)) {
+ callback(events);
+ }
+ else {
+ callback();
+ }
+ }else{
+ var url = source.url;
+ if (url) {
+ var success = source.success;
+ var error = source.error;
+ var complete = source.complete;
+ var data = $.extend({}, source.data || {});
+ var startParam = firstDefined(source.startParam, options.startParam);
+ var endParam = firstDefined(source.endParam, options.endParam);
+ if (startParam) {
+ data[startParam] = Math.round(+rangeStart / 1000);
+ }
+ if (endParam) {
+ data[endParam] = Math.round(+rangeEnd / 1000);
+ }
+ pushLoading();
+ $.ajax($.extend({}, ajaxDefaults, source, {
+ data: data,
+ success: function(events) {
+ events = events || [];
+ var res = applyAll(success, this, arguments);
+ if ($.isArray(res)) {
+ events = res;
+ }
+ callback(events);
+ },
+ error: function() {
+ applyAll(error, this, arguments);
+ callback();
+ },
+ complete: function() {
+ applyAll(complete, this, arguments);
+ popLoading();
+ }
+ }));
+ }else{
+ callback();
+ }
+ }
+ }
+
+
+
+ /* Sources
+ -----------------------------------------------------------------------------*/
+
+
+ function addEventSource(source) {
+ source = _addEventSource(source);
+ if (source) {
+ pendingSourceCnt++;
+ fetchEventSource(source, currentFetchID); // will eventually call reportEvents
+ }
+ }
+
+
+ function _addEventSource(source) {
+ if ($.isFunction(source) || $.isArray(source)) {
+ source = { events: source };
+ }
+ else if (typeof source == 'string') {
+ source = { url: source };
+ }
+ if (typeof source == 'object') {
+ normalizeSource(source);
+ sources.push(source);
+ return source;
+ }
+ }
+
+
+ function removeEventSource(source) {
+ sources = $.grep(sources, function(src) {
+ return !isSourcesEqual(src, source);
+ });
+ // remove all client events from that source
+ cache = $.grep(cache, function(e) {
+ return !isSourcesEqual(e.source, source);
+ });
+ reportEvents(cache);
+ }
+
+
+
+ /* Manipulation
+ -----------------------------------------------------------------------------*/
+
+
+ function updateEvent(event) { // update an existing event
+ var i, len = cache.length, e,
+ defaultEventEnd = getView().defaultEventEnd, // getView???
+ startDelta = event.start - event._start,
+ endDelta = event.end ?
+ (event.end - (event._end || defaultEventEnd(event))) // event._end would be null if event.end
+ : 0; // was null and event was just resized
+ for (i=0; i<len; i++) {
+ e = cache[i];
+ if (e._id == event._id && e != event) {
+ e.start = new Date(+e.start + startDelta);
+ if (event.end) {
+ if (e.end) {
+ e.end = new Date(+e.end + endDelta);
+ }else{
+ e.end = new Date(+defaultEventEnd(e) + endDelta);
+ }
+ }else{
+ e.end = null;
+ }
+ e.title = event.title;
+ e.url = event.url;
+ e.allDay = event.allDay;
+ e.className = event.className;
+ e.editable = event.editable;
+ e.color = event.color;
+ e.backgroudColor = event.backgroudColor;
+ e.borderColor = event.borderColor;
+ e.textColor = event.textColor;
+ normalizeEvent(e);
+ }
+ }
+ normalizeEvent(event);
+ reportEvents(cache);
+ }
+
+
+ function renderEvent(event, stick) {
+ normalizeEvent(event);
+ if (!event.source) {
+ if (stick) {
+ stickySource.events.push(event);
+ event.source = stickySource;
+ }
+ cache.push(event);
+ }
+ reportEvents(cache);
+ }
+
+
+ function removeEvents(filter) {
+ if (!filter) { // remove all
+ cache = [];
+ // clear all array sources
+ for (var i=0; i<sources.length; i++) {
+ if ($.isArray(sources[i].events)) {
+ sources[i].events = [];
+ }
+ }
+ }else{
+ if (!$.isFunction(filter)) { // an event ID
+ var id = filter + '';
+ filter = function(e) {
+ return e._id == id;
+ };
+ }
+ cache = $.grep(cache, filter, true);
+ // remove events from array sources
+ for (var i=0; i<sources.length; i++) {
+ if ($.isArray(sources[i].events)) {
+ sources[i].events = $.grep(sources[i].events, filter, true);
+ }
+ }
+ }
+ reportEvents(cache);
+ }
+
+
+ function clientEvents(filter) {
+ if ($.isFunction(filter)) {
+ return $.grep(cache, filter);
+ }
+ else if (filter) { // an event ID
+ filter += '';
+ return $.grep(cache, function(e) {
+ return e._id == filter;
+ });
+ }
+ return cache; // else, return all
+ }
+
+
+
+ /* Loading State
+ -----------------------------------------------------------------------------*/
+
+
+ function pushLoading() {
+ if (!loadingLevel++) {
+ trigger('loading', null, true);
+ }
+ }
+
+
+ function popLoading() {
+ if (!--loadingLevel) {
+ trigger('loading', null, false);
+ }
+ }
+
+
+
+ /* Event Normalization
+ -----------------------------------------------------------------------------*/
+
+
+ function normalizeEvent(event) {
+ var source = event.source || {};
+ var ignoreTimezone = firstDefined(source.ignoreTimezone, options.ignoreTimezone);
+ event._id = event._id || (event.id === undefined ? '_fc' + eventGUID++ : event.id + '');
+ if (event.date) {
+ if (!event.start) {
+ event.start = event.date;
+ }
+ delete event.date;
+ }
+ event._start = cloneDate(event.start = parseDate(event.start, ignoreTimezone));
+ event.end = parseDate(event.end, ignoreTimezone);
+ if (event.end && event.end <= event.start) {
+ event.end = null;
+ }
+ event._end = event.end ? cloneDate(event.end) : null;
+ if (event.allDay === undefined) {
+ event.allDay = firstDefined(source.allDayDefault, options.allDayDefault);
+ }
+ if (event.className) {
+ if (typeof event.className == 'string') {
+ event.className = event.className.split(/\s+/);
+ }
+ }else{
+ event.className = [];
+ }
+ // TODO: if there is no start date, return false to indicate an invalid event
+ }
+
+
+
+ /* Utils
+ ------------------------------------------------------------------------------*/
+
+
+ function normalizeSource(source) {
+ if (source.className) {
+ // TODO: repeat code, same code for event classNames
+ if (typeof source.className == 'string') {
+ source.className = source.className.split(/\s+/);
+ }
+ }else{
+ source.className = [];
+ }
+ var normalizers = fc.sourceNormalizers;
+ for (var i=0; i<normalizers.length; i++) {
+ normalizers[i](source);
+ }
+ }
+
+
+ function isSourcesEqual(source1, source2) {
+ return source1 && source2 && getSourcePrimitive(source1) == getSourcePrimitive(source2);
+ }
+
+
+ function getSourcePrimitive(source) {
+ return ((typeof source == 'object') ? (source.events || source.url) : '') || source;
+ }
+
+
+}
+
+
+fc.addDays = addDays;
+fc.cloneDate = cloneDate;
+fc.parseDate = parseDate;
+fc.parseISO8601 = parseISO8601;
+fc.parseTime = parseTime;
+fc.formatDate = formatDate;
+fc.formatDates = formatDates;
+
+
+
+/* Date Math
+-----------------------------------------------------------------------------*/
+
+var dayIDs = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'],
+ DAY_MS = 86400000,
+ HOUR_MS = 3600000,
+ MINUTE_MS = 60000;
+
+
+function addYears(d, n, keepTime) {
+ d.setFullYear(d.getFullYear() + n);
+ if (!keepTime) {
+ clearTime(d);
+ }
+ return d;
+}
+
+
+function addMonths(d, n, keepTime) { // prevents day overflow/underflow
+ if (+d) { // prevent infinite looping on invalid dates
+ var m = d.getMonth() + n,
+ check = cloneDate(d);
+ check.setDate(1);
+ check.setMonth(m);
+ d.setMonth(m);
+ if (!keepTime) {
+ clearTime(d);
+ }
+ while (d.getMonth() != check.getMonth()) {
+ d.setDate(d.getDate() + (d < check ? 1 : -1));
+ }
+ }
+ return d;
+}
+
+
+function addDays(d, n, keepTime) { // deals with daylight savings
+ if (+d) {
+ var dd = d.getDate() + n,
+ check = cloneDate(d);
+ check.setHours(9); // set to middle of day
+ check.setDate(dd);
+ d.setDate(dd);
+ if (!keepTime) {
+ clearTime(d);
+ }
+ fixDate(d, check);
+ }
+ return d;
+}
+
+
+function fixDate(d, check) { // force d to be on check's YMD, for daylight savings purposes
+ if (+d) { // prevent infinite looping on invalid dates
+ while (d.getDate() != check.getDate()) {
+ d.setTime(+d + (d < check ? 1 : -1) * HOUR_MS);
+ }
+ }
+}
+
+
+function addMinutes(d, n) {
+ d.setMinutes(d.getMinutes() + n);
+ return d;
+}
+
+
+function clearTime(d) {
+ d.setHours(0);
+ d.setMinutes(0);
+ d.setSeconds(0);
+ d.setMilliseconds(0);
+ return d;
+}
+
+
+function cloneDate(d, dontKeepTime) {
+ if (dontKeepTime) {
+ return clearTime(new Date(+d));
+ }
+ return new Date(+d);
+}
+
+
+function zeroDate() { // returns a Date with time 00:00:00 and dateOfMonth=1
+ var i=0, d;
+ do {
+ d = new Date(1970, i++, 1);
+ } while (d.getHours()); // != 0
+ return d;
+}
+
+
+function skipWeekend(date, inc, excl) {
+ inc = inc || 1;
+ while (!date.getDay() || (excl && date.getDay()==1 || !excl && date.getDay()==6)) {
+ addDays(date, inc);
+ }
+ return date;
+}
+
+
+function dayDiff(d1, d2) { // d1 - d2
+ return Math.round((cloneDate(d1, true) - cloneDate(d2, true)) / DAY_MS);
+}
+
+
+function setYMD(date, y, m, d) {
+ if (y !== undefined && y != date.getFullYear()) {
+ date.setDate(1);
+ date.setMonth(0);
+ date.setFullYear(y);
+ }
+ if (m !== undefined && m != date.getMonth()) {
+ date.setDate(1);
+ date.setMonth(m);
+ }
+ if (d !== undefined) {
+ date.setDate(d);
+ }
+}
+
+
+
+/* Date Parsing
+-----------------------------------------------------------------------------*/
+
+
+function parseDate(s, ignoreTimezone) { // ignoreTimezone defaults to true
+ if (typeof s == 'object') { // already a Date object
+ return s;
+ }
+ if (typeof s == 'number') { // a UNIX timestamp
+ return new Date(s * 1000);
+ }
+ if (typeof s == 'string') {
+ if (s.match(/^\d+(\.\d+)?$/)) { // a UNIX timestamp
+ return new Date(parseFloat(s) * 1000);
+ }
+ if (ignoreTimezone === undefined) {
+ ignoreTimezone = true;
+ }
+ return parseISO8601(s, ignoreTimezone) || (s ? new Date(s) : null);
+ }
+ // TODO: never return invalid dates (like from new Date(<string>)), return null instead
+ return null;
+}
+
+
+function parseISO8601(s, ignoreTimezone) { // ignoreTimezone defaults to false
+ // derived from http://delete.me.uk/2005/03/iso8601.html
+ // TODO: for a know glitch/feature, read tests/issue_206_parseDate_dst.html
+ var m = s.match(/^([0-9]{4})(-([0-9]{2})(-([0-9]{2})([T ]([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?(Z|(([-+])([0-9]{2})(:?([0-9]{2}))?))?)?)?)?$/);
+ if (!m) {
+ return null;
+ }
+ var date = new Date(m[1], 0, 1);
+ if (ignoreTimezone || !m[13]) {
+ var check = new Date(m[1], 0, 1, 9, 0);
+ if (m[3]) {
+ date.setMonth(m[3] - 1);
+ check.setMonth(m[3] - 1);
+ }
+ if (m[5]) {
+ date.setDate(m[5]);
+ check.setDate(m[5]);
+ }
+ fixDate(date, check);
+ if (m[7]) {
+ date.setHours(m[7]);
+ }
+ if (m[8]) {
+ date.setMinutes(m[8]);
+ }
+ if (m[10]) {
+ date.setSeconds(m[10]);
+ }
+ if (m[12]) {
+ date.setMilliseconds(Number("0." + m[12]) * 1000);
+ }
+ fixDate(date, check);
+ }else{
+ date.setUTCFullYear(
+ m[1],
+ m[3] ? m[3] - 1 : 0,
+ m[5] || 1
+ );
+ date.setUTCHours(
+ m[7] || 0,
+ m[8] || 0,
+ m[10] || 0,
+ m[12] ? Number("0." + m[12]) * 1000 : 0
+ );
+ if (m[14]) {
+ var offset = Number(m[16]) * 60 + (m[18] ? Number(m[18]) : 0);
+ offset *= m[15] == '-' ? 1 : -1;
+ date = new Date(+date + (offset * 60 * 1000));
+ }
+ }
+ return date;
+}
+
+
+function parseTime(s) { // returns minutes since start of day
+ if (typeof s == 'number') { // an hour
+ return s * 60;
+ }
+ if (typeof s == 'object') { // a Date object
+ return s.getHours() * 60 + s.getMinutes();
+ }
+ var m = s.match(/(\d+)(?::(\d+))?\s*(\w+)?/);
+ if (m) {
+ var h = parseInt(m[1], 10);
+ if (m[3]) {
+ h %= 12;
+ if (m[3].toLowerCase().charAt(0) == 'p') {
+ h += 12;
+ }
+ }
+ return h * 60 + (m[2] ? parseInt(m[2], 10) : 0);
+ }
+}
+
+
+
+/* Date Formatting
+-----------------------------------------------------------------------------*/
+// TODO: use same function formatDate(date, [date2], format, [options])
+
+
+function formatDate(date, format, options) {
+ return formatDates(date, null, format, options);
+}
+
+
+function formatDates(date1, date2, format, options) {
+ options = options || defaults;
+ var date = date1,
+ otherDate = date2,
+ i, len = format.length, c,
+ i2, formatter,
+ res = '';
+ for (i=0; i<len; i++) {
+ c = format.charAt(i);
+ if (c == "'") {
+ for (i2=i+1; i2<len; i2++) {
+ if (format.charAt(i2) == "'") {
+ if (date) {
+ if (i2 == i+1) {
+ res += "'";
+ }else{
+ res += format.substring(i+1, i2);
+ }
+ i = i2;
+ }
+ break;
+ }
+ }
+ }
+ else if (c == '(') {
+ for (i2=i+1; i2<len; i2++) {
+ if (format.charAt(i2) == ')') {
+ var subres = formatDate(date, format.substring(i+1, i2), options);
+ if (parseInt(subres.replace(/\D/, ''), 10)) {
+ res += subres;
+ }
+ i = i2;
+ break;
+ }
+ }
+ }
+ else if (c == '[') {
+ for (i2=i+1; i2<len; i2++) {
+ if (format.charAt(i2) == ']') {
+ var subformat = format.substring(i+1, i2);
+ var subres = formatDate(date, subformat, options);
+ if (subres != formatDate(otherDate, subformat, options)) {
+ res += subres;
+ }
+ i = i2;
+ break;
+ }
+ }
+ }
+ else if (c == '{') {
+ date = date2;
+ otherDate = date1;
+ }
+ else if (c == '}') {
+ date = date1;
+ otherDate = date2;
+ }
+ else {
+ for (i2=len; i2>i; i2--) {
+ if (formatter = dateFormatters[format.substring(i, i2)]) {
+ if (date) {
+ res += formatter(date, options);
+ }
+ i = i2 - 1;
+ break;
+ }
+ }
+ if (i2 == i) {
+ if (date) {
+ res += c;
+ }
+ }
+ }
+ }
+ return res;
+};
+
+
+var dateFormatters = {
+ s : function(d) { return d.getSeconds() },
+ ss : function(d) { return zeroPad(d.getSeconds()) },
+ m : function(d) { return d.getMinutes() },
+ mm : function(d) { return zeroPad(d.getMinutes()) },
+ h : function(d) { return d.getHours() % 12 || 12 },
+ hh : function(d) { return zeroPad(d.getHours() % 12 || 12) },
+ H : function(d) { return d.getHours() },
+ HH : function(d) { return zeroPad(d.getHours()) },
+ d : function(d) { return d.getDate() },
+ dd : function(d) { return zeroPad(d.getDate()) },
+ ddd : function(d,o) { return o.dayNamesShort[d.getDay()] },
+ dddd: function(d,o) { return o.dayNames[d.getDay()] },
+ M : function(d) { return d.getMonth() + 1 },
+ MM : function(d) { return zeroPad(d.getMonth() + 1) },
+ MMM : function(d,o) { return o.monthNamesShort[d.getMonth()] },
+ MMMM: function(d,o) { return o.monthNames[d.getMonth()] },
+ yy : function(d) { return (d.getFullYear()+'').substring(2) },
+ yyyy: function(d) { return d.getFullYear() },
+ t : function(d) { return d.getHours() < 12 ? 'a' : 'p' },
+ tt : function(d) { return d.getHours() < 12 ? 'am' : 'pm' },
+ T : function(d) { return d.getHours() < 12 ? 'A' : 'P' },
+ TT : function(d) { return d.getHours() < 12 ? 'AM' : 'PM' },
+ u : function(d) { return formatDate(d, "yyyy-MM-dd'T'HH:mm:ss'Z'") },
+ S : function(d) {
+ var date = d.getDate();
+ if (date > 10 && date < 20) {
+ return 'th';
+ }
+ return ['st', 'nd', 'rd'][date%10-1] || 'th';
+ }
+};
+
+
+
+fc.applyAll = applyAll;
+
+
+/* Event Date Math
+-----------------------------------------------------------------------------*/
+
+
+function exclEndDay(event) {
+ if (event.end) {
+ return _exclEndDay(event.end, event.allDay);
+ }else{
+ return addDays(cloneDate(event.start), 1);
+ }
+}
+
+
+function _exclEndDay(end, allDay) {
+ end = cloneDate(end);
+ return allDay || end.getHours() || end.getMinutes() ? addDays(end, 1) : clearTime(end);
+}
+
+
+function segCmp(a, b) {
+ return (b.msLength - a.msLength) * 100 + (a.event.start - b.event.start);
+}
+
+
+function segsCollide(seg1, seg2) {
+ return seg1.end > seg2.start && seg1.start < seg2.end;
+}
+
+
+
+/* Event Sorting
+-----------------------------------------------------------------------------*/
+
+
+// event rendering utilities
+function sliceSegs(events, visEventEnds, start, end) {
+ var segs = [],
+ i, len=events.length, event,
+ eventStart, eventEnd,
+ segStart, segEnd,
+ isStart, isEnd;
+ for (i=0; i<len; i++) {
+ event = events[i];
+ eventStart = event.start;
+ eventEnd = visEventEnds[i];
+ if (eventEnd > start && eventStart < end) {
+ if (eventStart < start) {
+ segStart = cloneDate(start);
+ isStart = false;
+ }else{
+ segStart = eventStart;
+ isStart = true;
+ }
+ if (eventEnd > end) {
+ segEnd = cloneDate(end);
+ isEnd = false;
+ }else{
+ segEnd = eventEnd;
+ isEnd = true;
+ }
+ segs.push({
+ event: event,
+ start: segStart,
+ end: segEnd,
+ isStart: isStart,
+ isEnd: isEnd,
+ msLength: segEnd - segStart
+ });
+ }
+ }
+ return segs.sort(segCmp);
+}
+
+
+// event rendering calculation utilities
+function stackSegs(segs) {
+ var levels = [],
+ i, len = segs.length, seg,
+ j, collide, k;
+ for (i=0; i<len; i++) {
+ seg = segs[i];
+ j = 0; // the level index where seg should belong
+ while (true) {
+ collide = false;
+ if (levels[j]) {
+ for (k=0; k<levels[j].length; k++) {
+ if (segsCollide(levels[j][k], seg)) {
+ collide = true;
+ break;
+ }
+ }
+ }
+ if (collide) {
+ j++;
+ }else{
+ break;
+ }
+ }
+ if (levels[j]) {
+ levels[j].push(seg);
+ }else{
+ levels[j] = [seg];
+ }
+ }
+ return levels;
+}
+
+
+
+/* Event Element Binding
+-----------------------------------------------------------------------------*/
+
+
+function lazySegBind(container, segs, bindHandlers) {
+ container.unbind('mouseover').mouseover(function(ev) {
+ var parent=ev.target, e,
+ i, seg;
+ while (parent != this) {
+ e = parent;
+ parent = parent.parentNode;
+ }
+ if ((i = e._fci) !== undefined) {
+ e._fci = undefined;
+ seg = segs[i];
+ bindHandlers(seg.event, seg.element, seg);
+ $(ev.target).trigger(ev);
+ }
+ ev.stopPropagation();
+ });
+}
+
+
+
+/* Element Dimensions
+-----------------------------------------------------------------------------*/
+
+
+function setOuterWidth(element, width, includeMargins) {
+ for (var i=0, e; i<element.length; i++) {
+ e = $(element[i]);
+ e.width(Math.max(0, width - hsides(e, includeMargins)));
+ }
+}
+
+
+function setOuterHeight(element, height, includeMargins) {
+ for (var i=0, e; i<element.length; i++) {
+ e = $(element[i]);
+ e.height(Math.max(0, height - vsides(e, includeMargins)));
+ }
+}
+
+
+// TODO: curCSS has been deprecated (jQuery 1.4.3 - 10/16/2010)
+
+
+function hsides(element, includeMargins) {
+ return hpadding(element) + hborders(element) + (includeMargins ? hmargins(element) : 0);
+}
+
+
+function hpadding(element) {
+ return (parseFloat($.curCSS(element[0], 'paddingLeft', true)) || 0) +
+ (parseFloat($.curCSS(element[0], 'paddingRight', true)) || 0);
+}
+
+
+function hmargins(element) {
+ return (parseFloat($.curCSS(element[0], 'marginLeft', true)) || 0) +
+ (parseFloat($.curCSS(element[0], 'marginRight', true)) || 0);
+}
+
+
+function hborders(element) {
+ return (parseFloat($.curCSS(element[0], 'borderLeftWidth', true)) || 0) +
+ (parseFloat($.curCSS(element[0], 'borderRightWidth', true)) || 0);
+}
+
+
+function vsides(element, includeMargins) {
+ return vpadding(element) + vborders(element) + (includeMargins ? vmargins(element) : 0);
+}
+
+
+function vpadding(element) {
+ return (parseFloat($.curCSS(element[0], 'paddingTop', true)) || 0) +
+ (parseFloat($.curCSS(element[0], 'paddingBottom', true)) || 0);
+}
+
+
+function vmargins(element) {
+ return (parseFloat($.curCSS(element[0], 'marginTop', true)) || 0) +
+ (parseFloat($.curCSS(element[0], 'marginBottom', true)) || 0);
+}
+
+
+function vborders(element) {
+ return (parseFloat($.curCSS(element[0], 'borderTopWidth', true)) || 0) +
+ (parseFloat($.curCSS(element[0], 'borderBottomWidth', true)) || 0);
+}
+
+
+function setMinHeight(element, height) {
+ height = (typeof height == 'number' ? height + 'px' : height);
+ element.each(function(i, _element) {
+ _element.style.cssText += ';min-height:' + height + ';_height:' + height;
+ // why can't we just use .css() ? i forget
+ });
+}
+
+
+
+/* Misc Utils
+-----------------------------------------------------------------------------*/
+
+
+//TODO: arraySlice
+//TODO: isFunction, grep ?
+
+
+function noop() { }
+
+
+function cmp(a, b) {
+ return a - b;
+}
+
+
+function arrayMax(a) {
+ return Math.max.apply(Math, a);
+}
+
+
+function zeroPad(n) {
+ return (n < 10 ? '0' : '') + n;
+}
+
+
+function smartProperty(obj, name) { // get a camel-cased/namespaced property of an object
+ if (obj[name] !== undefined) {
+ return obj[name];
+ }
+ var parts = name.split(/(?=[A-Z])/),
+ i=parts.length-1, res;
+ for (; i>=0; i--) {
+ res = obj[parts[i].toLowerCase()];
+ if (res !== undefined) {
+ return res;
+ }
+ }
+ return obj[''];
+}
+
+
+function htmlEscape(s) {
+ return s.replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/'/g, '&#039;')
+ .replace(/"/g, '&quot;')
+ .replace(/\n/g, '<br />');
+}
+
+
+function cssKey(_element) {
+ return _element.id + '/' + _element.className + '/' + _element.style.cssText.replace(/(^|;)\s*(top|left|width|height)\s*:[^;]*/ig, '');
+}
+
+
+function disableTextSelection(element) {
+ element
+ .attr('unselectable', 'on')
+ .css('MozUserSelect', 'none')
+ .bind('selectstart.ui', function() { return false; });
+}
+
+
+/*
+function enableTextSelection(element) {
+ element
+ .attr('unselectable', 'off')
+ .css('MozUserSelect', '')
+ .unbind('selectstart.ui');
+}
+*/
+
+
+function markFirstLast(e) {
+ e.children()
+ .removeClass('fc-first fc-last')
+ .filter(':first-child')
+ .addClass('fc-first')
+ .end()
+ .filter(':last-child')
+ .addClass('fc-last');
+}
+
+
+function setDayID(cell, date) {
+ cell.each(function(i, _cell) {
+ _cell.className = _cell.className.replace(/^fc-\w*/, 'fc-' + dayIDs[date.getDay()]);
+ // TODO: make a way that doesn't rely on order of classes
+ });
+}
+
+
+function getSkinCss(event, opt) {
+ var source = event.source || {};
+ var eventColor = event.color;
+ var sourceColor = source.color;
+ var optionColor = opt('eventColor');
+ var backgroundColor =
+ event.backgroundColor ||
+ eventColor ||
+ source.backgroundColor ||
+ sourceColor ||
+ opt('eventBackgroundColor') ||
+ optionColor;
+ var borderColor =
+ event.borderColor ||
+ eventColor ||
+ source.borderColor ||
+ sourceColor ||
+ opt('eventBorderColor') ||
+ optionColor;
+ var textColor =
+ event.textColor ||
+ source.textColor ||
+ opt('eventTextColor');
+ var statements = [];
+ if (backgroundColor) {
+ statements.push('background-color:' + backgroundColor);
+ }
+ if (borderColor) {
+ statements.push('border-color:' + borderColor);
+ }
+ if (textColor) {
+ statements.push('color:' + textColor);
+ }
+ return statements.join(';');
+}
+
+
+function applyAll(functions, thisObj, args) {
+ if ($.isFunction(functions)) {
+ functions = [ functions ];
+ }
+ if (functions) {
+ var i;
+ var ret;
+ for (i=0; i<functions.length; i++) {
+ ret = functions[i].apply(thisObj, args) || ret;
+ }
+ return ret;
+ }
+}
+
+
+function firstDefined() {
+ for (var i=0; i<arguments.length; i++) {
+ if (arguments[i] !== undefined) {
+ return arguments[i];
+ }
+ }
+}
+
+
+
+fcViews.month = MonthView;
+
+function MonthView(element, calendar) {
+ var t = this;
+
+
+ // exports
+ t.render = render;
+
+
+ // imports
+ BasicView.call(t, element, calendar, 'month');
+ var opt = t.opt;
+ var renderBasic = t.renderBasic;
+ var formatDate = calendar.formatDate;
+
+
+
+ function render(date, delta) {
+ if (delta) {
+ addMonths(date, delta);
+ date.setDate(1);
+ }
+ var start = cloneDate(date, true);
+ start.setDate(1);
+ var end = addMonths(cloneDate(start), 1);
+ var visStart = cloneDate(start);
+ var visEnd = cloneDate(end);
+ var firstDay = opt('firstDay');
+ var nwe = opt('weekends') ? 0 : 1;
+ if (nwe) {
+ skipWeekend(visStart);
+ skipWeekend(visEnd, -1, true);
+ }
+ addDays(visStart, -((visStart.getDay() - Math.max(firstDay, nwe) + 7) % 7));
+ addDays(visEnd, (7 - visEnd.getDay() + Math.max(firstDay, nwe)) % 7);
+ var rowCnt = Math.round((visEnd - visStart) / (DAY_MS * 7));
+ if (opt('weekMode') == 'fixed') {
+ addDays(visEnd, (6 - rowCnt) * 7);
+ rowCnt = 6;
+ }
+ t.title = formatDate(start, opt('titleFormat'));
+ t.start = start;
+ t.end = end;
+ t.visStart = visStart;
+ t.visEnd = visEnd;
+ renderBasic(6, rowCnt, nwe ? 5 : 7, true);
+ }
+
+
+}
+
+fcViews.basicWeek = BasicWeekView;
+
+function BasicWeekView(element, calendar) {
+ var t = this;
+
+
+ // exports
+ t.render = render;
+
+
+ // imports
+ BasicView.call(t, element, calendar, 'basicWeek');
+ var opt = t.opt;
+ var renderBasic = t.renderBasic;
+ var formatDates = calendar.formatDates;
+
+
+
+ function render(date, delta) {
+ if (delta) {
+ addDays(date, delta * 7);
+ }
+ var start = addDays(cloneDate(date), -((date.getDay() - opt('firstDay') + 7) % 7));
+ var end = addDays(cloneDate(start), 7);
+ var visStart = cloneDate(start);
+ var visEnd = cloneDate(end);
+ var weekends = opt('weekends');
+ if (!weekends) {
+ skipWeekend(visStart);
+ skipWeekend(visEnd, -1, true);
+ }
+ t.title = formatDates(
+ visStart,
+ addDays(cloneDate(visEnd), -1),
+ opt('titleFormat')
+ );
+ t.start = start;
+ t.end = end;
+ t.visStart = visStart;
+ t.visEnd = visEnd;
+ renderBasic(1, 1, weekends ? 7 : 5, false);
+ }
+
+
+}
+
+fcViews.basicDay = BasicDayView;
+
+//TODO: when calendar's date starts out on a weekend, shouldn't happen
+
+
+function BasicDayView(element, calendar) {
+ var t = this;
+
+
+ // exports
+ t.render = render;
+
+
+ // imports
+ BasicView.call(t, element, calendar, 'basicDay');
+ var opt = t.opt;
+ var renderBasic = t.renderBasic;
+ var formatDate = calendar.formatDate;
+
+
+
+ function render(date, delta) {
+ if (delta) {
+ addDays(date, delta);
+ if (!opt('weekends')) {
+ skipWeekend(date, delta < 0 ? -1 : 1);
+ }
+ }
+ t.title = formatDate(date, opt('titleFormat'));
+ t.start = t.visStart = cloneDate(date, true);
+ t.end = t.visEnd = addDays(cloneDate(t.start), 1);
+ renderBasic(1, 1, 1, false);
+ }
+
+
+}
+
+setDefaults({
+ weekMode: 'fixed'
+});
+
+
+function BasicView(element, calendar, viewName) {
+ var t = this;
+
+
+ // exports
+ t.renderBasic = renderBasic;
+ t.setHeight = setHeight;
+ t.setWidth = setWidth;
+ t.renderDayOverlay = renderDayOverlay;
+ t.defaultSelectionEnd = defaultSelectionEnd;
+ t.renderSelection = renderSelection;
+ t.clearSelection = clearSelection;
+ t.reportDayClick = reportDayClick; // for selection (kinda hacky)
+ t.dragStart = dragStart;
+ t.dragStop = dragStop;
+ t.defaultEventEnd = defaultEventEnd;
+ t.getHoverListener = function() { return hoverListener };
+ t.colContentLeft = colContentLeft;
+ t.colContentRight = colContentRight;
+ t.dayOfWeekCol = dayOfWeekCol;
+ t.dateCell = dateCell;
+ t.cellDate = cellDate;
+ t.cellIsAllDay = function() { return true };
+ t.allDayRow = allDayRow;
+ t.allDayBounds = allDayBounds;
+ t.getRowCnt = function() { return rowCnt };
+ t.getColCnt = function() { return colCnt };
+ t.getColWidth = function() { return colWidth };
+ t.getDaySegmentContainer = function() { return daySegmentContainer };
+
+
+ // imports
+ View.call(t, element, calendar, viewName);
+ OverlayManager.call(t);
+ SelectionManager.call(t);
+ BasicEventRenderer.call(t);
+ var opt = t.opt;
+ var trigger = t.trigger;
+ var clearEvents = t.clearEvents;
+ var renderOverlay = t.renderOverlay;
+ var clearOverlays = t.clearOverlays;
+ var daySelectionMousedown = t.daySelectionMousedown;
+ var formatDate = calendar.formatDate;
+
+
+ // locals
+
+ var head;
+ var headCells;
+ var body;
+ var bodyRows;
+ var bodyCells;
+ var bodyFirstCells;
+ var bodyCellTopInners;
+ var daySegmentContainer;
+
+ var viewWidth;
+ var viewHeight;
+ var colWidth;
+
+ var rowCnt, colCnt;
+ var coordinateGrid;
+ var hoverListener;
+ var colContentPositions;
+
+ var rtl, dis, dit;
+ var firstDay;
+ var nwe;
+ var tm;
+ var colFormat;
+
+
+
+ /* Rendering
+ ------------------------------------------------------------*/
+
+
+ disableTextSelection(element.addClass('fc-grid'));
+
+
+ function renderBasic(maxr, r, c, showNumbers) {
+ rowCnt = r;
+ colCnt = c;
+ updateOptions();
+ var firstTime = !body;
+ if (firstTime) {
+ buildSkeleton(maxr, showNumbers);
+ }else{
+ clearEvents();
+ }
+ updateCells(firstTime);
+ }
+
+
+
+ function updateOptions() {
+ rtl = opt('isRTL');
+ if (rtl) {
+ dis = -1;
+ dit = colCnt - 1;
+ }else{
+ dis = 1;
+ dit = 0;
+ }
+ firstDay = opt('firstDay');
+ nwe = opt('weekends') ? 0 : 1;
+ tm = opt('theme') ? 'ui' : 'fc';
+ colFormat = opt('columnFormat');
+ }
+
+
+
+ function buildSkeleton(maxRowCnt, showNumbers) {
+ var s;
+ var headerClass = tm + "-widget-header";
+ var contentClass = tm + "-widget-content";
+ var i, j;
+ var table;
+
+ s =
+ "<table class='fc-border-separate' style='width:100%' cellspacing='0'>" +
+ "<thead>" +
+ "<tr>";
+ for (i=0; i<colCnt; i++) {
+ s +=
+ "<th class='fc- " + headerClass + "'/>"; // need fc- for setDayID
+ }
+ s +=
+ "</tr>" +
+ "</thead>" +
+ "<tbody>";
+ for (i=0; i<maxRowCnt; i++) {
+ s +=
+ "<tr class='fc-week" + i + "'>";
+ for (j=0; j<colCnt; j++) {
+ s +=
+ "<td class='fc- " + contentClass + " fc-day" + (i*colCnt+j) + "'>" + // need fc- for setDayID
+ "<div>" +
+ (showNumbers ?
+ "<div class='fc-day-number'/>" :
+ ''
+ ) +
+ "<div class='fc-day-content'>" +
+ "<div style='position:relative'>&nbsp;</div>" +
+ "</div>" +
+ "</div>" +
+ "</td>";
+ }
+ s +=
+ "</tr>";
+ }
+ s +=
+ "</tbody>" +
+ "</table>";
+ table = $(s).appendTo(element);
+
+ head = table.find('thead');
+ headCells = head.find('th');
+ body = table.find('tbody');
+ bodyRows = body.find('tr');
+ bodyCells = body.find('td');
+ bodyFirstCells = bodyCells.filter(':first-child');
+ bodyCellTopInners = bodyRows.eq(0).find('div.fc-day-content div');
+
+ markFirstLast(head.add(head.find('tr'))); // marks first+last tr/th's
+ markFirstLast(bodyRows); // marks first+last td's
+ bodyRows.eq(0).addClass('fc-first'); // fc-last is done in updateCells
+
+ dayBind(bodyCells);
+
+ daySegmentContainer =
+ $("<div style='position:absolute;z-index:8;top:0;left:0'/>")
+ .appendTo(element);
+ }
+
+
+
+ function updateCells(firstTime) {
+ var dowDirty = firstTime || rowCnt == 1; // could the cells' day-of-weeks need updating?
+ var month = t.start.getMonth();
+ var today = clearTime(new Date());
+ var cell;
+ var date;
+ var row;
+
+ if (dowDirty) {
+ headCells.each(function(i, _cell) {
+ cell = $(_cell);
+ date = indexDate(i);
+ cell.html(formatDate(date, colFormat));
+ setDayID(cell, date);
+ });
+ }
+
+ bodyCells.each(function(i, _cell) {
+ cell = $(_cell);
+ date = indexDate(i);
+ if (date.getMonth() == month) {
+ cell.removeClass('fc-other-month');
+ }else{
+ cell.addClass('fc-other-month');
+ }
+ if (+date == +today) {
+ cell.addClass(tm + '-state-highlight fc-today');
+ }else{
+ cell.removeClass(tm + '-state-highlight fc-today');
+ }
+ cell.find('div.fc-day-number').text(date.getDate());
+ if (dowDirty) {
+ setDayID(cell, date);
+ }
+ });
+
+ bodyRows.each(function(i, _row) {
+ row = $(_row);
+ if (i < rowCnt) {
+ row.show();
+ if (i == rowCnt-1) {
+ row.addClass('fc-last');
+ }else{
+ row.removeClass('fc-last');
+ }
+ }else{
+ row.hide();
+ }
+ });
+ }
+
+
+
+ function setHeight(height) {
+ viewHeight = height;
+
+ var bodyHeight = viewHeight - head.height();
+ var rowHeight;
+ var rowHeightLast;
+ var cell;
+
+ if (opt('weekMode') == 'variable') {
+ rowHeight = rowHeightLast = Math.floor(bodyHeight / (rowCnt==1 ? 2 : 6));
+ }else{
+ rowHeight = Math.floor(bodyHeight / rowCnt);
+ rowHeightLast = bodyHeight - rowHeight * (rowCnt-1);
+ }
+
+ bodyFirstCells.each(function(i, _cell) {
+ if (i < rowCnt) {
+ cell = $(_cell);
+ setMinHeight(
+ cell.find('> div'),
+ (i==rowCnt-1 ? rowHeightLast : rowHeight) - vsides(cell)
+ );
+ }
+ });
+
+ }
+
+
+ function setWidth(width) {
+ viewWidth = width;
+ colContentPositions.clear();
+ colWidth = Math.floor(viewWidth / colCnt);
+ setOuterWidth(headCells.slice(0, -1), colWidth);
+ }
+
+
+
+ /* Day clicking and binding
+ -----------------------------------------------------------*/
+
+
+ function dayBind(days) {
+ days.click(dayClick)
+ .mousedown(daySelectionMousedown);
+ }
+
+
+ function dayClick(ev) {
+ if (!opt('selectable')) { // if selectable, SelectionManager will worry about dayClick
+ var index = parseInt(this.className.match(/fc\-day(\d+)/)[1]); // TODO: maybe use .data
+ var date = indexDate(index);
+ trigger('dayClick', this, date, true, ev);
+ }
+ }
+
+
+
+ /* Semi-transparent Overlay Helpers
+ ------------------------------------------------------*/
+
+
+ function renderDayOverlay(overlayStart, overlayEnd, refreshCoordinateGrid) { // overlayEnd is exclusive
+ if (refreshCoordinateGrid) {
+ coordinateGrid.build();
+ }
+ var rowStart = cloneDate(t.visStart);
+ var rowEnd = addDays(cloneDate(rowStart), colCnt);
+ for (var i=0; i<rowCnt; i++) {
+ var stretchStart = new Date(Math.max(rowStart, overlayStart));
+ var stretchEnd = new Date(Math.min(rowEnd, overlayEnd));
+ if (stretchStart < stretchEnd) {
+ var colStart, colEnd;
+ if (rtl) {
+ colStart = dayDiff(stretchEnd, rowStart)*dis+dit+1;
+ colEnd = dayDiff(stretchStart, rowStart)*dis+dit+1;
+ }else{
+ colStart = dayDiff(stretchStart, rowStart);
+ colEnd = dayDiff(stretchEnd, rowStart);
+ }
+ dayBind(
+ renderCellOverlay(i, colStart, i, colEnd-1)
+ );
+ }
+ addDays(rowStart, 7);
+ addDays(rowEnd, 7);
+ }
+ }
+
+
+ function renderCellOverlay(row0, col0, row1, col1) { // row1,col1 is inclusive
+ var rect = coordinateGrid.rect(row0, col0, row1, col1, element);
+ return renderOverlay(rect, element);
+ }
+
+
+
+ /* Selection
+ -----------------------------------------------------------------------*/
+
+
+ function defaultSelectionEnd(startDate, allDay) {
+ return cloneDate(startDate);
+ }
+
+
+ function renderSelection(startDate, endDate, allDay) {
+ renderDayOverlay(startDate, addDays(cloneDate(endDate), 1), true); // rebuild every time???
+ }
+
+
+ function clearSelection() {
+ clearOverlays();
+ }
+
+
+ function reportDayClick(date, allDay, ev) {
+ var cell = dateCell(date);
+ var _element = bodyCells[cell.row*colCnt + cell.col];
+ trigger('dayClick', _element, date, allDay, ev);
+ }
+
+
+
+ /* External Dragging
+ -----------------------------------------------------------------------*/
+
+
+ function dragStart(_dragElement, ev, ui) {
+ hoverListener.start(function(cell) {
+ clearOverlays();
+ if (cell) {
+ renderCellOverlay(cell.row, cell.col, cell.row, cell.col);
+ }
+ }, ev);
+ }
+
+
+ function dragStop(_dragElement, ev, ui) {
+ var cell = hoverListener.stop();
+ clearOverlays();
+ if (cell) {
+ var d = cellDate(cell);
+ trigger('drop', _dragElement, d, true, ev, ui);
+ }
+ }
+
+
+
+ /* Utilities
+ --------------------------------------------------------*/
+
+
+ function defaultEventEnd(event) {
+ return cloneDate(event.start);
+ }
+
+
+ coordinateGrid = new CoordinateGrid(function(rows, cols) {
+ var e, n, p;
+ headCells.each(function(i, _e) {
+ e = $(_e);
+ n = e.offset().left;
+ if (i) {
+ p[1] = n;
+ }
+ p = [n];
+ cols[i] = p;
+ });
+ p[1] = n + e.outerWidth();
+ bodyRows.each(function(i, _e) {
+ if (i < rowCnt) {
+ e = $(_e);
+ n = e.offset().top;
+ if (i) {
+ p[1] = n;
+ }
+ p = [n];
+ rows[i] = p;
+ }
+ });
+ p[1] = n + e.outerHeight();
+ });
+
+
+ hoverListener = new HoverListener(coordinateGrid);
+
+
+ colContentPositions = new HorizontalPositionCache(function(col) {
+ return bodyCellTopInners.eq(col);
+ });
+
+
+ function colContentLeft(col) {
+ return colContentPositions.left(col);
+ }
+
+
+ function colContentRight(col) {
+ return colContentPositions.right(col);
+ }
+
+
+
+
+ function dateCell(date) {
+ return {
+ row: Math.floor(dayDiff(date, t.visStart) / 7),
+ col: dayOfWeekCol(date.getDay())
+ };
+ }
+
+
+ function cellDate(cell) {
+ return _cellDate(cell.row, cell.col);
+ }
+
+
+ function _cellDate(row, col) {
+ return addDays(cloneDate(t.visStart), row*7 + col*dis+dit);
+ // what about weekends in middle of week?
+ }
+
+
+ function indexDate(index) {
+ return _cellDate(Math.floor(index/colCnt), index%colCnt);
+ }
+
+
+ function dayOfWeekCol(dayOfWeek) {
+ return ((dayOfWeek - Math.max(firstDay, nwe) + colCnt) % colCnt) * dis + dit;
+ }
+
+
+
+
+ function allDayRow(i) {
+ return bodyRows.eq(i);
+ }
+
+
+ function allDayBounds(i) {
+ return {
+ left: 0,
+ right: viewWidth
+ };
+ }
+
+
+}
+
+function BasicEventRenderer() {
+ var t = this;
+
+
+ // exports
+ t.renderEvents = renderEvents;
+ t.compileDaySegs = compileSegs; // for DayEventRenderer
+ t.clearEvents = clearEvents;
+ t.bindDaySeg = bindDaySeg;
+
+
+ // imports
+ DayEventRenderer.call(t);
+ var opt = t.opt;
+ var trigger = t.trigger;
+ //var setOverflowHidden = t.setOverflowHidden;
+ var isEventDraggable = t.isEventDraggable;
+ var isEventResizable = t.isEventResizable;
+ var reportEvents = t.reportEvents;
+ var reportEventClear = t.reportEventClear;
+ var eventElementHandlers = t.eventElementHandlers;
+ var showEvents = t.showEvents;
+ var hideEvents = t.hideEvents;
+ var eventDrop = t.eventDrop;
+ var getDaySegmentContainer = t.getDaySegmentContainer;
+ var getHoverListener = t.getHoverListener;
+ var renderDayOverlay = t.renderDayOverlay;
+ var clearOverlays = t.clearOverlays;
+ var getRowCnt = t.getRowCnt;
+ var getColCnt = t.getColCnt;
+ var renderDaySegs = t.renderDaySegs;
+ var resizableDayEvent = t.resizableDayEvent;
+
+
+
+ /* Rendering
+ --------------------------------------------------------------------*/
+
+
+ function renderEvents(events, modifiedEventId) {
+ reportEvents(events);
+ renderDaySegs(compileSegs(events), modifiedEventId);
+ }
+
+
+ function clearEvents() {
+ reportEventClear();
+ getDaySegmentContainer().empty();
+ }
+
+
+ function compileSegs(events) {
+ var rowCnt = getRowCnt(),
+ colCnt = getColCnt(),
+ d1 = cloneDate(t.visStart),
+ d2 = addDays(cloneDate(d1), colCnt),
+ visEventsEnds = $.map(events, exclEndDay),
+ i, row,
+ j, level,
+ k, seg,
+ segs=[];
+ for (i=0; i<rowCnt; i++) {
+ row = stackSegs(sliceSegs(events, visEventsEnds, d1, d2));
+ for (j=0; j<row.length; j++) {
+ level = row[j];
+ for (k=0; k<level.length; k++) {
+ seg = level[k];
+ seg.row = i;
+ seg.level = j; // not needed anymore
+ segs.push(seg);
+ }
+ }
+ addDays(d1, 7);
+ addDays(d2, 7);
+ }
+ return segs;
+ }
+
+
+ function bindDaySeg(event, eventElement, seg) {
+ if (isEventDraggable(event)) {
+ draggableDayEvent(event, eventElement);
+ }
+ if (seg.isEnd && isEventResizable(event)) {
+ resizableDayEvent(event, eventElement, seg);
+ }
+ eventElementHandlers(event, eventElement);
+ // needs to be after, because resizableDayEvent might stopImmediatePropagation on click
+ }
+
+
+
+ /* Dragging
+ ----------------------------------------------------------------------------*/
+
+
+ function draggableDayEvent(event, eventElement) {
+ var hoverListener = getHoverListener();
+ var dayDelta;
+ eventElement.draggable({
+ zIndex: 9,
+ delay: 50,
+ opacity: opt('dragOpacity'),
+ revertDuration: opt('dragRevertDuration'),
+ start: function(ev, ui) {
+ trigger('eventDragStart', eventElement, event, ev, ui);
+ hideEvents(event, eventElement);
+ hoverListener.start(function(cell, origCell, rowDelta, colDelta) {
+ eventElement.draggable('option', 'revert', !cell || !rowDelta && !colDelta);
+ clearOverlays();
+ if (cell) {
+ //setOverflowHidden(true);
+ dayDelta = rowDelta*7 + colDelta * (opt('isRTL') ? -1 : 1);
+ renderDayOverlay(
+ addDays(cloneDate(event.start), dayDelta),
+ addDays(exclEndDay(event), dayDelta)
+ );
+ }else{
+ //setOverflowHidden(false);
+ dayDelta = 0;
+ }
+ }, ev, 'drag');
+ },
+ stop: function(ev, ui) {
+ hoverListener.stop();
+ clearOverlays();
+ trigger('eventDragStop', eventElement, event, ev, ui);
+ if (dayDelta) {
+ eventDrop(this, event, dayDelta, 0, event.allDay, ev, ui);
+ }else{
+ eventElement.css('filter', ''); // clear IE opacity side-effects
+ showEvents(event, eventElement);
+ }
+ //setOverflowHidden(false);
+ }
+ });
+ }
+
+
+}
+
+fcViews.agendaWeek = AgendaWeekView;
+
+function AgendaWeekView(element, calendar) {
+ var t = this;
+
+
+ // exports
+ t.render = render;
+
+
+ // imports
+ AgendaView.call(t, element, calendar, 'agendaWeek');
+ var opt = t.opt;
+ var renderAgenda = t.renderAgenda;
+ var formatDates = calendar.formatDates;
+
+
+
+ function render(date, delta) {
+ if (delta) {
+ addDays(date, delta * 7);
+ }
+ var start = addDays(cloneDate(date), -((date.getDay() - opt('firstDay') + 7) % 7));
+ var end = addDays(cloneDate(start), 7);
+ var visStart = cloneDate(start);
+ var visEnd = cloneDate(end);
+ var weekends = opt('weekends');
+ if (!weekends) {
+ skipWeekend(visStart);
+ skipWeekend(visEnd, -1, true);
+ }
+ t.title = formatDates(
+ visStart,
+ addDays(cloneDate(visEnd), -1),
+ opt('titleFormat')
+ );
+ t.start = start;
+ t.end = end;
+ t.visStart = visStart;
+ t.visEnd = visEnd;
+ renderAgenda(weekends ? 7 : 5);
+ }
+
+
+}
+
+fcViews.agendaDay = AgendaDayView;
+
+function AgendaDayView(element, calendar) {
+ var t = this;
+
+
+ // exports
+ t.render = render;
+
+
+ // imports
+ AgendaView.call(t, element, calendar, 'agendaDay');
+ var opt = t.opt;
+ var renderAgenda = t.renderAgenda;
+ var formatDate = calendar.formatDate;
+
+
+
+ function render(date, delta) {
+ if (delta) {
+ addDays(date, delta);
+ if (!opt('weekends')) {
+ skipWeekend(date, delta < 0 ? -1 : 1);
+ }
+ }
+ var start = cloneDate(date, true);
+ var end = addDays(cloneDate(start), 1);
+ t.title = formatDate(date, opt('titleFormat'));
+ t.start = t.visStart = start;
+ t.end = t.visEnd = end;
+ renderAgenda(1);
+ }
+
+
+}
+
+setDefaults({
+ allDaySlot: true,
+ allDayText: 'all-day',
+ firstHour: 6,
+ slotMinutes: 30,
+ defaultEventMinutes: 120,
+ axisFormat: 'h(:mm)tt',
+ timeFormat: {
+ agenda: 'h:mm{ - h:mm}'
+ },
+ dragOpacity: {
+ agenda: .5
+ },
+ minTime: 0,
+ maxTime: 24
+});
+
+
+// TODO: make it work in quirks mode (event corners, all-day height)
+// TODO: test liquid width, especially in IE6
+
+
+function AgendaView(element, calendar, viewName) {
+ var t = this;
+
+
+ // exports
+ t.renderAgenda = renderAgenda;
+ t.setWidth = setWidth;
+ t.setHeight = setHeight;
+ t.beforeHide = beforeHide;
+ t.afterShow = afterShow;
+ t.defaultEventEnd = defaultEventEnd;
+ t.timePosition = timePosition;
+ t.dayOfWeekCol = dayOfWeekCol;
+ t.dateCell = dateCell;
+ t.cellDate = cellDate;
+ t.cellIsAllDay = cellIsAllDay;
+ t.allDayRow = getAllDayRow;
+ t.allDayBounds = allDayBounds;
+ t.getHoverListener = function() { return hoverListener };
+ t.colContentLeft = colContentLeft;
+ t.colContentRight = colContentRight;
+ t.getDaySegmentContainer = function() { return daySegmentContainer };
+ t.getSlotSegmentContainer = function() { return slotSegmentContainer };
+ t.getMinMinute = function() { return minMinute };
+ t.getMaxMinute = function() { return maxMinute };
+ t.getBodyContent = function() { return slotContent }; // !!??
+ t.getRowCnt = function() { return 1 };
+ t.getColCnt = function() { return colCnt };
+ t.getColWidth = function() { return colWidth };
+ t.getSlotHeight = function() { return slotHeight };
+ t.defaultSelectionEnd = defaultSelectionEnd;
+ t.renderDayOverlay = renderDayOverlay;
+ t.renderSelection = renderSelection;
+ t.clearSelection = clearSelection;
+ t.reportDayClick = reportDayClick; // selection mousedown hack
+ t.dragStart = dragStart;
+ t.dragStop = dragStop;
+
+
+ // imports
+ View.call(t, element, calendar, viewName);
+ OverlayManager.call(t);
+ SelectionManager.call(t);
+ AgendaEventRenderer.call(t);
+ var opt = t.opt;
+ var trigger = t.trigger;
+ var clearEvents = t.clearEvents;
+ var renderOverlay = t.renderOverlay;
+ var clearOverlays = t.clearOverlays;
+ var reportSelection = t.reportSelection;
+ var unselect = t.unselect;
+ var daySelectionMousedown = t.daySelectionMousedown;
+ var slotSegHtml = t.slotSegHtml;
+ var formatDate = calendar.formatDate;
+
+
+ // locals
+
+ var dayTable;
+ var dayHead;
+ var dayHeadCells;
+ var dayBody;
+ var dayBodyCells;
+ var dayBodyCellInners;
+ var dayBodyFirstCell;
+ var dayBodyFirstCellStretcher;
+ var slotLayer;
+ var daySegmentContainer;
+ var allDayTable;
+ var allDayRow;
+ var slotScroller;
+ var slotContent;
+ var slotSegmentContainer;
+ var slotTable;
+ var slotTableFirstInner;
+ var axisFirstCells;
+ var gutterCells;
+ var selectionHelper;
+
+ var viewWidth;
+ var viewHeight;
+ var axisWidth;
+ var colWidth;
+ var gutterWidth;
+ var slotHeight; // TODO: what if slotHeight changes? (see issue 650)
+ var savedScrollTop;
+
+ var colCnt;
+ var slotCnt;
+ var coordinateGrid;
+ var hoverListener;
+ var colContentPositions;
+ var slotTopCache = {};
+
+ var tm;
+ var firstDay;
+ var nwe; // no weekends (int)
+ var rtl, dis, dit; // day index sign / translate
+ var minMinute, maxMinute;
+ var colFormat;
+
+
+
+ /* Rendering
+ -----------------------------------------------------------------------------*/
+
+
+ disableTextSelection(element.addClass('fc-agenda'));
+
+
+ function renderAgenda(c) {
+ colCnt = c;
+ updateOptions();
+ if (!dayTable) {
+ buildSkeleton();
+ }else{
+ clearEvents();
+ }
+ updateCells();
+ }
+
+
+
+ function updateOptions() {
+ tm = opt('theme') ? 'ui' : 'fc';
+ nwe = opt('weekends') ? 0 : 1;
+ firstDay = opt('firstDay');
+ if (rtl = opt('isRTL')) {
+ dis = -1;
+ dit = colCnt - 1;
+ }else{
+ dis = 1;
+ dit = 0;
+ }
+ minMinute = parseTime(opt('minTime'));
+ maxMinute = parseTime(opt('maxTime'));
+ colFormat = opt('columnFormat');
+ }
+
+
+
+ function buildSkeleton() {
+ var headerClass = tm + "-widget-header";
+ var contentClass = tm + "-widget-content";
+ var s;
+ var i;
+ var d;
+ var maxd;
+ var minutes;
+ var slotNormal = opt('slotMinutes') % 15 == 0;
+
+ s =
+ "<table style='width:100%' class='fc-agenda-days fc-border-separate' cellspacing='0'>" +
+ "<thead>" +
+ "<tr>" +
+ "<th class='fc-agenda-axis " + headerClass + "'>&nbsp;</th>";
+ for (i=0; i<colCnt; i++) {
+ s +=
+ "<th class='fc- fc-col" + i + ' ' + headerClass + "'/>"; // fc- needed for setDayID
+ }
+ s +=
+ "<th class='fc-agenda-gutter " + headerClass + "'>&nbsp;</th>" +
+ "</tr>" +
+ "</thead>" +
+ "<tbody>" +
+ "<tr>" +
+ "<th class='fc-agenda-axis " + headerClass + "'>&nbsp;</th>";
+ for (i=0; i<colCnt; i++) {
+ s +=
+ "<td class='fc- fc-col" + i + ' ' + contentClass + "'>" + // fc- needed for setDayID
+ "<div>" +
+ "<div class='fc-day-content'>" +
+ "<div style='position:relative'>&nbsp;</div>" +
+ "</div>" +
+ "</div>" +
+ "</td>";
+ }
+ s +=
+ "<td class='fc-agenda-gutter " + contentClass + "'>&nbsp;</td>" +
+ "</tr>" +
+ "</tbody>" +
+ "</table>";
+ dayTable = $(s).appendTo(element);
+ dayHead = dayTable.find('thead');
+ dayHeadCells = dayHead.find('th').slice(1, -1);
+ dayBody = dayTable.find('tbody');
+ dayBodyCells = dayBody.find('td').slice(0, -1);
+ dayBodyCellInners = dayBodyCells.find('div.fc-day-content div');
+ dayBodyFirstCell = dayBodyCells.eq(0);
+ dayBodyFirstCellStretcher = dayBodyFirstCell.find('> div');
+
+ markFirstLast(dayHead.add(dayHead.find('tr')));
+ markFirstLast(dayBody.add(dayBody.find('tr')));
+
+ axisFirstCells = dayHead.find('th:first');
+ gutterCells = dayTable.find('.fc-agenda-gutter');
+
+ slotLayer =
+ $("<div style='position:absolute;z-index:2;left:0;width:100%'/>")
+ .appendTo(element);
+
+ if (opt('allDaySlot')) {
+
+ daySegmentContainer =
+ $("<div style='position:absolute;z-index:8;top:0;left:0'/>")
+ .appendTo(slotLayer);
+
+ s =
+ "<table style='width:100%' class='fc-agenda-allday' cellspacing='0'>" +
+ "<tr>" +
+ "<th class='" + headerClass + " fc-agenda-axis'>" + opt('allDayText') + "</th>" +
+ "<td>" +
+ "<div class='fc-day-content'><div style='position:relative'/></div>" +
+ "</td>" +
+ "<th class='" + headerClass + " fc-agenda-gutter'>&nbsp;</th>" +
+ "</tr>" +
+ "</table>";
+ allDayTable = $(s).appendTo(slotLayer);
+ allDayRow = allDayTable.find('tr');
+
+ dayBind(allDayRow.find('td'));
+
+ axisFirstCells = axisFirstCells.add(allDayTable.find('th:first'));
+ gutterCells = gutterCells.add(allDayTable.find('th.fc-agenda-gutter'));
+
+ slotLayer.append(
+ "<div class='fc-agenda-divider " + headerClass + "'>" +
+ "<div class='fc-agenda-divider-inner'/>" +
+ "</div>"
+ );
+
+ }else{
+
+ daySegmentContainer = $([]); // in jQuery 1.4, we can just do $()
+
+ }
+
+ slotScroller =
+ $("<div style='position:absolute;width:100%;overflow-x:hidden;overflow-y:auto'/>")
+ .appendTo(slotLayer);
+
+ slotContent =
+ $("<div style='position:relative;width:100%;overflow:hidden'/>")
+ .appendTo(slotScroller);
+
+ slotSegmentContainer =
+ $("<div style='position:absolute;z-index:8;top:0;left:0'/>")
+ .appendTo(slotContent);
+
+ s =
+ "<table class='fc-agenda-slots' style='width:100%' cellspacing='0'>" +
+ "<tbody>";
+ d = zeroDate();
+ maxd = addMinutes(cloneDate(d), maxMinute);
+ addMinutes(d, minMinute);
+ slotCnt = 0;
+ for (i=0; d < maxd; i++) {
+ minutes = d.getMinutes();
+ s +=
+ "<tr class='fc-slot" + i + ' ' + (!minutes ? '' : 'fc-minor') + "'>" +
+ "<th class='fc-agenda-axis " + headerClass + "'>" +
+ ((!slotNormal || !minutes) ? formatDate(d, opt('axisFormat')) : '&nbsp;') +
+ "</th>" +
+ "<td class='" + contentClass + "'>" +
+ "<div style='position:relative'>&nbsp;</div>" +
+ "</td>" +
+ "</tr>";
+ addMinutes(d, opt('slotMinutes'));
+ slotCnt++;
+ }
+ s +=
+ "</tbody>" +
+ "</table>";
+ slotTable = $(s).appendTo(slotContent);
+ slotTableFirstInner = slotTable.find('div:first');
+
+ slotBind(slotTable.find('td'));
+
+ axisFirstCells = axisFirstCells.add(slotTable.find('th:first'));
+ }
+
+
+
+ function updateCells() {
+ var i;
+ var headCell;
+ var bodyCell;
+ var date;
+ var today = clearTime(new Date());
+ for (i=0; i<colCnt; i++) {
+ date = colDate(i);
+ headCell = dayHeadCells.eq(i);
+ headCell.html(formatDate(date, colFormat));
+ bodyCell = dayBodyCells.eq(i);
+ if (+date == +today) {
+ bodyCell.addClass(tm + '-state-highlight fc-today');
+ }else{
+ bodyCell.removeClass(tm + '-state-highlight fc-today');
+ }
+ setDayID(headCell.add(bodyCell), date);
+ }
+ }
+
+
+
+ function setHeight(height, dateChanged) {
+ if (height === undefined) {
+ height = viewHeight;
+ }
+ viewHeight = height;
+ slotTopCache = {};
+
+ var headHeight = dayBody.position().top;
+ var allDayHeight = slotScroller.position().top; // including divider
+ var bodyHeight = Math.min( // total body height, including borders
+ height - headHeight, // when scrollbars
+ slotTable.height() + allDayHeight + 1 // when no scrollbars. +1 for bottom border
+ );
+
+ dayBodyFirstCellStretcher
+ .height(bodyHeight - vsides(dayBodyFirstCell));
+
+ slotLayer.css('top', headHeight);
+
+ slotScroller.height(bodyHeight - allDayHeight - 1);
+
+ slotHeight = slotTableFirstInner.height() + 1; // +1 for border
+
+ if (dateChanged) {
+ resetScroll();
+ }
+ }
+
+
+
+ function setWidth(width) {
+ viewWidth = width;
+ colContentPositions.clear();
+
+ axisWidth = 0;
+ setOuterWidth(
+ axisFirstCells
+ .width('')
+ .each(function(i, _cell) {
+ axisWidth = Math.max(axisWidth, $(_cell).outerWidth());
+ }),
+ axisWidth
+ );
+
+ var slotTableWidth = slotScroller[0].clientWidth; // needs to be done after axisWidth (for IE7)
+ //slotTable.width(slotTableWidth);
+
+ gutterWidth = slotScroller.width() - slotTableWidth;
+ if (gutterWidth) {
+ setOuterWidth(gutterCells, gutterWidth);
+ gutterCells
+ .show()
+ .prev()
+ .removeClass('fc-last');
+ }else{
+ gutterCells
+ .hide()
+ .prev()
+ .addClass('fc-last');
+ }
+
+ colWidth = Math.floor((slotTableWidth - axisWidth) / colCnt);
+ setOuterWidth(dayHeadCells.slice(0, -1), colWidth);
+ }
+
+
+
+ function resetScroll() {
+ var d0 = zeroDate();
+ var scrollDate = cloneDate(d0);
+ scrollDate.setHours(opt('firstHour'));
+ var top = timePosition(d0, scrollDate) + 1; // +1 for the border
+ function scroll() {
+ slotScroller.scrollTop(top);
+ }
+ scroll();
+ setTimeout(scroll, 0); // overrides any previous scroll state made by the browser
+ }
+
+
+ function beforeHide() {
+ savedScrollTop = slotScroller.scrollTop();
+ }
+
+
+ function afterShow() {
+ slotScroller.scrollTop(savedScrollTop);
+ }
+
+
+
+ /* Slot/Day clicking and binding
+ -----------------------------------------------------------------------*/
+
+
+ function dayBind(cells) {
+ cells.click(slotClick)
+ .mousedown(daySelectionMousedown);
+ }
+
+
+ function slotBind(cells) {
+ cells.click(slotClick)
+ .mousedown(slotSelectionMousedown);
+ }
+
+
+ function slotClick(ev) {
+ if (!opt('selectable')) { // if selectable, SelectionManager will worry about dayClick
+ var col = Math.min(colCnt-1, Math.floor((ev.pageX - dayTable.offset().left - axisWidth) / colWidth));
+ var date = colDate(col);
+ var rowMatch = this.parentNode.className.match(/fc-slot(\d+)/); // TODO: maybe use data
+ if (rowMatch) {
+ var mins = parseInt(rowMatch[1]) * opt('slotMinutes');
+ var hours = Math.floor(mins/60);
+ date.setHours(hours);
+ date.setMinutes(mins%60 + minMinute);
+ trigger('dayClick', dayBodyCells[col], date, false, ev);
+ }else{
+ trigger('dayClick', dayBodyCells[col], date, true, ev);
+ }
+ }
+ }
+
+
+
+ /* Semi-transparent Overlay Helpers
+ -----------------------------------------------------*/
+
+
+ function renderDayOverlay(startDate, endDate, refreshCoordinateGrid) { // endDate is exclusive
+ if (refreshCoordinateGrid) {
+ coordinateGrid.build();
+ }
+ var visStart = cloneDate(t.visStart);
+ var startCol, endCol;
+ if (rtl) {
+ startCol = dayDiff(endDate, visStart)*dis+dit+1;
+ endCol = dayDiff(startDate, visStart)*dis+dit+1;
+ }else{
+ startCol = dayDiff(startDate, visStart);
+ endCol = dayDiff(endDate, visStart);
+ }
+ startCol = Math.max(0, startCol);
+ endCol = Math.min(colCnt, endCol);
+ if (startCol < endCol) {
+ dayBind(
+ renderCellOverlay(0, startCol, 0, endCol-1)
+ );
+ }
+ }
+
+
+ function renderCellOverlay(row0, col0, row1, col1) { // only for all-day?
+ var rect = coordinateGrid.rect(row0, col0, row1, col1, slotLayer);
+ return renderOverlay(rect, slotLayer);
+ }
+
+
+ function renderSlotOverlay(overlayStart, overlayEnd) {
+ var dayStart = cloneDate(t.visStart);
+ var dayEnd = addDays(cloneDate(dayStart), 1);
+ for (var i=0; i<colCnt; i++) {
+ var stretchStart = new Date(Math.max(dayStart, overlayStart));
+ var stretchEnd = new Date(Math.min(dayEnd, overlayEnd));
+ if (stretchStart < stretchEnd) {
+ var col = i*dis+dit;
+ var rect = coordinateGrid.rect(0, col, 0, col, slotContent); // only use it for horizontal coords
+ var top = timePosition(dayStart, stretchStart);
+ var bottom = timePosition(dayStart, stretchEnd);
+ rect.top = top;
+ rect.height = bottom - top;
+ slotBind(
+ renderOverlay(rect, slotContent)
+ );
+ }
+ addDays(dayStart, 1);
+ addDays(dayEnd, 1);
+ }
+ }
+
+
+
+ /* Coordinate Utilities
+ -----------------------------------------------------------------------------*/
+
+
+ coordinateGrid = new CoordinateGrid(function(rows, cols) {
+ var e, n, p;
+ dayHeadCells.each(function(i, _e) {
+ e = $(_e);
+ n = e.offset().left;
+ if (i) {
+ p[1] = n;
+ }
+ p = [n];
+ cols[i] = p;
+ });
+ p[1] = n + e.outerWidth();
+ if (opt('allDaySlot')) {
+ e = allDayRow;
+ n = e.offset().top;
+ rows[0] = [n, n+e.outerHeight()];
+ }
+ var slotTableTop = slotContent.offset().top;
+ var slotScrollerTop = slotScroller.offset().top;
+ var slotScrollerBottom = slotScrollerTop + slotScroller.outerHeight();
+ function constrain(n) {
+ return Math.max(slotScrollerTop, Math.min(slotScrollerBottom, n));
+ }
+ for (var i=0; i<slotCnt; i++) {
+ rows.push([
+ constrain(slotTableTop + slotHeight*i),
+ constrain(slotTableTop + slotHeight*(i+1))
+ ]);
+ }
+ });
+
+
+ hoverListener = new HoverListener(coordinateGrid);
+
+
+ colContentPositions = new HorizontalPositionCache(function(col) {
+ return dayBodyCellInners.eq(col);
+ });
+
+
+ function colContentLeft(col) {
+ return colContentPositions.left(col);
+ }
+
+
+ function colContentRight(col) {
+ return colContentPositions.right(col);
+ }
+
+
+
+
+ function dateCell(date) { // "cell" terminology is now confusing
+ return {
+ row: Math.floor(dayDiff(date, t.visStart) / 7),
+ col: dayOfWeekCol(date.getDay())
+ };
+ }
+
+
+ function cellDate(cell) {
+ var d = colDate(cell.col);
+ var slotIndex = cell.row;
+ if (opt('allDaySlot')) {
+ slotIndex--;
+ }
+ if (slotIndex >= 0) {
+ addMinutes(d, minMinute + slotIndex * opt('slotMinutes'));
+ }
+ return d;
+ }
+
+
+ function colDate(col) { // returns dates with 00:00:00
+ return addDays(cloneDate(t.visStart), col*dis+dit);
+ }
+
+
+ function cellIsAllDay(cell) {
+ return opt('allDaySlot') && !cell.row;
+ }
+
+
+ function dayOfWeekCol(dayOfWeek) {
+ return ((dayOfWeek - Math.max(firstDay, nwe) + colCnt) % colCnt)*dis+dit;
+ }
+
+
+
+
+ // get the Y coordinate of the given time on the given day (both Date objects)
+ function timePosition(day, time) { // both date objects. day holds 00:00 of current day
+ day = cloneDate(day, true);
+ if (time < addMinutes(cloneDate(day), minMinute)) {
+ return 0;
+ }
+ if (time >= addMinutes(cloneDate(day), maxMinute)) {
+ return slotTable.height();
+ }
+ var slotMinutes = opt('slotMinutes'),
+ minutes = time.getHours()*60 + time.getMinutes() - minMinute,
+ slotI = Math.floor(minutes / slotMinutes),
+ slotTop = slotTopCache[slotI];
+ if (slotTop === undefined) {
+ slotTop = slotTopCache[slotI] = slotTable.find('tr:eq(' + slotI + ') td div')[0].offsetTop; //.position().top; // need this optimization???
+ }
+ return Math.max(0, Math.round(
+ slotTop - 1 + slotHeight * ((minutes % slotMinutes) / slotMinutes)
+ ));
+ }
+
+
+ function allDayBounds() {
+ return {
+ left: axisWidth,
+ right: viewWidth - gutterWidth
+ }
+ }
+
+
+ function getAllDayRow(index) {
+ return allDayRow;
+ }
+
+
+ function defaultEventEnd(event) {
+ var start = cloneDate(event.start);
+ if (event.allDay) {
+ return start;
+ }
+ return addMinutes(start, opt('defaultEventMinutes'));
+ }
+
+
+
+ /* Selection
+ ---------------------------------------------------------------------------------*/
+
+
+ function defaultSelectionEnd(startDate, allDay) {
+ if (allDay) {
+ return cloneDate(startDate);
+ }
+ return addMinutes(cloneDate(startDate), opt('slotMinutes'));
+ }
+
+
+ function renderSelection(startDate, endDate, allDay) { // only for all-day
+ if (allDay) {
+ if (opt('allDaySlot')) {
+ renderDayOverlay(startDate, addDays(cloneDate(endDate), 1), true);
+ }
+ }else{
+ renderSlotSelection(startDate, endDate);
+ }
+ }
+
+
+ function renderSlotSelection(startDate, endDate) {
+ var helperOption = opt('selectHelper');
+ coordinateGrid.build();
+ if (helperOption) {
+ var col = dayDiff(startDate, t.visStart) * dis + dit;
+ if (col >= 0 && col < colCnt) { // only works when times are on same day
+ var rect = coordinateGrid.rect(0, col, 0, col, slotContent); // only for horizontal coords
+ var top = timePosition(startDate, startDate);
+ var bottom = timePosition(startDate, endDate);
+ if (bottom > top) { // protect against selections that are entirely before or after visible range
+ rect.top = top;
+ rect.height = bottom - top;
+ rect.left += 2;
+ rect.width -= 5;
+ if ($.isFunction(helperOption)) {
+ var helperRes = helperOption(startDate, endDate);
+ if (helperRes) {
+ rect.position = 'absolute';
+ rect.zIndex = 8;
+ selectionHelper = $(helperRes)
+ .css(rect)
+ .appendTo(slotContent);
+ }
+ }else{
+ rect.isStart = true; // conside rect a "seg" now
+ rect.isEnd = true; //
+ selectionHelper = $(slotSegHtml(
+ {
+ title: '',
+ start: startDate,
+ end: endDate,
+ className: ['fc-select-helper'],
+ editable: false
+ },
+ rect
+ ));
+ selectionHelper.css('opacity', opt('dragOpacity'));
+ }
+ if (selectionHelper) {
+ slotBind(selectionHelper);
+ slotContent.append(selectionHelper);
+ setOuterWidth(selectionHelper, rect.width, true); // needs to be after appended
+ setOuterHeight(selectionHelper, rect.height, true);
+ }
+ }
+ }
+ }else{
+ renderSlotOverlay(startDate, endDate);
+ }
+ }
+
+
+ function clearSelection() {
+ clearOverlays();
+ if (selectionHelper) {
+ selectionHelper.remove();
+ selectionHelper = null;
+ }
+ }
+
+
+ function slotSelectionMousedown(ev) {
+ if (ev.which == 1 && opt('selectable')) { // ev.which==1 means left mouse button
+ unselect(ev);
+ var dates;
+ hoverListener.start(function(cell, origCell) {
+ clearSelection();
+ if (cell && cell.col == origCell.col && !cellIsAllDay(cell)) {
+ var d1 = cellDate(origCell);
+ var d2 = cellDate(cell);
+ dates = [
+ d1,
+ addMinutes(cloneDate(d1), opt('slotMinutes')),
+ d2,
+ addMinutes(cloneDate(d2), opt('slotMinutes'))
+ ].sort(cmp);
+ renderSlotSelection(dates[0], dates[3]);
+ }else{
+ dates = null;
+ }
+ }, ev);
+ $(document).one('mouseup', function(ev) {
+ hoverListener.stop();
+ if (dates) {
+ if (+dates[0] == +dates[1]) {
+ reportDayClick(dates[0], false, ev);
+ }
+ reportSelection(dates[0], dates[3], false, ev);
+ }
+ });
+ }
+ }
+
+
+ function reportDayClick(date, allDay, ev) {
+ trigger('dayClick', dayBodyCells[dayOfWeekCol(date.getDay())], date, allDay, ev);
+ }
+
+
+
+ /* External Dragging
+ --------------------------------------------------------------------------------*/
+
+
+ function dragStart(_dragElement, ev, ui) {
+ hoverListener.start(function(cell) {
+ clearOverlays();
+ if (cell) {
+ if (cellIsAllDay(cell)) {
+ renderCellOverlay(cell.row, cell.col, cell.row, cell.col);
+ }else{
+ var d1 = cellDate(cell);
+ var d2 = addMinutes(cloneDate(d1), opt('defaultEventMinutes'));
+ renderSlotOverlay(d1, d2);
+ }
+ }
+ }, ev);
+ }
+
+
+ function dragStop(_dragElement, ev, ui) {
+ var cell = hoverListener.stop();
+ clearOverlays();
+ if (cell) {
+ trigger('drop', _dragElement, cellDate(cell), cellIsAllDay(cell), ev, ui);
+ }
+ }
+
+
+}
+
+function AgendaEventRenderer() {
+ var t = this;
+
+
+ // exports
+ t.renderEvents = renderEvents;
+ t.compileDaySegs = compileDaySegs; // for DayEventRenderer
+ t.clearEvents = clearEvents;
+ t.slotSegHtml = slotSegHtml;
+ t.bindDaySeg = bindDaySeg;
+
+
+ // imports
+ DayEventRenderer.call(t);
+ var opt = t.opt;
+ var trigger = t.trigger;
+ //var setOverflowHidden = t.setOverflowHidden;
+ var isEventDraggable = t.isEventDraggable;
+ var isEventResizable = t.isEventResizable;
+ var eventEnd = t.eventEnd;
+ var reportEvents = t.reportEvents;
+ var reportEventClear = t.reportEventClear;
+ var eventElementHandlers = t.eventElementHandlers;
+ var setHeight = t.setHeight;
+ var getDaySegmentContainer = t.getDaySegmentContainer;
+ var getSlotSegmentContainer = t.getSlotSegmentContainer;
+ var getHoverListener = t.getHoverListener;
+ var getMaxMinute = t.getMaxMinute;
+ var getMinMinute = t.getMinMinute;
+ var timePosition = t.timePosition;
+ var colContentLeft = t.colContentLeft;
+ var colContentRight = t.colContentRight;
+ var renderDaySegs = t.renderDaySegs;
+ var resizableDayEvent = t.resizableDayEvent; // TODO: streamline binding architecture
+ var getColCnt = t.getColCnt;
+ var getColWidth = t.getColWidth;
+ var getSlotHeight = t.getSlotHeight;
+ var getBodyContent = t.getBodyContent;
+ var reportEventElement = t.reportEventElement;
+ var showEvents = t.showEvents;
+ var hideEvents = t.hideEvents;
+ var eventDrop = t.eventDrop;
+ var eventResize = t.eventResize;
+ var renderDayOverlay = t.renderDayOverlay;
+ var clearOverlays = t.clearOverlays;
+ var calendar = t.calendar;
+ var formatDate = calendar.formatDate;
+ var formatDates = calendar.formatDates;
+
+
+
+ /* Rendering
+ ----------------------------------------------------------------------------*/
+
+
+ function renderEvents(events, modifiedEventId) {
+ reportEvents(events);
+ var i, len=events.length,
+ dayEvents=[],
+ slotEvents=[];
+ for (i=0; i<len; i++) {
+ if (events[i].allDay) {
+ dayEvents.push(events[i]);
+ }else{
+ slotEvents.push(events[i]);
+ }
+ }
+ if (opt('allDaySlot')) {
+ renderDaySegs(compileDaySegs(dayEvents), modifiedEventId);
+ setHeight(); // no params means set to viewHeight
+ }
+ renderSlotSegs(compileSlotSegs(slotEvents), modifiedEventId);
+ }
+
+
+ function clearEvents() {
+ reportEventClear();
+ getDaySegmentContainer().empty();
+ getSlotSegmentContainer().empty();
+ }
+
+
+ function compileDaySegs(events) {
+ var levels = stackSegs(sliceSegs(events, $.map(events, exclEndDay), t.visStart, t.visEnd)),
+ i, levelCnt=levels.length, level,
+ j, seg,
+ segs=[];
+ for (i=0; i<levelCnt; i++) {
+ level = levels[i];
+ for (j=0; j<level.length; j++) {
+ seg = level[j];
+ seg.row = 0;
+ seg.level = i; // not needed anymore
+ segs.push(seg);
+ }
+ }
+ return segs;
+ }
+
+
+ function compileSlotSegs(events) {
+ var colCnt = getColCnt(),
+ minMinute = getMinMinute(),
+ maxMinute = getMaxMinute(),
+ d = addMinutes(cloneDate(t.visStart), minMinute),
+ visEventEnds = $.map(events, slotEventEnd),
+ i, col,
+ j, level,
+ k, seg,
+ segs=[];
+ for (i=0; i<colCnt; i++) {
+ col = stackSegs(sliceSegs(events, visEventEnds, d, addMinutes(cloneDate(d), maxMinute-minMinute)));
+ countForwardSegs(col);
+ for (j=0; j<col.length; j++) {
+ level = col[j];
+ for (k=0; k<level.length; k++) {
+ seg = level[k];
+ seg.col = i;
+ seg.level = j;
+ segs.push(seg);
+ }
+ }
+ addDays(d, 1, true);
+ }
+ return segs;
+ }
+
+
+ function slotEventEnd(event) {
+ if (event.end) {
+ return cloneDate(event.end);
+ }else{
+ return addMinutes(cloneDate(event.start), opt('defaultEventMinutes'));
+ }
+ }
+
+
+ // renders events in the 'time slots' at the bottom
+
+ function renderSlotSegs(segs, modifiedEventId) {
+
+ var i, segCnt=segs.length, seg,
+ event,
+ classes,
+ top, bottom,
+ colI, levelI, forward,
+ leftmost,
+ availWidth,
+ outerWidth,
+ left,
+ html='',
+ eventElements,
+ eventElement,
+ triggerRes,
+ vsideCache={},
+ hsideCache={},
+ key, val,
+ contentElement,
+ height,
+ slotSegmentContainer = getSlotSegmentContainer(),
+ rtl, dis, dit,
+ colCnt = getColCnt();
+
+ if (rtl = opt('isRTL')) {
+ dis = -1;
+ dit = colCnt - 1;
+ }else{
+ dis = 1;
+ dit = 0;
+ }
+
+ // calculate position/dimensions, create html
+ for (i=0; i<segCnt; i++) {
+ seg = segs[i];
+ event = seg.event;
+ top = timePosition(seg.start, seg.start);
+ bottom = timePosition(seg.start, seg.end);
+ colI = seg.col;
+ levelI = seg.level;
+ forward = seg.forward || 0;
+ leftmost = colContentLeft(colI*dis + dit);
+ availWidth = colContentRight(colI*dis + dit) - leftmost;
+ availWidth = Math.min(availWidth-6, availWidth*.95); // TODO: move this to CSS
+ if (levelI) {
+ // indented and thin
+ outerWidth = availWidth / (levelI + forward + 1);
+ }else{
+ if (forward) {
+ // moderately wide, aligned left still
+ outerWidth = ((availWidth / (forward + 1)) - (12/2)) * 2; // 12 is the predicted width of resizer =
+ }else{
+ // can be entire width, aligned left
+ outerWidth = availWidth;
+ }
+ }
+ left = leftmost + // leftmost possible
+ (availWidth / (levelI + forward + 1) * levelI) // indentation
+ * dis + (rtl ? availWidth - outerWidth : 0); // rtl
+ seg.top = top;
+ seg.left = left;
+ seg.outerWidth = outerWidth;
+ seg.outerHeight = bottom - top;
+ html += slotSegHtml(event, seg);
+ }
+ slotSegmentContainer[0].innerHTML = html; // faster than html()
+ eventElements = slotSegmentContainer.children();
+
+ // retrieve elements, run through eventRender callback, bind event handlers
+ for (i=0; i<segCnt; i++) {
+ seg = segs[i];
+ event = seg.event;
+ eventElement = $(eventElements[i]); // faster than eq()
+ triggerRes = trigger('eventRender', event, event, eventElement);
+ if (triggerRes === false) {
+ eventElement.remove();
+ }else{
+ if (triggerRes && triggerRes !== true) {
+ eventElement.remove();
+ eventElement = $(triggerRes)
+ .css({
+ position: 'absolute',
+ top: seg.top,
+ left: seg.left
+ })
+ .appendTo(slotSegmentContainer);
+ }
+ seg.element = eventElement;
+ if (event._id === modifiedEventId) {
+ bindSlotSeg(event, eventElement, seg);
+ }else{
+ eventElement[0]._fci = i; // for lazySegBind
+ }
+ reportEventElement(event, eventElement);
+ }
+ }
+
+ lazySegBind(slotSegmentContainer, segs, bindSlotSeg);
+
+ // record event sides and title positions
+ for (i=0; i<segCnt; i++) {
+ seg = segs[i];
+ if (eventElement = seg.element) {
+ val = vsideCache[key = seg.key = cssKey(eventElement[0])];
+ seg.vsides = val === undefined ? (vsideCache[key] = vsides(eventElement, true)) : val;
+ val = hsideCache[key];
+ seg.hsides = val === undefined ? (hsideCache[key] = hsides(eventElement, true)) : val;
+ contentElement = eventElement.find('div.fc-event-content');
+ if (contentElement.length) {
+ seg.contentTop = contentElement[0].offsetTop;
+ }
+ }
+ }
+
+ // set all positions/dimensions at once
+ for (i=0; i<segCnt; i++) {
+ seg = segs[i];
+ if (eventElement = seg.element) {
+ eventElement[0].style.width = Math.max(0, seg.outerWidth - seg.hsides) + 'px';
+ height = Math.max(0, seg.outerHeight - seg.vsides);
+ eventElement[0].style.height = height + 'px';
+ event = seg.event;
+ if (seg.contentTop !== undefined && height - seg.contentTop < 10) {
+ // not enough room for title, put it in the time header
+ eventElement.find('div.fc-event-time')
+ .text(formatDate(event.start, opt('timeFormat')) + ' - ' + event.title);
+ eventElement.find('div.fc-event-title')
+ .remove();
+ }
+ trigger('eventAfterRender', event, event, eventElement);
+ }
+ }
+
+ }
+
+
+ function slotSegHtml(event, seg) {
+ var html = "<";
+ var url = event.url;
+ var skinCss = getSkinCss(event, opt);
+ var skinCssAttr = (skinCss ? " style='" + skinCss + "'" : '');
+ var classes = ['fc-event', 'fc-event-skin', 'fc-event-vert'];
+ if (isEventDraggable(event)) {
+ classes.push('fc-event-draggable');
+ }
+ if (seg.isStart) {
+ classes.push('fc-corner-top');
+ }
+ if (seg.isEnd) {
+ classes.push('fc-corner-bottom');
+ }
+ classes = classes.concat(event.className);
+ if (event.source) {
+ classes = classes.concat(event.source.className || []);
+ }
+ if (url) {
+ html += "a href='" + htmlEscape(event.url) + "'";
+ }else{
+ html += "div";
+ }
+ html +=
+ " class='" + classes.join(' ') + "'" +
+ " style='position:absolute;z-index:8;top:" + seg.top + "px;left:" + seg.left + "px;" + skinCss + "'" +
+ ">" +
+ "<div class='fc-event-inner fc-event-skin'" + skinCssAttr + ">" +
+ "<div class='fc-event-head fc-event-skin'" + skinCssAttr + ">" +
+ "<div class='fc-event-time'>" +
+ htmlEscape(formatDates(event.start, event.end, opt('timeFormat'))) +
+ "</div>" +
+ "</div>" +
+ "<div class='fc-event-content'>" +
+ "<div class='fc-event-title'>" +
+ htmlEscape(event.title) +
+ "</div>" +
+ "</div>" +
+ "<div class='fc-event-bg'></div>" +
+ "</div>"; // close inner
+ if (seg.isEnd && isEventResizable(event)) {
+ html +=
+ "<div class='ui-resizable-handle ui-resizable-s'>=</div>";
+ }
+ html +=
+ "</" + (url ? "a" : "div") + ">";
+ return html;
+ }
+
+
+ function bindDaySeg(event, eventElement, seg) {
+ if (isEventDraggable(event)) {
+ draggableDayEvent(event, eventElement, seg.isStart);
+ }
+ if (seg.isEnd && isEventResizable(event)) {
+ resizableDayEvent(event, eventElement, seg);
+ }
+ eventElementHandlers(event, eventElement);
+ // needs to be after, because resizableDayEvent might stopImmediatePropagation on click
+ }
+
+
+ function bindSlotSeg(event, eventElement, seg) {
+ var timeElement = eventElement.find('div.fc-event-time');
+ if (isEventDraggable(event)) {
+ draggableSlotEvent(event, eventElement, timeElement);
+ }
+ if (seg.isEnd && isEventResizable(event)) {
+ resizableSlotEvent(event, eventElement, timeElement);
+ }
+ eventElementHandlers(event, eventElement);
+ }
+
+
+
+ /* Dragging
+ -----------------------------------------------------------------------------------*/
+
+
+ // when event starts out FULL-DAY
+
+ function draggableDayEvent(event, eventElement, isStart) {
+ var origWidth;
+ var revert;
+ var allDay=true;
+ var dayDelta;
+ var dis = opt('isRTL') ? -1 : 1;
+ var hoverListener = getHoverListener();
+ var colWidth = getColWidth();
+ var slotHeight = getSlotHeight();
+ var minMinute = getMinMinute();
+ eventElement.draggable({
+ zIndex: 9,
+ opacity: opt('dragOpacity', 'month'), // use whatever the month view was using
+ revertDuration: opt('dragRevertDuration'),
+ start: function(ev, ui) {
+ trigger('eventDragStart', eventElement, event, ev, ui);
+ hideEvents(event, eventElement);
+ origWidth = eventElement.width();
+ hoverListener.start(function(cell, origCell, rowDelta, colDelta) {
+ clearOverlays();
+ if (cell) {
+ //setOverflowHidden(true);
+ revert = false;
+ dayDelta = colDelta * dis;
+ if (!cell.row) {
+ // on full-days
+ renderDayOverlay(
+ addDays(cloneDate(event.start), dayDelta),
+ addDays(exclEndDay(event), dayDelta)
+ );
+ resetElement();
+ }else{
+ // mouse is over bottom slots
+ if (isStart) {
+ if (allDay) {
+ // convert event to temporary slot-event
+ eventElement.width(colWidth - 10); // don't use entire width
+ setOuterHeight(
+ eventElement,
+ slotHeight * Math.round(
+ (event.end ? ((event.end - event.start) / MINUTE_MS) : opt('defaultEventMinutes'))
+ / opt('slotMinutes')
+ )
+ );
+ eventElement.draggable('option', 'grid', [colWidth, 1]);
+ allDay = false;
+ }
+ }else{
+ revert = true;
+ }
+ }
+ revert = revert || (allDay && !dayDelta);
+ }else{
+ resetElement();
+ //setOverflowHidden(false);
+ revert = true;
+ }
+ eventElement.draggable('option', 'revert', revert);
+ }, ev, 'drag');
+ },
+ stop: function(ev, ui) {
+ hoverListener.stop();
+ clearOverlays();
+ trigger('eventDragStop', eventElement, event, ev, ui);
+ if (revert) {
+ // hasn't moved or is out of bounds (draggable has already reverted)
+ resetElement();
+ eventElement.css('filter', ''); // clear IE opacity side-effects
+ showEvents(event, eventElement);
+ }else{
+ // changed!
+ var minuteDelta = 0;
+ if (!allDay) {
+ minuteDelta = Math.round((eventElement.offset().top - getBodyContent().offset().top) / slotHeight)
+ * opt('slotMinutes')
+ + minMinute
+ - (event.start.getHours() * 60 + event.start.getMinutes());
+ }
+ eventDrop(this, event, dayDelta, minuteDelta, allDay, ev, ui);
+ }
+ //setOverflowHidden(false);
+ }
+ });
+ function resetElement() {
+ if (!allDay) {
+ eventElement
+ .width(origWidth)
+ .height('')
+ .draggable('option', 'grid', null);
+ allDay = true;
+ }
+ }
+ }
+
+
+ // when event starts out IN TIMESLOTS
+
+ function draggableSlotEvent(event, eventElement, timeElement) {
+ var origPosition;
+ var allDay=false;
+ var dayDelta;
+ var minuteDelta;
+ var prevMinuteDelta;
+ var dis = opt('isRTL') ? -1 : 1;
+ var hoverListener = getHoverListener();
+ var colCnt = getColCnt();
+ var colWidth = getColWidth();
+ var slotHeight = getSlotHeight();
+ eventElement.draggable({
+ zIndex: 9,
+ scroll: false,
+ grid: [colWidth, slotHeight],
+ axis: colCnt==1 ? 'y' : false,
+ opacity: opt('dragOpacity'),
+ revertDuration: opt('dragRevertDuration'),
+ start: function(ev, ui) {
+ trigger('eventDragStart', eventElement, event, ev, ui);
+ hideEvents(event, eventElement);
+ origPosition = eventElement.position();
+ minuteDelta = prevMinuteDelta = 0;
+ hoverListener.start(function(cell, origCell, rowDelta, colDelta) {
+ eventElement.draggable('option', 'revert', !cell);
+ clearOverlays();
+ if (cell) {
+ dayDelta = colDelta * dis;
+ if (opt('allDaySlot') && !cell.row) {
+ // over full days
+ if (!allDay) {
+ // convert to temporary all-day event
+ allDay = true;
+ timeElement.hide();
+ eventElement.draggable('option', 'grid', null);
+ }
+ renderDayOverlay(
+ addDays(cloneDate(event.start), dayDelta),
+ addDays(exclEndDay(event), dayDelta)
+ );
+ }else{
+ // on slots
+ resetElement();
+ }
+ }
+ }, ev, 'drag');
+ },
+ drag: function(ev, ui) {
+ minuteDelta = Math.round((ui.position.top - origPosition.top) / slotHeight) * opt('slotMinutes');
+ if (minuteDelta != prevMinuteDelta) {
+ if (!allDay) {
+ updateTimeText(minuteDelta);
+ }
+ prevMinuteDelta = minuteDelta;
+ }
+ },
+ stop: function(ev, ui) {
+ var cell = hoverListener.stop();
+ clearOverlays();
+ trigger('eventDragStop', eventElement, event, ev, ui);
+ if (cell && (dayDelta || minuteDelta || allDay)) {
+ // changed!
+ eventDrop(this, event, dayDelta, allDay ? 0 : minuteDelta, allDay, ev, ui);
+ }else{
+ // either no change or out-of-bounds (draggable has already reverted)
+ resetElement();
+ eventElement.css('filter', ''); // clear IE opacity side-effects
+ eventElement.css(origPosition); // sometimes fast drags make event revert to wrong position
+ updateTimeText(0);
+ showEvents(event, eventElement);
+ }
+ }
+ });
+ function updateTimeText(minuteDelta) {
+ var newStart = addMinutes(cloneDate(event.start), minuteDelta);
+ var newEnd;
+ if (event.end) {
+ newEnd = addMinutes(cloneDate(event.end), minuteDelta);
+ }
+ timeElement.text(formatDates(newStart, newEnd, opt('timeFormat')));
+ }
+ function resetElement() {
+ // convert back to original slot-event
+ if (allDay) {
+ timeElement.css('display', ''); // show() was causing display=inline
+ eventElement.draggable('option', 'grid', [colWidth, slotHeight]);
+ allDay = false;
+ }
+ }
+ }
+
+
+
+ /* Resizing
+ --------------------------------------------------------------------------------------*/
+
+
+ function resizableSlotEvent(event, eventElement, timeElement) {
+ var slotDelta, prevSlotDelta;
+ var slotHeight = getSlotHeight();
+ eventElement.resizable({
+ handles: {
+ s: 'div.ui-resizable-s'
+ },
+ grid: slotHeight,
+ start: function(ev, ui) {
+ slotDelta = prevSlotDelta = 0;
+ hideEvents(event, eventElement);
+ eventElement.css('z-index', 9);
+ trigger('eventResizeStart', this, event, ev, ui);
+ },
+ resize: function(ev, ui) {
+ // don't rely on ui.size.height, doesn't take grid into account
+ slotDelta = Math.round((Math.max(slotHeight, eventElement.height()) - ui.originalSize.height) / slotHeight);
+ if (slotDelta != prevSlotDelta) {
+ timeElement.text(
+ formatDates(
+ event.start,
+ (!slotDelta && !event.end) ? null : // no change, so don't display time range
+ addMinutes(eventEnd(event), opt('slotMinutes')*slotDelta),
+ opt('timeFormat')
+ )
+ );
+ prevSlotDelta = slotDelta;
+ }
+ },
+ stop: function(ev, ui) {
+ trigger('eventResizeStop', this, event, ev, ui);
+ if (slotDelta) {
+ eventResize(this, event, 0, opt('slotMinutes')*slotDelta, ev, ui);
+ }else{
+ eventElement.css('z-index', 8);
+ showEvents(event, eventElement);
+ // BUG: if event was really short, need to put title back in span
+ }
+ }
+ });
+ }
+
+
+}
+
+
+function countForwardSegs(levels) {
+ var i, j, k, level, segForward, segBack;
+ for (i=levels.length-1; i>0; i--) {
+ level = levels[i];
+ for (j=0; j<level.length; j++) {
+ segForward = level[j];
+ for (k=0; k<levels[i-1].length; k++) {
+ segBack = levels[i-1][k];
+ if (segsCollide(segForward, segBack)) {
+ segBack.forward = Math.max(segBack.forward||0, (segForward.forward||0)+1);
+ }
+ }
+ }
+ }
+}
+
+
+
+
+function View(element, calendar, viewName) {
+ var t = this;
+
+
+ // exports
+ t.element = element;
+ t.calendar = calendar;
+ t.name = viewName;
+ t.opt = opt;
+ t.trigger = trigger;
+ //t.setOverflowHidden = setOverflowHidden;
+ t.isEventDraggable = isEventDraggable;
+ t.isEventResizable = isEventResizable;
+ t.reportEvents = reportEvents;
+ t.eventEnd = eventEnd;
+ t.reportEventElement = reportEventElement;
+ t.reportEventClear = reportEventClear;
+ t.eventElementHandlers = eventElementHandlers;
+ t.showEvents = showEvents;
+ t.hideEvents = hideEvents;
+ t.eventDrop = eventDrop;
+ t.eventResize = eventResize;
+ // t.title
+ // t.start, t.end
+ // t.visStart, t.visEnd
+
+
+ // imports
+ var defaultEventEnd = t.defaultEventEnd;
+ var normalizeEvent = calendar.normalizeEvent; // in EventManager
+ var reportEventChange = calendar.reportEventChange;
+
+
+ // locals
+ var eventsByID = {};
+ var eventElements = [];
+ var eventElementsByID = {};
+ var options = calendar.options;
+
+
+
+ function opt(name, viewNameOverride) {
+ var v = options[name];
+ if (typeof v == 'object') {
+ return smartProperty(v, viewNameOverride || viewName);
+ }
+ return v;
+ }
+
+
+ function trigger(name, thisObj) {
+ return calendar.trigger.apply(
+ calendar,
+ [name, thisObj || t].concat(Array.prototype.slice.call(arguments, 2), [t])
+ );
+ }
+
+
+ /*
+ function setOverflowHidden(bool) {
+ element.css('overflow', bool ? 'hidden' : '');
+ }
+ */
+
+
+ function isEventDraggable(event) {
+ return isEventEditable(event) && !opt('disableDragging');
+ }
+
+
+ function isEventResizable(event) { // but also need to make sure the seg.isEnd == true
+ return isEventEditable(event) && !opt('disableResizing');
+ }
+
+
+ function isEventEditable(event) {
+ return firstDefined(event.editable, (event.source || {}).editable, opt('editable'));
+ }
+
+
+
+ /* Event Data
+ ------------------------------------------------------------------------------*/
+
+
+ // report when view receives new events
+ function reportEvents(events) { // events are already normalized at this point
+ eventsByID = {};
+ var i, len=events.length, event;
+ for (i=0; i<len; i++) {
+ event = events[i];
+ if (eventsByID[event._id]) {
+ eventsByID[event._id].push(event);
+ }else{
+ eventsByID[event._id] = [event];
+ }
+ }
+ }
+
+
+ // returns a Date object for an event's end
+ function eventEnd(event) {
+ return event.end ? cloneDate(event.end) : defaultEventEnd(event);
+ }
+
+
+
+ /* Event Elements
+ ------------------------------------------------------------------------------*/
+
+
+ // report when view creates an element for an event
+ function reportEventElement(event, element) {
+ eventElements.push(element);
+ if (eventElementsByID[event._id]) {
+ eventElementsByID[event._id].push(element);
+ }else{
+ eventElementsByID[event._id] = [element];
+ }
+ }
+
+
+ function reportEventClear() {
+ eventElements = [];
+ eventElementsByID = {};
+ }
+
+
+ // attaches eventClick, eventMouseover, eventMouseout
+ function eventElementHandlers(event, eventElement) {
+ eventElement
+ .click(function(ev) {
+ if (!eventElement.hasClass('ui-draggable-dragging') &&
+ !eventElement.hasClass('ui-resizable-resizing')) {
+ return trigger('eventClick', this, event, ev);
+ }
+ })
+ .hover(
+ function(ev) {
+ trigger('eventMouseover', this, event, ev);
+ },
+ function(ev) {
+ trigger('eventMouseout', this, event, ev);
+ }
+ );
+ // TODO: don't fire eventMouseover/eventMouseout *while* dragging is occuring (on subject element)
+ // TODO: same for resizing
+ }
+
+
+ function showEvents(event, exceptElement) {
+ eachEventElement(event, exceptElement, 'show');
+ }
+
+
+ function hideEvents(event, exceptElement) {
+ eachEventElement(event, exceptElement, 'hide');
+ }
+
+
+ function eachEventElement(event, exceptElement, funcName) {
+ var elements = eventElementsByID[event._id],
+ i, len = elements.length;
+ for (i=0; i<len; i++) {
+ if (!exceptElement || elements[i][0] != exceptElement[0]) {
+ elements[i][funcName]();
+ }
+ }
+ }
+
+
+
+ /* Event Modification Reporting
+ ---------------------------------------------------------------------------------*/
+
+
+ function eventDrop(e, event, dayDelta, minuteDelta, allDay, ev, ui) {
+ var oldAllDay = event.allDay;
+ var eventId = event._id;
+ moveEvents(eventsByID[eventId], dayDelta, minuteDelta, allDay);
+ trigger(
+ 'eventDrop',
+ e,
+ event,
+ dayDelta,
+ minuteDelta,
+ allDay,
+ function() {
+ // TODO: investigate cases where this inverse technique might not work
+ moveEvents(eventsByID[eventId], -dayDelta, -minuteDelta, oldAllDay);
+ reportEventChange(eventId);
+ },
+ ev,
+ ui
+ );
+ reportEventChange(eventId);
+ }
+
+
+ function eventResize(e, event, dayDelta, minuteDelta, ev, ui) {
+ var eventId = event._id;
+ elongateEvents(eventsByID[eventId], dayDelta, minuteDelta);
+ trigger(
+ 'eventResize',
+ e,
+ event,
+ dayDelta,
+ minuteDelta,
+ function() {
+ // TODO: investigate cases where this inverse technique might not work
+ elongateEvents(eventsByID[eventId], -dayDelta, -minuteDelta);
+ reportEventChange(eventId);
+ },
+ ev,
+ ui
+ );
+ reportEventChange(eventId);
+ }
+
+
+
+ /* Event Modification Math
+ ---------------------------------------------------------------------------------*/
+
+
+ function moveEvents(events, dayDelta, minuteDelta, allDay) {
+ minuteDelta = minuteDelta || 0;
+ for (var e, len=events.length, i=0; i<len; i++) {
+ e = events[i];
+ if (allDay !== undefined) {
+ e.allDay = allDay;
+ }
+ addMinutes(addDays(e.start, dayDelta, true), minuteDelta);
+ if (e.end) {
+ e.end = addMinutes(addDays(e.end, dayDelta, true), minuteDelta);
+ }
+ normalizeEvent(e, options);
+ }
+ }
+
+
+ function elongateEvents(events, dayDelta, minuteDelta) {
+ minuteDelta = minuteDelta || 0;
+ for (var e, len=events.length, i=0; i<len; i++) {
+ e = events[i];
+ e.end = addMinutes(addDays(eventEnd(e), dayDelta, true), minuteDelta);
+ normalizeEvent(e, options);
+ }
+ }
+
+
+}
+
+function DayEventRenderer() {
+ var t = this;
+
+
+ // exports
+ t.renderDaySegs = renderDaySegs;
+ t.resizableDayEvent = resizableDayEvent;
+
+
+ // imports
+ var opt = t.opt;
+ var trigger = t.trigger;
+ var isEventDraggable = t.isEventDraggable;
+ var isEventResizable = t.isEventResizable;
+ var eventEnd = t.eventEnd;
+ var reportEventElement = t.reportEventElement;
+ var showEvents = t.showEvents;
+ var hideEvents = t.hideEvents;
+ var eventResize = t.eventResize;
+ var getRowCnt = t.getRowCnt;
+ var getColCnt = t.getColCnt;
+ var getColWidth = t.getColWidth;
+ var allDayRow = t.allDayRow;
+ var allDayBounds = t.allDayBounds;
+ var colContentLeft = t.colContentLeft;
+ var colContentRight = t.colContentRight;
+ var dayOfWeekCol = t.dayOfWeekCol;
+ var dateCell = t.dateCell;
+ var compileDaySegs = t.compileDaySegs;
+ var getDaySegmentContainer = t.getDaySegmentContainer;
+ var bindDaySeg = t.bindDaySeg; //TODO: streamline this
+ var formatDates = t.calendar.formatDates;
+ var renderDayOverlay = t.renderDayOverlay;
+ var clearOverlays = t.clearOverlays;
+ var clearSelection = t.clearSelection;
+
+
+
+ /* Rendering
+ -----------------------------------------------------------------------------*/
+
+
+ function renderDaySegs(segs, modifiedEventId) {
+ var segmentContainer = getDaySegmentContainer();
+ var rowDivs;
+ var rowCnt = getRowCnt();
+ var colCnt = getColCnt();
+ var i = 0;
+ var rowI;
+ var levelI;
+ var colHeights;
+ var j;
+ var segCnt = segs.length;
+ var seg;
+ var top;
+ var k;
+ segmentContainer[0].innerHTML = daySegHTML(segs); // faster than .html()
+ daySegElementResolve(segs, segmentContainer.children());
+ daySegElementReport(segs);
+ daySegHandlers(segs, segmentContainer, modifiedEventId);
+ daySegCalcHSides(segs);
+ daySegSetWidths(segs);
+ daySegCalcHeights(segs);
+ rowDivs = getRowDivs();
+ // set row heights, calculate event tops (in relation to row top)
+ for (rowI=0; rowI<rowCnt; rowI++) {
+ levelI = 0;
+ colHeights = [];
+ for (j=0; j<colCnt; j++) {
+ colHeights[j] = 0;
+ }
+ while (i<segCnt && (seg = segs[i]).row == rowI) {
+ // loop through segs in a row
+ top = arrayMax(colHeights.slice(seg.startCol, seg.endCol));
+ seg.top = top;
+ top += seg.outerHeight;
+ for (k=seg.startCol; k<seg.endCol; k++) {
+ colHeights[k] = top;
+ }
+ i++;
+ }
+ rowDivs[rowI].height(arrayMax(colHeights));
+ }
+ daySegSetTops(segs, getRowTops(rowDivs));
+ }
+
+
+ function renderTempDaySegs(segs, adjustRow, adjustTop) {
+ var tempContainer = $("<div/>");
+ var elements;
+ var segmentContainer = getDaySegmentContainer();
+ var i;
+ var segCnt = segs.length;
+ var element;
+ tempContainer[0].innerHTML = daySegHTML(segs); // faster than .html()
+ elements = tempContainer.children();
+ segmentContainer.append(elements);
+ daySegElementResolve(segs, elements);
+ daySegCalcHSides(segs);
+ daySegSetWidths(segs);
+ daySegCalcHeights(segs);
+ daySegSetTops(segs, getRowTops(getRowDivs()));
+ elements = [];
+ for (i=0; i<segCnt; i++) {
+ element = segs[i].element;
+ if (element) {
+ if (segs[i].row === adjustRow) {
+ element.css('top', adjustTop);
+ }
+ elements.push(element[0]);
+ }
+ }
+ return $(elements);
+ }
+
+
+ function daySegHTML(segs) { // also sets seg.left and seg.outerWidth
+ var rtl = opt('isRTL');
+ var i;
+ var segCnt=segs.length;
+ var seg;
+ var event;
+ var url;
+ var classes;
+ var bounds = allDayBounds();
+ var minLeft = bounds.left;
+ var maxLeft = bounds.right;
+ var leftCol;
+ var rightCol;
+ var left;
+ var right;
+ var skinCss;
+ var html = '';
+ // calculate desired position/dimensions, create html
+ for (i=0; i<segCnt; i++) {
+ seg = segs[i];
+ event = seg.event;
+ classes = ['fc-event', 'fc-event-skin', 'fc-event-hori'];
+ if (isEventDraggable(event)) {
+ classes.push('fc-event-draggable');
+ }
+ if (rtl) {
+ if (seg.isStart) {
+ classes.push('fc-corner-right');
+ }
+ if (seg.isEnd) {
+ classes.push('fc-corner-left');
+ }
+ leftCol = dayOfWeekCol(seg.end.getDay()-1);
+ rightCol = dayOfWeekCol(seg.start.getDay());
+ left = seg.isEnd ? colContentLeft(leftCol) : minLeft;
+ right = seg.isStart ? colContentRight(rightCol) : maxLeft;
+ }else{
+ if (seg.isStart) {
+ classes.push('fc-corner-left');
+ }
+ if (seg.isEnd) {
+ classes.push('fc-corner-right');
+ }
+ leftCol = dayOfWeekCol(seg.start.getDay());
+ rightCol = dayOfWeekCol(seg.end.getDay()-1);
+ left = seg.isStart ? colContentLeft(leftCol) : minLeft;
+ right = seg.isEnd ? colContentRight(rightCol) : maxLeft;
+ }
+ classes = classes.concat(event.className);
+ if (event.source) {
+ classes = classes.concat(event.source.className || []);
+ }
+ url = event.url;
+ skinCss = getSkinCss(event, opt);
+ if (url) {
+ html += "<a href='" + htmlEscape(url) + "'";
+ }else{
+ html += "<div";
+ }
+ html +=
+ " class='" + classes.join(' ') + "'" +
+ " style='position:absolute;z-index:8;left:"+left+"px;" + skinCss + "'" +
+ ">" +
+ "<div" +
+ " class='fc-event-inner fc-event-skin'" +
+ (skinCss ? " style='" + skinCss + "'" : '') +
+ ">";
+ if (!event.allDay && seg.isStart) {
+ html +=
+ "<span class='fc-event-time'>" +
+ htmlEscape(formatDates(event.start, event.end, opt('timeFormat'))) +
+ "</span>";
+ }
+ html +=
+ "<span class='fc-event-title'>" + htmlEscape(event.title) + "</span>" +
+ "</div>";
+ if (seg.isEnd && isEventResizable(event)) {
+ html +=
+ "<div class='ui-resizable-handle ui-resizable-" + (rtl ? 'w' : 'e') + "'>" +
+ "&nbsp;&nbsp;&nbsp;" + // makes hit area a lot better for IE6/7
+ "</div>";
+ }
+ html +=
+ "</" + (url ? "a" : "div" ) + ">";
+ seg.left = left;
+ seg.outerWidth = right - left;
+ seg.startCol = leftCol;
+ seg.endCol = rightCol + 1; // needs to be exclusive
+ }
+ return html;
+ }
+
+
+ function daySegElementResolve(segs, elements) { // sets seg.element
+ var i;
+ var segCnt = segs.length;
+ var seg;
+ var event;
+ var element;
+ var triggerRes;
+ for (i=0; i<segCnt; i++) {
+ seg = segs[i];
+ event = seg.event;
+ element = $(elements[i]); // faster than .eq()
+ triggerRes = trigger('eventRender', event, event, element);
+ if (triggerRes === false) {
+ element.remove();
+ }else{
+ if (triggerRes && triggerRes !== true) {
+ triggerRes = $(triggerRes)
+ .css({
+ position: 'absolute',
+ left: seg.left
+ });
+ element.replaceWith(triggerRes);
+ element = triggerRes;
+ }
+ seg.element = element;
+ }
+ }
+ }
+
+
+ function daySegElementReport(segs) {
+ var i;
+ var segCnt = segs.length;
+ var seg;
+ var element;
+ for (i=0; i<segCnt; i++) {
+ seg = segs[i];
+ element = seg.element;
+ if (element) {
+ reportEventElement(seg.event, element);
+ }
+ }
+ }
+
+
+ function daySegHandlers(segs, segmentContainer, modifiedEventId) {
+ var i;
+ var segCnt = segs.length;
+ var seg;
+ var element;
+ var event;
+ // retrieve elements, run through eventRender callback, bind handlers
+ for (i=0; i<segCnt; i++) {
+ seg = segs[i];
+ element = seg.element;
+ if (element) {
+ event = seg.event;
+ if (event._id === modifiedEventId) {
+ bindDaySeg(event, element, seg);
+ }else{
+ element[0]._fci = i; // for lazySegBind
+ }
+ }
+ }
+ lazySegBind(segmentContainer, segs, bindDaySeg);
+ }
+
+
+ function daySegCalcHSides(segs) { // also sets seg.key
+ var i;
+ var segCnt = segs.length;
+ var seg;
+ var element;
+ var key, val;
+ var hsideCache = {};
+ // record event horizontal sides
+ for (i=0; i<segCnt; i++) {
+ seg = segs[i];
+ element = seg.element;
+ if (element) {
+ key = seg.key = cssKey(element[0]);
+ val = hsideCache[key];
+ if (val === undefined) {
+ val = hsideCache[key] = hsides(element, true);
+ }
+ seg.hsides = val;
+ }
+ }
+ }
+
+
+ function daySegSetWidths(segs) {
+ var i;
+ var segCnt = segs.length;
+ var seg;
+ var element;
+ for (i=0; i<segCnt; i++) {
+ seg = segs[i];
+ element = seg.element;
+ if (element) {
+ element[0].style.width = Math.max(0, seg.outerWidth - seg.hsides) + 'px';
+ }
+ }
+ }
+
+
+ function daySegCalcHeights(segs) {
+ var i;
+ var segCnt = segs.length;
+ var seg;
+ var element;
+ var key, val;
+ var vmarginCache = {};
+ // record event heights
+ for (i=0; i<segCnt; i++) {
+ seg = segs[i];
+ element = seg.element;
+ if (element) {
+ key = seg.key; // created in daySegCalcHSides
+ val = vmarginCache[key];
+ if (val === undefined) {
+ val = vmarginCache[key] = vmargins(element);
+ }
+ seg.outerHeight = element[0].offsetHeight + val;
+ }
+ }
+ }
+
+
+ function getRowDivs() {
+ var i;
+ var rowCnt = getRowCnt();
+ var rowDivs = [];
+ for (i=0; i<rowCnt; i++) {
+ rowDivs[i] = allDayRow(i)
+ .find('td:first div.fc-day-content > div'); // optimal selector?
+ }
+ return rowDivs;
+ }
+
+
+ function getRowTops(rowDivs) {
+ var i;
+ var rowCnt = rowDivs.length;
+ var tops = [];
+ for (i=0; i<rowCnt; i++) {
+ tops[i] = rowDivs[i][0].offsetTop; // !!?? but this means the element needs position:relative if in a table cell!!!!
+ }
+ return tops;
+ }
+
+
+ function daySegSetTops(segs, rowTops) { // also triggers eventAfterRender
+ var i;
+ var segCnt = segs.length;
+ var seg;
+ var element;
+ var event;
+ for (i=0; i<segCnt; i++) {
+ seg = segs[i];
+ element = seg.element;
+ if (element) {
+ element[0].style.top = rowTops[seg.row] + (seg.top||0) + 'px';
+ event = seg.event;
+ trigger('eventAfterRender', event, event, element);
+ }
+ }
+ }
+
+
+
+ /* Resizing
+ -----------------------------------------------------------------------------------*/
+
+
+ function resizableDayEvent(event, element, seg) {
+ var rtl = opt('isRTL');
+ var direction = rtl ? 'w' : 'e';
+ var handle = element.find('div.ui-resizable-' + direction);
+ var isResizing = false;
+
+ // TODO: look into using jquery-ui mouse widget for this stuff
+ disableTextSelection(element); // prevent native <a> selection for IE
+ element
+ .mousedown(function(ev) { // prevent native <a> selection for others
+ ev.preventDefault();
+ })
+ .click(function(ev) {
+ if (isResizing) {
+ ev.preventDefault(); // prevent link from being visited (only method that worked in IE6)
+ ev.stopImmediatePropagation(); // prevent fullcalendar eventClick handler from being called
+ // (eventElementHandlers needs to be bound after resizableDayEvent)
+ }
+ });
+
+ handle.mousedown(function(ev) {
+ if (ev.which != 1) {
+ return; // needs to be left mouse button
+ }
+ isResizing = true;
+ var hoverListener = t.getHoverListener();
+ var rowCnt = getRowCnt();
+ var colCnt = getColCnt();
+ var dis = rtl ? -1 : 1;
+ var dit = rtl ? colCnt-1 : 0;
+ var elementTop = element.css('top');
+ var dayDelta;
+ var helpers;
+ var eventCopy = $.extend({}, event);
+ var minCell = dateCell(event.start);
+ clearSelection();
+ $('body')
+ .css('cursor', direction + '-resize')
+ .one('mouseup', mouseup);
+ trigger('eventResizeStart', this, event, ev);
+ hoverListener.start(function(cell, origCell) {
+ if (cell) {
+ var r = Math.max(minCell.row, cell.row);
+ var c = cell.col;
+ if (rowCnt == 1) {
+ r = 0; // hack for all-day area in agenda views
+ }
+ if (r == minCell.row) {
+ if (rtl) {
+ c = Math.min(minCell.col, c);
+ }else{
+ c = Math.max(minCell.col, c);
+ }
+ }
+ dayDelta = (r*7 + c*dis+dit) - (origCell.row*7 + origCell.col*dis+dit);
+ var newEnd = addDays(eventEnd(event), dayDelta, true);
+ if (dayDelta) {
+ eventCopy.end = newEnd;
+ var oldHelpers = helpers;
+ helpers = renderTempDaySegs(compileDaySegs([eventCopy]), seg.row, elementTop);
+ helpers.find('*').css('cursor', direction + '-resize');
+ if (oldHelpers) {
+ oldHelpers.remove();
+ }
+ hideEvents(event);
+ }else{
+ if (helpers) {
+ showEvents(event);
+ helpers.remove();
+ helpers = null;
+ }
+ }
+ clearOverlays();
+ renderDayOverlay(event.start, addDays(cloneDate(newEnd), 1)); // coordinate grid already rebuild at hoverListener.start
+ }
+ }, ev);
+
+ function mouseup(ev) {
+ trigger('eventResizeStop', this, event, ev);
+ $('body').css('cursor', '');
+ hoverListener.stop();
+ clearOverlays();
+ if (dayDelta) {
+ eventResize(this, event, dayDelta, 0, ev);
+ // event redraw will clear helpers
+ }
+ // otherwise, the drag handler already restored the old events
+
+ setTimeout(function() { // make this happen after the element's click event
+ isResizing = false;
+ },0);
+ }
+
+ });
+ }
+
+
+}
+
+//BUG: unselect needs to be triggered when events are dragged+dropped
+
+function SelectionManager() {
+ var t = this;
+
+
+ // exports
+ t.select = select;
+ t.unselect = unselect;
+ t.reportSelection = reportSelection;
+ t.daySelectionMousedown = daySelectionMousedown;
+
+
+ // imports
+ var opt = t.opt;
+ var trigger = t.trigger;
+ var defaultSelectionEnd = t.defaultSelectionEnd;
+ var renderSelection = t.renderSelection;
+ var clearSelection = t.clearSelection;
+
+
+ // locals
+ var selected = false;
+
+
+
+ // unselectAuto
+ if (opt('selectable') && opt('unselectAuto')) {
+ $(document).mousedown(function(ev) {
+ var ignore = opt('unselectCancel');
+ if (ignore) {
+ if ($(ev.target).parents(ignore).length) { // could be optimized to stop after first match
+ return;
+ }
+ }
+ unselect(ev);
+ });
+ }
+
+
+ function select(startDate, endDate, allDay) {
+ unselect();
+ if (!endDate) {
+ endDate = defaultSelectionEnd(startDate, allDay);
+ }
+ renderSelection(startDate, endDate, allDay);
+ reportSelection(startDate, endDate, allDay);
+ }
+
+
+ function unselect(ev) {
+ if (selected) {
+ selected = false;
+ clearSelection();
+ trigger('unselect', null, ev);
+ }
+ }
+
+
+ function reportSelection(startDate, endDate, allDay, ev) {
+ selected = true;
+ trigger('select', null, startDate, endDate, allDay, ev);
+ }
+
+
+ function daySelectionMousedown(ev) { // not really a generic manager method, oh well
+ var cellDate = t.cellDate;
+ var cellIsAllDay = t.cellIsAllDay;
+ var hoverListener = t.getHoverListener();
+ var reportDayClick = t.reportDayClick; // this is hacky and sort of weird
+ if (ev.which == 1 && opt('selectable')) { // which==1 means left mouse button
+ unselect(ev);
+ var _mousedownElement = this;
+ var dates;
+ hoverListener.start(function(cell, origCell) { // TODO: maybe put cellDate/cellIsAllDay info in cell
+ clearSelection();
+ if (cell && cellIsAllDay(cell)) {
+ dates = [ cellDate(origCell), cellDate(cell) ].sort(cmp);
+ renderSelection(dates[0], dates[1], true);
+ }else{
+ dates = null;
+ }
+ }, ev);
+ $(document).one('mouseup', function(ev) {
+ hoverListener.stop();
+ if (dates) {
+ if (+dates[0] == +dates[1]) {
+ reportDayClick(dates[0], true, ev);
+ }
+ reportSelection(dates[0], dates[1], true, ev);
+ }
+ });
+ }
+ }
+
+
+}
+
+function OverlayManager() {
+ var t = this;
+
+
+ // exports
+ t.renderOverlay = renderOverlay;
+ t.clearOverlays = clearOverlays;
+
+
+ // locals
+ var usedOverlays = [];
+ var unusedOverlays = [];
+
+
+ function renderOverlay(rect, parent) {
+ var e = unusedOverlays.shift();
+ if (!e) {
+ e = $("<div class='fc-cell-overlay' style='position:absolute;z-index:3'/>");
+ }
+ if (e[0].parentNode != parent[0]) {
+ e.appendTo(parent);
+ }
+ usedOverlays.push(e.css(rect).show());
+ return e;
+ }
+
+
+ function clearOverlays() {
+ var e;
+ while (e = usedOverlays.shift()) {
+ unusedOverlays.push(e.hide().unbind());
+ }
+ }
+
+
+}
+
+function CoordinateGrid(buildFunc) {
+
+ var t = this;
+ var rows;
+ var cols;
+
+
+ t.build = function() {
+ rows = [];
+ cols = [];
+ buildFunc(rows, cols);
+ };
+
+
+ t.cell = function(x, y) {
+ var rowCnt = rows.length;
+ var colCnt = cols.length;
+ var i, r=-1, c=-1;
+ for (i=0; i<rowCnt; i++) {
+ if (y >= rows[i][0] && y < rows[i][1]) {
+ r = i;
+ break;
+ }
+ }
+ for (i=0; i<colCnt; i++) {
+ if (x >= cols[i][0] && x < cols[i][1]) {
+ c = i;
+ break;
+ }
+ }
+ return (r>=0 && c>=0) ? { row:r, col:c } : null;
+ };
+
+
+ t.rect = function(row0, col0, row1, col1, originElement) { // row1,col1 is inclusive
+ var origin = originElement.offset();
+ return {
+ top: rows[row0][0] - origin.top,
+ left: cols[col0][0] - origin.left,
+ width: cols[col1][1] - cols[col0][0],
+ height: rows[row1][1] - rows[row0][0]
+ };
+ };
+
+}
+
+function HoverListener(coordinateGrid) {
+
+
+ var t = this;
+ var bindType;
+ var change;
+ var firstCell;
+ var cell;
+
+
+ t.start = function(_change, ev, _bindType) {
+ change = _change;
+ firstCell = cell = null;
+ coordinateGrid.build();
+ mouse(ev);
+ bindType = _bindType || 'mousemove';
+ $(document).bind(bindType, mouse);
+ };
+
+
+ function mouse(ev) {
+ _fixUIEvent(ev); // see below
+ var newCell = coordinateGrid.cell(ev.pageX, ev.pageY);
+ if (!newCell != !cell || newCell && (newCell.row != cell.row || newCell.col != cell.col)) {
+ if (newCell) {
+ if (!firstCell) {
+ firstCell = newCell;
+ }
+ change(newCell, firstCell, newCell.row-firstCell.row, newCell.col-firstCell.col);
+ }else{
+ change(newCell, firstCell);
+ }
+ cell = newCell;
+ }
+ }
+
+
+ t.stop = function() {
+ $(document).unbind(bindType, mouse);
+ return cell;
+ };
+
+
+}
+
+
+
+// this fix was only necessary for jQuery UI 1.8.16 (and jQuery 1.7 or 1.7.1)
+// upgrading to jQuery UI 1.8.17 (and using either jQuery 1.7 or 1.7.1) fixed the problem
+// but keep this in here for 1.8.16 users
+// and maybe remove it down the line
+
+function _fixUIEvent(event) { // for issue 1168
+ if (event.pageX === undefined) {
+ event.pageX = event.originalEvent.pageX;
+ event.pageY = event.originalEvent.pageY;
+ }
+}
+function HorizontalPositionCache(getElement) {
+
+ var t = this,
+ elements = {},
+ lefts = {},
+ rights = {};
+
+ function e(i) {
+ return elements[i] = elements[i] || getElement(i);
+ }
+
+ t.left = function(i) {
+ return lefts[i] = lefts[i] === undefined ? e(i).position().left : lefts[i];
+ };
+
+ t.right = function(i) {
+ return rights[i] = rights[i] === undefined ? t.left(i) + e(i).width() : rights[i];
+ };
+
+ t.clear = function() {
+ elements = {};
+ lefts = {};
+ rights = {};
+ };
+
+}
+
+})(jQuery);
diff --git a/library/fullcalendar/fullcalendar.min.js b/library/fullcalendar/fullcalendar.min.js
new file mode 100644
index 000000000..df37bdfd8
--- /dev/null
+++ b/library/fullcalendar/fullcalendar.min.js
@@ -0,0 +1,114 @@
+/*
+
+ FullCalendar v1.5.3
+ http://arshaw.com/fullcalendar/
+
+ Use fullcalendar.css for basic styling.
+ For event drag & drop, requires jQuery UI draggable.
+ For event resizing, requires jQuery UI resizable.
+
+ Copyright (c) 2011 Adam Shaw
+ Dual licensed under the MIT and GPL licenses, located in
+ MIT-LICENSE.txt and GPL-LICENSE.txt respectively.
+
+ Date: Mon Feb 6 22:40:40 2012 -0800
+
+*/
+(function(m,ma){function wb(a){m.extend(true,Ya,a)}function Yb(a,b,e){function d(k){if(E){u();q();na();S(k)}else f()}function f(){B=b.theme?"ui":"fc";a.addClass("fc");b.isRTL&&a.addClass("fc-rtl");b.theme&&a.addClass("ui-widget");E=m("<div class='fc-content' style='position:relative'/>").prependTo(a);C=new Zb(X,b);(P=C.render())&&a.prepend(P);y(b.defaultView);m(window).resize(oa);t()||g()}function g(){setTimeout(function(){!n.start&&t()&&S()},0)}function l(){m(window).unbind("resize",oa);C.destroy();
+E.remove();a.removeClass("fc fc-rtl ui-widget")}function j(){return i.offsetWidth!==0}function t(){return m("body")[0].offsetWidth!==0}function y(k){if(!n||k!=n.name){F++;pa();var D=n,Z;if(D){(D.beforeHide||xb)();Za(E,E.height());D.element.hide()}else Za(E,1);E.css("overflow","hidden");if(n=Y[k])n.element.show();else n=Y[k]=new Ja[k](Z=s=m("<div class='fc-view fc-view-"+k+"' style='position:absolute'/>").appendTo(E),X);D&&C.deactivateButton(D.name);C.activateButton(k);S();E.css("overflow","");D&&
+Za(E,1);Z||(n.afterShow||xb)();F--}}function S(k){if(j()){F++;pa();o===ma&&u();var D=false;if(!n.start||k||r<n.start||r>=n.end){n.render(r,k||0);fa(true);D=true}else if(n.sizeDirty){n.clearEvents();fa();D=true}else if(n.eventsDirty){n.clearEvents();D=true}n.sizeDirty=false;n.eventsDirty=false;ga(D);W=a.outerWidth();C.updateTitle(n.title);k=new Date;k>=n.start&&k<n.end?C.disableButton("today"):C.enableButton("today");F--;n.trigger("viewDisplay",i)}}function Q(){q();if(j()){u();fa();pa();n.clearEvents();
+n.renderEvents(J);n.sizeDirty=false}}function q(){m.each(Y,function(k,D){D.sizeDirty=true})}function u(){o=b.contentHeight?b.contentHeight:b.height?b.height-(P?P.height():0)-Sa(E):Math.round(E.width()/Math.max(b.aspectRatio,0.5))}function fa(k){F++;n.setHeight(o,k);if(s){s.css("position","relative");s=null}n.setWidth(E.width(),k);F--}function oa(){if(!F)if(n.start){var k=++v;setTimeout(function(){if(k==v&&!F&&j())if(W!=(W=a.outerWidth())){F++;Q();n.trigger("windowResize",i);F--}},200)}else g()}function ga(k){if(!b.lazyFetching||
+ya(n.visStart,n.visEnd))ra();else k&&da()}function ra(){K(n.visStart,n.visEnd)}function sa(k){J=k;da()}function ha(k){da(k)}function da(k){na();if(j()){n.clearEvents();n.renderEvents(J,k);n.eventsDirty=false}}function na(){m.each(Y,function(k,D){D.eventsDirty=true})}function ua(k,D,Z){n.select(k,D,Z===ma?true:Z)}function pa(){n&&n.unselect()}function U(){S(-1)}function ca(){S(1)}function ka(){gb(r,-1);S()}function qa(){gb(r,1);S()}function G(){r=new Date;S()}function p(k,D,Z){if(k instanceof Date)r=
+N(k);else yb(r,k,D,Z);S()}function L(k,D,Z){k!==ma&&gb(r,k);D!==ma&&hb(r,D);Z!==ma&&ba(r,Z);S()}function c(){return N(r)}function z(){return n}function H(k,D){if(D===ma)return b[k];if(k=="height"||k=="contentHeight"||k=="aspectRatio"){b[k]=D;Q()}}function T(k,D){if(b[k])return b[k].apply(D||i,Array.prototype.slice.call(arguments,2))}var X=this;X.options=b;X.render=d;X.destroy=l;X.refetchEvents=ra;X.reportEvents=sa;X.reportEventChange=ha;X.rerenderEvents=da;X.changeView=y;X.select=ua;X.unselect=pa;
+X.prev=U;X.next=ca;X.prevYear=ka;X.nextYear=qa;X.today=G;X.gotoDate=p;X.incrementDate=L;X.formatDate=function(k,D){return Oa(k,D,b)};X.formatDates=function(k,D,Z){return ib(k,D,Z,b)};X.getDate=c;X.getView=z;X.option=H;X.trigger=T;$b.call(X,b,e);var ya=X.isFetchNeeded,K=X.fetchEvents,i=a[0],C,P,E,B,n,Y={},W,o,s,v=0,F=0,r=new Date,J=[],M;yb(r,b.year,b.month,b.date);b.droppable&&m(document).bind("dragstart",function(k,D){var Z=k.target,ja=m(Z);if(!ja.parents(".fc").length){var ia=b.dropAccept;if(m.isFunction(ia)?
+ia.call(Z,ja):ja.is(ia)){M=Z;n.dragStart(M,k,D)}}}).bind("dragstop",function(k,D){if(M){n.dragStop(M,k,D);M=null}})}function Zb(a,b){function e(){q=b.theme?"ui":"fc";if(b.header)return Q=m("<table class='fc-header' style='width:100%'/>").append(m("<tr/>").append(f("left")).append(f("center")).append(f("right")))}function d(){Q.remove()}function f(u){var fa=m("<td class='fc-header-"+u+"'/>");(u=b.header[u])&&m.each(u.split(" "),function(oa){oa>0&&fa.append("<span class='fc-header-space'/>");var ga;
+m.each(this.split(","),function(ra,sa){if(sa=="title"){fa.append("<span class='fc-header-title'><h2>&nbsp;</h2></span>");ga&&ga.addClass(q+"-corner-right");ga=null}else{var ha;if(a[sa])ha=a[sa];else if(Ja[sa])ha=function(){na.removeClass(q+"-state-hover");a.changeView(sa)};if(ha){ra=b.theme?jb(b.buttonIcons,sa):null;var da=jb(b.buttonText,sa),na=m("<span class='fc-button fc-button-"+sa+" "+q+"-state-default'><span class='fc-button-inner'><span class='fc-button-content'>"+(ra?"<span class='fc-icon-wrap'><span class='ui-icon ui-icon-"+
+ra+"'/></span>":da)+"</span><span class='fc-button-effect'><span></span></span></span></span>");if(na){na.click(function(){na.hasClass(q+"-state-disabled")||ha()}).mousedown(function(){na.not("."+q+"-state-active").not("."+q+"-state-disabled").addClass(q+"-state-down")}).mouseup(function(){na.removeClass(q+"-state-down")}).hover(function(){na.not("."+q+"-state-active").not("."+q+"-state-disabled").addClass(q+"-state-hover")},function(){na.removeClass(q+"-state-hover").removeClass(q+"-state-down")}).appendTo(fa);
+ga||na.addClass(q+"-corner-left");ga=na}}}});ga&&ga.addClass(q+"-corner-right")});return fa}function g(u){Q.find("h2").html(u)}function l(u){Q.find("span.fc-button-"+u).addClass(q+"-state-active")}function j(u){Q.find("span.fc-button-"+u).removeClass(q+"-state-active")}function t(u){Q.find("span.fc-button-"+u).addClass(q+"-state-disabled")}function y(u){Q.find("span.fc-button-"+u).removeClass(q+"-state-disabled")}var S=this;S.render=e;S.destroy=d;S.updateTitle=g;S.activateButton=l;S.deactivateButton=
+j;S.disableButton=t;S.enableButton=y;var Q=m([]),q}function $b(a,b){function e(c,z){return!ca||c<ca||z>ka}function d(c,z){ca=c;ka=z;L=[];c=++qa;G=z=U.length;for(var H=0;H<z;H++)f(U[H],c)}function f(c,z){g(c,function(H){if(z==qa){if(H){for(var T=0;T<H.length;T++){H[T].source=c;oa(H[T])}L=L.concat(H)}G--;G||ua(L)}})}function g(c,z){var H,T=Aa.sourceFetchers,X;for(H=0;H<T.length;H++){X=T[H](c,ca,ka,z);if(X===true)return;else if(typeof X=="object"){g(X,z);return}}if(H=c.events)if(m.isFunction(H)){u();
+H(N(ca),N(ka),function(C){z(C);fa()})}else m.isArray(H)?z(H):z();else if(c.url){var ya=c.success,K=c.error,i=c.complete;H=m.extend({},c.data||{});T=Ta(c.startParam,a.startParam);X=Ta(c.endParam,a.endParam);if(T)H[T]=Math.round(+ca/1E3);if(X)H[X]=Math.round(+ka/1E3);u();m.ajax(m.extend({},ac,c,{data:H,success:function(C){C=C||[];var P=$a(ya,this,arguments);if(m.isArray(P))C=P;z(C)},error:function(){$a(K,this,arguments);z()},complete:function(){$a(i,this,arguments);fa()}}))}else z()}function l(c){if(c=
+j(c)){G++;f(c,qa)}}function j(c){if(m.isFunction(c)||m.isArray(c))c={events:c};else if(typeof c=="string")c={url:c};if(typeof c=="object"){ga(c);U.push(c);return c}}function t(c){U=m.grep(U,function(z){return!ra(z,c)});L=m.grep(L,function(z){return!ra(z.source,c)});ua(L)}function y(c){var z,H=L.length,T,X=na().defaultEventEnd,ya=c.start-c._start,K=c.end?c.end-(c._end||X(c)):0;for(z=0;z<H;z++){T=L[z];if(T._id==c._id&&T!=c){T.start=new Date(+T.start+ya);T.end=c.end?T.end?new Date(+T.end+K):new Date(+X(T)+
+K):null;T.title=c.title;T.url=c.url;T.allDay=c.allDay;T.className=c.className;T.editable=c.editable;T.color=c.color;T.backgroudColor=c.backgroudColor;T.borderColor=c.borderColor;T.textColor=c.textColor;oa(T)}}oa(c);ua(L)}function S(c,z){oa(c);if(!c.source){if(z){pa.events.push(c);c.source=pa}L.push(c)}ua(L)}function Q(c){if(c){if(!m.isFunction(c)){var z=c+"";c=function(T){return T._id==z}}L=m.grep(L,c,true);for(H=0;H<U.length;H++)if(m.isArray(U[H].events))U[H].events=m.grep(U[H].events,c,true)}else{L=
+[];for(var H=0;H<U.length;H++)if(m.isArray(U[H].events))U[H].events=[]}ua(L)}function q(c){if(m.isFunction(c))return m.grep(L,c);else if(c){c+="";return m.grep(L,function(z){return z._id==c})}return L}function u(){p++||da("loading",null,true)}function fa(){--p||da("loading",null,false)}function oa(c){var z=c.source||{},H=Ta(z.ignoreTimezone,a.ignoreTimezone);c._id=c._id||(c.id===ma?"_fc"+bc++:c.id+"");if(c.date){if(!c.start)c.start=c.date;delete c.date}c._start=N(c.start=kb(c.start,H));c.end=kb(c.end,
+H);if(c.end&&c.end<=c.start)c.end=null;c._end=c.end?N(c.end):null;if(c.allDay===ma)c.allDay=Ta(z.allDayDefault,a.allDayDefault);if(c.className){if(typeof c.className=="string")c.className=c.className.split(/\s+/)}else c.className=[]}function ga(c){if(c.className){if(typeof c.className=="string")c.className=c.className.split(/\s+/)}else c.className=[];for(var z=Aa.sourceNormalizers,H=0;H<z.length;H++)z[H](c)}function ra(c,z){return c&&z&&sa(c)==sa(z)}function sa(c){return(typeof c=="object"?c.events||
+c.url:"")||c}var ha=this;ha.isFetchNeeded=e;ha.fetchEvents=d;ha.addEventSource=l;ha.removeEventSource=t;ha.updateEvent=y;ha.renderEvent=S;ha.removeEvents=Q;ha.clientEvents=q;ha.normalizeEvent=oa;var da=ha.trigger,na=ha.getView,ua=ha.reportEvents,pa={events:[]},U=[pa],ca,ka,qa=0,G=0,p=0,L=[];for(ha=0;ha<b.length;ha++)j(b[ha])}function gb(a,b,e){a.setFullYear(a.getFullYear()+b);e||Ka(a);return a}function hb(a,b,e){if(+a){b=a.getMonth()+b;var d=N(a);d.setDate(1);d.setMonth(b);a.setMonth(b);for(e||Ka(a);a.getMonth()!=
+d.getMonth();)a.setDate(a.getDate()+(a<d?1:-1))}return a}function ba(a,b,e){if(+a){b=a.getDate()+b;var d=N(a);d.setHours(9);d.setDate(b);a.setDate(b);e||Ka(a);lb(a,d)}return a}function lb(a,b){if(+a)for(;a.getDate()!=b.getDate();)a.setTime(+a+(a<b?1:-1)*cc)}function xa(a,b){a.setMinutes(a.getMinutes()+b);return a}function Ka(a){a.setHours(0);a.setMinutes(0);a.setSeconds(0);a.setMilliseconds(0);return a}function N(a,b){if(b)return Ka(new Date(+a));return new Date(+a)}function zb(){var a=0,b;do b=new Date(1970,
+a++,1);while(b.getHours());return b}function Fa(a,b,e){for(b=b||1;!a.getDay()||e&&a.getDay()==1||!e&&a.getDay()==6;)ba(a,b);return a}function Ca(a,b){return Math.round((N(a,true)-N(b,true))/Ab)}function yb(a,b,e,d){if(b!==ma&&b!=a.getFullYear()){a.setDate(1);a.setMonth(0);a.setFullYear(b)}if(e!==ma&&e!=a.getMonth()){a.setDate(1);a.setMonth(e)}d!==ma&&a.setDate(d)}function kb(a,b){if(typeof a=="object")return a;if(typeof a=="number")return new Date(a*1E3);if(typeof a=="string"){if(a.match(/^\d+(\.\d+)?$/))return new Date(parseFloat(a)*
+1E3);if(b===ma)b=true;return Bb(a,b)||(a?new Date(a):null)}return null}function Bb(a,b){a=a.match(/^([0-9]{4})(-([0-9]{2})(-([0-9]{2})([T ]([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?(Z|(([-+])([0-9]{2})(:?([0-9]{2}))?))?)?)?)?$/);if(!a)return null;var e=new Date(a[1],0,1);if(b||!a[13]){b=new Date(a[1],0,1,9,0);if(a[3]){e.setMonth(a[3]-1);b.setMonth(a[3]-1)}if(a[5]){e.setDate(a[5]);b.setDate(a[5])}lb(e,b);a[7]&&e.setHours(a[7]);a[8]&&e.setMinutes(a[8]);a[10]&&e.setSeconds(a[10]);a[12]&&e.setMilliseconds(Number("0."+
+a[12])*1E3);lb(e,b)}else{e.setUTCFullYear(a[1],a[3]?a[3]-1:0,a[5]||1);e.setUTCHours(a[7]||0,a[8]||0,a[10]||0,a[12]?Number("0."+a[12])*1E3:0);if(a[14]){b=Number(a[16])*60+(a[18]?Number(a[18]):0);b*=a[15]=="-"?1:-1;e=new Date(+e+b*60*1E3)}}return e}function mb(a){if(typeof a=="number")return a*60;if(typeof a=="object")return a.getHours()*60+a.getMinutes();if(a=a.match(/(\d+)(?::(\d+))?\s*(\w+)?/)){var b=parseInt(a[1],10);if(a[3]){b%=12;if(a[3].toLowerCase().charAt(0)=="p")b+=12}return b*60+(a[2]?parseInt(a[2],
+10):0)}}function Oa(a,b,e){return ib(a,null,b,e)}function ib(a,b,e,d){d=d||Ya;var f=a,g=b,l,j=e.length,t,y,S,Q="";for(l=0;l<j;l++){t=e.charAt(l);if(t=="'")for(y=l+1;y<j;y++){if(e.charAt(y)=="'"){if(f){Q+=y==l+1?"'":e.substring(l+1,y);l=y}break}}else if(t=="(")for(y=l+1;y<j;y++){if(e.charAt(y)==")"){l=Oa(f,e.substring(l+1,y),d);if(parseInt(l.replace(/\D/,""),10))Q+=l;l=y;break}}else if(t=="[")for(y=l+1;y<j;y++){if(e.charAt(y)=="]"){t=e.substring(l+1,y);l=Oa(f,t,d);if(l!=Oa(g,t,d))Q+=l;l=y;break}}else if(t==
+"{"){f=b;g=a}else if(t=="}"){f=a;g=b}else{for(y=j;y>l;y--)if(S=dc[e.substring(l,y)]){if(f)Q+=S(f,d);l=y-1;break}if(y==l)if(f)Q+=t}}return Q}function Ua(a){return a.end?ec(a.end,a.allDay):ba(N(a.start),1)}function ec(a,b){a=N(a);return b||a.getHours()||a.getMinutes()?ba(a,1):Ka(a)}function fc(a,b){return(b.msLength-a.msLength)*100+(a.event.start-b.event.start)}function Cb(a,b){return a.end>b.start&&a.start<b.end}function nb(a,b,e,d){var f=[],g,l=a.length,j,t,y,S,Q;for(g=0;g<l;g++){j=a[g];t=j.start;
+y=b[g];if(y>e&&t<d){if(t<e){t=N(e);S=false}else{t=t;S=true}if(y>d){y=N(d);Q=false}else{y=y;Q=true}f.push({event:j,start:t,end:y,isStart:S,isEnd:Q,msLength:y-t})}}return f.sort(fc)}function ob(a){var b=[],e,d=a.length,f,g,l,j;for(e=0;e<d;e++){f=a[e];for(g=0;;){l=false;if(b[g])for(j=0;j<b[g].length;j++)if(Cb(b[g][j],f)){l=true;break}if(l)g++;else break}if(b[g])b[g].push(f);else b[g]=[f]}return b}function Db(a,b,e){a.unbind("mouseover").mouseover(function(d){for(var f=d.target,g;f!=this;){g=f;f=f.parentNode}if((f=
+g._fci)!==ma){g._fci=ma;g=b[f];e(g.event,g.element,g);m(d.target).trigger(d)}d.stopPropagation()})}function Va(a,b,e){for(var d=0,f;d<a.length;d++){f=m(a[d]);f.width(Math.max(0,b-pb(f,e)))}}function Eb(a,b,e){for(var d=0,f;d<a.length;d++){f=m(a[d]);f.height(Math.max(0,b-Sa(f,e)))}}function pb(a,b){return gc(a)+hc(a)+(b?ic(a):0)}function gc(a){return(parseFloat(m.curCSS(a[0],"paddingLeft",true))||0)+(parseFloat(m.curCSS(a[0],"paddingRight",true))||0)}function ic(a){return(parseFloat(m.curCSS(a[0],
+"marginLeft",true))||0)+(parseFloat(m.curCSS(a[0],"marginRight",true))||0)}function hc(a){return(parseFloat(m.curCSS(a[0],"borderLeftWidth",true))||0)+(parseFloat(m.curCSS(a[0],"borderRightWidth",true))||0)}function Sa(a,b){return jc(a)+kc(a)+(b?Fb(a):0)}function jc(a){return(parseFloat(m.curCSS(a[0],"paddingTop",true))||0)+(parseFloat(m.curCSS(a[0],"paddingBottom",true))||0)}function Fb(a){return(parseFloat(m.curCSS(a[0],"marginTop",true))||0)+(parseFloat(m.curCSS(a[0],"marginBottom",true))||0)}
+function kc(a){return(parseFloat(m.curCSS(a[0],"borderTopWidth",true))||0)+(parseFloat(m.curCSS(a[0],"borderBottomWidth",true))||0)}function Za(a,b){b=typeof b=="number"?b+"px":b;a.each(function(e,d){d.style.cssText+=";min-height:"+b+";_height:"+b})}function xb(){}function Gb(a,b){return a-b}function Hb(a){return Math.max.apply(Math,a)}function Pa(a){return(a<10?"0":"")+a}function jb(a,b){if(a[b]!==ma)return a[b];b=b.split(/(?=[A-Z])/);for(var e=b.length-1,d;e>=0;e--){d=a[b[e].toLowerCase()];if(d!==
+ma)return d}return a[""]}function Qa(a){return a.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/'/g,"&#039;").replace(/"/g,"&quot;").replace(/\n/g,"<br />")}function Ib(a){return a.id+"/"+a.className+"/"+a.style.cssText.replace(/(^|;)\s*(top|left|width|height)\s*:[^;]*/ig,"")}function qb(a){a.attr("unselectable","on").css("MozUserSelect","none").bind("selectstart.ui",function(){return false})}function ab(a){a.children().removeClass("fc-first fc-last").filter(":first-child").addClass("fc-first").end().filter(":last-child").addClass("fc-last")}
+function rb(a,b){a.each(function(e,d){d.className=d.className.replace(/^fc-\w*/,"fc-"+lc[b.getDay()])})}function Jb(a,b){var e=a.source||{},d=a.color,f=e.color,g=b("eventColor"),l=a.backgroundColor||d||e.backgroundColor||f||b("eventBackgroundColor")||g;d=a.borderColor||d||e.borderColor||f||b("eventBorderColor")||g;a=a.textColor||e.textColor||b("eventTextColor");b=[];l&&b.push("background-color:"+l);d&&b.push("border-color:"+d);a&&b.push("color:"+a);return b.join(";")}function $a(a,b,e){if(m.isFunction(a))a=
+[a];if(a){var d,f;for(d=0;d<a.length;d++)f=a[d].apply(b,e)||f;return f}}function Ta(){for(var a=0;a<arguments.length;a++)if(arguments[a]!==ma)return arguments[a]}function mc(a,b){function e(j,t){if(t){hb(j,t);j.setDate(1)}j=N(j,true);j.setDate(1);t=hb(N(j),1);var y=N(j),S=N(t),Q=f("firstDay"),q=f("weekends")?0:1;if(q){Fa(y);Fa(S,-1,true)}ba(y,-((y.getDay()-Math.max(Q,q)+7)%7));ba(S,(7-S.getDay()+Math.max(Q,q))%7);Q=Math.round((S-y)/(Ab*7));if(f("weekMode")=="fixed"){ba(S,(6-Q)*7);Q=6}d.title=l(j,
+f("titleFormat"));d.start=j;d.end=t;d.visStart=y;d.visEnd=S;g(6,Q,q?5:7,true)}var d=this;d.render=e;sb.call(d,a,b,"month");var f=d.opt,g=d.renderBasic,l=b.formatDate}function nc(a,b){function e(j,t){t&&ba(j,t*7);j=ba(N(j),-((j.getDay()-f("firstDay")+7)%7));t=ba(N(j),7);var y=N(j),S=N(t),Q=f("weekends");if(!Q){Fa(y);Fa(S,-1,true)}d.title=l(y,ba(N(S),-1),f("titleFormat"));d.start=j;d.end=t;d.visStart=y;d.visEnd=S;g(1,1,Q?7:5,false)}var d=this;d.render=e;sb.call(d,a,b,"basicWeek");var f=d.opt,g=d.renderBasic,
+l=b.formatDates}function oc(a,b){function e(j,t){if(t){ba(j,t);f("weekends")||Fa(j,t<0?-1:1)}d.title=l(j,f("titleFormat"));d.start=d.visStart=N(j,true);d.end=d.visEnd=ba(N(d.start),1);g(1,1,1,false)}var d=this;d.render=e;sb.call(d,a,b,"basicDay");var f=d.opt,g=d.renderBasic,l=b.formatDate}function sb(a,b,e){function d(w,I,R,V){v=I;F=R;f();(I=!C)?g(w,V):z();l(I)}function f(){if(k=L("isRTL")){D=-1;Z=F-1}else{D=1;Z=0}ja=L("firstDay");ia=L("weekends")?0:1;la=L("theme")?"ui":"fc";$=L("columnFormat")}function g(w,
+I){var R,V=la+"-widget-header",ea=la+"-widget-content",aa;R="<table class='fc-border-separate' style='width:100%' cellspacing='0'><thead><tr>";for(aa=0;aa<F;aa++)R+="<th class='fc- "+V+"'/>";R+="</tr></thead><tbody>";for(aa=0;aa<w;aa++){R+="<tr class='fc-week"+aa+"'>";for(V=0;V<F;V++)R+="<td class='fc- "+ea+" fc-day"+(aa*F+V)+"'><div>"+(I?"<div class='fc-day-number'/>":"")+"<div class='fc-day-content'><div style='position:relative'>&nbsp;</div></div></div></td>";R+="</tr>"}R+="</tbody></table>";w=
+m(R).appendTo(a);K=w.find("thead");i=K.find("th");C=w.find("tbody");P=C.find("tr");E=C.find("td");B=E.filter(":first-child");n=P.eq(0).find("div.fc-day-content div");ab(K.add(K.find("tr")));ab(P);P.eq(0).addClass("fc-first");y(E);Y=m("<div style='position:absolute;z-index:8;top:0;left:0'/>").appendTo(a)}function l(w){var I=w||v==1,R=p.start.getMonth(),V=Ka(new Date),ea,aa,va;I&&i.each(function(wa,Ga){ea=m(Ga);aa=ca(wa);ea.html(ya(aa,$));rb(ea,aa)});E.each(function(wa,Ga){ea=m(Ga);aa=ca(wa);aa.getMonth()==
+R?ea.removeClass("fc-other-month"):ea.addClass("fc-other-month");+aa==+V?ea.addClass(la+"-state-highlight fc-today"):ea.removeClass(la+"-state-highlight fc-today");ea.find("div.fc-day-number").text(aa.getDate());I&&rb(ea,aa)});P.each(function(wa,Ga){va=m(Ga);if(wa<v){va.show();wa==v-1?va.addClass("fc-last"):va.removeClass("fc-last")}else va.hide()})}function j(w){o=w;w=o-K.height();var I,R,V;if(L("weekMode")=="variable")I=R=Math.floor(w/(v==1?2:6));else{I=Math.floor(w/v);R=w-I*(v-1)}B.each(function(ea,
+aa){if(ea<v){V=m(aa);Za(V.find("> div"),(ea==v-1?R:I)-Sa(V))}})}function t(w){W=w;M.clear();s=Math.floor(W/F);Va(i.slice(0,-1),s)}function y(w){w.click(S).mousedown(X)}function S(w){if(!L("selectable")){var I=parseInt(this.className.match(/fc\-day(\d+)/)[1]);I=ca(I);c("dayClick",this,I,true,w)}}function Q(w,I,R){R&&r.build();R=N(p.visStart);for(var V=ba(N(R),F),ea=0;ea<v;ea++){var aa=new Date(Math.max(R,w)),va=new Date(Math.min(V,I));if(aa<va){var wa;if(k){wa=Ca(va,R)*D+Z+1;aa=Ca(aa,R)*D+Z+1}else{wa=
+Ca(aa,R);aa=Ca(va,R)}y(q(ea,wa,ea,aa-1))}ba(R,7);ba(V,7)}}function q(w,I,R,V){w=r.rect(w,I,R,V,a);return H(w,a)}function u(w){return N(w)}function fa(w,I){Q(w,ba(N(I),1),true)}function oa(){T()}function ga(w,I,R){var V=ua(w);c("dayClick",E[V.row*F+V.col],w,I,R)}function ra(w,I){J.start(function(R){T();R&&q(R.row,R.col,R.row,R.col)},I)}function sa(w,I,R){var V=J.stop();T();if(V){V=pa(V);c("drop",w,V,true,I,R)}}function ha(w){return N(w.start)}function da(w){return M.left(w)}function na(w){return M.right(w)}
+function ua(w){return{row:Math.floor(Ca(w,p.visStart)/7),col:ka(w.getDay())}}function pa(w){return U(w.row,w.col)}function U(w,I){return ba(N(p.visStart),w*7+I*D+Z)}function ca(w){return U(Math.floor(w/F),w%F)}function ka(w){return(w-Math.max(ja,ia)+F)%F*D+Z}function qa(w){return P.eq(w)}function G(){return{left:0,right:W}}var p=this;p.renderBasic=d;p.setHeight=j;p.setWidth=t;p.renderDayOverlay=Q;p.defaultSelectionEnd=u;p.renderSelection=fa;p.clearSelection=oa;p.reportDayClick=ga;p.dragStart=ra;p.dragStop=
+sa;p.defaultEventEnd=ha;p.getHoverListener=function(){return J};p.colContentLeft=da;p.colContentRight=na;p.dayOfWeekCol=ka;p.dateCell=ua;p.cellDate=pa;p.cellIsAllDay=function(){return true};p.allDayRow=qa;p.allDayBounds=G;p.getRowCnt=function(){return v};p.getColCnt=function(){return F};p.getColWidth=function(){return s};p.getDaySegmentContainer=function(){return Y};Kb.call(p,a,b,e);Lb.call(p);Mb.call(p);pc.call(p);var L=p.opt,c=p.trigger,z=p.clearEvents,H=p.renderOverlay,T=p.clearOverlays,X=p.daySelectionMousedown,
+ya=b.formatDate,K,i,C,P,E,B,n,Y,W,o,s,v,F,r,J,M,k,D,Z,ja,ia,la,$;qb(a.addClass("fc-grid"));r=new Nb(function(w,I){var R,V,ea;i.each(function(aa,va){R=m(va);V=R.offset().left;if(aa)ea[1]=V;ea=[V];I[aa]=ea});ea[1]=V+R.outerWidth();P.each(function(aa,va){if(aa<v){R=m(va);V=R.offset().top;if(aa)ea[1]=V;ea=[V];w[aa]=ea}});ea[1]=V+R.outerHeight()});J=new Ob(r);M=new Pb(function(w){return n.eq(w)})}function pc(){function a(U,ca){S(U);ua(e(U),ca)}function b(){Q();ga().empty()}function e(U){var ca=da(),ka=
+na(),qa=N(g.visStart);ka=ba(N(qa),ka);var G=m.map(U,Ua),p,L,c,z,H,T,X=[];for(p=0;p<ca;p++){L=ob(nb(U,G,qa,ka));for(c=0;c<L.length;c++){z=L[c];for(H=0;H<z.length;H++){T=z[H];T.row=p;T.level=c;X.push(T)}}ba(qa,7);ba(ka,7)}return X}function d(U,ca,ka){t(U)&&f(U,ca);ka.isEnd&&y(U)&&pa(U,ca,ka);q(U,ca)}function f(U,ca){var ka=ra(),qa;ca.draggable({zIndex:9,delay:50,opacity:l("dragOpacity"),revertDuration:l("dragRevertDuration"),start:function(G,p){j("eventDragStart",ca,U,G,p);fa(U,ca);ka.start(function(L,
+c,z,H){ca.draggable("option","revert",!L||!z&&!H);ha();if(L){qa=z*7+H*(l("isRTL")?-1:1);sa(ba(N(U.start),qa),ba(Ua(U),qa))}else qa=0},G,"drag")},stop:function(G,p){ka.stop();ha();j("eventDragStop",ca,U,G,p);if(qa)oa(this,U,qa,0,U.allDay,G,p);else{ca.css("filter","");u(U,ca)}}})}var g=this;g.renderEvents=a;g.compileDaySegs=e;g.clearEvents=b;g.bindDaySeg=d;Qb.call(g);var l=g.opt,j=g.trigger,t=g.isEventDraggable,y=g.isEventResizable,S=g.reportEvents,Q=g.reportEventClear,q=g.eventElementHandlers,u=g.showEvents,
+fa=g.hideEvents,oa=g.eventDrop,ga=g.getDaySegmentContainer,ra=g.getHoverListener,sa=g.renderDayOverlay,ha=g.clearOverlays,da=g.getRowCnt,na=g.getColCnt,ua=g.renderDaySegs,pa=g.resizableDayEvent}function qc(a,b){function e(j,t){t&&ba(j,t*7);j=ba(N(j),-((j.getDay()-f("firstDay")+7)%7));t=ba(N(j),7);var y=N(j),S=N(t),Q=f("weekends");if(!Q){Fa(y);Fa(S,-1,true)}d.title=l(y,ba(N(S),-1),f("titleFormat"));d.start=j;d.end=t;d.visStart=y;d.visEnd=S;g(Q?7:5)}var d=this;d.render=e;Rb.call(d,a,b,"agendaWeek");
+var f=d.opt,g=d.renderAgenda,l=b.formatDates}function rc(a,b){function e(j,t){if(t){ba(j,t);f("weekends")||Fa(j,t<0?-1:1)}t=N(j,true);var y=ba(N(t),1);d.title=l(j,f("titleFormat"));d.start=d.visStart=t;d.end=d.visEnd=y;g(1)}var d=this;d.render=e;Rb.call(d,a,b,"agendaDay");var f=d.opt,g=d.renderAgenda,l=b.formatDate}function Rb(a,b,e){function d(h){Ba=h;f();v?P():g();l()}function f(){Wa=i("theme")?"ui":"fc";Sb=i("weekends")?0:1;Tb=i("firstDay");if(Ub=i("isRTL")){Ha=-1;Ia=Ba-1}else{Ha=1;Ia=0}La=mb(i("minTime"));
+bb=mb(i("maxTime"));Vb=i("columnFormat")}function g(){var h=Wa+"-widget-header",O=Wa+"-widget-content",x,A,ta,za,Da,Ea=i("slotMinutes")%15==0;x="<table style='width:100%' class='fc-agenda-days fc-border-separate' cellspacing='0'><thead><tr><th class='fc-agenda-axis "+h+"'>&nbsp;</th>";for(A=0;A<Ba;A++)x+="<th class='fc- fc-col"+A+" "+h+"'/>";x+="<th class='fc-agenda-gutter "+h+"'>&nbsp;</th></tr></thead><tbody><tr><th class='fc-agenda-axis "+h+"'>&nbsp;</th>";for(A=0;A<Ba;A++)x+="<td class='fc- fc-col"+
+A+" "+O+"'><div><div class='fc-day-content'><div style='position:relative'>&nbsp;</div></div></div></td>";x+="<td class='fc-agenda-gutter "+O+"'>&nbsp;</td></tr></tbody></table>";v=m(x).appendTo(a);F=v.find("thead");r=F.find("th").slice(1,-1);J=v.find("tbody");M=J.find("td").slice(0,-1);k=M.find("div.fc-day-content div");D=M.eq(0);Z=D.find("> div");ab(F.add(F.find("tr")));ab(J.add(J.find("tr")));aa=F.find("th:first");va=v.find(".fc-agenda-gutter");ja=m("<div style='position:absolute;z-index:2;left:0;width:100%'/>").appendTo(a);
+if(i("allDaySlot")){ia=m("<div style='position:absolute;z-index:8;top:0;left:0'/>").appendTo(ja);x="<table style='width:100%' class='fc-agenda-allday' cellspacing='0'><tr><th class='"+h+" fc-agenda-axis'>"+i("allDayText")+"</th><td><div class='fc-day-content'><div style='position:relative'/></div></td><th class='"+h+" fc-agenda-gutter'>&nbsp;</th></tr></table>";la=m(x).appendTo(ja);$=la.find("tr");q($.find("td"));aa=aa.add(la.find("th:first"));va=va.add(la.find("th.fc-agenda-gutter"));ja.append("<div class='fc-agenda-divider "+
+h+"'><div class='fc-agenda-divider-inner'/></div>")}else ia=m([]);w=m("<div style='position:absolute;width:100%;overflow-x:hidden;overflow-y:auto'/>").appendTo(ja);I=m("<div style='position:relative;width:100%;overflow:hidden'/>").appendTo(w);R=m("<div style='position:absolute;z-index:8;top:0;left:0'/>").appendTo(I);x="<table class='fc-agenda-slots' style='width:100%' cellspacing='0'><tbody>";ta=zb();za=xa(N(ta),bb);xa(ta,La);for(A=tb=0;ta<za;A++){Da=ta.getMinutes();x+="<tr class='fc-slot"+A+" "+
+(!Da?"":"fc-minor")+"'><th class='fc-agenda-axis "+h+"'>"+(!Ea||!Da?s(ta,i("axisFormat")):"&nbsp;")+"</th><td class='"+O+"'><div style='position:relative'>&nbsp;</div></td></tr>";xa(ta,i("slotMinutes"));tb++}x+="</tbody></table>";V=m(x).appendTo(I);ea=V.find("div:first");u(V.find("td"));aa=aa.add(V.find("th:first"))}function l(){var h,O,x,A,ta=Ka(new Date);for(h=0;h<Ba;h++){A=ua(h);O=r.eq(h);O.html(s(A,Vb));x=M.eq(h);+A==+ta?x.addClass(Wa+"-state-highlight fc-today"):x.removeClass(Wa+"-state-highlight fc-today");
+rb(O.add(x),A)}}function j(h,O){if(h===ma)h=Wb;Wb=h;ub={};var x=J.position().top,A=w.position().top;h=Math.min(h-x,V.height()+A+1);Z.height(h-Sa(D));ja.css("top",x);w.height(h-A-1);Xa=ea.height()+1;O&&y()}function t(h){Ga=h;cb.clear();Ma=0;Va(aa.width("").each(function(O,x){Ma=Math.max(Ma,m(x).outerWidth())}),Ma);h=w[0].clientWidth;if(vb=w.width()-h){Va(va,vb);va.show().prev().removeClass("fc-last")}else va.hide().prev().addClass("fc-last");db=Math.floor((h-Ma)/Ba);Va(r.slice(0,-1),db)}function y(){function h(){w.scrollTop(A)}
+var O=zb(),x=N(O);x.setHours(i("firstHour"));var A=ca(O,x)+1;h();setTimeout(h,0)}function S(){Xb=w.scrollTop()}function Q(){w.scrollTop(Xb)}function q(h){h.click(fa).mousedown(W)}function u(h){h.click(fa).mousedown(H)}function fa(h){if(!i("selectable")){var O=Math.min(Ba-1,Math.floor((h.pageX-v.offset().left-Ma)/db)),x=ua(O),A=this.parentNode.className.match(/fc-slot(\d+)/);if(A){A=parseInt(A[1])*i("slotMinutes");var ta=Math.floor(A/60);x.setHours(ta);x.setMinutes(A%60+La);C("dayClick",M[O],x,false,
+h)}else C("dayClick",M[O],x,true,h)}}function oa(h,O,x){x&&Na.build();var A=N(K.visStart);if(Ub){x=Ca(O,A)*Ha+Ia+1;h=Ca(h,A)*Ha+Ia+1}else{x=Ca(h,A);h=Ca(O,A)}x=Math.max(0,x);h=Math.min(Ba,h);x<h&&q(ga(0,x,0,h-1))}function ga(h,O,x,A){h=Na.rect(h,O,x,A,ja);return E(h,ja)}function ra(h,O){for(var x=N(K.visStart),A=ba(N(x),1),ta=0;ta<Ba;ta++){var za=new Date(Math.max(x,h)),Da=new Date(Math.min(A,O));if(za<Da){var Ea=ta*Ha+Ia;Ea=Na.rect(0,Ea,0,Ea,I);za=ca(x,za);Da=ca(x,Da);Ea.top=za;Ea.height=Da-za;u(E(Ea,
+I))}ba(x,1);ba(A,1)}}function sa(h){return cb.left(h)}function ha(h){return cb.right(h)}function da(h){return{row:Math.floor(Ca(h,K.visStart)/7),col:U(h.getDay())}}function na(h){var O=ua(h.col);h=h.row;i("allDaySlot")&&h--;h>=0&&xa(O,La+h*i("slotMinutes"));return O}function ua(h){return ba(N(K.visStart),h*Ha+Ia)}function pa(h){return i("allDaySlot")&&!h.row}function U(h){return(h-Math.max(Tb,Sb)+Ba)%Ba*Ha+Ia}function ca(h,O){h=N(h,true);if(O<xa(N(h),La))return 0;if(O>=xa(N(h),bb))return V.height();
+h=i("slotMinutes");O=O.getHours()*60+O.getMinutes()-La;var x=Math.floor(O/h),A=ub[x];if(A===ma)A=ub[x]=V.find("tr:eq("+x+") td div")[0].offsetTop;return Math.max(0,Math.round(A-1+Xa*(O%h/h)))}function ka(){return{left:Ma,right:Ga-vb}}function qa(){return $}function G(h){var O=N(h.start);if(h.allDay)return O;return xa(O,i("defaultEventMinutes"))}function p(h,O){if(O)return N(h);return xa(N(h),i("slotMinutes"))}function L(h,O,x){if(x)i("allDaySlot")&&oa(h,ba(N(O),1),true);else c(h,O)}function c(h,O){var x=
+i("selectHelper");Na.build();if(x){var A=Ca(h,K.visStart)*Ha+Ia;if(A>=0&&A<Ba){A=Na.rect(0,A,0,A,I);var ta=ca(h,h),za=ca(h,O);if(za>ta){A.top=ta;A.height=za-ta;A.left+=2;A.width-=5;if(m.isFunction(x)){if(h=x(h,O)){A.position="absolute";A.zIndex=8;wa=m(h).css(A).appendTo(I)}}else{A.isStart=true;A.isEnd=true;wa=m(o({title:"",start:h,end:O,className:["fc-select-helper"],editable:false},A));wa.css("opacity",i("dragOpacity"))}if(wa){u(wa);I.append(wa);Va(wa,A.width,true);Eb(wa,A.height,true)}}}}else ra(h,
+O)}function z(){B();if(wa){wa.remove();wa=null}}function H(h){if(h.which==1&&i("selectable")){Y(h);var O;Ra.start(function(x,A){z();if(x&&x.col==A.col&&!pa(x)){A=na(A);x=na(x);O=[A,xa(N(A),i("slotMinutes")),x,xa(N(x),i("slotMinutes"))].sort(Gb);c(O[0],O[3])}else O=null},h);m(document).one("mouseup",function(x){Ra.stop();if(O){+O[0]==+O[1]&&T(O[0],false,x);n(O[0],O[3],false,x)}})}}function T(h,O,x){C("dayClick",M[U(h.getDay())],h,O,x)}function X(h,O){Ra.start(function(x){B();if(x)if(pa(x))ga(x.row,
+x.col,x.row,x.col);else{x=na(x);var A=xa(N(x),i("defaultEventMinutes"));ra(x,A)}},O)}function ya(h,O,x){var A=Ra.stop();B();A&&C("drop",h,na(A),pa(A),O,x)}var K=this;K.renderAgenda=d;K.setWidth=t;K.setHeight=j;K.beforeHide=S;K.afterShow=Q;K.defaultEventEnd=G;K.timePosition=ca;K.dayOfWeekCol=U;K.dateCell=da;K.cellDate=na;K.cellIsAllDay=pa;K.allDayRow=qa;K.allDayBounds=ka;K.getHoverListener=function(){return Ra};K.colContentLeft=sa;K.colContentRight=ha;K.getDaySegmentContainer=function(){return ia};
+K.getSlotSegmentContainer=function(){return R};K.getMinMinute=function(){return La};K.getMaxMinute=function(){return bb};K.getBodyContent=function(){return I};K.getRowCnt=function(){return 1};K.getColCnt=function(){return Ba};K.getColWidth=function(){return db};K.getSlotHeight=function(){return Xa};K.defaultSelectionEnd=p;K.renderDayOverlay=oa;K.renderSelection=L;K.clearSelection=z;K.reportDayClick=T;K.dragStart=X;K.dragStop=ya;Kb.call(K,a,b,e);Lb.call(K);Mb.call(K);sc.call(K);var i=K.opt,C=K.trigger,
+P=K.clearEvents,E=K.renderOverlay,B=K.clearOverlays,n=K.reportSelection,Y=K.unselect,W=K.daySelectionMousedown,o=K.slotSegHtml,s=b.formatDate,v,F,r,J,M,k,D,Z,ja,ia,la,$,w,I,R,V,ea,aa,va,wa,Ga,Wb,Ma,db,vb,Xa,Xb,Ba,tb,Na,Ra,cb,ub={},Wa,Tb,Sb,Ub,Ha,Ia,La,bb,Vb;qb(a.addClass("fc-agenda"));Na=new Nb(function(h,O){function x(eb){return Math.max(Ea,Math.min(tc,eb))}var A,ta,za;r.each(function(eb,uc){A=m(uc);ta=A.offset().left;if(eb)za[1]=ta;za=[ta];O[eb]=za});za[1]=ta+A.outerWidth();if(i("allDaySlot")){A=
+$;ta=A.offset().top;h[0]=[ta,ta+A.outerHeight()]}for(var Da=I.offset().top,Ea=w.offset().top,tc=Ea+w.outerHeight(),fb=0;fb<tb;fb++)h.push([x(Da+Xa*fb),x(Da+Xa*(fb+1))])});Ra=new Ob(Na);cb=new Pb(function(h){return k.eq(h)})}function sc(){function a(o,s){sa(o);var v,F=o.length,r=[],J=[];for(v=0;v<F;v++)o[v].allDay?r.push(o[v]):J.push(o[v]);if(u("allDaySlot")){L(e(r),s);na()}g(d(J),s)}function b(){ha();ua().empty();pa().empty()}function e(o){o=ob(nb(o,m.map(o,Ua),q.visStart,q.visEnd));var s,v=o.length,
+F,r,J,M=[];for(s=0;s<v;s++){F=o[s];for(r=0;r<F.length;r++){J=F[r];J.row=0;J.level=s;M.push(J)}}return M}function d(o){var s=z(),v=ka(),F=ca(),r=xa(N(q.visStart),v),J=m.map(o,f),M,k,D,Z,ja,ia,la=[];for(M=0;M<s;M++){k=ob(nb(o,J,r,xa(N(r),F-v)));vc(k);for(D=0;D<k.length;D++){Z=k[D];for(ja=0;ja<Z.length;ja++){ia=Z[ja];ia.col=M;ia.level=D;la.push(ia)}}ba(r,1,true)}return la}function f(o){return o.end?N(o.end):xa(N(o.start),u("defaultEventMinutes"))}function g(o,s){var v,F=o.length,r,J,M,k,D,Z,ja,ia,la,
+$="",w,I,R={},V={},ea=pa(),aa;v=z();if(w=u("isRTL")){I=-1;aa=v-1}else{I=1;aa=0}for(v=0;v<F;v++){r=o[v];J=r.event;M=qa(r.start,r.start);k=qa(r.start,r.end);D=r.col;Z=r.level;ja=r.forward||0;ia=G(D*I+aa);la=p(D*I+aa)-ia;la=Math.min(la-6,la*0.95);D=Z?la/(Z+ja+1):ja?(la/(ja+1)-6)*2:la;Z=ia+la/(Z+ja+1)*Z*I+(w?la-D:0);r.top=M;r.left=Z;r.outerWidth=D;r.outerHeight=k-M;$+=l(J,r)}ea[0].innerHTML=$;w=ea.children();for(v=0;v<F;v++){r=o[v];J=r.event;$=m(w[v]);I=fa("eventRender",J,J,$);if(I===false)$.remove();
+else{if(I&&I!==true){$.remove();$=m(I).css({position:"absolute",top:r.top,left:r.left}).appendTo(ea)}r.element=$;if(J._id===s)t(J,$,r);else $[0]._fci=v;ya(J,$)}}Db(ea,o,t);for(v=0;v<F;v++){r=o[v];if($=r.element){J=R[s=r.key=Ib($[0])];r.vsides=J===ma?(R[s]=Sa($,true)):J;J=V[s];r.hsides=J===ma?(V[s]=pb($,true)):J;s=$.find("div.fc-event-content");if(s.length)r.contentTop=s[0].offsetTop}}for(v=0;v<F;v++){r=o[v];if($=r.element){$[0].style.width=Math.max(0,r.outerWidth-r.hsides)+"px";R=Math.max(0,r.outerHeight-
+r.vsides);$[0].style.height=R+"px";J=r.event;if(r.contentTop!==ma&&R-r.contentTop<10){$.find("div.fc-event-time").text(Y(J.start,u("timeFormat"))+" - "+J.title);$.find("div.fc-event-title").remove()}fa("eventAfterRender",J,J,$)}}}function l(o,s){var v="<",F=o.url,r=Jb(o,u),J=r?" style='"+r+"'":"",M=["fc-event","fc-event-skin","fc-event-vert"];oa(o)&&M.push("fc-event-draggable");s.isStart&&M.push("fc-corner-top");s.isEnd&&M.push("fc-corner-bottom");M=M.concat(o.className);if(o.source)M=M.concat(o.source.className||
+[]);v+=F?"a href='"+Qa(o.url)+"'":"div";v+=" class='"+M.join(" ")+"' style='position:absolute;z-index:8;top:"+s.top+"px;left:"+s.left+"px;"+r+"'><div class='fc-event-inner fc-event-skin'"+J+"><div class='fc-event-head fc-event-skin'"+J+"><div class='fc-event-time'>"+Qa(W(o.start,o.end,u("timeFormat")))+"</div></div><div class='fc-event-content'><div class='fc-event-title'>"+Qa(o.title)+"</div></div><div class='fc-event-bg'></div></div>";if(s.isEnd&&ga(o))v+="<div class='ui-resizable-handle ui-resizable-s'>=</div>";
+v+="</"+(F?"a":"div")+">";return v}function j(o,s,v){oa(o)&&y(o,s,v.isStart);v.isEnd&&ga(o)&&c(o,s,v);da(o,s)}function t(o,s,v){var F=s.find("div.fc-event-time");oa(o)&&S(o,s,F);v.isEnd&&ga(o)&&Q(o,s,F);da(o,s)}function y(o,s,v){function F(){if(!M){s.width(r).height("").draggable("option","grid",null);M=true}}var r,J,M=true,k,D=u("isRTL")?-1:1,Z=U(),ja=H(),ia=T(),la=ka();s.draggable({zIndex:9,opacity:u("dragOpacity","month"),revertDuration:u("dragRevertDuration"),start:function($,w){fa("eventDragStart",
+s,o,$,w);i(o,s);r=s.width();Z.start(function(I,R,V,ea){B();if(I){J=false;k=ea*D;if(I.row)if(v){if(M){s.width(ja-10);Eb(s,ia*Math.round((o.end?(o.end-o.start)/wc:u("defaultEventMinutes"))/u("slotMinutes")));s.draggable("option","grid",[ja,1]);M=false}}else J=true;else{E(ba(N(o.start),k),ba(Ua(o),k));F()}J=J||M&&!k}else{F();J=true}s.draggable("option","revert",J)},$,"drag")},stop:function($,w){Z.stop();B();fa("eventDragStop",s,o,$,w);if(J){F();s.css("filter","");K(o,s)}else{var I=0;M||(I=Math.round((s.offset().top-
+X().offset().top)/ia)*u("slotMinutes")+la-(o.start.getHours()*60+o.start.getMinutes()));C(this,o,k,I,M,$,w)}}})}function S(o,s,v){function F(I){var R=xa(N(o.start),I),V;if(o.end)V=xa(N(o.end),I);v.text(W(R,V,u("timeFormat")))}function r(){if(M){v.css("display","");s.draggable("option","grid",[$,w]);M=false}}var J,M=false,k,D,Z,ja=u("isRTL")?-1:1,ia=U(),la=z(),$=H(),w=T();s.draggable({zIndex:9,scroll:false,grid:[$,w],axis:la==1?"y":false,opacity:u("dragOpacity"),revertDuration:u("dragRevertDuration"),
+start:function(I,R){fa("eventDragStart",s,o,I,R);i(o,s);J=s.position();D=Z=0;ia.start(function(V,ea,aa,va){s.draggable("option","revert",!V);B();if(V){k=va*ja;if(u("allDaySlot")&&!V.row){if(!M){M=true;v.hide();s.draggable("option","grid",null)}E(ba(N(o.start),k),ba(Ua(o),k))}else r()}},I,"drag")},drag:function(I,R){D=Math.round((R.position.top-J.top)/w)*u("slotMinutes");if(D!=Z){M||F(D);Z=D}},stop:function(I,R){var V=ia.stop();B();fa("eventDragStop",s,o,I,R);if(V&&(k||D||M))C(this,o,k,M?0:D,M,I,R);
+else{r();s.css("filter","");s.css(J);F(0);K(o,s)}}})}function Q(o,s,v){var F,r,J=T();s.resizable({handles:{s:"div.ui-resizable-s"},grid:J,start:function(M,k){F=r=0;i(o,s);s.css("z-index",9);fa("eventResizeStart",this,o,M,k)},resize:function(M,k){F=Math.round((Math.max(J,s.height())-k.originalSize.height)/J);if(F!=r){v.text(W(o.start,!F&&!o.end?null:xa(ra(o),u("slotMinutes")*F),u("timeFormat")));r=F}},stop:function(M,k){fa("eventResizeStop",this,o,M,k);if(F)P(this,o,0,u("slotMinutes")*F,M,k);else{s.css("z-index",
+8);K(o,s)}}})}var q=this;q.renderEvents=a;q.compileDaySegs=e;q.clearEvents=b;q.slotSegHtml=l;q.bindDaySeg=j;Qb.call(q);var u=q.opt,fa=q.trigger,oa=q.isEventDraggable,ga=q.isEventResizable,ra=q.eventEnd,sa=q.reportEvents,ha=q.reportEventClear,da=q.eventElementHandlers,na=q.setHeight,ua=q.getDaySegmentContainer,pa=q.getSlotSegmentContainer,U=q.getHoverListener,ca=q.getMaxMinute,ka=q.getMinMinute,qa=q.timePosition,G=q.colContentLeft,p=q.colContentRight,L=q.renderDaySegs,c=q.resizableDayEvent,z=q.getColCnt,
+H=q.getColWidth,T=q.getSlotHeight,X=q.getBodyContent,ya=q.reportEventElement,K=q.showEvents,i=q.hideEvents,C=q.eventDrop,P=q.eventResize,E=q.renderDayOverlay,B=q.clearOverlays,n=q.calendar,Y=n.formatDate,W=n.formatDates}function vc(a){var b,e,d,f,g,l;for(b=a.length-1;b>0;b--){f=a[b];for(e=0;e<f.length;e++){g=f[e];for(d=0;d<a[b-1].length;d++){l=a[b-1][d];if(Cb(g,l))l.forward=Math.max(l.forward||0,(g.forward||0)+1)}}}}function Kb(a,b,e){function d(G,p){G=qa[G];if(typeof G=="object")return jb(G,p||e);
+return G}function f(G,p){return b.trigger.apply(b,[G,p||da].concat(Array.prototype.slice.call(arguments,2),[da]))}function g(G){return j(G)&&!d("disableDragging")}function l(G){return j(G)&&!d("disableResizing")}function j(G){return Ta(G.editable,(G.source||{}).editable,d("editable"))}function t(G){U={};var p,L=G.length,c;for(p=0;p<L;p++){c=G[p];if(U[c._id])U[c._id].push(c);else U[c._id]=[c]}}function y(G){return G.end?N(G.end):na(G)}function S(G,p){ca.push(p);if(ka[G._id])ka[G._id].push(p);else ka[G._id]=
+[p]}function Q(){ca=[];ka={}}function q(G,p){p.click(function(L){if(!p.hasClass("ui-draggable-dragging")&&!p.hasClass("ui-resizable-resizing"))return f("eventClick",this,G,L)}).hover(function(L){f("eventMouseover",this,G,L)},function(L){f("eventMouseout",this,G,L)})}function u(G,p){oa(G,p,"show")}function fa(G,p){oa(G,p,"hide")}function oa(G,p,L){G=ka[G._id];var c,z=G.length;for(c=0;c<z;c++)if(!p||G[c][0]!=p[0])G[c][L]()}function ga(G,p,L,c,z,H,T){var X=p.allDay,ya=p._id;sa(U[ya],L,c,z);f("eventDrop",
+G,p,L,c,z,function(){sa(U[ya],-L,-c,X);pa(ya)},H,T);pa(ya)}function ra(G,p,L,c,z,H){var T=p._id;ha(U[T],L,c);f("eventResize",G,p,L,c,function(){ha(U[T],-L,-c);pa(T)},z,H);pa(T)}function sa(G,p,L,c){L=L||0;for(var z,H=G.length,T=0;T<H;T++){z=G[T];if(c!==ma)z.allDay=c;xa(ba(z.start,p,true),L);if(z.end)z.end=xa(ba(z.end,p,true),L);ua(z,qa)}}function ha(G,p,L){L=L||0;for(var c,z=G.length,H=0;H<z;H++){c=G[H];c.end=xa(ba(y(c),p,true),L);ua(c,qa)}}var da=this;da.element=a;da.calendar=b;da.name=e;da.opt=
+d;da.trigger=f;da.isEventDraggable=g;da.isEventResizable=l;da.reportEvents=t;da.eventEnd=y;da.reportEventElement=S;da.reportEventClear=Q;da.eventElementHandlers=q;da.showEvents=u;da.hideEvents=fa;da.eventDrop=ga;da.eventResize=ra;var na=da.defaultEventEnd,ua=b.normalizeEvent,pa=b.reportEventChange,U={},ca=[],ka={},qa=b.options}function Qb(){function a(i,C){var P=z(),E=pa(),B=U(),n=0,Y,W,o=i.length,s,v;P[0].innerHTML=e(i);d(i,P.children());f(i);g(i,P,C);l(i);j(i);t(i);C=y();for(P=0;P<E;P++){Y=[];for(W=
+0;W<B;W++)Y[W]=0;for(;n<o&&(s=i[n]).row==P;){W=Hb(Y.slice(s.startCol,s.endCol));s.top=W;W+=s.outerHeight;for(v=s.startCol;v<s.endCol;v++)Y[v]=W;n++}C[P].height(Hb(Y))}Q(i,S(C))}function b(i,C,P){var E=m("<div/>"),B=z(),n=i.length,Y;E[0].innerHTML=e(i);E=E.children();B.append(E);d(i,E);l(i);j(i);t(i);Q(i,S(y()));E=[];for(B=0;B<n;B++)if(Y=i[B].element){i[B].row===C&&Y.css("top",P);E.push(Y[0])}return m(E)}function e(i){var C=fa("isRTL"),P,E=i.length,B,n,Y,W;P=ka();var o=P.left,s=P.right,v,F,r,J,M,k=
+"";for(P=0;P<E;P++){B=i[P];n=B.event;W=["fc-event","fc-event-skin","fc-event-hori"];ga(n)&&W.push("fc-event-draggable");if(C){B.isStart&&W.push("fc-corner-right");B.isEnd&&W.push("fc-corner-left");v=p(B.end.getDay()-1);F=p(B.start.getDay());r=B.isEnd?qa(v):o;J=B.isStart?G(F):s}else{B.isStart&&W.push("fc-corner-left");B.isEnd&&W.push("fc-corner-right");v=p(B.start.getDay());F=p(B.end.getDay()-1);r=B.isStart?qa(v):o;J=B.isEnd?G(F):s}W=W.concat(n.className);if(n.source)W=W.concat(n.source.className||
+[]);Y=n.url;M=Jb(n,fa);k+=Y?"<a href='"+Qa(Y)+"'":"<div";k+=" class='"+W.join(" ")+"' style='position:absolute;z-index:8;left:"+r+"px;"+M+"'><div class='fc-event-inner fc-event-skin'"+(M?" style='"+M+"'":"")+">";if(!n.allDay&&B.isStart)k+="<span class='fc-event-time'>"+Qa(T(n.start,n.end,fa("timeFormat")))+"</span>";k+="<span class='fc-event-title'>"+Qa(n.title)+"</span></div>";if(B.isEnd&&ra(n))k+="<div class='ui-resizable-handle ui-resizable-"+(C?"w":"e")+"'>&nbsp;&nbsp;&nbsp;</div>";k+="</"+(Y?
+"a":"div")+">";B.left=r;B.outerWidth=J-r;B.startCol=v;B.endCol=F+1}return k}function d(i,C){var P,E=i.length,B,n,Y;for(P=0;P<E;P++){B=i[P];n=B.event;Y=m(C[P]);n=oa("eventRender",n,n,Y);if(n===false)Y.remove();else{if(n&&n!==true){n=m(n).css({position:"absolute",left:B.left});Y.replaceWith(n);Y=n}B.element=Y}}}function f(i){var C,P=i.length,E,B;for(C=0;C<P;C++){E=i[C];(B=E.element)&&ha(E.event,B)}}function g(i,C,P){var E,B=i.length,n,Y,W;for(E=0;E<B;E++){n=i[E];if(Y=n.element){W=n.event;if(W._id===
+P)H(W,Y,n);else Y[0]._fci=E}}Db(C,i,H)}function l(i){var C,P=i.length,E,B,n,Y,W={};for(C=0;C<P;C++){E=i[C];if(B=E.element){n=E.key=Ib(B[0]);Y=W[n];if(Y===ma)Y=W[n]=pb(B,true);E.hsides=Y}}}function j(i){var C,P=i.length,E,B;for(C=0;C<P;C++){E=i[C];if(B=E.element)B[0].style.width=Math.max(0,E.outerWidth-E.hsides)+"px"}}function t(i){var C,P=i.length,E,B,n,Y,W={};for(C=0;C<P;C++){E=i[C];if(B=E.element){n=E.key;Y=W[n];if(Y===ma)Y=W[n]=Fb(B);E.outerHeight=B[0].offsetHeight+Y}}}function y(){var i,C=pa(),
+P=[];for(i=0;i<C;i++)P[i]=ca(i).find("td:first div.fc-day-content > div");return P}function S(i){var C,P=i.length,E=[];for(C=0;C<P;C++)E[C]=i[C][0].offsetTop;return E}function Q(i,C){var P,E=i.length,B,n;for(P=0;P<E;P++){B=i[P];if(n=B.element){n[0].style.top=C[B.row]+(B.top||0)+"px";B=B.event;oa("eventAfterRender",B,B,n)}}}function q(i,C,P){var E=fa("isRTL"),B=E?"w":"e",n=C.find("div.ui-resizable-"+B),Y=false;qb(C);C.mousedown(function(W){W.preventDefault()}).click(function(W){if(Y){W.preventDefault();
+W.stopImmediatePropagation()}});n.mousedown(function(W){function o(ia){oa("eventResizeStop",this,i,ia);m("body").css("cursor","");s.stop();ya();k&&ua(this,i,k,0,ia);setTimeout(function(){Y=false},0)}if(W.which==1){Y=true;var s=u.getHoverListener(),v=pa(),F=U(),r=E?-1:1,J=E?F-1:0,M=C.css("top"),k,D,Z=m.extend({},i),ja=L(i.start);K();m("body").css("cursor",B+"-resize").one("mouseup",o);oa("eventResizeStart",this,i,W);s.start(function(ia,la){if(ia){var $=Math.max(ja.row,ia.row);ia=ia.col;if(v==1)$=0;
+if($==ja.row)ia=E?Math.min(ja.col,ia):Math.max(ja.col,ia);k=$*7+ia*r+J-(la.row*7+la.col*r+J);la=ba(sa(i),k,true);if(k){Z.end=la;$=D;D=b(c([Z]),P.row,M);D.find("*").css("cursor",B+"-resize");$&&$.remove();na(i)}else if(D){da(i);D.remove();D=null}ya();X(i.start,ba(N(la),1))}},W)}})}var u=this;u.renderDaySegs=a;u.resizableDayEvent=q;var fa=u.opt,oa=u.trigger,ga=u.isEventDraggable,ra=u.isEventResizable,sa=u.eventEnd,ha=u.reportEventElement,da=u.showEvents,na=u.hideEvents,ua=u.eventResize,pa=u.getRowCnt,
+U=u.getColCnt,ca=u.allDayRow,ka=u.allDayBounds,qa=u.colContentLeft,G=u.colContentRight,p=u.dayOfWeekCol,L=u.dateCell,c=u.compileDaySegs,z=u.getDaySegmentContainer,H=u.bindDaySeg,T=u.calendar.formatDates,X=u.renderDayOverlay,ya=u.clearOverlays,K=u.clearSelection}function Mb(){function a(Q,q,u){b();q||(q=j(Q,u));t(Q,q,u);e(Q,q,u)}function b(Q){if(S){S=false;y();l("unselect",null,Q)}}function e(Q,q,u,fa){S=true;l("select",null,Q,q,u,fa)}function d(Q){var q=f.cellDate,u=f.cellIsAllDay,fa=f.getHoverListener(),
+oa=f.reportDayClick;if(Q.which==1&&g("selectable")){b(Q);var ga;fa.start(function(ra,sa){y();if(ra&&u(ra)){ga=[q(sa),q(ra)].sort(Gb);t(ga[0],ga[1],true)}else ga=null},Q);m(document).one("mouseup",function(ra){fa.stop();if(ga){+ga[0]==+ga[1]&&oa(ga[0],true,ra);e(ga[0],ga[1],true,ra)}})}}var f=this;f.select=a;f.unselect=b;f.reportSelection=e;f.daySelectionMousedown=d;var g=f.opt,l=f.trigger,j=f.defaultSelectionEnd,t=f.renderSelection,y=f.clearSelection,S=false;g("selectable")&&g("unselectAuto")&&m(document).mousedown(function(Q){var q=
+g("unselectCancel");if(q)if(m(Q.target).parents(q).length)return;b(Q)})}function Lb(){function a(g,l){var j=f.shift();j||(j=m("<div class='fc-cell-overlay' style='position:absolute;z-index:3'/>"));j[0].parentNode!=l[0]&&j.appendTo(l);d.push(j.css(g).show());return j}function b(){for(var g;g=d.shift();)f.push(g.hide().unbind())}var e=this;e.renderOverlay=a;e.clearOverlays=b;var d=[],f=[]}function Nb(a){var b=this,e,d;b.build=function(){e=[];d=[];a(e,d)};b.cell=function(f,g){var l=e.length,j=d.length,
+t,y=-1,S=-1;for(t=0;t<l;t++)if(g>=e[t][0]&&g<e[t][1]){y=t;break}for(t=0;t<j;t++)if(f>=d[t][0]&&f<d[t][1]){S=t;break}return y>=0&&S>=0?{row:y,col:S}:null};b.rect=function(f,g,l,j,t){t=t.offset();return{top:e[f][0]-t.top,left:d[g][0]-t.left,width:d[j][1]-d[g][0],height:e[l][1]-e[f][0]}}}function Ob(a){function b(j){xc(j);j=a.cell(j.pageX,j.pageY);if(!j!=!l||j&&(j.row!=l.row||j.col!=l.col)){if(j){g||(g=j);f(j,g,j.row-g.row,j.col-g.col)}else f(j,g);l=j}}var e=this,d,f,g,l;e.start=function(j,t,y){f=j;
+g=l=null;a.build();b(t);d=y||"mousemove";m(document).bind(d,b)};e.stop=function(){m(document).unbind(d,b);return l}}function xc(a){if(a.pageX===ma){a.pageX=a.originalEvent.pageX;a.pageY=a.originalEvent.pageY}}function Pb(a){function b(l){return d[l]=d[l]||a(l)}var e=this,d={},f={},g={};e.left=function(l){return f[l]=f[l]===ma?b(l).position().left:f[l]};e.right=function(l){return g[l]=g[l]===ma?e.left(l)+b(l).width():g[l]};e.clear=function(){d={};f={};g={}}}var Ya={defaultView:"month",aspectRatio:1.35,
+header:{left:"title",center:"",right:"today prev,next"},weekends:true,allDayDefault:true,ignoreTimezone:true,lazyFetching:true,startParam:"start",endParam:"end",titleFormat:{month:"MMMM yyyy",week:"MMM d[ yyyy]{ '&#8212;'[ MMM] d yyyy}",day:"dddd, MMM d, yyyy"},columnFormat:{month:"ddd",week:"ddd M/d",day:"dddd M/d"},timeFormat:{"":"h(:mm)t"},isRTL:false,firstDay:0,monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan",
+"Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],buttonText:{prev:"&nbsp;&#9668;&nbsp;",next:"&nbsp;&#9658;&nbsp;",prevYear:"&nbsp;&lt;&lt;&nbsp;",nextYear:"&nbsp;&gt;&gt;&nbsp;",today:"today",month:"month",week:"week",day:"day"},theme:false,buttonIcons:{prev:"circle-triangle-w",next:"circle-triangle-e"},unselectAuto:true,dropAccept:"*"},yc=
+{header:{left:"next,prev today",center:"",right:"title"},buttonText:{prev:"&nbsp;&#9658;&nbsp;",next:"&nbsp;&#9668;&nbsp;",prevYear:"&nbsp;&gt;&gt;&nbsp;",nextYear:"&nbsp;&lt;&lt;&nbsp;"},buttonIcons:{prev:"circle-triangle-e",next:"circle-triangle-w"}},Aa=m.fullCalendar={version:"1.5.3"},Ja=Aa.views={};m.fn.fullCalendar=function(a){if(typeof a=="string"){var b=Array.prototype.slice.call(arguments,1),e;this.each(function(){var f=m.data(this,"fullCalendar");if(f&&m.isFunction(f[a])){f=f[a].apply(f,
+b);if(e===ma)e=f;a=="destroy"&&m.removeData(this,"fullCalendar")}});if(e!==ma)return e;return this}var d=a.eventSources||[];delete a.eventSources;if(a.events){d.push(a.events);delete a.events}a=m.extend(true,{},Ya,a.isRTL||a.isRTL===ma&&Ya.isRTL?yc:{},a);this.each(function(f,g){f=m(g);g=new Yb(f,a,d);f.data("fullCalendar",g);g.render()});return this};Aa.sourceNormalizers=[];Aa.sourceFetchers=[];var ac={dataType:"json",cache:false},bc=1;Aa.addDays=ba;Aa.cloneDate=N;Aa.parseDate=kb;Aa.parseISO8601=
+Bb;Aa.parseTime=mb;Aa.formatDate=Oa;Aa.formatDates=ib;var lc=["sun","mon","tue","wed","thu","fri","sat"],Ab=864E5,cc=36E5,wc=6E4,dc={s:function(a){return a.getSeconds()},ss:function(a){return Pa(a.getSeconds())},m:function(a){return a.getMinutes()},mm:function(a){return Pa(a.getMinutes())},h:function(a){return a.getHours()%12||12},hh:function(a){return Pa(a.getHours()%12||12)},H:function(a){return a.getHours()},HH:function(a){return Pa(a.getHours())},d:function(a){return a.getDate()},dd:function(a){return Pa(a.getDate())},
+ddd:function(a,b){return b.dayNamesShort[a.getDay()]},dddd:function(a,b){return b.dayNames[a.getDay()]},M:function(a){return a.getMonth()+1},MM:function(a){return Pa(a.getMonth()+1)},MMM:function(a,b){return b.monthNamesShort[a.getMonth()]},MMMM:function(a,b){return b.monthNames[a.getMonth()]},yy:function(a){return(a.getFullYear()+"").substring(2)},yyyy:function(a){return a.getFullYear()},t:function(a){return a.getHours()<12?"a":"p"},tt:function(a){return a.getHours()<12?"am":"pm"},T:function(a){return a.getHours()<
+12?"A":"P"},TT:function(a){return a.getHours()<12?"AM":"PM"},u:function(a){return Oa(a,"yyyy-MM-dd'T'HH:mm:ss'Z'")},S:function(a){a=a.getDate();if(a>10&&a<20)return"th";return["st","nd","rd"][a%10-1]||"th"}};Aa.applyAll=$a;Ja.month=mc;Ja.basicWeek=nc;Ja.basicDay=oc;wb({weekMode:"fixed"});Ja.agendaWeek=qc;Ja.agendaDay=rc;wb({allDaySlot:true,allDayText:"all-day",firstHour:6,slotMinutes:30,defaultEventMinutes:120,axisFormat:"h(:mm)tt",timeFormat:{agenda:"h:mm{ - h:mm}"},dragOpacity:{agenda:0.5},minTime:0,
+maxTime:24})})(jQuery);
diff --git a/library/fullcalendar/fullcalendar.print.css b/library/fullcalendar/fullcalendar.print.css
new file mode 100644
index 000000000..e11c18163
--- /dev/null
+++ b/library/fullcalendar/fullcalendar.print.css
@@ -0,0 +1,61 @@
+/*
+ * FullCalendar v1.5.3 Print Stylesheet
+ *
+ * Include this stylesheet on your page to get a more printer-friendly calendar.
+ * When including this stylesheet, use the media='print' attribute of the <link> tag.
+ * Make sure to include this stylesheet IN ADDITION to the regular fullcalendar.css.
+ *
+ * Copyright (c) 2011 Adam Shaw
+ * Dual licensed under the MIT and GPL licenses, located in
+ * MIT-LICENSE.txt and GPL-LICENSE.txt respectively.
+ *
+ * Date: Mon Feb 6 22:40:40 2012 -0800
+ *
+ */
+
+
+ /* Events
+-----------------------------------------------------*/
+
+.fc-event-skin {
+ background: none !important;
+ color: #000 !important;
+ }
+
+/* horizontal events */
+
+.fc-event-hori {
+ border-width: 0 0 1px 0 !important;
+ border-bottom-style: dotted !important;
+ border-bottom-color: #000 !important;
+ padding: 1px 0 0 0 !important;
+ }
+
+.fc-event-hori .fc-event-inner {
+ border-width: 0 !important;
+ padding: 0 1px !important;
+ }
+
+/* vertical events */
+
+.fc-event-vert {
+ border-width: 0 0 0 1px !important;
+ border-left-style: dotted !important;
+ border-left-color: #000 !important;
+ padding: 0 1px 0 0 !important;
+ }
+
+.fc-event-vert .fc-event-inner {
+ border-width: 0 !important;
+ padding: 1px 0 !important;
+ }
+
+.fc-event-bg {
+ display: none !important;
+ }
+
+.fc-event .ui-resizable-handle {
+ display: none !important;
+ }
+
+
diff --git a/library/fullcalendar/gcal.js b/library/fullcalendar/gcal.js
new file mode 100644
index 000000000..e9bbe26d8
--- /dev/null
+++ b/library/fullcalendar/gcal.js
@@ -0,0 +1,112 @@
+/*
+ * FullCalendar v1.5.3 Google Calendar Plugin
+ *
+ * Copyright (c) 2011 Adam Shaw
+ * Dual licensed under the MIT and GPL licenses, located in
+ * MIT-LICENSE.txt and GPL-LICENSE.txt respectively.
+ *
+ * Date: Mon Feb 6 22:40:40 2012 -0800
+ *
+ */
+
+(function($) {
+
+
+var fc = $.fullCalendar;
+var formatDate = fc.formatDate;
+var parseISO8601 = fc.parseISO8601;
+var addDays = fc.addDays;
+var applyAll = fc.applyAll;
+
+
+fc.sourceNormalizers.push(function(sourceOptions) {
+ if (sourceOptions.dataType == 'gcal' ||
+ sourceOptions.dataType === undefined &&
+ (sourceOptions.url || '').match(/^(http|https):\/\/www.google.com\/calendar\/feeds\//)) {
+ sourceOptions.dataType = 'gcal';
+ if (sourceOptions.editable === undefined) {
+ sourceOptions.editable = false;
+ }
+ }
+});
+
+
+fc.sourceFetchers.push(function(sourceOptions, start, end) {
+ if (sourceOptions.dataType == 'gcal') {
+ return transformOptions(sourceOptions, start, end);
+ }
+});
+
+
+function transformOptions(sourceOptions, start, end) {
+
+ var success = sourceOptions.success;
+ var data = $.extend({}, sourceOptions.data || {}, {
+ 'start-min': formatDate(start, 'u'),
+ 'start-max': formatDate(end, 'u'),
+ 'singleevents': true,
+ 'max-results': 9999
+ });
+
+ var ctz = sourceOptions.currentTimezone;
+ if (ctz) {
+ data.ctz = ctz = ctz.replace(' ', '_');
+ }
+
+ return $.extend({}, sourceOptions, {
+ url: sourceOptions.url.replace(/\/basic$/, '/full') + '?alt=json-in-script&callback=?',
+ dataType: 'jsonp',
+ data: data,
+ startParam: false,
+ endParam: false,
+ success: function(data) {
+ var events = [];
+ if (data.feed.entry) {
+ $.each(data.feed.entry, function(i, entry) {
+ var startStr = entry['gd$when'][0]['startTime'];
+ var start = parseISO8601(startStr, true);
+ var end = parseISO8601(entry['gd$when'][0]['endTime'], true);
+ var allDay = startStr.indexOf('T') == -1;
+ var url;
+ $.each(entry.link, function(i, link) {
+ if (link.type == 'text/html') {
+ url = link.href;
+ if (ctz) {
+ url += (url.indexOf('?') == -1 ? '?' : '&') + 'ctz=' + ctz;
+ }
+ }
+ });
+ if (allDay) {
+ addDays(end, -1); // make inclusive
+ }
+ events.push({
+ id: entry['gCal$uid']['value'],
+ title: entry['title']['$t'],
+ url: url,
+ start: start,
+ end: end,
+ allDay: allDay,
+ location: entry['gd$where'][0]['valueString'],
+ description: entry['content']['$t']
+ });
+ });
+ }
+ var args = [events].concat(Array.prototype.slice.call(arguments, 1));
+ var res = applyAll(success, this, args);
+ if ($.isArray(res)) {
+ return res;
+ }
+ return events;
+ }
+ });
+
+}
+
+
+// legacy
+fc.gcalFeed = function(url, sourceOptions) {
+ return $.extend({}, sourceOptions, { url: url, dataType: 'gcal' });
+};
+
+
+})(jQuery);
diff --git a/library/slinky.php b/library/slinky.php
index 51432c3f5..cae1f755f 100755
--- a/library/slinky.php
+++ b/library/slinky.php
@@ -153,7 +153,7 @@ class Slinky {
public function set_service_from_url( $url = false ) {
if ( !$url )
$url = $this->url;
-
+
$host = parse_url( $url, PHP_URL_HOST );
switch ( str_replace( 'www.', '', $host ) ) {
case 'bit.ly':
@@ -181,6 +181,11 @@ class Slinky {
$this->service = new Slinky_Fongs();
break;
}
+ case $this->get( 'yourls-url' ):
+ if ( class_exists( 'Slinky_YourLS' ) ) {
+ $this->service = new Slinky_YourLS();
+ break;
+ }
case 'micurl.com':
if ( class_exists( 'Slinky_Micurl' ) ) {
$this->service = new Slinky_Micurl();
@@ -574,6 +579,31 @@ class Slinky_Fongs extends Slinky_Service {
}
}
+// yourls
+class Slinky_YourLS extends Slinky_Service {
+ function url_is_short( $url ) {
+ return stristr( $url, 'shit.li/' );
+ }
+
+ function url_is_long( $url ) {
+ return !stristr( $url, 'shit.li/' );
+ }
+
+ function make_short( $url ) {
+ echo $this->get( 'username' );
+ $use_ssl = $this->get( 'ssl' );
+ if ( $use_ssl )
+ $use_ssl = 's';
+ else
+ $use_ssl = '';
+ $result = $this->url_get( 'http'. $use_ssl . '://' . $this->get( 'yourls-url' ) . '/yourls-api.php?username=' . $this->get( 'username' ) . '&password=' . $this->get( 'password' ) . '&action=shorturl&format=simple&url=' . urlencode( $url ) );
+ if ( 1 != $result && 2 != $result )
+ return $result;
+ else
+ return $url;
+ }
+}
+
// Micu.rl
class Slinky_Micurl extends Slinky_Service {
function url_is_short( $url ) {
diff --git a/library/spam/README b/library/spam/README
new file mode 100644
index 000000000..a0d67fca7
--- /dev/null
+++ b/library/spam/README
@@ -0,0 +1,12 @@
+B8 for Friendica
+
+B8 is an excellent bayesian spam implementation for PHP. However when evaluating it for use in Friendica there were a few shortcomings. B8's primary audience is guestbooks and blogs - single user situations.
+
+Friendica is a multi-user distributed social environment. So the first thing we need to add to b8 is a concept of user ID.
+
+Second we don't want to use a second stored set of DB login credentials so we're going to implemetn Friendica's MySQL driver and use our existing connection and credentials.
+
+The third requirement is that the B8 processing model is to load a set of word/data sets from the DB, perform processing (which may change the value of the data) and then store the results back to the DB. We're in a highly dynamic environment with lots of sometimes concurrent message processing. So the plan is to alter the storage architecture to read data in, do processing, and then apply a somewhat atomic change operation where the changes are performed in a single query using the current data in storage rather than something passed through outside processing and where the data may be outdated come time to store it.
+
+In accordance with the LGPL of the B8 package these changes are available in source form at http://github.com/friendica/friendica in the directory library/spam
+ \ No newline at end of file
diff --git a/library/spam/b8/b8.php b/library/spam/b8/b8.php
new file mode 100644
index 000000000..28a3dd29f
--- /dev/null
+++ b/library/spam/b8/b8.php
@@ -0,0 +1,503 @@
+<?php
+
+# Copyright (C) 2006-2010 Tobias Leupold <tobias.leupold@web.de>
+#
+# b8 - A Bayesian spam filter written in PHP 5
+#
+# This program 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 in version 2.1 of the License.
+#
+# 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 Lesser General Public
+# License for more details.
+#
+# You should have received a copy of the GNU Lesser 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.
+
+/**
+ * Copyright (C) 2006-2010 Tobias Leupold <tobias.leupold@web.de>
+ *
+ * @license LGPL
+ * @access public
+ * @package b8
+ * @author Tobias Leupold
+ * @author Oliver Lillie (aka buggedcom) (original PHP 5 port)
+ */
+
+class b8
+{
+
+ public $config = array(
+ 'min_size' => 3,
+ 'max_size' => 30,
+ 'allow_numbers' => FALSE,
+ 'lexer' => 'default',
+ 'degenerator' => 'default',
+ 'storage' => 'dba',
+ 'use_relevant' => 15,
+ 'min_dev' => 0.2,
+ 'rob_s' => 0.3,
+ 'rob_x' => 0.5
+ );
+
+ private $_lexer = NULL;
+ private $_database = NULL;
+ private $_token_data = NULL;
+
+ const SPAM = 'spam';
+ const HAM = 'ham';
+ const LEARN = 'learn';
+ const UNLEARN = 'unlearn';
+
+ const STARTUP_FAIL_DATABASE = 'STARTUP_FAIL_DATABASE';
+ const STARTUP_FAIL_LEXER = 'STARTUP_FAIL_LEXER';
+ const TRAINER_CATEGORY_FAIL = 'TRAINER_CATEGORY_FAIL';
+
+ /**
+ * Constructs b8
+ *
+ * @access public
+ * @return void
+ */
+
+ function __construct($config = array(), $database_config)
+ {
+
+ # Validate config data
+
+ if(count($config) > 0) {
+
+ foreach ($config as $name=>$value) {
+
+ switch($name) {
+
+ case 'min_dev':
+ case 'rob_s':
+ case 'rob_x':
+ $this->config[$name] = (float) $value;
+ break;
+
+ case 'min_size':
+ case 'max_size':
+ case 'use_relevant':
+ $this->config[$name] = (int) $value;
+ break;
+
+ case 'allow_numbers':
+ $this->config[$name] = (bool) $value;
+ break;
+
+ case 'lexer':
+ $value = (string) strtolower($value);
+ $this->config[$name] = is_file(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'lexer' . DIRECTORY_SEPARATOR . "lexer_" . $value . '.php') === TRUE ? $value : 'default';
+ break;
+
+ case 'storage':
+ $this->config[$name] = (string) $value;
+ break;
+
+ }
+
+ }
+
+ }
+
+ # Setup the database backend
+
+ # Get the basic storage class used by all backends
+ if($this->load_class('b8_storage_base', dirname(__FILE__) . DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR . 'storage_base.php') === FALSE)
+ return;
+
+ # Get the degenerator we need
+ if($this->load_class('b8_degenerator_' . $this->config['degenerator'], dirname(__FILE__) . DIRECTORY_SEPARATOR . 'degenerator' . DIRECTORY_SEPARATOR . 'degenerator_' . $this->config['degenerator'] . '.php') === FALSE)
+ return;
+
+ # Get the actual storage backend we need
+ if($this->load_class('b8_storage_' . $this->config['storage'], dirname(__FILE__) . DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR . 'storage_' . $this->config['storage'] . '.php') === FALSE)
+ return;
+
+ # Setup the backend
+ $class = 'b8_storage_' . $this->config['storage'];
+ $this->_database = new $class(
+ $database_config,
+ $this->config['degenerator'], date('ymd')
+ );
+
+ # Setup the lexer class
+
+ if($this->load_class('b8_lexer_' . $this->config['lexer'], dirname(__FILE__) . DIRECTORY_SEPARATOR . 'lexer' . DIRECTORY_SEPARATOR . 'lexer_' . $this->config['lexer'] . '.php') === FALSE)
+ return;
+
+ $class = 'b8_lexer_' . $this->config['lexer'];
+ $this->_lexer = new $class(
+ array(
+ 'min_size' => $this->config['min_size'],
+ 'max_size' => $this->config['max_size'],
+ 'allow_numbers' => $this->config['allow_numbers']
+ )
+ );
+
+ }
+
+ /**
+ * Load a class file if a class has not been defined yet.
+ *
+ * @access public
+ * @return boolean Returns TRUE if everything is okay, otherwise FALSE.
+ */
+
+ public function load_class($class_name, $class_file)
+ {
+
+ if(class_exists($class_name, FALSE) === FALSE) {
+
+ $included = require_once $class_file;
+
+ if($included === FALSE or class_exists($class_name, FALSE) === FALSE)
+ return FALSE;
+
+ }
+
+ return TRUE;
+
+ }
+
+ /**
+ * Validates the class has all it needs to work.
+ *
+ * @access public
+ * @return mixed Returns TRUE if everything is okay, otherwise an error code.
+ */
+
+ public function validate()
+ {
+
+ if($this->_database === NULL)
+ return self::STARTUP_FAIL_DATABASE;
+
+ # Connect the database backend if we aren't connected yet
+
+ elseif($this->_database->connected === FALSE) {
+
+ $connection = $this->_database->connect();
+
+ if($connection !== TRUE)
+ return $connection;
+
+ }
+
+ if($this->_lexer === NULL)
+ return self::STARTUP_FAIL_LEXER;
+
+ return TRUE;
+
+ }
+
+ /**
+ * Classifies a text
+ *
+ * @access public
+ * @package default
+ * @param string $text
+ * @return float The rating between 0 (ham) and 1 (spam)
+ */
+
+ public function classify($uid,$text)
+ {
+
+ # Validate the startup
+
+ $started_up = $this->validate();
+
+ if($started_up !== TRUE)
+ return $started_up;
+
+ # Get the internal database variables, containing the number of ham and
+ # spam texts so the spam probability can be calculated in relation to them
+ $internals = $this->_database->get_internals($uid);
+
+ # Calculate the spamminess of all tokens
+
+ # Get all tokens we want to rate
+
+ $tokens = $this->_lexer->get_tokens($text);
+
+ # Check if the lexer failed
+ # (if so, $tokens will be a lexer error code, if not, $tokens will be an array)
+ if(!is_array($tokens))
+ return $tokens;
+
+ # Fetch all availible data for the token set from the database
+ $this->_token_data = $this->_database->get(array_keys($tokens),$uid);
+
+ # Calculate the spamminess and importance for each token (or a degenerated form of it)
+
+ $word_count = array();
+ $rating = array();
+ $importance = array();
+
+ foreach($tokens as $word => $count) {
+
+ $word_count[$word] = $count;
+
+ # Although we only call this function only here ... let's do the
+ # calculation stuff in a function to make this a bit less confusing ;-)
+ $rating[$word] = $this->_get_probability($word, $internals['texts_ham'], $internals['texts_spam']);
+
+ $importance[$word] = abs(0.5 - $rating[$word]);
+
+ }
+
+ # Order by importance
+ arsort($importance);
+ reset($importance);
+
+ # Get the most interesting tokens (use all if we have less than the given number)
+
+ $relevant = array();
+
+ for($i = 0; $i < $this->config['use_relevant']; $i++) {
+
+ if($tmp = each($importance)) {
+
+ # Important tokens remain
+
+ # If the token's rating is relevant enough, use it
+
+ if(abs(0.5 - $rating[$tmp['key']]) > $this->config['min_dev']) {
+
+ # Tokens that appear more than once also count more than once
+
+ for($x = 0, $l = $word_count[$tmp['key']]; $x < $l; $x++)
+ array_push($relevant, $rating[$tmp['key']]);
+
+ }
+
+ }
+
+ else {
+ # We have less than words to use, so we already
+ # use what we have and can break here
+ break;
+ }
+
+ }
+
+ # Calculate the spamminess of the text (thanks to Mr. Robinson ;-)
+ # We set both hamminess and Spamminess to 1 for the first multiplying
+ $hamminess = 1;
+ $spamminess = 1;
+
+ # Consider all relevant ratings
+ foreach($relevant as $value) {
+ $hamminess *= (1.0 - $value);
+ $spamminess *= $value;
+ }
+
+ # If no token was good for calculation, we really don't know how
+ # to rate this text; so we assume a spam and ham probability of 0.5
+
+ if($hamminess === 1 and $spamminess === 1) {
+ $hamminess = 0.5;
+ $spamminess = 0.5;
+ $n = 1;
+ }
+ else {
+ # Get the number of relevant ratings
+ $n = count($relevant);
+ }
+
+ # Calculate the combined rating
+
+ # The actual hamminess and spamminess
+ $hamminess = 1 - pow($hamminess, (1 / $n));
+ $spamminess = 1 - pow($spamminess, (1 / $n));
+
+ # Calculate the combined indicator
+ $probability = ($hamminess - $spamminess) / ($hamminess + $spamminess);
+
+ # We want a value between 0 and 1, not between -1 and +1, so ...
+ $probability = (1 + $probability) / 2;
+
+ # Alea iacta est
+ return $probability;
+
+ }
+
+ /**
+ * Calculate the spamminess of a single token also considering "degenerated" versions
+ *
+ * @access private
+ * @param string $word
+ * @param string $texts_ham
+ * @param string $texts_spam
+ * @return void
+ */
+
+ private function _get_probability($word, $texts_ham, $texts_spam)
+ {
+
+ # Let's see what we have!
+
+ if(isset($this->_token_data['tokens'][$word]) === TRUE) {
+ # The token was in the database, so we can use it's data as-is
+ # and calculate the spamminess of this token directly
+ return $this->_calc_probability($this->_token_data['tokens'][$word], $texts_ham, $texts_spam);
+ }
+
+ # Damn. The token was not found, so do we have at least similar words?
+
+ if(isset($this->_token_data['degenerates'][$word]) === TRUE) {
+
+ # We found similar words, so calculate the spamminess for each one
+ # and choose the most important one for the further calculation
+
+ # The default rating is 0.5 simply saying nothing
+ $rating = 0.5;
+
+ foreach($this->_token_data['degenerates'][$word] as $degenerate => $count) {
+
+ # Calculate the rating of the current degenerated token
+ $rating_tmp = $this->_calc_probability($count, $texts_ham, $texts_spam);
+
+ # Is it more important than the rating of another degenerated version?
+ if(abs(0.5 - $rating_tmp) > abs(0.5 - $rating))
+ $rating = $rating_tmp;
+
+ }
+
+ return $rating;
+
+ }
+
+ else {
+ # The token is really unknown, so choose the default rating
+ # for completely unknown tokens. This strips down to the
+ # robX parameter so we can cheap out the freaky math ;-)
+ return $this->config['rob_x'];
+ }
+
+ }
+
+ /**
+ * Do the actual spamminess calculation of a single token
+ *
+ * @access private
+ * @param array $data
+ * @param string $texts_ham
+ * @param string $texts_spam
+ * @return void
+ */
+
+ private function _calc_probability($data, $texts_ham, $texts_spam)
+ {
+
+ # Calculate the basic probability by Mr. Graham
+
+ # But: consider the number of ham and spam texts saved instead of the
+ # number of entries where the token appeared to calculate a relative
+ # spamminess because we count tokens appearing multiple times not just
+ # once but as often as they appear in the learned texts
+
+ $rel_ham = $data['count_ham'];
+ $rel_spam = $data['count_spam'];
+
+ if($texts_ham > 0)
+ $rel_ham = $data['count_ham'] / $texts_ham;
+
+ if($texts_spam > 0)
+ $rel_spam = $data['count_spam'] / $texts_spam;
+
+ $rating = $rel_spam / ($rel_ham + $rel_spam);
+
+ # Calculate the better probability proposed by Mr. Robinson
+ $all = $data['count_ham'] + $data['count_spam'];
+ return (($this->config['rob_s'] * $this->config['rob_x']) + ($all * $rating)) / ($this->config['rob_s'] + $all);
+
+ }
+
+ /**
+ * Check the validity of the category of a request
+ *
+ * @access private
+ * @param string $category
+ * @return void
+ */
+
+ private function _check_category($category)
+ {
+ return $category === self::HAM or $category === self::SPAM;
+ }
+
+ /**
+ * Learn a reference text
+ *
+ * @access public
+ * @param string $text
+ * @param const $category Either b8::SPAM or b8::HAM
+ * @return void
+ */
+
+ public function learn($text, $category, $uid)
+ {
+ return $this->_process_text($text, $category, self::LEARN, $uid);
+ }
+
+ /**
+ * Unlearn a reference text
+ *
+ * @access public
+ * @param string $text
+ * @param const $category Either b8::SPAM or b8::HAM
+ * @return void
+ */
+
+ public function unlearn($text, $category, $uid)
+ {
+ return $this->_process_text($text, $category, self::UNLEARN, $uid);
+ }
+
+ /**
+ * Does the actual interaction with the storage backend for learning or unlearning texts
+ *
+ * @access private
+ * @param string $text
+ * @param const $category Either b8::SPAM or b8::HAM
+ * @param const $action Either b8::LEARN or b8::UNLEARN
+ * @return void
+ */
+
+ private function _process_text($text, $category, $action, $uid = 0)
+ {
+
+ # Validate the startup
+
+ $started_up = $this->validate();
+
+ if($started_up !== TRUE)
+ return $started_up;
+
+ # Look if the request is okay
+ if($this->_check_category($category) === FALSE)
+ return self::TRAINER_CATEGORY_FAIL;
+
+ # Get all tokens from $text
+
+ $tokens = $this->_lexer->get_tokens($text);
+
+ # Check if the lexer failed
+ # (if so, $tokens will be a lexer error code, if not, $tokens will be an array)
+ if(!is_array($tokens))
+ return $tokens;
+
+ # Pass the tokens and what to do with it to the storage backend
+ return $this->_database->process_text($tokens, $category, $action, $uid);
+
+ }
+
+}
+
+?> \ No newline at end of file
diff --git a/library/spam/b8/b8.php.ORIG b/library/spam/b8/b8.php.ORIG
new file mode 100644
index 000000000..ea1e15ffa
--- /dev/null
+++ b/library/spam/b8/b8.php.ORIG
@@ -0,0 +1,503 @@
+<?php
+
+# Copyright (C) 2006-2010 Tobias Leupold <tobias.leupold@web.de>
+#
+# b8 - A Bayesian spam filter written in PHP 5
+#
+# This program 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 in version 2.1 of the License.
+#
+# 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 Lesser General Public
+# License for more details.
+#
+# You should have received a copy of the GNU Lesser 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.
+
+/**
+ * Copyright (C) 2006-2010 Tobias Leupold <tobias.leupold@web.de>
+ *
+ * @license LGPL
+ * @access public
+ * @package b8
+ * @author Tobias Leupold
+ * @author Oliver Lillie (aka buggedcom) (original PHP 5 port)
+ */
+
+class b8
+{
+
+ public $config = array(
+ 'min_size' => 3,
+ 'max_size' => 30,
+ 'allow_numbers' => FALSE,
+ 'lexer' => 'default',
+ 'degenerator' => 'default',
+ 'storage' => 'dba',
+ 'use_relevant' => 15,
+ 'min_dev' => 0.2,
+ 'rob_s' => 0.3,
+ 'rob_x' => 0.5
+ );
+
+ private $_lexer = NULL;
+ private $_database = NULL;
+ private $_token_data = NULL;
+
+ const SPAM = 'spam';
+ const HAM = 'ham';
+ const LEARN = 'learn';
+ const UNLEARN = 'unlearn';
+
+ const STARTUP_FAIL_DATABASE = 'STARTUP_FAIL_DATABASE';
+ const STARTUP_FAIL_LEXER = 'STARTUP_FAIL_LEXER';
+ const TRAINER_CATEGORY_FAIL = 'TRAINER_CATEGORY_FAIL';
+
+ /**
+ * Constructs b8
+ *
+ * @access public
+ * @return void
+ */
+
+ function __construct($config = array(), $database_config)
+ {
+
+ # Validate config data
+
+ if(count($config) > 0) {
+
+ foreach ($config as $name=>$value) {
+
+ switch($name) {
+
+ case 'min_dev':
+ case 'rob_s':
+ case 'rob_x':
+ $this->config[$name] = (float) $value;
+ break;
+
+ case 'min_size':
+ case 'max_size':
+ case 'use_relevant':
+ $this->config[$name] = (int) $value;
+ break;
+
+ case 'allow_numbers':
+ $this->config[$name] = (bool) $value;
+ break;
+
+ case 'lexer':
+ $value = (string) strtolower($value);
+ $this->config[$name] = is_file(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'lexer' . DIRECTORY_SEPARATOR . "lexer_" . $value . '.php') === TRUE ? $value : 'default';
+ break;
+
+ case 'storage':
+ $this->config[$name] = (string) $value;
+ break;
+
+ }
+
+ }
+
+ }
+
+ # Setup the database backend
+
+ # Get the basic storage class used by all backends
+ if($this->load_class('b8_storage_base', dirname(__FILE__) . DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR . 'storage_base.php') === FALSE)
+ return;
+
+ # Get the degenerator we need
+ if($this->load_class('b8_degenerator_' . $this->config['degenerator'], dirname(__FILE__) . DIRECTORY_SEPARATOR . 'degenerator' . DIRECTORY_SEPARATOR . 'degenerator_' . $this->config['degenerator'] . '.php') === FALSE)
+ return;
+
+ # Get the actual storage backend we need
+ if($this->load_class('b8_storage_' . $this->config['storage'], dirname(__FILE__) . DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR . 'storage_' . $this->config['storage'] . '.php') === FALSE)
+ return;
+
+ # Setup the backend
+ $class = 'b8_storage_' . $this->config['storage'];
+ $this->_database = new $class(
+ $database_config,
+ $this->config['degenerator'], date('ymd')
+ );
+
+ # Setup the lexer class
+
+ if($this->load_class('b8_lexer_' . $this->config['lexer'], dirname(__FILE__) . DIRECTORY_SEPARATOR . 'lexer' . DIRECTORY_SEPARATOR . 'lexer_' . $this->config['lexer'] . '.php') === FALSE)
+ return;
+
+ $class = 'b8_lexer_' . $this->config['lexer'];
+ $this->_lexer = new $class(
+ array(
+ 'min_size' => $this->config['min_size'],
+ 'max_size' => $this->config['max_size'],
+ 'allow_numbers' => $this->config['allow_numbers']
+ )
+ );
+
+ }
+
+ /**
+ * Load a class file if a class has not been defined yet.
+ *
+ * @access public
+ * @return boolean Returns TRUE if everything is okay, otherwise FALSE.
+ */
+
+ public function load_class($class_name, $class_file)
+ {
+
+ if(class_exists($class_name, FALSE) === FALSE) {
+
+ $included = require_once $class_file;
+
+ if($included === FALSE or class_exists($class_name, FALSE) === FALSE)
+ return FALSE;
+
+ }
+
+ return TRUE;
+
+ }
+
+ /**
+ * Validates the class has all it needs to work.
+ *
+ * @access public
+ * @return mixed Returns TRUE if everything is okay, otherwise an error code.
+ */
+
+ public function validate()
+ {
+
+ if($this->_database === NULL)
+ return self::STARTUP_FAIL_DATABASE;
+
+ # Connect the database backend if we aren't connected yet
+
+ elseif($this->_database->connected === FALSE) {
+
+ $connection = $this->_database->connect();
+
+ if($connection !== TRUE)
+ return $connection;
+
+ }
+
+ if($this->_lexer === NULL)
+ return self::STARTUP_FAIL_LEXER;
+
+ return TRUE;
+
+ }
+
+ /**
+ * Classifies a text
+ *
+ * @access public
+ * @package default
+ * @param string $text
+ * @return float The rating between 0 (ham) and 1 (spam)
+ */
+
+ public function classify($text)
+ {
+
+ # Validate the startup
+
+ $started_up = $this->validate();
+
+ if($started_up !== TRUE)
+ return $started_up;
+
+ # Get the internal database variables, containing the number of ham and
+ # spam texts so the spam probability can be calculated in relation to them
+ $internals = $this->_database->get_internals();
+
+ # Calculate the spamminess of all tokens
+
+ # Get all tokens we want to rate
+
+ $tokens = $this->_lexer->get_tokens($text);
+
+ # Check if the lexer failed
+ # (if so, $tokens will be a lexer error code, if not, $tokens will be an array)
+ if(!is_array($tokens))
+ return $tokens;
+
+ # Fetch all availible data for the token set from the database
+ $this->_token_data = $this->_database->get(array_keys($tokens));
+
+ # Calculate the spamminess and importance for each token (or a degenerated form of it)
+
+ $word_count = array();
+ $rating = array();
+ $importance = array();
+
+ foreach($tokens as $word => $count) {
+
+ $word_count[$word] = $count;
+
+ # Although we only call this function only here ... let's do the
+ # calculation stuff in a function to make this a bit less confusing ;-)
+ $rating[$word] = $this->_get_probability($word, $internals['texts_ham'], $internals['texts_spam']);
+
+ $importance[$word] = abs(0.5 - $rating[$word]);
+
+ }
+
+ # Order by importance
+ arsort($importance);
+ reset($importance);
+
+ # Get the most interesting tokens (use all if we have less than the given number)
+
+ $relevant = array();
+
+ for($i = 0; $i < $this->config['use_relevant']; $i++) {
+
+ if($tmp = each($importance)) {
+
+ # Important tokens remain
+
+ # If the token's rating is relevant enough, use it
+
+ if(abs(0.5 - $rating[$tmp['key']]) > $this->config['min_dev']) {
+
+ # Tokens that appear more than once also count more than once
+
+ for($x = 0, $l = $word_count[$tmp['key']]; $x < $l; $x++)
+ array_push($relevant, $rating[$tmp['key']]);
+
+ }
+
+ }
+
+ else {
+ # We have less than words to use, so we already
+ # use what we have and can break here
+ break;
+ }
+
+ }
+
+ # Calculate the spamminess of the text (thanks to Mr. Robinson ;-)
+ # We set both hamminess and Spamminess to 1 for the first multiplying
+ $hamminess = 1;
+ $spamminess = 1;
+
+ # Consider all relevant ratings
+ foreach($relevant as $value) {
+ $hamminess *= (1.0 - $value);
+ $spamminess *= $value;
+ }
+
+ # If no token was good for calculation, we really don't know how
+ # to rate this text; so we assume a spam and ham probability of 0.5
+
+ if($hamminess === 1 and $spamminess === 1) {
+ $hamminess = 0.5;
+ $spamminess = 0.5;
+ $n = 1;
+ }
+ else {
+ # Get the number of relevant ratings
+ $n = count($relevant);
+ }
+
+ # Calculate the combined rating
+
+ # The actual hamminess and spamminess
+ $hamminess = 1 - pow($hamminess, (1 / $n));
+ $spamminess = 1 - pow($spamminess, (1 / $n));
+
+ # Calculate the combined indicator
+ $probability = ($hamminess - $spamminess) / ($hamminess + $spamminess);
+
+ # We want a value between 0 and 1, not between -1 and +1, so ...
+ $probability = (1 + $probability) / 2;
+
+ # Alea iacta est
+ return $probability;
+
+ }
+
+ /**
+ * Calculate the spamminess of a single token also considering "degenerated" versions
+ *
+ * @access private
+ * @param string $word
+ * @param string $texts_ham
+ * @param string $texts_spam
+ * @return void
+ */
+
+ private function _get_probability($word, $texts_ham, $texts_spam)
+ {
+
+ # Let's see what we have!
+
+ if(isset($this->_token_data['tokens'][$word]) === TRUE) {
+ # The token was in the database, so we can use it's data as-is
+ # and calculate the spamminess of this token directly
+ return $this->_calc_probability($this->_token_data['tokens'][$word], $texts_ham, $texts_spam);
+ }
+
+ # Damn. The token was not found, so do we have at least similar words?
+
+ if(isset($this->_token_data['degenerates'][$word]) === TRUE) {
+
+ # We found similar words, so calculate the spamminess for each one
+ # and choose the most important one for the further calculation
+
+ # The default rating is 0.5 simply saying nothing
+ $rating = 0.5;
+
+ foreach($this->_token_data['degenerates'][$word] as $degenerate => $count) {
+
+ # Calculate the rating of the current degenerated token
+ $rating_tmp = $this->_calc_probability($count, $texts_ham, $texts_spam);
+
+ # Is it more important than the rating of another degenerated version?
+ if(abs(0.5 - $rating_tmp) > abs(0.5 - $rating))
+ $rating = $rating_tmp;
+
+ }
+
+ return $rating;
+
+ }
+
+ else {
+ # The token is really unknown, so choose the default rating
+ # for completely unknown tokens. This strips down to the
+ # robX parameter so we can cheap out the freaky math ;-)
+ return $this->config['rob_x'];
+ }
+
+ }
+
+ /**
+ * Do the actual spamminess calculation of a single token
+ *
+ * @access private
+ * @param array $data
+ * @param string $texts_ham
+ * @param string $texts_spam
+ * @return void
+ */
+
+ private function _calc_probability($data, $texts_ham, $texts_spam)
+ {
+
+ # Calculate the basic probability by Mr. Graham
+
+ # But: consider the number of ham and spam texts saved instead of the
+ # number of entries where the token appeared to calculate a relative
+ # spamminess because we count tokens appearing multiple times not just
+ # once but as often as they appear in the learned texts
+
+ $rel_ham = $data['count_ham'];
+ $rel_spam = $data['count_spam'];
+
+ if($texts_ham > 0)
+ $rel_ham = $data['count_ham'] / $texts_ham;
+
+ if($texts_spam > 0)
+ $rel_spam = $data['count_spam'] / $texts_spam;
+
+ $rating = $rel_spam / ($rel_ham + $rel_spam);
+
+ # Calculate the better probability proposed by Mr. Robinson
+ $all = $data['count_ham'] + $data['count_spam'];
+ return (($this->config['rob_s'] * $this->config['rob_x']) + ($all * $rating)) / ($this->config['rob_s'] + $all);
+
+ }
+
+ /**
+ * Check the validity of the category of a request
+ *
+ * @access private
+ * @param string $category
+ * @return void
+ */
+
+ private function _check_category($category)
+ {
+ return $category === self::HAM or $category === self::SPAM;
+ }
+
+ /**
+ * Learn a reference text
+ *
+ * @access public
+ * @param string $text
+ * @param const $category Either b8::SPAM or b8::HAM
+ * @return void
+ */
+
+ public function learn($text, $category)
+ {
+ return $this->_process_text($text, $category, self::LEARN);
+ }
+
+ /**
+ * Unlearn a reference text
+ *
+ * @access public
+ * @param string $text
+ * @param const $category Either b8::SPAM or b8::HAM
+ * @return void
+ */
+
+ public function unlearn($text, $category)
+ {
+ return $this->_process_text($text, $category, self::UNLEARN);
+ }
+
+ /**
+ * Does the actual interaction with the storage backend for learning or unlearning texts
+ *
+ * @access private
+ * @param string $text
+ * @param const $category Either b8::SPAM or b8::HAM
+ * @param const $action Either b8::LEARN or b8::UNLEARN
+ * @return void
+ */
+
+ private function _process_text($text, $category, $action)
+ {
+
+ # Validate the startup
+
+ $started_up = $this->validate();
+
+ if($started_up !== TRUE)
+ return $started_up;
+
+ # Look if the request is okay
+ if($this->_check_category($category) === FALSE)
+ return self::TRAINER_CATEGORY_FAIL;
+
+ # Get all tokens from $text
+
+ $tokens = $this->_lexer->get_tokens($text);
+
+ # Check if the lexer failed
+ # (if so, $tokens will be a lexer error code, if not, $tokens will be an array)
+ if(!is_array($tokens))
+ return $tokens;
+
+ # Pass the tokens and what to do with it to the storage backend
+ return $this->_database->process_text($tokens, $category, $action);
+
+ }
+
+}
+
+?> \ No newline at end of file
diff --git a/library/spam/b8/degenerator/degenerator_default.php b/library/spam/b8/degenerator/degenerator_default.php
new file mode 100644
index 000000000..4ff6d882b
--- /dev/null
+++ b/library/spam/b8/degenerator/degenerator_default.php
@@ -0,0 +1,127 @@
+<?php
+
+# Copyright (C) 2006-2010 Tobias Leupold <tobias.leupold@web.de>
+#
+# This file is part of the b8 package
+#
+# This program 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 in version 2.1 of the License.
+#
+# 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 Lesser General Public
+# License for more details.
+#
+# You should have received a copy of the GNU Lesser 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.
+
+/**
+ * Copyright (C) 2006-2010 Tobias Leupold <tobias.leupold@web.de>
+ *
+ * @license LGPL
+ * @access public
+ * @package b8
+ * @author Tobias Leupold
+ */
+
+class b8_degenerator_default
+{
+
+ public $degenerates = array();
+
+ /**
+ * Generates a list of "degenerated" words for a list of words.
+ *
+ * @access public
+ * @param array $tokens
+ * @return array An array containing an array of degenerated tokens for each token
+ */
+
+ public function degenerate(array $words)
+ {
+
+ $degenerates = array();
+
+ foreach($words as $word)
+ $degenerates[$word] = $this->_degenerate_word($word);
+
+ return $degenerates;
+
+ }
+
+ /**
+ * If the original word is not found in the database then
+ * we build "degenerated" versions of the word to lookup.
+ *
+ * @access private
+ * @param string $word
+ * @return array An array of degenerated words
+ */
+
+ protected function _degenerate_word($word)
+ {
+
+ # Check for any stored words so the process doesn't have to repeat
+ if(isset($this->degenerates[$word]) === TRUE)
+ return $this->degenerates[$word];
+
+ $degenerate = array();
+
+ # Add different version of upper and lower case and ucfirst
+ array_push($degenerate, strtolower($word));
+ array_push($degenerate, strtoupper($word));
+ array_push($degenerate, ucfirst($word));
+
+ # Degenerate all versions
+
+ foreach($degenerate as $alt_word) {
+
+ # Look for stuff like !!! and ???
+
+ if(preg_match('/[!?]$/', $alt_word) > 0) {
+
+ # Add versions with different !s and ?s
+
+ if(preg_match('/[!?]{2,}$/', $alt_word) > 0) {
+ $tmp = preg_replace('/([!?])+$/', '$1', $alt_word);
+ array_push($degenerate, $tmp);
+ }
+
+ $tmp = preg_replace('/([!?])+$/', '', $alt_word);
+ array_push($degenerate, $tmp);
+
+ }
+
+ # Look for ... at the end of the word
+
+ $alt_word_int = $alt_word;
+
+ while(preg_match('/[\.]$/', $alt_word_int) > 0) {
+ $alt_word_int = substr($alt_word_int, 0, strlen($alt_word_int) - 1);
+ array_push($degenerate, $alt_word_int);
+ }
+
+ }
+
+ # Some degenerates are the same as the original word. These don't have
+ # to be fetched, so we create a new array with only new tokens
+
+ $real_degenerate = array();
+
+ foreach($degenerate as $deg_word) {
+ if($word != $deg_word)
+ array_push($real_degenerate, $deg_word);
+ }
+
+ # Store the list of degenerates for the token
+ $this->degenerates[$word] = $real_degenerate;
+
+ return $real_degenerate;
+
+ }
+
+}
+
+?> \ No newline at end of file
diff --git a/library/spam/b8/lexer/lexer_default.php b/library/spam/b8/lexer/lexer_default.php
new file mode 100644
index 000000000..7b5ca22bf
--- /dev/null
+++ b/library/spam/b8/lexer/lexer_default.php
@@ -0,0 +1,205 @@
+<?php
+
+# Copyright (C) 2006-2010 Tobias Leupold <tobias.leupold@web.de>
+#
+# This file is part of the b8 package
+#
+# This program 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 in version 2.1 of the License.
+#
+# 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 Lesser General Public
+# License for more details.
+#
+# You should have received a copy of the GNU Lesser 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.
+
+/**
+ * Copyright (C) 2006-2010 Tobias Leupold <tobias.leupold@web.de>
+ *
+ * @license LGPL
+ * @access public
+ * @package b8
+ * @author Tobias Leupold
+ * @author Oliver Lillie (aka buggedcom) (original PHP 5 port)
+ */
+
+class b8_lexer_default
+{
+
+ const LEXER_TEXT_NOT_STRING = 'LEXER_TEXT_NOT_STRING';
+ const LEXER_TEXT_EMPTY = 'LEXER_TEXT_EMPTY';
+
+ public $config = NULL;
+
+ # The regular expressions we use to split the text to tokens
+
+ public $regexp = array(
+ 'ip' => '/([A-Za-z0-9\_\-\.]+)/',
+ 'raw_split' => '/[\s,\.\/"\:;\|<>\-_\[\]{}\+=\)\(\*\&\^%]+/',
+ 'html' => '/(<.+?>)/',
+ 'tagname' => '/(.+?)\s/',
+ 'numbers' => '/^[0-9]+$/'
+ );
+
+ /**
+ * Constructs the lexer.
+ *
+ * @access public
+ * @return void
+ */
+
+ function __construct($config)
+ {
+ $this->config = $config;
+ }
+
+ /**
+ * Generates the tokens required for the bayesian filter.
+ *
+ * @access public
+ * @param string $text
+ * @return array Returns the list of tokens
+ */
+
+ public function get_tokens($text)
+ {
+
+ # Check that we actually have a string ...
+ if(is_string($text) === FALSE)
+ return self::LEXER_TEXT_NOT_STRING;
+
+ # ... and that it's not empty
+ if(empty($text) === TRUE)
+ return self::LEXER_TEXT_EMPTY;
+
+ # Re-convert the text to the original characters coded in UTF-8, as
+ # they have been coded in html entities during the post process
+ $text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
+
+ $tokens = array();
+
+ # Find URLs and IP addresses
+
+ preg_match_all($this->regexp['ip'], $text, $raw_tokens);
+
+ foreach($raw_tokens[1] as $word) {
+
+ # Check for a dot
+ if(strpos($word, '.') === FALSE)
+ continue;
+
+ # Check that the word is valid, min and max sizes, etc.
+ if($this->_is_valid($word) === FALSE)
+ continue;
+
+ if(isset($tokens[$word]) === FALSE)
+ $tokens[$word] = 1;
+ else
+ $tokens[$word] += 1;
+
+ # Delete the word from the text so it doesn't get re-added.
+ $text = str_replace($word, '', $text);
+
+ # Also process the parts of the URLs
+ $url_parts = preg_split($this->regexp['raw_split'], $word);
+
+ foreach($url_parts as $word) {
+
+ # Again validate the part
+
+ if($this->_is_valid($word) === FALSE)
+ continue;
+
+ if(isset($tokens[$word]) === FALSE)
+ $tokens[$word] = 1;
+ else
+ $tokens[$word] += 1;
+
+ }
+
+ }
+
+ # Split the remaining text
+
+ $raw_tokens = preg_split($this->regexp['raw_split'], $text);
+
+ foreach($raw_tokens as $word) {
+
+ # Again validate the part
+
+ if($this->_is_valid($word) === FALSE)
+ continue;
+
+ if(isset($tokens[$word]) === FALSE)
+ $tokens[$word] = 1;
+ else
+ $tokens[$word] += 1;
+
+ }
+
+ # Process the HTML
+
+ preg_match_all($this->regexp['html'], $text, $raw_tokens);
+
+ foreach($raw_tokens[1] as $word) {
+
+ # Again validate the part
+
+ if($this->_is_valid($word) === FALSE)
+ continue;
+
+ # If the tag has parameters, just use the tag itself
+
+ if(strpos($word, ' ') !== FALSE) {
+ preg_match($this->regexp['tagname'], $word, $tmp);
+ $word = "{$tmp[1]}...>";
+ }
+
+ if(isset($tokens[$word]) === FALSE)
+ $tokens[$word] = 1;
+ else
+ $tokens[$word] += 1;
+
+ }
+
+ # Return a list of all found tokens
+ return $tokens;
+
+ }
+
+ /**
+ * Validates a token.
+ *
+ * @access private
+ * @param string $token The token string.
+ * @return boolean Returns TRUE if the token is valid, otherwise returns FALSE
+ */
+
+ private function _is_valid($token)
+ {
+
+ # Validate the size of the token
+
+ $len = strlen($token);
+
+ if($len < $this->config['min_size'] or $len > $this->config['max_size'])
+ return FALSE;
+
+ # We may want to exclude pure numbers
+ if($this->config['allow_numbers'] === FALSE) {
+ if(preg_match($this->regexp['numbers'], $token) > 0)
+ return FALSE;
+ }
+
+ # Token is okay
+ return TRUE;
+
+ }
+
+}
+
+?> \ No newline at end of file
diff --git a/library/spam/b8/storage/storage_base.php b/library/spam/b8/storage/storage_base.php
new file mode 100644
index 000000000..6b181ee96
--- /dev/null
+++ b/library/spam/b8/storage/storage_base.php
@@ -0,0 +1,396 @@
+<?php
+
+# Copyright (C) 2010 Tobias Leupold <tobias.leupold@web.de>
+#
+# This file is part of the b8 package
+#
+# This program 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 in version 2.1 of the License.
+#
+# 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 Lesser General Public
+# License for more details.
+#
+# You should have received a copy of the GNU Lesser 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.
+
+/**
+ * Functions used by all storage backends
+ * Copyright (C) 2010 Tobias Leupold <tobias.leupold@web.de>
+ *
+ * @license LGPL
+ * @access public
+ * @package b8
+ * @author Tobias Leupold
+ */
+
+abstract class b8_storage_base
+{
+
+ public $connected = FALSE;
+
+ protected $_degenerator = NULL;
+
+ const INTERNALS_TEXTS_HAM = 'bayes*texts.ham';
+ const INTERNALS_TEXTS_SPAM = 'bayes*texts.spam';
+ const INTERNALS_DBVERSION = 'bayes*dbversion';
+
+ const BACKEND_NOT_CONNECTED = 'BACKEND_NOT_CONNECTED';
+ const DATABASE_WRONG_VERSION = 'DATABASE_WRONG_VERSION';
+ const DATABASE_NOT_B8 = 'DATABASE_NOT_B8';
+
+ /**
+ * Validates the class has all it needs to work.
+ *
+ * @access protected
+ * @return mixed Returns TRUE if everything is okay, otherwise an error code.
+ */
+
+ protected function validate()
+ {
+
+ # We set up the degenerator here, as we would have to duplicate code if it
+ # was done in the constructor of the respective storage backend.
+ $class = 'b8_degenerator_' . $this->b8_config['degenerator'];
+ $this->_degenerator = new $class();
+
+ if($this->connected !== TRUE)
+ return self::BACKEND_NOT_CONNECTED;
+
+ return TRUE;
+
+ }
+
+ /**
+ * Checks if a b8 database is used and if it's version is okay
+ *
+ * @access protected
+ * @return mixed Returns TRUE if everything is okay, otherwise an error code.
+ */
+
+ protected function check_database($uid)
+ {
+
+ $internals = $this->get_internals($uid);
+
+ if(isset($internals['dbversion'])) {
+ if($internals['dbversion'] == "2") {
+ return TRUE;
+ }
+ else {
+ $this->connected = FALSE;
+ return self::DATABASE_WRONG_VERSION;
+ }
+ }
+ else {
+ $this->connected = FALSE;
+ return self::DATABASE_NOT_B8;
+ }
+
+ }
+
+ /**
+ * Parses the "count" data of a token.
+ *
+ * @access private
+ * @param string $data
+ * @return array Returns an array of the parsed data: array(count_ham, count_spam, lastseen).
+ */
+
+ private function _parse_count($data)
+ {
+
+ list($count_ham, $count_spam, $lastseen) = explode(' ', $data);
+
+ $count_ham = (int) $count_ham;
+ $count_spam = (int) $count_spam;
+
+ return array(
+ 'count_ham' => $count_ham,
+ 'count_spam' => $count_spam
+ );
+
+ }
+
+ /**
+ * Get the database's internal variables.
+ *
+ * @access public
+ * @return array Returns an array of all internals.
+ */
+
+ public function get_internals($uid)
+ {
+
+ $internals = $this->_get_query(
+ array(
+ self::INTERNALS_TEXTS_HAM,
+ self::INTERNALS_TEXTS_SPAM,
+ self::INTERNALS_DBVERSION
+ ),
+ $uid
+ );
+
+ return array(
+ 'texts_ham' => (int) $internals[self::INTERNALS_TEXTS_HAM],
+ 'texts_spam' => (int) $internals[self::INTERNALS_TEXTS_SPAM],
+ 'dbversion' => (int) $internals[self::INTERNALS_DBVERSION]
+ );
+
+ }
+
+ /**
+ * Get all data about a list of tags from the database.
+ *
+ * @access public
+ * @param array $tokens
+ * @return mixed Returns FALSE on failure, otherwise returns array of returned data in the format array('tokens' => array(token => count), 'degenerates' => array(token => array(degenerate => count))).
+ */
+
+ public function get($tokens, $uid)
+ {
+
+ # Validate the startup
+
+ $started_up = $this->validate();
+
+ if($started_up !== TRUE)
+ return $started_up;
+
+ # First we see what we have in the database.
+ $token_data = $this->_get_query($tokens, $uid);
+
+ # Check if we have to degenerate some tokens
+
+ $missing_tokens = array();
+
+ foreach($tokens as $token) {
+ if(!isset($token_data[$token]))
+ $missing_tokens[] = $token;
+ }
+
+ if(count($missing_tokens) > 0) {
+
+ # We have to degenerate some tokens
+ $degenerates_list = array();
+
+ # Generate a list of degenerated tokens for the missing tokens ...
+ $degenerates = $this->_degenerator->degenerate($missing_tokens);
+
+ # ... and look them up
+
+ foreach($degenerates as $token => $token_degenerates)
+ $degenerates_list = array_merge($degenerates_list, $token_degenerates);
+
+ $token_data = array_merge($token_data, $this->_get_query($degenerates_list));
+
+ }
+
+ # Here, we have all availible data in $token_data.
+
+ $return_data_tokens = array();
+ $return_data_degenerates = array();
+
+ foreach($tokens as $token) {
+
+ if(isset($token_data[$token]) === TRUE) {
+
+ # The token was found in the database
+
+ # Add the data ...
+ $return_data_tokens[$token] = $this->_parse_count($token_data[$token]);
+
+ # ... and update it's lastseen parameter
+ $this->_update($token, "{$return_data_tokens[$token]['count_ham']} {$return_data_tokens[$token]['count_spam']} " . $this->b8_config['today'], $uid );
+
+ }
+
+ else {
+
+ # The token was not found, so we look if we
+ # can return data for degenerated tokens
+
+ # Check all degenerated forms of the token
+
+ foreach($this->_degenerator->degenerates[$token] as $degenerate) {
+
+ if(isset($token_data[$degenerate]) === TRUE) {
+
+ # A degeneration of the token way found in the database
+
+ # Add the data ...
+ $return_data_degenerates[$token][$degenerate] = $this->_parse_count($token_data[$degenerate]);
+
+ # ... and update it's lastseen parameter
+ $this->_update($degenerate, "{$return_data_degenerates[$token][$degenerate]['count_ham']} {$return_data_degenerates[$token][$degenerate]['count_spam']} " . $this->b8_config['today'], $uid);
+
+ }
+
+ }
+
+ }
+
+ }
+
+ # Now, all token data directly found in the database is in $return_data_tokens
+ # and all data for degenerated versions is in $return_data_degenerates
+
+ # First, we commit the changes to the lastseen parameters
+ $this->_commit();
+
+ # Then, we return what we have
+ return array(
+ 'tokens' => $return_data_tokens,
+ 'degenerates' => $return_data_degenerates
+ );
+
+ }
+
+ /**
+ * Stores or deletes a list of tokens from the given category.
+ *
+ * @access public
+ * @param array $tokens
+ * @param const $category Either b8::HAM or b8::SPAM
+ * @param const $action Either b8::LEARN or b8::UNLEARN
+ * @return void
+ */
+
+ public function process_text($tokens, $category, $action, $uid)
+ {
+
+ # Validate the startup
+
+ $started_up = $this->validate();
+
+ if($started_up !== TRUE)
+ return $started_up;
+
+ # No matter what we do, we first have to check what data we have.
+
+ # First get the internals, including the ham texts and spam texts counter
+ $internals = $this->get_internals($uid);
+
+ # Then, fetch all data for all tokens we have (and update their lastseen parameters)
+ $token_data = $this->_get_query(array_keys($tokens), $uid);
+
+ # Process all tokens to learn/unlearn
+
+ foreach($tokens as $token => $count) {
+
+ if(isset($token_data[$token])) {
+
+ # We already have this token, so update it's data
+
+ # Get the existing data
+ list($count_ham, $count_spam, $lastseen) = explode(' ', $token_data[$token]);
+ $count_ham = (int) $count_ham;
+ $count_spam = (int) $count_spam;
+
+ # Increase or decrease the right counter
+
+ if($action === b8::LEARN) {
+ if($category === b8::HAM)
+ $count_ham += $count;
+ elseif($category === b8::SPAM)
+ $count_spam += $count;
+ }
+
+ elseif($action == b8::UNLEARN) {
+ if($category === b8::HAM)
+ $count_ham -= $count;
+ elseif($category === b8::SPAM)
+ $count_spam -= $count;
+ }
+
+ # We don't want to have negative values
+
+ if($count_ham < 0)
+ $count_ham = 0;
+
+ if($count_spam < 0)
+ $count_spam = 0;
+
+ # Now let's see if we have to update or delete the token
+ if($count_ham !== 0 or $count_spam !== 0)
+ $this->_update($token, "$count_ham $count_spam " . $this->b8_config['today'], $uid);
+ else
+ $this->_del($token, $uid);
+
+ }
+
+ else {
+
+ # We don't have the token. If we unlearn a text, we can't delete it
+ # as we don't have it anyway, so just do something if we learn a text
+
+ if($action === b8::LEARN) {
+
+ if($category === b8::HAM)
+ $data = '1 0 ';
+ elseif($category === b8::SPAM)
+ $data = '0 1 ';
+
+ $data .= $this->b8_config['today'];
+
+ $this->_put($token, $data, $uid);
+
+ }
+
+ }
+
+ }
+
+ # Now, all token have been processed, so let's update the right text
+
+ if($action === b8::LEARN) {
+
+ if($category === b8::HAM) {
+ $internals['texts_ham']++;
+ $this->_update(self::INTERNALS_TEXTS_HAM, $internals['texts_ham'], $uid);
+ }
+
+ elseif($category === b8::SPAM) {
+ $internals['texts_spam']++;
+ $this->_update(self::INTERNALS_TEXTS_SPAM, $internals['texts_spam'], $uid);
+ }
+
+ }
+
+ elseif($action == b8::UNLEARN) {
+
+ if($category === b8::HAM) {
+
+ $internals['texts_ham']--;
+
+ if($internals['texts_ham'] < 0)
+ $internals['texts_ham'] = 0;
+
+ $this->_update(self::INTERNALS_TEXTS_HAM, $internals['texts_ham'], $uid);
+
+ }
+
+ elseif($category === b8::SPAM) {
+
+ $internals['texts_spam']--;
+
+ if($internals['texts_spam'] < 0)
+ $internals['texts_spam'] = 0;
+
+ $this->_update(self::INTERNALS_TEXTS_SPAM, $internals['texts_spam'], $uid);
+
+ }
+
+ }
+
+ # We're done and can commit all changes to the database now
+ $this->_commit($uid);
+
+ }
+
+}
+
+?> \ No newline at end of file
diff --git a/library/spam/b8/storage/storage_base.php.ORIG b/library/spam/b8/storage/storage_base.php.ORIG
new file mode 100644
index 000000000..01f5a69d7
--- /dev/null
+++ b/library/spam/b8/storage/storage_base.php.ORIG
@@ -0,0 +1,395 @@
+<?php
+
+# Copyright (C) 2010 Tobias Leupold <tobias.leupold@web.de>
+#
+# This file is part of the b8 package
+#
+# This program 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 in version 2.1 of the License.
+#
+# 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 Lesser General Public
+# License for more details.
+#
+# You should have received a copy of the GNU Lesser 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.
+
+/**
+ * Functions used by all storage backends
+ * Copyright (C) 2010 Tobias Leupold <tobias.leupold@web.de>
+ *
+ * @license LGPL
+ * @access public
+ * @package b8
+ * @author Tobias Leupold
+ */
+
+abstract class b8_storage_base
+{
+
+ public $connected = FALSE;
+
+ protected $_degenerator = NULL;
+
+ const INTERNALS_TEXTS_HAM = 'bayes*texts.ham';
+ const INTERNALS_TEXTS_SPAM = 'bayes*texts.spam';
+ const INTERNALS_DBVERSION = 'bayes*dbversion';
+
+ const BACKEND_NOT_CONNECTED = 'BACKEND_NOT_CONNECTED';
+ const DATABASE_WRONG_VERSION = 'DATABASE_WRONG_VERSION';
+ const DATABASE_NOT_B8 = 'DATABASE_NOT_B8';
+
+ /**
+ * Validates the class has all it needs to work.
+ *
+ * @access protected
+ * @return mixed Returns TRUE if everything is okay, otherwise an error code.
+ */
+
+ protected function validate()
+ {
+
+ # We set up the degenerator here, as we would have to duplicate code if it
+ # was done in the constructor of the respective storage backend.
+ $class = 'b8_degenerator_' . $this->b8_config['degenerator'];
+ $this->_degenerator = new $class();
+
+ if($this->connected !== TRUE)
+ return self::BACKEND_NOT_CONNECTED;
+
+ return TRUE;
+
+ }
+
+ /**
+ * Checks if a b8 database is used and if it's version is okay
+ *
+ * @access protected
+ * @return mixed Returns TRUE if everything is okay, otherwise an error code.
+ */
+
+ protected function check_database()
+ {
+
+ $internals = $this->get_internals();
+
+ if(isset($internals['dbversion'])) {
+ if($internals['dbversion'] == "2") {
+ return TRUE;
+ }
+ else {
+ $this->connected = FALSE;
+ return self::DATABASE_WRONG_VERSION;
+ }
+ }
+ else {
+ $this->connected = FALSE;
+ return self::DATABASE_NOT_B8;
+ }
+
+ }
+
+ /**
+ * Parses the "count" data of a token.
+ *
+ * @access private
+ * @param string $data
+ * @return array Returns an array of the parsed data: array(count_ham, count_spam, lastseen).
+ */
+
+ private function _parse_count($data)
+ {
+
+ list($count_ham, $count_spam, $lastseen) = explode(' ', $data);
+
+ $count_ham = (int) $count_ham;
+ $count_spam = (int) $count_spam;
+
+ return array(
+ 'count_ham' => $count_ham,
+ 'count_spam' => $count_spam
+ );
+
+ }
+
+ /**
+ * Get the database's internal variables.
+ *
+ * @access public
+ * @return array Returns an array of all internals.
+ */
+
+ public function get_internals()
+ {
+
+ $internals = $this->_get_query(
+ array(
+ self::INTERNALS_TEXTS_HAM,
+ self::INTERNALS_TEXTS_SPAM,
+ self::INTERNALS_DBVERSION
+ )
+ );
+
+ return array(
+ 'texts_ham' => (int) $internals[self::INTERNALS_TEXTS_HAM],
+ 'texts_spam' => (int) $internals[self::INTERNALS_TEXTS_SPAM],
+ 'dbversion' => (int) $internals[self::INTERNALS_DBVERSION]
+ );
+
+ }
+
+ /**
+ * Get all data about a list of tags from the database.
+ *
+ * @access public
+ * @param array $tokens
+ * @return mixed Returns FALSE on failure, otherwise returns array of returned data in the format array('tokens' => array(token => count), 'degenerates' => array(token => array(degenerate => count))).
+ */
+
+ public function get($tokens)
+ {
+
+ # Validate the startup
+
+ $started_up = $this->validate();
+
+ if($started_up !== TRUE)
+ return $started_up;
+
+ # First we see what we have in the database.
+ $token_data = $this->_get_query($tokens);
+
+ # Check if we have to degenerate some tokens
+
+ $missing_tokens = array();
+
+ foreach($tokens as $token) {
+ if(!isset($token_data[$token]))
+ $missing_tokens[] = $token;
+ }
+
+ if(count($missing_tokens) > 0) {
+
+ # We have to degenerate some tokens
+ $degenerates_list = array();
+
+ # Generate a list of degenerated tokens for the missing tokens ...
+ $degenerates = $this->_degenerator->degenerate($missing_tokens);
+
+ # ... and look them up
+
+ foreach($degenerates as $token => $token_degenerates)
+ $degenerates_list = array_merge($degenerates_list, $token_degenerates);
+
+ $token_data = array_merge($token_data, $this->_get_query($degenerates_list));
+
+ }
+
+ # Here, we have all availible data in $token_data.
+
+ $return_data_tokens = array();
+ $return_data_degenerates = array();
+
+ foreach($tokens as $token) {
+
+ if(isset($token_data[$token]) === TRUE) {
+
+ # The token was found in the database
+
+ # Add the data ...
+ $return_data_tokens[$token] = $this->_parse_count($token_data[$token]);
+
+ # ... and update it's lastseen parameter
+ $this->_update($token, "{$return_data_tokens[$token]['count_ham']} {$return_data_tokens[$token]['count_spam']} " . $this->b8_config['today']);
+
+ }
+
+ else {
+
+ # The token was not found, so we look if we
+ # can return data for degenerated tokens
+
+ # Check all degenerated forms of the token
+
+ foreach($this->_degenerator->degenerates[$token] as $degenerate) {
+
+ if(isset($token_data[$degenerate]) === TRUE) {
+
+ # A degeneration of the token way found in the database
+
+ # Add the data ...
+ $return_data_degenerates[$token][$degenerate] = $this->_parse_count($token_data[$degenerate]);
+
+ # ... and update it's lastseen parameter
+ $this->_update($degenerate, "{$return_data_degenerates[$token][$degenerate]['count_ham']} {$return_data_degenerates[$token][$degenerate]['count_spam']} " . $this->b8_config['today']);
+
+ }
+
+ }
+
+ }
+
+ }
+
+ # Now, all token data directly found in the database is in $return_data_tokens
+ # and all data for degenerated versions is in $return_data_degenerates
+
+ # First, we commit the changes to the lastseen parameters
+ $this->_commit();
+
+ # Then, we return what we have
+ return array(
+ 'tokens' => $return_data_tokens,
+ 'degenerates' => $return_data_degenerates
+ );
+
+ }
+
+ /**
+ * Stores or deletes a list of tokens from the given category.
+ *
+ * @access public
+ * @param array $tokens
+ * @param const $category Either b8::HAM or b8::SPAM
+ * @param const $action Either b8::LEARN or b8::UNLEARN
+ * @return void
+ */
+
+ public function process_text($tokens, $category, $action)
+ {
+
+ # Validate the startup
+
+ $started_up = $this->validate();
+
+ if($started_up !== TRUE)
+ return $started_up;
+
+ # No matter what we do, we first have to check what data we have.
+
+ # First get the internals, including the ham texts and spam texts counter
+ $internals = $this->get_internals();
+
+ # Then, fetch all data for all tokens we have (and update their lastseen parameters)
+ $token_data = $this->_get_query(array_keys($tokens));
+
+ # Process all tokens to learn/unlearn
+
+ foreach($tokens as $token => $count) {
+
+ if(isset($token_data[$token])) {
+
+ # We already have this token, so update it's data
+
+ # Get the existing data
+ list($count_ham, $count_spam, $lastseen) = explode(' ', $token_data[$token]);
+ $count_ham = (int) $count_ham;
+ $count_spam = (int) $count_spam;
+
+ # Increase or decrease the right counter
+
+ if($action === b8::LEARN) {
+ if($category === b8::HAM)
+ $count_ham += $count;
+ elseif($category === b8::SPAM)
+ $count_spam += $count;
+ }
+
+ elseif($action == b8::UNLEARN) {
+ if($category === b8::HAM)
+ $count_ham -= $count;
+ elseif($category === b8::SPAM)
+ $count_spam -= $count;
+ }
+
+ # We don't want to have negative values
+
+ if($count_ham < 0)
+ $count_ham = 0;
+
+ if($count_spam < 0)
+ $count_spam = 0;
+
+ # Now let's see if we have to update or delete the token
+ if($count_ham !== 0 or $count_spam !== 0)
+ $this->_update($token, "$count_ham $count_spam " . $this->b8_config['today']);
+ else
+ $this->_del($token);
+
+ }
+
+ else {
+
+ # We don't have the token. If we unlearn a text, we can't delete it
+ # as we don't have it anyway, so just do something if we learn a text
+
+ if($action === b8::LEARN) {
+
+ if($category === b8::HAM)
+ $data = '1 0 ';
+ elseif($category === b8::SPAM)
+ $data = '0 1 ';
+
+ $data .= $this->b8_config['today'];
+
+ $this->_put($token, $data);
+
+ }
+
+ }
+
+ }
+
+ # Now, all token have been processed, so let's update the right text
+
+ if($action === b8::LEARN) {
+
+ if($category === b8::HAM) {
+ $internals['texts_ham']++;
+ $this->_update(self::INTERNALS_TEXTS_HAM, $internals['texts_ham']);
+ }
+
+ elseif($category === b8::SPAM) {
+ $internals['texts_spam']++;
+ $this->_update(self::INTERNALS_TEXTS_SPAM, $internals['texts_spam']);
+ }
+
+ }
+
+ elseif($action == b8::UNLEARN) {
+
+ if($category === b8::HAM) {
+
+ $internals['texts_ham']--;
+
+ if($internals['texts_ham'] < 0)
+ $internals['texts_ham'] = 0;
+
+ $this->_update(self::INTERNALS_TEXTS_HAM, $internals['texts_ham']);
+
+ }
+
+ elseif($category === b8::SPAM) {
+
+ $internals['texts_spam']--;
+
+ if($internals['texts_spam'] < 0)
+ $internals['texts_spam'] = 0;
+
+ $this->_update(self::INTERNALS_TEXTS_SPAM, $internals['texts_spam']);
+
+ }
+
+ }
+
+ # We're done and can commit all changes to the database now
+ $this->_commit();
+
+ }
+
+}
+
+?> \ No newline at end of file
diff --git a/library/spam/b8/storage/storage_dba.php b/library/spam/b8/storage/storage_dba.php
new file mode 100644
index 000000000..04618b23e
--- /dev/null
+++ b/library/spam/b8/storage/storage_dba.php
@@ -0,0 +1,198 @@
+<?php
+
+# Copyright (C) 2006-2010 Tobias Leupold <tobias.leupold@web.de>
+#
+# This file is part of the b8 package
+#
+# This program 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 in version 2.1 of the License.
+#
+# 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 Lesser General Public
+# License for more details.
+#
+# You should have received a copy of the GNU Lesser 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.
+
+/**
+ * The DBA (Berkeley DB) abstraction layer for communicating with the database.
+ * Copyright (C) 2006-2010 Tobias Leupold <tobias.leupold@web.de>
+ *
+ * @license LGPL
+ * @access public
+ * @package b8
+ * @author Tobias Leupold
+ */
+
+class b8_storage_dba extends b8_storage_base
+{
+
+ public $config = array(
+ 'database' => 'wordlist.db',
+ 'handler' => 'db4',
+ );
+
+ public $b8_config = array(
+ 'degenerator' => NULL,
+ 'today' => NULL
+ );
+
+ private $_db = NULL;
+
+ const DATABASE_CONNECTION_FAIL = 'DATABASE_CONNECTION_FAIL';
+
+ /**
+ * Constructs the database layer.
+ *
+ * @access public
+ * @param string $config
+ */
+
+ function __construct($config, $degenerator, $today)
+ {
+
+ # Pass some variables of the main b8 config to this class
+ $this->b8_config['degenerator'] = $degenerator;
+ $this->b8_config['today'] = $today;
+
+ # Validate the config items
+ if(count($config) > 0) {
+ foreach ($config as $name => $value) {
+ $this->config[$name] = (string) $value;
+ }
+ }
+
+ }
+
+ /**
+ * Closes the database connection.
+ *
+ * @access public
+ * @return void
+ */
+
+ function __destruct()
+ {
+ if($this->_db !== NULL) {
+ dba_close($this->_db);
+ $this->connected = FALSE;
+ }
+ }
+
+ /**
+ * Connect to the database and do some checks.
+ *
+ * @access public
+ * @return mixed Returns TRUE on a successful database connection, otherwise returns a constant from b8.
+ */
+
+ public function connect()
+ {
+
+ # Have we already connected?
+ if($this->_db !== NULL)
+ return TRUE;
+
+ # Open the database connection
+ $this->_db = dba_open(dirname(__FILE__) . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . $this->config['database'], "w", $this->config['handler']);
+
+ if($this->_db === FALSE) {
+ $this->connected = FALSE;
+ $this->_db = NULL;
+ return self::DATABASE_CONNECTION_FAIL;
+ }
+
+ # Everything is okay and connected
+
+ $this->connected = TRUE;
+
+ # Let's see if this is a b8 database and the version is okay
+ return $this->check_database();
+
+ }
+
+ /**
+ * Does the actual interaction with the database when fetching data.
+ *
+ * @access protected
+ * @param array $tokens
+ * @return mixed Returns an array of the returned data in the format array(token => data) or an empty array if there was no data.
+ */
+
+ protected function _get_query($tokens)
+ {
+
+ $data = array();
+
+ foreach ($tokens as $token) {
+
+ $count = dba_fetch($token, $this->_db);
+
+ if($count !== FALSE)
+ $data[$token] = $count;
+
+ }
+
+ return $data;
+
+ }
+
+ /**
+ * Store a token to the database.
+ *
+ * @access protected
+ * @param string $token
+ * @param string $count
+ * @return bool TRUE on success or FALSE on failure
+ */
+
+ protected function _put($token, $count) {
+ return dba_insert($token, $count, $this->_db);
+ }
+
+ /**
+ * Update an existing token.
+ *
+ * @access protected
+ * @param string $token
+ * @param string $count
+ * @return bool TRUE on success or FALSE on failure
+ */
+
+ protected function _update($token, $count)
+ {
+ return dba_replace($token, $count, $this->_db);
+ }
+
+ /**
+ * Remove a token from the database.
+ *
+ * @access protected
+ * @param string $token
+ * @return bool TRUE on success or FALSE on failure
+ */
+
+ protected function _del($token)
+ {
+ return dba_delete($token, $this->_db);
+ }
+
+ /**
+ * Does nothing :-D
+ *
+ * @access protected
+ * @return void
+ */
+
+ protected function _commit()
+ {
+ # We just need this function because the (My)SQL backend(s) need it.
+ return;
+ }
+
+}
+
+?> \ No newline at end of file
diff --git a/library/spam/b8/storage/storage_frndc.php b/library/spam/b8/storage/storage_frndc.php
new file mode 100644
index 000000000..2b9374f67
--- /dev/null
+++ b/library/spam/b8/storage/storage_frndc.php
@@ -0,0 +1,344 @@
+<?php
+
+# Copyright (C) 2006-2011 Tobias Leupold <tobias.leupold@web.de>
+#
+# This file is part of the b8 package
+#
+# This program 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 in version 2.1 of the License.
+#
+# 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 Lesser General Public
+# License for more details.
+#
+# You should have received a copy of the GNU Lesser 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.
+
+/**
+ * The MySQL abstraction layer for communicating with the database.
+ * Copyright (C) 2009 Oliver Lillie (aka buggedcom)
+ * Copyright (C) 2010-2011 Tobias Leupold <tobias.leupold@web.de>
+ *
+ * @license LGPL
+ * @access public
+ * @package b8
+ * @author Oliver Lillie (aka buggedcom) (original PHP 5 port and optimizations)
+ * @author Tobias Leupold
+ */
+
+class b8_storage_frndc extends b8_storage_base
+{
+
+ public $config = array(
+ 'database' => 'b8_wordlist',
+ 'table_name' => 'b8_wordlist',
+ 'host' => 'localhost',
+ 'user' => FALSE,
+ 'pass' => FALSE,
+ 'connection' => NULL
+ );
+
+ public $b8_config = array(
+ 'degenerator' => NULL,
+ 'today' => NULL
+ );
+
+ private $_connection = NULL;
+ private $_deletes = array();
+ private $_puts = array();
+ private $_updates = array();
+ private $uid = 0;
+
+ const DATABASE_CONNECTION_FAIL = 'DATABASE_CONNECTION_FAIL';
+ const DATABASE_CONNECTION_ERROR = 'DATABASE_CONNECTION_ERROR';
+ const DATABASE_CONNECTION_BAD_RESOURCE = 'DATABASE_CONNECTION_BAD_RESOURCE';
+ const DATABASE_SELECT_ERROR = 'DATABASE_SELECT_ERROR';
+ const DATABASE_TABLE_ACCESS_FAIL = 'DATABASE_TABLE_ACCESS_FAIL';
+ const DATABASE_WRONG_VERSION = 'DATABASE_WRONG_VERSION';
+
+ /**
+ * Constructs the database layer.
+ *
+ * @access public
+ * @param string $config
+ */
+
+ function __construct($config, $degenerator, $today)
+ {
+
+ # Pass some variables of the main b8 config to this class
+ $this->b8_config['degenerator'] = $degenerator;
+ $this->b8_config['today'] = $today;
+
+ # Validate the config items
+
+ if(count($config) > 0) {
+
+ foreach ($config as $name => $value) {
+
+ switch($name) {
+
+ case 'table_name':
+ case 'host':
+ case 'user':
+ case 'pass':
+ case 'database':
+ $this->config[$name] = (string) $value;
+ break;
+
+ case 'connection':
+
+ if($value !== NULL) {
+
+ if(is_resource($value) === TRUE) {
+ $resource_type = get_resource_type($value);
+ $this->config['connection'] = $resource_type !== 'mysql link' && $resource_type !== 'mysql link persistent' ? FALSE : $value;
+ }
+
+ else
+ $this->config['connection'] = FALSE;
+
+ }
+
+ break;
+
+ }
+
+ }
+
+ }
+
+ }
+
+ /**
+ * Closes the database connection.
+ *
+ * @access public
+ * @return void
+ */
+
+ function __destruct()
+ {
+
+ if($this->_connection === NULL)
+ return;
+
+ # Commit any changes before closing
+ $this->_commit();
+
+ # Just close the connection if no link-resource was passed and b8 created it's own connection
+ if($this->config['connection'] === NULL)
+ mysql_close($this->_connection);
+
+ $this->connected = FALSE;
+
+ }
+
+ /**
+ * Connect to the database and do some checks.
+ *
+ * @access public
+ * @return mixed Returns TRUE on a successful database connection, otherwise returns a constant from b8.
+ */
+
+ public function connect()
+ {
+
+ return TRUE;
+
+ # Are we already connected?
+ if($this->connected === TRUE)
+ return TRUE;
+
+ # Are we using an existing passed resource?
+ if($this->config['connection'] === FALSE) {
+ # ... yes we are, but the connection is not a resource, so return an error
+ $this->connected = FALSE;
+ return self::DATABASE_CONNECTION_BAD_RESOURCE;
+ }
+
+ elseif($this->config['connection'] === NULL) {
+
+ # ... no we aren't so we have to connect.
+
+ if($this->_connection = mysql_connect($this->config['host'], $this->config['user'], $this->config['pass'])) {
+ if(mysql_select_db($this->config['database'], $this->_connection) === FALSE) {
+ $this->connected = FALSE;
+ return self::DATABASE_SELECT_ERROR . ": " . mysql_error();
+ }
+ }
+ else {
+ $this->connected = FALSE;
+ return self::DATABASE_CONNECTION_ERROR;
+ }
+
+ }
+
+ else {
+ # ... yes we are
+ $this->_connection = $this->config['connection'];
+ }
+
+ # Just in case ...
+ if($this->_connection === NULL) {
+ $this->connected = FALSE;
+ return self::DATABASE_CONNECTION_FAIL;
+ }
+
+ # Check to see if the wordlist table exists
+ if(mysql_query('DESCRIBE ' . $this->config['table_name'], $this->_connection) === FALSE) {
+ $this->connected = FALSE;
+ return self::DATABASE_TABLE_ACCESS_FAIL . ": " . mysql_error();
+ }
+
+ # Everything is okay and connected
+ $this->connected = TRUE;
+
+ # Let's see if this is a b8 database and the version is okay
+ return $this->check_database();
+
+ }
+
+ /**
+ * Does the actual interaction with the database when fetching data.
+ *
+ * @access protected
+ * @param array $tokens
+ * @return mixed Returns an array of the returned data in the format array(token => data) or an empty array if there was no data.
+ */
+
+ protected function _get_query($tokens, $uid)
+ {
+
+ # Construct the query ...
+
+ if(count($tokens) > 0) {
+
+ $where = array();
+
+ foreach ($tokens as $token) {
+ $token = dbesc($token);
+ array_push($where, $token);
+ }
+
+ $where = 'token IN ("' . implode('", "', $where) . '")';
+ }
+
+ else {
+ $token = dbesc($token);
+ $where = 'token = "' . $token . '"';
+ }
+
+ # ... and fetch the data
+
+ $result = q('
+ SELECT token, count
+ FROM ' . $this->config['table_name'] . '
+ WHERE ' . $where . ' AND uid = ' . $uid );
+
+ return $result;
+
+ }
+
+ /**
+ * Store a token to the database.
+ *
+ * @access protected
+ * @param string $token
+ * @param string $count
+ * @return void
+ */
+
+ protected function _put($token, $count, $uid) {
+ $token = dbesc($token);
+ $count = dbesc($count);
+ $uid = dbesc($uid);
+ array_push($this->_puts, '("' . $token . '", "' . $count . '", '"' . $uid .'")');
+ }
+
+ /**
+ * Update an existing token.
+ *
+ * @access protected
+ * @param string $token
+ * @param string $count
+ * @return void
+ */
+
+ protected function _update($token, $count, $uid)
+ {
+ $token = dbesc($token);
+ $count = dbesc($count);
+ $uid = dbesc($uid);
+ array_push($this->_puts, '("' . $token . '", "' . $count . '", '"' . $uid .'")');
+ }
+
+ /**
+ * Remove a token from the database.
+ *
+ * @access protected
+ * @param string $token
+ * @return void
+ */
+
+ protected function _del($token, $uid)
+ {
+ $token = dbesc($token);
+ $uid = dbesc($uid);
+ $this->uid = $uid;
+ array_push($this->_deletes, $token);
+ }
+
+ /**
+ * Commits any modification queries.
+ *
+ * @access protected
+ * @return void
+ */
+
+ protected function _commit($uid)
+ {
+
+ if(count($this->_deletes) > 0) {
+
+ $result = q('
+ DELETE FROM ' . $this->config['table_name'] . '
+ WHERE token IN ("' . implode('", "', $this->_deletes) . '") AND uid = ' . $this->uid);
+
+ $this->_deletes = array();
+
+ }
+
+ if(count($this->_puts) > 0) {
+
+ $result = q('
+ INSERT INTO ' . $this->config['table_name'] . '(token, count, uid)
+ VALUES ' . implode(', ', $this->_puts));
+
+ $this->_puts = array();
+
+ }
+
+ if(count($this->_updates) > 0) {
+
+ // this still needs work
+ $result = q("select * from " . $this->config['table_name'] . ' where token = ';
+
+
+ $result = q('
+ INSERT INTO ' . $this->config['table_name'] . '(token, count, uid)
+ VALUES ' . implode(', ', $this->_updates) . ', ' . $uid . '
+ ON DUPLICATE KEY UPDATE ' . $this->config['table_name'] . '.count = VALUES(count);', $this->_connection);
+
+ $this->_updates = array();
+
+ }
+
+ }
+
+}
+
+?> \ No newline at end of file
diff --git a/library/spam/b8/storage/storage_mysql.php b/library/spam/b8/storage/storage_mysql.php
new file mode 100644
index 000000000..022536350
--- /dev/null
+++ b/library/spam/b8/storage/storage_mysql.php
@@ -0,0 +1,351 @@
+<?php
+
+# Copyright (C) 2006-2011 Tobias Leupold <tobias.leupold@web.de>
+#
+# This file is part of the b8 package
+#
+# This program 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 in version 2.1 of the License.
+#
+# 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 Lesser General Public
+# License for more details.
+#
+# You should have received a copy of the GNU Lesser 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.
+
+/**
+ * The MySQL abstraction layer for communicating with the database.
+ * Copyright (C) 2009 Oliver Lillie (aka buggedcom)
+ * Copyright (C) 2010-2011 Tobias Leupold <tobias.leupold@web.de>
+ *
+ * @license LGPL
+ * @access public
+ * @package b8
+ * @author Oliver Lillie (aka buggedcom) (original PHP 5 port and optimizations)
+ * @author Tobias Leupold
+ */
+
+class b8_storage_mysql extends b8_storage_base
+{
+
+ public $config = array(
+ 'database' => 'b8_wordlist',
+ 'table_name' => 'b8_wordlist',
+ 'host' => 'localhost',
+ 'user' => FALSE,
+ 'pass' => FALSE,
+ 'connection' => NULL
+ );
+
+ public $b8_config = array(
+ 'degenerator' => NULL,
+ 'today' => NULL
+ );
+
+ private $_connection = NULL;
+ private $_deletes = array();
+ private $_puts = array();
+ private $_updates = array();
+
+ const DATABASE_CONNECTION_FAIL = 'DATABASE_CONNECTION_FAIL';
+ const DATABASE_CONNECTION_ERROR = 'DATABASE_CONNECTION_ERROR';
+ const DATABASE_CONNECTION_BAD_RESOURCE = 'DATABASE_CONNECTION_BAD_RESOURCE';
+ const DATABASE_SELECT_ERROR = 'DATABASE_SELECT_ERROR';
+ const DATABASE_TABLE_ACCESS_FAIL = 'DATABASE_TABLE_ACCESS_FAIL';
+ const DATABASE_WRONG_VERSION = 'DATABASE_WRONG_VERSION';
+
+ /**
+ * Constructs the database layer.
+ *
+ * @access public
+ * @param string $config
+ */
+
+ function __construct($config, $degenerator, $today)
+ {
+
+ # Pass some variables of the main b8 config to this class
+ $this->b8_config['degenerator'] = $degenerator;
+ $this->b8_config['today'] = $today;
+
+ # Validate the config items
+
+ if(count($config) > 0) {
+
+ foreach ($config as $name => $value) {
+
+ switch($name) {
+
+ case 'table_name':
+ case 'host':
+ case 'user':
+ case 'pass':
+ case 'database':
+ $this->config[$name] = (string) $value;
+ break;
+
+ case 'connection':
+
+ if($value !== NULL) {
+
+ if(is_resource($value) === TRUE) {
+ $resource_type = get_resource_type($value);
+ $this->config['connection'] = $resource_type !== 'mysql link' && $resource_type !== 'mysql link persistent' ? FALSE : $value;
+ }
+
+ else
+ $this->config['connection'] = FALSE;
+
+ }
+
+ break;
+
+ }
+
+ }
+
+ }
+
+ }
+
+ /**
+ * Closes the database connection.
+ *
+ * @access public
+ * @return void
+ */
+
+ function __destruct()
+ {
+
+ if($this->_connection === NULL)
+ return;
+
+ # Commit any changes before closing
+ $this->_commit();
+
+ # Just close the connection if no link-resource was passed and b8 created it's own connection
+ if($this->config['connection'] === NULL)
+ mysql_close($this->_connection);
+
+ $this->connected = FALSE;
+
+ }
+
+ /**
+ * Connect to the database and do some checks.
+ *
+ * @access public
+ * @return mixed Returns TRUE on a successful database connection, otherwise returns a constant from b8.
+ */
+
+ public function connect()
+ {
+
+ # Are we already connected?
+ if($this->connected === TRUE)
+ return TRUE;
+
+ # Are we using an existing passed resource?
+ if($this->config['connection'] === FALSE) {
+ # ... yes we are, but the connection is not a resource, so return an error
+ $this->connected = FALSE;
+ return self::DATABASE_CONNECTION_BAD_RESOURCE;
+ }
+
+ elseif($this->config['connection'] === NULL) {
+
+ # ... no we aren't so we have to connect.
+
+ if($this->_connection = mysql_connect($this->config['host'], $this->config['user'], $this->config['pass'])) {
+ if(mysql_select_db($this->config['database'], $this->_connection) === FALSE) {
+ $this->connected = FALSE;
+ return self::DATABASE_SELECT_ERROR . ": " . mysql_error();
+ }
+ }
+ else {
+ $this->connected = FALSE;
+ return self::DATABASE_CONNECTION_ERROR;
+ }
+
+ }
+
+ else {
+ # ... yes we are
+ $this->_connection = $this->config['connection'];
+ }
+
+ # Just in case ...
+ if($this->_connection === NULL) {
+ $this->connected = FALSE;
+ return self::DATABASE_CONNECTION_FAIL;
+ }
+
+ # Check to see if the wordlist table exists
+ if(mysql_query('DESCRIBE ' . $this->config['table_name'], $this->_connection) === FALSE) {
+ $this->connected = FALSE;
+ return self::DATABASE_TABLE_ACCESS_FAIL . ": " . mysql_error();
+ }
+
+ # Everything is okay and connected
+ $this->connected = TRUE;
+
+ # Let's see if this is a b8 database and the version is okay
+ return $this->check_database();
+
+ }
+
+ /**
+ * Does the actual interaction with the database when fetching data.
+ *
+ * @access protected
+ * @param array $tokens
+ * @return mixed Returns an array of the returned data in the format array(token => data) or an empty array if there was no data.
+ */
+
+ protected function _get_query($tokens)
+ {
+
+ # Construct the query ...
+
+ if(count($tokens) > 0) {
+
+ $where = array();
+
+ foreach ($tokens as $token) {
+ $token = mysql_real_escape_string($token, $this->_connection);
+ array_push($where, $token);
+ }
+
+ $where = 'token IN ("' . implode('", "', $where) . '")';
+ }
+
+ else {
+ $token = mysql_real_escape_string($token, $this->_connection);
+ $where = 'token = "' . $token . '"';
+ }
+
+ # ... and fetch the data
+
+ $result = mysql_query('
+ SELECT token, count
+ FROM ' . $this->config['table_name'] . '
+ WHERE ' . $where . ';
+ ', $this->_connection);
+
+ $data = array();
+
+ while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
+ $data[$row['token']] = $row['count'];
+
+ mysql_free_result($result);
+
+ return $data;
+
+ }
+
+ /**
+ * Store a token to the database.
+ *
+ * @access protected
+ * @param string $token
+ * @param string $count
+ * @return void
+ */
+
+ protected function _put($token, $count) {
+ $token = mysql_real_escape_string($token, $this->_connection);
+ $count = mysql_real_escape_string($count, $this->_connection);;
+ array_push($this->_puts, '("' . $token . '", "' . $count . '")');
+ }
+
+ /**
+ * Update an existing token.
+ *
+ * @access protected
+ * @param string $token
+ * @param string $count
+ * @return void
+ */
+
+ protected function _update($token, $count)
+ {
+ $token = mysql_real_escape_string($token, $this->_connection);
+ $count = mysql_real_escape_string($count, $this->_connection);
+ array_push($this->_updates, '("' . $token . '", "' . $count . '")');
+ }
+
+ /**
+ * Remove a token from the database.
+ *
+ * @access protected
+ * @param string $token
+ * @return void
+ */
+
+ protected function _del($token)
+ {
+ $token = mysql_real_escape_string($token, $this->_connection);
+ array_push($this->_deletes, $token);
+ }
+
+ /**
+ * Commits any modification queries.
+ *
+ * @access protected
+ * @return void
+ */
+
+ protected function _commit()
+ {
+
+ if(count($this->_deletes) > 0) {
+
+ $result = mysql_query('
+ DELETE FROM ' . $this->config['table_name'] . '
+ WHERE token IN ("' . implode('", "', $this->_deletes) . '");
+ ', $this->_connection);
+
+ if(is_resource($result) === TRUE)
+ mysql_free_result($result);
+
+ $this->_deletes = array();
+
+ }
+
+ if(count($this->_puts) > 0) {
+
+ $result = mysql_query('
+ INSERT INTO ' . $this->config['table_name'] . '(token, count)
+ VALUES ' . implode(', ', $this->_puts) . ';', $this->_connection);
+
+ if(is_resource($result) === TRUE)
+ mysql_free_result($result);
+
+ $this->_puts = array();
+
+ }
+
+ if(count($this->_updates) > 0) {
+
+ $result = mysql_query('
+ INSERT INTO ' . $this->config['table_name'] . '(token, count)
+ VALUES ' . implode(', ', $this->_updates) . '
+ ON DUPLICATE KEY UPDATE ' . $this->config['table_name'] . '.count = VALUES(count);', $this->_connection);
+
+ if(is_resource($result) === TRUE)
+ mysql_free_result($result);
+
+ $this->_updates = array();
+
+ }
+
+ }
+
+}
+
+?> \ No newline at end of file
diff --git a/library/spam/doc/COPYING b/library/spam/doc/COPYING
new file mode 100644
index 000000000..8add30ad5
--- /dev/null
+++ b/library/spam/doc/COPYING
@@ -0,0 +1,504 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+ 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[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.
+
+ <one line to give the library's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 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.
+
+ <signature of Ty Coon>, 1 April 1990
+ Ty Coon, President of Vice
+
+That's all there is to it!
+
+
diff --git a/library/spam/doc/ChangeLog b/library/spam/doc/ChangeLog
new file mode 100644
index 000000000..78a4fc77f
--- /dev/null
+++ b/library/spam/doc/ChangeLog
@@ -0,0 +1,179 @@
+2010-12-30 Tobias Leupold <tobias.leupold@web.de>
+
+ * Release: Version 0.5.1
+
+ * Bigger changes:
+ - Fixed some issues with the scope of variables leading to problems when multiple instances of b8 are created. Thanks to Mike Creuzer for the bug report :-)
+ - Centralized the loading of class definition files in the b8 constructor and created a function to handle the inclusion.
+
+ * b8.php: Return a lexer error code instead of a rating if the lexer failed. The lexer never returned FALSE but b8 checked only for this value to validate the lexer didn't fail. Thanks to Matt Friedman for the bug report :-)
+
+ * lexer/lexer_default.php: A bit of code cleanup: less useless nesting.
+
+ * doc/readme.*: Updated the documentation, added a FAQ.
+
+2010-06-27 Tobias Leupold <tobias.leupold@web.de>
+
+ * Release: Version 0.5-r1
+
+ * doc/readme.*: Updated the documentation; forgot the newly introduced b8::HAM and b8::SPAM variables. Added some additional information about the storage model.
+
+2010-06-02 Tobias Leupold <tobias.leupold@web.de>
+
+ * Release: Version 0.5
+
+ * 100.000 Changes (new major release!), at a glance:
+ - No PHP 4 compatibility anymore. Much cleaner code base with less hacks.
+ - Completely reworked storage model. The SQL performance increased dramatically, the Berkeley DB performance remains as fast as it always has been.
+ - Better lexer which can also handle non-latin1 texts in a nice way, so that e. g. Cyrillic or Chinese texts can be classified more performant.
+ - No config files anymore, multiple instances of b8 can be now created in the same script with different configuration, databases and no problems.
+ - No spooky administration interface anymore that needs an SQL database, even if Berkeley DB is used (anybody who actually used this?! I never did ;-).
+ - No "install" scripts and routines and a less end-user compatible documentation. Anybody integrating b8 in his homepage won't be an end-user, will he?
+
+2009-02-03 Oliver Lillie (aka buggedcom)
+
+ * Revision: 221 (the original PHP 5 port)
+
+ * Rewrote Tobias' original class for optimisation and PHP 5 functionality.
+
+ * Improved database mysql query useage by over ~820%
+
+ * Class is faster, ~20%.
+
+ * Slight increase in memory usage, but it's small and given the advantages of the speed increase and query reduction it's worth it.
+
+ * Removed install code from mysql class and added a sql file. Anyone who wants to use this is generally going to be more advanced anyway and see the sql to install.
+
+2009-02-03 Tobias Leupold <tobias.leupold@web.de>
+
+ * Release: Version 0.4.4 -- changed the license type from GPL to LGPL
+
+2008-06-27 Tobias Leupold <tobias.leupold@web.de>
+
+ * Release: Version 0.4.3 -- no bugs found ... so let's make a release with only small changes ;-)
+
+ * b8.php: Removed debugging messages that were commented out anyway
+
+ * storage/storage_mysql.php: Made it possible to pass both a MySQL-link resource and a table name to b8. This makes b8 useable in the Redaxo CMS (and probably others)
+
+ * doc/readme.htm: Updated documentation accordingly
+
+2008-02-17 Tobias Leupold <tobias.leupold@web.de>
+
+ * Release: Version 0.4.2
+
+ * interface/backup.php: the bayes*dbversion tag is now written to a database emptied by drop(), so that it will be useable without an error message even if no backup is recovered afterwards.
+
+ * doc/readme.htm: added a security note to the configuration section (htaccess should be used to avoid everybody to be able to see the configuration)
+
+2007-09-17 Tobias Leupold <tobias.leupold@web.de>
+
+ * Release: Version 0.4.1
+
+ * storage/storage_mysql.php: fixed b8 crashing when getting passed a persistent MySQL resource link. Thanks to Paul Chapman for the bug report :-)
+
+2007-06-08 Tobias Leupold <tobias.leupold@web.de>
+
+ * Release: Version 0.4
+
+ * Let's go the whole hog. b8's class is now "b8" and no more "bayes", and all internal variables have now according names.
+
+ * Reworked the whole (surprisingly crappy) implementation of b8. No more global() calls, everything happens inside the classes now. Made that whole stuff really object oriented (as good as possible with PHP's poor OOP model ;-).
+
+ * No more PHP code in the configuration files.
+
+ * Created an extra lexer class. This is now also configurable.
+
+ * Storage classes now can create their own databases when this is requested by the configuration.
+
+ * MySQL calls are no random shots anymore: either, a MySQL-link resource is passed to b8 on startup which will be used for the queries, or the class sets up it's own link. Same for SQLite.
+
+ * The interface now uses a separate storage backend capable of SQL. In this way, we _really_ can query the database for e. g. an ordered list of tokens. After doing what we wanted with this work database, the b8 database can be synced with it.
+
+ * Added a lot of verbose error handling.
+
+ * Fixed a dumb error: all tokens from a text were used for the spamminess calculation, because two for() loops both used $i as their counter. D'oh!!! Now, the filter's performance is way better.
+
+ * Catched on the way how that whole math stuff works a little more ;-) Now, the calculation of the single probabilities proposed by Mr. Robinson does a little more the stuff it was intended to do, because ...
+
+ * Made some calculation constants parameters: the number of tokens to use, the default rating for unknown tokens and Gary Robinson's s constant.
+
+ * Introduced an optional minimum deviation that a token's rating must have to be considered in the spamminess calculation.
+
+ * The default extreme ratings for tokens only in ham or spam are now optional. One can also choose to calculate all ratings by Mr. Robinson's method.
+
+ * Noticed that text primary keys are not case sensitive by default in MySQL, which has a noticeable impact on the filter's performance. Informed the MySQL users about that.
+
+ * The whole code sucks much less ;-) b8 should be way more user friendly now.
+
+ * Re-wrote the whole documentation.
+
+ * Fixed the ChangeLog :-)
+
+2007-02-08 Tobias Leupold <tobias.leupold@web.de>
+
+ * Release: Version 0.3.3 again ;-)
+
+ * bayes-php is now b8. See http://www.nasauber.de/blog/text.php?text=58 for details :-) Thanks to Tobias Lang (http://langt.net/) for this cool new name!
+
+2007-01-05 Tobias Leupold <tobias.leupold@web.de>
+
+ * Release: Version 0.3.3
+
+ * Renamed the internal BerkeleyDB handle from "$db" to the less general name "$bayes_php_db" due to an collision with phpwcms's (http://www.phpwcms.de/) global $db variable and potentially other php programs.
+
+ * Commented out Laurent Goussard's SQLite storage class by default, as it's try { } catch { } calls break PHP 4
+
+2006-09-03 Tobias Leupold <tobias.leupold@web.de>
+
+ * Release: Version 0.3.2
+
+ * Laurent Goussard (loranger@free.fr) contributed an SQLite storage class(which needs PHP 5).
+
+ * I finally added my eMail address to the sources ;-)
+
+2006-07-24 Tobias Leupold <tobias.leupold@web.de>
+
+ * Release: Version 0.3.1
+
+ * Fixed a problem in the unlearn() function: If a text was unlearned that wasn't learned before (accidentaly), it could happen that the count parameter for this text was smaller than 0, breaking the spamminess calulation
+
+2006-07-02 Tobias Leupold <tobias.leupold@web.de>
+
+ * Release: Version 0.3
+
+ * Improved the get_tokens() function; the filter should now be a lot more performant, especially with short texts
+
+ * Added the "lastseen" parameter for each token to make the database maintainable (outdated tokens can be deleted)
+
+ * Added a real database maintainance interface
+
+2006-06-12 Tobias Leupold <tobias.leupold@web.de>
+
+ * Release: Version 0.2.1
+
+ * Fixed a problem in get_tokens() (if it was called more than once, tokens were counted more often than they appeared in the text)
+
+ * Slightly enhanced the default index.php interface: after learning a text as Ham or Spam, the rating before and after it is displayed to inform the user about it
+
+2006-05-21 Tobias Leupold <tobias.leupold@web.de>
+
+ * Release: Version 0.2
+
+ * Comments now in English (to pretend international success of bayes-php ;-)
+
+ * Recommendations of Paul Graham's article "Better Bayesian Filtering" ( http://www.paulgraham.com/better.html ) are now considered: Tokens that only appear in Ham or Spam and not in the other category are rated with 0.9998 or 0.0002 if they were less than 10 times in Ham or Spam and with 0.9999 or 0.0001 if they appeared more that 10 times. This should allow the filter to differentiate spam texts more sharp from ham texts. Also, token "degeneration" as described in the article is performed for unknown tokens to estimate their spamminess.
+
+ * The database connect is now swapped in a separate configuration file, so only this file has to be preserved if bayes-php is updated and only this file has to be changed to configure the script.
+
+2006-03-29 Tobias Leupold <tobias.leupold@web.de>
+
+ * Release: Version 0.1.1
+
+ * get_tokens() beachtet jetzt auch HTML-Tags und Wörter mit Akzenten und Apostrophen
+
+ * Verschiedene Kleinigkeiten "sauber" gemacht :-)
+
+2006-03-05 Tobias Leupold <tobias.leupold@web.de>
+
+ * Added 2007-06-08: Initial release (Version 0.1)
diff --git a/library/spam/doc/readme.htm b/library/spam/doc/readme.htm
new file mode 100644
index 000000000..727d5ae5f
--- /dev/null
+++ b/library/spam/doc/readme.htm
@@ -0,0 +1,707 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+<meta name="generator" content="Docutils 0.7: http://docutils.sourceforge.net/" />
+<title>b8: readme</title>
+<meta name="author" content="Tobias Leupold" />
+<meta name="date" content="2010-12-23" />
+<style type="text/css">
+
+/*
+:Author: David Goodger (goodger@python.org)
+:Id: $Id: html4css1.css 6253 2010-03-02 00:24:53Z milde $
+:Copyright: This stylesheet has been placed in the public domain.
+
+Default cascading style sheet for the HTML output of Docutils.
+
+See http://docutils.sf.net/docs/howto/html-stylesheets.html for how to
+customize this style sheet.
+*/
+
+/* used to remove borders from tables and images */
+.borderless, table.borderless td, table.borderless th {
+ border: 0 }
+
+table.borderless td, table.borderless th {
+ /* Override padding for "table.docutils td" with "! important".
+ The right padding separates the table cells. */
+ padding: 0 0.5em 0 0 ! important }
+
+.first {
+ /* Override more specific margin styles with "! important". */
+ margin-top: 0 ! important }
+
+.last, .with-subtitle {
+ margin-bottom: 0 ! important }
+
+.hidden {
+ display: none }
+
+a.toc-backref {
+ text-decoration: none ;
+ color: black }
+
+blockquote.epigraph {
+ margin: 2em 5em ; }
+
+dl.docutils dd {
+ margin-bottom: 0.5em }
+
+/* Uncomment (and remove this text!) to get bold-faced definition list terms
+dl.docutils dt {
+ font-weight: bold }
+*/
+
+div.abstract {
+ margin: 2em 5em }
+
+div.abstract p.topic-title {
+ font-weight: bold ;
+ text-align: center }
+
+div.admonition, div.attention, div.caution, div.danger, div.error,
+div.hint, div.important, div.note, div.tip, div.warning {
+ margin: 2em ;
+ border: medium outset ;
+ padding: 1em }
+
+div.admonition p.admonition-title, div.hint p.admonition-title,
+div.important p.admonition-title, div.note p.admonition-title,
+div.tip p.admonition-title {
+ font-weight: bold ;
+ font-family: sans-serif }
+
+div.attention p.admonition-title, div.caution p.admonition-title,
+div.danger p.admonition-title, div.error p.admonition-title,
+div.warning p.admonition-title {
+ color: red ;
+ font-weight: bold ;
+ font-family: sans-serif }
+
+/* Uncomment (and remove this text!) to get reduced vertical space in
+ compound paragraphs.
+div.compound .compound-first, div.compound .compound-middle {
+ margin-bottom: 0.5em }
+
+div.compound .compound-last, div.compound .compound-middle {
+ margin-top: 0.5em }
+*/
+
+div.dedication {
+ margin: 2em 5em ;
+ text-align: center ;
+ font-style: italic }
+
+div.dedication p.topic-title {
+ font-weight: bold ;
+ font-style: normal }
+
+div.figure {
+ margin-left: 2em ;
+ margin-right: 2em }
+
+div.footer, div.header {
+ clear: both;
+ font-size: smaller }
+
+div.line-block {
+ display: block ;
+ margin-top: 1em ;
+ margin-bottom: 1em }
+
+div.line-block div.line-block {
+ margin-top: 0 ;
+ margin-bottom: 0 ;
+ margin-left: 1.5em }
+
+div.sidebar {
+ margin: 0 0 0.5em 1em ;
+ border: medium outset ;
+ padding: 1em ;
+ background-color: #ffffee ;
+ width: 40% ;
+ float: right ;
+ clear: right }
+
+div.sidebar p.rubric {
+ font-family: sans-serif ;
+ font-size: medium }
+
+div.system-messages {
+ margin: 5em }
+
+div.system-messages h1 {
+ color: red }
+
+div.system-message {
+ border: medium outset ;
+ padding: 1em }
+
+div.system-message p.system-message-title {
+ color: red ;
+ font-weight: bold }
+
+div.topic {
+ margin: 2em }
+
+h1.section-subtitle, h2.section-subtitle, h3.section-subtitle,
+h4.section-subtitle, h5.section-subtitle, h6.section-subtitle {
+ margin-top: 0.4em }
+
+h1.title {
+ text-align: center }
+
+h2.subtitle {
+ text-align: center }
+
+hr.docutils {
+ width: 75% }
+
+img.align-left, .figure.align-left, object.align-left {
+ clear: left ;
+ float: left ;
+ margin-right: 1em }
+
+img.align-right, .figure.align-right, object.align-right {
+ clear: right ;
+ float: right ;
+ margin-left: 1em }
+
+img.align-center, .figure.align-center, object.align-center {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+}
+
+.align-left {
+ text-align: left }
+
+.align-center {
+ clear: both ;
+ text-align: center }
+
+.align-right {
+ text-align: right }
+
+/* reset inner alignment in figures */
+div.align-right {
+ text-align: left }
+
+/* div.align-center * { */
+/* text-align: left } */
+
+ol.simple, ul.simple {
+ margin-bottom: 1em }
+
+ol.arabic {
+ list-style: decimal }
+
+ol.loweralpha {
+ list-style: lower-alpha }
+
+ol.upperalpha {
+ list-style: upper-alpha }
+
+ol.lowerroman {
+ list-style: lower-roman }
+
+ol.upperroman {
+ list-style: upper-roman }
+
+p.attribution {
+ text-align: right ;
+ margin-left: 50% }
+
+p.caption {
+ font-style: italic }
+
+p.credits {
+ font-style: italic ;
+ font-size: smaller }
+
+p.label {
+ white-space: nowrap }
+
+p.rubric {
+ font-weight: bold ;
+ font-size: larger ;
+ color: maroon ;
+ text-align: center }
+
+p.sidebar-title {
+ font-family: sans-serif ;
+ font-weight: bold ;
+ font-size: larger }
+
+p.sidebar-subtitle {
+ font-family: sans-serif ;
+ font-weight: bold }
+
+p.topic-title {
+ font-weight: bold }
+
+pre.address {
+ margin-bottom: 0 ;
+ margin-top: 0 ;
+ font: inherit }
+
+pre.literal-block, pre.doctest-block {
+ margin-left: 2em ;
+ margin-right: 2em }
+
+span.classifier {
+ font-family: sans-serif ;
+ font-style: oblique }
+
+span.classifier-delimiter {
+ font-family: sans-serif ;
+ font-weight: bold }
+
+span.interpreted {
+ font-family: sans-serif }
+
+span.option {
+ white-space: nowrap }
+
+span.pre {
+ white-space: pre }
+
+span.problematic {
+ color: red }
+
+span.section-subtitle {
+ /* font-size relative to parent (h1..h6 element) */
+ font-size: 80% }
+
+table.citation {
+ border-left: solid 1px gray;
+ margin-left: 1px }
+
+table.docinfo {
+ margin: 2em 4em }
+
+table.docutils {
+ margin-top: 0.5em ;
+ margin-bottom: 0.5em }
+
+table.footnote {
+ border-left: solid 1px black;
+ margin-left: 1px }
+
+table.docutils td, table.docutils th,
+table.docinfo td, table.docinfo th {
+ padding-left: 0.5em ;
+ padding-right: 0.5em ;
+ vertical-align: top }
+
+table.docutils th.field-name, table.docinfo th.docinfo-name {
+ font-weight: bold ;
+ text-align: left ;
+ white-space: nowrap ;
+ padding-left: 0 }
+
+h1 tt.docutils, h2 tt.docutils, h3 tt.docutils,
+h4 tt.docutils, h5 tt.docutils, h6 tt.docutils {
+ font-size: 100% }
+
+ul.auto-toc {
+ list-style-type: none }
+
+</style>
+</head>
+<body>
+<div class="document" id="b8-readme">
+<h1 class="title">b8: readme</h1>
+<table class="docinfo" frame="void" rules="none">
+<col class="docinfo-name" />
+<col class="docinfo-content" />
+<tbody valign="top">
+<tr><th class="docinfo-name">Author:</th>
+<td>Tobias Leupold</td></tr>
+<tr class="field"><th class="docinfo-name">Homepage:</th><td class="field-body"><a class="reference external" href="http://nasauber.de/">http://nasauber.de/</a></td>
+</tr>
+<tr><th class="docinfo-name">Contact:</th>
+<td><a class="first last reference external" href="mailto:tobias.leupold&#64;web.de">tobias.leupold&#64;web.de</a></td></tr>
+<tr><th class="docinfo-name">Date:</th>
+<td>2010-12-23</td></tr>
+</tbody>
+</table>
+<div class="contents topic" id="table-of-contents">
+<p class="topic-title first">Table of Contents</p>
+<ul class="auto-toc simple">
+<li><a class="reference internal" href="#description-of-b8" id="id18">1&nbsp;&nbsp;&nbsp;Description of b8</a><ul class="auto-toc">
+<li><a class="reference internal" href="#what-is-b8" id="id19">1.1&nbsp;&nbsp;&nbsp;What is b8?</a></li>
+<li><a class="reference internal" href="#how-does-it-work" id="id20">1.2&nbsp;&nbsp;&nbsp;How does it work?</a></li>
+<li><a class="reference internal" href="#what-do-i-need-for-it" id="id21">1.3&nbsp;&nbsp;&nbsp;What do I need for it?</a></li>
+<li><a class="reference internal" href="#what-s-different" id="id22">1.4&nbsp;&nbsp;&nbsp;What's different?</a></li>
+</ul>
+</li>
+<li><a class="reference internal" href="#update-from-prior-versions" id="id23">2&nbsp;&nbsp;&nbsp;Update from prior versions</a><ul class="auto-toc">
+<li><a class="reference internal" href="#update-from-bayes-php-version-0-2-1-or-earlier" id="id24">2.1&nbsp;&nbsp;&nbsp;Update from bayes-php version 0.2.1 or earlier</a></li>
+<li><a class="reference internal" href="#update-from-bayes-php-version-0-3-or-later" id="id25">2.2&nbsp;&nbsp;&nbsp;Update from bayes-php version 0.3 or later</a></li>
+</ul>
+</li>
+<li><a class="reference internal" href="#installation" id="id26">3&nbsp;&nbsp;&nbsp;Installation</a></li>
+<li><a class="reference internal" href="#configuration" id="id27">4&nbsp;&nbsp;&nbsp;Configuration</a><ul class="auto-toc">
+<li><a class="reference internal" href="#b8-s-base-configuration" id="id28">4.1&nbsp;&nbsp;&nbsp;b8's base configuration</a></li>
+<li><a class="reference internal" href="#configuration-of-the-storage-backend" id="id29">4.2&nbsp;&nbsp;&nbsp;Configuration of the storage backend</a><ul class="auto-toc">
+<li><a class="reference internal" href="#settings-for-the-berkeley-db-dba-backend" id="id30">4.2.1&nbsp;&nbsp;&nbsp;Settings for the Berkeley DB (DBA) backend</a></li>
+<li><a class="reference internal" href="#settings-for-the-mysql-backend" id="id31">4.2.2&nbsp;&nbsp;&nbsp;Settings for the MySQL backend</a></li>
+</ul>
+</li>
+</ul>
+</li>
+<li><a class="reference internal" href="#using-b8" id="id32">5&nbsp;&nbsp;&nbsp;Using b8</a><ul class="auto-toc">
+<li><a class="reference internal" href="#setting-up-a-new-database" id="id33">5.1&nbsp;&nbsp;&nbsp;Setting up a new database</a><ul class="auto-toc">
+<li><a class="reference internal" href="#setting-up-a-new-berkeley-db" id="id34">5.1.1&nbsp;&nbsp;&nbsp;Setting up a new Berkeley DB</a></li>
+<li><a class="reference internal" href="#setting-up-a-new-mysql-table" id="id35">5.1.2&nbsp;&nbsp;&nbsp;Setting up a new MySQL table</a></li>
+</ul>
+</li>
+<li><a class="reference internal" href="#using-b8-in-your-scripts" id="id36">5.2&nbsp;&nbsp;&nbsp;Using b8 in your scripts</a></li>
+</ul>
+</li>
+<li><a class="reference internal" href="#tips-on-operation" id="id37">6&nbsp;&nbsp;&nbsp;Tips on operation</a></li>
+<li><a class="reference internal" href="#closing" id="id38">7&nbsp;&nbsp;&nbsp;Closing</a></li>
+<li><a class="reference internal" href="#references" id="id39">8&nbsp;&nbsp;&nbsp;References</a></li>
+<li><a class="reference internal" href="#appendix" id="id40">9&nbsp;&nbsp;&nbsp;Appendix</a><ul class="auto-toc">
+<li><a class="reference internal" href="#faq" id="id41">9.1&nbsp;&nbsp;&nbsp;FAQ</a><ul class="auto-toc">
+<li><a class="reference internal" href="#what-about-more-than-two-categories" id="id42">9.1.1&nbsp;&nbsp;&nbsp;What about more than two categories?</a></li>
+<li><a class="reference internal" href="#what-about-a-list-with-words-to-ignore" id="id43">9.1.2&nbsp;&nbsp;&nbsp;What about a list with words to ignore?</a></li>
+<li><a class="reference internal" href="#why-is-it-called-b8" id="id44">9.1.3&nbsp;&nbsp;&nbsp;Why is it called &quot;b8&quot;?</a></li>
+</ul>
+</li>
+<li><a class="reference internal" href="#about-the-database" id="id45">9.2&nbsp;&nbsp;&nbsp;About the database</a><ul class="auto-toc">
+<li><a class="reference internal" href="#the-database-layout" id="id46">9.2.1&nbsp;&nbsp;&nbsp;The database layout</a></li>
+<li><a class="reference internal" href="#the-lastseen-parameter" id="id47">9.2.2&nbsp;&nbsp;&nbsp;The &quot;lastseen&quot; parameter</a></li>
+</ul>
+</li>
+</ul>
+</li>
+</ul>
+</div>
+<div class="section" id="description-of-b8">
+<h1><a class="toc-backref" href="#id18">1&nbsp;&nbsp;&nbsp;Description of b8</a></h1>
+<div class="section" id="what-is-b8">
+<h2><a class="toc-backref" href="#id19">1.1&nbsp;&nbsp;&nbsp;What is b8?</a></h2>
+<p>b8 is a spam filter implemented in <a class="reference external" href="http://www.php.net/">PHP</a>. It is intended to keep your weblog or guestbook spam-free. The filter can be used anywhere in your PHP code and tells you whether a text is spam or not, using statistical text analysis. See <a class="reference internal" href="#how-does-it-work">How does it work?</a> for details about this. To be able to do this, b8 first has to learn some spam and some ham example texts to decide what's good and what's not. If it makes mistakes classifying unknown texts, they can be corrected and b8 learns from the corrections, getting better with each learned text.</p>
+<p>At the moment of this writing, b8 has classified 14411 guestbook entries and weblog comments on my homepage since december 2006. 131 were ham. 39 spam texts (0.27 %) have been rated as ham (false negatives), with not even one false positive (ham message classified as spam). This results in a sensitivity of 99.73 % (the probability that a spam text will actually be rated as spam) and a specifity of 100 % (the probability that a ham text will actually be rated as ham) for me. I hope, you'll get the same good results :-)</p>
+<p>Basically, b8 is a statistical (&quot;Bayesian&quot;<a class="footnote-reference" href="#id2" id="id1">[1]</a>) spam filter like <a class="reference external" href="http://bogofilter.sourceforge.net/">Bogofilter</a> or <a class="reference external" href="http://spambayes.sourceforge.net/">SpamBayes</a>, but it is not intended to classify e-mails. When I started to write b8, I didn't find a good PHP spam filter (or any spam filter that wasn't just some example code how one <em>could</em> implement a Bayesian spam filter in PHP) that was intended to filter weblog or guestbook entries. That's why I had to write my own ;-) <br />
+Caused by it's purpose, the way b8 works is slightly different from most of the Bayesian email spam filters out there. See <a class="reference internal" href="#what-s-different">What's different?</a> if you're interested in the details.</p>
+<table class="docutils footnote" frame="void" id="id2" rules="none">
+<colgroup><col class="label" /><col /></colgroup>
+<tbody valign="top">
+<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>A mathematician told me that the math in b8 actually does not use Bayes' theorem but some derived algorithms that are just related to it. So … let's simply believe that and stop claiming b8 was a <em>Bayesian</em> spam filter ;-)</td></tr>
+</tbody>
+</table>
+</div>
+<div class="section" id="how-does-it-work">
+<h2><a class="toc-backref" href="#id20">1.2&nbsp;&nbsp;&nbsp;How does it work?</a></h2>
+<p>b8 basically uses the math and technique described in Paul Graham's article &quot;A Plan For Spam&quot; <a class="footnote-reference" href="#planforspam" id="id3">[2]</a> to distinguish ham and spam. The improvements proposed in Graham's article &quot;Better Bayesian Filtering&quot; <a class="footnote-reference" href="#betterbayesian" id="id4">[3]</a> and Gary Robinson's article &quot;Spam Detection&quot; <a class="footnote-reference" href="#spamdetection" id="id5">[4]</a> have also been considered. See also the article &quot;A Statistical Approach to the Spam Problem&quot; <a class="footnote-reference" href="#statisticalapproach" id="id6">[5]</a>.</p>
+<p>b8 cuts the text to classify to pieces, extracting stuff like e-mail addresses, links and HTML tags. For each such token, it calculates a single probability for a text containing it being spam, based on what the filter has learned so far. When the token was not seen before, b8 tries to find similar ones using the &quot;degeneration&quot; described in <a class="footnote-reference" href="#betterbayesian" id="id7">[3]</a> and uses the most relevant value found. If really nothing is found, b8 assumes a default rating for this token for the further calculations. <br />
+Then, b8 takes the most relevant values (which have a rating far from 0.5, which would mean we don't know what it is) and calculates the probability that the whole text is spam by the inverse chi-square function described in <a class="footnote-reference" href="#spamdetection" id="id8">[4]</a>.
+There are some parameters that can be set which influence the filter's behaviour (see below).</p>
+<p>In short words: you give b8 a text and it returns a value between 0 and 1, saying it's ham when it's near 0 and saying it's spam when it's near 1.</p>
+</div>
+<div class="section" id="what-do-i-need-for-it">
+<h2><a class="toc-backref" href="#id21">1.3&nbsp;&nbsp;&nbsp;What do I need for it?</a></h2>
+<p>Not much! You just need PHP 5 on the server where b8 will be used (b8 version 0.5 finally dropped PHP 4 compatibility – thankfully ;-) and a proper storage possibility for the wordlists. I strongly recommend using <a class="reference external" href="http://www.oracle.com/database/berkeley-db/index.html">Berkeley DB</a>. See below how you can check if you can use it and why you should use it. If the server's PHP wasn't compiled with Berkeley DB support, a <a class="reference external" href="http://mysql.com/">MySQL</a> table can be used alternatively.</p>
+</div>
+<div class="section" id="what-s-different">
+<h2><a class="toc-backref" href="#id22">1.4&nbsp;&nbsp;&nbsp;What's different?</a></h2>
+<p>b8 is designed to classify weblog or guestbook entries, not e-mails. For this reason, it uses a slightly different technique than most of the other statistical spam filters out there use.</p>
+<p>My experience was that spam entries on my weblog or guestbook were often quite short, sometimes just something like &quot;123abc&quot; as text and a link to a suspect homepage. Some spam bots don't even made a difference between e. g. the &quot;name&quot; and &quot;text&quot; fields and posted their text as email address, for example. Considering this, b8 just takes one string to classify, making no difference between &quot;headers&quot; and &quot;text&quot;. <br />
+The other thing is that most statistical spam filters count one token one time, no matter how often it appears in the text (as Graham describes it in <a class="footnote-reference" href="#planforspam" id="id9">[2]</a>). b8 does count how often a token was seen and learns or considers this. Additionally, the number of learned ham and spam texts are saved and used as the calculation base for the single probabilities. Why this? Because a text containing one link (no matter where it points to, just indicated by a &quot;http://&quot; or a &quot;www.&quot;) might not be spam, but a text containing 20 links might be.</p>
+<p>This means that b8 might be good for classifying weblog or guestbook entries (I really think it is ;-) – but very likely, it will work quite poor when being used for something else (like classifying e-mails). But as said above, for this task, there are a lot of very good filters out there to choose from.</p>
+</div>
+</div>
+<div class="section" id="update-from-prior-versions">
+<h1><a class="toc-backref" href="#id23">2&nbsp;&nbsp;&nbsp;Update from prior versions</a></h1>
+<p>If this is a new b8 installation, read on at the <a class="reference internal" href="#installation">Installation</a> section!</p>
+<div class="section" id="update-from-bayes-php-version-0-2-1-or-earlier">
+<h2><a class="toc-backref" href="#id24">2.1&nbsp;&nbsp;&nbsp;Update from bayes-php version 0.2.1 or earlier</a></h2>
+<p>Please first follow the database update instructions of the bayes-php-0.3 release if you update from a version prior to bayes-php-0.3 and then read the following paragraph about updating from a version &lt;0.3.3.</p>
+</div>
+<div class="section" id="update-from-bayes-php-version-0-3-or-later">
+<h2><a class="toc-backref" href="#id25">2.2&nbsp;&nbsp;&nbsp;Update from bayes-php version 0.3 or later</a></h2>
+<dl class="docutils">
+<dt><strong>You use Berkeley DB?</strong></dt>
+<dd>Everything's fine, you can simply continue using your database.</dd>
+<dt><strong>You use MySQL?</strong></dt>
+<dd>The <tt class="docutils literal">CREATE</tt> statement of b8's wordlist has changed. The best is probably to create a dump via your favorite administration tool or script, create the new table and re-insert all data. The layout is still the same: there's one &quot;token&quot; column and one &quot;data&quot; column. Having done that, you can keep using your data.</dd>
+<dt><strong>You use SQLite?</strong></dt>
+<dd>Sorry, at the moment, there's no SQLite backend for b8. But we're working on it :-)</dd>
+</dl>
+<p>The configuration model of b8 has changed. Please read through the <a class="reference internal" href="#configuration">Configuration</a> section and update your configuration accordingly.</p>
+<p>b8's lexer has been partially re-written. It should now be able to handle all kind of non-latin-1 input, like cyrillic, chinese or japanese texts. Caused by this fact, much more tokens will be recognized when classifying such texts. Therefore, you could get different results in b8's ratings, even if the same database is used and although the math is still the same.</p>
+<p>b8 0.5 introduced two constants that can be used in the <tt class="docutils literal">learn()</tt> and <tt class="docutils literal">unlearn()</tt> functions: <tt class="docutils literal"><span class="pre">b8::HAM</span></tt> and <tt class="docutils literal"><span class="pre">b8::SPAM</span></tt>. The literal values &quot;ham&quot; and &quot;spam&quot; can still be used anyway.</p>
+</div>
+</div>
+<div class="section" id="installation">
+<h1><a class="toc-backref" href="#id26">3&nbsp;&nbsp;&nbsp;Installation</a></h1>
+<p>Installing b8 on your server is quite easy. You just have to provide the needed files. To do this, you could just upload the whole <tt class="docutils literal">b8</tt> subdirectory to the base directory of your homepage. It contains the filter itself and all needed backend classes. The other directories (<tt class="docutils literal">doc</tt>, <tt class="docutils literal">example</tt> and <tt class="docutils literal">install</tt>) are not used by b8.</p>
+<p>That's it ;-)</p>
+</div>
+<div class="section" id="configuration">
+<h1><a class="toc-backref" href="#id27">4&nbsp;&nbsp;&nbsp;Configuration</a></h1>
+<p>The configuration is passed as arrays when instantiating a new b8 object. Two arrays can be passed to b8, one containing b8's base configuration and some settings for the lexer (which should be common for all lexer classes, in case some other lexer than the default one will be written one day) and one for the storage backend. <br />
+You can have a look at <tt class="docutils literal">example/index.php</tt> to see how this can be done. <a class="reference internal" href="#using-b8-in-your-scripts">Using b8 in your scripts</a> also shows example code showing how b8 can be included in a PHP script.</p>
+<p>Not all values have to be set. When some values are missing, the default ones will be used. If you do use the default settings, you don't have to pass them to b8.</p>
+<div class="section" id="b8-s-base-configuration">
+<h2><a class="toc-backref" href="#id28">4.1&nbsp;&nbsp;&nbsp;b8's base configuration</a></h2>
+<p>All these values can be set in the &quot;config_b8&quot; array (the first parameter) passed to b8. The name of the array doesn't matter (of course), it just has to be the first argument.</p>
+<p>These are some basic settings telling b8 which backend classes to use:</p>
+<blockquote>
+<dl class="docutils">
+<dt><strong>storage</strong></dt>
+<dd><p class="first">This defines which storage backend will be used to save b8's wordlist. Currently, two backends are available: <a class="reference external" href="http://www.oracle.com/database/berkeley-db/index.html">Berkeley DB</a> (<tt class="docutils literal">dba</tt>) and <a class="reference external" href="http://mysql.com/">MySQL</a> (<tt class="docutils literal">mysql</tt>). At the moment, b8 does not support <a class="reference external" href="http://sqlite.org/">SQLite</a> (as the previous version did), but it will be (hopefully) re-added in one of the next releases. The default is <tt class="docutils literal">dba</tt> (string).</p>
+<dl class="docutils">
+<dt><em>Berkeley DB</em></dt>
+<dd>This is the preferred storage backend. It was the original backend for the filter and remains the most performant. b8's storage model is optimized for this database, as it is really fast and fits perfectly to what the filter needs to do the job. All content is saved in a single file, you don't need special user rights or a database server. <br />
+If you don't know whether your server's PHP can use a Berkeley DB, simply run the script <tt class="docutils literal">install/setup_berkeleydb.php</tt>. If it shows a Berkeley DB handler, please use this backend.</dd>
+<dt><em>MySQL</em></dt>
+<dd>As some webspace hosters don't allow using a Berkeley DB (but please be sure to check if you can use it!), but most do provide a MySQL server, using a MySQL table for the wordlist is provided as an alternative storage method. As said above, b8 was always intended to use a Berkeley DB. It doesn't use or need SQL to query the database. So, very likely, this will work less performant, produce a lot of unnecessary overhead and waste computing power. But it will do fine anyway!</dd>
+</dl>
+<p class="last">See <a class="reference internal" href="#configuration-of-the-storage-backend">Configuration of the storage backend</a> for the settings of the chosen backend.</p>
+</dd>
+<dt><strong>degenerator</strong></dt>
+<dd>The degenerator class to be used. See <a class="reference internal" href="#how-does-it-work">How does it work?</a> and <a class="footnote-reference" href="#betterbayesian" id="id12">[3]</a> if you're interested in what &quot;degeneration&quot; is. Defaults to <tt class="docutils literal">default</tt> (string). At the moment, only one degenerator exists, so you probably don't want to change this unless you have written your own degenerator.</dd>
+<dt><strong>lexer</strong></dt>
+<dd><p class="first">The lexer class to be used. Defaults to <tt class="docutils literal">default</tt> (string). At the moment, only one lexer exists, so you probably don't want to change this unless you have written your own lexer.</p>
+<p>The behaviour of the lexer can be additionally configured with the following variables:</p>
+<blockquote class="last">
+<dl class="docutils">
+<dt><strong>min_size</strong></dt>
+<dd>The minimal length for a token to be considered when calculating the rating of a text. Defaults to <tt class="docutils literal">3</tt> (integer).</dd>
+<dt><strong>max_size</strong></dt>
+<dd>The maximal length for a token to be considered when calculating the rating of a text. Defaults to <tt class="docutils literal">30</tt> (integer).</dd>
+<dt><strong>allow_numbers</strong></dt>
+<dd>Should pure numbers also be considered? Defaults to <tt class="docutils literal">FALSE</tt> (boolean).</dd>
+</dl>
+</blockquote>
+</dd>
+</dl>
+</blockquote>
+<p>The following settings influence the mathematical internals of b8. If you want to experiment, feel free to play around with them; but be warned: wrong settings of these values will result in poor performance or could even &quot;short-circuit&quot; the filter. <br />
+Leave these values as they are unless you know what you are doing!</p>
+<p>The &quot;Statistical discussion about b8&quot; <a class="footnote-reference" href="#b8statistic" id="id13">[6]</a> shows why the default values are the default ones.</p>
+<blockquote>
+<dl class="docutils">
+<dt><strong>use_relevant</strong></dt>
+<dd>This tells b8 how many tokens should be used when calculating the spamminess of a text. The default setting is <tt class="docutils literal">15</tt> (integer). This seems to be a quite reasonable value. When using to many tokens, the filter will fail on texts filled with useless stuff or with passages from a newspaper, etc. not being very spammish. <br />
+The tokens counted multiple times (see above) are added in addition to this value. They don't replace other ratings.</dd>
+<dt><strong>min_dev</strong></dt>
+<dd>This defines a minimum deviation from 0.5 that a token's rating must have to be considered when calculating the spamminess. Tokens with a rating closer to 0.5 than this value will simply be skipped. <br />
+If you don't want to use this feature, set this to <tt class="docutils literal">0</tt>. Defaults to <tt class="docutils literal">0.2</tt> (float). Read <a class="footnote-reference" href="#b8statistic" id="id14">[6]</a> before increasing this.</dd>
+<dt><strong>rob_x</strong></dt>
+<dd>This is Gary Robinson's <em>x</em> constant (cf. <a class="footnote-reference" href="#spamdetection" id="id15">[4]</a>). A completely unknown token will be rated with the value of <tt class="docutils literal">rob_x</tt>. The default <tt class="docutils literal">0.5</tt> (float) seems to be quite reasonable, as we can't say if a token that also can't be rated by degeneration is good or bad. <br />
+If you receive much more spam than ham or vice versa, you could change this setting accordingly.</dd>
+<dt><strong>rob_s</strong></dt>
+<dd>This is Gary Robinson's <em>s</em> constant. This is essentially the probability that the <em>rob_x</em> value is correct for a completely unknown token. It will also shift the probability of rarely seen tokens towards this value. The default is <tt class="docutils literal">0.3</tt> (float) <br />
+See <a class="footnote-reference" href="#spamdetection" id="id16">[4]</a> for a closer description of the <em>s</em> constant and read <a class="footnote-reference" href="#b8statistic" id="id17">[6]</a> for specific information about this constant in b8's algorithms.</dd>
+</dl>
+</blockquote>
+</div>
+<div class="section" id="configuration-of-the-storage-backend">
+<h2><a class="toc-backref" href="#id29">4.2&nbsp;&nbsp;&nbsp;Configuration of the storage backend</a></h2>
+<p>All the following values can be set in the &quot;config_database&quot; array (the second parameter) passed to b8. The name of the array doesn't matter (of course), it just has to be the second argument.</p>
+<div class="section" id="settings-for-the-berkeley-db-dba-backend">
+<h3><a class="toc-backref" href="#id30">4.2.1&nbsp;&nbsp;&nbsp;Settings for the Berkeley DB (DBA) backend</a></h3>
+<dl class="docutils">
+<dt><strong>database</strong></dt>
+<dd>The filename of the database file, relative to the location of <tt class="docutils literal">b8.php</tt>. Defaults to <tt class="docutils literal">wordlist.db</tt> (string).</dd>
+<dt><strong>handler</strong></dt>
+<dd>The DBA handler to use (cf. <a class="reference external" href="http://php.net/manual/en/dba.requirements.php">the PHP documentation</a> and <a class="reference internal" href="#setting-up-a-new-berkeley-db">Setting up a new Berkeley DB</a>). Defaults to <tt class="docutils literal">db4</tt> (string).</dd>
+</dl>
+</div>
+<div class="section" id="settings-for-the-mysql-backend">
+<h3><a class="toc-backref" href="#id31">4.2.2&nbsp;&nbsp;&nbsp;Settings for the MySQL backend</a></h3>
+<dl class="docutils">
+<dt><strong>database</strong></dt>
+<dd>The database containing b8's wordlist table. Defaults to <tt class="docutils literal">b8_wordlist</tt> (string).</dd>
+<dt><strong>table_name</strong></dt>
+<dd>The table containing b8's wordlist. Defaults to <tt class="docutils literal">b8_wordlist</tt> (string).</dd>
+<dt><strong>host</strong></dt>
+<dd>The host of the MySQL server. Defaults to <tt class="docutils literal">localhost</tt> (string).</dd>
+<dt><strong>user</strong></dt>
+<dd>The user name used to open the database connection. Defaults to <tt class="docutils literal">FALSE</tt> (boolean).</dd>
+<dt><strong>pass</strong></dt>
+<dd>The password required to open the database connection. Defaults to <tt class="docutils literal">FALSE</tt> (boolean).</dd>
+<dt><strong>connection</strong></dt>
+<dd>An existing MySQL link-resource that can be used by b8. Defaults to <tt class="docutils literal">NULL</tt> (NULL).</dd>
+</dl>
+</div>
+</div>
+</div>
+<div class="section" id="using-b8">
+<h1><a class="toc-backref" href="#id32">5&nbsp;&nbsp;&nbsp;Using b8</a></h1>
+<p>Now, that everything is configured, you can start to use b8. A sample script that shows what can be done with the filter exists in <tt class="docutils literal">example/index.php</tt>. The best thing for testing how all this works is to use this script before using b8 in your own scripts.</p>
+<p>Before you can start, you have to setup a database so that b8 can store a wordlist.</p>
+<div class="section" id="setting-up-a-new-database">
+<h2><a class="toc-backref" href="#id33">5.1&nbsp;&nbsp;&nbsp;Setting up a new database</a></h2>
+<div class="section" id="setting-up-a-new-berkeley-db">
+<h3><a class="toc-backref" href="#id34">5.1.1&nbsp;&nbsp;&nbsp;Setting up a new Berkeley DB</a></h3>
+<p>I wrote a script to setup a new Berkeley DB for b8. It is located in <tt class="docutils literal">install/setup_berkeleydb.php</tt>. Just run this script on your server and be sure that the directory containing it has the proper access rights set so that the server's HTTP server user or PHP user can create a new file in it (probably <tt class="docutils literal">0777</tt>). The script is quite self-explaining, just run it.</p>
+<p>Of course, you can also create a Berkeley DB by hand. In this case, you just have to insert three keys:</p>
+<pre class="literal-block">
+bayes*dbversion =&gt; 2
+bayes*texts.ham =&gt; 0
+bayes*texts.spam =&gt; 0
+</pre>
+<p>Be sure to set the right DBA handler in the storage backend configuration if it's not <tt class="docutils literal">db4</tt>.</p>
+</div>
+<div class="section" id="setting-up-a-new-mysql-table">
+<h3><a class="toc-backref" href="#id35">5.1.2&nbsp;&nbsp;&nbsp;Setting up a new MySQL table</a></h3>
+<p>The SQL file <tt class="docutils literal">install/setup_mysql.sql</tt> contains both the create statement for the wordlist table of b8 and the <tt class="docutils literal">INSERT</tt> statements for adding the necessary internal variables.</p>
+<p>Simply change the table name according to your needs (or leave it as it is ;-) and run the SQL to setup a b8 wordlist MySQL table.</p>
+</div>
+</div>
+<div class="section" id="using-b8-in-your-scripts">
+<h2><a class="toc-backref" href="#id36">5.2&nbsp;&nbsp;&nbsp;Using b8 in your scripts</a></h2>
+<p>Just have a look at the example script located in <tt class="docutils literal">example/index.php</tt> to see how you can include b8 in your scripts. Essentially, this strips down to:</p>
+<pre class="literal-block">
+# Include the b8 code
+require &quot;{$_SERVER['DOCUMENT_ROOT']}/b8/b8.php&quot;;
+
+# Do some configuration
+
+$config_b8 = array(
+ 'some_key' =&gt; 'some_value',
+ 'foo' =&gt; 'bar'
+);
+
+$config_database = array(
+ 'some_key' =&gt; 'some_value',
+ 'foo' =&gt; 'bar'
+);
+
+# Create a new b8 instance
+$b8 = new b8($config_b8, $config_database);
+</pre>
+<p>b8 provides three functions in an object oriented way (called e. g. via <tt class="docutils literal"><span class="pre">$b8-&gt;classify($text)</span></tt>):</p>
+<dl class="docutils">
+<dt><strong>learn($text, $category)</strong></dt>
+<dd>This saves the reference text <tt class="docutils literal">$text</tt> (string) in the category <tt class="docutils literal">$category</tt> (b8 constant). <br />
+b8 0.5 introduced two constants that can be used as <tt class="docutils literal">$category</tt>: <tt class="docutils literal"><span class="pre">b8::HAM</span></tt> and <tt class="docutils literal"><span class="pre">b8::SPAM</span></tt>. To be downward compatible with older versions of b8, the literal values &quot;ham&quot; and &quot;spam&quot; (case-sensitive strings) can still be used here.</dd>
+<dt><strong>unlearn($text, $category)</strong></dt>
+<dd>This function just exists to delete a text from a category in which is has been stored accidentally before. It deletes the reference text <tt class="docutils literal">$text</tt> (string) from the category <tt class="docutils literal">$category</tt> (either the constants <tt class="docutils literal"><span class="pre">b8::HAM</span></tt> or <tt class="docutils literal"><span class="pre">b8::SPAM</span></tt> or the literal case-sensitive strings &quot;ham&quot; or &quot;spam&quot; – cf. above). <br />
+<strong>Don't delete a spam text from ham after saving it in spam or vice versa, as long you don't have stored it accidentally in the wrong category before!</strong> This will not improve performance, quite the opposite: it will actually break the filter after a time, as the counter for saved ham or spam texts will reach 0, although you have ham or spam tokens stored: the filter will try to remove texts from the ham or spam data which have never been stored there, decrease the counter for tokens which are found just skip the non-existing words.</dd>
+<dt><strong>classify($text)</strong></dt>
+<dd>This function takes the text <tt class="docutils literal">$text</tt> (string), calculates it's probability for being spam it and returns a value between 0 and 1 (float). <br />
+A value close to 0 says the text is more likely ham and a value close to 1 says the text is more likely spam. What to do with this value is <em>your</em> business ;-) See also <a class="reference internal" href="#tips-on-operation">Tips on operation</a> below.</dd>
+</dl>
+</div>
+</div>
+<div class="section" id="tips-on-operation">
+<h1><a class="toc-backref" href="#id37">6&nbsp;&nbsp;&nbsp;Tips on operation</a></h1>
+<p>Before b8 can decide whether a text is spam or ham, you have to tell it what you consider as spam or ham. At least one learned spam or one learned ham text is needed to calculate anything. To get good ratings, you need both learned ham and learned spam texts, the more the better. <br />
+What's considered as &quot;ham&quot; or &quot;spam&quot; can be very different, depending on the operation site. On my homepage, practically each and every text posted in English or using cyrillic letters is spam. On an English or Russian homepage, this will be not the case. So I think it's not really meaningful to provide some &quot;spam data&quot; to start. Just train b8 with &quot;your&quot; spam and ham.</p>
+<p>For the practical use, I advise to give the filter all data availible. E. g. name, email address, homepage, IP address und of course the text itself should be stored in a variable (e. g. separated with an <tt class="docutils literal">\n</tt> or just a space or tab after each block) and then be classified. The learning should also be done with all data availible. <br />
+Saving the IP address is probably only meaningful for spam entries, because spammers often use the same IP address multiple times. In principle, you can leave out the IP of ham entries.</p>
+<p>You can use b8 e. g. in a guestbook script and let it classify the text before saving it. Everyone has to decide which rating is necessary to classify a text as &quot;spam&quot;, but a rating of &gt;= 0.8 seems to be reasonable for me. If one expects the spam to be in another language that the ham entries or the spams are very short normally, one could also think about a limit of 0.7. <br />
+The email filters out there mostly use &gt; 0.9 or even &gt; 0.99; but keep in mind that they have way more data to analyze in most of the cases. A guestbook entry may be quite short, especially when it's spam.</p>
+<p>In my opinion, a autolearn function is very handy. I save spam messages with a rating higher than 0.7 but less than 0.9 automatically as spam. I don't do this with ham messages in an automated way to prevent the filter from saving a false negative as ham and then classifying and learning all the spam as ham when I'm on holidays ;-)</p>
+</div>
+<div class="section" id="closing">
+<h1><a class="toc-backref" href="#id38">7&nbsp;&nbsp;&nbsp;Closing</a></h1>
+<p>So … that's it. Thanks for using b8! If you find a bug or have an idea how to make b8 better, let me know. I'm also always looking forward to get e-mails from people using b8 on their homepages :-)</p>
+</div>
+<div class="section" id="references">
+<h1><a class="toc-backref" href="#id39">8&nbsp;&nbsp;&nbsp;References</a></h1>
+<table class="docutils footnote" frame="void" id="planforspam" rules="none">
+<colgroup><col class="label" /><col /></colgroup>
+<tbody valign="top">
+<tr><td class="label">[2]</td><td><em>(<a class="fn-backref" href="#id3">1</a>, <a class="fn-backref" href="#id9">2</a>)</em> Paul Graham, <em>A Plan For Spam</em> (<a class="reference external" href="http://paulgraham.com/spam.html">http://paulgraham.com/spam.html</a>)</td></tr>
+</tbody>
+</table>
+<table class="docutils footnote" frame="void" id="betterbayesian" rules="none">
+<colgroup><col class="label" /><col /></colgroup>
+<tbody valign="top">
+<tr><td class="label">[3]</td><td><em>(<a class="fn-backref" href="#id4">1</a>, <a class="fn-backref" href="#id7">2</a>, <a class="fn-backref" href="#id12">3</a>)</em> Paul Graham, <em>Better Bayesian Filtering</em> (<a class="reference external" href="http://paulgraham.com/better.html">http://paulgraham.com/better.html</a>)</td></tr>
+</tbody>
+</table>
+<table class="docutils footnote" frame="void" id="spamdetection" rules="none">
+<colgroup><col class="label" /><col /></colgroup>
+<tbody valign="top">
+<tr><td class="label">[4]</td><td><em>(<a class="fn-backref" href="#id5">1</a>, <a class="fn-backref" href="#id8">2</a>, <a class="fn-backref" href="#id15">3</a>, <a class="fn-backref" href="#id16">4</a>)</em> Gary Robinson, <em>Spam Detection</em> (<a class="reference external" href="http://radio.weblogs.com/0101454/stories/2002/09/16/spamDetection.html">http://radio.weblogs.com/0101454/stories/2002/09/16/spamDetection.html</a>)</td></tr>
+</tbody>
+</table>
+<table class="docutils footnote" frame="void" id="statisticalapproach" rules="none">
+<colgroup><col class="label" /><col /></colgroup>
+<tbody valign="top">
+<tr><td class="label"><a class="fn-backref" href="#id6">[5]</a></td><td><em>A Statistical Approach to the Spam Problem</em> (<a class="reference external" href="http://linuxjournal.com/article/6467">http://linuxjournal.com/article/6467</a>)</td></tr>
+</tbody>
+</table>
+<table class="docutils footnote" frame="void" id="b8statistic" rules="none">
+<colgroup><col class="label" /><col /></colgroup>
+<tbody valign="top">
+<tr><td class="label">[6]</td><td><em>(<a class="fn-backref" href="#id13">1</a>, <a class="fn-backref" href="#id14">2</a>, <a class="fn-backref" href="#id17">3</a>)</em> Tobias Leupold, <em>Statistical discussion about b8</em> (<a class="reference external" href="http://nasauber.de/opensource/b8/discussion/">http://nasauber.de/opensource/b8/discussion/</a>)</td></tr>
+</tbody>
+</table>
+</div>
+<div class="section" id="appendix">
+<h1><a class="toc-backref" href="#id40">9&nbsp;&nbsp;&nbsp;Appendix</a></h1>
+<div class="section" id="faq">
+<h2><a class="toc-backref" href="#id41">9.1&nbsp;&nbsp;&nbsp;FAQ</a></h2>
+<div class="section" id="what-about-more-than-two-categories">
+<h3><a class="toc-backref" href="#id42">9.1.1&nbsp;&nbsp;&nbsp;What about more than two categories?</a></h3>
+<p>I wrote b8 with the <a class="reference external" href="http://en.wikipedia.org/wiki/KISS_principle">KISS principle</a> in mind. For the &quot;end-user&quot;, we have a class with almost no setup to do that can do three things: classify a text, learn a text and un-learn a text. Normally, there's no need to un-learn a text, so essentially, there are only two functions we need. <br />
+This simplicity is only possible because b8 only knows two categories (normally &quot;Ham&quot; and &quot;Spam&quot; or some other category pair) and tells you, in one float number between 0 and 1, if a given texts rather fits in the first or the second category. If we would support multiple categories, more work would have to be done and things would become more complicated. One would have to setup the categories, have another database layout (perhaps making it mandatory to have SQL) and one float number would not be sufficient to describe b8's output, so more code would be needed – even outside of b8.</p>
+<p>All the code, the database layout and particularly the math is intended to do exactly one thing: distinguish between two categories. I think it would be a lot of work to change b8 so that it would support more than two categories. Probably, this is possible to do, but don't ask me in which way we would have to change the math to get multiple-category support – I'm a dentist, not a mathematician ;-) <br />
+Apart from this I do believe that most people using b8 don't want or need multiple categories. They just want to know if a text is spam or not, don't they? I do, at least ;-)</p>
+<p>But let's think about the multiple-category thing. How would we calculate a rating for more than two categories? If we had a third one, let's call it &quot;<a class="reference external" href="http://en.wikipedia.org/wiki/Treet">Treet</a>&quot;, how would we calculate a rating? We could calculate three different ratings. One for &quot;Ham&quot;, one for &quot;Spam&quot; and one for &quot;Treet&quot; and choose the highest one to tell the user what category fits best for the text. This could be done by using a small wrapper script using three instances of b8 as-is and three different databases, each containing texts being &quot;Ham&quot;, &quot;Spam&quot;, &quot;Treet&quot; and the respective counterparts. <br />
+But here's the problem: if we have &quot;Ham&quot; and &quot;Spam&quot;, &quot;Spam&quot; is the counterpart of &quot;Ham&quot;. But what's the counterpart of &quot;Spam&quot; if we have more than one additional category? Where do the &quot;Non-Ham&quot;, &quot;Non-Spam&quot; and &quot;Non-Treet&quot; texts come from?</p>
+<p>Another approach, a direct calculation of more than two probabilities (the &quot;Ham&quot; probability is simply 1 minus the &quot;Spam&quot; probability, so we actually get two probabilities with the return value of b8) out of one database would require big changes in b8's structure and math.</p>
+<p>There's a project called <a class="reference external" href="http://xhtml.net/scripts/PHPNaiveBayesianFilter">PHPNaiveBayesianFilter</a> which supports multiple categories by default. The author calls his software &quot;Version 1.0&quot;, but I think this is the very first release, not a stable or mature one. The most recent change of that release dates back to 2003 according to the &quot;changed&quot; date of the files inside the zip archive, so probably, this project is dead or has never been alive and under active development at all. <br />
+Actually, I played around with that code but the results weren't really good, so I decided to write my own spam filter from scratch back in early 2006 ;-)</p>
+<p>All in all, there seems to be no easy way to implement multiple (meaning more than two) categories using b8's current code base and probably, b8 will never support more than two categories. Perhaps, a fork or a complete re-write would be better than implementing such a feature. Anyway, I don't close my mind to multiple categories in b8. Feel free to tell me how multiple categories could be implementented in b8 or how a multiple-category version using the same code base (sharing a common abstract class?) could be written.</p>
+</div>
+<div class="section" id="what-about-a-list-with-words-to-ignore">
+<h3><a class="toc-backref" href="#id43">9.1.2&nbsp;&nbsp;&nbsp;What about a list with words to ignore?</a></h3>
+<p>Some people suggested to introduce a list with words that b8 will simply ignore. Like &quot;and&quot;, &quot;or&quot;, &quot;the&quot;, and so on. I don't think this is very meaningful.</p>
+<p>First, it would just work for the particular language that has been stored in the list. Speaking of my homepage, most of my spam is English, almost all my ham is German. So I would have to maintain a list with the probably less interesting words for at least two languages. Additionally, I get spam in Chinese, Japanese and Cyrillic writing or something else I can't read as well. What word should be ignored in those texts? <br />
+Second, why should we ever exclude words? Who tells us those words are <em>actually</em> meaningless? If a word appears both in ham and spam, it's rating will be near 0.5 and so, it won't be used for the final calculation if a appropriate minimum deviation was set. So b8 will exclude it anyway without any blacklist. And think of this: if we excluded a word of which we only <em>think</em> it doesn't mean anything but it actually does appear more often in ham or spam, the results will get even worse.</p>
+<p>So why should we care about things we do not have to care about? ;-)</p>
+</div>
+<div class="section" id="why-is-it-called-b8">
+<h3><a class="toc-backref" href="#id44">9.1.3&nbsp;&nbsp;&nbsp;Why is it called &quot;b8&quot;?</a></h3>
+<p>The initial name for the filter was (damn creative!) &quot;bayes-php&quot;. There were two main reasons for searching another name: 1. &quot;bayes-php&quot; sucks. 2. the <a class="reference external" href="http://php.net/license/3_01.txt">PHP License</a> says the PHP guys do not like when the name of a script written in PHP contains the word &quot;PHP&quot;. Read the <a class="reference external" href="http://www.php.net/license/index.php#faq-lic">License FAQ</a> for a reasonable argumentation about this.</p>
+<p>Luckily, <a class="reference external" href="http://langt.net/">Tobias Lang</a> proposed the new name &quot;b8&quot;. And these are the reasons why I chose this name:</p>
+<ul class="simple">
+<li>&quot;bayes-php&quot; is a &quot;b&quot; followed by 8 letters.</li>
+<li>&quot;b8&quot; is short and handy. Additionally, there was no program with the name &quot;b8&quot; or &quot;bate&quot;</li>
+<li>The English verb &quot;to bate&quot; means &quot;to decrease&quot; – and that's what b8 does: it decreases the number of spam entries in your weblog or guestbook!</li>
+<li>&quot;b8&quot; just sounds way cooler than &quot;bayes-php&quot; ;-)</li>
+</ul>
+</div>
+</div>
+<div class="section" id="about-the-database">
+<h2><a class="toc-backref" href="#id45">9.2&nbsp;&nbsp;&nbsp;About the database</a></h2>
+<div class="section" id="the-database-layout">
+<h3><a class="toc-backref" href="#id46">9.2.1&nbsp;&nbsp;&nbsp;The database layout</a></h3>
+<p>The database layout is quite simple. It's just key:value for everything stored. There are three &quot;internal&quot; variables stored as normal tokens (but all containing a <tt class="docutils literal">*</tt> which is always used as a split character by the lexer, so we can't get collisions):</p>
+<dl class="docutils">
+<dt><strong>bayes*dbversion</strong></dt>
+<dd>This indicates the database's &quot;version&quot;. The first versions of b8 did not set this. Version &quot;2&quot; indicates that we have a database created by a b8 version already storing <a class="reference internal" href="#the-lastseen-parameter">the &quot;lastseen&quot; parameter</a>.</dd>
+<dt><strong>bayes*texts.ham</strong></dt>
+<dd>The number of ham texts learned.</dd>
+<dt><strong>bayes*texts.spam</strong></dt>
+<dd>The number of spam texts learned.</dd>
+</dl>
+<p>Each &quot;normal&quot; token is stored with it's literal name as the key and it's data as the value. The data consists of the count of the token in all ham and spam texts and the date when the token was used the last time, all in one string and separated by spaces. So we have the following scheme:</p>
+<pre class="literal-block">
+&quot;token&quot; =&gt; &quot;count_ham count_spam lastseen&quot;
+</pre>
+</div>
+<div class="section" id="the-lastseen-parameter">
+<h3><a class="toc-backref" href="#id47">9.2.2&nbsp;&nbsp;&nbsp;The &quot;lastseen&quot; parameter</a></h3>
+<p>Somebody looking at the code might be wondering why b8 stores this &quot;lastseen&quot; parameter. This value is not used for any calculation at the moment. Initially, it was intended to keep the database maintainable in a way that &quot;old&quot; data could be removed. When e. g. a token only appeared once in ham or spam and has not been seen for a year, one could simply delete it from the database. <br />
+I actually never used this feature (does anybody?). So probably, some changes will be done to this one day. Perhaps, I find a way to include this data in the spamminess calculation in a meaningful way, or at least for some statistics. One could also make this optional to keep the calculation effort small if this is needed.</p>
+<p>Feel free to send me any suggestions about this!</p>
+</div>
+</div>
+</div>
+</div>
+</body>
+</html>
diff --git a/library/spam/doc/readme.rst b/library/spam/doc/readme.rst
new file mode 100644
index 000000000..451b28326
--- /dev/null
+++ b/library/spam/doc/readme.rst
@@ -0,0 +1,371 @@
+==========
+b8: readme
+==========
+
+:Author: Tobias Leupold
+:Homepage: http://nasauber.de/
+:Contact: tobias.leupold@web.de
+:Date: |date|
+
+.. contents:: Table of Contents
+
+Description of b8
+=================
+
+What is b8?
+-----------
+
+b8 is a spam filter implemented in `PHP <http://www.php.net/>`__. It is intended to keep your weblog or guestbook spam-free. The filter can be used anywhere in your PHP code and tells you whether a text is spam or not, using statistical text analysis. See `How does it work?`_ for details about this. To be able to do this, b8 first has to learn some spam and some ham example texts to decide what's good and what's not. If it makes mistakes classifying unknown texts, they can be corrected and b8 learns from the corrections, getting better with each learned text.
+
+At the moment of this writing, b8 has classified 14411 guestbook entries and weblog comments on my homepage since december 2006. 131 were ham. 39 spam texts (0.27 %) have been rated as ham (false negatives), with not even one false positive (ham message classified as spam). This results in a sensitivity of 99.73 % (the probability that a spam text will actually be rated as spam) and a specifity of 100 % (the probability that a ham text will actually be rated as ham) for me. I hope, you'll get the same good results :-)
+
+Basically, b8 is a statistical ("Bayesian"[#]_) spam filter like `Bogofilter <http://bogofilter.sourceforge.net/>`__ or `SpamBayes <http://spambayes.sourceforge.net/>`__, but it is not intended to classify e-mails. When I started to write b8, I didn't find a good PHP spam filter (or any spam filter that wasn't just some example code how one *could* implement a Bayesian spam filter in PHP) that was intended to filter weblog or guestbook entries. That's why I had to write my own ;-) |br|
+Caused by it's purpose, the way b8 works is slightly different from most of the Bayesian email spam filters out there. See `What's different?`_ if you're interested in the details.
+
+.. [#] A mathematician told me that the math in b8 actually does not use Bayes' theorem but some derived algorithms that are just related to it. So … let's simply believe that and stop claiming b8 was a *Bayesian* spam filter ;-)
+
+How does it work?
+-----------------
+
+b8 basically uses the math and technique described in Paul Graham's article "A Plan For Spam" [#planforspam]_ to distinguish ham and spam. The improvements proposed in Graham's article "Better Bayesian Filtering" [#betterbayesian]_ and Gary Robinson's article "Spam Detection" [#spamdetection]_ have also been considered. See also the article "A Statistical Approach to the Spam Problem" [#statisticalapproach]_.
+
+b8 cuts the text to classify to pieces, extracting stuff like e-mail addresses, links and HTML tags. For each such token, it calculates a single probability for a text containing it being spam, based on what the filter has learned so far. When the token was not seen before, b8 tries to find similar ones using the "degeneration" described in [#betterbayesian]_ and uses the most relevant value found. If really nothing is found, b8 assumes a default rating for this token for the further calculations. |br|
+Then, b8 takes the most relevant values (which have a rating far from 0.5, which would mean we don't know what it is) and calculates the probability that the whole text is spam by the inverse chi-square function described in [#spamdetection]_.
+There are some parameters that can be set which influence the filter's behaviour (see below).
+
+In short words: you give b8 a text and it returns a value between 0 and 1, saying it's ham when it's near 0 and saying it's spam when it's near 1.
+
+What do I need for it?
+----------------------
+
+Not much! You just need PHP 5 on the server where b8 will be used (b8 version 0.5 finally dropped PHP 4 compatibility – thankfully ;-) and a proper storage possibility for the wordlists. I strongly recommend using `Berkeley DB <http://www.oracle.com/database/berkeley-db/index.html>`_. See below how you can check if you can use it and why you should use it. If the server's PHP wasn't compiled with Berkeley DB support, a `MySQL <http://mysql.com/>`_ table can be used alternatively.
+
+What's different?
+-----------------
+
+b8 is designed to classify weblog or guestbook entries, not e-mails. For this reason, it uses a slightly different technique than most of the other statistical spam filters out there use.
+
+My experience was that spam entries on my weblog or guestbook were often quite short, sometimes just something like "123abc" as text and a link to a suspect homepage. Some spam bots don't even made a difference between e. g. the "name" and "text" fields and posted their text as email address, for example. Considering this, b8 just takes one string to classify, making no difference between "headers" and "text". |br|
+The other thing is that most statistical spam filters count one token one time, no matter how often it appears in the text (as Graham describes it in [#planforspam]_). b8 does count how often a token was seen and learns or considers this. Additionally, the number of learned ham and spam texts are saved and used as the calculation base for the single probabilities. Why this? Because a text containing one link (no matter where it points to, just indicated by a "\h\t\t\p\:\/\/" or a "www.") might not be spam, but a text containing 20 links might be.
+
+This means that b8 might be good for classifying weblog or guestbook entries (I really think it is ;-) – but very likely, it will work quite poor when being used for something else (like classifying e-mails). But as said above, for this task, there are a lot of very good filters out there to choose from.
+
+Update from prior versions
+==========================
+
+If this is a new b8 installation, read on at the `Installation`_ section!
+
+Update from bayes-php version 0.2.1 or earlier
+----------------------------------------------
+
+Please first follow the database update instructions of the bayes-php-0.3 release if you update from a version prior to bayes-php-0.3 and then read the following paragraph about updating from a version <0.3.3.
+
+Update from bayes-php version 0.3 or later
+------------------------------------------
+
+**You use Berkeley DB?**
+ Everything's fine, you can simply continue using your database.
+
+**You use MySQL?**
+ The ``CREATE`` statement of b8's wordlist has changed. The best is probably to create a dump via your favorite administration tool or script, create the new table and re-insert all data. The layout is still the same: there's one "token" column and one "data" column. Having done that, you can keep using your data.
+
+**You use SQLite?**
+ Sorry, at the moment, there's no SQLite backend for b8. But we're working on it :-)
+
+The configuration model of b8 has changed. Please read through the `Configuration`_ section and update your configuration accordingly.
+
+b8's lexer has been partially re-written. It should now be able to handle all kind of non-latin-1 input, like cyrillic, chinese or japanese texts. Caused by this fact, much more tokens will be recognized when classifying such texts. Therefore, you could get different results in b8's ratings, even if the same database is used and although the math is still the same.
+
+b8 0.5 introduced two constants that can be used in the ``learn()`` and ``unlearn()`` functions: ``b8::HAM`` and ``b8::SPAM``. The literal values "ham" and "spam" can still be used anyway.
+
+Installation
+============
+
+Installing b8 on your server is quite easy. You just have to provide the needed files. To do this, you could just upload the whole ``b8`` subdirectory to the base directory of your homepage. It contains the filter itself and all needed backend classes. The other directories (``doc``, ``example`` and ``install``) are not used by b8.
+
+That's it ;-)
+
+Configuration
+=============
+
+The configuration is passed as arrays when instantiating a new b8 object. Two arrays can be passed to b8, one containing b8's base configuration and some settings for the lexer (which should be common for all lexer classes, in case some other lexer than the default one will be written one day) and one for the storage backend. |br|
+You can have a look at ``example/index.php`` to see how this can be done. `Using b8 in your scripts`_ also shows example code showing how b8 can be included in a PHP script.
+
+Not all values have to be set. When some values are missing, the default ones will be used. If you do use the default settings, you don't have to pass them to b8.
+
+b8's base configuration
+-----------------------
+
+All these values can be set in the "config_b8" array (the first parameter) passed to b8. The name of the array doesn't matter (of course), it just has to be the first argument.
+
+These are some basic settings telling b8 which backend classes to use:
+
+ **storage**
+ This defines which storage backend will be used to save b8's wordlist. Currently, two backends are available: `Berkeley DB <http://www.oracle.com/database/berkeley-db/index.html>`_ (``dba``) and `MySQL <http://mysql.com/>`_ (``mysql``). At the moment, b8 does not support `SQLite <http://sqlite.org/>`_ (as the previous version did), but it will be (hopefully) re-added in one of the next releases. The default is ``dba`` (string).
+
+ *Berkeley DB*
+ This is the preferred storage backend. It was the original backend for the filter and remains the most performant. b8's storage model is optimized for this database, as it is really fast and fits perfectly to what the filter needs to do the job. All content is saved in a single file, you don't need special user rights or a database server. |br|
+ If you don't know whether your server's PHP can use a Berkeley DB, simply run the script ``install/setup_berkeleydb.php``. If it shows a Berkeley DB handler, please use this backend.
+
+ *MySQL*
+ As some webspace hosters don't allow using a Berkeley DB (but please be sure to check if you can use it!), but most do provide a MySQL server, using a MySQL table for the wordlist is provided as an alternative storage method. As said above, b8 was always intended to use a Berkeley DB. It doesn't use or need SQL to query the database. So, very likely, this will work less performant, produce a lot of unnecessary overhead and waste computing power. But it will do fine anyway!
+
+ See `Configuration of the storage backend`_ for the settings of the chosen backend.
+
+ **degenerator**
+ The degenerator class to be used. See `How does it work?`_ and [#betterbayesian]_ if you're interested in what "degeneration" is. Defaults to ``default`` (string). At the moment, only one degenerator exists, so you probably don't want to change this unless you have written your own degenerator.
+
+ **lexer**
+ The lexer class to be used. Defaults to ``default`` (string). At the moment, only one lexer exists, so you probably don't want to change this unless you have written your own lexer.
+
+ The behaviour of the lexer can be additionally configured with the following variables:
+
+ **min_size**
+ The minimal length for a token to be considered when calculating the rating of a text. Defaults to ``3`` (integer).
+
+ **max_size**
+ The maximal length for a token to be considered when calculating the rating of a text. Defaults to ``30`` (integer).
+
+ **allow_numbers**
+ Should pure numbers also be considered? Defaults to ``FALSE`` (boolean).
+
+The following settings influence the mathematical internals of b8. If you want to experiment, feel free to play around with them; but be warned: wrong settings of these values will result in poor performance or could even "short-circuit" the filter. |br|
+Leave these values as they are unless you know what you are doing!
+
+The "Statistical discussion about b8" [#b8statistic]_ shows why the default values are the default ones.
+
+ **use_relevant**
+ This tells b8 how many tokens should be used when calculating the spamminess of a text. The default setting is ``15`` (integer). This seems to be a quite reasonable value. When using to many tokens, the filter will fail on texts filled with useless stuff or with passages from a newspaper, etc. not being very spammish. |br|
+ The tokens counted multiple times (see above) are added in addition to this value. They don't replace other ratings.
+
+ **min_dev**
+ This defines a minimum deviation from 0.5 that a token's rating must have to be considered when calculating the spamminess. Tokens with a rating closer to 0.5 than this value will simply be skipped. |br|
+ If you don't want to use this feature, set this to ``0``. Defaults to ``0.2`` (float). Read [#b8statistic]_ before increasing this.
+
+ **rob_x**
+ This is Gary Robinson's *x* constant (cf. [#spamdetection]_). A completely unknown token will be rated with the value of ``rob_x``. The default ``0.5`` (float) seems to be quite reasonable, as we can't say if a token that also can't be rated by degeneration is good or bad. |br|
+ If you receive much more spam than ham or vice versa, you could change this setting accordingly.
+
+ **rob_s**
+ This is Gary Robinson's *s* constant. This is essentially the probability that the *rob_x* value is correct for a completely unknown token. It will also shift the probability of rarely seen tokens towards this value. The default is ``0.3`` (float) |br|
+ See [#spamdetection]_ for a closer description of the *s* constant and read [#b8statistic]_ for specific information about this constant in b8's algorithms.
+
+Configuration of the storage backend
+------------------------------------
+
+All the following values can be set in the "config_database" array (the second parameter) passed to b8. The name of the array doesn't matter (of course), it just has to be the second argument.
+
+Settings for the Berkeley DB (DBA) backend
+``````````````````````````````````````````
+**database**
+ The filename of the database file, relative to the location of ``b8.php``. Defaults to ``wordlist.db`` (string).
+
+**handler**
+ The DBA handler to use (cf. `the PHP documentation <http://php.net/manual/en/dba.requirements.php>`_ and `Setting up a new Berkeley DB`_). Defaults to ``db4`` (string).
+
+Settings for the MySQL backend
+``````````````````````````````
+
+**database**
+ The database containing b8's wordlist table. Defaults to ``b8_wordlist`` (string).
+
+**table_name**
+ The table containing b8's wordlist. Defaults to ``b8_wordlist`` (string).
+
+**host**
+ The host of the MySQL server. Defaults to ``localhost`` (string).
+
+**user**
+ The user name used to open the database connection. Defaults to ``FALSE`` (boolean).
+
+**pass**
+ The password required to open the database connection. Defaults to ``FALSE`` (boolean).
+
+**connection**
+ An existing MySQL link-resource that can be used by b8. Defaults to ``NULL`` (NULL).
+
+Using b8
+========
+
+Now, that everything is configured, you can start to use b8. A sample script that shows what can be done with the filter exists in ``example/index.php``. The best thing for testing how all this works is to use this script before using b8 in your own scripts.
+
+Before you can start, you have to setup a database so that b8 can store a wordlist.
+
+Setting up a new database
+-------------------------
+
+Setting up a new Berkeley DB
+````````````````````````````
+
+I wrote a script to setup a new Berkeley DB for b8. It is located in ``install/setup_berkeleydb.php``. Just run this script on your server and be sure that the directory containing it has the proper access rights set so that the server's HTTP server user or PHP user can create a new file in it (probably ``0777``). The script is quite self-explaining, just run it.
+
+Of course, you can also create a Berkeley DB by hand. In this case, you just have to insert three keys:
+
+::
+
+ bayes*dbversion => 2
+ bayes*texts.ham => 0
+ bayes*texts.spam => 0
+
+Be sure to set the right DBA handler in the storage backend configuration if it's not ``db4``.
+
+Setting up a new MySQL table
+````````````````````````````
+
+The SQL file ``install/setup_mysql.sql`` contains both the create statement for the wordlist table of b8 and the ``INSERT`` statements for adding the necessary internal variables.
+
+Simply change the table name according to your needs (or leave it as it is ;-) and run the SQL to setup a b8 wordlist MySQL table.
+
+Using b8 in your scripts
+------------------------
+
+Just have a look at the example script located in ``example/index.php`` to see how you can include b8 in your scripts. Essentially, this strips down to:
+
+::
+
+ # Include the b8 code
+ require "{$_SERVER['DOCUMENT_ROOT']}/b8/b8.php";
+
+ # Do some configuration
+
+ $config_b8 = array(
+ 'some_key' => 'some_value',
+ 'foo' => 'bar'
+ );
+
+ $config_database = array(
+ 'some_key' => 'some_value',
+ 'foo' => 'bar'
+ );
+
+ # Create a new b8 instance
+ $b8 = new b8($config_b8, $config_database);
+
+b8 provides three functions in an object oriented way (called e. g. via ``$b8->classify($text)``):
+
+**learn($text, $category)**
+ This saves the reference text ``$text`` (string) in the category ``$category`` (b8 constant). |br|
+ b8 0.5 introduced two constants that can be used as ``$category``: ``b8::HAM`` and ``b8::SPAM``. To be downward compatible with older versions of b8, the literal values "ham" and "spam" (case-sensitive strings) can still be used here.
+
+**unlearn($text, $category)**
+ This function just exists to delete a text from a category in which is has been stored accidentally before. It deletes the reference text ``$text`` (string) from the category ``$category`` (either the constants ``b8::HAM`` or ``b8::SPAM`` or the literal case-sensitive strings "ham" or "spam" – cf. above). |br|
+ **Don't delete a spam text from ham after saving it in spam or vice versa, as long you don't have stored it accidentally in the wrong category before!** This will not improve performance, quite the opposite: it will actually break the filter after a time, as the counter for saved ham or spam texts will reach 0, although you have ham or spam tokens stored: the filter will try to remove texts from the ham or spam data which have never been stored there, decrease the counter for tokens which are found just skip the non-existing words.
+
+**classify($text)**
+ This function takes the text ``$text`` (string), calculates it's probability for being spam it and returns a value between 0 and 1 (float). |br|
+ A value close to 0 says the text is more likely ham and a value close to 1 says the text is more likely spam. What to do with this value is *your* business ;-) See also `Tips on operation`_ below.
+
+Tips on operation
+=================
+
+Before b8 can decide whether a text is spam or ham, you have to tell it what you consider as spam or ham. At least one learned spam or one learned ham text is needed to calculate anything. To get good ratings, you need both learned ham and learned spam texts, the more the better. |br|
+What's considered as "ham" or "spam" can be very different, depending on the operation site. On my homepage, practically each and every text posted in English or using cyrillic letters is spam. On an English or Russian homepage, this will be not the case. So I think it's not really meaningful to provide some "spam data" to start. Just train b8 with "your" spam and ham.
+
+For the practical use, I advise to give the filter all data availible. E. g. name, email address, homepage, IP address und of course the text itself should be stored in a variable (e. g. separated with an ``\n`` or just a space or tab after each block) and then be classified. The learning should also be done with all data availible. |br|
+Saving the IP address is probably only meaningful for spam entries, because spammers often use the same IP address multiple times. In principle, you can leave out the IP of ham entries.
+
+You can use b8 e. g. in a guestbook script and let it classify the text before saving it. Everyone has to decide which rating is necessary to classify a text as "spam", but a rating of >= 0.8 seems to be reasonable for me. If one expects the spam to be in another language that the ham entries or the spams are very short normally, one could also think about a limit of 0.7. |br|
+The email filters out there mostly use > 0.9 or even > 0.99; but keep in mind that they have way more data to analyze in most of the cases. A guestbook entry may be quite short, especially when it's spam.
+
+In my opinion, a autolearn function is very handy. I save spam messages with a rating higher than 0.7 but less than 0.9 automatically as spam. I don't do this with ham messages in an automated way to prevent the filter from saving a false negative as ham and then classifying and learning all the spam as ham when I'm on holidays ;-)
+
+Closing
+=======
+
+So … that's it. Thanks for using b8! If you find a bug or have an idea how to make b8 better, let me know. I'm also always looking forward to get e-mails from people using b8 on their homepages :-)
+
+References
+==========
+
+.. [#planforspam] Paul Graham, *A Plan For Spam* (http://paulgraham.com/spam.html)
+.. [#betterbayesian] Paul Graham, *Better Bayesian Filtering* (http://paulgraham.com/better.html)
+.. [#spamdetection] Gary Robinson, *Spam Detection* (http://radio.weblogs.com/0101454/stories/2002/09/16/spamDetection.html)
+.. [#statisticalapproach] *A Statistical Approach to the Spam Problem* (http://linuxjournal.com/article/6467)
+.. [#b8statistic] Tobias Leupold, *Statistical discussion about b8* (http://nasauber.de/opensource/b8/discussion/)
+
+Appendix
+========
+
+FAQ
+---
+
+What about more than two categories?
+````````````````````````````````````
+
+I wrote b8 with the `KISS principle <http://en.wikipedia.org/wiki/KISS_principle>`__ in mind. For the "end-user", we have a class with almost no setup to do that can do three things: classify a text, learn a text and un-learn a text. Normally, there's no need to un-learn a text, so essentially, there are only two functions we need. |br|
+This simplicity is only possible because b8 only knows two categories (normally "Ham" and "Spam" or some other category pair) and tells you, in one float number between 0 and 1, if a given texts rather fits in the first or the second category. If we would support multiple categories, more work would have to be done and things would become more complicated. One would have to setup the categories, have another database layout (perhaps making it mandatory to have SQL) and one float number would not be sufficient to describe b8's output, so more code would be needed – even outside of b8.
+
+All the code, the database layout and particularly the math is intended to do exactly one thing: distinguish between two categories. I think it would be a lot of work to change b8 so that it would support more than two categories. Probably, this is possible to do, but don't ask me in which way we would have to change the math to get multiple-category support – I'm a dentist, not a mathematician ;-) |br|
+Apart from this I do believe that most people using b8 don't want or need multiple categories. They just want to know if a text is spam or not, don't they? I do, at least ;-)
+
+But let's think about the multiple-category thing. How would we calculate a rating for more than two categories? If we had a third one, let's call it "`Treet <http://en.wikipedia.org/wiki/Treet>`__", how would we calculate a rating? We could calculate three different ratings. One for "Ham", one for "Spam" and one for "Treet" and choose the highest one to tell the user what category fits best for the text. This could be done by using a small wrapper script using three instances of b8 as-is and three different databases, each containing texts being "Ham", "Spam", "Treet" and the respective counterparts. |br|
+But here's the problem: if we have "Ham" and "Spam", "Spam" is the counterpart of "Ham". But what's the counterpart of "Spam" if we have more than one additional category? Where do the "Non-Ham", "Non-Spam" and "Non-Treet" texts come from?
+
+Another approach, a direct calculation of more than two probabilities (the "Ham" probability is simply 1 minus the "Spam" probability, so we actually get two probabilities with the return value of b8) out of one database would require big changes in b8's structure and math.
+
+There's a project called `PHPNaiveBayesianFilter <http://xhtml.net/scripts/PHPNaiveBayesianFilter>`__ which supports multiple categories by default. The author calls his software "Version 1.0", but I think this is the very first release, not a stable or mature one. The most recent change of that release dates back to 2003 according to the "changed" date of the files inside the zip archive, so probably, this project is dead or has never been alive and under active development at all. |br|
+Actually, I played around with that code but the results weren't really good, so I decided to write my own spam filter from scratch back in early 2006 ;-)
+
+All in all, there seems to be no easy way to implement multiple (meaning more than two) categories using b8's current code base and probably, b8 will never support more than two categories. Perhaps, a fork or a complete re-write would be better than implementing such a feature. Anyway, I don't close my mind to multiple categories in b8. Feel free to tell me how multiple categories could be implementented in b8 or how a multiple-category version using the same code base (sharing a common abstract class?) could be written.
+
+What about a list with words to ignore?
+```````````````````````````````````````
+
+Some people suggested to introduce a list with words that b8 will simply ignore. Like "and", "or", "the", and so on. I don't think this is very meaningful.
+
+First, it would just work for the particular language that has been stored in the list. Speaking of my homepage, most of my spam is English, almost all my ham is German. So I would have to maintain a list with the probably less interesting words for at least two languages. Additionally, I get spam in Chinese, Japanese and Cyrillic writing or something else I can't read as well. What word should be ignored in those texts? |br|
+Second, why should we ever exclude words? Who tells us those words are *actually* meaningless? If a word appears both in ham and spam, it's rating will be near 0.5 and so, it won't be used for the final calculation if a appropriate minimum deviation was set. So b8 will exclude it anyway without any blacklist. And think of this: if we excluded a word of which we only *think* it doesn't mean anything but it actually does appear more often in ham or spam, the results will get even worse.
+
+So why should we care about things we do not have to care about? ;-)
+
+
+Why is it called "b8"?
+``````````````````````
+
+The initial name for the filter was (damn creative!) "bayes-php". There were two main reasons for searching another name: 1. "bayes-php" sucks. 2. the `PHP License <http://php.net/license/3_01.txt>`_ says the PHP guys do not like when the name of a script written in PHP contains the word "PHP". Read the `License FAQ <http://www.php.net/license/index.php#faq-lic>`_ for a reasonable argumentation about this.
+
+Luckily, `Tobias Lang <http://langt.net/>`_ proposed the new name "b8". And these are the reasons why I chose this name:
+
+- "bayes-php" is a "b" followed by 8 letters.
+- "b8" is short and handy. Additionally, there was no program with the name "b8" or "bate"
+- The English verb "to bate" means "to decrease" – and that's what b8 does: it decreases the number of spam entries in your weblog or guestbook!
+- "b8" just sounds way cooler than "bayes-php" ;-)
+
+About the database
+------------------
+
+The database layout
+```````````````````
+
+The database layout is quite simple. It's just key:value for everything stored. There are three "internal" variables stored as normal tokens (but all containing a ``*`` which is always used as a split character by the lexer, so we can't get collisions):
+
+**bayes*dbversion**
+ This indicates the database's "version". The first versions of b8 did not set this. Version "2" indicates that we have a database created by a b8 version already storing `the "lastseen" parameter`_.
+
+**bayes*texts.ham**
+ The number of ham texts learned.
+
+**bayes*texts.spam**
+ The number of spam texts learned.
+
+Each "normal" token is stored with it's literal name as the key and it's data as the value. The data consists of the count of the token in all ham and spam texts and the date when the token was used the last time, all in one string and separated by spaces. So we have the following scheme:
+
+::
+
+ "token" => "count_ham count_spam lastseen"
+
+The "lastseen" parameter
+````````````````````````
+
+Somebody looking at the code might be wondering why b8 stores this "lastseen" parameter. This value is not used for any calculation at the moment. Initially, it was intended to keep the database maintainable in a way that "old" data could be removed. When e. g. a token only appeared once in ham or spam and has not been seen for a year, one could simply delete it from the database. |br|
+I actually never used this feature (does anybody?). So probably, some changes will be done to this one day. Perhaps, I find a way to include this data in the spamminess calculation in a meaningful way, or at least for some statistics. One could also make this optional to keep the calculation effort small if this is needed.
+
+Feel free to send me any suggestions about this!
+
+.. |br| raw:: html
+
+ <br />
+
+.. section-numbering::
+
+.. |date| date::
diff --git a/library/spam/example/index.php b/library/spam/example/index.php
new file mode 100644
index 000000000..6d3c14260
--- /dev/null
+++ b/library/spam/example/index.php
@@ -0,0 +1,241 @@
+<?php
+
+# Copyright (C) 2006-2010 Tobias Leupold <tobias.leupold@web.de>
+#
+# This file is part of the b8 package
+#
+# This program 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 in version 2.1 of the License.
+#
+# 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 Lesser General Public
+# License for more details.
+#
+# You should have received a copy of the GNU Lesser 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.
+
+
+### This is an example script demonstrating how b8 can be used. ###
+
+#/*
+
+# Use this code block if you want to use Berkeley DB.
+
+# The database filename is interpreted relative to the b8.php script location.
+
+$config_b8 = array(
+ 'storage' => 'dba'
+);
+
+$config_database = array(
+ 'database' => 'wordlist.db',
+ 'handler' => 'db4'
+);
+
+#*/
+
+/*
+
+# Use this code block if you want to use MySQL.
+
+# An existing link resource can be passed to b8 by setting
+# $config_database['connection'] to this link resource.
+# Be sure to set your database access data otherwise!
+
+$config_b8 = array(
+ 'storage' => 'mysql'
+);
+
+$config_database = array(
+ 'database' => 'test',
+ 'table_name' => 'b8_wordlist',
+ 'host' => 'localhost',
+ 'user' => '',
+ 'pass' => ''
+);
+
+*/
+
+# To be able to calculate the time the classification took
+
+$time_start = NULL;
+
+function microtimeFloat()
+{
+ list($usec, $sec) = explode(" ", microtime());
+ return ((float) $usec + (float) $sec);
+}
+
+# Output a nicely colored rating
+
+function formatRating($rating)
+{
+
+ if($rating === FALSE)
+ return "<span style=\"color:red\">could not calculate spaminess</span>";
+
+ $red = floor(255 * $rating);
+ $green = floor(255 * (1 - $rating));
+
+ return "<span style=\"color:rgb($red, $green, 0);\"><b>" . sprintf("%5f", $rating) . "</b></span>";
+
+}
+
+echo <<<END
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
+ "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
+
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
+
+<head>
+
+<title>example b8 interface</title>
+
+<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
+
+<meta name="dc.creator" content="Tobias Leupold" />
+<meta name="dc.rights" content="Copyright (c) by Tobias Leupold" />
+
+</head>
+
+<body>
+
+<div>
+
+<h1>example b8 interface</h1>
+
+
+END;
+
+$postedText = "";
+
+if(isset($_POST['action']) and $_POST['text'] == "")
+ echo "<p style=\"color:red;\"><b>Please type in a text!</b></p>\n\n";
+
+elseif(isset($_POST['action']) and $_POST['text'] != "") {
+
+ $time_start = microtimeFloat();
+
+ # Include the b8 code
+ require dirname(__FILE__) . "/../b8/b8.php";
+
+ # Create a new b8 instance
+ $b8 = new b8($config_b8, $config_database);
+
+ # Check if everything worked smoothly
+
+ $started_up = $b8->validate();
+
+ if($started_up !== TRUE) {
+ echo "<b>example:</b> Could not initialize b8. error code: $started_up";
+ exit;
+ }
+
+ $text = stripslashes($_POST['text']);
+ $postedText = htmlentities($text, ENT_QUOTES, 'UTF-8');
+
+ switch($_POST['action']) {
+
+ case "Classify":
+ echo "<p><b>Spaminess: " . formatRating($b8->classify($text)) . "</b></p>\n";
+ break;
+
+ case "Save as Spam":
+
+ $ratingBefore = $b8->classify($text);
+ $b8->learn($text, b8::SPAM);
+ $ratingAfter = $b8->classify($text);
+
+ echo "<p>Saved the text as Spam</p>\n\n";
+
+ echo "<div><table>\n";
+ echo "<tr><td>Classification before learning:</td><td>" . formatRating($ratingBefore) . "</td></tr>\n";
+ echo "<tr><td>Classification after learning:</td><td>" . formatRating($ratingAfter) . "</td></tr>\n";
+ echo "</table></div>\n\n";
+
+ break;
+
+ case "Save as Ham":
+
+ $ratingBefore = $b8->classify($text);
+ $b8->learn($text, b8::HAM);
+ $ratingAfter = $b8->classify($text);
+
+ echo "<p>Saved the text as Ham</p>\n\n";
+
+ echo "<div><table>\n";
+ echo "<tr><td>Classification before learning:</td><td>" . formatRating($ratingBefore) . "</td></tr>\n";
+ echo "<tr><td>Classification after learning:</td><td>" . formatRating($ratingAfter) . "</td></tr>\n";
+ echo "</table></div>\n\n";
+
+ break;
+
+ case "Delete from Spam":
+ $b8->unlearn($text, b8::SPAM);
+ echo "<p style=\"color:green\">Deleted the text from Spam</p>\n\n";
+ break;
+
+ case "Delete from Ham":
+ $b8->unlearn($text, b8::HAM);
+ echo "<p style=\"color:green\">Deleted the text from Ham</p>\n\n";
+ break;
+
+ }
+
+ $mem_used = round(memory_get_usage() / 1048576, 5);
+ $peak_mem_used = round(memory_get_peak_usage() / 1048576, 5);
+ $time_taken = round(microtimeFloat() - $time_start, 5);
+
+}
+
+echo <<<END
+<div>
+<form action="{$_SERVER['PHP_SELF']}" method="post">
+<div>
+<textarea name="text" cols="50" rows="16">$postedText</textarea>
+</div>
+<table>
+<tr>
+<td><input type="submit" name="action" value="Classify" /></td>
+</tr>
+<tr>
+<td><input type="submit" name="action" value="Save as Spam" /></td>
+<td><input type="submit" name="action" value="Save as Ham" /></td>
+</tr>
+<tr>
+<td><input type="submit" name="action" value="Delete from Spam" /></td>
+<td><input type="submit" name="action" value="Delete from Ham" /></td>
+</tr>
+</table>
+</form>
+</div>
+
+</div>
+
+END;
+
+if($time_start !== NULL) {
+
+echo <<<END
+<div>
+<table border="0">
+<tr><td>Memory used: </td><td>$mem_used&thinsp;MB</td></tr>
+<tr><td>Peak memory used:</td><td>$peak_mem_used&thinsp;MB</td></tr>
+<tr><td>Time taken: </td><td>$time_taken&thinsp;sec</td></tr>
+</table>
+</div>
+
+END;
+
+}
+
+?>
+
+</body>
+
+</html>
diff --git a/library/spam/install/setup_berkeleydb.php b/library/spam/install/setup_berkeleydb.php
new file mode 100644
index 000000000..81e1d5afa
--- /dev/null
+++ b/library/spam/install/setup_berkeleydb.php
@@ -0,0 +1,240 @@
+<?php
+
+# Copyright (C) 2010 Tobias Leupold <tobias.leupold@web.de>
+#
+# This file is part of the b8 package
+#
+# This program 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 in version 2.1 of the License.
+#
+# 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 Lesser General Public
+# License for more details.
+#
+# You should have received a copy of the GNU Lesser 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.
+
+echo <<<END
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
+ "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
+
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
+
+<head>
+
+<title>b8 Berkeley DB setup</title>
+
+<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
+
+<meta name="dc.creator" content="Tobias Leupold" />
+<meta name="dc.rights" content="Copyright (c) by Tobias Leupold" />
+
+</head>
+
+<body>
+
+<div>
+
+<h1>b8 Berkeley DB setup</h1>
+
+
+END;
+
+$failed = FALSE;
+
+if(isset($_POST['handler'])) {
+
+ $dbfile = $_POST['dbfile'];
+ $dbfile_directory = $_SERVER['DOCUMENT_ROOT'] . dirname($_SERVER['PHP_SELF']);
+
+ echo "<h2>Creating database</h2>\n\n";
+
+ echo "<p>\n";
+
+ echo "Checking database file name &hellip; ";
+
+ if($dbfile == "") {
+ echo "<span style=\"color:red;\">Please provide the name of the database file!</span><br />\n";
+ $failed = TRUE;
+ }
+ else
+ echo "$dbfile<br />\n";
+
+ if(!$failed) {
+
+ echo "Touching/Creating " . htmlentities($dbfile) . " &hellip; ";
+
+ if(touch($dbfile) === FALSE) {
+ echo "<span style=\"color:red;\">Failed to touch the database file. Please check the given filename and/or fix the permissions of $dbfile_directory.</span><br />\n";
+ $failed = TRUE;
+ }
+ else
+ echo "done<br />\n";
+
+ }
+
+ if(!$failed) {
+
+ echo "Setting file permissions to 0666 &hellip ";
+
+ if(chmod($dbfile, 0666) === FALSE) {
+ echo "<span style=\"color:red;\">Failed to change the permissions of $dbfile_directory/$dbfile. Please adjust them manually.</span><br />\n";
+ $failed = TRUE;
+ }
+ else
+ echo "done<br />\n";
+
+ }
+
+ if(!$failed) {
+
+ echo "Checking if the given file is empty &hellip ";
+
+ if(filesize($dbfile) > 0) {
+ echo "<span style=\"color:red;\">$dbfile_directory/$dbfile is not empty. Can't create a new database. Please delete/empty this file or give another filename.</span><br />\n";
+ $failed = TRUE;
+ }
+ else
+ echo "it is<br />\n";
+
+ }
+
+ if(!$failed) {
+
+ echo "Connecting to $dbfile &hellip; ";
+
+ $db = dba_open($dbfile, "c", $_POST['handler']);
+
+ if($db === FALSE) {
+ echo "<span style=\"color:red;\">Could not connect to the database!</span><br />\n";
+ $failed = TRUE;
+ }
+ else
+ echo "done<br />\n";
+
+ }
+
+ if(!$failed) {
+
+ echo "Storing necessary internal variables &hellip ";
+
+ $internals = array(
+ "bayes*dbversion" => "2",
+ "bayes*texts.ham" => "0",
+ "bayes*texts.spam" => "0"
+ );
+
+ foreach($internals as $key => $value) {
+ if(dba_insert($key, $value, $db) === FALSE) {
+ echo "<span style=\"color:red;\">Failed to insert data!</span><br />\n";
+ $failed = TRUE;
+ break;
+ }
+ }
+
+ if(!$failed)
+ echo "done<br />\n";
+
+ }
+
+ if(!$failed) {
+
+ echo "Trying to read data from the database &hellip ";
+
+ $dbversion = dba_fetch("bayes*dbversion", $db);
+
+ if($dbversion != "2") {
+ echo "<span style=\"color:red;\">Failed to read data!</span><br />\n";
+ $failed = TRUE;
+ }
+ else
+ echo "success<br />\n";
+ }
+
+ if(!$failed) {
+
+ dba_close($db);
+
+ echo "</p>\n\n";
+ echo "<p style=\"color:green;\">Successfully created a new b8 database!</p>\n\n";
+ echo "<table>\n";
+ echo "<tr><td>Filename:</td><td>$dbfile_directory/$dbfile</td></tr>\n";
+ echo "<tr><td>DBA handler:</td><td>{$_POST['handler']}</td><tr>\n";
+ echo "</table>\n\n";
+ echo "<p>Move this file to it's destination directory (default: the base directory of b8) to use it with b8. Be sure to use the right DBA handler in b8's configuration.";
+
+ }
+
+ echo "</p>\n\n";
+
+}
+
+if($failed === TRUE or !isset($_POST['handler'])) {
+
+echo <<<END
+<form action="{$_SERVER['PHP_SELF']}" method="post">
+
+<h2>DBA Handler</h2>
+
+<p>
+The following table shows all available DBA handlers. Please choose the "Berkeley DB" one.
+</p>
+
+<table>
+<tr><td></td><td><b>Handler</b></td><td><b>Description</b></td></tr>
+
+END;
+
+foreach(dba_handlers(TRUE) as $name => $version) {
+
+ $checked = "";
+
+ if(!isset($_POST['handler'])) {
+ if(strpos($version, "Berkeley") !== FALSE )
+ $checked = " checked=\"checked\"";
+ }
+ else {
+ if($_POST['handler'] == $name)
+ $checked = " checked=\"checked\"";
+ }
+
+ echo "<tr><td><input type=\"radio\" name=\"handler\" value=\"$name\"$checked /></td><td>$name</td><td>$version</td></tr>\n";
+
+}
+
+echo <<<END
+</table>
+
+<h2>Database file</h2>
+
+<p>
+Please the name of the desired database file. It will be created in the directory where this script is located.
+</p>
+
+<p>
+<input type="text" name="dbfile" value="wordlist.db" />
+</p>
+
+<p>
+<input type="submit" value="Create the database" />
+</p>
+
+</form>
+
+
+END;
+
+}
+
+?>
+
+</div>
+
+</body>
+
+</html>
diff --git a/library/spam/install/setup_mysql.sql b/library/spam/install/setup_mysql.sql
new file mode 100644
index 000000000..ac43274e9
--- /dev/null
+++ b/library/spam/install/setup_mysql.sql
@@ -0,0 +1,27 @@
+
+-- Copyright (C) 2010 Tobias Leupold <tobias.leupold@web.de>
+--
+-- This file is part of the b8 package
+--
+-- This program 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 in version 2.1 of the License.
+--
+-- 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 Lesser General Public
+-- License for more details.
+--
+-- You should have received a copy of the GNU Lesser 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.
+
+CREATE TABLE `b8_wordlist` (
+ `token` varchar(255) character set utf8 collate utf8_bin NOT NULL,
+ `count` varchar(255) default NULL,
+ PRIMARY KEY (`token`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+
+INSERT INTO `b8_wordlist` VALUES ('bayes*dbversion', '2');
+INSERT INTO `b8_wordlist` VALUES ('bayes*texts.ham', '0');
+INSERT INTO `b8_wordlist` VALUES ('bayes*texts.spam', '0');
diff --git a/library/tinymce/jscripts/tiny_mce/plugins/bbcode/editor_plugin_src.js b/library/tinymce/jscripts/tiny_mce/plugins/bbcode/editor_plugin_src.js
index b8a3abb31..e5f716b29 100755
--- a/library/tinymce/jscripts/tiny_mce/plugins/bbcode/editor_plugin_src.js
+++ b/library/tinymce/jscripts/tiny_mce/plugins/bbcode/editor_plugin_src.js
@@ -105,6 +105,7 @@
rep(/<u>/gi,"[u]");
rep(/<blockquote[^>]*>/gi,"[quote]");
rep(/<\/blockquote>/gi,"[/quote]");
+ rep(/<hr \/>/gi,"[hr]");
rep(/<br \/>/gi,"\n\n");
rep(/<br\/>/gi,"\n\n");
rep(/<br>/gi,"\n");
@@ -135,6 +136,7 @@
rep(/\[\/i\]/gi,"</em>");
rep(/\[u\]/gi,"<u>");
rep(/\[\/u\]/gi,"</u>");
+ rep(/\[hr\]/gi,"<hr />");
rep(/\[bookmark=([^\]]+)\](.*?)\[\/bookmark\]/gi,"<a class=\"bookmark\" href=\"$1\">$2</a>");
rep(/\[url=([^\]]+)\](.*?)\[\/url\]/gi,"<a href=\"$1\">$2</a>");
rep(/\[url\](.*?)\[\/url\]/gi,"<a href=\"$1\">$1</a>");